2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
23 import jalview.analysis.Conservation;
24 import jalview.api.AlignViewportI;
25 import jalview.datamodel.AlignmentAnnotation;
26 import jalview.datamodel.AlignmentI;
27 import jalview.datamodel.Annotation;
28 import jalview.datamodel.ColumnSelection;
29 import jalview.datamodel.GraphLine;
30 import jalview.datamodel.HiddenColumns;
31 import jalview.datamodel.HiddenSequences;
32 import jalview.datamodel.SequenceGroup;
33 import jalview.datamodel.SequenceI;
34 import jalview.schemes.ColourSchemeI;
35 import jalview.schemes.ColourSchemeProperty;
36 import jalview.util.ColorUtils;
38 import java.awt.Color;
39 import java.io.BufferedReader;
40 import java.io.FileReader;
41 import java.io.InputStreamReader;
42 import java.io.StringReader;
44 import java.util.ArrayList;
45 import java.util.BitSet;
46 import java.util.Enumeration;
47 import java.util.Hashtable;
48 import java.util.List;
50 import java.util.StringTokenizer;
51 import java.util.Vector;
53 public class AnnotationFile
55 public AnnotationFile()
61 * character used to write newlines
63 protected String newline = System.getProperty("line.separator");
66 * set new line string and reset the output buffer
70 public void setNewlineString(String nl)
76 public String getNewlineString()
85 text = new StringBuffer("JALVIEW_ANNOTATION" + newline + "# Created: "
86 + new java.util.Date() + newline + newline);
92 * convenience method for pre-2.9 annotation files which have no view, hidden
93 * columns or hidden row keywords.
98 * @return annotation file as a string.
100 public String printAnnotations(AlignmentAnnotation[] annotations,
101 List<SequenceGroup> list, Hashtable properties)
103 return printAnnotations(annotations, list, properties, null, null, null);
108 * hold all the information about a particular view definition read from or
109 * written out in an annotations file.
113 // TODO this class is not used - remove?
114 public final String viewname;
116 public final HiddenSequences hidseqs;
118 public final HiddenColumns hiddencols;
120 public final Hashtable hiddenRepSeqs;
122 public ViewDef(String vname, HiddenSequences hseqs,
123 HiddenColumns hcols, Hashtable hRepSeqs)
125 this.viewname = vname;
126 this.hidseqs = hseqs;
127 this.hiddencols = hcols;
128 this.hiddenRepSeqs = hRepSeqs;
133 * Prepare an annotation file given a set of annotations, groups, alignment
134 * properties and views.
140 * @return annotation file
142 public String printAnnotations(AlignmentAnnotation[] annotations,
143 List<SequenceGroup> list, Hashtable properties,
145 AlignmentI al, ViewDef view)
149 if (view.viewname != null)
151 text.append("VIEW_DEF\t" + view.viewname + "\n");
155 // list = view.visibleGroups;
159 cs = view.hiddencols;
163 // add hidden rep sequences.
166 // first target - store and restore all settings for a view.
167 if (al != null && al.hasSeqrep())
169 text.append("VIEW_SETREF\t" + al.getSeqrep().getName() + "\n");
171 if (cs != null && cs.hasHiddenColumns())
173 text.append("VIEW_HIDECOLS\t");
174 List<int[]> hc = cs.getHiddenRegions();
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();
669 HiddenColumns hidden = viewport.getAlignment().getHiddenColumns();
672 colSel = new ColumnSelection();
676 hidden = new HiddenColumns();
678 boolean rslt = readAnnotationFile(viewport.getAlignment(), hidden,
680 if (rslt && (colSel.hasSelectedColumns() || hidden.hasHiddenColumns()))
682 viewport.setColumnSelection(colSel);
683 viewport.getAlignment().setHiddenColumns(hidden);
689 public boolean readAnnotationFile(AlignmentI al, String file,
690 DataSourceType sourceType)
692 return readAnnotationFile(al, null, file, sourceType);
695 public boolean readAnnotationFile(AlignmentI al, HiddenColumns hidden,
696 String file, DataSourceType sourceType)
698 BufferedReader in = null;
701 if (sourceType == DataSourceType.FILE)
703 in = new BufferedReader(new FileReader(file));
705 else if (sourceType == DataSourceType.URL)
707 URL url = new URL(file);
708 in = new BufferedReader(new InputStreamReader(url.openStream()));
710 else if (sourceType == DataSourceType.PASTE)
712 in = new BufferedReader(new StringReader(file));
714 else if (sourceType == DataSourceType.CLASSLOADER)
716 java.io.InputStream is = getClass().getResourceAsStream("/" + file);
719 in = new BufferedReader(new java.io.InputStreamReader(is));
724 return parseAnnotationFrom(al, hidden, in);
727 } catch (Exception ex)
729 ex.printStackTrace();
730 System.out.println("Problem reading annotation file: " + ex);
733 System.out.println("Last read line " + nlinesread + ": '"
734 + lastread + "' (first 80 chars) ...");
743 String lastread = "";
745 private static String GRAPHLINE = "GRAPHLINE", COMBINE = "COMBINE";
747 public boolean parseAnnotationFrom(AlignmentI al, HiddenColumns hidden,
748 BufferedReader in) throws Exception
751 ArrayList<Object[]> combineAnnotation_calls = new ArrayList<Object[]>();
752 ArrayList<Object[]> deferredAnnotation_calls = new ArrayList<Object[]>();
753 boolean modified = false;
754 String groupRef = null;
755 Hashtable groupRefRows = new Hashtable();
757 Hashtable autoAnnots = new Hashtable();
759 String line, label, description, token;
760 int graphStyle, index;
762 int existingAnnotations = 0;
763 // when true - will add new rows regardless of whether they are duplicate
764 // auto-annotation like consensus or conservation graphs
765 boolean overrideAutoAnnot = false;
766 if (al.getAlignmentAnnotation() != null)
768 existingAnnotations = al.getAlignmentAnnotation().length;
769 if (existingAnnotations > 0)
771 AlignmentAnnotation[] aa = al.getAlignmentAnnotation();
772 for (int aai = 0; aai < aa.length; aai++)
774 if (aa[aai].autoCalculated)
776 // make a note of the name and description
778 autoAnnotsKey(aa[aai], aa[aai].sequenceRef,
779 (aa[aai].groupRef == null ? null
780 : aa[aai].groupRef.getName())),
787 int alWidth = al.getWidth();
790 Annotation[] annotations;
791 AlignmentAnnotation annotation = null;
793 // First confirm this is an Annotation file
794 boolean jvAnnotationFile = false;
795 while ((line = in.readLine()) != null)
798 lastread = new String(line);
799 if (line.indexOf("#") == 0)
804 if (line.indexOf("JALVIEW_ANNOTATION") > -1)
806 jvAnnotationFile = true;
811 if (!jvAnnotationFile)
817 while ((line = in.readLine()) != null)
820 lastread = new String(line);
821 if (line.indexOf("#") == 0
822 || line.indexOf("JALVIEW_ANNOTATION") > -1
823 || line.length() == 0)
828 st = new StringTokenizer(line, "\t");
829 token = st.nextToken();
830 if (token.equalsIgnoreCase("COLOUR"))
832 // TODO: use graduated colour def'n here too
833 colourAnnotations(al, st.nextToken(), st.nextToken());
838 else if (token.equalsIgnoreCase(COMBINE))
840 // keep a record of current state and resolve groupRef at end
841 combineAnnotation_calls
842 .add(new Object[] { st, refSeq, groupRef });
846 else if (token.equalsIgnoreCase("ROWPROPERTIES"))
848 addRowProperties(al, st);
852 else if (token.equalsIgnoreCase(GRAPHLINE))
855 deferredAnnotation_calls.add(new Object[] { GRAPHLINE, st,
861 else if (token.equalsIgnoreCase("SEQUENCE_REF"))
863 if (st.hasMoreTokens())
865 refSeq = al.findName(refSeqId = st.nextToken());
872 refSeqIndex = Integer.parseInt(st.nextToken());
877 .println("WARNING: SEQUENCE_REF index must be > 0 in AnnotationFile");
879 } catch (Exception ex)
891 else if (token.equalsIgnoreCase("GROUP_REF"))
893 // Group references could be forward or backwards, so they are
894 // resolved after the whole file is read in
896 if (st.hasMoreTokens())
898 groupRef = st.nextToken();
899 if (groupRef.length() < 1)
901 groupRef = null; // empty string
905 if (groupRefRows.get(groupRef) == null)
907 groupRefRows.put(groupRef, new Vector());
913 else if (token.equalsIgnoreCase("SEQUENCE_GROUP"))
920 else if (token.equalsIgnoreCase("PROPERTIES"))
922 addProperties(al, st);
927 else if (token.equalsIgnoreCase("BELOW_ALIGNMENT"))
929 setBelowAlignment(al, st);
933 else if (token.equalsIgnoreCase("ALIGNMENT"))
935 addAlignmentDetails(al, st);
939 // else if (token.equalsIgnoreCase("VIEW_DEF"))
941 // addOrSetView(al,st);
945 else if (token.equalsIgnoreCase("VIEW_SETREF"))
949 al.setSeqrep(refSeq);
954 else if (token.equalsIgnoreCase("VIEW_HIDECOLS"))
956 if (st.hasMoreTokens())
960 hidden = new HiddenColumns();
962 parseHideCols(hidden, st.nextToken());
967 else if (token.equalsIgnoreCase("HIDE_INSERTIONS"))
969 SequenceI sr = refSeq == null ? al.getSeqrep() : refSeq;
972 sr = al.getSequenceAt(0);
979 .println("Cannot process HIDE_INSERTIONS without an alignment view: Ignoring line: "
984 // consider deferring this till after the file has been parsed ?
985 hidden.hideInsertionsFor(sr);
992 // Parse out the annotation row
993 graphStyle = AlignmentAnnotation.getGraphValueFromString(token);
994 label = st.nextToken();
997 annotations = new Annotation[alWidth];
999 float score = Float.NaN;
1001 if (st.hasMoreTokens())
1003 line = st.nextToken();
1005 if (line.indexOf("|") == -1)
1008 if (st.hasMoreTokens())
1010 line = st.nextToken();
1014 if (st.hasMoreTokens())
1016 // This must be the score
1017 score = Float.valueOf(st.nextToken()).floatValue();
1020 st = new StringTokenizer(line, "|", true);
1022 boolean emptyColumn = true;
1023 boolean onlyOneElement = (st.countTokens() == 1);
1025 while (st.hasMoreElements() && index < alWidth)
1027 token = st.nextToken().trim();
1033 score = Float.valueOf(token).floatValue();
1035 } catch (NumberFormatException ex)
1040 if (token.equals("|"))
1051 annotations[index++] = parseAnnotation(token, graphStyle);
1052 emptyColumn = false;
1058 annotation = new AlignmentAnnotation(label, description,
1059 (index == 0) ? null : annotations, 0, 0, graphStyle);
1061 annotation.score = score;
1062 if (!overrideAutoAnnot
1063 && autoAnnots.containsKey(autoAnnotsKey(annotation, refSeq,
1066 // skip - we've already got an automatic annotation of this type.
1069 // otherwise add it!
1073 annotation.belowAlignment = false;
1074 // make a copy of refSeq so we can find other matches in the alignment
1075 SequenceI referedSeq = refSeq;
1078 // copy before we do any mapping business.
1079 // TODO: verify that undo/redo with 1:many sequence associated
1080 // annotations can be undone correctly
1081 AlignmentAnnotation ann = new AlignmentAnnotation(annotation);
1083 .createSequenceMapping(referedSeq, refSeqIndex, false);
1084 annotation.adjustForAlignment();
1085 referedSeq.addAlignmentAnnotation(annotation);
1086 al.addAnnotation(annotation);
1087 al.setAnnotationIndex(annotation,
1088 al.getAlignmentAnnotation().length
1089 - existingAnnotations - 1);
1090 if (groupRef != null)
1092 ((Vector) groupRefRows.get(groupRef)).addElement(annotation);
1094 // and recover our virgin copy to use again if necessary.
1097 } while (refSeqId != null
1098 && (referedSeq = al.findName(referedSeq, refSeqId, true)) != null);
1102 al.addAnnotation(annotation);
1103 al.setAnnotationIndex(annotation,
1104 al.getAlignmentAnnotation().length - existingAnnotations
1106 if (groupRef != null)
1108 ((Vector) groupRefRows.get(groupRef)).addElement(annotation);
1111 // and set modification flag
1114 // Resolve the groupRefs
1115 Hashtable<String, SequenceGroup> groupRefLookup = new Hashtable<String, SequenceGroup>();
1116 Enumeration en = groupRefRows.keys();
1118 while (en.hasMoreElements())
1120 groupRef = (String) en.nextElement();
1121 boolean matched = false;
1122 // Resolve group: TODO: add a getGroupByName method to alignments
1123 for (SequenceGroup theGroup : al.getGroups())
1125 if (theGroup.getName().equals(groupRef))
1129 // TODO: specify and implement duplication of alignment annotation
1130 // for multiple group references.
1132 .println("Ignoring 1:many group reference mappings for group name '"
1138 Vector rowset = (Vector) groupRefRows.get(groupRef);
1139 groupRefLookup.put(groupRef, theGroup);
1140 if (rowset != null && rowset.size() > 0)
1142 AlignmentAnnotation alan = null;
1143 for (int elm = 0, elmSize = rowset.size(); elm < elmSize; elm++)
1145 alan = (AlignmentAnnotation) rowset.elementAt(elm);
1146 alan.groupRef = theGroup;
1152 ((Vector) groupRefRows.get(groupRef)).removeAllElements();
1154 // process any deferred attribute settings for each context
1155 for (Object[] _deferred_args : deferredAnnotation_calls)
1157 if (_deferred_args[0] == GRAPHLINE)
1160 (StringTokenizer) _deferred_args[1], // st
1161 (SequenceI) _deferred_args[2], // refSeq
1162 (_deferred_args[3] == null) ? null : groupRefLookup
1163 .get(_deferred_args[3]) // the reference
1169 // finally, combine all the annotation rows within each context.
1171 * number of combine statements in this annotation file. Used to create
1172 * new groups for combined annotation graphs without disturbing existing
1175 int combinecount = 0;
1176 for (Object[] _combine_args : combineAnnotation_calls)
1178 combineAnnotations(al,
1180 (StringTokenizer) _combine_args[0], // st
1181 (SequenceI) _combine_args[1], // refSeq
1182 (_combine_args[2] == null) ? null : groupRefLookup
1183 .get(_combine_args[2]) // the reference group,
1191 private void parseHideCols(HiddenColumns hidden, String nextToken)
1193 StringTokenizer inval = new StringTokenizer(nextToken, ",");
1194 while (inval.hasMoreTokens())
1196 String range = inval.nextToken().trim();
1197 int from, to = range.indexOf("-");
1200 from = to = Integer.parseInt(range);
1203 hidden.hideColumns(from, to);
1208 from = Integer.parseInt(range.substring(0, to));
1209 if (to < range.length() - 1)
1211 to = Integer.parseInt(range.substring(to + 1));
1217 if (from > 0 && to >= from)
1219 hidden.hideColumns(from, to);
1225 private Object autoAnnotsKey(AlignmentAnnotation annotation,
1226 SequenceI refSeq, String groupRef)
1228 return annotation.graph + "\t" + annotation.label + "\t"
1229 + annotation.description + "\t"
1230 + (refSeq != null ? refSeq.getDisplayId(true) : "");
1233 Annotation parseAnnotation(String string, int graphStyle)
1235 // don't do the glyph test if we don't want secondary structure
1236 boolean hasSymbols = (graphStyle == AlignmentAnnotation.NO_GRAPH);
1237 String desc = null, displayChar = null;
1238 char ss = ' '; // secondaryStructure
1240 boolean parsedValue = false, dcset = false;
1243 Color colour = null;
1244 int i = string.indexOf("[");
1245 int j = string.indexOf("]");
1246 if (i > -1 && j > -1)
1248 colour = ColorUtils.parseColourString(string.substring(i + 1,
1250 if (i > 0 && string.charAt(i - 1) == ',')
1252 // clip the preceding comma as well
1255 string = string.substring(0, i) + string.substring(j + 1);
1258 StringTokenizer st = new StringTokenizer(string, ",", true);
1260 boolean seenContent = false;
1262 while (st.hasMoreTokens())
1265 token = st.nextToken().trim();
1266 if (token.equals(","))
1268 if (!seenContent && parsedValue && !dcset)
1270 // allow the value below the bar/line to be empty
1274 seenContent = false;
1286 displayChar = token;
1288 value = new Float(token).floatValue();
1291 } catch (NumberFormatException ex)
1297 if (token.length() == 1)
1299 displayChar = token;
1303 && (token.length() == 1 && "()<>[]{}AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz"
1306 // Either this character represents a helix or sheet
1307 // or an integer which can be displayed
1308 ss = token.charAt(0);
1309 if (displayChar.equals(token.substring(0, 1)))
1314 else if (desc == null || (parsedValue && pass > 2))
1320 // if (!dcset && string.charAt(string.length() - 1) == ',')
1322 // displayChar = " "; // empty display char symbol.
1324 if (displayChar != null && desc != null && desc.length() == 1)
1326 if (displayChar.length() > 1)
1328 // switch desc and displayChar - legacy support
1329 String tmp = displayChar;
1335 if (displayChar.equals(desc))
1337 // duplicate label - hangover from the 'robust parser' above
1342 Annotation anot = new Annotation(displayChar, desc, ss, value);
1344 anot.colour = colour;
1349 void colourAnnotations(AlignmentI al, String label, String colour)
1351 Color awtColour = ColorUtils.parseColourString(colour);
1352 Annotation[] annotations;
1353 for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1355 if (al.getAlignmentAnnotation()[i].label.equalsIgnoreCase(label))
1357 annotations = al.getAlignmentAnnotation()[i].annotations;
1358 for (int j = 0; j < annotations.length; j++)
1360 if (annotations[j] != null)
1362 annotations[j].colour = awtColour;
1369 void combineAnnotations(AlignmentI al, int combineCount,
1370 StringTokenizer st, SequenceI seqRef, SequenceGroup groupRef)
1372 String group = st.nextToken();
1373 // First make sure we are not overwriting the graphIndex
1375 if (al.getAlignmentAnnotation() != null)
1377 for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1379 AlignmentAnnotation aa = al.getAlignmentAnnotation()[i];
1381 if (aa.graphGroup > graphGroup)
1383 // try to number graphGroups in order of occurence.
1384 graphGroup = aa.graphGroup + 1;
1386 if (aa.sequenceRef == seqRef && aa.groupRef == groupRef
1387 && aa.label.equalsIgnoreCase(group))
1389 if (aa.graphGroup > -1)
1391 graphGroup = aa.graphGroup;
1395 if (graphGroup <= combineCount)
1397 graphGroup = combineCount + 1;
1399 aa.graphGroup = graphGroup;
1405 // Now update groups
1406 while (st.hasMoreTokens())
1408 group = st.nextToken();
1409 for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1411 AlignmentAnnotation aa = al.getAlignmentAnnotation()[i];
1412 if (aa.sequenceRef == seqRef && aa.groupRef == groupRef
1413 && aa.label.equalsIgnoreCase(group))
1415 aa.graphGroup = graphGroup;
1424 .println("Couldn't combine annotations. None are added to alignment yet!");
1428 void addLine(AlignmentI al, StringTokenizer st, SequenceI seqRef,
1429 SequenceGroup groupRef)
1431 String group = st.nextToken();
1432 AlignmentAnnotation[] alannot = al.getAlignmentAnnotation();
1433 String nextToken = st.nextToken();
1437 value = Float.valueOf(nextToken);
1438 } catch (NumberFormatException e)
1440 System.err.println("line " + nlinesread + ": Threshold '" + nextToken
1441 + "' invalid, setting to zero");
1443 String label = st.hasMoreTokens() ? st.nextToken() : null;
1444 Color colour = null;
1445 if (st.hasMoreTokens())
1447 colour = ColorUtils.parseColourString(st.nextToken());
1449 if (alannot != null)
1451 for (int i = 0; i < alannot.length; i++)
1453 if (alannot[i].label.equalsIgnoreCase(group)
1454 && (seqRef == null || alannot[i].sequenceRef == seqRef)
1455 && (groupRef == null || alannot[i].groupRef == groupRef))
1457 alannot[i].setThreshold(new GraphLine(value, label, colour));
1463 void addGroup(AlignmentI al, StringTokenizer st)
1465 SequenceGroup sg = new SequenceGroup();
1466 sg.setName(st.nextToken());
1470 rng = st.nextToken();
1471 if (rng.length() > 0 && !rng.startsWith("*"))
1473 sg.setStartRes(Integer.parseInt(rng) - 1);
1479 rng = st.nextToken();
1480 if (rng.length() > 0 && !rng.startsWith("*"))
1482 sg.setEndRes(Integer.parseInt(rng) - 1);
1486 sg.setEndRes(al.getWidth() - 1);
1488 } catch (Exception e)
1491 .println("Couldn't parse Group Start or End Field as '*' or a valid column or sequence index: '"
1492 + rng + "' - assuming alignment width for group.");
1493 // assume group is full width
1495 sg.setEndRes(al.getWidth() - 1);
1498 String index = st.nextToken();
1499 if (index.equals("-1"))
1501 while (st.hasMoreElements())
1503 sg.addSequence(al.findName(st.nextToken()), false);
1508 StringTokenizer st2 = new StringTokenizer(index, ",");
1510 while (st2.hasMoreTokens())
1512 String tmp = st2.nextToken();
1513 if (tmp.equals("*"))
1515 for (int i = 0; i < al.getHeight(); i++)
1517 sg.addSequence(al.getSequenceAt(i), false);
1520 else if (tmp.indexOf("-") >= 0)
1522 StringTokenizer st3 = new StringTokenizer(tmp, "-");
1524 int start = (Integer.parseInt(st3.nextToken()));
1525 int end = (Integer.parseInt(st3.nextToken()));
1529 for (int i = start; i <= end; i++)
1531 sg.addSequence(al.getSequenceAt(i - 1), false);
1537 sg.addSequence(al.getSequenceAt(Integer.parseInt(tmp) - 1), false);
1544 sg.setStartRes(refSeq.findIndex(sg.getStartRes() + 1) - 1);
1545 sg.setEndRes(refSeq.findIndex(sg.getEndRes() + 1) - 1);
1546 sg.setSeqrep(refSeq);
1549 if (sg.getSize() > 0)
1555 void addRowProperties(AlignmentI al, StringTokenizer st)
1557 String label = st.nextToken(), keyValue, key, value;
1558 boolean scaletofit = false, centerlab = false, showalllabs = false;
1559 while (st.hasMoreTokens())
1561 keyValue = st.nextToken();
1562 key = keyValue.substring(0, keyValue.indexOf("="));
1563 value = keyValue.substring(keyValue.indexOf("=") + 1);
1564 if (key.equalsIgnoreCase("scaletofit"))
1566 scaletofit = Boolean.valueOf(value).booleanValue();
1568 if (key.equalsIgnoreCase("showalllabs"))
1570 showalllabs = Boolean.valueOf(value).booleanValue();
1572 if (key.equalsIgnoreCase("centrelabs"))
1574 centerlab = Boolean.valueOf(value).booleanValue();
1576 AlignmentAnnotation[] alr = al.getAlignmentAnnotation();
1579 for (int i = 0; i < alr.length; i++)
1581 if (alr[i].label.equalsIgnoreCase(label))
1583 alr[i].centreColLabels = centerlab;
1584 alr[i].scaleColLabel = scaletofit;
1585 alr[i].showAllColLabels = showalllabs;
1592 void addProperties(AlignmentI al, StringTokenizer st)
1595 // So far we have only added groups to the annotationHash,
1596 // the idea is in the future properties can be added to
1597 // alignments, other annotations etc
1598 if (al.getGroups() == null)
1603 String name = st.nextToken();
1604 SequenceGroup sg = null;
1605 for (SequenceGroup _sg : al.getGroups())
1607 if ((sg = _sg).getName().equals(name))
1619 String keyValue, key, value;
1620 ColourSchemeI def = sg.getColourScheme();
1621 while (st.hasMoreTokens())
1623 keyValue = st.nextToken();
1624 key = keyValue.substring(0, keyValue.indexOf("="));
1625 value = keyValue.substring(keyValue.indexOf("=") + 1);
1627 if (key.equalsIgnoreCase("description"))
1629 sg.setDescription(value);
1631 else if (key.equalsIgnoreCase("colour"))
1633 sg.cs.setColourScheme(ColourSchemeProperty
1634 .getColourScheme(al, value));
1636 else if (key.equalsIgnoreCase("pidThreshold"))
1638 sg.cs.setThreshold(Integer.parseInt(value), true);
1641 else if (key.equalsIgnoreCase("consThreshold"))
1643 sg.cs.setConservationInc(Integer.parseInt(value));
1644 Conservation c = new Conservation("Group", sg.getSequences(null),
1645 sg.getStartRes(), sg.getEndRes() + 1);
1648 c.verdict(false, 25); // TODO: refer to conservation percent threshold
1650 sg.cs.setConservation(c);
1653 else if (key.equalsIgnoreCase("outlineColour"))
1655 sg.setOutlineColour(ColorUtils.parseColourString(value));
1657 else if (key.equalsIgnoreCase("displayBoxes"))
1659 sg.setDisplayBoxes(Boolean.valueOf(value).booleanValue());
1661 else if (key.equalsIgnoreCase("showUnconserved"))
1663 sg.setShowNonconserved(Boolean.valueOf(value).booleanValue());
1665 else if (key.equalsIgnoreCase("displayText"))
1667 sg.setDisplayText(Boolean.valueOf(value).booleanValue());
1669 else if (key.equalsIgnoreCase("colourText"))
1671 sg.setColourText(Boolean.valueOf(value).booleanValue());
1673 else if (key.equalsIgnoreCase("textCol1"))
1675 sg.textColour = ColorUtils.parseColourString(value);
1677 else if (key.equalsIgnoreCase("textCol2"))
1679 sg.textColour2 = ColorUtils.parseColourString(value);
1681 else if (key.equalsIgnoreCase("textColThreshold"))
1683 sg.thresholdTextColour = Integer.parseInt(value);
1685 else if (key.equalsIgnoreCase("idColour"))
1687 Color idColour = ColorUtils.parseColourString(value);
1688 sg.setIdColour(idColour == null ? Color.black : idColour);
1690 else if (key.equalsIgnoreCase("hide"))
1692 // see bug https://mantis.lifesci.dundee.ac.uk/view.php?id=25847
1693 sg.setHidereps(true);
1695 else if (key.equalsIgnoreCase("hidecols"))
1697 // see bug https://mantis.lifesci.dundee.ac.uk/view.php?id=25847
1698 sg.setHideCols(true);
1700 sg.recalcConservation();
1702 if (sg.getColourScheme() == null)
1704 sg.setColourScheme(def);
1709 void setBelowAlignment(AlignmentI al, StringTokenizer st)
1712 AlignmentAnnotation aa, ala[] = al.getAlignmentAnnotation();
1716 .print("Warning - no annotation to set below for sequence associated annotation:");
1718 while (st.hasMoreTokens())
1720 token = st.nextToken();
1723 System.err.print(" " + token);
1727 for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1729 aa = al.getAlignmentAnnotation()[i];
1730 if (aa.sequenceRef == refSeq && aa.label.equals(token))
1732 aa.belowAlignment = true;
1739 System.err.print("\n");
1743 void addAlignmentDetails(AlignmentI al, StringTokenizer st)
1745 String keyValue, key, value;
1746 while (st.hasMoreTokens())
1748 keyValue = st.nextToken();
1749 key = keyValue.substring(0, keyValue.indexOf("="));
1750 value = keyValue.substring(keyValue.indexOf("=") + 1);
1751 al.setProperty(key, value);
1756 * Write annotations as a CSV file of the form 'label, value, value, ...' for
1759 * @param annotations
1760 * @return CSV file as a string.
1762 public String printCSVAnnotations(AlignmentAnnotation[] annotations)
1764 if (annotations == null)
1768 StringBuffer sp = new StringBuffer();
1769 for (int i = 0; i < annotations.length; i++)
1771 String atos = annotations[i].toString();
1775 int cp = atos.indexOf("\n", p);
1776 sp.append(annotations[i].label);
1780 sp.append(atos.substring(p, cp + 1));
1784 sp.append(atos.substring(p));
1790 return sp.toString();
1793 public String printAnnotationsForView(AlignViewportI viewport)
1795 return printAnnotations(viewport.isShowAnnotation() ? viewport
1796 .getAlignment().getAlignmentAnnotation() : null, viewport
1797 .getAlignment().getGroups(), viewport.getAlignment()
1798 .getProperties(), viewport.getAlignment().getHiddenColumns(),
1799 viewport.getAlignment(), null);
1802 public String printAnnotationsForAlignment(AlignmentI al)
1804 return printAnnotations(al.getAlignmentAnnotation(), al.getGroups(),
1805 al.getProperties(), null, al, null);