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