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.*;
29 // import org.apache.log4j.*;
32 * This class is supposed to parse a Stockholm format file into Jalview There
33 * are TODOs in this class: we do not know what the database source and version
34 * is for the file when parsing the #GS= AC tag which associates accessions with
35 * sequences. Database references are also not parsed correctly: a separate
36 * reference string parser must be added to parse the database reference form
37 * into Jalview's local representation.
39 * @author bsb at sanger.ac.uk
40 * @version 0.3 + jalview mods
43 public class StockholmFile extends AlignFile
45 // static Logger logger = Logger.getLogger("jalview.io.StockholmFile");
47 public StockholmFile()
51 public StockholmFile(String inFile, String type) throws IOException
56 public StockholmFile(FileParse source) throws IOException
61 public void initData()
67 * Parse a file in Stockholm format into Jalview's data model. The file has to
68 * be passed at construction time
71 * If there is an error with the input file
73 public void parse() throws IOException
75 StringBuffer treeString = new StringBuffer();
76 String treeName = null;
77 // --------------- Variable Definitions -------------------
81 Hashtable seqAnn = new Hashtable(); // Sequence related annotations
82 Hashtable seqs = new Hashtable();
83 Regex p, r, rend, s, x;
85 // Temporary line for processing RNA annotation
86 // String RNAannot = "";
88 // ------------------ Parsing File ----------------------
89 // First, we have to check that this file has STOCKHOLM format, i.e. the
90 // first line must match
91 r = new Regex("# STOCKHOLM ([\\d\\.]+)");
92 if (!r.search(nextLine()))
94 throw new IOException(
95 "This file is not in valid STOCKHOLM format: First line does not contain '# STOCKHOLM'");
99 version = r.stringMatched(1);
100 // logger.debug("Stockholm version: " + version);
103 // We define some Regexes here that will be used regularily later
104 rend = new Regex("^\\s*\\/\\/"); // Find the end of an alignment
105 p = new Regex("(\\S+)\\/(\\d+)\\-(\\d+)"); // split sequence id in
107 s = new Regex("(\\S+)\\s+(\\S*)\\s+(.*)"); // Parses annotation subtype
108 r = new Regex("#=(G[FSRC]?)\\s+(.*)"); // Finds any annotation line
109 x = new Regex("(\\S+)\\s+(\\S+)"); // split id from sequence
111 // Convert all bracket types to parentheses (necessary for passing to VARNA)
112 Regex openparen = new Regex("(<|\\[)", "(");
113 Regex closeparen = new Regex("(>|\\])", ")");
115 // Detect if file is RNA by looking for bracket types
116 Regex detectbrackets = new Regex("(<|>|\\[|\\]|\\(|\\))");
123 openparen.optimize();
124 closeparen.optimize();
126 while ((line = nextLine()) != null)
128 if (line.length() == 0)
132 if (rend.search(line))
134 // End of the alignment, pass stuff back
136 this.noSeqs = seqs.size();
137 // logger.debug("Number of sequences: " + this.noSeqs);
138 Enumeration accs = seqs.keys();
139 while (accs.hasMoreElements())
141 String acc = (String) accs.nextElement();
142 // logger.debug("Processing sequence " + acc);
143 String seq = (String) seqs.remove(acc);
144 if (maxLength < seq.length())
146 maxLength = seq.length();
152 * Retrieve hash of annotations for this accession Associate
153 * Annotation with accession
155 Hashtable accAnnotations = null;
157 if (seqAnn != null && seqAnn.containsKey(acc))
159 accAnnotations = (Hashtable) seqAnn.remove(acc);
160 // TODO: add structures to sequence
163 // Split accession in id and from/to
166 sid = p.stringMatched(1);
167 start = Integer.parseInt(p.stringMatched(2));
168 end = Integer.parseInt(p.stringMatched(3));
170 // logger.debug(sid + ", " + start + ", " + end);
172 Sequence seqO = new Sequence(sid, seq, start, end);
173 // Add Description (if any)
174 if (accAnnotations != null && accAnnotations.containsKey("DE"))
176 String desc = (String) accAnnotations.get("DE");
177 seqO.setDescription((desc == null) ? "" : desc);
179 // Add DB References (if any)
180 if (accAnnotations != null && accAnnotations.containsKey("DR"))
182 String dbr = (String) accAnnotations.get("DR");
183 if (dbr != null && dbr.indexOf(";") > -1)
185 String src = dbr.substring(0, dbr.indexOf(";"));
186 String acn = dbr.substring(dbr.indexOf(";") + 1);
187 jalview.util.DBRefUtils.parseToDbRef(seqO, src, "0", acn);
188 // seqO.addDBRef(dbref);
191 if (accAnnotations != null && accAnnotations.containsKey("SS"))
193 Vector v = (Vector) accAnnotations.get("SS");
195 for (int i = 0; i < v.size(); i++)
197 AlignmentAnnotation an = (AlignmentAnnotation) v.elementAt(i);
198 seqO.addAlignmentAnnotation(an);
199 // annotations.add(an);
203 Hashtable features = null;
204 // We need to adjust the positions of all features to account for gaps
207 features = (Hashtable) accAnnotations.remove("features");
208 } catch (java.lang.NullPointerException e)
210 // loggerwarn("Getting Features for " + acc + ": " +
214 // if we have features
215 if (features != null)
217 int posmap[] = seqO.findPositionMap();
218 Enumeration i = features.keys();
219 while (i.hasMoreElements())
221 // TODO: parse out secondary structure annotation as annotation
223 // TODO: parse out scores as annotation row
224 // TODO: map coding region to core jalview feature types
225 String type = i.nextElement().toString();
226 Hashtable content = (Hashtable) features.remove(type);
227 Enumeration j = content.keys();
228 while (j.hasMoreElements())
230 String desc = j.nextElement().toString();
231 String ns = content.get(desc).toString();
232 char[] byChar = ns.toCharArray();
233 for (int k = 0; k < byChar.length; k++)
236 if (!(c == ' ' || c == '_' || c == '-' || c == '.')) // PFAM
243 int new_pos = posmap[k]; // look up nearest seqeunce
244 // position to this column
245 SequenceFeature feat = new SequenceFeature(type, desc,
246 new_pos, new_pos, 0f, null);
248 seqO.addSequenceFeature(feat);
258 // logger.debug("Adding seq " + acc + " from " + start + " to " + end
260 this.seqs.addElement(seqO);
262 return; // finished parsing this segment of source
264 else if (!r.search(line))
266 // System.err.println("Found sequence line: " + line);
268 // Split sequence in sequence and accession parts
271 // logger.error("Could not parse sequence line: " + line);
272 throw new IOException("Could not parse sequence line: " + line);
274 String ns = (String) seqs.get(x.stringMatched(1));
279 ns += x.stringMatched(2);
281 seqs.put(x.stringMatched(1), ns);
285 String annType = r.stringMatched(1);
286 String annContent = r.stringMatched(2);
288 // System.err.println("type:" + annType + " content: " + annContent);
290 if (annType.equals("GF"))
293 * Generic per-File annotation, free text Magic features: #=GF NH
294 * <tree in New Hampshire eXtended format> #=GF TN <Unique identifier
295 * for the next tree> Pfam descriptions: 7. DESCRIPTION OF FIELDS
297 * Compulsory fields: ------------------
299 * AC Accession number: Accession number in form PFxxxxx.version or
300 * PBxxxxxx. ID Identification: One word name for family. DE
301 * Definition: Short description of family. AU Author: Authors of the
302 * entry. SE Source of seed: The source suggesting the seed members
303 * belong to one family. GA Gathering method: Search threshold to
304 * build the full alignment. TC Trusted Cutoff: Lowest sequence score
305 * and domain score of match in the full alignment. NC Noise Cutoff:
306 * Highest sequence score and domain score of match not in full
307 * alignment. TP Type: Type of family -- presently Family, Domain,
308 * Motif or Repeat. SQ Sequence: Number of sequences in alignment. AM
309 * Alignment Method The order ls and fs hits are aligned to the model
310 * to build the full align. // End of alignment.
312 * Optional fields: ----------------
314 * DC Database Comment: Comment about database reference. DR Database
315 * Reference: Reference to external database. RC Reference Comment:
316 * Comment about literature reference. RN Reference Number: Reference
317 * Number. RM Reference Medline: Eight digit medline UI number. RT
318 * Reference Title: Reference Title. RA Reference Author: Reference
319 * Author RL Reference Location: Journal location. PI Previous
320 * identifier: Record of all previous ID lines. KW Keywords: Keywords.
321 * CC Comment: Comments. NE Pfam accession: Indicates a nested domain.
322 * NL Location: Location of nested domains - sequence ID, start and
325 * Obsolete fields: ----------- AL Alignment method of seed: The
326 * method used to align the seed members.
328 // Let's save the annotations, maybe we'll be able to do something
329 // with them later...
330 Regex an = new Regex("(\\w+)\\s*(.*)");
331 if (an.search(annContent))
333 if (an.stringMatched(1).equals("NH"))
335 treeString.append(an.stringMatched(2));
337 else if (an.stringMatched(1).equals("TN"))
339 if (treeString.length() > 0)
341 if (treeName == null)
343 treeName = "Tree " + (getTreeCount() + 1);
345 addNewickTree(treeName, treeString.toString());
347 treeName = an.stringMatched(2);
348 treeString = new StringBuffer();
350 setAlignmentProperty(an.stringMatched(1), an.stringMatched(2));
353 else if (annType.equals("GS"))
355 // Generic per-Sequence annotation, free text
357 * Pfam uses these features: Feature Description ---------------------
358 * ----------- AC <accession> ACcession number DE <freetext>
359 * DEscription DR <db>; <accession>; Database Reference OS <organism>
360 * OrganiSm (species) OC <clade> Organism Classification (clade, etc.)
361 * LO <look> Look (Color, etc.)
363 if (s.search(annContent))
365 String acc = s.stringMatched(1);
366 String type = s.stringMatched(2);
367 String content = s.stringMatched(3);
368 // TODO: store DR in a vector.
369 // TODO: store AC according to generic file db annotation.
371 if (seqAnn.containsKey(acc))
373 ann = (Hashtable) seqAnn.get(acc);
377 ann = new Hashtable();
379 ann.put(type, content);
380 seqAnn.put(acc, ann);
384 throw new IOException("Error parsing " + line);
387 else if (annType.equals("GC"))
389 // Generic per-Column annotation, exactly 1 char per column
390 // always need a label.
391 if (x.search(annContent))
393 // parse out and create alignment annotation directly.
394 parseAnnotationRow(annotations, x.stringMatched(1),
398 else if (annType.equals("GR"))
400 // Generic per-Sequence AND per-Column markup, exactly 1 char per
403 * Feature Description Markup letters ------- -----------
404 * -------------- SS Secondary Structure [HGIEBTSCX] SA Surface
405 * Accessibility [0-9X] (0=0%-10%; ...; 9=90%-100%) TM TransMembrane
406 * [Mio] PP Posterior Probability [0-9*] (0=0.00-0.05; 1=0.05-0.15;
407 * *=0.95-1.00) LI LIgand binding [*] AS Active Site [*] IN INtron (in
410 if (s.search(annContent))
412 String acc = s.stringMatched(1);
413 String type = s.stringMatched(2);
414 String seq = new String(s.stringMatched(3));
415 String description = null;
416 // Check for additional information about the current annotation
417 // We use a simple string tokenizer here for speed
418 StringTokenizer sep = new StringTokenizer(seq, " \t");
419 description = sep.nextToken();
420 if (sep.hasMoreTokens())
422 seq = sep.nextToken();
427 description = new String();
429 // sequence id with from-to fields
432 // Get an object with all the annotations for this sequence
433 if (seqAnn.containsKey(acc))
435 // logger.debug("Found annotations for " + acc);
436 ann = (Hashtable) seqAnn.get(acc);
440 // logger.debug("Creating new annotations holder for " + acc);
441 ann = new Hashtable();
442 seqAnn.put(acc, ann);
444 // TODO test structure, call parseAnnotationRow with vector from
445 // hashtable for specific sequence
447 // Get an object with all the content for an annotation
448 if (ann.containsKey("features"))
450 // logger.debug("Found features for " + acc);
451 features = (Hashtable) ann.get("features");
455 // logger.debug("Creating new features holder for " + acc);
456 features = new Hashtable();
457 ann.put("features", features);
461 if (features.containsKey(this.id2type(type)))
463 // logger.debug("Found content for " + this.id2type(type));
464 content = (Hashtable) features.get(this.id2type(type));
468 // logger.debug("Creating new content holder for " +
469 // this.id2type(type));
470 content = new Hashtable();
471 features.put(this.id2type(type), content);
473 String ns = (String) content.get(description);
479 content.put(description, ns);
481 if (type.equals("SS"))
484 if (seqAnn.containsKey(acc))
486 strucAnn = (Hashtable) seqAnn.get(acc);
490 strucAnn = new Hashtable();
493 Vector newStruc = new Vector();
494 parseAnnotationRow(newStruc, type, ns);
496 strucAnn.put(type, newStruc);
497 seqAnn.put(acc, strucAnn);
503 .println("Warning - couldn't parse sequence annotation row line:\n"
505 // throw new IOException("Error parsing " + line);
510 throw new IOException("Unknown annotation detected: " + annType
515 if (treeString.length() > 0)
517 if (treeName == null)
519 treeName = "Tree " + (1 + getTreeCount());
521 addNewickTree(treeName, treeString.toString());
525 protected static AlignmentAnnotation parseAnnotationRow(
526 Vector annotation, String label, String annots)
528 String convert1, convert2 = null;
530 // Convert all bracket types to parentheses
531 Regex openparen = new Regex("(<|\\[)", "(");
532 Regex closeparen = new Regex("(>|\\])", ")");
534 // Detect if file is RNA by looking for bracket types
535 Regex detectbrackets = new Regex("(<|>|\\[|\\]|\\(|\\))");
537 convert1 = openparen.replaceAll(annots);
538 convert2 = closeparen.replaceAll(convert1);
541 String type = (label.indexOf("_cons") == label.length() - 5) ? label
542 .substring(0, label.length() - 5) : label;
544 type = id2type(type);
545 if (type.equals("secondary structure"))
549 // decide on secondary structure or not.
550 Annotation[] els = new Annotation[annots.length()];
551 for (int i = 0; i < annots.length(); i++)
553 String pos = annots.substring(i, i + 1);
555 ann = new Annotation(pos, "", ' ', 0f); // 0f is 'valid' null - will not
559 if (detectbrackets.search(pos))
561 ann.secondaryStructure = jalview.schemes.ResidueProperties
562 .getRNASecStrucState(pos).charAt(0);
566 ann.secondaryStructure = jalview.schemes.ResidueProperties
567 .getDssp3state(pos).charAt(0);
570 if (ann.secondaryStructure == pos.charAt(0) || pos.charAt(0) == 'C')
572 ann.displayCharacter = ""; // null; // " ";
576 ann.displayCharacter = " " + ann.displayCharacter;
582 AlignmentAnnotation annot = null;
583 Enumeration e = annotation.elements();
584 while (e.hasMoreElements())
586 annot = (AlignmentAnnotation) e.nextElement();
587 if (annot.label.equals(type))
593 annot = new AlignmentAnnotation(type, type, els);
594 annotation.addElement(annot);
598 Annotation[] anns = new Annotation[annot.annotations.length
600 System.arraycopy(annot.annotations, 0, anns, 0,
601 annot.annotations.length);
602 System.arraycopy(els, 0, anns, annot.annotations.length, els.length);
603 annot.annotations = anns;
604 // System.out.println("else: ");
609 public static String print(SequenceI[] s)
611 return "not yet implemented";
614 public String print()
616 return print(getSeqsAsArray());
619 private static Hashtable typeIds = null;
624 typeIds = new Hashtable();
625 typeIds.put("SS", "secondary structure");
626 typeIds.put("SA", "surface accessibility");
627 typeIds.put("TM", "transmembrane");
628 typeIds.put("PP", "posterior probability");
629 typeIds.put("LI", "ligand binding");
630 typeIds.put("AS", "active site");
631 typeIds.put("IN", "intron");
632 typeIds.put("IR", "interacting residue");
633 typeIds.put("AC", "accession");
634 typeIds.put("OS", "organism");
635 typeIds.put("CL", "class");
636 typeIds.put("DE", "description");
637 typeIds.put("DR", "reference");
638 typeIds.put("LO", "look");
639 typeIds.put("RF", "reference positions");
644 protected static String id2type(String id)
646 if (typeIds.containsKey(id))
648 return (String) typeIds.get(id);
650 System.err.println("Warning : Unknown Stockholm annotation type code "
655 * //ssline is complete secondary structure line private AlignmentAnnotation
656 * addHelices(Vector annotation, String label, String ssline) {
658 * // decide on secondary structure or not. Annotation[] els = new
659 * Annotation[ssline.length()]; for (int i = 0; i < ssline.length(); i++) {
660 * String pos = ssline.substring(i, i + 1); Annotation ann; ann = new
661 * Annotation(pos, "", ' ', 0f); // 0f is 'valid' null - will not
663 * ann.secondaryStructure =
664 * jalview.schemes.ResidueProperties.getRNAssState(pos).charAt(0);
666 * ann.displayCharacter = "x" + ann.displayCharacter;
668 * System.out.println(ann.displayCharacter);
670 * els[i] = ann; } AlignmentAnnotation helicesAnnot = null; Enumeration e =
671 * annotation.elements(); while (e.hasMoreElements()) { helicesAnnot =
672 * (AlignmentAnnotation) e.nextElement(); if (helicesAnnot.label.equals(type))
673 * break; helicesAnnot = null; } if (helicesAnnot == null) { helicesAnnot =
674 * new AlignmentAnnotation(type, type, els);
675 * annotation.addElement(helicesAnnot); } else { Annotation[] anns = new
676 * Annotation[helicesAnnot.annotations.length + els.length];
677 * System.arraycopy(helicesAnnot.annotations, 0, anns, 0,
678 * helicesAnnot.annotations.length); System.arraycopy(els, 0, anns,
679 * helicesAnnot.annotations.length, els.length); helicesAnnot.annotations =
682 * helicesAnnot.features = Rna.GetBasePairs(ssline);
683 * Rna.HelixMap(helicesAnnot.features);
686 * return helicesAnnot; }