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 java.awt.Color;
24 import java.io.BufferedReader;
25 import java.util.ArrayList;
26 import java.util.BitSet;
27 import java.util.Enumeration;
28 import java.util.HashMap;
29 import java.util.Hashtable;
30 import java.util.List;
32 import java.util.StringTokenizer;
33 import java.util.Vector;
35 import jalview.analysis.Conservation;
36 import jalview.api.AlignViewportI;
37 import jalview.datamodel.Alignment;
38 import jalview.datamodel.AlignmentAnnotation;
39 import jalview.datamodel.AlignmentI;
40 import jalview.datamodel.Annotation;
41 import jalview.datamodel.ColumnSelection;
42 import jalview.datamodel.GraphLine;
43 import jalview.datamodel.HiddenColumns;
44 import jalview.datamodel.HiddenSequences;
45 import jalview.datamodel.SequenceGroup;
46 import jalview.datamodel.SequenceI;
47 import jalview.schemes.ColourSchemeI;
48 import jalview.schemes.ColourSchemeProperty;
49 import jalview.util.ColorUtils;
51 public class AnnotationFile
53 private static final String GRAPHLINE = "GRAPHLINE";
55 private static final String COMBINE = "COMBINE";
57 protected String newline = System.getProperty("line.separator");
59 private StringBuffer text;
61 private SequenceI refSeq = null;
63 private String refSeqId = null;
65 private long nlinesread = 0;
67 private String lastread = "";
70 * default calcId string for new annotation
72 private String defaultCalcId = null;
77 public AnnotationFile()
84 text = new StringBuffer("JALVIEW_ANNOTATION" + newline + "# Created: "
85 + new java.util.Date() + newline + newline);
91 * convenience method for pre-2.9 annotation files which have no view, hidden
92 * columns or hidden row keywords.
97 * @return annotation file as a string.
99 public String printAnnotations(AlignmentAnnotation[] annotations,
100 List<SequenceGroup> list, Hashtable properties)
102 return printAnnotations(annotations, list, properties, null, null,
108 * hold all the information about a particular view definition read from or
109 * written out in an annotations file.
113 // TODO this class is not used - remove?
114 public final String viewname;
116 public final HiddenSequences hidseqs;
118 public final HiddenColumns hiddencols;
120 public final Hashtable hiddenRepSeqs;
122 public ViewDef(String vname, HiddenSequences hseqs, HiddenColumns hcols,
125 this.viewname = vname;
126 this.hidseqs = hseqs;
127 this.hiddencols = hcols;
128 this.hiddenRepSeqs = hRepSeqs;
133 * Prepare an annotation file given a set of annotations, groups, alignment
134 * properties and views.
140 * @return annotation file
142 public String printAnnotations(AlignmentAnnotation[] annotations,
143 List<SequenceGroup> list, Hashtable properties, HiddenColumns cs,
144 AlignmentI al, ViewDef view)
148 if (view.viewname != null)
150 text.append("VIEW_DEF\t" + view.viewname + "\n");
154 // list = view.visibleGroups;
158 cs = view.hiddencols;
162 // add hidden rep sequences.
165 // first target - store and restore all settings for a view.
166 if (al != null && al.hasSeqrep())
168 text.append("VIEW_SETREF\t" + al.getSeqrep().getName() + "\n");
170 if (cs != null && cs.hasHiddenColumns())
172 text.append("VIEW_HIDECOLS\t");
174 String regions = cs.regionsToString(",", "-");
175 text.append(regions);
178 // TODO: allow efficient recovery of annotation data shown in several
180 if (annotations != null)
182 boolean oneColour = true;
183 AlignmentAnnotation row;
185 SequenceI refSeq = null;
186 SequenceGroup refGroup = null;
188 StringBuffer colours = new StringBuffer();
189 StringBuffer graphLine = new StringBuffer();
190 StringBuffer rowprops = new StringBuffer();
191 Hashtable<Integer, String> graphGroup = new Hashtable<>();
192 Hashtable<Integer, Object[]> graphGroup_refs = new Hashtable<>();
193 BitSet graphGroupSeen = new BitSet();
195 java.awt.Color color;
197 for (int i = 0; i < annotations.length; i++)
199 row = annotations[i];
201 if (!row.visible && !row.hasScore() && !(row.graphGroup > -1
202 && graphGroupSeen.get(row.graphGroup)))
210 // mark any sequence references for the row
211 writeSequence_Ref(refSeq, row.sequenceRef);
212 refSeq = row.sequenceRef;
213 // mark any group references for the row
214 writeGroup_Ref(refGroup, row.groupRef);
215 refGroup = row.groupRef;
217 boolean hasGlyphs = row.hasIcons, hasLabels = row.hasText,
218 hasValues = row.hasScore, hasText = false;
219 // lookahead to check what the annotation row object actually contains.
220 for (int j = 0; row.annotations != null
221 && j < row.annotations.length
222 && (!hasGlyphs || !hasLabels || !hasValues); j++)
224 if (row.annotations[j] != null)
226 hasLabels |= (row.annotations[j].displayCharacter != null
227 && row.annotations[j].displayCharacter.length() > 0
228 && !row.annotations[j].displayCharacter.equals(" "));
229 hasGlyphs |= (row.annotations[j].secondaryStructure != 0
230 && row.annotations[j].secondaryStructure != ' ');
231 hasValues |= (!Float.isNaN(row.annotations[j].value)); // NaNs can't
234 hasText |= (row.annotations[j].description != null
235 && row.annotations[j].description.length() > 0);
239 if (row.graph == AlignmentAnnotation.NO_GRAPH)
241 text.append("NO_GRAPH\t");
242 hasValues = false; // only secondary structure
243 // hasLabels = false; // and annotation description string.
247 if (row.graph == AlignmentAnnotation.BAR_GRAPH)
249 text.append("BAR_GRAPH\t");
250 hasGlyphs = false; // no secondary structure
253 else if (row.graph == AlignmentAnnotation.LINE_GRAPH)
255 hasGlyphs = false; // no secondary structure
256 text.append("LINE_GRAPH\t");
259 if (row.getThreshold() != null)
261 graphLine.append("GRAPHLINE\t");
262 graphLine.append(row.label);
263 graphLine.append("\t");
264 graphLine.append(row.getThreshold().value);
265 graphLine.append("\t");
266 graphLine.append(row.getThreshold().label);
267 graphLine.append("\t");
268 graphLine.append(jalview.util.Format
269 .getHexString(row.getThreshold().colour));
270 graphLine.append(newline);
273 if (row.graphGroup > -1)
275 graphGroupSeen.set(row.graphGroup);
276 Integer key = Integer.valueOf(row.graphGroup);
277 if (graphGroup.containsKey(key))
279 graphGroup.put(key, graphGroup.get(key) + "\t" + row.label);
284 graphGroup_refs.put(key, new Object[] { refSeq, refGroup });
285 graphGroup.put(key, row.label);
290 text.append(row.label + "\t");
291 if (row.description != null)
293 text.append(row.description + "\t");
295 for (int j = 0; row.annotations != null
296 && j < row.annotations.length; j++)
299 && jalview.util.Comparison.isGap(refSeq.getCharAt(j)))
304 if (row.annotations[j] != null)
307 if (hasGlyphs) // could be also hasGlyphs || ...
311 if (row.annotations[j].secondaryStructure != ' ')
313 // only write out the field if its not whitespace.
314 text.append(row.annotations[j].secondaryStructure);
320 if (!Float.isNaN(row.annotations[j].value))
322 text.append(comma + row.annotations[j].value);
326 // System.err.println("Skipping NaN - not valid value.");
327 text.append(comma + 0f);// row.annotations[j].value);
333 // TODO: labels are emitted after values for bar graphs.
334 if // empty labels are allowed, so
335 (row.annotations[j].displayCharacter != null
336 && row.annotations[j].displayCharacter.length() > 0
337 && !row.annotations[j].displayCharacter.equals(" "))
339 text.append(comma + row.annotations[j].displayCharacter);
345 if (row.annotations[j].description != null
346 && row.annotations[j].description.length() > 0
347 && !row.annotations[j].description
348 .equals(row.annotations[j].displayCharacter))
350 text.append(comma + row.annotations[j].description);
354 if (color != null && !color.equals(row.annotations[j].colour))
359 color = row.annotations[j].colour;
361 if (row.annotations[j].colour != null
362 && row.annotations[j].colour != java.awt.Color.black)
364 text.append(comma + "[" + jalview.util.Format
365 .getHexString(row.annotations[j].colour) + "]");
374 text.append("\t" + row.score);
377 text.append(newline);
379 if (color != null && color != java.awt.Color.black && oneColour)
381 colours.append("COLOUR\t");
382 colours.append(row.label);
383 colours.append("\t");
384 colours.append(jalview.util.Format.getHexString(color));
385 colours.append(newline);
387 if (row.scaleColLabel || row.showAllColLabels
388 || row.centreColLabels)
390 rowprops.append("ROWPROPERTIES\t");
391 rowprops.append(row.label);
392 rowprops.append("\tscaletofit=");
393 rowprops.append(row.scaleColLabel);
394 rowprops.append("\tshowalllabs=");
395 rowprops.append(row.showAllColLabels);
396 rowprops.append("\tcentrelabs=");
397 rowprops.append(row.centreColLabels);
398 rowprops.append(newline);
400 if (graphLine.length() > 0)
402 text.append(graphLine.toString());
403 graphLine.setLength(0);
407 text.append(newline);
409 text.append(colours.toString());
410 if (graphGroup.size() > 0)
412 SequenceI oldRefSeq = refSeq;
413 SequenceGroup oldRefGroup = refGroup;
414 for (Map.Entry<Integer, String> combine_statement : graphGroup
417 Object[] seqRefAndGroup = graphGroup_refs
418 .get(combine_statement.getKey());
420 writeSequence_Ref(refSeq, (SequenceI) seqRefAndGroup[0]);
421 refSeq = (SequenceI) seqRefAndGroup[0];
423 writeGroup_Ref(refGroup, (SequenceGroup) seqRefAndGroup[1]);
424 refGroup = (SequenceGroup) seqRefAndGroup[1];
425 text.append("COMBINE\t");
426 text.append(combine_statement.getValue());
427 text.append(newline);
429 writeSequence_Ref(refSeq, oldRefSeq);
432 writeGroup_Ref(refGroup, oldRefGroup);
433 refGroup = oldRefGroup;
435 text.append(rowprops.toString());
443 if (properties != null)
445 text.append(newline);
446 text.append(newline);
447 text.append("ALIGNMENT");
448 Enumeration en = properties.keys();
449 while (en.hasMoreElements())
451 String key = en.nextElement().toString();
455 text.append(properties.get(key));
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 public boolean annotateAlignmentView(AlignViewportI viewport, Object file,
645 DataSourceType protocol)
647 ColumnSelection colSel = viewport.getColumnSelection();
648 HiddenColumns hidden = viewport.getAlignment().getHiddenColumns();
651 colSel = new ColumnSelection();
655 hidden = new HiddenColumns();
657 boolean rslt = readAnnotationFile(viewport.getAlignment(), hidden, file,
659 if (rslt && (colSel.hasSelectedColumns() || hidden.hasHiddenColumns()))
661 viewport.setColumnSelection(colSel);
662 viewport.getAlignment().setHiddenColumns(hidden);
668 public boolean readAnnotationFile(AlignmentI al, String file,
669 DataSourceType sourceType)
671 return readAnnotationFile(al, null, file, sourceType);
675 * read an annotation file onto the alignment, but apply the given calcId
682 public boolean readAnnotationFileWithCalcId(Alignment aln, String calcId, String file,
685 defaultCalcId=calcId;
686 return readAnnotationFile(aln, null, file, url);
689 public boolean readAnnotationFile(AlignmentI al, HiddenColumns hidden,
690 Object file, DataSourceType sourceType)
692 BufferedReader in = null;
695 in = new FileParse().getBufferedReader(file, sourceType);
698 return parseAnnotationFrom(al, hidden, in);
700 } catch (Exception ex)
702 ex.printStackTrace();
703 System.out.println("Problem reading annotation file: " + ex);
706 System.out.println("Last read line " + nlinesread + ": '" + lastread
707 + "' (first 80 chars) ...");
714 public boolean parseAnnotationFrom(AlignmentI al, HiddenColumns hidden,
715 BufferedReader in) throws Exception
718 ArrayList<Object[]> combineAnnotation_calls = new ArrayList<>();
719 ArrayList<Object[]> deferredAnnotation_calls = new ArrayList<>();
720 boolean modified = false;
721 String groupRef = null;
722 Hashtable groupRefRows = new Hashtable();
724 Hashtable autoAnnots = new Hashtable();
726 String line, label, description, token;
727 int graphStyle, index;
729 int existingAnnotations = 0;
730 // when true - will add new rows regardless of whether they are duplicate
731 // auto-annotation like consensus or conservation graphs
732 boolean overrideAutoAnnot = false;
733 if (al.getAlignmentAnnotation() != null)
735 existingAnnotations = al.getAlignmentAnnotation().length;
736 if (existingAnnotations > 0)
738 AlignmentAnnotation[] aa = al.getAlignmentAnnotation();
739 for (int aai = 0; aai < aa.length; aai++)
741 if (aa[aai].autoCalculated)
743 // make a note of the name and description
745 autoAnnotsKey(aa[aai], aa[aai].sequenceRef,
746 (aa[aai].groupRef == null ? null
747 : aa[aai].groupRef.getName())),
754 int alWidth = al.getWidth();
757 Annotation[] annotations;
758 AlignmentAnnotation annotation = null;
760 // First confirm this is an Annotation file
761 boolean jvAnnotationFile = false;
762 while ((line = in.readLine()) != null)
765 lastread = new String(line);
766 if (line.indexOf("#") == 0)
771 if (line.indexOf("JALVIEW_ANNOTATION") > -1)
773 jvAnnotationFile = true;
778 if (!jvAnnotationFile)
784 while ((line = in.readLine()) != null)
787 lastread = new String(line);
788 if (line.indexOf("#") == 0
789 || line.indexOf("JALVIEW_ANNOTATION") > -1
790 || line.length() == 0)
795 st = new StringTokenizer(line, "\t");
796 token = st.nextToken();
797 if (token.equalsIgnoreCase("COLOUR"))
799 // TODO: use graduated colour def'n here too
800 colourAnnotations(al, st.nextToken(), st.nextToken());
805 else if (token.equalsIgnoreCase(COMBINE))
807 // keep a record of current state and resolve groupRef at end
808 combineAnnotation_calls
810 { st, refSeq, groupRef });
814 else if (token.equalsIgnoreCase("ROWPROPERTIES"))
816 addRowProperties(al, st);
820 else if (token.equalsIgnoreCase(GRAPHLINE))
823 deferredAnnotation_calls
825 { GRAPHLINE, st, refSeq, groupRef });
830 else if (token.equalsIgnoreCase("SEQUENCE_REF"))
832 if (st.hasMoreTokens())
834 refSeq = al.findName(refSeqId = st.nextToken());
841 refSeqIndex = Integer.parseInt(st.nextToken());
846 "WARNING: SEQUENCE_REF index must be > 0 in AnnotationFile");
848 } catch (Exception ex)
860 else if (token.equalsIgnoreCase("GROUP_REF"))
862 // Group references could be forward or backwards, so they are
863 // resolved after the whole file is read in
865 if (st.hasMoreTokens())
867 groupRef = st.nextToken();
868 if (groupRef.length() < 1)
870 groupRef = null; // empty string
874 if (groupRefRows.get(groupRef) == null)
876 groupRefRows.put(groupRef, new Vector());
882 else if (token.equalsIgnoreCase("SEQUENCE_GROUP"))
889 else if (token.equalsIgnoreCase("PROPERTIES"))
891 addProperties(al, st);
896 else if (token.equalsIgnoreCase("BELOW_ALIGNMENT"))
898 setBelowAlignment(al, st);
902 else if (token.equalsIgnoreCase("ALIGNMENT"))
904 addAlignmentDetails(al, st);
908 // else if (token.equalsIgnoreCase("VIEW_DEF"))
910 // addOrSetView(al,st);
914 else if (token.equalsIgnoreCase("VIEW_SETREF"))
918 al.setSeqrep(refSeq);
923 else if (token.equalsIgnoreCase("VIEW_HIDECOLS"))
925 if (st.hasMoreTokens())
929 hidden = new HiddenColumns();
931 parseHideCols(hidden, st.nextToken());
936 else if (token.equalsIgnoreCase("HIDE_INSERTIONS"))
938 SequenceI sr = refSeq == null ? al.getSeqrep() : refSeq;
941 sr = al.getSequenceAt(0);
948 "Cannot process HIDE_INSERTIONS without an alignment view: Ignoring line: "
953 // consider deferring this till after the file has been parsed ?
954 hidden.hideList(sr.getInsertions());
961 // Parse out the annotation row
962 graphStyle = AlignmentAnnotation.getGraphValueFromString(token);
963 label = st.nextToken();
966 annotations = new Annotation[alWidth];
968 float score = Float.NaN;
970 if (st.hasMoreTokens())
972 line = st.nextToken();
974 if (line.indexOf("|") == -1)
977 if (st.hasMoreTokens())
979 line = st.nextToken();
983 if (st.hasMoreTokens())
985 // This must be the score
986 score = Float.valueOf(st.nextToken()).floatValue();
989 st = new StringTokenizer(line, "|", true);
991 boolean emptyColumn = true;
992 boolean onlyOneElement = (st.countTokens() == 1);
994 while (st.hasMoreElements() && index < alWidth)
996 token = st.nextToken().trim();
1002 score = Float.valueOf(token).floatValue();
1004 } catch (NumberFormatException ex)
1009 if (token.equals("|"))
1020 annotations[index++] = parseAnnotation(token, graphStyle);
1021 emptyColumn = false;
1027 annotation = new AlignmentAnnotation(label, description,
1028 (index == 0) ? null : annotations, 0, 0, graphStyle);
1029 annotation.setCalcId(defaultCalcId);
1030 annotation.score = score;
1031 if (!overrideAutoAnnot && autoAnnots
1032 .containsKey(autoAnnotsKey(annotation, refSeq, groupRef)))
1034 // skip - we've already got an automatic annotation of this type.
1037 // otherwise add it!
1041 annotation.belowAlignment = false;
1042 // make a copy of refSeq so we can find other matches in the alignment
1043 SequenceI referedSeq = refSeq;
1046 // copy before we do any mapping business.
1047 // TODO: verify that undo/redo with 1:many sequence associated
1048 // annotations can be undone correctly
1049 AlignmentAnnotation ann = new AlignmentAnnotation(annotation);
1050 annotation.createSequenceMapping(referedSeq, refSeqIndex,
1052 annotation.adjustForAlignment();
1053 referedSeq.addAlignmentAnnotation(annotation);
1054 al.addAnnotation(annotation);
1055 al.setAnnotationIndex(annotation,
1056 al.getAlignmentAnnotation().length - existingAnnotations
1058 if (groupRef != null)
1060 ((Vector) groupRefRows.get(groupRef)).addElement(annotation);
1062 // and recover our virgin copy to use again if necessary.
1065 } while (refSeqId != null && (referedSeq = al.findName(referedSeq,
1066 refSeqId, true)) != null);
1070 al.addAnnotation(annotation);
1071 al.setAnnotationIndex(annotation,
1072 al.getAlignmentAnnotation().length - existingAnnotations
1074 if (groupRef != null)
1076 ((Vector) groupRefRows.get(groupRef)).addElement(annotation);
1079 // and set modification flag
1082 // Resolve the groupRefs
1083 Hashtable<String, SequenceGroup> groupRefLookup = new Hashtable<>();
1084 Enumeration en = groupRefRows.keys();
1086 while (en.hasMoreElements())
1088 groupRef = (String) en.nextElement();
1089 boolean matched = false;
1090 // Resolve group: TODO: add a getGroupByName method to alignments
1091 for (SequenceGroup theGroup : al.getGroups())
1093 if (theGroup.getName().equals(groupRef))
1097 // TODO: specify and implement duplication of alignment annotation
1098 // for multiple group references.
1100 "Ignoring 1:many group reference mappings for group name '"
1106 Vector rowset = (Vector) groupRefRows.get(groupRef);
1107 groupRefLookup.put(groupRef, theGroup);
1108 if (rowset != null && rowset.size() > 0)
1110 AlignmentAnnotation alan = null;
1111 for (int elm = 0, elmSize = rowset
1112 .size(); elm < elmSize; elm++)
1114 alan = (AlignmentAnnotation) rowset.elementAt(elm);
1115 alan.groupRef = theGroup;
1121 ((Vector) groupRefRows.get(groupRef)).removeAllElements();
1123 // process any deferred attribute settings for each context
1124 for (Object[] _deferred_args : deferredAnnotation_calls)
1126 if (_deferred_args[0] == GRAPHLINE)
1128 addLine(al, (StringTokenizer) _deferred_args[1], // st
1129 (SequenceI) _deferred_args[2], // refSeq
1130 (_deferred_args[3] == null) ? null
1131 : groupRefLookup.get(_deferred_args[3]) // the
1139 // finally, combine all the annotation rows within each context.
1141 * number of combine statements in this annotation file. Used to create
1142 * new groups for combined annotation graphs without disturbing existing
1145 int combinecount = 0;
1146 for (Object[] _combine_args : combineAnnotation_calls)
1148 combineAnnotations(al, ++combinecount,
1149 (StringTokenizer) _combine_args[0], // st
1150 (SequenceI) _combine_args[1], // refSeq
1151 (_combine_args[2] == null) ? null
1152 : groupRefLookup.get(_combine_args[2]) // the reference
1161 private void parseHideCols(HiddenColumns hidden, String nextToken)
1163 StringTokenizer inval = new StringTokenizer(nextToken, ",");
1164 while (inval.hasMoreTokens())
1166 String range = inval.nextToken().trim();
1167 int from, to = range.indexOf("-");
1170 from = to = Integer.parseInt(range);
1173 hidden.hideColumns(from, to);
1178 from = Integer.parseInt(range.substring(0, to));
1179 if (to < range.length() - 1)
1181 to = Integer.parseInt(range.substring(to + 1));
1187 if (from > 0 && to >= from)
1189 hidden.hideColumns(from, to);
1195 private Object autoAnnotsKey(AlignmentAnnotation annotation,
1196 SequenceI refSeq, String groupRef)
1198 return annotation.graph + "\t" + annotation.label + "\t"
1199 + annotation.description + "\t"
1200 + (refSeq != null ? refSeq.getDisplayId(true) : "");
1203 Annotation parseAnnotation(String string, int graphStyle)
1205 // don't do the glyph test if we don't want secondary structure
1206 boolean hasSymbols = (graphStyle == AlignmentAnnotation.NO_GRAPH);
1207 String desc = null, displayChar = null;
1208 char ss = ' '; // secondaryStructure
1210 boolean parsedValue = false, dcset = false;
1213 Color colour = null;
1214 int i = string.indexOf("[");
1215 int j = string.indexOf("]");
1216 if (i > -1 && j > -1)
1218 colour = ColorUtils.parseColourString(string.substring(i + 1, j));
1219 if (i > 0 && string.charAt(i - 1) == ',')
1221 // clip the preceding comma as well
1224 string = string.substring(0, i) + string.substring(j + 1);
1227 StringTokenizer st = new StringTokenizer(string, ",", true);
1229 boolean seenContent = false;
1231 while (st.hasMoreTokens())
1234 token = st.nextToken().trim();
1235 if (token.equals(","))
1237 if (!seenContent && parsedValue && !dcset)
1239 // allow the value below the bar/line to be empty
1243 seenContent = false;
1255 displayChar = token;
1257 value = Float.valueOf(token).floatValue();
1260 } catch (NumberFormatException ex)
1266 if (token.length() == 1)
1268 displayChar = token;
1271 if (hasSymbols && (token.length() == 1
1272 && "()<>[]{}AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz"
1275 // Either this character represents a helix or sheet
1276 // or an integer which can be displayed
1277 ss = token.charAt(0);
1278 if (displayChar.equals(token.substring(0, 1)))
1283 else if (desc == null || (parsedValue && pass > 2))
1289 // if (!dcset && string.charAt(string.length() - 1) == ',')
1291 // displayChar = " "; // empty display char symbol.
1293 if (displayChar != null && desc != null && desc.length() == 1)
1295 if (displayChar.length() > 1)
1297 // switch desc and displayChar - legacy support
1298 String tmp = displayChar;
1304 if (displayChar.equals(desc))
1306 // duplicate label - hangover from the 'robust parser' above
1311 Annotation anot = new Annotation(displayChar, desc, ss, value);
1313 anot.colour = colour;
1318 void colourAnnotations(AlignmentI al, String label, String colour)
1320 Color awtColour = ColorUtils.parseColourString(colour);
1321 Annotation[] annotations;
1322 for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1324 if (al.getAlignmentAnnotation()[i].label.equalsIgnoreCase(label))
1326 annotations = al.getAlignmentAnnotation()[i].annotations;
1327 for (int j = 0; j < annotations.length; j++)
1329 if (annotations[j] != null)
1331 annotations[j].colour = awtColour;
1338 void combineAnnotations(AlignmentI al, int combineCount,
1339 StringTokenizer st, SequenceI seqRef, SequenceGroup groupRef)
1341 String group = st.nextToken();
1342 // First make sure we are not overwriting the graphIndex
1344 if (al.getAlignmentAnnotation() != null)
1346 for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1348 AlignmentAnnotation aa = al.getAlignmentAnnotation()[i];
1350 if (aa.graphGroup > graphGroup)
1352 // try to number graphGroups in order of occurence.
1353 graphGroup = aa.graphGroup + 1;
1355 if (aa.sequenceRef == seqRef && aa.groupRef == groupRef
1356 && aa.label.equalsIgnoreCase(group))
1358 if (aa.graphGroup > -1)
1360 graphGroup = aa.graphGroup;
1364 if (graphGroup <= combineCount)
1366 graphGroup = combineCount + 1;
1368 aa.graphGroup = graphGroup;
1374 // Now update groups
1375 while (st.hasMoreTokens())
1377 group = st.nextToken();
1378 for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1380 AlignmentAnnotation aa = al.getAlignmentAnnotation()[i];
1381 if (aa.sequenceRef == seqRef && aa.groupRef == groupRef
1382 && aa.label.equalsIgnoreCase(group))
1384 aa.graphGroup = graphGroup;
1393 "Couldn't combine annotations. None are added to alignment yet!");
1397 void addLine(AlignmentI al, StringTokenizer st, SequenceI seqRef,
1398 SequenceGroup groupRef)
1400 String group = st.nextToken();
1401 AlignmentAnnotation[] alannot = al.getAlignmentAnnotation();
1402 String nextToken = st.nextToken();
1406 value = Float.valueOf(nextToken);
1407 } catch (NumberFormatException e)
1409 System.err.println("line " + nlinesread + ": Threshold '" + nextToken
1410 + "' invalid, setting to zero");
1412 String label = st.hasMoreTokens() ? st.nextToken() : null;
1413 Color colour = null;
1414 if (st.hasMoreTokens())
1416 colour = ColorUtils.parseColourString(st.nextToken());
1418 if (alannot != null)
1420 for (int i = 0; i < alannot.length; i++)
1422 if (alannot[i].label.equalsIgnoreCase(group)
1423 && (seqRef == null || alannot[i].sequenceRef == seqRef)
1424 && (groupRef == null || alannot[i].groupRef == groupRef))
1426 alannot[i].setThreshold(new GraphLine(value, label, colour));
1432 void addGroup(AlignmentI al, StringTokenizer st)
1434 SequenceGroup sg = new SequenceGroup();
1435 sg.setName(st.nextToken());
1439 rng = st.nextToken();
1440 if (rng.length() > 0 && !rng.startsWith("*"))
1442 sg.setStartRes(Integer.parseInt(rng) - 1);
1448 rng = st.nextToken();
1449 if (rng.length() > 0 && !rng.startsWith("*"))
1451 sg.setEndRes(Integer.parseInt(rng) - 1);
1455 sg.setEndRes(al.getWidth() - 1);
1457 } catch (Exception e)
1460 "Couldn't parse Group Start or End Field as '*' or a valid column or sequence index: '"
1461 + rng + "' - assuming alignment width for group.");
1462 // assume group is full width
1464 sg.setEndRes(al.getWidth() - 1);
1467 String index = st.nextToken();
1468 if (index.equals("-1"))
1470 while (st.hasMoreElements())
1472 sg.addSequence(al.findName(st.nextToken()), false);
1477 StringTokenizer st2 = new StringTokenizer(index, ",");
1479 while (st2.hasMoreTokens())
1481 String tmp = st2.nextToken();
1482 if (tmp.equals("*"))
1484 for (int i = 0; i < al.getHeight(); i++)
1486 sg.addSequence(al.getSequenceAt(i), false);
1489 else if (tmp.indexOf("-") >= 0)
1491 StringTokenizer st3 = new StringTokenizer(tmp, "-");
1493 int start = (Integer.parseInt(st3.nextToken()));
1494 int end = (Integer.parseInt(st3.nextToken()));
1498 for (int i = start; i <= end; i++)
1500 sg.addSequence(al.getSequenceAt(i - 1), false);
1506 sg.addSequence(al.getSequenceAt(Integer.parseInt(tmp) - 1),
1514 sg.setStartRes(refSeq.findIndex(sg.getStartRes() + 1) - 1);
1515 sg.setEndRes(refSeq.findIndex(sg.getEndRes() + 1) - 1);
1516 sg.setSeqrep(refSeq);
1519 if (sg.getSize() > 0)
1525 void addRowProperties(AlignmentI al, StringTokenizer st)
1527 String label = st.nextToken(), keyValue, key, value;
1528 boolean scaletofit = false, centerlab = false, showalllabs = false;
1529 while (st.hasMoreTokens())
1531 keyValue = st.nextToken();
1532 key = keyValue.substring(0, keyValue.indexOf("="));
1533 value = keyValue.substring(keyValue.indexOf("=") + 1);
1534 if (key.equalsIgnoreCase("scaletofit"))
1536 scaletofit = Boolean.valueOf(value).booleanValue();
1538 if (key.equalsIgnoreCase("showalllabs"))
1540 showalllabs = Boolean.valueOf(value).booleanValue();
1542 if (key.equalsIgnoreCase("centrelabs"))
1544 centerlab = Boolean.valueOf(value).booleanValue();
1546 AlignmentAnnotation[] alr = al.getAlignmentAnnotation();
1549 for (int i = 0; i < alr.length; i++)
1551 if (alr[i].label.equalsIgnoreCase(label))
1553 alr[i].centreColLabels = centerlab;
1554 alr[i].scaleColLabel = scaletofit;
1555 alr[i].showAllColLabels = showalllabs;
1562 void addProperties(AlignmentI al, StringTokenizer st)
1565 // So far we have only added groups to the annotationHash,
1566 // the idea is in the future properties can be added to
1567 // alignments, other annotations etc
1568 if (al.getGroups() == null)
1573 String name = st.nextToken();
1575 Map<String, String> properties = new HashMap<>();
1576 while (st.hasMoreTokens())
1578 String keyValue = st.nextToken();
1579 String key = keyValue.substring(0, keyValue.indexOf("="));
1580 String value = keyValue.substring(keyValue.indexOf("=") + 1);
1581 properties.put(key, value);
1584 for (SequenceGroup sg : al.getGroups())
1586 if (sg.getName().equals(name))
1588 addProperties(sg, properties, al);
1594 * Helper method that applies any specified properties to a SequenceGroup
1600 private void addProperties(SequenceGroup sg,
1601 Map<String, String> properties, AlignmentI al)
1603 ColourSchemeI def = sg.getColourScheme();
1604 for (String key : properties.keySet())
1606 String value = properties.get(key);
1607 if (key.equalsIgnoreCase("description"))
1609 sg.setDescription(value);
1611 else if (key.equalsIgnoreCase("colour"))
1613 // TODO need to notify colourscheme of view reference once it is
1615 sg.cs.setColourScheme(
1616 ColourSchemeProperty.getColourScheme(null, al, value));
1618 else if (key.equalsIgnoreCase("pidThreshold"))
1620 sg.cs.setThreshold(Integer.parseInt(value), true);
1623 else if (key.equalsIgnoreCase("consThreshold"))
1625 sg.cs.setConservationInc(Integer.parseInt(value));
1626 Conservation c = new Conservation("Group", sg.getSequences(null),
1627 sg.getStartRes(), sg.getEndRes() + 1);
1630 c.verdict(false, 25); // TODO: refer to conservation percent threshold
1632 sg.cs.setConservation(c);
1635 else if (key.equalsIgnoreCase("outlineColour"))
1637 sg.setOutlineColour(ColorUtils.parseColourString(value));
1639 else if (key.equalsIgnoreCase("displayBoxes"))
1641 sg.setDisplayBoxes(Boolean.valueOf(value).booleanValue());
1643 else if (key.equalsIgnoreCase("showUnconserved"))
1645 sg.setShowNonconserved(Boolean.valueOf(value).booleanValue());
1647 else if (key.equalsIgnoreCase("displayText"))
1649 sg.setDisplayText(Boolean.valueOf(value).booleanValue());
1651 else if (key.equalsIgnoreCase("colourText"))
1653 sg.setColourText(Boolean.valueOf(value).booleanValue());
1655 else if (key.equalsIgnoreCase("textCol1"))
1657 sg.textColour = ColorUtils.parseColourString(value);
1659 else if (key.equalsIgnoreCase("textCol2"))
1661 sg.textColour2 = ColorUtils.parseColourString(value);
1663 else if (key.equalsIgnoreCase("textColThreshold"))
1665 sg.thresholdTextColour = Integer.parseInt(value);
1667 else if (key.equalsIgnoreCase("idColour"))
1669 Color idColour = ColorUtils.parseColourString(value);
1670 sg.setIdColour(idColour == null ? Color.black : idColour);
1672 else if (key.equalsIgnoreCase("hide"))
1674 // see bug https://mantis.lifesci.dundee.ac.uk/view.php?id=25847
1675 sg.setHidereps(true);
1677 else if (key.equalsIgnoreCase("hidecols"))
1679 // see bug https://mantis.lifesci.dundee.ac.uk/view.php?id=25847
1680 sg.setHideCols(true);
1682 sg.recalcConservation();
1685 if (sg.getColourScheme() == null)
1687 sg.setColourScheme(def);
1691 void setBelowAlignment(AlignmentI al, StringTokenizer st)
1694 AlignmentAnnotation aa, ala[] = al.getAlignmentAnnotation();
1698 "Warning - no annotation to set below for sequence associated annotation:");
1700 while (st.hasMoreTokens())
1702 token = st.nextToken();
1705 System.err.print(" " + token);
1709 for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1711 aa = al.getAlignmentAnnotation()[i];
1712 if (aa.sequenceRef == refSeq && aa.label.equals(token))
1714 aa.belowAlignment = true;
1721 System.err.print("\n");
1725 void addAlignmentDetails(AlignmentI al, StringTokenizer st)
1727 String keyValue, key, value;
1728 while (st.hasMoreTokens())
1730 keyValue = st.nextToken();
1731 key = keyValue.substring(0, keyValue.indexOf("="));
1732 value = keyValue.substring(keyValue.indexOf("=") + 1);
1733 al.setProperty(key, value);
1738 * Write annotations as a CSV file of the form 'label, value, value, ...' for
1741 * @param annotations
1742 * @return CSV file as a string.
1744 public String printCSVAnnotations(AlignmentAnnotation[] annotations)
1746 if (annotations == null)
1750 StringBuffer sp = new StringBuffer();
1751 for (int i = 0; i < annotations.length; i++)
1753 String atos = annotations[i].toString();
1757 int cp = atos.indexOf("\n", p);
1758 sp.append(annotations[i].label);
1762 sp.append(atos.substring(p, cp + 1));
1766 sp.append(atos.substring(p));
1772 return sp.toString();
1775 public String printAnnotationsForView(AlignViewportI viewport)
1777 return printAnnotations(
1778 viewport.isShowAnnotation()
1779 ? viewport.getAlignment().getAlignmentAnnotation()
1781 viewport.getAlignment().getGroups(),
1782 viewport.getAlignment().getProperties(),
1783 viewport.getAlignment().getHiddenColumns(),
1784 viewport.getAlignment(), null);
1787 public String printAnnotationsForAlignment(AlignmentI al)
1789 return printAnnotations(al.getAlignmentAnnotation(), al.getGroups(),
1790 al.getProperties(), null, al, null);