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.AlignmentAnnotation;
37 import jalview.datamodel.AlignmentI;
38 import jalview.datamodel.Annotation;
39 import jalview.datamodel.ColumnSelection;
40 import jalview.datamodel.GraphLine;
41 import jalview.datamodel.HiddenColumns;
42 import jalview.datamodel.HiddenSequences;
43 import jalview.datamodel.SequenceGroup;
44 import jalview.datamodel.SequenceI;
45 import jalview.schemes.ColourSchemeI;
46 import jalview.schemes.ColourSchemeProperty;
47 import jalview.util.ColorUtils;
49 public class AnnotationFile
51 private static final String GRAPHLINE = "GRAPHLINE";
53 private static final String COMBINE = "COMBINE";
55 protected String newline = System.getProperty("line.separator");
57 private StringBuffer text;
59 private SequenceI refSeq = null;
61 private String refSeqId = null;
63 private long nlinesread = 0;
65 private String lastread = "";
70 public AnnotationFile()
77 text = new StringBuffer("JALVIEW_ANNOTATION" + newline + "# Created: "
78 + new java.util.Date() + newline + newline);
84 * convenience method for pre-2.9 annotation files which have no view, hidden
85 * columns or hidden row keywords.
90 * @return annotation file as a string.
92 public String printAnnotations(AlignmentAnnotation[] annotations,
93 List<SequenceGroup> list, Hashtable properties)
95 return printAnnotations(annotations, list, properties, null, null,
101 * hold all the information about a particular view definition read from or
102 * written out in an annotations file.
106 // TODO this class is not used - remove?
107 public final String viewname;
109 public final HiddenSequences hidseqs;
111 public final HiddenColumns hiddencols;
113 public final Hashtable hiddenRepSeqs;
115 public ViewDef(String vname, HiddenSequences hseqs, HiddenColumns hcols,
118 this.viewname = vname;
119 this.hidseqs = hseqs;
120 this.hiddencols = hcols;
121 this.hiddenRepSeqs = hRepSeqs;
126 * Prepare an annotation file given a set of annotations, groups, alignment
127 * properties and views.
133 * @return annotation file
135 public String printAnnotations(AlignmentAnnotation[] annotations,
136 List<SequenceGroup> list, Hashtable properties, HiddenColumns cs,
137 AlignmentI al, ViewDef view)
141 if (view.viewname != null)
143 text.append("VIEW_DEF\t" + view.viewname + "\n");
147 // list = view.visibleGroups;
151 cs = view.hiddencols;
155 // add hidden rep sequences.
158 // first target - store and restore all settings for a view.
159 if (al != null && al.hasSeqrep())
161 text.append("VIEW_SETREF\t" + al.getSeqrep().getName() + "\n");
163 if (cs != null && cs.hasHiddenColumns())
165 text.append("VIEW_HIDECOLS\t");
167 String regions = cs.regionsToString(",", "-");
168 text.append(regions);
171 // TODO: allow efficient recovery of annotation data shown in several
173 if (annotations != null)
175 boolean oneColour = true;
176 AlignmentAnnotation row;
178 SequenceI refSeq = null;
179 SequenceGroup refGroup = null;
181 StringBuffer colours = new StringBuffer();
182 StringBuffer graphLine = new StringBuffer();
183 StringBuffer rowprops = new StringBuffer();
184 Hashtable<Integer, String> graphGroup = new Hashtable<>();
185 Hashtable<Integer, Object[]> graphGroup_refs = new Hashtable<>();
186 BitSet graphGroupSeen = new BitSet();
188 java.awt.Color color;
190 for (int i = 0; i < annotations.length; i++)
192 row = annotations[i];
194 if (!row.visible && !row.hasScore() && !(row.graphGroup > -1
195 && graphGroupSeen.get(row.graphGroup)))
203 // mark any sequence references for the row
204 writeSequence_Ref(refSeq, row.sequenceRef);
205 refSeq = row.sequenceRef;
206 // mark any group references for the row
207 writeGroup_Ref(refGroup, row.groupRef);
208 refGroup = row.groupRef;
210 boolean hasGlyphs = row.hasIcons, hasLabels = row.hasText,
211 hasValues = row.hasScore, hasText = false;
212 // lookahead to check what the annotation row object actually contains.
213 for (int j = 0; row.annotations != null
214 && j < row.annotations.length
215 && (!hasGlyphs || !hasLabels || !hasValues); j++)
217 if (row.annotations[j] != null)
219 hasLabels |= (row.annotations[j].displayCharacter != null
220 && row.annotations[j].displayCharacter.length() > 0
221 && !row.annotations[j].displayCharacter.equals(" "));
222 hasGlyphs |= (row.annotations[j].secondaryStructure != 0
223 && row.annotations[j].secondaryStructure != ' ');
224 hasValues |= (!Float.isNaN(row.annotations[j].value)); // NaNs can't
227 hasText |= (row.annotations[j].description != null
228 && row.annotations[j].description.length() > 0);
232 if (row.graph == AlignmentAnnotation.NO_GRAPH)
234 text.append("NO_GRAPH\t");
235 hasValues = false; // only secondary structure
236 // hasLabels = false; // and annotation description string.
240 if (row.graph == AlignmentAnnotation.BAR_GRAPH)
242 text.append("BAR_GRAPH\t");
243 hasGlyphs = false; // no secondary structure
246 else if (row.graph == AlignmentAnnotation.LINE_GRAPH)
248 hasGlyphs = false; // no secondary structure
249 text.append("LINE_GRAPH\t");
252 if (row.getThreshold() != null)
254 graphLine.append("GRAPHLINE\t");
255 graphLine.append(row.label);
256 graphLine.append("\t");
257 graphLine.append(row.getThreshold().value);
258 graphLine.append("\t");
259 graphLine.append(row.getThreshold().label);
260 graphLine.append("\t");
261 graphLine.append(jalview.util.Format
262 .getHexString(row.getThreshold().colour));
263 graphLine.append(newline);
266 if (row.graphGroup > -1)
268 graphGroupSeen.set(row.graphGroup);
269 Integer key = Integer.valueOf(row.graphGroup);
270 if (graphGroup.containsKey(key))
272 graphGroup.put(key, graphGroup.get(key) + "\t" + row.label);
277 graphGroup_refs.put(key, new Object[] { refSeq, refGroup });
278 graphGroup.put(key, row.label);
283 text.append(row.label + "\t");
284 if (row.description != null)
286 text.append(row.description + "\t");
288 for (int j = 0; row.annotations != null
289 && j < row.annotations.length; j++)
292 && jalview.util.Comparison.isGap(refSeq.getCharAt(j)))
297 if (row.annotations[j] != null)
300 if (hasGlyphs) // could be also hasGlyphs || ...
304 if (row.annotations[j].secondaryStructure != ' ')
306 // only write out the field if its not whitespace.
307 text.append(row.annotations[j].secondaryStructure);
313 if (!Float.isNaN(row.annotations[j].value))
315 text.append(comma + row.annotations[j].value);
319 // System.err.println("Skipping NaN - not valid value.");
320 text.append(comma + 0f);// row.annotations[j].value);
326 // TODO: labels are emitted after values for bar graphs.
327 if // empty labels are allowed, so
328 (row.annotations[j].displayCharacter != null
329 && row.annotations[j].displayCharacter.length() > 0
330 && !row.annotations[j].displayCharacter.equals(" "))
332 text.append(comma + row.annotations[j].displayCharacter);
338 if (row.annotations[j].description != null
339 && row.annotations[j].description.length() > 0
340 && !row.annotations[j].description
341 .equals(row.annotations[j].displayCharacter))
343 text.append(comma + row.annotations[j].description);
347 if (color != null && !color.equals(row.annotations[j].colour))
352 color = row.annotations[j].colour;
354 if (row.annotations[j].colour != null
355 && row.annotations[j].colour != java.awt.Color.black)
357 text.append(comma + "[" + jalview.util.Format
358 .getHexString(row.annotations[j].colour) + "]");
367 text.append("\t" + row.score);
370 text.append(newline);
372 if (color != null && color != java.awt.Color.black && oneColour)
374 colours.append("COLOUR\t");
375 colours.append(row.label);
376 colours.append("\t");
377 colours.append(jalview.util.Format.getHexString(color));
378 colours.append(newline);
380 if (row.scaleColLabel || row.showAllColLabels
381 || row.centreColLabels)
383 rowprops.append("ROWPROPERTIES\t");
384 rowprops.append(row.label);
385 rowprops.append("\tscaletofit=");
386 rowprops.append(row.scaleColLabel);
387 rowprops.append("\tshowalllabs=");
388 rowprops.append(row.showAllColLabels);
389 rowprops.append("\tcentrelabs=");
390 rowprops.append(row.centreColLabels);
391 rowprops.append(newline);
393 if (graphLine.length() > 0)
395 text.append(graphLine.toString());
396 graphLine.setLength(0);
400 text.append(newline);
402 text.append(colours.toString());
403 if (graphGroup.size() > 0)
405 SequenceI oldRefSeq = refSeq;
406 SequenceGroup oldRefGroup = refGroup;
407 for (Map.Entry<Integer, String> combine_statement : graphGroup
410 Object[] seqRefAndGroup = graphGroup_refs
411 .get(combine_statement.getKey());
413 writeSequence_Ref(refSeq, (SequenceI) seqRefAndGroup[0]);
414 refSeq = (SequenceI) seqRefAndGroup[0];
416 writeGroup_Ref(refGroup, (SequenceGroup) seqRefAndGroup[1]);
417 refGroup = (SequenceGroup) seqRefAndGroup[1];
418 text.append("COMBINE\t");
419 text.append(combine_statement.getValue());
420 text.append(newline);
422 writeSequence_Ref(refSeq, oldRefSeq);
425 writeGroup_Ref(refGroup, oldRefGroup);
426 refGroup = oldRefGroup;
428 text.append(rowprops.toString());
436 if (properties != null)
438 text.append(newline);
439 text.append(newline);
440 text.append("ALIGNMENT");
441 Enumeration en = properties.keys();
442 while (en.hasMoreElements())
444 String key = en.nextElement().toString();
448 text.append(properties.get(key));
450 // TODO: output alignment visualization settings here if required
451 // iterate through one or more views, defining, marking columns and rows
452 // as visible/hidden, and emmitting view properties.
453 // View specific annotation is
456 return text.toString();
459 private Object writeGroup_Ref(SequenceGroup refGroup,
460 SequenceGroup next_refGroup)
462 if (next_refGroup == null)
465 if (refGroup != null)
467 text.append(newline);
468 text.append("GROUP_REF\t");
469 text.append("ALIGNMENT");
470 text.append(newline);
476 if (refGroup == null || refGroup != next_refGroup)
478 text.append(newline);
479 text.append("GROUP_REF\t");
480 text.append(next_refGroup.getName());
481 text.append(newline);
488 private boolean writeSequence_Ref(SequenceI refSeq, SequenceI next_refSeq)
491 if (next_refSeq == null)
495 text.append(newline);
496 text.append("SEQUENCE_REF\t");
497 text.append("ALIGNMENT");
498 text.append(newline);
504 if (refSeq == null || refSeq != next_refSeq)
506 text.append(newline);
507 text.append("SEQUENCE_REF\t");
508 text.append(next_refSeq.getName());
509 text.append(newline);
516 protected void printGroups(List<SequenceGroup> list)
518 SequenceI seqrep = null;
519 for (SequenceGroup sg : list)
523 text.append("SEQUENCE_GROUP\t" + sg.getName() + "\t"
524 + (sg.getStartRes() + 1) + "\t" + (sg.getEndRes() + 1)
530 seqrep = sg.getSeqrep();
531 text.append("SEQUENCE_REF\t");
532 text.append(seqrep.getName());
533 text.append(newline);
534 text.append("SEQUENCE_GROUP\t");
535 text.append(sg.getName());
537 text.append((seqrep.findPosition(sg.getStartRes())));
539 text.append((seqrep.findPosition(sg.getEndRes())));
543 for (int s = 0; s < sg.getSize(); s++)
545 text.append(sg.getSequenceAt(s).getName());
548 text.append(newline);
549 text.append("PROPERTIES\t");
550 text.append(sg.getName());
553 if (sg.getDescription() != null)
555 text.append("description=");
556 text.append(sg.getDescription());
561 text.append("colour=");
562 text.append(ColourSchemeProperty
563 .getColourName(sg.cs.getColourScheme()));
565 if (sg.cs.getThreshold() != 0)
567 text.append("pidThreshold=");
568 text.append(sg.cs.getThreshold());
570 if (sg.cs.conservationApplied())
572 text.append("consThreshold=");
573 text.append(sg.cs.getConservationInc());
577 text.append("outlineColour=");
578 text.append(jalview.util.Format.getHexString(sg.getOutlineColour()));
581 text.append("displayBoxes=");
582 text.append(sg.getDisplayBoxes());
584 text.append("displayText=");
585 text.append(sg.getDisplayText());
587 text.append("colourText=");
588 text.append(sg.getColourText());
590 text.append("showUnconserved=");
591 text.append(sg.getShowNonconserved());
593 if (sg.textColour != java.awt.Color.black)
595 text.append("textCol1=");
596 text.append(jalview.util.Format.getHexString(sg.textColour));
599 if (sg.textColour2 != java.awt.Color.white)
601 text.append("textCol2=");
602 text.append(jalview.util.Format.getHexString(sg.textColour2));
605 if (sg.thresholdTextColour != 0)
607 text.append("textColThreshold=");
608 text.append(sg.thresholdTextColour);
611 if (sg.idColour != null)
613 text.append("idColour=");
614 text.append(jalview.util.Format.getHexString(sg.idColour));
619 text.append("hide=true\t");
623 text.append("hidecols=true\t");
627 // terminate the last line and clear the sequence ref for the group
628 text.append(newline);
629 text.append("SEQUENCE_REF");
631 text.append(newline);
632 text.append(newline);
637 public boolean annotateAlignmentView(AlignViewportI viewport, Object file,
638 DataSourceType protocol)
640 ColumnSelection colSel = viewport.getColumnSelection();
641 HiddenColumns hidden = viewport.getAlignment().getHiddenColumns();
644 colSel = new ColumnSelection();
648 hidden = new HiddenColumns();
650 boolean rslt = readAnnotationFile(viewport.getAlignment(), hidden, file,
652 if (rslt && (colSel.hasSelectedColumns() || hidden.hasHiddenColumns()))
654 viewport.setColumnSelection(colSel);
655 viewport.getAlignment().setHiddenColumns(hidden);
661 public boolean readAnnotationFile(AlignmentI al, String file,
662 DataSourceType sourceType)
664 return readAnnotationFile(al, null, file, sourceType);
667 public boolean readAnnotationFile(AlignmentI al, HiddenColumns hidden,
668 Object file, DataSourceType sourceType)
670 BufferedReader in = null;
673 in = new FileParse().getBufferedReader(file, sourceType);
676 return parseAnnotationFrom(al, hidden, in);
678 } catch (Exception ex)
680 ex.printStackTrace();
681 System.out.println("Problem reading annotation file: " + ex);
684 System.out.println("Last read line " + nlinesread + ": '" + lastread
685 + "' (first 80 chars) ...");
692 public boolean parseAnnotationFrom(AlignmentI al, HiddenColumns hidden,
693 BufferedReader in) throws Exception
696 ArrayList<Object[]> combineAnnotation_calls = new ArrayList<>();
697 ArrayList<Object[]> deferredAnnotation_calls = new ArrayList<>();
698 boolean modified = false;
699 String groupRef = null;
700 Hashtable groupRefRows = new Hashtable();
702 Hashtable autoAnnots = new Hashtable();
704 String line, label, description, token;
705 int graphStyle, index;
707 int existingAnnotations = 0;
708 // when true - will add new rows regardless of whether they are duplicate
709 // auto-annotation like consensus or conservation graphs
710 boolean overrideAutoAnnot = false;
711 if (al.getAlignmentAnnotation() != null)
713 existingAnnotations = al.getAlignmentAnnotation().length;
714 if (existingAnnotations > 0)
716 AlignmentAnnotation[] aa = al.getAlignmentAnnotation();
717 for (int aai = 0; aai < aa.length; aai++)
719 if (aa[aai].autoCalculated)
721 // make a note of the name and description
723 autoAnnotsKey(aa[aai], aa[aai].sequenceRef,
724 (aa[aai].groupRef == null ? null
725 : aa[aai].groupRef.getName())),
732 int alWidth = al.getWidth();
735 Annotation[] annotations;
736 AlignmentAnnotation annotation = null;
738 // First confirm this is an Annotation file
739 boolean jvAnnotationFile = false;
740 while ((line = in.readLine()) != null)
743 lastread = new String(line);
744 if (line.indexOf("#") == 0)
749 if (line.indexOf("JALVIEW_ANNOTATION") > -1)
751 jvAnnotationFile = true;
756 if (!jvAnnotationFile)
762 while ((line = in.readLine()) != null)
765 lastread = new String(line);
766 if (line.indexOf("#") == 0
767 || line.indexOf("JALVIEW_ANNOTATION") > -1
768 || line.length() == 0)
773 st = new StringTokenizer(line, "\t");
774 token = st.nextToken();
775 if (token.equalsIgnoreCase("COLOUR"))
777 // TODO: use graduated colour def'n here too
778 colourAnnotations(al, st.nextToken(), st.nextToken());
783 else if (token.equalsIgnoreCase(COMBINE))
785 // keep a record of current state and resolve groupRef at end
786 combineAnnotation_calls
788 { st, refSeq, groupRef });
792 else if (token.equalsIgnoreCase("ROWPROPERTIES"))
794 addRowProperties(al, st);
798 else if (token.equalsIgnoreCase(GRAPHLINE))
801 deferredAnnotation_calls
803 { GRAPHLINE, st, refSeq, groupRef });
808 else if (token.equalsIgnoreCase("SEQUENCE_REF"))
810 if (st.hasMoreTokens())
812 refSeq = al.findName(refSeqId = st.nextToken());
819 refSeqIndex = Integer.parseInt(st.nextToken());
824 "WARNING: SEQUENCE_REF index must be > 0 in AnnotationFile");
826 } catch (Exception ex)
838 else if (token.equalsIgnoreCase("GROUP_REF"))
840 // Group references could be forward or backwards, so they are
841 // resolved after the whole file is read in
843 if (st.hasMoreTokens())
845 groupRef = st.nextToken();
846 if (groupRef.length() < 1)
848 groupRef = null; // empty string
852 if (groupRefRows.get(groupRef) == null)
854 groupRefRows.put(groupRef, new Vector());
860 else if (token.equalsIgnoreCase("SEQUENCE_GROUP"))
867 else if (token.equalsIgnoreCase("PROPERTIES"))
869 addProperties(al, st);
874 else if (token.equalsIgnoreCase("BELOW_ALIGNMENT"))
876 setBelowAlignment(al, st);
880 else if (token.equalsIgnoreCase("ALIGNMENT"))
882 addAlignmentDetails(al, st);
886 // else if (token.equalsIgnoreCase("VIEW_DEF"))
888 // addOrSetView(al,st);
892 else if (token.equalsIgnoreCase("VIEW_SETREF"))
896 al.setSeqrep(refSeq);
901 else if (token.equalsIgnoreCase("VIEW_HIDECOLS"))
903 if (st.hasMoreTokens())
907 hidden = new HiddenColumns();
909 parseHideCols(hidden, st.nextToken());
914 else if (token.equalsIgnoreCase("HIDE_INSERTIONS"))
916 SequenceI sr = refSeq == null ? al.getSeqrep() : refSeq;
919 sr = al.getSequenceAt(0);
926 "Cannot process HIDE_INSERTIONS without an alignment view: Ignoring line: "
931 // consider deferring this till after the file has been parsed ?
932 hidden.hideList(sr.getInsertions());
939 // Parse out the annotation row
940 graphStyle = AlignmentAnnotation.getGraphValueFromString(token);
941 label = st.nextToken();
944 annotations = new Annotation[alWidth];
946 float score = Float.NaN;
948 if (st.hasMoreTokens())
950 line = st.nextToken();
952 if (line.indexOf("|") == -1)
955 if (st.hasMoreTokens())
957 line = st.nextToken();
961 if (st.hasMoreTokens())
963 // This must be the score
964 score = Float.valueOf(st.nextToken()).floatValue();
967 st = new StringTokenizer(line, "|", true);
969 boolean emptyColumn = true;
970 boolean onlyOneElement = (st.countTokens() == 1);
972 while (st.hasMoreElements() && index < alWidth)
974 token = st.nextToken().trim();
980 score = Float.valueOf(token).floatValue();
982 } catch (NumberFormatException ex)
987 if (token.equals("|"))
998 annotations[index++] = parseAnnotation(token, graphStyle);
1005 annotation = new AlignmentAnnotation(label, description,
1006 (index == 0) ? null : annotations, 0, 0, graphStyle);
1008 annotation.score = score;
1009 if (!overrideAutoAnnot && autoAnnots
1010 .containsKey(autoAnnotsKey(annotation, refSeq, groupRef)))
1012 // skip - we've already got an automatic annotation of this type.
1015 // otherwise add it!
1019 annotation.belowAlignment = false;
1020 // make a copy of refSeq so we can find other matches in the alignment
1021 SequenceI referedSeq = refSeq;
1024 // copy before we do any mapping business.
1025 // TODO: verify that undo/redo with 1:many sequence associated
1026 // annotations can be undone correctly
1027 AlignmentAnnotation ann = new AlignmentAnnotation(annotation);
1028 annotation.createSequenceMapping(referedSeq, refSeqIndex,
1030 annotation.adjustForAlignment();
1031 referedSeq.addAlignmentAnnotation(annotation);
1032 al.addAnnotation(annotation);
1033 al.setAnnotationIndex(annotation,
1034 al.getAlignmentAnnotation().length - existingAnnotations
1036 if (groupRef != null)
1038 ((Vector) groupRefRows.get(groupRef)).addElement(annotation);
1040 // and recover our virgin copy to use again if necessary.
1043 } while (refSeqId != null && (referedSeq = al.findName(referedSeq,
1044 refSeqId, true)) != null);
1048 al.addAnnotation(annotation);
1049 al.setAnnotationIndex(annotation,
1050 al.getAlignmentAnnotation().length - existingAnnotations
1052 if (groupRef != null)
1054 ((Vector) groupRefRows.get(groupRef)).addElement(annotation);
1057 // and set modification flag
1060 // Resolve the groupRefs
1061 Hashtable<String, SequenceGroup> groupRefLookup = new Hashtable<>();
1062 Enumeration en = groupRefRows.keys();
1064 while (en.hasMoreElements())
1066 groupRef = (String) en.nextElement();
1067 boolean matched = false;
1068 // Resolve group: TODO: add a getGroupByName method to alignments
1069 for (SequenceGroup theGroup : al.getGroups())
1071 if (theGroup.getName().equals(groupRef))
1075 // TODO: specify and implement duplication of alignment annotation
1076 // for multiple group references.
1078 "Ignoring 1:many group reference mappings for group name '"
1084 Vector rowset = (Vector) groupRefRows.get(groupRef);
1085 groupRefLookup.put(groupRef, theGroup);
1086 if (rowset != null && rowset.size() > 0)
1088 AlignmentAnnotation alan = null;
1089 for (int elm = 0, elmSize = rowset
1090 .size(); elm < elmSize; elm++)
1092 alan = (AlignmentAnnotation) rowset.elementAt(elm);
1093 alan.groupRef = theGroup;
1099 ((Vector) groupRefRows.get(groupRef)).removeAllElements();
1101 // process any deferred attribute settings for each context
1102 for (Object[] _deferred_args : deferredAnnotation_calls)
1104 if (_deferred_args[0] == GRAPHLINE)
1106 addLine(al, (StringTokenizer) _deferred_args[1], // st
1107 (SequenceI) _deferred_args[2], // refSeq
1108 (_deferred_args[3] == null) ? null
1109 : groupRefLookup.get(_deferred_args[3]) // the
1117 // finally, combine all the annotation rows within each context.
1119 * number of combine statements in this annotation file. Used to create
1120 * new groups for combined annotation graphs without disturbing existing
1123 int combinecount = 0;
1124 for (Object[] _combine_args : combineAnnotation_calls)
1126 combineAnnotations(al, ++combinecount,
1127 (StringTokenizer) _combine_args[0], // st
1128 (SequenceI) _combine_args[1], // refSeq
1129 (_combine_args[2] == null) ? null
1130 : groupRefLookup.get(_combine_args[2]) // the reference
1139 private void parseHideCols(HiddenColumns hidden, String nextToken)
1141 StringTokenizer inval = new StringTokenizer(nextToken, ",");
1142 while (inval.hasMoreTokens())
1144 String range = inval.nextToken().trim();
1145 int from, to = range.indexOf("-");
1148 from = to = Integer.parseInt(range);
1151 hidden.hideColumns(from, to);
1156 from = Integer.parseInt(range.substring(0, to));
1157 if (to < range.length() - 1)
1159 to = Integer.parseInt(range.substring(to + 1));
1165 if (from > 0 && to >= from)
1167 hidden.hideColumns(from, to);
1173 private Object autoAnnotsKey(AlignmentAnnotation annotation,
1174 SequenceI refSeq, String groupRef)
1176 return annotation.graph + "\t" + annotation.label + "\t"
1177 + annotation.description + "\t"
1178 + (refSeq != null ? refSeq.getDisplayId(true) : "");
1181 Annotation parseAnnotation(String string, int graphStyle)
1183 // don't do the glyph test if we don't want secondary structure
1184 boolean hasSymbols = (graphStyle == AlignmentAnnotation.NO_GRAPH);
1185 String desc = null, displayChar = null;
1186 char ss = ' '; // secondaryStructure
1188 boolean parsedValue = false, dcset = false;
1191 Color colour = null;
1192 int i = string.indexOf("[");
1193 int j = string.indexOf("]");
1194 if (i > -1 && j > -1)
1196 colour = ColorUtils.parseColourString(string.substring(i + 1, j));
1197 if (i > 0 && string.charAt(i - 1) == ',')
1199 // clip the preceding comma as well
1202 string = string.substring(0, i) + string.substring(j + 1);
1205 StringTokenizer st = new StringTokenizer(string, ",", true);
1207 boolean seenContent = false;
1209 while (st.hasMoreTokens())
1212 token = st.nextToken().trim();
1213 if (token.equals(","))
1215 if (!seenContent && parsedValue && !dcset)
1217 // allow the value below the bar/line to be empty
1221 seenContent = false;
1233 displayChar = token;
1235 value = Float.valueOf(token).floatValue();
1238 } catch (NumberFormatException ex)
1244 if (token.length() == 1)
1246 displayChar = token;
1249 if (hasSymbols && (token.length() == 1
1250 && "()<>[]{}AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz"
1253 // Either this character represents a helix or sheet
1254 // or an integer which can be displayed
1255 ss = token.charAt(0);
1256 if (displayChar.equals(token.substring(0, 1)))
1261 else if (desc == null || (parsedValue && pass > 2))
1267 // if (!dcset && string.charAt(string.length() - 1) == ',')
1269 // displayChar = " "; // empty display char symbol.
1271 if (displayChar != null && desc != null && desc.length() == 1)
1273 if (displayChar.length() > 1)
1275 // switch desc and displayChar - legacy support
1276 String tmp = displayChar;
1282 if (displayChar.equals(desc))
1284 // duplicate label - hangover from the 'robust parser' above
1289 Annotation anot = new Annotation(displayChar, desc, ss, value);
1291 anot.colour = colour;
1296 void colourAnnotations(AlignmentI al, String label, String colour)
1298 Color awtColour = ColorUtils.parseColourString(colour);
1299 Annotation[] annotations;
1300 for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1302 if (al.getAlignmentAnnotation()[i].label.equalsIgnoreCase(label))
1304 annotations = al.getAlignmentAnnotation()[i].annotations;
1305 for (int j = 0; j < annotations.length; j++)
1307 if (annotations[j] != null)
1309 annotations[j].colour = awtColour;
1316 void combineAnnotations(AlignmentI al, int combineCount,
1317 StringTokenizer st, SequenceI seqRef, SequenceGroup groupRef)
1319 String group = st.nextToken();
1320 // First make sure we are not overwriting the graphIndex
1322 if (al.getAlignmentAnnotation() != null)
1324 for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1326 AlignmentAnnotation aa = al.getAlignmentAnnotation()[i];
1328 if (aa.graphGroup > graphGroup)
1330 // try to number graphGroups in order of occurence.
1331 graphGroup = aa.graphGroup + 1;
1333 if (aa.sequenceRef == seqRef && aa.groupRef == groupRef
1334 && aa.label.equalsIgnoreCase(group))
1336 if (aa.graphGroup > -1)
1338 graphGroup = aa.graphGroup;
1342 if (graphGroup <= combineCount)
1344 graphGroup = combineCount + 1;
1346 aa.graphGroup = graphGroup;
1352 // Now update groups
1353 while (st.hasMoreTokens())
1355 group = st.nextToken();
1356 for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1358 AlignmentAnnotation aa = al.getAlignmentAnnotation()[i];
1359 if (aa.sequenceRef == seqRef && aa.groupRef == groupRef
1360 && aa.label.equalsIgnoreCase(group))
1362 aa.graphGroup = graphGroup;
1371 "Couldn't combine annotations. None are added to alignment yet!");
1375 void addLine(AlignmentI al, StringTokenizer st, SequenceI seqRef,
1376 SequenceGroup groupRef)
1378 String group = st.nextToken();
1379 AlignmentAnnotation[] alannot = al.getAlignmentAnnotation();
1380 String nextToken = st.nextToken();
1384 value = Float.valueOf(nextToken);
1385 } catch (NumberFormatException e)
1387 System.err.println("line " + nlinesread + ": Threshold '" + nextToken
1388 + "' invalid, setting to zero");
1390 String label = st.hasMoreTokens() ? st.nextToken() : null;
1391 Color colour = null;
1392 if (st.hasMoreTokens())
1394 colour = ColorUtils.parseColourString(st.nextToken());
1396 if (alannot != null)
1398 for (int i = 0; i < alannot.length; i++)
1400 if (alannot[i].label.equalsIgnoreCase(group)
1401 && (seqRef == null || alannot[i].sequenceRef == seqRef)
1402 && (groupRef == null || alannot[i].groupRef == groupRef))
1404 alannot[i].setThreshold(new GraphLine(value, label, colour));
1410 void addGroup(AlignmentI al, StringTokenizer st)
1412 SequenceGroup sg = new SequenceGroup();
1413 sg.setName(st.nextToken());
1417 rng = st.nextToken();
1418 if (rng.length() > 0 && !rng.startsWith("*"))
1420 sg.setStartRes(Integer.parseInt(rng) - 1);
1426 rng = st.nextToken();
1427 if (rng.length() > 0 && !rng.startsWith("*"))
1429 sg.setEndRes(Integer.parseInt(rng) - 1);
1433 sg.setEndRes(al.getWidth() - 1);
1435 } catch (Exception e)
1438 "Couldn't parse Group Start or End Field as '*' or a valid column or sequence index: '"
1439 + rng + "' - assuming alignment width for group.");
1440 // assume group is full width
1442 sg.setEndRes(al.getWidth() - 1);
1445 String index = st.nextToken();
1446 if (index.equals("-1"))
1448 while (st.hasMoreElements())
1450 sg.addSequence(al.findName(st.nextToken()), false);
1455 StringTokenizer st2 = new StringTokenizer(index, ",");
1457 while (st2.hasMoreTokens())
1459 String tmp = st2.nextToken();
1460 if (tmp.equals("*"))
1462 for (int i = 0; i < al.getHeight(); i++)
1464 sg.addSequence(al.getSequenceAt(i), false);
1467 else if (tmp.indexOf("-") >= 0)
1469 StringTokenizer st3 = new StringTokenizer(tmp, "-");
1471 int start = (Integer.parseInt(st3.nextToken()));
1472 int end = (Integer.parseInt(st3.nextToken()));
1476 for (int i = start; i <= end; i++)
1478 sg.addSequence(al.getSequenceAt(i - 1), false);
1484 sg.addSequence(al.getSequenceAt(Integer.parseInt(tmp) - 1),
1492 sg.setStartRes(refSeq.findIndex(sg.getStartRes() + 1) - 1);
1493 sg.setEndRes(refSeq.findIndex(sg.getEndRes() + 1) - 1);
1494 sg.setSeqrep(refSeq);
1497 if (sg.getSize() > 0)
1503 void addRowProperties(AlignmentI al, StringTokenizer st)
1505 String label = st.nextToken(), keyValue, key, value;
1506 boolean scaletofit = false, centerlab = false, showalllabs = false;
1507 while (st.hasMoreTokens())
1509 keyValue = st.nextToken();
1510 key = keyValue.substring(0, keyValue.indexOf("="));
1511 value = keyValue.substring(keyValue.indexOf("=") + 1);
1512 if (key.equalsIgnoreCase("scaletofit"))
1514 scaletofit = Boolean.valueOf(value).booleanValue();
1516 if (key.equalsIgnoreCase("showalllabs"))
1518 showalllabs = Boolean.valueOf(value).booleanValue();
1520 if (key.equalsIgnoreCase("centrelabs"))
1522 centerlab = Boolean.valueOf(value).booleanValue();
1524 AlignmentAnnotation[] alr = al.getAlignmentAnnotation();
1527 for (int i = 0; i < alr.length; i++)
1529 if (alr[i].label.equalsIgnoreCase(label))
1531 alr[i].centreColLabels = centerlab;
1532 alr[i].scaleColLabel = scaletofit;
1533 alr[i].showAllColLabels = showalllabs;
1540 void addProperties(AlignmentI al, StringTokenizer st)
1543 // So far we have only added groups to the annotationHash,
1544 // the idea is in the future properties can be added to
1545 // alignments, other annotations etc
1546 if (al.getGroups() == null)
1551 String name = st.nextToken();
1552 SequenceGroup sg = null;
1553 for (SequenceGroup _sg : al.getGroups())
1555 if ((sg = _sg).getName().equals(name))
1567 String keyValue, key, value;
1568 ColourSchemeI def = sg.getColourScheme();
1569 while (st.hasMoreTokens())
1571 keyValue = st.nextToken();
1572 key = keyValue.substring(0, keyValue.indexOf("="));
1573 value = keyValue.substring(keyValue.indexOf("=") + 1);
1575 if (key.equalsIgnoreCase("description"))
1577 sg.setDescription(value);
1579 else if (key.equalsIgnoreCase("colour"))
1581 // TODO need to notify colourscheme of view reference once it is
1583 sg.cs.setColourScheme(
1584 ColourSchemeProperty.getColourScheme(null, al, value));
1586 else if (key.equalsIgnoreCase("pidThreshold"))
1588 sg.cs.setThreshold(Integer.parseInt(value), true);
1591 else if (key.equalsIgnoreCase("consThreshold"))
1593 sg.cs.setConservationInc(Integer.parseInt(value));
1594 Conservation c = new Conservation("Group", sg.getSequences(null),
1595 sg.getStartRes(), sg.getEndRes() + 1);
1598 c.verdict(false, 25); // TODO: refer to conservation percent threshold
1600 sg.cs.setConservation(c);
1603 else if (key.equalsIgnoreCase("outlineColour"))
1605 sg.setOutlineColour(ColorUtils.parseColourString(value));
1607 else if (key.equalsIgnoreCase("displayBoxes"))
1609 sg.setDisplayBoxes(Boolean.valueOf(value).booleanValue());
1611 else if (key.equalsIgnoreCase("showUnconserved"))
1613 sg.setShowNonconserved(Boolean.valueOf(value).booleanValue());
1615 else if (key.equalsIgnoreCase("displayText"))
1617 sg.setDisplayText(Boolean.valueOf(value).booleanValue());
1619 else if (key.equalsIgnoreCase("colourText"))
1621 sg.setColourText(Boolean.valueOf(value).booleanValue());
1623 else if (key.equalsIgnoreCase("textCol1"))
1625 sg.textColour = ColorUtils.parseColourString(value);
1627 else if (key.equalsIgnoreCase("textCol2"))
1629 sg.textColour2 = ColorUtils.parseColourString(value);
1631 else if (key.equalsIgnoreCase("textColThreshold"))
1633 sg.thresholdTextColour = Integer.parseInt(value);
1635 else if (key.equalsIgnoreCase("idColour"))
1637 Color idColour = ColorUtils.parseColourString(value);
1638 sg.setIdColour(idColour == null ? Color.black : idColour);
1640 else if (key.equalsIgnoreCase("hide"))
1642 // see bug https://mantis.lifesci.dundee.ac.uk/view.php?id=25847
1643 sg.setHidereps(true);
1645 else if (key.equalsIgnoreCase("hidecols"))
1647 // see bug https://mantis.lifesci.dundee.ac.uk/view.php?id=25847
1648 sg.setHideCols(true);
1650 sg.recalcConservation();
1652 if (sg.getColourScheme() == null)
1654 sg.setColourScheme(def);
1659 void setBelowAlignment(AlignmentI al, StringTokenizer st)
1662 AlignmentAnnotation aa, ala[] = al.getAlignmentAnnotation();
1666 "Warning - no annotation to set below for sequence associated annotation:");
1668 while (st.hasMoreTokens())
1670 token = st.nextToken();
1673 System.err.print(" " + token);
1677 for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1679 aa = al.getAlignmentAnnotation()[i];
1680 if (aa.sequenceRef == refSeq && aa.label.equals(token))
1682 aa.belowAlignment = true;
1689 System.err.print("\n");
1693 void addAlignmentDetails(AlignmentI al, StringTokenizer st)
1695 String keyValue, key, value;
1696 while (st.hasMoreTokens())
1698 keyValue = st.nextToken();
1699 key = keyValue.substring(0, keyValue.indexOf("="));
1700 value = keyValue.substring(keyValue.indexOf("=") + 1);
1701 al.setProperty(key, value);
1706 * Write annotations as a CSV file of the form 'label, value, value, ...' for
1709 * @param annotations
1710 * @return CSV file as a string.
1712 public String printCSVAnnotations(AlignmentAnnotation[] annotations)
1714 if (annotations == null)
1718 StringBuffer sp = new StringBuffer();
1719 for (int i = 0; i < annotations.length; i++)
1721 String atos = annotations[i].toString();
1725 int cp = atos.indexOf("\n", p);
1726 sp.append(annotations[i].label);
1730 sp.append(atos.substring(p, cp + 1));
1734 sp.append(atos.substring(p));
1740 return sp.toString();
1743 public String printAnnotationsForView(AlignViewportI viewport)
1745 return printAnnotations(
1746 viewport.isShowAnnotation()
1747 ? viewport.getAlignment().getAlignmentAnnotation()
1749 viewport.getAlignment().getGroups(),
1750 viewport.getAlignment().getProperties(),
1751 viewport.getAlignment().getHiddenColumns(),
1752 viewport.getAlignment(), null);
1755 public String printAnnotationsForAlignment(AlignmentI al)
1757 return printAnnotations(al.getAlignmentAnnotation(), al.getGroups(),
1758 al.getProperties(), null, al, null);