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.HashMap;
29 import java.util.Hashtable;
30 import java.util.List;
32 import java.util.StringTokenizer;
33 import java.util.Vector;
35 import jalview.analysis.Conservation;
36 import jalview.api.AlignViewportI;
37 import jalview.datamodel.AlignmentAnnotation;
38 import jalview.datamodel.AlignmentI;
39 import jalview.datamodel.Annotation;
40 import jalview.datamodel.ColumnSelection;
41 import jalview.datamodel.GraphLine;
42 import jalview.datamodel.HiddenColumns;
43 import jalview.datamodel.HiddenSequences;
44 import jalview.datamodel.SequenceGroup;
45 import jalview.datamodel.SequenceI;
46 import jalview.schemes.ColourSchemeI;
47 import jalview.schemes.ColourSchemeProperty;
48 import jalview.util.ColorUtils;
50 public class AnnotationFile
52 private static final String GRAPHLINE = "GRAPHLINE";
54 private static final String COMBINE = "COMBINE";
56 protected String newline = System.getProperty("line.separator");
58 private StringBuffer text;
60 private SequenceI refSeq = null;
62 private String refSeqId = null;
64 private long nlinesread = 0;
66 private String lastread = "";
71 public AnnotationFile()
78 text = new StringBuffer("JALVIEW_ANNOTATION" + newline + "# Created: "
79 + new java.util.Date() + newline + newline);
85 * convenience method for pre-2.9 annotation files which have no view, hidden
86 * columns or hidden row keywords.
91 * @return annotation file as a string.
93 public String printAnnotations(AlignmentAnnotation[] annotations,
94 List<SequenceGroup> list, Hashtable properties)
96 return printAnnotations(annotations, list, properties, null, null,
102 * hold all the information about a particular view definition read from or
103 * written out in an annotations file.
107 // TODO this class is not used - remove?
108 public final String viewname;
110 public final HiddenSequences hidseqs;
112 public final HiddenColumns hiddencols;
114 public final Hashtable hiddenRepSeqs;
116 public ViewDef(String vname, HiddenSequences hseqs, HiddenColumns hcols,
119 this.viewname = vname;
120 this.hidseqs = hseqs;
121 this.hiddencols = hcols;
122 this.hiddenRepSeqs = hRepSeqs;
127 * Prepare an annotation file given a set of annotations, groups, alignment
128 * properties and views.
134 * @return annotation file
136 public String printAnnotations(AlignmentAnnotation[] annotations,
137 List<SequenceGroup> list, Hashtable properties, HiddenColumns cs,
138 AlignmentI al, ViewDef view)
142 if (view.viewname != null)
144 text.append("VIEW_DEF\t" + view.viewname + "\n");
148 // list = view.visibleGroups;
152 cs = view.hiddencols;
156 // add hidden rep sequences.
159 // first target - store and restore all settings for a view.
160 if (al != null && al.hasSeqrep())
162 text.append("VIEW_SETREF\t" + al.getSeqrep().getName() + "\n");
164 if (cs != null && cs.hasHiddenColumns())
166 text.append("VIEW_HIDECOLS\t");
168 String regions = cs.regionsToString(",", "-");
169 text.append(regions);
172 // TODO: allow efficient recovery of annotation data shown in several
174 if (annotations != null)
176 boolean oneColour = true;
177 AlignmentAnnotation row;
179 SequenceI refSeq = null;
180 SequenceGroup refGroup = null;
182 StringBuffer colours = new StringBuffer();
183 StringBuffer graphLine = new StringBuffer();
184 StringBuffer rowprops = new StringBuffer();
185 Hashtable<Integer, String> graphGroup = new Hashtable<>();
186 Hashtable<Integer, Object[]> graphGroup_refs = new Hashtable<>();
187 BitSet graphGroupSeen = new BitSet();
189 java.awt.Color color;
191 for (int i = 0; i < annotations.length; i++)
193 row = annotations[i];
195 if (!row.visible && !row.hasScore() && !(row.graphGroup > -1
196 && graphGroupSeen.get(row.graphGroup)))
204 // mark any sequence references for the row
205 writeSequence_Ref(refSeq, row.sequenceRef);
206 refSeq = row.sequenceRef;
207 // mark any group references for the row
208 writeGroup_Ref(refGroup, row.groupRef);
209 refGroup = row.groupRef;
211 boolean hasGlyphs = row.hasIcons, hasLabels = row.hasText,
212 hasValues = row.hasScore, hasText = false;
213 // lookahead to check what the annotation row object actually contains.
214 for (int j = 0; row.annotations != null
215 && j < row.annotations.length
216 && (!hasGlyphs || !hasLabels || !hasValues); j++)
218 if (row.annotations[j] != null)
220 hasLabels |= (row.annotations[j].displayCharacter != null
221 && row.annotations[j].displayCharacter.length() > 0
222 && !row.annotations[j].displayCharacter.equals(" "));
223 hasGlyphs |= (row.annotations[j].secondaryStructure != 0
224 && row.annotations[j].secondaryStructure != ' ');
225 hasValues |= (!Float.isNaN(row.annotations[j].value)); // NaNs can't
228 hasText |= (row.annotations[j].description != null
229 && row.annotations[j].description.length() > 0);
233 if (row.graph == AlignmentAnnotation.NO_GRAPH)
235 text.append("NO_GRAPH\t");
236 hasValues = false; // only secondary structure
237 // hasLabels = false; // and annotation description string.
241 if (row.graph == AlignmentAnnotation.BAR_GRAPH)
243 text.append("BAR_GRAPH\t");
244 hasGlyphs = false; // no secondary structure
247 else if (row.graph == AlignmentAnnotation.LINE_GRAPH)
249 hasGlyphs = false; // no secondary structure
250 text.append("LINE_GRAPH\t");
253 if (row.getThreshold() != null)
255 graphLine.append("GRAPHLINE\t");
256 graphLine.append(row.label);
257 graphLine.append("\t");
258 graphLine.append(row.getThreshold().value);
259 graphLine.append("\t");
260 graphLine.append(row.getThreshold().label);
261 graphLine.append("\t");
262 graphLine.append(jalview.util.Format
263 .getHexString(row.getThreshold().colour));
264 graphLine.append(newline);
267 if (row.graphGroup > -1)
269 graphGroupSeen.set(row.graphGroup);
270 Integer key = Integer.valueOf(row.graphGroup);
271 if (graphGroup.containsKey(key))
273 graphGroup.put(key, graphGroup.get(key) + "\t" + row.label);
278 graphGroup_refs.put(key, new Object[] { refSeq, refGroup });
279 graphGroup.put(key, row.label);
284 text.append(row.label + "\t");
285 if (row.description != null)
287 text.append(row.description + "\t");
289 for (int j = 0; row.annotations != null
290 && j < row.annotations.length; j++)
293 && jalview.util.Comparison.isGap(refSeq.getCharAt(j)))
298 if (row.annotations[j] != null)
301 if (hasGlyphs) // could be also hasGlyphs || ...
305 if (row.annotations[j].secondaryStructure != ' ')
307 // only write out the field if its not whitespace.
308 text.append(row.annotations[j].secondaryStructure);
314 if (!Float.isNaN(row.annotations[j].value))
316 text.append(comma + row.annotations[j].value);
320 // System.err.println("Skipping NaN - not valid value.");
321 text.append(comma + 0f);// row.annotations[j].value);
327 // TODO: labels are emitted after values for bar graphs.
328 if // empty labels are allowed, so
329 (row.annotations[j].displayCharacter != null
330 && row.annotations[j].displayCharacter.length() > 0
331 && !row.annotations[j].displayCharacter.equals(" "))
333 text.append(comma + row.annotations[j].displayCharacter);
339 if (row.annotations[j].description != null
340 && row.annotations[j].description.length() > 0
341 && !row.annotations[j].description
342 .equals(row.annotations[j].displayCharacter))
344 text.append(comma + row.annotations[j].description);
348 if (color != null && !color.equals(row.annotations[j].colour))
353 color = row.annotations[j].colour;
355 if (row.annotations[j].colour != null
356 && row.annotations[j].colour != java.awt.Color.black)
358 text.append(comma + "[" + jalview.util.Format
359 .getHexString(row.annotations[j].colour) + "]");
368 text.append("\t" + row.score);
371 text.append(newline);
373 if (color != null && color != java.awt.Color.black && oneColour)
375 colours.append("COLOUR\t");
376 colours.append(row.label);
377 colours.append("\t");
378 colours.append(jalview.util.Format.getHexString(color));
379 colours.append(newline);
381 if (row.scaleColLabel || row.showAllColLabels
382 || row.centreColLabels)
384 rowprops.append("ROWPROPERTIES\t");
385 rowprops.append(row.label);
386 rowprops.append("\tscaletofit=");
387 rowprops.append(row.scaleColLabel);
388 rowprops.append("\tshowalllabs=");
389 rowprops.append(row.showAllColLabels);
390 rowprops.append("\tcentrelabs=");
391 rowprops.append(row.centreColLabels);
392 rowprops.append(newline);
394 if (graphLine.length() > 0)
396 text.append(graphLine.toString());
397 graphLine.setLength(0);
401 text.append(newline);
403 text.append(colours.toString());
404 if (graphGroup.size() > 0)
406 SequenceI oldRefSeq = refSeq;
407 SequenceGroup oldRefGroup = refGroup;
408 for (Map.Entry<Integer, String> combine_statement : graphGroup
411 Object[] seqRefAndGroup = graphGroup_refs
412 .get(combine_statement.getKey());
414 writeSequence_Ref(refSeq, (SequenceI) seqRefAndGroup[0]);
415 refSeq = (SequenceI) seqRefAndGroup[0];
417 writeGroup_Ref(refGroup, (SequenceGroup) seqRefAndGroup[1]);
418 refGroup = (SequenceGroup) seqRefAndGroup[1];
419 text.append("COMBINE\t");
420 text.append(combine_statement.getValue());
421 text.append(newline);
423 writeSequence_Ref(refSeq, oldRefSeq);
426 writeGroup_Ref(refGroup, oldRefGroup);
427 refGroup = oldRefGroup;
429 text.append(rowprops.toString());
437 if (properties != null)
439 text.append(newline);
440 text.append(newline);
441 text.append("ALIGNMENT");
442 Enumeration en = properties.keys();
443 while (en.hasMoreElements())
445 String key = en.nextElement().toString();
449 text.append(properties.get(key));
451 // TODO: output alignment visualization settings here if required
452 // iterate through one or more views, defining, marking columns and rows
453 // as visible/hidden, and emmitting view properties.
454 // View specific annotation is
457 return text.toString();
460 private Object writeGroup_Ref(SequenceGroup refGroup,
461 SequenceGroup next_refGroup)
463 if (next_refGroup == null)
466 if (refGroup != null)
468 text.append(newline);
469 text.append("GROUP_REF\t");
470 text.append("ALIGNMENT");
471 text.append(newline);
477 if (refGroup == null || refGroup != next_refGroup)
479 text.append(newline);
480 text.append("GROUP_REF\t");
481 text.append(next_refGroup.getName());
482 text.append(newline);
489 private boolean writeSequence_Ref(SequenceI refSeq, SequenceI next_refSeq)
492 if (next_refSeq == null)
496 text.append(newline);
497 text.append("SEQUENCE_REF\t");
498 text.append("ALIGNMENT");
499 text.append(newline);
505 if (refSeq == null || refSeq != next_refSeq)
507 text.append(newline);
508 text.append("SEQUENCE_REF\t");
509 text.append(next_refSeq.getName());
510 text.append(newline);
517 protected void printGroups(List<SequenceGroup> list)
519 SequenceI seqrep = null;
520 for (SequenceGroup sg : list)
524 text.append("SEQUENCE_GROUP\t" + sg.getName() + "\t"
525 + (sg.getStartRes() + 1) + "\t" + (sg.getEndRes() + 1)
531 seqrep = sg.getSeqrep();
532 text.append("SEQUENCE_REF\t");
533 text.append(seqrep.getName());
534 text.append(newline);
535 text.append("SEQUENCE_GROUP\t");
536 text.append(sg.getName());
538 text.append((seqrep.findPosition(sg.getStartRes())));
540 text.append((seqrep.findPosition(sg.getEndRes())));
544 for (int s = 0; s < sg.getSize(); s++)
546 text.append(sg.getSequenceAt(s).getName());
549 text.append(newline);
550 text.append("PROPERTIES\t");
551 text.append(sg.getName());
554 if (sg.getDescription() != null)
556 text.append("description=");
557 text.append(sg.getDescription());
562 text.append("colour=");
563 text.append(ColourSchemeProperty
564 .getColourName(sg.cs.getColourScheme()));
566 if (sg.cs.getThreshold() != 0)
568 text.append("pidThreshold=");
569 text.append(sg.cs.getThreshold());
571 if (sg.cs.conservationApplied())
573 text.append("consThreshold=");
574 text.append(sg.cs.getConservationInc());
578 text.append("outlineColour=");
579 text.append(jalview.util.Format.getHexString(sg.getOutlineColour()));
582 text.append("displayBoxes=");
583 text.append(sg.getDisplayBoxes());
585 text.append("displayText=");
586 text.append(sg.getDisplayText());
588 text.append("colourText=");
589 text.append(sg.getColourText());
591 text.append("showUnconserved=");
592 text.append(sg.getShowNonconserved());
594 if (sg.textColour != java.awt.Color.black)
596 text.append("textCol1=");
597 text.append(jalview.util.Format.getHexString(sg.textColour));
600 if (sg.textColour2 != java.awt.Color.white)
602 text.append("textCol2=");
603 text.append(jalview.util.Format.getHexString(sg.textColour2));
606 if (sg.thresholdTextColour != 0)
608 text.append("textColThreshold=");
609 text.append(sg.thresholdTextColour);
612 if (sg.idColour != null)
614 text.append("idColour=");
615 text.append(jalview.util.Format.getHexString(sg.idColour));
620 text.append("hide=true\t");
624 text.append("hidecols=true\t");
628 // terminate the last line and clear the sequence ref for the group
629 text.append(newline);
630 text.append("SEQUENCE_REF");
632 text.append(newline);
633 text.append(newline);
638 public boolean annotateAlignmentView(AlignViewportI viewport, Object file,
639 DataSourceType protocol)
641 ColumnSelection colSel = viewport.getColumnSelection();
642 HiddenColumns hidden = viewport.getAlignment().getHiddenColumns();
645 colSel = new ColumnSelection();
649 hidden = new HiddenColumns();
651 boolean rslt = readAnnotationFile(viewport.getAlignment(), hidden, file,
653 if (rslt && (colSel.hasSelectedColumns() || hidden.hasHiddenColumns()))
655 viewport.setColumnSelection(colSel);
656 viewport.getAlignment().setHiddenColumns(hidden);
662 public boolean readAnnotationFile(AlignmentI al, String file,
663 DataSourceType sourceType)
665 return readAnnotationFile(al, null, file, sourceType);
668 public boolean readAnnotationFile(AlignmentI al, HiddenColumns hidden,
669 Object file, DataSourceType sourceType)
671 BufferedReader in = null;
674 in = new FileParse().getBufferedReader(file, sourceType);
677 return parseAnnotationFrom(al, hidden, in);
679 } catch (Exception ex)
681 ex.printStackTrace();
682 System.out.println("Problem reading annotation file: " + ex);
685 System.out.println("Last read line " + nlinesread + ": '" + lastread
686 + "' (first 80 chars) ...");
693 public boolean parseAnnotationFrom(AlignmentI al, HiddenColumns hidden,
694 BufferedReader in) throws Exception
697 ArrayList<Object[]> combineAnnotation_calls = new ArrayList<>();
698 ArrayList<Object[]> deferredAnnotation_calls = new ArrayList<>();
699 boolean modified = false;
700 String groupRef = null;
701 Hashtable groupRefRows = new Hashtable();
703 Hashtable autoAnnots = new Hashtable();
705 String line, label, description, token;
706 int graphStyle, index;
708 int existingAnnotations = 0;
709 // when true - will add new rows regardless of whether they are duplicate
710 // auto-annotation like consensus or conservation graphs
711 boolean overrideAutoAnnot = false;
712 if (al.getAlignmentAnnotation() != null)
714 existingAnnotations = al.getAlignmentAnnotation().length;
715 if (existingAnnotations > 0)
717 AlignmentAnnotation[] aa = al.getAlignmentAnnotation();
718 for (int aai = 0; aai < aa.length; aai++)
720 if (aa[aai].autoCalculated)
722 // make a note of the name and description
724 autoAnnotsKey(aa[aai], aa[aai].sequenceRef,
725 (aa[aai].groupRef == null ? null
726 : aa[aai].groupRef.getName())),
733 int alWidth = al.getWidth();
736 Annotation[] annotations;
737 AlignmentAnnotation annotation = null;
739 // First confirm this is an Annotation file
740 boolean jvAnnotationFile = false;
741 while ((line = in.readLine()) != null)
744 lastread = new String(line);
745 if (line.indexOf("#") == 0)
750 if (line.indexOf("JALVIEW_ANNOTATION") > -1)
752 jvAnnotationFile = true;
757 if (!jvAnnotationFile)
763 while ((line = in.readLine()) != null)
766 lastread = new String(line);
767 if (line.indexOf("#") == 0
768 || line.indexOf("JALVIEW_ANNOTATION") > -1
769 || line.length() == 0)
774 st = new StringTokenizer(line, "\t");
775 token = st.nextToken();
776 if (token.equalsIgnoreCase("COLOUR"))
778 // TODO: use graduated colour def'n here too
779 colourAnnotations(al, st.nextToken(), st.nextToken());
784 else if (token.equalsIgnoreCase(COMBINE))
786 // keep a record of current state and resolve groupRef at end
787 combineAnnotation_calls
789 { st, refSeq, groupRef });
793 else if (token.equalsIgnoreCase("ROWPROPERTIES"))
795 addRowProperties(al, st);
799 else if (token.equalsIgnoreCase(GRAPHLINE))
802 deferredAnnotation_calls
804 { GRAPHLINE, st, refSeq, groupRef });
809 else if (token.equalsIgnoreCase("SEQUENCE_REF"))
811 if (st.hasMoreTokens())
813 refSeq = al.findName(refSeqId = st.nextToken());
820 refSeqIndex = Integer.parseInt(st.nextToken());
825 "WARNING: SEQUENCE_REF index must be > 0 in AnnotationFile");
827 } catch (Exception ex)
839 else if (token.equalsIgnoreCase("GROUP_REF"))
841 // Group references could be forward or backwards, so they are
842 // resolved after the whole file is read in
844 if (st.hasMoreTokens())
846 groupRef = st.nextToken();
847 if (groupRef.length() < 1)
849 groupRef = null; // empty string
853 if (groupRefRows.get(groupRef) == null)
855 groupRefRows.put(groupRef, new Vector());
861 else if (token.equalsIgnoreCase("SEQUENCE_GROUP"))
868 else if (token.equalsIgnoreCase("PROPERTIES"))
870 addProperties(al, st);
875 else if (token.equalsIgnoreCase("BELOW_ALIGNMENT"))
877 setBelowAlignment(al, st);
881 else if (token.equalsIgnoreCase("ALIGNMENT"))
883 addAlignmentDetails(al, st);
887 // else if (token.equalsIgnoreCase("VIEW_DEF"))
889 // addOrSetView(al,st);
893 else if (token.equalsIgnoreCase("VIEW_SETREF"))
897 al.setSeqrep(refSeq);
902 else if (token.equalsIgnoreCase("VIEW_HIDECOLS"))
904 if (st.hasMoreTokens())
908 hidden = new HiddenColumns();
910 parseHideCols(hidden, st.nextToken());
915 else if (token.equalsIgnoreCase("HIDE_INSERTIONS"))
917 SequenceI sr = refSeq == null ? al.getSeqrep() : refSeq;
920 sr = al.getSequenceAt(0);
927 "Cannot process HIDE_INSERTIONS without an alignment view: Ignoring line: "
932 // consider deferring this till after the file has been parsed ?
933 hidden.hideList(sr.getInsertions());
940 // Parse out the annotation row
941 graphStyle = AlignmentAnnotation.getGraphValueFromString(token);
942 label = st.nextToken();
945 annotations = new Annotation[alWidth];
947 float score = Float.NaN;
949 if (st.hasMoreTokens())
951 line = st.nextToken();
953 if (line.indexOf("|") == -1)
956 if (st.hasMoreTokens())
958 line = st.nextToken();
962 if (st.hasMoreTokens())
964 // This must be the score
965 score = Float.valueOf(st.nextToken()).floatValue();
968 st = new StringTokenizer(line, "|", true);
970 boolean emptyColumn = true;
971 boolean onlyOneElement = (st.countTokens() == 1);
973 while (st.hasMoreElements() && index < alWidth)
975 token = st.nextToken().trim();
981 score = Float.valueOf(token).floatValue();
983 } catch (NumberFormatException ex)
988 if (token.equals("|"))
999 annotations[index++] = parseAnnotation(token, graphStyle);
1000 emptyColumn = false;
1006 annotation = new AlignmentAnnotation(label, description,
1007 (index == 0) ? null : annotations, 0, 0, graphStyle);
1009 annotation.score = score;
1010 if (!overrideAutoAnnot && autoAnnots
1011 .containsKey(autoAnnotsKey(annotation, refSeq, groupRef)))
1013 // skip - we've already got an automatic annotation of this type.
1016 // otherwise add it!
1020 annotation.belowAlignment = false;
1021 // make a copy of refSeq so we can find other matches in the alignment
1022 SequenceI referedSeq = refSeq;
1025 // copy before we do any mapping business.
1026 // TODO: verify that undo/redo with 1:many sequence associated
1027 // annotations can be undone correctly
1028 AlignmentAnnotation ann = new AlignmentAnnotation(annotation);
1029 annotation.createSequenceMapping(referedSeq, refSeqIndex,
1031 annotation.adjustForAlignment();
1032 referedSeq.addAlignmentAnnotation(annotation);
1033 al.addAnnotation(annotation);
1034 al.setAnnotationIndex(annotation,
1035 al.getAlignmentAnnotation().length - existingAnnotations
1037 if (groupRef != null)
1039 ((Vector) groupRefRows.get(groupRef)).addElement(annotation);
1041 // and recover our virgin copy to use again if necessary.
1044 } while (refSeqId != null && (referedSeq = al.findName(referedSeq,
1045 refSeqId, true)) != null);
1049 al.addAnnotation(annotation);
1050 al.setAnnotationIndex(annotation,
1051 al.getAlignmentAnnotation().length - existingAnnotations
1053 if (groupRef != null)
1055 ((Vector) groupRefRows.get(groupRef)).addElement(annotation);
1058 // and set modification flag
1061 // Resolve the groupRefs
1062 Hashtable<String, SequenceGroup> groupRefLookup = new Hashtable<>();
1063 Enumeration en = groupRefRows.keys();
1065 while (en.hasMoreElements())
1067 groupRef = (String) en.nextElement();
1068 boolean matched = false;
1069 // Resolve group: TODO: add a getGroupByName method to alignments
1070 for (SequenceGroup theGroup : al.getGroups())
1072 if (theGroup.getName().equals(groupRef))
1076 // TODO: specify and implement duplication of alignment annotation
1077 // for multiple group references.
1079 "Ignoring 1:many group reference mappings for group name '"
1085 Vector rowset = (Vector) groupRefRows.get(groupRef);
1086 groupRefLookup.put(groupRef, theGroup);
1087 if (rowset != null && rowset.size() > 0)
1089 AlignmentAnnotation alan = null;
1091 elmSize = rowset.size(); elm < elmSize; elm++)
1093 alan = (AlignmentAnnotation) rowset.elementAt(elm);
1094 alan.groupRef = theGroup;
1100 ((Vector) groupRefRows.get(groupRef)).removeAllElements();
1102 // process any deferred attribute settings for each context
1103 for (Object[] _deferred_args : deferredAnnotation_calls)
1105 if (_deferred_args[0] == GRAPHLINE)
1107 addLine(al, (StringTokenizer) _deferred_args[1], // st
1108 (SequenceI) _deferred_args[2], // refSeq
1109 (_deferred_args[3] == null) ? null
1110 : groupRefLookup.get(_deferred_args[3]) // the
1118 // finally, combine all the annotation rows within each context.
1120 * number of combine statements in this annotation file. Used to create
1121 * new groups for combined annotation graphs without disturbing existing
1124 int combinecount = 0;
1125 for (Object[] _combine_args : combineAnnotation_calls)
1127 combineAnnotations(al, ++combinecount,
1128 (StringTokenizer) _combine_args[0], // st
1129 (SequenceI) _combine_args[1], // refSeq
1130 (_combine_args[2] == null) ? null
1131 : groupRefLookup.get(_combine_args[2]) // the reference
1140 private void parseHideCols(HiddenColumns hidden, String nextToken)
1142 StringTokenizer inval = new StringTokenizer(nextToken, ",");
1143 while (inval.hasMoreTokens())
1145 String range = inval.nextToken().trim();
1146 int from, to = range.indexOf("-");
1149 from = to = Integer.parseInt(range);
1152 hidden.hideColumns(from, to);
1157 from = Integer.parseInt(range.substring(0, to));
1158 if (to < range.length() - 1)
1160 to = Integer.parseInt(range.substring(to + 1));
1166 if (from > 0 && to >= from)
1168 hidden.hideColumns(from, to);
1174 private Object autoAnnotsKey(AlignmentAnnotation annotation,
1175 SequenceI refSeq, String groupRef)
1177 return annotation.graph + "\t" + annotation.label + "\t"
1178 + annotation.description + "\t"
1179 + (refSeq != null ? refSeq.getDisplayId(true) : "");
1182 Annotation parseAnnotation(String string, int graphStyle)
1184 // don't do the glyph test if we don't want secondary structure
1185 boolean hasSymbols = (graphStyle == AlignmentAnnotation.NO_GRAPH);
1186 String desc = null, displayChar = null;
1187 char ss = ' '; // secondaryStructure
1189 boolean parsedValue = false, dcset = false;
1192 Color colour = null;
1193 int i = string.indexOf("[");
1194 int j = string.indexOf("]");
1195 if (i > -1 && j > -1)
1197 colour = ColorUtils.parseColourString(string.substring(i + 1, j));
1198 if (i > 0 && string.charAt(i - 1) == ',')
1200 // clip the preceding comma as well
1203 string = string.substring(0, i) + string.substring(j + 1);
1206 StringTokenizer st = new StringTokenizer(string, ",", true);
1208 boolean seenContent = false;
1210 while (st.hasMoreTokens())
1213 token = st.nextToken().trim();
1214 if (token.equals(","))
1216 if (!seenContent && parsedValue && !dcset)
1218 // allow the value below the bar/line to be empty
1222 seenContent = false;
1234 displayChar = token;
1236 value = Float.valueOf(token).floatValue();
1239 } catch (NumberFormatException ex)
1245 if (token.length() == 1)
1247 displayChar = token;
1250 if (hasSymbols && (token.length() == 1
1251 && "()<>[]{}AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz"
1254 // Either this character represents a helix or sheet
1255 // or an integer which can be displayed
1256 ss = token.charAt(0);
1257 if (displayChar.equals(token.substring(0, 1)))
1262 else if (desc == null || (parsedValue && pass > 2))
1268 // if (!dcset && string.charAt(string.length() - 1) == ',')
1270 // displayChar = " "; // empty display char symbol.
1272 if (displayChar != null && desc != null && desc.length() == 1)
1274 if (displayChar.length() > 1)
1276 // switch desc and displayChar - legacy support
1277 String tmp = displayChar;
1283 if (displayChar.equals(desc))
1285 // duplicate label - hangover from the 'robust parser' above
1290 Annotation anot = new Annotation(displayChar, desc, ss, value);
1292 anot.colour = colour;
1297 void colourAnnotations(AlignmentI al, String label, String colour)
1299 Color awtColour = ColorUtils.parseColourString(colour);
1300 Annotation[] annotations;
1301 for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1303 if (al.getAlignmentAnnotation()[i].label.equalsIgnoreCase(label))
1305 annotations = al.getAlignmentAnnotation()[i].annotations;
1306 for (int j = 0; j < annotations.length; j++)
1308 if (annotations[j] != null)
1310 annotations[j].colour = awtColour;
1317 void combineAnnotations(AlignmentI al, int combineCount,
1318 StringTokenizer st, SequenceI seqRef, SequenceGroup groupRef)
1320 String group = st.nextToken();
1321 // First make sure we are not overwriting the graphIndex
1323 if (al.getAlignmentAnnotation() != null)
1325 for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1327 AlignmentAnnotation aa = al.getAlignmentAnnotation()[i];
1329 if (aa.graphGroup > graphGroup)
1331 // try to number graphGroups in order of occurence.
1332 graphGroup = aa.graphGroup + 1;
1334 if (aa.sequenceRef == seqRef && aa.groupRef == groupRef
1335 && aa.label.equalsIgnoreCase(group))
1337 if (aa.graphGroup > -1)
1339 graphGroup = aa.graphGroup;
1343 if (graphGroup <= combineCount)
1345 graphGroup = combineCount + 1;
1347 aa.graphGroup = graphGroup;
1353 // Now update groups
1354 while (st.hasMoreTokens())
1356 group = st.nextToken();
1357 for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1359 AlignmentAnnotation aa = al.getAlignmentAnnotation()[i];
1360 if (aa.sequenceRef == seqRef && aa.groupRef == groupRef
1361 && aa.label.equalsIgnoreCase(group))
1363 aa.graphGroup = graphGroup;
1372 "Couldn't combine annotations. None are added to alignment yet!");
1376 void addLine(AlignmentI al, StringTokenizer st, SequenceI seqRef,
1377 SequenceGroup groupRef)
1379 String group = st.nextToken();
1380 AlignmentAnnotation[] alannot = al.getAlignmentAnnotation();
1381 String nextToken = st.nextToken();
1385 value = Float.valueOf(nextToken);
1386 } catch (NumberFormatException e)
1388 System.err.println("line " + nlinesread + ": Threshold '" + nextToken
1389 + "' invalid, setting to zero");
1391 String label = st.hasMoreTokens() ? st.nextToken() : null;
1392 Color colour = null;
1393 if (st.hasMoreTokens())
1395 colour = ColorUtils.parseColourString(st.nextToken());
1397 if (alannot != null)
1399 for (int i = 0; i < alannot.length; i++)
1401 if (alannot[i].label.equalsIgnoreCase(group)
1402 && (seqRef == null || alannot[i].sequenceRef == seqRef)
1403 && (groupRef == null || alannot[i].groupRef == groupRef))
1405 alannot[i].setThreshold(new GraphLine(value, label, colour));
1411 void addGroup(AlignmentI al, StringTokenizer st)
1413 SequenceGroup sg = new SequenceGroup();
1414 sg.setName(st.nextToken());
1418 rng = st.nextToken();
1419 if (rng.length() > 0 && !rng.startsWith("*"))
1421 sg.setStartRes(Integer.parseInt(rng) - 1);
1427 rng = st.nextToken();
1428 if (rng.length() > 0 && !rng.startsWith("*"))
1430 sg.setEndRes(Integer.parseInt(rng) - 1);
1434 sg.setEndRes(al.getWidth() - 1);
1436 } catch (Exception e)
1439 "Couldn't parse Group Start or End Field as '*' or a valid column or sequence index: '"
1440 + rng + "' - assuming alignment width for group.");
1441 // assume group is full width
1443 sg.setEndRes(al.getWidth() - 1);
1446 String index = st.nextToken();
1447 if (index.equals("-1"))
1449 while (st.hasMoreElements())
1451 sg.addSequence(al.findName(st.nextToken()), false);
1456 StringTokenizer st2 = new StringTokenizer(index, ",");
1458 while (st2.hasMoreTokens())
1460 String tmp = st2.nextToken();
1461 if (tmp.equals("*"))
1463 for (int i = 0; i < al.getHeight(); i++)
1465 sg.addSequence(al.getSequenceAt(i), false);
1468 else if (tmp.indexOf("-") >= 0)
1470 StringTokenizer st3 = new StringTokenizer(tmp, "-");
1472 int start = (Integer.parseInt(st3.nextToken()));
1473 int end = (Integer.parseInt(st3.nextToken()));
1477 for (int i = start; i <= end; i++)
1479 sg.addSequence(al.getSequenceAt(i - 1), false);
1485 sg.addSequence(al.getSequenceAt(Integer.parseInt(tmp) - 1),
1493 sg.setStartRes(refSeq.findIndex(sg.getStartRes() + 1) - 1);
1494 sg.setEndRes(refSeq.findIndex(sg.getEndRes() + 1) - 1);
1495 sg.setSeqrep(refSeq);
1498 if (sg.getSize() > 0)
1504 void addRowProperties(AlignmentI al, StringTokenizer st)
1506 String label = st.nextToken(), keyValue, key, value;
1507 boolean scaletofit = false, centerlab = false, showalllabs = false;
1508 while (st.hasMoreTokens())
1510 keyValue = st.nextToken();
1511 key = keyValue.substring(0, keyValue.indexOf("="));
1512 value = keyValue.substring(keyValue.indexOf("=") + 1);
1513 if (key.equalsIgnoreCase("scaletofit"))
1515 scaletofit = Boolean.valueOf(value).booleanValue();
1517 if (key.equalsIgnoreCase("showalllabs"))
1519 showalllabs = Boolean.valueOf(value).booleanValue();
1521 if (key.equalsIgnoreCase("centrelabs"))
1523 centerlab = Boolean.valueOf(value).booleanValue();
1525 AlignmentAnnotation[] alr = al.getAlignmentAnnotation();
1528 for (int i = 0; i < alr.length; i++)
1530 if (alr[i].label.equalsIgnoreCase(label))
1532 alr[i].centreColLabels = centerlab;
1533 alr[i].scaleColLabel = scaletofit;
1534 alr[i].showAllColLabels = showalllabs;
1541 void addProperties(AlignmentI al, StringTokenizer st)
1544 // So far we have only added groups to the annotationHash,
1545 // the idea is in the future properties can be added to
1546 // alignments, other annotations etc
1547 if (al.getGroups() == null)
1552 String name = st.nextToken();
1554 Map<String, String> properties = new HashMap<>();
1555 while (st.hasMoreTokens())
1557 String keyValue = st.nextToken();
1558 String key = keyValue.substring(0, keyValue.indexOf("="));
1559 String value = keyValue.substring(keyValue.indexOf("=") + 1);
1560 properties.put(key, value);
1563 for (SequenceGroup sg : al.getGroups())
1565 if (sg.getName().equals(name))
1567 addProperties(sg, properties, al);
1573 * Helper method that applies any specified properties to a SequenceGroup
1579 private void addProperties(SequenceGroup sg,
1580 Map<String, String> properties, AlignmentI al)
1582 ColourSchemeI def = sg.getColourScheme();
1583 for (String key : properties.keySet())
1585 String value = properties.get(key);
1586 if (key.equalsIgnoreCase("description"))
1588 sg.setDescription(value);
1590 else if (key.equalsIgnoreCase("colour"))
1592 // TODO need to notify colourscheme of view reference once it is
1594 sg.cs.setColourScheme(
1595 ColourSchemeProperty.getColourScheme(null, al, value));
1597 else if (key.equalsIgnoreCase("pidThreshold"))
1599 sg.cs.setThreshold(Integer.parseInt(value), true);
1602 else if (key.equalsIgnoreCase("consThreshold"))
1604 sg.cs.setConservationInc(Integer.parseInt(value));
1605 Conservation c = new Conservation("Group", sg.getSequences(null),
1606 sg.getStartRes(), sg.getEndRes() + 1);
1609 c.verdict(false, 25); // TODO: refer to conservation percent threshold
1611 sg.cs.setConservation(c);
1614 else if (key.equalsIgnoreCase("outlineColour"))
1616 sg.setOutlineColour(ColorUtils.parseColourString(value));
1618 else if (key.equalsIgnoreCase("displayBoxes"))
1620 sg.setDisplayBoxes(Boolean.valueOf(value).booleanValue());
1622 else if (key.equalsIgnoreCase("showUnconserved"))
1624 sg.setShowNonconserved(Boolean.valueOf(value).booleanValue());
1626 else if (key.equalsIgnoreCase("displayText"))
1628 sg.setDisplayText(Boolean.valueOf(value).booleanValue());
1630 else if (key.equalsIgnoreCase("colourText"))
1632 sg.setColourText(Boolean.valueOf(value).booleanValue());
1634 else if (key.equalsIgnoreCase("textCol1"))
1636 sg.textColour = ColorUtils.parseColourString(value);
1638 else if (key.equalsIgnoreCase("textCol2"))
1640 sg.textColour2 = ColorUtils.parseColourString(value);
1642 else if (key.equalsIgnoreCase("textColThreshold"))
1644 sg.thresholdTextColour = Integer.parseInt(value);
1646 else if (key.equalsIgnoreCase("idColour"))
1648 Color idColour = ColorUtils.parseColourString(value);
1649 sg.setIdColour(idColour == null ? Color.black : idColour);
1651 else if (key.equalsIgnoreCase("hide"))
1653 // see bug https://mantis.lifesci.dundee.ac.uk/view.php?id=25847
1654 sg.setHidereps(true);
1656 else if (key.equalsIgnoreCase("hidecols"))
1658 // see bug https://mantis.lifesci.dundee.ac.uk/view.php?id=25847
1659 sg.setHideCols(true);
1661 sg.recalcConservation();
1664 if (sg.getColourScheme() == null)
1666 sg.setColourScheme(def);
1670 void setBelowAlignment(AlignmentI al, StringTokenizer st)
1673 AlignmentAnnotation aa, ala[] = al.getAlignmentAnnotation();
1677 "Warning - no annotation to set below for sequence associated annotation:");
1679 while (st.hasMoreTokens())
1681 token = st.nextToken();
1684 System.err.print(" " + token);
1688 for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1690 aa = al.getAlignmentAnnotation()[i];
1691 if (aa.sequenceRef == refSeq && aa.label.equals(token))
1693 aa.belowAlignment = true;
1700 System.err.print("\n");
1704 void addAlignmentDetails(AlignmentI al, StringTokenizer st)
1706 String keyValue, key, value;
1707 while (st.hasMoreTokens())
1709 keyValue = st.nextToken();
1710 key = keyValue.substring(0, keyValue.indexOf("="));
1711 value = keyValue.substring(keyValue.indexOf("=") + 1);
1712 al.setProperty(key, value);
1717 * Write annotations as a CSV file of the form 'label, value, value, ...' for
1720 * @param annotations
1721 * @return CSV file as a string.
1723 public String printCSVAnnotations(AlignmentAnnotation[] annotations)
1725 if (annotations == null)
1729 StringBuffer sp = new StringBuffer();
1730 for (int i = 0; i < annotations.length; i++)
1732 String atos = annotations[i].toString();
1736 int cp = atos.indexOf("\n", p);
1737 sp.append(annotations[i].label);
1741 sp.append(atos.substring(p, cp + 1));
1745 sp.append(atos.substring(p));
1751 return sp.toString();
1754 public String printAnnotationsForView(AlignViewportI viewport)
1756 return printAnnotations(
1757 viewport.isShowAnnotation()
1758 ? viewport.getAlignment().getAlignmentAnnotation()
1760 viewport.getAlignment().getGroups(),
1761 viewport.getAlignment().getProperties(),
1762 viewport.getAlignment().getHiddenColumns(),
1763 viewport.getAlignment(), null);
1766 public String printAnnotationsForAlignment(AlignmentI al)
1768 return printAnnotations(al.getAlignmentAnnotation(), al.getGroups(),
1769 al.getProperties(), null, al, null);