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.PDBEntry;
32 import jalview.datamodel.PDBEntry.Type;
33 import jalview.datamodel.SequenceGroup;
34 import jalview.datamodel.SequenceI;
35 import jalview.schemes.ColourSchemeI;
36 import jalview.schemes.ColourSchemeProperty;
37 import jalview.structure.StructureSelectionManager;
38 import jalview.util.ColorUtils;
40 import java.awt.Color;
41 import java.io.BufferedReader;
43 import java.io.FileReader;
44 import java.io.InputStreamReader;
45 import java.io.StringReader;
47 import java.util.ArrayList;
48 import java.util.BitSet;
49 import java.util.Enumeration;
50 import java.util.Hashtable;
51 import java.util.List;
53 import java.util.StringTokenizer;
54 import java.util.Vector;
56 public class AnnotationFile
60 SequenceI refSeq = null;
62 String refSeqId = null;
64 String[] StructModelHeader = null;
71 * used for resolving absolute references to resources relative to
72 * annotationFile location
76 private static String GRAPHLINE = "GRAPHLINE", COMBINE = "COMBINE",
77 STRUCTMODEL = "STRUCTMODEL",
78 HEADER_STRUCT_MODEL = "HEADER_STRUCT_MODEL";
80 public AnnotationFile()
86 * character used to write newlines
88 protected String newline = System.getProperty("line.separator");
91 * set new line string and reset the output buffer
95 public void setNewlineString(String nl)
101 public String getNewlineString()
109 text = new StringBuffer("JALVIEW_ANNOTATION" + newline + "# Created: "
110 + new java.util.Date() + newline + newline);
116 * convenience method for pre-2.9 annotation files which have no view, hidden
117 * columns or hidden row keywords.
122 * @return annotation file as a string.
124 public String printAnnotations(AlignmentAnnotation[] annotations,
125 List<SequenceGroup> list, Hashtable properties)
127 return printAnnotations(annotations, list, properties, null, null, null);
132 * hold all the information about a particular view definition read from or
133 * written out in an annotations file.
137 public String viewname;
139 public HiddenSequences hidseqs;
141 public ColumnSelection hiddencols;
143 public Vector visibleGroups;
145 public Hashtable hiddenRepSeqs;
147 public ViewDef(String viewname, HiddenSequences hidseqs,
148 ColumnSelection hiddencols, Hashtable hiddenRepSeqs)
150 this.viewname = viewname;
151 this.hidseqs = hidseqs;
152 this.hiddencols = hiddencols;
153 this.hiddenRepSeqs = hiddenRepSeqs;
158 * Prepare an annotation file given a set of annotations, groups, alignment
159 * properties and views.
165 * @return annotation file
167 public String printAnnotations(AlignmentAnnotation[] annotations,
168 List<SequenceGroup> list, Hashtable properties,
169 ColumnSelection cs, AlignmentI al, ViewDef view)
173 if (view.viewname != null)
175 text.append("VIEW_DEF\t" + view.viewname + "\n");
179 list = view.visibleGroups;
183 cs = view.hiddencols;
187 // add hidden rep sequences.
190 // first target - store and restore all settings for a view.
191 if (al != null && al.hasSeqrep())
193 text.append("VIEW_SETREF\t" + al.getSeqrep().getName() + "\n");
195 if (cs != null && cs.hasHiddenColumns())
197 text.append("VIEW_HIDECOLS\t");
198 List<int[]> hc = cs.getHiddenColumns();
199 boolean comma = false;
216 // TODO: allow efficient recovery of annotation data shown in several
218 if (annotations != null)
220 boolean oneColour = true;
221 AlignmentAnnotation row;
223 SequenceI refSeq = null;
224 SequenceGroup refGroup = null;
226 StringBuffer colours = new StringBuffer();
227 StringBuffer graphLine = new StringBuffer();
228 StringBuffer rowprops = new StringBuffer();
229 Hashtable<Integer, String> graphGroup = new Hashtable<Integer, String>();
230 Hashtable<Integer, Object[]> graphGroup_refs = new Hashtable<Integer, Object[]>();
231 BitSet graphGroupSeen = new BitSet();
233 java.awt.Color color;
235 for (int i = 0; i < annotations.length; i++)
237 row = annotations[i];
241 && !(row.graphGroup > -1 && graphGroupSeen
242 .get(row.graphGroup)))
250 // mark any sequence references for the row
251 writeSequence_Ref(refSeq, row.sequenceRef);
252 refSeq = row.sequenceRef;
253 // mark any group references for the row
254 writeGroup_Ref(refGroup, row.groupRef);
255 refGroup = row.groupRef;
257 boolean hasGlyphs = row.hasIcons, hasLabels = row.hasText, hasValues = row.hasScore, hasText = false;
258 // lookahead to check what the annotation row object actually contains.
259 for (int j = 0; row.annotations != null
260 && j < row.annotations.length
261 && (!hasGlyphs || !hasLabels || !hasValues); j++)
263 if (row.annotations[j] != null)
265 hasLabels |= (row.annotations[j].displayCharacter != null
266 && row.annotations[j].displayCharacter.length() > 0 && !row.annotations[j].displayCharacter
268 hasGlyphs |= (row.annotations[j].secondaryStructure != 0 && row.annotations[j].secondaryStructure != ' ');
269 hasValues |= (!Float.isNaN(row.annotations[j].value)); // NaNs can't
272 hasText |= (row.annotations[j].description != null && row.annotations[j].description
277 if (row.graph == AlignmentAnnotation.NO_GRAPH)
279 text.append("NO_GRAPH\t");
280 hasValues = false; // only secondary structure
281 // hasLabels = false; // and annotation description string.
285 if (row.graph == AlignmentAnnotation.BAR_GRAPH)
287 text.append("BAR_GRAPH\t");
288 hasGlyphs = false; // no secondary structure
291 else if (row.graph == AlignmentAnnotation.LINE_GRAPH)
293 hasGlyphs = false; // no secondary structure
294 text.append("LINE_GRAPH\t");
297 if (row.getThreshold() != null)
299 graphLine.append("GRAPHLINE\t");
300 graphLine.append(row.label);
301 graphLine.append("\t");
302 graphLine.append(row.getThreshold().value);
303 graphLine.append("\t");
304 graphLine.append(row.getThreshold().label);
305 graphLine.append("\t");
306 graphLine.append(jalview.util.Format.getHexString(row
307 .getThreshold().colour));
308 graphLine.append(newline);
311 if (row.graphGroup > -1)
313 graphGroupSeen.set(row.graphGroup);
314 Integer key = new Integer(row.graphGroup);
315 if (graphGroup.containsKey(key))
317 graphGroup.put(key, graphGroup.get(key) + "\t" + row.label);
322 graphGroup_refs.put(key, new Object[] { refSeq, refGroup });
323 graphGroup.put(key, row.label);
328 text.append(row.label + "\t");
329 if (row.description != null)
331 text.append(row.description + "\t");
333 for (int j = 0; row.annotations != null
334 && j < row.annotations.length; j++)
337 && jalview.util.Comparison.isGap(refSeq.getCharAt(j)))
342 if (row.annotations[j] != null)
345 if (hasGlyphs) // could be also hasGlyphs || ...
349 if (row.annotations[j].secondaryStructure != ' ')
351 // only write out the field if its not whitespace.
352 text.append(row.annotations[j].secondaryStructure);
358 if (!Float.isNaN(row.annotations[j].value))
360 text.append(comma + row.annotations[j].value);
364 // System.err.println("Skipping NaN - not valid value.");
365 text.append(comma + 0f);// row.annotations[j].value);
371 // TODO: labels are emitted after values for bar graphs.
372 if // empty labels are allowed, so
373 (row.annotations[j].displayCharacter != null
374 && row.annotations[j].displayCharacter.length() > 0
375 && !row.annotations[j].displayCharacter.equals(" "))
377 text.append(comma + row.annotations[j].displayCharacter);
383 if (row.annotations[j].description != null
384 && row.annotations[j].description.length() > 0
385 && !row.annotations[j].description
386 .equals(row.annotations[j].displayCharacter))
388 text.append(comma + row.annotations[j].description);
392 if (color != null && !color.equals(row.annotations[j].colour))
397 color = row.annotations[j].colour;
399 if (row.annotations[j].colour != null
400 && row.annotations[j].colour != java.awt.Color.black)
404 + jalview.util.Format
405 .getHexString(row.annotations[j].colour)
415 text.append("\t" + row.score);
418 text.append(newline);
420 if (color != null && color != java.awt.Color.black && oneColour)
422 colours.append("COLOUR\t");
423 colours.append(row.label);
424 colours.append("\t");
425 colours.append(jalview.util.Format.getHexString(color));
426 colours.append(newline);
428 if (row.scaleColLabel || row.showAllColLabels
429 || row.centreColLabels)
431 rowprops.append("ROWPROPERTIES\t");
432 rowprops.append(row.label);
433 rowprops.append("\tscaletofit=");
434 rowprops.append(row.scaleColLabel);
435 rowprops.append("\tshowalllabs=");
436 rowprops.append(row.showAllColLabels);
437 rowprops.append("\tcentrelabs=");
438 rowprops.append(row.centreColLabels);
439 rowprops.append(newline);
441 if (graphLine.length() > 0)
443 text.append(graphLine.toString());
444 graphLine.setLength(0);
448 text.append(newline);
450 text.append(colours.toString());
451 if (graphGroup.size() > 0)
453 SequenceI oldRefSeq = refSeq;
454 SequenceGroup oldRefGroup = refGroup;
455 for (Map.Entry<Integer, String> combine_statement : graphGroup
458 Object[] seqRefAndGroup = graphGroup_refs.get(combine_statement
461 writeSequence_Ref(refSeq, (SequenceI) seqRefAndGroup[0]);
462 refSeq = (SequenceI) seqRefAndGroup[0];
464 writeGroup_Ref(refGroup, (SequenceGroup) seqRefAndGroup[1]);
465 refGroup = (SequenceGroup) seqRefAndGroup[1];
466 text.append("COMBINE\t");
467 text.append(combine_statement.getValue());
468 text.append(newline);
470 writeSequence_Ref(refSeq, oldRefSeq);
473 writeGroup_Ref(refGroup, oldRefGroup);
474 refGroup = oldRefGroup;
476 text.append(rowprops.toString());
484 if (properties != null)
486 text.append(newline);
487 text.append(newline);
488 text.append("ALIGNMENT");
489 Enumeration en = properties.keys();
490 while (en.hasMoreElements())
492 String key = en.nextElement().toString();
496 text.append(properties.get(key));
498 // TODO: output alignment visualization settings here if required
499 // iterate through one or more views, defining, marking columns and rows
500 // as visible/hidden, and emmitting view properties.
501 // View specific annotation is
504 return text.toString();
507 private Object writeGroup_Ref(SequenceGroup refGroup,
508 SequenceGroup next_refGroup)
510 if (next_refGroup == null)
513 if (refGroup != null)
515 text.append(newline);
516 text.append("GROUP_REF\t");
517 text.append("ALIGNMENT");
518 text.append(newline);
524 if (refGroup == null || refGroup != next_refGroup)
526 text.append(newline);
527 text.append("GROUP_REF\t");
528 text.append(next_refGroup.getName());
529 text.append(newline);
536 private boolean writeSequence_Ref(SequenceI refSeq, SequenceI next_refSeq)
539 if (next_refSeq == null)
543 text.append(newline);
544 text.append("SEQUENCE_REF\t");
545 text.append("ALIGNMENT");
546 text.append(newline);
552 if (refSeq == null || refSeq != next_refSeq)
554 text.append(newline);
555 text.append("SEQUENCE_REF\t");
556 text.append(next_refSeq.getName());
557 text.append(newline);
564 public void printGroups(List<SequenceGroup> list)
566 SequenceI seqrep = null;
567 for (SequenceGroup sg : list)
571 text.append("SEQUENCE_GROUP\t" + sg.getName() + "\t"
572 + (sg.getStartRes() + 1) + "\t" + (sg.getEndRes() + 1)
578 seqrep = sg.getSeqrep();
579 text.append("SEQUENCE_REF\t");
580 text.append(seqrep.getName());
581 text.append(newline);
582 text.append("SEQUENCE_GROUP\t");
583 text.append(sg.getName());
585 text.append((seqrep.findPosition(sg.getStartRes())));
587 text.append((seqrep.findPosition(sg.getEndRes())));
591 for (int s = 0; s < sg.getSize(); s++)
593 text.append(sg.getSequenceAt(s).getName());
596 text.append(newline);
597 text.append("PROPERTIES\t");
598 text.append(sg.getName());
601 if (sg.getDescription() != null)
603 text.append("description=");
604 text.append(sg.getDescription());
609 text.append("colour=");
610 text.append(sg.cs.toString());
612 if (sg.cs.getThreshold() != 0)
614 text.append("pidThreshold=");
615 text.append(sg.cs.getThreshold());
617 if (sg.cs.conservationApplied())
619 text.append("consThreshold=");
620 text.append(sg.cs.getConservationInc());
624 text.append("outlineColour=");
625 text.append(jalview.util.Format.getHexString(sg.getOutlineColour()));
628 text.append("displayBoxes=");
629 text.append(sg.getDisplayBoxes());
631 text.append("displayText=");
632 text.append(sg.getDisplayText());
634 text.append("colourText=");
635 text.append(sg.getColourText());
637 text.append("showUnconserved=");
638 text.append(sg.getShowNonconserved());
640 if (sg.textColour != java.awt.Color.black)
642 text.append("textCol1=");
643 text.append(jalview.util.Format.getHexString(sg.textColour));
646 if (sg.textColour2 != java.awt.Color.white)
648 text.append("textCol2=");
649 text.append(jalview.util.Format.getHexString(sg.textColour2));
652 if (sg.thresholdTextColour != 0)
654 text.append("textColThreshold=");
655 text.append(sg.thresholdTextColour);
658 if (sg.idColour != null)
660 text.append("idColour=");
661 text.append(jalview.util.Format.getHexString(sg.idColour));
666 text.append("hide=true\t");
670 text.append("hidecols=true\t");
674 // terminate the last line and clear the sequence ref for the group
675 text.append(newline);
676 text.append("SEQUENCE_REF");
678 text.append(newline);
679 text.append(newline);
685 public boolean annotateAlignmentView(AlignViewportI viewport,
686 String file, DataSourceType protocol)
688 ColumnSelection colSel = viewport.getColumnSelection();
691 colSel = new ColumnSelection();
693 boolean rslt = readAnnotationFile(viewport.getAlignment(), colSel,
695 if (rslt && (colSel.hasSelectedColumns() || colSel.hasHiddenColumns()))
697 viewport.setColumnSelection(colSel);
703 public boolean readAnnotationFile(AlignmentI al, String file,
704 DataSourceType sourceType)
706 return readAnnotationFile(al, null, file, sourceType);
709 public boolean readAnnotationFile(AlignmentI al, ColumnSelection colSel,
710 String file, DataSourceType sourceType)
713 BufferedReader in = null;
716 if (sourceType == DataSourceType.FILE)
718 in = new BufferedReader(new FileReader(file));
719 baseUri = new File(file).getParent();
729 else if (sourceType == DataSourceType.URL)
731 URL url = new URL(file);
732 in = new BufferedReader(new InputStreamReader(url.openStream()));
733 String bs = url.toExternalForm();
734 baseUri = bs.substring(0, bs.indexOf(url.getHost())
735 + url.getHost().length());
736 baseUri += url.toURI().getPath();
737 if (baseUri.lastIndexOf("/") > -1)
739 baseUri = baseUri.substring(0, baseUri.lastIndexOf("/")) + "/";
742 else if (sourceType == DataSourceType.PASTE)
744 in = new BufferedReader(new StringReader(file));
745 // TODO - support mimencoded PDBs for a paste.. ?
748 else if (sourceType == DataSourceType.CLASSLOADER)
750 java.io.InputStream is = getClass().getResourceAsStream("/" + file);
753 in = new BufferedReader(new java.io.InputStreamReader(is));
754 // TODO: this probably doesn't work for classloader - needs a test
755 baseUri = new File("/" + file).getParent() + "/";
760 return parseAnnotationFrom(al, colSel, in);
763 } catch (Exception ex)
765 ex.printStackTrace();
766 System.out.println("Problem reading annotation file: " + ex);
769 System.out.println("Last read line " + nlinesread + ": '"
770 + lastread + "' (first 80 chars) ...");
778 public boolean parseAnnotationFrom(AlignmentI al, ColumnSelection colSel,
779 BufferedReader in) throws Exception
782 ArrayList<Object[]> combineAnnotation_calls = new ArrayList<Object[]>();
783 ArrayList<Object[]> deferredAnnotation_calls = new ArrayList<Object[]>();
784 boolean modified = false;
785 String groupRef = null;
786 Hashtable groupRefRows = new Hashtable();
788 Hashtable autoAnnots = new Hashtable();
790 String line, label, description, token;
791 int graphStyle, index;
793 int existingAnnotations = 0;
794 // when true - will add new rows regardless of whether they are duplicate
795 // auto-annotation like consensus or conservation graphs
796 boolean overrideAutoAnnot = false;
797 if (al.getAlignmentAnnotation() != null)
799 existingAnnotations = al.getAlignmentAnnotation().length;
800 if (existingAnnotations > 0)
802 AlignmentAnnotation[] aa = al.getAlignmentAnnotation();
803 for (int aai = 0; aai < aa.length; aai++)
805 if (aa[aai].autoCalculated)
807 // make a note of the name and description
809 autoAnnotsKey(aa[aai], aa[aai].sequenceRef,
810 (aa[aai].groupRef == null ? null
811 : aa[aai].groupRef.getName())),
818 int alWidth = al.getWidth();
821 Annotation[] annotations;
822 AlignmentAnnotation annotation = null;
824 // First confirm this is an Annotation file
825 boolean jvAnnotationFile = false;
826 while ((line = in.readLine()) != null)
829 lastread = new String(line);
830 if (line.indexOf("#") == 0)
835 if (line.indexOf("JALVIEW_ANNOTATION") > -1)
837 jvAnnotationFile = true;
842 if (!jvAnnotationFile)
848 while ((line = in.readLine()) != null)
851 lastread = new String(line);
852 if (line.indexOf("#") == 0
853 || line.indexOf("JALVIEW_ANNOTATION") > -1
854 || line.length() == 0)
859 st = new StringTokenizer(line, "\t");
860 token = st.nextToken();
861 if (token.equalsIgnoreCase("COLOUR"))
863 // TODO: use graduated colour def'n here too
864 colourAnnotations(al, st.nextToken(), st.nextToken());
869 else if (token.equalsIgnoreCase(COMBINE))
871 // keep a record of current state and resolve groupRef at end
872 combineAnnotation_calls
873 .add(new Object[] { st, refSeq, groupRef });
877 else if (token.equalsIgnoreCase("ROWPROPERTIES"))
879 addRowProperties(al, st);
883 else if (token.equalsIgnoreCase(GRAPHLINE))
886 deferredAnnotation_calls.add(new Object[] { GRAPHLINE, st,
892 else if (token.equalsIgnoreCase("SEQUENCE_REF"))
894 if (st.hasMoreTokens())
896 refSeq = al.findName(refSeqId = st.nextToken());
903 refSeqIndex = Integer.parseInt(st.nextToken());
908 .println("WARNING: SEQUENCE_REF index must be > 0 in AnnotationFile");
910 } catch (Exception ex)
922 else if (token.equalsIgnoreCase("GROUP_REF"))
924 // Group references could be forward or backwards, so they are
925 // resolved after the whole file is read in
927 if (st.hasMoreTokens())
929 groupRef = st.nextToken();
930 if (groupRef.length() < 1)
932 groupRef = null; // empty string
936 if (groupRefRows.get(groupRef) == null)
938 groupRefRows.put(groupRef, new Vector());
944 else if (token.equalsIgnoreCase("SEQUENCE_GROUP"))
951 else if (token.equalsIgnoreCase("PROPERTIES"))
953 addProperties(al, st);
958 else if (token.equalsIgnoreCase("BELOW_ALIGNMENT"))
960 setBelowAlignment(al, st);
964 else if (token.equalsIgnoreCase("ALIGNMENT"))
966 addAlignmentDetails(al, st);
970 else if (token.equalsIgnoreCase("VIEW_SETREF"))
974 al.setSeqrep(refSeq);
979 else if (token.equalsIgnoreCase("VIEW_HIDECOLS"))
981 if (st.hasMoreTokens())
985 colSel = new ColumnSelection();
987 parseHideCols(colSel, st.nextToken());
992 else if (token.equalsIgnoreCase("HIDE_INSERTIONS"))
994 SequenceI sr = refSeq == null ? al.getSeqrep() : refSeq;
997 sr = al.getSequenceAt(0);
1004 .println("Cannot process HIDE_INSERTIONS without an alignment view: Ignoring line: "
1009 // consider deferring this till after the file has been parsed ?
1010 colSel.hideInsertionsFor(sr);
1016 else if (token.equalsIgnoreCase(HEADER_STRUCT_MODEL))
1018 int hSize = st.countTokens();
1019 StructModelHeader = new String[hSize];
1020 for (int x = 0; x < hSize; x++)
1022 StructModelHeader[x] = st.nextToken();
1026 else if (token.equalsIgnoreCase(STRUCTMODEL))
1028 boolean failedtoadd = true;
1029 // expects STRUCTMODEL <Query> <TemplateSeqId> <ModelFile>
1030 // <FastaMappingFile>
1031 String querySeqId = !st.hasMoreTokens() ? "" : st.nextToken();
1032 SequenceI querySeq = al.findName(querySeqId);
1033 if (st.hasMoreTokens()) {
1034 refSeq = al.findName(refSeqId = st.nextToken());
1037 System.err.println("Couldn't locate " + refSeqId
1038 + " in the alignment for STRUCTMODEL");
1043 int tSize = st.countTokens() + 2;
1044 String[] rowData = new String[tSize];
1045 rowData[0] = querySeqId;
1046 rowData[1] = refSeqId;
1047 for (int x = 2; x < tSize; x++)
1049 rowData[x] = st.nextToken();
1051 if (processStructModel(al, querySeq, refSeq,
1052 StructModelHeader, rowData, baseUri))
1054 failedtoadd = false;
1061 .println("Need minimum of <Query> <TemplateSeqId> <ModelFile> <FastaMappingFile> as tab separated fields after"
1068 // Parse out the annotation row
1069 graphStyle = AlignmentAnnotation.getGraphValueFromString(token);
1070 label = st.nextToken();
1073 annotations = new Annotation[alWidth];
1075 float score = Float.NaN;
1077 if (st.hasMoreTokens())
1079 line = st.nextToken();
1081 if (line.indexOf("|") == -1)
1084 if (st.hasMoreTokens())
1086 line = st.nextToken();
1090 if (st.hasMoreTokens())
1092 // This must be the score
1093 score = Float.valueOf(st.nextToken()).floatValue();
1096 st = new StringTokenizer(line, "|", true);
1098 boolean emptyColumn = true;
1099 boolean onlyOneElement = (st.countTokens() == 1);
1101 while (st.hasMoreElements() && index < alWidth)
1103 token = st.nextToken().trim();
1109 score = Float.valueOf(token).floatValue();
1111 } catch (NumberFormatException ex)
1116 if (token.equals("|"))
1127 annotations[index++] = parseAnnotation(token, graphStyle);
1128 emptyColumn = false;
1134 annotation = new AlignmentAnnotation(label, description,
1135 (index == 0) ? null : annotations, 0, 0, graphStyle);
1137 annotation.score = score;
1138 if (!overrideAutoAnnot
1139 && autoAnnots.containsKey(autoAnnotsKey(annotation, refSeq,
1142 // skip - we've already got an automatic annotation of this type.
1145 // otherwise add it!
1149 annotation.belowAlignment = false;
1150 // make a copy of refSeq so we can find other matches in the alignment
1151 SequenceI referedSeq = refSeq;
1154 // copy before we do any mapping business.
1155 // TODO: verify that undo/redo with 1:many sequence associated
1156 // annotations can be undone correctly
1157 AlignmentAnnotation ann = new AlignmentAnnotation(annotation);
1159 .createSequenceMapping(referedSeq, refSeqIndex, false);
1160 annotation.adjustForAlignment();
1161 referedSeq.addAlignmentAnnotation(annotation);
1162 al.addAnnotation(annotation);
1163 al.setAnnotationIndex(annotation,
1164 al.getAlignmentAnnotation().length
1165 - existingAnnotations - 1);
1166 if (groupRef != null)
1168 ((Vector) groupRefRows.get(groupRef)).addElement(annotation);
1170 // and recover our virgin copy to use again if necessary.
1173 } while (refSeqId != null
1174 && (referedSeq = al.findName(referedSeq, refSeqId, true)) != null);
1178 al.addAnnotation(annotation);
1179 al.setAnnotationIndex(annotation,
1180 al.getAlignmentAnnotation().length - existingAnnotations
1182 if (groupRef != null)
1184 ((Vector) groupRefRows.get(groupRef)).addElement(annotation);
1187 // and set modification flag
1190 // Resolve the groupRefs
1191 Hashtable<String, SequenceGroup> groupRefLookup = new Hashtable<String, SequenceGroup>();
1192 Enumeration en = groupRefRows.keys();
1194 while (en.hasMoreElements())
1196 groupRef = (String) en.nextElement();
1197 boolean matched = false;
1198 // Resolve group: TODO: add a getGroupByName method to alignments
1199 for (SequenceGroup theGroup : al.getGroups())
1201 if (theGroup.getName().equals(groupRef))
1205 // TODO: specify and implement duplication of alignment annotation
1206 // for multiple group references.
1208 .println("Ignoring 1:many group reference mappings for group name '"
1214 Vector rowset = (Vector) groupRefRows.get(groupRef);
1215 groupRefLookup.put(groupRef, theGroup);
1216 if (rowset != null && rowset.size() > 0)
1218 AlignmentAnnotation alan = null;
1219 for (int elm = 0, elmSize = rowset.size(); elm < elmSize; elm++)
1221 alan = (AlignmentAnnotation) rowset.elementAt(elm);
1222 alan.groupRef = theGroup;
1228 ((Vector) groupRefRows.get(groupRef)).removeAllElements();
1230 // process any deferred attribute settings for each context
1231 for (Object[] _deferred_args : deferredAnnotation_calls)
1233 if (_deferred_args[0] == GRAPHLINE)
1236 (StringTokenizer) _deferred_args[1], // st
1237 (SequenceI) _deferred_args[2], // refSeq
1238 (_deferred_args[3] == null) ? null : groupRefLookup
1239 .get(_deferred_args[3]) // the reference
1245 // finally, combine all the annotation rows within each context.
1247 * number of combine statements in this annotation file. Used to create
1248 * new groups for combined annotation graphs without disturbing existing
1251 int combinecount = 0;
1252 for (Object[] _combine_args : combineAnnotation_calls)
1254 combineAnnotations(al,
1256 (StringTokenizer) _combine_args[0], // st
1257 (SequenceI) _combine_args[1], // refSeq
1258 (_combine_args[2] == null) ? null : groupRefLookup
1259 .get(_combine_args[2]) // the reference group,
1268 * Resolve structural model to a reference sequence and register it to
1269 * StructureSelectionManager
1272 * @param querySequence
1273 * @param templateSeq
1274 * @param structModelHeader
1275 * @param structModelData
1276 * @return true if model and sequence was added
1278 static boolean processStructModel(AlignmentI al, SequenceI querySequence,
1279 SequenceI templateSeq,
1280 String[] structModelHeader,
1281 String[] structModelData, String baseUri)
1283 String warningMessage = null;
1284 boolean added = false;
1286 String structureModelFile = resolveAbsolutePath(structModelData[2],
1288 String fastaMappingFile = resolveAbsolutePath(structModelData[3],
1290 // System.out.println("Model File >> " + structureModelFile);
1291 // System.out.println("Fasta File >> " + fastaMappingFile);
1292 String modelName = StructureFile.safeName(structureModelFile);
1293 PDBEntry phyre2PDBEntry = new PDBEntry(modelName, " ",
1295 structureModelFile);
1296 String phyre2ModelDesc = generatePhyre2InfoHTMLTable(
1297 structModelHeader, structModelData);
1298 phyre2PDBEntry.setProperty("PHYRE2_MODEL_INFO", phyre2ModelDesc);
1299 templateSeq.getDatasetSequence().addPDBId(phyre2PDBEntry);
1300 if (querySequence != null)
1302 querySequence.getDatasetSequence().addPDBId(phyre2PDBEntry);
1304 StructureSelectionManager ssm = StructureSelectionManager
1305 .getStructureSelectionManager();
1306 ssm.registerPhyre2Template(structureModelFile, fastaMappingFile);
1309 } catch (Exception x)
1311 warningMessage = x.toString();
1313 if (warningMessage !=null)
1315 System.err.println("Warnings whilst processing STRUCTMODEL: "+warningMessage);
1321 static String generatePhyre2InfoHTMLTable(String[] structModelHeader,
1322 String[] structModelData)
1324 StringBuilder phyre2InfoBuilder = new StringBuilder();
1325 if (isGenerateStructInfoHtml(structModelHeader, structModelData))
1327 phyre2InfoBuilder.append("<html><table border=\"1\" width=100%>")
1328 .append("<tr><td colspan=\"2\"><strong>Phyre2 Template Info</strong></td></tr>");
1329 for (int x = 4; x < structModelData.length; x++)
1331 phyre2InfoBuilder.append("<tr><td>").append(structModelHeader[x])
1332 .append("</td><td>").append(structModelData[x])
1333 .append("</td></tr>");
1335 phyre2InfoBuilder.append("</table></html>");
1337 return phyre2InfoBuilder.toString();
1340 static boolean isGenerateStructInfoHtml(String[] header, String[] data)
1342 boolean generate = true;
1343 if (header == null || data == null)
1347 if (header.length < 3 || data.length < 3)
1354 static String resolveAbsolutePath(String relURI, String _baseUri)
1356 if (relURI.indexOf(":/") > -1 || relURI.startsWith("/")
1357 || "".equals(_baseUri) || relURI.startsWith(_baseUri))
1361 return _baseUri + relURI;
1364 private void parseHideCols(ColumnSelection colSel, String nextToken)
1366 StringTokenizer inval = new StringTokenizer(nextToken, ",");
1367 while (inval.hasMoreTokens())
1369 String range = inval.nextToken().trim();
1370 int from, to = range.indexOf("-");
1373 from = to = Integer.parseInt(range);
1376 colSel.hideColumns(from, to);
1381 from = Integer.parseInt(range.substring(0, to));
1382 if (to < range.length() - 1)
1384 to = Integer.parseInt(range.substring(to + 1));
1390 if (from > 0 && to >= from)
1392 colSel.hideColumns(from, to);
1398 private Object autoAnnotsKey(AlignmentAnnotation annotation,
1399 SequenceI refSeq, String groupRef)
1401 return annotation.graph + "\t" + annotation.label + "\t"
1402 + annotation.description + "\t"
1403 + (refSeq != null ? refSeq.getDisplayId(true) : "");
1406 Annotation parseAnnotation(String string, int graphStyle)
1408 // don't do the glyph test if we don't want secondary structure
1409 boolean hasSymbols = (graphStyle == AlignmentAnnotation.NO_GRAPH);
1410 String desc = null, displayChar = null;
1411 char ss = ' '; // secondaryStructure
1413 boolean parsedValue = false, dcset = false;
1416 Color colour = null;
1417 int i = string.indexOf("[");
1418 int j = string.indexOf("]");
1419 if (i > -1 && j > -1)
1421 colour = ColorUtils.parseColourString(string.substring(i + 1,
1423 if (i > 0 && string.charAt(i - 1) == ',')
1425 // clip the preceding comma as well
1428 string = string.substring(0, i) + string.substring(j + 1);
1431 StringTokenizer st = new StringTokenizer(string, ",", true);
1433 boolean seenContent = false;
1435 while (st.hasMoreTokens())
1438 token = st.nextToken().trim();
1439 if (token.equals(","))
1441 if (!seenContent && parsedValue && !dcset)
1443 // allow the value below the bar/line to be empty
1447 seenContent = false;
1459 displayChar = token;
1461 value = new Float(token).floatValue();
1464 } catch (NumberFormatException ex)
1470 if (token.length() == 1)
1472 displayChar = token;
1476 && (token.length() == 1 && "()<>[]{}AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz"
1479 // Either this character represents a helix or sheet
1480 // or an integer which can be displayed
1481 ss = token.charAt(0);
1482 if (displayChar.equals(token.substring(0, 1)))
1487 else if (desc == null || (parsedValue && pass > 2))
1493 // if (!dcset && string.charAt(string.length() - 1) == ',')
1495 // displayChar = " "; // empty display char symbol.
1497 if (displayChar != null && desc != null && desc.length() == 1)
1499 if (displayChar.length() > 1)
1501 // switch desc and displayChar - legacy support
1502 String tmp = displayChar;
1508 if (displayChar.equals(desc))
1510 // duplicate label - hangover from the 'robust parser' above
1515 Annotation anot = new Annotation(displayChar, desc, ss, value);
1517 anot.colour = colour;
1522 void colourAnnotations(AlignmentI al, String label, String colour)
1524 Color awtColour = ColorUtils.parseColourString(colour);
1525 Annotation[] annotations;
1526 for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1528 if (al.getAlignmentAnnotation()[i].label.equalsIgnoreCase(label))
1530 annotations = al.getAlignmentAnnotation()[i].annotations;
1531 for (int j = 0; j < annotations.length; j++)
1533 if (annotations[j] != null)
1535 annotations[j].colour = awtColour;
1542 void combineAnnotations(AlignmentI al, int combineCount,
1543 StringTokenizer st, SequenceI seqRef, SequenceGroup groupRef)
1545 String group = st.nextToken();
1546 // First make sure we are not overwriting the graphIndex
1548 if (al.getAlignmentAnnotation() != null)
1550 for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1552 AlignmentAnnotation aa = al.getAlignmentAnnotation()[i];
1554 if (aa.graphGroup > graphGroup)
1556 // try to number graphGroups in order of occurence.
1557 graphGroup = aa.graphGroup + 1;
1559 if (aa.sequenceRef == seqRef && aa.groupRef == groupRef
1560 && aa.label.equalsIgnoreCase(group))
1562 if (aa.graphGroup > -1)
1564 graphGroup = aa.graphGroup;
1568 if (graphGroup <= combineCount)
1570 graphGroup = combineCount + 1;
1572 aa.graphGroup = graphGroup;
1578 // Now update groups
1579 while (st.hasMoreTokens())
1581 group = st.nextToken();
1582 for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1584 AlignmentAnnotation aa = al.getAlignmentAnnotation()[i];
1585 if (aa.sequenceRef == seqRef && aa.groupRef == groupRef
1586 && aa.label.equalsIgnoreCase(group))
1588 aa.graphGroup = graphGroup;
1597 .println("Couldn't combine annotations. None are added to alignment yet!");
1601 void addLine(AlignmentI al, StringTokenizer st, SequenceI seqRef,
1602 SequenceGroup groupRef)
1604 String group = st.nextToken();
1605 AlignmentAnnotation[] alannot = al.getAlignmentAnnotation();
1606 String nextToken = st.nextToken();
1610 value = Float.valueOf(nextToken);
1611 } catch (NumberFormatException e)
1613 System.err.println("line " + nlinesread + ": Threshold '" + nextToken
1614 + "' invalid, setting to zero");
1616 String label = st.hasMoreTokens() ? st.nextToken() : null;
1617 Color colour = null;
1618 if (st.hasMoreTokens())
1620 colour = ColorUtils.parseColourString(st.nextToken());
1622 if (alannot != null)
1624 for (int i = 0; i < alannot.length; i++)
1626 if (alannot[i].label.equalsIgnoreCase(group)
1627 && (seqRef == null || alannot[i].sequenceRef == seqRef)
1628 && (groupRef == null || alannot[i].groupRef == groupRef))
1630 alannot[i].setThreshold(new GraphLine(value, label, colour));
1636 void addGroup(AlignmentI al, StringTokenizer st)
1638 SequenceGroup sg = new SequenceGroup();
1639 sg.setName(st.nextToken());
1643 rng = st.nextToken();
1644 if (rng.length() > 0 && !rng.startsWith("*"))
1646 sg.setStartRes(Integer.parseInt(rng) - 1);
1652 rng = st.nextToken();
1653 if (rng.length() > 0 && !rng.startsWith("*"))
1655 sg.setEndRes(Integer.parseInt(rng) - 1);
1659 sg.setEndRes(al.getWidth() - 1);
1661 } catch (Exception e)
1664 .println("Couldn't parse Group Start or End Field as '*' or a valid column or sequence index: '"
1665 + rng + "' - assuming alignment width for group.");
1666 // assume group is full width
1668 sg.setEndRes(al.getWidth() - 1);
1671 String index = st.nextToken();
1672 if (index.equals("-1"))
1674 while (st.hasMoreElements())
1676 sg.addSequence(al.findName(st.nextToken()), false);
1681 StringTokenizer st2 = new StringTokenizer(index, ",");
1683 while (st2.hasMoreTokens())
1685 String tmp = st2.nextToken();
1686 if (tmp.equals("*"))
1688 for (int i = 0; i < al.getHeight(); i++)
1690 sg.addSequence(al.getSequenceAt(i), false);
1693 else if (tmp.indexOf("-") >= 0)
1695 StringTokenizer st3 = new StringTokenizer(tmp, "-");
1697 int start = (Integer.parseInt(st3.nextToken()));
1698 int end = (Integer.parseInt(st3.nextToken()));
1702 for (int i = start; i <= end; i++)
1704 sg.addSequence(al.getSequenceAt(i - 1), false);
1710 sg.addSequence(al.getSequenceAt(Integer.parseInt(tmp) - 1), false);
1717 sg.setStartRes(refSeq.findIndex(sg.getStartRes() + 1) - 1);
1718 sg.setEndRes(refSeq.findIndex(sg.getEndRes() + 1) - 1);
1719 sg.setSeqrep(refSeq);
1722 if (sg.getSize() > 0)
1728 void addRowProperties(AlignmentI al, StringTokenizer st)
1730 String label = st.nextToken(), keyValue, key, value;
1731 boolean scaletofit = false, centerlab = false, showalllabs = false;
1732 while (st.hasMoreTokens())
1734 keyValue = st.nextToken();
1735 key = keyValue.substring(0, keyValue.indexOf("="));
1736 value = keyValue.substring(keyValue.indexOf("=") + 1);
1737 if (key.equalsIgnoreCase("scaletofit"))
1739 scaletofit = Boolean.valueOf(value).booleanValue();
1741 if (key.equalsIgnoreCase("showalllabs"))
1743 showalllabs = Boolean.valueOf(value).booleanValue();
1745 if (key.equalsIgnoreCase("centrelabs"))
1747 centerlab = Boolean.valueOf(value).booleanValue();
1749 AlignmentAnnotation[] alr = al.getAlignmentAnnotation();
1752 for (int i = 0; i < alr.length; i++)
1754 if (alr[i].label.equalsIgnoreCase(label))
1756 alr[i].centreColLabels = centerlab;
1757 alr[i].scaleColLabel = scaletofit;
1758 alr[i].showAllColLabels = showalllabs;
1765 void addProperties(AlignmentI al, StringTokenizer st)
1768 // So far we have only added groups to the annotationHash,
1769 // the idea is in the future properties can be added to
1770 // alignments, other annotations etc
1771 if (al.getGroups() == null)
1776 String name = st.nextToken();
1777 SequenceGroup sg = null;
1778 for (SequenceGroup _sg : al.getGroups())
1780 if ((sg = _sg).getName().equals(name))
1792 String keyValue, key, value;
1793 ColourSchemeI def = sg.getColourScheme();
1794 while (st.hasMoreTokens())
1796 keyValue = st.nextToken();
1797 key = keyValue.substring(0, keyValue.indexOf("="));
1798 value = keyValue.substring(keyValue.indexOf("=") + 1);
1800 if (key.equalsIgnoreCase("description"))
1802 sg.setDescription(value);
1804 else if (key.equalsIgnoreCase("colour"))
1806 sg.cs.setColourScheme(ColourSchemeProperty
1807 .getColourScheme(al, value));
1809 else if (key.equalsIgnoreCase("pidThreshold"))
1811 sg.cs.setThreshold(Integer.parseInt(value), true);
1814 else if (key.equalsIgnoreCase("consThreshold"))
1816 sg.cs.setConservationInc(Integer.parseInt(value));
1817 Conservation c = new Conservation("Group", sg.getSequences(null),
1818 sg.getStartRes(), sg.getEndRes() + 1);
1821 c.verdict(false, 25); // TODO: refer to conservation percent threshold
1823 sg.cs.setConservation(c);
1826 else if (key.equalsIgnoreCase("outlineColour"))
1828 sg.setOutlineColour(ColorUtils.parseColourString(value));
1830 else if (key.equalsIgnoreCase("displayBoxes"))
1832 sg.setDisplayBoxes(Boolean.valueOf(value).booleanValue());
1834 else if (key.equalsIgnoreCase("showUnconserved"))
1836 sg.setShowNonconserved(Boolean.valueOf(value).booleanValue());
1838 else if (key.equalsIgnoreCase("displayText"))
1840 sg.setDisplayText(Boolean.valueOf(value).booleanValue());
1842 else if (key.equalsIgnoreCase("colourText"))
1844 sg.setColourText(Boolean.valueOf(value).booleanValue());
1846 else if (key.equalsIgnoreCase("textCol1"))
1848 sg.textColour = ColorUtils.parseColourString(value);
1850 else if (key.equalsIgnoreCase("textCol2"))
1852 sg.textColour2 = ColorUtils.parseColourString(value);
1854 else if (key.equalsIgnoreCase("textColThreshold"))
1856 sg.thresholdTextColour = Integer.parseInt(value);
1858 else if (key.equalsIgnoreCase("idColour"))
1860 Color idColour = ColorUtils.parseColourString(value);
1861 sg.setIdColour(idColour == null ? Color.black : idColour);
1863 else if (key.equalsIgnoreCase("hide"))
1865 // see bug https://mantis.lifesci.dundee.ac.uk/view.php?id=25847
1866 sg.setHidereps(true);
1868 else if (key.equalsIgnoreCase("hidecols"))
1870 // see bug https://mantis.lifesci.dundee.ac.uk/view.php?id=25847
1871 sg.setHideCols(true);
1873 sg.recalcConservation();
1875 if (sg.getColourScheme() == null)
1877 sg.setColourScheme(def);
1882 void setBelowAlignment(AlignmentI al, StringTokenizer st)
1885 AlignmentAnnotation aa, ala[] = al.getAlignmentAnnotation();
1889 .print("Warning - no annotation to set below for sequence associated annotation:");
1891 while (st.hasMoreTokens())
1893 token = st.nextToken();
1896 System.err.print(" " + token);
1900 for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1902 aa = al.getAlignmentAnnotation()[i];
1903 if (aa.sequenceRef == refSeq && aa.label.equals(token))
1905 aa.belowAlignment = true;
1912 System.err.print("\n");
1916 void addAlignmentDetails(AlignmentI al, StringTokenizer st)
1918 String keyValue, key, value;
1919 while (st.hasMoreTokens())
1921 keyValue = st.nextToken();
1922 key = keyValue.substring(0, keyValue.indexOf("="));
1923 value = keyValue.substring(keyValue.indexOf("=") + 1);
1924 al.setProperty(key, value);
1929 * Write annotations as a CSV file of the form 'label, value, value, ...' for
1932 * @param annotations
1933 * @return CSV file as a string.
1935 public String printCSVAnnotations(AlignmentAnnotation[] annotations)
1937 if (annotations == null)
1941 StringBuffer sp = new StringBuffer();
1942 for (int i = 0; i < annotations.length; i++)
1944 String atos = annotations[i].toString();
1948 int cp = atos.indexOf("\n", p);
1949 sp.append(annotations[i].label);
1953 sp.append(atos.substring(p, cp + 1));
1957 sp.append(atos.substring(p));
1963 return sp.toString();
1966 public String printAnnotationsForView(AlignViewportI viewport)
1968 return printAnnotations(viewport.isShowAnnotation() ? viewport
1969 .getAlignment().getAlignmentAnnotation() : null, viewport
1970 .getAlignment().getGroups(), viewport.getAlignment()
1971 .getProperties(), viewport.getColumnSelection(),
1972 viewport.getAlignment(), null);
1975 public String printAnnotationsForAlignment(AlignmentI al)
1977 return printAnnotations(al.getAlignmentAnnotation(), al.getGroups(),
1978 al.getProperties(), null, al, null);