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