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