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