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
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 of the License, or (at your option) any later version.
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.
16 * You should have received a copy of the GNU General Public License along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * This extension was written by Benjamin Schuster-Boeckler at sanger.ac.uk
26 import com.stevesoft.pat.*;
27 import jalview.datamodel.*;
28 import jalview.analysis.Rna;
30 // import org.apache.log4j.*;
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.
40 * @author bsb at sanger.ac.uk
41 * @version 0.3 + jalview mods
44 public class StockholmFile extends AlignFile
46 // static Logger logger = Logger.getLogger("jalview.io.StockholmFile");
48 public StockholmFile()
52 public StockholmFile(String inFile, String type) throws IOException
57 public StockholmFile(FileParse source) throws IOException
62 public void initData()
68 * Parse a file in Stockholm format into Jalview's data model. The file has to
69 * be passed at construction time
72 * If there is an error with the input file
74 public void parse() throws IOException
76 StringBuffer treeString = new StringBuffer();
77 String treeName = null;
78 // --------------- Variable Definitions -------------------
82 Hashtable seqAnn = new Hashtable(); // Sequence related annotations
83 Hashtable seqs = new Hashtable();
84 Regex p, r, rend, s, x;
86 // Temporary line for processing RNA annotation
87 // String RNAannot = "";
89 // ------------------ Parsing File ----------------------
90 // First, we have to check that this file has STOCKHOLM format, i.e. the
91 // first line must match
92 r = new Regex("# STOCKHOLM ([\\d\\.]+)");
93 if (!r.search(nextLine()))
95 throw new IOException(
96 "This file is not in valid STOCKHOLM format: First line does not contain '# STOCKHOLM'");
100 version = r.stringMatched(1);
101 // logger.debug("Stockholm version: " + version);
104 // We define some Regexes here that will be used regularily later
105 rend = new Regex("^\\s*\\/\\/"); // Find the end of an alignment
106 p = new Regex("(\\S+)\\/(\\d+)\\-(\\d+)"); // split sequence id in
108 s = new Regex("(\\S+)\\s+(\\S*)\\s+(.*)"); // Parses annotation subtype
109 r = new Regex("#=(G[FSRC]?)\\s+(.*)"); // Finds any annotation line
110 x = new Regex("(\\S+)\\s+(\\S+)"); // split id from sequence
112 // Convert all bracket types to parentheses (necessary for passing to VARNA)
113 Regex openparen = new Regex("(<|\\[)", "(");
114 Regex closeparen = new Regex("(>|\\])", ")");
116 // Detect if file is RNA by looking for bracket types
117 Regex detectbrackets = new Regex("(<|>|\\[|\\]|\\(|\\))");
124 openparen.optimize();
125 closeparen.optimize();
127 while ((line = nextLine()) != null)
129 if (line.length() == 0)
133 if (rend.search(line))
135 // End of the alignment, pass stuff back
137 this.noSeqs = seqs.size();
138 // logger.debug("Number of sequences: " + this.noSeqs);
139 Enumeration accs = seqs.keys();
140 while (accs.hasMoreElements())
142 String acc = (String) accs.nextElement();
143 // logger.debug("Processing sequence " + acc);
144 String seq = (String) seqs.remove(acc);
145 if (maxLength < seq.length())
147 maxLength = seq.length();
153 * Retrieve hash of annotations for this accession Associate
154 * Annotation with accession
156 Hashtable accAnnotations = null;
158 if (seqAnn != null && seqAnn.containsKey(acc))
160 accAnnotations = (Hashtable) seqAnn.remove(acc);
161 // TODO: add structures to sequence
164 // Split accession in id and from/to
167 sid = p.stringMatched(1);
168 start = Integer.parseInt(p.stringMatched(2));
169 end = Integer.parseInt(p.stringMatched(3));
171 // logger.debug(sid + ", " + start + ", " + end);
173 Sequence seqO = new Sequence(sid, seq, start, end);
174 // Add Description (if any)
175 if (accAnnotations != null && accAnnotations.containsKey("DE"))
177 String desc = (String) accAnnotations.get("DE");
178 seqO.setDescription((desc == null) ? "" : desc);
180 // Add DB References (if any)
181 if (accAnnotations != null && accAnnotations.containsKey("DR"))
183 String dbr = (String) accAnnotations.get("DR");
184 if (dbr != null && dbr.indexOf(";") > -1)
186 String src = dbr.substring(0, dbr.indexOf(";"));
187 String acn = dbr.substring(dbr.indexOf(";") + 1);
188 jalview.util.DBRefUtils.parseToDbRef(seqO, src, "0", acn);
189 // seqO.addDBRef(dbref);
192 if (accAnnotations != null && accAnnotations.containsKey("SS"))
194 Vector v = (Vector) accAnnotations.get("SS");
196 for (int i = 0; i < v.size(); i++)
198 AlignmentAnnotation an = (AlignmentAnnotation) v.elementAt(i);
199 seqO.addAlignmentAnnotation(an);
200 // annotations.add(an);
204 Hashtable features = null;
205 // We need to adjust the positions of all features to account for gaps
208 features = (Hashtable) accAnnotations.remove("features");
209 } catch (java.lang.NullPointerException e)
211 // loggerwarn("Getting Features for " + acc + ": " +
215 // if we have features
216 if (features != null)
218 int posmap[] = seqO.findPositionMap();
219 Enumeration i = features.keys();
220 while (i.hasMoreElements())
222 // TODO: parse out secondary structure annotation as annotation
224 // TODO: parse out scores as annotation row
225 // TODO: map coding region to core jalview feature types
226 String type = i.nextElement().toString();
227 Hashtable content = (Hashtable) features.remove(type);
228 Enumeration j = content.keys();
229 while (j.hasMoreElements())
231 String desc = j.nextElement().toString();
232 String ns = content.get(desc).toString();
233 char[] byChar = ns.toCharArray();
234 for (int k = 0; k < byChar.length; k++)
237 if (!(c == ' ' || c == '_' || c == '-' || c == '.')) // PFAM
244 int new_pos = posmap[k]; // look up nearest seqeunce
245 // position to this column
246 SequenceFeature feat = new SequenceFeature(type, desc,
247 new_pos, new_pos, 0f, null);
249 seqO.addSequenceFeature(feat);
259 // logger.debug("Adding seq " + acc + " from " + start + " to " + end
261 this.seqs.addElement(seqO);
263 return; // finished parsing this segment of source
265 else if (!r.search(line))
267 // System.err.println("Found sequence line: " + line);
269 // Split sequence in sequence and accession parts
272 // logger.error("Could not parse sequence line: " + line);
273 throw new IOException("Could not parse sequence line: " + line);
275 String ns = (String) seqs.get(x.stringMatched(1));
280 ns += x.stringMatched(2);
282 seqs.put(x.stringMatched(1), ns);
286 String annType = r.stringMatched(1);
287 String annContent = r.stringMatched(2);
289 // System.err.println("type:" + annType + " content: " + annContent);
291 if (annType.equals("GF"))
294 * Generic per-File annotation, free text Magic features: #=GF NH
295 * <tree in New Hampshire eXtended format> #=GF TN <Unique identifier
296 * for the next tree> Pfam descriptions: 7. DESCRIPTION OF FIELDS
298 * Compulsory fields: ------------------
300 * AC Accession number: Accession number in form PFxxxxx.version or
301 * PBxxxxxx. ID Identification: One word name for family. DE
302 * Definition: Short description of family. AU Author: Authors of the
303 * entry. SE Source of seed: The source suggesting the seed members
304 * belong to one family. GA Gathering method: Search threshold to
305 * build the full alignment. TC Trusted Cutoff: Lowest sequence score
306 * and domain score of match in the full alignment. NC Noise Cutoff:
307 * Highest sequence score and domain score of match not in full
308 * alignment. TP Type: Type of family -- presently Family, Domain,
309 * Motif or Repeat. SQ Sequence: Number of sequences in alignment. AM
310 * Alignment Method The order ls and fs hits are aligned to the model
311 * to build the full align. // End of alignment.
313 * Optional fields: ----------------
315 * DC Database Comment: Comment about database reference. DR Database
316 * Reference: Reference to external database. RC Reference Comment:
317 * Comment about literature reference. RN Reference Number: Reference
318 * Number. RM Reference Medline: Eight digit medline UI number. RT
319 * Reference Title: Reference Title. RA Reference Author: Reference
320 * Author RL Reference Location: Journal location. PI Previous
321 * identifier: Record of all previous ID lines. KW Keywords: Keywords.
322 * CC Comment: Comments. NE Pfam accession: Indicates a nested domain.
323 * NL Location: Location of nested domains - sequence ID, start and
326 * Obsolete fields: ----------- AL Alignment method of seed: The
327 * method used to align the seed members.
329 // Let's save the annotations, maybe we'll be able to do something
330 // with them later...
331 Regex an = new Regex("(\\w+)\\s*(.*)");
332 if (an.search(annContent))
334 if (an.stringMatched(1).equals("NH"))
336 treeString.append(an.stringMatched(2));
338 else if (an.stringMatched(1).equals("TN"))
340 if (treeString.length() > 0)
342 if (treeName == null)
344 treeName = "Tree " + (getTreeCount() + 1);
346 addNewickTree(treeName, treeString.toString());
348 treeName = an.stringMatched(2);
349 treeString = new StringBuffer();
351 setAlignmentProperty(an.stringMatched(1), an.stringMatched(2));
354 else if (annType.equals("GS"))
356 // Generic per-Sequence annotation, free text
358 * Pfam uses these features: Feature Description ---------------------
359 * ----------- AC <accession> ACcession number DE <freetext>
360 * DEscription DR <db>; <accession>; Database Reference OS <organism>
361 * OrganiSm (species) OC <clade> Organism Classification (clade, etc.)
362 * LO <look> Look (Color, etc.)
364 if (s.search(annContent))
366 String acc = s.stringMatched(1);
367 String type = s.stringMatched(2);
368 String content = s.stringMatched(3);
369 // TODO: store DR in a vector.
370 // TODO: store AC according to generic file db annotation.
372 if (seqAnn.containsKey(acc))
374 ann = (Hashtable) seqAnn.get(acc);
378 ann = new Hashtable();
380 ann.put(type, content);
381 seqAnn.put(acc, ann);
385 throw new IOException("Error parsing " + line);
388 else if (annType.equals("GC"))
390 // Generic per-Column annotation, exactly 1 char per column
391 // always need a label.
392 if (x.search(annContent))
394 // parse out and create alignment annotation directly.
395 parseAnnotationRow(annotations, x.stringMatched(1),
399 else if (annType.equals("GR"))
401 // Generic per-Sequence AND per-Column markup, exactly 1 char per
404 * Feature Description Markup letters ------- -----------
405 * -------------- SS Secondary Structure [HGIEBTSCX] SA Surface
406 * Accessibility [0-9X] (0=0%-10%; ...; 9=90%-100%) TM TransMembrane
407 * [Mio] PP Posterior Probability [0-9*] (0=0.00-0.05; 1=0.05-0.15;
408 * *=0.95-1.00) LI LIgand binding [*] AS Active Site [*] IN INtron (in
411 if (s.search(annContent))
413 String acc = s.stringMatched(1);
414 String type = s.stringMatched(2);
415 String seq = new String(s.stringMatched(3));
416 String description = null;
417 // Check for additional information about the current annotation
418 // We use a simple string tokenizer here for speed
419 StringTokenizer sep = new StringTokenizer(seq, " \t");
420 description = sep.nextToken();
421 if (sep.hasMoreTokens())
423 seq = sep.nextToken();
428 description = new String();
430 // sequence id with from-to fields
433 // Get an object with all the annotations for this sequence
434 if (seqAnn.containsKey(acc))
436 // logger.debug("Found annotations for " + acc);
437 ann = (Hashtable) seqAnn.get(acc);
441 // logger.debug("Creating new annotations holder for " + acc);
442 ann = new Hashtable();
443 seqAnn.put(acc, ann);
445 // TODO test structure, call parseAnnotationRow with vector from
446 // hashtable for specific sequence
448 // Get an object with all the content for an annotation
449 if (ann.containsKey("features"))
451 // logger.debug("Found features for " + acc);
452 features = (Hashtable) ann.get("features");
456 // logger.debug("Creating new features holder for " + acc);
457 features = new Hashtable();
458 ann.put("features", features);
462 if (features.containsKey(this.id2type(type)))
464 // logger.debug("Found content for " + this.id2type(type));
465 content = (Hashtable) features.get(this.id2type(type));
469 // logger.debug("Creating new content holder for " +
470 // this.id2type(type));
471 content = new Hashtable();
472 features.put(this.id2type(type), content);
474 String ns = (String) content.get(description);
480 content.put(description, ns);
482 if (type.equals("SS"))
485 if (seqAnn.containsKey(acc))
487 strucAnn = (Hashtable) seqAnn.get(acc);
491 strucAnn = new Hashtable();
494 Vector newStruc = new Vector();
495 parseAnnotationRow(newStruc, type, ns);
497 strucAnn.put(type, newStruc);
498 seqAnn.put(acc, strucAnn);
504 .println("Warning - couldn't parse sequence annotation row line:\n"
506 // throw new IOException("Error parsing " + line);
511 throw new IOException("Unknown annotation detected: " + annType
516 if (treeString.length() > 0)
518 if (treeName == null)
520 treeName = "Tree " + (1 + getTreeCount());
522 addNewickTree(treeName, treeString.toString());
526 protected static AlignmentAnnotation parseAnnotationRow(
527 Vector annotation, String label, String annots)
529 String convert1, convert2 = null;
531 // Convert all bracket types to parentheses
532 Regex openparen = new Regex("(<|\\[)", "(");
533 Regex closeparen = new Regex("(>|\\])", ")");
535 // Detect if file is RNA by looking for bracket types
536 Regex detectbrackets = new Regex("(<|>|\\[|\\]|\\(|\\))");
538 convert1 = openparen.replaceAll(annots);
539 convert2 = closeparen.replaceAll(convert1);
542 String type = (label.indexOf("_cons") == label.length() - 5) ? label
543 .substring(0, label.length() - 5) : label;
545 type = id2type(type);
546 if (type.equals("secondary structure"))
550 // decide on secondary structure or not.
551 Annotation[] els = new Annotation[annots.length()];
552 for (int i = 0; i < annots.length(); i++)
554 String pos = annots.substring(i, i + 1);
556 ann = new Annotation(pos, "", ' ', 0f); // 0f is 'valid' null - will not
560 if (detectbrackets.search(pos))
562 ann.secondaryStructure = jalview.schemes.ResidueProperties
563 .getRNASecStrucState(pos).charAt(0);
567 ann.secondaryStructure = jalview.schemes.ResidueProperties
568 .getDssp3state(pos).charAt(0);
571 if (ann.secondaryStructure == pos.charAt(0) || pos.charAt(0) == 'C')
573 ann.displayCharacter = ""; // null; // " ";
577 ann.displayCharacter = " " + ann.displayCharacter;
583 AlignmentAnnotation annot = null;
584 Enumeration e = annotation.elements();
585 while (e.hasMoreElements())
587 annot = (AlignmentAnnotation) e.nextElement();
588 if (annot.label.equals(type))
594 annot = new AlignmentAnnotation(type, type, els);
595 annotation.addElement(annot);
599 Annotation[] anns = new Annotation[annot.annotations.length
601 System.arraycopy(annot.annotations, 0, anns, 0,
602 annot.annotations.length);
603 System.arraycopy(els, 0, anns, annot.annotations.length, els.length);
604 annot.annotations = anns;
605 // System.out.println("else: ");
610 public static String print(SequenceI[] s)
612 return "not yet implemented";
615 public String print()
617 return print(getSeqsAsArray());
620 private static Hashtable typeIds = null;
625 typeIds = new Hashtable();
626 typeIds.put("SS", "secondary structure");
627 typeIds.put("SA", "surface accessibility");
628 typeIds.put("TM", "transmembrane");
629 typeIds.put("PP", "posterior probability");
630 typeIds.put("LI", "ligand binding");
631 typeIds.put("AS", "active site");
632 typeIds.put("IN", "intron");
633 typeIds.put("IR", "interacting residue");
634 typeIds.put("AC", "accession");
635 typeIds.put("OS", "organism");
636 typeIds.put("CL", "class");
637 typeIds.put("DE", "description");
638 typeIds.put("DR", "reference");
639 typeIds.put("LO", "look");
640 typeIds.put("RF", "reference positions");
645 protected static String id2type(String id)
647 if (typeIds.containsKey(id))
649 return (String) typeIds.get(id);
651 System.err.println("Warning : Unknown Stockholm annotation type code "
656 * //ssline is complete secondary structure line private AlignmentAnnotation
657 * addHelices(Vector annotation, String label, String ssline) {
659 * // decide on secondary structure or not. Annotation[] els = new
660 * Annotation[ssline.length()]; for (int i = 0; i < ssline.length(); i++) {
661 * String pos = ssline.substring(i, i + 1); Annotation ann; ann = new
662 * Annotation(pos, "", ' ', 0f); // 0f is 'valid' null - will not
664 * ann.secondaryStructure =
665 * jalview.schemes.ResidueProperties.getRNAssState(pos).charAt(0);
667 * ann.displayCharacter = "x" + ann.displayCharacter;
669 * System.out.println(ann.displayCharacter);
671 * els[i] = ann; } AlignmentAnnotation helicesAnnot = null; Enumeration e =
672 * annotation.elements(); while (e.hasMoreElements()) { helicesAnnot =
673 * (AlignmentAnnotation) e.nextElement(); if (helicesAnnot.label.equals(type))
674 * break; helicesAnnot = null; } if (helicesAnnot == null) { helicesAnnot =
675 * new AlignmentAnnotation(type, type, els);
676 * annotation.addElement(helicesAnnot); } else { Annotation[] anns = new
677 * Annotation[helicesAnnot.annotations.length + els.length];
678 * System.arraycopy(helicesAnnot.annotations, 0, anns, 0,
679 * helicesAnnot.annotations.length); System.arraycopy(els, 0, anns,
680 * helicesAnnot.annotations.length, els.length); helicesAnnot.annotations =
683 * helicesAnnot.features = Rna.GetBasePairs(ssline);
684 * Rna.HelixMap(helicesAnnot.features);
687 * return helicesAnnot; }