2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.6)
\r
3 * Copyright (C) 2010 J Procter, AM Waterhouse, G Barton, M Clamp, S Searle
\r
5 * This file is part of Jalview.
\r
7 * Jalview is free software: you can redistribute it and/or
\r
8 * modify it under the terms of the GNU General Public License
\r
9 * as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
\r
11 * Jalview is distributed in the hope that it will be useful, but
\r
12 * WITHOUT ANY WARRANTY; without even the implied warranty
\r
13 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
\r
14 * PURPOSE. See the GNU General Public License for more details.
\r
16 * You should have received a copy of the GNU General Public License along with Jalview. If not, see <http://www.gnu.org/licenses/>.
\r
19 * This extension was written by Benjamin Schuster-Boeckler at sanger.ac.uk
\r
26 import com.stevesoft.pat.*;
\r
27 import jalview.datamodel.*;
\r
28 import jalview.analysis.Rna;
\r
30 // import org.apache.log4j.*;
\r
33 * This class is supposed to parse a Stockholm format file into Jalview There
\r
34 * are TODOs in this class: we do not know what the database source and version
\r
35 * is for the file when parsing the #GS= AC tag which associates accessions with
\r
36 * sequences. Database references are also not parsed correctly: a separate
\r
37 * reference string parser must be added to parse the database reference form
\r
38 * into Jalview's local representation.
\r
40 * @author bsb at sanger.ac.uk
\r
41 * @version 0.3 + jalview mods
\r
44 public class StockholmFile extends AlignFile
\r
46 // static Logger logger = Logger.getLogger("jalview.io.StockholmFile");
\r
48 public StockholmFile()
\r
52 public StockholmFile(String inFile, String type) throws IOException
\r
54 super(inFile, type);
\r
57 public StockholmFile(FileParse source) throws IOException
\r
62 public void initData()
\r
68 * Parse a file in Stockholm format into Jalview's data model. The file has to
\r
69 * be passed at construction time
\r
71 * @throws IOException
\r
72 * If there is an error with the input file
\r
74 public void parse() throws IOException
\r
76 StringBuffer treeString = new StringBuffer();
\r
77 String treeName = null;
\r
78 // --------------- Variable Definitions -------------------
\r
82 Hashtable seqAnn = new Hashtable(); // Sequence related annotations
\r
83 Hashtable seqs = new Hashtable();
\r
84 Regex p, r, rend, s, x;
\r
86 // Temporary line for processing RNA annotation
\r
87 // String RNAannot = "";
\r
89 // ------------------ Parsing File ----------------------
\r
90 // First, we have to check that this file has STOCKHOLM format, i.e. the
\r
91 // first line must match
\r
92 r = new Regex("# STOCKHOLM ([\\d\\.]+)");
\r
93 if (!r.search(nextLine()))
\r
95 throw new IOException(
\r
96 "This file is not in valid STOCKHOLM format: First line does not contain '# STOCKHOLM'");
\r
100 version = r.stringMatched(1);
\r
101 // logger.debug("Stockholm version: " + version);
\r
104 // We define some Regexes here that will be used regularily later
\r
105 rend = new Regex("^\\s*\\/\\/"); // Find the end of an alignment
\r
106 p = new Regex("(\\S+)\\/(\\d+)\\-(\\d+)"); // split sequence id in
\r
108 s = new Regex("(\\S+)\\s+(\\S*)\\s+(.*)"); // Parses annotation subtype
\r
109 r = new Regex("#=(G[FSRC]?)\\s+(.*)"); // Finds any annotation line
\r
110 x = new Regex("(\\S+)\\s+(\\S+)"); // split id from sequence
\r
112 // Convert all bracket types to parentheses (necessary for passing to VARNA)
\r
113 Regex openparen = new Regex("(<|\\[)", "(");
\r
114 Regex closeparen = new Regex("(>|\\])", ")");
\r
116 // Detect if file is RNA by looking for bracket types
\r
117 Regex detectbrackets = new Regex("(<|>|\\[|\\]|\\(|\\))");
\r
124 openparen.optimize();
\r
125 closeparen.optimize();
\r
127 while ((line = nextLine()) != null)
\r
129 if (line.length() == 0)
\r
133 if (rend.search(line))
\r
135 // End of the alignment, pass stuff back
\r
137 this.noSeqs = seqs.size();
\r
138 // logger.debug("Number of sequences: " + this.noSeqs);
\r
139 Enumeration accs = seqs.keys();
\r
140 while (accs.hasMoreElements())
\r
142 String acc = (String) accs.nextElement();
\r
143 // logger.debug("Processing sequence " + acc);
\r
144 String seq = (String) seqs.remove(acc);
\r
145 if (maxLength < seq.length())
\r
147 maxLength = seq.length();
\r
152 // Retrieve hash of annotations for this accession
\r
153 Hashtable accAnnotations = null;
\r
155 if (seqAnn != null && seqAnn.containsKey(acc))
\r
157 accAnnotations = (Hashtable) seqAnn.remove(acc);
\r
160 // Split accession in id and from/to
\r
163 sid = p.stringMatched(1);
\r
164 start = Integer.parseInt(p.stringMatched(2));
\r
165 end = Integer.parseInt(p.stringMatched(3));
\r
167 // logger.debug(sid + ", " + start + ", " + end);
\r
169 Sequence seqO = new Sequence(sid, seq, start, end);
\r
170 // Add Description (if any)
\r
171 if (accAnnotations != null && accAnnotations.containsKey("DE"))
\r
173 String desc = (String) accAnnotations.get("DE");
\r
174 seqO.setDescription((desc == null) ? "" : desc);
\r
176 // Add DB References (if any)
\r
177 if (accAnnotations != null && accAnnotations.containsKey("DR"))
\r
179 String dbr = (String) accAnnotations.get("DR");
\r
180 if (dbr != null && dbr.indexOf(";") > -1)
\r
182 String src = dbr.substring(0, dbr.indexOf(";"));
\r
183 String acn = dbr.substring(dbr.indexOf(";") + 1);
\r
184 jalview.util.DBRefUtils.parseToDbRef(seqO, src, "0", acn);
\r
185 // seqO.addDBRef(dbref);
\r
188 Hashtable features = null;
\r
189 // We need to adjust the positions of all features to account for gaps
\r
192 features = (Hashtable) accAnnotations.remove("features");
\r
193 } catch (java.lang.NullPointerException e)
\r
195 // loggerwarn("Getting Features for " + acc + ": " +
\r
196 // e.getMessage());
\r
199 // if we have features
\r
200 if (features != null)
\r
202 int posmap[] = seqO.findPositionMap();
\r
203 Enumeration i = features.keys();
\r
204 while (i.hasMoreElements())
\r
206 // TODO: parse out secondary structure annotation as annotation
\r
208 // TODO: parse out scores as annotation row
\r
209 // TODO: map coding region to core jalview feature types
\r
210 String type = i.nextElement().toString();
\r
211 Hashtable content = (Hashtable) features.remove(type);
\r
212 Enumeration j = content.keys();
\r
213 while (j.hasMoreElements())
\r
215 String desc = j.nextElement().toString();
\r
216 String ns = content.get(desc).toString();
\r
217 char[] byChar = ns.toCharArray();
\r
218 for (int k = 0; k < byChar.length; k++)
\r
220 char c = byChar[k];
\r
221 if (!(c == ' ' || c == '_' || c == '-' || c == '.')) // PFAM
\r
228 int new_pos = posmap[k]; // look up nearest seqeunce
\r
229 // position to this column
\r
230 SequenceFeature feat = new SequenceFeature(type, desc,
\r
231 new_pos, new_pos, 0f, null);
\r
233 seqO.addSequenceFeature(feat);
\r
243 // logger.debug("Adding seq " + acc + " from " + start + " to " + end
\r
245 this.seqs.addElement(seqO);
\r
247 return; // finished parsing this segment of source
\r
249 else if (!r.search(line))
\r
251 // System.err.println("Found sequence line: " + line);
\r
253 // Split sequence in sequence and accession parts
\r
254 if (!x.search(line))
\r
256 // logger.error("Could not parse sequence line: " + line);
\r
257 throw new IOException("Could not parse sequence line: " + line);
\r
259 String ns = (String) seqs.get(x.stringMatched(1));
\r
264 ns += x.stringMatched(2);
\r
266 seqs.put(x.stringMatched(1), ns);
\r
270 String annType = r.stringMatched(1);
\r
271 String annContent = r.stringMatched(2);
\r
273 // System.err.println("type:" + annType + " content: " + annContent);
\r
275 if (annType.equals("GF"))
\r
278 * Generic per-File annotation, free text Magic features: #=GF NH
\r
279 * <tree in New Hampshire eXtended format> #=GF TN <Unique identifier
\r
280 * for the next tree> Pfam descriptions: 7. DESCRIPTION OF FIELDS
\r
282 * Compulsory fields: ------------------
\r
284 * AC Accession number: Accession number in form PFxxxxx.version or
\r
285 * PBxxxxxx. ID Identification: One word name for family. DE
\r
286 * Definition: Short description of family. AU Author: Authors of the
\r
287 * entry. SE Source of seed: The source suggesting the seed members
\r
288 * belong to one family. GA Gathering method: Search threshold to
\r
289 * build the full alignment. TC Trusted Cutoff: Lowest sequence score
\r
290 * and domain score of match in the full alignment. NC Noise Cutoff:
\r
291 * Highest sequence score and domain score of match not in full
\r
292 * alignment. TP Type: Type of family -- presently Family, Domain,
\r
293 * Motif or Repeat. SQ Sequence: Number of sequences in alignment. AM
\r
294 * Alignment Method The order ls and fs hits are aligned to the model
\r
295 * to build the full align. // End of alignment.
\r
297 * Optional fields: ----------------
\r
299 * DC Database Comment: Comment about database reference. DR Database
\r
300 * Reference: Reference to external database. RC Reference Comment:
\r
301 * Comment about literature reference. RN Reference Number: Reference
\r
302 * Number. RM Reference Medline: Eight digit medline UI number. RT
\r
303 * Reference Title: Reference Title. RA Reference Author: Reference
\r
304 * Author RL Reference Location: Journal location. PI Previous
\r
305 * identifier: Record of all previous ID lines. KW Keywords: Keywords.
\r
306 * CC Comment: Comments. NE Pfam accession: Indicates a nested domain.
\r
307 * NL Location: Location of nested domains - sequence ID, start and
\r
310 * Obsolete fields: ----------- AL Alignment method of seed: The
\r
311 * method used to align the seed members.
\r
313 // Let's save the annotations, maybe we'll be able to do something
\r
314 // with them later...
\r
315 Regex an = new Regex("(\\w+)\\s*(.*)");
\r
316 if (an.search(annContent))
\r
318 if (an.stringMatched(1).equals("NH"))
\r
320 treeString.append(an.stringMatched(2));
\r
322 else if (an.stringMatched(1).equals("TN"))
\r
324 if (treeString.length() > 0)
\r
326 if (treeName == null)
\r
328 treeName = "Tree " + (getTreeCount() + 1);
\r
330 addNewickTree(treeName, treeString.toString());
\r
332 treeName = an.stringMatched(2);
\r
333 treeString = new StringBuffer();
\r
335 setAlignmentProperty(an.stringMatched(1), an.stringMatched(2));
\r
338 else if (annType.equals("GS"))
\r
340 // Generic per-Sequence annotation, free text
\r
342 * Pfam uses these features: Feature Description ---------------------
\r
343 * ----------- AC <accession> ACcession number DE <freetext>
\r
344 * DEscription DR <db>; <accession>; Database Reference OS <organism>
\r
345 * OrganiSm (species) OC <clade> Organism Classification (clade, etc.)
\r
346 * LO <look> Look (Color, etc.)
\r
348 if (s.search(annContent))
\r
350 String acc = s.stringMatched(1);
\r
351 String type = s.stringMatched(2);
\r
352 String content = s.stringMatched(3);
\r
353 // TODO: store DR in a vector.
\r
354 // TODO: store AC according to generic file db annotation.
\r
356 if (seqAnn.containsKey(acc))
\r
358 ann = (Hashtable) seqAnn.get(acc);
\r
362 ann = new Hashtable();
\r
364 ann.put(type, content);
\r
365 seqAnn.put(acc, ann);
\r
369 throw new IOException("Error parsing " + line);
\r
372 else if (annType.equals("GC"))
\r
374 // Generic per-Column annotation, exactly 1 char per column
\r
375 // always need a label.
\r
376 if (x.search(annContent))
\r
378 // parse out and create alignment annotation directly.
\r
379 parseAnnotationRow(annotations, x.stringMatched(1),
\r
380 x.stringMatched(2));
\r
383 else if (annType.equals("GR"))
\r
385 // Generic per-Sequence AND per-Column markup, exactly 1 char per
\r
388 * Feature Description Markup letters ------- -----------
\r
389 * -------------- SS Secondary Structure [HGIEBTSCX] SA Surface
\r
390 * Accessibility [0-9X] (0=0%-10%; ...; 9=90%-100%) TM TransMembrane
\r
391 * [Mio] PP Posterior Probability [0-9*] (0=0.00-0.05; 1=0.05-0.15;
\r
392 * *=0.95-1.00) LI LIgand binding [*] AS Active Site [*] IN INtron (in
\r
395 if (s.search(annContent))
\r
397 String acc = s.stringMatched(1);
\r
398 String type = s.stringMatched(2);
\r
399 String seq = new String(s.stringMatched(3));
\r
400 String description = null;
\r
401 // Check for additional information about the current annotation
\r
402 // We use a simple string tokenizer here for speed
\r
403 StringTokenizer sep = new StringTokenizer(seq, " \t");
\r
404 description = sep.nextToken();
\r
405 if (sep.hasMoreTokens())
\r
407 seq = sep.nextToken();
\r
412 description = new String();
\r
414 // sequence id with from-to fields
\r
417 // Get an object with all the annotations for this sequence
\r
418 if (seqAnn.containsKey(acc))
\r
420 // logger.debug("Found annotations for " + acc);
\r
421 ann = (Hashtable) seqAnn.get(acc);
\r
425 // logger.debug("Creating new annotations holder for " + acc);
\r
426 ann = new Hashtable();
\r
427 seqAnn.put(acc, ann);
\r
430 Hashtable features;
\r
431 // Get an object with all the content for an annotation
\r
432 if (ann.containsKey("features"))
\r
434 // logger.debug("Found features for " + acc);
\r
435 features = (Hashtable) ann.get("features");
\r
439 // logger.debug("Creating new features holder for " + acc);
\r
440 features = new Hashtable();
\r
441 ann.put("features", features);
\r
445 if (features.containsKey(this.id2type(type)))
\r
447 // logger.debug("Found content for " + this.id2type(type));
\r
448 content = (Hashtable) features.get(this.id2type(type));
\r
452 // logger.debug("Creating new content holder for " +
\r
453 // this.id2type(type));
\r
454 content = new Hashtable();
\r
455 features.put(this.id2type(type), content);
\r
457 String ns = (String) content.get(description);
\r
463 content.put(description, ns);
\r
468 .println("Warning - couldn't parse sequence annotation row line:\n"
\r
470 // throw new IOException("Error parsing " + line);
\r
475 throw new IOException("Unknown annotation detected: " + annType
\r
476 + " " + annContent);
\r
480 if (treeString.length() > 0)
\r
482 if (treeName == null)
\r
484 treeName = "Tree " + (1 + getTreeCount());
\r
486 addNewickTree(treeName, treeString.toString());
\r
490 private AlignmentAnnotation parseAnnotationRow(Vector annotation,
\r
491 String label, String annots)
\r
493 String convert1, convert2 = null;
\r
495 // Convert all bracket types to parentheses
\r
496 Regex openparen = new Regex("(<|\\[)", "(");
\r
497 Regex closeparen = new Regex("(>|\\])", ")");
\r
499 // Detect if file is RNA by looking for bracket types
\r
500 Regex detectbrackets = new Regex("(<|>|\\[|\\]|\\(|\\))");
\r
502 convert1 = openparen.replaceAll(annots);
\r
503 convert2 = closeparen.replaceAll(convert1);
\r
506 String type = (label.indexOf("_cons") == label.length() - 5) ? label
\r
507 .substring(0, label.length() - 5) : label;
\r
508 boolean ss = false;
\r
509 type = id2type(type);
\r
510 if (type.equals("secondary structure"))
\r
514 // decide on secondary structure or not.
\r
515 Annotation[] els = new Annotation[annots.length()];
\r
516 for (int i = 0; i < annots.length(); i++)
\r
518 String pos = annots.substring(i, i + 1);
\r
520 ann = new Annotation(pos, "", ' ', 0f); // 0f is 'valid' null - will not
\r
524 if (detectbrackets.search(pos))
\r
526 ann.secondaryStructure = jalview.schemes.ResidueProperties
\r
527 .getRNASecStrucState(pos).charAt(0);
\r
531 ann.secondaryStructure = jalview.schemes.ResidueProperties
\r
532 .getDssp3state(pos).charAt(0);
\r
535 if (ann.secondaryStructure == pos.charAt(0) || pos.charAt(0) == 'C')
\r
537 ann.displayCharacter = ""; // null; // " ";
\r
541 ann.displayCharacter = " " + ann.displayCharacter;
\r
547 AlignmentAnnotation annot = null;
\r
548 Enumeration e = annotation.elements();
\r
549 while (e.hasMoreElements())
\r
551 annot = (AlignmentAnnotation) e.nextElement();
\r
552 if (annot.label.equals(type))
\r
558 annot = new AlignmentAnnotation(type, type, els);
\r
559 annotation.addElement(annot);
\r
563 Annotation[] anns = new Annotation[annot.annotations.length
\r
565 System.arraycopy(annot.annotations, 0, anns, 0,
\r
566 annot.annotations.length);
\r
567 System.arraycopy(els, 0, anns, annot.annotations.length, els.length);
\r
568 annot.annotations = anns;
\r
573 public static String print(SequenceI[] s)
\r
575 return "not yet implemented";
\r
578 public String print()
\r
580 return print(getSeqsAsArray());
\r
583 private static Hashtable typeIds = null;
\r
586 if (typeIds == null)
\r
588 typeIds = new Hashtable();
\r
589 typeIds.put("SS", "secondary structure");
\r
590 typeIds.put("SA", "surface accessibility");
\r
591 typeIds.put("TM", "transmembrane");
\r
592 typeIds.put("PP", "posterior probability");
\r
593 typeIds.put("LI", "ligand binding");
\r
594 typeIds.put("AS", "active site");
\r
595 typeIds.put("IN", "intron");
\r
596 typeIds.put("IR", "interacting residue");
\r
597 typeIds.put("AC", "accession");
\r
598 typeIds.put("OS", "organism");
\r
599 typeIds.put("CL", "class");
\r
600 typeIds.put("DE", "description");
\r
601 typeIds.put("DR", "reference");
\r
602 typeIds.put("LO", "look");
\r
603 typeIds.put("RF", "reference positions");
\r
608 private String id2type(String id)
\r
610 if (typeIds.containsKey(id))
\r
612 return (String) typeIds.get(id);
\r
614 System.err.println("Warning : Unknown Stockholm annotation type code "
\r
619 * //ssline is complete secondary structure line private AlignmentAnnotation
\r
620 * addHelices(Vector annotation, String label, String ssline) {
\r
622 * // decide on secondary structure or not. Annotation[] els = new
\r
623 * Annotation[ssline.length()]; for (int i = 0; i < ssline.length(); i++) {
\r
624 * String pos = ssline.substring(i, i + 1); Annotation ann; ann = new
\r
625 * Annotation(pos, "", ' ', 0f); // 0f is 'valid' null - will not
\r
627 * ann.secondaryStructure =
\r
628 * jalview.schemes.ResidueProperties.getRNAssState(pos).charAt(0);
\r
630 * ann.displayCharacter = "x" + ann.displayCharacter;
\r
632 * System.out.println(ann.displayCharacter);
\r
634 * els[i] = ann; } AlignmentAnnotation helicesAnnot = null; Enumeration e =
\r
635 * annotation.elements(); while (e.hasMoreElements()) { helicesAnnot =
\r
636 * (AlignmentAnnotation) e.nextElement(); if (helicesAnnot.label.equals(type))
\r
637 * break; helicesAnnot = null; } if (helicesAnnot == null) { helicesAnnot =
\r
638 * new AlignmentAnnotation(type, type, els);
\r
639 * annotation.addElement(helicesAnnot); } else { Annotation[] anns = new
\r
640 * Annotation[helicesAnnot.annotations.length + els.length];
\r
641 * System.arraycopy(helicesAnnot.annotations, 0, anns, 0,
\r
642 * helicesAnnot.annotations.length); System.arraycopy(els, 0, anns,
\r
643 * helicesAnnot.annotations.length, els.length); helicesAnnot.annotations =
\r
646 * helicesAnnot.features = Rna.GetBasePairs(ssline);
\r
647 * Rna.HelixMap(helicesAnnot.features);
\r
650 * return helicesAnnot; }
\r