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");
175 String regions = cs.regionsToString(",", "-");
176 text.append(regions);
179 // TODO: allow efficient recovery of annotation data shown in several
181 if (annotations != null)
183 boolean oneColour = true;
184 AlignmentAnnotation row;
186 SequenceI refSeq = null;
187 SequenceGroup refGroup = null;
189 StringBuffer colours = new StringBuffer();
190 StringBuffer graphLine = new StringBuffer();
191 StringBuffer rowprops = new StringBuffer();
192 Hashtable<Integer, String> graphGroup = new Hashtable<>();
193 Hashtable<Integer, Object[]> graphGroup_refs = new Hashtable<>();
194 BitSet graphGroupSeen = new BitSet();
196 java.awt.Color color;
198 for (int i = 0; i < annotations.length; i++)
200 row = annotations[i];
204 && !(row.graphGroup > -1 && graphGroupSeen
205 .get(row.graphGroup)))
213 // mark any sequence references for the row
214 writeSequence_Ref(refSeq, row.sequenceRef);
215 refSeq = row.sequenceRef;
216 // mark any group references for the row
217 writeGroup_Ref(refGroup, row.groupRef);
218 refGroup = row.groupRef;
220 boolean hasGlyphs = row.hasIcons, hasLabels = row.hasText, hasValues = row.hasScore, hasText = false;
221 // lookahead to check what the annotation row object actually contains.
222 for (int j = 0; row.annotations != null
223 && j < row.annotations.length
224 && (!hasGlyphs || !hasLabels || !hasValues); j++)
226 if (row.annotations[j] != null)
228 hasLabels |= (row.annotations[j].displayCharacter != null
229 && row.annotations[j].displayCharacter.length() > 0 && !row.annotations[j].displayCharacter
231 hasGlyphs |= (row.annotations[j].secondaryStructure != 0 && row.annotations[j].secondaryStructure != ' ');
232 hasValues |= (!Float.isNaN(row.annotations[j].value)); // NaNs can't
235 hasText |= (row.annotations[j].description != null && row.annotations[j].description
240 if (row.graph == AlignmentAnnotation.NO_GRAPH)
242 text.append("NO_GRAPH\t");
243 hasValues = false; // only secondary structure
244 // hasLabels = false; // and annotation description string.
248 if (row.graph == AlignmentAnnotation.BAR_GRAPH)
250 text.append("BAR_GRAPH\t");
251 hasGlyphs = false; // no secondary structure
254 else if (row.graph == AlignmentAnnotation.LINE_GRAPH)
256 hasGlyphs = false; // no secondary structure
257 text.append("LINE_GRAPH\t");
260 if (row.getThreshold() != null)
262 graphLine.append("GRAPHLINE\t");
263 graphLine.append(row.label);
264 graphLine.append("\t");
265 graphLine.append(row.getThreshold().value);
266 graphLine.append("\t");
267 graphLine.append(row.getThreshold().label);
268 graphLine.append("\t");
269 graphLine.append(jalview.util.Format.getHexString(row
270 .getThreshold().colour));
271 graphLine.append(newline);
274 if (row.graphGroup > -1)
276 graphGroupSeen.set(row.graphGroup);
277 Integer key = new Integer(row.graphGroup);
278 if (graphGroup.containsKey(key))
280 graphGroup.put(key, graphGroup.get(key) + "\t" + row.label);
285 graphGroup_refs.put(key, new Object[] { refSeq, refGroup });
286 graphGroup.put(key, row.label);
291 text.append(row.label + "\t");
292 if (row.description != null)
294 text.append(row.description + "\t");
296 for (int j = 0; row.annotations != null
297 && j < row.annotations.length; j++)
300 && jalview.util.Comparison.isGap(refSeq.getCharAt(j)))
305 if (row.annotations[j] != null)
308 if (hasGlyphs) // could be also hasGlyphs || ...
312 if (row.annotations[j].secondaryStructure != ' ')
314 // only write out the field if its not whitespace.
315 text.append(row.annotations[j].secondaryStructure);
321 if (!Float.isNaN(row.annotations[j].value))
323 text.append(comma + row.annotations[j].value);
327 // System.err.println("Skipping NaN - not valid value.");
328 text.append(comma + 0f);// row.annotations[j].value);
334 // TODO: labels are emitted after values for bar graphs.
335 if // empty labels are allowed, so
336 (row.annotations[j].displayCharacter != null
337 && row.annotations[j].displayCharacter.length() > 0
338 && !row.annotations[j].displayCharacter.equals(" "))
340 text.append(comma + row.annotations[j].displayCharacter);
346 if (row.annotations[j].description != null
347 && row.annotations[j].description.length() > 0
348 && !row.annotations[j].description
349 .equals(row.annotations[j].displayCharacter))
351 text.append(comma + row.annotations[j].description);
355 if (color != null && !color.equals(row.annotations[j].colour))
360 color = row.annotations[j].colour;
362 if (row.annotations[j].colour != null
363 && row.annotations[j].colour != java.awt.Color.black)
367 + jalview.util.Format
368 .getHexString(row.annotations[j].colour)
378 text.append("\t" + row.score);
381 text.append(newline);
383 if (color != null && color != java.awt.Color.black && oneColour)
385 colours.append("COLOUR\t");
386 colours.append(row.label);
387 colours.append("\t");
388 colours.append(jalview.util.Format.getHexString(color));
389 colours.append(newline);
391 if (row.scaleColLabel || row.showAllColLabels
392 || row.centreColLabels)
394 rowprops.append("ROWPROPERTIES\t");
395 rowprops.append(row.label);
396 rowprops.append("\tscaletofit=");
397 rowprops.append(row.scaleColLabel);
398 rowprops.append("\tshowalllabs=");
399 rowprops.append(row.showAllColLabels);
400 rowprops.append("\tcentrelabs=");
401 rowprops.append(row.centreColLabels);
402 rowprops.append(newline);
404 if (graphLine.length() > 0)
406 text.append(graphLine.toString());
407 graphLine.setLength(0);
411 text.append(newline);
413 text.append(colours.toString());
414 if (graphGroup.size() > 0)
416 SequenceI oldRefSeq = refSeq;
417 SequenceGroup oldRefGroup = refGroup;
418 for (Map.Entry<Integer, String> combine_statement : graphGroup
421 Object[] seqRefAndGroup = graphGroup_refs.get(combine_statement
424 writeSequence_Ref(refSeq, (SequenceI) seqRefAndGroup[0]);
425 refSeq = (SequenceI) seqRefAndGroup[0];
427 writeGroup_Ref(refGroup, (SequenceGroup) seqRefAndGroup[1]);
428 refGroup = (SequenceGroup) seqRefAndGroup[1];
429 text.append("COMBINE\t");
430 text.append(combine_statement.getValue());
431 text.append(newline);
433 writeSequence_Ref(refSeq, oldRefSeq);
436 writeGroup_Ref(refGroup, oldRefGroup);
437 refGroup = oldRefGroup;
439 text.append(rowprops.toString());
447 if (properties != null)
449 text.append(newline);
450 text.append(newline);
451 text.append("ALIGNMENT");
452 Enumeration en = properties.keys();
453 while (en.hasMoreElements())
455 String key = en.nextElement().toString();
459 text.append(properties.get(key));
461 // TODO: output alignment visualization settings here if required
462 // iterate through one or more views, defining, marking columns and rows
463 // as visible/hidden, and emmitting view properties.
464 // View specific annotation is
467 return text.toString();
470 private Object writeGroup_Ref(SequenceGroup refGroup,
471 SequenceGroup next_refGroup)
473 if (next_refGroup == null)
476 if (refGroup != null)
478 text.append(newline);
479 text.append("GROUP_REF\t");
480 text.append("ALIGNMENT");
481 text.append(newline);
487 if (refGroup == null || refGroup != next_refGroup)
489 text.append(newline);
490 text.append("GROUP_REF\t");
491 text.append(next_refGroup.getName());
492 text.append(newline);
499 private boolean writeSequence_Ref(SequenceI refSeq, SequenceI next_refSeq)
502 if (next_refSeq == null)
506 text.append(newline);
507 text.append("SEQUENCE_REF\t");
508 text.append("ALIGNMENT");
509 text.append(newline);
515 if (refSeq == null || refSeq != next_refSeq)
517 text.append(newline);
518 text.append("SEQUENCE_REF\t");
519 text.append(next_refSeq.getName());
520 text.append(newline);
527 protected void printGroups(List<SequenceGroup> list)
529 SequenceI seqrep = null;
530 for (SequenceGroup sg : list)
534 text.append("SEQUENCE_GROUP\t" + sg.getName() + "\t"
535 + (sg.getStartRes() + 1) + "\t" + (sg.getEndRes() + 1)
541 seqrep = sg.getSeqrep();
542 text.append("SEQUENCE_REF\t");
543 text.append(seqrep.getName());
544 text.append(newline);
545 text.append("SEQUENCE_GROUP\t");
546 text.append(sg.getName());
548 text.append((seqrep.findPosition(sg.getStartRes())));
550 text.append((seqrep.findPosition(sg.getEndRes())));
554 for (int s = 0; s < sg.getSize(); s++)
556 text.append(sg.getSequenceAt(s).getName());
559 text.append(newline);
560 text.append("PROPERTIES\t");
561 text.append(sg.getName());
564 if (sg.getDescription() != null)
566 text.append("description=");
567 text.append(sg.getDescription());
572 text.append("colour=");
573 text.append(ColourSchemeProperty.getColourName(sg.cs
574 .getColourScheme()));
576 if (sg.cs.getThreshold() != 0)
578 text.append("pidThreshold=");
579 text.append(sg.cs.getThreshold());
581 if (sg.cs.conservationApplied())
583 text.append("consThreshold=");
584 text.append(sg.cs.getConservationInc());
588 text.append("outlineColour=");
589 text.append(jalview.util.Format.getHexString(sg.getOutlineColour()));
592 text.append("displayBoxes=");
593 text.append(sg.getDisplayBoxes());
595 text.append("displayText=");
596 text.append(sg.getDisplayText());
598 text.append("colourText=");
599 text.append(sg.getColourText());
601 text.append("showUnconserved=");
602 text.append(sg.getShowNonconserved());
604 if (sg.textColour != java.awt.Color.black)
606 text.append("textCol1=");
607 text.append(jalview.util.Format.getHexString(sg.textColour));
610 if (sg.textColour2 != java.awt.Color.white)
612 text.append("textCol2=");
613 text.append(jalview.util.Format.getHexString(sg.textColour2));
616 if (sg.thresholdTextColour != 0)
618 text.append("textColThreshold=");
619 text.append(sg.thresholdTextColour);
622 if (sg.idColour != null)
624 text.append("idColour=");
625 text.append(jalview.util.Format.getHexString(sg.idColour));
630 text.append("hide=true\t");
634 text.append("hidecols=true\t");
638 // terminate the last line and clear the sequence ref for the group
639 text.append(newline);
640 text.append("SEQUENCE_REF");
642 text.append(newline);
643 text.append(newline);
648 SequenceI refSeq = null;
650 String refSeqId = null;
652 public boolean annotateAlignmentView(AlignViewportI viewport,
653 String file, DataSourceType protocol)
655 ColumnSelection colSel = viewport.getColumnSelection();
656 HiddenColumns hidden = viewport.getAlignment().getHiddenColumns();
659 colSel = new ColumnSelection();
663 hidden = new HiddenColumns();
665 boolean rslt = readAnnotationFile(viewport.getAlignment(), hidden,
667 if (rslt && (colSel.hasSelectedColumns() || hidden.hasHiddenColumns()))
669 viewport.setColumnSelection(colSel);
670 viewport.getAlignment().setHiddenColumns(hidden);
676 public boolean readAnnotationFile(AlignmentI al, String file,
677 DataSourceType sourceType)
679 return readAnnotationFile(al, null, file, sourceType);
682 public boolean readAnnotationFile(AlignmentI al, HiddenColumns hidden,
683 String file, DataSourceType sourceType)
685 BufferedReader in = null;
688 if (sourceType == DataSourceType.FILE)
690 in = new BufferedReader(new FileReader(file));
692 else if (sourceType == DataSourceType.URL)
694 URL url = new URL(file);
695 in = new BufferedReader(new InputStreamReader(url.openStream()));
697 else if (sourceType == DataSourceType.PASTE)
699 in = new BufferedReader(new StringReader(file));
701 else if (sourceType == DataSourceType.CLASSLOADER)
703 java.io.InputStream is = getClass().getResourceAsStream("/" + file);
706 in = new BufferedReader(new java.io.InputStreamReader(is));
711 return parseAnnotationFrom(al, hidden, in);
714 } catch (Exception ex)
716 ex.printStackTrace();
717 System.out.println("Problem reading annotation file: " + ex);
720 System.out.println("Last read line " + nlinesread + ": '"
721 + lastread + "' (first 80 chars) ...");
730 String lastread = "";
732 private static String GRAPHLINE = "GRAPHLINE", COMBINE = "COMBINE";
734 public boolean parseAnnotationFrom(AlignmentI al, HiddenColumns hidden,
735 BufferedReader in) throws Exception
738 ArrayList<Object[]> combineAnnotation_calls = new ArrayList<>();
739 ArrayList<Object[]> deferredAnnotation_calls = new ArrayList<>();
740 boolean modified = false;
741 String groupRef = null;
742 Hashtable groupRefRows = new Hashtable();
744 Hashtable autoAnnots = new Hashtable();
746 String line, label, description, token;
747 int graphStyle, index;
749 int existingAnnotations = 0;
750 // when true - will add new rows regardless of whether they are duplicate
751 // auto-annotation like consensus or conservation graphs
752 boolean overrideAutoAnnot = false;
753 if (al.getAlignmentAnnotation() != null)
755 existingAnnotations = al.getAlignmentAnnotation().length;
756 if (existingAnnotations > 0)
758 AlignmentAnnotation[] aa = al.getAlignmentAnnotation();
759 for (int aai = 0; aai < aa.length; aai++)
761 if (aa[aai].autoCalculated)
763 // make a note of the name and description
765 autoAnnotsKey(aa[aai], aa[aai].sequenceRef,
766 (aa[aai].groupRef == null ? null
767 : aa[aai].groupRef.getName())),
774 int alWidth = al.getWidth();
777 Annotation[] annotations;
778 AlignmentAnnotation annotation = null;
780 // First confirm this is an Annotation file
781 boolean jvAnnotationFile = false;
782 while ((line = in.readLine()) != null)
785 lastread = new String(line);
786 if (line.indexOf("#") == 0)
791 if (line.indexOf("JALVIEW_ANNOTATION") > -1)
793 jvAnnotationFile = true;
798 if (!jvAnnotationFile)
804 while ((line = in.readLine()) != null)
807 lastread = new String(line);
808 if (line.indexOf("#") == 0
809 || line.indexOf("JALVIEW_ANNOTATION") > -1
810 || line.length() == 0)
815 st = new StringTokenizer(line, "\t");
816 token = st.nextToken();
817 if (token.equalsIgnoreCase("COLOUR"))
819 // TODO: use graduated colour def'n here too
820 colourAnnotations(al, st.nextToken(), st.nextToken());
825 else if (token.equalsIgnoreCase(COMBINE))
827 // keep a record of current state and resolve groupRef at end
828 combineAnnotation_calls
829 .add(new Object[] { st, refSeq, groupRef });
833 else if (token.equalsIgnoreCase("ROWPROPERTIES"))
835 addRowProperties(al, st);
839 else if (token.equalsIgnoreCase(GRAPHLINE))
842 deferredAnnotation_calls.add(new Object[] { GRAPHLINE, st,
848 else if (token.equalsIgnoreCase("SEQUENCE_REF"))
850 if (st.hasMoreTokens())
852 refSeq = al.findName(refSeqId = st.nextToken());
859 refSeqIndex = Integer.parseInt(st.nextToken());
864 .println("WARNING: SEQUENCE_REF index must be > 0 in AnnotationFile");
866 } catch (Exception ex)
878 else if (token.equalsIgnoreCase("GROUP_REF"))
880 // Group references could be forward or backwards, so they are
881 // resolved after the whole file is read in
883 if (st.hasMoreTokens())
885 groupRef = st.nextToken();
886 if (groupRef.length() < 1)
888 groupRef = null; // empty string
892 if (groupRefRows.get(groupRef) == null)
894 groupRefRows.put(groupRef, new Vector());
900 else if (token.equalsIgnoreCase("SEQUENCE_GROUP"))
907 else if (token.equalsIgnoreCase("PROPERTIES"))
909 addProperties(al, st);
914 else if (token.equalsIgnoreCase("BELOW_ALIGNMENT"))
916 setBelowAlignment(al, st);
920 else if (token.equalsIgnoreCase("ALIGNMENT"))
922 addAlignmentDetails(al, st);
926 // else if (token.equalsIgnoreCase("VIEW_DEF"))
928 // addOrSetView(al,st);
932 else if (token.equalsIgnoreCase("VIEW_SETREF"))
936 al.setSeqrep(refSeq);
941 else if (token.equalsIgnoreCase("VIEW_HIDECOLS"))
943 if (st.hasMoreTokens())
947 hidden = new HiddenColumns();
949 parseHideCols(hidden, st.nextToken());
954 else if (token.equalsIgnoreCase("HIDE_INSERTIONS"))
956 SequenceI sr = refSeq == null ? al.getSeqrep() : refSeq;
959 sr = al.getSequenceAt(0);
966 .println("Cannot process HIDE_INSERTIONS without an alignment view: Ignoring line: "
971 // consider deferring this till after the file has been parsed ?
972 hidden.hideInsertionsFor(sr);
979 // Parse out the annotation row
980 graphStyle = AlignmentAnnotation.getGraphValueFromString(token);
981 label = st.nextToken();
984 annotations = new Annotation[alWidth];
986 float score = Float.NaN;
988 if (st.hasMoreTokens())
990 line = st.nextToken();
992 if (line.indexOf("|") == -1)
995 if (st.hasMoreTokens())
997 line = st.nextToken();
1001 if (st.hasMoreTokens())
1003 // This must be the score
1004 score = Float.valueOf(st.nextToken()).floatValue();
1007 st = new StringTokenizer(line, "|", true);
1009 boolean emptyColumn = true;
1010 boolean onlyOneElement = (st.countTokens() == 1);
1012 while (st.hasMoreElements() && index < alWidth)
1014 token = st.nextToken().trim();
1020 score = Float.valueOf(token).floatValue();
1022 } catch (NumberFormatException ex)
1027 if (token.equals("|"))
1038 annotations[index++] = parseAnnotation(token, graphStyle);
1039 emptyColumn = false;
1045 annotation = new AlignmentAnnotation(label, description,
1046 (index == 0) ? null : annotations, 0, 0, graphStyle);
1048 annotation.score = score;
1049 if (!overrideAutoAnnot
1050 && autoAnnots.containsKey(autoAnnotsKey(annotation, refSeq,
1053 // skip - we've already got an automatic annotation of this type.
1056 // otherwise add it!
1060 annotation.belowAlignment = false;
1061 // make a copy of refSeq so we can find other matches in the alignment
1062 SequenceI referedSeq = refSeq;
1065 // copy before we do any mapping business.
1066 // TODO: verify that undo/redo with 1:many sequence associated
1067 // annotations can be undone correctly
1068 AlignmentAnnotation ann = new AlignmentAnnotation(annotation);
1070 .createSequenceMapping(referedSeq, refSeqIndex, false);
1071 annotation.adjustForAlignment();
1072 referedSeq.addAlignmentAnnotation(annotation);
1073 al.addAnnotation(annotation);
1074 al.setAnnotationIndex(annotation,
1075 al.getAlignmentAnnotation().length
1076 - existingAnnotations - 1);
1077 if (groupRef != null)
1079 ((Vector) groupRefRows.get(groupRef)).addElement(annotation);
1081 // and recover our virgin copy to use again if necessary.
1084 } while (refSeqId != null
1085 && (referedSeq = al.findName(referedSeq, refSeqId, true)) != null);
1089 al.addAnnotation(annotation);
1090 al.setAnnotationIndex(annotation,
1091 al.getAlignmentAnnotation().length - existingAnnotations
1093 if (groupRef != null)
1095 ((Vector) groupRefRows.get(groupRef)).addElement(annotation);
1098 // and set modification flag
1101 // Resolve the groupRefs
1102 Hashtable<String, SequenceGroup> groupRefLookup = new Hashtable<>();
1103 Enumeration en = groupRefRows.keys();
1105 while (en.hasMoreElements())
1107 groupRef = (String) en.nextElement();
1108 boolean matched = false;
1109 // Resolve group: TODO: add a getGroupByName method to alignments
1110 for (SequenceGroup theGroup : al.getGroups())
1112 if (theGroup.getName().equals(groupRef))
1116 // TODO: specify and implement duplication of alignment annotation
1117 // for multiple group references.
1119 .println("Ignoring 1:many group reference mappings for group name '"
1125 Vector rowset = (Vector) groupRefRows.get(groupRef);
1126 groupRefLookup.put(groupRef, theGroup);
1127 if (rowset != null && rowset.size() > 0)
1129 AlignmentAnnotation alan = null;
1130 for (int elm = 0, elmSize = rowset.size(); elm < elmSize; elm++)
1132 alan = (AlignmentAnnotation) rowset.elementAt(elm);
1133 alan.groupRef = theGroup;
1139 ((Vector) groupRefRows.get(groupRef)).removeAllElements();
1141 // process any deferred attribute settings for each context
1142 for (Object[] _deferred_args : deferredAnnotation_calls)
1144 if (_deferred_args[0] == GRAPHLINE)
1147 (StringTokenizer) _deferred_args[1], // st
1148 (SequenceI) _deferred_args[2], // refSeq
1149 (_deferred_args[3] == null) ? null : groupRefLookup
1150 .get(_deferred_args[3]) // the reference
1156 // finally, combine all the annotation rows within each context.
1158 * number of combine statements in this annotation file. Used to create
1159 * new groups for combined annotation graphs without disturbing existing
1162 int combinecount = 0;
1163 for (Object[] _combine_args : combineAnnotation_calls)
1165 combineAnnotations(al,
1167 (StringTokenizer) _combine_args[0], // st
1168 (SequenceI) _combine_args[1], // refSeq
1169 (_combine_args[2] == null) ? null : groupRefLookup
1170 .get(_combine_args[2]) // the reference group,
1178 private void parseHideCols(HiddenColumns hidden, String nextToken)
1180 StringTokenizer inval = new StringTokenizer(nextToken, ",");
1181 while (inval.hasMoreTokens())
1183 String range = inval.nextToken().trim();
1184 int from, to = range.indexOf("-");
1187 from = to = Integer.parseInt(range);
1190 hidden.hideColumns(from, to);
1195 from = Integer.parseInt(range.substring(0, to));
1196 if (to < range.length() - 1)
1198 to = Integer.parseInt(range.substring(to + 1));
1204 if (from > 0 && to >= from)
1206 hidden.hideColumns(from, to);
1212 private Object autoAnnotsKey(AlignmentAnnotation annotation,
1213 SequenceI refSeq, String groupRef)
1215 return annotation.graph + "\t" + annotation.label + "\t"
1216 + annotation.description + "\t"
1217 + (refSeq != null ? refSeq.getDisplayId(true) : "");
1220 Annotation parseAnnotation(String string, int graphStyle)
1222 // don't do the glyph test if we don't want secondary structure
1223 boolean hasSymbols = (graphStyle == AlignmentAnnotation.NO_GRAPH);
1224 String desc = null, displayChar = null;
1225 char ss = ' '; // secondaryStructure
1227 boolean parsedValue = false, dcset = false;
1230 Color colour = null;
1231 int i = string.indexOf("[");
1232 int j = string.indexOf("]");
1233 if (i > -1 && j > -1)
1235 colour = ColorUtils.parseColourString(string.substring(i + 1,
1237 if (i > 0 && string.charAt(i - 1) == ',')
1239 // clip the preceding comma as well
1242 string = string.substring(0, i) + string.substring(j + 1);
1245 StringTokenizer st = new StringTokenizer(string, ",", true);
1247 boolean seenContent = false;
1249 while (st.hasMoreTokens())
1252 token = st.nextToken().trim();
1253 if (token.equals(","))
1255 if (!seenContent && parsedValue && !dcset)
1257 // allow the value below the bar/line to be empty
1261 seenContent = false;
1273 displayChar = token;
1275 value = new Float(token).floatValue();
1278 } catch (NumberFormatException ex)
1284 if (token.length() == 1)
1286 displayChar = token;
1290 && (token.length() == 1 && "()<>[]{}AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz"
1293 // Either this character represents a helix or sheet
1294 // or an integer which can be displayed
1295 ss = token.charAt(0);
1296 if (displayChar.equals(token.substring(0, 1)))
1301 else if (desc == null || (parsedValue && pass > 2))
1307 // if (!dcset && string.charAt(string.length() - 1) == ',')
1309 // displayChar = " "; // empty display char symbol.
1311 if (displayChar != null && desc != null && desc.length() == 1)
1313 if (displayChar.length() > 1)
1315 // switch desc and displayChar - legacy support
1316 String tmp = displayChar;
1322 if (displayChar.equals(desc))
1324 // duplicate label - hangover from the 'robust parser' above
1329 Annotation anot = new Annotation(displayChar, desc, ss, value);
1331 anot.colour = colour;
1336 void colourAnnotations(AlignmentI al, String label, String colour)
1338 Color awtColour = ColorUtils.parseColourString(colour);
1339 Annotation[] annotations;
1340 for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1342 if (al.getAlignmentAnnotation()[i].label.equalsIgnoreCase(label))
1344 annotations = al.getAlignmentAnnotation()[i].annotations;
1345 for (int j = 0; j < annotations.length; j++)
1347 if (annotations[j] != null)
1349 annotations[j].colour = awtColour;
1356 void combineAnnotations(AlignmentI al, int combineCount,
1357 StringTokenizer st, SequenceI seqRef, SequenceGroup groupRef)
1359 String group = st.nextToken();
1360 // First make sure we are not overwriting the graphIndex
1362 if (al.getAlignmentAnnotation() != null)
1364 for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1366 AlignmentAnnotation aa = al.getAlignmentAnnotation()[i];
1368 if (aa.graphGroup > graphGroup)
1370 // try to number graphGroups in order of occurence.
1371 graphGroup = aa.graphGroup + 1;
1373 if (aa.sequenceRef == seqRef && aa.groupRef == groupRef
1374 && aa.label.equalsIgnoreCase(group))
1376 if (aa.graphGroup > -1)
1378 graphGroup = aa.graphGroup;
1382 if (graphGroup <= combineCount)
1384 graphGroup = combineCount + 1;
1386 aa.graphGroup = graphGroup;
1392 // Now update groups
1393 while (st.hasMoreTokens())
1395 group = st.nextToken();
1396 for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1398 AlignmentAnnotation aa = al.getAlignmentAnnotation()[i];
1399 if (aa.sequenceRef == seqRef && aa.groupRef == groupRef
1400 && aa.label.equalsIgnoreCase(group))
1402 aa.graphGroup = graphGroup;
1411 .println("Couldn't combine annotations. None are added to alignment yet!");
1415 void addLine(AlignmentI al, StringTokenizer st, SequenceI seqRef,
1416 SequenceGroup groupRef)
1418 String group = st.nextToken();
1419 AlignmentAnnotation[] alannot = al.getAlignmentAnnotation();
1420 String nextToken = st.nextToken();
1424 value = Float.valueOf(nextToken);
1425 } catch (NumberFormatException e)
1427 System.err.println("line " + nlinesread + ": Threshold '" + nextToken
1428 + "' invalid, setting to zero");
1430 String label = st.hasMoreTokens() ? st.nextToken() : null;
1431 Color colour = null;
1432 if (st.hasMoreTokens())
1434 colour = ColorUtils.parseColourString(st.nextToken());
1436 if (alannot != null)
1438 for (int i = 0; i < alannot.length; i++)
1440 if (alannot[i].label.equalsIgnoreCase(group)
1441 && (seqRef == null || alannot[i].sequenceRef == seqRef)
1442 && (groupRef == null || alannot[i].groupRef == groupRef))
1444 alannot[i].setThreshold(new GraphLine(value, label, colour));
1450 void addGroup(AlignmentI al, StringTokenizer st)
1452 SequenceGroup sg = new SequenceGroup();
1453 sg.setName(st.nextToken());
1457 rng = st.nextToken();
1458 if (rng.length() > 0 && !rng.startsWith("*"))
1460 sg.setStartRes(Integer.parseInt(rng) - 1);
1466 rng = st.nextToken();
1467 if (rng.length() > 0 && !rng.startsWith("*"))
1469 sg.setEndRes(Integer.parseInt(rng) - 1);
1473 sg.setEndRes(al.getWidth() - 1);
1475 } catch (Exception e)
1478 .println("Couldn't parse Group Start or End Field as '*' or a valid column or sequence index: '"
1479 + rng + "' - assuming alignment width for group.");
1480 // assume group is full width
1482 sg.setEndRes(al.getWidth() - 1);
1485 String index = st.nextToken();
1486 if (index.equals("-1"))
1488 while (st.hasMoreElements())
1490 sg.addSequence(al.findName(st.nextToken()), false);
1495 StringTokenizer st2 = new StringTokenizer(index, ",");
1497 while (st2.hasMoreTokens())
1499 String tmp = st2.nextToken();
1500 if (tmp.equals("*"))
1502 for (int i = 0; i < al.getHeight(); i++)
1504 sg.addSequence(al.getSequenceAt(i), false);
1507 else if (tmp.indexOf("-") >= 0)
1509 StringTokenizer st3 = new StringTokenizer(tmp, "-");
1511 int start = (Integer.parseInt(st3.nextToken()));
1512 int end = (Integer.parseInt(st3.nextToken()));
1516 for (int i = start; i <= end; i++)
1518 sg.addSequence(al.getSequenceAt(i - 1), false);
1524 sg.addSequence(al.getSequenceAt(Integer.parseInt(tmp) - 1), false);
1531 sg.setStartRes(refSeq.findIndex(sg.getStartRes() + 1) - 1);
1532 sg.setEndRes(refSeq.findIndex(sg.getEndRes() + 1) - 1);
1533 sg.setSeqrep(refSeq);
1536 if (sg.getSize() > 0)
1542 void addRowProperties(AlignmentI al, StringTokenizer st)
1544 String label = st.nextToken(), keyValue, key, value;
1545 boolean scaletofit = false, centerlab = false, showalllabs = false;
1546 while (st.hasMoreTokens())
1548 keyValue = st.nextToken();
1549 key = keyValue.substring(0, keyValue.indexOf("="));
1550 value = keyValue.substring(keyValue.indexOf("=") + 1);
1551 if (key.equalsIgnoreCase("scaletofit"))
1553 scaletofit = Boolean.valueOf(value).booleanValue();
1555 if (key.equalsIgnoreCase("showalllabs"))
1557 showalllabs = Boolean.valueOf(value).booleanValue();
1559 if (key.equalsIgnoreCase("centrelabs"))
1561 centerlab = Boolean.valueOf(value).booleanValue();
1563 AlignmentAnnotation[] alr = al.getAlignmentAnnotation();
1566 for (int i = 0; i < alr.length; i++)
1568 if (alr[i].label.equalsIgnoreCase(label))
1570 alr[i].centreColLabels = centerlab;
1571 alr[i].scaleColLabel = scaletofit;
1572 alr[i].showAllColLabels = showalllabs;
1579 void addProperties(AlignmentI al, StringTokenizer st)
1582 // So far we have only added groups to the annotationHash,
1583 // the idea is in the future properties can be added to
1584 // alignments, other annotations etc
1585 if (al.getGroups() == null)
1590 String name = st.nextToken();
1591 SequenceGroup sg = null;
1592 for (SequenceGroup _sg : al.getGroups())
1594 if ((sg = _sg).getName().equals(name))
1606 String keyValue, key, value;
1607 ColourSchemeI def = sg.getColourScheme();
1608 while (st.hasMoreTokens())
1610 keyValue = st.nextToken();
1611 key = keyValue.substring(0, keyValue.indexOf("="));
1612 value = keyValue.substring(keyValue.indexOf("=") + 1);
1614 if (key.equalsIgnoreCase("description"))
1616 sg.setDescription(value);
1618 else if (key.equalsIgnoreCase("colour"))
1620 sg.cs.setColourScheme(ColourSchemeProperty
1621 .getColourScheme(al, value));
1623 else if (key.equalsIgnoreCase("pidThreshold"))
1625 sg.cs.setThreshold(Integer.parseInt(value), true);
1628 else if (key.equalsIgnoreCase("consThreshold"))
1630 sg.cs.setConservationInc(Integer.parseInt(value));
1631 Conservation c = new Conservation("Group", sg.getSequences(null),
1632 sg.getStartRes(), sg.getEndRes() + 1);
1635 c.verdict(false, 25); // TODO: refer to conservation percent threshold
1637 sg.cs.setConservation(c);
1640 else if (key.equalsIgnoreCase("outlineColour"))
1642 sg.setOutlineColour(ColorUtils.parseColourString(value));
1644 else if (key.equalsIgnoreCase("displayBoxes"))
1646 sg.setDisplayBoxes(Boolean.valueOf(value).booleanValue());
1648 else if (key.equalsIgnoreCase("showUnconserved"))
1650 sg.setShowNonconserved(Boolean.valueOf(value).booleanValue());
1652 else if (key.equalsIgnoreCase("displayText"))
1654 sg.setDisplayText(Boolean.valueOf(value).booleanValue());
1656 else if (key.equalsIgnoreCase("colourText"))
1658 sg.setColourText(Boolean.valueOf(value).booleanValue());
1660 else if (key.equalsIgnoreCase("textCol1"))
1662 sg.textColour = ColorUtils.parseColourString(value);
1664 else if (key.equalsIgnoreCase("textCol2"))
1666 sg.textColour2 = ColorUtils.parseColourString(value);
1668 else if (key.equalsIgnoreCase("textColThreshold"))
1670 sg.thresholdTextColour = Integer.parseInt(value);
1672 else if (key.equalsIgnoreCase("idColour"))
1674 Color idColour = ColorUtils.parseColourString(value);
1675 sg.setIdColour(idColour == null ? Color.black : idColour);
1677 else if (key.equalsIgnoreCase("hide"))
1679 // see bug https://mantis.lifesci.dundee.ac.uk/view.php?id=25847
1680 sg.setHidereps(true);
1682 else if (key.equalsIgnoreCase("hidecols"))
1684 // see bug https://mantis.lifesci.dundee.ac.uk/view.php?id=25847
1685 sg.setHideCols(true);
1687 sg.recalcConservation();
1689 if (sg.getColourScheme() == null)
1691 sg.setColourScheme(def);
1696 void setBelowAlignment(AlignmentI al, StringTokenizer st)
1699 AlignmentAnnotation aa, ala[] = al.getAlignmentAnnotation();
1703 .print("Warning - no annotation to set below for sequence associated annotation:");
1705 while (st.hasMoreTokens())
1707 token = st.nextToken();
1710 System.err.print(" " + token);
1714 for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1716 aa = al.getAlignmentAnnotation()[i];
1717 if (aa.sequenceRef == refSeq && aa.label.equals(token))
1719 aa.belowAlignment = true;
1726 System.err.print("\n");
1730 void addAlignmentDetails(AlignmentI al, StringTokenizer st)
1732 String keyValue, key, value;
1733 while (st.hasMoreTokens())
1735 keyValue = st.nextToken();
1736 key = keyValue.substring(0, keyValue.indexOf("="));
1737 value = keyValue.substring(keyValue.indexOf("=") + 1);
1738 al.setProperty(key, value);
1743 * Write annotations as a CSV file of the form 'label, value, value, ...' for
1746 * @param annotations
1747 * @return CSV file as a string.
1749 public String printCSVAnnotations(AlignmentAnnotation[] annotations)
1751 if (annotations == null)
1755 StringBuffer sp = new StringBuffer();
1756 for (int i = 0; i < annotations.length; i++)
1758 String atos = annotations[i].toString();
1762 int cp = atos.indexOf("\n", p);
1763 sp.append(annotations[i].label);
1767 sp.append(atos.substring(p, cp + 1));
1771 sp.append(atos.substring(p));
1777 return sp.toString();
1780 public String printAnnotationsForView(AlignViewportI viewport)
1782 return printAnnotations(viewport.isShowAnnotation() ? viewport
1783 .getAlignment().getAlignmentAnnotation() : null, viewport
1784 .getAlignment().getGroups(), viewport.getAlignment()
1785 .getProperties(), viewport.getAlignment().getHiddenColumns(),
1786 viewport.getAlignment(), null);
1789 public String printAnnotationsForAlignment(AlignmentI al)
1791 return printAnnotations(al.getAlignmentAnnotation(), al.getGroups(),
1792 al.getProperties(), null, al, null);