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,
109 * hold all the information about a particular view definition read from or
110 * written out in an annotations file.
114 // TODO this class is not used - remove?
115 public final String viewname;
117 public final HiddenSequences hidseqs;
119 public final HiddenColumns hiddencols;
121 public final Hashtable hiddenRepSeqs;
123 public ViewDef(String vname, HiddenSequences hseqs, HiddenColumns hcols,
126 this.viewname = vname;
127 this.hidseqs = hseqs;
128 this.hiddencols = hcols;
129 this.hiddenRepSeqs = hRepSeqs;
134 * Prepare an annotation file given a set of annotations, groups, alignment
135 * properties and views.
141 * @return annotation file
143 public String printAnnotations(AlignmentAnnotation[] annotations,
144 List<SequenceGroup> list, Hashtable properties, HiddenColumns cs,
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");
175 String regions = cs.regionsToString(",", "-");
176 text.append(regions);
179 // TODO: allow efficient recovery of annotation data shown in several
181 if (annotations != null)
183 boolean oneColour = true;
184 AlignmentAnnotation row;
186 SequenceI refSeq = null;
187 SequenceGroup refGroup = null;
189 StringBuffer colours = new StringBuffer();
190 StringBuffer graphLine = new StringBuffer();
191 StringBuffer rowprops = new StringBuffer();
192 Hashtable<Integer, String> graphGroup = new Hashtable<>();
193 Hashtable<Integer, Object[]> graphGroup_refs = new Hashtable<>();
194 BitSet graphGroupSeen = new BitSet();
196 java.awt.Color color;
198 for (int i = 0; i < annotations.length; i++)
200 row = annotations[i];
202 if (!row.visible && !row.hasScore() && !(row.graphGroup > -1
203 && graphGroupSeen.get(row.graphGroup)))
211 // mark any sequence references for the row
212 writeSequence_Ref(refSeq, row.sequenceRef);
213 refSeq = row.sequenceRef;
214 // mark any group references for the row
215 writeGroup_Ref(refGroup, row.groupRef);
216 refGroup = row.groupRef;
218 boolean hasGlyphs = row.hasIcons, hasLabels = row.hasText,
219 hasValues = row.hasScore, hasText = false;
220 // lookahead to check what the annotation row object actually contains.
221 for (int j = 0; row.annotations != null
222 && j < row.annotations.length
223 && (!hasGlyphs || !hasLabels || !hasValues); j++)
225 if (row.annotations[j] != null)
227 hasLabels |= (row.annotations[j].displayCharacter != null
228 && row.annotations[j].displayCharacter.length() > 0
229 && !row.annotations[j].displayCharacter.equals(" "));
230 hasGlyphs |= (row.annotations[j].secondaryStructure != 0
231 && row.annotations[j].secondaryStructure != ' ');
232 hasValues |= (!Float.isNaN(row.annotations[j].value)); // NaNs can't
235 hasText |= (row.annotations[j].description != null
236 && row.annotations[j].description.length() > 0);
240 if (row.graph == AlignmentAnnotation.NO_GRAPH)
242 text.append("NO_GRAPH\t");
243 hasValues = false; // only secondary structure
244 // hasLabels = false; // and annotation description string.
248 if (row.graph == AlignmentAnnotation.BAR_GRAPH)
250 text.append("BAR_GRAPH\t");
251 hasGlyphs = false; // no secondary structure
254 else if (row.graph == AlignmentAnnotation.LINE_GRAPH)
256 hasGlyphs = false; // no secondary structure
257 text.append("LINE_GRAPH\t");
260 if (row.getThreshold() != null)
262 graphLine.append("GRAPHLINE\t");
263 graphLine.append(row.label);
264 graphLine.append("\t");
265 graphLine.append(row.getThreshold().value);
266 graphLine.append("\t");
267 graphLine.append(row.getThreshold().label);
268 graphLine.append("\t");
269 graphLine.append(jalview.util.Format
270 .getHexString(row.getThreshold().colour));
271 graphLine.append(newline);
274 if (row.graphGroup > -1)
276 graphGroupSeen.set(row.graphGroup);
277 Integer key = new Integer(row.graphGroup);
278 if (graphGroup.containsKey(key))
280 graphGroup.put(key, graphGroup.get(key) + "\t" + row.label);
285 graphGroup_refs.put(key, new Object[] { refSeq, refGroup });
286 graphGroup.put(key, row.label);
291 text.append(row.label + "\t");
292 if (row.description != null)
294 text.append(row.description + "\t");
296 for (int j = 0; row.annotations != null
297 && j < row.annotations.length; j++)
300 && jalview.util.Comparison.isGap(refSeq.getCharAt(j)))
305 if (row.annotations[j] != null)
308 if (hasGlyphs) // could be also hasGlyphs || ...
312 if (row.annotations[j].secondaryStructure != ' ')
314 // only write out the field if its not whitespace.
315 text.append(row.annotations[j].secondaryStructure);
321 if (!Float.isNaN(row.annotations[j].value))
323 text.append(comma + row.annotations[j].value);
327 // System.err.println("Skipping NaN - not valid value.");
328 text.append(comma + 0f);// row.annotations[j].value);
334 // TODO: labels are emitted after values for bar graphs.
335 if // empty labels are allowed, so
336 (row.annotations[j].displayCharacter != null
337 && row.annotations[j].displayCharacter.length() > 0
338 && !row.annotations[j].displayCharacter.equals(" "))
340 text.append(comma + row.annotations[j].displayCharacter);
346 if (row.annotations[j].description != null
347 && row.annotations[j].description.length() > 0
348 && !row.annotations[j].description
349 .equals(row.annotations[j].displayCharacter))
351 text.append(comma + row.annotations[j].description);
355 if (color != null && !color.equals(row.annotations[j].colour))
360 color = row.annotations[j].colour;
362 if (row.annotations[j].colour != null
363 && row.annotations[j].colour != java.awt.Color.black)
365 text.append(comma + "[" + jalview.util.Format
366 .getHexString(row.annotations[j].colour) + "]");
375 text.append("\t" + row.score);
378 text.append(newline);
380 if (color != null && color != java.awt.Color.black && oneColour)
382 colours.append("COLOUR\t");
383 colours.append(row.label);
384 colours.append("\t");
385 colours.append(jalview.util.Format.getHexString(color));
386 colours.append(newline);
388 if (row.scaleColLabel || row.showAllColLabels
389 || row.centreColLabels)
391 rowprops.append("ROWPROPERTIES\t");
392 rowprops.append(row.label);
393 rowprops.append("\tscaletofit=");
394 rowprops.append(row.scaleColLabel);
395 rowprops.append("\tshowalllabs=");
396 rowprops.append(row.showAllColLabels);
397 rowprops.append("\tcentrelabs=");
398 rowprops.append(row.centreColLabels);
399 rowprops.append(newline);
401 if (graphLine.length() > 0)
403 text.append(graphLine.toString());
404 graphLine.setLength(0);
408 text.append(newline);
410 text.append(colours.toString());
411 if (graphGroup.size() > 0)
413 SequenceI oldRefSeq = refSeq;
414 SequenceGroup oldRefGroup = refGroup;
415 for (Map.Entry<Integer, String> combine_statement : graphGroup
418 Object[] seqRefAndGroup = graphGroup_refs
419 .get(combine_statement.getKey());
421 writeSequence_Ref(refSeq, (SequenceI) seqRefAndGroup[0]);
422 refSeq = (SequenceI) seqRefAndGroup[0];
424 writeGroup_Ref(refGroup, (SequenceGroup) seqRefAndGroup[1]);
425 refGroup = (SequenceGroup) seqRefAndGroup[1];
426 text.append("COMBINE\t");
427 text.append(combine_statement.getValue());
428 text.append(newline);
430 writeSequence_Ref(refSeq, oldRefSeq);
433 writeGroup_Ref(refGroup, oldRefGroup);
434 refGroup = oldRefGroup;
436 text.append(rowprops.toString());
444 if (properties != null)
446 text.append(newline);
447 text.append(newline);
448 text.append("ALIGNMENT");
449 Enumeration en = properties.keys();
450 while (en.hasMoreElements())
452 String key = en.nextElement().toString();
456 text.append(properties.get(key));
458 // TODO: output alignment visualization settings here if required
459 // iterate through one or more views, defining, marking columns and rows
460 // as visible/hidden, and emmitting view properties.
461 // View specific annotation is
464 return text.toString();
467 private Object writeGroup_Ref(SequenceGroup refGroup,
468 SequenceGroup next_refGroup)
470 if (next_refGroup == null)
473 if (refGroup != null)
475 text.append(newline);
476 text.append("GROUP_REF\t");
477 text.append("ALIGNMENT");
478 text.append(newline);
484 if (refGroup == null || refGroup != next_refGroup)
486 text.append(newline);
487 text.append("GROUP_REF\t");
488 text.append(next_refGroup.getName());
489 text.append(newline);
496 private boolean writeSequence_Ref(SequenceI refSeq, SequenceI next_refSeq)
499 if (next_refSeq == null)
503 text.append(newline);
504 text.append("SEQUENCE_REF\t");
505 text.append("ALIGNMENT");
506 text.append(newline);
512 if (refSeq == null || refSeq != next_refSeq)
514 text.append(newline);
515 text.append("SEQUENCE_REF\t");
516 text.append(next_refSeq.getName());
517 text.append(newline);
524 protected void printGroups(List<SequenceGroup> list)
526 SequenceI seqrep = null;
527 for (SequenceGroup sg : list)
531 text.append("SEQUENCE_GROUP\t" + sg.getName() + "\t"
532 + (sg.getStartRes() + 1) + "\t" + (sg.getEndRes() + 1)
538 seqrep = sg.getSeqrep();
539 text.append("SEQUENCE_REF\t");
540 text.append(seqrep.getName());
541 text.append(newline);
542 text.append("SEQUENCE_GROUP\t");
543 text.append(sg.getName());
545 text.append((seqrep.findPosition(sg.getStartRes())));
547 text.append((seqrep.findPosition(sg.getEndRes())));
551 for (int s = 0; s < sg.getSize(); s++)
553 text.append(sg.getSequenceAt(s).getName());
556 text.append(newline);
557 text.append("PROPERTIES\t");
558 text.append(sg.getName());
561 if (sg.getDescription() != null)
563 text.append("description=");
564 text.append(sg.getDescription());
569 text.append("colour=");
570 text.append(ColourSchemeProperty
571 .getColourName(sg.cs.getColourScheme()));
573 if (sg.cs.getThreshold() != 0)
575 text.append("pidThreshold=");
576 text.append(sg.cs.getThreshold());
578 if (sg.cs.conservationApplied())
580 text.append("consThreshold=");
581 text.append(sg.cs.getConservationInc());
585 text.append("outlineColour=");
586 text.append(jalview.util.Format.getHexString(sg.getOutlineColour()));
589 text.append("displayBoxes=");
590 text.append(sg.getDisplayBoxes());
592 text.append("displayText=");
593 text.append(sg.getDisplayText());
595 text.append("colourText=");
596 text.append(sg.getColourText());
598 text.append("showUnconserved=");
599 text.append(sg.getShowNonconserved());
601 if (sg.textColour != java.awt.Color.black)
603 text.append("textCol1=");
604 text.append(jalview.util.Format.getHexString(sg.textColour));
607 if (sg.textColour2 != java.awt.Color.white)
609 text.append("textCol2=");
610 text.append(jalview.util.Format.getHexString(sg.textColour2));
613 if (sg.thresholdTextColour != 0)
615 text.append("textColThreshold=");
616 text.append(sg.thresholdTextColour);
619 if (sg.idColour != null)
621 text.append("idColour=");
622 text.append(jalview.util.Format.getHexString(sg.idColour));
627 text.append("hide=true\t");
631 text.append("hidecols=true\t");
635 // terminate the last line and clear the sequence ref for the group
636 text.append(newline);
637 text.append("SEQUENCE_REF");
639 text.append(newline);
640 text.append(newline);
645 SequenceI refSeq = null;
647 String refSeqId = null;
649 public boolean annotateAlignmentView(AlignViewportI viewport, Object file,
650 DataSourceType protocol)
652 ColumnSelection colSel = viewport.getColumnSelection();
653 HiddenColumns hidden = viewport.getAlignment().getHiddenColumns();
656 colSel = new ColumnSelection();
660 hidden = new HiddenColumns();
662 boolean rslt = readAnnotationFile(viewport.getAlignment(), hidden, file,
664 if (rslt && (colSel.hasSelectedColumns() || hidden.hasHiddenColumns()))
666 viewport.setColumnSelection(colSel);
667 viewport.getAlignment().setHiddenColumns(hidden);
673 public boolean readAnnotationFile(AlignmentI al, String file,
674 DataSourceType sourceType)
676 return readAnnotationFile(al, null, file, sourceType);
679 public boolean readAnnotationFile(AlignmentI al, HiddenColumns hidden,
680 Object file, DataSourceType sourceType)
682 BufferedReader in = null;
685 if (sourceType == DataSourceType.FILE)
687 in = FileLoader.getBuffereReader(file);
689 else if (sourceType == DataSourceType.URL)
691 URL url = new URL(file.toString());
692 in = new BufferedReader(new InputStreamReader(url.openStream()));
694 else if (sourceType == DataSourceType.PASTE)
696 in = new BufferedReader(new StringReader(file.toString()));
698 else if (sourceType == DataSourceType.CLASSLOADER)
700 java.io.InputStream is = getClass().getResourceAsStream("/" + file);
703 in = new BufferedReader(new java.io.InputStreamReader(is));
708 return parseAnnotationFrom(al, hidden, in);
711 } catch (Exception ex)
713 ex.printStackTrace();
714 System.out.println("Problem reading annotation file: " + ex);
717 System.out.println("Last read line " + nlinesread + ": '" + lastread
718 + "' (first 80 chars) ...");
727 String lastread = "";
729 private static String GRAPHLINE = "GRAPHLINE", COMBINE = "COMBINE";
731 public boolean parseAnnotationFrom(AlignmentI al, HiddenColumns hidden,
732 BufferedReader in) throws Exception
735 ArrayList<Object[]> combineAnnotation_calls = new ArrayList<>();
736 ArrayList<Object[]> deferredAnnotation_calls = new ArrayList<>();
737 boolean modified = false;
738 String groupRef = null;
739 Hashtable groupRefRows = new Hashtable();
741 Hashtable autoAnnots = new Hashtable();
743 String line, label, description, token;
744 int graphStyle, index;
746 int existingAnnotations = 0;
747 // when true - will add new rows regardless of whether they are duplicate
748 // auto-annotation like consensus or conservation graphs
749 boolean overrideAutoAnnot = false;
750 if (al.getAlignmentAnnotation() != null)
752 existingAnnotations = al.getAlignmentAnnotation().length;
753 if (existingAnnotations > 0)
755 AlignmentAnnotation[] aa = al.getAlignmentAnnotation();
756 for (int aai = 0; aai < aa.length; aai++)
758 if (aa[aai].autoCalculated)
760 // make a note of the name and description
762 autoAnnotsKey(aa[aai], aa[aai].sequenceRef,
763 (aa[aai].groupRef == null ? null
764 : aa[aai].groupRef.getName())),
771 int alWidth = al.getWidth();
774 Annotation[] annotations;
775 AlignmentAnnotation annotation = null;
777 // First confirm this is an Annotation file
778 boolean jvAnnotationFile = false;
779 while ((line = in.readLine()) != null)
782 lastread = new String(line);
783 if (line.indexOf("#") == 0)
788 if (line.indexOf("JALVIEW_ANNOTATION") > -1)
790 jvAnnotationFile = true;
795 if (!jvAnnotationFile)
801 while ((line = in.readLine()) != null)
804 lastread = new String(line);
805 if (line.indexOf("#") == 0
806 || line.indexOf("JALVIEW_ANNOTATION") > -1
807 || line.length() == 0)
812 st = new StringTokenizer(line, "\t");
813 token = st.nextToken();
814 if (token.equalsIgnoreCase("COLOUR"))
816 // TODO: use graduated colour def'n here too
817 colourAnnotations(al, st.nextToken(), st.nextToken());
822 else if (token.equalsIgnoreCase(COMBINE))
824 // keep a record of current state and resolve groupRef at end
825 combineAnnotation_calls
827 { st, refSeq, groupRef });
831 else if (token.equalsIgnoreCase("ROWPROPERTIES"))
833 addRowProperties(al, st);
837 else if (token.equalsIgnoreCase(GRAPHLINE))
840 deferredAnnotation_calls
842 { GRAPHLINE, st, refSeq, groupRef });
847 else if (token.equalsIgnoreCase("SEQUENCE_REF"))
849 if (st.hasMoreTokens())
851 refSeq = al.findName(refSeqId = st.nextToken());
858 refSeqIndex = Integer.parseInt(st.nextToken());
863 "WARNING: SEQUENCE_REF index must be > 0 in AnnotationFile");
865 } catch (Exception ex)
877 else if (token.equalsIgnoreCase("GROUP_REF"))
879 // Group references could be forward or backwards, so they are
880 // resolved after the whole file is read in
882 if (st.hasMoreTokens())
884 groupRef = st.nextToken();
885 if (groupRef.length() < 1)
887 groupRef = null; // empty string
891 if (groupRefRows.get(groupRef) == null)
893 groupRefRows.put(groupRef, new Vector());
899 else if (token.equalsIgnoreCase("SEQUENCE_GROUP"))
906 else if (token.equalsIgnoreCase("PROPERTIES"))
908 addProperties(al, st);
913 else if (token.equalsIgnoreCase("BELOW_ALIGNMENT"))
915 setBelowAlignment(al, st);
919 else if (token.equalsIgnoreCase("ALIGNMENT"))
921 addAlignmentDetails(al, st);
925 // else if (token.equalsIgnoreCase("VIEW_DEF"))
927 // addOrSetView(al,st);
931 else if (token.equalsIgnoreCase("VIEW_SETREF"))
935 al.setSeqrep(refSeq);
940 else if (token.equalsIgnoreCase("VIEW_HIDECOLS"))
942 if (st.hasMoreTokens())
946 hidden = new HiddenColumns();
948 parseHideCols(hidden, st.nextToken());
953 else if (token.equalsIgnoreCase("HIDE_INSERTIONS"))
955 SequenceI sr = refSeq == null ? al.getSeqrep() : refSeq;
958 sr = al.getSequenceAt(0);
965 "Cannot process HIDE_INSERTIONS without an alignment view: Ignoring line: "
970 // consider deferring this till after the file has been parsed ?
971 hidden.hideList(sr.getInsertions());
978 // Parse out the annotation row
979 graphStyle = AlignmentAnnotation.getGraphValueFromString(token);
980 label = st.nextToken();
983 annotations = new Annotation[alWidth];
985 float score = Float.NaN;
987 if (st.hasMoreTokens())
989 line = st.nextToken();
991 if (line.indexOf("|") == -1)
994 if (st.hasMoreTokens())
996 line = st.nextToken();
1000 if (st.hasMoreTokens())
1002 // This must be the score
1003 score = Float.valueOf(st.nextToken()).floatValue();
1006 st = new StringTokenizer(line, "|", true);
1008 boolean emptyColumn = true;
1009 boolean onlyOneElement = (st.countTokens() == 1);
1011 while (st.hasMoreElements() && index < alWidth)
1013 token = st.nextToken().trim();
1019 score = Float.valueOf(token).floatValue();
1021 } catch (NumberFormatException ex)
1026 if (token.equals("|"))
1037 annotations[index++] = parseAnnotation(token, graphStyle);
1038 emptyColumn = false;
1044 annotation = new AlignmentAnnotation(label, description,
1045 (index == 0) ? null : annotations, 0, 0, graphStyle);
1047 annotation.score = score;
1048 if (!overrideAutoAnnot && autoAnnots
1049 .containsKey(autoAnnotsKey(annotation, refSeq, groupRef)))
1051 // skip - we've already got an automatic annotation of this type.
1054 // otherwise add it!
1058 annotation.belowAlignment = false;
1059 // make a copy of refSeq so we can find other matches in the alignment
1060 SequenceI referedSeq = refSeq;
1063 // copy before we do any mapping business.
1064 // TODO: verify that undo/redo with 1:many sequence associated
1065 // annotations can be undone correctly
1066 AlignmentAnnotation ann = new AlignmentAnnotation(annotation);
1067 annotation.createSequenceMapping(referedSeq, refSeqIndex,
1069 annotation.adjustForAlignment();
1070 referedSeq.addAlignmentAnnotation(annotation);
1071 al.addAnnotation(annotation);
1072 al.setAnnotationIndex(annotation,
1073 al.getAlignmentAnnotation().length - existingAnnotations
1075 if (groupRef != null)
1077 ((Vector) groupRefRows.get(groupRef)).addElement(annotation);
1079 // and recover our virgin copy to use again if necessary.
1082 } while (refSeqId != null && (referedSeq = al.findName(referedSeq,
1083 refSeqId, true)) != null);
1087 al.addAnnotation(annotation);
1088 al.setAnnotationIndex(annotation,
1089 al.getAlignmentAnnotation().length - existingAnnotations
1091 if (groupRef != null)
1093 ((Vector) groupRefRows.get(groupRef)).addElement(annotation);
1096 // and set modification flag
1099 // Resolve the groupRefs
1100 Hashtable<String, SequenceGroup> groupRefLookup = new Hashtable<>();
1101 Enumeration en = groupRefRows.keys();
1103 while (en.hasMoreElements())
1105 groupRef = (String) en.nextElement();
1106 boolean matched = false;
1107 // Resolve group: TODO: add a getGroupByName method to alignments
1108 for (SequenceGroup theGroup : al.getGroups())
1110 if (theGroup.getName().equals(groupRef))
1114 // TODO: specify and implement duplication of alignment annotation
1115 // for multiple group references.
1117 "Ignoring 1:many group reference mappings for group name '"
1123 Vector rowset = (Vector) groupRefRows.get(groupRef);
1124 groupRefLookup.put(groupRef, theGroup);
1125 if (rowset != null && rowset.size() > 0)
1127 AlignmentAnnotation alan = null;
1128 for (int elm = 0, elmSize = rowset
1129 .size(); elm < elmSize; elm++)
1131 alan = (AlignmentAnnotation) rowset.elementAt(elm);
1132 alan.groupRef = theGroup;
1138 ((Vector) groupRefRows.get(groupRef)).removeAllElements();
1140 // process any deferred attribute settings for each context
1141 for (Object[] _deferred_args : deferredAnnotation_calls)
1143 if (_deferred_args[0] == GRAPHLINE)
1145 addLine(al, (StringTokenizer) _deferred_args[1], // st
1146 (SequenceI) _deferred_args[2], // refSeq
1147 (_deferred_args[3] == null) ? null
1148 : groupRefLookup.get(_deferred_args[3]) // the
1156 // finally, combine all the annotation rows within each context.
1158 * number of combine statements in this annotation file. Used to create
1159 * new groups for combined annotation graphs without disturbing existing
1162 int combinecount = 0;
1163 for (Object[] _combine_args : combineAnnotation_calls)
1165 combineAnnotations(al, ++combinecount,
1166 (StringTokenizer) _combine_args[0], // st
1167 (SequenceI) _combine_args[1], // refSeq
1168 (_combine_args[2] == null) ? null
1169 : groupRefLookup.get(_combine_args[2]) // the reference
1178 private void parseHideCols(HiddenColumns hidden, String nextToken)
1180 StringTokenizer inval = new StringTokenizer(nextToken, ",");
1181 while (inval.hasMoreTokens())
1183 String range = inval.nextToken().trim();
1184 int from, to = range.indexOf("-");
1187 from = to = Integer.parseInt(range);
1190 hidden.hideColumns(from, to);
1195 from = Integer.parseInt(range.substring(0, to));
1196 if (to < range.length() - 1)
1198 to = Integer.parseInt(range.substring(to + 1));
1204 if (from > 0 && to >= from)
1206 hidden.hideColumns(from, to);
1212 private Object autoAnnotsKey(AlignmentAnnotation annotation,
1213 SequenceI refSeq, String groupRef)
1215 return annotation.graph + "\t" + annotation.label + "\t"
1216 + annotation.description + "\t"
1217 + (refSeq != null ? refSeq.getDisplayId(true) : "");
1220 Annotation parseAnnotation(String string, int graphStyle)
1222 // don't do the glyph test if we don't want secondary structure
1223 boolean hasSymbols = (graphStyle == AlignmentAnnotation.NO_GRAPH);
1224 String desc = null, displayChar = null;
1225 char ss = ' '; // secondaryStructure
1227 boolean parsedValue = false, dcset = false;
1230 Color colour = null;
1231 int i = string.indexOf("[");
1232 int j = string.indexOf("]");
1233 if (i > -1 && j > -1)
1235 colour = ColorUtils.parseColourString(string.substring(i + 1, j));
1236 if (i > 0 && string.charAt(i - 1) == ',')
1238 // clip the preceding comma as well
1241 string = string.substring(0, i) + string.substring(j + 1);
1244 StringTokenizer st = new StringTokenizer(string, ",", true);
1246 boolean seenContent = false;
1248 while (st.hasMoreTokens())
1251 token = st.nextToken().trim();
1252 if (token.equals(","))
1254 if (!seenContent && parsedValue && !dcset)
1256 // allow the value below the bar/line to be empty
1260 seenContent = false;
1272 displayChar = token;
1274 value = new Float(token).floatValue();
1277 } catch (NumberFormatException ex)
1283 if (token.length() == 1)
1285 displayChar = token;
1288 if (hasSymbols && (token.length() == 1
1289 && "()<>[]{}AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz"
1292 // Either this character represents a helix or sheet
1293 // or an integer which can be displayed
1294 ss = token.charAt(0);
1295 if (displayChar.equals(token.substring(0, 1)))
1300 else if (desc == null || (parsedValue && pass > 2))
1306 // if (!dcset && string.charAt(string.length() - 1) == ',')
1308 // displayChar = " "; // empty display char symbol.
1310 if (displayChar != null && desc != null && desc.length() == 1)
1312 if (displayChar.length() > 1)
1314 // switch desc and displayChar - legacy support
1315 String tmp = displayChar;
1321 if (displayChar.equals(desc))
1323 // duplicate label - hangover from the 'robust parser' above
1328 Annotation anot = new Annotation(displayChar, desc, ss, value);
1330 anot.colour = colour;
1335 void colourAnnotations(AlignmentI al, String label, String colour)
1337 Color awtColour = ColorUtils.parseColourString(colour);
1338 Annotation[] annotations;
1339 for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1341 if (al.getAlignmentAnnotation()[i].label.equalsIgnoreCase(label))
1343 annotations = al.getAlignmentAnnotation()[i].annotations;
1344 for (int j = 0; j < annotations.length; j++)
1346 if (annotations[j] != null)
1348 annotations[j].colour = awtColour;
1355 void combineAnnotations(AlignmentI al, int combineCount,
1356 StringTokenizer st, SequenceI seqRef, SequenceGroup groupRef)
1358 String group = st.nextToken();
1359 // First make sure we are not overwriting the graphIndex
1361 if (al.getAlignmentAnnotation() != null)
1363 for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1365 AlignmentAnnotation aa = al.getAlignmentAnnotation()[i];
1367 if (aa.graphGroup > graphGroup)
1369 // try to number graphGroups in order of occurence.
1370 graphGroup = aa.graphGroup + 1;
1372 if (aa.sequenceRef == seqRef && aa.groupRef == groupRef
1373 && aa.label.equalsIgnoreCase(group))
1375 if (aa.graphGroup > -1)
1377 graphGroup = aa.graphGroup;
1381 if (graphGroup <= combineCount)
1383 graphGroup = combineCount + 1;
1385 aa.graphGroup = graphGroup;
1391 // Now update groups
1392 while (st.hasMoreTokens())
1394 group = st.nextToken();
1395 for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1397 AlignmentAnnotation aa = al.getAlignmentAnnotation()[i];
1398 if (aa.sequenceRef == seqRef && aa.groupRef == groupRef
1399 && aa.label.equalsIgnoreCase(group))
1401 aa.graphGroup = graphGroup;
1410 "Couldn't combine annotations. None are added to alignment yet!");
1414 void addLine(AlignmentI al, StringTokenizer st, SequenceI seqRef,
1415 SequenceGroup groupRef)
1417 String group = st.nextToken();
1418 AlignmentAnnotation[] alannot = al.getAlignmentAnnotation();
1419 String nextToken = st.nextToken();
1423 value = Float.valueOf(nextToken);
1424 } catch (NumberFormatException e)
1426 System.err.println("line " + nlinesread + ": Threshold '" + nextToken
1427 + "' invalid, setting to zero");
1429 String label = st.hasMoreTokens() ? st.nextToken() : null;
1430 Color colour = null;
1431 if (st.hasMoreTokens())
1433 colour = ColorUtils.parseColourString(st.nextToken());
1435 if (alannot != null)
1437 for (int i = 0; i < alannot.length; i++)
1439 if (alannot[i].label.equalsIgnoreCase(group)
1440 && (seqRef == null || alannot[i].sequenceRef == seqRef)
1441 && (groupRef == null || alannot[i].groupRef == groupRef))
1443 alannot[i].setThreshold(new GraphLine(value, label, colour));
1449 void addGroup(AlignmentI al, StringTokenizer st)
1451 SequenceGroup sg = new SequenceGroup();
1452 sg.setName(st.nextToken());
1456 rng = st.nextToken();
1457 if (rng.length() > 0 && !rng.startsWith("*"))
1459 sg.setStartRes(Integer.parseInt(rng) - 1);
1465 rng = st.nextToken();
1466 if (rng.length() > 0 && !rng.startsWith("*"))
1468 sg.setEndRes(Integer.parseInt(rng) - 1);
1472 sg.setEndRes(al.getWidth() - 1);
1474 } catch (Exception e)
1477 "Couldn't parse Group Start or End Field as '*' or a valid column or sequence index: '"
1478 + rng + "' - assuming alignment width for group.");
1479 // assume group is full width
1481 sg.setEndRes(al.getWidth() - 1);
1484 String index = st.nextToken();
1485 if (index.equals("-1"))
1487 while (st.hasMoreElements())
1489 sg.addSequence(al.findName(st.nextToken()), false);
1494 StringTokenizer st2 = new StringTokenizer(index, ",");
1496 while (st2.hasMoreTokens())
1498 String tmp = st2.nextToken();
1499 if (tmp.equals("*"))
1501 for (int i = 0; i < al.getHeight(); i++)
1503 sg.addSequence(al.getSequenceAt(i), false);
1506 else if (tmp.indexOf("-") >= 0)
1508 StringTokenizer st3 = new StringTokenizer(tmp, "-");
1510 int start = (Integer.parseInt(st3.nextToken()));
1511 int end = (Integer.parseInt(st3.nextToken()));
1515 for (int i = start; i <= end; i++)
1517 sg.addSequence(al.getSequenceAt(i - 1), false);
1523 sg.addSequence(al.getSequenceAt(Integer.parseInt(tmp) - 1),
1531 sg.setStartRes(refSeq.findIndex(sg.getStartRes() + 1) - 1);
1532 sg.setEndRes(refSeq.findIndex(sg.getEndRes() + 1) - 1);
1533 sg.setSeqrep(refSeq);
1536 if (sg.getSize() > 0)
1542 void addRowProperties(AlignmentI al, StringTokenizer st)
1544 String label = st.nextToken(), keyValue, key, value;
1545 boolean scaletofit = false, centerlab = false, showalllabs = false;
1546 while (st.hasMoreTokens())
1548 keyValue = st.nextToken();
1549 key = keyValue.substring(0, keyValue.indexOf("="));
1550 value = keyValue.substring(keyValue.indexOf("=") + 1);
1551 if (key.equalsIgnoreCase("scaletofit"))
1553 scaletofit = Boolean.valueOf(value).booleanValue();
1555 if (key.equalsIgnoreCase("showalllabs"))
1557 showalllabs = Boolean.valueOf(value).booleanValue();
1559 if (key.equalsIgnoreCase("centrelabs"))
1561 centerlab = Boolean.valueOf(value).booleanValue();
1563 AlignmentAnnotation[] alr = al.getAlignmentAnnotation();
1566 for (int i = 0; i < alr.length; i++)
1568 if (alr[i].label.equalsIgnoreCase(label))
1570 alr[i].centreColLabels = centerlab;
1571 alr[i].scaleColLabel = scaletofit;
1572 alr[i].showAllColLabels = showalllabs;
1579 void addProperties(AlignmentI al, StringTokenizer st)
1582 // So far we have only added groups to the annotationHash,
1583 // the idea is in the future properties can be added to
1584 // alignments, other annotations etc
1585 if (al.getGroups() == null)
1590 String name = st.nextToken();
1591 SequenceGroup sg = null;
1592 for (SequenceGroup _sg : al.getGroups())
1594 if ((sg = _sg).getName().equals(name))
1606 String keyValue, key, value;
1607 ColourSchemeI def = sg.getColourScheme();
1608 while (st.hasMoreTokens())
1610 keyValue = st.nextToken();
1611 key = keyValue.substring(0, keyValue.indexOf("="));
1612 value = keyValue.substring(keyValue.indexOf("=") + 1);
1614 if (key.equalsIgnoreCase("description"))
1616 sg.setDescription(value);
1618 else if (key.equalsIgnoreCase("colour"))
1620 sg.cs.setColourScheme(
1621 ColourSchemeProperty.getColourScheme(al, value));
1623 else if (key.equalsIgnoreCase("pidThreshold"))
1625 sg.cs.setThreshold(Integer.parseInt(value), true);
1628 else if (key.equalsIgnoreCase("consThreshold"))
1630 sg.cs.setConservationInc(Integer.parseInt(value));
1631 Conservation c = new Conservation("Group", sg.getSequences(null),
1632 sg.getStartRes(), sg.getEndRes() + 1);
1635 c.verdict(false, 25); // TODO: refer to conservation percent threshold
1637 sg.cs.setConservation(c);
1640 else if (key.equalsIgnoreCase("outlineColour"))
1642 sg.setOutlineColour(ColorUtils.parseColourString(value));
1644 else if (key.equalsIgnoreCase("displayBoxes"))
1646 sg.setDisplayBoxes(Boolean.valueOf(value).booleanValue());
1648 else if (key.equalsIgnoreCase("showUnconserved"))
1650 sg.setShowNonconserved(Boolean.valueOf(value).booleanValue());
1652 else if (key.equalsIgnoreCase("displayText"))
1654 sg.setDisplayText(Boolean.valueOf(value).booleanValue());
1656 else if (key.equalsIgnoreCase("colourText"))
1658 sg.setColourText(Boolean.valueOf(value).booleanValue());
1660 else if (key.equalsIgnoreCase("textCol1"))
1662 sg.textColour = ColorUtils.parseColourString(value);
1664 else if (key.equalsIgnoreCase("textCol2"))
1666 sg.textColour2 = ColorUtils.parseColourString(value);
1668 else if (key.equalsIgnoreCase("textColThreshold"))
1670 sg.thresholdTextColour = Integer.parseInt(value);
1672 else if (key.equalsIgnoreCase("idColour"))
1674 Color idColour = ColorUtils.parseColourString(value);
1675 sg.setIdColour(idColour == null ? Color.black : idColour);
1677 else if (key.equalsIgnoreCase("hide"))
1679 // see bug https://mantis.lifesci.dundee.ac.uk/view.php?id=25847
1680 sg.setHidereps(true);
1682 else if (key.equalsIgnoreCase("hidecols"))
1684 // see bug https://mantis.lifesci.dundee.ac.uk/view.php?id=25847
1685 sg.setHideCols(true);
1687 sg.recalcConservation();
1689 if (sg.getColourScheme() == null)
1691 sg.setColourScheme(def);
1696 void setBelowAlignment(AlignmentI al, StringTokenizer st)
1699 AlignmentAnnotation aa, ala[] = al.getAlignmentAnnotation();
1703 "Warning - no annotation to set below for sequence associated annotation:");
1705 while (st.hasMoreTokens())
1707 token = st.nextToken();
1710 System.err.print(" " + token);
1714 for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1716 aa = al.getAlignmentAnnotation()[i];
1717 if (aa.sequenceRef == refSeq && aa.label.equals(token))
1719 aa.belowAlignment = true;
1726 System.err.print("\n");
1730 void addAlignmentDetails(AlignmentI al, StringTokenizer st)
1732 String keyValue, key, value;
1733 while (st.hasMoreTokens())
1735 keyValue = st.nextToken();
1736 key = keyValue.substring(0, keyValue.indexOf("="));
1737 value = keyValue.substring(keyValue.indexOf("=") + 1);
1738 al.setProperty(key, value);
1743 * Write annotations as a CSV file of the form 'label, value, value, ...' for
1746 * @param annotations
1747 * @return CSV file as a string.
1749 public String printCSVAnnotations(AlignmentAnnotation[] annotations)
1751 if (annotations == null)
1755 StringBuffer sp = new StringBuffer();
1756 for (int i = 0; i < annotations.length; i++)
1758 String atos = annotations[i].toString();
1762 int cp = atos.indexOf("\n", p);
1763 sp.append(annotations[i].label);
1767 sp.append(atos.substring(p, cp + 1));
1771 sp.append(atos.substring(p));
1777 return sp.toString();
1780 public String printAnnotationsForView(AlignViewportI viewport)
1782 return printAnnotations(
1783 viewport.isShowAnnotation()
1784 ? viewport.getAlignment().getAlignmentAnnotation()
1786 viewport.getAlignment().getGroups(),
1787 viewport.getAlignment().getProperties(),
1788 viewport.getAlignment().getHiddenColumns(),
1789 viewport.getAlignment(), null);
1792 public String printAnnotationsForAlignment(AlignmentI al)
1794 return printAnnotations(al.getAlignmentAnnotation(), al.getGroups(),
1795 al.getProperties(), null, al, null);