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