571ed793bcee4927e1da25e68a99c8c40fe355c2
[jalview.git] / src / jalview / io / AnnotationFile.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
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.
11  *  
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.
16  * 
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.
20  */
21 package jalview.io;
22
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.gui.Desktop;
36 import jalview.schemes.ColourSchemeI;
37 import jalview.schemes.ColourSchemeProperty;
38 import jalview.schemes.UserColourScheme;
39 import jalview.structure.StructureSelectionManager;
40
41 import java.io.BufferedReader;
42 import java.io.File;
43 import java.io.FileReader;
44 import java.io.InputStreamReader;
45 import java.io.StringReader;
46 import java.net.URL;
47 import java.util.ArrayList;
48 import java.util.BitSet;
49 import java.util.Enumeration;
50 import java.util.Hashtable;
51 import java.util.List;
52 import java.util.Map;
53 import java.util.StringTokenizer;
54 import java.util.Vector;
55
56 public class AnnotationFile
57 {
58   public AnnotationFile()
59   {
60     init();
61   }
62
63   /**
64    * character used to write newlines
65    */
66   protected String newline = System.getProperty("line.separator");
67
68   /**
69    * set new line string and reset the output buffer
70    * 
71    * @param nl
72    */
73   public void setNewlineString(String nl)
74   {
75     newline = nl;
76     init();
77   }
78
79   public String getNewlineString()
80   {
81     return newline;
82   }
83
84   StringBuffer text;
85
86   private void init()
87   {
88     text = new StringBuffer("JALVIEW_ANNOTATION" + newline + "# Created: "
89             + new java.util.Date() + newline + newline);
90     refSeq = null;
91     refSeqId = null;
92   }
93
94   /**
95    * convenience method for pre-2.9 annotation files which have no view, hidden
96    * columns or hidden row keywords.
97    * 
98    * @param annotations
99    * @param list
100    * @param properties
101    * @return annotation file as a string.
102    */
103   public String printAnnotations(AlignmentAnnotation[] annotations,
104           List<SequenceGroup> list, Hashtable properties)
105   {
106     return printAnnotations(annotations, list, properties, null, null, null);
107
108   }
109
110   /**
111    * hold all the information about a particular view definition read from or
112    * written out in an annotations file.
113    */
114   public class ViewDef
115   {
116     public String viewname;
117
118     public HiddenSequences hidseqs;
119
120     public ColumnSelection hiddencols;
121
122     public Vector visibleGroups;
123
124     public Hashtable hiddenRepSeqs;
125
126     public ViewDef(String viewname, HiddenSequences hidseqs,
127             ColumnSelection hiddencols, Hashtable hiddenRepSeqs)
128     {
129       this.viewname = viewname;
130       this.hidseqs = hidseqs;
131       this.hiddencols = hiddencols;
132       this.hiddenRepSeqs = hiddenRepSeqs;
133     }
134   }
135
136   /**
137    * Prepare an annotation file given a set of annotations, groups, alignment
138    * properties and views.
139    * 
140    * @param annotations
141    * @param list
142    * @param properties
143    * @param views
144    * @return annotation file
145    */
146   public String printAnnotations(AlignmentAnnotation[] annotations,
147           List<SequenceGroup> list, Hashtable properties,
148           ColumnSelection cs, AlignmentI al, ViewDef view)
149   {
150     if (view != null)
151     {
152       if (view.viewname != null)
153       {
154         text.append("VIEW_DEF\t" + view.viewname + "\n");
155       }
156       if (list == null)
157       {
158         list = view.visibleGroups;
159       }
160       if (cs == null)
161       {
162         cs = view.hiddencols;
163       }
164       if (al == null)
165       {
166         // add hidden rep sequences.
167       }
168     }
169     // first target - store and restore all settings for a view.
170     if (al != null && al.hasSeqrep())
171     {
172       text.append("VIEW_SETREF\t" + al.getSeqrep().getName() + "\n");
173     }
174     if (cs != null && cs.hasHiddenColumns())
175     {
176       text.append("VIEW_HIDECOLS\t");
177       List<int[]> hc = cs.getHiddenColumns();
178       boolean comma = false;
179       for (int[] r : hc)
180       {
181         if (!comma)
182         {
183           comma = true;
184         }
185         else
186         {
187           text.append(",");
188         }
189         text.append(r[0]);
190         text.append("-");
191         text.append(r[1]);
192       }
193       text.append("\n");
194     }
195     // TODO: allow efficient recovery of annotation data shown in several
196     // different views
197     if (annotations != null)
198     {
199       boolean oneColour = true;
200       AlignmentAnnotation row;
201       String comma;
202       SequenceI refSeq = null;
203       SequenceGroup refGroup = null;
204
205       StringBuffer colours = new StringBuffer();
206       StringBuffer graphLine = new StringBuffer();
207       StringBuffer rowprops = new StringBuffer();
208       Hashtable<Integer, String> graphGroup = new Hashtable<Integer, String>();
209       Hashtable<Integer, Object[]> graphGroup_refs = new Hashtable<Integer, Object[]>();
210       BitSet graphGroupSeen = new BitSet();
211
212       java.awt.Color color;
213
214       for (int i = 0; i < annotations.length; i++)
215       {
216         row = annotations[i];
217
218         if (!row.visible
219                 && !row.hasScore()
220                 && !(row.graphGroup > -1 && graphGroupSeen
221                         .get(row.graphGroup)))
222         {
223           continue;
224         }
225
226         color = null;
227         oneColour = true;
228
229         // mark any sequence references for the row
230         writeSequence_Ref(refSeq, row.sequenceRef);
231         refSeq = row.sequenceRef;
232         // mark any group references for the row
233         writeGroup_Ref(refGroup, row.groupRef);
234         refGroup = row.groupRef;
235
236         boolean hasGlyphs = row.hasIcons, hasLabels = row.hasText, hasValues = row.hasScore, hasText = false;
237         // lookahead to check what the annotation row object actually contains.
238         for (int j = 0; row.annotations != null
239                 && j < row.annotations.length
240                 && (!hasGlyphs || !hasLabels || !hasValues); j++)
241         {
242           if (row.annotations[j] != null)
243           {
244             hasLabels |= (row.annotations[j].displayCharacter != null
245                     && row.annotations[j].displayCharacter.length() > 0 && !row.annotations[j].displayCharacter
246                     .equals(" "));
247             hasGlyphs |= (row.annotations[j].secondaryStructure != 0 && row.annotations[j].secondaryStructure != ' ');
248             hasValues |= (!Float.isNaN(row.annotations[j].value)); // NaNs can't
249             // be
250             // rendered..
251             hasText |= (row.annotations[j].description != null && row.annotations[j].description
252                     .length() > 0);
253           }
254         }
255
256         if (row.graph == AlignmentAnnotation.NO_GRAPH)
257         {
258           text.append("NO_GRAPH\t");
259           hasValues = false; // only secondary structure
260           // hasLabels = false; // and annotation description string.
261         }
262         else
263         {
264           if (row.graph == AlignmentAnnotation.BAR_GRAPH)
265           {
266             text.append("BAR_GRAPH\t");
267             hasGlyphs = false; // no secondary structure
268
269           }
270           else if (row.graph == AlignmentAnnotation.LINE_GRAPH)
271           {
272             hasGlyphs = false; // no secondary structure
273             text.append("LINE_GRAPH\t");
274           }
275
276           if (row.getThreshold() != null)
277           {
278             graphLine.append("GRAPHLINE\t");
279             graphLine.append(row.label);
280             graphLine.append("\t");
281             graphLine.append(row.getThreshold().value);
282             graphLine.append("\t");
283             graphLine.append(row.getThreshold().label);
284             graphLine.append("\t");
285             graphLine.append(jalview.util.Format.getHexString(row
286                     .getThreshold().colour));
287             graphLine.append(newline);
288           }
289
290           if (row.graphGroup > -1)
291           {
292             graphGroupSeen.set(row.graphGroup);
293             Integer key = new Integer(row.graphGroup);
294             if (graphGroup.containsKey(key))
295             {
296               graphGroup.put(key, graphGroup.get(key) + "\t" + row.label);
297
298             }
299             else
300             {
301               graphGroup_refs.put(key, new Object[] { refSeq, refGroup });
302               graphGroup.put(key, row.label);
303             }
304           }
305         }
306
307         text.append(row.label + "\t");
308         if (row.description != null)
309         {
310           text.append(row.description + "\t");
311         }
312         for (int j = 0; row.annotations != null
313                 && j < row.annotations.length; j++)
314         {
315           if (refSeq != null
316                   && jalview.util.Comparison.isGap(refSeq.getCharAt(j)))
317           {
318             continue;
319           }
320
321           if (row.annotations[j] != null)
322           {
323             comma = "";
324             if (hasGlyphs) // could be also hasGlyphs || ...
325             {
326
327               text.append(comma);
328               if (row.annotations[j].secondaryStructure != ' ')
329               {
330                 // only write out the field if its not whitespace.
331                 text.append(row.annotations[j].secondaryStructure);
332               }
333               comma = ",";
334             }
335             if (hasValues)
336             {
337               if (!Float.isNaN(row.annotations[j].value))
338               {
339                 text.append(comma + row.annotations[j].value);
340               }
341               else
342               {
343                 // System.err.println("Skipping NaN - not valid value.");
344                 text.append(comma + 0f);// row.annotations[j].value);
345               }
346               comma = ",";
347             }
348             if (hasLabels)
349             {
350               // TODO: labels are emitted after values for bar graphs.
351               if // empty labels are allowed, so
352               (row.annotations[j].displayCharacter != null
353                       && row.annotations[j].displayCharacter.length() > 0
354                       && !row.annotations[j].displayCharacter.equals(" "))
355               {
356                 text.append(comma + row.annotations[j].displayCharacter);
357                 comma = ",";
358               }
359             }
360             if (hasText)
361             {
362               if (row.annotations[j].description != null
363                       && row.annotations[j].description.length() > 0
364                       && !row.annotations[j].description
365                               .equals(row.annotations[j].displayCharacter))
366               {
367                 text.append(comma + row.annotations[j].description);
368                 comma = ",";
369               }
370             }
371             if (color != null && !color.equals(row.annotations[j].colour))
372             {
373               oneColour = false;
374             }
375
376             color = row.annotations[j].colour;
377
378             if (row.annotations[j].colour != null
379                     && row.annotations[j].colour != java.awt.Color.black)
380             {
381               text.append(comma
382                       + "["
383                       + jalview.util.Format
384                               .getHexString(row.annotations[j].colour)
385                       + "]");
386               comma = ",";
387             }
388           }
389           text.append("|");
390         }
391
392         if (row.hasScore())
393         {
394           text.append("\t" + row.score);
395         }
396
397         text.append(newline);
398
399         if (color != null && color != java.awt.Color.black && oneColour)
400         {
401           colours.append("COLOUR\t");
402           colours.append(row.label);
403           colours.append("\t");
404           colours.append(jalview.util.Format.getHexString(color));
405           colours.append(newline);
406         }
407         if (row.scaleColLabel || row.showAllColLabels
408                 || row.centreColLabels)
409         {
410           rowprops.append("ROWPROPERTIES\t");
411           rowprops.append(row.label);
412           rowprops.append("\tscaletofit=");
413           rowprops.append(row.scaleColLabel);
414           rowprops.append("\tshowalllabs=");
415           rowprops.append(row.showAllColLabels);
416           rowprops.append("\tcentrelabs=");
417           rowprops.append(row.centreColLabels);
418           rowprops.append(newline);
419         }
420         if (graphLine.length() > 0)
421         {
422           text.append(graphLine.toString());
423           graphLine.setLength(0);
424         }
425       }
426
427       text.append(newline);
428
429       text.append(colours.toString());
430       if (graphGroup.size() > 0)
431       {
432         SequenceI oldRefSeq = refSeq;
433         SequenceGroup oldRefGroup = refGroup;
434         for (Map.Entry<Integer, String> combine_statement : graphGroup
435                 .entrySet())
436         {
437           Object[] seqRefAndGroup = graphGroup_refs.get(combine_statement
438                   .getKey());
439
440           writeSequence_Ref(refSeq, (SequenceI) seqRefAndGroup[0]);
441           refSeq = (SequenceI) seqRefAndGroup[0];
442
443           writeGroup_Ref(refGroup, (SequenceGroup) seqRefAndGroup[1]);
444           refGroup = (SequenceGroup) seqRefAndGroup[1];
445           text.append("COMBINE\t");
446           text.append(combine_statement.getValue());
447           text.append(newline);
448         }
449         writeSequence_Ref(refSeq, oldRefSeq);
450         refSeq = oldRefSeq;
451
452         writeGroup_Ref(refGroup, oldRefGroup);
453         refGroup = oldRefGroup;
454       }
455       text.append(rowprops.toString());
456     }
457
458     if (list != null)
459     {
460       printGroups(list);
461     }
462
463     if (properties != null)
464     {
465       text.append(newline);
466       text.append(newline);
467       text.append("ALIGNMENT");
468       Enumeration en = properties.keys();
469       while (en.hasMoreElements())
470       {
471         String key = en.nextElement().toString();
472         text.append("\t");
473         text.append(key);
474         text.append("=");
475         text.append(properties.get(key));
476       }
477       // TODO: output alignment visualization settings here if required
478       // iterate through one or more views, defining, marking columns and rows
479       // as visible/hidden, and emmitting view properties.
480       // View specific annotation is
481     }
482
483     return text.toString();
484   }
485
486   private Object writeGroup_Ref(SequenceGroup refGroup,
487           SequenceGroup next_refGroup)
488   {
489     if (next_refGroup == null)
490     {
491
492       if (refGroup != null)
493       {
494         text.append(newline);
495         text.append("GROUP_REF\t");
496         text.append("ALIGNMENT");
497         text.append(newline);
498       }
499       return true;
500     }
501     else
502     {
503       if (refGroup == null || refGroup != next_refGroup)
504       {
505         text.append(newline);
506         text.append("GROUP_REF\t");
507         text.append(next_refGroup.getName());
508         text.append(newline);
509         return true;
510       }
511     }
512     return false;
513   }
514
515   private boolean writeSequence_Ref(SequenceI refSeq, SequenceI next_refSeq)
516   {
517
518     if (next_refSeq == null)
519     {
520       if (refSeq != null)
521       {
522         text.append(newline);
523         text.append("SEQUENCE_REF\t");
524         text.append("ALIGNMENT");
525         text.append(newline);
526         return true;
527       }
528     }
529     else
530     {
531       if (refSeq == null || refSeq != next_refSeq)
532       {
533         text.append(newline);
534         text.append("SEQUENCE_REF\t");
535         text.append(next_refSeq.getName());
536         text.append(newline);
537         return true;
538       }
539     }
540     return false;
541   }
542
543   public void printGroups(List<SequenceGroup> list)
544   {
545     SequenceI seqrep = null;
546     for (SequenceGroup sg : list)
547     {
548       if (!sg.hasSeqrep())
549       {
550         text.append("SEQUENCE_GROUP\t" + sg.getName() + "\t"
551                 + (sg.getStartRes() + 1) + "\t" + (sg.getEndRes() + 1)
552                 + "\t" + "-1\t");
553         seqrep = null;
554       }
555       else
556       {
557         seqrep = sg.getSeqrep();
558         text.append("SEQUENCE_REF\t");
559         text.append(seqrep.getName());
560         text.append(newline);
561         text.append("SEQUENCE_GROUP\t");
562         text.append(sg.getName());
563         text.append("\t");
564         text.append((seqrep.findPosition(sg.getStartRes())));
565         text.append("\t");
566         text.append((seqrep.findPosition(sg.getEndRes())));
567         text.append("\t");
568         text.append("-1\t");
569       }
570       for (int s = 0; s < sg.getSize(); s++)
571       {
572         text.append(sg.getSequenceAt(s).getName());
573         text.append("\t");
574       }
575       text.append(newline);
576       text.append("PROPERTIES\t");
577       text.append(sg.getName());
578       text.append("\t");
579
580       if (sg.getDescription() != null)
581       {
582         text.append("description=");
583         text.append(sg.getDescription());
584         text.append("\t");
585       }
586       if (sg.cs != null)
587       {
588         text.append("colour=");
589         text.append(ColourSchemeProperty.getColourName(sg.cs));
590         text.append("\t");
591         if (sg.cs.getThreshold() != 0)
592         {
593           text.append("pidThreshold=");
594           text.append(sg.cs.getThreshold());
595         }
596         if (sg.cs.conservationApplied())
597         {
598           text.append("consThreshold=");
599           text.append(sg.cs.getConservationInc());
600           text.append("\t");
601         }
602       }
603       text.append("outlineColour=");
604       text.append(jalview.util.Format.getHexString(sg.getOutlineColour()));
605       text.append("\t");
606
607       text.append("displayBoxes=");
608       text.append(sg.getDisplayBoxes());
609       text.append("\t");
610       text.append("displayText=");
611       text.append(sg.getDisplayText());
612       text.append("\t");
613       text.append("colourText=");
614       text.append(sg.getColourText());
615       text.append("\t");
616       text.append("showUnconserved=");
617       text.append(sg.getShowNonconserved());
618       text.append("\t");
619       if (sg.textColour != java.awt.Color.black)
620       {
621         text.append("textCol1=");
622         text.append(jalview.util.Format.getHexString(sg.textColour));
623         text.append("\t");
624       }
625       if (sg.textColour2 != java.awt.Color.white)
626       {
627         text.append("textCol2=");
628         text.append(jalview.util.Format.getHexString(sg.textColour2));
629         text.append("\t");
630       }
631       if (sg.thresholdTextColour != 0)
632       {
633         text.append("textColThreshold=");
634         text.append(sg.thresholdTextColour);
635         text.append("\t");
636       }
637       if (sg.idColour != null)
638       {
639         text.append("idColour=");
640         text.append(jalview.util.Format.getHexString(sg.idColour));
641         text.append("\t");
642       }
643       if (sg.isHidereps())
644       {
645         text.append("hide=true\t");
646       }
647       if (sg.isHideCols())
648       {
649         text.append("hidecols=true\t");
650       }
651       if (seqrep != null)
652       {
653         // terminate the last line and clear the sequence ref for the group
654         text.append(newline);
655         text.append("SEQUENCE_REF");
656       }
657       text.append(newline);
658       text.append(newline);
659
660     }
661   }
662
663   SequenceI refSeq = null;
664
665   String refSeqId = null;
666
667   public boolean annotateAlignmentView(AlignViewportI viewport,
668           String file, DataSourceType protocol)
669   {
670     ColumnSelection colSel = viewport.getColumnSelection();
671     if (colSel == null)
672     {
673       colSel = new ColumnSelection();
674     }
675     boolean rslt = readAnnotationFile(viewport.getAlignment(), colSel,
676             file, protocol);
677     if (rslt && (colSel.hasSelectedColumns() || colSel.hasHiddenColumns()))
678     {
679       viewport.setColumnSelection(colSel);
680     }
681
682     return rslt;
683   }
684
685   public boolean readAnnotationFile(AlignmentI al, String file,
686           DataSourceType sourceType)
687   {
688     return readAnnotationFile(al, null, file, sourceType);
689   }
690
691   public boolean readAnnotationFile(AlignmentI al, ColumnSelection colSel,
692           String file, DataSourceType sourceType)
693   {
694     baseUri = "";
695     BufferedReader in = null;
696     try
697     {
698       if (sourceType == DataSourceType.FILE)
699       {
700         in = new BufferedReader(new FileReader(file));
701         baseUri = new File(file).getParent();
702         if (baseUri == null)
703         {
704           baseUri = "";
705         }
706         else
707         {
708           baseUri += "/";
709         }
710       }
711       else if (sourceType == DataSourceType.URL)
712       {
713         URL url = new URL(file);
714         in = new BufferedReader(new InputStreamReader(url.openStream()));
715         String bs = url.toExternalForm();
716         baseUri = bs.substring(0, bs.indexOf(url.getHost())
717                 + url.getHost().length());
718         baseUri += url.toURI().getPath();
719         if (baseUri.lastIndexOf("/") > -1)
720         {
721           baseUri = baseUri.substring(0, baseUri.lastIndexOf("/")) + "/";
722         }
723       }
724       else if (sourceType == DataSourceType.PASTE)
725       {
726         in = new BufferedReader(new StringReader(file));
727         // TODO - support mimencoded PDBs for a paste.. ?
728         baseUri = "";
729       }
730       else if (sourceType == DataSourceType.CLASSLOADER)
731       {
732         java.io.InputStream is = getClass().getResourceAsStream("/" + file);
733         if (is != null)
734         {
735           in = new BufferedReader(new java.io.InputStreamReader(is));
736           // TODO: this probably doesn't work for classloader - needs a test
737           baseUri = new File("/" + file).getParent() + "/";
738         }
739       }
740       if (in != null)
741       {
742         return parseAnnotationFrom(al, colSel, in);
743       }
744
745     } catch (Exception ex)
746     {
747       ex.printStackTrace();
748       System.out.println("Problem reading annotation file: " + ex);
749       if (nlinesread > 0)
750       {
751         System.out.println("Last read line " + nlinesread + ": '"
752                 + lastread + "' (first 80 chars) ...");
753       }
754       return false;
755     }
756     return false;
757   }
758
759   long nlinesread = 0;
760
761   String lastread = "";
762
763   /**
764    * used for resolving absolute references to resources relative to
765    * annotationFile location
766    */
767   String baseUri = "";
768
769   private static String GRAPHLINE = "GRAPHLINE", COMBINE = "COMBINE",
770           STRUCTMODEL = "STRUCTMODEL";
771
772   public boolean parseAnnotationFrom(AlignmentI al, ColumnSelection colSel,
773           BufferedReader in) throws Exception
774   {
775     nlinesread = 0;
776     ArrayList<Object[]> combineAnnotation_calls = new ArrayList<Object[]>();
777     ArrayList<Object[]> deferredAnnotation_calls = new ArrayList<Object[]>();
778     boolean modified = false;
779     String groupRef = null;
780     Hashtable groupRefRows = new Hashtable();
781
782     Hashtable autoAnnots = new Hashtable();
783     {
784       String line, label, description, token;
785       int graphStyle, index;
786       int refSeqIndex = 1;
787       int existingAnnotations = 0;
788       // when true - will add new rows regardless of whether they are duplicate
789       // auto-annotation like consensus or conservation graphs
790       boolean overrideAutoAnnot = false;
791       if (al.getAlignmentAnnotation() != null)
792       {
793         existingAnnotations = al.getAlignmentAnnotation().length;
794         if (existingAnnotations > 0)
795         {
796           AlignmentAnnotation[] aa = al.getAlignmentAnnotation();
797           for (int aai = 0; aai < aa.length; aai++)
798           {
799             if (aa[aai].autoCalculated)
800             {
801               // make a note of the name and description
802               autoAnnots.put(
803                       autoAnnotsKey(aa[aai], aa[aai].sequenceRef,
804                               (aa[aai].groupRef == null ? null
805                                       : aa[aai].groupRef.getName())),
806                       new Integer(1));
807             }
808           }
809         }
810       }
811
812       int alWidth = al.getWidth();
813
814       StringTokenizer st;
815       Annotation[] annotations;
816       AlignmentAnnotation annotation = null;
817
818       // First confirm this is an Annotation file
819       boolean jvAnnotationFile = false;
820       while ((line = in.readLine()) != null)
821       {
822         nlinesread++;
823         lastread = new String(line);
824         if (line.indexOf("#") == 0)
825         {
826           continue;
827         }
828
829         if (line.indexOf("JALVIEW_ANNOTATION") > -1)
830         {
831           jvAnnotationFile = true;
832           break;
833         }
834       }
835
836       if (!jvAnnotationFile)
837       {
838         in.close();
839         return false;
840       }
841
842       while ((line = in.readLine()) != null)
843       {
844         nlinesread++;
845         lastread = new String(line);
846         if (line.indexOf("#") == 0
847                 || line.indexOf("JALVIEW_ANNOTATION") > -1
848                 || line.length() == 0)
849         {
850           continue;
851         }
852
853         st = new StringTokenizer(line, "\t");
854         token = st.nextToken();
855         if (token.equalsIgnoreCase("COLOUR"))
856         {
857           // TODO: use graduated colour def'n here too
858           colourAnnotations(al, st.nextToken(), st.nextToken());
859           modified = true;
860           continue;
861         }
862
863         else if (token.equalsIgnoreCase(COMBINE))
864         {
865           // keep a record of current state and resolve groupRef at end
866           combineAnnotation_calls
867                   .add(new Object[] { st, refSeq, groupRef });
868           modified = true;
869           continue;
870         }
871         else if (token.equalsIgnoreCase("ROWPROPERTIES"))
872         {
873           addRowProperties(al, st);
874           modified = true;
875           continue;
876         }
877         else if (token.equalsIgnoreCase(GRAPHLINE))
878         {
879           // resolve at end
880           deferredAnnotation_calls.add(new Object[] { GRAPHLINE, st,
881               refSeq, groupRef });
882           modified = true;
883           continue;
884         }
885
886         else if (token.equalsIgnoreCase("SEQUENCE_REF"))
887         {
888           if (st.hasMoreTokens())
889           {
890             refSeq = al.findName(refSeqId = st.nextToken());
891             if (refSeq == null)
892             {
893               refSeqId = null;
894             }
895             try
896             {
897               refSeqIndex = Integer.parseInt(st.nextToken());
898               if (refSeqIndex < 1)
899               {
900                 refSeqIndex = 1;
901                 System.out
902                         .println("WARNING: SEQUENCE_REF index must be > 0 in AnnotationFile");
903               }
904             } catch (Exception ex)
905             {
906               refSeqIndex = 1;
907             }
908           }
909           else
910           {
911             refSeq = null;
912             refSeqId = null;
913           }
914           continue;
915         }
916         else if (token.equalsIgnoreCase("GROUP_REF"))
917         {
918           // Group references could be forward or backwards, so they are
919           // resolved after the whole file is read in
920           groupRef = null;
921           if (st.hasMoreTokens())
922           {
923             groupRef = st.nextToken();
924             if (groupRef.length() < 1)
925             {
926               groupRef = null; // empty string
927             }
928             else
929             {
930               if (groupRefRows.get(groupRef) == null)
931               {
932                 groupRefRows.put(groupRef, new Vector());
933               }
934             }
935           }
936           continue;
937         }
938         else if (token.equalsIgnoreCase("SEQUENCE_GROUP"))
939         {
940           addGroup(al, st);
941           modified = true;
942           continue;
943         }
944
945         else if (token.equalsIgnoreCase("PROPERTIES"))
946         {
947           addProperties(al, st);
948           modified = true;
949           continue;
950         }
951
952         else if (token.equalsIgnoreCase("BELOW_ALIGNMENT"))
953         {
954           setBelowAlignment(al, st);
955           modified = true;
956           continue;
957         }
958         else if (token.equalsIgnoreCase("ALIGNMENT"))
959         {
960           addAlignmentDetails(al, st);
961           modified = true;
962           continue;
963         }
964         // else if (token.equalsIgnoreCase("VIEW_DEF"))
965         // {
966         // addOrSetView(al,st);
967         // modified = true;
968         // continue;
969         // }
970         else if (token.equalsIgnoreCase("VIEW_SETREF"))
971         {
972           if (refSeq != null)
973           {
974             al.setSeqrep(refSeq);
975           }
976           modified = true;
977           continue;
978         }
979         else if (token.equalsIgnoreCase("VIEW_HIDECOLS"))
980         {
981           if (st.hasMoreTokens())
982           {
983             if (colSel == null)
984             {
985               colSel = new ColumnSelection();
986             }
987             parseHideCols(colSel, st.nextToken());
988           }
989           modified = true;
990           continue;
991         }
992         else if (token.equalsIgnoreCase("HIDE_INSERTIONS"))
993         {
994           SequenceI sr = refSeq == null ? al.getSeqrep() : refSeq;
995           if (sr == null)
996           {
997             sr = al.getSequenceAt(0);
998           }
999           if (sr != null)
1000           {
1001             if (colSel == null)
1002             {
1003               System.err
1004                       .println("Cannot process HIDE_INSERTIONS without an alignment view: Ignoring line: "
1005                               + line);
1006             }
1007             else
1008             {
1009               // consider deferring this till after the file has been parsed ?
1010               colSel.hideInsertionsFor(sr);
1011             }
1012           }
1013           modified = true;
1014           continue;
1015         }
1016         else if (token.equalsIgnoreCase(STRUCTMODEL))
1017         {
1018           boolean failedtoadd = true;
1019           // expect
1020           // STRUCTMODEL <TemplateSeqId> <ModelFile> <FastaMappingFile>
1021           // <Confidence> <%.I.D>
1022           // <MatchStart> <MatchEnd> <Coverage> [<Other Information>]
1023           if (st.hasMoreTokens()) {
1024             refSeq = al.findName(refSeqId = st.nextToken());
1025             if (refSeq == null)
1026             {
1027               System.err.println("Couldn't locate " + refSeqId
1028                       + " in the alignment for STRUCTMODEL");
1029               refSeqId = null;
1030             }
1031             else
1032             {
1033               String tempId = st.nextToken();
1034               String fastaMapping = st.nextToken();
1035               String confidence = 100 * Double.valueOf(st.nextToken()) + "";
1036               String pid = st.nextToken();
1037               String alignRange = st.nextToken() + "-" + st.nextToken();
1038               String otherInfo = st.hasMoreTokens() ? st.nextToken() : "";
1039               String coverage = "";
1040               if (add_structmodel(al, refSeq, tempId, fastaMapping,
1041                       alignRange, coverage,
1042                       confidence, pid, otherInfo))
1043               {
1044                 failedtoadd = false;
1045               }
1046             }
1047           }
1048           if (failedtoadd)
1049           {
1050             System.err
1051                     .println("Need <TemplateSeqId> <ModelFile> <FastaMappingFile> <Confidence> <%.I.D> <MatchStart> <MatchEnd> <Coverage> [<Other Information>] as tab separated fields after"
1052                             + STRUCTMODEL
1053                             + ".\nNote: other information could be provided in html format ");
1054           } else {
1055             modified = true;
1056           }
1057           continue;
1058         }
1059         // Parse out the annotation row
1060         graphStyle = AlignmentAnnotation.getGraphValueFromString(token);
1061         label = st.nextToken();
1062
1063         index = 0;
1064         annotations = new Annotation[alWidth];
1065         description = null;
1066         float score = Float.NaN;
1067
1068         if (st.hasMoreTokens())
1069         {
1070           line = st.nextToken();
1071
1072           if (line.indexOf("|") == -1)
1073           {
1074             description = line;
1075             if (st.hasMoreTokens())
1076             {
1077               line = st.nextToken();
1078             }
1079           }
1080
1081           if (st.hasMoreTokens())
1082           {
1083             // This must be the score
1084             score = Float.valueOf(st.nextToken()).floatValue();
1085           }
1086
1087           st = new StringTokenizer(line, "|", true);
1088
1089           boolean emptyColumn = true;
1090           boolean onlyOneElement = (st.countTokens() == 1);
1091
1092           while (st.hasMoreElements() && index < alWidth)
1093           {
1094             token = st.nextToken().trim();
1095
1096             if (onlyOneElement)
1097             {
1098               try
1099               {
1100                 score = Float.valueOf(token).floatValue();
1101                 break;
1102               } catch (NumberFormatException ex)
1103               {
1104               }
1105             }
1106
1107             if (token.equals("|"))
1108             {
1109               if (emptyColumn)
1110               {
1111                 index++;
1112               }
1113
1114               emptyColumn = true;
1115             }
1116             else
1117             {
1118               annotations[index++] = parseAnnotation(token, graphStyle);
1119               emptyColumn = false;
1120             }
1121           }
1122
1123         }
1124
1125         annotation = new AlignmentAnnotation(label, description,
1126                 (index == 0) ? null : annotations, 0, 0, graphStyle);
1127
1128         annotation.score = score;
1129         if (!overrideAutoAnnot
1130                 && autoAnnots.containsKey(autoAnnotsKey(annotation, refSeq,
1131                         groupRef)))
1132         {
1133           // skip - we've already got an automatic annotation of this type.
1134           continue;
1135         }
1136         // otherwise add it!
1137         if (refSeq != null)
1138         {
1139
1140           annotation.belowAlignment = false;
1141           // make a copy of refSeq so we can find other matches in the alignment
1142           SequenceI referedSeq = refSeq;
1143           do
1144           {
1145             // copy before we do any mapping business.
1146             // TODO: verify that undo/redo with 1:many sequence associated
1147             // annotations can be undone correctly
1148             AlignmentAnnotation ann = new AlignmentAnnotation(annotation);
1149             annotation
1150                     .createSequenceMapping(referedSeq, refSeqIndex, false);
1151             annotation.adjustForAlignment();
1152             referedSeq.addAlignmentAnnotation(annotation);
1153             al.addAnnotation(annotation);
1154             al.setAnnotationIndex(annotation,
1155                     al.getAlignmentAnnotation().length
1156                             - existingAnnotations - 1);
1157             if (groupRef != null)
1158             {
1159               ((Vector) groupRefRows.get(groupRef)).addElement(annotation);
1160             }
1161             // and recover our virgin copy to use again if necessary.
1162             annotation = ann;
1163
1164           } while (refSeqId != null
1165                   && (referedSeq = al.findName(referedSeq, refSeqId, true)) != null);
1166         }
1167         else
1168         {
1169           al.addAnnotation(annotation);
1170           al.setAnnotationIndex(annotation,
1171                   al.getAlignmentAnnotation().length - existingAnnotations
1172                           - 1);
1173           if (groupRef != null)
1174           {
1175             ((Vector) groupRefRows.get(groupRef)).addElement(annotation);
1176           }
1177         }
1178         // and set modification flag
1179         modified = true;
1180       }
1181       // Resolve the groupRefs
1182       Hashtable<String, SequenceGroup> groupRefLookup = new Hashtable<String, SequenceGroup>();
1183       Enumeration en = groupRefRows.keys();
1184
1185       while (en.hasMoreElements())
1186       {
1187         groupRef = (String) en.nextElement();
1188         boolean matched = false;
1189         // Resolve group: TODO: add a getGroupByName method to alignments
1190         for (SequenceGroup theGroup : al.getGroups())
1191         {
1192           if (theGroup.getName().equals(groupRef))
1193           {
1194             if (matched)
1195             {
1196               // TODO: specify and implement duplication of alignment annotation
1197               // for multiple group references.
1198               System.err
1199                       .println("Ignoring 1:many group reference mappings for group name '"
1200                               + groupRef + "'");
1201             }
1202             else
1203             {
1204               matched = true;
1205               Vector rowset = (Vector) groupRefRows.get(groupRef);
1206               groupRefLookup.put(groupRef, theGroup);
1207               if (rowset != null && rowset.size() > 0)
1208               {
1209                 AlignmentAnnotation alan = null;
1210                 for (int elm = 0, elmSize = rowset.size(); elm < elmSize; elm++)
1211                 {
1212                   alan = (AlignmentAnnotation) rowset.elementAt(elm);
1213                   alan.groupRef = theGroup;
1214                 }
1215               }
1216             }
1217           }
1218         }
1219         ((Vector) groupRefRows.get(groupRef)).removeAllElements();
1220       }
1221       // process any deferred attribute settings for each context
1222       for (Object[] _deferred_args : deferredAnnotation_calls)
1223       {
1224         if (_deferred_args[0] == GRAPHLINE)
1225         {
1226           addLine(al,
1227                   (StringTokenizer) _deferred_args[1], // st
1228                   (SequenceI) _deferred_args[2], // refSeq
1229                   (_deferred_args[3] == null) ? null : groupRefLookup
1230                           .get(_deferred_args[3]) // the reference
1231                                                   // group, or null
1232           );
1233         }
1234       }
1235
1236       // finally, combine all the annotation rows within each context.
1237       /**
1238        * number of combine statements in this annotation file. Used to create
1239        * new groups for combined annotation graphs without disturbing existing
1240        * ones
1241        */
1242       int combinecount = 0;
1243       for (Object[] _combine_args : combineAnnotation_calls)
1244       {
1245         combineAnnotations(al,
1246                 ++combinecount,
1247                 (StringTokenizer) _combine_args[0], // st
1248                 (SequenceI) _combine_args[1], // refSeq
1249                 (_combine_args[2] == null) ? null : groupRefLookup
1250                         .get(_combine_args[2]) // the reference group,
1251                                                // or null
1252         );
1253       }
1254     }
1255     return modified;
1256   }
1257
1258   /**
1259    * resolve a structural model and generate and add an alignment sequence for
1260    * it
1261    * 
1262    * @param refSeq2
1263    * @param tempId
1264    * @param urlToModel
1265    * @param urlToPairwise
1266    * @return true if model and sequence was added
1267    */
1268   private boolean add_structmodel(AlignmentI al, SequenceI refSeq,
1269           String modelFile, String fastaFile, String aRange,
1270           String coverage, String confidence,
1271           String pid, String otherInfo)
1272   {
1273     String warningMessage = null;
1274     boolean added = false;
1275     try {
1276       String structureModelFile = resolveAbsolute(modelFile);
1277       String fastaMappingFile = resolveAbsolute(fastaFile);
1278       // System.out.println("Model File >> " + fastaMappingFile);
1279       // System.out.println("Fasta File >> " + structureModelFile);
1280       PDBEntry phyre2PDBEntry = new PDBEntry(modelFile, null, Type.FILE,
1281               structureModelFile);
1282       String phyre2ModelDesc = generatePhyre2InfoHTMLTable(aRange,
1283               coverage, confidence, pid, otherInfo);
1284       phyre2PDBEntry.setProperty("PHYRE2_MODEL_INFO", phyre2ModelDesc);
1285       refSeq.getDatasetSequence().addPDBId(phyre2PDBEntry);
1286       StructureSelectionManager ssm = StructureSelectionManager
1287               .getStructureSelectionManager(Desktop.instance);
1288       ssm.registerPhyre2Template(structureModelFile, fastaMappingFile);
1289       added = true;
1290
1291     } catch (Exception x)
1292     {
1293       warningMessage = x.toString();
1294     } finally {
1295       if (warningMessage !=null)
1296       {
1297         System.err.println("Warnings whilst processing STRUCTMODEL: "+warningMessage);
1298       }
1299     }
1300     return added;
1301   }
1302
1303   private String generatePhyre2InfoHTMLTable(String aRange,
1304           String coverage, String confidence, String pid, String otherInfo)
1305   {
1306     StringBuilder phyre2InfoBuilder = new StringBuilder();
1307     phyre2InfoBuilder.append("<html><table border=\"1\" width=100%>");
1308     phyre2InfoBuilder
1309             .append("<tr><td colspan=\"2\"><strong>Phyre2 Template Info</strong></td></tr>");
1310     if (aRange != null && !aRange.isEmpty())
1311     {
1312       phyre2InfoBuilder.append("<tr><td>").append("Aligned range")
1313               .append("</td><td>").append(aRange).append("</td></tr>");
1314     }
1315     if (coverage != null && !coverage.isEmpty())
1316     {
1317       phyre2InfoBuilder.append("<tr><td>").append("Coverage")
1318               .append("</td><td>").append(coverage).append("</td></tr>");
1319     }
1320     if (confidence != null && !confidence.isEmpty())
1321     {
1322       phyre2InfoBuilder.append("<tr><td>").append("Confidence")
1323               .append("</td><td>").append(confidence).append("</td></tr>");
1324     }
1325     if (pid != null && !pid.isEmpty())
1326     {
1327       phyre2InfoBuilder.append("<tr><td>").append("%.i.d")
1328               .append("</td><td>").append(pid).append("</td></tr>");
1329     }
1330     if (otherInfo != null && !otherInfo.isEmpty())
1331     {
1332       phyre2InfoBuilder.append("<tr><td>").append("Other information")
1333               .append("</td><td>").append(otherInfo).append("</td></tr>");
1334     }
1335     phyre2InfoBuilder.append("</table></html>");
1336     return phyre2InfoBuilder.toString();
1337   }
1338
1339   private String resolveAbsolute(String relURI)
1340   {
1341     if (relURI.indexOf(":/") > -1 || relURI.startsWith("/")
1342             || "".equals(baseUri) || relURI.startsWith(baseUri))
1343     {
1344       return relURI;
1345     }
1346     return baseUri + relURI;
1347   }
1348
1349   private void parseHideCols(ColumnSelection colSel, String nextToken)
1350   {
1351     StringTokenizer inval = new StringTokenizer(nextToken, ",");
1352     while (inval.hasMoreTokens())
1353     {
1354       String range = inval.nextToken().trim();
1355       int from, to = range.indexOf("-");
1356       if (to == -1)
1357       {
1358         from = to = Integer.parseInt(range);
1359         if (from >= 0)
1360         {
1361           colSel.hideColumns(from, to);
1362         }
1363       }
1364       else
1365       {
1366         from = Integer.parseInt(range.substring(0, to));
1367         if (to < range.length() - 1)
1368         {
1369           to = Integer.parseInt(range.substring(to + 1));
1370         }
1371         else
1372         {
1373           to = from;
1374         }
1375         if (from > 0 && to >= from)
1376         {
1377           colSel.hideColumns(from, to);
1378         }
1379       }
1380     }
1381   }
1382
1383   private Object autoAnnotsKey(AlignmentAnnotation annotation,
1384           SequenceI refSeq, String groupRef)
1385   {
1386     return annotation.graph + "\t" + annotation.label + "\t"
1387             + annotation.description + "\t"
1388             + (refSeq != null ? refSeq.getDisplayId(true) : "");
1389   }
1390
1391   Annotation parseAnnotation(String string, int graphStyle)
1392   {
1393     boolean hasSymbols = (graphStyle == AlignmentAnnotation.NO_GRAPH); // don't
1394     // do the
1395     // glyph
1396     // test
1397     // if we
1398     // don't
1399     // want
1400     // secondary
1401     // structure
1402     String desc = null, displayChar = null;
1403     char ss = ' '; // secondaryStructure
1404     float value = 0;
1405     boolean parsedValue = false, dcset = false;
1406
1407     // find colour here
1408     java.awt.Color colour = null;
1409     int i = string.indexOf("[");
1410     int j = string.indexOf("]");
1411     if (i > -1 && j > -1)
1412     {
1413       UserColourScheme ucs = new UserColourScheme();
1414
1415       colour = ucs.getColourFromString(string.substring(i + 1, j));
1416       if (i > 0 && string.charAt(i - 1) == ',')
1417       {
1418         // clip the preceding comma as well
1419         i--;
1420       }
1421       string = string.substring(0, i) + string.substring(j + 1);
1422     }
1423
1424     StringTokenizer st = new StringTokenizer(string, ",", true);
1425     String token;
1426     boolean seenContent = false;
1427     int pass = 0;
1428     while (st.hasMoreTokens())
1429     {
1430       pass++;
1431       token = st.nextToken().trim();
1432       if (token.equals(","))
1433       {
1434         if (!seenContent && parsedValue && !dcset)
1435         {
1436           // allow the value below the bar/line to be empty
1437           dcset = true;
1438           displayChar = " ";
1439         }
1440         seenContent = false;
1441         continue;
1442       }
1443       else
1444       {
1445         seenContent = true;
1446       }
1447
1448       if (!parsedValue)
1449       {
1450         try
1451         {
1452           displayChar = token;
1453           // foo
1454           value = new Float(token).floatValue();
1455           parsedValue = true;
1456           continue;
1457         } catch (NumberFormatException ex)
1458         {
1459         }
1460       }
1461       else
1462       {
1463         if (token.length() == 1)
1464         {
1465           displayChar = token;
1466         }
1467       }
1468       if (hasSymbols
1469               && (token.length() == 1 && "()<>[]{}AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz"
1470                       .contains(token)))
1471       {
1472         // Either this character represents a helix or sheet
1473         // or an integer which can be displayed
1474         ss = token.charAt(0);
1475         if (displayChar.equals(token.substring(0, 1)))
1476         {
1477           displayChar = "";
1478         }
1479       }
1480       else if (desc == null || (parsedValue && pass > 2))
1481       {
1482         desc = token;
1483       }
1484
1485     }
1486     // if (!dcset && string.charAt(string.length() - 1) == ',')
1487     // {
1488     // displayChar = " "; // empty display char symbol.
1489     // }
1490     if (displayChar != null && desc != null && desc.length() == 1)
1491     {
1492       if (displayChar.length() > 1)
1493       {
1494         // switch desc and displayChar - legacy support
1495         String tmp = displayChar;
1496         displayChar = desc;
1497         desc = tmp;
1498       }
1499       else
1500       {
1501         if (displayChar.equals(desc))
1502         {
1503           // duplicate label - hangover from the 'robust parser' above
1504           desc = null;
1505         }
1506       }
1507     }
1508     Annotation anot = new Annotation(displayChar, desc, ss, value);
1509
1510     anot.colour = colour;
1511
1512     return anot;
1513   }
1514
1515   void colourAnnotations(AlignmentI al, String label, String colour)
1516   {
1517     UserColourScheme ucs = new UserColourScheme(colour);
1518     Annotation[] annotations;
1519     for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1520     {
1521       if (al.getAlignmentAnnotation()[i].label.equalsIgnoreCase(label))
1522       {
1523         annotations = al.getAlignmentAnnotation()[i].annotations;
1524         for (int j = 0; j < annotations.length; j++)
1525         {
1526           if (annotations[j] != null)
1527           {
1528             annotations[j].colour = ucs.findColour('A');
1529           }
1530         }
1531       }
1532     }
1533   }
1534
1535   void combineAnnotations(AlignmentI al, int combineCount,
1536           StringTokenizer st, SequenceI seqRef, SequenceGroup groupRef)
1537   {
1538     String group = st.nextToken();
1539     // First make sure we are not overwriting the graphIndex
1540     int graphGroup = 0;
1541     if (al.getAlignmentAnnotation() != null)
1542     {
1543       for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1544       {
1545         AlignmentAnnotation aa = al.getAlignmentAnnotation()[i];
1546
1547         if (aa.graphGroup > graphGroup)
1548         {
1549           // try to number graphGroups in order of occurence.
1550           graphGroup = aa.graphGroup + 1;
1551         }
1552         if (aa.sequenceRef == seqRef && aa.groupRef == groupRef
1553                 && aa.label.equalsIgnoreCase(group))
1554         {
1555           if (aa.graphGroup > -1)
1556           {
1557             graphGroup = aa.graphGroup;
1558           }
1559           else
1560           {
1561             if (graphGroup <= combineCount)
1562             {
1563               graphGroup = combineCount + 1;
1564             }
1565             aa.graphGroup = graphGroup;
1566           }
1567           break;
1568         }
1569       }
1570
1571       // Now update groups
1572       while (st.hasMoreTokens())
1573       {
1574         group = st.nextToken();
1575         for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1576         {
1577           AlignmentAnnotation aa = al.getAlignmentAnnotation()[i];
1578           if (aa.sequenceRef == seqRef && aa.groupRef == groupRef
1579                   && aa.label.equalsIgnoreCase(group))
1580           {
1581             aa.graphGroup = graphGroup;
1582             break;
1583           }
1584         }
1585       }
1586     }
1587     else
1588     {
1589       System.err
1590               .println("Couldn't combine annotations. None are added to alignment yet!");
1591     }
1592   }
1593
1594   void addLine(AlignmentI al, StringTokenizer st, SequenceI seqRef,
1595           SequenceGroup groupRef)
1596   {
1597     String group = st.nextToken();
1598     AlignmentAnnotation annotation = null, alannot[] = al
1599             .getAlignmentAnnotation();
1600     float value = new Float(st.nextToken()).floatValue();
1601     String label = st.hasMoreTokens() ? st.nextToken() : null;
1602     java.awt.Color colour = null;
1603     if (st.hasMoreTokens())
1604     {
1605       UserColourScheme ucs = new UserColourScheme(st.nextToken());
1606       colour = ucs.findColour('A');
1607     }
1608     if (alannot != null)
1609     {
1610       for (int i = 0; i < alannot.length; i++)
1611       {
1612         if (alannot[i].label.equalsIgnoreCase(group)
1613                 && (seqRef == null || alannot[i].sequenceRef == seqRef)
1614                 && (groupRef == null || alannot[i].groupRef == groupRef))
1615         {
1616           alannot[i].setThreshold(new GraphLine(value, label, colour));
1617         }
1618       }
1619     }
1620     if (annotation == null)
1621     {
1622       return;
1623     }
1624   }
1625
1626   void addGroup(AlignmentI al, StringTokenizer st)
1627   {
1628     SequenceGroup sg = new SequenceGroup();
1629     sg.setName(st.nextToken());
1630     String rng = "";
1631     try
1632     {
1633       rng = st.nextToken();
1634       if (rng.length() > 0 && !rng.startsWith("*"))
1635       {
1636         sg.setStartRes(Integer.parseInt(rng) - 1);
1637       }
1638       else
1639       {
1640         sg.setStartRes(0);
1641       }
1642       rng = st.nextToken();
1643       if (rng.length() > 0 && !rng.startsWith("*"))
1644       {
1645         sg.setEndRes(Integer.parseInt(rng) - 1);
1646       }
1647       else
1648       {
1649         sg.setEndRes(al.getWidth() - 1);
1650       }
1651     } catch (Exception e)
1652     {
1653       System.err
1654               .println("Couldn't parse Group Start or End Field as '*' or a valid column or sequence index: '"
1655                       + rng + "' - assuming alignment width for group.");
1656       // assume group is full width
1657       sg.setStartRes(0);
1658       sg.setEndRes(al.getWidth() - 1);
1659     }
1660
1661     String index = st.nextToken();
1662     if (index.equals("-1"))
1663     {
1664       while (st.hasMoreElements())
1665       {
1666         sg.addSequence(al.findName(st.nextToken()), false);
1667       }
1668     }
1669     else
1670     {
1671       StringTokenizer st2 = new StringTokenizer(index, ",");
1672
1673       while (st2.hasMoreTokens())
1674       {
1675         String tmp = st2.nextToken();
1676         if (tmp.equals("*"))
1677         {
1678           for (int i = 0; i < al.getHeight(); i++)
1679           {
1680             sg.addSequence(al.getSequenceAt(i), false);
1681           }
1682         }
1683         else if (tmp.indexOf("-") >= 0)
1684         {
1685           StringTokenizer st3 = new StringTokenizer(tmp, "-");
1686
1687           int start = (Integer.parseInt(st3.nextToken()));
1688           int end = (Integer.parseInt(st3.nextToken()));
1689
1690           if (end > start)
1691           {
1692             for (int i = start; i <= end; i++)
1693             {
1694               sg.addSequence(al.getSequenceAt(i - 1), false);
1695             }
1696           }
1697         }
1698         else
1699         {
1700           sg.addSequence(al.getSequenceAt(Integer.parseInt(tmp) - 1), false);
1701         }
1702       }
1703     }
1704
1705     if (refSeq != null)
1706     {
1707       sg.setStartRes(refSeq.findIndex(sg.getStartRes() + 1) - 1);
1708       sg.setEndRes(refSeq.findIndex(sg.getEndRes() + 1) - 1);
1709       sg.setSeqrep(refSeq);
1710     }
1711
1712     if (sg.getSize() > 0)
1713     {
1714       al.addGroup(sg);
1715     }
1716   }
1717
1718   void addRowProperties(AlignmentI al, StringTokenizer st)
1719   {
1720     String label = st.nextToken(), keyValue, key, value;
1721     boolean scaletofit = false, centerlab = false, showalllabs = false;
1722     while (st.hasMoreTokens())
1723     {
1724       keyValue = st.nextToken();
1725       key = keyValue.substring(0, keyValue.indexOf("="));
1726       value = keyValue.substring(keyValue.indexOf("=") + 1);
1727       if (key.equalsIgnoreCase("scaletofit"))
1728       {
1729         scaletofit = Boolean.valueOf(value).booleanValue();
1730       }
1731       if (key.equalsIgnoreCase("showalllabs"))
1732       {
1733         showalllabs = Boolean.valueOf(value).booleanValue();
1734       }
1735       if (key.equalsIgnoreCase("centrelabs"))
1736       {
1737         centerlab = Boolean.valueOf(value).booleanValue();
1738       }
1739       AlignmentAnnotation[] alr = al.getAlignmentAnnotation();
1740       if (alr != null)
1741       {
1742         for (int i = 0; i < alr.length; i++)
1743         {
1744           if (alr[i].label.equalsIgnoreCase(label))
1745           {
1746             alr[i].centreColLabels = centerlab;
1747             alr[i].scaleColLabel = scaletofit;
1748             alr[i].showAllColLabels = showalllabs;
1749           }
1750         }
1751       }
1752     }
1753   }
1754
1755   void addProperties(AlignmentI al, StringTokenizer st)
1756   {
1757
1758     // So far we have only added groups to the annotationHash,
1759     // the idea is in the future properties can be added to
1760     // alignments, other annotations etc
1761     if (al.getGroups() == null)
1762     {
1763       return;
1764     }
1765
1766     String name = st.nextToken();
1767     SequenceGroup sg = null;
1768     for (SequenceGroup _sg : al.getGroups())
1769     {
1770       if ((sg = _sg).getName().equals(name))
1771       {
1772         break;
1773       }
1774       else
1775       {
1776         sg = null;
1777       }
1778     }
1779
1780     if (sg != null)
1781     {
1782       String keyValue, key, value;
1783       ColourSchemeI def = sg.cs;
1784       sg.cs = null;
1785       while (st.hasMoreTokens())
1786       {
1787         keyValue = st.nextToken();
1788         key = keyValue.substring(0, keyValue.indexOf("="));
1789         value = keyValue.substring(keyValue.indexOf("=") + 1);
1790
1791         if (key.equalsIgnoreCase("description"))
1792         {
1793           sg.setDescription(value);
1794         }
1795         else if (key.equalsIgnoreCase("colour"))
1796         {
1797           sg.cs = ColourSchemeProperty.getColour(al, value);
1798         }
1799         else if (key.equalsIgnoreCase("pidThreshold"))
1800         {
1801           sg.cs.setThreshold(Integer.parseInt(value), true);
1802
1803         }
1804         else if (key.equalsIgnoreCase("consThreshold"))
1805         {
1806           sg.cs.setConservationInc(Integer.parseInt(value));
1807           Conservation c = new Conservation("Group", sg.getSequences(null),
1808                   sg.getStartRes(), sg.getEndRes() + 1);
1809
1810           c.calculate();
1811           c.verdict(false, 25); // TODO: refer to conservation percent threshold
1812
1813           sg.cs.setConservation(c);
1814
1815         }
1816         else if (key.equalsIgnoreCase("outlineColour"))
1817         {
1818           sg.setOutlineColour(new UserColourScheme(value).findColour('A'));
1819         }
1820         else if (key.equalsIgnoreCase("displayBoxes"))
1821         {
1822           sg.setDisplayBoxes(Boolean.valueOf(value).booleanValue());
1823         }
1824         else if (key.equalsIgnoreCase("showUnconserved"))
1825         {
1826           sg.setShowNonconserved(Boolean.valueOf(value).booleanValue());
1827         }
1828         else if (key.equalsIgnoreCase("displayText"))
1829         {
1830           sg.setDisplayText(Boolean.valueOf(value).booleanValue());
1831         }
1832         else if (key.equalsIgnoreCase("colourText"))
1833         {
1834           sg.setColourText(Boolean.valueOf(value).booleanValue());
1835         }
1836         else if (key.equalsIgnoreCase("textCol1"))
1837         {
1838           sg.textColour = new UserColourScheme(value).findColour('A');
1839         }
1840         else if (key.equalsIgnoreCase("textCol2"))
1841         {
1842           sg.textColour2 = new UserColourScheme(value).findColour('A');
1843         }
1844         else if (key.equalsIgnoreCase("textColThreshold"))
1845         {
1846           sg.thresholdTextColour = Integer.parseInt(value);
1847         }
1848         else if (key.equalsIgnoreCase("idColour"))
1849         {
1850           // consider warning if colour doesn't resolve to a real colour
1851           sg.setIdColour((def = new UserColourScheme(value))
1852                   .findColour('A'));
1853         }
1854         else if (key.equalsIgnoreCase("hide"))
1855         {
1856           // see bug https://mantis.lifesci.dundee.ac.uk/view.php?id=25847
1857           sg.setHidereps(true);
1858         }
1859         else if (key.equalsIgnoreCase("hidecols"))
1860         {
1861           // see bug https://mantis.lifesci.dundee.ac.uk/view.php?id=25847
1862           sg.setHideCols(true);
1863         }
1864         sg.recalcConservation();
1865       }
1866       if (sg.cs == null)
1867       {
1868         sg.cs = def;
1869       }
1870     }
1871   }
1872
1873   void setBelowAlignment(AlignmentI al, StringTokenizer st)
1874   {
1875     String token;
1876     AlignmentAnnotation aa, ala[] = al.getAlignmentAnnotation();
1877     if (ala == null)
1878     {
1879       System.err
1880               .print("Warning - no annotation to set below for sequence associated annotation:");
1881     }
1882     while (st.hasMoreTokens())
1883     {
1884       token = st.nextToken();
1885       if (ala == null)
1886       {
1887         System.err.print(" " + token);
1888       }
1889       else
1890       {
1891         for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1892         {
1893           aa = al.getAlignmentAnnotation()[i];
1894           if (aa.sequenceRef == refSeq && aa.label.equals(token))
1895           {
1896             aa.belowAlignment = true;
1897           }
1898         }
1899       }
1900     }
1901     if (ala == null)
1902     {
1903       System.err.print("\n");
1904     }
1905   }
1906
1907   void addAlignmentDetails(AlignmentI al, StringTokenizer st)
1908   {
1909     String keyValue, key, value;
1910     while (st.hasMoreTokens())
1911     {
1912       keyValue = st.nextToken();
1913       key = keyValue.substring(0, keyValue.indexOf("="));
1914       value = keyValue.substring(keyValue.indexOf("=") + 1);
1915       al.setProperty(key, value);
1916     }
1917   }
1918
1919   /**
1920    * Write annotations as a CSV file of the form 'label, value, value, ...' for
1921    * each row.
1922    * 
1923    * @param annotations
1924    * @return CSV file as a string.
1925    */
1926   public String printCSVAnnotations(AlignmentAnnotation[] annotations)
1927   {
1928     if (annotations == null)
1929     {
1930       return "";
1931     }
1932     StringBuffer sp = new StringBuffer();
1933     for (int i = 0; i < annotations.length; i++)
1934     {
1935       String atos = annotations[i].toString();
1936       int p = 0;
1937       do
1938       {
1939         int cp = atos.indexOf("\n", p);
1940         sp.append(annotations[i].label);
1941         sp.append(",");
1942         if (cp > p)
1943         {
1944           sp.append(atos.substring(p, cp + 1));
1945         }
1946         else
1947         {
1948           sp.append(atos.substring(p));
1949           sp.append(newline);
1950         }
1951         p = cp + 1;
1952       } while (p > 0);
1953     }
1954     return sp.toString();
1955   }
1956
1957   public String printAnnotationsForView(AlignViewportI viewport)
1958   {
1959     return printAnnotations(viewport.isShowAnnotation() ? viewport
1960             .getAlignment().getAlignmentAnnotation() : null, viewport
1961             .getAlignment().getGroups(), viewport.getAlignment()
1962             .getProperties(), viewport.getColumnSelection(),
1963             viewport.getAlignment(), null);
1964   }
1965
1966   public String printAnnotationsForAlignment(AlignmentI al)
1967   {
1968     return printAnnotations(al.getAlignmentAnnotation(), al.getGroups(),
1969             al.getProperties(), null, al, null);
1970   }
1971 }