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;
39 import jalview.structure.StructureSelectionManager;
41 import java.io.BufferedReader;
43 import java.io.FileReader;
44 import java.io.IOException;
45 import java.io.InputStreamReader;
46 import java.io.StringReader;
48 import java.util.ArrayList;
49 import java.util.BitSet;
50 import java.util.Enumeration;
51 import java.util.Hashtable;
52 import java.util.List;
54 import java.util.StringTokenizer;
55 import java.util.Vector;
57 public class AnnotationFile
59 public AnnotationFile()
65 * character used to write newlines
67 protected String newline = System.getProperty("line.separator");
70 * set new line string and reset the output buffer
74 public void setNewlineString(String nl)
80 public String getNewlineString()
89 text = new StringBuffer("JALVIEW_ANNOTATION" + newline + "# Created: "
90 + new java.util.Date() + newline + newline);
96 * convenience method for pre-2.9 annotation files which have no view, hidden
97 * columns or hidden row keywords.
102 * @return annotation file as a string.
104 public String printAnnotations(AlignmentAnnotation[] annotations,
105 List<SequenceGroup> list, Hashtable properties)
107 return printAnnotations(annotations, list, properties, null, null, null);
112 * hold all the information about a particular view definition read from or
113 * written out in an annotations file.
117 public String viewname;
119 public HiddenSequences hidseqs;
121 public ColumnSelection hiddencols;
123 public Vector visibleGroups;
125 public Hashtable hiddenRepSeqs;
127 public ViewDef(String viewname, HiddenSequences hidseqs,
128 ColumnSelection hiddencols, Hashtable hiddenRepSeqs)
130 this.viewname = viewname;
131 this.hidseqs = hidseqs;
132 this.hiddencols = hiddencols;
133 this.hiddenRepSeqs = hiddenRepSeqs;
138 * Prepare an annotation file given a set of annotations, groups, alignment
139 * properties and views.
145 * @return annotation file
147 public String printAnnotations(AlignmentAnnotation[] annotations,
148 List<SequenceGroup> list, Hashtable properties,
149 ColumnSelection cs, AlignmentI al, ViewDef view)
153 if (view.viewname != null)
155 text.append("VIEW_DEF\t" + view.viewname + "\n");
159 list = view.visibleGroups;
163 cs = view.hiddencols;
167 // add hidden rep sequences.
170 // first target - store and restore all settings for a view.
171 if (al != null && al.hasSeqrep())
173 text.append("VIEW_SETREF\t" + al.getSeqrep().getName() + "\n");
175 if (cs != null && cs.hasHiddenColumns())
177 text.append("VIEW_HIDECOLS\t");
178 List<int[]> hc = cs.getHiddenColumns();
179 boolean comma = false;
196 // TODO: allow efficient recovery of annotation data shown in several
198 if (annotations != null)
200 boolean oneColour = true;
201 AlignmentAnnotation row;
203 SequenceI refSeq = null;
204 SequenceGroup refGroup = null;
206 StringBuffer colours = new StringBuffer();
207 StringBuffer graphLine = new StringBuffer();
208 StringBuffer rowprops = new StringBuffer();
209 Hashtable<Integer, String> graphGroup = new Hashtable<Integer, String>();
210 Hashtable<Integer, Object[]> graphGroup_refs = new Hashtable<Integer, Object[]>();
211 BitSet graphGroupSeen = new BitSet();
213 java.awt.Color color;
215 for (int i = 0; i < annotations.length; i++)
217 row = annotations[i];
221 && !(row.graphGroup > -1 && graphGroupSeen
222 .get(row.graphGroup)))
230 // mark any sequence references for the row
231 writeSequence_Ref(refSeq, row.sequenceRef);
232 refSeq = row.sequenceRef;
233 // mark any group references for the row
234 writeGroup_Ref(refGroup, row.groupRef);
235 refGroup = row.groupRef;
237 boolean hasGlyphs = row.hasIcons, hasLabels = row.hasText, hasValues = row.hasScore, hasText = false;
238 // lookahead to check what the annotation row object actually contains.
239 for (int j = 0; row.annotations != null
240 && j < row.annotations.length
241 && (!hasGlyphs || !hasLabels || !hasValues); j++)
243 if (row.annotations[j] != null)
245 hasLabels |= (row.annotations[j].displayCharacter != null
246 && row.annotations[j].displayCharacter.length() > 0 && !row.annotations[j].displayCharacter
248 hasGlyphs |= (row.annotations[j].secondaryStructure != 0 && row.annotations[j].secondaryStructure != ' ');
249 hasValues |= (!Float.isNaN(row.annotations[j].value)); // NaNs can't
252 hasText |= (row.annotations[j].description != null && row.annotations[j].description
257 if (row.graph == AlignmentAnnotation.NO_GRAPH)
259 text.append("NO_GRAPH\t");
260 hasValues = false; // only secondary structure
261 // hasLabels = false; // and annotation description string.
265 if (row.graph == AlignmentAnnotation.BAR_GRAPH)
267 text.append("BAR_GRAPH\t");
268 hasGlyphs = false; // no secondary structure
271 else if (row.graph == AlignmentAnnotation.LINE_GRAPH)
273 hasGlyphs = false; // no secondary structure
274 text.append("LINE_GRAPH\t");
277 if (row.getThreshold() != null)
279 graphLine.append("GRAPHLINE\t");
280 graphLine.append(row.label);
281 graphLine.append("\t");
282 graphLine.append(row.getThreshold().value);
283 graphLine.append("\t");
284 graphLine.append(row.getThreshold().label);
285 graphLine.append("\t");
286 graphLine.append(jalview.util.Format.getHexString(row
287 .getThreshold().colour));
288 graphLine.append(newline);
291 if (row.graphGroup > -1)
293 graphGroupSeen.set(row.graphGroup);
294 Integer key = new Integer(row.graphGroup);
295 if (graphGroup.containsKey(key))
297 graphGroup.put(key, graphGroup.get(key) + "\t" + row.label);
302 graphGroup_refs.put(key, new Object[] { refSeq, refGroup });
303 graphGroup.put(key, row.label);
308 text.append(row.label + "\t");
309 if (row.description != null)
311 text.append(row.description + "\t");
313 for (int j = 0; row.annotations != null
314 && j < row.annotations.length; j++)
317 && jalview.util.Comparison.isGap(refSeq.getCharAt(j)))
322 if (row.annotations[j] != null)
325 if (hasGlyphs) // could be also hasGlyphs || ...
329 if (row.annotations[j].secondaryStructure != ' ')
331 // only write out the field if its not whitespace.
332 text.append(row.annotations[j].secondaryStructure);
338 if (!Float.isNaN(row.annotations[j].value))
340 text.append(comma + row.annotations[j].value);
344 // System.err.println("Skipping NaN - not valid value.");
345 text.append(comma + 0f);// row.annotations[j].value);
351 // TODO: labels are emitted after values for bar graphs.
352 if // empty labels are allowed, so
353 (row.annotations[j].displayCharacter != null
354 && row.annotations[j].displayCharacter.length() > 0
355 && !row.annotations[j].displayCharacter.equals(" "))
357 text.append(comma + row.annotations[j].displayCharacter);
363 if (row.annotations[j].description != null
364 && row.annotations[j].description.length() > 0
365 && !row.annotations[j].description
366 .equals(row.annotations[j].displayCharacter))
368 text.append(comma + row.annotations[j].description);
372 if (color != null && !color.equals(row.annotations[j].colour))
377 color = row.annotations[j].colour;
379 if (row.annotations[j].colour != null
380 && row.annotations[j].colour != java.awt.Color.black)
384 + jalview.util.Format
385 .getHexString(row.annotations[j].colour)
395 text.append("\t" + row.score);
398 text.append(newline);
400 if (color != null && color != java.awt.Color.black && oneColour)
402 colours.append("COLOUR\t");
403 colours.append(row.label);
404 colours.append("\t");
405 colours.append(jalview.util.Format.getHexString(color));
406 colours.append(newline);
408 if (row.scaleColLabel || row.showAllColLabels
409 || row.centreColLabels)
411 rowprops.append("ROWPROPERTIES\t");
412 rowprops.append(row.label);
413 rowprops.append("\tscaletofit=");
414 rowprops.append(row.scaleColLabel);
415 rowprops.append("\tshowalllabs=");
416 rowprops.append(row.showAllColLabels);
417 rowprops.append("\tcentrelabs=");
418 rowprops.append(row.centreColLabels);
419 rowprops.append(newline);
421 if (graphLine.length() > 0)
423 text.append(graphLine.toString());
424 graphLine.setLength(0);
428 text.append(newline);
430 text.append(colours.toString());
431 if (graphGroup.size() > 0)
433 SequenceI oldRefSeq = refSeq;
434 SequenceGroup oldRefGroup = refGroup;
435 for (Map.Entry<Integer, String> combine_statement : graphGroup
438 Object[] seqRefAndGroup = graphGroup_refs.get(combine_statement
441 writeSequence_Ref(refSeq, (SequenceI) seqRefAndGroup[0]);
442 refSeq = (SequenceI) seqRefAndGroup[0];
444 writeGroup_Ref(refGroup, (SequenceGroup) seqRefAndGroup[1]);
445 refGroup = (SequenceGroup) seqRefAndGroup[1];
446 text.append("COMBINE\t");
447 text.append(combine_statement.getValue());
448 text.append(newline);
450 writeSequence_Ref(refSeq, oldRefSeq);
453 writeGroup_Ref(refGroup, oldRefGroup);
454 refGroup = oldRefGroup;
456 text.append(rowprops.toString());
464 if (properties != null)
466 text.append(newline);
467 text.append(newline);
468 text.append("ALIGNMENT");
469 Enumeration en = properties.keys();
470 while (en.hasMoreElements())
472 String key = en.nextElement().toString();
476 text.append(properties.get(key));
478 // TODO: output alignment visualization settings here if required
479 // iterate through one or more views, defining, marking columns and rows
480 // as visible/hidden, and emmitting view properties.
481 // View specific annotation is
484 return text.toString();
487 private Object writeGroup_Ref(SequenceGroup refGroup,
488 SequenceGroup next_refGroup)
490 if (next_refGroup == null)
493 if (refGroup != null)
495 text.append(newline);
496 text.append("GROUP_REF\t");
497 text.append("ALIGNMENT");
498 text.append(newline);
504 if (refGroup == null || refGroup != next_refGroup)
506 text.append(newline);
507 text.append("GROUP_REF\t");
508 text.append(next_refGroup.getName());
509 text.append(newline);
516 private boolean writeSequence_Ref(SequenceI refSeq, SequenceI next_refSeq)
519 if (next_refSeq == null)
523 text.append(newline);
524 text.append("SEQUENCE_REF\t");
525 text.append("ALIGNMENT");
526 text.append(newline);
532 if (refSeq == null || refSeq != next_refSeq)
534 text.append(newline);
535 text.append("SEQUENCE_REF\t");
536 text.append(next_refSeq.getName());
537 text.append(newline);
544 public void printGroups(List<SequenceGroup> list)
546 SequenceI seqrep = null;
547 for (SequenceGroup sg : list)
551 text.append("SEQUENCE_GROUP\t" + sg.getName() + "\t"
552 + (sg.getStartRes() + 1) + "\t" + (sg.getEndRes() + 1)
558 seqrep = sg.getSeqrep();
559 text.append("SEQUENCE_REF\t");
560 text.append(seqrep.getName());
561 text.append(newline);
562 text.append("SEQUENCE_GROUP\t");
563 text.append(sg.getName());
565 text.append((seqrep.findPosition(sg.getStartRes())));
567 text.append((seqrep.findPosition(sg.getEndRes())));
571 for (int s = 0; s < sg.getSize(); s++)
573 text.append(sg.getSequenceAt(s).getName());
576 text.append(newline);
577 text.append("PROPERTIES\t");
578 text.append(sg.getName());
581 if (sg.getDescription() != null)
583 text.append("description=");
584 text.append(sg.getDescription());
589 text.append("colour=");
590 text.append(ColourSchemeProperty.getColourName(sg.cs));
592 if (sg.cs.getThreshold() != 0)
594 text.append("pidThreshold=");
595 text.append(sg.cs.getThreshold());
597 if (sg.cs.conservationApplied())
599 text.append("consThreshold=");
600 text.append(sg.cs.getConservationInc());
604 text.append("outlineColour=");
605 text.append(jalview.util.Format.getHexString(sg.getOutlineColour()));
608 text.append("displayBoxes=");
609 text.append(sg.getDisplayBoxes());
611 text.append("displayText=");
612 text.append(sg.getDisplayText());
614 text.append("colourText=");
615 text.append(sg.getColourText());
617 text.append("showUnconserved=");
618 text.append(sg.getShowNonconserved());
620 if (sg.textColour != java.awt.Color.black)
622 text.append("textCol1=");
623 text.append(jalview.util.Format.getHexString(sg.textColour));
626 if (sg.textColour2 != java.awt.Color.white)
628 text.append("textCol2=");
629 text.append(jalview.util.Format.getHexString(sg.textColour2));
632 if (sg.thresholdTextColour != 0)
634 text.append("textColThreshold=");
635 text.append(sg.thresholdTextColour);
638 if (sg.idColour != null)
640 text.append("idColour=");
641 text.append(jalview.util.Format.getHexString(sg.idColour));
646 text.append("hide=true\t");
650 text.append("hidecols=true\t");
654 // terminate the last line and clear the sequence ref for the group
655 text.append(newline);
656 text.append("SEQUENCE_REF");
658 text.append(newline);
659 text.append(newline);
664 SequenceI refSeq = null;
666 String refSeqId = null;
668 public boolean annotateAlignmentView(AlignViewportI viewport,
669 String file, String protocol)
671 ColumnSelection colSel = viewport.getColumnSelection();
674 colSel = new ColumnSelection();
676 boolean rslt = readAnnotationFile(viewport.getAlignment(), colSel,
678 if (rslt && (colSel.hasSelectedColumns() || colSel.hasHiddenColumns()))
680 viewport.setColumnSelection(colSel);
686 public boolean readAnnotationFile(AlignmentI al, String file,
689 return readAnnotationFile(al, null, file, protocol);
692 public boolean readAnnotationFile(AlignmentI al, ColumnSelection colSel,
693 String file, String protocol)
696 BufferedReader in = null;
699 if (protocol.equals(AppletFormatAdapter.FILE))
701 in = new BufferedReader(new FileReader(file));
702 baseUri = new File(file).getParent();
712 else if (protocol.equals(AppletFormatAdapter.URL))
714 URL url = new URL(file);
715 in = new BufferedReader(new InputStreamReader(url.openStream()));
716 String bs = url.toExternalForm();
717 baseUri = bs.substring(0, bs.indexOf(url.getHost())
718 + url.getHost().length());
719 baseUri += url.toURI().getPath();
720 if (baseUri.lastIndexOf("/") > -1)
722 baseUri = baseUri.substring(0, baseUri.lastIndexOf("/")) + "/";
725 else if (protocol.equals(AppletFormatAdapter.PASTE))
727 in = new BufferedReader(new StringReader(file));
728 // TODO - support mimencoded PDBs for a paste.. ?
731 else if (protocol.equals(AppletFormatAdapter.CLASSLOADER))
733 java.io.InputStream is = getClass().getResourceAsStream("/" + file);
736 in = new BufferedReader(new java.io.InputStreamReader(is));
737 // TODO: this probably doesn't work for classloader - needs a test
738 baseUri = new File("/" + file).getParent() + "/";
743 return parseAnnotationFrom(al, colSel, in);
746 } catch (Exception ex)
748 ex.printStackTrace();
749 System.out.println("Problem reading annotation file: " + ex);
752 System.out.println("Last read line " + nlinesread + ": '"
753 + lastread + "' (first 80 chars) ...");
762 String lastread = "";
765 * used for resolving absolute references to resources relative to
766 * annotationFile location
770 private static String GRAPHLINE = "GRAPHLINE", COMBINE = "COMBINE",
771 STRUCTMODEL = "STRUCTMODEL";
773 public boolean parseAnnotationFrom(AlignmentI al, ColumnSelection colSel,
774 BufferedReader in) throws Exception
777 ArrayList<Object[]> combineAnnotation_calls = new ArrayList<Object[]>();
778 ArrayList<Object[]> deferredAnnotation_calls = new ArrayList<Object[]>();
779 boolean modified = false;
780 String groupRef = null;
781 Hashtable groupRefRows = new Hashtable();
783 Hashtable autoAnnots = new Hashtable();
785 String line, label, description, token;
786 int graphStyle, index;
788 int existingAnnotations = 0;
789 // when true - will add new rows regardless of whether they are duplicate
790 // auto-annotation like consensus or conservation graphs
791 boolean overrideAutoAnnot = false;
792 if (al.getAlignmentAnnotation() != null)
794 existingAnnotations = al.getAlignmentAnnotation().length;
795 if (existingAnnotations > 0)
797 AlignmentAnnotation[] aa = al.getAlignmentAnnotation();
798 for (int aai = 0; aai < aa.length; aai++)
800 if (aa[aai].autoCalculated)
802 // make a note of the name and description
804 autoAnnotsKey(aa[aai], aa[aai].sequenceRef,
805 (aa[aai].groupRef == null ? null
806 : aa[aai].groupRef.getName())),
813 int alWidth = al.getWidth();
816 Annotation[] annotations;
817 AlignmentAnnotation annotation = null;
819 // First confirm this is an Annotation file
820 boolean jvAnnotationFile = false;
821 while ((line = in.readLine()) != null)
824 lastread = new String(line);
825 if (line.indexOf("#") == 0)
830 if (line.indexOf("JALVIEW_ANNOTATION") > -1)
832 jvAnnotationFile = true;
837 if (!jvAnnotationFile)
843 while ((line = in.readLine()) != null)
846 lastread = new String(line);
847 if (line.indexOf("#") == 0
848 || line.indexOf("JALVIEW_ANNOTATION") > -1
849 || line.length() == 0)
854 st = new StringTokenizer(line, "\t");
855 token = st.nextToken();
856 if (token.equalsIgnoreCase("COLOUR"))
858 // TODO: use graduated colour def'n here too
859 colourAnnotations(al, st.nextToken(), st.nextToken());
864 else if (token.equalsIgnoreCase(COMBINE))
866 // keep a record of current state and resolve groupRef at end
867 combineAnnotation_calls
868 .add(new Object[] { st, refSeq, groupRef });
872 else if (token.equalsIgnoreCase("ROWPROPERTIES"))
874 addRowProperties(al, st);
878 else if (token.equalsIgnoreCase(GRAPHLINE))
881 deferredAnnotation_calls.add(new Object[] { GRAPHLINE, st,
887 else if (token.equalsIgnoreCase("SEQUENCE_REF"))
889 if (st.hasMoreTokens())
891 refSeq = al.findName(refSeqId = st.nextToken());
898 refSeqIndex = Integer.parseInt(st.nextToken());
903 .println("WARNING: SEQUENCE_REF index must be > 0 in AnnotationFile");
905 } catch (Exception ex)
917 else if (token.equalsIgnoreCase("GROUP_REF"))
919 // Group references could be forward or backwards, so they are
920 // resolved after the whole file is read in
922 if (st.hasMoreTokens())
924 groupRef = st.nextToken();
925 if (groupRef.length() < 1)
927 groupRef = null; // empty string
931 if (groupRefRows.get(groupRef) == null)
933 groupRefRows.put(groupRef, new Vector());
939 else if (token.equalsIgnoreCase("SEQUENCE_GROUP"))
946 else if (token.equalsIgnoreCase("PROPERTIES"))
948 addProperties(al, st);
953 else if (token.equalsIgnoreCase("BELOW_ALIGNMENT"))
955 setBelowAlignment(al, st);
959 else if (token.equalsIgnoreCase("ALIGNMENT"))
961 addAlignmentDetails(al, st);
965 // else if (token.equalsIgnoreCase("VIEW_DEF"))
967 // addOrSetView(al,st);
971 else if (token.equalsIgnoreCase("VIEW_SETREF"))
975 al.setSeqrep(refSeq);
980 else if (token.equalsIgnoreCase("VIEW_HIDECOLS"))
982 if (st.hasMoreTokens())
986 colSel = new ColumnSelection();
988 parseHideCols(colSel, st.nextToken());
993 else if (token.equalsIgnoreCase("HIDE_INSERTIONS"))
995 SequenceI sr = refSeq == null ? al.getSeqrep() : refSeq;
998 sr = al.getSequenceAt(0);
1005 .println("Cannot process HIDE_INSERTIONS without an alignment view: Ignoring line: "
1010 // consider deferring this till after the file has been parsed ?
1011 colSel.hideInsertionsFor(sr);
1017 else if (token.equalsIgnoreCase(STRUCTMODEL))
1019 boolean failedtoadd = true;
1021 // STRUCTMODEL <QUERYID> <TemplateID> <URL to model> <URL to
1023 if (st.hasMoreTokens()) {
1024 refSeq = al.findName(refSeqId = st.nextToken());
1027 System.err.println("Couldn't locate " + refSeqId
1028 + " in the alignment for STRUCTMODEL");
1033 String tempId = st.nextToken();
1034 String urlToModel = st.nextToken();
1035 String urlToPairwise = st.hasMoreTokens() ? st.nextToken()
1037 if (add_structmodel(al, refSeq, tempId, urlToModel,
1040 failedtoadd = false;
1047 .println("Need <QueryId> <TemplateId> <URL to Model> [<URL to pairwise alignment>] as tab separated fields after "
1054 // Parse out the annotation row
1055 graphStyle = AlignmentAnnotation.getGraphValueFromString(token);
1056 label = st.nextToken();
1059 annotations = new Annotation[alWidth];
1061 float score = Float.NaN;
1063 if (st.hasMoreTokens())
1065 line = st.nextToken();
1067 if (line.indexOf("|") == -1)
1070 if (st.hasMoreTokens())
1072 line = st.nextToken();
1076 if (st.hasMoreTokens())
1078 // This must be the score
1079 score = Float.valueOf(st.nextToken()).floatValue();
1082 st = new StringTokenizer(line, "|", true);
1084 boolean emptyColumn = true;
1085 boolean onlyOneElement = (st.countTokens() == 1);
1087 while (st.hasMoreElements() && index < alWidth)
1089 token = st.nextToken().trim();
1095 score = Float.valueOf(token).floatValue();
1097 } catch (NumberFormatException ex)
1102 if (token.equals("|"))
1113 annotations[index++] = parseAnnotation(token, graphStyle);
1114 emptyColumn = false;
1120 annotation = new AlignmentAnnotation(label, description,
1121 (index == 0) ? null : annotations, 0, 0, graphStyle);
1123 annotation.score = score;
1124 if (!overrideAutoAnnot
1125 && autoAnnots.containsKey(autoAnnotsKey(annotation, refSeq,
1128 // skip - we've already got an automatic annotation of this type.
1131 // otherwise add it!
1135 annotation.belowAlignment = false;
1136 // make a copy of refSeq so we can find other matches in the alignment
1137 SequenceI referedSeq = refSeq;
1140 // copy before we do any mapping business.
1141 // TODO: verify that undo/redo with 1:many sequence associated
1142 // annotations can be undone correctly
1143 AlignmentAnnotation ann = new AlignmentAnnotation(annotation);
1145 .createSequenceMapping(referedSeq, refSeqIndex, false);
1146 annotation.adjustForAlignment();
1147 referedSeq.addAlignmentAnnotation(annotation);
1148 al.addAnnotation(annotation);
1149 al.setAnnotationIndex(annotation,
1150 al.getAlignmentAnnotation().length
1151 - existingAnnotations - 1);
1152 if (groupRef != null)
1154 ((Vector) groupRefRows.get(groupRef)).addElement(annotation);
1156 // and recover our virgin copy to use again if necessary.
1159 } while (refSeqId != null
1160 && (referedSeq = al.findName(referedSeq, refSeqId, true)) != null);
1164 al.addAnnotation(annotation);
1165 al.setAnnotationIndex(annotation,
1166 al.getAlignmentAnnotation().length - existingAnnotations
1168 if (groupRef != null)
1170 ((Vector) groupRefRows.get(groupRef)).addElement(annotation);
1173 // and set modification flag
1176 // Resolve the groupRefs
1177 Hashtable<String, SequenceGroup> groupRefLookup = new Hashtable<String, SequenceGroup>();
1178 Enumeration en = groupRefRows.keys();
1180 while (en.hasMoreElements())
1182 groupRef = (String) en.nextElement();
1183 boolean matched = false;
1184 // Resolve group: TODO: add a getGroupByName method to alignments
1185 for (SequenceGroup theGroup : al.getGroups())
1187 if (theGroup.getName().equals(groupRef))
1191 // TODO: specify and implement duplication of alignment annotation
1192 // for multiple group references.
1194 .println("Ignoring 1:many group reference mappings for group name '"
1200 Vector rowset = (Vector) groupRefRows.get(groupRef);
1201 groupRefLookup.put(groupRef, theGroup);
1202 if (rowset != null && rowset.size() > 0)
1204 AlignmentAnnotation alan = null;
1205 for (int elm = 0, elmSize = rowset.size(); elm < elmSize; elm++)
1207 alan = (AlignmentAnnotation) rowset.elementAt(elm);
1208 alan.groupRef = theGroup;
1214 ((Vector) groupRefRows.get(groupRef)).removeAllElements();
1216 // process any deferred attribute settings for each context
1217 for (Object[] _deferred_args : deferredAnnotation_calls)
1219 if (_deferred_args[0] == GRAPHLINE)
1222 (StringTokenizer) _deferred_args[1], // st
1223 (SequenceI) _deferred_args[2], // refSeq
1224 (_deferred_args[3] == null) ? null : groupRefLookup
1225 .get(_deferred_args[3]) // the reference
1231 // finally, combine all the annotation rows within each context.
1233 * number of combine statements in this annotation file. Used to create
1234 * new groups for combined annotation graphs without disturbing existing
1237 int combinecount = 0;
1238 for (Object[] _combine_args : combineAnnotation_calls)
1240 combineAnnotations(al,
1242 (StringTokenizer) _combine_args[0], // st
1243 (SequenceI) _combine_args[1], // refSeq
1244 (_combine_args[2] == null) ? null : groupRefLookup
1245 .get(_combine_args[2]) // the reference group,
1254 * resolve a structural model and generate and add an alignment sequence for
1260 * @param urlToPairwise
1261 * @return true if model and sequence was added
1263 private boolean add_structmodel(AlignmentI al, SequenceI refSeq2, String tempId,
1264 String urlToModel, String urlToPairwise)
1266 String warningMessage = null, modelPath = null, modelProt = null, aliPath = null, aliProt = null;
1267 boolean added = false;
1269 // locate tempId. if it exists, will need to merge, otherwise:
1270 SequenceI templateSeq = al.findName(tempId);
1271 // 1. load urlToModel
1272 modelPath = resolveAbsolute(urlToModel);
1273 modelProt = AppletFormatAdapter.checkProtocol(modelPath);
1274 // need to transfer to local temp file ?
1275 PDBEntry modelpe = new PDBEntry(tempId, null, Type.FILE, modelPath);
1276 PDBEntry templpe = new PDBEntry(tempId, null, Type.FILE, modelPath);
1277 refSeq2.addPDBId(modelpe);
1278 aliPath = resolveAbsolute(urlToPairwise);
1279 aliProt = AppletFormatAdapter.checkProtocol(aliPath);
1280 // 2. load urlToPairwise
1281 AlignmentI pwa = new AppletFormatAdapter().readFile(aliPath, aliProt,
1283 SequenceI qPw = null, tPw = null;
1286 // resolve query/template sequences in provided alignment
1287 qPw = pwa.findName(refSeqId);
1288 tPw = pwa.findName(tempId);
1291 // (qPw != null && tPw != null)
1294 // refalQ vvva--addrvvvtttddd
1295 // refalT ---aaaa---sss---ddd
1296 // profalQ ---v-v-v-a.-.-a---dd--r--vvvtt--td--dd
1297 // profalT ---.-.-.-aa-a-a---..--.--sss..--.d--dd
1298 // Pragmatic solution here:
1299 // Map templpe onto refalT only where refalT and refalQ are both
1302 // columns for start..end in refSeq2
1303 int[] gapMap = refSeq2.gapMap();
1304 // insert gaps in tPw
1305 int curi = 0, width = refSeq2.getLength();
1310 // assume 1:1 - so synthesise sequences to use to construct mapping
1311 StructureFile pdbf = StructureSelectionManager
1312 .getStructureSelectionManager().setMapping(false,
1313 new SequenceI[] { refSeq2.getDatasetSequence() },
1314 null, modelPath, modelProt);
1315 refSeq2.getDatasetSequence().addPDBId(modelpe);
1316 if (templateSeq == null && tPw != null)
1318 tPw.createDatasetSequence();
1319 tPw.getDatasetSequence().addPDBId(templpe); // needs to set mapping based on model yet...
1320 al.addSequence(tPw);
1324 // 3. pad/insert gaps in urlToPairwise according to gaps already present in
1326 // 4. add padded tempId sequence to alignment
1327 // 4. associate urlToModel with refSeq2 based on position map provided by
1329 // 5. associate urlToModel with tempId based on position map provided by
1331 // start a thread to load urlToModel and process/annotate sequences.
1332 } catch (IOException x)
1334 warningMessage = x.toString();
1336 if (warningMessage !=null)
1338 System.err.println("Warnings whilst processing STRUCTMODEL: "+warningMessage);
1344 private String resolveAbsolute(String relURI)
1346 if (relURI.indexOf(":/") > -1 || relURI.startsWith("/")
1347 || "".equals(baseUri) || relURI.startsWith(baseUri))
1351 return baseUri + relURI;
1354 private void parseHideCols(ColumnSelection colSel, String nextToken)
1356 StringTokenizer inval = new StringTokenizer(nextToken, ",");
1357 while (inval.hasMoreTokens())
1359 String range = inval.nextToken().trim();
1360 int from, to = range.indexOf("-");
1363 from = to = Integer.parseInt(range);
1366 colSel.hideColumns(from, to);
1371 from = Integer.parseInt(range.substring(0, to));
1372 if (to < range.length() - 1)
1374 to = Integer.parseInt(range.substring(to + 1));
1380 if (from > 0 && to >= from)
1382 colSel.hideColumns(from, to);
1388 private Object autoAnnotsKey(AlignmentAnnotation annotation,
1389 SequenceI refSeq, String groupRef)
1391 return annotation.graph + "\t" + annotation.label + "\t"
1392 + annotation.description + "\t"
1393 + (refSeq != null ? refSeq.getDisplayId(true) : "");
1396 Annotation parseAnnotation(String string, int graphStyle)
1398 boolean hasSymbols = (graphStyle == AlignmentAnnotation.NO_GRAPH); // don't
1407 String desc = null, displayChar = null;
1408 char ss = ' '; // secondaryStructure
1410 boolean parsedValue = false, dcset = false;
1413 java.awt.Color colour = null;
1414 int i = string.indexOf("[");
1415 int j = string.indexOf("]");
1416 if (i > -1 && j > -1)
1418 UserColourScheme ucs = new UserColourScheme();
1420 colour = ucs.getColourFromString(string.substring(i + 1, j));
1421 if (i > 0 && string.charAt(i - 1) == ',')
1423 // clip the preceding comma as well
1426 string = string.substring(0, i) + string.substring(j + 1);
1429 StringTokenizer st = new StringTokenizer(string, ",", true);
1431 boolean seenContent = false;
1433 while (st.hasMoreTokens())
1436 token = st.nextToken().trim();
1437 if (token.equals(","))
1439 if (!seenContent && parsedValue && !dcset)
1441 // allow the value below the bar/line to be empty
1445 seenContent = false;
1457 displayChar = token;
1459 value = new Float(token).floatValue();
1462 } catch (NumberFormatException ex)
1468 if (token.length() == 1)
1470 displayChar = token;
1474 && (token.length() == 1 && "()<>[]{}AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz"
1477 // Either this character represents a helix or sheet
1478 // or an integer which can be displayed
1479 ss = token.charAt(0);
1480 if (displayChar.equals(token.substring(0, 1)))
1485 else if (desc == null || (parsedValue && pass > 2))
1491 // if (!dcset && string.charAt(string.length() - 1) == ',')
1493 // displayChar = " "; // empty display char symbol.
1495 if (displayChar != null && desc != null && desc.length() == 1)
1497 if (displayChar.length() > 1)
1499 // switch desc and displayChar - legacy support
1500 String tmp = displayChar;
1506 if (displayChar.equals(desc))
1508 // duplicate label - hangover from the 'robust parser' above
1513 Annotation anot = new Annotation(displayChar, desc, ss, value);
1515 anot.colour = colour;
1520 void colourAnnotations(AlignmentI al, String label, String colour)
1522 UserColourScheme ucs = new UserColourScheme(colour);
1523 Annotation[] annotations;
1524 for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1526 if (al.getAlignmentAnnotation()[i].label.equalsIgnoreCase(label))
1528 annotations = al.getAlignmentAnnotation()[i].annotations;
1529 for (int j = 0; j < annotations.length; j++)
1531 if (annotations[j] != null)
1533 annotations[j].colour = ucs.findColour('A');
1540 void combineAnnotations(AlignmentI al, int combineCount,
1541 StringTokenizer st, SequenceI seqRef, SequenceGroup groupRef)
1543 String group = st.nextToken();
1544 // First make sure we are not overwriting the graphIndex
1546 if (al.getAlignmentAnnotation() != null)
1548 for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1550 AlignmentAnnotation aa = al.getAlignmentAnnotation()[i];
1552 if (aa.graphGroup > graphGroup)
1554 // try to number graphGroups in order of occurence.
1555 graphGroup = aa.graphGroup + 1;
1557 if (aa.sequenceRef == seqRef && aa.groupRef == groupRef
1558 && aa.label.equalsIgnoreCase(group))
1560 if (aa.graphGroup > -1)
1562 graphGroup = aa.graphGroup;
1566 if (graphGroup <= combineCount)
1568 graphGroup = combineCount + 1;
1570 aa.graphGroup = graphGroup;
1576 // Now update groups
1577 while (st.hasMoreTokens())
1579 group = st.nextToken();
1580 for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1582 AlignmentAnnotation aa = al.getAlignmentAnnotation()[i];
1583 if (aa.sequenceRef == seqRef && aa.groupRef == groupRef
1584 && aa.label.equalsIgnoreCase(group))
1586 aa.graphGroup = graphGroup;
1595 .println("Couldn't combine annotations. None are added to alignment yet!");
1599 void addLine(AlignmentI al, StringTokenizer st, SequenceI seqRef,
1600 SequenceGroup groupRef)
1602 String group = st.nextToken();
1603 AlignmentAnnotation annotation = null, alannot[] = al
1604 .getAlignmentAnnotation();
1605 float value = new Float(st.nextToken()).floatValue();
1606 String label = st.hasMoreTokens() ? st.nextToken() : null;
1607 java.awt.Color colour = null;
1608 if (st.hasMoreTokens())
1610 UserColourScheme ucs = new UserColourScheme(st.nextToken());
1611 colour = ucs.findColour('A');
1613 if (alannot != null)
1615 for (int i = 0; i < alannot.length; i++)
1617 if (alannot[i].label.equalsIgnoreCase(group)
1618 && (seqRef == null || alannot[i].sequenceRef == seqRef)
1619 && (groupRef == null || alannot[i].groupRef == groupRef))
1621 alannot[i].setThreshold(new GraphLine(value, label, colour));
1625 if (annotation == null)
1631 void addGroup(AlignmentI al, StringTokenizer st)
1633 SequenceGroup sg = new SequenceGroup();
1634 sg.setName(st.nextToken());
1638 rng = st.nextToken();
1639 if (rng.length() > 0 && !rng.startsWith("*"))
1641 sg.setStartRes(Integer.parseInt(rng) - 1);
1647 rng = st.nextToken();
1648 if (rng.length() > 0 && !rng.startsWith("*"))
1650 sg.setEndRes(Integer.parseInt(rng) - 1);
1654 sg.setEndRes(al.getWidth() - 1);
1656 } catch (Exception e)
1659 .println("Couldn't parse Group Start or End Field as '*' or a valid column or sequence index: '"
1660 + rng + "' - assuming alignment width for group.");
1661 // assume group is full width
1663 sg.setEndRes(al.getWidth() - 1);
1666 String index = st.nextToken();
1667 if (index.equals("-1"))
1669 while (st.hasMoreElements())
1671 sg.addSequence(al.findName(st.nextToken()), false);
1676 StringTokenizer st2 = new StringTokenizer(index, ",");
1678 while (st2.hasMoreTokens())
1680 String tmp = st2.nextToken();
1681 if (tmp.equals("*"))
1683 for (int i = 0; i < al.getHeight(); i++)
1685 sg.addSequence(al.getSequenceAt(i), false);
1688 else if (tmp.indexOf("-") >= 0)
1690 StringTokenizer st3 = new StringTokenizer(tmp, "-");
1692 int start = (Integer.parseInt(st3.nextToken()));
1693 int end = (Integer.parseInt(st3.nextToken()));
1697 for (int i = start; i <= end; i++)
1699 sg.addSequence(al.getSequenceAt(i - 1), false);
1705 sg.addSequence(al.getSequenceAt(Integer.parseInt(tmp) - 1), false);
1712 sg.setStartRes(refSeq.findIndex(sg.getStartRes() + 1) - 1);
1713 sg.setEndRes(refSeq.findIndex(sg.getEndRes() + 1) - 1);
1714 sg.setSeqrep(refSeq);
1717 if (sg.getSize() > 0)
1723 void addRowProperties(AlignmentI al, StringTokenizer st)
1725 String label = st.nextToken(), keyValue, key, value;
1726 boolean scaletofit = false, centerlab = false, showalllabs = false;
1727 while (st.hasMoreTokens())
1729 keyValue = st.nextToken();
1730 key = keyValue.substring(0, keyValue.indexOf("="));
1731 value = keyValue.substring(keyValue.indexOf("=") + 1);
1732 if (key.equalsIgnoreCase("scaletofit"))
1734 scaletofit = Boolean.valueOf(value).booleanValue();
1736 if (key.equalsIgnoreCase("showalllabs"))
1738 showalllabs = Boolean.valueOf(value).booleanValue();
1740 if (key.equalsIgnoreCase("centrelabs"))
1742 centerlab = Boolean.valueOf(value).booleanValue();
1744 AlignmentAnnotation[] alr = al.getAlignmentAnnotation();
1747 for (int i = 0; i < alr.length; i++)
1749 if (alr[i].label.equalsIgnoreCase(label))
1751 alr[i].centreColLabels = centerlab;
1752 alr[i].scaleColLabel = scaletofit;
1753 alr[i].showAllColLabels = showalllabs;
1760 void addProperties(AlignmentI al, StringTokenizer st)
1763 // So far we have only added groups to the annotationHash,
1764 // the idea is in the future properties can be added to
1765 // alignments, other annotations etc
1766 if (al.getGroups() == null)
1771 String name = st.nextToken();
1772 SequenceGroup sg = null;
1773 for (SequenceGroup _sg : al.getGroups())
1775 if ((sg = _sg).getName().equals(name))
1787 String keyValue, key, value;
1788 ColourSchemeI def = sg.cs;
1790 while (st.hasMoreTokens())
1792 keyValue = st.nextToken();
1793 key = keyValue.substring(0, keyValue.indexOf("="));
1794 value = keyValue.substring(keyValue.indexOf("=") + 1);
1796 if (key.equalsIgnoreCase("description"))
1798 sg.setDescription(value);
1800 else if (key.equalsIgnoreCase("colour"))
1802 sg.cs = ColourSchemeProperty.getColour(al, value);
1804 else if (key.equalsIgnoreCase("pidThreshold"))
1806 sg.cs.setThreshold(Integer.parseInt(value), true);
1809 else if (key.equalsIgnoreCase("consThreshold"))
1811 sg.cs.setConservationInc(Integer.parseInt(value));
1812 Conservation c = new Conservation("Group",
1813 ResidueProperties.propHash, 3, sg.getSequences(null),
1814 sg.getStartRes(), sg.getEndRes() + 1);
1817 c.verdict(false, 25); // TODO: refer to conservation percent threshold
1819 sg.cs.setConservation(c);
1822 else if (key.equalsIgnoreCase("outlineColour"))
1824 sg.setOutlineColour(new UserColourScheme(value).findColour('A'));
1826 else if (key.equalsIgnoreCase("displayBoxes"))
1828 sg.setDisplayBoxes(Boolean.valueOf(value).booleanValue());
1830 else if (key.equalsIgnoreCase("showUnconserved"))
1832 sg.setShowNonconserved(Boolean.valueOf(value).booleanValue());
1834 else if (key.equalsIgnoreCase("displayText"))
1836 sg.setDisplayText(Boolean.valueOf(value).booleanValue());
1838 else if (key.equalsIgnoreCase("colourText"))
1840 sg.setColourText(Boolean.valueOf(value).booleanValue());
1842 else if (key.equalsIgnoreCase("textCol1"))
1844 sg.textColour = new UserColourScheme(value).findColour('A');
1846 else if (key.equalsIgnoreCase("textCol2"))
1848 sg.textColour2 = new UserColourScheme(value).findColour('A');
1850 else if (key.equalsIgnoreCase("textColThreshold"))
1852 sg.thresholdTextColour = Integer.parseInt(value);
1854 else if (key.equalsIgnoreCase("idColour"))
1856 // consider warning if colour doesn't resolve to a real colour
1857 sg.setIdColour((def = new UserColourScheme(value))
1860 else if (key.equalsIgnoreCase("hide"))
1862 // see bug https://mantis.lifesci.dundee.ac.uk/view.php?id=25847
1863 sg.setHidereps(true);
1865 else if (key.equalsIgnoreCase("hidecols"))
1867 // see bug https://mantis.lifesci.dundee.ac.uk/view.php?id=25847
1868 sg.setHideCols(true);
1870 sg.recalcConservation();
1879 void setBelowAlignment(AlignmentI al, StringTokenizer st)
1882 AlignmentAnnotation aa, ala[] = al.getAlignmentAnnotation();
1886 .print("Warning - no annotation to set below for sequence associated annotation:");
1888 while (st.hasMoreTokens())
1890 token = st.nextToken();
1893 System.err.print(" " + token);
1897 for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1899 aa = al.getAlignmentAnnotation()[i];
1900 if (aa.sequenceRef == refSeq && aa.label.equals(token))
1902 aa.belowAlignment = true;
1909 System.err.print("\n");
1913 void addAlignmentDetails(AlignmentI al, StringTokenizer st)
1915 String keyValue, key, value;
1916 while (st.hasMoreTokens())
1918 keyValue = st.nextToken();
1919 key = keyValue.substring(0, keyValue.indexOf("="));
1920 value = keyValue.substring(keyValue.indexOf("=") + 1);
1921 al.setProperty(key, value);
1926 * Write annotations as a CSV file of the form 'label, value, value, ...' for
1929 * @param annotations
1930 * @return CSV file as a string.
1932 public String printCSVAnnotations(AlignmentAnnotation[] annotations)
1934 if (annotations == null)
1938 StringBuffer sp = new StringBuffer();
1939 for (int i = 0; i < annotations.length; i++)
1941 String atos = annotations[i].toString();
1945 int cp = atos.indexOf("\n", p);
1946 sp.append(annotations[i].label);
1950 sp.append(atos.substring(p, cp + 1));
1954 sp.append(atos.substring(p));
1960 return sp.toString();
1963 public String printAnnotationsForView(AlignViewportI viewport)
1965 return printAnnotations(viewport.isShowAnnotation() ? viewport
1966 .getAlignment().getAlignmentAnnotation() : null, viewport
1967 .getAlignment().getGroups(), viewport.getAlignment()
1968 .getProperties(), viewport.getColumnSelection(),
1969 viewport.getAlignment(), null);
1972 public String printAnnotationsForAlignment(AlignmentI al)
1974 return printAnnotations(al.getAlignmentAnnotation(), al.getGroups(),
1975 al.getProperties(), null, al, null);