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