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