2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.2)
3 * Copyright (C) 2014 The Jalview Authors
5 * This file is part of Jalview.
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.
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.
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.
22 * This extension was written by Benjamin Schuster-Boeckler at sanger.ac.uk
26 import jalview.datamodel.AlignmentI;
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.util.Format;
37 import java.io.BufferedReader;
38 import java.io.FileReader;
39 import java.io.IOException;
40 import java.util.ArrayList;
41 import java.util.Enumeration;
42 import java.util.Hashtable;
43 import java.util.List;
44 import java.util.StringTokenizer;
45 import java.util.Vector;
47 import com.stevesoft.pat.Regex;
49 import fr.orsay.lri.varna.exceptions.ExceptionUnmatchedClosingParentheses;
50 import fr.orsay.lri.varna.factories.RNAFactory;
51 import fr.orsay.lri.varna.models.rna.RNA;
53 // import org.apache.log4j.*;
56 * This class is supposed to parse a Stockholm format file into Jalview There
57 * are TODOs in this class: we do not know what the database source and version
58 * is for the file when parsing the #GS= AC tag which associates accessions with
59 * sequences. Database references are also not parsed correctly: a separate
60 * reference string parser must be added to parse the database reference form
61 * into Jalview's local representation.
63 * @author bsb at sanger.ac.uk
64 * @author Natasha Shersnev (Dundee, UK) (Stockholm file writer)
65 * @author Lauren Lui (UCSC, USA) (RNA secondary structure annotation import as
67 * @author Anne Menard (Paris, FR) (VARNA parsing of Stockholm file data)
68 * @version 0.3 + jalview mods
71 public class StockholmFile extends AlignFile
73 // static Logger logger = Logger.getLogger("jalview.io.StockholmFile");
74 protected ArrayList<RNA> result;
76 StringBuffer out; // output buffer
80 public StockholmFile()
85 * Creates a new StockholmFile object for output.
87 public StockholmFile(AlignmentI al)
92 public StockholmFile(String inFile, String type) throws IOException
97 public StockholmFile(FileParse source) throws IOException
102 public void initData()
108 * Parse a file in Stockholm format into Jalview's data model using VARNA
110 * @throws IOException
111 * If there is an error with the input file
113 public void parse_with_VARNA(java.io.File inFile) throws IOException
115 FileReader fr = null;
116 fr = new FileReader(inFile);
118 BufferedReader r = new BufferedReader(fr);
122 result = RNAFactory.loadSecStrStockholm(r);
123 } catch (ExceptionUnmatchedClosingParentheses umcp)
125 errormessage = "Unmatched parentheses in annotation. Aborting ("
126 + umcp.getMessage() + ")";
127 throw new IOException(umcp);
129 // DEBUG System.out.println("this is the secondary scructure:"
131 SequenceI[] seqs = new SequenceI[result.size()];
133 for (int i = 0; i < result.size(); i++)
135 // DEBUG System.err.println("Processing i'th sequence in Stockholm file")
136 RNA current = result.get(i);
138 String seq = current.getSeq();
139 String rna = current.getStructDBN(true);
140 // DEBUG System.out.println(seq);
141 // DEBUG System.err.println(rna);
143 int end = seq.length() - 1;
144 id = safeName(getDataName());
145 seqs[i] = new Sequence(id, seq, begin, end);
146 String[] annot = new String[rna.length()];
147 Annotation[] ann = new Annotation[rna.length()];
148 for (int j = 0; j < rna.length(); j++)
150 annot[j] = rna.substring(j, j + 1);
154 for (int k = 0; k < rna.length(); k++)
156 ann[k] = new Annotation(annot[k], "",
157 jalview.schemes.ResidueProperties.getRNASecStrucState(
158 annot[k]).charAt(0), 0f);
161 AlignmentAnnotation align = new AlignmentAnnotation("Sec. str.",
162 current.getID(), ann);
164 seqs[i].addAlignmentAnnotation(align);
165 seqs[i].setRNA(result.get(i));
166 this.annotations.addElement(align);
173 * Parse a file in Stockholm format into Jalview's data model. The file has to
174 * be passed at construction time
176 * @throws IOException
177 * If there is an error with the input file
179 public void parse() throws IOException
181 StringBuffer treeString = new StringBuffer();
182 String treeName = null;
183 // --------------- Variable Definitions -------------------
187 Hashtable seqAnn = new Hashtable(); // Sequence related annotations
188 Hashtable seqs = new Hashtable();
189 Regex p, r, rend, s, x;
190 // Temporary line for processing RNA annotation
191 // String RNAannot = "";
193 // ------------------ Parsing File ----------------------
194 // First, we have to check that this file has STOCKHOLM format, i.e. the
195 // first line must match
197 r = new Regex("# STOCKHOLM ([\\d\\.]+)");
198 if (!r.search(nextLine()))
200 throw new IOException(
201 "This file is not in valid STOCKHOLM format: First line does not contain '# STOCKHOLM'");
205 version = r.stringMatched(1);
207 // logger.debug("Stockholm version: " + version);
210 // We define some Regexes here that will be used regularily later
211 rend = new Regex("^\\s*\\/\\/"); // Find the end of an alignment
212 p = new Regex("(\\S+)\\/(\\d+)\\-(\\d+)"); // split sequence id in
214 s = new Regex("(\\S+)\\s+(\\S*)\\s+(.*)"); // Parses annotation subtype
215 r = new Regex("#=(G[FSRC]?)\\s+(.*)"); // Finds any annotation line
216 x = new Regex("(\\S+)\\s+(\\S+)"); // split id from sequence
218 // Convert all bracket types to parentheses (necessary for passing to VARNA)
219 Regex openparen = new Regex("(<|\\[)", "(");
220 Regex closeparen = new Regex("(>|\\])", ")");
222 // Detect if file is RNA by looking for bracket types
223 Regex detectbrackets = new Regex("(<|>|\\[|\\]|\\(|\\))");
230 openparen.optimize();
231 closeparen.optimize();
233 while ((line = nextLine()) != null)
235 if (line.length() == 0)
239 if (rend.search(line))
241 // End of the alignment, pass stuff back
242 this.noSeqs = seqs.size();
244 String seqdb, dbsource = null;
245 Regex pf = new Regex("PF[0-9]{5}(.*)"); // Finds AC for Pfam
246 Regex rf = new Regex("RF[0-9]{5}(.*)"); // Finds AC for Rfam
247 if (getAlignmentProperty("AC") != null)
249 String dbType = getAlignmentProperty("AC").toString();
250 if (pf.search(dbType))
252 // PFAM Alignment - so references are typically from Uniprot
255 else if (rf.search(dbType))
260 // logger.debug("Number of sequences: " + this.noSeqs);
261 Enumeration accs = seqs.keys();
262 while (accs.hasMoreElements())
264 String acc = (String) accs.nextElement();
265 // logger.debug("Processing sequence " + acc);
266 String seq = (String) seqs.remove(acc);
267 if (maxLength < seq.length())
269 maxLength = seq.length();
275 * Retrieve hash of annotations for this accession Associate
276 * Annotation with accession
278 Hashtable accAnnotations = null;
280 if (seqAnn != null && seqAnn.containsKey(acc))
282 accAnnotations = (Hashtable) seqAnn.remove(acc);
283 // TODO: add structures to sequence
286 // Split accession in id and from/to
289 sid = p.stringMatched(1);
290 start = Integer.parseInt(p.stringMatched(2));
291 end = Integer.parseInt(p.stringMatched(3));
293 // logger.debug(sid + ", " + start + ", " + end);
295 Sequence seqO = new Sequence(sid, seq, start, end);
296 // Add Description (if any)
297 if (accAnnotations != null && accAnnotations.containsKey("DE"))
299 String desc = (String) accAnnotations.get("DE");
300 seqO.setDescription((desc == null) ? "" : desc);
302 // Add DB References (if any)
303 if (accAnnotations != null && accAnnotations.containsKey("DR"))
305 String dbr = (String) accAnnotations.get("DR");
306 if (dbr != null && dbr.indexOf(";") > -1)
308 String src = dbr.substring(0, dbr.indexOf(";"));
309 String acn = dbr.substring(dbr.indexOf(";") + 1);
310 jalview.util.DBRefUtils.parseToDbRef(seqO, src, "0", acn);
314 if (accAnnotations != null && accAnnotations.containsKey("AC"))
316 if (dbsource != null)
318 String dbr = (String) accAnnotations.get("AC");
321 // we could get very clever here - but for now - just try to
322 // guess accession type from source of alignment plus structure
324 guessDatabaseFor(seqO, dbr, dbsource);
328 // else - do what ? add the data anyway and prompt the user to
329 // specify what references these are ?
332 Hashtable features = null;
333 // We need to adjust the positions of all features to account for gaps
336 features = (Hashtable) accAnnotations.remove("features");
337 } catch (java.lang.NullPointerException e)
339 // loggerwarn("Getting Features for " + acc + ": " +
343 // if we have features
344 if (features != null)
346 int posmap[] = seqO.findPositionMap();
347 Enumeration i = features.keys();
348 while (i.hasMoreElements())
350 // TODO: parse out secondary structure annotation as annotation
352 // TODO: parse out scores as annotation row
353 // TODO: map coding region to core jalview feature types
354 String type = i.nextElement().toString();
355 Hashtable content = (Hashtable) features.remove(type);
357 // add alignment annotation for this feature
358 String key = type2id(type);
361 if (accAnnotations != null
362 && accAnnotations.containsKey(key))
364 Vector vv = (Vector) accAnnotations.get(key);
365 for (int ii = 0; ii < vv.size(); ii++)
367 AlignmentAnnotation an = (AlignmentAnnotation) vv
369 seqO.addAlignmentAnnotation(an);
374 Enumeration j = content.keys();
375 while (j.hasMoreElements())
377 String desc = j.nextElement().toString();
378 String ns = content.get(desc).toString();
379 char[] byChar = ns.toCharArray();
380 for (int k = 0; k < byChar.length; k++)
383 if (!(c == ' ' || c == '_' || c == '-' || c == '.')) // PFAM
390 int new_pos = posmap[k]; // look up nearest seqeunce
391 // position to this column
392 SequenceFeature feat = new SequenceFeature(type, desc,
393 new_pos, new_pos, 0f, null);
395 seqO.addSequenceFeature(feat);
405 // logger.debug("Adding seq " + acc + " from " + start + " to " + end
407 this.seqs.addElement(seqO);
409 return; // finished parsing this segment of source
411 else if (!r.search(line))
413 // System.err.println("Found sequence line: " + line);
415 // Split sequence in sequence and accession parts
418 // logger.error("Could not parse sequence line: " + line);
419 throw new IOException("Could not parse sequence line: " + line);
421 String ns = (String) seqs.get(x.stringMatched(1));
426 ns += x.stringMatched(2);
428 seqs.put(x.stringMatched(1), ns);
432 String annType = r.stringMatched(1);
433 String annContent = r.stringMatched(2);
435 // System.err.println("type:" + annType + " content: " + annContent);
437 if (annType.equals("GF"))
440 * Generic per-File annotation, free text Magic features: #=GF NH
441 * <tree in New Hampshire eXtended format> #=GF TN <Unique identifier
442 * for the next tree> Pfam descriptions: 7. DESCRIPTION OF FIELDS
444 * Compulsory fields: ------------------
446 * AC Accession number: Accession number in form PFxxxxx.version or
447 * PBxxxxxx. ID Identification: One word name for family. DE
448 * Definition: Short description of family. AU Author: Authors of the
449 * entry. SE Source of seed: The source suggesting the seed members
450 * belong to one family. GA Gathering method: Search threshold to
451 * build the full alignment. TC Trusted Cutoff: Lowest sequence score
452 * and domain score of match in the full alignment. NC Noise Cutoff:
453 * Highest sequence score and domain score of match not in full
454 * alignment. TP Type: Type of family -- presently Family, Domain,
455 * Motif or Repeat. SQ Sequence: Number of sequences in alignment. AM
456 * Alignment Method The order ls and fs hits are aligned to the model
457 * to build the full align. // End of alignment.
459 * Optional fields: ----------------
461 * DC Database Comment: Comment about database reference. DR Database
462 * Reference: Reference to external database. RC Reference Comment:
463 * Comment about literature reference. RN Reference Number: Reference
464 * Number. RM Reference Medline: Eight digit medline UI number. RT
465 * Reference Title: Reference Title. RA Reference Author: Reference
466 * Author RL Reference Location: Journal location. PI Previous
467 * identifier: Record of all previous ID lines. KW Keywords: Keywords.
468 * CC Comment: Comments. NE Pfam accession: Indicates a nested domain.
469 * NL Location: Location of nested domains - sequence ID, start and
472 * Obsolete fields: ----------- AL Alignment method of seed: The
473 * method used to align the seed members.
475 // Let's save the annotations, maybe we'll be able to do something
476 // with them later...
477 Regex an = new Regex("(\\w+)\\s*(.*)");
478 if (an.search(annContent))
480 if (an.stringMatched(1).equals("NH"))
482 treeString.append(an.stringMatched(2));
484 else if (an.stringMatched(1).equals("TN"))
486 if (treeString.length() > 0)
488 if (treeName == null)
490 treeName = "Tree " + (getTreeCount() + 1);
492 addNewickTree(treeName, treeString.toString());
494 treeName = an.stringMatched(2);
495 treeString = new StringBuffer();
497 setAlignmentProperty(an.stringMatched(1), an.stringMatched(2));
500 else if (annType.equals("GS"))
502 // Generic per-Sequence annotation, free text
504 * Pfam uses these features: Feature Description ---------------------
505 * ----------- AC <accession> ACcession number DE <freetext>
506 * DEscription DR <db>; <accession>; Database Reference OS <organism>
507 * OrganiSm (species) OC <clade> Organism Classification (clade, etc.)
508 * LO <look> Look (Color, etc.)
510 if (s.search(annContent))
512 String acc = s.stringMatched(1);
513 String type = s.stringMatched(2);
514 String content = s.stringMatched(3);
515 // TODO: store DR in a vector.
516 // TODO: store AC according to generic file db annotation.
518 if (seqAnn.containsKey(acc))
520 ann = (Hashtable) seqAnn.get(acc);
524 ann = new Hashtable();
526 ann.put(type, content);
527 seqAnn.put(acc, ann);
531 throw new IOException("Error parsing " + line);
534 else if (annType.equals("GC"))
536 // Generic per-Column annotation, exactly 1 char per column
537 // always need a label.
538 if (x.search(annContent))
540 // parse out and create alignment annotation directly.
541 parseAnnotationRow(annotations, x.stringMatched(1),
545 else if (annType.equals("GR"))
547 // Generic per-Sequence AND per-Column markup, exactly 1 char per
550 * Feature Description Markup letters ------- -----------
551 * -------------- SS Secondary Structure [HGIEBTSCX] SA Surface
552 * Accessibility [0-9X] (0=0%-10%; ...; 9=90%-100%) TM TransMembrane
553 * [Mio] PP Posterior Probability [0-9*] (0=0.00-0.05; 1=0.05-0.15;
554 * *=0.95-1.00) LI LIgand binding [*] AS Active Site [*] IN INtron (in
557 if (s.search(annContent))
559 String acc = s.stringMatched(1);
560 String type = s.stringMatched(2);
561 String seq = new String(s.stringMatched(3));
562 String description = null;
563 // Check for additional information about the current annotation
564 // We use a simple string tokenizer here for speed
565 StringTokenizer sep = new StringTokenizer(seq, " \t");
566 description = sep.nextToken();
567 if (sep.hasMoreTokens())
569 seq = sep.nextToken();
574 description = new String();
576 // sequence id with from-to fields
579 // Get an object with all the annotations for this sequence
580 if (seqAnn.containsKey(acc))
582 // logger.debug("Found annotations for " + acc);
583 ann = (Hashtable) seqAnn.get(acc);
587 // logger.debug("Creating new annotations holder for " + acc);
588 ann = new Hashtable();
589 seqAnn.put(acc, ann);
591 // TODO test structure, call parseAnnotationRow with vector from
592 // hashtable for specific sequence
594 // Get an object with all the content for an annotation
595 if (ann.containsKey("features"))
597 // logger.debug("Found features for " + acc);
598 features = (Hashtable) ann.get("features");
602 // logger.debug("Creating new features holder for " + acc);
603 features = new Hashtable();
604 ann.put("features", features);
608 if (features.containsKey(this.id2type(type)))
610 // logger.debug("Found content for " + this.id2type(type));
611 content = (Hashtable) features.get(this.id2type(type));
615 // logger.debug("Creating new content holder for " +
616 // this.id2type(type));
617 content = new Hashtable();
618 features.put(this.id2type(type), content);
620 String ns = (String) content.get(description);
626 content.put(description, ns);
628 // if(type.equals("SS")){
630 if (seqAnn.containsKey(acc))
632 strucAnn = (Hashtable) seqAnn.get(acc);
636 strucAnn = new Hashtable();
639 Vector newStruc = new Vector();
640 parseAnnotationRow(newStruc, type, ns);
642 strucAnn.put(type, newStruc);
643 seqAnn.put(acc, strucAnn);
649 .println("Warning - couldn't parse sequence annotation row line:\n"
651 // throw new IOException("Error parsing " + line);
656 throw new IOException("Unknown annotation detected: " + annType
661 if (treeString.length() > 0)
663 if (treeName == null)
665 treeName = "Tree " + (1 + getTreeCount());
667 addNewickTree(treeName, treeString.toString());
672 * Demangle an accession string and guess the originating sequence database
673 * for a given sequence
676 * sequence to be annotated
678 * Accession string for sequence
680 * source database for alignment (PFAM or RFAM)
682 private void guessDatabaseFor(Sequence seqO, String dbr, String dbsource)
684 DBRefEntry dbrf = null;
685 List<DBRefEntry> dbrs = new ArrayList<DBRefEntry>();
686 String seqdb = "Unknown", sdbac = "" + dbr;
687 int st = -1, en = -1, p;
688 if ((st = sdbac.indexOf("/")) > -1)
690 String num, range = sdbac.substring(st + 1);
691 sdbac = sdbac.substring(0, st);
692 if ((p = range.indexOf("-")) > -1)
695 if (p < range.length())
697 num = range.substring(p).trim();
700 en = Integer.parseInt(num);
701 } catch (NumberFormatException x)
703 // could warn here that index is invalid
712 num = range.substring(0, p).trim();
715 st = Integer.parseInt(num);
716 } catch (NumberFormatException x)
718 // could warn here that index is invalid
722 if (dbsource.equals("PFAM"))
725 if (sdbac.indexOf(".") > -1)
727 // strip of last subdomain
728 sdbac = sdbac.substring(0, sdbac.indexOf("."));
729 dbrf = jalview.util.DBRefUtils.parseToDbRef(seqO, seqdb, dbsource,
736 dbrf = jalview.util.DBRefUtils.parseToDbRef(seqO, dbsource, dbsource,
745 seqdb = "EMBL"; // total guess - could be ENA, or something else these
747 if (sdbac.indexOf(".") > -1)
749 // strip off last subdomain
750 sdbac = sdbac.substring(0, sdbac.indexOf("."));
751 dbrf = jalview.util.DBRefUtils.parseToDbRef(seqO, seqdb, dbsource,
759 dbrf = jalview.util.DBRefUtils.parseToDbRef(seqO, dbsource, dbsource,
766 if (st != -1 && en != -1)
768 for (DBRefEntry d : dbrs)
770 jalview.util.MapList mp = new jalview.util.MapList(new int[]
771 { seqO.getStart(), seqO.getEnd() }, new int[]
773 jalview.datamodel.Mapping mping = new Mapping(mp);
779 protected static AlignmentAnnotation parseAnnotationRow(
780 Vector annotation, String label, String annots)
782 String convert1, convert2 = null;
784 // Convert all bracket types to parentheses
785 Regex openparen = new Regex("(<|\\[)", "(");
786 Regex closeparen = new Regex("(>|\\])", ")");
788 // Detect if file is RNA by looking for bracket types
789 Regex detectbrackets = new Regex("(<|>|\\[|\\]|\\(|\\))");
791 convert1 = openparen.replaceAll(annots);
792 convert2 = closeparen.replaceAll(convert1);
796 if (label.contains("_cons"))
798 type = (label.indexOf("_cons") == label.length() - 5) ? label
799 .substring(0, label.length() - 5) : label;
802 type = id2type(type);
803 if (type.equals("secondary structure"))
807 // decide on secondary structure or not.
808 Annotation[] els = new Annotation[annots.length()];
809 for (int i = 0; i < annots.length(); i++)
811 String pos = annots.substring(i, i + 1);
813 ann = new Annotation(pos, "", ' ', 0f); // 0f is 'valid' null - will not
817 if (detectbrackets.search(pos))
819 ann.secondaryStructure = jalview.schemes.ResidueProperties
820 .getRNASecStrucState(pos).charAt(0);
824 ann.secondaryStructure = jalview.schemes.ResidueProperties
825 .getDssp3state(pos).charAt(0);
828 if (ann.secondaryStructure == pos.charAt(0) || pos.charAt(0) == 'C')
830 ann.displayCharacter = ""; // null; // " ";
834 ann.displayCharacter = " " + ann.displayCharacter;
840 AlignmentAnnotation annot = null;
841 Enumeration e = annotation.elements();
842 while (e.hasMoreElements())
844 annot = (AlignmentAnnotation) e.nextElement();
845 if (annot.label.equals(type))
851 annot = new AlignmentAnnotation(type, type, els);
852 annotation.addElement(annot);
856 Annotation[] anns = new Annotation[annot.annotations.length
858 System.arraycopy(annot.annotations, 0, anns, 0,
859 annot.annotations.length);
860 System.arraycopy(els, 0, anns, annot.annotations.length, els.length);
861 annot.annotations = anns;
862 // System.out.println("else: ");
867 public String print(SequenceI[] s)
869 // find max length of id
873 Hashtable dataRef = null;
874 while ((in < s.length) && (s[in] != null))
876 String tmp = printId(s[in]);
877 if (s[in].getSequence().length > max)
879 max = s[in].getSequence().length;
882 if (tmp.length() > maxid)
884 maxid = tmp.length();
886 if (s[in].getDBRef() != null)
888 for (int idb = 0; idb < s[in].getDBRef().length; idb++)
891 dataRef = new Hashtable();
893 String datAs1 = s[in].getDBRef()[idb].getSource().toString()
895 + s[in].getDBRef()[idb].getAccessionId().toString();
896 dataRef.put(tmp, datAs1);
904 // output database type
905 if (al.getProperties() != null)
907 if (!al.getProperties().isEmpty())
909 Enumeration key = al.getProperties().keys();
910 Enumeration val = al.getProperties().elements();
911 while (key.hasMoreElements())
913 out.append("#=GF " + key.nextElement() + " " + val.nextElement());
919 // output database accessions
922 Enumeration en = dataRef.keys();
923 while (en.hasMoreElements())
925 Object idd = en.nextElement();
926 String type = (String) dataRef.remove(idd);
927 out.append(new Format("%-" + (maxid - 2) + "s").form("#=GS "
928 + idd.toString() + " "));
929 if (type.contains("PFAM") || type.contains("RFAM"))
932 out.append(" AC " + type.substring(type.indexOf(";") + 1));
936 out.append(" DR " + type + " ");
942 // output annotations
943 while (i < s.length && s[i] != null)
945 if (s[i].getDatasetSequence() != null)
947 SequenceI ds = s[i].getDatasetSequence();
948 AlignmentAnnotation[] alAnot;
951 alAnot = s[i].getAnnotation();
955 for (int j = 0; j < alAnot.length; j++)
957 if (ds.getSequenceFeatures() != null)
959 feature = ds.getSequenceFeatures()[0].type;
961 String key = type2id(feature);
966 // out.append("#=GR ");
967 out.append(new Format("%-" + maxid + "s").form("#=GR "
968 + printId(s[i]) + " " + key + " "));
969 ann = alAnot[j].annotations;
971 for (int k = 0; k < ann.length; k++)
974 String ch = (annot == null) ? Character.toString(s[i]
975 .getCharAt(k)) : annot.displayCharacter;
976 if (ch.length() == 0)
978 if (key.equals("SS"))
980 char ll = annot.secondaryStructure;
981 seq = (Character.toString(ll).equals(" ")) ? seq + "C"
989 else if (ch.length() == 1)
993 else if (ch.length() > 1)
1004 out.append(new Format("%-" + maxid + "s").form(printId(s[i]) + " "));
1005 out.append(s[i].getSequenceAsString());
1006 out.append(newline);
1010 // alignment annotation
1011 AlignmentAnnotation aa;
1012 if (al.getAlignmentAnnotation() != null)
1014 for (int ia = 0; ia < al.getAlignmentAnnotation().length; ia++)
1016 aa = al.getAlignmentAnnotation()[ia];
1017 if (aa.autoCalculated || !aa.visible)
1024 if (aa.label.equals("seq"))
1027 label = type2id(aa.label.toLowerCase()) + "_cons";
1032 out.append(new Format("%-" + maxid + "s").form("#=GC " + label
1034 for (int j = 0; j < aa.annotations.length; j++)
1036 String ch = (aa.annotations[j] == null) ? "-"
1037 : aa.annotations[j].displayCharacter;
1038 if (ch.length() == 0)
1040 char ll = aa.annotations[j].secondaryStructure;
1041 if (Character.toString(ll).equals(" "))
1046 else if (ch.length() == 1)
1050 else if (ch.length() > 1)
1052 seq += ch.charAt(1);
1056 out.append(newline);
1059 return out.toString();
1062 public String print()
1064 out = new StringBuffer();
1065 out.append("# STOCKHOLM 1.0");
1066 out.append(newline);
1067 print(getSeqsAsArray());
1070 out.append(newline);
1071 return out.toString();
1074 private static Hashtable typeIds = null;
1077 if (typeIds == null)
1079 typeIds = new Hashtable();
1080 typeIds.put("SS", "secondary structure");
1081 typeIds.put("SA", "surface accessibility");
1082 typeIds.put("TM", "transmembrane");
1083 typeIds.put("PP", "posterior probability");
1084 typeIds.put("LI", "ligand binding");
1085 typeIds.put("AS", "active site");
1086 typeIds.put("IN", "intron");
1087 typeIds.put("IR", "interacting residue");
1088 typeIds.put("AC", "accession");
1089 typeIds.put("OS", "organism");
1090 typeIds.put("CL", "class");
1091 typeIds.put("DE", "description");
1092 typeIds.put("DR", "reference");
1093 typeIds.put("LO", "look");
1094 typeIds.put("RF", "reference positions");
1099 protected static String id2type(String id)
1101 if (typeIds.containsKey(id))
1103 return (String) typeIds.get(id);
1105 System.err.println("Warning : Unknown Stockholm annotation type code "
1110 protected static String type2id(String type)
1113 Enumeration e = typeIds.keys();
1114 while (e.hasMoreElements())
1116 Object ll = e.nextElement();
1117 if (typeIds.get(ll).toString().equals(type))
1125 return (String) key;
1127 System.err.println("Warning : Unknown Stockholm annotation type: "
1133 * make a friendly ID string.
1136 * @return truncated dataName to after last '/'
1138 private String safeName(String dataName)
1141 while ((b = dataName.indexOf("/")) > -1 && b < dataName.length())
1143 dataName = dataName.substring(b + 1).trim();
1146 int e = (dataName.length() - dataName.indexOf(".")) + 1;
1147 dataName = dataName.substring(1, e).trim();