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