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.ResidueProperties;
36 import jalview.schemes.UserColourScheme;
37 import jalview.util.Comparison;
38 import jalview.util.Format;
40 import java.io.BufferedReader;
41 import java.io.FileReader;
42 import java.io.InputStreamReader;
43 import java.io.StringReader;
45 import java.util.ArrayList;
46 import java.util.BitSet;
47 import java.util.Enumeration;
48 import java.util.Hashtable;
49 import java.util.List;
51 import java.util.StringTokenizer;
52 import java.util.Vector;
54 public class AnnotationFile
56 public AnnotationFile()
62 * character used to write newlines
64 protected String newline = System.getProperty("line.separator");
67 * set new line string and reset the output buffer
71 public void setNewlineString(String nl)
77 public String getNewlineString()
86 text = new StringBuffer("JALVIEW_ANNOTATION" + newline + "# Created: "
87 + new java.util.Date() + newline + newline);
93 * convenience method for pre-2.8.3 annotation files which have no view,
94 * hidden columns or hidden row keywords.
99 * @return annotation file as a string.
101 public String printAnnotations(AlignmentAnnotation[] annotations,
102 List<SequenceGroup> list, Hashtable properties)
104 return printAnnotations(annotations, list, properties, null, null, null);
109 * hold all the information about a particular view definition read from or
110 * written out in an annotations file.
114 public String viewname;
116 public HiddenSequences hidseqs;
118 public ColumnSelection hiddencols;
120 public Vector visibleGroups;
122 public Hashtable hiddenRepSeqs;
124 public ViewDef(String viewname, HiddenSequences hidseqs,
125 ColumnSelection hiddencols, Hashtable hiddenRepSeqs)
127 this.viewname = viewname;
128 this.hidseqs = hidseqs;
129 this.hiddencols = hiddencols;
130 this.hiddenRepSeqs = hiddenRepSeqs;
135 * Prepare an annotation file given a set of annotations, groups, alignment
136 * properties and views.
142 * @return annotation file
144 public String printAnnotations(AlignmentAnnotation[] annotations,
145 List<SequenceGroup> list, Hashtable properties,
146 ColumnSelection cs, AlignmentI al, ViewDef view)
150 if (view.viewname != null)
152 text.append("VIEW_DEF\t" + view.viewname + "\n");
156 list = view.visibleGroups;
160 cs = view.hiddencols;
164 // add hidden rep sequences.
167 // first target - store and restore all settings for a view.
168 if (al != null && al.hasSeqrep())
170 text.append("VIEW_SETREF\t" + al.getSeqrep().getName() + "\n");
172 if (cs != null && cs.hasHiddenColumns())
174 text.append("VIEW_HIDECOLS\t");
175 List<int[]> hc = cs.getHiddenColumns();
176 boolean comma = false;
193 // TODO: allow efficient recovery of annotation data shown in several
195 if (annotations != null)
197 boolean oneColour = true;
198 AlignmentAnnotation row;
200 SequenceI refSeq = null;
201 SequenceGroup refGroup = null;
203 StringBuffer colours = new StringBuffer();
204 StringBuffer graphLine = new StringBuffer();
205 StringBuffer rowprops = new StringBuffer();
206 Hashtable<Integer, String> graphGroup = new Hashtable<Integer, String>();
207 Hashtable<Integer, Object[]> graphGroup_refs = new Hashtable<Integer, Object[]>();
208 BitSet graphGroupSeen = new BitSet();
210 java.awt.Color color;
212 for (int i = 0; i < annotations.length; i++)
214 row = annotations[i];
218 && !(row.graphGroup > -1 && graphGroupSeen
219 .get(row.graphGroup)))
227 // mark any sequence references for the row
228 writeSequence_Ref(refSeq, row.sequenceRef);
229 refSeq = row.sequenceRef;
230 // mark any group references for the row
231 writeGroup_Ref(refGroup, row.groupRef);
232 refGroup = row.groupRef;
234 boolean hasGlyphs = row.hasIcons, hasLabels = row.hasText, hasValues = row.hasScore, hasText = false;
235 // lookahead to check what the annotation row object actually contains.
236 for (int j = 0; row.annotations != null
237 && j < row.annotations.length
238 && (!hasGlyphs || !hasLabels || !hasValues); j++)
240 if (row.annotations[j] != null)
242 hasLabels |= (row.annotations[j].displayCharacter != null
243 && row.annotations[j].displayCharacter.length() > 0 && !row.annotations[j].displayCharacter
245 hasGlyphs |= (row.annotations[j].secondaryStructure != 0 && row.annotations[j].secondaryStructure != ' ');
246 hasValues |= (row.annotations[j].value != Float.NaN); // NaNs can't
249 hasText |= (row.annotations[j].description != null && row.annotations[j].description
254 if (row.graph == AlignmentAnnotation.NO_GRAPH)
256 text.append("NO_GRAPH\t");
257 hasValues = false; // only secondary structure
258 // hasLabels = false; // and annotation description string.
262 if (row.graph == AlignmentAnnotation.BAR_GRAPH)
264 text.append("BAR_GRAPH\t");
265 hasGlyphs = false; // no secondary structure
268 else if (row.graph == AlignmentAnnotation.LINE_GRAPH)
270 hasGlyphs = false; // no secondary structure
271 text.append("LINE_GRAPH\t");
274 if (row.getThreshold() != null)
276 graphLine.append("GRAPHLINE\t");
277 graphLine.append(row.label);
278 graphLine.append("\t");
279 graphLine.append(row.getThreshold().value);
280 graphLine.append("\t");
281 graphLine.append(row.getThreshold().label);
282 graphLine.append("\t");
284 .append(Format.getHexString(row.getThreshold().colour));
285 graphLine.append(newline);
288 if (row.graphGroup > -1)
290 graphGroupSeen.set(row.graphGroup);
291 Integer key = new Integer(row.graphGroup);
292 if (graphGroup.containsKey(key))
294 graphGroup.put(key, graphGroup.get(key) + "\t" + row.label);
299 graphGroup_refs.put(key, new Object[]
300 { refSeq, refGroup });
301 graphGroup.put(key, row.label);
306 text.append(row.label + "\t");
307 if (row.description != null)
309 text.append(row.description + "\t");
311 for (int j = 0; row.annotations != null
312 && j < row.annotations.length; j++)
315 && Comparison.isGap(refSeq.getCharAt(j)))
320 if (row.annotations[j] != null)
323 if (hasGlyphs) // could be also hasGlyphs || ...
327 if (row.annotations[j].secondaryStructure != ' ')
329 // only write out the field if its not whitespace.
330 text.append(row.annotations[j].secondaryStructure);
336 if (row.annotations[j].value != Float.NaN)
338 text.append(comma + row.annotations[j].value);
342 System.err.println("Skipping NaN - not valid value.");
343 text.append(comma + 0f);// row.annotations[j].value);
349 // TODO: labels are emitted after values for bar graphs.
350 if // empty labels are allowed, so
351 (row.annotations[j].displayCharacter != null
352 && row.annotations[j].displayCharacter.length() > 0
353 && !row.annotations[j].displayCharacter.equals(" "))
355 text.append(comma + row.annotations[j].displayCharacter);
361 if (row.annotations[j].description != null
362 && row.annotations[j].description.length() > 0
363 && !row.annotations[j].description
364 .equals(row.annotations[j].displayCharacter))
366 text.append(comma + row.annotations[j].description);
370 if (color != null && !color.equals(row.annotations[j].colour))
375 color = row.annotations[j].colour;
377 if (row.annotations[j].colour != null
378 && row.annotations[j].colour != java.awt.Color.black)
383 .getHexString(row.annotations[j].colour)
393 text.append("\t" + row.score);
396 text.append(newline);
398 if (color != null && color != java.awt.Color.black && oneColour)
400 colours.append("COLOUR\t");
401 colours.append(row.label);
402 colours.append("\t");
403 colours.append(Format.getHexString(color));
404 colours.append(newline);
406 if (row.scaleColLabel || row.showAllColLabels
407 || row.centreColLabels)
409 rowprops.append("ROWPROPERTIES\t");
410 rowprops.append(row.label);
411 rowprops.append("\tscaletofit=");
412 rowprops.append(row.scaleColLabel);
413 rowprops.append("\tshowalllabs=");
414 rowprops.append(row.showAllColLabels);
415 rowprops.append("\tcentrelabs=");
416 rowprops.append(row.centreColLabels);
417 rowprops.append(newline);
419 if (graphLine.length() > 0)
421 text.append(graphLine.toString());
422 graphLine.setLength(0);
426 text.append(newline);
428 text.append(colours.toString());
429 if (graphGroup.size() > 0)
431 SequenceI oldRefSeq = refSeq;
432 SequenceGroup oldRefGroup = refGroup;
433 for (Map.Entry<Integer, String> combine_statement : graphGroup
436 Object[] seqRefAndGroup = graphGroup_refs.get(combine_statement
439 writeSequence_Ref(refSeq, (SequenceI) seqRefAndGroup[0]);
440 refSeq = (SequenceI) seqRefAndGroup[0];
442 writeGroup_Ref(refGroup, (SequenceGroup) seqRefAndGroup[1]);
443 refGroup = (SequenceGroup) seqRefAndGroup[1];
444 text.append("COMBINE\t");
445 text.append(combine_statement.getValue());
446 text.append(newline);
448 writeSequence_Ref(refSeq, oldRefSeq);
451 writeGroup_Ref(refGroup, oldRefGroup);
452 refGroup = oldRefGroup;
454 text.append(rowprops.toString());
462 if (properties != null)
464 text.append(newline);
465 text.append(newline);
466 text.append("ALIGNMENT");
467 Enumeration en = properties.keys();
468 while (en.hasMoreElements())
470 String key = en.nextElement().toString();
474 text.append(properties.get(key));
476 // TODO: output alignment visualization settings here if required
477 // iterate through one or more views, defining, marking columns and rows as visible/hidden, and emmitting view properties.
478 // View specific annotation is
481 return text.toString();
484 private Object writeGroup_Ref(SequenceGroup refGroup,
485 SequenceGroup next_refGroup)
487 if (next_refGroup == null)
490 if (refGroup != null)
492 text.append(newline);
493 text.append("GROUP_REF\t");
494 text.append("ALIGNMENT");
495 text.append(newline);
501 if (refGroup == null || refGroup != next_refGroup)
503 text.append(newline);
504 text.append("GROUP_REF\t");
505 text.append(next_refGroup.getName());
506 text.append(newline);
513 private boolean writeSequence_Ref(SequenceI refSeq, SequenceI next_refSeq)
516 if (next_refSeq == null)
520 text.append(newline);
521 text.append("SEQUENCE_REF\t");
522 text.append("ALIGNMENT");
523 text.append(newline);
529 if (refSeq == null || refSeq != next_refSeq)
531 text.append(newline);
532 text.append("SEQUENCE_REF\t");
533 text.append(next_refSeq.getName());
534 text.append(newline);
541 public void printGroups(List<SequenceGroup> list)
543 SequenceI seqrep = null;
544 for (SequenceGroup sg : list)
548 text.append("SEQUENCE_GROUP\t" + sg.getName() + "\t"
549 + (sg.getStartRes() + 1) + "\t" + (sg.getEndRes() + 1)
555 seqrep = sg.getSeqrep();
556 text.append("SEQUENCE_REF\t");
557 text.append(seqrep.getName());
558 text.append(newline);
559 text.append("SEQUENCE_GROUP\t");
560 text.append(sg.getName());
562 text.append((seqrep.findPosition(sg.getStartRes())));
564 text.append((seqrep.findPosition(sg.getEndRes())));
568 for (int s = 0; s < sg.getSize(); s++)
570 text.append(sg.getSequenceAt(s).getName());
573 text.append(newline);
574 text.append("PROPERTIES\t");
575 text.append(sg.getName());
578 if (sg.getDescription() != null)
580 text.append("description=");
581 text.append(sg.getDescription());
586 text.append("colour=");
587 text.append(ColourSchemeProperty.getColourName(sg.cs));
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(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(Format.getHexString(sg.textColour));
623 if (sg.textColour2 != java.awt.Color.white)
625 text.append("textCol2=");
626 text.append(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(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, String protocol)
668 ColumnSelection colSel = viewport.getColumnSelection();
671 colSel = new ColumnSelection();
673 boolean rslt = readAnnotationFile(viewport.getAlignment(), colSel,
676 && (colSel.hasSelectedColumns() || colSel.hasHiddenColumns()))
678 viewport.setColumnSelection(colSel);
683 public boolean readAnnotationFile(AlignmentI al, String file,
686 return readAnnotationFile(al, null, file, protocol);
689 public boolean readAnnotationFile(AlignmentI al, ColumnSelection colSel,
690 String file, String protocol)
692 BufferedReader in = null;
695 if (protocol.equals(AppletFormatAdapter.FILE))
697 in = new BufferedReader(new FileReader(file));
699 else if (protocol.equals(AppletFormatAdapter.URL))
701 URL url = new URL(file);
702 in = new BufferedReader(new InputStreamReader(url.openStream()));
704 else if (protocol.equals(AppletFormatAdapter.PASTE))
706 in = new BufferedReader(new StringReader(file));
708 else if (protocol.equals(AppletFormatAdapter.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,
746 ArrayList<Object[]> combineAnnotation_calls = new ArrayList<Object[]>();
747 ArrayList<Object[]> deferredAnnotation_calls = new ArrayList<Object[]>();
748 boolean modified = false;
749 String groupRef = null;
750 Hashtable groupRefRows = new Hashtable();
752 Hashtable autoAnnots = new Hashtable();
754 String line, label, description, token;
755 int graphStyle, index;
757 int existingAnnotations = 0;
758 // when true - will add new rows regardless of whether they are duplicate
759 // auto-annotation like consensus or conservation graphs
760 boolean overrideAutoAnnot = false;
761 if (al.getAlignmentAnnotation() != null)
763 existingAnnotations = al.getAlignmentAnnotation().length;
764 if (existingAnnotations > 0)
766 AlignmentAnnotation[] aa = al.getAlignmentAnnotation();
767 for (int aai = 0; aai < aa.length; aai++)
769 if (aa[aai].autoCalculated)
771 // make a note of the name and description
773 autoAnnotsKey(aa[aai], aa[aai].sequenceRef,
774 (aa[aai].groupRef == null ? null
775 : aa[aai].groupRef.getName())),
782 int alWidth = al.getWidth();
785 Annotation[] annotations;
786 AlignmentAnnotation annotation = null;
788 // First confirm this is an Annotation file
789 boolean jvAnnotationFile = false;
790 while ((line = in.readLine()) != null)
793 lastread = new String(line);
794 if (line.indexOf("#") == 0)
799 if (line.indexOf("JALVIEW_ANNOTATION") > -1)
801 jvAnnotationFile = true;
806 if (!jvAnnotationFile)
812 while ((line = in.readLine()) != null)
815 lastread = new String(line);
816 if (line.indexOf("#") == 0
817 || line.indexOf("JALVIEW_ANNOTATION") > -1
818 || line.length() == 0)
823 st = new StringTokenizer(line, "\t");
824 token = st.nextToken();
825 if (token.equalsIgnoreCase("COLOUR"))
827 // TODO: use graduated colour def'n here too
828 colourAnnotations(al, st.nextToken(), st.nextToken());
833 else if (token.equalsIgnoreCase(COMBINE))
835 // keep a record of current state and resolve groupRef at end
836 combineAnnotation_calls.add(new Object[]
837 { st, refSeq, groupRef });
841 else if (token.equalsIgnoreCase("ROWPROPERTIES"))
843 addRowProperties(al, st);
847 else if (token.equalsIgnoreCase(GRAPHLINE))
850 deferredAnnotation_calls.add(new Object[]
851 { GRAPHLINE, st, refSeq, groupRef });
856 else if (token.equalsIgnoreCase("SEQUENCE_REF"))
858 if (st.hasMoreTokens())
860 refSeq = al.findName(refSeqId = st.nextToken());
867 refSeqIndex = Integer.parseInt(st.nextToken());
872 .println("WARNING: SEQUENCE_REF index must be > 0 in AnnotationFile");
874 } catch (Exception ex)
886 else if (token.equalsIgnoreCase("GROUP_REF"))
888 // Group references could be forward or backwards, so they are
889 // resolved after the whole file is read in
891 if (st.hasMoreTokens())
893 groupRef = st.nextToken();
894 if (groupRef.length() < 1)
896 groupRef = null; // empty string
900 if (groupRefRows.get(groupRef) == null)
902 groupRefRows.put(groupRef, new Vector());
908 else if (token.equalsIgnoreCase("SEQUENCE_GROUP"))
915 else if (token.equalsIgnoreCase("PROPERTIES"))
917 addProperties(al, st);
922 else if (token.equalsIgnoreCase("BELOW_ALIGNMENT"))
924 setBelowAlignment(al, st);
928 else if (token.equalsIgnoreCase("ALIGNMENT"))
930 addAlignmentDetails(al, st);
934 // else if (token.equalsIgnoreCase("VIEW_DEF"))
936 // addOrSetView(al,st);
940 else if (token.equalsIgnoreCase("VIEW_SETREF"))
944 al.setSeqrep(refSeq);
949 else if (token.equalsIgnoreCase("VIEW_HIDECOLS"))
951 if (st.hasMoreTokens())
955 colSel = new ColumnSelection();
957 parseHideCols(colSel, st.nextToken());
962 else if (token.equalsIgnoreCase("HIDE_INSERTIONS"))
964 SequenceI sr = refSeq == null ? al.getSeqrep() : refSeq;
967 sr = al.getSequenceAt(0);
974 .println("Cannot process HIDE_INSERTIONS without an alignment view: Ignoring line: "
979 // consider deferring this till after the file has been parsed ?
980 colSel.hideInsertionsFor(sr);
987 // Parse out the annotation row
988 graphStyle = AlignmentAnnotation.getGraphValueFromString(token);
989 label = st.nextToken();
992 annotations = new Annotation[alWidth];
994 float score = Float.NaN;
996 if (st.hasMoreTokens())
998 line = st.nextToken();
1000 if (line.indexOf("|") == -1)
1003 if (st.hasMoreTokens())
1005 line = st.nextToken();
1009 if (st.hasMoreTokens())
1011 // This must be the score
1012 score = Float.valueOf(st.nextToken()).floatValue();
1015 st = new StringTokenizer(line, "|", true);
1017 boolean emptyColumn = true;
1018 boolean onlyOneElement = (st.countTokens() == 1);
1020 while (st.hasMoreElements() && index < alWidth)
1022 token = st.nextToken().trim();
1028 score = Float.valueOf(token).floatValue();
1030 } catch (NumberFormatException ex)
1035 if (token.equals("|"))
1046 annotations[index++] = parseAnnotation(token, graphStyle);
1047 emptyColumn = false;
1053 annotation = new AlignmentAnnotation(label, description,
1054 (index == 0) ? null : annotations, 0, 0, graphStyle);
1056 annotation.score = score;
1057 if (!overrideAutoAnnot
1058 && autoAnnots.containsKey(autoAnnotsKey(annotation, refSeq,
1061 // skip - we've already got an automatic annotation of this type.
1064 // otherwise add it!
1068 annotation.belowAlignment = false;
1069 // make a copy of refSeq so we can find other matches in the alignment
1070 SequenceI referedSeq = refSeq;
1073 // copy before we do any mapping business.
1074 // TODO: verify that undo/redo with 1:many sequence associated
1075 // annotations can be undone correctly
1076 AlignmentAnnotation ann = new AlignmentAnnotation(annotation);
1078 .createSequenceMapping(referedSeq, refSeqIndex, false);
1079 annotation.adjustForAlignment();
1080 referedSeq.addAlignmentAnnotation(annotation);
1081 al.addAnnotation(annotation);
1082 al.setAnnotationIndex(annotation,
1083 al.getAlignmentAnnotation().length
1084 - existingAnnotations - 1);
1085 if (groupRef != null)
1087 ((Vector) groupRefRows.get(groupRef)).addElement(annotation);
1089 // and recover our virgin copy to use again if necessary.
1092 } while (refSeqId != null
1093 && (referedSeq = al.findName(referedSeq, refSeqId, true)) != null);
1097 al.addAnnotation(annotation);
1098 al.setAnnotationIndex(annotation,
1099 al.getAlignmentAnnotation().length - existingAnnotations
1101 if (groupRef != null)
1103 ((Vector) groupRefRows.get(groupRef)).addElement(annotation);
1106 // and set modification flag
1109 // Resolve the groupRefs
1110 Hashtable<String, SequenceGroup> groupRefLookup = new Hashtable<String, SequenceGroup>();
1111 Enumeration en = groupRefRows.keys();
1113 while (en.hasMoreElements())
1115 groupRef = (String) en.nextElement();
1116 boolean matched = false;
1117 // Resolve group: TODO: add a getGroupByName method to alignments
1118 for (SequenceGroup theGroup : al.getGroups())
1120 if (theGroup.getName().equals(groupRef))
1124 // TODO: specify and implement duplication of alignment annotation
1125 // for multiple group references.
1127 .println("Ignoring 1:many group reference mappings for group name '"
1133 Vector rowset = (Vector) groupRefRows.get(groupRef);
1134 groupRefLookup.put(groupRef, theGroup);
1135 if (rowset != null && rowset.size() > 0)
1137 AlignmentAnnotation alan = null;
1138 for (int elm = 0, elmSize = rowset.size(); elm < elmSize; elm++)
1140 alan = (AlignmentAnnotation) rowset.elementAt(elm);
1141 alan.groupRef = theGroup;
1147 ((Vector) groupRefRows.get(groupRef)).removeAllElements();
1149 // process any deferred attribute settings for each context
1150 for (Object[] _deferred_args : deferredAnnotation_calls)
1152 if (_deferred_args[0] == GRAPHLINE)
1155 (StringTokenizer) _deferred_args[1], // st
1156 (SequenceI) _deferred_args[2], // refSeq
1157 (_deferred_args[3] == null) ? null : groupRefLookup
1158 .get(_deferred_args[3]) // the reference
1164 // finally, combine all the annotation rows within each context.
1166 * number of combine statements in this annotation file. Used to create
1167 * new groups for combined annotation graphs without disturbing existing
1170 int combinecount = 0;
1171 for (Object[] _combine_args : combineAnnotation_calls)
1173 combineAnnotations(al,
1175 (StringTokenizer) _combine_args[0], // st
1176 (SequenceI) _combine_args[1], // refSeq
1177 (_combine_args[2] == null) ? null : groupRefLookup
1178 .get(_combine_args[2]) // the reference group,
1186 private void parseHideCols(ColumnSelection colSel, String nextToken)
1188 StringTokenizer inval = new StringTokenizer(nextToken,",");
1189 while (inval.hasMoreTokens())
1191 String range = inval.nextToken().trim();
1192 int from, to = range.indexOf("-");
1195 from = to = Integer.parseInt(range);
1198 colSel.hideColumns(from, to);
1203 from = Integer.parseInt(range.substring(0, to));
1204 if (to < range.length() - 1)
1206 to = Integer.parseInt(range.substring(to + 1));
1212 if (from > 0 && to >= from)
1214 colSel.hideColumns(from, to);
1220 private Object autoAnnotsKey(AlignmentAnnotation annotation,
1221 SequenceI refSeq, String groupRef)
1223 return annotation.graph + "\t" + annotation.label + "\t"
1224 + annotation.description + "\t"
1225 + (refSeq != null ? refSeq.getDisplayId(true) : "");
1228 Annotation parseAnnotation(String string, int graphStyle)
1230 boolean hasSymbols = (graphStyle == AlignmentAnnotation.NO_GRAPH); // don't
1239 String desc = null, displayChar = null;
1240 char ss = ' '; // secondaryStructure
1242 boolean parsedValue = false, dcset = false;
1245 java.awt.Color colour = null;
1246 int i = string.indexOf("[");
1247 int j = string.indexOf("]");
1248 if (i > -1 && j > -1)
1250 UserColourScheme ucs = new UserColourScheme();
1252 colour = ucs.getColourFromString(string.substring(i + 1, j));
1253 if (i > 0 && string.charAt(i - 1) == ',')
1255 // clip the preceding comma as well
1258 string = string.substring(0, i) + string.substring(j + 1);
1261 StringTokenizer st = new StringTokenizer(string, ",", true);
1263 boolean seenContent = false;
1265 while (st.hasMoreTokens())
1268 token = st.nextToken().trim();
1269 if (token.equals(","))
1271 if (!seenContent && parsedValue && !dcset)
1273 // allow the value below the bar/line to be empty
1277 seenContent = false;
1289 displayChar = token;
1291 value = new Float(token).floatValue();
1294 } catch (NumberFormatException ex)
1300 if (token.length() == 1)
1302 displayChar = token;
1306 && (token.equals("H") || token.equals("E")
1307 || token.equals("S") || token.equals(" ")))
1309 // Either this character represents a helix or sheet
1310 // or an integer which can be displayed
1311 ss = token.charAt(0);
1312 if (displayChar.equals(token.substring(0, 1)))
1317 else if (desc == null || (parsedValue && pass > 2))
1323 // if (!dcset && string.charAt(string.length() - 1) == ',')
1325 // displayChar = " "; // empty display char symbol.
1327 if (displayChar != null && desc != null && desc.length() == 1)
1329 if (displayChar.length() > 1)
1331 // switch desc and displayChar - legacy support
1332 String tmp = displayChar;
1338 if (displayChar.equals(desc))
1340 // duplicate label - hangover from the 'robust parser' above
1345 Annotation anot = new Annotation(displayChar, desc, ss, value);
1347 anot.colour = colour;
1352 void colourAnnotations(AlignmentI al, String label, String colour)
1354 UserColourScheme ucs = new UserColourScheme(colour);
1355 Annotation[] annotations;
1356 for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1358 if (al.getAlignmentAnnotation()[i].label.equalsIgnoreCase(label))
1360 annotations = al.getAlignmentAnnotation()[i].annotations;
1361 for (int j = 0; j < annotations.length; j++)
1363 if (annotations[j] != null)
1365 annotations[j].colour = ucs.findColour('A');
1372 void combineAnnotations(AlignmentI al, int combineCount,
1373 StringTokenizer st, SequenceI seqRef, SequenceGroup groupRef)
1375 String group = st.nextToken();
1376 // First make sure we are not overwriting the graphIndex
1378 if (al.getAlignmentAnnotation() != null)
1380 for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1382 AlignmentAnnotation aa = al.getAlignmentAnnotation()[i];
1384 if (aa.graphGroup > graphGroup)
1386 // try to number graphGroups in order of occurence.
1387 graphGroup = aa.graphGroup + 1;
1389 if (aa.sequenceRef == seqRef && aa.groupRef == groupRef
1390 && aa.label.equalsIgnoreCase(group))
1392 if (aa.graphGroup > -1)
1394 graphGroup = aa.graphGroup;
1398 if (graphGroup <= combineCount)
1400 graphGroup = combineCount + 1;
1402 aa.graphGroup = graphGroup;
1408 // Now update groups
1409 while (st.hasMoreTokens())
1411 group = st.nextToken();
1412 for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1414 AlignmentAnnotation aa = al.getAlignmentAnnotation()[i];
1415 if (aa.sequenceRef == seqRef && aa.groupRef == groupRef
1416 && aa.label.equalsIgnoreCase(group))
1418 aa.graphGroup = graphGroup;
1427 .println("Couldn't combine annotations. None are added to alignment yet!");
1431 void addLine(AlignmentI al, StringTokenizer st, SequenceI seqRef,
1432 SequenceGroup groupRef)
1434 String group = st.nextToken();
1435 AlignmentAnnotation annotation = null, alannot[] = al
1436 .getAlignmentAnnotation();
1437 float value = new Float(st.nextToken()).floatValue();
1438 String label = st.hasMoreTokens() ? st.nextToken() : null;
1439 java.awt.Color colour = null;
1440 if (st.hasMoreTokens())
1442 UserColourScheme ucs = new UserColourScheme(st.nextToken());
1443 colour = ucs.findColour('A');
1445 if (alannot != null)
1447 for (int i = 0; i < alannot.length; i++)
1449 if (alannot[i].label.equalsIgnoreCase(group)
1450 && (seqRef == null || alannot[i].sequenceRef == seqRef)
1451 && (groupRef == null || alannot[i].groupRef == groupRef))
1453 alannot[i].setThreshold(new GraphLine(value, label, colour));
1457 if (annotation == null)
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.cs;
1622 while (st.hasMoreTokens())
1624 keyValue = st.nextToken();
1625 key = keyValue.substring(0, keyValue.indexOf("="));
1626 value = keyValue.substring(keyValue.indexOf("=") + 1);
1628 if (key.equalsIgnoreCase("description"))
1630 sg.setDescription(value);
1632 else if (key.equalsIgnoreCase("colour"))
1634 sg.cs = ColourSchemeProperty.getColour(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",
1645 ResidueProperties.propHash, 3, sg.getSequences(null),
1646 sg.getStartRes(), sg.getEndRes() + 1);
1649 c.verdict(false, 25); // TODO: refer to conservation percent threshold
1651 sg.cs.setConservation(c);
1654 else if (key.equalsIgnoreCase("outlineColour"))
1656 sg.setOutlineColour(new UserColourScheme(value).findColour('A'));
1658 else if (key.equalsIgnoreCase("displayBoxes"))
1660 sg.setDisplayBoxes(Boolean.valueOf(value).booleanValue());
1662 else if (key.equalsIgnoreCase("showUnconserved"))
1664 sg.setShowNonconserved(Boolean.valueOf(value).booleanValue());
1666 else if (key.equalsIgnoreCase("displayText"))
1668 sg.setDisplayText(Boolean.valueOf(value).booleanValue());
1670 else if (key.equalsIgnoreCase("colourText"))
1672 sg.setColourText(Boolean.valueOf(value).booleanValue());
1674 else if (key.equalsIgnoreCase("textCol1"))
1676 sg.textColour = new UserColourScheme(value).findColour('A');
1678 else if (key.equalsIgnoreCase("textCol2"))
1680 sg.textColour2 = new UserColourScheme(value).findColour('A');
1682 else if (key.equalsIgnoreCase("textColThreshold"))
1684 sg.thresholdTextColour = Integer.parseInt(value);
1686 else if (key.equalsIgnoreCase("idColour"))
1688 // consider warning if colour doesn't resolve to a real colour
1689 sg.setIdColour((def = new UserColourScheme(value))
1692 else if (key.equalsIgnoreCase("hide"))
1694 // see bug https://mantis.lifesci.dundee.ac.uk/view.php?id=25847
1695 sg.setHidereps(true);
1697 else if (key.equalsIgnoreCase("hidecols"))
1699 // see bug https://mantis.lifesci.dundee.ac.uk/view.php?id=25847
1700 sg.setHideCols(true);
1702 sg.recalcConservation();
1711 void setBelowAlignment(AlignmentI al, StringTokenizer st)
1714 AlignmentAnnotation aa, ala[] = al.getAlignmentAnnotation();
1718 .print("Warning - no annotation to set below for sequence associated annotation:");
1720 while (st.hasMoreTokens())
1722 token = st.nextToken();
1725 System.err.print(" " + token);
1729 for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1731 aa = al.getAlignmentAnnotation()[i];
1732 if (aa.sequenceRef == refSeq && aa.label.equals(token))
1734 aa.belowAlignment = true;
1741 System.err.print("\n");
1745 void addAlignmentDetails(AlignmentI al, StringTokenizer st)
1747 String keyValue, key, value;
1748 while (st.hasMoreTokens())
1750 keyValue = st.nextToken();
1751 key = keyValue.substring(0, keyValue.indexOf("="));
1752 value = keyValue.substring(keyValue.indexOf("=") + 1);
1753 al.setProperty(key, value);
1758 * Write annotations as a CSV file of the form 'label, value, value, ...' for
1761 * @param annotations
1762 * @return CSV file as a string.
1764 public String printCSVAnnotations(AlignmentAnnotation[] annotations)
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);