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