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, Map<Object, Object> properties,
145 HiddenColumns 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");
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 for (Object ko : properties.keySet())
451 String key = ko.toString();
455 text.append(properties.get(ko));
457 // TODO: output alignment visualization settings here if required
458 // iterate through one or more views, defining, marking columns and rows
459 // as visible/hidden, and emmitting view properties.
460 // View specific annotation is
463 return text.toString();
466 private Object writeGroup_Ref(SequenceGroup refGroup,
467 SequenceGroup next_refGroup)
469 if (next_refGroup == null)
472 if (refGroup != null)
474 text.append(newline);
475 text.append("GROUP_REF\t");
476 text.append("ALIGNMENT");
477 text.append(newline);
483 if (refGroup == null || refGroup != next_refGroup)
485 text.append(newline);
486 text.append("GROUP_REF\t");
487 text.append(next_refGroup.getName());
488 text.append(newline);
495 private boolean writeSequence_Ref(SequenceI refSeq, SequenceI next_refSeq)
498 if (next_refSeq == null)
502 text.append(newline);
503 text.append("SEQUENCE_REF\t");
504 text.append("ALIGNMENT");
505 text.append(newline);
511 if (refSeq == null || refSeq != next_refSeq)
513 text.append(newline);
514 text.append("SEQUENCE_REF\t");
515 text.append(next_refSeq.getName());
516 text.append(newline);
523 protected void printGroups(List<SequenceGroup> list)
525 SequenceI seqrep = null;
526 for (SequenceGroup sg : list)
530 text.append("SEQUENCE_GROUP\t" + sg.getName() + "\t"
531 + (sg.getStartRes() + 1) + "\t" + (sg.getEndRes() + 1)
537 seqrep = sg.getSeqrep();
538 text.append("SEQUENCE_REF\t");
539 text.append(seqrep.getName());
540 text.append(newline);
541 text.append("SEQUENCE_GROUP\t");
542 text.append(sg.getName());
544 text.append((seqrep.findPosition(sg.getStartRes())));
546 text.append((seqrep.findPosition(sg.getEndRes())));
550 for (int s = 0; s < sg.getSize(); s++)
552 text.append(sg.getSequenceAt(s).getName());
555 text.append(newline);
556 text.append("PROPERTIES\t");
557 text.append(sg.getName());
560 if (sg.getDescription() != null)
562 text.append("description=");
563 text.append(sg.getDescription());
568 text.append("colour=");
569 text.append(ColourSchemeProperty
570 .getColourName(sg.cs.getColourScheme()));
572 if (sg.cs.getThreshold() != 0)
574 text.append("pidThreshold=");
575 text.append(sg.cs.getThreshold());
577 if (sg.cs.conservationApplied())
579 text.append("consThreshold=");
580 text.append(sg.cs.getConservationInc());
584 text.append("outlineColour=");
585 text.append(jalview.util.Format.getHexString(sg.getOutlineColour()));
588 text.append("displayBoxes=");
589 text.append(sg.getDisplayBoxes());
591 text.append("displayText=");
592 text.append(sg.getDisplayText());
594 text.append("colourText=");
595 text.append(sg.getColourText());
597 text.append("showUnconserved=");
598 text.append(sg.getShowNonconserved());
600 if (sg.textColour != java.awt.Color.black)
602 text.append("textCol1=");
603 text.append(jalview.util.Format.getHexString(sg.textColour));
606 if (sg.textColour2 != java.awt.Color.white)
608 text.append("textCol2=");
609 text.append(jalview.util.Format.getHexString(sg.textColour2));
612 if (sg.thresholdTextColour != 0)
614 text.append("textColThreshold=");
615 text.append(sg.thresholdTextColour);
618 if (sg.idColour != null)
620 text.append("idColour=");
621 text.append(jalview.util.Format.getHexString(sg.idColour));
626 text.append("hide=true\t");
630 text.append("hidecols=true\t");
634 // terminate the last line and clear the sequence ref for the group
635 text.append(newline);
636 text.append("SEQUENCE_REF");
638 text.append(newline);
639 text.append(newline);
644 SequenceI refSeq = null;
646 String refSeqId = null;
648 public boolean annotateAlignmentView(AlignViewportI viewport, String file,
649 DataSourceType protocol)
651 ColumnSelection colSel = viewport.getColumnSelection();
652 HiddenColumns hidden = viewport.getAlignment().getHiddenColumns();
655 colSel = new ColumnSelection();
659 hidden = new HiddenColumns();
661 boolean rslt = readAnnotationFile(viewport.getAlignment(), hidden, file,
663 if (rslt && (colSel.hasSelectedColumns() || hidden.hasHiddenColumns()))
665 viewport.setColumnSelection(colSel);
666 viewport.getAlignment().setHiddenColumns(hidden);
672 public boolean readAnnotationFile(AlignmentI al, String file,
673 DataSourceType sourceType)
675 return readAnnotationFile(al, null, file, sourceType);
678 public boolean readAnnotationFile(AlignmentI al, HiddenColumns hidden,
679 String file, DataSourceType sourceType)
681 BufferedReader in = null;
684 if (sourceType == DataSourceType.FILE)
686 in = new BufferedReader(new FileReader(file));
688 else if (sourceType == DataSourceType.URL)
690 URL url = new URL(file);
691 in = new BufferedReader(new InputStreamReader(url.openStream()));
693 else if (sourceType == DataSourceType.PASTE)
695 in = new BufferedReader(new StringReader(file));
697 else if (sourceType == DataSourceType.CLASSLOADER)
699 java.io.InputStream is = getClass().getResourceAsStream("/" + file);
702 in = new BufferedReader(new java.io.InputStreamReader(is));
707 return parseAnnotationFrom(al, hidden, in);
710 } catch (Exception ex)
712 ex.printStackTrace();
713 System.out.println("Problem reading annotation file: " + ex);
716 System.out.println("Last read line " + nlinesread + ": '" + lastread
717 + "' (first 80 chars) ...");
726 String lastread = "";
728 private static String GRAPHLINE = "GRAPHLINE", COMBINE = "COMBINE";
730 public boolean parseAnnotationFrom(AlignmentI al, HiddenColumns hidden,
731 BufferedReader in) throws Exception
734 ArrayList<Object[]> combineAnnotation_calls = new ArrayList<>();
735 ArrayList<Object[]> deferredAnnotation_calls = new ArrayList<>();
736 boolean modified = false;
737 String groupRef = null;
738 Hashtable groupRefRows = new Hashtable();
740 Hashtable autoAnnots = new Hashtable();
742 String line, label, description, token;
743 int graphStyle, index;
745 int existingAnnotations = 0;
746 // when true - will add new rows regardless of whether they are duplicate
747 // auto-annotation like consensus or conservation graphs
748 boolean overrideAutoAnnot = false;
749 if (al.getAlignmentAnnotation() != null)
751 existingAnnotations = al.getAlignmentAnnotation().length;
752 if (existingAnnotations > 0)
754 AlignmentAnnotation[] aa = al.getAlignmentAnnotation();
755 for (int aai = 0; aai < aa.length; aai++)
757 if (aa[aai].autoCalculated)
759 // make a note of the name and description
761 autoAnnotsKey(aa[aai], aa[aai].sequenceRef,
762 (aa[aai].groupRef == null ? null
763 : aa[aai].groupRef.getName())),
770 int alWidth = al.getWidth();
773 Annotation[] annotations;
774 AlignmentAnnotation annotation = null;
776 // First confirm this is an Annotation file
777 boolean jvAnnotationFile = false;
778 while ((line = in.readLine()) != null)
781 lastread = new String(line);
782 if (line.indexOf("#") == 0)
787 if (line.indexOf("JALVIEW_ANNOTATION") > -1)
789 jvAnnotationFile = true;
794 if (!jvAnnotationFile)
800 while ((line = in.readLine()) != null)
803 lastread = new String(line);
804 if (line.indexOf("#") == 0
805 || line.indexOf("JALVIEW_ANNOTATION") > -1
806 || line.length() == 0)
811 st = new StringTokenizer(line, "\t");
812 token = st.nextToken();
813 if (token.equalsIgnoreCase("COLOUR"))
815 // TODO: use graduated colour def'n here too
816 colourAnnotations(al, st.nextToken(), st.nextToken());
821 else if (token.equalsIgnoreCase(COMBINE))
823 // keep a record of current state and resolve groupRef at end
824 combineAnnotation_calls
826 { st, refSeq, groupRef });
830 else if (token.equalsIgnoreCase("ROWPROPERTIES"))
832 addRowProperties(al, st);
836 else if (token.equalsIgnoreCase(GRAPHLINE))
839 deferredAnnotation_calls
841 { GRAPHLINE, st, refSeq, groupRef });
846 else if (token.equalsIgnoreCase("SEQUENCE_REF"))
848 if (st.hasMoreTokens())
850 refSeq = al.findName(refSeqId = st.nextToken());
857 refSeqIndex = Integer.parseInt(st.nextToken());
862 "WARNING: SEQUENCE_REF index must be > 0 in AnnotationFile");
864 } catch (Exception ex)
876 else if (token.equalsIgnoreCase("GROUP_REF"))
878 // Group references could be forward or backwards, so they are
879 // resolved after the whole file is read in
881 if (st.hasMoreTokens())
883 groupRef = st.nextToken();
884 if (groupRef.length() < 1)
886 groupRef = null; // empty string
890 if (groupRefRows.get(groupRef) == null)
892 groupRefRows.put(groupRef, new Vector());
898 else if (token.equalsIgnoreCase("SEQUENCE_GROUP"))
905 else if (token.equalsIgnoreCase("PROPERTIES"))
907 addProperties(al, st);
912 else if (token.equalsIgnoreCase("BELOW_ALIGNMENT"))
914 setBelowAlignment(al, st);
918 else if (token.equalsIgnoreCase("ALIGNMENT"))
920 addAlignmentDetails(al, st);
924 // else if (token.equalsIgnoreCase("VIEW_DEF"))
926 // addOrSetView(al,st);
930 else if (token.equalsIgnoreCase("VIEW_SETREF"))
934 al.setSeqrep(refSeq);
939 else if (token.equalsIgnoreCase("VIEW_HIDECOLS"))
941 if (st.hasMoreTokens())
945 hidden = new HiddenColumns();
947 parseHideCols(hidden, st.nextToken());
952 else if (token.equalsIgnoreCase("HIDE_INSERTIONS"))
954 SequenceI sr = refSeq == null ? al.getSeqrep() : refSeq;
957 sr = al.getSequenceAt(0);
964 "Cannot process HIDE_INSERTIONS without an alignment view: Ignoring line: "
969 // consider deferring this till after the file has been parsed ?
970 hidden.hideInsertionsFor(sr);
977 // Parse out the annotation row
978 graphStyle = AlignmentAnnotation.getGraphValueFromString(token);
979 label = st.nextToken();
982 annotations = new Annotation[alWidth];
984 float score = Float.NaN;
986 if (st.hasMoreTokens())
988 line = st.nextToken();
990 if (line.indexOf("|") == -1)
993 if (st.hasMoreTokens())
995 line = st.nextToken();
999 if (st.hasMoreTokens())
1001 // This must be the score
1002 score = Float.valueOf(st.nextToken()).floatValue();
1005 st = new StringTokenizer(line, "|", true);
1007 boolean emptyColumn = true;
1008 boolean onlyOneElement = (st.countTokens() == 1);
1010 while (st.hasMoreElements() && index < alWidth)
1012 token = st.nextToken().trim();
1018 score = Float.valueOf(token).floatValue();
1020 } catch (NumberFormatException ex)
1025 if (token.equals("|"))
1036 annotations[index++] = parseAnnotation(token, graphStyle);
1037 emptyColumn = false;
1043 annotation = new AlignmentAnnotation(label, description,
1044 (index == 0) ? null : annotations, 0, 0, graphStyle);
1046 annotation.score = score;
1047 if (!overrideAutoAnnot && autoAnnots
1048 .containsKey(autoAnnotsKey(annotation, refSeq, groupRef)))
1050 // skip - we've already got an automatic annotation of this type.
1053 // otherwise add it!
1057 annotation.belowAlignment = false;
1058 // make a copy of refSeq so we can find other matches in the alignment
1059 SequenceI referedSeq = refSeq;
1062 // copy before we do any mapping business.
1063 // TODO: verify that undo/redo with 1:many sequence associated
1064 // annotations can be undone correctly
1065 AlignmentAnnotation ann = new AlignmentAnnotation(annotation);
1066 annotation.createSequenceMapping(referedSeq, refSeqIndex,
1068 annotation.adjustForAlignment();
1069 referedSeq.addAlignmentAnnotation(annotation);
1070 al.addAnnotation(annotation);
1071 al.setAnnotationIndex(annotation,
1072 al.getAlignmentAnnotation().length - existingAnnotations
1074 if (groupRef != null)
1076 ((Vector) groupRefRows.get(groupRef)).addElement(annotation);
1078 // and recover our virgin copy to use again if necessary.
1081 } while (refSeqId != null && (referedSeq = al.findName(referedSeq,
1082 refSeqId, true)) != null);
1086 al.addAnnotation(annotation);
1087 al.setAnnotationIndex(annotation,
1088 al.getAlignmentAnnotation().length - existingAnnotations
1090 if (groupRef != null)
1092 ((Vector) groupRefRows.get(groupRef)).addElement(annotation);
1095 // and set modification flag
1098 // Resolve the groupRefs
1099 Hashtable<String, SequenceGroup> groupRefLookup = new Hashtable<>();
1100 Enumeration en = groupRefRows.keys();
1102 while (en.hasMoreElements())
1104 groupRef = (String) en.nextElement();
1105 boolean matched = false;
1106 // Resolve group: TODO: add a getGroupByName method to alignments
1107 for (SequenceGroup theGroup : al.getGroups())
1109 if (theGroup.getName().equals(groupRef))
1113 // TODO: specify and implement duplication of alignment annotation
1114 // for multiple group references.
1116 "Ignoring 1:many group reference mappings for group name '"
1122 Vector rowset = (Vector) groupRefRows.get(groupRef);
1123 groupRefLookup.put(groupRef, theGroup);
1124 if (rowset != null && rowset.size() > 0)
1126 AlignmentAnnotation alan = null;
1127 for (int elm = 0, elmSize = rowset
1128 .size(); elm < elmSize; elm++)
1130 alan = (AlignmentAnnotation) rowset.elementAt(elm);
1131 alan.groupRef = theGroup;
1137 ((Vector) groupRefRows.get(groupRef)).removeAllElements();
1139 // process any deferred attribute settings for each context
1140 for (Object[] _deferred_args : deferredAnnotation_calls)
1142 if (_deferred_args[0] == GRAPHLINE)
1144 addLine(al, (StringTokenizer) _deferred_args[1], // st
1145 (SequenceI) _deferred_args[2], // refSeq
1146 (_deferred_args[3] == null) ? null
1147 : groupRefLookup.get(_deferred_args[3]) // the
1155 // finally, combine all the annotation rows within each context.
1157 * number of combine statements in this annotation file. Used to create
1158 * new groups for combined annotation graphs without disturbing existing
1161 int combinecount = 0;
1162 for (Object[] _combine_args : combineAnnotation_calls)
1164 combineAnnotations(al, ++combinecount,
1165 (StringTokenizer) _combine_args[0], // st
1166 (SequenceI) _combine_args[1], // refSeq
1167 (_combine_args[2] == null) ? null
1168 : groupRefLookup.get(_combine_args[2]) // the reference
1177 private void parseHideCols(HiddenColumns hidden, String nextToken)
1179 StringTokenizer inval = new StringTokenizer(nextToken, ",");
1180 while (inval.hasMoreTokens())
1182 String range = inval.nextToken().trim();
1183 int from, to = range.indexOf("-");
1186 from = to = Integer.parseInt(range);
1189 hidden.hideColumns(from, to);
1194 from = Integer.parseInt(range.substring(0, to));
1195 if (to < range.length() - 1)
1197 to = Integer.parseInt(range.substring(to + 1));
1203 if (from > 0 && to >= from)
1205 hidden.hideColumns(from, to);
1211 private Object autoAnnotsKey(AlignmentAnnotation annotation,
1212 SequenceI refSeq, String groupRef)
1214 return annotation.graph + "\t" + annotation.label + "\t"
1215 + annotation.description + "\t"
1216 + (refSeq != null ? refSeq.getDisplayId(true) : "");
1219 Annotation parseAnnotation(String string, int graphStyle)
1221 // don't do the glyph test if we don't want secondary structure
1222 boolean hasSymbols = (graphStyle == AlignmentAnnotation.NO_GRAPH);
1223 String desc = null, displayChar = null;
1224 char ss = ' '; // secondaryStructure
1226 boolean parsedValue = false, dcset = false;
1229 Color colour = null;
1230 int i = string.indexOf("[");
1231 int j = string.indexOf("]");
1232 if (i > -1 && j > -1)
1234 colour = ColorUtils.parseColourString(string.substring(i + 1, j));
1235 if (i > 0 && string.charAt(i - 1) == ',')
1237 // clip the preceding comma as well
1240 string = string.substring(0, i) + string.substring(j + 1);
1243 StringTokenizer st = new StringTokenizer(string, ",", true);
1245 boolean seenContent = false;
1247 while (st.hasMoreTokens())
1250 token = st.nextToken().trim();
1251 if (token.equals(","))
1253 if (!seenContent && parsedValue && !dcset)
1255 // allow the value below the bar/line to be empty
1259 seenContent = false;
1271 displayChar = token;
1273 value = new Float(token).floatValue();
1276 } catch (NumberFormatException ex)
1282 if (token.length() == 1)
1284 displayChar = token;
1287 if (hasSymbols && (token.length() == 1
1288 && "()<>[]{}AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz"
1291 // Either this character represents a helix or sheet
1292 // or an integer which can be displayed
1293 ss = token.charAt(0);
1294 if (displayChar.equals(token.substring(0, 1)))
1299 else if (desc == null || (parsedValue && pass > 2))
1305 // if (!dcset && string.charAt(string.length() - 1) == ',')
1307 // displayChar = " "; // empty display char symbol.
1309 if (displayChar != null && desc != null && desc.length() == 1)
1311 if (displayChar.length() > 1)
1313 // switch desc and displayChar - legacy support
1314 String tmp = displayChar;
1320 if (displayChar.equals(desc))
1322 // duplicate label - hangover from the 'robust parser' above
1327 Annotation anot = new Annotation(displayChar, desc, ss, value);
1329 anot.colour = colour;
1334 void colourAnnotations(AlignmentI al, String label, String colour)
1336 Color awtColour = ColorUtils.parseColourString(colour);
1337 Annotation[] annotations;
1338 for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1340 if (al.getAlignmentAnnotation()[i].label.equalsIgnoreCase(label))
1342 annotations = al.getAlignmentAnnotation()[i].annotations;
1343 for (int j = 0; j < annotations.length; j++)
1345 if (annotations[j] != null)
1347 annotations[j].colour = awtColour;
1354 void combineAnnotations(AlignmentI al, int combineCount,
1355 StringTokenizer st, SequenceI seqRef, SequenceGroup groupRef)
1357 String group = st.nextToken();
1358 // First make sure we are not overwriting the graphIndex
1360 if (al.getAlignmentAnnotation() != null)
1362 for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1364 AlignmentAnnotation aa = al.getAlignmentAnnotation()[i];
1366 if (aa.graphGroup > graphGroup)
1368 // try to number graphGroups in order of occurence.
1369 graphGroup = aa.graphGroup + 1;
1371 if (aa.sequenceRef == seqRef && aa.groupRef == groupRef
1372 && aa.label.equalsIgnoreCase(group))
1374 if (aa.graphGroup > -1)
1376 graphGroup = aa.graphGroup;
1380 if (graphGroup <= combineCount)
1382 graphGroup = combineCount + 1;
1384 aa.graphGroup = graphGroup;
1390 // Now update groups
1391 while (st.hasMoreTokens())
1393 group = st.nextToken();
1394 for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1396 AlignmentAnnotation aa = al.getAlignmentAnnotation()[i];
1397 if (aa.sequenceRef == seqRef && aa.groupRef == groupRef
1398 && aa.label.equalsIgnoreCase(group))
1400 aa.graphGroup = graphGroup;
1409 "Couldn't combine annotations. None are added to alignment yet!");
1413 void addLine(AlignmentI al, StringTokenizer st, SequenceI seqRef,
1414 SequenceGroup groupRef)
1416 String group = st.nextToken();
1417 AlignmentAnnotation[] alannot = al.getAlignmentAnnotation();
1418 String nextToken = st.nextToken();
1422 value = Float.valueOf(nextToken);
1423 } catch (NumberFormatException e)
1425 System.err.println("line " + nlinesread + ": Threshold '" + nextToken
1426 + "' invalid, setting to zero");
1428 String label = st.hasMoreTokens() ? st.nextToken() : null;
1429 Color colour = null;
1430 if (st.hasMoreTokens())
1432 colour = ColorUtils.parseColourString(st.nextToken());
1434 if (alannot != null)
1436 for (int i = 0; i < alannot.length; i++)
1438 if (alannot[i].label.equalsIgnoreCase(group)
1439 && (seqRef == null || alannot[i].sequenceRef == seqRef)
1440 && (groupRef == null || alannot[i].groupRef == groupRef))
1442 alannot[i].setThreshold(new GraphLine(value, label, colour));
1448 void addGroup(AlignmentI al, StringTokenizer st)
1450 SequenceGroup sg = new SequenceGroup();
1451 sg.setName(st.nextToken());
1455 rng = st.nextToken();
1456 if (rng.length() > 0 && !rng.startsWith("*"))
1458 sg.setStartRes(Integer.parseInt(rng) - 1);
1464 rng = st.nextToken();
1465 if (rng.length() > 0 && !rng.startsWith("*"))
1467 sg.setEndRes(Integer.parseInt(rng) - 1);
1471 sg.setEndRes(al.getWidth() - 1);
1473 } catch (Exception e)
1476 "Couldn't parse Group Start or End Field as '*' or a valid column or sequence index: '"
1477 + rng + "' - assuming alignment width for group.");
1478 // assume group is full width
1480 sg.setEndRes(al.getWidth() - 1);
1483 String index = st.nextToken();
1484 if (index.equals("-1"))
1486 while (st.hasMoreElements())
1488 sg.addSequence(al.findName(st.nextToken()), false);
1493 StringTokenizer st2 = new StringTokenizer(index, ",");
1495 while (st2.hasMoreTokens())
1497 String tmp = st2.nextToken();
1498 if (tmp.equals("*"))
1500 for (int i = 0; i < al.getHeight(); i++)
1502 sg.addSequence(al.getSequenceAt(i), false);
1505 else if (tmp.indexOf("-") >= 0)
1507 StringTokenizer st3 = new StringTokenizer(tmp, "-");
1509 int start = (Integer.parseInt(st3.nextToken()));
1510 int end = (Integer.parseInt(st3.nextToken()));
1514 for (int i = start; i <= end; i++)
1516 sg.addSequence(al.getSequenceAt(i - 1), false);
1522 sg.addSequence(al.getSequenceAt(Integer.parseInt(tmp) - 1),
1530 sg.setStartRes(refSeq.findIndex(sg.getStartRes() + 1) - 1);
1531 sg.setEndRes(refSeq.findIndex(sg.getEndRes() + 1) - 1);
1532 sg.setSeqrep(refSeq);
1535 if (sg.getSize() > 0)
1541 void addRowProperties(AlignmentI al, StringTokenizer st)
1543 String label = st.nextToken(), keyValue, key, value;
1544 boolean scaletofit = false, centerlab = false, showalllabs = false;
1545 while (st.hasMoreTokens())
1547 keyValue = st.nextToken();
1548 key = keyValue.substring(0, keyValue.indexOf("="));
1549 value = keyValue.substring(keyValue.indexOf("=") + 1);
1550 if (key.equalsIgnoreCase("scaletofit"))
1552 scaletofit = Boolean.valueOf(value).booleanValue();
1554 if (key.equalsIgnoreCase("showalllabs"))
1556 showalllabs = Boolean.valueOf(value).booleanValue();
1558 if (key.equalsIgnoreCase("centrelabs"))
1560 centerlab = Boolean.valueOf(value).booleanValue();
1562 AlignmentAnnotation[] alr = al.getAlignmentAnnotation();
1565 for (int i = 0; i < alr.length; i++)
1567 if (alr[i].label.equalsIgnoreCase(label))
1569 alr[i].centreColLabels = centerlab;
1570 alr[i].scaleColLabel = scaletofit;
1571 alr[i].showAllColLabels = showalllabs;
1578 void addProperties(AlignmentI al, StringTokenizer st)
1581 // So far we have only added groups to the annotationHash,
1582 // the idea is in the future properties can be added to
1583 // alignments, other annotations etc
1584 if (al.getGroups() == null)
1589 String name = st.nextToken();
1590 SequenceGroup sg = null;
1591 for (SequenceGroup _sg : al.getGroups())
1593 if ((sg = _sg).getName().equals(name))
1605 String keyValue, key, value;
1606 ColourSchemeI def = sg.getColourScheme();
1607 while (st.hasMoreTokens())
1609 keyValue = st.nextToken();
1610 key = keyValue.substring(0, keyValue.indexOf("="));
1611 value = keyValue.substring(keyValue.indexOf("=") + 1);
1613 if (key.equalsIgnoreCase("description"))
1615 sg.setDescription(value);
1617 else if (key.equalsIgnoreCase("colour"))
1619 sg.cs.setColourScheme(
1620 ColourSchemeProperty.getColourScheme(al, value));
1622 else if (key.equalsIgnoreCase("pidThreshold"))
1624 sg.cs.setThreshold(Integer.parseInt(value), true);
1627 else if (key.equalsIgnoreCase("consThreshold"))
1629 sg.cs.setConservationInc(Integer.parseInt(value));
1630 Conservation c = new Conservation("Group", sg.getSequences(null),
1631 sg.getStartRes(), sg.getEndRes() + 1);
1634 c.verdict(false, 25); // TODO: refer to conservation percent threshold
1636 sg.cs.setConservation(c);
1639 else if (key.equalsIgnoreCase("outlineColour"))
1641 sg.setOutlineColour(ColorUtils.parseColourString(value));
1643 else if (key.equalsIgnoreCase("displayBoxes"))
1645 sg.setDisplayBoxes(Boolean.valueOf(value).booleanValue());
1647 else if (key.equalsIgnoreCase("showUnconserved"))
1649 sg.setShowNonconserved(Boolean.valueOf(value).booleanValue());
1651 else if (key.equalsIgnoreCase("displayText"))
1653 sg.setDisplayText(Boolean.valueOf(value).booleanValue());
1655 else if (key.equalsIgnoreCase("colourText"))
1657 sg.setColourText(Boolean.valueOf(value).booleanValue());
1659 else if (key.equalsIgnoreCase("textCol1"))
1661 sg.textColour = ColorUtils.parseColourString(value);
1663 else if (key.equalsIgnoreCase("textCol2"))
1665 sg.textColour2 = ColorUtils.parseColourString(value);
1667 else if (key.equalsIgnoreCase("textColThreshold"))
1669 sg.thresholdTextColour = Integer.parseInt(value);
1671 else if (key.equalsIgnoreCase("idColour"))
1673 Color idColour = ColorUtils.parseColourString(value);
1674 sg.setIdColour(idColour == null ? Color.black : idColour);
1676 else if (key.equalsIgnoreCase("hide"))
1678 // see bug https://mantis.lifesci.dundee.ac.uk/view.php?id=25847
1679 sg.setHidereps(true);
1681 else if (key.equalsIgnoreCase("hidecols"))
1683 // see bug https://mantis.lifesci.dundee.ac.uk/view.php?id=25847
1684 sg.setHideCols(true);
1686 sg.recalcConservation();
1688 if (sg.getColourScheme() == null)
1690 sg.setColourScheme(def);
1695 void setBelowAlignment(AlignmentI al, StringTokenizer st)
1698 AlignmentAnnotation aa, ala[] = al.getAlignmentAnnotation();
1702 "Warning - no annotation to set below for sequence associated annotation:");
1704 while (st.hasMoreTokens())
1706 token = st.nextToken();
1709 System.err.print(" " + token);
1713 for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1715 aa = al.getAlignmentAnnotation()[i];
1716 if (aa.sequenceRef == refSeq && aa.label.equals(token))
1718 aa.belowAlignment = true;
1725 System.err.print("\n");
1729 void addAlignmentDetails(AlignmentI al, StringTokenizer st)
1731 String keyValue, key, value;
1732 while (st.hasMoreTokens())
1734 keyValue = st.nextToken();
1735 key = keyValue.substring(0, keyValue.indexOf("="));
1736 value = keyValue.substring(keyValue.indexOf("=") + 1);
1737 al.setProperty(key, value);
1742 * Write annotations as a CSV file of the form 'label, value, value, ...' for
1745 * @param annotations
1746 * @return CSV file as a string.
1748 public String printCSVAnnotations(AlignmentAnnotation[] annotations)
1750 if (annotations == null)
1754 StringBuffer sp = new StringBuffer();
1755 for (int i = 0; i < annotations.length; i++)
1757 String atos = annotations[i].toString();
1761 int cp = atos.indexOf("\n", p);
1762 sp.append(annotations[i].label);
1766 sp.append(atos.substring(p, cp + 1));
1770 sp.append(atos.substring(p));
1776 return sp.toString();
1779 public String printAnnotationsForView(AlignViewportI viewport)
1781 return printAnnotations(
1782 viewport.isShowAnnotation()
1783 ? viewport.getAlignment().getAlignmentAnnotation()
1785 viewport.getAlignment().getGroups(),
1786 viewport.getAlignment().getProperties(),
1787 viewport.getAlignment().getHiddenColumns(),
1788 viewport.getAlignment(), null);
1791 public String printAnnotationsForAlignment(AlignmentI al)
1793 return printAnnotations(al.getAlignmentAnnotation(), al.getGroups(),
1794 al.getProperties(), null, al, null);