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.schemes.ResidueProperties;
38 import jalview.schemes.UserColourScheme;
40 import java.io.BufferedReader;
41 import java.io.FileReader;
42 import java.io.IOException;
43 import java.io.InputStreamReader;
44 import java.io.StringReader;
46 import java.util.ArrayList;
47 import java.util.BitSet;
48 import java.util.Enumeration;
49 import java.util.Hashtable;
50 import java.util.List;
52 import java.util.StringTokenizer;
53 import java.util.Vector;
55 public class AnnotationFile
57 public AnnotationFile()
63 * character used to write newlines
65 protected String newline = System.getProperty("line.separator");
68 * set new line string and reset the output buffer
72 public void setNewlineString(String nl)
78 public String getNewlineString()
87 text = new StringBuffer("JALVIEW_ANNOTATION" + newline + "# Created: "
88 + new java.util.Date() + newline + newline);
94 * convenience method for pre-2.9 annotation files which have no view, hidden
95 * columns or hidden row keywords.
100 * @return annotation file as a string.
102 public String printAnnotations(AlignmentAnnotation[] annotations,
103 List<SequenceGroup> list, Hashtable properties)
105 return printAnnotations(annotations, list, properties, null, null, null);
110 * hold all the information about a particular view definition read from or
111 * written out in an annotations file.
115 public String viewname;
117 public HiddenSequences hidseqs;
119 public ColumnSelection hiddencols;
121 public Vector visibleGroups;
123 public Hashtable hiddenRepSeqs;
125 public ViewDef(String viewname, HiddenSequences hidseqs,
126 ColumnSelection hiddencols, Hashtable hiddenRepSeqs)
128 this.viewname = viewname;
129 this.hidseqs = hidseqs;
130 this.hiddencols = hiddencols;
131 this.hiddenRepSeqs = hiddenRepSeqs;
136 * Prepare an annotation file given a set of annotations, groups, alignment
137 * properties and views.
143 * @return annotation file
145 public String printAnnotations(AlignmentAnnotation[] annotations,
146 List<SequenceGroup> list, Hashtable properties,
147 ColumnSelection cs, AlignmentI al, ViewDef view)
151 if (view.viewname != null)
153 text.append("VIEW_DEF\t" + view.viewname + "\n");
157 list = view.visibleGroups;
161 cs = view.hiddencols;
165 // add hidden rep sequences.
168 // first target - store and restore all settings for a view.
169 if (al != null && al.hasSeqrep())
171 text.append("VIEW_SETREF\t" + al.getSeqrep().getName() + "\n");
173 if (cs != null && cs.hasHiddenColumns())
175 text.append("VIEW_HIDECOLS\t");
176 List<int[]> hc = cs.getHiddenColumns();
177 boolean comma = false;
194 // TODO: allow efficient recovery of annotation data shown in several
196 if (annotations != null)
198 boolean oneColour = true;
199 AlignmentAnnotation row;
201 SequenceI refSeq = null;
202 SequenceGroup refGroup = null;
204 StringBuffer colours = new StringBuffer();
205 StringBuffer graphLine = new StringBuffer();
206 StringBuffer rowprops = new StringBuffer();
207 Hashtable<Integer, String> graphGroup = new Hashtable<Integer, String>();
208 Hashtable<Integer, Object[]> graphGroup_refs = new Hashtable<Integer, Object[]>();
209 BitSet graphGroupSeen = new BitSet();
211 java.awt.Color color;
213 for (int i = 0; i < annotations.length; i++)
215 row = annotations[i];
219 && !(row.graphGroup > -1 && graphGroupSeen
220 .get(row.graphGroup)))
228 // mark any sequence references for the row
229 writeSequence_Ref(refSeq, row.sequenceRef);
230 refSeq = row.sequenceRef;
231 // mark any group references for the row
232 writeGroup_Ref(refGroup, row.groupRef);
233 refGroup = row.groupRef;
235 boolean hasGlyphs = row.hasIcons, hasLabels = row.hasText, hasValues = row.hasScore, hasText = false;
236 // lookahead to check what the annotation row object actually contains.
237 for (int j = 0; row.annotations != null
238 && j < row.annotations.length
239 && (!hasGlyphs || !hasLabels || !hasValues); j++)
241 if (row.annotations[j] != null)
243 hasLabels |= (row.annotations[j].displayCharacter != null
244 && row.annotations[j].displayCharacter.length() > 0 && !row.annotations[j].displayCharacter
246 hasGlyphs |= (row.annotations[j].secondaryStructure != 0 && row.annotations[j].secondaryStructure != ' ');
247 hasValues |= (!Float.isNaN(row.annotations[j].value)); // NaNs can't
250 hasText |= (row.annotations[j].description != null && row.annotations[j].description
255 if (row.graph == AlignmentAnnotation.NO_GRAPH)
257 text.append("NO_GRAPH\t");
258 hasValues = false; // only secondary structure
259 // hasLabels = false; // and annotation description string.
263 if (row.graph == AlignmentAnnotation.BAR_GRAPH)
265 text.append("BAR_GRAPH\t");
266 hasGlyphs = false; // no secondary structure
269 else if (row.graph == AlignmentAnnotation.LINE_GRAPH)
271 hasGlyphs = false; // no secondary structure
272 text.append("LINE_GRAPH\t");
275 if (row.getThreshold() != null)
277 graphLine.append("GRAPHLINE\t");
278 graphLine.append(row.label);
279 graphLine.append("\t");
280 graphLine.append(row.getThreshold().value);
281 graphLine.append("\t");
282 graphLine.append(row.getThreshold().label);
283 graphLine.append("\t");
284 graphLine.append(jalview.util.Format.getHexString(row
285 .getThreshold().colour));
286 graphLine.append(newline);
289 if (row.graphGroup > -1)
291 graphGroupSeen.set(row.graphGroup);
292 Integer key = new Integer(row.graphGroup);
293 if (graphGroup.containsKey(key))
295 graphGroup.put(key, graphGroup.get(key) + "\t" + row.label);
300 graphGroup_refs.put(key, new Object[] { refSeq, refGroup });
301 graphGroup.put(key, row.label);
306 text.append(row.label + "\t");
307 if (row.description != null)
309 text.append(row.description + "\t");
311 for (int j = 0; row.annotations != null
312 && j < row.annotations.length; j++)
315 && jalview.util.Comparison.isGap(refSeq.getCharAt(j)))
320 if (row.annotations[j] != null)
323 if (hasGlyphs) // could be also hasGlyphs || ...
327 if (row.annotations[j].secondaryStructure != ' ')
329 // only write out the field if its not whitespace.
330 text.append(row.annotations[j].secondaryStructure);
336 if (!Float.isNaN(row.annotations[j].value))
338 text.append(comma + row.annotations[j].value);
342 // System.err.println("Skipping NaN - not valid value.");
343 text.append(comma + 0f);// row.annotations[j].value);
349 // TODO: labels are emitted after values for bar graphs.
350 if // empty labels are allowed, so
351 (row.annotations[j].displayCharacter != null
352 && row.annotations[j].displayCharacter.length() > 0
353 && !row.annotations[j].displayCharacter.equals(" "))
355 text.append(comma + row.annotations[j].displayCharacter);
361 if (row.annotations[j].description != null
362 && row.annotations[j].description.length() > 0
363 && !row.annotations[j].description
364 .equals(row.annotations[j].displayCharacter))
366 text.append(comma + row.annotations[j].description);
370 if (color != null && !color.equals(row.annotations[j].colour))
375 color = row.annotations[j].colour;
377 if (row.annotations[j].colour != null
378 && row.annotations[j].colour != java.awt.Color.black)
382 + jalview.util.Format
383 .getHexString(row.annotations[j].colour)
393 text.append("\t" + row.score);
396 text.append(newline);
398 if (color != null && color != java.awt.Color.black && oneColour)
400 colours.append("COLOUR\t");
401 colours.append(row.label);
402 colours.append("\t");
403 colours.append(jalview.util.Format.getHexString(color));
404 colours.append(newline);
406 if (row.scaleColLabel || row.showAllColLabels
407 || row.centreColLabels)
409 rowprops.append("ROWPROPERTIES\t");
410 rowprops.append(row.label);
411 rowprops.append("\tscaletofit=");
412 rowprops.append(row.scaleColLabel);
413 rowprops.append("\tshowalllabs=");
414 rowprops.append(row.showAllColLabels);
415 rowprops.append("\tcentrelabs=");
416 rowprops.append(row.centreColLabels);
417 rowprops.append(newline);
419 if (graphLine.length() > 0)
421 text.append(graphLine.toString());
422 graphLine.setLength(0);
426 text.append(newline);
428 text.append(colours.toString());
429 if (graphGroup.size() > 0)
431 SequenceI oldRefSeq = refSeq;
432 SequenceGroup oldRefGroup = refGroup;
433 for (Map.Entry<Integer, String> combine_statement : graphGroup
436 Object[] seqRefAndGroup = graphGroup_refs.get(combine_statement
439 writeSequence_Ref(refSeq, (SequenceI) seqRefAndGroup[0]);
440 refSeq = (SequenceI) seqRefAndGroup[0];
442 writeGroup_Ref(refGroup, (SequenceGroup) seqRefAndGroup[1]);
443 refGroup = (SequenceGroup) seqRefAndGroup[1];
444 text.append("COMBINE\t");
445 text.append(combine_statement.getValue());
446 text.append(newline);
448 writeSequence_Ref(refSeq, oldRefSeq);
451 writeGroup_Ref(refGroup, oldRefGroup);
452 refGroup = oldRefGroup;
454 text.append(rowprops.toString());
462 if (properties != null)
464 text.append(newline);
465 text.append(newline);
466 text.append("ALIGNMENT");
467 Enumeration en = properties.keys();
468 while (en.hasMoreElements())
470 String key = en.nextElement().toString();
474 text.append(properties.get(key));
476 // TODO: output alignment visualization settings here if required
477 // iterate through one or more views, defining, marking columns and rows
478 // as visible/hidden, and emmitting view properties.
479 // View specific annotation is
482 return text.toString();
485 private Object writeGroup_Ref(SequenceGroup refGroup,
486 SequenceGroup next_refGroup)
488 if (next_refGroup == null)
491 if (refGroup != null)
493 text.append(newline);
494 text.append("GROUP_REF\t");
495 text.append("ALIGNMENT");
496 text.append(newline);
502 if (refGroup == null || refGroup != next_refGroup)
504 text.append(newline);
505 text.append("GROUP_REF\t");
506 text.append(next_refGroup.getName());
507 text.append(newline);
514 private boolean writeSequence_Ref(SequenceI refSeq, SequenceI next_refSeq)
517 if (next_refSeq == null)
521 text.append(newline);
522 text.append("SEQUENCE_REF\t");
523 text.append("ALIGNMENT");
524 text.append(newline);
530 if (refSeq == null || refSeq != next_refSeq)
532 text.append(newline);
533 text.append("SEQUENCE_REF\t");
534 text.append(next_refSeq.getName());
535 text.append(newline);
542 public void printGroups(List<SequenceGroup> list)
544 SequenceI seqrep = null;
545 for (SequenceGroup sg : list)
549 text.append("SEQUENCE_GROUP\t" + sg.getName() + "\t"
550 + (sg.getStartRes() + 1) + "\t" + (sg.getEndRes() + 1)
556 seqrep = sg.getSeqrep();
557 text.append("SEQUENCE_REF\t");
558 text.append(seqrep.getName());
559 text.append(newline);
560 text.append("SEQUENCE_GROUP\t");
561 text.append(sg.getName());
563 text.append((seqrep.findPosition(sg.getStartRes())));
565 text.append((seqrep.findPosition(sg.getEndRes())));
569 for (int s = 0; s < sg.getSize(); s++)
571 text.append(sg.getSequenceAt(s).getName());
574 text.append(newline);
575 text.append("PROPERTIES\t");
576 text.append(sg.getName());
579 if (sg.getDescription() != null)
581 text.append("description=");
582 text.append(sg.getDescription());
587 text.append("colour=");
588 text.append(ColourSchemeProperty.getColourName(sg.cs));
590 if (sg.cs.getThreshold() != 0)
592 text.append("pidThreshold=");
593 text.append(sg.cs.getThreshold());
595 if (sg.cs.conservationApplied())
597 text.append("consThreshold=");
598 text.append(sg.cs.getConservationInc());
602 text.append("outlineColour=");
603 text.append(jalview.util.Format.getHexString(sg.getOutlineColour()));
606 text.append("displayBoxes=");
607 text.append(sg.getDisplayBoxes());
609 text.append("displayText=");
610 text.append(sg.getDisplayText());
612 text.append("colourText=");
613 text.append(sg.getColourText());
615 text.append("showUnconserved=");
616 text.append(sg.getShowNonconserved());
618 if (sg.textColour != java.awt.Color.black)
620 text.append("textCol1=");
621 text.append(jalview.util.Format.getHexString(sg.textColour));
624 if (sg.textColour2 != java.awt.Color.white)
626 text.append("textCol2=");
627 text.append(jalview.util.Format.getHexString(sg.textColour2));
630 if (sg.thresholdTextColour != 0)
632 text.append("textColThreshold=");
633 text.append(sg.thresholdTextColour);
636 if (sg.idColour != null)
638 text.append("idColour=");
639 text.append(jalview.util.Format.getHexString(sg.idColour));
644 text.append("hide=true\t");
648 text.append("hidecols=true\t");
652 // terminate the last line and clear the sequence ref for the group
653 text.append(newline);
654 text.append("SEQUENCE_REF");
656 text.append(newline);
657 text.append(newline);
662 SequenceI refSeq = null;
664 String refSeqId = null;
666 public boolean annotateAlignmentView(AlignViewportI viewport,
667 String file, String protocol)
669 ColumnSelection colSel = viewport.getColumnSelection();
672 colSel = new ColumnSelection();
674 boolean rslt = readAnnotationFile(viewport.getAlignment(), colSel,
676 if (rslt && (colSel.hasSelectedColumns() || colSel.hasHiddenColumns()))
678 viewport.setColumnSelection(colSel);
684 public boolean readAnnotationFile(AlignmentI al, String file,
687 return readAnnotationFile(al, null, file, protocol);
690 public boolean readAnnotationFile(AlignmentI al, ColumnSelection colSel,
691 String file, String protocol)
693 BufferedReader in = null;
696 if (protocol.equals(AppletFormatAdapter.FILE))
698 in = new BufferedReader(new FileReader(file));
700 else if (protocol.equals(AppletFormatAdapter.URL))
702 URL url = new URL(file);
703 in = new BufferedReader(new InputStreamReader(url.openStream()));
705 else if (protocol.equals(AppletFormatAdapter.PASTE))
707 in = new BufferedReader(new StringReader(file));
709 else if (protocol.equals(AppletFormatAdapter.CLASSLOADER))
711 java.io.InputStream is = getClass().getResourceAsStream("/" + file);
714 in = new BufferedReader(new java.io.InputStreamReader(is));
719 return parseAnnotationFrom(al, colSel, in);
722 } catch (Exception ex)
724 ex.printStackTrace();
725 System.out.println("Problem reading annotation file: " + ex);
728 System.out.println("Last read line " + nlinesread + ": '"
729 + lastread + "' (first 80 chars) ...");
738 String lastread = "";
740 private static String GRAPHLINE = "GRAPHLINE", COMBINE = "COMBINE",
741 STRUCTMODEL = "STRUCTMODEL";
743 public boolean parseAnnotationFrom(AlignmentI al, ColumnSelection colSel,
744 BufferedReader in) throws Exception
747 ArrayList<Object[]> combineAnnotation_calls = new ArrayList<Object[]>();
748 ArrayList<Object[]> deferredAnnotation_calls = new ArrayList<Object[]>();
749 boolean modified = false;
750 String groupRef = null;
751 Hashtable groupRefRows = new Hashtable();
753 Hashtable autoAnnots = new Hashtable();
755 String line, label, description, token;
756 int graphStyle, index;
758 int existingAnnotations = 0;
759 // when true - will add new rows regardless of whether they are duplicate
760 // auto-annotation like consensus or conservation graphs
761 boolean overrideAutoAnnot = false;
762 if (al.getAlignmentAnnotation() != null)
764 existingAnnotations = al.getAlignmentAnnotation().length;
765 if (existingAnnotations > 0)
767 AlignmentAnnotation[] aa = al.getAlignmentAnnotation();
768 for (int aai = 0; aai < aa.length; aai++)
770 if (aa[aai].autoCalculated)
772 // make a note of the name and description
774 autoAnnotsKey(aa[aai], aa[aai].sequenceRef,
775 (aa[aai].groupRef == null ? null
776 : aa[aai].groupRef.getName())),
783 int alWidth = al.getWidth();
786 Annotation[] annotations;
787 AlignmentAnnotation annotation = null;
789 // First confirm this is an Annotation file
790 boolean jvAnnotationFile = false;
791 while ((line = in.readLine()) != null)
794 lastread = new String(line);
795 if (line.indexOf("#") == 0)
800 if (line.indexOf("JALVIEW_ANNOTATION") > -1)
802 jvAnnotationFile = true;
807 if (!jvAnnotationFile)
813 while ((line = in.readLine()) != null)
816 lastread = new String(line);
817 if (line.indexOf("#") == 0
818 || line.indexOf("JALVIEW_ANNOTATION") > -1
819 || line.length() == 0)
824 st = new StringTokenizer(line, "\t");
825 token = st.nextToken();
826 if (token.equalsIgnoreCase("COLOUR"))
828 // TODO: use graduated colour def'n here too
829 colourAnnotations(al, st.nextToken(), st.nextToken());
834 else if (token.equalsIgnoreCase(COMBINE))
836 // keep a record of current state and resolve groupRef at end
837 combineAnnotation_calls
838 .add(new Object[] { st, refSeq, groupRef });
842 else if (token.equalsIgnoreCase("ROWPROPERTIES"))
844 addRowProperties(al, st);
848 else if (token.equalsIgnoreCase(GRAPHLINE))
851 deferredAnnotation_calls.add(new Object[] { GRAPHLINE, st,
857 else if (token.equalsIgnoreCase("SEQUENCE_REF"))
859 if (st.hasMoreTokens())
861 refSeq = al.findName(refSeqId = st.nextToken());
868 refSeqIndex = Integer.parseInt(st.nextToken());
873 .println("WARNING: SEQUENCE_REF index must be > 0 in AnnotationFile");
875 } catch (Exception ex)
887 else if (token.equalsIgnoreCase("GROUP_REF"))
889 // Group references could be forward or backwards, so they are
890 // resolved after the whole file is read in
892 if (st.hasMoreTokens())
894 groupRef = st.nextToken();
895 if (groupRef.length() < 1)
897 groupRef = null; // empty string
901 if (groupRefRows.get(groupRef) == null)
903 groupRefRows.put(groupRef, new Vector());
909 else if (token.equalsIgnoreCase("SEQUENCE_GROUP"))
916 else if (token.equalsIgnoreCase("PROPERTIES"))
918 addProperties(al, st);
923 else if (token.equalsIgnoreCase("BELOW_ALIGNMENT"))
925 setBelowAlignment(al, st);
929 else if (token.equalsIgnoreCase("ALIGNMENT"))
931 addAlignmentDetails(al, st);
935 // else if (token.equalsIgnoreCase("VIEW_DEF"))
937 // addOrSetView(al,st);
941 else if (token.equalsIgnoreCase("VIEW_SETREF"))
945 al.setSeqrep(refSeq);
950 else if (token.equalsIgnoreCase("VIEW_HIDECOLS"))
952 if (st.hasMoreTokens())
956 colSel = new ColumnSelection();
958 parseHideCols(colSel, st.nextToken());
963 else if (token.equalsIgnoreCase("HIDE_INSERTIONS"))
965 SequenceI sr = refSeq == null ? al.getSeqrep() : refSeq;
968 sr = al.getSequenceAt(0);
975 .println("Cannot process HIDE_INSERTIONS without an alignment view: Ignoring line: "
980 // consider deferring this till after the file has been parsed ?
981 colSel.hideInsertionsFor(sr);
987 else if (token.equalsIgnoreCase(STRUCTMODEL))
989 boolean failedtoadd = true;
991 // STRUCTMODEL <QUERYID> <TemplateID> <URL to model> <URL to
993 if (st.hasMoreTokens()) {
994 refSeq = al.findName(refSeqId = st.nextToken());
997 System.err.println("Couldn't locate " + refSeqId
998 + " in the alignment for STRUCTMODEL");
1003 String tempId = st.nextToken();
1004 String urlToModel = st.nextToken();
1005 String urlToPairwise = st.hasMoreTokens() ? st.nextToken()
1007 if (add_structmodel(al, refSeq, tempId, urlToModel,
1010 failedtoadd = false;
1017 .println("Need <QueryId> <TemplateId> <URL to Model> [<URL to pairwise alignment>] as tab separated fields after "
1024 // Parse out the annotation row
1025 graphStyle = AlignmentAnnotation.getGraphValueFromString(token);
1026 label = st.nextToken();
1029 annotations = new Annotation[alWidth];
1031 float score = Float.NaN;
1033 if (st.hasMoreTokens())
1035 line = st.nextToken();
1037 if (line.indexOf("|") == -1)
1040 if (st.hasMoreTokens())
1042 line = st.nextToken();
1046 if (st.hasMoreTokens())
1048 // This must be the score
1049 score = Float.valueOf(st.nextToken()).floatValue();
1052 st = new StringTokenizer(line, "|", true);
1054 boolean emptyColumn = true;
1055 boolean onlyOneElement = (st.countTokens() == 1);
1057 while (st.hasMoreElements() && index < alWidth)
1059 token = st.nextToken().trim();
1065 score = Float.valueOf(token).floatValue();
1067 } catch (NumberFormatException ex)
1072 if (token.equals("|"))
1083 annotations[index++] = parseAnnotation(token, graphStyle);
1084 emptyColumn = false;
1090 annotation = new AlignmentAnnotation(label, description,
1091 (index == 0) ? null : annotations, 0, 0, graphStyle);
1093 annotation.score = score;
1094 if (!overrideAutoAnnot
1095 && autoAnnots.containsKey(autoAnnotsKey(annotation, refSeq,
1098 // skip - we've already got an automatic annotation of this type.
1101 // otherwise add it!
1105 annotation.belowAlignment = false;
1106 // make a copy of refSeq so we can find other matches in the alignment
1107 SequenceI referedSeq = refSeq;
1110 // copy before we do any mapping business.
1111 // TODO: verify that undo/redo with 1:many sequence associated
1112 // annotations can be undone correctly
1113 AlignmentAnnotation ann = new AlignmentAnnotation(annotation);
1115 .createSequenceMapping(referedSeq, refSeqIndex, false);
1116 annotation.adjustForAlignment();
1117 referedSeq.addAlignmentAnnotation(annotation);
1118 al.addAnnotation(annotation);
1119 al.setAnnotationIndex(annotation,
1120 al.getAlignmentAnnotation().length
1121 - existingAnnotations - 1);
1122 if (groupRef != null)
1124 ((Vector) groupRefRows.get(groupRef)).addElement(annotation);
1126 // and recover our virgin copy to use again if necessary.
1129 } while (refSeqId != null
1130 && (referedSeq = al.findName(referedSeq, refSeqId, true)) != null);
1134 al.addAnnotation(annotation);
1135 al.setAnnotationIndex(annotation,
1136 al.getAlignmentAnnotation().length - existingAnnotations
1138 if (groupRef != null)
1140 ((Vector) groupRefRows.get(groupRef)).addElement(annotation);
1143 // and set modification flag
1146 // Resolve the groupRefs
1147 Hashtable<String, SequenceGroup> groupRefLookup = new Hashtable<String, SequenceGroup>();
1148 Enumeration en = groupRefRows.keys();
1150 while (en.hasMoreElements())
1152 groupRef = (String) en.nextElement();
1153 boolean matched = false;
1154 // Resolve group: TODO: add a getGroupByName method to alignments
1155 for (SequenceGroup theGroup : al.getGroups())
1157 if (theGroup.getName().equals(groupRef))
1161 // TODO: specify and implement duplication of alignment annotation
1162 // for multiple group references.
1164 .println("Ignoring 1:many group reference mappings for group name '"
1170 Vector rowset = (Vector) groupRefRows.get(groupRef);
1171 groupRefLookup.put(groupRef, theGroup);
1172 if (rowset != null && rowset.size() > 0)
1174 AlignmentAnnotation alan = null;
1175 for (int elm = 0, elmSize = rowset.size(); elm < elmSize; elm++)
1177 alan = (AlignmentAnnotation) rowset.elementAt(elm);
1178 alan.groupRef = theGroup;
1184 ((Vector) groupRefRows.get(groupRef)).removeAllElements();
1186 // process any deferred attribute settings for each context
1187 for (Object[] _deferred_args : deferredAnnotation_calls)
1189 if (_deferred_args[0] == GRAPHLINE)
1192 (StringTokenizer) _deferred_args[1], // st
1193 (SequenceI) _deferred_args[2], // refSeq
1194 (_deferred_args[3] == null) ? null : groupRefLookup
1195 .get(_deferred_args[3]) // the reference
1201 // finally, combine all the annotation rows within each context.
1203 * number of combine statements in this annotation file. Used to create
1204 * new groups for combined annotation graphs without disturbing existing
1207 int combinecount = 0;
1208 for (Object[] _combine_args : combineAnnotation_calls)
1210 combineAnnotations(al,
1212 (StringTokenizer) _combine_args[0], // st
1213 (SequenceI) _combine_args[1], // refSeq
1214 (_combine_args[2] == null) ? null : groupRefLookup
1215 .get(_combine_args[2]) // the reference group,
1224 * resolve a structural model and generate and add an alignment sequence for
1230 * @param urlToPairwise
1231 * @return true if model and sequence was added
1233 private boolean add_structmodel(AlignmentI al, SequenceI refSeq2, String tempId,
1234 String urlToModel, String urlToPairwise)
1236 String warningMessage=null;
1237 boolean added = false;
1239 // locate tempId. if it exists, will need to merge, otherwise:
1240 SequenceI templateSeq = al.findName(tempId);
1241 // 1. load urlToModel
1242 // TODO: get base for current import operation and resolve against it
1243 // transfer to local temp file ?
1244 PDBEntry modelpe = new PDBEntry(tempId,null,Type.FILE,urlToModel);
1245 PDBEntry templpe = new PDBEntry(tempId, null, Type.FILE, urlToModel);
1246 refSeq2.addPDBId(modelpe);
1248 // 2. load urlToPairwise
1249 AlignmentI pwa = new AppletFormatAdapter().readFile(urlToPairwise,
1250 AppletFormatAdapter.checkProtocol(urlToPairwise), "FASTA");
1251 SequenceI qPw = null, tPw = null;
1254 // resolve query/template sequences in provided alignment
1255 qPw = pwa.findName(refSeqId);
1256 tPw = pwa.findName(tempId);
1259 // (qPw != null && tPw != null)
1262 // refalQ vvva--addrvvvtttddd
1263 // refalT ---aaaa---sss---ddd
1264 // profalQ ---v-v-v-a.-.-a---dd--r--vvvtt--td--dd
1265 // profalT ---.-.-.-aa-a-a---..--.--sss..--.d--dd
1266 // Pragmatic solution here:
1267 // Map templpe onto refalT only where refalT and refalQ are both
1270 // columns for start..end in refSeq2
1271 int[] gapMap = refSeq2.gapMap();
1272 // insert gaps in tPw
1273 int curi = 0, width = refSeq2.getLength();
1278 // assume 1:1 - so synthesise sequences to use to construct mapping ?
1279 refSeq2.getDatasetSequence().addPDBId(modelpe);
1280 if (templateSeq == null && tPw != null)
1282 tPw.createDatasetSequence();
1283 tPw.getDatasetSequence().addPDBId(templpe); // needs to set mapping based on model yet...
1284 al.addSequence(tPw);
1288 // 3. pad/insert gaps in urlToPairwise according to gaps already present in
1290 // 4. add padded tempId sequence to alignment
1291 // 4. associate urlToModel with refSeq2 based on position map provided by
1293 // 5. associate urlToModel with tempId based on position map provided by
1295 // start a thread to load urlToModel and process/annotate sequences.
1296 } catch (IOException x)
1298 warningMessage = x.toString();
1300 if (warningMessage !=null)
1302 System.err.println("Warnings whilst processing STRUCTMODEL: "+warningMessage);
1308 private void parseHideCols(ColumnSelection colSel, String nextToken)
1310 StringTokenizer inval = new StringTokenizer(nextToken, ",");
1311 while (inval.hasMoreTokens())
1313 String range = inval.nextToken().trim();
1314 int from, to = range.indexOf("-");
1317 from = to = Integer.parseInt(range);
1320 colSel.hideColumns(from, to);
1325 from = Integer.parseInt(range.substring(0, to));
1326 if (to < range.length() - 1)
1328 to = Integer.parseInt(range.substring(to + 1));
1334 if (from > 0 && to >= from)
1336 colSel.hideColumns(from, to);
1342 private Object autoAnnotsKey(AlignmentAnnotation annotation,
1343 SequenceI refSeq, String groupRef)
1345 return annotation.graph + "\t" + annotation.label + "\t"
1346 + annotation.description + "\t"
1347 + (refSeq != null ? refSeq.getDisplayId(true) : "");
1350 Annotation parseAnnotation(String string, int graphStyle)
1352 boolean hasSymbols = (graphStyle == AlignmentAnnotation.NO_GRAPH); // don't
1361 String desc = null, displayChar = null;
1362 char ss = ' '; // secondaryStructure
1364 boolean parsedValue = false, dcset = false;
1367 java.awt.Color colour = null;
1368 int i = string.indexOf("[");
1369 int j = string.indexOf("]");
1370 if (i > -1 && j > -1)
1372 UserColourScheme ucs = new UserColourScheme();
1374 colour = ucs.getColourFromString(string.substring(i + 1, j));
1375 if (i > 0 && string.charAt(i - 1) == ',')
1377 // clip the preceding comma as well
1380 string = string.substring(0, i) + string.substring(j + 1);
1383 StringTokenizer st = new StringTokenizer(string, ",", true);
1385 boolean seenContent = false;
1387 while (st.hasMoreTokens())
1390 token = st.nextToken().trim();
1391 if (token.equals(","))
1393 if (!seenContent && parsedValue && !dcset)
1395 // allow the value below the bar/line to be empty
1399 seenContent = false;
1411 displayChar = token;
1413 value = new Float(token).floatValue();
1416 } catch (NumberFormatException ex)
1422 if (token.length() == 1)
1424 displayChar = token;
1428 && (token.length() == 1 && "()<>[]{}AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz"
1431 // Either this character represents a helix or sheet
1432 // or an integer which can be displayed
1433 ss = token.charAt(0);
1434 if (displayChar.equals(token.substring(0, 1)))
1439 else if (desc == null || (parsedValue && pass > 2))
1445 // if (!dcset && string.charAt(string.length() - 1) == ',')
1447 // displayChar = " "; // empty display char symbol.
1449 if (displayChar != null && desc != null && desc.length() == 1)
1451 if (displayChar.length() > 1)
1453 // switch desc and displayChar - legacy support
1454 String tmp = displayChar;
1460 if (displayChar.equals(desc))
1462 // duplicate label - hangover from the 'robust parser' above
1467 Annotation anot = new Annotation(displayChar, desc, ss, value);
1469 anot.colour = colour;
1474 void colourAnnotations(AlignmentI al, String label, String colour)
1476 UserColourScheme ucs = new UserColourScheme(colour);
1477 Annotation[] annotations;
1478 for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1480 if (al.getAlignmentAnnotation()[i].label.equalsIgnoreCase(label))
1482 annotations = al.getAlignmentAnnotation()[i].annotations;
1483 for (int j = 0; j < annotations.length; j++)
1485 if (annotations[j] != null)
1487 annotations[j].colour = ucs.findColour('A');
1494 void combineAnnotations(AlignmentI al, int combineCount,
1495 StringTokenizer st, SequenceI seqRef, SequenceGroup groupRef)
1497 String group = st.nextToken();
1498 // First make sure we are not overwriting the graphIndex
1500 if (al.getAlignmentAnnotation() != null)
1502 for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1504 AlignmentAnnotation aa = al.getAlignmentAnnotation()[i];
1506 if (aa.graphGroup > graphGroup)
1508 // try to number graphGroups in order of occurence.
1509 graphGroup = aa.graphGroup + 1;
1511 if (aa.sequenceRef == seqRef && aa.groupRef == groupRef
1512 && aa.label.equalsIgnoreCase(group))
1514 if (aa.graphGroup > -1)
1516 graphGroup = aa.graphGroup;
1520 if (graphGroup <= combineCount)
1522 graphGroup = combineCount + 1;
1524 aa.graphGroup = graphGroup;
1530 // Now update groups
1531 while (st.hasMoreTokens())
1533 group = st.nextToken();
1534 for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1536 AlignmentAnnotation aa = al.getAlignmentAnnotation()[i];
1537 if (aa.sequenceRef == seqRef && aa.groupRef == groupRef
1538 && aa.label.equalsIgnoreCase(group))
1540 aa.graphGroup = graphGroup;
1549 .println("Couldn't combine annotations. None are added to alignment yet!");
1553 void addLine(AlignmentI al, StringTokenizer st, SequenceI seqRef,
1554 SequenceGroup groupRef)
1556 String group = st.nextToken();
1557 AlignmentAnnotation annotation = null, alannot[] = al
1558 .getAlignmentAnnotation();
1559 float value = new Float(st.nextToken()).floatValue();
1560 String label = st.hasMoreTokens() ? st.nextToken() : null;
1561 java.awt.Color colour = null;
1562 if (st.hasMoreTokens())
1564 UserColourScheme ucs = new UserColourScheme(st.nextToken());
1565 colour = ucs.findColour('A');
1567 if (alannot != null)
1569 for (int i = 0; i < alannot.length; i++)
1571 if (alannot[i].label.equalsIgnoreCase(group)
1572 && (seqRef == null || alannot[i].sequenceRef == seqRef)
1573 && (groupRef == null || alannot[i].groupRef == groupRef))
1575 alannot[i].setThreshold(new GraphLine(value, label, colour));
1579 if (annotation == null)
1585 void addGroup(AlignmentI al, StringTokenizer st)
1587 SequenceGroup sg = new SequenceGroup();
1588 sg.setName(st.nextToken());
1592 rng = st.nextToken();
1593 if (rng.length() > 0 && !rng.startsWith("*"))
1595 sg.setStartRes(Integer.parseInt(rng) - 1);
1601 rng = st.nextToken();
1602 if (rng.length() > 0 && !rng.startsWith("*"))
1604 sg.setEndRes(Integer.parseInt(rng) - 1);
1608 sg.setEndRes(al.getWidth() - 1);
1610 } catch (Exception e)
1613 .println("Couldn't parse Group Start or End Field as '*' or a valid column or sequence index: '"
1614 + rng + "' - assuming alignment width for group.");
1615 // assume group is full width
1617 sg.setEndRes(al.getWidth() - 1);
1620 String index = st.nextToken();
1621 if (index.equals("-1"))
1623 while (st.hasMoreElements())
1625 sg.addSequence(al.findName(st.nextToken()), false);
1630 StringTokenizer st2 = new StringTokenizer(index, ",");
1632 while (st2.hasMoreTokens())
1634 String tmp = st2.nextToken();
1635 if (tmp.equals("*"))
1637 for (int i = 0; i < al.getHeight(); i++)
1639 sg.addSequence(al.getSequenceAt(i), false);
1642 else if (tmp.indexOf("-") >= 0)
1644 StringTokenizer st3 = new StringTokenizer(tmp, "-");
1646 int start = (Integer.parseInt(st3.nextToken()));
1647 int end = (Integer.parseInt(st3.nextToken()));
1651 for (int i = start; i <= end; i++)
1653 sg.addSequence(al.getSequenceAt(i - 1), false);
1659 sg.addSequence(al.getSequenceAt(Integer.parseInt(tmp) - 1), false);
1666 sg.setStartRes(refSeq.findIndex(sg.getStartRes() + 1) - 1);
1667 sg.setEndRes(refSeq.findIndex(sg.getEndRes() + 1) - 1);
1668 sg.setSeqrep(refSeq);
1671 if (sg.getSize() > 0)
1677 void addRowProperties(AlignmentI al, StringTokenizer st)
1679 String label = st.nextToken(), keyValue, key, value;
1680 boolean scaletofit = false, centerlab = false, showalllabs = false;
1681 while (st.hasMoreTokens())
1683 keyValue = st.nextToken();
1684 key = keyValue.substring(0, keyValue.indexOf("="));
1685 value = keyValue.substring(keyValue.indexOf("=") + 1);
1686 if (key.equalsIgnoreCase("scaletofit"))
1688 scaletofit = Boolean.valueOf(value).booleanValue();
1690 if (key.equalsIgnoreCase("showalllabs"))
1692 showalllabs = Boolean.valueOf(value).booleanValue();
1694 if (key.equalsIgnoreCase("centrelabs"))
1696 centerlab = Boolean.valueOf(value).booleanValue();
1698 AlignmentAnnotation[] alr = al.getAlignmentAnnotation();
1701 for (int i = 0; i < alr.length; i++)
1703 if (alr[i].label.equalsIgnoreCase(label))
1705 alr[i].centreColLabels = centerlab;
1706 alr[i].scaleColLabel = scaletofit;
1707 alr[i].showAllColLabels = showalllabs;
1714 void addProperties(AlignmentI al, StringTokenizer st)
1717 // So far we have only added groups to the annotationHash,
1718 // the idea is in the future properties can be added to
1719 // alignments, other annotations etc
1720 if (al.getGroups() == null)
1725 String name = st.nextToken();
1726 SequenceGroup sg = null;
1727 for (SequenceGroup _sg : al.getGroups())
1729 if ((sg = _sg).getName().equals(name))
1741 String keyValue, key, value;
1742 ColourSchemeI def = sg.cs;
1744 while (st.hasMoreTokens())
1746 keyValue = st.nextToken();
1747 key = keyValue.substring(0, keyValue.indexOf("="));
1748 value = keyValue.substring(keyValue.indexOf("=") + 1);
1750 if (key.equalsIgnoreCase("description"))
1752 sg.setDescription(value);
1754 else if (key.equalsIgnoreCase("colour"))
1756 sg.cs = ColourSchemeProperty.getColour(al, value);
1758 else if (key.equalsIgnoreCase("pidThreshold"))
1760 sg.cs.setThreshold(Integer.parseInt(value), true);
1763 else if (key.equalsIgnoreCase("consThreshold"))
1765 sg.cs.setConservationInc(Integer.parseInt(value));
1766 Conservation c = new Conservation("Group",
1767 ResidueProperties.propHash, 3, sg.getSequences(null),
1768 sg.getStartRes(), sg.getEndRes() + 1);
1771 c.verdict(false, 25); // TODO: refer to conservation percent threshold
1773 sg.cs.setConservation(c);
1776 else if (key.equalsIgnoreCase("outlineColour"))
1778 sg.setOutlineColour(new UserColourScheme(value).findColour('A'));
1780 else if (key.equalsIgnoreCase("displayBoxes"))
1782 sg.setDisplayBoxes(Boolean.valueOf(value).booleanValue());
1784 else if (key.equalsIgnoreCase("showUnconserved"))
1786 sg.setShowNonconserved(Boolean.valueOf(value).booleanValue());
1788 else if (key.equalsIgnoreCase("displayText"))
1790 sg.setDisplayText(Boolean.valueOf(value).booleanValue());
1792 else if (key.equalsIgnoreCase("colourText"))
1794 sg.setColourText(Boolean.valueOf(value).booleanValue());
1796 else if (key.equalsIgnoreCase("textCol1"))
1798 sg.textColour = new UserColourScheme(value).findColour('A');
1800 else if (key.equalsIgnoreCase("textCol2"))
1802 sg.textColour2 = new UserColourScheme(value).findColour('A');
1804 else if (key.equalsIgnoreCase("textColThreshold"))
1806 sg.thresholdTextColour = Integer.parseInt(value);
1808 else if (key.equalsIgnoreCase("idColour"))
1810 // consider warning if colour doesn't resolve to a real colour
1811 sg.setIdColour((def = new UserColourScheme(value))
1814 else if (key.equalsIgnoreCase("hide"))
1816 // see bug https://mantis.lifesci.dundee.ac.uk/view.php?id=25847
1817 sg.setHidereps(true);
1819 else if (key.equalsIgnoreCase("hidecols"))
1821 // see bug https://mantis.lifesci.dundee.ac.uk/view.php?id=25847
1822 sg.setHideCols(true);
1824 sg.recalcConservation();
1833 void setBelowAlignment(AlignmentI al, StringTokenizer st)
1836 AlignmentAnnotation aa, ala[] = al.getAlignmentAnnotation();
1840 .print("Warning - no annotation to set below for sequence associated annotation:");
1842 while (st.hasMoreTokens())
1844 token = st.nextToken();
1847 System.err.print(" " + token);
1851 for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1853 aa = al.getAlignmentAnnotation()[i];
1854 if (aa.sequenceRef == refSeq && aa.label.equals(token))
1856 aa.belowAlignment = true;
1863 System.err.print("\n");
1867 void addAlignmentDetails(AlignmentI al, StringTokenizer st)
1869 String keyValue, key, value;
1870 while (st.hasMoreTokens())
1872 keyValue = st.nextToken();
1873 key = keyValue.substring(0, keyValue.indexOf("="));
1874 value = keyValue.substring(keyValue.indexOf("=") + 1);
1875 al.setProperty(key, value);
1880 * Write annotations as a CSV file of the form 'label, value, value, ...' for
1883 * @param annotations
1884 * @return CSV file as a string.
1886 public String printCSVAnnotations(AlignmentAnnotation[] annotations)
1888 if (annotations == null)
1892 StringBuffer sp = new StringBuffer();
1893 for (int i = 0; i < annotations.length; i++)
1895 String atos = annotations[i].toString();
1899 int cp = atos.indexOf("\n", p);
1900 sp.append(annotations[i].label);
1904 sp.append(atos.substring(p, cp + 1));
1908 sp.append(atos.substring(p));
1914 return sp.toString();
1917 public String printAnnotationsForView(AlignViewportI viewport)
1919 return printAnnotations(viewport.isShowAnnotation() ? viewport
1920 .getAlignment().getAlignmentAnnotation() : null, viewport
1921 .getAlignment().getGroups(), viewport.getAlignment()
1922 .getProperties(), viewport.getColumnSelection(),
1923 viewport.getAlignment(), null);
1926 public String printAnnotationsForAlignment(AlignmentI al)
1928 return printAnnotations(al.getAlignmentAnnotation(), al.getGroups(),
1929 al.getProperties(), null, al, null);