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.HiddenSequences;
31 import jalview.datamodel.SequenceGroup;
32 import jalview.datamodel.SequenceI;
33 import jalview.schemes.ColourSchemeI;
34 import jalview.schemes.ColourSchemeProperty;
35 import jalview.schemes.ResidueProperties;
36 import jalview.schemes.UserColourScheme;
38 import java.io.BufferedReader;
39 import java.io.FileReader;
40 import java.io.InputStreamReader;
41 import java.io.StringReader;
43 import java.util.ArrayList;
44 import java.util.BitSet;
45 import java.util.Enumeration;
46 import java.util.Hashtable;
47 import java.util.List;
49 import java.util.StringTokenizer;
50 import java.util.Vector;
52 public class AnnotationFile
54 public AnnotationFile()
60 * character used to write newlines
62 protected String newline = System.getProperty("line.separator");
65 * set new line string and reset the output buffer
69 public void setNewlineString(String nl)
75 public String getNewlineString()
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, null);
107 * hold all the information about a particular view definition read from or
108 * written out in an annotations file.
112 public String viewname;
114 public HiddenSequences hidseqs;
116 public ColumnSelection hiddencols;
118 public Vector visibleGroups;
120 public Hashtable hiddenRepSeqs;
122 public ViewDef(String viewname, HiddenSequences hidseqs,
123 ColumnSelection hiddencols, Hashtable hiddenRepSeqs)
125 this.viewname = viewname;
126 this.hidseqs = hidseqs;
127 this.hiddencols = hiddencols;
128 this.hiddenRepSeqs = hiddenRepSeqs;
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,
144 ColumnSelection cs, 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");
173 List<int[]> hc = cs.getHiddenColumns();
174 boolean comma = false;
191 // TODO: allow efficient recovery of annotation data shown in several
193 if (annotations != null)
195 boolean oneColour = true;
196 AlignmentAnnotation row;
198 SequenceI refSeq = null;
199 SequenceGroup refGroup = null;
201 StringBuffer colours = new StringBuffer();
202 StringBuffer graphLine = new StringBuffer();
203 StringBuffer rowprops = new StringBuffer();
204 Hashtable<Integer, String> graphGroup = new Hashtable<Integer, String>();
205 Hashtable<Integer, Object[]> graphGroup_refs = new Hashtable<Integer, Object[]>();
206 BitSet graphGroupSeen = new BitSet();
208 java.awt.Color color;
210 for (int i = 0; i < annotations.length; i++)
212 row = annotations[i];
216 && !(row.graphGroup > -1 && graphGroupSeen
217 .get(row.graphGroup)))
225 // mark any sequence references for the row
226 writeSequence_Ref(refSeq, row.sequenceRef);
227 refSeq = row.sequenceRef;
228 // mark any group references for the row
229 writeGroup_Ref(refGroup, row.groupRef);
230 refGroup = row.groupRef;
232 boolean hasGlyphs = row.hasIcons, hasLabels = row.hasText, hasValues = row.hasScore, hasText = false;
233 // lookahead to check what the annotation row object actually contains.
234 for (int j = 0; row.annotations != null
235 && j < row.annotations.length
236 && (!hasGlyphs || !hasLabels || !hasValues); j++)
238 if (row.annotations[j] != null)
240 hasLabels |= (row.annotations[j].displayCharacter != null
241 && row.annotations[j].displayCharacter.length() > 0 && !row.annotations[j].displayCharacter
243 hasGlyphs |= (row.annotations[j].secondaryStructure != 0 && row.annotations[j].secondaryStructure != ' ');
244 hasValues |= (!Float.isNaN(row.annotations[j].value)); // NaNs can't
247 hasText |= (row.annotations[j].description != null && row.annotations[j].description
252 if (row.graph == AlignmentAnnotation.NO_GRAPH)
254 text.append("NO_GRAPH\t");
255 hasValues = false; // only secondary structure
256 // hasLabels = false; // and annotation description string.
260 if (row.graph == AlignmentAnnotation.BAR_GRAPH)
262 text.append("BAR_GRAPH\t");
263 hasGlyphs = false; // no secondary structure
266 else if (row.graph == AlignmentAnnotation.LINE_GRAPH)
268 hasGlyphs = false; // no secondary structure
269 text.append("LINE_GRAPH\t");
272 if (row.getThreshold() != null)
274 graphLine.append("GRAPHLINE\t");
275 graphLine.append(row.label);
276 graphLine.append("\t");
277 graphLine.append(row.getThreshold().value);
278 graphLine.append("\t");
279 graphLine.append(row.getThreshold().label);
280 graphLine.append("\t");
281 graphLine.append(jalview.util.Format.getHexString(row
282 .getThreshold().colour));
283 graphLine.append(newline);
286 if (row.graphGroup > -1)
288 graphGroupSeen.set(row.graphGroup);
289 Integer key = new Integer(row.graphGroup);
290 if (graphGroup.containsKey(key))
292 graphGroup.put(key, graphGroup.get(key) + "\t" + row.label);
297 graphGroup_refs.put(key, new Object[] { refSeq, refGroup });
298 graphGroup.put(key, row.label);
303 text.append(row.label + "\t");
304 if (row.description != null)
306 text.append(row.description + "\t");
308 for (int j = 0; row.annotations != null
309 && j < row.annotations.length; j++)
312 && jalview.util.Comparison.isGap(refSeq.getCharAt(j)))
317 if (row.annotations[j] != null)
320 if (hasGlyphs) // could be also hasGlyphs || ...
324 if (row.annotations[j].secondaryStructure != ' ')
326 // only write out the field if its not whitespace.
327 text.append(row.annotations[j].secondaryStructure);
333 if (!Float.isNaN(row.annotations[j].value))
335 text.append(comma + row.annotations[j].value);
339 // System.err.println("Skipping NaN - not valid value.");
340 text.append(comma + 0f);// row.annotations[j].value);
346 // TODO: labels are emitted after values for bar graphs.
347 if // empty labels are allowed, so
348 (row.annotations[j].displayCharacter != null
349 && row.annotations[j].displayCharacter.length() > 0
350 && !row.annotations[j].displayCharacter.equals(" "))
352 text.append(comma + row.annotations[j].displayCharacter);
358 if (row.annotations[j].description != null
359 && row.annotations[j].description.length() > 0
360 && !row.annotations[j].description
361 .equals(row.annotations[j].displayCharacter))
363 text.append(comma + row.annotations[j].description);
367 if (color != null && !color.equals(row.annotations[j].colour))
372 color = row.annotations[j].colour;
374 if (row.annotations[j].colour != null
375 && row.annotations[j].colour != java.awt.Color.black)
379 + jalview.util.Format
380 .getHexString(row.annotations[j].colour)
390 text.append("\t" + row.score);
393 text.append(newline);
395 if (color != null && color != java.awt.Color.black && oneColour)
397 colours.append("COLOUR\t");
398 colours.append(row.label);
399 colours.append("\t");
400 colours.append(jalview.util.Format.getHexString(color));
401 colours.append(newline);
403 if (row.scaleColLabel || row.showAllColLabels
404 || row.centreColLabels)
406 rowprops.append("ROWPROPERTIES\t");
407 rowprops.append(row.label);
408 rowprops.append("\tscaletofit=");
409 rowprops.append(row.scaleColLabel);
410 rowprops.append("\tshowalllabs=");
411 rowprops.append(row.showAllColLabels);
412 rowprops.append("\tcentrelabs=");
413 rowprops.append(row.centreColLabels);
414 rowprops.append(newline);
416 if (graphLine.length() > 0)
418 text.append(graphLine.toString());
419 graphLine.setLength(0);
423 text.append(newline);
425 text.append(colours.toString());
426 if (graphGroup.size() > 0)
428 SequenceI oldRefSeq = refSeq;
429 SequenceGroup oldRefGroup = refGroup;
430 for (Map.Entry<Integer, String> combine_statement : graphGroup
433 Object[] seqRefAndGroup = graphGroup_refs.get(combine_statement
436 writeSequence_Ref(refSeq, (SequenceI) seqRefAndGroup[0]);
437 refSeq = (SequenceI) seqRefAndGroup[0];
439 writeGroup_Ref(refGroup, (SequenceGroup) seqRefAndGroup[1]);
440 refGroup = (SequenceGroup) seqRefAndGroup[1];
441 text.append("COMBINE\t");
442 text.append(combine_statement.getValue());
443 text.append(newline);
445 writeSequence_Ref(refSeq, oldRefSeq);
448 writeGroup_Ref(refGroup, oldRefGroup);
449 refGroup = oldRefGroup;
451 text.append(rowprops.toString());
459 if (properties != null)
461 text.append(newline);
462 text.append(newline);
463 text.append("ALIGNMENT");
464 Enumeration en = properties.keys();
465 while (en.hasMoreElements())
467 String key = en.nextElement().toString();
471 text.append(properties.get(key));
473 // TODO: output alignment visualization settings here if required
474 // iterate through one or more views, defining, marking columns and rows
475 // as visible/hidden, and emmitting view properties.
476 // View specific annotation is
479 return text.toString();
482 private Object writeGroup_Ref(SequenceGroup refGroup,
483 SequenceGroup next_refGroup)
485 if (next_refGroup == null)
488 if (refGroup != null)
490 text.append(newline);
491 text.append("GROUP_REF\t");
492 text.append("ALIGNMENT");
493 text.append(newline);
499 if (refGroup == null || refGroup != next_refGroup)
501 text.append(newline);
502 text.append("GROUP_REF\t");
503 text.append(next_refGroup.getName());
504 text.append(newline);
511 private boolean writeSequence_Ref(SequenceI refSeq, SequenceI next_refSeq)
514 if (next_refSeq == null)
518 text.append(newline);
519 text.append("SEQUENCE_REF\t");
520 text.append("ALIGNMENT");
521 text.append(newline);
527 if (refSeq == null || refSeq != next_refSeq)
529 text.append(newline);
530 text.append("SEQUENCE_REF\t");
531 text.append(next_refSeq.getName());
532 text.append(newline);
539 public void printGroups(List<SequenceGroup> list)
541 SequenceI seqrep = null;
542 for (SequenceGroup sg : list)
546 text.append("SEQUENCE_GROUP\t" + sg.getName() + "\t"
547 + (sg.getStartRes() + 1) + "\t" + (sg.getEndRes() + 1)
553 seqrep = sg.getSeqrep();
554 text.append("SEQUENCE_REF\t");
555 text.append(seqrep.getName());
556 text.append(newline);
557 text.append("SEQUENCE_GROUP\t");
558 text.append(sg.getName());
560 text.append((seqrep.findPosition(sg.getStartRes())));
562 text.append((seqrep.findPosition(sg.getEndRes())));
566 for (int s = 0; s < sg.getSize(); s++)
568 text.append(sg.getSequenceAt(s).getName());
571 text.append(newline);
572 text.append("PROPERTIES\t");
573 text.append(sg.getName());
576 if (sg.getDescription() != null)
578 text.append("description=");
579 text.append(sg.getDescription());
584 text.append("colour=");
585 text.append(ColourSchemeProperty.getColourName(sg.cs));
587 if (sg.cs.getThreshold() != 0)
589 text.append("pidThreshold=");
590 text.append(sg.cs.getThreshold());
592 if (sg.cs.conservationApplied())
594 text.append("consThreshold=");
595 text.append(sg.cs.getConservationInc());
599 text.append("outlineColour=");
600 text.append(jalview.util.Format.getHexString(sg.getOutlineColour()));
603 text.append("displayBoxes=");
604 text.append(sg.getDisplayBoxes());
606 text.append("displayText=");
607 text.append(sg.getDisplayText());
609 text.append("colourText=");
610 text.append(sg.getColourText());
612 text.append("showUnconserved=");
613 text.append(sg.getShowNonconserved());
615 if (sg.textColour != java.awt.Color.black)
617 text.append("textCol1=");
618 text.append(jalview.util.Format.getHexString(sg.textColour));
621 if (sg.textColour2 != java.awt.Color.white)
623 text.append("textCol2=");
624 text.append(jalview.util.Format.getHexString(sg.textColour2));
627 if (sg.thresholdTextColour != 0)
629 text.append("textColThreshold=");
630 text.append(sg.thresholdTextColour);
633 if (sg.idColour != null)
635 text.append("idColour=");
636 text.append(jalview.util.Format.getHexString(sg.idColour));
641 text.append("hide=true\t");
645 text.append("hidecols=true\t");
649 // terminate the last line and clear the sequence ref for the group
650 text.append(newline);
651 text.append("SEQUENCE_REF");
653 text.append(newline);
654 text.append(newline);
659 SequenceI refSeq = null;
661 String refSeqId = null;
663 public boolean annotateAlignmentView(AlignViewportI viewport,
664 String file, String protocol)
666 ColumnSelection colSel = viewport.getColumnSelection();
669 colSel = new ColumnSelection();
671 boolean rslt = readAnnotationFile(viewport.getAlignment(), colSel,
673 if (rslt && (colSel.hasSelectedColumns() || colSel.hasHiddenColumns()))
675 viewport.setColumnSelection(colSel);
681 public boolean readAnnotationFile(AlignmentI al, String file,
684 return readAnnotationFile(al, null, file, protocol);
687 public boolean readAnnotationFile(AlignmentI al, ColumnSelection colSel,
688 String file, String protocol)
690 BufferedReader in = null;
693 if (protocol.equals(AppletFormatAdapter.FILE))
695 in = new BufferedReader(new FileReader(file));
697 else if (protocol.equals(AppletFormatAdapter.URL))
699 URL url = new URL(file);
700 in = new BufferedReader(new InputStreamReader(url.openStream()));
702 else if (protocol.equals(AppletFormatAdapter.PASTE))
704 in = new BufferedReader(new StringReader(file));
706 else if (protocol.equals(AppletFormatAdapter.CLASSLOADER))
708 java.io.InputStream is = getClass().getResourceAsStream("/" + file);
711 in = new BufferedReader(new java.io.InputStreamReader(is));
716 return parseAnnotationFrom(al, colSel, in);
719 } catch (Exception ex)
721 ex.printStackTrace();
722 System.out.println("Problem reading annotation file: " + ex);
725 System.out.println("Last read line " + nlinesread + ": '"
726 + lastread + "' (first 80 chars) ...");
735 String lastread = "";
737 private static String GRAPHLINE = "GRAPHLINE", COMBINE = "COMBINE",
738 STRUCTMODEL = "STRUCTMODEL";
740 public boolean parseAnnotationFrom(AlignmentI al, ColumnSelection colSel,
741 BufferedReader in) throws Exception
744 ArrayList<Object[]> combineAnnotation_calls = new ArrayList<Object[]>();
745 ArrayList<Object[]> deferredAnnotation_calls = new ArrayList<Object[]>();
746 boolean modified = false;
747 String groupRef = null;
748 Hashtable groupRefRows = new Hashtable();
750 Hashtable autoAnnots = new Hashtable();
752 String line, label, description, token;
753 int graphStyle, index;
755 int existingAnnotations = 0;
756 // when true - will add new rows regardless of whether they are duplicate
757 // auto-annotation like consensus or conservation graphs
758 boolean overrideAutoAnnot = false;
759 if (al.getAlignmentAnnotation() != null)
761 existingAnnotations = al.getAlignmentAnnotation().length;
762 if (existingAnnotations > 0)
764 AlignmentAnnotation[] aa = al.getAlignmentAnnotation();
765 for (int aai = 0; aai < aa.length; aai++)
767 if (aa[aai].autoCalculated)
769 // make a note of the name and description
771 autoAnnotsKey(aa[aai], aa[aai].sequenceRef,
772 (aa[aai].groupRef == null ? null
773 : aa[aai].groupRef.getName())),
780 int alWidth = al.getWidth();
783 Annotation[] annotations;
784 AlignmentAnnotation annotation = null;
786 // First confirm this is an Annotation file
787 boolean jvAnnotationFile = false;
788 while ((line = in.readLine()) != null)
791 lastread = new String(line);
792 if (line.indexOf("#") == 0)
797 if (line.indexOf("JALVIEW_ANNOTATION") > -1)
799 jvAnnotationFile = true;
804 if (!jvAnnotationFile)
810 while ((line = in.readLine()) != null)
813 lastread = new String(line);
814 if (line.indexOf("#") == 0
815 || line.indexOf("JALVIEW_ANNOTATION") > -1
816 || line.length() == 0)
821 st = new StringTokenizer(line, "\t");
822 token = st.nextToken();
823 if (token.equalsIgnoreCase("COLOUR"))
825 // TODO: use graduated colour def'n here too
826 colourAnnotations(al, st.nextToken(), st.nextToken());
831 else if (token.equalsIgnoreCase(COMBINE))
833 // keep a record of current state and resolve groupRef at end
834 combineAnnotation_calls
835 .add(new Object[] { st, refSeq, groupRef });
839 else if (token.equalsIgnoreCase("ROWPROPERTIES"))
841 addRowProperties(al, st);
845 else if (token.equalsIgnoreCase(GRAPHLINE))
848 deferredAnnotation_calls.add(new Object[] { GRAPHLINE, st,
854 else if (token.equalsIgnoreCase("SEQUENCE_REF"))
856 if (st.hasMoreTokens())
858 refSeq = al.findName(refSeqId = st.nextToken());
865 refSeqIndex = Integer.parseInt(st.nextToken());
870 .println("WARNING: SEQUENCE_REF index must be > 0 in AnnotationFile");
872 } catch (Exception ex)
884 else if (token.equalsIgnoreCase("GROUP_REF"))
886 // Group references could be forward or backwards, so they are
887 // resolved after the whole file is read in
889 if (st.hasMoreTokens())
891 groupRef = st.nextToken();
892 if (groupRef.length() < 1)
894 groupRef = null; // empty string
898 if (groupRefRows.get(groupRef) == null)
900 groupRefRows.put(groupRef, new Vector());
906 else if (token.equalsIgnoreCase("SEQUENCE_GROUP"))
913 else if (token.equalsIgnoreCase("PROPERTIES"))
915 addProperties(al, st);
920 else if (token.equalsIgnoreCase("BELOW_ALIGNMENT"))
922 setBelowAlignment(al, st);
926 else if (token.equalsIgnoreCase("ALIGNMENT"))
928 addAlignmentDetails(al, st);
932 // else if (token.equalsIgnoreCase("VIEW_DEF"))
934 // addOrSetView(al,st);
938 else if (token.equalsIgnoreCase("VIEW_SETREF"))
942 al.setSeqrep(refSeq);
947 else if (token.equalsIgnoreCase("VIEW_HIDECOLS"))
949 if (st.hasMoreTokens())
953 colSel = new ColumnSelection();
955 parseHideCols(colSel, st.nextToken());
960 else if (token.equalsIgnoreCase("HIDE_INSERTIONS"))
962 SequenceI sr = refSeq == null ? al.getSeqrep() : refSeq;
965 sr = al.getSequenceAt(0);
972 .println("Cannot process HIDE_INSERTIONS without an alignment view: Ignoring line: "
977 // consider deferring this till after the file has been parsed ?
978 colSel.hideInsertionsFor(sr);
984 else if (token.equalsIgnoreCase(STRUCTMODEL))
986 boolean failedtoadd = true;
988 // STRUCTMODEL <QUERYID> <TemplateID> <URL to model> <URL to
990 if (st.hasMoreTokens()) {
991 refSeq = al.findName(refSeqId = st.nextToken());
994 System.err.println("Couldn't locate " + refSeqId
995 + " in the alignment for STRUCTMODEL");
1000 String tempId = st.nextToken();
1001 String urlToModel = st.nextToken();
1002 String urlToPairwise = st.hasMoreTokens() ? st.nextToken()
1004 if (add_structmodel(refSeq, tempId, urlToModel, urlToPairwise))
1006 failedtoadd = false;
1013 .println("Need <QueryId> <TemplateId> <URL to Model> [<URL to pairwise alignment>] as tab separated fields after "
1020 // Parse out the annotation row
1021 graphStyle = AlignmentAnnotation.getGraphValueFromString(token);
1022 label = st.nextToken();
1025 annotations = new Annotation[alWidth];
1027 float score = Float.NaN;
1029 if (st.hasMoreTokens())
1031 line = st.nextToken();
1033 if (line.indexOf("|") == -1)
1036 if (st.hasMoreTokens())
1038 line = st.nextToken();
1042 if (st.hasMoreTokens())
1044 // This must be the score
1045 score = Float.valueOf(st.nextToken()).floatValue();
1048 st = new StringTokenizer(line, "|", true);
1050 boolean emptyColumn = true;
1051 boolean onlyOneElement = (st.countTokens() == 1);
1053 while (st.hasMoreElements() && index < alWidth)
1055 token = st.nextToken().trim();
1061 score = Float.valueOf(token).floatValue();
1063 } catch (NumberFormatException ex)
1068 if (token.equals("|"))
1079 annotations[index++] = parseAnnotation(token, graphStyle);
1080 emptyColumn = false;
1086 annotation = new AlignmentAnnotation(label, description,
1087 (index == 0) ? null : annotations, 0, 0, graphStyle);
1089 annotation.score = score;
1090 if (!overrideAutoAnnot
1091 && autoAnnots.containsKey(autoAnnotsKey(annotation, refSeq,
1094 // skip - we've already got an automatic annotation of this type.
1097 // otherwise add it!
1101 annotation.belowAlignment = false;
1102 // make a copy of refSeq so we can find other matches in the alignment
1103 SequenceI referedSeq = refSeq;
1106 // copy before we do any mapping business.
1107 // TODO: verify that undo/redo with 1:many sequence associated
1108 // annotations can be undone correctly
1109 AlignmentAnnotation ann = new AlignmentAnnotation(annotation);
1111 .createSequenceMapping(referedSeq, refSeqIndex, false);
1112 annotation.adjustForAlignment();
1113 referedSeq.addAlignmentAnnotation(annotation);
1114 al.addAnnotation(annotation);
1115 al.setAnnotationIndex(annotation,
1116 al.getAlignmentAnnotation().length
1117 - existingAnnotations - 1);
1118 if (groupRef != null)
1120 ((Vector) groupRefRows.get(groupRef)).addElement(annotation);
1122 // and recover our virgin copy to use again if necessary.
1125 } while (refSeqId != null
1126 && (referedSeq = al.findName(referedSeq, refSeqId, true)) != null);
1130 al.addAnnotation(annotation);
1131 al.setAnnotationIndex(annotation,
1132 al.getAlignmentAnnotation().length - existingAnnotations
1134 if (groupRef != null)
1136 ((Vector) groupRefRows.get(groupRef)).addElement(annotation);
1139 // and set modification flag
1142 // Resolve the groupRefs
1143 Hashtable<String, SequenceGroup> groupRefLookup = new Hashtable<String, SequenceGroup>();
1144 Enumeration en = groupRefRows.keys();
1146 while (en.hasMoreElements())
1148 groupRef = (String) en.nextElement();
1149 boolean matched = false;
1150 // Resolve group: TODO: add a getGroupByName method to alignments
1151 for (SequenceGroup theGroup : al.getGroups())
1153 if (theGroup.getName().equals(groupRef))
1157 // TODO: specify and implement duplication of alignment annotation
1158 // for multiple group references.
1160 .println("Ignoring 1:many group reference mappings for group name '"
1166 Vector rowset = (Vector) groupRefRows.get(groupRef);
1167 groupRefLookup.put(groupRef, theGroup);
1168 if (rowset != null && rowset.size() > 0)
1170 AlignmentAnnotation alan = null;
1171 for (int elm = 0, elmSize = rowset.size(); elm < elmSize; elm++)
1173 alan = (AlignmentAnnotation) rowset.elementAt(elm);
1174 alan.groupRef = theGroup;
1180 ((Vector) groupRefRows.get(groupRef)).removeAllElements();
1182 // process any deferred attribute settings for each context
1183 for (Object[] _deferred_args : deferredAnnotation_calls)
1185 if (_deferred_args[0] == GRAPHLINE)
1188 (StringTokenizer) _deferred_args[1], // st
1189 (SequenceI) _deferred_args[2], // refSeq
1190 (_deferred_args[3] == null) ? null : groupRefLookup
1191 .get(_deferred_args[3]) // the reference
1197 // finally, combine all the annotation rows within each context.
1199 * number of combine statements in this annotation file. Used to create
1200 * new groups for combined annotation graphs without disturbing existing
1203 int combinecount = 0;
1204 for (Object[] _combine_args : combineAnnotation_calls)
1206 combineAnnotations(al,
1208 (StringTokenizer) _combine_args[0], // st
1209 (SequenceI) _combine_args[1], // refSeq
1210 (_combine_args[2] == null) ? null : groupRefLookup
1211 .get(_combine_args[2]) // the reference group,
1220 * resolve a structural model and generate and add an alignment sequence for
1226 * @param urlToPairwise
1227 * @return true if model and sequence was added
1229 private boolean add_structmodel(SequenceI refSeq2, String tempId,
1230 String urlToModel, String urlToPairwise)
1236 private void add_structmodel(StringTokenizer st)
1239 // TODO Auto-generated method stub
1243 private void parseHideCols(ColumnSelection colSel, String nextToken)
1245 StringTokenizer inval = new StringTokenizer(nextToken, ",");
1246 while (inval.hasMoreTokens())
1248 String range = inval.nextToken().trim();
1249 int from, to = range.indexOf("-");
1252 from = to = Integer.parseInt(range);
1255 colSel.hideColumns(from, to);
1260 from = Integer.parseInt(range.substring(0, to));
1261 if (to < range.length() - 1)
1263 to = Integer.parseInt(range.substring(to + 1));
1269 if (from > 0 && to >= from)
1271 colSel.hideColumns(from, to);
1277 private Object autoAnnotsKey(AlignmentAnnotation annotation,
1278 SequenceI refSeq, String groupRef)
1280 return annotation.graph + "\t" + annotation.label + "\t"
1281 + annotation.description + "\t"
1282 + (refSeq != null ? refSeq.getDisplayId(true) : "");
1285 Annotation parseAnnotation(String string, int graphStyle)
1287 boolean hasSymbols = (graphStyle == AlignmentAnnotation.NO_GRAPH); // don't
1296 String desc = null, displayChar = null;
1297 char ss = ' '; // secondaryStructure
1299 boolean parsedValue = false, dcset = false;
1302 java.awt.Color colour = null;
1303 int i = string.indexOf("[");
1304 int j = string.indexOf("]");
1305 if (i > -1 && j > -1)
1307 UserColourScheme ucs = new UserColourScheme();
1309 colour = ucs.getColourFromString(string.substring(i + 1, j));
1310 if (i > 0 && string.charAt(i - 1) == ',')
1312 // clip the preceding comma as well
1315 string = string.substring(0, i) + string.substring(j + 1);
1318 StringTokenizer st = new StringTokenizer(string, ",", true);
1320 boolean seenContent = false;
1322 while (st.hasMoreTokens())
1325 token = st.nextToken().trim();
1326 if (token.equals(","))
1328 if (!seenContent && parsedValue && !dcset)
1330 // allow the value below the bar/line to be empty
1334 seenContent = false;
1346 displayChar = token;
1348 value = new Float(token).floatValue();
1351 } catch (NumberFormatException ex)
1357 if (token.length() == 1)
1359 displayChar = token;
1363 && (token.length() == 1 && "()<>[]{}AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz"
1366 // Either this character represents a helix or sheet
1367 // or an integer which can be displayed
1368 ss = token.charAt(0);
1369 if (displayChar.equals(token.substring(0, 1)))
1374 else if (desc == null || (parsedValue && pass > 2))
1380 // if (!dcset && string.charAt(string.length() - 1) == ',')
1382 // displayChar = " "; // empty display char symbol.
1384 if (displayChar != null && desc != null && desc.length() == 1)
1386 if (displayChar.length() > 1)
1388 // switch desc and displayChar - legacy support
1389 String tmp = displayChar;
1395 if (displayChar.equals(desc))
1397 // duplicate label - hangover from the 'robust parser' above
1402 Annotation anot = new Annotation(displayChar, desc, ss, value);
1404 anot.colour = colour;
1409 void colourAnnotations(AlignmentI al, String label, String colour)
1411 UserColourScheme ucs = new UserColourScheme(colour);
1412 Annotation[] annotations;
1413 for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1415 if (al.getAlignmentAnnotation()[i].label.equalsIgnoreCase(label))
1417 annotations = al.getAlignmentAnnotation()[i].annotations;
1418 for (int j = 0; j < annotations.length; j++)
1420 if (annotations[j] != null)
1422 annotations[j].colour = ucs.findColour('A');
1429 void combineAnnotations(AlignmentI al, int combineCount,
1430 StringTokenizer st, SequenceI seqRef, SequenceGroup groupRef)
1432 String group = st.nextToken();
1433 // First make sure we are not overwriting the graphIndex
1435 if (al.getAlignmentAnnotation() != null)
1437 for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1439 AlignmentAnnotation aa = al.getAlignmentAnnotation()[i];
1441 if (aa.graphGroup > graphGroup)
1443 // try to number graphGroups in order of occurence.
1444 graphGroup = aa.graphGroup + 1;
1446 if (aa.sequenceRef == seqRef && aa.groupRef == groupRef
1447 && aa.label.equalsIgnoreCase(group))
1449 if (aa.graphGroup > -1)
1451 graphGroup = aa.graphGroup;
1455 if (graphGroup <= combineCount)
1457 graphGroup = combineCount + 1;
1459 aa.graphGroup = graphGroup;
1465 // Now update groups
1466 while (st.hasMoreTokens())
1468 group = st.nextToken();
1469 for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1471 AlignmentAnnotation aa = al.getAlignmentAnnotation()[i];
1472 if (aa.sequenceRef == seqRef && aa.groupRef == groupRef
1473 && aa.label.equalsIgnoreCase(group))
1475 aa.graphGroup = graphGroup;
1484 .println("Couldn't combine annotations. None are added to alignment yet!");
1488 void addLine(AlignmentI al, StringTokenizer st, SequenceI seqRef,
1489 SequenceGroup groupRef)
1491 String group = st.nextToken();
1492 AlignmentAnnotation annotation = null, alannot[] = al
1493 .getAlignmentAnnotation();
1494 float value = new Float(st.nextToken()).floatValue();
1495 String label = st.hasMoreTokens() ? st.nextToken() : null;
1496 java.awt.Color colour = null;
1497 if (st.hasMoreTokens())
1499 UserColourScheme ucs = new UserColourScheme(st.nextToken());
1500 colour = ucs.findColour('A');
1502 if (alannot != null)
1504 for (int i = 0; i < alannot.length; i++)
1506 if (alannot[i].label.equalsIgnoreCase(group)
1507 && (seqRef == null || alannot[i].sequenceRef == seqRef)
1508 && (groupRef == null || alannot[i].groupRef == groupRef))
1510 alannot[i].setThreshold(new GraphLine(value, label, colour));
1514 if (annotation == null)
1520 void addGroup(AlignmentI al, StringTokenizer st)
1522 SequenceGroup sg = new SequenceGroup();
1523 sg.setName(st.nextToken());
1527 rng = st.nextToken();
1528 if (rng.length() > 0 && !rng.startsWith("*"))
1530 sg.setStartRes(Integer.parseInt(rng) - 1);
1536 rng = st.nextToken();
1537 if (rng.length() > 0 && !rng.startsWith("*"))
1539 sg.setEndRes(Integer.parseInt(rng) - 1);
1543 sg.setEndRes(al.getWidth() - 1);
1545 } catch (Exception e)
1548 .println("Couldn't parse Group Start or End Field as '*' or a valid column or sequence index: '"
1549 + rng + "' - assuming alignment width for group.");
1550 // assume group is full width
1552 sg.setEndRes(al.getWidth() - 1);
1555 String index = st.nextToken();
1556 if (index.equals("-1"))
1558 while (st.hasMoreElements())
1560 sg.addSequence(al.findName(st.nextToken()), false);
1565 StringTokenizer st2 = new StringTokenizer(index, ",");
1567 while (st2.hasMoreTokens())
1569 String tmp = st2.nextToken();
1570 if (tmp.equals("*"))
1572 for (int i = 0; i < al.getHeight(); i++)
1574 sg.addSequence(al.getSequenceAt(i), false);
1577 else if (tmp.indexOf("-") >= 0)
1579 StringTokenizer st3 = new StringTokenizer(tmp, "-");
1581 int start = (Integer.parseInt(st3.nextToken()));
1582 int end = (Integer.parseInt(st3.nextToken()));
1586 for (int i = start; i <= end; i++)
1588 sg.addSequence(al.getSequenceAt(i - 1), false);
1594 sg.addSequence(al.getSequenceAt(Integer.parseInt(tmp) - 1), false);
1601 sg.setStartRes(refSeq.findIndex(sg.getStartRes() + 1) - 1);
1602 sg.setEndRes(refSeq.findIndex(sg.getEndRes() + 1) - 1);
1603 sg.setSeqrep(refSeq);
1606 if (sg.getSize() > 0)
1612 void addRowProperties(AlignmentI al, StringTokenizer st)
1614 String label = st.nextToken(), keyValue, key, value;
1615 boolean scaletofit = false, centerlab = false, showalllabs = false;
1616 while (st.hasMoreTokens())
1618 keyValue = st.nextToken();
1619 key = keyValue.substring(0, keyValue.indexOf("="));
1620 value = keyValue.substring(keyValue.indexOf("=") + 1);
1621 if (key.equalsIgnoreCase("scaletofit"))
1623 scaletofit = Boolean.valueOf(value).booleanValue();
1625 if (key.equalsIgnoreCase("showalllabs"))
1627 showalllabs = Boolean.valueOf(value).booleanValue();
1629 if (key.equalsIgnoreCase("centrelabs"))
1631 centerlab = Boolean.valueOf(value).booleanValue();
1633 AlignmentAnnotation[] alr = al.getAlignmentAnnotation();
1636 for (int i = 0; i < alr.length; i++)
1638 if (alr[i].label.equalsIgnoreCase(label))
1640 alr[i].centreColLabels = centerlab;
1641 alr[i].scaleColLabel = scaletofit;
1642 alr[i].showAllColLabels = showalllabs;
1649 void addProperties(AlignmentI al, StringTokenizer st)
1652 // So far we have only added groups to the annotationHash,
1653 // the idea is in the future properties can be added to
1654 // alignments, other annotations etc
1655 if (al.getGroups() == null)
1660 String name = st.nextToken();
1661 SequenceGroup sg = null;
1662 for (SequenceGroup _sg : al.getGroups())
1664 if ((sg = _sg).getName().equals(name))
1676 String keyValue, key, value;
1677 ColourSchemeI def = sg.cs;
1679 while (st.hasMoreTokens())
1681 keyValue = st.nextToken();
1682 key = keyValue.substring(0, keyValue.indexOf("="));
1683 value = keyValue.substring(keyValue.indexOf("=") + 1);
1685 if (key.equalsIgnoreCase("description"))
1687 sg.setDescription(value);
1689 else if (key.equalsIgnoreCase("colour"))
1691 sg.cs = ColourSchemeProperty.getColour(al, value);
1693 else if (key.equalsIgnoreCase("pidThreshold"))
1695 sg.cs.setThreshold(Integer.parseInt(value), true);
1698 else if (key.equalsIgnoreCase("consThreshold"))
1700 sg.cs.setConservationInc(Integer.parseInt(value));
1701 Conservation c = new Conservation("Group",
1702 ResidueProperties.propHash, 3, sg.getSequences(null),
1703 sg.getStartRes(), sg.getEndRes() + 1);
1706 c.verdict(false, 25); // TODO: refer to conservation percent threshold
1708 sg.cs.setConservation(c);
1711 else if (key.equalsIgnoreCase("outlineColour"))
1713 sg.setOutlineColour(new UserColourScheme(value).findColour('A'));
1715 else if (key.equalsIgnoreCase("displayBoxes"))
1717 sg.setDisplayBoxes(Boolean.valueOf(value).booleanValue());
1719 else if (key.equalsIgnoreCase("showUnconserved"))
1721 sg.setShowNonconserved(Boolean.valueOf(value).booleanValue());
1723 else if (key.equalsIgnoreCase("displayText"))
1725 sg.setDisplayText(Boolean.valueOf(value).booleanValue());
1727 else if (key.equalsIgnoreCase("colourText"))
1729 sg.setColourText(Boolean.valueOf(value).booleanValue());
1731 else if (key.equalsIgnoreCase("textCol1"))
1733 sg.textColour = new UserColourScheme(value).findColour('A');
1735 else if (key.equalsIgnoreCase("textCol2"))
1737 sg.textColour2 = new UserColourScheme(value).findColour('A');
1739 else if (key.equalsIgnoreCase("textColThreshold"))
1741 sg.thresholdTextColour = Integer.parseInt(value);
1743 else if (key.equalsIgnoreCase("idColour"))
1745 // consider warning if colour doesn't resolve to a real colour
1746 sg.setIdColour((def = new UserColourScheme(value))
1749 else if (key.equalsIgnoreCase("hide"))
1751 // see bug https://mantis.lifesci.dundee.ac.uk/view.php?id=25847
1752 sg.setHidereps(true);
1754 else if (key.equalsIgnoreCase("hidecols"))
1756 // see bug https://mantis.lifesci.dundee.ac.uk/view.php?id=25847
1757 sg.setHideCols(true);
1759 sg.recalcConservation();
1768 void setBelowAlignment(AlignmentI al, StringTokenizer st)
1771 AlignmentAnnotation aa, ala[] = al.getAlignmentAnnotation();
1775 .print("Warning - no annotation to set below for sequence associated annotation:");
1777 while (st.hasMoreTokens())
1779 token = st.nextToken();
1782 System.err.print(" " + token);
1786 for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1788 aa = al.getAlignmentAnnotation()[i];
1789 if (aa.sequenceRef == refSeq && aa.label.equals(token))
1791 aa.belowAlignment = true;
1798 System.err.print("\n");
1802 void addAlignmentDetails(AlignmentI al, StringTokenizer st)
1804 String keyValue, key, value;
1805 while (st.hasMoreTokens())
1807 keyValue = st.nextToken();
1808 key = keyValue.substring(0, keyValue.indexOf("="));
1809 value = keyValue.substring(keyValue.indexOf("=") + 1);
1810 al.setProperty(key, value);
1815 * Write annotations as a CSV file of the form 'label, value, value, ...' for
1818 * @param annotations
1819 * @return CSV file as a string.
1821 public String printCSVAnnotations(AlignmentAnnotation[] annotations)
1823 if (annotations == null)
1827 StringBuffer sp = new StringBuffer();
1828 for (int i = 0; i < annotations.length; i++)
1830 String atos = annotations[i].toString();
1834 int cp = atos.indexOf("\n", p);
1835 sp.append(annotations[i].label);
1839 sp.append(atos.substring(p, cp + 1));
1843 sp.append(atos.substring(p));
1849 return sp.toString();
1852 public String printAnnotationsForView(AlignViewportI viewport)
1854 return printAnnotations(viewport.isShowAnnotation() ? viewport
1855 .getAlignment().getAlignmentAnnotation() : null, viewport
1856 .getAlignment().getGroups(), viewport.getAlignment()
1857 .getProperties(), viewport.getColumnSelection(),
1858 viewport.getAlignment(), null);
1861 public String printAnnotationsForAlignment(AlignmentI al)
1863 return printAnnotations(al.getAlignmentAnnotation(), al.getGroups(),
1864 al.getProperties(), null, al, null);