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.Colour;
34 import jalview.schemes.ColourSchemeI;
35 import jalview.schemes.ColourSchemeProperty;
36 import jalview.schemes.ResidueProperties;
37 import jalview.schemes.UserColourScheme;
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 public String viewname;
115 public HiddenSequences hidseqs;
117 public ColumnSelection hiddencols;
119 public Vector visibleGroups;
121 public Hashtable hiddenRepSeqs;
123 public ViewDef(String viewname, HiddenSequences hidseqs,
124 ColumnSelection hiddencols, Hashtable hiddenRepSeqs)
126 this.viewname = viewname;
127 this.hidseqs = hidseqs;
128 this.hiddencols = hiddencols;
129 this.hiddenRepSeqs = hiddenRepSeqs;
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 public 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));
588 if (sg.cs.getThreshold() != 0)
590 text.append("pidThreshold=");
591 text.append(sg.cs.getThreshold());
593 if (sg.cs.conservationApplied())
595 text.append("consThreshold=");
596 text.append(sg.cs.getConservationInc());
600 text.append("outlineColour=");
601 text.append(jalview.util.Format.getHexString(sg.getOutlineColour()));
604 text.append("displayBoxes=");
605 text.append(sg.getDisplayBoxes());
607 text.append("displayText=");
608 text.append(sg.getDisplayText());
610 text.append("colourText=");
611 text.append(sg.getColourText());
613 text.append("showUnconserved=");
614 text.append(sg.getShowNonconserved());
616 if (sg.textColour != java.awt.Color.black)
618 text.append("textCol1=");
619 text.append(jalview.util.Format.getHexString(sg.textColour));
622 if (sg.textColour2 != java.awt.Color.white)
624 text.append("textCol2=");
625 text.append(jalview.util.Format.getHexString(sg.textColour2));
628 if (sg.thresholdTextColour != 0)
630 text.append("textColThreshold=");
631 text.append(sg.thresholdTextColour);
634 if (sg.idColour != null)
636 text.append("idColour=");
637 text.append(jalview.util.Format.getHexString(sg.idColour));
642 text.append("hide=true\t");
646 text.append("hidecols=true\t");
650 // terminate the last line and clear the sequence ref for the group
651 text.append(newline);
652 text.append("SEQUENCE_REF");
654 text.append(newline);
655 text.append(newline);
660 SequenceI refSeq = null;
662 String refSeqId = null;
664 public boolean annotateAlignmentView(AlignViewportI viewport,
665 String file, String protocol)
667 ColumnSelection colSel = viewport.getColumnSelection();
670 colSel = new ColumnSelection();
672 boolean rslt = readAnnotationFile(viewport.getAlignment(), colSel,
674 if (rslt && (colSel.hasSelectedColumns() || colSel.hasHiddenColumns()))
676 viewport.setColumnSelection(colSel);
682 public boolean readAnnotationFile(AlignmentI al, String file,
685 return readAnnotationFile(al, null, file, protocol);
688 public boolean readAnnotationFile(AlignmentI al, ColumnSelection colSel,
689 String file, String protocol)
691 BufferedReader in = null;
694 if (protocol.equals(AppletFormatAdapter.FILE))
696 in = new BufferedReader(new FileReader(file));
698 else if (protocol.equals(AppletFormatAdapter.URL))
700 URL url = new URL(file);
701 in = new BufferedReader(new InputStreamReader(url.openStream()));
703 else if (protocol.equals(AppletFormatAdapter.PASTE))
705 in = new BufferedReader(new StringReader(file));
707 else if (protocol.equals(AppletFormatAdapter.CLASSLOADER))
709 java.io.InputStream is = getClass().getResourceAsStream("/" + file);
712 in = new BufferedReader(new java.io.InputStreamReader(is));
717 return parseAnnotationFrom(al, colSel, in);
720 } catch (Exception ex)
722 ex.printStackTrace();
723 System.out.println("Problem reading annotation file: " + ex);
726 System.out.println("Last read line " + nlinesread + ": '"
727 + lastread + "' (first 80 chars) ...");
736 String lastread = "";
738 private static String GRAPHLINE = "GRAPHLINE", COMBINE = "COMBINE";
740 public boolean parseAnnotationFrom(AlignmentI al, ColumnSelection colSel,
741 BufferedReader in) throws Exception
744 ArrayList<Object[]> combineAnnotation_calls = new ArrayList<Object[]>();
745 ArrayList<Object[]> deferredAnnotation_calls = new ArrayList<Object[]>();
746 boolean modified = false;
747 String groupRef = null;
748 Hashtable groupRefRows = new Hashtable();
750 Hashtable autoAnnots = new Hashtable();
752 String line, label, description, token;
753 int graphStyle, index;
755 int existingAnnotations = 0;
756 // when true - will add new rows regardless of whether they are duplicate
757 // auto-annotation like consensus or conservation graphs
758 boolean overrideAutoAnnot = false;
759 if (al.getAlignmentAnnotation() != null)
761 existingAnnotations = al.getAlignmentAnnotation().length;
762 if (existingAnnotations > 0)
764 AlignmentAnnotation[] aa = al.getAlignmentAnnotation();
765 for (int aai = 0; aai < aa.length; aai++)
767 if (aa[aai].autoCalculated)
769 // make a note of the name and description
771 autoAnnotsKey(aa[aai], aa[aai].sequenceRef,
772 (aa[aai].groupRef == null ? null
773 : aa[aai].groupRef.getName())),
780 int alWidth = al.getWidth();
783 Annotation[] annotations;
784 AlignmentAnnotation annotation = null;
786 // First confirm this is an Annotation file
787 boolean jvAnnotationFile = false;
788 while ((line = in.readLine()) != null)
791 lastread = new String(line);
792 if (line.indexOf("#") == 0)
797 if (line.indexOf("JALVIEW_ANNOTATION") > -1)
799 jvAnnotationFile = true;
804 if (!jvAnnotationFile)
810 while ((line = in.readLine()) != null)
813 lastread = new String(line);
814 if (line.indexOf("#") == 0
815 || line.indexOf("JALVIEW_ANNOTATION") > -1
816 || line.length() == 0)
821 st = new StringTokenizer(line, "\t");
822 token = st.nextToken();
823 if (token.equalsIgnoreCase("COLOUR"))
825 // TODO: use graduated colour def'n here too
826 colourAnnotations(al, st.nextToken(), st.nextToken());
831 else if (token.equalsIgnoreCase(COMBINE))
833 // keep a record of current state and resolve groupRef at end
834 combineAnnotation_calls
835 .add(new Object[] { st, refSeq, groupRef });
839 else if (token.equalsIgnoreCase("ROWPROPERTIES"))
841 addRowProperties(al, st);
845 else if (token.equalsIgnoreCase(GRAPHLINE))
848 deferredAnnotation_calls.add(new Object[] { GRAPHLINE, st,
854 else if (token.equalsIgnoreCase("SEQUENCE_REF"))
856 if (st.hasMoreTokens())
858 refSeq = al.findName(refSeqId = st.nextToken());
865 refSeqIndex = Integer.parseInt(st.nextToken());
870 .println("WARNING: SEQUENCE_REF index must be > 0 in AnnotationFile");
872 } catch (Exception ex)
884 else if (token.equalsIgnoreCase("GROUP_REF"))
886 // Group references could be forward or backwards, so they are
887 // resolved after the whole file is read in
889 if (st.hasMoreTokens())
891 groupRef = st.nextToken();
892 if (groupRef.length() < 1)
894 groupRef = null; // empty string
898 if (groupRefRows.get(groupRef) == null)
900 groupRefRows.put(groupRef, new Vector());
906 else if (token.equalsIgnoreCase("SEQUENCE_GROUP"))
913 else if (token.equalsIgnoreCase("PROPERTIES"))
915 addProperties(al, st);
920 else if (token.equalsIgnoreCase("BELOW_ALIGNMENT"))
922 setBelowAlignment(al, st);
926 else if (token.equalsIgnoreCase("ALIGNMENT"))
928 addAlignmentDetails(al, st);
932 // else if (token.equalsIgnoreCase("VIEW_DEF"))
934 // addOrSetView(al,st);
938 else if (token.equalsIgnoreCase("VIEW_SETREF"))
942 al.setSeqrep(refSeq);
947 else if (token.equalsIgnoreCase("VIEW_HIDECOLS"))
949 if (st.hasMoreTokens())
953 colSel = new ColumnSelection();
955 parseHideCols(colSel, st.nextToken());
960 else if (token.equalsIgnoreCase("HIDE_INSERTIONS"))
962 SequenceI sr = refSeq == null ? al.getSeqrep() : refSeq;
965 sr = al.getSequenceAt(0);
972 .println("Cannot process HIDE_INSERTIONS without an alignment view: Ignoring line: "
977 // consider deferring this till after the file has been parsed ?
978 colSel.hideInsertionsFor(sr);
985 // Parse out the annotation row
986 graphStyle = AlignmentAnnotation.getGraphValueFromString(token);
987 label = st.nextToken();
990 annotations = new Annotation[alWidth];
992 float score = Float.NaN;
994 if (st.hasMoreTokens())
996 line = st.nextToken();
998 if (line.indexOf("|") == -1)
1001 if (st.hasMoreTokens())
1003 line = st.nextToken();
1007 if (st.hasMoreTokens())
1009 // This must be the score
1010 score = Float.valueOf(st.nextToken()).floatValue();
1013 st = new StringTokenizer(line, "|", true);
1015 boolean emptyColumn = true;
1016 boolean onlyOneElement = (st.countTokens() == 1);
1018 while (st.hasMoreElements() && index < alWidth)
1020 token = st.nextToken().trim();
1026 score = Float.valueOf(token).floatValue();
1028 } catch (NumberFormatException ex)
1033 if (token.equals("|"))
1044 annotations[index++] = parseAnnotation(token, graphStyle);
1045 emptyColumn = false;
1051 annotation = new AlignmentAnnotation(label, description,
1052 (index == 0) ? null : annotations, 0, 0, graphStyle);
1054 annotation.score = score;
1055 if (!overrideAutoAnnot
1056 && autoAnnots.containsKey(autoAnnotsKey(annotation, refSeq,
1059 // skip - we've already got an automatic annotation of this type.
1062 // otherwise add it!
1066 annotation.belowAlignment = false;
1067 // make a copy of refSeq so we can find other matches in the alignment
1068 SequenceI referedSeq = refSeq;
1071 // copy before we do any mapping business.
1072 // TODO: verify that undo/redo with 1:many sequence associated
1073 // annotations can be undone correctly
1074 AlignmentAnnotation ann = new AlignmentAnnotation(annotation);
1076 .createSequenceMapping(referedSeq, refSeqIndex, false);
1077 annotation.adjustForAlignment();
1078 referedSeq.addAlignmentAnnotation(annotation);
1079 al.addAnnotation(annotation);
1080 al.setAnnotationIndex(annotation,
1081 al.getAlignmentAnnotation().length
1082 - existingAnnotations - 1);
1083 if (groupRef != null)
1085 ((Vector) groupRefRows.get(groupRef)).addElement(annotation);
1087 // and recover our virgin copy to use again if necessary.
1090 } while (refSeqId != null
1091 && (referedSeq = al.findName(referedSeq, refSeqId, true)) != null);
1095 al.addAnnotation(annotation);
1096 al.setAnnotationIndex(annotation,
1097 al.getAlignmentAnnotation().length - existingAnnotations
1099 if (groupRef != null)
1101 ((Vector) groupRefRows.get(groupRef)).addElement(annotation);
1104 // and set modification flag
1107 // Resolve the groupRefs
1108 Hashtable<String, SequenceGroup> groupRefLookup = new Hashtable<String, SequenceGroup>();
1109 Enumeration en = groupRefRows.keys();
1111 while (en.hasMoreElements())
1113 groupRef = (String) en.nextElement();
1114 boolean matched = false;
1115 // Resolve group: TODO: add a getGroupByName method to alignments
1116 for (SequenceGroup theGroup : al.getGroups())
1118 if (theGroup.getName().equals(groupRef))
1122 // TODO: specify and implement duplication of alignment annotation
1123 // for multiple group references.
1125 .println("Ignoring 1:many group reference mappings for group name '"
1131 Vector rowset = (Vector) groupRefRows.get(groupRef);
1132 groupRefLookup.put(groupRef, theGroup);
1133 if (rowset != null && rowset.size() > 0)
1135 AlignmentAnnotation alan = null;
1136 for (int elm = 0, elmSize = rowset.size(); elm < elmSize; elm++)
1138 alan = (AlignmentAnnotation) rowset.elementAt(elm);
1139 alan.groupRef = theGroup;
1145 ((Vector) groupRefRows.get(groupRef)).removeAllElements();
1147 // process any deferred attribute settings for each context
1148 for (Object[] _deferred_args : deferredAnnotation_calls)
1150 if (_deferred_args[0] == GRAPHLINE)
1153 (StringTokenizer) _deferred_args[1], // st
1154 (SequenceI) _deferred_args[2], // refSeq
1155 (_deferred_args[3] == null) ? null : groupRefLookup
1156 .get(_deferred_args[3]) // the reference
1162 // finally, combine all the annotation rows within each context.
1164 * number of combine statements in this annotation file. Used to create
1165 * new groups for combined annotation graphs without disturbing existing
1168 int combinecount = 0;
1169 for (Object[] _combine_args : combineAnnotation_calls)
1171 combineAnnotations(al,
1173 (StringTokenizer) _combine_args[0], // st
1174 (SequenceI) _combine_args[1], // refSeq
1175 (_combine_args[2] == null) ? null : groupRefLookup
1176 .get(_combine_args[2]) // the reference group,
1184 private void parseHideCols(ColumnSelection colSel, String nextToken)
1186 StringTokenizer inval = new StringTokenizer(nextToken, ",");
1187 while (inval.hasMoreTokens())
1189 String range = inval.nextToken().trim();
1190 int from, to = range.indexOf("-");
1193 from = to = Integer.parseInt(range);
1196 colSel.hideColumns(from, to);
1201 from = Integer.parseInt(range.substring(0, to));
1202 if (to < range.length() - 1)
1204 to = Integer.parseInt(range.substring(to + 1));
1210 if (from > 0 && to >= from)
1212 colSel.hideColumns(from, to);
1218 private Object autoAnnotsKey(AlignmentAnnotation annotation,
1219 SequenceI refSeq, String groupRef)
1221 return annotation.graph + "\t" + annotation.label + "\t"
1222 + annotation.description + "\t"
1223 + (refSeq != null ? refSeq.getDisplayId(true) : "");
1226 Annotation parseAnnotation(String string, int graphStyle)
1228 boolean hasSymbols = (graphStyle == AlignmentAnnotation.NO_GRAPH); // don't
1237 String desc = null, displayChar = null;
1238 char ss = ' '; // secondaryStructure
1240 boolean parsedValue = false, dcset = false;
1243 java.awt.Color colour = null;
1244 int i = string.indexOf("[");
1245 int j = string.indexOf("]");
1246 if (i > -1 && j > -1)
1248 UserColourScheme ucs = new UserColourScheme();
1250 colour = ucs.getColourFromString(string.substring(i + 1, j));
1251 if (i > 0 && string.charAt(i - 1) == ',')
1253 // clip the preceding comma as well
1256 string = string.substring(0, i) + string.substring(j + 1);
1259 StringTokenizer st = new StringTokenizer(string, ",", true);
1261 boolean seenContent = false;
1263 while (st.hasMoreTokens())
1266 token = st.nextToken().trim();
1267 if (token.equals(","))
1269 if (!seenContent && parsedValue && !dcset)
1271 // allow the value below the bar/line to be empty
1275 seenContent = false;
1287 displayChar = token;
1289 value = new Float(token).floatValue();
1292 } catch (NumberFormatException ex)
1298 if (token.length() == 1)
1300 displayChar = token;
1304 && (token.length() == 1 && "()<>[]{}AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz"
1307 // Either this character represents a helix or sheet
1308 // or an integer which can be displayed
1309 ss = token.charAt(0);
1310 if (displayChar.equals(token.substring(0, 1)))
1315 else if (desc == null || (parsedValue && pass > 2))
1321 // if (!dcset && string.charAt(string.length() - 1) == ',')
1323 // displayChar = " "; // empty display char symbol.
1325 if (displayChar != null && desc != null && desc.length() == 1)
1327 if (displayChar.length() > 1)
1329 // switch desc and displayChar - legacy support
1330 String tmp = displayChar;
1336 if (displayChar.equals(desc))
1338 // duplicate label - hangover from the 'robust parser' above
1343 Annotation anot = new Annotation(displayChar, desc, ss, value);
1345 anot.colour = colour;
1350 void colourAnnotations(AlignmentI al, String label, String colour)
1352 UserColourScheme ucs = new UserColourScheme(colour);
1353 Annotation[] annotations;
1354 for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1356 if (al.getAlignmentAnnotation()[i].label.equalsIgnoreCase(label))
1358 annotations = al.getAlignmentAnnotation()[i].annotations;
1359 for (int j = 0; j < annotations.length; j++)
1361 if (annotations[j] != null)
1363 annotations[j].colour = ucs.findColour('A');
1370 void combineAnnotations(AlignmentI al, int combineCount,
1371 StringTokenizer st, SequenceI seqRef, SequenceGroup groupRef)
1373 String group = st.nextToken();
1374 // First make sure we are not overwriting the graphIndex
1376 if (al.getAlignmentAnnotation() != null)
1378 for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1380 AlignmentAnnotation aa = al.getAlignmentAnnotation()[i];
1382 if (aa.graphGroup > graphGroup)
1384 // try to number graphGroups in order of occurence.
1385 graphGroup = aa.graphGroup + 1;
1387 if (aa.sequenceRef == seqRef && aa.groupRef == groupRef
1388 && aa.label.equalsIgnoreCase(group))
1390 if (aa.graphGroup > -1)
1392 graphGroup = aa.graphGroup;
1396 if (graphGroup <= combineCount)
1398 graphGroup = combineCount + 1;
1400 aa.graphGroup = graphGroup;
1406 // Now update groups
1407 while (st.hasMoreTokens())
1409 group = st.nextToken();
1410 for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1412 AlignmentAnnotation aa = al.getAlignmentAnnotation()[i];
1413 if (aa.sequenceRef == seqRef && aa.groupRef == groupRef
1414 && aa.label.equalsIgnoreCase(group))
1416 aa.graphGroup = graphGroup;
1425 .println("Couldn't combine annotations. None are added to alignment yet!");
1429 void addLine(AlignmentI al, StringTokenizer st, SequenceI seqRef,
1430 SequenceGroup groupRef)
1432 String group = st.nextToken();
1433 AlignmentAnnotation annotation = null, alannot[] = al
1434 .getAlignmentAnnotation();
1435 float value = new Float(st.nextToken()).floatValue();
1436 String label = st.hasMoreTokens() ? st.nextToken() : null;
1437 java.awt.Color colour = null;
1438 if (st.hasMoreTokens())
1440 UserColourScheme ucs = new UserColourScheme(st.nextToken());
1441 colour = ucs.findColour('A');
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));
1455 if (annotation == null)
1461 void addGroup(AlignmentI al, StringTokenizer st)
1463 SequenceGroup sg = new SequenceGroup();
1464 sg.setName(st.nextToken());
1468 rng = st.nextToken();
1469 if (rng.length() > 0 && !rng.startsWith("*"))
1471 sg.setStartRes(Integer.parseInt(rng) - 1);
1477 rng = st.nextToken();
1478 if (rng.length() > 0 && !rng.startsWith("*"))
1480 sg.setEndRes(Integer.parseInt(rng) - 1);
1484 sg.setEndRes(al.getWidth() - 1);
1486 } catch (Exception e)
1489 .println("Couldn't parse Group Start or End Field as '*' or a valid column or sequence index: '"
1490 + rng + "' - assuming alignment width for group.");
1491 // assume group is full width
1493 sg.setEndRes(al.getWidth() - 1);
1496 String index = st.nextToken();
1497 if (index.equals("-1"))
1499 while (st.hasMoreElements())
1501 sg.addSequence(al.findName(st.nextToken()), false);
1506 StringTokenizer st2 = new StringTokenizer(index, ",");
1508 while (st2.hasMoreTokens())
1510 String tmp = st2.nextToken();
1511 if (tmp.equals("*"))
1513 for (int i = 0; i < al.getHeight(); i++)
1515 sg.addSequence(al.getSequenceAt(i), false);
1518 else if (tmp.indexOf("-") >= 0)
1520 StringTokenizer st3 = new StringTokenizer(tmp, "-");
1522 int start = (Integer.parseInt(st3.nextToken()));
1523 int end = (Integer.parseInt(st3.nextToken()));
1527 for (int i = start; i <= end; i++)
1529 sg.addSequence(al.getSequenceAt(i - 1), false);
1535 sg.addSequence(al.getSequenceAt(Integer.parseInt(tmp) - 1), false);
1542 sg.setStartRes(refSeq.findIndex(sg.getStartRes() + 1) - 1);
1543 sg.setEndRes(refSeq.findIndex(sg.getEndRes() + 1) - 1);
1544 sg.setSeqrep(refSeq);
1547 if (sg.getSize() > 0)
1553 void addRowProperties(AlignmentI al, StringTokenizer st)
1555 String label = st.nextToken(), keyValue, key, value;
1556 boolean scaletofit = false, centerlab = false, showalllabs = false;
1557 while (st.hasMoreTokens())
1559 keyValue = st.nextToken();
1560 key = keyValue.substring(0, keyValue.indexOf("="));
1561 value = keyValue.substring(keyValue.indexOf("=") + 1);
1562 if (key.equalsIgnoreCase("scaletofit"))
1564 scaletofit = Boolean.valueOf(value).booleanValue();
1566 if (key.equalsIgnoreCase("showalllabs"))
1568 showalllabs = Boolean.valueOf(value).booleanValue();
1570 if (key.equalsIgnoreCase("centrelabs"))
1572 centerlab = Boolean.valueOf(value).booleanValue();
1574 AlignmentAnnotation[] alr = al.getAlignmentAnnotation();
1577 for (int i = 0; i < alr.length; i++)
1579 if (alr[i].label.equalsIgnoreCase(label))
1581 alr[i].centreColLabels = centerlab;
1582 alr[i].scaleColLabel = scaletofit;
1583 alr[i].showAllColLabels = showalllabs;
1590 void addProperties(AlignmentI al, StringTokenizer st)
1593 // So far we have only added groups to the annotationHash,
1594 // the idea is in the future properties can be added to
1595 // alignments, other annotations etc
1596 if (al.getGroups() == null)
1601 String name = st.nextToken();
1602 SequenceGroup sg = null;
1603 for (SequenceGroup _sg : al.getGroups())
1605 if ((sg = _sg).getName().equals(name))
1617 String keyValue, key, value;
1618 ColourSchemeI def = sg.cs;
1620 while (st.hasMoreTokens())
1622 keyValue = st.nextToken();
1623 key = keyValue.substring(0, keyValue.indexOf("="));
1624 value = keyValue.substring(keyValue.indexOf("=") + 1);
1626 if (key.equalsIgnoreCase("description"))
1628 sg.setDescription(value);
1630 else if (key.equalsIgnoreCase("colour"))
1632 sg.cs = ColourSchemeProperty.getColour(al, value);
1634 else if (key.equalsIgnoreCase("pidThreshold"))
1636 sg.cs.setThreshold(Integer.parseInt(value), true);
1639 else if (key.equalsIgnoreCase("consThreshold"))
1641 sg.cs.setConservationInc(Integer.parseInt(value));
1642 Conservation c = new Conservation("Group",
1643 ResidueProperties.propHash, 3, sg.getSequences(null),
1644 sg.getStartRes(), sg.getEndRes() + 1);
1647 c.verdict(false, 25); // TODO: refer to conservation percent threshold
1649 sg.cs.setConservation(c);
1652 else if (key.equalsIgnoreCase("outlineColour"))
1654 sg.setOutlineColour(new UserColourScheme(value).findColour('A'));
1656 else if (key.equalsIgnoreCase("displayBoxes"))
1658 sg.setDisplayBoxes(Boolean.valueOf(value).booleanValue());
1660 else if (key.equalsIgnoreCase("showUnconserved"))
1662 sg.setShowNonconserved(Boolean.valueOf(value).booleanValue());
1664 else if (key.equalsIgnoreCase("displayText"))
1666 sg.setDisplayText(Boolean.valueOf(value).booleanValue());
1668 else if (key.equalsIgnoreCase("colourText"))
1670 sg.setColourText(Boolean.valueOf(value).booleanValue());
1672 else if (key.equalsIgnoreCase("textCol1"))
1674 sg.textColour = new Colour(
1675 new UserColourScheme(value).findColour('A'));
1677 else if (key.equalsIgnoreCase("textCol2"))
1679 sg.textColour2 = new Colour(
1680 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);