2 * Jalview - A Sequence Alignment Editor and Viewer (Development Version 2.4.1)
\r
3 * Copyright (C) 2009 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle
\r
5 * This program is free software; you can redistribute it and/or
\r
6 * modify it under the terms of the GNU General Public License
\r
7 * as published by the Free Software Foundation; either version 2
\r
8 * of the License, or (at your option) any later version.
\r
10 * This program is distributed in the hope that it will be useful,
\r
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
\r
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
\r
13 * GNU General Public License for more details.
\r
15 * You should have received a copy of the GNU General Public License
\r
16 * along with this program; if not, write to the Free Software
\r
17 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
\r
20 * This extension was written by Benjamin Schuster-Boeckler at sanger.ac.uk
\r
27 import com.stevesoft.pat.*;
\r
28 import jalview.datamodel.*;
\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 // ------------------ Parsing File ----------------------
\r
87 // First, we have to check that this file has STOCKHOLM format, i.e. the
\r
88 // first line must match
\r
89 r = new Regex("# STOCKHOLM ([\\d\\.]+)");
\r
90 if (!r.search(nextLine()))
\r
92 throw new IOException(
\r
93 "This file is not in valid STOCKHOLM format: First line does not contain '# STOCKHOLM'");
\r
97 version = r.stringMatched(1);
\r
98 // logger.debug("Stockholm version: " + version);
\r
101 // We define some Regexes here that will be used regularily later
\r
102 rend = new Regex("\\/\\/"); // Find the end of an alignment
\r
103 p = new Regex("(\\S+)\\/(\\d+)\\-(\\d+)"); // split sequence id in
\r
105 s = new Regex("(\\S+)\\s+(\\S*)\\s+(.*)"); // Parses annotation subtype
\r
106 r = new Regex("#=(G[FSRC]?)\\s+(.*)"); // Finds any annotation line
\r
107 x = new Regex("(\\S+)\\s+(\\S+)"); // split id from sequence
\r
115 while ((line = nextLine()) != null)
\r
117 if (line.length() == 0)
\r
121 if (rend.search(line))
\r
123 // End of the alignment, pass stuff back
\r
125 this.noSeqs = seqs.size();
\r
126 // logger.debug("Number of sequences: " + this.noSeqs);
\r
127 Enumeration accs = seqs.keys();
\r
128 while (accs.hasMoreElements())
\r
130 String acc = (String) accs.nextElement();
\r
131 // logger.debug("Processing sequence " + acc);
\r
132 String seq = (String) seqs.remove(acc);
\r
133 if (maxLength < seq.length())
\r
135 maxLength = seq.length();
\r
140 // Retrieve hash of annotations for this accession
\r
141 Hashtable accAnnotations = null;
\r
143 if (seqAnn != null && seqAnn.containsKey(acc))
\r
145 accAnnotations = (Hashtable) seqAnn.remove(acc);
\r
148 // Split accession in id and from/to
\r
151 sid = p.stringMatched(1);
\r
152 start = Integer.parseInt(p.stringMatched(2));
\r
153 end = Integer.parseInt(p.stringMatched(3));
\r
155 // logger.debug(sid + ", " + start + ", " + end);
\r
157 Sequence seqO = new Sequence(sid, seq, start, end);
\r
158 // Add Description (if any)
\r
159 if (accAnnotations != null && accAnnotations.containsKey("DE"))
\r
161 String desc = (String) accAnnotations.get("DE");
\r
162 seqO.setDescription((desc == null) ? "" : desc);
\r
164 // Add DB References (if any)
\r
165 if (accAnnotations != null && accAnnotations.containsKey("DR"))
\r
167 String dbr = (String) accAnnotations.get("DR");
\r
168 if (dbr != null && dbr.indexOf(";") > -1)
\r
170 String src = dbr.substring(0, dbr.indexOf(";"));
\r
171 String acn = dbr.substring(dbr.indexOf(";") + 1);
\r
172 jalview.util.DBRefUtils.parseToDbRef(seqO, src, "0", acn);
\r
173 // seqO.addDBRef(dbref);
\r
176 Hashtable features = null;
\r
177 // We need to adjust the positions of all features to account for gaps
\r
180 features = (Hashtable) accAnnotations.remove("features");
\r
181 } catch (java.lang.NullPointerException e)
\r
183 // loggerwarn("Getting Features for " + acc + ": " +
\r
184 // e.getMessage());
\r
187 // if we have features
\r
188 if (features != null)
\r
190 int posmap[] = seqO.findPositionMap();
\r
191 Enumeration i = features.keys();
\r
192 while (i.hasMoreElements())
\r
194 // TODO: parse out secondary structure annotation as annotation
\r
196 // TODO: parse out scores as annotation row
\r
197 // TODO: map coding region to core jalview feature types
\r
198 String type = i.nextElement().toString();
\r
199 Hashtable content = (Hashtable) features.remove(type);
\r
200 Enumeration j = content.keys();
\r
201 while (j.hasMoreElements())
\r
203 String desc = j.nextElement().toString();
\r
204 String ns = content.get(desc).toString();
\r
205 char[] byChar = ns.toCharArray();
\r
206 for (int k = 0; k < byChar.length; k++)
\r
208 char c = byChar[k];
\r
209 if (!(c == ' ' || c == '_' || c == '-' || c == '.')) // PFAM
\r
216 int new_pos = posmap[k]; // look up nearest seqeunce
\r
217 // position to this column
\r
218 SequenceFeature feat = new SequenceFeature(type, desc,
\r
219 new_pos, new_pos, 0f, null);
\r
221 seqO.addSequenceFeature(feat);
\r
231 // logger.debug("Adding seq " + acc + " from " + start + " to " + end
\r
233 this.seqs.addElement(seqO);
\r
235 return; // finished parsing this segment of source
\r
237 else if (!r.search(line))
\r
239 // System.err.println("Found sequence line: " + line);
\r
241 // Split sequence in sequence and accession parts
\r
242 if (!x.search(line))
\r
244 // logger.error("Could not parse sequence line: " + line);
\r
245 throw new IOException("Could not parse sequence line: " + line);
\r
247 String ns = (String) seqs.get(x.stringMatched(1));
\r
252 ns += x.stringMatched(2);
\r
254 seqs.put(x.stringMatched(1), ns);
\r
258 String annType = r.stringMatched(1);
\r
259 String annContent = r.stringMatched(2);
\r
261 // System.err.println("type:" + annType + " content: " + annContent);
\r
263 if (annType.equals("GF"))
\r
266 * Generic per-File annotation, free text Magic features: #=GF NH
\r
267 * <tree in New Hampshire eXtended format> #=GF TN <Unique identifier
\r
268 * for the next tree> Pfam descriptions: 7. DESCRIPTION OF FIELDS
\r
270 * Compulsory fields: ------------------
\r
272 * AC Accession number: Accession number in form PFxxxxx.version or
\r
273 * PBxxxxxx. ID Identification: One word name for family. DE
\r
274 * Definition: Short description of family. AU Author: Authors of the
\r
275 * entry. SE Source of seed: The source suggesting the seed members
\r
276 * belong to one family. GA Gathering method: Search threshold to
\r
277 * build the full alignment. TC Trusted Cutoff: Lowest sequence score
\r
278 * and domain score of match in the full alignment. NC Noise Cutoff:
\r
279 * Highest sequence score and domain score of match not in full
\r
280 * alignment. TP Type: Type of family -- presently Family, Domain,
\r
281 * Motif or Repeat. SQ Sequence: Number of sequences in alignment. AM
\r
282 * Alignment Method The order ls and fs hits are aligned to the model
\r
283 * to build the full align. // End of alignment.
\r
285 * Optional fields: ----------------
\r
287 * DC Database Comment: Comment about database reference. DR Database
\r
288 * Reference: Reference to external database. RC Reference Comment:
\r
289 * Comment about literature reference. RN Reference Number: Reference
\r
290 * Number. RM Reference Medline: Eight digit medline UI number. RT
\r
291 * Reference Title: Reference Title. RA Reference Author: Reference
\r
292 * Author RL Reference Location: Journal location. PI Previous
\r
293 * identifier: Record of all previous ID lines. KW Keywords: Keywords.
\r
294 * CC Comment: Comments. NE Pfam accession: Indicates a nested domain.
\r
295 * NL Location: Location of nested domains - sequence ID, start and
\r
298 * Obsolete fields: ----------- AL Alignment method of seed: The
\r
299 * method used to align the seed members.
\r
301 // Let's save the annotations, maybe we'll be able to do something
\r
302 // with them later...
\r
303 Regex an = new Regex("(\\w+)\\s*(.*)");
\r
304 if (an.search(annContent))
\r
306 if (an.stringMatched(1).equals("NH"))
\r
308 treeString.append(an.stringMatched(2));
\r
310 else if (an.stringMatched(1).equals("TN"))
\r
312 if (treeString.length() > 0)
\r
314 if (treeName == null)
\r
316 treeName = "Tree " + (getTreeCount() + 1);
\r
318 addNewickTree(treeName, treeString.toString());
\r
320 treeName = an.stringMatched(2);
\r
321 treeString = new StringBuffer();
\r
323 setAlignmentProperty(an.stringMatched(1), an.stringMatched(2));
\r
326 else if (annType.equals("GS"))
\r
328 // Generic per-Sequence annotation, free text
\r
330 * Pfam uses these features: Feature Description ---------------------
\r
331 * ----------- AC <accession> ACcession number DE <freetext>
\r
332 * DEscription DR <db>; <accession>; Database Reference OS <organism>
\r
333 * OrganiSm (species) OC <clade> Organism Classification (clade, etc.)
\r
334 * LO <look> Look (Color, etc.)
\r
336 if (s.search(annContent))
\r
338 String acc = s.stringMatched(1);
\r
339 String type = s.stringMatched(2);
\r
340 String content = s.stringMatched(3);
\r
341 // TODO: store DR in a vector.
\r
342 // TODO: store AC according to generic file db annotation.
\r
344 if (seqAnn.containsKey(acc))
\r
346 ann = (Hashtable) seqAnn.get(acc);
\r
350 ann = new Hashtable();
\r
352 ann.put(type, content);
\r
353 seqAnn.put(acc, ann);
\r
357 throw new IOException("Error parsing " + line);
\r
360 else if (annType.equals("GC"))
\r
362 // Generic per-Column annotation, exactly 1 char per column
\r
363 // always need a label.
\r
364 if (x.search(annContent))
\r
366 // parse out and create alignment annotation directly.
\r
367 parseAnnotationRow(annotations, x.stringMatched(1), x
\r
368 .stringMatched(2));
\r
371 else if (annType.equals("GR"))
\r
373 // Generic per-Sequence AND per-Column markup, exactly 1 char per
\r
376 * Feature Description Markup letters ------- -----------
\r
377 * -------------- SS Secondary Structure [HGIEBTSCX] SA Surface
\r
378 * Accessibility [0-9X] (0=0%-10%; ...; 9=90%-100%) TM TransMembrane
\r
379 * [Mio] PP Posterior Probability [0-9*] (0=0.00-0.05; 1=0.05-0.15;
\r
380 * *=0.95-1.00) LI LIgand binding [*] AS Active Site [*] IN INtron (in
\r
383 if (s.search(annContent))
\r
385 String acc = s.stringMatched(1);
\r
386 String type = s.stringMatched(2);
\r
387 String seq = new String(s.stringMatched(3));
\r
388 String description = null;
\r
389 // Check for additional information about the current annotation
\r
390 // We use a simple string tokenizer here for speed
\r
391 StringTokenizer sep = new StringTokenizer(seq, " \t");
\r
392 description = sep.nextToken();
\r
393 if (sep.hasMoreTokens())
\r
395 seq = sep.nextToken();
\r
400 description = new String();
\r
402 // sequence id with from-to fields
\r
405 // Get an object with all the annotations for this sequence
\r
406 if (seqAnn.containsKey(acc))
\r
408 // logger.debug("Found annotations for " + acc);
\r
409 ann = (Hashtable) seqAnn.get(acc);
\r
413 // logger.debug("Creating new annotations holder for " + acc);
\r
414 ann = new Hashtable();
\r
415 seqAnn.put(acc, ann);
\r
418 Hashtable features;
\r
419 // Get an object with all the content for an annotation
\r
420 if (ann.containsKey("features"))
\r
422 // logger.debug("Found features for " + acc);
\r
423 features = (Hashtable) ann.get("features");
\r
427 // logger.debug("Creating new features holder for " + acc);
\r
428 features = new Hashtable();
\r
429 ann.put("features", features);
\r
433 if (features.containsKey(this.id2type(type)))
\r
435 // logger.debug("Found content for " + this.id2type(type));
\r
436 content = (Hashtable) features.get(this.id2type(type));
\r
440 // logger.debug("Creating new content holder for " +
\r
441 // this.id2type(type));
\r
442 content = new Hashtable();
\r
443 features.put(this.id2type(type), content);
\r
445 String ns = (String) content.get(description);
\r
451 content.put(description, seq);
\r
456 .println("Warning - couldn't parse sequence annotation row line:\n"
\r
458 // throw new IOException("Error parsing " + line);
\r
463 throw new IOException("Unknown annotation detected: " + annType
\r
464 + " " + annContent);
\r
468 if (treeString.length() > 0)
\r
470 if (treeName == null)
\r
472 treeName = "Tree " + (1 + getTreeCount());
\r
474 addNewickTree(treeName, treeString.toString());
\r
478 private AlignmentAnnotation parseAnnotationRow(Vector annotation,
\r
479 String label, String annots)
\r
481 String type = (label.indexOf("_cons") == label.length() - 5) ? label
\r
482 .substring(0, label.length() - 5) : label;
\r
483 boolean ss = false;
\r
484 type = id2type(type);
\r
485 if (type.equals("secondary structure"))
\r
489 // decide on secondary structure or not.
\r
490 Annotation[] els = new Annotation[annots.length()];
\r
491 for (int i = 0; i < annots.length(); i++)
\r
493 String pos = annots.substring(i, i + 1);
\r
495 ann = new Annotation(pos, "", ' ', 0f); // 0f is 'valid' null - will not
\r
499 ann.secondaryStructure = jalview.schemes.ResidueProperties
\r
500 .getDssp3state(pos).charAt(0);
\r
501 if (ann.secondaryStructure == pos.charAt(0) || pos.charAt(0) == 'C')
\r
503 ann.displayCharacter = ""; // null; // " ";
\r
507 ann.displayCharacter = " " + ann.displayCharacter;
\r
513 AlignmentAnnotation annot = null;
\r
514 Enumeration e = annotation.elements();
\r
515 while (e.hasMoreElements())
\r
517 annot = (AlignmentAnnotation) e.nextElement();
\r
518 if (annot.label.equals(type))
\r
524 annot = new AlignmentAnnotation(type, type, els);
\r
525 annotation.addElement(annot);
\r
529 Annotation[] anns = new Annotation[annot.annotations.length
\r
531 System.arraycopy(annot.annotations, 0, anns, 0,
\r
532 annot.annotations.length);
\r
533 System.arraycopy(els, 0, anns, annot.annotations.length, els.length);
\r
534 annot.annotations = anns;
\r
539 public static String print(SequenceI[] s)
\r
541 return "not yet implemented";
\r
544 public String print()
\r
546 return print(getSeqsAsArray());
\r
549 private static Hashtable typeIds = null;
\r
552 if (typeIds == null)
\r
554 typeIds = new Hashtable();
\r
555 typeIds.put("SS", "secondary structure");
\r
556 typeIds.put("SA", "surface accessibility");
\r
557 typeIds.put("TM", "transmembrane");
\r
558 typeIds.put("PP", "posterior probability");
\r
559 typeIds.put("LI", "ligand binding");
\r
560 typeIds.put("AS", "active site");
\r
561 typeIds.put("IN", "intron");
\r
562 typeIds.put("IR", "interacting residue");
\r
563 typeIds.put("AC", "accession");
\r
564 typeIds.put("OS", "organism");
\r
565 typeIds.put("CL", "class");
\r
566 typeIds.put("DE", "description");
\r
567 typeIds.put("DR", "reference");
\r
568 typeIds.put("LO", "look");
\r
569 typeIds.put("RF", "reference positions");
\r
574 private String id2type(String id)
\r
576 if (typeIds.containsKey(id))
\r
578 return (String) typeIds.get(id);
\r
580 System.err.println("Warning : Unknown Stockholm annotation type code "
\r