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