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.HiddenSequences;
31 import jalview.datamodel.SequenceGroup;
32 import jalview.datamodel.SequenceI;
33 import jalview.schemes.ColourSchemeI;
34 import jalview.schemes.ColourSchemeProperty;
35 import jalview.schemes.UserColourScheme;
37 import java.io.BufferedReader;
38 import java.io.FileReader;
39 import java.io.InputStreamReader;
40 import java.io.StringReader;
42 import java.util.ArrayList;
43 import java.util.BitSet;
44 import java.util.Enumeration;
45 import java.util.Hashtable;
46 import java.util.List;
48 import java.util.StringTokenizer;
49 import java.util.Vector;
51 public class AnnotationFile
53 public AnnotationFile()
59 * character used to write newlines
61 protected String newline = System.getProperty("line.separator");
64 * set new line string and reset the output buffer
68 public void setNewlineString(String nl)
74 public String getNewlineString()
83 text = new StringBuffer("JALVIEW_ANNOTATION" + newline + "# Created: "
84 + new java.util.Date() + newline + newline);
90 * convenience method for pre-2.9 annotation files which have no view, hidden
91 * columns or hidden row keywords.
96 * @return annotation file as a string.
98 public String printAnnotations(AlignmentAnnotation[] annotations,
99 List<SequenceGroup> list, Hashtable properties)
101 return printAnnotations(annotations, list, properties, null, null, null);
106 * hold all the information about a particular view definition read from or
107 * written out in an annotations file.
111 public String viewname;
113 public HiddenSequences hidseqs;
115 public ColumnSelection hiddencols;
117 public Vector visibleGroups;
119 public Hashtable hiddenRepSeqs;
121 public ViewDef(String viewname, HiddenSequences hidseqs,
122 ColumnSelection hiddencols, Hashtable hiddenRepSeqs)
124 this.viewname = viewname;
125 this.hidseqs = hidseqs;
126 this.hiddencols = hiddencols;
127 this.hiddenRepSeqs = hiddenRepSeqs;
132 * Prepare an annotation file given a set of annotations, groups, alignment
133 * properties and views.
139 * @return annotation file
141 public String printAnnotations(AlignmentAnnotation[] annotations,
142 List<SequenceGroup> list, Hashtable properties,
143 ColumnSelection cs, AlignmentI al, ViewDef view)
147 if (view.viewname != null)
149 text.append("VIEW_DEF\t" + view.viewname + "\n");
153 list = view.visibleGroups;
157 cs = view.hiddencols;
161 // add hidden rep sequences.
164 // first target - store and restore all settings for a view.
165 if (al != null && al.hasSeqrep())
167 text.append("VIEW_SETREF\t" + al.getSeqrep().getName() + "\n");
169 if (cs != null && cs.hasHiddenColumns())
171 text.append("VIEW_HIDECOLS\t");
172 List<int[]> hc = cs.getHiddenColumns();
173 boolean comma = false;
190 // TODO: allow efficient recovery of annotation data shown in several
192 if (annotations != null)
194 boolean oneColour = true;
195 AlignmentAnnotation row;
197 SequenceI refSeq = null;
198 SequenceGroup refGroup = null;
200 StringBuffer colours = new StringBuffer();
201 StringBuffer graphLine = new StringBuffer();
202 StringBuffer rowprops = new StringBuffer();
203 Hashtable<Integer, String> graphGroup = new Hashtable<Integer, String>();
204 Hashtable<Integer, Object[]> graphGroup_refs = new Hashtable<Integer, Object[]>();
205 BitSet graphGroupSeen = new BitSet();
207 java.awt.Color color;
209 for (int i = 0; i < annotations.length; i++)
211 row = annotations[i];
215 && !(row.graphGroup > -1 && graphGroupSeen
216 .get(row.graphGroup)))
224 // mark any sequence references for the row
225 writeSequence_Ref(refSeq, row.sequenceRef);
226 refSeq = row.sequenceRef;
227 // mark any group references for the row
228 writeGroup_Ref(refGroup, row.groupRef);
229 refGroup = row.groupRef;
231 boolean hasGlyphs = row.hasIcons, hasLabels = row.hasText, hasValues = row.hasScore, hasText = false;
232 // lookahead to check what the annotation row object actually contains.
233 for (int j = 0; row.annotations != null
234 && j < row.annotations.length
235 && (!hasGlyphs || !hasLabels || !hasValues); j++)
237 if (row.annotations[j] != null)
239 hasLabels |= (row.annotations[j].displayCharacter != null
240 && row.annotations[j].displayCharacter.length() > 0 && !row.annotations[j].displayCharacter
242 hasGlyphs |= (row.annotations[j].secondaryStructure != 0 && row.annotations[j].secondaryStructure != ' ');
243 hasValues |= (!Float.isNaN(row.annotations[j].value)); // NaNs can't
246 hasText |= (row.annotations[j].description != null && row.annotations[j].description
251 if (row.graph == AlignmentAnnotation.NO_GRAPH)
253 text.append("NO_GRAPH\t");
254 hasValues = false; // only secondary structure
255 // hasLabels = false; // and annotation description string.
259 if (row.graph == AlignmentAnnotation.BAR_GRAPH)
261 text.append("BAR_GRAPH\t");
262 hasGlyphs = false; // no secondary structure
265 else if (row.graph == AlignmentAnnotation.LINE_GRAPH)
267 hasGlyphs = false; // no secondary structure
268 text.append("LINE_GRAPH\t");
271 if (row.getThreshold() != null)
273 graphLine.append("GRAPHLINE\t");
274 graphLine.append(row.label);
275 graphLine.append("\t");
276 graphLine.append(row.getThreshold().value);
277 graphLine.append("\t");
278 graphLine.append(row.getThreshold().label);
279 graphLine.append("\t");
280 graphLine.append(jalview.util.Format.getHexString(row
281 .getThreshold().colour));
282 graphLine.append(newline);
285 if (row.graphGroup > -1)
287 graphGroupSeen.set(row.graphGroup);
288 Integer key = new Integer(row.graphGroup);
289 if (graphGroup.containsKey(key))
291 graphGroup.put(key, graphGroup.get(key) + "\t" + row.label);
296 graphGroup_refs.put(key, new Object[] { refSeq, refGroup });
297 graphGroup.put(key, row.label);
302 text.append(row.label + "\t");
303 if (row.description != null)
305 text.append(row.description + "\t");
307 for (int j = 0; row.annotations != null
308 && j < row.annotations.length; j++)
311 && jalview.util.Comparison.isGap(refSeq.getCharAt(j)))
316 if (row.annotations[j] != null)
319 if (hasGlyphs) // could be also hasGlyphs || ...
323 if (row.annotations[j].secondaryStructure != ' ')
325 // only write out the field if its not whitespace.
326 text.append(row.annotations[j].secondaryStructure);
332 if (!Float.isNaN(row.annotations[j].value))
334 text.append(comma + row.annotations[j].value);
338 // System.err.println("Skipping NaN - not valid value.");
339 text.append(comma + 0f);// row.annotations[j].value);
345 // TODO: labels are emitted after values for bar graphs.
346 if // empty labels are allowed, so
347 (row.annotations[j].displayCharacter != null
348 && row.annotations[j].displayCharacter.length() > 0
349 && !row.annotations[j].displayCharacter.equals(" "))
351 text.append(comma + row.annotations[j].displayCharacter);
357 if (row.annotations[j].description != null
358 && row.annotations[j].description.length() > 0
359 && !row.annotations[j].description
360 .equals(row.annotations[j].displayCharacter))
362 text.append(comma + row.annotations[j].description);
366 if (color != null && !color.equals(row.annotations[j].colour))
371 color = row.annotations[j].colour;
373 if (row.annotations[j].colour != null
374 && row.annotations[j].colour != java.awt.Color.black)
378 + jalview.util.Format
379 .getHexString(row.annotations[j].colour)
389 text.append("\t" + row.score);
392 text.append(newline);
394 if (color != null && color != java.awt.Color.black && oneColour)
396 colours.append("COLOUR\t");
397 colours.append(row.label);
398 colours.append("\t");
399 colours.append(jalview.util.Format.getHexString(color));
400 colours.append(newline);
402 if (row.scaleColLabel || row.showAllColLabels
403 || row.centreColLabels)
405 rowprops.append("ROWPROPERTIES\t");
406 rowprops.append(row.label);
407 rowprops.append("\tscaletofit=");
408 rowprops.append(row.scaleColLabel);
409 rowprops.append("\tshowalllabs=");
410 rowprops.append(row.showAllColLabels);
411 rowprops.append("\tcentrelabs=");
412 rowprops.append(row.centreColLabels);
413 rowprops.append(newline);
415 if (graphLine.length() > 0)
417 text.append(graphLine.toString());
418 graphLine.setLength(0);
422 text.append(newline);
424 text.append(colours.toString());
425 if (graphGroup.size() > 0)
427 SequenceI oldRefSeq = refSeq;
428 SequenceGroup oldRefGroup = refGroup;
429 for (Map.Entry<Integer, String> combine_statement : graphGroup
432 Object[] seqRefAndGroup = graphGroup_refs.get(combine_statement
435 writeSequence_Ref(refSeq, (SequenceI) seqRefAndGroup[0]);
436 refSeq = (SequenceI) seqRefAndGroup[0];
438 writeGroup_Ref(refGroup, (SequenceGroup) seqRefAndGroup[1]);
439 refGroup = (SequenceGroup) seqRefAndGroup[1];
440 text.append("COMBINE\t");
441 text.append(combine_statement.getValue());
442 text.append(newline);
444 writeSequence_Ref(refSeq, oldRefSeq);
447 writeGroup_Ref(refGroup, oldRefGroup);
448 refGroup = oldRefGroup;
450 text.append(rowprops.toString());
458 if (properties != null)
460 text.append(newline);
461 text.append(newline);
462 text.append("ALIGNMENT");
463 Enumeration en = properties.keys();
464 while (en.hasMoreElements())
466 String key = en.nextElement().toString();
470 text.append(properties.get(key));
472 // TODO: output alignment visualization settings here if required
473 // iterate through one or more views, defining, marking columns and rows
474 // as visible/hidden, and emmitting view properties.
475 // View specific annotation is
478 return text.toString();
481 private Object writeGroup_Ref(SequenceGroup refGroup,
482 SequenceGroup next_refGroup)
484 if (next_refGroup == null)
487 if (refGroup != null)
489 text.append(newline);
490 text.append("GROUP_REF\t");
491 text.append("ALIGNMENT");
492 text.append(newline);
498 if (refGroup == null || refGroup != next_refGroup)
500 text.append(newline);
501 text.append("GROUP_REF\t");
502 text.append(next_refGroup.getName());
503 text.append(newline);
510 private boolean writeSequence_Ref(SequenceI refSeq, SequenceI next_refSeq)
513 if (next_refSeq == null)
517 text.append(newline);
518 text.append("SEQUENCE_REF\t");
519 text.append("ALIGNMENT");
520 text.append(newline);
526 if (refSeq == null || refSeq != next_refSeq)
528 text.append(newline);
529 text.append("SEQUENCE_REF\t");
530 text.append(next_refSeq.getName());
531 text.append(newline);
538 public void printGroups(List<SequenceGroup> list)
540 SequenceI seqrep = null;
541 for (SequenceGroup sg : list)
545 text.append("SEQUENCE_GROUP\t" + sg.getName() + "\t"
546 + (sg.getStartRes() + 1) + "\t" + (sg.getEndRes() + 1)
552 seqrep = sg.getSeqrep();
553 text.append("SEQUENCE_REF\t");
554 text.append(seqrep.getName());
555 text.append(newline);
556 text.append("SEQUENCE_GROUP\t");
557 text.append(sg.getName());
559 text.append((seqrep.findPosition(sg.getStartRes())));
561 text.append((seqrep.findPosition(sg.getEndRes())));
565 for (int s = 0; s < sg.getSize(); s++)
567 text.append(sg.getSequenceAt(s).getName());
570 text.append(newline);
571 text.append("PROPERTIES\t");
572 text.append(sg.getName());
575 if (sg.getDescription() != null)
577 text.append("description=");
578 text.append(sg.getDescription());
583 text.append("colour=");
584 text.append(ColourSchemeProperty.getColourName(sg.cs));
586 if (sg.cs.getThreshold() != 0)
588 text.append("pidThreshold=");
589 text.append(sg.cs.getThreshold());
591 if (sg.cs.conservationApplied())
593 text.append("consThreshold=");
594 text.append(sg.cs.getConservationInc());
598 text.append("outlineColour=");
599 text.append(jalview.util.Format.getHexString(sg.getOutlineColour()));
602 text.append("displayBoxes=");
603 text.append(sg.getDisplayBoxes());
605 text.append("displayText=");
606 text.append(sg.getDisplayText());
608 text.append("colourText=");
609 text.append(sg.getColourText());
611 text.append("showUnconserved=");
612 text.append(sg.getShowNonconserved());
614 if (sg.textColour != java.awt.Color.black)
616 text.append("textCol1=");
617 text.append(jalview.util.Format.getHexString(sg.textColour));
620 if (sg.textColour2 != java.awt.Color.white)
622 text.append("textCol2=");
623 text.append(jalview.util.Format.getHexString(sg.textColour2));
626 if (sg.thresholdTextColour != 0)
628 text.append("textColThreshold=");
629 text.append(sg.thresholdTextColour);
632 if (sg.idColour != null)
634 text.append("idColour=");
635 text.append(jalview.util.Format.getHexString(sg.idColour));
640 text.append("hide=true\t");
644 text.append("hidecols=true\t");
648 // terminate the last line and clear the sequence ref for the group
649 text.append(newline);
650 text.append("SEQUENCE_REF");
652 text.append(newline);
653 text.append(newline);
658 SequenceI refSeq = null;
660 String refSeqId = null;
662 public boolean annotateAlignmentView(AlignViewportI viewport,
663 String file, String protocol)
665 ColumnSelection colSel = viewport.getColumnSelection();
668 colSel = new ColumnSelection();
670 boolean rslt = readAnnotationFile(viewport.getAlignment(), colSel,
672 if (rslt && (colSel.hasSelectedColumns() || colSel.hasHiddenColumns()))
674 viewport.setColumnSelection(colSel);
680 public boolean readAnnotationFile(AlignmentI al, String file,
683 return readAnnotationFile(al, null, file, protocol);
686 public boolean readAnnotationFile(AlignmentI al, ColumnSelection colSel,
687 String file, String protocol)
689 BufferedReader in = null;
692 if (protocol.equals(AppletFormatAdapter.FILE))
694 in = new BufferedReader(new FileReader(file));
696 else if (protocol.equals(AppletFormatAdapter.URL))
698 URL url = new URL(file);
699 in = new BufferedReader(new InputStreamReader(url.openStream()));
701 else if (protocol.equals(AppletFormatAdapter.PASTE))
703 in = new BufferedReader(new StringReader(file));
705 else if (protocol.equals(AppletFormatAdapter.CLASSLOADER))
707 java.io.InputStream is = getClass().getResourceAsStream("/" + file);
710 in = new BufferedReader(new java.io.InputStreamReader(is));
715 return parseAnnotationFrom(al, colSel, in);
718 } catch (Exception ex)
720 ex.printStackTrace();
721 System.out.println("Problem reading annotation file: " + ex);
724 System.out.println("Last read line " + nlinesread + ": '"
725 + lastread + "' (first 80 chars) ...");
734 String lastread = "";
736 private static String GRAPHLINE = "GRAPHLINE", COMBINE = "COMBINE";
738 public boolean parseAnnotationFrom(AlignmentI al, ColumnSelection colSel,
739 BufferedReader in) throws Exception
742 ArrayList<Object[]> combineAnnotation_calls = new ArrayList<Object[]>();
743 ArrayList<Object[]> deferredAnnotation_calls = new ArrayList<Object[]>();
744 boolean modified = false;
745 String groupRef = null;
746 Hashtable groupRefRows = new Hashtable();
748 Hashtable autoAnnots = new Hashtable();
750 String line, label, description, token;
751 int graphStyle, index;
753 int existingAnnotations = 0;
754 // when true - will add new rows regardless of whether they are duplicate
755 // auto-annotation like consensus or conservation graphs
756 boolean overrideAutoAnnot = false;
757 if (al.getAlignmentAnnotation() != null)
759 existingAnnotations = al.getAlignmentAnnotation().length;
760 if (existingAnnotations > 0)
762 AlignmentAnnotation[] aa = al.getAlignmentAnnotation();
763 for (int aai = 0; aai < aa.length; aai++)
765 if (aa[aai].autoCalculated)
767 // make a note of the name and description
769 autoAnnotsKey(aa[aai], aa[aai].sequenceRef,
770 (aa[aai].groupRef == null ? null
771 : aa[aai].groupRef.getName())),
778 int alWidth = al.getWidth();
781 Annotation[] annotations;
782 AlignmentAnnotation annotation = null;
784 // First confirm this is an Annotation file
785 boolean jvAnnotationFile = false;
786 while ((line = in.readLine()) != null)
789 lastread = new String(line);
790 if (line.indexOf("#") == 0)
795 if (line.indexOf("JALVIEW_ANNOTATION") > -1)
797 jvAnnotationFile = true;
802 if (!jvAnnotationFile)
808 while ((line = in.readLine()) != null)
811 lastread = new String(line);
812 if (line.indexOf("#") == 0
813 || line.indexOf("JALVIEW_ANNOTATION") > -1
814 || line.length() == 0)
819 st = new StringTokenizer(line, "\t");
820 token = st.nextToken();
821 if (token.equalsIgnoreCase("COLOUR"))
823 // TODO: use graduated colour def'n here too
824 colourAnnotations(al, st.nextToken(), st.nextToken());
829 else if (token.equalsIgnoreCase(COMBINE))
831 // keep a record of current state and resolve groupRef at end
832 combineAnnotation_calls
833 .add(new Object[] { st, refSeq, groupRef });
837 else if (token.equalsIgnoreCase("ROWPROPERTIES"))
839 addRowProperties(al, st);
843 else if (token.equalsIgnoreCase(GRAPHLINE))
846 deferredAnnotation_calls.add(new Object[] { GRAPHLINE, st,
852 else if (token.equalsIgnoreCase("SEQUENCE_REF"))
854 if (st.hasMoreTokens())
856 refSeq = al.findName(refSeqId = st.nextToken());
863 refSeqIndex = Integer.parseInt(st.nextToken());
868 .println("WARNING: SEQUENCE_REF index must be > 0 in AnnotationFile");
870 } catch (Exception ex)
882 else if (token.equalsIgnoreCase("GROUP_REF"))
884 // Group references could be forward or backwards, so they are
885 // resolved after the whole file is read in
887 if (st.hasMoreTokens())
889 groupRef = st.nextToken();
890 if (groupRef.length() < 1)
892 groupRef = null; // empty string
896 if (groupRefRows.get(groupRef) == null)
898 groupRefRows.put(groupRef, new Vector());
904 else if (token.equalsIgnoreCase("SEQUENCE_GROUP"))
911 else if (token.equalsIgnoreCase("PROPERTIES"))
913 addProperties(al, st);
918 else if (token.equalsIgnoreCase("BELOW_ALIGNMENT"))
920 setBelowAlignment(al, st);
924 else if (token.equalsIgnoreCase("ALIGNMENT"))
926 addAlignmentDetails(al, st);
930 // else if (token.equalsIgnoreCase("VIEW_DEF"))
932 // addOrSetView(al,st);
936 else if (token.equalsIgnoreCase("VIEW_SETREF"))
940 al.setSeqrep(refSeq);
945 else if (token.equalsIgnoreCase("VIEW_HIDECOLS"))
947 if (st.hasMoreTokens())
951 colSel = new ColumnSelection();
953 parseHideCols(colSel, st.nextToken());
958 else if (token.equalsIgnoreCase("HIDE_INSERTIONS"))
960 SequenceI sr = refSeq == null ? al.getSeqrep() : refSeq;
963 sr = al.getSequenceAt(0);
970 .println("Cannot process HIDE_INSERTIONS without an alignment view: Ignoring line: "
975 // consider deferring this till after the file has been parsed ?
976 colSel.hideInsertionsFor(sr);
983 // Parse out the annotation row
984 graphStyle = AlignmentAnnotation.getGraphValueFromString(token);
985 label = st.nextToken();
988 annotations = new Annotation[alWidth];
990 float score = Float.NaN;
992 if (st.hasMoreTokens())
994 line = st.nextToken();
996 if (line.indexOf("|") == -1)
999 if (st.hasMoreTokens())
1001 line = st.nextToken();
1005 if (st.hasMoreTokens())
1007 // This must be the score
1008 score = Float.valueOf(st.nextToken()).floatValue();
1011 st = new StringTokenizer(line, "|", true);
1013 boolean emptyColumn = true;
1014 boolean onlyOneElement = (st.countTokens() == 1);
1016 while (st.hasMoreElements() && index < alWidth)
1018 token = st.nextToken().trim();
1024 score = Float.valueOf(token).floatValue();
1026 } catch (NumberFormatException ex)
1031 if (token.equals("|"))
1042 annotations[index++] = parseAnnotation(token, graphStyle);
1043 emptyColumn = false;
1049 annotation = new AlignmentAnnotation(label, description,
1050 (index == 0) ? null : annotations, 0, 0, graphStyle);
1052 annotation.score = score;
1053 if (!overrideAutoAnnot
1054 && autoAnnots.containsKey(autoAnnotsKey(annotation, refSeq,
1057 // skip - we've already got an automatic annotation of this type.
1060 // otherwise add it!
1064 annotation.belowAlignment = false;
1065 // make a copy of refSeq so we can find other matches in the alignment
1066 SequenceI referedSeq = refSeq;
1069 // copy before we do any mapping business.
1070 // TODO: verify that undo/redo with 1:many sequence associated
1071 // annotations can be undone correctly
1072 AlignmentAnnotation ann = new AlignmentAnnotation(annotation);
1074 .createSequenceMapping(referedSeq, refSeqIndex, false);
1075 annotation.adjustForAlignment();
1076 referedSeq.addAlignmentAnnotation(annotation);
1077 al.addAnnotation(annotation);
1078 al.setAnnotationIndex(annotation,
1079 al.getAlignmentAnnotation().length
1080 - existingAnnotations - 1);
1081 if (groupRef != null)
1083 ((Vector) groupRefRows.get(groupRef)).addElement(annotation);
1085 // and recover our virgin copy to use again if necessary.
1088 } while (refSeqId != null
1089 && (referedSeq = al.findName(referedSeq, refSeqId, true)) != null);
1093 al.addAnnotation(annotation);
1094 al.setAnnotationIndex(annotation,
1095 al.getAlignmentAnnotation().length - existingAnnotations
1097 if (groupRef != null)
1099 ((Vector) groupRefRows.get(groupRef)).addElement(annotation);
1102 // and set modification flag
1105 // Resolve the groupRefs
1106 Hashtable<String, SequenceGroup> groupRefLookup = new Hashtable<String, SequenceGroup>();
1107 Enumeration en = groupRefRows.keys();
1109 while (en.hasMoreElements())
1111 groupRef = (String) en.nextElement();
1112 boolean matched = false;
1113 // Resolve group: TODO: add a getGroupByName method to alignments
1114 for (SequenceGroup theGroup : al.getGroups())
1116 if (theGroup.getName().equals(groupRef))
1120 // TODO: specify and implement duplication of alignment annotation
1121 // for multiple group references.
1123 .println("Ignoring 1:many group reference mappings for group name '"
1129 Vector rowset = (Vector) groupRefRows.get(groupRef);
1130 groupRefLookup.put(groupRef, theGroup);
1131 if (rowset != null && rowset.size() > 0)
1133 AlignmentAnnotation alan = null;
1134 for (int elm = 0, elmSize = rowset.size(); elm < elmSize; elm++)
1136 alan = (AlignmentAnnotation) rowset.elementAt(elm);
1137 alan.groupRef = theGroup;
1143 ((Vector) groupRefRows.get(groupRef)).removeAllElements();
1145 // process any deferred attribute settings for each context
1146 for (Object[] _deferred_args : deferredAnnotation_calls)
1148 if (_deferred_args[0] == GRAPHLINE)
1151 (StringTokenizer) _deferred_args[1], // st
1152 (SequenceI) _deferred_args[2], // refSeq
1153 (_deferred_args[3] == null) ? null : groupRefLookup
1154 .get(_deferred_args[3]) // the reference
1160 // finally, combine all the annotation rows within each context.
1162 * number of combine statements in this annotation file. Used to create
1163 * new groups for combined annotation graphs without disturbing existing
1166 int combinecount = 0;
1167 for (Object[] _combine_args : combineAnnotation_calls)
1169 combineAnnotations(al,
1171 (StringTokenizer) _combine_args[0], // st
1172 (SequenceI) _combine_args[1], // refSeq
1173 (_combine_args[2] == null) ? null : groupRefLookup
1174 .get(_combine_args[2]) // the reference group,
1182 private void parseHideCols(ColumnSelection colSel, String nextToken)
1184 StringTokenizer inval = new StringTokenizer(nextToken, ",");
1185 while (inval.hasMoreTokens())
1187 String range = inval.nextToken().trim();
1188 int from, to = range.indexOf("-");
1191 from = to = Integer.parseInt(range);
1194 colSel.hideColumns(from, to);
1199 from = Integer.parseInt(range.substring(0, to));
1200 if (to < range.length() - 1)
1202 to = Integer.parseInt(range.substring(to + 1));
1208 if (from > 0 && to >= from)
1210 colSel.hideColumns(from, to);
1216 private Object autoAnnotsKey(AlignmentAnnotation annotation,
1217 SequenceI refSeq, String groupRef)
1219 return annotation.graph + "\t" + annotation.label + "\t"
1220 + annotation.description + "\t"
1221 + (refSeq != null ? refSeq.getDisplayId(true) : "");
1224 Annotation parseAnnotation(String string, int graphStyle)
1226 boolean hasSymbols = (graphStyle == AlignmentAnnotation.NO_GRAPH); // don't
1235 String desc = null, displayChar = null;
1236 char ss = ' '; // secondaryStructure
1238 boolean parsedValue = false, dcset = false;
1241 java.awt.Color colour = null;
1242 int i = string.indexOf("[");
1243 int j = string.indexOf("]");
1244 if (i > -1 && j > -1)
1246 UserColourScheme ucs = new UserColourScheme();
1248 colour = ucs.getColourFromString(string.substring(i + 1, j));
1249 if (i > 0 && string.charAt(i - 1) == ',')
1251 // clip the preceding comma as well
1254 string = string.substring(0, i) + string.substring(j + 1);
1257 StringTokenizer st = new StringTokenizer(string, ",", true);
1259 boolean seenContent = false;
1261 while (st.hasMoreTokens())
1264 token = st.nextToken().trim();
1265 if (token.equals(","))
1267 if (!seenContent && parsedValue && !dcset)
1269 // allow the value below the bar/line to be empty
1273 seenContent = false;
1285 displayChar = token;
1287 value = new Float(token).floatValue();
1290 } catch (NumberFormatException ex)
1296 if (token.length() == 1)
1298 displayChar = token;
1302 && (token.length() == 1 && "()<>[]{}AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz"
1305 // Either this character represents a helix or sheet
1306 // or an integer which can be displayed
1307 ss = token.charAt(0);
1308 if (displayChar.equals(token.substring(0, 1)))
1313 else if (desc == null || (parsedValue && pass > 2))
1319 // if (!dcset && string.charAt(string.length() - 1) == ',')
1321 // displayChar = " "; // empty display char symbol.
1323 if (displayChar != null && desc != null && desc.length() == 1)
1325 if (displayChar.length() > 1)
1327 // switch desc and displayChar - legacy support
1328 String tmp = displayChar;
1334 if (displayChar.equals(desc))
1336 // duplicate label - hangover from the 'robust parser' above
1341 Annotation anot = new Annotation(displayChar, desc, ss, value);
1343 anot.colour = colour;
1348 void colourAnnotations(AlignmentI al, String label, String colour)
1350 UserColourScheme ucs = new UserColourScheme(colour);
1351 Annotation[] annotations;
1352 for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1354 if (al.getAlignmentAnnotation()[i].label.equalsIgnoreCase(label))
1356 annotations = al.getAlignmentAnnotation()[i].annotations;
1357 for (int j = 0; j < annotations.length; j++)
1359 if (annotations[j] != null)
1361 annotations[j].colour = ucs.findColour('A');
1368 void combineAnnotations(AlignmentI al, int combineCount,
1369 StringTokenizer st, SequenceI seqRef, SequenceGroup groupRef)
1371 String group = st.nextToken();
1372 // First make sure we are not overwriting the graphIndex
1374 if (al.getAlignmentAnnotation() != null)
1376 for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1378 AlignmentAnnotation aa = al.getAlignmentAnnotation()[i];
1380 if (aa.graphGroup > graphGroup)
1382 // try to number graphGroups in order of occurence.
1383 graphGroup = aa.graphGroup + 1;
1385 if (aa.sequenceRef == seqRef && aa.groupRef == groupRef
1386 && aa.label.equalsIgnoreCase(group))
1388 if (aa.graphGroup > -1)
1390 graphGroup = aa.graphGroup;
1394 if (graphGroup <= combineCount)
1396 graphGroup = combineCount + 1;
1398 aa.graphGroup = graphGroup;
1404 // Now update groups
1405 while (st.hasMoreTokens())
1407 group = st.nextToken();
1408 for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1410 AlignmentAnnotation aa = al.getAlignmentAnnotation()[i];
1411 if (aa.sequenceRef == seqRef && aa.groupRef == groupRef
1412 && aa.label.equalsIgnoreCase(group))
1414 aa.graphGroup = graphGroup;
1423 .println("Couldn't combine annotations. None are added to alignment yet!");
1427 void addLine(AlignmentI al, StringTokenizer st, SequenceI seqRef,
1428 SequenceGroup groupRef)
1430 String group = st.nextToken();
1431 AlignmentAnnotation annotation = null, alannot[] = al
1432 .getAlignmentAnnotation();
1433 float value = new Float(st.nextToken()).floatValue();
1434 String label = st.hasMoreTokens() ? st.nextToken() : null;
1435 java.awt.Color colour = null;
1436 if (st.hasMoreTokens())
1438 UserColourScheme ucs = new UserColourScheme(st.nextToken());
1439 colour = ucs.findColour('A');
1441 if (alannot != null)
1443 for (int i = 0; i < alannot.length; i++)
1445 if (alannot[i].label.equalsIgnoreCase(group)
1446 && (seqRef == null || alannot[i].sequenceRef == seqRef)
1447 && (groupRef == null || alannot[i].groupRef == groupRef))
1449 alannot[i].setThreshold(new GraphLine(value, label, colour));
1453 if (annotation == null)
1459 void addGroup(AlignmentI al, StringTokenizer st)
1461 SequenceGroup sg = new SequenceGroup();
1462 sg.setName(st.nextToken());
1466 rng = st.nextToken();
1467 if (rng.length() > 0 && !rng.startsWith("*"))
1469 sg.setStartRes(Integer.parseInt(rng) - 1);
1475 rng = st.nextToken();
1476 if (rng.length() > 0 && !rng.startsWith("*"))
1478 sg.setEndRes(Integer.parseInt(rng) - 1);
1482 sg.setEndRes(al.getWidth() - 1);
1484 } catch (Exception e)
1487 .println("Couldn't parse Group Start or End Field as '*' or a valid column or sequence index: '"
1488 + rng + "' - assuming alignment width for group.");
1489 // assume group is full width
1491 sg.setEndRes(al.getWidth() - 1);
1494 String index = st.nextToken();
1495 if (index.equals("-1"))
1497 while (st.hasMoreElements())
1499 sg.addSequence(al.findName(st.nextToken()), false);
1504 StringTokenizer st2 = new StringTokenizer(index, ",");
1506 while (st2.hasMoreTokens())
1508 String tmp = st2.nextToken();
1509 if (tmp.equals("*"))
1511 for (int i = 0; i < al.getHeight(); i++)
1513 sg.addSequence(al.getSequenceAt(i), false);
1516 else if (tmp.indexOf("-") >= 0)
1518 StringTokenizer st3 = new StringTokenizer(tmp, "-");
1520 int start = (Integer.parseInt(st3.nextToken()));
1521 int end = (Integer.parseInt(st3.nextToken()));
1525 for (int i = start; i <= end; i++)
1527 sg.addSequence(al.getSequenceAt(i - 1), false);
1533 sg.addSequence(al.getSequenceAt(Integer.parseInt(tmp) - 1), false);
1540 sg.setStartRes(refSeq.findIndex(sg.getStartRes() + 1) - 1);
1541 sg.setEndRes(refSeq.findIndex(sg.getEndRes() + 1) - 1);
1542 sg.setSeqrep(refSeq);
1545 if (sg.getSize() > 0)
1551 void addRowProperties(AlignmentI al, StringTokenizer st)
1553 String label = st.nextToken(), keyValue, key, value;
1554 boolean scaletofit = false, centerlab = false, showalllabs = false;
1555 while (st.hasMoreTokens())
1557 keyValue = st.nextToken();
1558 key = keyValue.substring(0, keyValue.indexOf("="));
1559 value = keyValue.substring(keyValue.indexOf("=") + 1);
1560 if (key.equalsIgnoreCase("scaletofit"))
1562 scaletofit = Boolean.valueOf(value).booleanValue();
1564 if (key.equalsIgnoreCase("showalllabs"))
1566 showalllabs = Boolean.valueOf(value).booleanValue();
1568 if (key.equalsIgnoreCase("centrelabs"))
1570 centerlab = Boolean.valueOf(value).booleanValue();
1572 AlignmentAnnotation[] alr = al.getAlignmentAnnotation();
1575 for (int i = 0; i < alr.length; i++)
1577 if (alr[i].label.equalsIgnoreCase(label))
1579 alr[i].centreColLabels = centerlab;
1580 alr[i].scaleColLabel = scaletofit;
1581 alr[i].showAllColLabels = showalllabs;
1588 void addProperties(AlignmentI al, StringTokenizer st)
1591 // So far we have only added groups to the annotationHash,
1592 // the idea is in the future properties can be added to
1593 // alignments, other annotations etc
1594 if (al.getGroups() == null)
1599 String name = st.nextToken();
1600 SequenceGroup sg = null;
1601 for (SequenceGroup _sg : al.getGroups())
1603 if ((sg = _sg).getName().equals(name))
1615 String keyValue, key, value;
1616 ColourSchemeI def = sg.cs;
1618 while (st.hasMoreTokens())
1620 keyValue = st.nextToken();
1621 key = keyValue.substring(0, keyValue.indexOf("="));
1622 value = keyValue.substring(keyValue.indexOf("=") + 1);
1624 if (key.equalsIgnoreCase("description"))
1626 sg.setDescription(value);
1628 else if (key.equalsIgnoreCase("colour"))
1630 sg.cs = ColourSchemeProperty.getColour(al, value);
1632 else if (key.equalsIgnoreCase("pidThreshold"))
1634 sg.cs.setThreshold(Integer.parseInt(value), true);
1637 else if (key.equalsIgnoreCase("consThreshold"))
1639 sg.cs.setConservationInc(Integer.parseInt(value));
1640 Conservation c = new Conservation("Group", 3,
1641 sg.getSequences(null), sg.getStartRes(),
1642 sg.getEndRes() + 1);
1645 c.verdict(false, 25); // TODO: refer to conservation percent threshold
1647 sg.cs.setConservation(c);
1650 else if (key.equalsIgnoreCase("outlineColour"))
1652 sg.setOutlineColour(new UserColourScheme(value).findColour('A'));
1654 else if (key.equalsIgnoreCase("displayBoxes"))
1656 sg.setDisplayBoxes(Boolean.valueOf(value).booleanValue());
1658 else if (key.equalsIgnoreCase("showUnconserved"))
1660 sg.setShowNonconserved(Boolean.valueOf(value).booleanValue());
1662 else if (key.equalsIgnoreCase("displayText"))
1664 sg.setDisplayText(Boolean.valueOf(value).booleanValue());
1666 else if (key.equalsIgnoreCase("colourText"))
1668 sg.setColourText(Boolean.valueOf(value).booleanValue());
1670 else if (key.equalsIgnoreCase("textCol1"))
1672 sg.textColour = new UserColourScheme(value).findColour('A');
1674 else if (key.equalsIgnoreCase("textCol2"))
1676 sg.textColour2 = new UserColourScheme(value).findColour('A');
1678 else if (key.equalsIgnoreCase("textColThreshold"))
1680 sg.thresholdTextColour = Integer.parseInt(value);
1682 else if (key.equalsIgnoreCase("idColour"))
1684 // consider warning if colour doesn't resolve to a real colour
1685 sg.setIdColour((def = new UserColourScheme(value))
1688 else if (key.equalsIgnoreCase("hide"))
1690 // see bug https://mantis.lifesci.dundee.ac.uk/view.php?id=25847
1691 sg.setHidereps(true);
1693 else if (key.equalsIgnoreCase("hidecols"))
1695 // see bug https://mantis.lifesci.dundee.ac.uk/view.php?id=25847
1696 sg.setHideCols(true);
1698 sg.recalcConservation();
1707 void setBelowAlignment(AlignmentI al, StringTokenizer st)
1710 AlignmentAnnotation aa, ala[] = al.getAlignmentAnnotation();
1714 .print("Warning - no annotation to set below for sequence associated annotation:");
1716 while (st.hasMoreTokens())
1718 token = st.nextToken();
1721 System.err.print(" " + token);
1725 for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1727 aa = al.getAlignmentAnnotation()[i];
1728 if (aa.sequenceRef == refSeq && aa.label.equals(token))
1730 aa.belowAlignment = true;
1737 System.err.print("\n");
1741 void addAlignmentDetails(AlignmentI al, StringTokenizer st)
1743 String keyValue, key, value;
1744 while (st.hasMoreTokens())
1746 keyValue = st.nextToken();
1747 key = keyValue.substring(0, keyValue.indexOf("="));
1748 value = keyValue.substring(keyValue.indexOf("=") + 1);
1749 al.setProperty(key, value);
1754 * Write annotations as a CSV file of the form 'label, value, value, ...' for
1757 * @param annotations
1758 * @return CSV file as a string.
1760 public String printCSVAnnotations(AlignmentAnnotation[] annotations)
1762 if (annotations == null)
1766 StringBuffer sp = new StringBuffer();
1767 for (int i = 0; i < annotations.length; i++)
1769 String atos = annotations[i].toString();
1773 int cp = atos.indexOf("\n", p);
1774 sp.append(annotations[i].label);
1778 sp.append(atos.substring(p, cp + 1));
1782 sp.append(atos.substring(p));
1788 return sp.toString();
1791 public String printAnnotationsForView(AlignViewportI viewport)
1793 return printAnnotations(viewport.isShowAnnotation() ? viewport
1794 .getAlignment().getAlignmentAnnotation() : null, viewport
1795 .getAlignment().getGroups(), viewport.getAlignment()
1796 .getProperties(), viewport.getColumnSelection(),
1797 viewport.getAlignment(), null);
1800 public String printAnnotationsForAlignment(AlignmentI al)
1802 return printAnnotations(al.getAlignmentAnnotation(), al.getGroups(),
1803 al.getProperties(), null, al, null);