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