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