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 jalview.analysis.Conservation;
24 import jalview.api.AlignViewportI;
25 import jalview.datamodel.AlignmentAnnotation;
26 import jalview.datamodel.AlignmentI;
27 import jalview.datamodel.Annotation;
28 import jalview.datamodel.ColumnSelection;
29 import jalview.datamodel.GraphLine;
30 import jalview.datamodel.HiddenColumns;
31 import jalview.datamodel.HiddenSequences;
32 import jalview.datamodel.SequenceGroup;
33 import jalview.datamodel.SequenceI;
34 import jalview.schemes.ColourSchemeI;
35 import jalview.schemes.ColourSchemeProperty;
36 import jalview.util.ColorUtils;
38 import java.awt.Color;
39 import java.io.BufferedReader;
40 import java.io.FileReader;
41 import java.io.InputStreamReader;
42 import java.io.StringReader;
44 import java.util.ArrayList;
45 import java.util.BitSet;
46 import java.util.Enumeration;
47 import java.util.Hashtable;
48 import java.util.List;
50 import java.util.StringTokenizer;
51 import java.util.Vector;
53 public class AnnotationFile
55 public AnnotationFile()
61 * character used to write newlines
63 protected String newline = System.getProperty("line.separator");
66 * set new line string and reset the output buffer
70 public void setNewlineString(String nl)
76 public String getNewlineString()
85 text = new StringBuffer("JALVIEW_ANNOTATION" + newline + "# Created: "
86 + new java.util.Date() + newline + newline);
92 * convenience method for pre-2.9 annotation files which have no view, hidden
93 * columns or hidden row keywords.
98 * @return annotation file as a string.
100 public String printAnnotations(AlignmentAnnotation[] annotations,
101 List<SequenceGroup> list, Hashtable properties)
103 return printAnnotations(annotations, list, properties, null, null, null);
108 * hold all the information about a particular view definition read from or
109 * written out in an annotations file.
113 // TODO this class is not used - remove?
114 public final String viewname;
116 public final HiddenSequences hidseqs;
118 public final HiddenColumns hiddencols;
120 public final Hashtable hiddenRepSeqs;
122 public ViewDef(String vname, HiddenSequences hseqs,
123 HiddenColumns hcols, Hashtable hRepSeqs)
125 this.viewname = vname;
126 this.hidseqs = hseqs;
127 this.hiddencols = hcols;
128 this.hiddenRepSeqs = hRepSeqs;
133 * Prepare an annotation file given a set of annotations, groups, alignment
134 * properties and views.
140 * @return annotation file
142 public String printAnnotations(AlignmentAnnotation[] annotations,
143 List<SequenceGroup> list, Hashtable properties,
145 AlignmentI al, ViewDef view)
149 if (view.viewname != null)
151 text.append("VIEW_DEF\t" + view.viewname + "\n");
155 // list = view.visibleGroups;
159 cs = view.hiddencols;
163 // add hidden rep sequences.
166 // first target - store and restore all settings for a view.
167 if (al != null && al.hasSeqrep())
169 text.append("VIEW_SETREF\t" + al.getSeqrep().getName() + "\n");
171 if (cs != null && cs.hasHiddenColumns())
173 text.append("VIEW_HIDECOLS\t");
174 boolean comma = false;
175 for (int[] r : cs.getHiddenRegions())
191 // TODO: allow efficient recovery of annotation data shown in several
193 if (annotations != null)
195 boolean oneColour = true;
196 AlignmentAnnotation row;
198 SequenceI refSeq = null;
199 SequenceGroup refGroup = null;
201 StringBuffer colours = new StringBuffer();
202 StringBuffer graphLine = new StringBuffer();
203 StringBuffer rowprops = new StringBuffer();
204 Hashtable<Integer, String> graphGroup = new Hashtable<>();
205 Hashtable<Integer, Object[]> graphGroup_refs = new Hashtable<>();
206 BitSet graphGroupSeen = new BitSet();
208 java.awt.Color color;
210 for (int i = 0; i < annotations.length; i++)
212 row = annotations[i];
216 && !(row.graphGroup > -1 && graphGroupSeen
217 .get(row.graphGroup)))
225 // mark any sequence references for the row
226 writeSequence_Ref(refSeq, row.sequenceRef);
227 refSeq = row.sequenceRef;
228 // mark any group references for the row
229 writeGroup_Ref(refGroup, row.groupRef);
230 refGroup = row.groupRef;
232 boolean hasGlyphs = row.hasIcons, hasLabels = row.hasText, hasValues = row.hasScore, hasText = false;
233 // lookahead to check what the annotation row object actually contains.
234 for (int j = 0; row.annotations != null
235 && j < row.annotations.length
236 && (!hasGlyphs || !hasLabels || !hasValues); j++)
238 if (row.annotations[j] != null)
240 hasLabels |= (row.annotations[j].displayCharacter != null
241 && row.annotations[j].displayCharacter.length() > 0 && !row.annotations[j].displayCharacter
243 hasGlyphs |= (row.annotations[j].secondaryStructure != 0 && row.annotations[j].secondaryStructure != ' ');
244 hasValues |= (!Float.isNaN(row.annotations[j].value)); // NaNs can't
247 hasText |= (row.annotations[j].description != null && row.annotations[j].description
252 if (row.graph == AlignmentAnnotation.NO_GRAPH)
254 text.append("NO_GRAPH\t");
255 hasValues = false; // only secondary structure
256 // hasLabels = false; // and annotation description string.
260 if (row.graph == AlignmentAnnotation.BAR_GRAPH)
262 text.append("BAR_GRAPH\t");
263 hasGlyphs = false; // no secondary structure
266 else if (row.graph == AlignmentAnnotation.LINE_GRAPH)
268 hasGlyphs = false; // no secondary structure
269 text.append("LINE_GRAPH\t");
272 if (row.getThreshold() != null)
274 graphLine.append("GRAPHLINE\t");
275 graphLine.append(row.label);
276 graphLine.append("\t");
277 graphLine.append(row.getThreshold().value);
278 graphLine.append("\t");
279 graphLine.append(row.getThreshold().label);
280 graphLine.append("\t");
281 graphLine.append(jalview.util.Format.getHexString(row
282 .getThreshold().colour));
283 graphLine.append(newline);
286 if (row.graphGroup > -1)
288 graphGroupSeen.set(row.graphGroup);
289 Integer key = new Integer(row.graphGroup);
290 if (graphGroup.containsKey(key))
292 graphGroup.put(key, graphGroup.get(key) + "\t" + row.label);
297 graphGroup_refs.put(key, new Object[] { refSeq, refGroup });
298 graphGroup.put(key, row.label);
303 text.append(row.label + "\t");
304 if (row.description != null)
306 text.append(row.description + "\t");
308 for (int j = 0; row.annotations != null
309 && j < row.annotations.length; j++)
312 && jalview.util.Comparison.isGap(refSeq.getCharAt(j)))
317 if (row.annotations[j] != null)
320 if (hasGlyphs) // could be also hasGlyphs || ...
324 if (row.annotations[j].secondaryStructure != ' ')
326 // only write out the field if its not whitespace.
327 text.append(row.annotations[j].secondaryStructure);
333 if (!Float.isNaN(row.annotations[j].value))
335 text.append(comma + row.annotations[j].value);
339 // System.err.println("Skipping NaN - not valid value.");
340 text.append(comma + 0f);// row.annotations[j].value);
346 // TODO: labels are emitted after values for bar graphs.
347 if // empty labels are allowed, so
348 (row.annotations[j].displayCharacter != null
349 && row.annotations[j].displayCharacter.length() > 0
350 && !row.annotations[j].displayCharacter.equals(" "))
352 text.append(comma + row.annotations[j].displayCharacter);
358 if (row.annotations[j].description != null
359 && row.annotations[j].description.length() > 0
360 && !row.annotations[j].description
361 .equals(row.annotations[j].displayCharacter))
363 text.append(comma + row.annotations[j].description);
367 if (color != null && !color.equals(row.annotations[j].colour))
372 color = row.annotations[j].colour;
374 if (row.annotations[j].colour != null
375 && row.annotations[j].colour != java.awt.Color.black)
379 + jalview.util.Format
380 .getHexString(row.annotations[j].colour)
390 text.append("\t" + row.score);
393 text.append(newline);
395 if (color != null && color != java.awt.Color.black && oneColour)
397 colours.append("COLOUR\t");
398 colours.append(row.label);
399 colours.append("\t");
400 colours.append(jalview.util.Format.getHexString(color));
401 colours.append(newline);
403 if (row.scaleColLabel || row.showAllColLabels
404 || row.centreColLabels)
406 rowprops.append("ROWPROPERTIES\t");
407 rowprops.append(row.label);
408 rowprops.append("\tscaletofit=");
409 rowprops.append(row.scaleColLabel);
410 rowprops.append("\tshowalllabs=");
411 rowprops.append(row.showAllColLabels);
412 rowprops.append("\tcentrelabs=");
413 rowprops.append(row.centreColLabels);
414 rowprops.append(newline);
416 if (graphLine.length() > 0)
418 text.append(graphLine.toString());
419 graphLine.setLength(0);
423 text.append(newline);
425 text.append(colours.toString());
426 if (graphGroup.size() > 0)
428 SequenceI oldRefSeq = refSeq;
429 SequenceGroup oldRefGroup = refGroup;
430 for (Map.Entry<Integer, String> combine_statement : graphGroup
433 Object[] seqRefAndGroup = graphGroup_refs.get(combine_statement
436 writeSequence_Ref(refSeq, (SequenceI) seqRefAndGroup[0]);
437 refSeq = (SequenceI) seqRefAndGroup[0];
439 writeGroup_Ref(refGroup, (SequenceGroup) seqRefAndGroup[1]);
440 refGroup = (SequenceGroup) seqRefAndGroup[1];
441 text.append("COMBINE\t");
442 text.append(combine_statement.getValue());
443 text.append(newline);
445 writeSequence_Ref(refSeq, oldRefSeq);
448 writeGroup_Ref(refGroup, oldRefGroup);
449 refGroup = oldRefGroup;
451 text.append(rowprops.toString());
459 if (properties != null)
461 text.append(newline);
462 text.append(newline);
463 text.append("ALIGNMENT");
464 Enumeration en = properties.keys();
465 while (en.hasMoreElements())
467 String key = en.nextElement().toString();
471 text.append(properties.get(key));
473 // TODO: output alignment visualization settings here if required
474 // iterate through one or more views, defining, marking columns and rows
475 // as visible/hidden, and emmitting view properties.
476 // View specific annotation is
479 return text.toString();
482 private Object writeGroup_Ref(SequenceGroup refGroup,
483 SequenceGroup next_refGroup)
485 if (next_refGroup == null)
488 if (refGroup != null)
490 text.append(newline);
491 text.append("GROUP_REF\t");
492 text.append("ALIGNMENT");
493 text.append(newline);
499 if (refGroup == null || refGroup != next_refGroup)
501 text.append(newline);
502 text.append("GROUP_REF\t");
503 text.append(next_refGroup.getName());
504 text.append(newline);
511 private boolean writeSequence_Ref(SequenceI refSeq, SequenceI next_refSeq)
514 if (next_refSeq == null)
518 text.append(newline);
519 text.append("SEQUENCE_REF\t");
520 text.append("ALIGNMENT");
521 text.append(newline);
527 if (refSeq == null || refSeq != next_refSeq)
529 text.append(newline);
530 text.append("SEQUENCE_REF\t");
531 text.append(next_refSeq.getName());
532 text.append(newline);
539 protected void printGroups(List<SequenceGroup> list)
541 SequenceI seqrep = null;
542 for (SequenceGroup sg : list)
546 text.append("SEQUENCE_GROUP\t" + sg.getName() + "\t"
547 + (sg.getStartRes() + 1) + "\t" + (sg.getEndRes() + 1)
553 seqrep = sg.getSeqrep();
554 text.append("SEQUENCE_REF\t");
555 text.append(seqrep.getName());
556 text.append(newline);
557 text.append("SEQUENCE_GROUP\t");
558 text.append(sg.getName());
560 text.append((seqrep.findPosition(sg.getStartRes())));
562 text.append((seqrep.findPosition(sg.getEndRes())));
566 for (int s = 0; s < sg.getSize(); s++)
568 text.append(sg.getSequenceAt(s).getName());
571 text.append(newline);
572 text.append("PROPERTIES\t");
573 text.append(sg.getName());
576 if (sg.getDescription() != null)
578 text.append("description=");
579 text.append(sg.getDescription());
584 text.append("colour=");
585 text.append(ColourSchemeProperty.getColourName(sg.cs
586 .getColourScheme()));
588 if (sg.cs.getThreshold() != 0)
590 text.append("pidThreshold=");
591 text.append(sg.cs.getThreshold());
593 if (sg.cs.conservationApplied())
595 text.append("consThreshold=");
596 text.append(sg.cs.getConservationInc());
600 text.append("outlineColour=");
601 text.append(jalview.util.Format.getHexString(sg.getOutlineColour()));
604 text.append("displayBoxes=");
605 text.append(sg.getDisplayBoxes());
607 text.append("displayText=");
608 text.append(sg.getDisplayText());
610 text.append("colourText=");
611 text.append(sg.getColourText());
613 text.append("showUnconserved=");
614 text.append(sg.getShowNonconserved());
616 if (sg.textColour != java.awt.Color.black)
618 text.append("textCol1=");
619 text.append(jalview.util.Format.getHexString(sg.textColour));
622 if (sg.textColour2 != java.awt.Color.white)
624 text.append("textCol2=");
625 text.append(jalview.util.Format.getHexString(sg.textColour2));
628 if (sg.thresholdTextColour != 0)
630 text.append("textColThreshold=");
631 text.append(sg.thresholdTextColour);
634 if (sg.idColour != null)
636 text.append("idColour=");
637 text.append(jalview.util.Format.getHexString(sg.idColour));
642 text.append("hide=true\t");
646 text.append("hidecols=true\t");
650 // terminate the last line and clear the sequence ref for the group
651 text.append(newline);
652 text.append("SEQUENCE_REF");
654 text.append(newline);
655 text.append(newline);
660 SequenceI refSeq = null;
662 String refSeqId = null;
664 public boolean annotateAlignmentView(AlignViewportI viewport,
665 String file, DataSourceType protocol)
667 ColumnSelection colSel = viewport.getColumnSelection();
668 HiddenColumns hidden = viewport.getAlignment().getHiddenColumns();
671 colSel = new ColumnSelection();
675 hidden = new HiddenColumns();
677 boolean rslt = readAnnotationFile(viewport.getAlignment(), hidden,
679 if (rslt && (colSel.hasSelectedColumns() || hidden.hasHiddenColumns()))
681 viewport.setColumnSelection(colSel);
682 viewport.getAlignment().setHiddenColumns(hidden);
688 public boolean readAnnotationFile(AlignmentI al, String file,
689 DataSourceType sourceType)
691 return readAnnotationFile(al, null, file, sourceType);
694 public boolean readAnnotationFile(AlignmentI al, HiddenColumns hidden,
695 String file, DataSourceType sourceType)
697 BufferedReader in = null;
700 if (sourceType == DataSourceType.FILE)
702 in = new BufferedReader(new FileReader(file));
704 else if (sourceType == DataSourceType.URL)
706 URL url = new URL(file);
707 in = new BufferedReader(new InputStreamReader(url.openStream()));
709 else if (sourceType == DataSourceType.PASTE)
711 in = new BufferedReader(new StringReader(file));
713 else if (sourceType == DataSourceType.CLASSLOADER)
715 java.io.InputStream is = getClass().getResourceAsStream("/" + file);
718 in = new BufferedReader(new java.io.InputStreamReader(is));
723 return parseAnnotationFrom(al, hidden, in);
726 } catch (Exception ex)
728 ex.printStackTrace();
729 System.out.println("Problem reading annotation file: " + ex);
732 System.out.println("Last read line " + nlinesread + ": '"
733 + lastread + "' (first 80 chars) ...");
742 String lastread = "";
744 private static String GRAPHLINE = "GRAPHLINE", COMBINE = "COMBINE";
746 public boolean parseAnnotationFrom(AlignmentI al, HiddenColumns hidden,
747 BufferedReader in) throws Exception
750 ArrayList<Object[]> combineAnnotation_calls = new ArrayList<>();
751 ArrayList<Object[]> deferredAnnotation_calls = new ArrayList<>();
752 boolean modified = false;
753 String groupRef = null;
754 Hashtable groupRefRows = new Hashtable();
756 Hashtable autoAnnots = new Hashtable();
758 String line, label, description, token;
759 int graphStyle, index;
761 int existingAnnotations = 0;
762 // when true - will add new rows regardless of whether they are duplicate
763 // auto-annotation like consensus or conservation graphs
764 boolean overrideAutoAnnot = false;
765 if (al.getAlignmentAnnotation() != null)
767 existingAnnotations = al.getAlignmentAnnotation().length;
768 if (existingAnnotations > 0)
770 AlignmentAnnotation[] aa = al.getAlignmentAnnotation();
771 for (int aai = 0; aai < aa.length; aai++)
773 if (aa[aai].autoCalculated)
775 // make a note of the name and description
777 autoAnnotsKey(aa[aai], aa[aai].sequenceRef,
778 (aa[aai].groupRef == null ? null
779 : aa[aai].groupRef.getName())),
786 int alWidth = al.getWidth();
789 Annotation[] annotations;
790 AlignmentAnnotation annotation = null;
792 // First confirm this is an Annotation file
793 boolean jvAnnotationFile = false;
794 while ((line = in.readLine()) != null)
797 lastread = new String(line);
798 if (line.indexOf("#") == 0)
803 if (line.indexOf("JALVIEW_ANNOTATION") > -1)
805 jvAnnotationFile = true;
810 if (!jvAnnotationFile)
816 while ((line = in.readLine()) != null)
819 lastread = new String(line);
820 if (line.indexOf("#") == 0
821 || line.indexOf("JALVIEW_ANNOTATION") > -1
822 || line.length() == 0)
827 st = new StringTokenizer(line, "\t");
828 token = st.nextToken();
829 if (token.equalsIgnoreCase("COLOUR"))
831 // TODO: use graduated colour def'n here too
832 colourAnnotations(al, st.nextToken(), st.nextToken());
837 else if (token.equalsIgnoreCase(COMBINE))
839 // keep a record of current state and resolve groupRef at end
840 combineAnnotation_calls
841 .add(new Object[] { st, refSeq, groupRef });
845 else if (token.equalsIgnoreCase("ROWPROPERTIES"))
847 addRowProperties(al, st);
851 else if (token.equalsIgnoreCase(GRAPHLINE))
854 deferredAnnotation_calls.add(new Object[] { GRAPHLINE, st,
860 else if (token.equalsIgnoreCase("SEQUENCE_REF"))
862 if (st.hasMoreTokens())
864 refSeq = al.findName(refSeqId = st.nextToken());
871 refSeqIndex = Integer.parseInt(st.nextToken());
876 .println("WARNING: SEQUENCE_REF index must be > 0 in AnnotationFile");
878 } catch (Exception ex)
890 else if (token.equalsIgnoreCase("GROUP_REF"))
892 // Group references could be forward or backwards, so they are
893 // resolved after the whole file is read in
895 if (st.hasMoreTokens())
897 groupRef = st.nextToken();
898 if (groupRef.length() < 1)
900 groupRef = null; // empty string
904 if (groupRefRows.get(groupRef) == null)
906 groupRefRows.put(groupRef, new Vector());
912 else if (token.equalsIgnoreCase("SEQUENCE_GROUP"))
919 else if (token.equalsIgnoreCase("PROPERTIES"))
921 addProperties(al, st);
926 else if (token.equalsIgnoreCase("BELOW_ALIGNMENT"))
928 setBelowAlignment(al, st);
932 else if (token.equalsIgnoreCase("ALIGNMENT"))
934 addAlignmentDetails(al, st);
938 // else if (token.equalsIgnoreCase("VIEW_DEF"))
940 // addOrSetView(al,st);
944 else if (token.equalsIgnoreCase("VIEW_SETREF"))
948 al.setSeqrep(refSeq);
953 else if (token.equalsIgnoreCase("VIEW_HIDECOLS"))
955 if (st.hasMoreTokens())
959 hidden = new HiddenColumns();
961 parseHideCols(hidden, st.nextToken());
966 else if (token.equalsIgnoreCase("HIDE_INSERTIONS"))
968 SequenceI sr = refSeq == null ? al.getSeqrep() : refSeq;
971 sr = al.getSequenceAt(0);
978 .println("Cannot process HIDE_INSERTIONS without an alignment view: Ignoring line: "
983 // consider deferring this till after the file has been parsed ?
984 hidden.hideInsertionsFor(sr);
991 // Parse out the annotation row
992 graphStyle = AlignmentAnnotation.getGraphValueFromString(token);
993 label = st.nextToken();
996 annotations = new Annotation[alWidth];
998 float score = Float.NaN;
1000 if (st.hasMoreTokens())
1002 line = st.nextToken();
1004 if (line.indexOf("|") == -1)
1007 if (st.hasMoreTokens())
1009 line = st.nextToken();
1013 if (st.hasMoreTokens())
1015 // This must be the score
1016 score = Float.valueOf(st.nextToken()).floatValue();
1019 st = new StringTokenizer(line, "|", true);
1021 boolean emptyColumn = true;
1022 boolean onlyOneElement = (st.countTokens() == 1);
1024 while (st.hasMoreElements() && index < alWidth)
1026 token = st.nextToken().trim();
1032 score = Float.valueOf(token).floatValue();
1034 } catch (NumberFormatException ex)
1039 if (token.equals("|"))
1050 annotations[index++] = parseAnnotation(token, graphStyle);
1051 emptyColumn = false;
1057 annotation = new AlignmentAnnotation(label, description,
1058 (index == 0) ? null : annotations, 0, 0, graphStyle);
1060 annotation.score = score;
1061 if (!overrideAutoAnnot
1062 && autoAnnots.containsKey(autoAnnotsKey(annotation, refSeq,
1065 // skip - we've already got an automatic annotation of this type.
1068 // otherwise add it!
1072 annotation.belowAlignment = false;
1073 // make a copy of refSeq so we can find other matches in the alignment
1074 SequenceI referedSeq = refSeq;
1077 // copy before we do any mapping business.
1078 // TODO: verify that undo/redo with 1:many sequence associated
1079 // annotations can be undone correctly
1080 AlignmentAnnotation ann = new AlignmentAnnotation(annotation);
1082 .createSequenceMapping(referedSeq, refSeqIndex, false);
1083 annotation.adjustForAlignment();
1084 referedSeq.addAlignmentAnnotation(annotation);
1085 al.addAnnotation(annotation);
1086 al.setAnnotationIndex(annotation,
1087 al.getAlignmentAnnotation().length
1088 - existingAnnotations - 1);
1089 if (groupRef != null)
1091 ((Vector) groupRefRows.get(groupRef)).addElement(annotation);
1093 // and recover our virgin copy to use again if necessary.
1096 } while (refSeqId != null
1097 && (referedSeq = al.findName(referedSeq, refSeqId, true)) != null);
1101 al.addAnnotation(annotation);
1102 al.setAnnotationIndex(annotation,
1103 al.getAlignmentAnnotation().length - existingAnnotations
1105 if (groupRef != null)
1107 ((Vector) groupRefRows.get(groupRef)).addElement(annotation);
1110 // and set modification flag
1113 // Resolve the groupRefs
1114 Hashtable<String, SequenceGroup> groupRefLookup = new Hashtable<>();
1115 Enumeration en = groupRefRows.keys();
1117 while (en.hasMoreElements())
1119 groupRef = (String) en.nextElement();
1120 boolean matched = false;
1121 // Resolve group: TODO: add a getGroupByName method to alignments
1122 for (SequenceGroup theGroup : al.getGroups())
1124 if (theGroup.getName().equals(groupRef))
1128 // TODO: specify and implement duplication of alignment annotation
1129 // for multiple group references.
1131 .println("Ignoring 1:many group reference mappings for group name '"
1137 Vector rowset = (Vector) groupRefRows.get(groupRef);
1138 groupRefLookup.put(groupRef, theGroup);
1139 if (rowset != null && rowset.size() > 0)
1141 AlignmentAnnotation alan = null;
1142 for (int elm = 0, elmSize = rowset.size(); elm < elmSize; elm++)
1144 alan = (AlignmentAnnotation) rowset.elementAt(elm);
1145 alan.groupRef = theGroup;
1151 ((Vector) groupRefRows.get(groupRef)).removeAllElements();
1153 // process any deferred attribute settings for each context
1154 for (Object[] _deferred_args : deferredAnnotation_calls)
1156 if (_deferred_args[0] == GRAPHLINE)
1159 (StringTokenizer) _deferred_args[1], // st
1160 (SequenceI) _deferred_args[2], // refSeq
1161 (_deferred_args[3] == null) ? null : groupRefLookup
1162 .get(_deferred_args[3]) // the reference
1168 // finally, combine all the annotation rows within each context.
1170 * number of combine statements in this annotation file. Used to create
1171 * new groups for combined annotation graphs without disturbing existing
1174 int combinecount = 0;
1175 for (Object[] _combine_args : combineAnnotation_calls)
1177 combineAnnotations(al,
1179 (StringTokenizer) _combine_args[0], // st
1180 (SequenceI) _combine_args[1], // refSeq
1181 (_combine_args[2] == null) ? null : groupRefLookup
1182 .get(_combine_args[2]) // the reference group,
1190 private void parseHideCols(HiddenColumns hidden, String nextToken)
1192 StringTokenizer inval = new StringTokenizer(nextToken, ",");
1193 while (inval.hasMoreTokens())
1195 String range = inval.nextToken().trim();
1196 int from, to = range.indexOf("-");
1199 from = to = Integer.parseInt(range);
1202 hidden.hideColumns(from, to);
1207 from = Integer.parseInt(range.substring(0, to));
1208 if (to < range.length() - 1)
1210 to = Integer.parseInt(range.substring(to + 1));
1216 if (from > 0 && to >= from)
1218 hidden.hideColumns(from, to);
1224 private Object autoAnnotsKey(AlignmentAnnotation annotation,
1225 SequenceI refSeq, String groupRef)
1227 return annotation.graph + "\t" + annotation.label + "\t"
1228 + annotation.description + "\t"
1229 + (refSeq != null ? refSeq.getDisplayId(true) : "");
1232 Annotation parseAnnotation(String string, int graphStyle)
1234 // don't do the glyph test if we don't want secondary structure
1235 boolean hasSymbols = (graphStyle == AlignmentAnnotation.NO_GRAPH);
1236 String desc = null, displayChar = null;
1237 char ss = ' '; // secondaryStructure
1239 boolean parsedValue = false, dcset = false;
1242 Color colour = null;
1243 int i = string.indexOf("[");
1244 int j = string.indexOf("]");
1245 if (i > -1 && j > -1)
1247 colour = ColorUtils.parseColourString(string.substring(i + 1,
1249 if (i > 0 && string.charAt(i - 1) == ',')
1251 // clip the preceding comma as well
1254 string = string.substring(0, i) + string.substring(j + 1);
1257 StringTokenizer st = new StringTokenizer(string, ",", true);
1259 boolean seenContent = false;
1261 while (st.hasMoreTokens())
1264 token = st.nextToken().trim();
1265 if (token.equals(","))
1267 if (!seenContent && parsedValue && !dcset)
1269 // allow the value below the bar/line to be empty
1273 seenContent = false;
1285 displayChar = token;
1287 value = new Float(token).floatValue();
1290 } catch (NumberFormatException ex)
1296 if (token.length() == 1)
1298 displayChar = token;
1302 && (token.length() == 1 && "()<>[]{}AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz"
1305 // Either this character represents a helix or sheet
1306 // or an integer which can be displayed
1307 ss = token.charAt(0);
1308 if (displayChar.equals(token.substring(0, 1)))
1313 else if (desc == null || (parsedValue && pass > 2))
1319 // if (!dcset && string.charAt(string.length() - 1) == ',')
1321 // displayChar = " "; // empty display char symbol.
1323 if (displayChar != null && desc != null && desc.length() == 1)
1325 if (displayChar.length() > 1)
1327 // switch desc and displayChar - legacy support
1328 String tmp = displayChar;
1334 if (displayChar.equals(desc))
1336 // duplicate label - hangover from the 'robust parser' above
1341 Annotation anot = new Annotation(displayChar, desc, ss, value);
1343 anot.colour = colour;
1348 void colourAnnotations(AlignmentI al, String label, String colour)
1350 Color awtColour = ColorUtils.parseColourString(colour);
1351 Annotation[] annotations;
1352 for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1354 if (al.getAlignmentAnnotation()[i].label.equalsIgnoreCase(label))
1356 annotations = al.getAlignmentAnnotation()[i].annotations;
1357 for (int j = 0; j < annotations.length; j++)
1359 if (annotations[j] != null)
1361 annotations[j].colour = awtColour;
1368 void combineAnnotations(AlignmentI al, int combineCount,
1369 StringTokenizer st, SequenceI seqRef, SequenceGroup groupRef)
1371 String group = st.nextToken();
1372 // First make sure we are not overwriting the graphIndex
1374 if (al.getAlignmentAnnotation() != null)
1376 for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1378 AlignmentAnnotation aa = al.getAlignmentAnnotation()[i];
1380 if (aa.graphGroup > graphGroup)
1382 // try to number graphGroups in order of occurence.
1383 graphGroup = aa.graphGroup + 1;
1385 if (aa.sequenceRef == seqRef && aa.groupRef == groupRef
1386 && aa.label.equalsIgnoreCase(group))
1388 if (aa.graphGroup > -1)
1390 graphGroup = aa.graphGroup;
1394 if (graphGroup <= combineCount)
1396 graphGroup = combineCount + 1;
1398 aa.graphGroup = graphGroup;
1404 // Now update groups
1405 while (st.hasMoreTokens())
1407 group = st.nextToken();
1408 for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1410 AlignmentAnnotation aa = al.getAlignmentAnnotation()[i];
1411 if (aa.sequenceRef == seqRef && aa.groupRef == groupRef
1412 && aa.label.equalsIgnoreCase(group))
1414 aa.graphGroup = graphGroup;
1423 .println("Couldn't combine annotations. None are added to alignment yet!");
1427 void addLine(AlignmentI al, StringTokenizer st, SequenceI seqRef,
1428 SequenceGroup groupRef)
1430 String group = st.nextToken();
1431 AlignmentAnnotation[] alannot = al.getAlignmentAnnotation();
1432 String nextToken = st.nextToken();
1436 value = Float.valueOf(nextToken);
1437 } catch (NumberFormatException e)
1439 System.err.println("line " + nlinesread + ": Threshold '" + nextToken
1440 + "' invalid, setting to zero");
1442 String label = st.hasMoreTokens() ? st.nextToken() : null;
1443 Color colour = null;
1444 if (st.hasMoreTokens())
1446 colour = ColorUtils.parseColourString(st.nextToken());
1448 if (alannot != null)
1450 for (int i = 0; i < alannot.length; i++)
1452 if (alannot[i].label.equalsIgnoreCase(group)
1453 && (seqRef == null || alannot[i].sequenceRef == seqRef)
1454 && (groupRef == null || alannot[i].groupRef == groupRef))
1456 alannot[i].setThreshold(new GraphLine(value, label, colour));
1462 void addGroup(AlignmentI al, StringTokenizer st)
1464 SequenceGroup sg = new SequenceGroup();
1465 sg.setName(st.nextToken());
1469 rng = st.nextToken();
1470 if (rng.length() > 0 && !rng.startsWith("*"))
1472 sg.setStartRes(Integer.parseInt(rng) - 1);
1478 rng = st.nextToken();
1479 if (rng.length() > 0 && !rng.startsWith("*"))
1481 sg.setEndRes(Integer.parseInt(rng) - 1);
1485 sg.setEndRes(al.getWidth() - 1);
1487 } catch (Exception e)
1490 .println("Couldn't parse Group Start or End Field as '*' or a valid column or sequence index: '"
1491 + rng + "' - assuming alignment width for group.");
1492 // assume group is full width
1494 sg.setEndRes(al.getWidth() - 1);
1497 String index = st.nextToken();
1498 if (index.equals("-1"))
1500 while (st.hasMoreElements())
1502 sg.addSequence(al.findName(st.nextToken()), false);
1507 StringTokenizer st2 = new StringTokenizer(index, ",");
1509 while (st2.hasMoreTokens())
1511 String tmp = st2.nextToken();
1512 if (tmp.equals("*"))
1514 for (int i = 0; i < al.getHeight(); i++)
1516 sg.addSequence(al.getSequenceAt(i), false);
1519 else if (tmp.indexOf("-") >= 0)
1521 StringTokenizer st3 = new StringTokenizer(tmp, "-");
1523 int start = (Integer.parseInt(st3.nextToken()));
1524 int end = (Integer.parseInt(st3.nextToken()));
1528 for (int i = start; i <= end; i++)
1530 sg.addSequence(al.getSequenceAt(i - 1), false);
1536 sg.addSequence(al.getSequenceAt(Integer.parseInt(tmp) - 1), false);
1543 sg.setStartRes(refSeq.findIndex(sg.getStartRes() + 1) - 1);
1544 sg.setEndRes(refSeq.findIndex(sg.getEndRes() + 1) - 1);
1545 sg.setSeqrep(refSeq);
1548 if (sg.getSize() > 0)
1554 void addRowProperties(AlignmentI al, StringTokenizer st)
1556 String label = st.nextToken(), keyValue, key, value;
1557 boolean scaletofit = false, centerlab = false, showalllabs = false;
1558 while (st.hasMoreTokens())
1560 keyValue = st.nextToken();
1561 key = keyValue.substring(0, keyValue.indexOf("="));
1562 value = keyValue.substring(keyValue.indexOf("=") + 1);
1563 if (key.equalsIgnoreCase("scaletofit"))
1565 scaletofit = Boolean.valueOf(value).booleanValue();
1567 if (key.equalsIgnoreCase("showalllabs"))
1569 showalllabs = Boolean.valueOf(value).booleanValue();
1571 if (key.equalsIgnoreCase("centrelabs"))
1573 centerlab = Boolean.valueOf(value).booleanValue();
1575 AlignmentAnnotation[] alr = al.getAlignmentAnnotation();
1578 for (int i = 0; i < alr.length; i++)
1580 if (alr[i].label.equalsIgnoreCase(label))
1582 alr[i].centreColLabels = centerlab;
1583 alr[i].scaleColLabel = scaletofit;
1584 alr[i].showAllColLabels = showalllabs;
1591 void addProperties(AlignmentI al, StringTokenizer st)
1594 // So far we have only added groups to the annotationHash,
1595 // the idea is in the future properties can be added to
1596 // alignments, other annotations etc
1597 if (al.getGroups() == null)
1602 String name = st.nextToken();
1603 SequenceGroup sg = null;
1604 for (SequenceGroup _sg : al.getGroups())
1606 if ((sg = _sg).getName().equals(name))
1618 String keyValue, key, value;
1619 ColourSchemeI def = sg.getColourScheme();
1620 while (st.hasMoreTokens())
1622 keyValue = st.nextToken();
1623 key = keyValue.substring(0, keyValue.indexOf("="));
1624 value = keyValue.substring(keyValue.indexOf("=") + 1);
1626 if (key.equalsIgnoreCase("description"))
1628 sg.setDescription(value);
1630 else if (key.equalsIgnoreCase("colour"))
1632 sg.cs.setColourScheme(ColourSchemeProperty
1633 .getColourScheme(al, value));
1635 else if (key.equalsIgnoreCase("pidThreshold"))
1637 sg.cs.setThreshold(Integer.parseInt(value), true);
1640 else if (key.equalsIgnoreCase("consThreshold"))
1642 sg.cs.setConservationInc(Integer.parseInt(value));
1643 Conservation c = new Conservation("Group", sg.getSequences(null),
1644 sg.getStartRes(), sg.getEndRes() + 1);
1647 c.verdict(false, 25); // TODO: refer to conservation percent threshold
1649 sg.cs.setConservation(c);
1652 else if (key.equalsIgnoreCase("outlineColour"))
1654 sg.setOutlineColour(ColorUtils.parseColourString(value));
1656 else if (key.equalsIgnoreCase("displayBoxes"))
1658 sg.setDisplayBoxes(Boolean.valueOf(value).booleanValue());
1660 else if (key.equalsIgnoreCase("showUnconserved"))
1662 sg.setShowNonconserved(Boolean.valueOf(value).booleanValue());
1664 else if (key.equalsIgnoreCase("displayText"))
1666 sg.setDisplayText(Boolean.valueOf(value).booleanValue());
1668 else if (key.equalsIgnoreCase("colourText"))
1670 sg.setColourText(Boolean.valueOf(value).booleanValue());
1672 else if (key.equalsIgnoreCase("textCol1"))
1674 sg.textColour = ColorUtils.parseColourString(value);
1676 else if (key.equalsIgnoreCase("textCol2"))
1678 sg.textColour2 = ColorUtils.parseColourString(value);
1680 else if (key.equalsIgnoreCase("textColThreshold"))
1682 sg.thresholdTextColour = Integer.parseInt(value);
1684 else if (key.equalsIgnoreCase("idColour"))
1686 Color idColour = ColorUtils.parseColourString(value);
1687 sg.setIdColour(idColour == null ? Color.black : idColour);
1689 else if (key.equalsIgnoreCase("hide"))
1691 // see bug https://mantis.lifesci.dundee.ac.uk/view.php?id=25847
1692 sg.setHidereps(true);
1694 else if (key.equalsIgnoreCase("hidecols"))
1696 // see bug https://mantis.lifesci.dundee.ac.uk/view.php?id=25847
1697 sg.setHideCols(true);
1699 sg.recalcConservation();
1701 if (sg.getColourScheme() == null)
1703 sg.setColourScheme(def);
1708 void setBelowAlignment(AlignmentI al, StringTokenizer st)
1711 AlignmentAnnotation aa, ala[] = al.getAlignmentAnnotation();
1715 .print("Warning - no annotation to set below for sequence associated annotation:");
1717 while (st.hasMoreTokens())
1719 token = st.nextToken();
1722 System.err.print(" " + token);
1726 for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1728 aa = al.getAlignmentAnnotation()[i];
1729 if (aa.sequenceRef == refSeq && aa.label.equals(token))
1731 aa.belowAlignment = true;
1738 System.err.print("\n");
1742 void addAlignmentDetails(AlignmentI al, StringTokenizer st)
1744 String keyValue, key, value;
1745 while (st.hasMoreTokens())
1747 keyValue = st.nextToken();
1748 key = keyValue.substring(0, keyValue.indexOf("="));
1749 value = keyValue.substring(keyValue.indexOf("=") + 1);
1750 al.setProperty(key, value);
1755 * Write annotations as a CSV file of the form 'label, value, value, ...' for
1758 * @param annotations
1759 * @return CSV file as a string.
1761 public String printCSVAnnotations(AlignmentAnnotation[] annotations)
1763 if (annotations == null)
1767 StringBuffer sp = new StringBuffer();
1768 for (int i = 0; i < annotations.length; i++)
1770 String atos = annotations[i].toString();
1774 int cp = atos.indexOf("\n", p);
1775 sp.append(annotations[i].label);
1779 sp.append(atos.substring(p, cp + 1));
1783 sp.append(atos.substring(p));
1789 return sp.toString();
1792 public String printAnnotationsForView(AlignViewportI viewport)
1794 return printAnnotations(viewport.isShowAnnotation() ? viewport
1795 .getAlignment().getAlignmentAnnotation() : null, viewport
1796 .getAlignment().getGroups(), viewport.getAlignment()
1797 .getProperties(), viewport.getAlignment().getHiddenColumns(),
1798 viewport.getAlignment(), null);
1801 public String printAnnotationsForAlignment(AlignmentI al)
1803 return printAnnotations(al.getAlignmentAnnotation(), al.getGroups(),
1804 al.getProperties(), null, al, null);