2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
23 import java.awt.Color;
24 import java.io.BufferedReader;
25 import java.util.ArrayList;
26 import java.util.BitSet;
27 import java.util.Enumeration;
28 import java.util.Hashtable;
29 import java.util.List;
31 import java.util.StringTokenizer;
32 import java.util.Vector;
34 import jalview.analysis.Conservation;
35 import jalview.api.AlignViewportI;
36 import jalview.datamodel.Alignment;
37 import jalview.datamodel.AlignmentAnnotation;
38 import jalview.datamodel.AlignmentI;
39 import jalview.datamodel.Annotation;
40 import jalview.datamodel.ColumnSelection;
41 import jalview.datamodel.GraphLine;
42 import jalview.datamodel.HiddenColumns;
43 import jalview.datamodel.HiddenSequences;
44 import jalview.datamodel.SequenceGroup;
45 import jalview.datamodel.SequenceI;
46 import jalview.schemes.ColourSchemeI;
47 import jalview.schemes.ColourSchemeProperty;
48 import jalview.util.ColorUtils;
50 public class AnnotationFile
52 private static final String GRAPHLINE = "GRAPHLINE";
54 private static final String COMBINE = "COMBINE";
56 protected String newline = System.getProperty("line.separator");
58 private StringBuffer text;
60 private SequenceI refSeq = null;
62 private String refSeqId = null;
64 private long nlinesread = 0;
66 private String lastread = "";
69 * default calcId string for new annotation
71 private String defaultCalcId = null;
76 public AnnotationFile()
83 text = new StringBuffer("JALVIEW_ANNOTATION" + newline + "# Created: "
84 + new java.util.Date() + newline + newline);
90 * convenience method for pre-2.9 annotation files which have no view, hidden
91 * columns or hidden row keywords.
96 * @return annotation file as a string.
98 public String printAnnotations(AlignmentAnnotation[] annotations,
99 List<SequenceGroup> list, Hashtable properties)
101 return printAnnotations(annotations, list, properties, null, null,
107 * hold all the information about a particular view definition read from or
108 * written out in an annotations file.
112 // TODO this class is not used - remove?
113 public final String viewname;
115 public final HiddenSequences hidseqs;
117 public final HiddenColumns hiddencols;
119 public final Hashtable hiddenRepSeqs;
121 public ViewDef(String vname, HiddenSequences hseqs, HiddenColumns hcols,
124 this.viewname = vname;
125 this.hidseqs = hseqs;
126 this.hiddencols = hcols;
127 this.hiddenRepSeqs = hRepSeqs;
132 * Prepare an annotation file given a set of annotations, groups, alignment
133 * properties and views.
139 * @return annotation file
141 public String printAnnotations(AlignmentAnnotation[] annotations,
142 List<SequenceGroup> list, Hashtable properties, HiddenColumns cs,
143 AlignmentI al, ViewDef view)
147 if (view.viewname != null)
149 text.append("VIEW_DEF\t" + view.viewname + "\n");
153 // list = view.visibleGroups;
157 cs = view.hiddencols;
161 // add hidden rep sequences.
164 // first target - store and restore all settings for a view.
165 if (al != null && al.hasSeqrep())
167 text.append("VIEW_SETREF\t" + al.getSeqrep().getName() + "\n");
169 if (cs != null && cs.hasHiddenColumns())
171 text.append("VIEW_HIDECOLS\t");
173 String regions = cs.regionsToString(",", "-");
174 text.append(regions);
177 // TODO: allow efficient recovery of annotation data shown in several
179 if (annotations != null)
181 boolean oneColour = true;
182 AlignmentAnnotation row;
184 SequenceI refSeq = null;
185 SequenceGroup refGroup = null;
187 StringBuffer colours = new StringBuffer();
188 StringBuffer graphLine = new StringBuffer();
189 StringBuffer rowprops = new StringBuffer();
190 Hashtable<Integer, String> graphGroup = new Hashtable<>();
191 Hashtable<Integer, Object[]> graphGroup_refs = new Hashtable<>();
192 BitSet graphGroupSeen = new BitSet();
194 java.awt.Color color;
196 for (int i = 0; i < annotations.length; i++)
198 row = annotations[i];
200 if (!row.visible && !row.hasScore() && !(row.graphGroup > -1
201 && graphGroupSeen.get(row.graphGroup)))
209 // mark any sequence references for the row
210 writeSequence_Ref(refSeq, row.sequenceRef);
211 refSeq = row.sequenceRef;
212 // mark any group references for the row
213 writeGroup_Ref(refGroup, row.groupRef);
214 refGroup = row.groupRef;
216 boolean hasGlyphs = row.hasIcons, hasLabels = row.hasText,
217 hasValues = row.hasScore, hasText = false;
218 // lookahead to check what the annotation row object actually contains.
219 for (int j = 0; row.annotations != null
220 && j < row.annotations.length
221 && (!hasGlyphs || !hasLabels || !hasValues); j++)
223 if (row.annotations[j] != null)
225 hasLabels |= (row.annotations[j].displayCharacter != null
226 && row.annotations[j].displayCharacter.length() > 0
227 && !row.annotations[j].displayCharacter.equals(" "));
228 hasGlyphs |= (row.annotations[j].secondaryStructure != 0
229 && row.annotations[j].secondaryStructure != ' ');
230 hasValues |= (!Float.isNaN(row.annotations[j].value)); // NaNs can't
233 hasText |= (row.annotations[j].description != null
234 && row.annotations[j].description.length() > 0);
238 if (row.graph == AlignmentAnnotation.NO_GRAPH)
240 text.append("NO_GRAPH\t");
241 hasValues = false; // only secondary structure
242 // hasLabels = false; // and annotation description string.
246 if (row.graph == AlignmentAnnotation.BAR_GRAPH)
248 text.append("BAR_GRAPH\t");
249 hasGlyphs = false; // no secondary structure
252 else if (row.graph == AlignmentAnnotation.LINE_GRAPH)
254 hasGlyphs = false; // no secondary structure
255 text.append("LINE_GRAPH\t");
258 if (row.getThreshold() != null)
260 graphLine.append("GRAPHLINE\t");
261 graphLine.append(row.label);
262 graphLine.append("\t");
263 graphLine.append(row.getThreshold().value);
264 graphLine.append("\t");
265 graphLine.append(row.getThreshold().label);
266 graphLine.append("\t");
267 graphLine.append(jalview.util.Format
268 .getHexString(row.getThreshold().colour));
269 graphLine.append(newline);
272 if (row.graphGroup > -1)
274 graphGroupSeen.set(row.graphGroup);
275 Integer key = Integer.valueOf(row.graphGroup);
276 if (graphGroup.containsKey(key))
278 graphGroup.put(key, graphGroup.get(key) + "\t" + row.label);
283 graphGroup_refs.put(key, new Object[] { refSeq, refGroup });
284 graphGroup.put(key, row.label);
289 text.append(row.label + "\t");
290 if (row.description != null)
292 text.append(row.description + "\t");
294 for (int j = 0; row.annotations != null
295 && j < row.annotations.length; j++)
298 && jalview.util.Comparison.isGap(refSeq.getCharAt(j)))
303 if (row.annotations[j] != null)
306 if (hasGlyphs) // could be also hasGlyphs || ...
310 if (row.annotations[j].secondaryStructure != ' ')
312 // only write out the field if its not whitespace.
313 text.append(row.annotations[j].secondaryStructure);
319 if (!Float.isNaN(row.annotations[j].value))
321 text.append(comma + row.annotations[j].value);
325 // System.err.println("Skipping NaN - not valid value.");
326 text.append(comma + 0f);// row.annotations[j].value);
332 // TODO: labels are emitted after values for bar graphs.
333 if // empty labels are allowed, so
334 (row.annotations[j].displayCharacter != null
335 && row.annotations[j].displayCharacter.length() > 0
336 && !row.annotations[j].displayCharacter.equals(" "))
338 text.append(comma + row.annotations[j].displayCharacter);
344 if (row.annotations[j].description != null
345 && row.annotations[j].description.length() > 0
346 && !row.annotations[j].description
347 .equals(row.annotations[j].displayCharacter))
349 text.append(comma + row.annotations[j].description);
353 if (color != null && !color.equals(row.annotations[j].colour))
358 color = row.annotations[j].colour;
360 if (row.annotations[j].colour != null
361 && row.annotations[j].colour != java.awt.Color.black)
363 text.append(comma + "[" + jalview.util.Format
364 .getHexString(row.annotations[j].colour) + "]");
373 text.append("\t" + row.score);
376 text.append(newline);
378 if (color != null && color != java.awt.Color.black && oneColour)
380 colours.append("COLOUR\t");
381 colours.append(row.label);
382 colours.append("\t");
383 colours.append(jalview.util.Format.getHexString(color));
384 colours.append(newline);
386 if (row.scaleColLabel || row.showAllColLabels
387 || row.centreColLabels)
389 rowprops.append("ROWPROPERTIES\t");
390 rowprops.append(row.label);
391 rowprops.append("\tscaletofit=");
392 rowprops.append(row.scaleColLabel);
393 rowprops.append("\tshowalllabs=");
394 rowprops.append(row.showAllColLabels);
395 rowprops.append("\tcentrelabs=");
396 rowprops.append(row.centreColLabels);
397 rowprops.append(newline);
399 if (graphLine.length() > 0)
401 text.append(graphLine.toString());
402 graphLine.setLength(0);
406 text.append(newline);
408 text.append(colours.toString());
409 if (graphGroup.size() > 0)
411 SequenceI oldRefSeq = refSeq;
412 SequenceGroup oldRefGroup = refGroup;
413 for (Map.Entry<Integer, String> combine_statement : graphGroup
416 Object[] seqRefAndGroup = graphGroup_refs
417 .get(combine_statement.getKey());
419 writeSequence_Ref(refSeq, (SequenceI) seqRefAndGroup[0]);
420 refSeq = (SequenceI) seqRefAndGroup[0];
422 writeGroup_Ref(refGroup, (SequenceGroup) seqRefAndGroup[1]);
423 refGroup = (SequenceGroup) seqRefAndGroup[1];
424 text.append("COMBINE\t");
425 text.append(combine_statement.getValue());
426 text.append(newline);
428 writeSequence_Ref(refSeq, oldRefSeq);
431 writeGroup_Ref(refGroup, oldRefGroup);
432 refGroup = oldRefGroup;
434 text.append(rowprops.toString());
442 if (properties != null)
444 text.append(newline);
445 text.append(newline);
446 text.append("ALIGNMENT");
447 Enumeration en = properties.keys();
448 while (en.hasMoreElements())
450 String key = en.nextElement().toString();
454 text.append(properties.get(key));
456 // TODO: output alignment visualization settings here if required
457 // iterate through one or more views, defining, marking columns and rows
458 // as visible/hidden, and emmitting view properties.
459 // View specific annotation is
462 return text.toString();
465 private Object writeGroup_Ref(SequenceGroup refGroup,
466 SequenceGroup next_refGroup)
468 if (next_refGroup == null)
471 if (refGroup != null)
473 text.append(newline);
474 text.append("GROUP_REF\t");
475 text.append("ALIGNMENT");
476 text.append(newline);
482 if (refGroup == null || refGroup != next_refGroup)
484 text.append(newline);
485 text.append("GROUP_REF\t");
486 text.append(next_refGroup.getName());
487 text.append(newline);
494 private boolean writeSequence_Ref(SequenceI refSeq, SequenceI next_refSeq)
497 if (next_refSeq == null)
501 text.append(newline);
502 text.append("SEQUENCE_REF\t");
503 text.append("ALIGNMENT");
504 text.append(newline);
510 if (refSeq == null || refSeq != next_refSeq)
512 text.append(newline);
513 text.append("SEQUENCE_REF\t");
514 text.append(next_refSeq.getName());
515 text.append(newline);
522 protected void printGroups(List<SequenceGroup> list)
524 SequenceI seqrep = null;
525 for (SequenceGroup sg : list)
529 text.append("SEQUENCE_GROUP\t" + sg.getName() + "\t"
530 + (sg.getStartRes() + 1) + "\t" + (sg.getEndRes() + 1)
536 seqrep = sg.getSeqrep();
537 text.append("SEQUENCE_REF\t");
538 text.append(seqrep.getName());
539 text.append(newline);
540 text.append("SEQUENCE_GROUP\t");
541 text.append(sg.getName());
543 text.append((seqrep.findPosition(sg.getStartRes())));
545 text.append((seqrep.findPosition(sg.getEndRes())));
549 for (int s = 0; s < sg.getSize(); s++)
551 text.append(sg.getSequenceAt(s).getName());
554 text.append(newline);
555 text.append("PROPERTIES\t");
556 text.append(sg.getName());
559 if (sg.getDescription() != null)
561 text.append("description=");
562 text.append(sg.getDescription());
567 text.append("colour=");
568 text.append(ColourSchemeProperty
569 .getColourName(sg.cs.getColourScheme()));
571 if (sg.cs.getThreshold() != 0)
573 text.append("pidThreshold=");
574 text.append(sg.cs.getThreshold());
576 if (sg.cs.conservationApplied())
578 text.append("consThreshold=");
579 text.append(sg.cs.getConservationInc());
583 text.append("outlineColour=");
584 text.append(jalview.util.Format.getHexString(sg.getOutlineColour()));
587 text.append("displayBoxes=");
588 text.append(sg.getDisplayBoxes());
590 text.append("displayText=");
591 text.append(sg.getDisplayText());
593 text.append("colourText=");
594 text.append(sg.getColourText());
596 text.append("showUnconserved=");
597 text.append(sg.getShowNonconserved());
599 if (sg.textColour != java.awt.Color.black)
601 text.append("textCol1=");
602 text.append(jalview.util.Format.getHexString(sg.textColour));
605 if (sg.textColour2 != java.awt.Color.white)
607 text.append("textCol2=");
608 text.append(jalview.util.Format.getHexString(sg.textColour2));
611 if (sg.thresholdTextColour != 0)
613 text.append("textColThreshold=");
614 text.append(sg.thresholdTextColour);
617 if (sg.idColour != null)
619 text.append("idColour=");
620 text.append(jalview.util.Format.getHexString(sg.idColour));
625 text.append("hide=true\t");
629 text.append("hidecols=true\t");
633 // terminate the last line and clear the sequence ref for the group
634 text.append(newline);
635 text.append("SEQUENCE_REF");
637 text.append(newline);
638 text.append(newline);
643 public boolean annotateAlignmentView(AlignViewportI viewport, Object file,
644 DataSourceType protocol)
646 ColumnSelection colSel = viewport.getColumnSelection();
647 HiddenColumns hidden = viewport.getAlignment().getHiddenColumns();
650 colSel = new ColumnSelection();
654 hidden = new HiddenColumns();
656 boolean rslt = readAnnotationFile(viewport.getAlignment(), hidden, file,
658 if (rslt && (colSel.hasSelectedColumns() || hidden.hasHiddenColumns()))
660 viewport.setColumnSelection(colSel);
661 viewport.getAlignment().setHiddenColumns(hidden);
667 public boolean readAnnotationFile(AlignmentI al, String file,
668 DataSourceType sourceType)
670 return readAnnotationFile(al, null, file, sourceType);
674 * read an annotation file onto the alignment, but apply the given calcId
681 public boolean readAnnotationFileWithCalcId(Alignment aln, String calcId, String file,
684 defaultCalcId=calcId;
685 return readAnnotationFile(aln, null, file, url);
688 public boolean readAnnotationFile(AlignmentI al, HiddenColumns hidden,
689 Object file, DataSourceType sourceType)
691 BufferedReader in = null;
694 in = new FileParse().getBufferedReader(file, sourceType);
697 return parseAnnotationFrom(al, hidden, in);
699 } catch (Exception ex)
701 ex.printStackTrace();
702 System.out.println("Problem reading annotation file: " + ex);
705 System.out.println("Last read line " + nlinesread + ": '" + lastread
706 + "' (first 80 chars) ...");
713 public boolean parseAnnotationFrom(AlignmentI al, HiddenColumns hidden,
714 BufferedReader in) throws Exception
717 ArrayList<Object[]> combineAnnotation_calls = new ArrayList<>();
718 ArrayList<Object[]> deferredAnnotation_calls = new ArrayList<>();
719 boolean modified = false;
720 String groupRef = null;
721 Hashtable groupRefRows = new Hashtable();
723 Hashtable autoAnnots = new Hashtable();
725 String line, label, description, token;
726 int graphStyle, index;
728 int existingAnnotations = 0;
729 // when true - will add new rows regardless of whether they are duplicate
730 // auto-annotation like consensus or conservation graphs
731 boolean overrideAutoAnnot = false;
732 if (al.getAlignmentAnnotation() != null)
734 existingAnnotations = al.getAlignmentAnnotation().length;
735 if (existingAnnotations > 0)
737 AlignmentAnnotation[] aa = al.getAlignmentAnnotation();
738 for (int aai = 0; aai < aa.length; aai++)
740 if (aa[aai].autoCalculated)
742 // make a note of the name and description
744 autoAnnotsKey(aa[aai], aa[aai].sequenceRef,
745 (aa[aai].groupRef == null ? null
746 : aa[aai].groupRef.getName())),
753 int alWidth = al.getWidth();
756 Annotation[] annotations;
757 AlignmentAnnotation annotation = null;
759 // First confirm this is an Annotation file
760 boolean jvAnnotationFile = false;
761 while ((line = in.readLine()) != null)
764 lastread = new String(line);
765 if (line.indexOf("#") == 0)
770 if (line.indexOf("JALVIEW_ANNOTATION") > -1)
772 jvAnnotationFile = true;
777 if (!jvAnnotationFile)
783 while ((line = in.readLine()) != null)
786 lastread = new String(line);
787 if (line.indexOf("#") == 0
788 || line.indexOf("JALVIEW_ANNOTATION") > -1
789 || line.length() == 0)
794 st = new StringTokenizer(line, "\t");
795 token = st.nextToken();
796 if (token.equalsIgnoreCase("COLOUR"))
798 // TODO: use graduated colour def'n here too
799 colourAnnotations(al, st.nextToken(), st.nextToken());
804 else if (token.equalsIgnoreCase(COMBINE))
806 // keep a record of current state and resolve groupRef at end
807 combineAnnotation_calls
809 { st, refSeq, groupRef });
813 else if (token.equalsIgnoreCase("ROWPROPERTIES"))
815 addRowProperties(al, st);
819 else if (token.equalsIgnoreCase(GRAPHLINE))
822 deferredAnnotation_calls
824 { GRAPHLINE, st, refSeq, groupRef });
829 else if (token.equalsIgnoreCase("SEQUENCE_REF"))
831 if (st.hasMoreTokens())
833 refSeq = al.findName(refSeqId = st.nextToken());
840 refSeqIndex = Integer.parseInt(st.nextToken());
845 "WARNING: SEQUENCE_REF index must be > 0 in AnnotationFile");
847 } catch (Exception ex)
859 else if (token.equalsIgnoreCase("GROUP_REF"))
861 // Group references could be forward or backwards, so they are
862 // resolved after the whole file is read in
864 if (st.hasMoreTokens())
866 groupRef = st.nextToken();
867 if (groupRef.length() < 1)
869 groupRef = null; // empty string
873 if (groupRefRows.get(groupRef) == null)
875 groupRefRows.put(groupRef, new Vector());
881 else if (token.equalsIgnoreCase("SEQUENCE_GROUP"))
888 else if (token.equalsIgnoreCase("PROPERTIES"))
890 addProperties(al, st);
895 else if (token.equalsIgnoreCase("BELOW_ALIGNMENT"))
897 setBelowAlignment(al, st);
901 else if (token.equalsIgnoreCase("ALIGNMENT"))
903 addAlignmentDetails(al, st);
907 // else if (token.equalsIgnoreCase("VIEW_DEF"))
909 // addOrSetView(al,st);
913 else if (token.equalsIgnoreCase("VIEW_SETREF"))
917 al.setSeqrep(refSeq);
922 else if (token.equalsIgnoreCase("VIEW_HIDECOLS"))
924 if (st.hasMoreTokens())
928 hidden = new HiddenColumns();
930 parseHideCols(hidden, st.nextToken());
935 else if (token.equalsIgnoreCase("HIDE_INSERTIONS"))
937 SequenceI sr = refSeq == null ? al.getSeqrep() : refSeq;
940 sr = al.getSequenceAt(0);
947 "Cannot process HIDE_INSERTIONS without an alignment view: Ignoring line: "
952 // consider deferring this till after the file has been parsed ?
953 hidden.hideList(sr.getInsertions());
960 // Parse out the annotation row
961 graphStyle = AlignmentAnnotation.getGraphValueFromString(token);
962 label = st.nextToken();
965 annotations = new Annotation[alWidth];
967 float score = Float.NaN;
969 if (st.hasMoreTokens())
971 line = st.nextToken();
973 if (line.indexOf("|") == -1)
976 if (st.hasMoreTokens())
978 line = st.nextToken();
982 if (st.hasMoreTokens())
984 // This must be the score
985 score = Float.valueOf(st.nextToken()).floatValue();
988 st = new StringTokenizer(line, "|", true);
990 boolean emptyColumn = true;
991 boolean onlyOneElement = (st.countTokens() == 1);
993 while (st.hasMoreElements() && index < alWidth)
995 token = st.nextToken().trim();
1001 score = Float.valueOf(token).floatValue();
1003 } catch (NumberFormatException ex)
1008 if (token.equals("|"))
1019 annotations[index++] = parseAnnotation(token, graphStyle);
1020 emptyColumn = false;
1026 annotation = new AlignmentAnnotation(label, description,
1027 (index == 0) ? null : annotations, 0, 0, graphStyle);
1028 annotation.setCalcId(defaultCalcId);
1029 annotation.score = score;
1030 if (!overrideAutoAnnot && autoAnnots
1031 .containsKey(autoAnnotsKey(annotation, refSeq, groupRef)))
1033 // skip - we've already got an automatic annotation of this type.
1036 // otherwise add it!
1040 annotation.belowAlignment = false;
1041 // make a copy of refSeq so we can find other matches in the alignment
1042 SequenceI referedSeq = refSeq;
1045 // copy before we do any mapping business.
1046 // TODO: verify that undo/redo with 1:many sequence associated
1047 // annotations can be undone correctly
1048 AlignmentAnnotation ann = new AlignmentAnnotation(annotation);
1049 annotation.createSequenceMapping(referedSeq, refSeqIndex,
1051 annotation.adjustForAlignment();
1052 referedSeq.addAlignmentAnnotation(annotation);
1053 al.addAnnotation(annotation);
1054 al.setAnnotationIndex(annotation,
1055 al.getAlignmentAnnotation().length - existingAnnotations
1057 if (groupRef != null)
1059 ((Vector) groupRefRows.get(groupRef)).addElement(annotation);
1061 // and recover our virgin copy to use again if necessary.
1064 } while (refSeqId != null && (referedSeq = al.findName(referedSeq,
1065 refSeqId, true)) != null);
1069 al.addAnnotation(annotation);
1070 al.setAnnotationIndex(annotation,
1071 al.getAlignmentAnnotation().length - existingAnnotations
1073 if (groupRef != null)
1075 ((Vector) groupRefRows.get(groupRef)).addElement(annotation);
1078 // and set modification flag
1081 // Resolve the groupRefs
1082 Hashtable<String, SequenceGroup> groupRefLookup = new Hashtable<>();
1083 Enumeration en = groupRefRows.keys();
1085 while (en.hasMoreElements())
1087 groupRef = (String) en.nextElement();
1088 boolean matched = false;
1089 // Resolve group: TODO: add a getGroupByName method to alignments
1090 for (SequenceGroup theGroup : al.getGroups())
1092 if (theGroup.getName().equals(groupRef))
1096 // TODO: specify and implement duplication of alignment annotation
1097 // for multiple group references.
1099 "Ignoring 1:many group reference mappings for group name '"
1105 Vector rowset = (Vector) groupRefRows.get(groupRef);
1106 groupRefLookup.put(groupRef, theGroup);
1107 if (rowset != null && rowset.size() > 0)
1109 AlignmentAnnotation alan = null;
1110 for (int elm = 0, elmSize = rowset
1111 .size(); elm < elmSize; elm++)
1113 alan = (AlignmentAnnotation) rowset.elementAt(elm);
1114 alan.groupRef = theGroup;
1120 ((Vector) groupRefRows.get(groupRef)).removeAllElements();
1122 // process any deferred attribute settings for each context
1123 for (Object[] _deferred_args : deferredAnnotation_calls)
1125 if (_deferred_args[0] == GRAPHLINE)
1127 addLine(al, (StringTokenizer) _deferred_args[1], // st
1128 (SequenceI) _deferred_args[2], // refSeq
1129 (_deferred_args[3] == null) ? null
1130 : groupRefLookup.get(_deferred_args[3]) // the
1138 // finally, combine all the annotation rows within each context.
1140 * number of combine statements in this annotation file. Used to create
1141 * new groups for combined annotation graphs without disturbing existing
1144 int combinecount = 0;
1145 for (Object[] _combine_args : combineAnnotation_calls)
1147 combineAnnotations(al, ++combinecount,
1148 (StringTokenizer) _combine_args[0], // st
1149 (SequenceI) _combine_args[1], // refSeq
1150 (_combine_args[2] == null) ? null
1151 : groupRefLookup.get(_combine_args[2]) // the reference
1160 private void parseHideCols(HiddenColumns hidden, String nextToken)
1162 StringTokenizer inval = new StringTokenizer(nextToken, ",");
1163 while (inval.hasMoreTokens())
1165 String range = inval.nextToken().trim();
1166 int from, to = range.indexOf("-");
1169 from = to = Integer.parseInt(range);
1172 hidden.hideColumns(from, to);
1177 from = Integer.parseInt(range.substring(0, to));
1178 if (to < range.length() - 1)
1180 to = Integer.parseInt(range.substring(to + 1));
1186 if (from > 0 && to >= from)
1188 hidden.hideColumns(from, to);
1194 private Object autoAnnotsKey(AlignmentAnnotation annotation,
1195 SequenceI refSeq, String groupRef)
1197 return annotation.graph + "\t" + annotation.label + "\t"
1198 + annotation.description + "\t"
1199 + (refSeq != null ? refSeq.getDisplayId(true) : "");
1202 Annotation parseAnnotation(String string, int graphStyle)
1204 // don't do the glyph test if we don't want secondary structure
1205 boolean hasSymbols = (graphStyle == AlignmentAnnotation.NO_GRAPH);
1206 String desc = null, displayChar = null;
1207 char ss = ' '; // secondaryStructure
1209 boolean parsedValue = false, dcset = false;
1212 Color colour = null;
1213 int i = string.indexOf("[");
1214 int j = string.indexOf("]");
1215 if (i > -1 && j > -1)
1217 colour = ColorUtils.parseColourString(string.substring(i + 1, j));
1218 if (i > 0 && string.charAt(i - 1) == ',')
1220 // clip the preceding comma as well
1223 string = string.substring(0, i) + string.substring(j + 1);
1226 StringTokenizer st = new StringTokenizer(string, ",", true);
1228 boolean seenContent = false;
1230 while (st.hasMoreTokens())
1233 token = st.nextToken().trim();
1234 if (token.equals(","))
1236 if (!seenContent && parsedValue && !dcset)
1238 // allow the value below the bar/line to be empty
1242 seenContent = false;
1254 displayChar = token;
1256 value = Float.valueOf(token).floatValue();
1259 } catch (NumberFormatException ex)
1265 if (token.length() == 1)
1267 displayChar = token;
1270 if (hasSymbols && (token.length() == 1
1271 && "()<>[]{}AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz"
1274 // Either this character represents a helix or sheet
1275 // or an integer which can be displayed
1276 ss = token.charAt(0);
1277 if (displayChar.equals(token.substring(0, 1)))
1282 else if (desc == null || (parsedValue && pass > 2))
1288 // if (!dcset && string.charAt(string.length() - 1) == ',')
1290 // displayChar = " "; // empty display char symbol.
1292 if (displayChar != null && desc != null && desc.length() == 1)
1294 if (displayChar.length() > 1)
1296 // switch desc and displayChar - legacy support
1297 String tmp = displayChar;
1303 if (displayChar.equals(desc))
1305 // duplicate label - hangover from the 'robust parser' above
1310 Annotation anot = new Annotation(displayChar, desc, ss, value);
1312 anot.colour = colour;
1317 void colourAnnotations(AlignmentI al, String label, String colour)
1319 Color awtColour = ColorUtils.parseColourString(colour);
1320 Annotation[] annotations;
1321 for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1323 if (al.getAlignmentAnnotation()[i].label.equalsIgnoreCase(label))
1325 annotations = al.getAlignmentAnnotation()[i].annotations;
1326 for (int j = 0; j < annotations.length; j++)
1328 if (annotations[j] != null)
1330 annotations[j].colour = awtColour;
1337 void combineAnnotations(AlignmentI al, int combineCount,
1338 StringTokenizer st, SequenceI seqRef, SequenceGroup groupRef)
1340 String group = st.nextToken();
1341 // First make sure we are not overwriting the graphIndex
1343 if (al.getAlignmentAnnotation() != null)
1345 for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1347 AlignmentAnnotation aa = al.getAlignmentAnnotation()[i];
1349 if (aa.graphGroup > graphGroup)
1351 // try to number graphGroups in order of occurence.
1352 graphGroup = aa.graphGroup + 1;
1354 if (aa.sequenceRef == seqRef && aa.groupRef == groupRef
1355 && aa.label.equalsIgnoreCase(group))
1357 if (aa.graphGroup > -1)
1359 graphGroup = aa.graphGroup;
1363 if (graphGroup <= combineCount)
1365 graphGroup = combineCount + 1;
1367 aa.graphGroup = graphGroup;
1373 // Now update groups
1374 while (st.hasMoreTokens())
1376 group = st.nextToken();
1377 for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1379 AlignmentAnnotation aa = al.getAlignmentAnnotation()[i];
1380 if (aa.sequenceRef == seqRef && aa.groupRef == groupRef
1381 && aa.label.equalsIgnoreCase(group))
1383 aa.graphGroup = graphGroup;
1392 "Couldn't combine annotations. None are added to alignment yet!");
1396 void addLine(AlignmentI al, StringTokenizer st, SequenceI seqRef,
1397 SequenceGroup groupRef)
1399 String group = st.nextToken();
1400 AlignmentAnnotation[] alannot = al.getAlignmentAnnotation();
1401 String nextToken = st.nextToken();
1405 value = Float.valueOf(nextToken);
1406 } catch (NumberFormatException e)
1408 System.err.println("line " + nlinesread + ": Threshold '" + nextToken
1409 + "' invalid, setting to zero");
1411 String label = st.hasMoreTokens() ? st.nextToken() : null;
1412 Color colour = null;
1413 if (st.hasMoreTokens())
1415 colour = ColorUtils.parseColourString(st.nextToken());
1417 if (alannot != null)
1419 for (int i = 0; i < alannot.length; i++)
1421 if (alannot[i].label.equalsIgnoreCase(group)
1422 && (seqRef == null || alannot[i].sequenceRef == seqRef)
1423 && (groupRef == null || alannot[i].groupRef == groupRef))
1425 alannot[i].setThreshold(new GraphLine(value, label, colour));
1431 void addGroup(AlignmentI al, StringTokenizer st)
1433 SequenceGroup sg = new SequenceGroup();
1434 sg.setName(st.nextToken());
1438 rng = st.nextToken();
1439 if (rng.length() > 0 && !rng.startsWith("*"))
1441 sg.setStartRes(Integer.parseInt(rng) - 1);
1447 rng = st.nextToken();
1448 if (rng.length() > 0 && !rng.startsWith("*"))
1450 sg.setEndRes(Integer.parseInt(rng) - 1);
1454 sg.setEndRes(al.getWidth() - 1);
1456 } catch (Exception e)
1459 "Couldn't parse Group Start or End Field as '*' or a valid column or sequence index: '"
1460 + rng + "' - assuming alignment width for group.");
1461 // assume group is full width
1463 sg.setEndRes(al.getWidth() - 1);
1466 String index = st.nextToken();
1467 if (index.equals("-1"))
1469 while (st.hasMoreElements())
1471 sg.addSequence(al.findName(st.nextToken()), false);
1476 StringTokenizer st2 = new StringTokenizer(index, ",");
1478 while (st2.hasMoreTokens())
1480 String tmp = st2.nextToken();
1481 if (tmp.equals("*"))
1483 for (int i = 0; i < al.getHeight(); i++)
1485 sg.addSequence(al.getSequenceAt(i), false);
1488 else if (tmp.indexOf("-") >= 0)
1490 StringTokenizer st3 = new StringTokenizer(tmp, "-");
1492 int start = (Integer.parseInt(st3.nextToken()));
1493 int end = (Integer.parseInt(st3.nextToken()));
1497 for (int i = start; i <= end; i++)
1499 sg.addSequence(al.getSequenceAt(i - 1), false);
1505 sg.addSequence(al.getSequenceAt(Integer.parseInt(tmp) - 1),
1513 sg.setStartRes(refSeq.findIndex(sg.getStartRes() + 1) - 1);
1514 sg.setEndRes(refSeq.findIndex(sg.getEndRes() + 1) - 1);
1515 sg.setSeqrep(refSeq);
1518 if (sg.getSize() > 0)
1524 void addRowProperties(AlignmentI al, StringTokenizer st)
1526 String label = st.nextToken(), keyValue, key, value;
1527 boolean scaletofit = false, centerlab = false, showalllabs = false;
1528 while (st.hasMoreTokens())
1530 keyValue = st.nextToken();
1531 key = keyValue.substring(0, keyValue.indexOf("="));
1532 value = keyValue.substring(keyValue.indexOf("=") + 1);
1533 if (key.equalsIgnoreCase("scaletofit"))
1535 scaletofit = Boolean.valueOf(value).booleanValue();
1537 if (key.equalsIgnoreCase("showalllabs"))
1539 showalllabs = Boolean.valueOf(value).booleanValue();
1541 if (key.equalsIgnoreCase("centrelabs"))
1543 centerlab = Boolean.valueOf(value).booleanValue();
1545 AlignmentAnnotation[] alr = al.getAlignmentAnnotation();
1548 for (int i = 0; i < alr.length; i++)
1550 if (alr[i].label.equalsIgnoreCase(label))
1552 alr[i].centreColLabels = centerlab;
1553 alr[i].scaleColLabel = scaletofit;
1554 alr[i].showAllColLabels = showalllabs;
1561 void addProperties(AlignmentI al, StringTokenizer st)
1564 // So far we have only added groups to the annotationHash,
1565 // the idea is in the future properties can be added to
1566 // alignments, other annotations etc
1567 if (al.getGroups() == null)
1572 String name = st.nextToken();
1573 SequenceGroup sg = null;
1574 for (SequenceGroup _sg : al.getGroups())
1576 if ((sg = _sg).getName().equals(name))
1588 String keyValue, key, value;
1589 ColourSchemeI def = sg.getColourScheme();
1590 while (st.hasMoreTokens())
1592 keyValue = st.nextToken();
1593 key = keyValue.substring(0, keyValue.indexOf("="));
1594 value = keyValue.substring(keyValue.indexOf("=") + 1);
1596 if (key.equalsIgnoreCase("description"))
1598 sg.setDescription(value);
1600 else if (key.equalsIgnoreCase("colour"))
1602 // TODO need to notify colourscheme of view reference once it is
1604 sg.cs.setColourScheme(
1605 ColourSchemeProperty.getColourScheme(null, al, value));
1607 else if (key.equalsIgnoreCase("pidThreshold"))
1609 sg.cs.setThreshold(Integer.parseInt(value), true);
1612 else if (key.equalsIgnoreCase("consThreshold"))
1614 sg.cs.setConservationInc(Integer.parseInt(value));
1615 Conservation c = new Conservation("Group", sg.getSequences(null),
1616 sg.getStartRes(), sg.getEndRes() + 1);
1619 c.verdict(false, 25); // TODO: refer to conservation percent threshold
1621 sg.cs.setConservation(c);
1624 else if (key.equalsIgnoreCase("outlineColour"))
1626 sg.setOutlineColour(ColorUtils.parseColourString(value));
1628 else if (key.equalsIgnoreCase("displayBoxes"))
1630 sg.setDisplayBoxes(Boolean.valueOf(value).booleanValue());
1632 else if (key.equalsIgnoreCase("showUnconserved"))
1634 sg.setShowNonconserved(Boolean.valueOf(value).booleanValue());
1636 else if (key.equalsIgnoreCase("displayText"))
1638 sg.setDisplayText(Boolean.valueOf(value).booleanValue());
1640 else if (key.equalsIgnoreCase("colourText"))
1642 sg.setColourText(Boolean.valueOf(value).booleanValue());
1644 else if (key.equalsIgnoreCase("textCol1"))
1646 sg.textColour = ColorUtils.parseColourString(value);
1648 else if (key.equalsIgnoreCase("textCol2"))
1650 sg.textColour2 = ColorUtils.parseColourString(value);
1652 else if (key.equalsIgnoreCase("textColThreshold"))
1654 sg.thresholdTextColour = Integer.parseInt(value);
1656 else if (key.equalsIgnoreCase("idColour"))
1658 Color idColour = ColorUtils.parseColourString(value);
1659 sg.setIdColour(idColour == null ? Color.black : idColour);
1661 else if (key.equalsIgnoreCase("hide"))
1663 // see bug https://mantis.lifesci.dundee.ac.uk/view.php?id=25847
1664 sg.setHidereps(true);
1666 else if (key.equalsIgnoreCase("hidecols"))
1668 // see bug https://mantis.lifesci.dundee.ac.uk/view.php?id=25847
1669 sg.setHideCols(true);
1671 sg.recalcConservation();
1673 if (sg.getColourScheme() == null)
1675 sg.setColourScheme(def);
1680 void setBelowAlignment(AlignmentI al, StringTokenizer st)
1683 AlignmentAnnotation aa, ala[] = al.getAlignmentAnnotation();
1687 "Warning - no annotation to set below for sequence associated annotation:");
1689 while (st.hasMoreTokens())
1691 token = st.nextToken();
1694 System.err.print(" " + token);
1698 for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1700 aa = al.getAlignmentAnnotation()[i];
1701 if (aa.sequenceRef == refSeq && aa.label.equals(token))
1703 aa.belowAlignment = true;
1710 System.err.print("\n");
1714 void addAlignmentDetails(AlignmentI al, StringTokenizer st)
1716 String keyValue, key, value;
1717 while (st.hasMoreTokens())
1719 keyValue = st.nextToken();
1720 key = keyValue.substring(0, keyValue.indexOf("="));
1721 value = keyValue.substring(keyValue.indexOf("=") + 1);
1722 al.setProperty(key, value);
1727 * Write annotations as a CSV file of the form 'label, value, value, ...' for
1730 * @param annotations
1731 * @return CSV file as a string.
1733 public String printCSVAnnotations(AlignmentAnnotation[] annotations)
1735 if (annotations == null)
1739 StringBuffer sp = new StringBuffer();
1740 for (int i = 0; i < annotations.length; i++)
1742 String atos = annotations[i].toString();
1746 int cp = atos.indexOf("\n", p);
1747 sp.append(annotations[i].label);
1751 sp.append(atos.substring(p, cp + 1));
1755 sp.append(atos.substring(p));
1761 return sp.toString();
1764 public String printAnnotationsForView(AlignViewportI viewport)
1766 return printAnnotations(
1767 viewport.isShowAnnotation()
1768 ? viewport.getAlignment().getAlignmentAnnotation()
1770 viewport.getAlignment().getGroups(),
1771 viewport.getAlignment().getProperties(),
1772 viewport.getAlignment().getHiddenColumns(),
1773 viewport.getAlignment(), null);
1776 public String printAnnotationsForAlignment(AlignmentI al)
1778 return printAnnotations(al.getAlignmentAnnotation(), al.getGroups(),
1779 al.getProperties(), null, al, null);