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