JAL-3691 automatic insertion of Locale.ROOT to toUpperCase() and toLowerCase() and...
[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.util.Locale;
27
28 import java.io.BufferedReader;
29 import java.io.FileReader;
30 import java.io.IOException;
31 import java.util.ArrayList;
32 import java.util.Enumeration;
33 import java.util.Hashtable;
34 import java.util.LinkedHashMap;
35 import java.util.List;
36 import java.util.Map;
37 import java.util.Vector;
38
39 import com.stevesoft.pat.Regex;
40
41 import fr.orsay.lri.varna.exceptions.ExceptionUnmatchedClosingParentheses;
42 import fr.orsay.lri.varna.factories.RNAFactory;
43 import fr.orsay.lri.varna.models.rna.RNA;
44 import jalview.analysis.Rna;
45 import jalview.datamodel.AlignmentAnnotation;
46 import jalview.datamodel.AlignmentI;
47 import jalview.datamodel.Annotation;
48 import jalview.datamodel.DBRefEntry;
49 import jalview.datamodel.DBRefSource;
50 import jalview.datamodel.Mapping;
51 import jalview.datamodel.Sequence;
52 import jalview.datamodel.SequenceFeature;
53 import jalview.datamodel.SequenceI;
54 import jalview.schemes.ResidueProperties;
55 import jalview.util.Comparison;
56 import jalview.util.DBRefUtils;
57 import jalview.util.Format;
58 import jalview.util.MessageManager;
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 Regex OPEN_PAREN = new Regex("(<|\\[)", "(");
83 //
84 //  private static final Regex CLOSE_PAREN = new Regex("(>|\\])", ")");
85
86   public static final Regex DETECT_BRACKETS = new Regex(
87           "(<|>|\\[|\\]|\\(|\\)|\\{|\\})");
88
89   // WUSS extended symbols. Avoid ambiguity with protein SS annotations by using NOT_RNASS first.
90   public static final String RNASS_BRACKETS = "<>[](){}AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz";
91
92   // use the following regex to decide an annotations (whole) line is NOT an RNA
93   // SS (it contains only E,H,e,h and other non-brace/non-alpha chars)
94   private static final Regex NOT_RNASS = new Regex(
95           "^[^<>[\\](){}A-DF-Za-df-z]*$");
96
97   StringBuffer out; // output buffer
98
99   AlignmentI al;
100
101   public StockholmFile()
102   {
103   }
104
105   /**
106    * Creates a new StockholmFile object for output.
107    */
108   public StockholmFile(AlignmentI al)
109   {
110     this.al = al;
111   }
112
113   public StockholmFile(String inFile, DataSourceType type)
114           throws IOException
115   {
116     super(inFile, type);
117   }
118
119   public StockholmFile(FileParse source) throws IOException
120   {
121     super(source);
122   }
123
124   @Override
125   public void initData()
126   {
127     super.initData();
128   }
129
130   /**
131    * Parse a file in Stockholm format into Jalview's data model using VARNA
132    * 
133    * @throws IOException
134    *           If there is an error with the input file
135    */
136   public void parse_with_VARNA(java.io.File inFile) throws IOException
137   {
138     FileReader fr = null;
139     fr = new FileReader(inFile);
140
141     BufferedReader r = new BufferedReader(fr);
142     List<RNA> result = null;
143     try
144     {
145       result = RNAFactory.loadSecStrStockholm(r);
146     } catch (ExceptionUnmatchedClosingParentheses umcp)
147     {
148       errormessage = "Unmatched parentheses in annotation. Aborting ("
149               + umcp.getMessage() + ")";
150       throw new IOException(umcp);
151     }
152     // DEBUG System.out.println("this is the secondary scructure:"
153     // +result.size());
154     SequenceI[] seqs = new SequenceI[result.size()];
155     String id = null;
156     for (int i = 0; i < result.size(); i++)
157     {
158       // DEBUG System.err.println("Processing i'th sequence in Stockholm file")
159       RNA current = result.get(i);
160
161       String seq = current.getSeq();
162       String rna = current.getStructDBN(true);
163       // DEBUG System.out.println(seq);
164       // DEBUG System.err.println(rna);
165       int begin = 0;
166       int end = seq.length() - 1;
167       id = safeName(getDataName());
168       seqs[i] = new Sequence(id, seq, begin, end);
169       String[] annot = new String[rna.length()];
170       Annotation[] ann = new Annotation[rna.length()];
171       for (int j = 0; j < rna.length(); j++)
172       {
173         annot[j] = rna.substring(j, j + 1);
174
175       }
176
177       for (int k = 0; k < rna.length(); k++)
178       {
179         ann[k] = new Annotation(annot[k], "",
180                 Rna.getRNASecStrucState(annot[k]).charAt(0), 0f);
181
182       }
183       AlignmentAnnotation align = new AlignmentAnnotation("Sec. str.",
184               current.getID(), ann);
185
186       seqs[i].addAlignmentAnnotation(align);
187       seqs[i].setRNA(result.get(i));
188       this.annotations.addElement(align);
189     }
190     this.setSeqs(seqs);
191
192   }
193
194   /**
195    * Parse a file in Stockholm format into Jalview's data model. The file has to
196    * be passed at construction time
197    * 
198    * @throws IOException
199    *           If there is an error with the input file
200    */
201   @Override
202   public void parse() throws IOException
203   {
204     StringBuffer treeString = new StringBuffer();
205     String treeName = null;
206     // --------------- Variable Definitions -------------------
207     String line;
208     String version;
209     // String id;
210     Hashtable seqAnn = new Hashtable(); // Sequence related annotations
211     LinkedHashMap<String, String> seqs = new LinkedHashMap<>();
212     Regex p, r, rend, s, x;
213     // Temporary line for processing RNA annotation
214     // String RNAannot = "";
215
216     // ------------------ Parsing File ----------------------
217     // First, we have to check that this file has STOCKHOLM format, i.e. the
218     // first line must match
219
220     r = new Regex("# STOCKHOLM ([\\d\\.]+)");
221     if (!r.search(nextLine()))
222     {
223       throw new IOException(MessageManager
224               .getString("exception.stockholm_invalid_format"));
225     }
226     else
227     {
228       version = r.stringMatched(1);
229
230       // logger.debug("Stockholm version: " + version);
231     }
232
233     // We define some Regexes here that will be used regularily later
234     rend = new Regex("^\\s*\\/\\/"); // Find the end of an alignment
235     p = new Regex("(\\S+)\\/(\\d+)\\-(\\d+)"); // split sequence id in
236     // id/from/to
237     s = new Regex("(\\S+)\\s+(\\S*)\\s+(.*)"); // Parses annotation subtype
238     r = new Regex("#=(G[FSRC]?)\\s+(.*)"); // Finds any annotation line
239     x = new Regex("(\\S+)\\s+(\\S+)"); // split id from sequence
240
241     // Convert all bracket types to parentheses (necessary for passing to VARNA)
242     Regex openparen = new Regex("(<|\\[)", "(");
243     Regex closeparen = new Regex("(>|\\])", ")");
244
245 //    // Detect if file is RNA by looking for bracket types
246 //    Regex detectbrackets = new Regex("(<|>|\\[|\\]|\\(|\\))");
247
248     rend.optimize();
249     p.optimize();
250     s.optimize();
251     r.optimize();
252     x.optimize();
253     openparen.optimize();
254     closeparen.optimize();
255
256     while ((line = nextLine()) != null)
257     {
258       if (line.length() == 0)
259       {
260         continue;
261       }
262       if (rend.search(line))
263       {
264         // End of the alignment, pass stuff back
265         this.noSeqs = seqs.size();
266
267         String dbsource = null;
268         Regex pf = new Regex("PF[0-9]{5}(.*)"); // Finds AC for Pfam
269         Regex rf = new Regex("RF[0-9]{5}(.*)"); // Finds AC for Rfam
270         if (getAlignmentProperty("AC") != null)
271         {
272           String dbType = getAlignmentProperty("AC").toString();
273           if (pf.search(dbType))
274           {
275             // PFAM Alignment - so references are typically from Uniprot
276             dbsource = "PFAM";
277           }
278           else if (rf.search(dbType))
279           {
280             dbsource = "RFAM";
281           }
282         }
283         // logger.debug("Number of sequences: " + this.noSeqs);
284         for (Map.Entry<String, String> skey : seqs.entrySet())
285         {
286           // logger.debug("Processing sequence " + acc);
287           String acc = skey.getKey();
288           String seq = skey.getValue();
289           if (maxLength < seq.length())
290           {
291             maxLength = seq.length();
292           }
293           int start = 1;
294           int end = -1;
295           String sid = acc;
296           /*
297            * Retrieve hash of annotations for this accession Associate
298            * Annotation with accession
299            */
300           Hashtable accAnnotations = null;
301
302           if (seqAnn != null && seqAnn.containsKey(acc))
303           {
304             accAnnotations = (Hashtable) seqAnn.remove(acc);
305             // TODO: add structures to sequence
306           }
307
308           // Split accession in id and from/to
309           if (p.search(acc))
310           {
311             sid = p.stringMatched(1);
312             start = Integer.parseInt(p.stringMatched(2));
313             end = Integer.parseInt(p.stringMatched(3));
314           }
315           // logger.debug(sid + ", " + start + ", " + end);
316
317           Sequence seqO = new Sequence(sid, seq, start, end);
318           // Add Description (if any)
319           if (accAnnotations != null && accAnnotations.containsKey("DE"))
320           {
321             String desc = (String) accAnnotations.get("DE");
322             seqO.setDescription((desc == null) ? "" : desc);
323           }
324           // Add DB References (if any)
325           if (accAnnotations != null && accAnnotations.containsKey("DR"))
326           {
327             String dbr = (String) accAnnotations.get("DR");
328             if (dbr != null && dbr.indexOf(";") > -1)
329             {
330               String src = dbr.substring(0, dbr.indexOf(";"));
331               String acn = dbr.substring(dbr.indexOf(";") + 1);
332               jalview.util.DBRefUtils.parseToDbRef(seqO, src, "0", acn);
333             }
334           }
335
336           if (accAnnotations != null && accAnnotations.containsKey("AC"))
337           {
338             String dbr = (String) accAnnotations.get("AC");
339             if (dbr != null)
340             {
341               // we could get very clever here - but for now - just try to
342               // guess accession type from type of sequence, source of alignment 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 references are lost
531             // suggest overriding this method for Stockholm files to catch and properly
532             // process CC, DR etc into multivalued properties
533             setAlignmentProperty(an.stringMatched(1), an.stringMatched(2));
534           }
535         }
536         else if (annType.equals("GS"))
537         {
538           // Generic per-Sequence annotation, free text
539           /*
540            * Pfam uses these features: Feature Description ---------------------
541            * ----------- AC <accession> ACcession number DE <freetext>
542            * DEscription DR <db>; <accession>; Database Reference OS <organism>
543            * OrganiSm (species) OC <clade> Organism Classification (clade, etc.)
544            * LO <look> Look (Color, etc.)
545            */
546           if (s.search(annContent))
547           {
548             String acc = s.stringMatched(1);
549             String type = s.stringMatched(2);
550             String content = s.stringMatched(3);
551             // TODO: store DR in a vector.
552             // TODO: store AC according to generic file db annotation.
553             Hashtable ann;
554             if (seqAnn.containsKey(acc))
555             {
556               ann = (Hashtable) seqAnn.get(acc);
557             }
558             else
559             {
560               ann = new Hashtable();
561             }
562             ann.put(type, content);
563             seqAnn.put(acc, ann);
564           }
565           else
566           {
567             // throw new IOException("Error parsing " + line);
568             System.err.println(">> missing annotation: " + line);
569           }
570         }
571         else if (annType.equals("GC"))
572         {
573           // Generic per-Column annotation, exactly 1 char per column
574           // always need a label.
575           if (x.search(annContent))
576           {
577             // parse out and create alignment annotation directly.
578             parseAnnotationRow(annotations, x.stringMatched(1),
579                     x.stringMatched(2));
580           }
581         }
582         else if (annType.equals("GR"))
583         {
584           // Generic per-Sequence AND per-Column markup, exactly 1 char per
585           // column
586           /*
587            * Feature Description Markup letters ------- -----------
588            * -------------- SS Secondary Structure [HGIEBTSCX] SA Surface
589            * Accessibility [0-9X] (0=0%-10%; ...; 9=90%-100%) TM TransMembrane
590            * [Mio] PP Posterior Probability [0-9*] (0=0.00-0.05; 1=0.05-0.15;
591            * *=0.95-1.00) LI LIgand binding [*] AS Active Site [*] IN INtron (in
592            * or after) [0-2]
593            */
594           if (s.search(annContent))
595           {
596             String acc = s.stringMatched(1);
597             String type = s.stringMatched(2);
598             String oseq = s.stringMatched(3);
599             /*
600              * copy of annotation field that may be processed into whitespace chunks
601              */
602             String seq = new String(oseq);
603
604             Hashtable ann;
605             // Get an object with all the annotations for this sequence
606             if (seqAnn.containsKey(acc))
607             {
608               // logger.debug("Found annotations for " + acc);
609               ann = (Hashtable) seqAnn.get(acc);
610             }
611             else
612             {
613               // logger.debug("Creating new annotations holder for " + acc);
614               ann = new Hashtable();
615               seqAnn.put(acc, ann);
616             }
617
618             // // start of block for appending annotation lines for wrapped
619             // stokchholm file
620             // TODO test structure, call parseAnnotationRow with vector from
621             // hashtable for specific sequence
622
623             Hashtable features;
624             // Get an object with all the content for an annotation
625             if (ann.containsKey("features"))
626             {
627               // logger.debug("Found features for " + acc);
628               features = (Hashtable) ann.get("features");
629             }
630             else
631             {
632               // logger.debug("Creating new features holder for " + acc);
633               features = new Hashtable();
634               ann.put("features", features);
635             }
636
637             Hashtable content;
638             if (features.containsKey(this.id2type(type)))
639             {
640               // logger.debug("Found content for " + this.id2type(type));
641               content = (Hashtable) features.get(this.id2type(type));
642             }
643             else
644             {
645               // logger.debug("Creating new content holder for " +
646               // this.id2type(type));
647               content = new Hashtable();
648               features.put(this.id2type(type), content);
649             }
650             String ns = (String) content.get(ANNOTATION);
651
652             if (ns == null)
653             {
654               ns = "";
655             }
656             // finally, append the annotation line
657             ns += seq;
658             content.put(ANNOTATION, ns);
659             // // end of wrapped annotation block.
660             // // Now a new row is created with the current set of data
661
662             Hashtable strucAnn;
663             if (seqAnn.containsKey(acc))
664             {
665               strucAnn = (Hashtable) seqAnn.get(acc);
666             }
667             else
668             {
669               strucAnn = new Hashtable();
670             }
671
672             Vector<AlignmentAnnotation> newStruc = new Vector<>();
673             parseAnnotationRow(newStruc, type, ns);
674             for (AlignmentAnnotation alan : newStruc)
675             {
676               alan.visible = false;
677             }
678             // new annotation overwrites any existing annotation...
679
680             strucAnn.put(type, newStruc);
681             seqAnn.put(acc, strucAnn);
682           }
683           // }
684           else
685           {
686             System.err.println(
687                     "Warning - couldn't parse sequence annotation row line:\n"
688                             + line);
689             // throw new IOException("Error parsing " + line);
690           }
691         }
692         else
693         {
694           throw new IOException(MessageManager.formatMessage(
695                   "exception.unknown_annotation_detected", new String[]
696                   { annType, annContent }));
697         }
698       }
699     }
700     if (treeString.length() > 0)
701     {
702       if (treeName == null)
703       {
704         treeName = "Tree " + (1 + getTreeCount());
705       }
706       addNewickTree(treeName, treeString.toString());
707     }
708   }
709
710   /**
711    * Demangle an accession string and guess the originating sequence database
712    * for a given sequence
713    * 
714    * @param seqO
715    *          sequence to be annotated
716    * @param dbr
717    *          Accession string for sequence
718    * @param dbsource
719    *          source database for alignment (PFAM or RFAM)
720    */
721   private void guessDatabaseFor(Sequence seqO, String dbr, String dbsource)
722   {
723     DBRefEntry dbrf = null;
724     List<DBRefEntry> dbrs = new ArrayList<>();
725     String seqdb = "Unknown", sdbac = "" + dbr;
726     int st = -1, en = -1, p;
727     if ((st = sdbac.indexOf("/")) > -1)
728     {
729       String num, range = sdbac.substring(st + 1);
730       sdbac = sdbac.substring(0, st);
731       if ((p = range.indexOf("-")) > -1)
732       {
733         p++;
734         if (p < range.length())
735         {
736           num = range.substring(p).trim();
737           try
738           {
739             en = Integer.parseInt(num);
740           } catch (NumberFormatException x)
741           {
742             // could warn here that index is invalid
743             en = -1;
744           }
745         }
746       }
747       else
748       {
749         p = range.length();
750       }
751       num = range.substring(0, p).trim();
752       try
753       {
754         st = Integer.parseInt(num);
755       } catch (NumberFormatException x)
756       {
757         // could warn here that index is invalid
758         st = -1;
759       }
760     }
761     if (dbsource == null)
762     {
763       // make up an origin based on whether the sequence looks like it is nucleotide
764       // or protein
765       dbsource = (seqO.isProtein()) ? "PFAM" : "RFAM";
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
831     // convert1 = OPEN_PAREN.replaceAll(annots);
832     // convert2 = CLOSE_PAREN.replaceAll(convert1);
833     // annots = convert2;
834
835     String type = label;
836     if (label.contains("_cons"))
837     {
838       type = (label.indexOf("_cons") == label.length() - 5)
839               ? label.substring(0, label.length() - 5)
840               : label;
841     }
842     boolean ss = false, posterior = false;
843     type = id2type(type);
844
845     boolean isrnass = false;
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       Annotation ann;
863       ann = new Annotation(pos, "", ' ', 0f); // 0f is 'valid' null - will not
864       // be written out
865       if (ss)
866       {
867         // if (" .-_".indexOf(pos) == -1)
868         {
869           if (isrnass && RNASS_BRACKETS.indexOf(pos) >= 0)
870           {
871             ann.secondaryStructure = Rna.getRNASecStrucState(pos).charAt(0);
872             ann.displayCharacter = "" + pos.charAt(0);
873           }
874           else
875           {
876             ann.secondaryStructure = ResidueProperties.getDssp3state(pos)
877                     .charAt(0);
878
879             if (ann.secondaryStructure == pos.charAt(0))
880             {
881               ann.displayCharacter = ""; // null; // " ";
882             }
883             else
884             {
885               ann.displayCharacter = " " + ann.displayCharacter;
886             }
887           }
888         }
889
890       }
891       if (posterior && !ann.isWhitespace()
892               && !Comparison.isGap(pos.charAt(0)))
893       {
894         float val = 0;
895         // symbol encodes values - 0..*==0..10
896         if (pos.charAt(0) == '*')
897         {
898           val = 10;
899         }
900         else
901         {
902           val = pos.charAt(0) - '0';
903           if (val > 9)
904           {
905             val = 10;
906           }
907         }
908         ann.value = val;
909       }
910
911       els[i] = ann;
912     }
913     AlignmentAnnotation annot = null;
914     Enumeration<AlignmentAnnotation> e = annotation.elements();
915     while (e.hasMoreElements())
916     {
917       annot = e.nextElement();
918       if (annot.label.equals(type))
919       {
920         break;
921       }
922       annot = null;
923     }
924     if (annot == null)
925     {
926       annot = new AlignmentAnnotation(type, type, els);
927       annotation.addElement(annot);
928     }
929     else
930     {
931       Annotation[] anns = new Annotation[annot.annotations.length
932               + els.length];
933       System.arraycopy(annot.annotations, 0, anns, 0,
934               annot.annotations.length);
935       System.arraycopy(els, 0, anns, annot.annotations.length, els.length);
936       annot.annotations = anns;
937       // System.out.println("else: ");
938     }
939     return annot;
940   }
941
942   private String dbref_to_ac_record(DBRefEntry ref)
943   {
944     return ref.getSource().toString() + " ; "
945             + ref.getAccessionId().toString();
946   }
947   @Override
948   public String print(SequenceI[] s, boolean jvSuffix)
949   {
950     out = new StringBuffer();
951     out.append("# STOCKHOLM 1.0");
952     out.append(newline);
953
954     // find max length of id
955     int max = 0;
956     int maxid = 0;
957     int in = 0;
958     int slen = s.length;
959     SequenceI seq;
960     Hashtable<String, String> dataRef = null;
961     boolean isAA = s[in].isProtein();
962     while ((in < slen) && ((seq = s[in]) != null))
963     {
964       String tmp = printId(seq, jvSuffix);
965       max = Math.max(max, seq.getLength());
966
967       if (tmp.length() > maxid)
968       {
969         maxid = tmp.length();
970       }
971       List<DBRefEntry> seqrefs = seq.getDBRefs();
972       int ndb;
973       if (seqrefs != null && (ndb = seqrefs.size()) > 0)
974       {
975         if (dataRef == null)
976         {
977           dataRef = new Hashtable<>();
978         }
979         List<DBRefEntry> primrefs = seq.getPrimaryDBRefs();
980         if (primrefs.size() >= 1)
981         {
982           dataRef.put(tmp, dbref_to_ac_record(primrefs.get(0)));
983         }
984         else
985         {
986           for (int idb = 0; idb < seq.getDBRefs().size(); idb++)
987           {
988             DBRefEntry dbref = seq.getDBRefs().get(idb);
989             dataRef.put(tmp, dbref_to_ac_record(dbref));
990             // if we put in a uniprot or EMBL record then we're done:
991             if (isAA && DBRefSource.UNIPROT
992                     .equals(DBRefUtils.getCanonicalName(dbref.getSource())))
993             {
994               break;
995             }
996             if (!isAA && DBRefSource.EMBL
997                     .equals(DBRefUtils.getCanonicalName(dbref.getSource())))
998             {
999               break;
1000             }
1001           }
1002         }
1003       }
1004       in++;
1005     }
1006     maxid += 9;
1007     int i = 0;
1008
1009     // output database type
1010     if (al.getProperties() != null)
1011     {
1012       if (!al.getProperties().isEmpty())
1013       {
1014         Enumeration key = al.getProperties().keys();
1015         Enumeration val = al.getProperties().elements();
1016         while (key.hasMoreElements())
1017         {
1018           out.append("#=GF " + key.nextElement() + " " + val.nextElement());
1019           out.append(newline);
1020         }
1021       }
1022     }
1023
1024     // output database accessions
1025     if (dataRef != null)
1026     {
1027       Enumeration<String> en = dataRef.keys();
1028       while (en.hasMoreElements())
1029       {
1030         Object idd = en.nextElement();
1031         String type = dataRef.remove(idd);
1032         out.append(new Format("%-" + (maxid - 2) + "s")
1033                 .form("#=GS " + idd.toString() + " "));
1034         if (isAA && type.contains("UNIPROT")
1035                 || (!isAA && type.contains("EMBL")))
1036         {
1037
1038           out.append(" AC " + type.substring(type.indexOf(";") + 1));
1039         }
1040         else
1041         {
1042           out.append(" DR " + type + " ");
1043         }
1044         out.append(newline);
1045       }
1046     }
1047
1048     // output annotations
1049     while (i < slen && (seq = s[i]) != null)
1050     {
1051       AlignmentAnnotation[] alAnot = seq.getAnnotation();
1052       if (alAnot != null)
1053       {
1054         Annotation[] ann;
1055         for (int j = 0, nj = alAnot.length; j < nj; j++)
1056         {
1057
1058           String key = type2id(alAnot[j].label);
1059           boolean isrna = alAnot[j].isValidStruc();
1060
1061           if (isrna)
1062           {
1063             // hardwire to secondary structure if there is RNA secondary
1064             // structure on the annotation
1065             key = "SS";
1066           }
1067           if (key == null)
1068           {
1069
1070             continue;
1071           }
1072
1073           // out.append("#=GR ");
1074           out.append(new Format("%-" + maxid + "s").form(
1075                   "#=GR " + printId(seq, jvSuffix) + " " + key + " "));
1076           ann = alAnot[j].annotations;
1077           String sseq = "";
1078           for (int k = 0, nk = ann.length; k < nk; k++)
1079           {
1080             sseq += outputCharacter(key, k, isrna, ann, seq);
1081           }
1082           out.append(sseq);
1083           out.append(newline);
1084         }
1085       }
1086
1087       out.append(new Format("%-" + maxid + "s")
1088               .form(printId(seq, jvSuffix) + " "));
1089       out.append(seq.getSequenceAsString());
1090       out.append(newline);
1091       i++;
1092     }
1093
1094     // alignment annotation
1095     AlignmentAnnotation aa;
1096     AlignmentAnnotation[] an = al.getAlignmentAnnotation();
1097     if (an != null)
1098     {
1099       for (int ia = 0, na = an.length; ia < na; ia++)
1100       {
1101         aa = an[ia];
1102         if (aa.autoCalculated || !aa.visible || aa.sequenceRef != null)
1103         {
1104           continue;
1105         }
1106         String sseq = "";
1107         String label;
1108         String key = "";
1109         if (aa.label.equals("seq"))
1110         {
1111           label = "seq_cons";
1112         }
1113         else
1114         {
1115           key = type2id(aa.label.toLowerCase(Locale.ROOT));
1116           if (key == null)
1117           {
1118             label = aa.label;
1119           }
1120           else
1121           {
1122             label = key + "_cons";
1123           }
1124         }
1125         if (label == null)
1126         {
1127           label = aa.label;
1128         }
1129         label = label.replace(" ", "_");
1130
1131         out.append(
1132                 new Format("%-" + maxid + "s").form("#=GC " + label + " "));
1133         boolean isrna = aa.isValidStruc();
1134         for (int j = 0, nj = aa.annotations.length; j < nj; j++)
1135         {
1136           sseq += outputCharacter(key, j, isrna, aa.annotations, null);
1137         }
1138         out.append(sseq);
1139         out.append(newline);
1140       }
1141     }
1142
1143     out.append("//");
1144     out.append(newline);
1145
1146     return out.toString();
1147   }
1148
1149   /**
1150    * add an annotation character to the output row
1151    * 
1152    * @param seq
1153    * @param key
1154    * @param k
1155    * @param isrna
1156    * @param ann
1157    * @param sequenceI
1158    */
1159   private char outputCharacter(String key, int k, boolean isrna,
1160           Annotation[] ann, SequenceI sequenceI)
1161   {
1162     char seq = ' ';
1163     Annotation annot = ann[k];
1164     String ch = (annot == null)
1165             ? ((sequenceI == null) ? "-"
1166                     : Character.toString(sequenceI.getCharAt(k)))
1167             : (annot.displayCharacter == null
1168                     ? String.valueOf(annot.secondaryStructure)
1169                     : annot.displayCharacter);
1170     if (ch == null)
1171     {
1172       ch = " ";
1173     }
1174     if (key != null && key.equals("SS"))
1175     {
1176       char ssannotchar = ' ';
1177       boolean charset = false;
1178       if (annot == null)
1179       {
1180         // sensible gap character
1181         ssannotchar = ' ';
1182         charset = true;
1183       }
1184       else
1185       {
1186         // valid secondary structure AND no alternative label (e.g. ' B')
1187         if (annot.secondaryStructure > ' ' && ch.length() < 2)
1188         {
1189           ssannotchar = annot.secondaryStructure;
1190           charset = true;
1191         }
1192       }
1193       if (charset)
1194       {
1195         return (ssannotchar == ' ' && isrna) ? '.' : ssannotchar;
1196       }
1197     }
1198
1199     if (ch.length() == 0)
1200     {
1201       seq = '.';
1202     }
1203     else if (ch.length() == 1)
1204     {
1205       seq = ch.charAt(0);
1206     }
1207     else if (ch.length() > 1)
1208     {
1209       seq = ch.charAt(1);
1210     }
1211
1212     return (seq == ' ' && key != null && key.equals("SS") && isrna) ? '.'
1213             : seq;
1214   }
1215
1216   public String print()
1217   {
1218     out = new StringBuffer();
1219     out.append("# STOCKHOLM 1.0");
1220     out.append(newline);
1221     print(getSeqsAsArray(), false);
1222
1223     out.append("//");
1224     out.append(newline);
1225     return out.toString();
1226   }
1227
1228   private static Hashtable typeIds = null;
1229
1230   static
1231   {
1232     if (typeIds == null)
1233     {
1234       typeIds = new Hashtable();
1235       typeIds.put("SS", "Secondary Structure");
1236       typeIds.put("SA", "Surface Accessibility");
1237       typeIds.put("TM", "transmembrane");
1238       typeIds.put("PP", "Posterior Probability");
1239       typeIds.put("LI", "ligand binding");
1240       typeIds.put("AS", "active site");
1241       typeIds.put("IN", "intron");
1242       typeIds.put("IR", "interacting residue");
1243       typeIds.put("AC", "accession");
1244       typeIds.put("OS", "organism");
1245       typeIds.put("CL", "class");
1246       typeIds.put("DE", "description");
1247       typeIds.put("DR", "reference");
1248       typeIds.put("LO", "look");
1249       typeIds.put("RF", "Reference Positions");
1250
1251     }
1252   }
1253
1254   protected static String id2type(String id)
1255   {
1256     if (typeIds.containsKey(id))
1257     {
1258       return (String) typeIds.get(id);
1259     }
1260     System.err.println(
1261             "Warning : Unknown Stockholm annotation type code " + id);
1262     return id;
1263   }
1264
1265   protected static String type2id(String type)
1266   {
1267     String key = null;
1268     Enumeration e = typeIds.keys();
1269     while (e.hasMoreElements())
1270     {
1271       Object ll = e.nextElement();
1272       if (typeIds.get(ll).toString().equalsIgnoreCase(type))
1273       {
1274         key = (String) ll;
1275         break;
1276       }
1277     }
1278     if (key != null)
1279     {
1280       return key;
1281     }
1282     System.err.println(
1283             "Warning : Unknown Stockholm annotation type: " + type);
1284     return key;
1285   }
1286
1287   /**
1288    * make a friendly ID string.
1289    * 
1290    * @param dataName
1291    * @return truncated dataName to after last '/'
1292    */
1293   private String safeName(String dataName)
1294   {
1295     int b = 0;
1296     while ((b = dataName.indexOf("/")) > -1 && b < dataName.length())
1297     {
1298       dataName = dataName.substring(b + 1).trim();
1299
1300     }
1301     int e = (dataName.length() - dataName.indexOf(".")) + 1;
1302     dataName = dataName.substring(1, e).trim();
1303     return dataName;
1304   }
1305 }