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