file format enum wip changes
[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, DataSourceType sourceType)
95           throws IOException
96   {
97     super(inFile, sourceType);
98   }
99
100   public StockholmFile(FileParse source) throws IOException
101   {
102     super(source);
103   }
104
105   @Override
106   public void initData()
107   {
108     super.initData();
109   }
110
111   /**
112    * Parse a file in Stockholm format into Jalview's data model using VARNA
113    * 
114    * @throws IOException
115    *           If there is an error with the input file
116    */
117   public void parse_with_VARNA(java.io.File inFile) throws IOException
118   {
119     FileReader fr = null;
120     fr = new FileReader(inFile);
121
122     BufferedReader r = new BufferedReader(fr);
123     result = null;
124     try
125     {
126       result = RNAFactory.loadSecStrStockholm(r);
127     } catch (ExceptionUnmatchedClosingParentheses umcp)
128     {
129       errormessage = "Unmatched parentheses in annotation. Aborting ("
130               + umcp.getMessage() + ")";
131       throw new IOException(umcp);
132     }
133     // DEBUG System.out.println("this is the secondary scructure:"
134     // +result.size());
135     SequenceI[] seqs = new SequenceI[result.size()];
136     String id = null;
137     for (int i = 0; i < result.size(); i++)
138     {
139       // DEBUG System.err.println("Processing i'th sequence in Stockholm file")
140       RNA current = result.get(i);
141
142       String seq = current.getSeq();
143       String rna = current.getStructDBN(true);
144       // DEBUG System.out.println(seq);
145       // DEBUG System.err.println(rna);
146       int begin = 0;
147       int end = seq.length() - 1;
148       id = safeName(getDataName());
149       seqs[i] = new Sequence(id, seq, begin, end);
150       String[] annot = new String[rna.length()];
151       Annotation[] ann = new Annotation[rna.length()];
152       for (int j = 0; j < rna.length(); j++)
153       {
154         annot[j] = rna.substring(j, j + 1);
155
156       }
157
158       for (int k = 0; k < rna.length(); k++)
159       {
160         ann[k] = new Annotation(annot[k], "",
161                 jalview.schemes.ResidueProperties.getRNASecStrucState(
162                         annot[k]).charAt(0), 0f);
163
164       }
165       AlignmentAnnotation align = new AlignmentAnnotation("Sec. str.",
166               current.getID(), ann);
167
168       seqs[i].addAlignmentAnnotation(align);
169       seqs[i].setRNA(result.get(i));
170       this.annotations.addElement(align);
171     }
172     this.setSeqs(seqs);
173
174   }
175
176   /**
177    * Parse a file in Stockholm format into Jalview's data model. The file has to
178    * be passed at construction time
179    * 
180    * @throws IOException
181    *           If there is an error with the input file
182    */
183   @Override
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               jalview.util.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",
427                   new String[] { 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[] { line }));
541             System.err.println(">> missing annotation: " + 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 = jalview.util.DBRefUtils.parseToDbRef(seqO, seqdb, dbsource,
745                 sdbac);
746         if (dbrf != null)
747         {
748           dbrs.add(dbrf);
749         }
750       }
751       dbrf = jalview.util.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 = jalview.util.DBRefUtils.parseToDbRef(seqO, seqdb, dbsource,
767                 sdbac);
768         if (dbrf != null)
769         {
770           dbrs.add(dbrf);
771         }
772       }
773
774       dbrf = jalview.util.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         jalview.util.MapList mp = new jalview.util.MapList(new int[] {
786             seqO.getStart(), seqO.getEnd() }, new int[] { st, en }, 1, 1);
787         jalview.datamodel.Mapping mping = new Mapping(mp);
788         d.setMap(mping);
789       }
790     }
791   }
792
793   protected static AlignmentAnnotation parseAnnotationRow(
794           Vector annotation, String label, String annots)
795   {
796     String convert1, convert2 = null;
797
798     // Convert all bracket types to parentheses
799     Regex openparen = new Regex("(<|\\[)", "(");
800     Regex closeparen = new Regex("(>|\\])", ")");
801
802     // Detect if file is RNA by looking for bracket types
803     Regex detectbrackets = new Regex("(<|>|\\[|\\]|\\(|\\))");
804
805     convert1 = openparen.replaceAll(annots);
806     convert2 = closeparen.replaceAll(convert1);
807     annots = convert2;
808
809     String type = label;
810     if (label.contains("_cons"))
811     {
812       type = (label.indexOf("_cons") == label.length() - 5) ? label
813               .substring(0, label.length() - 5) : label;
814     }
815     boolean ss = false;
816     type = id2type(type);
817     if (type.equals("secondary structure"))
818     {
819       ss = true;
820     }
821     // decide on secondary structure or not.
822     Annotation[] els = new Annotation[annots.length()];
823     for (int i = 0; i < annots.length(); i++)
824     {
825       String pos = annots.substring(i, i + 1);
826       Annotation ann;
827       ann = new Annotation(pos, "", ' ', 0f); // 0f is 'valid' null - will not
828       // be written out
829       if (ss)
830       {
831         // if (" .-_".indexOf(pos) == -1)
832         {
833           if (detectbrackets.search(pos))
834           {
835             ann.secondaryStructure = jalview.schemes.ResidueProperties
836                     .getRNASecStrucState(pos).charAt(0);
837           }
838           else
839           {
840             ann.secondaryStructure = jalview.schemes.ResidueProperties
841                     .getDssp3state(pos).charAt(0);
842           }
843
844           if (ann.secondaryStructure == pos.charAt(0))
845           {
846             ann.displayCharacter = ""; // null; // " ";
847           }
848           else
849           {
850             ann.displayCharacter = " " + ann.displayCharacter;
851           }
852         }
853
854       }
855
856       els[i] = ann;
857     }
858     AlignmentAnnotation annot = null;
859     Enumeration e = annotation.elements();
860     while (e.hasMoreElements())
861     {
862       annot = (AlignmentAnnotation) e.nextElement();
863       if (annot.label.equals(type))
864       {
865         break;
866       }
867       annot = null;
868     }
869     if (annot == null)
870     {
871       annot = new AlignmentAnnotation(type, type, els);
872       annotation.addElement(annot);
873     }
874     else
875     {
876       Annotation[] anns = new Annotation[annot.annotations.length
877               + els.length];
878       System.arraycopy(annot.annotations, 0, anns, 0,
879               annot.annotations.length);
880       System.arraycopy(els, 0, anns, annot.annotations.length, els.length);
881       annot.annotations = anns;
882       // System.out.println("else: ");
883     }
884     return annot;
885   }
886
887   public String print(SequenceI[] s)
888   {
889     // find max length of id
890     int max = 0;
891     int maxid = 0;
892     int in = 0;
893     Hashtable dataRef = null;
894     while ((in < s.length) && (s[in] != null))
895     {
896       String tmp = printId(s[in]);
897       if (s[in].getSequence().length > max)
898       {
899         max = s[in].getSequence().length;
900       }
901
902       if (tmp.length() > maxid)
903       {
904         maxid = tmp.length();
905       }
906       if (s[in].getDBRefs() != null)
907       {
908         for (int idb = 0; idb < s[in].getDBRefs().length; idb++)
909         {
910           if (dataRef == null)
911           {
912             dataRef = new Hashtable();
913           }
914
915           String datAs1 = s[in].getDBRefs()[idb].getSource().toString()
916                   + " ; "
917                   + s[in].getDBRefs()[idb].getAccessionId().toString();
918           dataRef.put(tmp, datAs1);
919         }
920       }
921       in++;
922     }
923     maxid += 9;
924     int i = 0;
925
926     // output database type
927     if (al.getProperties() != null)
928     {
929       if (!al.getProperties().isEmpty())
930       {
931         Enumeration key = al.getProperties().keys();
932         Enumeration val = al.getProperties().elements();
933         while (key.hasMoreElements())
934         {
935           out.append("#=GF " + key.nextElement() + " " + val.nextElement());
936           out.append(newline);
937         }
938       }
939     }
940
941     // output database accessions
942     if (dataRef != null)
943     {
944       Enumeration en = dataRef.keys();
945       while (en.hasMoreElements())
946       {
947         Object idd = en.nextElement();
948         String type = (String) dataRef.remove(idd);
949         out.append(new Format("%-" + (maxid - 2) + "s").form("#=GS "
950                 + idd.toString() + " "));
951         if (type.contains("PFAM") || type.contains("RFAM"))
952         {
953
954           out.append(" AC " + type.substring(type.indexOf(";") + 1));
955         }
956         else
957         {
958           out.append(" DR " + type + " ");
959         }
960         out.append(newline);
961       }
962     }
963
964     // output annotations
965     while (i < s.length && s[i] != null)
966     {
967       if (s[i].getDatasetSequence() != null)
968       {
969         SequenceI ds = s[i].getDatasetSequence();
970         AlignmentAnnotation[] alAnot;
971         Annotation[] ann;
972         Annotation annot;
973         alAnot = s[i].getAnnotation();
974         String feature = "";
975         if (alAnot != null)
976         {
977           for (int j = 0; j < alAnot.length; j++)
978           {
979             if (ds.getSequenceFeatures() != null)
980             {
981               feature = ds.getSequenceFeatures()[0].type;
982             }
983             // ?bug - feature may still have previous loop value
984             String key = type2id(feature);
985
986             if (key == null)
987             {
988               continue;
989             }
990
991             // out.append("#=GR ");
992             out.append(new Format("%-" + maxid + "s").form("#=GR "
993                     + printId(s[i]) + " " + key + " "));
994             ann = alAnot[j].annotations;
995             boolean isrna = alAnot[j].isValidStruc();
996             String seq = "";
997             for (int k = 0; k < ann.length; k++)
998             {
999               seq += outputCharacter(key, k, isrna, ann, s[i]);
1000             }
1001             out.append(seq);
1002             out.append(newline);
1003           }
1004         }
1005       }
1006
1007       out.append(new Format("%-" + maxid + "s").form(printId(s[i]) + " "));
1008       out.append(s[i].getSequenceAsString());
1009       out.append(newline);
1010       i++;
1011     }
1012
1013     // alignment annotation
1014     AlignmentAnnotation aa;
1015     if (al.getAlignmentAnnotation() != null)
1016     {
1017       for (int ia = 0; ia < al.getAlignmentAnnotation().length; ia++)
1018       {
1019         aa = al.getAlignmentAnnotation()[ia];
1020         if (aa.autoCalculated || !aa.visible || aa.sequenceRef != null)
1021         {
1022           continue;
1023         }
1024         String seq = "";
1025         String label;
1026         String key = "";
1027         if (aa.label.equals("seq"))
1028         {
1029           label = "seq_cons";
1030         }
1031         else
1032         {
1033           key = type2id(aa.label.toLowerCase());
1034           if (key == null)
1035           {
1036             label = aa.label;
1037           }
1038           else
1039           {
1040             label = key + "_cons";
1041           }
1042         }
1043         if (label == null)
1044         {
1045           label = aa.label;
1046         }
1047         label = label.replace(" ", "_");
1048
1049         out.append(new Format("%-" + maxid + "s").form("#=GC " + label
1050                 + " "));
1051         boolean isrna = aa.isValidStruc();
1052         for (int j = 0; j < aa.annotations.length; j++)
1053         {
1054           seq += outputCharacter(key, j, isrna, aa.annotations, null);
1055         }
1056         out.append(seq);
1057         out.append(newline);
1058       }
1059     }
1060     return out.toString();
1061   }
1062
1063   /**
1064    * add an annotation character to the output row
1065    * 
1066    * @param seq
1067    * @param key
1068    * @param k
1069    * @param isrna
1070    * @param ann
1071    * @param sequenceI
1072    */
1073   private char outputCharacter(String key, int k, boolean isrna,
1074           Annotation[] ann, SequenceI sequenceI)
1075   {
1076     char seq = ' ';
1077     Annotation annot = ann[k];
1078     String ch = (annot == null) ? ((sequenceI == null) ? "-" : Character
1079             .toString(sequenceI.getCharAt(k))) : annot.displayCharacter;
1080     if (key != null && key.equals("SS"))
1081     {
1082       if (annot == null)
1083       {
1084         // sensible gap character if one is available or make one up
1085         return sequenceI == null ? '-' : sequenceI.getCharAt(k);
1086       }
1087       else
1088       {
1089         // valid secondary structure AND no alternative label (e.g. ' B')
1090         if (annot.secondaryStructure > ' ' && ch.length() < 2)
1091         {
1092           return annot.secondaryStructure;
1093         }
1094       }
1095     }
1096
1097     if (ch.length() == 0)
1098     {
1099       seq = '.';
1100     }
1101     else if (ch.length() == 1)
1102     {
1103       seq = ch.charAt(0);
1104     }
1105     else if (ch.length() > 1)
1106     {
1107       seq = ch.charAt(1);
1108     }
1109     return seq;
1110   }
1111
1112   @Override
1113   public String print()
1114   {
1115     out = new StringBuffer();
1116     out.append("# STOCKHOLM 1.0");
1117     out.append(newline);
1118     print(getSeqsAsArray());
1119
1120     out.append("//");
1121     out.append(newline);
1122     return out.toString();
1123   }
1124
1125   private static Hashtable typeIds = null;
1126   static
1127   {
1128     if (typeIds == null)
1129     {
1130       typeIds = new Hashtable();
1131       typeIds.put("SS", "secondary structure");
1132       typeIds.put("SA", "surface accessibility");
1133       typeIds.put("TM", "transmembrane");
1134       typeIds.put("PP", "posterior probability");
1135       typeIds.put("LI", "ligand binding");
1136       typeIds.put("AS", "active site");
1137       typeIds.put("IN", "intron");
1138       typeIds.put("IR", "interacting residue");
1139       typeIds.put("AC", "accession");
1140       typeIds.put("OS", "organism");
1141       typeIds.put("CL", "class");
1142       typeIds.put("DE", "description");
1143       typeIds.put("DR", "reference");
1144       typeIds.put("LO", "look");
1145       typeIds.put("RF", "reference positions");
1146
1147     }
1148   }
1149
1150   protected static String id2type(String id)
1151   {
1152     if (typeIds.containsKey(id))
1153     {
1154       return (String) typeIds.get(id);
1155     }
1156     System.err.println("Warning : Unknown Stockholm annotation type code "
1157             + id);
1158     return id;
1159   }
1160
1161   protected static String type2id(String type)
1162   {
1163     String key = null;
1164     Enumeration e = typeIds.keys();
1165     while (e.hasMoreElements())
1166     {
1167       Object ll = e.nextElement();
1168       if (typeIds.get(ll).toString().equals(type))
1169       {
1170         key = (String) ll;
1171         break;
1172       }
1173     }
1174     if (key != null)
1175     {
1176       return key;
1177     }
1178     System.err.println("Warning : Unknown Stockholm annotation type: "
1179             + type);
1180     return key;
1181   }
1182
1183   /**
1184    * make a friendly ID string.
1185    * 
1186    * @param dataName
1187    * @return truncated dataName to after last '/'
1188    */
1189   private String safeName(String dataName)
1190   {
1191     int b = 0;
1192     while ((b = dataName.indexOf("/")) > -1 && b < dataName.length())
1193     {
1194       dataName = dataName.substring(b + 1).trim();
1195
1196     }
1197     int e = (dataName.length() - dataName.indexOf(".")) + 1;
1198     dataName = dataName.substring(1, e).trim();
1199     return dataName;
1200   }
1201 }