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