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.util.ColorUtils;
37 import java.awt.Color;
38 import java.io.BufferedReader;
39 import java.io.FileReader;
40 import java.io.InputStreamReader;
41 import java.io.StringReader;
43 import java.util.ArrayList;
44 import java.util.BitSet;
45 import java.util.Enumeration;
46 import java.util.Hashtable;
47 import java.util.List;
49 import java.util.StringTokenizer;
50 import java.util.Vector;
52 public class AnnotationFile
54 public AnnotationFile()
60 * character used to write newlines
62 protected String newline = System.getProperty("line.separator");
65 * set new line string and reset the output buffer
69 public void setNewlineString(String nl)
75 public String getNewlineString()
84 text = new StringBuffer("JALVIEW_ANNOTATION" + newline + "# Created: "
85 + new java.util.Date() + newline + newline);
91 * convenience method for pre-2.9 annotation files which have no view, hidden
92 * columns or hidden row keywords.
97 * @return annotation file as a string.
99 public String printAnnotations(AlignmentAnnotation[] annotations,
100 List<SequenceGroup> list, Hashtable properties)
102 return printAnnotations(annotations, list, properties, null, null, null);
107 * hold all the information about a particular view definition read from or
108 * written out in an annotations file.
112 // TODO this class is not used - remove?
113 public final String viewname;
115 public final HiddenSequences hidseqs;
117 public final ColumnSelection hiddencols;
119 // public final Vector visibleGroups;
121 public final Hashtable hiddenRepSeqs;
123 public ViewDef(String vname, HiddenSequences hseqs,
124 ColumnSelection hcols, Hashtable hRepSeqs)
126 this.viewname = vname;
127 this.hidseqs = hseqs;
128 this.hiddencols = hcols;
129 this.hiddenRepSeqs = hRepSeqs;
134 * Prepare an annotation file given a set of annotations, groups, alignment
135 * properties and views.
141 * @return annotation file
143 public String printAnnotations(AlignmentAnnotation[] annotations,
144 List<SequenceGroup> list, Hashtable properties,
145 ColumnSelection cs, AlignmentI al, ViewDef view)
149 if (view.viewname != null)
151 text.append("VIEW_DEF\t" + view.viewname + "\n");
155 // list = view.visibleGroups;
159 cs = view.hiddencols;
163 // add hidden rep sequences.
166 // first target - store and restore all settings for a view.
167 if (al != null && al.hasSeqrep())
169 text.append("VIEW_SETREF\t" + al.getSeqrep().getName() + "\n");
171 if (cs != null && cs.hasHiddenColumns())
173 text.append("VIEW_HIDECOLS\t");
174 List<int[]> hc = cs.getHiddenColumns();
175 boolean comma = false;
192 // TODO: allow efficient recovery of annotation data shown in several
194 if (annotations != null)
196 boolean oneColour = true;
197 AlignmentAnnotation row;
199 SequenceI refSeq = null;
200 SequenceGroup refGroup = null;
202 StringBuffer colours = new StringBuffer();
203 StringBuffer graphLine = new StringBuffer();
204 StringBuffer rowprops = new StringBuffer();
205 Hashtable<Integer, String> graphGroup = new Hashtable<Integer, String>();
206 Hashtable<Integer, Object[]> graphGroup_refs = new Hashtable<Integer, Object[]>();
207 BitSet graphGroupSeen = new BitSet();
209 java.awt.Color color;
211 for (int i = 0; i < annotations.length; i++)
213 row = annotations[i];
217 && !(row.graphGroup > -1 && graphGroupSeen
218 .get(row.graphGroup)))
226 // mark any sequence references for the row
227 writeSequence_Ref(refSeq, row.sequenceRef);
228 refSeq = row.sequenceRef;
229 // mark any group references for the row
230 writeGroup_Ref(refGroup, row.groupRef);
231 refGroup = row.groupRef;
233 boolean hasGlyphs = row.hasIcons, hasLabels = row.hasText, hasValues = row.hasScore, hasText = false;
234 // lookahead to check what the annotation row object actually contains.
235 for (int j = 0; row.annotations != null
236 && j < row.annotations.length
237 && (!hasGlyphs || !hasLabels || !hasValues); j++)
239 if (row.annotations[j] != null)
241 hasLabels |= (row.annotations[j].displayCharacter != null
242 && row.annotations[j].displayCharacter.length() > 0 && !row.annotations[j].displayCharacter
244 hasGlyphs |= (row.annotations[j].secondaryStructure != 0 && row.annotations[j].secondaryStructure != ' ');
245 hasValues |= (!Float.isNaN(row.annotations[j].value)); // NaNs can't
248 hasText |= (row.annotations[j].description != null && row.annotations[j].description
253 if (row.graph == AlignmentAnnotation.NO_GRAPH)
255 text.append("NO_GRAPH\t");
256 hasValues = false; // only secondary structure
257 // hasLabels = false; // and annotation description string.
261 if (row.graph == AlignmentAnnotation.BAR_GRAPH)
263 text.append("BAR_GRAPH\t");
264 hasGlyphs = false; // no secondary structure
267 else if (row.graph == AlignmentAnnotation.LINE_GRAPH)
269 hasGlyphs = false; // no secondary structure
270 text.append("LINE_GRAPH\t");
273 if (row.getThreshold() != null)
275 graphLine.append("GRAPHLINE\t");
276 graphLine.append(row.label);
277 graphLine.append("\t");
278 graphLine.append(row.getThreshold().value);
279 graphLine.append("\t");
280 graphLine.append(row.getThreshold().label);
281 graphLine.append("\t");
282 graphLine.append(jalview.util.Format.getHexString(row
283 .getThreshold().colour));
284 graphLine.append(newline);
287 if (row.graphGroup > -1)
289 graphGroupSeen.set(row.graphGroup);
290 Integer key = new Integer(row.graphGroup);
291 if (graphGroup.containsKey(key))
293 graphGroup.put(key, graphGroup.get(key) + "\t" + row.label);
298 graphGroup_refs.put(key, new Object[] { refSeq, refGroup });
299 graphGroup.put(key, row.label);
304 text.append(row.label + "\t");
305 if (row.description != null)
307 text.append(row.description + "\t");
309 for (int j = 0; row.annotations != null
310 && j < row.annotations.length; j++)
313 && jalview.util.Comparison.isGap(refSeq.getCharAt(j)))
318 if (row.annotations[j] != null)
321 if (hasGlyphs) // could be also hasGlyphs || ...
325 if (row.annotations[j].secondaryStructure != ' ')
327 // only write out the field if its not whitespace.
328 text.append(row.annotations[j].secondaryStructure);
334 if (!Float.isNaN(row.annotations[j].value))
336 text.append(comma + row.annotations[j].value);
340 // System.err.println("Skipping NaN - not valid value.");
341 text.append(comma + 0f);// row.annotations[j].value);
347 // TODO: labels are emitted after values for bar graphs.
348 if // empty labels are allowed, so
349 (row.annotations[j].displayCharacter != null
350 && row.annotations[j].displayCharacter.length() > 0
351 && !row.annotations[j].displayCharacter.equals(" "))
353 text.append(comma + row.annotations[j].displayCharacter);
359 if (row.annotations[j].description != null
360 && row.annotations[j].description.length() > 0
361 && !row.annotations[j].description
362 .equals(row.annotations[j].displayCharacter))
364 text.append(comma + row.annotations[j].description);
368 if (color != null && !color.equals(row.annotations[j].colour))
373 color = row.annotations[j].colour;
375 if (row.annotations[j].colour != null
376 && row.annotations[j].colour != java.awt.Color.black)
380 + jalview.util.Format
381 .getHexString(row.annotations[j].colour)
391 text.append("\t" + row.score);
394 text.append(newline);
396 if (color != null && color != java.awt.Color.black && oneColour)
398 colours.append("COLOUR\t");
399 colours.append(row.label);
400 colours.append("\t");
401 colours.append(jalview.util.Format.getHexString(color));
402 colours.append(newline);
404 if (row.scaleColLabel || row.showAllColLabels
405 || row.centreColLabels)
407 rowprops.append("ROWPROPERTIES\t");
408 rowprops.append(row.label);
409 rowprops.append("\tscaletofit=");
410 rowprops.append(row.scaleColLabel);
411 rowprops.append("\tshowalllabs=");
412 rowprops.append(row.showAllColLabels);
413 rowprops.append("\tcentrelabs=");
414 rowprops.append(row.centreColLabels);
415 rowprops.append(newline);
417 if (graphLine.length() > 0)
419 text.append(graphLine.toString());
420 graphLine.setLength(0);
424 text.append(newline);
426 text.append(colours.toString());
427 if (graphGroup.size() > 0)
429 SequenceI oldRefSeq = refSeq;
430 SequenceGroup oldRefGroup = refGroup;
431 for (Map.Entry<Integer, String> combine_statement : graphGroup
434 Object[] seqRefAndGroup = graphGroup_refs.get(combine_statement
437 writeSequence_Ref(refSeq, (SequenceI) seqRefAndGroup[0]);
438 refSeq = (SequenceI) seqRefAndGroup[0];
440 writeGroup_Ref(refGroup, (SequenceGroup) seqRefAndGroup[1]);
441 refGroup = (SequenceGroup) seqRefAndGroup[1];
442 text.append("COMBINE\t");
443 text.append(combine_statement.getValue());
444 text.append(newline);
446 writeSequence_Ref(refSeq, oldRefSeq);
449 writeGroup_Ref(refGroup, oldRefGroup);
450 refGroup = oldRefGroup;
452 text.append(rowprops.toString());
460 if (properties != null)
462 text.append(newline);
463 text.append(newline);
464 text.append("ALIGNMENT");
465 Enumeration en = properties.keys();
466 while (en.hasMoreElements())
468 String key = en.nextElement().toString();
472 text.append(properties.get(key));
474 // TODO: output alignment visualization settings here if required
475 // iterate through one or more views, defining, marking columns and rows
476 // as visible/hidden, and emmitting view properties.
477 // View specific annotation is
480 return text.toString();
483 private Object writeGroup_Ref(SequenceGroup refGroup,
484 SequenceGroup next_refGroup)
486 if (next_refGroup == null)
489 if (refGroup != null)
491 text.append(newline);
492 text.append("GROUP_REF\t");
493 text.append("ALIGNMENT");
494 text.append(newline);
500 if (refGroup == null || refGroup != next_refGroup)
502 text.append(newline);
503 text.append("GROUP_REF\t");
504 text.append(next_refGroup.getName());
505 text.append(newline);
512 private boolean writeSequence_Ref(SequenceI refSeq, SequenceI next_refSeq)
515 if (next_refSeq == null)
519 text.append(newline);
520 text.append("SEQUENCE_REF\t");
521 text.append("ALIGNMENT");
522 text.append(newline);
528 if (refSeq == null || refSeq != next_refSeq)
530 text.append(newline);
531 text.append("SEQUENCE_REF\t");
532 text.append(next_refSeq.getName());
533 text.append(newline);
540 protected void printGroups(List<SequenceGroup> list)
542 SequenceI seqrep = null;
543 for (SequenceGroup sg : list)
547 text.append("SEQUENCE_GROUP\t" + sg.getName() + "\t"
548 + (sg.getStartRes() + 1) + "\t" + (sg.getEndRes() + 1)
554 seqrep = sg.getSeqrep();
555 text.append("SEQUENCE_REF\t");
556 text.append(seqrep.getName());
557 text.append(newline);
558 text.append("SEQUENCE_GROUP\t");
559 text.append(sg.getName());
561 text.append((seqrep.findPosition(sg.getStartRes())));
563 text.append((seqrep.findPosition(sg.getEndRes())));
567 for (int s = 0; s < sg.getSize(); s++)
569 text.append(sg.getSequenceAt(s).getName());
572 text.append(newline);
573 text.append("PROPERTIES\t");
574 text.append(sg.getName());
577 if (sg.getDescription() != null)
579 text.append("description=");
580 text.append(sg.getDescription());
585 text.append("colour=");
586 text.append(ColourSchemeProperty.getColourName(sg.cs
587 .getColourScheme()));
589 if (sg.cs.getThreshold() != 0)
591 text.append("pidThreshold=");
592 text.append(sg.cs.getThreshold());
594 if (sg.cs.conservationApplied())
596 text.append("consThreshold=");
597 text.append(sg.cs.getConservationInc());
601 text.append("outlineColour=");
602 text.append(jalview.util.Format.getHexString(sg.getOutlineColour()));
605 text.append("displayBoxes=");
606 text.append(sg.getDisplayBoxes());
608 text.append("displayText=");
609 text.append(sg.getDisplayText());
611 text.append("colourText=");
612 text.append(sg.getColourText());
614 text.append("showUnconserved=");
615 text.append(sg.getShowNonconserved());
617 if (sg.textColour != java.awt.Color.black)
619 text.append("textCol1=");
620 text.append(jalview.util.Format.getHexString(sg.textColour));
623 if (sg.textColour2 != java.awt.Color.white)
625 text.append("textCol2=");
626 text.append(jalview.util.Format.getHexString(sg.textColour2));
629 if (sg.thresholdTextColour != 0)
631 text.append("textColThreshold=");
632 text.append(sg.thresholdTextColour);
635 if (sg.idColour != null)
637 text.append("idColour=");
638 text.append(jalview.util.Format.getHexString(sg.idColour));
643 text.append("hide=true\t");
647 text.append("hidecols=true\t");
651 // terminate the last line and clear the sequence ref for the group
652 text.append(newline);
653 text.append("SEQUENCE_REF");
655 text.append(newline);
656 text.append(newline);
661 SequenceI refSeq = null;
663 String refSeqId = null;
665 public boolean annotateAlignmentView(AlignViewportI viewport,
666 String file, DataSourceType protocol)
668 ColumnSelection colSel = viewport.getColumnSelection();
671 colSel = new ColumnSelection();
673 boolean rslt = readAnnotationFile(viewport.getAlignment(), colSel,
675 if (rslt && (colSel.hasSelectedColumns() || colSel.hasHiddenColumns()))
677 viewport.setColumnSelection(colSel);
683 public boolean readAnnotationFile(AlignmentI al, String file,
684 DataSourceType sourceType)
686 return readAnnotationFile(al, null, file, sourceType);
689 public boolean readAnnotationFile(AlignmentI al, ColumnSelection colSel,
690 String file, DataSourceType sourceType)
692 BufferedReader in = null;
695 if (sourceType == DataSourceType.FILE)
697 in = new BufferedReader(new FileReader(file));
699 else if (sourceType == DataSourceType.URL)
701 URL url = new URL(file);
702 in = new BufferedReader(new InputStreamReader(url.openStream()));
704 else if (sourceType == DataSourceType.PASTE)
706 in = new BufferedReader(new StringReader(file));
708 else if (sourceType == DataSourceType.CLASSLOADER)
710 java.io.InputStream is = getClass().getResourceAsStream("/" + file);
713 in = new BufferedReader(new java.io.InputStreamReader(is));
718 return parseAnnotationFrom(al, colSel, in);
721 } catch (Exception ex)
723 ex.printStackTrace();
724 System.out.println("Problem reading annotation file: " + ex);
727 System.out.println("Last read line " + nlinesread + ": '"
728 + lastread + "' (first 80 chars) ...");
737 String lastread = "";
739 private static String GRAPHLINE = "GRAPHLINE", COMBINE = "COMBINE";
741 public boolean parseAnnotationFrom(AlignmentI al, ColumnSelection colSel,
742 BufferedReader in) throws Exception
745 ArrayList<Object[]> combineAnnotation_calls = new ArrayList<Object[]>();
746 ArrayList<Object[]> deferredAnnotation_calls = new ArrayList<Object[]>();
747 boolean modified = false;
748 String groupRef = null;
749 Hashtable groupRefRows = new Hashtable();
751 Hashtable autoAnnots = new Hashtable();
753 String line, label, description, token;
754 int graphStyle, index;
756 int existingAnnotations = 0;
757 // when true - will add new rows regardless of whether they are duplicate
758 // auto-annotation like consensus or conservation graphs
759 boolean overrideAutoAnnot = false;
760 if (al.getAlignmentAnnotation() != null)
762 existingAnnotations = al.getAlignmentAnnotation().length;
763 if (existingAnnotations > 0)
765 AlignmentAnnotation[] aa = al.getAlignmentAnnotation();
766 for (int aai = 0; aai < aa.length; aai++)
768 if (aa[aai].autoCalculated)
770 // make a note of the name and description
772 autoAnnotsKey(aa[aai], aa[aai].sequenceRef,
773 (aa[aai].groupRef == null ? null
774 : aa[aai].groupRef.getName())),
781 int alWidth = al.getWidth();
784 Annotation[] annotations;
785 AlignmentAnnotation annotation = null;
787 // First confirm this is an Annotation file
788 boolean jvAnnotationFile = false;
789 while ((line = in.readLine()) != null)
792 lastread = new String(line);
793 if (line.indexOf("#") == 0)
798 if (line.indexOf("JALVIEW_ANNOTATION") > -1)
800 jvAnnotationFile = true;
805 if (!jvAnnotationFile)
811 while ((line = in.readLine()) != null)
814 lastread = new String(line);
815 if (line.indexOf("#") == 0
816 || line.indexOf("JALVIEW_ANNOTATION") > -1
817 || line.length() == 0)
822 st = new StringTokenizer(line, "\t");
823 token = st.nextToken();
824 if (token.equalsIgnoreCase("COLOUR"))
826 // TODO: use graduated colour def'n here too
827 colourAnnotations(al, st.nextToken(), st.nextToken());
832 else if (token.equalsIgnoreCase(COMBINE))
834 // keep a record of current state and resolve groupRef at end
835 combineAnnotation_calls
836 .add(new Object[] { st, refSeq, groupRef });
840 else if (token.equalsIgnoreCase("ROWPROPERTIES"))
842 addRowProperties(al, st);
846 else if (token.equalsIgnoreCase(GRAPHLINE))
849 deferredAnnotation_calls.add(new Object[] { GRAPHLINE, st,
855 else if (token.equalsIgnoreCase("SEQUENCE_REF"))
857 if (st.hasMoreTokens())
859 refSeq = al.findName(refSeqId = st.nextToken());
866 refSeqIndex = Integer.parseInt(st.nextToken());
871 .println("WARNING: SEQUENCE_REF index must be > 0 in AnnotationFile");
873 } catch (Exception ex)
885 else if (token.equalsIgnoreCase("GROUP_REF"))
887 // Group references could be forward or backwards, so they are
888 // resolved after the whole file is read in
890 if (st.hasMoreTokens())
892 groupRef = st.nextToken();
893 if (groupRef.length() < 1)
895 groupRef = null; // empty string
899 if (groupRefRows.get(groupRef) == null)
901 groupRefRows.put(groupRef, new Vector());
907 else if (token.equalsIgnoreCase("SEQUENCE_GROUP"))
914 else if (token.equalsIgnoreCase("PROPERTIES"))
916 addProperties(al, st);
921 else if (token.equalsIgnoreCase("BELOW_ALIGNMENT"))
923 setBelowAlignment(al, st);
927 else if (token.equalsIgnoreCase("ALIGNMENT"))
929 addAlignmentDetails(al, st);
933 // else if (token.equalsIgnoreCase("VIEW_DEF"))
935 // addOrSetView(al,st);
939 else if (token.equalsIgnoreCase("VIEW_SETREF"))
943 al.setSeqrep(refSeq);
948 else if (token.equalsIgnoreCase("VIEW_HIDECOLS"))
950 if (st.hasMoreTokens())
954 colSel = new ColumnSelection();
956 parseHideCols(colSel, st.nextToken());
961 else if (token.equalsIgnoreCase("HIDE_INSERTIONS"))
963 SequenceI sr = refSeq == null ? al.getSeqrep() : refSeq;
966 sr = al.getSequenceAt(0);
973 .println("Cannot process HIDE_INSERTIONS without an alignment view: Ignoring line: "
978 // consider deferring this till after the file has been parsed ?
979 colSel.hideInsertionsFor(sr);
986 // Parse out the annotation row
987 graphStyle = AlignmentAnnotation.getGraphValueFromString(token);
988 label = st.nextToken();
991 annotations = new Annotation[alWidth];
993 float score = Float.NaN;
995 if (st.hasMoreTokens())
997 line = st.nextToken();
999 if (line.indexOf("|") == -1)
1002 if (st.hasMoreTokens())
1004 line = st.nextToken();
1008 if (st.hasMoreTokens())
1010 // This must be the score
1011 score = Float.valueOf(st.nextToken()).floatValue();
1014 st = new StringTokenizer(line, "|", true);
1016 boolean emptyColumn = true;
1017 boolean onlyOneElement = (st.countTokens() == 1);
1019 while (st.hasMoreElements() && index < alWidth)
1021 token = st.nextToken().trim();
1027 score = Float.valueOf(token).floatValue();
1029 } catch (NumberFormatException ex)
1034 if (token.equals("|"))
1045 annotations[index++] = parseAnnotation(token, graphStyle);
1046 emptyColumn = false;
1052 annotation = new AlignmentAnnotation(label, description,
1053 (index == 0) ? null : annotations, 0, 0, graphStyle);
1055 annotation.score = score;
1056 if (!overrideAutoAnnot
1057 && autoAnnots.containsKey(autoAnnotsKey(annotation, refSeq,
1060 // skip - we've already got an automatic annotation of this type.
1063 // otherwise add it!
1067 annotation.belowAlignment = false;
1068 // make a copy of refSeq so we can find other matches in the alignment
1069 SequenceI referedSeq = refSeq;
1072 // copy before we do any mapping business.
1073 // TODO: verify that undo/redo with 1:many sequence associated
1074 // annotations can be undone correctly
1075 AlignmentAnnotation ann = new AlignmentAnnotation(annotation);
1077 .createSequenceMapping(referedSeq, refSeqIndex, false);
1078 annotation.adjustForAlignment();
1079 referedSeq.addAlignmentAnnotation(annotation);
1080 al.addAnnotation(annotation);
1081 al.setAnnotationIndex(annotation,
1082 al.getAlignmentAnnotation().length
1083 - existingAnnotations - 1);
1084 if (groupRef != null)
1086 ((Vector) groupRefRows.get(groupRef)).addElement(annotation);
1088 // and recover our virgin copy to use again if necessary.
1091 } while (refSeqId != null
1092 && (referedSeq = al.findName(referedSeq, refSeqId, true)) != null);
1096 al.addAnnotation(annotation);
1097 al.setAnnotationIndex(annotation,
1098 al.getAlignmentAnnotation().length - existingAnnotations
1100 if (groupRef != null)
1102 ((Vector) groupRefRows.get(groupRef)).addElement(annotation);
1105 // and set modification flag
1108 // Resolve the groupRefs
1109 Hashtable<String, SequenceGroup> groupRefLookup = new Hashtable<String, SequenceGroup>();
1110 Enumeration en = groupRefRows.keys();
1112 while (en.hasMoreElements())
1114 groupRef = (String) en.nextElement();
1115 boolean matched = false;
1116 // Resolve group: TODO: add a getGroupByName method to alignments
1117 for (SequenceGroup theGroup : al.getGroups())
1119 if (theGroup.getName().equals(groupRef))
1123 // TODO: specify and implement duplication of alignment annotation
1124 // for multiple group references.
1126 .println("Ignoring 1:many group reference mappings for group name '"
1132 Vector rowset = (Vector) groupRefRows.get(groupRef);
1133 groupRefLookup.put(groupRef, theGroup);
1134 if (rowset != null && rowset.size() > 0)
1136 AlignmentAnnotation alan = null;
1137 for (int elm = 0, elmSize = rowset.size(); elm < elmSize; elm++)
1139 alan = (AlignmentAnnotation) rowset.elementAt(elm);
1140 alan.groupRef = theGroup;
1146 ((Vector) groupRefRows.get(groupRef)).removeAllElements();
1148 // process any deferred attribute settings for each context
1149 for (Object[] _deferred_args : deferredAnnotation_calls)
1151 if (_deferred_args[0] == GRAPHLINE)
1154 (StringTokenizer) _deferred_args[1], // st
1155 (SequenceI) _deferred_args[2], // refSeq
1156 (_deferred_args[3] == null) ? null : groupRefLookup
1157 .get(_deferred_args[3]) // the reference
1163 // finally, combine all the annotation rows within each context.
1165 * number of combine statements in this annotation file. Used to create
1166 * new groups for combined annotation graphs without disturbing existing
1169 int combinecount = 0;
1170 for (Object[] _combine_args : combineAnnotation_calls)
1172 combineAnnotations(al,
1174 (StringTokenizer) _combine_args[0], // st
1175 (SequenceI) _combine_args[1], // refSeq
1176 (_combine_args[2] == null) ? null : groupRefLookup
1177 .get(_combine_args[2]) // the reference group,
1185 private void parseHideCols(ColumnSelection colSel, String nextToken)
1187 StringTokenizer inval = new StringTokenizer(nextToken, ",");
1188 while (inval.hasMoreTokens())
1190 String range = inval.nextToken().trim();
1191 int from, to = range.indexOf("-");
1194 from = to = Integer.parseInt(range);
1197 colSel.hideColumns(from, to);
1202 from = Integer.parseInt(range.substring(0, to));
1203 if (to < range.length() - 1)
1205 to = Integer.parseInt(range.substring(to + 1));
1211 if (from > 0 && to >= from)
1213 colSel.hideColumns(from, to);
1219 private Object autoAnnotsKey(AlignmentAnnotation annotation,
1220 SequenceI refSeq, String groupRef)
1222 return annotation.graph + "\t" + annotation.label + "\t"
1223 + annotation.description + "\t"
1224 + (refSeq != null ? refSeq.getDisplayId(true) : "");
1227 Annotation parseAnnotation(String string, int graphStyle)
1229 // don't do the glyph test if we don't want secondary structure
1230 boolean hasSymbols = (graphStyle == AlignmentAnnotation.NO_GRAPH);
1231 String desc = null, displayChar = null;
1232 char ss = ' '; // secondaryStructure
1234 boolean parsedValue = false, dcset = false;
1237 Color colour = null;
1238 int i = string.indexOf("[");
1239 int j = string.indexOf("]");
1240 if (i > -1 && j > -1)
1242 colour = ColorUtils.parseColourString(string.substring(i + 1,
1244 if (i > 0 && string.charAt(i - 1) == ',')
1246 // clip the preceding comma as well
1249 string = string.substring(0, i) + string.substring(j + 1);
1252 StringTokenizer st = new StringTokenizer(string, ",", true);
1254 boolean seenContent = false;
1256 while (st.hasMoreTokens())
1259 token = st.nextToken().trim();
1260 if (token.equals(","))
1262 if (!seenContent && parsedValue && !dcset)
1264 // allow the value below the bar/line to be empty
1268 seenContent = false;
1280 displayChar = token;
1282 value = new Float(token).floatValue();
1285 } catch (NumberFormatException ex)
1291 if (token.length() == 1)
1293 displayChar = token;
1297 && (token.length() == 1 && "()<>[]{}AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz"
1300 // Either this character represents a helix or sheet
1301 // or an integer which can be displayed
1302 ss = token.charAt(0);
1303 if (displayChar.equals(token.substring(0, 1)))
1308 else if (desc == null || (parsedValue && pass > 2))
1314 // if (!dcset && string.charAt(string.length() - 1) == ',')
1316 // displayChar = " "; // empty display char symbol.
1318 if (displayChar != null && desc != null && desc.length() == 1)
1320 if (displayChar.length() > 1)
1322 // switch desc and displayChar - legacy support
1323 String tmp = displayChar;
1329 if (displayChar.equals(desc))
1331 // duplicate label - hangover from the 'robust parser' above
1336 Annotation anot = new Annotation(displayChar, desc, ss, value);
1338 anot.colour = colour;
1343 void colourAnnotations(AlignmentI al, String label, String colour)
1345 Color awtColour = ColorUtils.parseColourString(colour);
1346 Annotation[] annotations;
1347 for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1349 if (al.getAlignmentAnnotation()[i].label.equalsIgnoreCase(label))
1351 annotations = al.getAlignmentAnnotation()[i].annotations;
1352 for (int j = 0; j < annotations.length; j++)
1354 if (annotations[j] != null)
1356 annotations[j].colour = awtColour;
1363 void combineAnnotations(AlignmentI al, int combineCount,
1364 StringTokenizer st, SequenceI seqRef, SequenceGroup groupRef)
1366 String group = st.nextToken();
1367 // First make sure we are not overwriting the graphIndex
1369 if (al.getAlignmentAnnotation() != null)
1371 for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1373 AlignmentAnnotation aa = al.getAlignmentAnnotation()[i];
1375 if (aa.graphGroup > graphGroup)
1377 // try to number graphGroups in order of occurence.
1378 graphGroup = aa.graphGroup + 1;
1380 if (aa.sequenceRef == seqRef && aa.groupRef == groupRef
1381 && aa.label.equalsIgnoreCase(group))
1383 if (aa.graphGroup > -1)
1385 graphGroup = aa.graphGroup;
1389 if (graphGroup <= combineCount)
1391 graphGroup = combineCount + 1;
1393 aa.graphGroup = graphGroup;
1399 // Now update groups
1400 while (st.hasMoreTokens())
1402 group = st.nextToken();
1403 for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1405 AlignmentAnnotation aa = al.getAlignmentAnnotation()[i];
1406 if (aa.sequenceRef == seqRef && aa.groupRef == groupRef
1407 && aa.label.equalsIgnoreCase(group))
1409 aa.graphGroup = graphGroup;
1418 .println("Couldn't combine annotations. None are added to alignment yet!");
1422 void addLine(AlignmentI al, StringTokenizer st, SequenceI seqRef,
1423 SequenceGroup groupRef)
1425 String group = st.nextToken();
1426 AlignmentAnnotation[] alannot = al.getAlignmentAnnotation();
1427 String nextToken = st.nextToken();
1431 value = Float.valueOf(nextToken);
1432 } catch (NumberFormatException e)
1434 System.err.println("line " + nlinesread + ": Threshold '" + nextToken
1435 + "' invalid, setting to zero");
1437 String label = st.hasMoreTokens() ? st.nextToken() : null;
1438 Color colour = null;
1439 if (st.hasMoreTokens())
1441 colour = ColorUtils.parseColourString(st.nextToken());
1443 if (alannot != null)
1445 for (int i = 0; i < alannot.length; i++)
1447 if (alannot[i].label.equalsIgnoreCase(group)
1448 && (seqRef == null || alannot[i].sequenceRef == seqRef)
1449 && (groupRef == null || alannot[i].groupRef == groupRef))
1451 alannot[i].setThreshold(new GraphLine(value, label, colour));
1457 void addGroup(AlignmentI al, StringTokenizer st)
1459 SequenceGroup sg = new SequenceGroup();
1460 sg.setName(st.nextToken());
1464 rng = st.nextToken();
1465 if (rng.length() > 0 && !rng.startsWith("*"))
1467 sg.setStartRes(Integer.parseInt(rng) - 1);
1473 rng = st.nextToken();
1474 if (rng.length() > 0 && !rng.startsWith("*"))
1476 sg.setEndRes(Integer.parseInt(rng) - 1);
1480 sg.setEndRes(al.getWidth() - 1);
1482 } catch (Exception e)
1485 .println("Couldn't parse Group Start or End Field as '*' or a valid column or sequence index: '"
1486 + rng + "' - assuming alignment width for group.");
1487 // assume group is full width
1489 sg.setEndRes(al.getWidth() - 1);
1492 String index = st.nextToken();
1493 if (index.equals("-1"))
1495 while (st.hasMoreElements())
1497 sg.addSequence(al.findName(st.nextToken()), false);
1502 StringTokenizer st2 = new StringTokenizer(index, ",");
1504 while (st2.hasMoreTokens())
1506 String tmp = st2.nextToken();
1507 if (tmp.equals("*"))
1509 for (int i = 0; i < al.getHeight(); i++)
1511 sg.addSequence(al.getSequenceAt(i), false);
1514 else if (tmp.indexOf("-") >= 0)
1516 StringTokenizer st3 = new StringTokenizer(tmp, "-");
1518 int start = (Integer.parseInt(st3.nextToken()));
1519 int end = (Integer.parseInt(st3.nextToken()));
1523 for (int i = start; i <= end; i++)
1525 sg.addSequence(al.getSequenceAt(i - 1), false);
1531 sg.addSequence(al.getSequenceAt(Integer.parseInt(tmp) - 1), false);
1538 sg.setStartRes(refSeq.findIndex(sg.getStartRes() + 1) - 1);
1539 sg.setEndRes(refSeq.findIndex(sg.getEndRes() + 1) - 1);
1540 sg.setSeqrep(refSeq);
1543 if (sg.getSize() > 0)
1549 void addRowProperties(AlignmentI al, StringTokenizer st)
1551 String label = st.nextToken(), keyValue, key, value;
1552 boolean scaletofit = false, centerlab = false, showalllabs = false;
1553 while (st.hasMoreTokens())
1555 keyValue = st.nextToken();
1556 key = keyValue.substring(0, keyValue.indexOf("="));
1557 value = keyValue.substring(keyValue.indexOf("=") + 1);
1558 if (key.equalsIgnoreCase("scaletofit"))
1560 scaletofit = Boolean.valueOf(value).booleanValue();
1562 if (key.equalsIgnoreCase("showalllabs"))
1564 showalllabs = Boolean.valueOf(value).booleanValue();
1566 if (key.equalsIgnoreCase("centrelabs"))
1568 centerlab = Boolean.valueOf(value).booleanValue();
1570 AlignmentAnnotation[] alr = al.getAlignmentAnnotation();
1573 for (int i = 0; i < alr.length; i++)
1575 if (alr[i].label.equalsIgnoreCase(label))
1577 alr[i].centreColLabels = centerlab;
1578 alr[i].scaleColLabel = scaletofit;
1579 alr[i].showAllColLabels = showalllabs;
1586 void addProperties(AlignmentI al, StringTokenizer st)
1589 // So far we have only added groups to the annotationHash,
1590 // the idea is in the future properties can be added to
1591 // alignments, other annotations etc
1592 if (al.getGroups() == null)
1597 String name = st.nextToken();
1598 SequenceGroup sg = null;
1599 for (SequenceGroup _sg : al.getGroups())
1601 if ((sg = _sg).getName().equals(name))
1613 String keyValue, key, value;
1614 ColourSchemeI def = sg.getColourScheme();
1615 while (st.hasMoreTokens())
1617 keyValue = st.nextToken();
1618 key = keyValue.substring(0, keyValue.indexOf("="));
1619 value = keyValue.substring(keyValue.indexOf("=") + 1);
1621 if (key.equalsIgnoreCase("description"))
1623 sg.setDescription(value);
1625 else if (key.equalsIgnoreCase("colour"))
1627 sg.cs.setColourScheme(ColourSchemeProperty
1628 .getColourScheme(al, value));
1630 else if (key.equalsIgnoreCase("pidThreshold"))
1632 sg.cs.setThreshold(Integer.parseInt(value), true);
1635 else if (key.equalsIgnoreCase("consThreshold"))
1637 sg.cs.setConservationInc(Integer.parseInt(value));
1638 Conservation c = new Conservation("Group", sg.getSequences(null),
1639 sg.getStartRes(), sg.getEndRes() + 1);
1642 c.verdict(false, 25); // TODO: refer to conservation percent threshold
1644 sg.cs.setConservation(c);
1647 else if (key.equalsIgnoreCase("outlineColour"))
1649 sg.setOutlineColour(ColorUtils.parseColourString(value));
1651 else if (key.equalsIgnoreCase("displayBoxes"))
1653 sg.setDisplayBoxes(Boolean.valueOf(value).booleanValue());
1655 else if (key.equalsIgnoreCase("showUnconserved"))
1657 sg.setShowNonconserved(Boolean.valueOf(value).booleanValue());
1659 else if (key.equalsIgnoreCase("displayText"))
1661 sg.setDisplayText(Boolean.valueOf(value).booleanValue());
1663 else if (key.equalsIgnoreCase("colourText"))
1665 sg.setColourText(Boolean.valueOf(value).booleanValue());
1667 else if (key.equalsIgnoreCase("textCol1"))
1669 sg.textColour = ColorUtils.parseColourString(value);
1671 else if (key.equalsIgnoreCase("textCol2"))
1673 sg.textColour2 = ColorUtils.parseColourString(value);
1675 else if (key.equalsIgnoreCase("textColThreshold"))
1677 sg.thresholdTextColour = Integer.parseInt(value);
1679 else if (key.equalsIgnoreCase("idColour"))
1681 Color idColour = ColorUtils.parseColourString(value);
1682 sg.setIdColour(idColour == null ? Color.black : idColour);
1684 else if (key.equalsIgnoreCase("hide"))
1686 // see bug https://mantis.lifesci.dundee.ac.uk/view.php?id=25847
1687 sg.setHidereps(true);
1689 else if (key.equalsIgnoreCase("hidecols"))
1691 // see bug https://mantis.lifesci.dundee.ac.uk/view.php?id=25847
1692 sg.setHideCols(true);
1694 sg.recalcConservation();
1696 if (sg.getColourScheme() == null)
1698 sg.setColourScheme(def);
1703 void setBelowAlignment(AlignmentI al, StringTokenizer st)
1706 AlignmentAnnotation aa, ala[] = al.getAlignmentAnnotation();
1710 .print("Warning - no annotation to set below for sequence associated annotation:");
1712 while (st.hasMoreTokens())
1714 token = st.nextToken();
1717 System.err.print(" " + token);
1721 for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1723 aa = al.getAlignmentAnnotation()[i];
1724 if (aa.sequenceRef == refSeq && aa.label.equals(token))
1726 aa.belowAlignment = true;
1733 System.err.print("\n");
1737 void addAlignmentDetails(AlignmentI al, StringTokenizer st)
1739 String keyValue, key, value;
1740 while (st.hasMoreTokens())
1742 keyValue = st.nextToken();
1743 key = keyValue.substring(0, keyValue.indexOf("="));
1744 value = keyValue.substring(keyValue.indexOf("=") + 1);
1745 al.setProperty(key, value);
1750 * Write annotations as a CSV file of the form 'label, value, value, ...' for
1753 * @param annotations
1754 * @return CSV file as a string.
1756 public String printCSVAnnotations(AlignmentAnnotation[] annotations)
1758 if (annotations == null)
1762 StringBuffer sp = new StringBuffer();
1763 for (int i = 0; i < annotations.length; i++)
1765 String atos = annotations[i].toString();
1769 int cp = atos.indexOf("\n", p);
1770 sp.append(annotations[i].label);
1774 sp.append(atos.substring(p, cp + 1));
1778 sp.append(atos.substring(p));
1784 return sp.toString();
1787 public String printAnnotationsForView(AlignViewportI viewport)
1789 return printAnnotations(viewport.isShowAnnotation() ? viewport
1790 .getAlignment().getAlignmentAnnotation() : null, viewport
1791 .getAlignment().getGroups(), viewport.getAlignment()
1792 .getProperties(), viewport.getColumnSelection(),
1793 viewport.getAlignment(), null);
1796 public String printAnnotationsForAlignment(AlignmentI al)
1798 return printAnnotations(al.getAlignmentAnnotation(), al.getGroups(),
1799 al.getProperties(), null, al, null);