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