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.HashMap;
48 import java.util.HashSet;
49 import java.util.Hashtable;
50 import java.util.Iterator;
51 import java.util.List;
54 import java.util.StringTokenizer;
55 import java.util.Vector;
57 public class AnnotationFile
59 public AnnotationFile()
65 * character used to write newlines
67 protected String newline = System.getProperty("line.separator");
70 * set new line string and reset the output buffer
74 public void setNewlineString(String nl)
80 public String getNewlineString()
89 text = new StringBuffer("JALVIEW_ANNOTATION" + newline + "# Created: "
90 + new java.util.Date() + newline + newline);
96 * convenience method for pre-2.9 annotation files which have no view, hidden
97 * columns or hidden row keywords.
102 * @return annotation file as a string.
104 public String printAnnotations(AlignmentAnnotation[] annotations,
105 List<SequenceGroup> list, Hashtable properties)
107 return printAnnotations(annotations, list, properties, null, null,
113 * hold all the information about a particular view definition read from or
114 * written out in an annotations file.
118 // TODO this class is not used - remove?
119 public final String viewname;
121 public final HiddenSequences hidseqs;
123 public final HiddenColumns hiddencols;
125 public final Hashtable hiddenRepSeqs;
127 public ViewDef(String vname, HiddenSequences hseqs, HiddenColumns hcols,
130 this.viewname = vname;
131 this.hidseqs = hseqs;
132 this.hiddencols = hcols;
133 this.hiddenRepSeqs = hRepSeqs;
138 * Prepare an annotation file given a set of annotations, groups, alignment
139 * properties and views.
145 * @return annotation file
147 public String printAnnotations(AlignmentAnnotation[] annotations,
148 List<SequenceGroup> list, Hashtable properties, HiddenColumns cs,
149 AlignmentI al, ViewDef view)
153 if (view.viewname != null)
155 text.append("VIEW_DEF\t" + view.viewname + "\n");
159 // list = view.visibleGroups;
163 cs = view.hiddencols;
167 // add hidden rep sequences.
170 // first target - store and restore all settings for a view.
171 if (al != null && al.hasSeqrep())
173 text.append("VIEW_SETREF\t" + al.getSeqrep().getName() + "\n");
175 if (cs != null && cs.hasHiddenColumns())
177 text.append("VIEW_HIDECOLS\t");
179 String regions = cs.regionsToString(",", "-");
180 text.append(regions);
183 // TODO: allow efficient recovery of annotation data shown in several
185 if (annotations != null)
187 boolean oneColour = true;
188 AlignmentAnnotation row;
190 SequenceI refSeq = null;
191 SequenceGroup refGroup = null;
193 StringBuffer colours = new StringBuffer();
194 StringBuffer graphLine = new StringBuffer();
195 StringBuffer rowprops = new StringBuffer();
196 Hashtable<Integer, String> graphGroup = new Hashtable<>();
197 Hashtable<Integer, Object[]> graphGroup_refs = new Hashtable<>();
198 BitSet graphGroupSeen = new BitSet();
200 java.awt.Color color;
202 for (int i = 0; i < annotations.length; i++)
204 row = annotations[i];
206 if (!row.visible && !row.hasScore() && !(row.graphGroup > -1
207 && graphGroupSeen.get(row.graphGroup)))
215 // mark any sequence references for the row
216 writeSequence_Ref(refSeq, row.sequenceRef);
217 refSeq = row.sequenceRef;
218 // mark any group references for the row
219 writeGroup_Ref(refGroup, row.groupRef);
220 refGroup = row.groupRef;
222 boolean hasGlyphs = row.hasIcons, hasLabels = row.hasText,
223 hasValues = row.hasScore, hasText = false;
224 // lookahead to check what the annotation row object actually contains.
225 for (int j = 0; row.annotations != null
226 && j < row.annotations.length
227 && (!hasGlyphs || !hasLabels || !hasValues); j++)
229 if (row.annotations[j] != null)
231 hasLabels |= (row.annotations[j].displayCharacter != null
232 && row.annotations[j].displayCharacter.length() > 0
233 && !row.annotations[j].displayCharacter.equals(" "));
234 hasGlyphs |= (row.annotations[j].secondaryStructure != 0
235 && row.annotations[j].secondaryStructure != ' ');
236 hasValues |= (!Float.isNaN(row.annotations[j].value)); // NaNs can't
239 hasText |= (row.annotations[j].description != null
240 && row.annotations[j].description.length() > 0);
244 if (row.graph == AlignmentAnnotation.NO_GRAPH)
246 text.append("NO_GRAPH\t");
247 hasValues = false; // only secondary structure
248 // hasLabels = false; // and annotation description string.
252 if (row.graph == AlignmentAnnotation.BAR_GRAPH)
254 text.append("BAR_GRAPH\t");
255 hasGlyphs = false; // no secondary structure
258 else if (row.graph == AlignmentAnnotation.LINE_GRAPH)
260 hasGlyphs = false; // no secondary structure
261 text.append("LINE_GRAPH\t");
264 if (row.getThreshold() != null)
266 graphLine.append("GRAPHLINE\t");
267 graphLine.append(row.label);
268 graphLine.append("\t");
269 graphLine.append(row.getThreshold().value);
270 graphLine.append("\t");
271 graphLine.append(row.getThreshold().label);
272 graphLine.append("\t");
273 graphLine.append(jalview.util.Format
274 .getHexString(row.getThreshold().colour));
275 graphLine.append(newline);
278 if (row.graphGroup > -1)
280 graphGroupSeen.set(row.graphGroup);
281 Integer key = new Integer(row.graphGroup);
282 if (graphGroup.containsKey(key))
284 graphGroup.put(key, graphGroup.get(key) + "\t" + row.label);
289 graphGroup_refs.put(key, new Object[] { refSeq, refGroup });
290 graphGroup.put(key, row.label);
295 text.append(row.label + "\t");
296 if (row.description != null)
298 text.append(row.description + "\t");
300 for (int j = 0; row.annotations != null
301 && j < row.annotations.length; j++)
304 && jalview.util.Comparison.isGap(refSeq.getCharAt(j)))
309 if (row.annotations[j] != null)
312 if (hasGlyphs) // could be also hasGlyphs || ...
316 if (row.annotations[j].secondaryStructure != ' ')
318 // only write out the field if its not whitespace.
319 text.append(row.annotations[j].secondaryStructure);
325 if (!Float.isNaN(row.annotations[j].value))
327 text.append(comma + row.annotations[j].value);
331 // System.err.println("Skipping NaN - not valid value.");
332 text.append(comma + 0f);// row.annotations[j].value);
338 // TODO: labels are emitted after values for bar graphs.
339 if // empty labels are allowed, so
340 (row.annotations[j].displayCharacter != null
341 && row.annotations[j].displayCharacter.length() > 0
342 && !row.annotations[j].displayCharacter.equals(" "))
344 text.append(comma + row.annotations[j].displayCharacter);
350 if (row.annotations[j].description != null
351 && row.annotations[j].description.length() > 0
352 && !row.annotations[j].description
353 .equals(row.annotations[j].displayCharacter))
355 text.append(comma + row.annotations[j].description);
359 if (color != null && !color.equals(row.annotations[j].colour))
364 color = row.annotations[j].colour;
366 if (row.annotations[j].colour != null
367 && row.annotations[j].colour != java.awt.Color.black)
369 text.append(comma + "[" + jalview.util.Format
370 .getHexString(row.annotations[j].colour) + "]");
379 text.append("\t" + row.score);
382 text.append(newline);
384 if (color != null && color != java.awt.Color.black && oneColour)
386 colours.append("COLOUR\t");
387 colours.append(row.label);
388 colours.append("\t");
389 colours.append(jalview.util.Format.getHexString(color));
390 colours.append(newline);
392 if (row.scaleColLabel || row.showAllColLabels
393 || row.centreColLabels)
395 rowprops.append("ROWPROPERTIES\t");
396 rowprops.append(row.label);
397 rowprops.append("\tscaletofit=");
398 rowprops.append(row.scaleColLabel);
399 rowprops.append("\tshowalllabs=");
400 rowprops.append(row.showAllColLabels);
401 rowprops.append("\tcentrelabs=");
402 rowprops.append(row.centreColLabels);
403 rowprops.append(newline);
405 if (graphLine.length() > 0)
407 text.append(graphLine.toString());
408 graphLine.setLength(0);
412 text.append(newline);
414 text.append(colours.toString());
415 if (graphGroup.size() > 0)
417 SequenceI oldRefSeq = refSeq;
418 SequenceGroup oldRefGroup = refGroup;
419 for (Map.Entry<Integer, String> combine_statement : graphGroup
422 Object[] seqRefAndGroup = graphGroup_refs
423 .get(combine_statement.getKey());
425 writeSequence_Ref(refSeq, (SequenceI) seqRefAndGroup[0]);
426 refSeq = (SequenceI) seqRefAndGroup[0];
428 writeGroup_Ref(refGroup, (SequenceGroup) seqRefAndGroup[1]);
429 refGroup = (SequenceGroup) seqRefAndGroup[1];
430 text.append("COMBINE\t");
431 text.append(combine_statement.getValue());
432 text.append(newline);
434 writeSequence_Ref(refSeq, oldRefSeq);
437 writeGroup_Ref(refGroup, oldRefGroup);
438 refGroup = oldRefGroup;
440 text.append(rowprops.toString());
448 if (properties != null)
450 text.append(newline);
451 text.append(newline);
452 text.append("ALIGNMENT");
453 Enumeration en = properties.keys();
454 while (en.hasMoreElements())
456 String key = en.nextElement().toString();
460 text.append(properties.get(key));
462 // TODO: output alignment visualization settings here if required
463 // iterate through one or more views, defining, marking columns and rows
464 // as visible/hidden, and emmitting view properties.
465 // View specific annotation is
468 return text.toString();
471 private Object writeGroup_Ref(SequenceGroup refGroup,
472 SequenceGroup next_refGroup)
474 if (next_refGroup == null)
477 if (refGroup != null)
479 text.append(newline);
480 text.append("GROUP_REF\t");
481 text.append("ALIGNMENT");
482 text.append(newline);
488 if (refGroup == null || refGroup != next_refGroup)
490 text.append(newline);
491 text.append("GROUP_REF\t");
492 text.append(next_refGroup.getName());
493 text.append(newline);
500 private boolean writeSequence_Ref(SequenceI refSeq, SequenceI next_refSeq)
503 if (next_refSeq == null)
507 text.append(newline);
508 text.append("SEQUENCE_REF\t");
509 text.append("ALIGNMENT");
510 text.append(newline);
516 if (refSeq == null || refSeq != next_refSeq)
518 text.append(newline);
519 text.append("SEQUENCE_REF\t");
520 text.append(next_refSeq.getName());
521 text.append(newline);
528 protected void printGroups(List<SequenceGroup> list)
530 SequenceI seqrep = null;
531 for (SequenceGroup sg : list)
535 text.append("SEQUENCE_GROUP\t" + sg.getName() + "\t"
536 + (sg.getStartRes() + 1) + "\t" + (sg.getEndRes() + 1)
542 seqrep = sg.getSeqrep();
543 text.append("SEQUENCE_REF\t");
544 text.append(seqrep.getName());
545 text.append(newline);
546 text.append("SEQUENCE_GROUP\t");
547 text.append(sg.getName());
549 text.append((seqrep.findPosition(sg.getStartRes())));
551 text.append((seqrep.findPosition(sg.getEndRes())));
555 for (int s = 0; s < sg.getSize(); s++)
557 text.append(sg.getSequenceAt(s).getName());
560 text.append(newline);
561 text.append("PROPERTIES\t");
562 text.append(sg.getName());
565 if (sg.getDescription() != null)
567 text.append("description=");
568 text.append(sg.getDescription());
573 text.append("colour=");
574 text.append(ColourSchemeProperty
575 .getColourName(sg.cs.getColourScheme()));
577 if (sg.cs.getThreshold() != 0)
579 text.append("pidThreshold=");
580 text.append(sg.cs.getThreshold());
582 if (sg.cs.conservationApplied())
584 text.append("consThreshold=");
585 text.append(sg.cs.getConservationInc());
589 text.append("outlineColour=");
590 text.append(jalview.util.Format.getHexString(sg.getOutlineColour()));
593 text.append("displayBoxes=");
594 text.append(sg.getDisplayBoxes());
596 text.append("displayText=");
597 text.append(sg.getDisplayText());
599 text.append("colourText=");
600 text.append(sg.getColourText());
602 text.append("showUnconserved=");
603 text.append(sg.getShowNonconserved());
605 if (sg.textColour != java.awt.Color.black)
607 text.append("textCol1=");
608 text.append(jalview.util.Format.getHexString(sg.textColour));
611 if (sg.textColour2 != java.awt.Color.white)
613 text.append("textCol2=");
614 text.append(jalview.util.Format.getHexString(sg.textColour2));
617 if (sg.thresholdTextColour != 0)
619 text.append("textColThreshold=");
620 text.append(sg.thresholdTextColour);
623 if (sg.idColour != null)
625 text.append("idColour=");
626 text.append(jalview.util.Format.getHexString(sg.idColour));
631 text.append("hide=true\t");
635 text.append("hidecols=true\t");
639 // terminate the last line and clear the sequence ref for the group
640 text.append(newline);
641 text.append("SEQUENCE_REF");
643 text.append(newline);
644 text.append(newline);
649 SequenceI refSeq = null;
651 String refSeqId = null;
653 public boolean annotateAlignmentView(AlignViewportI viewport, String file,
654 DataSourceType protocol)
656 ColumnSelection colSel = viewport.getColumnSelection();
657 HiddenColumns hidden = viewport.getAlignment().getHiddenColumns();
660 colSel = new ColumnSelection();
664 hidden = new HiddenColumns();
666 boolean rslt = readAnnotationFile(viewport.getAlignment(), hidden, file,
668 if (rslt && (colSel.hasSelectedColumns() || hidden.hasHiddenColumns()))
670 viewport.setColumnSelection(colSel);
671 viewport.getAlignment().setHiddenColumns(hidden);
677 public boolean readAnnotationFile(AlignmentI al, String file,
678 DataSourceType sourceType)
680 return readAnnotationFile(al, null, file, sourceType);
683 public boolean readAnnotationFile(AlignmentI al, HiddenColumns hidden,
684 String file, DataSourceType sourceType)
686 BufferedReader in = null;
689 if (sourceType == DataSourceType.FILE)
691 in = new BufferedReader(new FileReader(file));
693 else if (sourceType == DataSourceType.URL)
695 URL url = new URL(file);
696 in = new BufferedReader(new InputStreamReader(url.openStream()));
698 else if (sourceType == DataSourceType.PASTE)
700 in = new BufferedReader(new StringReader(file));
702 else if (sourceType == DataSourceType.CLASSLOADER)
704 java.io.InputStream is = getClass().getResourceAsStream("/" + file);
707 in = new BufferedReader(new java.io.InputStreamReader(is));
712 return parseAnnotationFrom(al, hidden, in);
715 } catch (Exception ex)
717 ex.printStackTrace();
718 System.out.println("Problem reading annotation file: " + ex);
721 System.out.println("Last read line " + nlinesread + ": '" + lastread
722 + "' (first 80 chars) ...");
731 String lastread = "";
733 private static String GRAPHLINE = "GRAPHLINE", COMBINE = "COMBINE";
735 public boolean parseAnnotationFrom(AlignmentI al, HiddenColumns hidden,
736 BufferedReader in) throws Exception
739 List<Object[]> combineAnnotation_calls = new ArrayList<>();
740 List<Object[]> deferredAnnotation_calls = new ArrayList<>();
741 boolean modified = false;
742 String groupRef = null;
743 Map<String, Vector<AlignmentAnnotation>> groupRefRows = new HashMap<>();
745 Set<String> autoAnnots = new HashSet<>();
746 String line, label, description, token;
747 int graphStyle, index;
749 int existingAnnotationCount = 0;
750 // when true - will add new rows regardless of whether they are duplicate
751 // auto-annotation like consensus or conservation graphs
752 boolean overrideAutoAnnot = false;
753 if (al.getAlignmentAnnotation() != null)
755 existingAnnotationCount = al.getAlignmentAnnotation().length;
756 if (existingAnnotationCount > 0)
758 AlignmentAnnotation[] aa = al.getAlignmentAnnotation();
759 for (int aai = 0; aai < aa.length; aai++)
761 if (aa[aai].autoCalculated)
763 // make a note of the name and description
764 autoAnnots.add(autoAnnotsKey(aa[aai], aa[aai].sequenceRef,
765 (aa[aai].groupRef == null ? null
766 : 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 || line.indexOf("JALVIEW_ANNOTATION") > -1
807 || line.length() == 0)
812 st = new StringTokenizer(line, "\t");
813 token = st.nextToken();
814 if (token.equalsIgnoreCase("COLOUR"))
816 // TODO: use graduated colour def'n here too
817 colourAnnotations(al, st.nextToken(), st.nextToken());
822 else if (token.equalsIgnoreCase(COMBINE))
824 // keep a record of current state and resolve groupRef at end
825 combineAnnotation_calls.add(new Object[] { st, refSeq, groupRef });
829 else if (token.equalsIgnoreCase("ROWPROPERTIES"))
831 addRowProperties(al, st);
835 else if (token.equalsIgnoreCase(GRAPHLINE))
838 deferredAnnotation_calls
840 { GRAPHLINE, st, refSeq, groupRef });
845 else if (token.equalsIgnoreCase("SEQUENCE_REF"))
847 if (st.hasMoreTokens())
849 refSeq = al.findName(refSeqId = st.nextToken());
856 refSeqIndex = Integer.parseInt(st.nextToken());
861 "WARNING: SEQUENCE_REF index must be > 0 in AnnotationFile");
863 } catch (Exception ex)
875 else if (token.equalsIgnoreCase("GROUP_REF"))
877 // Group references could be forward or backwards, so they are
878 // resolved after the whole file is read in
880 if (st.hasMoreTokens())
882 groupRef = st.nextToken();
883 if (groupRef.length() < 1)
885 groupRef = null; // empty string
889 if (groupRefRows.get(groupRef) == null)
891 groupRefRows.put(groupRef, new Vector<>());
897 else if (token.equalsIgnoreCase("SEQUENCE_GROUP"))
904 else if (token.equalsIgnoreCase("PROPERTIES"))
906 addProperties(al, st);
911 else if (token.equalsIgnoreCase("BELOW_ALIGNMENT"))
913 setBelowAlignment(al, st);
917 else if (token.equalsIgnoreCase("ALIGNMENT"))
919 addAlignmentDetails(al, st);
923 // else if (token.equalsIgnoreCase("VIEW_DEF"))
925 // addOrSetView(al,st);
929 else if (token.equalsIgnoreCase("VIEW_SETREF"))
933 al.setSeqrep(refSeq);
938 else if (token.equalsIgnoreCase("VIEW_HIDECOLS"))
940 if (st.hasMoreTokens())
944 hidden = new HiddenColumns();
946 parseHideCols(hidden, st.nextToken());
951 else if (token.equalsIgnoreCase("HIDE_INSERTIONS"))
953 SequenceI sr = refSeq == null ? al.getSeqrep() : refSeq;
956 sr = al.getSequenceAt(0);
963 "Cannot process HIDE_INSERTIONS without an alignment view: Ignoring line: "
968 // consider deferring this till after the file has been parsed ?
969 hidden.hideList(sr.getInsertions());
976 // Parse out the annotation row
977 graphStyle = AlignmentAnnotation.getGraphValueFromString(token);
978 label = st.nextToken();
981 annotations = new Annotation[alWidth];
983 float score = Float.NaN;
985 if (st.hasMoreTokens())
987 line = st.nextToken();
989 if (line.indexOf("|") == -1)
992 if (st.hasMoreTokens())
994 line = st.nextToken();
998 if (st.hasMoreTokens())
1000 // This must be the score
1001 score = Float.valueOf(st.nextToken()).floatValue();
1004 st = new StringTokenizer(line, "|", true);
1006 boolean emptyColumn = true;
1007 boolean onlyOneElement = (st.countTokens() == 1);
1009 while (st.hasMoreElements() && index < alWidth)
1011 token = st.nextToken().trim();
1017 score = Float.valueOf(token).floatValue();
1019 } catch (NumberFormatException ex)
1024 if (token.equals("|"))
1035 annotations[index++] = parseAnnotation(token, graphStyle);
1036 emptyColumn = false;
1042 annotation = new AlignmentAnnotation(label, description,
1043 (index == 0) ? null : annotations, 0, 0, graphStyle);
1045 annotation.score = score;
1046 if (!overrideAutoAnnot && autoAnnots
1047 .contains(autoAnnotsKey(annotation, refSeq, groupRef)))
1049 // skip - we've already got an automatic annotation of this type.
1052 // otherwise add it!
1056 annotation.belowAlignment = false;
1057 // make a copy of refSeq so we can find other matches in the alignment
1058 SequenceI referedSeq = refSeq;
1061 // copy before we do any mapping business.
1062 // TODO: verify that undo/redo with 1:many sequence associated
1063 // annotations can be undone correctly
1064 AlignmentAnnotation ann = new AlignmentAnnotation(annotation);
1065 annotation.createSequenceMapping(referedSeq, refSeqIndex, false);
1066 annotation.adjustForAlignment();
1067 referedSeq.addAlignmentAnnotation(annotation);
1068 al.addAnnotation(annotation);
1069 al.setAnnotationIndex(annotation,
1070 al.getAlignmentAnnotation().length
1071 - existingAnnotationCount - 1);
1072 if (groupRef != null)
1074 groupRefRows.get(groupRef).addElement(annotation);
1076 // and recover our virgin copy to use again if necessary.
1079 } while (refSeqId != null && (referedSeq = al.findName(referedSeq,
1080 refSeqId, true)) != null);
1084 al.addAnnotation(annotation);
1085 al.setAnnotationIndex(annotation, al.getAlignmentAnnotation().length
1086 - existingAnnotationCount - 1);
1087 if (groupRef != null)
1089 groupRefRows.get(groupRef).addElement(annotation);
1092 // and set modification flag
1095 // Resolve the groupRefs
1096 Hashtable<String, SequenceGroup> groupRefLookup = new Hashtable<>();
1097 Iterator<String> en = groupRefRows.keySet().iterator();
1099 while (en.hasNext())
1101 groupRef = en.next();
1102 boolean matched = false;
1103 // Resolve group: TODO: add a getGroupByName method to alignments
1104 for (SequenceGroup theGroup : al.getGroups())
1106 if (theGroup.getName().equals(groupRef))
1110 // TODO: specify and implement duplication of alignment annotation
1111 // for multiple group references.
1113 "Ignoring 1:many group reference mappings for group name '"
1119 Vector<AlignmentAnnotation> rowset = groupRefRows.get(groupRef);
1120 groupRefLookup.put(groupRef, theGroup);
1121 if (rowset != null && rowset.size() > 0)
1123 AlignmentAnnotation alan = null;
1124 for (int elm = 0, elmSize = rowset
1125 .size(); elm < elmSize; elm++)
1127 alan = rowset.elementAt(elm);
1128 alan.groupRef = theGroup;
1134 groupRefRows.get(groupRef).removeAllElements();
1136 // process any deferred attribute settings for each context
1137 for (Object[] _deferred_args : deferredAnnotation_calls)
1139 if (_deferred_args[0] == GRAPHLINE)
1141 addLine(al, (StringTokenizer) _deferred_args[1], // st
1142 (SequenceI) _deferred_args[2], // refSeq
1143 (_deferred_args[3] == null) ? null
1144 : groupRefLookup.get(_deferred_args[3]) // the
1152 // finally, combine all the annotation rows within each context.
1154 * number of combine statements in this annotation file. Used to create new
1155 * groups for combined annotation graphs without disturbing existing ones
1157 int combinecount = 0;
1158 for (Object[] _combine_args : combineAnnotation_calls)
1160 combineAnnotations(al, ++combinecount,
1161 (StringTokenizer) _combine_args[0], // st
1162 (SequenceI) _combine_args[1], // refSeq
1163 (_combine_args[2] == null) ? null
1164 : groupRefLookup.get(_combine_args[2]) // the reference
1173 private void parseHideCols(HiddenColumns hidden, String nextToken)
1175 StringTokenizer inval = new StringTokenizer(nextToken, ",");
1176 while (inval.hasMoreTokens())
1178 String range = inval.nextToken().trim();
1179 int from, to = range.indexOf("-");
1182 from = to = Integer.parseInt(range);
1185 hidden.hideColumns(from, to);
1190 from = Integer.parseInt(range.substring(0, to));
1191 if (to < range.length() - 1)
1193 to = Integer.parseInt(range.substring(to + 1));
1199 if (from > 0 && to >= from)
1201 hidden.hideColumns(from, to);
1207 private String autoAnnotsKey(AlignmentAnnotation annotation,
1208 SequenceI refSeq, String groupRef)
1210 return annotation.graph + "\t" + annotation.label + "\t"
1211 + annotation.description + "\t"
1212 + (refSeq != null ? refSeq.getDisplayId(true) : "");
1215 Annotation parseAnnotation(String string, int graphStyle)
1217 // don't do the glyph test if we don't want secondary structure
1218 boolean hasSymbols = (graphStyle == AlignmentAnnotation.NO_GRAPH);
1219 String desc = null, displayChar = null;
1220 char ss = ' '; // secondaryStructure
1222 boolean parsedValue = false, dcset = false;
1225 Color colour = null;
1226 int i = string.indexOf("[");
1227 int j = string.indexOf("]");
1228 if (i > -1 && j > -1)
1230 colour = ColorUtils.parseColourString(string.substring(i + 1, j));
1231 if (i > 0 && string.charAt(i - 1) == ',')
1233 // clip the preceding comma as well
1236 string = string.substring(0, i) + string.substring(j + 1);
1239 StringTokenizer st = new StringTokenizer(string, ",", true);
1241 boolean seenContent = false;
1243 while (st.hasMoreTokens())
1246 token = st.nextToken().trim();
1247 if (token.equals(","))
1249 if (!seenContent && parsedValue && !dcset)
1251 // allow the value below the bar/line to be empty
1255 seenContent = false;
1267 displayChar = token;
1269 value = new Float(token).floatValue();
1272 } catch (NumberFormatException ex)
1278 if (token.length() == 1)
1280 displayChar = token;
1283 if (hasSymbols && (token.length() == 1
1284 && "()<>[]{}AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz"
1287 // Either this character represents a helix or sheet
1288 // or an integer which can be displayed
1289 ss = token.charAt(0);
1290 if (displayChar.equals(token.substring(0, 1)))
1295 else if (desc == null || (parsedValue && pass > 2))
1301 // if (!dcset && string.charAt(string.length() - 1) == ',')
1303 // displayChar = " "; // empty display char symbol.
1305 if (displayChar != null && desc != null && desc.length() == 1)
1307 if (displayChar.length() > 1)
1309 // switch desc and displayChar - legacy support
1310 String tmp = displayChar;
1316 if (displayChar.equals(desc))
1318 // duplicate label - hangover from the 'robust parser' above
1323 Annotation anot = new Annotation(displayChar, desc, ss, value);
1325 anot.colour = colour;
1330 void colourAnnotations(AlignmentI al, String label, String colour)
1332 Color awtColour = ColorUtils.parseColourString(colour);
1333 Annotation[] annotations;
1334 for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1336 if (al.getAlignmentAnnotation()[i].label.equalsIgnoreCase(label))
1338 annotations = al.getAlignmentAnnotation()[i].annotations;
1339 for (int j = 0; j < annotations.length; j++)
1341 if (annotations[j] != null)
1343 annotations[j].colour = awtColour;
1350 void combineAnnotations(AlignmentI al, int combineCount,
1351 StringTokenizer st, SequenceI seqRef, SequenceGroup groupRef)
1353 String group = st.nextToken();
1354 // First make sure we are not overwriting the graphIndex
1356 if (al.getAlignmentAnnotation() != null)
1358 for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1360 AlignmentAnnotation aa = al.getAlignmentAnnotation()[i];
1362 if (aa.graphGroup > graphGroup)
1364 // try to number graphGroups in order of occurence.
1365 graphGroup = aa.graphGroup + 1;
1367 if (aa.sequenceRef == seqRef && aa.groupRef == groupRef
1368 && aa.label.equalsIgnoreCase(group))
1370 if (aa.graphGroup > -1)
1372 graphGroup = aa.graphGroup;
1376 if (graphGroup <= combineCount)
1378 graphGroup = combineCount + 1;
1380 aa.graphGroup = graphGroup;
1386 // Now update groups
1387 while (st.hasMoreTokens())
1389 group = st.nextToken();
1390 for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1392 AlignmentAnnotation aa = al.getAlignmentAnnotation()[i];
1393 if (aa.sequenceRef == seqRef && aa.groupRef == groupRef
1394 && aa.label.equalsIgnoreCase(group))
1396 aa.graphGroup = graphGroup;
1405 "Couldn't combine annotations. None are added to alignment yet!");
1409 void addLine(AlignmentI al, StringTokenizer st, SequenceI seqRef,
1410 SequenceGroup groupRef)
1412 String group = st.nextToken();
1413 AlignmentAnnotation[] alannot = al.getAlignmentAnnotation();
1414 String nextToken = st.nextToken();
1418 value = Float.valueOf(nextToken);
1419 } catch (NumberFormatException e)
1421 System.err.println("line " + nlinesread + ": Threshold '" + nextToken
1422 + "' invalid, setting to zero");
1424 String label = st.hasMoreTokens() ? st.nextToken() : null;
1425 Color colour = null;
1426 if (st.hasMoreTokens())
1428 colour = ColorUtils.parseColourString(st.nextToken());
1430 if (alannot != null)
1432 for (int i = 0; i < alannot.length; i++)
1434 if (alannot[i].label.equalsIgnoreCase(group)
1435 && (seqRef == null || alannot[i].sequenceRef == seqRef)
1436 && (groupRef == null || alannot[i].groupRef == groupRef))
1438 alannot[i].setThreshold(new GraphLine(value, label, colour));
1444 void addGroup(AlignmentI al, StringTokenizer st)
1446 SequenceGroup sg = new SequenceGroup();
1447 sg.setName(st.nextToken());
1451 rng = st.nextToken();
1452 if (rng.length() > 0 && !rng.startsWith("*"))
1454 sg.setStartRes(Integer.parseInt(rng) - 1);
1460 rng = st.nextToken();
1461 if (rng.length() > 0 && !rng.startsWith("*"))
1463 sg.setEndRes(Integer.parseInt(rng) - 1);
1467 sg.setEndRes(al.getWidth() - 1);
1469 } catch (Exception e)
1472 "Couldn't parse Group Start or End Field as '*' or a valid column or sequence index: '"
1473 + rng + "' - assuming alignment width for group.");
1474 // assume group is full width
1476 sg.setEndRes(al.getWidth() - 1);
1479 String index = st.nextToken();
1480 if (index.equals("-1"))
1482 while (st.hasMoreElements())
1484 sg.addSequence(al.findName(st.nextToken()), false);
1489 StringTokenizer st2 = new StringTokenizer(index, ",");
1491 while (st2.hasMoreTokens())
1493 String tmp = st2.nextToken();
1494 if (tmp.equals("*"))
1496 for (int i = 0; i < al.getHeight(); i++)
1498 sg.addSequence(al.getSequenceAt(i), false);
1501 else if (tmp.indexOf("-") >= 0)
1503 StringTokenizer st3 = new StringTokenizer(tmp, "-");
1505 int start = (Integer.parseInt(st3.nextToken()));
1506 int end = (Integer.parseInt(st3.nextToken()));
1510 for (int i = start; i <= end; i++)
1512 sg.addSequence(al.getSequenceAt(i - 1), false);
1518 sg.addSequence(al.getSequenceAt(Integer.parseInt(tmp) - 1),
1526 sg.setStartRes(refSeq.findIndex(sg.getStartRes() + 1) - 1);
1527 sg.setEndRes(refSeq.findIndex(sg.getEndRes() + 1) - 1);
1528 sg.setSeqrep(refSeq);
1531 if (sg.getSize() > 0)
1537 void addRowProperties(AlignmentI al, StringTokenizer st)
1539 String label = st.nextToken(), keyValue, key, value;
1540 boolean scaletofit = false, centerlab = false, showalllabs = false;
1541 while (st.hasMoreTokens())
1543 keyValue = st.nextToken();
1544 key = keyValue.substring(0, keyValue.indexOf("="));
1545 value = keyValue.substring(keyValue.indexOf("=") + 1);
1546 if (key.equalsIgnoreCase("scaletofit"))
1548 scaletofit = Boolean.valueOf(value).booleanValue();
1550 if (key.equalsIgnoreCase("showalllabs"))
1552 showalllabs = Boolean.valueOf(value).booleanValue();
1554 if (key.equalsIgnoreCase("centrelabs"))
1556 centerlab = Boolean.valueOf(value).booleanValue();
1558 AlignmentAnnotation[] alr = al.getAlignmentAnnotation();
1561 for (int i = 0; i < alr.length; i++)
1563 if (alr[i].label.equalsIgnoreCase(label))
1565 alr[i].centreColLabels = centerlab;
1566 alr[i].scaleColLabel = scaletofit;
1567 alr[i].showAllColLabels = showalllabs;
1574 void addProperties(AlignmentI al, StringTokenizer st)
1577 // So far we have only added groups to the annotationHash,
1578 // the idea is in the future properties can be added to
1579 // alignments, other annotations etc
1580 if (al.getGroups() == null)
1585 String name = st.nextToken();
1586 SequenceGroup sg = null;
1587 for (SequenceGroup _sg : al.getGroups())
1589 if ((sg = _sg).getName().equals(name))
1601 String keyValue, key, value;
1602 ColourSchemeI def = sg.getColourScheme();
1603 while (st.hasMoreTokens())
1605 keyValue = st.nextToken();
1606 key = keyValue.substring(0, keyValue.indexOf("="));
1607 value = keyValue.substring(keyValue.indexOf("=") + 1);
1609 if (key.equalsIgnoreCase("description"))
1611 sg.setDescription(value);
1613 else if (key.equalsIgnoreCase("colour"))
1615 // TODO need to notify colourscheme of view reference once it is
1617 sg.cs.setColourScheme(
1618 ColourSchemeProperty.getColourScheme(null, al, value));
1620 else if (key.equalsIgnoreCase("pidThreshold"))
1622 sg.cs.setThreshold(Integer.parseInt(value), true);
1625 else if (key.equalsIgnoreCase("consThreshold"))
1627 sg.cs.setConservationInc(Integer.parseInt(value));
1628 Conservation c = new Conservation("Group", sg.getSequences(null),
1629 sg.getStartRes(), sg.getEndRes() + 1);
1632 c.verdict(false, 25); // TODO: refer to conservation percent threshold
1634 sg.cs.setConservation(c);
1637 else if (key.equalsIgnoreCase("outlineColour"))
1639 sg.setOutlineColour(ColorUtils.parseColourString(value));
1641 else if (key.equalsIgnoreCase("displayBoxes"))
1643 sg.setDisplayBoxes(Boolean.valueOf(value).booleanValue());
1645 else if (key.equalsIgnoreCase("showUnconserved"))
1647 sg.setShowNonconserved(Boolean.valueOf(value).booleanValue());
1649 else if (key.equalsIgnoreCase("displayText"))
1651 sg.setDisplayText(Boolean.valueOf(value).booleanValue());
1653 else if (key.equalsIgnoreCase("colourText"))
1655 sg.setColourText(Boolean.valueOf(value).booleanValue());
1657 else if (key.equalsIgnoreCase("textCol1"))
1659 sg.textColour = ColorUtils.parseColourString(value);
1661 else if (key.equalsIgnoreCase("textCol2"))
1663 sg.textColour2 = ColorUtils.parseColourString(value);
1665 else if (key.equalsIgnoreCase("textColThreshold"))
1667 sg.thresholdTextColour = Integer.parseInt(value);
1669 else if (key.equalsIgnoreCase("idColour"))
1671 Color idColour = ColorUtils.parseColourString(value);
1672 sg.setIdColour(idColour == null ? Color.black : idColour);
1674 else if (key.equalsIgnoreCase("hide"))
1676 // see bug https://mantis.lifesci.dundee.ac.uk/view.php?id=25847
1677 sg.setHidereps(true);
1679 else if (key.equalsIgnoreCase("hidecols"))
1681 // see bug https://mantis.lifesci.dundee.ac.uk/view.php?id=25847
1682 sg.setHideCols(true);
1684 sg.recalcConservation();
1686 if (sg.getColourScheme() == null)
1688 sg.setColourScheme(def);
1693 void setBelowAlignment(AlignmentI al, StringTokenizer st)
1696 AlignmentAnnotation aa, ala[] = al.getAlignmentAnnotation();
1700 "Warning - no annotation to set below for sequence associated annotation:");
1702 while (st.hasMoreTokens())
1704 token = st.nextToken();
1707 System.err.print(" " + token);
1711 for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1713 aa = al.getAlignmentAnnotation()[i];
1714 if (aa.sequenceRef == refSeq && aa.label.equals(token))
1716 aa.belowAlignment = true;
1723 System.err.print("\n");
1727 void addAlignmentDetails(AlignmentI al, StringTokenizer st)
1729 String keyValue, key, value;
1730 while (st.hasMoreTokens())
1732 keyValue = st.nextToken();
1733 key = keyValue.substring(0, keyValue.indexOf("="));
1734 value = keyValue.substring(keyValue.indexOf("=") + 1);
1735 al.setProperty(key, value);
1740 * Write annotations as a CSV file of the form 'label, value, value, ...' for
1743 * @param annotations
1744 * @return CSV file as a string.
1746 public String printCSVAnnotations(AlignmentAnnotation[] annotations)
1748 if (annotations == null)
1752 StringBuffer sp = new StringBuffer();
1753 for (int i = 0; i < annotations.length; i++)
1755 String atos = annotations[i].toString();
1759 int cp = atos.indexOf("\n", p);
1760 sp.append(annotations[i].label);
1764 sp.append(atos.substring(p, cp + 1));
1768 sp.append(atos.substring(p));
1774 return sp.toString();
1777 public String printAnnotationsForView(AlignViewportI viewport)
1779 return printAnnotations(
1780 viewport.isShowAnnotation()
1781 ? viewport.getAlignment().getAlignmentAnnotation()
1783 viewport.getAlignment().getGroups(),
1784 viewport.getAlignment().getProperties(),
1785 viewport.getAlignment().getHiddenColumns(),
1786 viewport.getAlignment(), null);
1789 public String printAnnotationsForAlignment(AlignmentI al)
1791 return printAnnotations(al.getAlignmentAnnotation(), al.getGroups(),
1792 al.getProperties(), null, al, null);