a4bc6311ac26e2bbe072cc975b4f8427b40cde6a
[jalview.git] / src / jalview / io / StockholmFile.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 /*
22  * This extension was written by Benjamin Schuster-Boeckler at sanger.ac.uk
23  */
24 package jalview.io;
25
26 import jalview.analysis.Rna;
27 import jalview.datamodel.AlignmentAnnotation;
28 import jalview.datamodel.AlignmentI;
29 import jalview.datamodel.Annotation;
30 import jalview.datamodel.DBRefEntry;
31 import jalview.datamodel.DBRefSource;
32 import jalview.datamodel.Mapping;
33 import jalview.datamodel.Sequence;
34 import jalview.datamodel.SequenceFeature;
35 import jalview.datamodel.SequenceI;
36 import jalview.schemes.ResidueProperties;
37 import jalview.util.Comparison;
38 import jalview.util.DBRefUtils;
39 import jalview.util.Format;
40 import jalview.util.MessageManager;
41 import jalview.util.Platform;
42
43 import java.io.BufferedReader;
44 import java.io.FileReader;
45 import java.io.IOException;
46 import java.util.ArrayList;
47 import java.util.Enumeration;
48 import java.util.Hashtable;
49 import java.util.LinkedHashMap;
50 import java.util.List;
51 import java.util.Locale;
52 import java.util.Map;
53 import java.util.Vector;
54
55 import com.stevesoft.pat.Regex;
56
57 import fr.orsay.lri.varna.exceptions.ExceptionUnmatchedClosingParentheses;
58 import fr.orsay.lri.varna.factories.RNAFactory;
59 import fr.orsay.lri.varna.models.rna.RNA;
60
61 /**
62  * This class is supposed to parse a Stockholm format file into Jalview There
63  * are TODOs in this class: we do not know what the database source and version
64  * is for the file when parsing the #GS= AC tag which associates accessions with
65  * sequences. Database references are also not parsed correctly: a separate
66  * reference string parser must be added to parse the database reference form
67  * into Jalview's local representation.
68  * 
69  * @author bsb at sanger.ac.uk
70  * @author Natasha Shersnev (Dundee, UK) (Stockholm file writer)
71  * @author Lauren Lui (UCSC, USA) (RNA secondary structure annotation import as
72  *         stockholm)
73  * @author Anne Menard (Paris, FR) (VARNA parsing of Stockholm file data)
74  * @version 0.3 + jalview mods
75  * 
76  */
77 public class StockholmFile extends AlignFile
78 {
79   private static final String ANNOTATION = "annotation";
80
81   private static final char UNDERSCORE = '_';
82   
83   // WUSS extended symbols. Avoid ambiguity with protein SS annotations by using NOT_RNASS first.
84
85   public static final String RNASS_BRACKETS = "<>[](){}AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz";
86
87   public static final int REGEX_STOCKHOLM = 0;
88
89   public static final int REGEX_BRACKETS = 1;
90   // use the following regex to decide an annotations (whole) line is NOT an RNA
91   // SS (it contains only E,H,e,h and other non-brace/non-alpha chars)
92   public static final int REGEX_NOT_RNASS = 2;
93
94   private static final int REGEX_ANNOTATION = 3;
95
96   private static final int REGEX_PFAM = 4;
97
98   private static final int REGEX_RFAM = 5;
99
100   private static final int REGEX_ALIGN_END = 6;
101
102   private static final int REGEX_SPLIT_ID = 7;
103
104   private static final int REGEX_SUBTYPE = 8;
105
106   private static final int REGEX_ANNOTATION_LINE = 9;
107
108   private static final int REGEX_REMOVE_ID = 10;
109
110   private static final int REGEX_OPEN_PAREN = 11;
111
112   private static final int REGEX_CLOSE_PAREN = 12;
113
114   public static final int REGEX_MAX = 13;
115
116   private static Regex REGEX[] = new Regex[REGEX_MAX];
117
118   /**
119    * Centralize all actual Regex instantialization in Platform.
120    * // JBPNote: Why is this 'centralisation' better ?
121    * @param id
122    * @return
123    */
124   private static Regex getRegex(int id)
125   {
126     if (REGEX[id] == null)
127     {
128       String pat = null, pat2 = null;
129       switch (id)
130       {
131       case REGEX_STOCKHOLM:
132         pat = "# STOCKHOLM ([\\d\\.]+)";
133         break;
134       case REGEX_BRACKETS:
135         // for reference; not used
136         pat = "(<|>|\\[|\\]|\\(|\\)|\\{|\\})";
137         break;
138       case REGEX_NOT_RNASS:
139         pat = "^[^<>[\\](){}ADFJ-RUVWYZadfj-ruvwyz]*$"; // update 2.11.2
140         break;
141       case REGEX_ANNOTATION:
142         pat = "(\\w+)\\s*(.*)";
143         break;
144       case REGEX_PFAM:
145         pat = "PF[0-9]{5}(.*)";
146         break;
147       case REGEX_RFAM:
148         pat = "RF[0-9]{5}(.*)";
149         break;
150       case REGEX_ALIGN_END:
151         pat = "^\\s*\\/\\/";
152         break;
153       case REGEX_SPLIT_ID:
154         pat = "(\\S+)\\/(\\d+)\\-(\\d+)";
155         break;
156       case REGEX_SUBTYPE:
157         pat = "(\\S+)\\s+(\\S*)\\s+(.*)";
158         break;
159       case REGEX_ANNOTATION_LINE:
160         pat = "#=(G[FSRC]?)\\s+(.*)";
161         break;
162       case REGEX_REMOVE_ID:
163         pat = "(\\S+)\\s+(\\S+)";
164         break;
165       case REGEX_OPEN_PAREN:
166         pat = "(<|\\[)";
167         pat2 = "(";
168         break;
169       case REGEX_CLOSE_PAREN:
170         pat = "(>|\\])";
171         pat2 = ")";
172         break;
173       default:
174         return null;
175       }
176       REGEX[id] = Platform.newRegex(pat, pat2);
177     }
178     return REGEX[id];
179   }
180
181   StringBuffer out; // output buffer
182
183   private AlignmentI al;
184
185   public StockholmFile()
186   {
187   }
188
189   /**
190    * Creates a new StockholmFile object for output
191    */
192   public StockholmFile(AlignmentI al)
193   {
194     this.al = al;
195   }
196
197   public StockholmFile(String inFile, DataSourceType type)
198           throws IOException
199   {
200     super(inFile, type);
201   }
202
203   public StockholmFile(FileParse source) throws IOException
204   {
205     super(source);
206   }
207
208   @Override
209   public void initData()
210   {
211     super.initData();
212   }
213
214   /**
215    * Parse a file in Stockholm format into Jalview's data model using VARNA
216    * 
217    * @throws IOException
218    *           If there is an error with the input file
219    */
220   public void parse_with_VARNA(java.io.File inFile) throws IOException
221   {
222     FileReader fr = null;
223     fr = new FileReader(inFile);
224
225     BufferedReader r = new BufferedReader(fr);
226     List<RNA> result = null;
227     try
228     {
229       result = RNAFactory.loadSecStrStockholm(r);
230     } catch (ExceptionUnmatchedClosingParentheses umcp)
231     {
232       errormessage = "Unmatched parentheses in annotation. Aborting ("
233               + umcp.getMessage() + ")";
234       throw new IOException(umcp);
235     }
236     // DEBUG System.out.println("this is the secondary scructure:"
237     // +result.size());
238     SequenceI[] seqs = new SequenceI[result.size()];
239     String id = null;
240     for (int i = 0; i < result.size(); i++)
241     {
242       // DEBUG System.err.println("Processing i'th sequence in Stockholm file")
243       RNA current = result.get(i);
244
245       String seq = current.getSeq();
246       String rna = current.getStructDBN(true);
247       // DEBUG System.out.println(seq);
248       // DEBUG System.err.println(rna);
249       int begin = 0;
250       int end = seq.length() - 1;
251       id = safeName(getDataName());
252       seqs[i] = new Sequence(id, seq, begin, end);
253       String[] annot = new String[rna.length()];
254       Annotation[] ann = new Annotation[rna.length()];
255       for (int j = 0; j < rna.length(); j++)
256       {
257         annot[j] = rna.substring(j, j + 1);
258
259       }
260
261       for (int k = 0; k < rna.length(); k++)
262       {
263         ann[k] = new Annotation(annot[k], "",
264                 Rna.getRNASecStrucState(annot[k]).charAt(0), 0f);
265
266       }
267       AlignmentAnnotation align = new AlignmentAnnotation("Sec. str.",
268               current.getID(), ann);
269
270       seqs[i].addAlignmentAnnotation(align);
271       seqs[i].setRNA(result.get(i));
272       this.annotations.addElement(align);
273     }
274     this.setSeqs(seqs);
275
276   }
277
278   /**
279    * Parse a file in Stockholm format into Jalview's data model. The file has to
280    * be passed at construction time
281    * 
282    * @throws IOException
283    *           If there is an error with the input file
284    */
285   @Override
286   public void parse() throws IOException
287   {
288     StringBuffer treeString = new StringBuffer();
289     String treeName = null;
290     // --------------- Variable Definitions -------------------
291     String line;
292     String version;
293     // String id;
294     Hashtable seqAnn = new Hashtable(); // Sequence related annotations
295     LinkedHashMap<String, String> seqs = new LinkedHashMap<>();
296     Regex p, r, rend, s, x;
297     // Temporary line for processing RNA annotation
298     // String RNAannot = "";
299
300     // ------------------ Parsing File ----------------------
301     // First, we have to check that this file has STOCKHOLM format, i.e. the
302     // first line must match
303
304     r = getRegex(REGEX_STOCKHOLM);
305     if (!r.search(nextLine()))
306     {
307       throw new IOException(MessageManager
308               .getString("exception.stockholm_invalid_format"));
309     }
310     else
311     {
312       version = r.stringMatched(1);
313
314       // logger.debug("Stockholm version: " + version);
315     }
316
317     // We define some Regexes here that will be used regularily later
318     rend = getRegex(REGEX_ALIGN_END);//"^\\s*\\/\\/"); // Find the end of an alignment
319     p = getRegex(REGEX_SPLIT_ID);//"(\\S+)\\/(\\d+)\\-(\\d+)"); // split sequence id in
320     // id/from/to
321     s = getRegex(REGEX_SUBTYPE);// "(\\S+)\\s+(\\S*)\\s+(.*)"); // Parses
322                                 // annotation subtype
323     r = getRegex(REGEX_ANNOTATION_LINE);// "#=(G[FSRC]?)\\s+(.*)"); // Finds any
324                                         // annotation line
325     x = getRegex(REGEX_REMOVE_ID);// "(\\S+)\\s+(\\S+)"); // split id from
326                                   // sequence
327
328     // Convert all bracket types to parentheses (necessary for passing to VARNA)
329     Regex openparen = getRegex(REGEX_OPEN_PAREN);//"(<|\\[)", "(");
330     Regex closeparen = getRegex(REGEX_CLOSE_PAREN);//"(>|\\])", ")");
331
332 //    // Detect if file is RNA by looking for bracket types
333 //    Regex detectbrackets = new Regex("(<|>|\\[|\\]|\\(|\\))");
334
335     rend.optimize();
336     p.optimize();
337     s.optimize();
338     r.optimize();
339     x.optimize();
340     openparen.optimize();
341     closeparen.optimize();
342
343     while ((line = nextLine()) != null)
344     {
345       if (line.length() == 0)
346       {
347         continue;
348       }
349       if (rend.search(line))
350       {
351         // End of the alignment, pass stuff back
352         this.noSeqs = seqs.size();
353
354         String dbsource = null;
355         Regex pf = getRegex(REGEX_PFAM); // Finds AC for Pfam
356         Regex rf = getRegex(REGEX_RFAM); // Finds AC for Rfam
357         if (getAlignmentProperty("AC") != null)
358         {
359           String dbType = getAlignmentProperty("AC").toString();
360           if (pf.search(dbType))
361           {
362             // PFAM Alignment - so references are typically from Uniprot
363             dbsource = "PFAM";
364           }
365           else if (rf.search(dbType))
366           {
367             dbsource = "RFAM";
368           }
369         }
370         // logger.debug("Number of sequences: " + this.noSeqs);
371         for (Map.Entry<String, String> skey : seqs.entrySet())
372         {
373           // logger.debug("Processing sequence " + acc);
374           String acc = skey.getKey();
375           String seq = skey.getValue();
376           if (maxLength < seq.length())
377           {
378             maxLength = seq.length();
379           }
380           int start = 1;
381           int end = -1;
382           String sid = acc;
383           /*
384            * Retrieve hash of annotations for this accession Associate
385            * Annotation with accession
386            */
387           Hashtable accAnnotations = null;
388
389           if (seqAnn != null && seqAnn.containsKey(acc))
390           {
391             accAnnotations = (Hashtable) seqAnn.remove(acc);
392             // TODO: add structures to sequence
393           }
394
395           // Split accession in id and from/to
396           if (p.search(acc))
397           {
398             sid = p.stringMatched(1);
399             start = Integer.parseInt(p.stringMatched(2));
400             end = Integer.parseInt(p.stringMatched(3));
401           }
402           // logger.debug(sid + ", " + start + ", " + end);
403
404           Sequence seqO = new Sequence(sid, seq, start, end);
405           // Add Description (if any)
406           if (accAnnotations != null && accAnnotations.containsKey("DE"))
407           {
408             String desc = (String) accAnnotations.get("DE");
409             seqO.setDescription((desc == null) ? "" : desc);
410           }
411           // Add DB References (if any)
412           if (accAnnotations != null && accAnnotations.containsKey("DR"))
413           {
414             String dbr = (String) accAnnotations.get("DR");
415             if (dbr != null && dbr.indexOf(";") > -1)
416             {
417               String src = dbr.substring(0, dbr.indexOf(";"));
418               String acn = dbr.substring(dbr.indexOf(";") + 1);
419               jalview.util.DBRefUtils.parseToDbRef(seqO, src, "0", acn);
420             }
421           }
422
423           if (accAnnotations != null && accAnnotations.containsKey("AC"))
424           {
425               String dbr = (String) accAnnotations.get("AC");
426               if (dbr != null)
427               {
428                 // we could get very clever here - but for now - just try to
429               // guess accession type from type of sequence, source of alignment plus
430               // structure
431                 // of accession
432                 guessDatabaseFor(seqO, dbr, dbsource);
433             }
434             // else - do what ? add the data anyway and prompt the user to
435             // specify what references these are ?
436           }
437
438           Hashtable features = null;
439           // We need to adjust the positions of all features to account for gaps
440           try
441           {
442             features = (Hashtable) accAnnotations.remove("features");
443           } catch (java.lang.NullPointerException e)
444           {
445             // loggerwarn("Getting Features for " + acc + ": " +
446             // e.getMessage());
447             // continue;
448           }
449           // if we have features
450           if (features != null)
451           {
452             int posmap[] = seqO.findPositionMap();
453             Enumeration i = features.keys();
454             while (i.hasMoreElements())
455             {
456               // TODO: parse out secondary structure annotation as annotation
457               // row
458               // TODO: parse out scores as annotation row
459               // TODO: map coding region to core jalview feature types
460               String type = i.nextElement().toString();
461               Hashtable content = (Hashtable) features.remove(type);
462
463               // add alignment annotation for this feature
464               String key = type2id(type);
465
466               /*
467                * have we added annotation rows for this type ?
468                */
469               boolean annotsAdded = false;
470               if (key != null)
471               {
472                 if (accAnnotations != null
473                         && accAnnotations.containsKey(key))
474                 {
475                   Vector vv = (Vector) accAnnotations.get(key);
476                   for (int ii = 0; ii < vv.size(); ii++)
477                   {
478                     annotsAdded = true;
479                     AlignmentAnnotation an = (AlignmentAnnotation) vv
480                             .elementAt(ii);
481                     seqO.addAlignmentAnnotation(an);
482                     annotations.add(an);
483                   }
484                 }
485               }
486
487               Enumeration j = content.keys();
488               while (j.hasMoreElements())
489               {
490                 String desc = j.nextElement().toString();
491                 if (ANNOTATION.equals(desc) && annotsAdded)
492                 {
493                   // don't add features if we already added an annotation row
494                   continue;
495                 }
496                 String ns = content.get(desc).toString();
497                 char[] byChar = ns.toCharArray();
498                 for (int k = 0; k < byChar.length; k++)
499                 {
500                   char c = byChar[k];
501                   if (!(c == ' ' || c == '_' || c == '-' || c == '.')) // PFAM
502                   // uses
503                   // '.'
504                   // for
505                   // feature
506                   // background
507                   {
508                     int new_pos = posmap[k]; // look up nearest seqeunce
509                     // position to this column
510                     SequenceFeature feat = new SequenceFeature(type, desc,
511                             new_pos, new_pos, null);
512
513                     seqO.addSequenceFeature(feat);
514                   }
515                 }
516               }
517
518             }
519
520           }
521           // garbage collect
522
523           // logger.debug("Adding seq " + acc + " from " + start + " to " + end
524           // + ": " + seq);
525           this.seqs.addElement(seqO);
526         }
527         return; // finished parsing this segment of source
528       }
529       else if (!r.search(line))
530       {
531         // System.err.println("Found sequence line: " + line);
532
533         // Split sequence in sequence and accession parts
534         if (!x.search(line))
535         {
536           // logger.error("Could not parse sequence line: " + line);
537           throw new IOException(MessageManager.formatMessage(
538                   "exception.couldnt_parse_sequence_line", new String[]
539                   { line }));
540         }
541         String ns = seqs.get(x.stringMatched(1));
542         if (ns == null)
543         {
544           ns = "";
545         }
546         ns += x.stringMatched(2);
547
548         seqs.put(x.stringMatched(1), ns);
549       }
550       else
551       {
552         String annType = r.stringMatched(1);
553         String annContent = r.stringMatched(2);
554
555         // System.err.println("type:" + annType + " content: " + annContent);
556
557         if (annType.equals("GF"))
558         {
559           /*
560            * Generic per-File annotation, free text Magic features: #=GF NH
561            * <tree in New Hampshire eXtended format> #=GF TN <Unique identifier
562            * for the next tree> Pfam descriptions: 7. DESCRIPTION OF FIELDS
563            * 
564            * Compulsory fields: ------------------
565            * 
566            * AC Accession number: Accession number in form PFxxxxx.version or
567            * PBxxxxxx. ID Identification: One word name for family. DE
568            * Definition: Short description of family. AU Author: Authors of the
569            * entry. SE Source of seed: The source suggesting the seed members
570            * belong to one family. GA Gathering method: Search threshold to
571            * build the full alignment. TC Trusted Cutoff: Lowest sequence score
572            * and domain score of match in the full alignment. NC Noise Cutoff:
573            * Highest sequence score and domain score of match not in full
574            * alignment. TP Type: Type of family -- presently Family, Domain,
575            * Motif or Repeat. SQ Sequence: Number of sequences in alignment. AM
576            * Alignment Method The order ls and fs hits are aligned to the model
577            * to build the full align. // End of alignment.
578            * 
579            * Optional fields: ----------------
580            * 
581            * DC Database Comment: Comment about database reference. DR Database
582            * Reference: Reference to external database. RC Reference Comment:
583            * Comment about literature reference. RN Reference Number: Reference
584            * Number. RM Reference Medline: Eight digit medline UI number. RT
585            * Reference Title: Reference Title. RA Reference Author: Reference
586            * Author RL Reference Location: Journal location. PI Previous
587            * identifier: Record of all previous ID lines. KW Keywords: Keywords.
588            * CC Comment: Comments. NE Pfam accession: Indicates a nested domain.
589            * NL Location: Location of nested domains - sequence ID, start and
590            * end of insert.
591            * 
592            * Obsolete fields: ----------- AL Alignment method of seed: The
593            * method used to align the seed members.
594            */
595           // Let's save the annotations, maybe we'll be able to do something
596           // with them later...
597           Regex an = getRegex(REGEX_ANNOTATION);
598           if (an.search(annContent))
599           {
600             if (an.stringMatched(1).equals("NH"))
601             {
602               treeString.append(an.stringMatched(2));
603             }
604             else if (an.stringMatched(1).equals("TN"))
605             {
606               if (treeString.length() > 0)
607               {
608                 if (treeName == null)
609                 {
610                   treeName = "Tree " + (getTreeCount() + 1);
611                 }
612                 addNewickTree(treeName, treeString.toString());
613               }
614               treeName = an.stringMatched(2);
615               treeString = new StringBuffer();
616             }
617             // TODO: JAL-3532 - this is where GF comments and database references are lost
618             // suggest overriding this method for Stockholm files to catch and properly
619             // process CC, DR etc into multivalued properties
620             setAlignmentProperty(an.stringMatched(1), an.stringMatched(2));
621           }
622         }
623         else if (annType.equals("GS"))
624         {
625           // Generic per-Sequence annotation, free text
626           /*
627            * Pfam uses these features: Feature Description ---------------------
628            * ----------- AC <accession> ACcession number DE <freetext>
629            * DEscription DR <db>; <accession>; Database Reference OS <organism>
630            * OrganiSm (species) OC <clade> Organism Classification (clade, etc.)
631            * LO <look> Look (Color, etc.)
632            */
633           if (s.search(annContent))
634           {
635             String acc = s.stringMatched(1);
636             String type = s.stringMatched(2);
637             String content = s.stringMatched(3);
638             // TODO: store DR in a vector.
639             // TODO: store AC according to generic file db annotation.
640             Hashtable ann;
641             if (seqAnn.containsKey(acc))
642             {
643               ann = (Hashtable) seqAnn.get(acc);
644             }
645             else
646             {
647               ann = new Hashtable();
648             }
649             ann.put(type, content);
650             seqAnn.put(acc, ann);
651           }
652           else
653           {
654             // throw new IOException("Error parsing " + line);
655             System.err.println(">> missing annotation: " + line);
656           }
657         }
658         else if (annType.equals("GC"))
659         {
660           // Generic per-Column annotation, exactly 1 char per column
661           // always need a label.
662           if (x.search(annContent))
663           {
664             // parse out and create alignment annotation directly.
665             parseAnnotationRow(annotations, x.stringMatched(1),
666                     x.stringMatched(2));
667           }
668         }
669         else if (annType.equals("GR"))
670         {
671           // Generic per-Sequence AND per-Column markup, exactly 1 char per
672           // column
673           /*
674            * Feature Description Markup letters ------- -----------
675            * -------------- SS Secondary Structure [HGIEBTSCX] SA Surface
676            * Accessibility [0-9X] (0=0%-10%; ...; 9=90%-100%) TM TransMembrane
677            * [Mio] PP Posterior Probability [0-9*] (0=0.00-0.05; 1=0.05-0.15;
678            * *=0.95-1.00) LI LIgand binding [*] AS Active Site [*] IN INtron (in
679            * or after) [0-2]
680            */
681           if (s.search(annContent))
682           {
683             String acc = s.stringMatched(1);
684             String type = s.stringMatched(2);
685             String oseq = s.stringMatched(3);
686             /*
687              * copy of annotation field that may be processed into whitespace chunks
688              */
689             String seq = new String(oseq);
690
691             Hashtable ann;
692             // Get an object with all the annotations for this sequence
693             if (seqAnn.containsKey(acc))
694             {
695               // logger.debug("Found annotations for " + acc);
696               ann = (Hashtable) seqAnn.get(acc);
697             }
698             else
699             {
700               // logger.debug("Creating new annotations holder for " + acc);
701               ann = new Hashtable();
702               seqAnn.put(acc, ann);
703             }
704
705             // // start of block for appending annotation lines for wrapped
706             // stokchholm file
707             // TODO test structure, call parseAnnotationRow with vector from
708             // hashtable for specific sequence
709
710             Hashtable features;
711             // Get an object with all the content for an annotation
712             if (ann.containsKey("features"))
713             {
714               // logger.debug("Found features for " + acc);
715               features = (Hashtable) ann.get("features");
716             }
717             else
718             {
719               // logger.debug("Creating new features holder for " + acc);
720               features = new Hashtable();
721               ann.put("features", features);
722             }
723
724             Hashtable content;
725             if (features.containsKey(this.id2type(type)))
726             {
727               // logger.debug("Found content for " + this.id2type(type));
728               content = (Hashtable) features
729                       .get(this.id2type(type));
730             }
731             else
732             {
733               // logger.debug("Creating new content holder for " +
734               // this.id2type(type));
735               content = new Hashtable();
736               features.put(id2type(type), content);
737             }
738             String ns = (String) content.get(ANNOTATION);
739
740             if (ns == null)
741             {
742               ns = "";
743             }
744             // finally, append the annotation line
745             ns += seq;
746             content.put(ANNOTATION, ns);
747             // // end of wrapped annotation block.
748             // // Now a new row is created with the current set of data
749
750             Hashtable strucAnn;
751             if (seqAnn.containsKey(acc))
752             {
753               strucAnn = (Hashtable) seqAnn.get(acc);
754             }
755             else
756             {
757               strucAnn = new Hashtable();
758             }
759
760             Vector<AlignmentAnnotation> newStruc = new Vector<>();
761             parseAnnotationRow(newStruc, type, ns);
762             for (AlignmentAnnotation alan : newStruc)
763             {
764               alan.visible = false;
765             }
766             // new annotation overwrites any existing annotation...
767
768             strucAnn.put(type, newStruc);
769             seqAnn.put(acc, strucAnn);
770           }
771           // }
772           else
773           {
774             System.err.println(
775                     "Warning - couldn't parse sequence annotation row line:\n"
776                             + line);
777             // throw new IOException("Error parsing " + line);
778           }
779         }
780         else
781         {
782           throw new IOException(MessageManager.formatMessage(
783                   "exception.unknown_annotation_detected", new String[]
784                   { annType, annContent }));
785         }
786       }
787     }
788     if (treeString.length() > 0)
789     {
790       if (treeName == null)
791       {
792         treeName = "Tree " + (1 + getTreeCount());
793       }
794       addNewickTree(treeName, treeString.toString());
795     }
796   }
797
798   /**
799    * Demangle an accession string and guess the originating sequence database
800    * for a given sequence
801    * 
802    * @param seqO
803    *          sequence to be annotated
804    * @param dbr
805    *          Accession string for sequence
806    * @param dbsource
807    *          source database for alignment (PFAM or RFAM)
808    */
809   private void guessDatabaseFor(Sequence seqO, String dbr, String dbsource)
810   {
811     DBRefEntry dbrf = null;
812     List<DBRefEntry> dbrs = new ArrayList<>();
813     String seqdb = "Unknown", sdbac = "" + dbr;
814     int st = -1, en = -1, p;
815     if ((st = sdbac.indexOf("/")) > -1)
816     {
817       String num, range = sdbac.substring(st + 1);
818       sdbac = sdbac.substring(0, st);
819       if ((p = range.indexOf("-")) > -1)
820       {
821         p++;
822         if (p < range.length())
823         {
824           num = range.substring(p).trim();
825           try
826           {
827             en = Integer.parseInt(num);
828           } catch (NumberFormatException x)
829           {
830             // could warn here that index is invalid
831             en = -1;
832           }
833         }
834       }
835       else
836       {
837         p = range.length();
838       }
839       num = range.substring(0, p).trim();
840       try
841       {
842         st = Integer.parseInt(num);
843       } catch (NumberFormatException x)
844       {
845         // could warn here that index is invalid
846         st = -1;
847       }
848     }
849     if (dbsource == null)
850     {
851       // make up an origin based on whether the sequence looks like it is nucleotide
852       // or protein
853       dbsource = (seqO.isProtein()) ? "PFAM" : "RFAM";
854     }
855     if (dbsource.equals("PFAM"))
856     {
857       seqdb = "UNIPROT";
858       if (sdbac.indexOf(".") > -1)
859       {
860         // strip of last subdomain
861         sdbac = sdbac.substring(0, sdbac.indexOf("."));
862         dbrf = jalview.util.DBRefUtils.parseToDbRef(seqO, seqdb, dbsource,
863                 sdbac);
864         if (dbrf != null)
865         {
866           dbrs.add(dbrf);
867         }
868       }
869       dbrf = jalview.util.DBRefUtils.parseToDbRef(seqO, dbsource, dbsource,
870               dbr);
871       if (dbr != null)
872       {
873         dbrs.add(dbrf);
874       }
875     }
876     else
877     {
878       seqdb = "EMBL"; // total guess - could be ENA, or something else these
879                       // days
880       if (sdbac.indexOf(".") > -1)
881       {
882         // strip off last subdomain
883         sdbac = sdbac.substring(0, sdbac.indexOf("."));
884         dbrf = jalview.util.DBRefUtils.parseToDbRef(seqO, seqdb, dbsource,
885                 sdbac);
886         if (dbrf != null)
887         {
888           dbrs.add(dbrf);
889         }
890       }
891
892       dbrf = jalview.util.DBRefUtils.parseToDbRef(seqO, dbsource, dbsource,
893               dbr);
894       if (dbrf != null)
895       {
896         dbrs.add(dbrf);
897       }
898     }
899     if (st != -1 && en != -1)
900     {
901       for (DBRefEntry d : dbrs)
902       {
903         jalview.util.MapList mp = new jalview.util.MapList(
904                 new int[]
905                 { seqO.getStart(), seqO.getEnd() }, new int[] { st, en }, 1,
906                 1);
907         jalview.datamodel.Mapping mping = new Mapping(mp);
908         d.setMap(mping);
909       }
910     }
911   }
912
913   protected static AlignmentAnnotation parseAnnotationRow(
914           Vector<AlignmentAnnotation> annotation, String label,
915           String annots)
916   {
917           String convert1, convert2 = null;
918     // String convert1 = OPEN_PAREN.replaceAll(annots);
919     // String convert2 = CLOSE_PAREN.replaceAll(convert1);
920     // annots = convert2;
921
922     String type = label;
923     if (label.contains("_cons"))
924     {
925       type = (label.indexOf("_cons") == label.length() - 5)
926               ? label.substring(0, label.length() - 5)
927               : label;
928     }
929     boolean ss = false, posterior = false;
930     type = id2type(type);
931
932     boolean isrnass = false;
933     if (type.equalsIgnoreCase("secondary structure"))
934     {
935       ss = true;
936       isrnass = !getRegex(REGEX_NOT_RNASS).search(annots); // sorry about the double
937                                                      // negative
938                                            // here (it's easier for dealing with
939                                            // other non-alpha-non-brace chars)
940     }
941     if (type.equalsIgnoreCase("posterior probability"))
942     {
943       posterior = true;
944     }
945     // decide on secondary structure or not.
946     Annotation[] els = new Annotation[annots.length()];
947     for (int i = 0; i < annots.length(); i++)
948     {
949       String pos = annots.substring(i, i + 1);
950       // TODO 2.12 release: verify this Stockholm IO behaviour change in release notes
951       if (UNDERSCORE == pos.charAt(0))
952       {
953         pos = " ";
954       }
955       Annotation ann;
956       ann = new Annotation(pos, "", ' ', 0f); // 0f is 'valid' null - will not
957       // be written out
958       if (ss)
959       {
960         // if (" .-_".indexOf(pos) == -1)
961         {
962           if (isrnass && RNASS_BRACKETS.indexOf(pos) >= 0)
963           {
964             ann.secondaryStructure = Rna.getRNASecStrucState(pos).charAt(0);
965             ann.displayCharacter = "" + pos.charAt(0);
966           }
967           else
968           {
969             ann.secondaryStructure = ResidueProperties.getDssp3state(pos)
970                     .charAt(0);
971
972             if (ann.secondaryStructure == pos.charAt(0))
973             {
974               ann.displayCharacter = ""; // null; // " ";
975             }
976             else
977             {
978               ann.displayCharacter = " " + ann.displayCharacter;
979             }
980           }
981         }
982
983       }
984       if (posterior && !ann.isWhitespace()
985               && !Comparison.isGap(pos.charAt(0)))
986       {
987         float val = 0;
988         // symbol encodes values - 0..*==0..10
989         if (pos.charAt(0) == '*')
990         {
991           val = 10;
992         }
993         else
994         {
995           val = pos.charAt(0) - '0';
996           if (val > 9)
997           {
998             val = 10;
999           }
1000         }
1001         ann.value = val;
1002       }
1003
1004       els[i] = ann;
1005     }
1006     AlignmentAnnotation annot = null;
1007     Enumeration<AlignmentAnnotation> e = annotation.elements();
1008     while (e.hasMoreElements())
1009     {
1010       annot = e.nextElement();
1011       if (annot.label.equals(type))
1012       {
1013         break;
1014       }
1015       annot = null;
1016     }
1017     if (annot == null)
1018     {
1019       annot = new AlignmentAnnotation(type, type, els);
1020       annotation.addElement(annot);
1021     }
1022     else
1023     {
1024       Annotation[] anns = new Annotation[annot.annotations.length
1025               + els.length];
1026       System.arraycopy(annot.annotations, 0, anns, 0,
1027               annot.annotations.length);
1028       System.arraycopy(els, 0, anns, annot.annotations.length, els.length);
1029       annot.annotations = anns;
1030       // System.out.println("else: ");
1031     }
1032     return annot;
1033   }
1034
1035   private String dbref_to_ac_record(DBRefEntry ref)
1036   {
1037     return ref.getSource().toString() + " ; "
1038             + ref.getAccessionId().toString();
1039   }
1040   @Override
1041   public String print(SequenceI[] s, boolean jvSuffix)
1042   {
1043     out = new StringBuffer();
1044     out.append("# STOCKHOLM 1.0");
1045     out.append(newline);
1046
1047     // find max length of id
1048     int max = 0;
1049     int maxid = 0;
1050     int in = 0;
1051     int slen = s.length;
1052     SequenceI seq;
1053     Hashtable<String, String> dataRef = null;
1054     boolean isAA = s[in].isProtein();
1055     while ((in < slen) && ((seq = s[in]) != null))
1056     {
1057       String tmp = printId(seq, jvSuffix);
1058       max = Math.max(max, seq.getLength());
1059
1060       if (tmp.length() > maxid)
1061       {
1062         maxid = tmp.length();
1063       }
1064       List<DBRefEntry> seqrefs = seq.getDBRefs();
1065       int ndb;
1066       if (seqrefs != null && (ndb = seqrefs.size()) > 0)
1067       {
1068         if (dataRef == null)
1069         {
1070           dataRef = new Hashtable<>();
1071         }
1072         List<DBRefEntry> primrefs = seq.getPrimaryDBRefs();
1073         if (primrefs.size() >= 1)
1074         {
1075           dataRef.put(tmp, dbref_to_ac_record(primrefs.get(0)));
1076         }
1077         else
1078         {
1079           for (int idb = 0; idb < ndb; idb++)
1080           {
1081             DBRefEntry dbref = seqrefs.get(idb);
1082             dataRef.put(tmp, dbref_to_ac_record(dbref));
1083             // if we put in a uniprot or EMBL record then we're done:
1084             if ((isAA ? DBRefSource.UNIPROT : DBRefSource.EMBL)
1085                     .equals(DBRefUtils.getCanonicalName(dbref.getSource())))
1086             {
1087               break;
1088             }
1089           }
1090         }
1091       }
1092       in++;
1093     }
1094     maxid += 9;
1095     int i = 0;
1096
1097     // output database type
1098     if (al.getProperties() != null)
1099     {
1100       if (!al.getProperties().isEmpty())
1101       {
1102         Enumeration key = al.getProperties().keys();
1103         Enumeration val = al.getProperties().elements();
1104         while (key.hasMoreElements())
1105         {
1106           out.append("#=GF " + key.nextElement() + " " + val.nextElement());
1107           out.append(newline);
1108         }
1109       }
1110     }
1111
1112     // output database accessions
1113     if (dataRef != null)
1114     {
1115       Enumeration<String> en = dataRef.keys();
1116       while (en.hasMoreElements())
1117       {
1118         Object idd = en.nextElement();
1119         String type = dataRef.remove(idd);
1120         out.append(new Format("%-" + (maxid - 2) + "s")
1121                 .form("#=GS " + idd.toString() + " "));
1122         if (isAA && type.contains("UNIPROT")
1123                 || (!isAA && type.contains("EMBL")))
1124         {
1125
1126           out.append(" AC " + type.substring(type.indexOf(";") + 1));
1127         }
1128         else
1129         {
1130           out.append(" DR " + type + " ");
1131         }
1132         out.append(newline);
1133       }
1134     }
1135
1136     // output annotations
1137     while (i < slen && (seq = s[i]) != null)
1138     {
1139       AlignmentAnnotation[] alAnot = seq.getAnnotation();
1140       if (alAnot != null)
1141       {
1142         Annotation[] ann;
1143         for (int j = 0; j < alAnot.length; j++)
1144         {
1145
1146           if (alAnot[j].annotations != null)
1147           {
1148             String key = type2id(alAnot[j].label);
1149             boolean isrna = alAnot[j].isValidStruc();
1150
1151             if (isrna)
1152             {
1153               // hardwire to secondary structure if there is RNA secondary
1154               // structure on the annotation
1155               key = "SS";
1156             }
1157             if (key == null)
1158             {
1159               continue;
1160             }
1161
1162             // out.append("#=GR ");
1163             out.append(new Format("%-" + maxid + "s").form(
1164                     "#=GR " + printId(s[i], jvSuffix) + " " + key + " "));
1165             ann = alAnot[j].annotations;
1166             String sseq = "";
1167             for (int k = 0; k < ann.length; k++)
1168             {
1169               sseq += outputCharacter(key, k, isrna, ann, s[i]);
1170             }
1171             out.append(sseq);
1172             out.append(newline);
1173           }
1174         }
1175       }
1176
1177       out.append(new Format("%-" + maxid + "s")
1178               .form(printId(seq, jvSuffix) + " "));
1179       out.append(seq.getSequenceAsString());
1180       out.append(newline);
1181       i++;
1182     }
1183
1184     // alignment annotation
1185     AlignmentAnnotation aa;
1186     AlignmentAnnotation[] an = al.getAlignmentAnnotation();
1187     if (an != null)
1188     {
1189       for (int ia = 0, na = an.length; ia < na; ia++)
1190       {
1191         aa = an[ia];
1192         if (aa.autoCalculated || !aa.visible || aa.sequenceRef != null)
1193         {
1194           continue;
1195         }
1196         String sseq = "";
1197         String label;
1198         String key = "";
1199         if (aa.label.equals("seq"))
1200         {
1201           label = "seq_cons";
1202         }
1203         else
1204         {
1205           key = type2id(aa.label.toLowerCase(Locale.ROOT));
1206           if (key == null)
1207           {
1208             label = aa.label;
1209           }
1210           else
1211           {
1212             label = key + "_cons";
1213           }
1214         }
1215         if (label == null)
1216         {
1217           label = aa.label;
1218         }
1219         label = label.replace(" ", "_");
1220
1221         out.append(
1222                 new Format("%-" + maxid + "s").form("#=GC " + label + " "));
1223         boolean isrna = aa.isValidStruc();
1224         for (int j = 0, nj = aa.annotations.length; j < nj; j++)
1225         {
1226           sseq += outputCharacter(key, j, isrna, aa.annotations, null);
1227         }
1228         out.append(sseq);
1229         out.append(newline);
1230       }
1231     }
1232
1233     out.append("//");
1234     out.append(newline);
1235
1236     return out.toString();
1237   }
1238
1239   /**
1240    * add an annotation character to the output row
1241    * 
1242    * @param seq
1243    * @param key
1244    * @param k
1245    * @param isrna
1246    * @param ann
1247    * @param sequenceI
1248    */
1249   private char outputCharacter(String key, int k, boolean isrna,
1250           Annotation[] ann, SequenceI sequenceI)
1251   {
1252     char seq = ' ';
1253     Annotation annot = ann[k];
1254     String ch = (annot == null)
1255             ? ((sequenceI == null) ? "-"
1256                     : Character.toString(sequenceI.getCharAt(k)))
1257             : (annot.displayCharacter == null
1258                     ? String.valueOf(annot.secondaryStructure)
1259                     : annot.displayCharacter);
1260     if (ch == null)
1261     {
1262       ch = " ";
1263     }
1264     if (key != null && key.equals("SS"))
1265     {
1266       char ssannotchar = ' ';
1267       boolean charset = false;
1268       if (annot == null)
1269       {
1270         // sensible gap character
1271         ssannotchar = ' ';
1272         charset = true;
1273       }
1274       else
1275       {
1276         // valid secondary structure AND no alternative label (e.g. ' B')
1277         if (annot.secondaryStructure > ' ' && ch.length() < 2)
1278         {
1279           ssannotchar = annot.secondaryStructure;
1280           charset = true;
1281         }
1282       }
1283       if (charset)
1284       {
1285         return (ssannotchar == ' ' && isrna) ? '.' : ssannotchar;
1286       }
1287     }
1288
1289     if (ch.length() == 0)
1290     {
1291       seq = '.';
1292     }
1293     else if (ch.length() == 1)
1294     {
1295       seq = ch.charAt(0);
1296     }
1297     else if (ch.length() > 1)
1298     {
1299       seq = ch.charAt(1);
1300     }
1301
1302     return (seq == ' ' && key != null && key.equals("SS") && isrna) ? '.'
1303             : seq;
1304   }
1305
1306   /**
1307    * make a friendly ID string.
1308    * 
1309    * @param dataName
1310    * @return truncated dataName to after last '/'
1311    */
1312   private String safeName(String dataName)
1313   {
1314     int b = 0;
1315     while ((b = dataName.indexOf("/")) > -1 && b < dataName.length())
1316     {
1317       dataName = dataName.substring(b + 1).trim();
1318
1319     }
1320     int e = (dataName.length() - dataName.indexOf(".")) + 1;
1321     dataName = dataName.substring(1, e).trim();
1322     return dataName;
1323   }
1324   
1325   
1326   public String print()
1327   {
1328     out = new StringBuffer();
1329     out.append("# STOCKHOLM 1.0");
1330     out.append(newline);
1331     print(getSeqsAsArray(), false);
1332
1333     out.append("//");
1334     out.append(newline);
1335     return out.toString();
1336   }
1337
1338   private static Hashtable typeIds = null;
1339
1340   static
1341   {
1342     if (typeIds == null)
1343     {
1344       typeIds = new Hashtable();
1345       typeIds.put("SS", "Secondary Structure");
1346       typeIds.put("SA", "Surface Accessibility");
1347       typeIds.put("TM", "transmembrane");
1348       typeIds.put("PP", "Posterior Probability");
1349       typeIds.put("LI", "ligand binding");
1350       typeIds.put("AS", "active site");
1351       typeIds.put("IN", "intron");
1352       typeIds.put("IR", "interacting residue");
1353       typeIds.put("AC", "accession");
1354       typeIds.put("OS", "organism");
1355       typeIds.put("CL", "class");
1356       typeIds.put("DE", "description");
1357       typeIds.put("DR", "reference");
1358       typeIds.put("LO", "look");
1359       typeIds.put("RF", "Reference Positions");
1360
1361     }
1362   }
1363
1364   
1365   protected static String id2type(String id)
1366   {
1367     if (typeIds.containsKey(id))
1368     {
1369       return (String) typeIds.get(id);
1370     }
1371     System.err.println(
1372             "Warning : Unknown Stockholm annotation type code " + id);
1373     return id;
1374   }
1375
1376   protected static String type2id(String type)
1377   {
1378     String key = null;
1379     Enumeration e = typeIds.keys();
1380     while (e.hasMoreElements())
1381     {
1382       Object ll = e.nextElement();
1383       if (typeIds.get(ll).toString().equalsIgnoreCase(type))
1384       {
1385         key = (String) ll;
1386         break;
1387       }
1388     }
1389     if (key != null)
1390     {
1391       return key;
1392     }
1393     System.err.println(
1394             "Warning : Unknown Stockholm annotation type: " + type);
1395     return key;
1396   }
1397 }