Output accession number for file in stockholm format
[jalview.git] / src / jalview / io / StockholmFile.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8)
3  * Copyright (C) 2012 J Procter, AM Waterhouse, LM Lui, J Engelhardt, G Barton, M Clamp, S Searle
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 of the License, or (at your option) any later version.
10  *  
11  * Jalview is distributed in the hope that it will be useful, but 
12  * WITHOUT ANY WARRANTY; without even the implied warranty 
13  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
14  * PURPOSE.  See the GNU General Public License for more details.
15  * 
16  * You should have received a copy of the GNU General Public License along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
17  */
18 /*
19  * This extension was written by Benjamin Schuster-Boeckler at sanger.ac.uk
20  */
21 package jalview.io;
22
23 import java.io.*;
24 import java.util.*;
25
26 import com.stevesoft.pat.*;
27 import jalview.datamodel.*;
28 import jalview.util.Format;
29
30 // import org.apache.log4j.*;
31
32 /**
33  * This class is supposed to parse a Stockholm format file into Jalview There
34  * are TODOs in this class: we do not know what the database source and version
35  * is for the file when parsing the #GS= AC tag which associates accessions with
36  * sequences. Database references are also not parsed correctly: a separate
37  * reference string parser must be added to parse the database reference form
38  * into Jalview's local representation.
39  * 
40  * @author bsb at sanger.ac.uk
41  * @version 0.3 + jalview mods
42  * 
43  */
44 public class StockholmFile extends AlignFile
45 {
46   // static Logger logger = Logger.getLogger("jalview.io.StockholmFile");
47   StringBuffer out; // output buffer
48   AlignmentI al;
49   
50   public StockholmFile()
51   {
52   }
53
54   /**
55   * Creates a new StockholmFile object for output.
56   */
57   public StockholmFile(AlignmentI al)
58   {
59     this.al = al;
60   }
61   
62   public StockholmFile(String inFile, String type) throws IOException
63   {
64     super(inFile, type);
65   }
66
67   public StockholmFile(FileParse source) throws IOException
68   {
69     super(source);
70   }
71
72   public void initData()
73   {
74     super.initData();
75   }
76
77   /**
78    * Parse a file in Stockholm format into Jalview's data model. The file has to
79    * be passed at construction time
80    * 
81    * @throws IOException
82    *           If there is an error with the input file
83    */
84   public void parse() throws IOException
85   {
86     StringBuffer treeString = new StringBuffer();
87     String treeName = null;
88     // --------------- Variable Definitions -------------------
89     String line;
90     String version;
91     // String id;
92     Hashtable seqAnn = new Hashtable(); // Sequence related annotations
93     Hashtable seqs = new Hashtable();
94     Regex p, r, rend, s, x;
95
96     // Temporary line for processing RNA annotation
97     // String RNAannot = "";
98
99     // ------------------ Parsing File ----------------------
100     // First, we have to check that this file has STOCKHOLM format, i.e. the
101     // first line must match
102     r = new Regex("# STOCKHOLM ([\\d\\.]+)");
103     if (!r.search(nextLine()))
104     {
105       throw new IOException(
106               "This file is not in valid STOCKHOLM format: First line does not contain '# STOCKHOLM'");
107     }
108     else
109     {
110       version = r.stringMatched(1);
111       // logger.debug("Stockholm version: " + version);
112     }
113
114     // We define some Regexes here that will be used regularily later
115     rend = new Regex("^\\s*\\/\\/"); // Find the end of an alignment
116     p = new Regex("(\\S+)\\/(\\d+)\\-(\\d+)"); // split sequence id in
117     // id/from/to
118     s = new Regex("(\\S+)\\s+(\\S*)\\s+(.*)"); // Parses annotation subtype
119     r = new Regex("#=(G[FSRC]?)\\s+(.*)"); // Finds any annotation line
120     x = new Regex("(\\S+)\\s+(\\S+)"); // split id from sequence
121
122     // Convert all bracket types to parentheses (necessary for passing to VARNA)
123     Regex openparen = new Regex("(<|\\[)", "(");
124     Regex closeparen = new Regex("(>|\\])", ")");
125
126     // Detect if file is RNA by looking for bracket types
127     Regex detectbrackets = new Regex("(<|>|\\[|\\]|\\(|\\))");
128
129     rend.optimize();
130     p.optimize();
131     s.optimize();
132     r.optimize();
133     x.optimize();
134     openparen.optimize();
135     closeparen.optimize();
136
137     while ((line = nextLine()) != null)
138     {
139       if (line.length() == 0)
140       {
141         continue;
142       }
143       if (rend.search(line))
144       {
145         // End of the alignment, pass stuff back
146         this.noSeqs = seqs.size();
147         
148         String propety = null;
149         Regex pf = new Regex("PF[0-9]{5}(.*)"); // Finds AC for Pfam
150         Regex rf = new Regex("RF[0-9]{5}(.*)"); // Finds AC for Rfam
151         if (getAlignmentProperty("AC") != null)
152         {
153           String dbType = getAlignmentProperty("AC").toString();
154           if (pf.search(dbType))
155           {
156             propety = "PFAM";
157           }
158           else if (rf.search(dbType))
159           {
160                 propety = "RFAM";
161           }
162         }
163         // logger.debug("Number of sequences: " + this.noSeqs);
164         Enumeration accs = seqs.keys();
165         while (accs.hasMoreElements())
166         {
167           String acc = (String) accs.nextElement();
168           // logger.debug("Processing sequence " + acc);
169           String seq = (String) seqs.remove(acc);
170           if (maxLength < seq.length())
171           {
172             maxLength = seq.length();
173           }
174           int start = 1;
175           int end = -1;
176           String sid = acc;
177           /*
178            * Retrieve hash of annotations for this accession Associate
179            * Annotation with accession
180            */
181           Hashtable accAnnotations = null;
182
183           if (seqAnn != null && seqAnn.containsKey(acc))
184           {
185             accAnnotations = (Hashtable) seqAnn.remove(acc);
186             // TODO: add structures to sequence
187           }
188
189           // Split accession in id and from/to
190           if (p.search(acc))
191           {
192             sid = p.stringMatched(1);
193             start = Integer.parseInt(p.stringMatched(2));
194             end = Integer.parseInt(p.stringMatched(3));
195           }
196           // logger.debug(sid + ", " + start + ", " + end);
197
198           Sequence seqO = new Sequence(sid, seq, start, end);
199           // Add Description (if any)
200           if (accAnnotations != null && accAnnotations.containsKey("DE"))
201           {
202             String desc = (String) accAnnotations.get("DE");
203             seqO.setDescription((desc == null) ? "" : desc);
204           }
205           
206          
207             
208           // Add DB References (if any)
209           if (accAnnotations != null && accAnnotations.containsKey("DR"))
210           {
211             String dbr = (String) accAnnotations.get("DR");
212             if (dbr != null && dbr.indexOf(";") > -1)
213             {
214               String src = dbr.substring(0, dbr.indexOf(";"));
215               String acn = dbr.substring(dbr.indexOf(";") + 1);
216               jalview.util.DBRefUtils.parseToDbRef(seqO, src, "0", acn);
217             }            
218           }
219           
220           if (accAnnotations != null && accAnnotations.containsKey("AC") && propety != null)
221           {
222             String dbr = (String) accAnnotations.get("AC");
223             if (dbr != null)
224             {
225               String src = propety;
226               String acn = dbr.toString();
227               jalview.util.DBRefUtils.parseToDbRef(seqO, src, "0", acn);
228             }            
229           }
230           
231       
232           Hashtable features = null;
233           // We need to adjust the positions of all features to account for gaps
234           try
235           {
236             features = (Hashtable) accAnnotations.remove("features");
237           } catch (java.lang.NullPointerException e)
238           {
239             // loggerwarn("Getting Features for " + acc + ": " +
240             // e.getMessage());
241             // continue;
242           }
243           // if we have features
244           if (features != null)
245           {
246             int posmap[] = seqO.findPositionMap();
247             Enumeration i = features.keys();
248             while (i.hasMoreElements())
249             {
250               // TODO: parse out secondary structure annotation as annotation
251               // row
252               // TODO: parse out scores as annotation row
253               // TODO: map coding region to core jalview feature types
254               String type = i.nextElement().toString();
255               Hashtable content = (Hashtable) features.remove(type);
256              
257               // add alignment annotation for this feature
258               String key = type2id(type);
259               if (key != null) 
260               {
261                 if (accAnnotations != null && accAnnotations.containsKey(key))
262                 {
263                   Vector vv = (Vector) accAnnotations.get(key); 
264                   for (int ii = 0; ii < vv.size(); ii++)
265                   {
266                     AlignmentAnnotation an = (AlignmentAnnotation) vv.elementAt(ii);
267                     seqO.addAlignmentAnnotation(an);            
268                   }        
269                 }
270               }
271               
272               Enumeration j = content.keys();
273               while (j.hasMoreElements())
274               {
275                 String desc = j.nextElement().toString();
276                 String ns = content.get(desc).toString();
277                 char[] byChar = ns.toCharArray();
278                 for (int k = 0; k < byChar.length; k++)
279                 {
280                   char c = byChar[k];
281                   if (!(c == ' ' || c == '_' || c == '-' || c == '.')) // PFAM
282                   // uses
283                   // '.'
284                   // for
285                   // feature
286                   // background
287                   {
288                     int new_pos = posmap[k]; // look up nearest seqeunce
289                     // position to this column
290                     SequenceFeature feat = new SequenceFeature(type, desc,
291                             new_pos, new_pos, 0f, null);
292
293                     seqO.addSequenceFeature(feat);
294                   }
295                 }
296               }
297
298             }
299
300           }
301           // garbage collect
302
303           // logger.debug("Adding seq " + acc + " from " + start + " to " + end
304           // + ": " + seq);
305           this.seqs.addElement(seqO);
306         }
307         return; // finished parsing this segment of source
308       }
309       else if (!r.search(line))
310       {
311         // System.err.println("Found sequence line: " + line);
312
313         // Split sequence in sequence and accession parts
314         if (!x.search(line))
315         {
316           // logger.error("Could not parse sequence line: " + line);
317           throw new IOException("Could not parse sequence line: " + line);
318         }
319         String ns = (String) seqs.get(x.stringMatched(1));
320         if (ns == null)
321         {
322           ns = "";
323         }
324         ns += x.stringMatched(2);
325
326         seqs.put(x.stringMatched(1), ns);
327       }
328       else
329       {
330         String annType = r.stringMatched(1);
331         String annContent = r.stringMatched(2);
332
333         // System.err.println("type:" + annType + " content: " + annContent);
334
335         if (annType.equals("GF"))
336         {
337           /*
338            * Generic per-File annotation, free text Magic features: #=GF NH
339            * <tree in New Hampshire eXtended format> #=GF TN <Unique identifier
340            * for the next tree> Pfam descriptions: 7. DESCRIPTION OF FIELDS
341            * 
342            * Compulsory fields: ------------------
343            * 
344            * AC Accession number: Accession number in form PFxxxxx.version or
345            * PBxxxxxx. ID Identification: One word name for family. DE
346            * Definition: Short description of family. AU Author: Authors of the
347            * entry. SE Source of seed: The source suggesting the seed members
348            * belong to one family. GA Gathering method: Search threshold to
349            * build the full alignment. TC Trusted Cutoff: Lowest sequence score
350            * and domain score of match in the full alignment. NC Noise Cutoff:
351            * Highest sequence score and domain score of match not in full
352            * alignment. TP Type: Type of family -- presently Family, Domain,
353            * Motif or Repeat. SQ Sequence: Number of sequences in alignment. AM
354            * Alignment Method The order ls and fs hits are aligned to the model
355            * to build the full align. // End of alignment.
356            * 
357            * Optional fields: ----------------
358            * 
359            * DC Database Comment: Comment about database reference. DR Database
360            * Reference: Reference to external database. RC Reference Comment:
361            * Comment about literature reference. RN Reference Number: Reference
362            * Number. RM Reference Medline: Eight digit medline UI number. RT
363            * Reference Title: Reference Title. RA Reference Author: Reference
364            * Author RL Reference Location: Journal location. PI Previous
365            * identifier: Record of all previous ID lines. KW Keywords: Keywords.
366            * CC Comment: Comments. NE Pfam accession: Indicates a nested domain.
367            * NL Location: Location of nested domains - sequence ID, start and
368            * end of insert.
369            * 
370            * Obsolete fields: ----------- AL Alignment method of seed: The
371            * method used to align the seed members.
372            */
373           // Let's save the annotations, maybe we'll be able to do something
374           // with them later...
375           Regex an = new Regex("(\\w+)\\s*(.*)");
376           if (an.search(annContent))
377           {
378             if (an.stringMatched(1).equals("NH"))
379             {
380               treeString.append(an.stringMatched(2));
381             }
382             else if (an.stringMatched(1).equals("TN"))
383             {
384               if (treeString.length() > 0)
385               {
386                 if (treeName == null)
387                 {
388                   treeName = "Tree " + (getTreeCount() + 1);
389                 }
390                 addNewickTree(treeName, treeString.toString());
391               }
392               treeName = an.stringMatched(2);
393               treeString = new StringBuffer();
394             }
395             setAlignmentProperty(an.stringMatched(1), an.stringMatched(2));
396           }
397         }
398         else if (annType.equals("GS"))
399         {
400           // Generic per-Sequence annotation, free text
401           /*
402            * Pfam uses these features: Feature Description ---------------------
403            * ----------- AC <accession> ACcession number DE <freetext>
404            * DEscription DR <db>; <accession>; Database Reference OS <organism>
405            * OrganiSm (species) OC <clade> Organism Classification (clade, etc.)
406            * LO <look> Look (Color, etc.)
407            */
408           if (s.search(annContent))
409           {
410             String acc = s.stringMatched(1);
411             String type = s.stringMatched(2);
412             String content = s.stringMatched(3);
413             // TODO: store DR in a vector.
414             // TODO: store AC according to generic file db annotation.
415             Hashtable ann;
416             if (seqAnn.containsKey(acc))
417             {
418               ann = (Hashtable) seqAnn.get(acc);
419             }
420             else
421             {
422               ann = new Hashtable();
423             }
424             ann.put(type, content);
425             seqAnn.put(acc, ann);
426           }
427           else
428           {
429             throw new IOException("Error parsing " + line);
430           }
431         }
432         else if (annType.equals("GC"))
433         {
434           // Generic per-Column annotation, exactly 1 char per column
435           // always need a label.
436           if (x.search(annContent))
437           {
438             // parse out and create alignment annotation directly.
439             parseAnnotationRow(annotations, x.stringMatched(1),
440                     x.stringMatched(2));
441           }
442         }
443         else if (annType.equals("GR"))
444         {
445           // Generic per-Sequence AND per-Column markup, exactly 1 char per
446           // column
447           /*
448            * Feature Description Markup letters ------- -----------
449            * -------------- SS Secondary Structure [HGIEBTSCX] SA Surface
450            * Accessibility [0-9X] (0=0%-10%; ...; 9=90%-100%) TM TransMembrane
451            * [Mio] PP Posterior Probability [0-9*] (0=0.00-0.05; 1=0.05-0.15;
452            * *=0.95-1.00) LI LIgand binding [*] AS Active Site [*] IN INtron (in
453            * or after) [0-2]
454            */
455           if (s.search(annContent))
456           {
457             String acc = s.stringMatched(1);
458             String type = s.stringMatched(2);
459             String seq = new String(s.stringMatched(3));
460             String description = null;
461             // Check for additional information about the current annotation
462             // We use a simple string tokenizer here for speed
463             StringTokenizer sep = new StringTokenizer(seq, " \t");
464             description = sep.nextToken();
465             if (sep.hasMoreTokens())
466             {
467               seq = sep.nextToken();
468             }
469             else
470             {
471               seq = description;
472               description = new String();
473             }
474             // sequence id with from-to fields
475
476             Hashtable ann;
477             // Get an object with all the annotations for this sequence
478             if (seqAnn.containsKey(acc))
479             {
480               // logger.debug("Found annotations for " + acc);
481               ann = (Hashtable) seqAnn.get(acc);
482             }
483             else
484             {
485               // logger.debug("Creating new annotations holder for " + acc);
486               ann = new Hashtable();
487               seqAnn.put(acc, ann);
488             }
489             // TODO test structure, call parseAnnotationRow with vector from
490             // hashtable for specific sequence
491             Hashtable features;
492             // Get an object with all the content for an annotation
493             if (ann.containsKey("features"))
494             {
495               // logger.debug("Found features for " + acc);
496               features = (Hashtable) ann.get("features");
497             }
498             else
499             {
500               // logger.debug("Creating new features holder for " + acc);
501               features = new Hashtable();
502               ann.put("features", features);
503             }
504
505             Hashtable content;
506             if (features.containsKey(this.id2type(type)))
507             {
508               // logger.debug("Found content for " + this.id2type(type));
509               content = (Hashtable) features.get(this.id2type(type));
510             }
511             else
512             {
513               // logger.debug("Creating new content holder for " +
514               // this.id2type(type));
515               content = new Hashtable();
516               features.put(this.id2type(type), content);
517             }
518             String ns = (String) content.get(description);
519             if (ns == null)
520             {
521               ns = "";
522             }
523             ns += seq;
524             content.put(description, ns);
525             Hashtable strucAnn;
526             if (seqAnn.containsKey(acc))
527             {
528               strucAnn = (Hashtable) seqAnn.get(acc);
529             }
530             else
531             {
532               strucAnn = new Hashtable();
533             }
534
535             Vector newStruc = new Vector();
536             parseAnnotationRow(newStruc, type, ns);
537             strucAnn.put(type, newStruc);
538             seqAnn.put(acc, strucAnn);
539           }
540           else
541           {
542             System.err
543                     .println("Warning - couldn't parse sequence annotation row line:\n"
544                             + line);
545             // throw new IOException("Error parsing " + line);
546           }
547         }
548         else
549         {
550           throw new IOException("Unknown annotation detected: " + annType
551                   + " " + annContent);
552         }
553       }
554     }
555     if (treeString.length() > 0)
556     {
557       if (treeName == null)
558       {
559         treeName = "Tree " + (1 + getTreeCount());
560       }
561       addNewickTree(treeName, treeString.toString());
562     }
563   }
564
565   protected static AlignmentAnnotation parseAnnotationRow(
566           Vector annotation, String label, String annots)
567   {
568     String convert1, convert2 = null;
569
570     // Convert all bracket types to parentheses
571     Regex openparen = new Regex("(<|\\[)", "(");
572     Regex closeparen = new Regex("(>|\\])", ")");
573
574     // Detect if file is RNA by looking for bracket types
575     Regex detectbrackets = new Regex("(<|>|\\[|\\]|\\(|\\))");
576
577     convert1 = openparen.replaceAll(annots);
578     convert2 = closeparen.replaceAll(convert1);
579     annots = convert2;
580     
581     String type = label;
582     if (label.contains("_cons")) {
583         type = (label.indexOf("_cons") == label.length() - 5) ? label
584                 .substring(0, label.length() - 5) : label;      
585     }      
586     boolean ss = false;
587     type = id2type(type);
588     if (type.equals("secondary structure"))
589     {
590       ss = true;
591     }
592     // decide on secondary structure or not.
593     Annotation[] els = new Annotation[annots.length()];
594     for (int i = 0; i < annots.length(); i++)
595     {
596       String pos = annots.substring(i, i + 1);
597       Annotation ann;
598       ann = new Annotation(pos, "", ' ', 0f); // 0f is 'valid' null - will not
599       // be written out
600       if (ss)
601       {
602         if (detectbrackets.search(pos))
603         {
604           ann.secondaryStructure = jalview.schemes.ResidueProperties
605                   .getRNASecStrucState(pos).charAt(0);
606         }
607         else
608         {
609           ann.secondaryStructure = jalview.schemes.ResidueProperties
610                   .getDssp3state(pos).charAt(0);
611         }
612
613         if (ann.secondaryStructure == pos.charAt(0) || pos.charAt(0) == 'C')
614         {
615           ann.displayCharacter = ""; // null; // " ";
616         }
617         else
618         {
619           ann.displayCharacter = " " + ann.displayCharacter;
620         }
621       }
622
623       els[i] = ann;
624     }
625     AlignmentAnnotation annot = null;
626     Enumeration e = annotation.elements();
627     while (e.hasMoreElements())
628     {
629       annot = (AlignmentAnnotation) e.nextElement();
630       if (annot.label.equals(type))
631         break;
632       annot = null;
633     }
634     if (annot == null)
635     {
636       annot = new AlignmentAnnotation(type, type, els);
637       annotation.addElement(annot);
638     }
639     else
640     {
641       Annotation[] anns = new Annotation[annot.annotations.length
642               + els.length];
643       System.arraycopy(annot.annotations, 0, anns, 0,
644               annot.annotations.length);
645       System.arraycopy(els, 0, anns, annot.annotations.length, els.length);
646       annot.annotations = anns;
647       // System.out.println("else: ");
648     }
649     return annot;
650   }
651   
652   public String print(SequenceI[] s)
653   {
654           // find max length of id
655             int max = 0;
656             int maxid = 0;
657             int in = 0;
658             Hashtable dataRef = null;
659             while ((in < s.length) && (s[in] != null))
660             {
661               String tmp = printId(s[in]);
662               if (s[in].getSequence().length > max)
663               {
664                 max = s[in].getSequence().length;
665               }
666
667               if (tmp.length() > maxid)
668               {
669                 maxid = tmp.length();
670               }
671               if (s[in].getDBRef() != null)
672               {  
673                 for (int idb = 0; idb < s[in].getDBRef().length; idb++)
674                 {               
675                   if (dataRef == null) 
676                         dataRef = new Hashtable();
677   
678                   String datAs1 = s[in].getDBRef()[idb].getSource().toString() + " ; " +s[in].getDBRef()[idb].getAccessionId().toString();
679                   dataRef.put(tmp, datAs1);
680             }
681           }
682               in++;
683             }
684             maxid += 9;
685             int i = 0;
686             
687             // output database type
688             if (al.getProperties() != null)
689             {
690               if (!al.getProperties().isEmpty())
691               {
692                 Enumeration key = al.getProperties().keys();
693                 Enumeration val = al.getProperties().elements();
694                 while (key.hasMoreElements())
695                 {  
696                    out.append("#=GF " + key.nextElement() + " " + val.nextElement());
697                    out.append(newline);
698                 }
699               }  
700             }
701             
702             // output  database accessions 
703             if (dataRef != null)
704             {
705               Enumeration en = dataRef.keys();    
706               while (en.hasMoreElements())
707               {
708                  Object idd = en.nextElement();
709                  String type = (String) dataRef.remove(idd);
710                  out.append(new Format("%-" + (maxid - 2) + "s").form("#=GS " +idd.toString() + " "));
711                  if (type.contains("PFAM") || type.contains("RFAM") )
712                  {
713                 
714                         out.append(" AC " + type.substring(type.indexOf(";") + 1));
715                  } else
716                  {
717                     out.append(" DR " + type + " ");
718                  }
719                  out.append(newline);
720               } 
721             }
722             
723             // output annotations
724             while (i < s.length && s[i] != null) 
725             {
726               if (s[i].getDatasetSequence() != null) 
727               {
728                 SequenceI ds = s[i].getDatasetSequence();       
729                         AlignmentAnnotation[] alAnot;
730                     Annotation[] ann;
731                     Annotation annot;  
732                     alAnot = s[i].getAnnotation();
733                     String feature = "";
734                 if (alAnot != null) 
735                 {
736                           for (int j = 0; j < alAnot.length; j++) 
737                           {     
738                             if (ds.getSequenceFeatures() != null) 
739                     {
740                                   feature = ds.getSequenceFeatures()[0].type;
741                             }   
742                             String key = type2id(feature);
743                             
744                        
745                         if (key == null)
746                             continue;
747                         
748                           //  out.append("#=GR ");
749                             out.append(new Format("%-" + maxid + "s").form("#=GR " + printId(s[i]) + " " + key + " "));
750                             ann = alAnot[j].annotations;
751                             String seq = "";
752                                 for (int k = 0; k < ann.length; k++) 
753                                 {         
754                               annot = ann[k]; 
755                               String ch = (annot == null) ? Character.toString(s[i].getCharAt(k)) : annot.displayCharacter;
756                               if (ch.length() == 0)
757                           {
758                             if (key.equals("SS")) {
759                               char ll = annot.secondaryStructure;
760                                   seq = (Character.toString(ll).equals(" ")) ? seq + "C" : seq + ll;    
761                                 } else {
762                                   seq += ".";  
763                                   }
764                                 } else if (ch.length() == 1) {
765                                       seq += ch;
766                                     } else if (ch.length() > 1) {
767                                       seq += ch.charAt(1) ;
768                                 }   
769                               }
770                               out.append(seq);
771                               out.append(newline);
772                           }
773                 }
774                   }
775             
776               out.append(new Format("%-" + maxid + "s").form(printId(s[i])+" "));
777                   out.append(s[i].getSequenceAsString());
778                   out.append(newline);  
779               i++;
780             } 
781             
782             // alignment annotation
783             AlignmentAnnotation aa;
784             if (al.getAlignmentAnnotation() != null) 
785             {
786               for (int ia = 0; ia < al.getAlignmentAnnotation().length; ia++)
787               {
788                 aa = al.getAlignmentAnnotation()[ia];
789                 if (aa.autoCalculated || !aa.visible)
790                 {
791                   continue;
792                 }
793                 String seq = "";
794                 String label;
795                 
796                 if (aa.label.equals("seq"))
797                   label = "seq_cons";
798                 else
799                   label = type2id(aa.label.toLowerCase())+"_cons";
800
801                 if (label == null) 
802                   label = aa.label;     
803                  
804                 out.append(new Format("%-" + maxid + "s").form("#=GC " + label+" "));
805                 for (int j = 0; j < aa.annotations.length; j++) 
806                 {
807                   String ch = (aa.annotations[j] == null) ? "-" : aa.annotations[j].displayCharacter ;
808                   if (ch.length() == 0) 
809                   {
810                     char ll = aa.annotations[j].secondaryStructure;
811                             if (Character.toString(ll).equals(" "))
812                               seq += "C";
813                                 else 
814                               seq += ll;  
815                   } else if (ch.length() == 1) {
816                     seq += ch;
817                   } else if (ch.length() > 1) {
818                     seq += ch.charAt(1) ;
819                   }   
820                 }
821                     out.append(seq);
822                 out.append(newline);
823               }
824             }
825                 return out.toString();
826   }
827
828   public String print()
829   {
830         out = new StringBuffer();
831         out.append("# STOCKHOLM 1.0");
832         out.append(newline); 
833     print(getSeqsAsArray());
834             
835     out.append("//");
836     out.append(newline);  
837     return out.toString();
838   }
839
840   private static Hashtable typeIds = null;
841   static
842   {
843     if (typeIds == null)
844     {
845       typeIds = new Hashtable();
846       typeIds.put("SS", "secondary structure");
847       typeIds.put("SA", "surface accessibility");
848       typeIds.put("TM", "transmembrane");
849       typeIds.put("PP", "posterior probability");
850       typeIds.put("LI", "ligand binding");
851       typeIds.put("AS", "active site");
852       typeIds.put("IN", "intron");
853       typeIds.put("IR", "interacting residue");
854       typeIds.put("AC", "accession");
855       typeIds.put("OS", "organism");
856       typeIds.put("CL", "class");
857       typeIds.put("DE", "description");
858       typeIds.put("DR", "reference");
859       typeIds.put("LO", "look");
860       typeIds.put("RF", "reference positions");
861
862     }
863   }
864
865   protected static String id2type(String id)
866   {
867     if (typeIds.containsKey(id))
868     {
869       return (String) typeIds.get(id);
870     }
871     System.err.println("Warning : Unknown Stockholm annotation type code "
872             + id);
873     return id;
874   }
875   
876   protected static String type2id(String type)
877   {
878           String key = null;
879           Enumeration e = typeIds.keys();
880       while (e.hasMoreElements()) 
881       {
882         Object ll = e.nextElement();
883         if (typeIds.get(ll).toString().equals(type))
884         {       
885           key = (String) ll;
886           break;
887         }
888       }  
889       if (key != null) 
890       {
891          return (String) key;
892       }
893       System.err.println("Warning : Unknown Stockholm annotation type: "
894             + type);
895     return key;
896   }
897   /**
898    * //ssline is complete secondary structure line private AlignmentAnnotation
899    * addHelices(Vector annotation, String label, String ssline) {
900    * 
901    * // decide on secondary structure or not. Annotation[] els = new
902    * Annotation[ssline.length()]; for (int i = 0; i < ssline.length(); i++) {
903    * String pos = ssline.substring(i, i + 1); Annotation ann; ann = new
904    * Annotation(pos, "", ' ', 0f); // 0f is 'valid' null - will not
905    * 
906    * ann.secondaryStructure =
907    * jalview.schemes.ResidueProperties.getRNAssState(pos).charAt(0);
908    * 
909    * ann.displayCharacter = "x" + ann.displayCharacter;
910    * 
911    * System.out.println(ann.displayCharacter);
912    * 
913    * els[i] = ann; } AlignmentAnnotation helicesAnnot = null; Enumeration e =
914    * annotation.elements(); while (e.hasMoreElements()) { helicesAnnot =
915    * (AlignmentAnnotation) e.nextElement(); if (helicesAnnot.label.equals(type))
916    * break; helicesAnnot = null; } if (helicesAnnot == null) { helicesAnnot =
917    * new AlignmentAnnotation(type, type, els);
918    * annotation.addElement(helicesAnnot); } else { Annotation[] anns = new
919    * Annotation[helicesAnnot.annotations.length + els.length];
920    * System.arraycopy(helicesAnnot.annotations, 0, anns, 0,
921    * helicesAnnot.annotations.length); System.arraycopy(els, 0, anns,
922    * helicesAnnot.annotations.length, els.length); helicesAnnot.annotations =
923    * anns; }
924    * 
925    * helicesAnnot.features = Rna.GetBasePairs(ssline);
926    * Rna.HelixMap(helicesAnnot.features);
927    * 
928    * 
929    * return helicesAnnot; }
930    */
931 }