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