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