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.DynamicData;
30 import jalview.datamodel.DynamicData.DataType;
31 import jalview.datamodel.GraphLine;
32 import jalview.datamodel.HiddenSequences;
33 import jalview.datamodel.PDBEntry;
34 import jalview.datamodel.PDBEntry.Type;
35 import jalview.datamodel.SequenceGroup;
36 import jalview.datamodel.SequenceI;
37 import jalview.schemes.ColourSchemeI;
38 import jalview.schemes.ColourSchemeProperty;
39 import jalview.structure.StructureSelectionManager;
40 import jalview.util.ColorUtils;
42 import java.awt.Color;
43 import java.io.BufferedReader;
45 import java.io.FileReader;
46 import java.io.InputStreamReader;
47 import java.io.StringReader;
49 import java.util.ArrayList;
50 import java.util.BitSet;
51 import java.util.Enumeration;
52 import java.util.Hashtable;
53 import java.util.List;
55 import java.util.StringTokenizer;
56 import java.util.Vector;
58 public class AnnotationFile
62 SequenceI refSeq = null;
64 String refSeqId = null;
66 String[] StructModelHeader = null;
73 * used for resolving absolute references to resources relative to
74 * annotationFile location
78 private static String GRAPHLINE = "GRAPHLINE", COMBINE = "COMBINE",
79 STRUCTMODEL = "STRUCTMODEL",
80 HEADER_STRUCT_MODEL = "HEADER_STRUCT_MODEL";
82 public AnnotationFile()
88 * character used to write newlines
90 protected String newline = System.getProperty("line.separator");
93 * set new line string and reset the output buffer
97 public void setNewlineString(String nl)
103 public String getNewlineString()
111 text = new StringBuffer("JALVIEW_ANNOTATION" + newline + "# Created: "
112 + new java.util.Date() + newline + newline);
118 * convenience method for pre-2.9 annotation files which have no view, hidden
119 * columns or hidden row keywords.
124 * @return annotation file as a string.
126 public String printAnnotations(AlignmentAnnotation[] annotations,
127 List<SequenceGroup> list, Hashtable properties)
129 return printAnnotations(annotations, list, properties, null, null, null);
134 * hold all the information about a particular view definition read from or
135 * written out in an annotations file.
139 public String viewname;
141 public HiddenSequences hidseqs;
143 public ColumnSelection hiddencols;
145 public Vector visibleGroups;
147 public Hashtable hiddenRepSeqs;
149 public ViewDef(String viewname, HiddenSequences hidseqs,
150 ColumnSelection hiddencols, Hashtable hiddenRepSeqs)
152 this.viewname = viewname;
153 this.hidseqs = hidseqs;
154 this.hiddencols = hiddencols;
155 this.hiddenRepSeqs = hiddenRepSeqs;
160 * Prepare an annotation file given a set of annotations, groups, alignment
161 * properties and views.
167 * @return annotation file
169 public String printAnnotations(AlignmentAnnotation[] annotations,
170 List<SequenceGroup> list, Hashtable properties,
171 ColumnSelection cs, AlignmentI al, ViewDef view)
175 if (view.viewname != null)
177 text.append("VIEW_DEF\t" + view.viewname + "\n");
181 list = view.visibleGroups;
185 cs = view.hiddencols;
189 // add hidden rep sequences.
192 // first target - store and restore all settings for a view.
193 if (al != null && al.hasSeqrep())
195 text.append("VIEW_SETREF\t" + al.getSeqrep().getName() + "\n");
197 if (cs != null && cs.hasHiddenColumns())
199 text.append("VIEW_HIDECOLS\t");
200 List<int[]> hc = cs.getHiddenColumns();
201 boolean comma = false;
218 // TODO: allow efficient recovery of annotation data shown in several
220 if (annotations != null)
222 boolean oneColour = true;
223 AlignmentAnnotation row;
225 SequenceI refSeq = null;
226 SequenceGroup refGroup = null;
228 StringBuffer colours = new StringBuffer();
229 StringBuffer graphLine = new StringBuffer();
230 StringBuffer rowprops = new StringBuffer();
231 Hashtable<Integer, String> graphGroup = new Hashtable<Integer, String>();
232 Hashtable<Integer, Object[]> graphGroup_refs = new Hashtable<Integer, Object[]>();
233 BitSet graphGroupSeen = new BitSet();
235 java.awt.Color color;
237 for (int i = 0; i < annotations.length; i++)
239 row = annotations[i];
243 && !(row.graphGroup > -1 && graphGroupSeen
244 .get(row.graphGroup)))
252 // mark any sequence references for the row
253 writeSequence_Ref(refSeq, row.sequenceRef);
254 refSeq = row.sequenceRef;
255 // mark any group references for the row
256 writeGroup_Ref(refGroup, row.groupRef);
257 refGroup = row.groupRef;
259 boolean hasGlyphs = row.hasIcons, hasLabels = row.hasText, hasValues = row.hasScore, hasText = false;
260 // lookahead to check what the annotation row object actually contains.
261 for (int j = 0; row.annotations != null
262 && j < row.annotations.length
263 && (!hasGlyphs || !hasLabels || !hasValues); j++)
265 if (row.annotations[j] != null)
267 hasLabels |= (row.annotations[j].displayCharacter != null
268 && row.annotations[j].displayCharacter.length() > 0 && !row.annotations[j].displayCharacter
270 hasGlyphs |= (row.annotations[j].secondaryStructure != 0 && row.annotations[j].secondaryStructure != ' ');
271 hasValues |= (!Float.isNaN(row.annotations[j].value)); // NaNs can't
274 hasText |= (row.annotations[j].description != null && row.annotations[j].description
279 if (row.graph == AlignmentAnnotation.NO_GRAPH)
281 text.append("NO_GRAPH\t");
282 hasValues = false; // only secondary structure
283 // hasLabels = false; // and annotation description string.
287 if (row.graph == AlignmentAnnotation.BAR_GRAPH)
289 text.append("BAR_GRAPH\t");
290 hasGlyphs = false; // no secondary structure
293 else if (row.graph == AlignmentAnnotation.LINE_GRAPH)
295 hasGlyphs = false; // no secondary structure
296 text.append("LINE_GRAPH\t");
299 if (row.getThreshold() != null)
301 graphLine.append("GRAPHLINE\t");
302 graphLine.append(row.label);
303 graphLine.append("\t");
304 graphLine.append(row.getThreshold().value);
305 graphLine.append("\t");
306 graphLine.append(row.getThreshold().label);
307 graphLine.append("\t");
308 graphLine.append(jalview.util.Format.getHexString(row
309 .getThreshold().colour));
310 graphLine.append(newline);
313 if (row.graphGroup > -1)
315 graphGroupSeen.set(row.graphGroup);
316 Integer key = new Integer(row.graphGroup);
317 if (graphGroup.containsKey(key))
319 graphGroup.put(key, graphGroup.get(key) + "\t" + row.label);
324 graphGroup_refs.put(key, new Object[] { refSeq, refGroup });
325 graphGroup.put(key, row.label);
330 text.append(row.label + "\t");
331 if (row.description != null)
333 text.append(row.description + "\t");
335 for (int j = 0; row.annotations != null
336 && j < row.annotations.length; j++)
339 && jalview.util.Comparison.isGap(refSeq.getCharAt(j)))
344 if (row.annotations[j] != null)
347 if (hasGlyphs) // could be also hasGlyphs || ...
351 if (row.annotations[j].secondaryStructure != ' ')
353 // only write out the field if its not whitespace.
354 text.append(row.annotations[j].secondaryStructure);
360 if (!Float.isNaN(row.annotations[j].value))
362 text.append(comma + row.annotations[j].value);
366 // System.err.println("Skipping NaN - not valid value.");
367 text.append(comma + 0f);// row.annotations[j].value);
373 // TODO: labels are emitted after values for bar graphs.
374 if // empty labels are allowed, so
375 (row.annotations[j].displayCharacter != null
376 && row.annotations[j].displayCharacter.length() > 0
377 && !row.annotations[j].displayCharacter.equals(" "))
379 text.append(comma + row.annotations[j].displayCharacter);
385 if (row.annotations[j].description != null
386 && row.annotations[j].description.length() > 0
387 && !row.annotations[j].description
388 .equals(row.annotations[j].displayCharacter))
390 text.append(comma + row.annotations[j].description);
394 if (color != null && !color.equals(row.annotations[j].colour))
399 color = row.annotations[j].colour;
401 if (row.annotations[j].colour != null
402 && row.annotations[j].colour != java.awt.Color.black)
406 + jalview.util.Format
407 .getHexString(row.annotations[j].colour)
417 text.append("\t" + row.score);
420 text.append(newline);
422 if (color != null && color != java.awt.Color.black && oneColour)
424 colours.append("COLOUR\t");
425 colours.append(row.label);
426 colours.append("\t");
427 colours.append(jalview.util.Format.getHexString(color));
428 colours.append(newline);
430 if (row.scaleColLabel || row.showAllColLabels
431 || row.centreColLabels)
433 rowprops.append("ROWPROPERTIES\t");
434 rowprops.append(row.label);
435 rowprops.append("\tscaletofit=");
436 rowprops.append(row.scaleColLabel);
437 rowprops.append("\tshowalllabs=");
438 rowprops.append(row.showAllColLabels);
439 rowprops.append("\tcentrelabs=");
440 rowprops.append(row.centreColLabels);
441 rowprops.append(newline);
443 if (graphLine.length() > 0)
445 text.append(graphLine.toString());
446 graphLine.setLength(0);
450 text.append(newline);
452 text.append(colours.toString());
453 if (graphGroup.size() > 0)
455 SequenceI oldRefSeq = refSeq;
456 SequenceGroup oldRefGroup = refGroup;
457 for (Map.Entry<Integer, String> combine_statement : graphGroup
460 Object[] seqRefAndGroup = graphGroup_refs.get(combine_statement
463 writeSequence_Ref(refSeq, (SequenceI) seqRefAndGroup[0]);
464 refSeq = (SequenceI) seqRefAndGroup[0];
466 writeGroup_Ref(refGroup, (SequenceGroup) seqRefAndGroup[1]);
467 refGroup = (SequenceGroup) seqRefAndGroup[1];
468 text.append("COMBINE\t");
469 text.append(combine_statement.getValue());
470 text.append(newline);
472 writeSequence_Ref(refSeq, oldRefSeq);
475 writeGroup_Ref(refGroup, oldRefGroup);
476 refGroup = oldRefGroup;
478 text.append(rowprops.toString());
486 if (properties != null)
488 text.append(newline);
489 text.append(newline);
490 text.append("ALIGNMENT");
491 Enumeration en = properties.keys();
492 while (en.hasMoreElements())
494 String key = en.nextElement().toString();
498 text.append(properties.get(key));
500 // TODO: output alignment visualization settings here if required
501 // iterate through one or more views, defining, marking columns and rows
502 // as visible/hidden, and emmitting view properties.
503 // View specific annotation is
506 return text.toString();
509 private Object writeGroup_Ref(SequenceGroup refGroup,
510 SequenceGroup next_refGroup)
512 if (next_refGroup == null)
515 if (refGroup != null)
517 text.append(newline);
518 text.append("GROUP_REF\t");
519 text.append("ALIGNMENT");
520 text.append(newline);
526 if (refGroup == null || refGroup != next_refGroup)
528 text.append(newline);
529 text.append("GROUP_REF\t");
530 text.append(next_refGroup.getName());
531 text.append(newline);
538 private boolean writeSequence_Ref(SequenceI refSeq, SequenceI next_refSeq)
541 if (next_refSeq == null)
545 text.append(newline);
546 text.append("SEQUENCE_REF\t");
547 text.append("ALIGNMENT");
548 text.append(newline);
554 if (refSeq == null || refSeq != next_refSeq)
556 text.append(newline);
557 text.append("SEQUENCE_REF\t");
558 text.append(next_refSeq.getName());
559 text.append(newline);
566 public void printGroups(List<SequenceGroup> list)
568 SequenceI seqrep = null;
569 for (SequenceGroup sg : list)
573 text.append("SEQUENCE_GROUP\t" + sg.getName() + "\t"
574 + (sg.getStartRes() + 1) + "\t" + (sg.getEndRes() + 1)
580 seqrep = sg.getSeqrep();
581 text.append("SEQUENCE_REF\t");
582 text.append(seqrep.getName());
583 text.append(newline);
584 text.append("SEQUENCE_GROUP\t");
585 text.append(sg.getName());
587 text.append((seqrep.findPosition(sg.getStartRes())));
589 text.append((seqrep.findPosition(sg.getEndRes())));
593 for (int s = 0; s < sg.getSize(); s++)
595 text.append(sg.getSequenceAt(s).getName());
598 text.append(newline);
599 text.append("PROPERTIES\t");
600 text.append(sg.getName());
603 if (sg.getDescription() != null)
605 text.append("description=");
606 text.append(sg.getDescription());
611 text.append("colour=");
612 text.append(sg.cs.toString());
614 if (sg.cs.getThreshold() != 0)
616 text.append("pidThreshold=");
617 text.append(sg.cs.getThreshold());
619 if (sg.cs.conservationApplied())
621 text.append("consThreshold=");
622 text.append(sg.cs.getConservationInc());
626 text.append("outlineColour=");
627 text.append(jalview.util.Format.getHexString(sg.getOutlineColour()));
630 text.append("displayBoxes=");
631 text.append(sg.getDisplayBoxes());
633 text.append("displayText=");
634 text.append(sg.getDisplayText());
636 text.append("colourText=");
637 text.append(sg.getColourText());
639 text.append("showUnconserved=");
640 text.append(sg.getShowNonconserved());
642 if (sg.textColour != java.awt.Color.black)
644 text.append("textCol1=");
645 text.append(jalview.util.Format.getHexString(sg.textColour));
648 if (sg.textColour2 != java.awt.Color.white)
650 text.append("textCol2=");
651 text.append(jalview.util.Format.getHexString(sg.textColour2));
654 if (sg.thresholdTextColour != 0)
656 text.append("textColThreshold=");
657 text.append(sg.thresholdTextColour);
660 if (sg.idColour != null)
662 text.append("idColour=");
663 text.append(jalview.util.Format.getHexString(sg.idColour));
668 text.append("hide=true\t");
672 text.append("hidecols=true\t");
676 // terminate the last line and clear the sequence ref for the group
677 text.append(newline);
678 text.append("SEQUENCE_REF");
680 text.append(newline);
681 text.append(newline);
687 public boolean annotateAlignmentView(AlignViewportI viewport,
688 String file, DataSourceType protocol)
690 ColumnSelection colSel = viewport.getColumnSelection();
693 colSel = new ColumnSelection();
695 boolean rslt = readAnnotationFile(viewport.getAlignment(), colSel,
697 if (rslt && (colSel.hasSelectedColumns() || colSel.hasHiddenColumns()))
699 viewport.setColumnSelection(colSel);
705 public boolean readAnnotationFile(AlignmentI al, String file,
706 DataSourceType sourceType)
708 return readAnnotationFile(al, null, file, sourceType);
711 public boolean readAnnotationFile(AlignmentI al, ColumnSelection colSel,
712 String file, DataSourceType sourceType)
715 BufferedReader in = null;
718 if (sourceType == DataSourceType.FILE)
720 in = new BufferedReader(new FileReader(file));
721 baseUri = new File(file).getParent();
731 else if (sourceType == DataSourceType.URL)
733 URL url = new URL(file);
734 in = new BufferedReader(new InputStreamReader(url.openStream()));
735 String bs = url.toExternalForm();
736 baseUri = bs.substring(0, bs.indexOf(url.getHost())
737 + url.getHost().length());
738 baseUri += url.toURI().getPath();
739 if (baseUri.lastIndexOf("/") > -1)
741 baseUri = baseUri.substring(0, baseUri.lastIndexOf("/")) + "/";
744 else if (sourceType == DataSourceType.PASTE)
746 in = new BufferedReader(new StringReader(file));
747 // TODO - support mimencoded PDBs for a paste.. ?
750 else if (sourceType == DataSourceType.CLASSLOADER)
752 java.io.InputStream is = getClass().getResourceAsStream("/" + file);
755 in = new BufferedReader(new java.io.InputStreamReader(is));
756 // TODO: this probably doesn't work for classloader - needs a test
757 baseUri = new File("/" + file).getParent() + "/";
762 return parseAnnotationFrom(al, colSel, in);
765 } catch (Exception ex)
767 ex.printStackTrace();
768 System.out.println("Problem reading annotation file: " + ex);
771 System.out.println("Last read line " + nlinesread + ": '"
772 + lastread + "' (first 80 chars) ...");
780 public boolean parseAnnotationFrom(AlignmentI al, ColumnSelection colSel,
781 BufferedReader in) throws Exception
784 ArrayList<Object[]> combineAnnotation_calls = new ArrayList<Object[]>();
785 ArrayList<Object[]> deferredAnnotation_calls = new ArrayList<Object[]>();
786 boolean modified = false;
787 String groupRef = null;
788 Hashtable groupRefRows = new Hashtable();
790 Hashtable autoAnnots = new Hashtable();
792 String line, label, description, token;
793 int graphStyle, index;
795 int existingAnnotations = 0;
796 // when true - will add new rows regardless of whether they are duplicate
797 // auto-annotation like consensus or conservation graphs
798 boolean overrideAutoAnnot = false;
799 if (al.getAlignmentAnnotation() != null)
801 existingAnnotations = al.getAlignmentAnnotation().length;
802 if (existingAnnotations > 0)
804 AlignmentAnnotation[] aa = al.getAlignmentAnnotation();
805 for (int aai = 0; aai < aa.length; aai++)
807 if (aa[aai].autoCalculated)
809 // make a note of the name and description
811 autoAnnotsKey(aa[aai], aa[aai].sequenceRef,
812 (aa[aai].groupRef == null ? null
813 : aa[aai].groupRef.getName())),
820 int alWidth = al.getWidth();
823 Annotation[] annotations;
824 AlignmentAnnotation annotation = null;
826 // First confirm this is an Annotation file
827 boolean jvAnnotationFile = false;
828 while ((line = in.readLine()) != null)
831 lastread = new String(line);
832 if (line.indexOf("#") == 0)
837 if (line.indexOf("JALVIEW_ANNOTATION") > -1)
839 jvAnnotationFile = true;
844 if (!jvAnnotationFile)
850 while ((line = in.readLine()) != null)
853 lastread = new String(line);
854 if (line.indexOf("#") == 0
855 || line.indexOf("JALVIEW_ANNOTATION") > -1
856 || line.length() == 0)
861 st = new StringTokenizer(line, "\t");
862 token = st.nextToken();
863 if (token.equalsIgnoreCase("COLOUR"))
865 // TODO: use graduated colour def'n here too
866 colourAnnotations(al, st.nextToken(), st.nextToken());
871 else if (token.equalsIgnoreCase(COMBINE))
873 // keep a record of current state and resolve groupRef at end
874 combineAnnotation_calls
875 .add(new Object[] { st, refSeq, groupRef });
879 else if (token.equalsIgnoreCase("ROWPROPERTIES"))
881 addRowProperties(al, st);
885 else if (token.equalsIgnoreCase(GRAPHLINE))
888 deferredAnnotation_calls.add(new Object[] { GRAPHLINE, st,
894 else if (token.equalsIgnoreCase("SEQUENCE_REF"))
896 if (st.hasMoreTokens())
898 refSeq = al.findName(refSeqId = st.nextToken());
905 refSeqIndex = Integer.parseInt(st.nextToken());
910 .println("WARNING: SEQUENCE_REF index must be > 0 in AnnotationFile");
912 } catch (Exception ex)
924 else if (token.equalsIgnoreCase("GROUP_REF"))
926 // Group references could be forward or backwards, so they are
927 // resolved after the whole file is read in
929 if (st.hasMoreTokens())
931 groupRef = st.nextToken();
932 if (groupRef.length() < 1)
934 groupRef = null; // empty string
938 if (groupRefRows.get(groupRef) == null)
940 groupRefRows.put(groupRef, new Vector());
946 else if (token.equalsIgnoreCase("SEQUENCE_GROUP"))
953 else if (token.equalsIgnoreCase("PROPERTIES"))
955 addProperties(al, st);
960 else if (token.equalsIgnoreCase("BELOW_ALIGNMENT"))
962 setBelowAlignment(al, st);
966 else if (token.equalsIgnoreCase("ALIGNMENT"))
968 addAlignmentDetails(al, st);
972 else if (token.equalsIgnoreCase("VIEW_SETREF"))
976 al.setSeqrep(refSeq);
981 else if (token.equalsIgnoreCase("VIEW_HIDECOLS"))
983 if (st.hasMoreTokens())
987 colSel = new ColumnSelection();
989 parseHideCols(colSel, st.nextToken());
994 else if (token.equalsIgnoreCase("HIDE_INSERTIONS"))
996 SequenceI sr = refSeq == null ? al.getSeqrep() : refSeq;
999 sr = al.getSequenceAt(0);
1006 .println("Cannot process HIDE_INSERTIONS without an alignment view: Ignoring line: "
1011 // consider deferring this till after the file has been parsed ?
1012 colSel.hideInsertionsFor(sr);
1018 else if (token.equalsIgnoreCase(HEADER_STRUCT_MODEL))
1020 int hSize = st.countTokens();
1021 StructModelHeader = new String[hSize];
1022 for (int x = 0; x < hSize; x++)
1024 StructModelHeader[x] = st.nextToken();
1028 else if (token.equalsIgnoreCase(STRUCTMODEL))
1030 boolean failedtoadd = true;
1031 // expects STRUCTMODEL <Query> <TemplateSeqId> <ModelFile>
1032 // <FastaMappingFile>
1033 String querySeqId = !st.hasMoreTokens() ? "" : st.nextToken();
1034 SequenceI querySeq = al.findName(querySeqId);
1035 if (st.hasMoreTokens()) {
1036 refSeq = al.findName(refSeqId = st.nextToken());
1039 System.err.println("Couldn't locate " + refSeqId
1040 + " in the alignment for STRUCTMODEL");
1045 int tSize = st.countTokens() + 2;
1046 String[] rowData = new String[tSize];
1047 rowData[0] = querySeqId;
1048 rowData[1] = refSeqId;
1049 for (int x = 2; x < tSize; x++)
1051 rowData[x] = st.nextToken();
1053 if (processStructModel(al, querySeq, refSeq,
1054 StructModelHeader, rowData, baseUri))
1056 failedtoadd = false;
1063 .println("Need minimum of <Query> <TemplateSeqId> <ModelFile> <FastaMappingFile> as tab separated fields after"
1070 // Parse out the annotation row
1071 graphStyle = AlignmentAnnotation.getGraphValueFromString(token);
1072 label = st.nextToken();
1075 annotations = new Annotation[alWidth];
1077 float score = Float.NaN;
1079 if (st.hasMoreTokens())
1081 line = st.nextToken();
1083 if (line.indexOf("|") == -1)
1086 if (st.hasMoreTokens())
1088 line = st.nextToken();
1092 if (st.hasMoreTokens())
1094 // This must be the score
1095 score = Float.valueOf(st.nextToken()).floatValue();
1098 st = new StringTokenizer(line, "|", true);
1100 boolean emptyColumn = true;
1101 boolean onlyOneElement = (st.countTokens() == 1);
1103 while (st.hasMoreElements() && index < alWidth)
1105 token = st.nextToken().trim();
1111 score = Float.valueOf(token).floatValue();
1113 } catch (NumberFormatException ex)
1118 if (token.equals("|"))
1129 annotations[index++] = parseAnnotation(token, graphStyle);
1130 emptyColumn = false;
1136 annotation = new AlignmentAnnotation(label, description,
1137 (index == 0) ? null : annotations, 0, 0, graphStyle);
1139 annotation.score = score;
1140 if (!overrideAutoAnnot
1141 && autoAnnots.containsKey(autoAnnotsKey(annotation, refSeq,
1144 // skip - we've already got an automatic annotation of this type.
1147 // otherwise add it!
1151 annotation.belowAlignment = false;
1152 // make a copy of refSeq so we can find other matches in the alignment
1153 SequenceI referedSeq = refSeq;
1156 // copy before we do any mapping business.
1157 // TODO: verify that undo/redo with 1:many sequence associated
1158 // annotations can be undone correctly
1159 AlignmentAnnotation ann = new AlignmentAnnotation(annotation);
1161 .createSequenceMapping(referedSeq, refSeqIndex, false);
1162 annotation.adjustForAlignment();
1163 referedSeq.addAlignmentAnnotation(annotation);
1164 al.addAnnotation(annotation);
1165 al.setAnnotationIndex(annotation,
1166 al.getAlignmentAnnotation().length
1167 - existingAnnotations - 1);
1168 if (groupRef != null)
1170 ((Vector) groupRefRows.get(groupRef)).addElement(annotation);
1172 // and recover our virgin copy to use again if necessary.
1175 } while (refSeqId != null
1176 && (referedSeq = al.findName(referedSeq, refSeqId, true)) != null);
1180 al.addAnnotation(annotation);
1181 al.setAnnotationIndex(annotation,
1182 al.getAlignmentAnnotation().length - existingAnnotations
1184 if (groupRef != null)
1186 ((Vector) groupRefRows.get(groupRef)).addElement(annotation);
1189 // and set modification flag
1192 // Resolve the groupRefs
1193 Hashtable<String, SequenceGroup> groupRefLookup = new Hashtable<String, SequenceGroup>();
1194 Enumeration en = groupRefRows.keys();
1196 while (en.hasMoreElements())
1198 groupRef = (String) en.nextElement();
1199 boolean matched = false;
1200 // Resolve group: TODO: add a getGroupByName method to alignments
1201 for (SequenceGroup theGroup : al.getGroups())
1203 if (theGroup.getName().equals(groupRef))
1207 // TODO: specify and implement duplication of alignment annotation
1208 // for multiple group references.
1210 .println("Ignoring 1:many group reference mappings for group name '"
1216 Vector rowset = (Vector) groupRefRows.get(groupRef);
1217 groupRefLookup.put(groupRef, theGroup);
1218 if (rowset != null && rowset.size() > 0)
1220 AlignmentAnnotation alan = null;
1221 for (int elm = 0, elmSize = rowset.size(); elm < elmSize; elm++)
1223 alan = (AlignmentAnnotation) rowset.elementAt(elm);
1224 alan.groupRef = theGroup;
1230 ((Vector) groupRefRows.get(groupRef)).removeAllElements();
1232 // process any deferred attribute settings for each context
1233 for (Object[] _deferred_args : deferredAnnotation_calls)
1235 if (_deferred_args[0] == GRAPHLINE)
1238 (StringTokenizer) _deferred_args[1], // st
1239 (SequenceI) _deferred_args[2], // refSeq
1240 (_deferred_args[3] == null) ? null : groupRefLookup
1241 .get(_deferred_args[3]) // the reference
1247 // finally, combine all the annotation rows within each context.
1249 * number of combine statements in this annotation file. Used to create
1250 * new groups for combined annotation graphs without disturbing existing
1253 int combinecount = 0;
1254 for (Object[] _combine_args : combineAnnotation_calls)
1256 combineAnnotations(al,
1258 (StringTokenizer) _combine_args[0], // st
1259 (SequenceI) _combine_args[1], // refSeq
1260 (_combine_args[2] == null) ? null : groupRefLookup
1261 .get(_combine_args[2]) // the reference group,
1270 * Resolve structural model to a reference sequence and register it to
1271 * StructureSelectionManager
1274 * @param querySequence
1275 * @param templateSeq
1276 * @param structModelHeader
1277 * @param structModelData
1278 * @return true if model and sequence was added
1280 static boolean processStructModel(AlignmentI al, SequenceI querySequence,
1281 SequenceI templateSeq,
1282 String[] structModelHeader,
1283 String[] structModelData, String baseUri)
1285 String warningMessage = null;
1286 boolean added = false;
1288 String structureModelFile = resolveAbsolutePath(structModelData[2],
1290 String fastaMappingFile = resolveAbsolutePath(structModelData[3],
1292 // System.out.println("Model File >> " + structureModelFile);
1293 // System.out.println("Fasta File >> " + fastaMappingFile);
1294 String modelName = StructureFile.safeName(structureModelFile);
1295 PDBEntry phyre2PDBEntry = new PDBEntry(modelName, " ",
1297 structureModelFile);
1298 List<DynamicData> phyreDD = generatePhyreDynamicDataList(
1299 structModelHeader, structModelData);
1300 phyre2PDBEntry.setProperty("DYNAMIC_DATA_PHYRE2", phyreDD);
1301 templateSeq.getDatasetSequence().addPDBId(phyre2PDBEntry);
1302 if (querySequence != null)
1304 querySequence.getDatasetSequence().addPDBId(phyre2PDBEntry);
1306 StructureSelectionManager ssm = StructureSelectionManager
1307 .getStructureSelectionManager();
1308 ssm.registerPhyre2Template(structureModelFile, fastaMappingFile);
1311 } catch (Exception x)
1313 warningMessage = x.toString();
1315 if (warningMessage !=null)
1317 System.err.println("Warnings whilst processing STRUCTMODEL: "+warningMessage);
1323 static List<DynamicData> generatePhyreDynamicDataList(
1324 String[] headerArray,
1328 if (headerArray == null || dataArray == null)
1330 throw new IllegalArgumentException(
1331 "Header or data arrays must not be null");
1334 if (headerArray.length != dataArray.length)
1336 throw new IllegalArgumentException(
1337 "Header and data arrays must be of same lenght");
1339 List<DynamicData> dynamicDataList = new ArrayList<DynamicData>();
1341 for (String data : dataArray)
1343 // first four column should be hidden;
1344 boolean show = (x > 4);
1345 dynamicDataList.add(new DynamicData(headerArray[x], data, DataType.S,
1349 return dynamicDataList;
1352 static String resolveAbsolutePath(String relURI, String _baseUri)
1354 if (relURI.indexOf(":/") > -1 || relURI.startsWith("/")
1355 || "".equals(_baseUri) || relURI.startsWith(_baseUri))
1359 return _baseUri + relURI;
1362 private void parseHideCols(ColumnSelection colSel, String nextToken)
1364 StringTokenizer inval = new StringTokenizer(nextToken, ",");
1365 while (inval.hasMoreTokens())
1367 String range = inval.nextToken().trim();
1368 int from, to = range.indexOf("-");
1371 from = to = Integer.parseInt(range);
1374 colSel.hideColumns(from, to);
1379 from = Integer.parseInt(range.substring(0, to));
1380 if (to < range.length() - 1)
1382 to = Integer.parseInt(range.substring(to + 1));
1388 if (from > 0 && to >= from)
1390 colSel.hideColumns(from, to);
1396 private Object autoAnnotsKey(AlignmentAnnotation annotation,
1397 SequenceI refSeq, String groupRef)
1399 return annotation.graph + "\t" + annotation.label + "\t"
1400 + annotation.description + "\t"
1401 + (refSeq != null ? refSeq.getDisplayId(true) : "");
1404 Annotation parseAnnotation(String string, int graphStyle)
1406 // don't do the glyph test if we don't want secondary structure
1407 boolean hasSymbols = (graphStyle == AlignmentAnnotation.NO_GRAPH);
1408 String desc = null, displayChar = null;
1409 char ss = ' '; // secondaryStructure
1411 boolean parsedValue = false, dcset = false;
1414 Color colour = null;
1415 int i = string.indexOf("[");
1416 int j = string.indexOf("]");
1417 if (i > -1 && j > -1)
1419 colour = ColorUtils.parseColourString(string.substring(i + 1,
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 Color awtColour = ColorUtils.parseColourString(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 = awtColour;
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[] alannot = al.getAlignmentAnnotation();
1604 String nextToken = st.nextToken();
1608 value = Float.valueOf(nextToken);
1609 } catch (NumberFormatException e)
1611 System.err.println("line " + nlinesread + ": Threshold '" + nextToken
1612 + "' invalid, setting to zero");
1614 String label = st.hasMoreTokens() ? st.nextToken() : null;
1615 Color colour = null;
1616 if (st.hasMoreTokens())
1618 colour = ColorUtils.parseColourString(st.nextToken());
1620 if (alannot != null)
1622 for (int i = 0; i < alannot.length; i++)
1624 if (alannot[i].label.equalsIgnoreCase(group)
1625 && (seqRef == null || alannot[i].sequenceRef == seqRef)
1626 && (groupRef == null || alannot[i].groupRef == groupRef))
1628 alannot[i].setThreshold(new GraphLine(value, label, colour));
1634 void addGroup(AlignmentI al, StringTokenizer st)
1636 SequenceGroup sg = new SequenceGroup();
1637 sg.setName(st.nextToken());
1641 rng = st.nextToken();
1642 if (rng.length() > 0 && !rng.startsWith("*"))
1644 sg.setStartRes(Integer.parseInt(rng) - 1);
1650 rng = st.nextToken();
1651 if (rng.length() > 0 && !rng.startsWith("*"))
1653 sg.setEndRes(Integer.parseInt(rng) - 1);
1657 sg.setEndRes(al.getWidth() - 1);
1659 } catch (Exception e)
1662 .println("Couldn't parse Group Start or End Field as '*' or a valid column or sequence index: '"
1663 + rng + "' - assuming alignment width for group.");
1664 // assume group is full width
1666 sg.setEndRes(al.getWidth() - 1);
1669 String index = st.nextToken();
1670 if (index.equals("-1"))
1672 while (st.hasMoreElements())
1674 sg.addSequence(al.findName(st.nextToken()), false);
1679 StringTokenizer st2 = new StringTokenizer(index, ",");
1681 while (st2.hasMoreTokens())
1683 String tmp = st2.nextToken();
1684 if (tmp.equals("*"))
1686 for (int i = 0; i < al.getHeight(); i++)
1688 sg.addSequence(al.getSequenceAt(i), false);
1691 else if (tmp.indexOf("-") >= 0)
1693 StringTokenizer st3 = new StringTokenizer(tmp, "-");
1695 int start = (Integer.parseInt(st3.nextToken()));
1696 int end = (Integer.parseInt(st3.nextToken()));
1700 for (int i = start; i <= end; i++)
1702 sg.addSequence(al.getSequenceAt(i - 1), false);
1708 sg.addSequence(al.getSequenceAt(Integer.parseInt(tmp) - 1), false);
1715 sg.setStartRes(refSeq.findIndex(sg.getStartRes() + 1) - 1);
1716 sg.setEndRes(refSeq.findIndex(sg.getEndRes() + 1) - 1);
1717 sg.setSeqrep(refSeq);
1720 if (sg.getSize() > 0)
1726 void addRowProperties(AlignmentI al, StringTokenizer st)
1728 String label = st.nextToken(), keyValue, key, value;
1729 boolean scaletofit = false, centerlab = false, showalllabs = false;
1730 while (st.hasMoreTokens())
1732 keyValue = st.nextToken();
1733 key = keyValue.substring(0, keyValue.indexOf("="));
1734 value = keyValue.substring(keyValue.indexOf("=") + 1);
1735 if (key.equalsIgnoreCase("scaletofit"))
1737 scaletofit = Boolean.valueOf(value).booleanValue();
1739 if (key.equalsIgnoreCase("showalllabs"))
1741 showalllabs = Boolean.valueOf(value).booleanValue();
1743 if (key.equalsIgnoreCase("centrelabs"))
1745 centerlab = Boolean.valueOf(value).booleanValue();
1747 AlignmentAnnotation[] alr = al.getAlignmentAnnotation();
1750 for (int i = 0; i < alr.length; i++)
1752 if (alr[i].label.equalsIgnoreCase(label))
1754 alr[i].centreColLabels = centerlab;
1755 alr[i].scaleColLabel = scaletofit;
1756 alr[i].showAllColLabels = showalllabs;
1763 void addProperties(AlignmentI al, StringTokenizer st)
1766 // So far we have only added groups to the annotationHash,
1767 // the idea is in the future properties can be added to
1768 // alignments, other annotations etc
1769 if (al.getGroups() == null)
1774 String name = st.nextToken();
1775 SequenceGroup sg = null;
1776 for (SequenceGroup _sg : al.getGroups())
1778 if ((sg = _sg).getName().equals(name))
1790 String keyValue, key, value;
1791 ColourSchemeI def = sg.getColourScheme();
1792 while (st.hasMoreTokens())
1794 keyValue = st.nextToken();
1795 key = keyValue.substring(0, keyValue.indexOf("="));
1796 value = keyValue.substring(keyValue.indexOf("=") + 1);
1798 if (key.equalsIgnoreCase("description"))
1800 sg.setDescription(value);
1802 else if (key.equalsIgnoreCase("colour"))
1804 sg.cs.setColourScheme(ColourSchemeProperty
1805 .getColourScheme(al, value));
1807 else if (key.equalsIgnoreCase("pidThreshold"))
1809 sg.cs.setThreshold(Integer.parseInt(value), true);
1812 else if (key.equalsIgnoreCase("consThreshold"))
1814 sg.cs.setConservationInc(Integer.parseInt(value));
1815 Conservation c = new Conservation("Group", sg.getSequences(null),
1816 sg.getStartRes(), sg.getEndRes() + 1);
1819 c.verdict(false, 25); // TODO: refer to conservation percent threshold
1821 sg.cs.setConservation(c);
1824 else if (key.equalsIgnoreCase("outlineColour"))
1826 sg.setOutlineColour(ColorUtils.parseColourString(value));
1828 else if (key.equalsIgnoreCase("displayBoxes"))
1830 sg.setDisplayBoxes(Boolean.valueOf(value).booleanValue());
1832 else if (key.equalsIgnoreCase("showUnconserved"))
1834 sg.setShowNonconserved(Boolean.valueOf(value).booleanValue());
1836 else if (key.equalsIgnoreCase("displayText"))
1838 sg.setDisplayText(Boolean.valueOf(value).booleanValue());
1840 else if (key.equalsIgnoreCase("colourText"))
1842 sg.setColourText(Boolean.valueOf(value).booleanValue());
1844 else if (key.equalsIgnoreCase("textCol1"))
1846 sg.textColour = ColorUtils.parseColourString(value);
1848 else if (key.equalsIgnoreCase("textCol2"))
1850 sg.textColour2 = ColorUtils.parseColourString(value);
1852 else if (key.equalsIgnoreCase("textColThreshold"))
1854 sg.thresholdTextColour = Integer.parseInt(value);
1856 else if (key.equalsIgnoreCase("idColour"))
1858 Color idColour = ColorUtils.parseColourString(value);
1859 sg.setIdColour(idColour == null ? Color.black : idColour);
1861 else if (key.equalsIgnoreCase("hide"))
1863 // see bug https://mantis.lifesci.dundee.ac.uk/view.php?id=25847
1864 sg.setHidereps(true);
1866 else if (key.equalsIgnoreCase("hidecols"))
1868 // see bug https://mantis.lifesci.dundee.ac.uk/view.php?id=25847
1869 sg.setHideCols(true);
1871 sg.recalcConservation();
1873 if (sg.getColourScheme() == null)
1875 sg.setColourScheme(def);
1880 void setBelowAlignment(AlignmentI al, StringTokenizer st)
1883 AlignmentAnnotation aa, ala[] = al.getAlignmentAnnotation();
1887 .print("Warning - no annotation to set below for sequence associated annotation:");
1889 while (st.hasMoreTokens())
1891 token = st.nextToken();
1894 System.err.print(" " + token);
1898 for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1900 aa = al.getAlignmentAnnotation()[i];
1901 if (aa.sequenceRef == refSeq && aa.label.equals(token))
1903 aa.belowAlignment = true;
1910 System.err.print("\n");
1914 void addAlignmentDetails(AlignmentI al, StringTokenizer st)
1916 String keyValue, key, value;
1917 while (st.hasMoreTokens())
1919 keyValue = st.nextToken();
1920 key = keyValue.substring(0, keyValue.indexOf("="));
1921 value = keyValue.substring(keyValue.indexOf("=") + 1);
1922 al.setProperty(key, value);
1927 * Write annotations as a CSV file of the form 'label, value, value, ...' for
1930 * @param annotations
1931 * @return CSV file as a string.
1933 public String printCSVAnnotations(AlignmentAnnotation[] annotations)
1935 if (annotations == null)
1939 StringBuffer sp = new StringBuffer();
1940 for (int i = 0; i < annotations.length; i++)
1942 String atos = annotations[i].toString();
1946 int cp = atos.indexOf("\n", p);
1947 sp.append(annotations[i].label);
1951 sp.append(atos.substring(p, cp + 1));
1955 sp.append(atos.substring(p));
1961 return sp.toString();
1964 public String printAnnotationsForView(AlignViewportI viewport)
1966 return printAnnotations(viewport.isShowAnnotation() ? viewport
1967 .getAlignment().getAlignmentAnnotation() : null, viewport
1968 .getAlignment().getGroups(), viewport.getAlignment()
1969 .getProperties(), viewport.getColumnSelection(),
1970 viewport.getAlignment(), null);
1973 public String printAnnotationsForAlignment(AlignmentI al)
1975 return printAnnotations(al.getAlignmentAnnotation(), al.getGroups(),
1976 al.getProperties(), null, al, null);