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.io.FileReader;
26 import java.io.InputStreamReader;
27 import java.io.StringReader;
29 import java.util.ArrayList;
30 import java.util.BitSet;
31 import java.util.Enumeration;
32 import java.util.HashMap;
33 import java.util.Hashtable;
34 import java.util.List;
36 import java.util.StringTokenizer;
37 import java.util.Vector;
39 import jalview.analysis.Conservation;
40 import jalview.api.AlignViewportI;
41 import jalview.datamodel.AlignmentAnnotation;
42 import jalview.datamodel.AlignmentI;
43 import jalview.datamodel.Annotation;
44 import jalview.datamodel.ColumnSelection;
45 import jalview.datamodel.GraphLine;
46 import jalview.datamodel.HiddenColumns;
47 import jalview.datamodel.HiddenSequences;
48 import jalview.datamodel.SequenceGroup;
49 import jalview.datamodel.SequenceI;
50 import jalview.schemes.ColourSchemeI;
51 import jalview.schemes.ColourSchemeProperty;
52 import jalview.util.ColorUtils;
54 public class AnnotationFile
56 public AnnotationFile()
62 * character used to write newlines
64 protected String newline = System.getProperty("line.separator");
67 * set new line string and reset the output buffer
71 public void setNewlineString(String nl)
77 public String getNewlineString()
86 text = new StringBuffer("JALVIEW_ANNOTATION" + newline + "# Created: "
87 + new java.util.Date() + newline + newline);
93 * convenience method for pre-2.9 annotation files which have no view, hidden
94 * columns or hidden row keywords.
99 * @return annotation file as a string.
101 public String printAnnotations(AlignmentAnnotation[] annotations,
102 List<SequenceGroup> list, Hashtable properties)
104 return printAnnotations(annotations, list, properties, null, null,
110 * hold all the information about a particular view definition read from or
111 * written out in an annotations file.
115 // TODO this class is not used - remove?
116 public final String viewname;
118 public final HiddenSequences hidseqs;
120 public final HiddenColumns hiddencols;
122 public final Hashtable hiddenRepSeqs;
124 public ViewDef(String vname, HiddenSequences hseqs, HiddenColumns hcols,
127 this.viewname = vname;
128 this.hidseqs = hseqs;
129 this.hiddencols = hcols;
130 this.hiddenRepSeqs = hRepSeqs;
135 * Prepare an annotation file given a set of annotations, groups, alignment
136 * properties and views.
142 * @return annotation file
144 public String printAnnotations(AlignmentAnnotation[] annotations,
145 List<SequenceGroup> list, Hashtable properties, HiddenColumns cs,
146 AlignmentI al, ViewDef view)
150 if (view.viewname != null)
152 text.append("VIEW_DEF\t" + view.viewname + "\n");
156 // list = view.visibleGroups;
160 cs = view.hiddencols;
164 // add hidden rep sequences.
167 // first target - store and restore all settings for a view.
168 if (al != null && al.hasSeqrep())
170 text.append("VIEW_SETREF\t" + al.getSeqrep().getName() + "\n");
172 if (cs != null && cs.hasHiddenColumns())
174 text.append("VIEW_HIDECOLS\t");
176 String regions = cs.regionsToString(",", "-");
177 text.append(regions);
180 // TODO: allow efficient recovery of annotation data shown in several
182 if (annotations != null)
184 boolean oneColour = true;
185 AlignmentAnnotation row;
187 SequenceI refSeq = null;
188 SequenceGroup refGroup = null;
190 StringBuffer colours = new StringBuffer();
191 StringBuffer graphLine = new StringBuffer();
192 StringBuffer rowprops = new StringBuffer();
193 Hashtable<Integer, String> graphGroup = new Hashtable<>();
194 Hashtable<Integer, Object[]> graphGroup_refs = new Hashtable<>();
195 BitSet graphGroupSeen = new BitSet();
197 java.awt.Color color;
199 for (int i = 0; i < annotations.length; i++)
201 row = annotations[i];
203 if (!row.visible && !row.hasScore() && !(row.graphGroup > -1
204 && graphGroupSeen.get(row.graphGroup)))
212 // mark any sequence references for the row
213 writeSequence_Ref(refSeq, row.sequenceRef);
214 refSeq = row.sequenceRef;
215 // mark any group references for the row
216 writeGroup_Ref(refGroup, row.groupRef);
217 refGroup = row.groupRef;
219 boolean hasGlyphs = row.hasIcons, hasLabels = row.hasText,
220 hasValues = row.hasScore, hasText = false;
221 // lookahead to check what the annotation row object actually contains.
222 for (int j = 0; row.annotations != null
223 && j < row.annotations.length
224 && (!hasGlyphs || !hasLabels || !hasValues); j++)
226 if (row.annotations[j] != null)
228 hasLabels |= (row.annotations[j].displayCharacter != null
229 && row.annotations[j].displayCharacter.length() > 0
230 && !row.annotations[j].displayCharacter.equals(" "));
231 hasGlyphs |= (row.annotations[j].secondaryStructure != 0
232 && row.annotations[j].secondaryStructure != ' ');
233 hasValues |= (!Float.isNaN(row.annotations[j].value)); // NaNs can't
236 hasText |= (row.annotations[j].description != null
237 && row.annotations[j].description.length() > 0);
241 if (row.graph == AlignmentAnnotation.NO_GRAPH)
243 text.append("NO_GRAPH\t");
244 hasValues = false; // only secondary structure
245 // hasLabels = false; // and annotation description string.
249 if (row.graph == AlignmentAnnotation.BAR_GRAPH)
251 text.append("BAR_GRAPH\t");
252 hasGlyphs = false; // no secondary structure
255 else if (row.graph == AlignmentAnnotation.LINE_GRAPH)
257 hasGlyphs = false; // no secondary structure
258 text.append("LINE_GRAPH\t");
261 if (row.getThreshold() != null)
263 graphLine.append("GRAPHLINE\t");
264 graphLine.append(row.label);
265 graphLine.append("\t");
266 graphLine.append(row.getThreshold().value);
267 graphLine.append("\t");
268 graphLine.append(row.getThreshold().label);
269 graphLine.append("\t");
270 graphLine.append(jalview.util.Format
271 .getHexString(row.getThreshold().colour));
272 graphLine.append(newline);
275 if (row.graphGroup > -1)
277 graphGroupSeen.set(row.graphGroup);
278 Integer key = Integer.valueOf(row.graphGroup);
279 if (graphGroup.containsKey(key))
281 graphGroup.put(key, graphGroup.get(key) + "\t" + row.label);
286 graphGroup_refs.put(key, new Object[] { refSeq, refGroup });
287 graphGroup.put(key, row.label);
292 text.append(row.label + "\t");
293 if (row.description != null)
295 text.append(row.description + "\t");
297 for (int j = 0; row.annotations != null
298 && j < row.annotations.length; j++)
301 && jalview.util.Comparison.isGap(refSeq.getCharAt(j)))
306 if (row.annotations[j] != null)
309 if (hasGlyphs) // could be also hasGlyphs || ...
313 if (row.annotations[j].secondaryStructure != ' ')
315 // only write out the field if its not whitespace.
316 text.append(row.annotations[j].secondaryStructure);
322 if (!Float.isNaN(row.annotations[j].value))
324 text.append(comma + row.annotations[j].value);
328 // System.err.println("Skipping NaN - not valid value.");
329 text.append(comma + 0f);// row.annotations[j].value);
335 // TODO: labels are emitted after values for bar graphs.
336 if // empty labels are allowed, so
337 (row.annotations[j].displayCharacter != null
338 && row.annotations[j].displayCharacter.length() > 0
339 && !row.annotations[j].displayCharacter.equals(" "))
341 text.append(comma + row.annotations[j].displayCharacter);
347 if (row.annotations[j].description != null
348 && row.annotations[j].description.length() > 0
349 && !row.annotations[j].description
350 .equals(row.annotations[j].displayCharacter))
352 text.append(comma + row.annotations[j].description);
356 if (color != null && !color.equals(row.annotations[j].colour))
361 color = row.annotations[j].colour;
363 if (row.annotations[j].colour != null
364 && row.annotations[j].colour != java.awt.Color.black)
366 text.append(comma + "[" + jalview.util.Format
367 .getHexString(row.annotations[j].colour) + "]");
376 text.append("\t" + row.score);
379 text.append(newline);
381 if (color != null && color != java.awt.Color.black && oneColour)
383 colours.append("COLOUR\t");
384 colours.append(row.label);
385 colours.append("\t");
386 colours.append(jalview.util.Format.getHexString(color));
387 colours.append(newline);
389 if (row.scaleColLabel || row.showAllColLabels
390 || row.centreColLabels)
392 rowprops.append("ROWPROPERTIES\t");
393 rowprops.append(row.label);
394 rowprops.append("\tscaletofit=");
395 rowprops.append(row.scaleColLabel);
396 rowprops.append("\tshowalllabs=");
397 rowprops.append(row.showAllColLabels);
398 rowprops.append("\tcentrelabs=");
399 rowprops.append(row.centreColLabels);
400 rowprops.append(newline);
402 if (graphLine.length() > 0)
404 text.append(graphLine.toString());
405 graphLine.setLength(0);
409 text.append(newline);
411 text.append(colours.toString());
412 if (graphGroup.size() > 0)
414 SequenceI oldRefSeq = refSeq;
415 SequenceGroup oldRefGroup = refGroup;
416 for (Map.Entry<Integer, String> combine_statement : graphGroup
419 Object[] seqRefAndGroup = graphGroup_refs
420 .get(combine_statement.getKey());
422 writeSequence_Ref(refSeq, (SequenceI) seqRefAndGroup[0]);
423 refSeq = (SequenceI) seqRefAndGroup[0];
425 writeGroup_Ref(refGroup, (SequenceGroup) seqRefAndGroup[1]);
426 refGroup = (SequenceGroup) seqRefAndGroup[1];
427 text.append("COMBINE\t");
428 text.append(combine_statement.getValue());
429 text.append(newline);
431 writeSequence_Ref(refSeq, oldRefSeq);
434 writeGroup_Ref(refGroup, oldRefGroup);
435 refGroup = oldRefGroup;
437 text.append(rowprops.toString());
445 if (properties != null)
447 text.append(newline);
448 text.append(newline);
449 text.append("ALIGNMENT");
450 Enumeration en = properties.keys();
451 while (en.hasMoreElements())
453 String key = en.nextElement().toString();
457 text.append(properties.get(key));
459 // TODO: output alignment visualization settings here if required
460 // iterate through one or more views, defining, marking columns and rows
461 // as visible/hidden, and emmitting view properties.
462 // View specific annotation is
465 return text.toString();
468 private Object writeGroup_Ref(SequenceGroup refGroup,
469 SequenceGroup next_refGroup)
471 if (next_refGroup == null)
474 if (refGroup != null)
476 text.append(newline);
477 text.append("GROUP_REF\t");
478 text.append("ALIGNMENT");
479 text.append(newline);
485 if (refGroup == null || refGroup != next_refGroup)
487 text.append(newline);
488 text.append("GROUP_REF\t");
489 text.append(next_refGroup.getName());
490 text.append(newline);
497 private boolean writeSequence_Ref(SequenceI refSeq, SequenceI next_refSeq)
500 if (next_refSeq == null)
504 text.append(newline);
505 text.append("SEQUENCE_REF\t");
506 text.append("ALIGNMENT");
507 text.append(newline);
513 if (refSeq == null || refSeq != next_refSeq)
515 text.append(newline);
516 text.append("SEQUENCE_REF\t");
517 text.append(next_refSeq.getName());
518 text.append(newline);
525 protected void printGroups(List<SequenceGroup> list)
527 SequenceI seqrep = null;
528 for (SequenceGroup sg : list)
532 text.append("SEQUENCE_GROUP\t" + sg.getName() + "\t"
533 + (sg.getStartRes() + 1) + "\t" + (sg.getEndRes() + 1)
539 seqrep = sg.getSeqrep();
540 text.append("SEQUENCE_REF\t");
541 text.append(seqrep.getName());
542 text.append(newline);
543 text.append("SEQUENCE_GROUP\t");
544 text.append(sg.getName());
546 text.append((seqrep.findPosition(sg.getStartRes())));
548 text.append((seqrep.findPosition(sg.getEndRes())));
552 for (int s = 0; s < sg.getSize(); s++)
554 text.append(sg.getSequenceAt(s).getName());
557 text.append(newline);
558 text.append("PROPERTIES\t");
559 text.append(sg.getName());
562 if (sg.getDescription() != null)
564 text.append("description=");
565 text.append(sg.getDescription());
570 text.append("colour=");
571 text.append(ColourSchemeProperty
572 .getColourName(sg.cs.getColourScheme()));
574 if (sg.cs.getThreshold() != 0)
576 text.append("pidThreshold=");
577 text.append(sg.cs.getThreshold());
579 if (sg.cs.conservationApplied())
581 text.append("consThreshold=");
582 text.append(sg.cs.getConservationInc());
586 text.append("outlineColour=");
587 text.append(jalview.util.Format.getHexString(sg.getOutlineColour()));
590 text.append("displayBoxes=");
591 text.append(sg.getDisplayBoxes());
593 text.append("displayText=");
594 text.append(sg.getDisplayText());
596 text.append("colourText=");
597 text.append(sg.getColourText());
599 text.append("showUnconserved=");
600 text.append(sg.getShowNonconserved());
602 if (sg.textColour != java.awt.Color.black)
604 text.append("textCol1=");
605 text.append(jalview.util.Format.getHexString(sg.textColour));
608 if (sg.textColour2 != java.awt.Color.white)
610 text.append("textCol2=");
611 text.append(jalview.util.Format.getHexString(sg.textColour2));
614 if (sg.thresholdTextColour != 0)
616 text.append("textColThreshold=");
617 text.append(sg.thresholdTextColour);
620 if (sg.idColour != null)
622 text.append("idColour=");
623 text.append(jalview.util.Format.getHexString(sg.idColour));
628 text.append("hide=true\t");
632 text.append("hidecols=true\t");
636 // terminate the last line and clear the sequence ref for the group
637 text.append(newline);
638 text.append("SEQUENCE_REF");
640 text.append(newline);
641 text.append(newline);
646 SequenceI refSeq = null;
648 String refSeqId = null;
650 public boolean annotateAlignmentView(AlignViewportI viewport, String file,
651 DataSourceType protocol)
653 ColumnSelection colSel = viewport.getColumnSelection();
654 HiddenColumns hidden = viewport.getAlignment().getHiddenColumns();
657 colSel = new ColumnSelection();
661 hidden = new HiddenColumns();
663 boolean rslt = readAnnotationFile(viewport.getAlignment(), hidden, file,
665 if (rslt && (colSel.hasSelectedColumns() || hidden.hasHiddenColumns()))
667 viewport.setColumnSelection(colSel);
668 viewport.getAlignment().setHiddenColumns(hidden);
674 public boolean readAnnotationFile(AlignmentI al, String file,
675 DataSourceType sourceType)
677 return readAnnotationFile(al, null, file, sourceType);
680 public boolean readAnnotationFile(AlignmentI al, HiddenColumns hidden,
681 String file, DataSourceType sourceType)
683 BufferedReader in = null;
686 if (sourceType == DataSourceType.FILE)
688 in = new BufferedReader(new FileReader(file));
690 else if (sourceType == DataSourceType.URL)
692 URL url = new URL(file);
693 in = new BufferedReader(new InputStreamReader(url.openStream()));
695 else if (sourceType == DataSourceType.PASTE)
697 in = new BufferedReader(new StringReader(file));
699 else if (sourceType == DataSourceType.CLASSLOADER)
701 java.io.InputStream is = getClass().getResourceAsStream("/" + file);
704 in = new BufferedReader(new java.io.InputStreamReader(is));
709 return parseAnnotationFrom(al, hidden, in);
712 } catch (Exception ex)
714 ex.printStackTrace();
715 System.out.println("Problem reading annotation file: " + ex);
718 System.out.println("Last read line " + nlinesread + ": '" + lastread
719 + "' (first 80 chars) ...");
728 String lastread = "";
730 private static String GRAPHLINE = "GRAPHLINE", COMBINE = "COMBINE";
732 public boolean parseAnnotationFrom(AlignmentI al, HiddenColumns hidden,
733 BufferedReader in) throws Exception
736 ArrayList<Object[]> combineAnnotation_calls = new ArrayList<>();
737 ArrayList<Object[]> deferredAnnotation_calls = new ArrayList<>();
738 boolean modified = false;
739 String groupRef = null;
740 Hashtable groupRefRows = new Hashtable();
742 Hashtable autoAnnots = new Hashtable();
744 String line, label, description, token;
745 int graphStyle, index;
747 int existingAnnotations = 0;
748 // when true - will add new rows regardless of whether they are duplicate
749 // auto-annotation like consensus or conservation graphs
750 boolean overrideAutoAnnot = false;
751 if (al.getAlignmentAnnotation() != null)
753 existingAnnotations = al.getAlignmentAnnotation().length;
754 if (existingAnnotations > 0)
756 AlignmentAnnotation[] aa = al.getAlignmentAnnotation();
757 for (int aai = 0; aai < aa.length; aai++)
759 if (aa[aai].autoCalculated)
761 // make a note of the name and description
763 autoAnnotsKey(aa[aai], aa[aai].sequenceRef,
764 (aa[aai].groupRef == null ? null
765 : aa[aai].groupRef.getName())),
772 int alWidth = al.getWidth();
775 Annotation[] annotations;
776 AlignmentAnnotation annotation = null;
778 // First confirm this is an Annotation file
779 boolean jvAnnotationFile = false;
780 while ((line = in.readLine()) != null)
783 lastread = new String(line);
784 if (line.indexOf("#") == 0)
789 if (line.indexOf("JALVIEW_ANNOTATION") > -1)
791 jvAnnotationFile = true;
796 if (!jvAnnotationFile)
802 while ((line = in.readLine()) != null)
805 lastread = new String(line);
806 if (line.indexOf("#") == 0
807 || line.indexOf("JALVIEW_ANNOTATION") > -1
808 || line.length() == 0)
813 st = new StringTokenizer(line, "\t");
814 token = st.nextToken();
815 if (token.equalsIgnoreCase("COLOUR"))
817 // TODO: use graduated colour def'n here too
818 colourAnnotations(al, st.nextToken(), st.nextToken());
823 else if (token.equalsIgnoreCase(COMBINE))
825 // keep a record of current state and resolve groupRef at end
826 combineAnnotation_calls
828 { st, refSeq, groupRef });
832 else if (token.equalsIgnoreCase("ROWPROPERTIES"))
834 addRowProperties(al, st);
838 else if (token.equalsIgnoreCase(GRAPHLINE))
841 deferredAnnotation_calls
843 { GRAPHLINE, st, refSeq, groupRef });
848 else if (token.equalsIgnoreCase("SEQUENCE_REF"))
850 if (st.hasMoreTokens())
852 refSeq = al.findName(refSeqId = st.nextToken());
859 refSeqIndex = Integer.parseInt(st.nextToken());
864 "WARNING: SEQUENCE_REF index must be > 0 in AnnotationFile");
866 } catch (Exception ex)
878 else if (token.equalsIgnoreCase("GROUP_REF"))
880 // Group references could be forward or backwards, so they are
881 // resolved after the whole file is read in
883 if (st.hasMoreTokens())
885 groupRef = st.nextToken();
886 if (groupRef.length() < 1)
888 groupRef = null; // empty string
892 if (groupRefRows.get(groupRef) == null)
894 groupRefRows.put(groupRef, new Vector());
900 else if (token.equalsIgnoreCase("SEQUENCE_GROUP"))
907 else if (token.equalsIgnoreCase("PROPERTIES"))
909 addProperties(al, st);
914 else if (token.equalsIgnoreCase("BELOW_ALIGNMENT"))
916 setBelowAlignment(al, st);
920 else if (token.equalsIgnoreCase("ALIGNMENT"))
922 addAlignmentDetails(al, st);
926 // else if (token.equalsIgnoreCase("VIEW_DEF"))
928 // addOrSetView(al,st);
932 else if (token.equalsIgnoreCase("VIEW_SETREF"))
936 al.setSeqrep(refSeq);
941 else if (token.equalsIgnoreCase("VIEW_HIDECOLS"))
943 if (st.hasMoreTokens())
947 hidden = new HiddenColumns();
949 parseHideCols(hidden, st.nextToken());
954 else if (token.equalsIgnoreCase("HIDE_INSERTIONS"))
956 SequenceI sr = refSeq == null ? al.getSeqrep() : refSeq;
959 sr = al.getSequenceAt(0);
966 "Cannot process HIDE_INSERTIONS without an alignment view: Ignoring line: "
971 // consider deferring this till after the file has been parsed ?
972 hidden.hideList(sr.getInsertions());
979 // Parse out the annotation row
980 graphStyle = AlignmentAnnotation.getGraphValueFromString(token);
981 label = st.nextToken();
984 annotations = new Annotation[alWidth];
986 float score = Float.NaN;
988 if (st.hasMoreTokens())
990 line = st.nextToken();
992 if (line.indexOf("|") == -1)
995 if (st.hasMoreTokens())
997 line = st.nextToken();
1001 if (st.hasMoreTokens())
1003 // This must be the score
1004 score = Float.valueOf(st.nextToken()).floatValue();
1007 st = new StringTokenizer(line, "|", true);
1009 boolean emptyColumn = true;
1010 boolean onlyOneElement = (st.countTokens() == 1);
1012 while (st.hasMoreElements() && index < alWidth)
1014 token = st.nextToken().trim();
1020 score = Float.valueOf(token).floatValue();
1022 } catch (NumberFormatException ex)
1027 if (token.equals("|"))
1038 annotations[index++] = parseAnnotation(token, graphStyle);
1039 emptyColumn = false;
1045 annotation = new AlignmentAnnotation(label, description,
1046 (index == 0) ? null : annotations, 0, 0, graphStyle);
1048 annotation.score = score;
1049 if (!overrideAutoAnnot && autoAnnots
1050 .containsKey(autoAnnotsKey(annotation, refSeq, groupRef)))
1052 // skip - we've already got an automatic annotation of this type.
1055 // otherwise add it!
1059 annotation.belowAlignment = false;
1060 // make a copy of refSeq so we can find other matches in the alignment
1061 SequenceI referedSeq = refSeq;
1064 // copy before we do any mapping business.
1065 // TODO: verify that undo/redo with 1:many sequence associated
1066 // annotations can be undone correctly
1067 AlignmentAnnotation ann = new AlignmentAnnotation(annotation);
1068 annotation.createSequenceMapping(referedSeq, refSeqIndex,
1070 annotation.adjustForAlignment();
1071 referedSeq.addAlignmentAnnotation(annotation);
1072 al.addAnnotation(annotation);
1073 al.setAnnotationIndex(annotation,
1074 al.getAlignmentAnnotation().length - existingAnnotations
1076 if (groupRef != null)
1078 ((Vector) groupRefRows.get(groupRef)).addElement(annotation);
1080 // and recover our virgin copy to use again if necessary.
1083 } while (refSeqId != null && (referedSeq = al.findName(referedSeq,
1084 refSeqId, true)) != null);
1088 al.addAnnotation(annotation);
1089 al.setAnnotationIndex(annotation,
1090 al.getAlignmentAnnotation().length - existingAnnotations
1092 if (groupRef != null)
1094 ((Vector) groupRefRows.get(groupRef)).addElement(annotation);
1097 // and set modification flag
1100 // Resolve the groupRefs
1101 Hashtable<String, SequenceGroup> groupRefLookup = new Hashtable<>();
1102 Enumeration en = groupRefRows.keys();
1104 while (en.hasMoreElements())
1106 groupRef = (String) en.nextElement();
1107 boolean matched = false;
1108 // Resolve group: TODO: add a getGroupByName method to alignments
1109 for (SequenceGroup theGroup : al.getGroups())
1111 if (theGroup.getName().equals(groupRef))
1115 // TODO: specify and implement duplication of alignment annotation
1116 // for multiple group references.
1118 "Ignoring 1:many group reference mappings for group name '"
1124 Vector rowset = (Vector) groupRefRows.get(groupRef);
1125 groupRefLookup.put(groupRef, theGroup);
1126 if (rowset != null && rowset.size() > 0)
1128 AlignmentAnnotation alan = null;
1129 for (int elm = 0, elmSize = rowset
1130 .size(); elm < elmSize; elm++)
1132 alan = (AlignmentAnnotation) rowset.elementAt(elm);
1133 alan.groupRef = theGroup;
1139 ((Vector) groupRefRows.get(groupRef)).removeAllElements();
1141 // process any deferred attribute settings for each context
1142 for (Object[] _deferred_args : deferredAnnotation_calls)
1144 if (_deferred_args[0] == GRAPHLINE)
1146 addLine(al, (StringTokenizer) _deferred_args[1], // st
1147 (SequenceI) _deferred_args[2], // refSeq
1148 (_deferred_args[3] == null) ? null
1149 : groupRefLookup.get(_deferred_args[3]) // the
1157 // finally, combine all the annotation rows within each context.
1159 * number of combine statements in this annotation file. Used to create
1160 * new groups for combined annotation graphs without disturbing existing
1163 int combinecount = 0;
1164 for (Object[] _combine_args : combineAnnotation_calls)
1166 combineAnnotations(al, ++combinecount,
1167 (StringTokenizer) _combine_args[0], // st
1168 (SequenceI) _combine_args[1], // refSeq
1169 (_combine_args[2] == null) ? null
1170 : groupRefLookup.get(_combine_args[2]) // the reference
1179 private void parseHideCols(HiddenColumns hidden, String nextToken)
1181 StringTokenizer inval = new StringTokenizer(nextToken, ",");
1182 while (inval.hasMoreTokens())
1184 String range = inval.nextToken().trim();
1185 int from, to = range.indexOf("-");
1188 from = to = Integer.parseInt(range);
1191 hidden.hideColumns(from, to);
1196 from = Integer.parseInt(range.substring(0, to));
1197 if (to < range.length() - 1)
1199 to = Integer.parseInt(range.substring(to + 1));
1205 if (from > 0 && to >= from)
1207 hidden.hideColumns(from, to);
1213 private Object autoAnnotsKey(AlignmentAnnotation annotation,
1214 SequenceI refSeq, String groupRef)
1216 return annotation.graph + "\t" + annotation.label + "\t"
1217 + annotation.description + "\t"
1218 + (refSeq != null ? refSeq.getDisplayId(true) : "");
1221 Annotation parseAnnotation(String string, int graphStyle)
1223 // don't do the glyph test if we don't want secondary structure
1224 boolean hasSymbols = (graphStyle == AlignmentAnnotation.NO_GRAPH);
1225 String desc = null, displayChar = null;
1226 char ss = ' '; // secondaryStructure
1228 boolean parsedValue = false, dcset = false;
1231 Color colour = null;
1232 int i = string.indexOf("[");
1233 int j = string.indexOf("]");
1234 if (i > -1 && j > -1)
1236 colour = ColorUtils.parseColourString(string.substring(i + 1, j));
1237 if (i > 0 && string.charAt(i - 1) == ',')
1239 // clip the preceding comma as well
1242 string = string.substring(0, i) + string.substring(j + 1);
1245 StringTokenizer st = new StringTokenizer(string, ",", true);
1247 boolean seenContent = false;
1249 while (st.hasMoreTokens())
1252 token = st.nextToken().trim();
1253 if (token.equals(","))
1255 if (!seenContent && parsedValue && !dcset)
1257 // allow the value below the bar/line to be empty
1261 seenContent = false;
1273 displayChar = token;
1275 value = Float.valueOf(token).floatValue();
1278 } catch (NumberFormatException ex)
1284 if (token.length() == 1)
1286 displayChar = token;
1289 if (hasSymbols && (token.length() == 1
1290 && "()<>[]{}AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz"
1293 // Either this character represents a helix or sheet
1294 // or an integer which can be displayed
1295 ss = token.charAt(0);
1296 if (displayChar.equals(token.substring(0, 1)))
1301 else if (desc == null || (parsedValue && pass > 2))
1307 // if (!dcset && string.charAt(string.length() - 1) == ',')
1309 // displayChar = " "; // empty display char symbol.
1311 if (displayChar != null && desc != null && desc.length() == 1)
1313 if (displayChar.length() > 1)
1315 // switch desc and displayChar - legacy support
1316 String tmp = displayChar;
1322 if (displayChar.equals(desc))
1324 // duplicate label - hangover from the 'robust parser' above
1329 Annotation anot = new Annotation(displayChar, desc, ss, value);
1331 anot.colour = colour;
1336 void colourAnnotations(AlignmentI al, String label, String colour)
1338 Color awtColour = ColorUtils.parseColourString(colour);
1339 Annotation[] annotations;
1340 for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1342 if (al.getAlignmentAnnotation()[i].label.equalsIgnoreCase(label))
1344 annotations = al.getAlignmentAnnotation()[i].annotations;
1345 for (int j = 0; j < annotations.length; j++)
1347 if (annotations[j] != null)
1349 annotations[j].colour = awtColour;
1356 void combineAnnotations(AlignmentI al, int combineCount,
1357 StringTokenizer st, SequenceI seqRef, SequenceGroup groupRef)
1359 String group = st.nextToken();
1360 // First make sure we are not overwriting the graphIndex
1362 if (al.getAlignmentAnnotation() != null)
1364 for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1366 AlignmentAnnotation aa = al.getAlignmentAnnotation()[i];
1368 if (aa.graphGroup > graphGroup)
1370 // try to number graphGroups in order of occurence.
1371 graphGroup = aa.graphGroup + 1;
1373 if (aa.sequenceRef == seqRef && aa.groupRef == groupRef
1374 && aa.label.equalsIgnoreCase(group))
1376 if (aa.graphGroup > -1)
1378 graphGroup = aa.graphGroup;
1382 if (graphGroup <= combineCount)
1384 graphGroup = combineCount + 1;
1386 aa.graphGroup = graphGroup;
1392 // Now update groups
1393 while (st.hasMoreTokens())
1395 group = st.nextToken();
1396 for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1398 AlignmentAnnotation aa = al.getAlignmentAnnotation()[i];
1399 if (aa.sequenceRef == seqRef && aa.groupRef == groupRef
1400 && aa.label.equalsIgnoreCase(group))
1402 aa.graphGroup = graphGroup;
1411 "Couldn't combine annotations. None are added to alignment yet!");
1415 void addLine(AlignmentI al, StringTokenizer st, SequenceI seqRef,
1416 SequenceGroup groupRef)
1418 String group = st.nextToken();
1419 AlignmentAnnotation[] alannot = al.getAlignmentAnnotation();
1420 String nextToken = st.nextToken();
1424 value = Float.valueOf(nextToken);
1425 } catch (NumberFormatException e)
1427 System.err.println("line " + nlinesread + ": Threshold '" + nextToken
1428 + "' invalid, setting to zero");
1430 String label = st.hasMoreTokens() ? st.nextToken() : null;
1431 Color colour = null;
1432 if (st.hasMoreTokens())
1434 colour = ColorUtils.parseColourString(st.nextToken());
1436 if (alannot != null)
1438 for (int i = 0; i < alannot.length; i++)
1440 if (alannot[i].label.equalsIgnoreCase(group)
1441 && (seqRef == null || alannot[i].sequenceRef == seqRef)
1442 && (groupRef == null || alannot[i].groupRef == groupRef))
1444 alannot[i].setThreshold(new GraphLine(value, label, colour));
1450 void addGroup(AlignmentI al, StringTokenizer st)
1452 SequenceGroup sg = new SequenceGroup();
1453 sg.setName(st.nextToken());
1457 rng = st.nextToken();
1458 if (rng.length() > 0 && !rng.startsWith("*"))
1460 sg.setStartRes(Integer.parseInt(rng) - 1);
1466 rng = st.nextToken();
1467 if (rng.length() > 0 && !rng.startsWith("*"))
1469 sg.setEndRes(Integer.parseInt(rng) - 1);
1473 sg.setEndRes(al.getWidth() - 1);
1475 } catch (Exception e)
1478 "Couldn't parse Group Start or End Field as '*' or a valid column or sequence index: '"
1479 + rng + "' - assuming alignment width for group.");
1480 // assume group is full width
1482 sg.setEndRes(al.getWidth() - 1);
1485 String index = st.nextToken();
1486 if (index.equals("-1"))
1488 while (st.hasMoreElements())
1490 sg.addSequence(al.findName(st.nextToken()), false);
1495 StringTokenizer st2 = new StringTokenizer(index, ",");
1497 while (st2.hasMoreTokens())
1499 String tmp = st2.nextToken();
1500 if (tmp.equals("*"))
1502 for (int i = 0; i < al.getHeight(); i++)
1504 sg.addSequence(al.getSequenceAt(i), false);
1507 else if (tmp.indexOf("-") >= 0)
1509 StringTokenizer st3 = new StringTokenizer(tmp, "-");
1511 int start = (Integer.parseInt(st3.nextToken()));
1512 int end = (Integer.parseInt(st3.nextToken()));
1516 for (int i = start; i <= end; i++)
1518 sg.addSequence(al.getSequenceAt(i - 1), false);
1524 sg.addSequence(al.getSequenceAt(Integer.parseInt(tmp) - 1),
1532 sg.setStartRes(refSeq.findIndex(sg.getStartRes() + 1) - 1);
1533 sg.setEndRes(refSeq.findIndex(sg.getEndRes() + 1) - 1);
1534 sg.setSeqrep(refSeq);
1537 if (sg.getSize() > 0)
1543 void addRowProperties(AlignmentI al, StringTokenizer st)
1545 String label = st.nextToken(), keyValue, key, value;
1546 boolean scaletofit = false, centerlab = false, showalllabs = false;
1547 while (st.hasMoreTokens())
1549 keyValue = st.nextToken();
1550 key = keyValue.substring(0, keyValue.indexOf("="));
1551 value = keyValue.substring(keyValue.indexOf("=") + 1);
1552 if (key.equalsIgnoreCase("scaletofit"))
1554 scaletofit = Boolean.valueOf(value).booleanValue();
1556 if (key.equalsIgnoreCase("showalllabs"))
1558 showalllabs = Boolean.valueOf(value).booleanValue();
1560 if (key.equalsIgnoreCase("centrelabs"))
1562 centerlab = Boolean.valueOf(value).booleanValue();
1564 AlignmentAnnotation[] alr = al.getAlignmentAnnotation();
1567 for (int i = 0; i < alr.length; i++)
1569 if (alr[i].label.equalsIgnoreCase(label))
1571 alr[i].centreColLabels = centerlab;
1572 alr[i].scaleColLabel = scaletofit;
1573 alr[i].showAllColLabels = showalllabs;
1580 void addProperties(AlignmentI al, StringTokenizer st)
1583 // So far we have only added groups to the annotationHash,
1584 // the idea is in the future properties can be added to
1585 // alignments, other annotations etc
1586 if (al.getGroups() == null)
1591 String name = st.nextToken();
1593 Map<String, String> properties = new HashMap<>();
1594 while (st.hasMoreTokens())
1596 String keyValue = st.nextToken();
1597 String key = keyValue.substring(0, keyValue.indexOf("="));
1598 String value = keyValue.substring(keyValue.indexOf("=") + 1);
1599 properties.put(key, value);
1602 for (SequenceGroup sg : al.getGroups())
1604 if (sg.getName().equals(name))
1606 addProperties(sg, properties, al);
1612 * Helper method that applies any specified properties to a SequenceGroup
1617 private void addProperties(SequenceGroup sg, Map<String, String> properties, AlignmentI al)
1619 ColourSchemeI def = sg.getColourScheme();
1620 for (String key : properties.keySet())
1622 String value = properties.get(key);
1623 if (key.equalsIgnoreCase("description"))
1625 sg.setDescription(value);
1627 else if (key.equalsIgnoreCase("colour"))
1629 // TODO need to notify colourscheme of view reference once it is
1631 sg.cs.setColourScheme(
1632 ColourSchemeProperty.getColourScheme(null, al, value));
1634 else if (key.equalsIgnoreCase("pidThreshold"))
1636 sg.cs.setThreshold(Integer.parseInt(value), true);
1639 else if (key.equalsIgnoreCase("consThreshold"))
1641 sg.cs.setConservationInc(Integer.parseInt(value));
1642 Conservation c = new Conservation("Group", sg.getSequences(null),
1643 sg.getStartRes(), sg.getEndRes() + 1);
1646 c.verdict(false, 25); // TODO: refer to conservation percent threshold
1648 sg.cs.setConservation(c);
1651 else if (key.equalsIgnoreCase("outlineColour"))
1653 sg.setOutlineColour(ColorUtils.parseColourString(value));
1655 else if (key.equalsIgnoreCase("displayBoxes"))
1657 sg.setDisplayBoxes(Boolean.valueOf(value).booleanValue());
1659 else if (key.equalsIgnoreCase("showUnconserved"))
1661 sg.setShowNonconserved(Boolean.valueOf(value).booleanValue());
1663 else if (key.equalsIgnoreCase("displayText"))
1665 sg.setDisplayText(Boolean.valueOf(value).booleanValue());
1667 else if (key.equalsIgnoreCase("colourText"))
1669 sg.setColourText(Boolean.valueOf(value).booleanValue());
1671 else if (key.equalsIgnoreCase("textCol1"))
1673 sg.textColour = ColorUtils.parseColourString(value);
1675 else if (key.equalsIgnoreCase("textCol2"))
1677 sg.textColour2 = ColorUtils.parseColourString(value);
1679 else if (key.equalsIgnoreCase("textColThreshold"))
1681 sg.thresholdTextColour = Integer.parseInt(value);
1683 else if (key.equalsIgnoreCase("idColour"))
1685 Color idColour = ColorUtils.parseColourString(value);
1686 sg.setIdColour(idColour == null ? Color.black : idColour);
1688 else if (key.equalsIgnoreCase("hide"))
1690 // see bug https://mantis.lifesci.dundee.ac.uk/view.php?id=25847
1691 sg.setHidereps(true);
1693 else if (key.equalsIgnoreCase("hidecols"))
1695 // see bug https://mantis.lifesci.dundee.ac.uk/view.php?id=25847
1696 sg.setHideCols(true);
1698 sg.recalcConservation();
1701 if (sg.getColourScheme() == null)
1703 sg.setColourScheme(def);
1707 void setBelowAlignment(AlignmentI al, StringTokenizer st)
1710 AlignmentAnnotation aa, ala[] = al.getAlignmentAnnotation();
1714 "Warning - no annotation to set below for sequence associated annotation:");
1716 while (st.hasMoreTokens())
1718 token = st.nextToken();
1721 System.err.print(" " + token);
1725 for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1727 aa = al.getAlignmentAnnotation()[i];
1728 if (aa.sequenceRef == refSeq && aa.label.equals(token))
1730 aa.belowAlignment = true;
1737 System.err.print("\n");
1741 void addAlignmentDetails(AlignmentI al, StringTokenizer st)
1743 String keyValue, key, value;
1744 while (st.hasMoreTokens())
1746 keyValue = st.nextToken();
1747 key = keyValue.substring(0, keyValue.indexOf("="));
1748 value = keyValue.substring(keyValue.indexOf("=") + 1);
1749 al.setProperty(key, value);
1754 * Write annotations as a CSV file of the form 'label, value, value, ...' for
1757 * @param annotations
1758 * @return CSV file as a string.
1760 public String printCSVAnnotations(AlignmentAnnotation[] annotations)
1762 if (annotations == null)
1766 StringBuffer sp = new StringBuffer();
1767 for (int i = 0; i < annotations.length; i++)
1769 String atos = annotations[i].toString();
1773 int cp = atos.indexOf("\n", p);
1774 sp.append(annotations[i].label);
1778 sp.append(atos.substring(p, cp + 1));
1782 sp.append(atos.substring(p));
1788 return sp.toString();
1791 public String printAnnotationsForView(AlignViewportI viewport)
1793 return printAnnotations(
1794 viewport.isShowAnnotation()
1795 ? viewport.getAlignment().getAlignmentAnnotation()
1797 viewport.getAlignment().getGroups(),
1798 viewport.getAlignment().getProperties(),
1799 viewport.getAlignment().getHiddenColumns(),
1800 viewport.getAlignment(), null);
1803 public String printAnnotationsForAlignment(AlignmentI al)
1805 return printAnnotations(al.getAlignmentAnnotation(), al.getGroups(),
1806 al.getProperties(), null, al, null);