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.util.Format;
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");
47 StringBuffer out; // output buffer
50 public StockholmFile()
55 * Creates a new StockholmFile object for output.
57 public StockholmFile(AlignmentI al)
62 public StockholmFile(String inFile, String type) throws IOException
67 public StockholmFile(FileParse source) throws IOException
72 public void initData()
78 * Parse a file in Stockholm format into Jalview's data model. The file has to
79 * be passed at construction time
82 * If there is an error with the input file
84 public void parse() throws IOException
86 StringBuffer treeString = new StringBuffer();
87 String treeName = null;
88 // --------------- Variable Definitions -------------------
92 Hashtable seqAnn = new Hashtable(); // Sequence related annotations
93 Hashtable seqs = new Hashtable();
94 Regex p, r, rend, s, x;
96 // Temporary line for processing RNA annotation
97 // String RNAannot = "";
99 // ------------------ Parsing File ----------------------
100 // First, we have to check that this file has STOCKHOLM format, i.e. the
101 // first line must match
102 r = new Regex("# STOCKHOLM ([\\d\\.]+)");
103 if (!r.search(nextLine()))
105 throw new IOException(
106 "This file is not in valid STOCKHOLM format: First line does not contain '# STOCKHOLM'");
110 version = r.stringMatched(1);
111 // logger.debug("Stockholm version: " + version);
114 // We define some Regexes here that will be used regularily later
115 rend = new Regex("^\\s*\\/\\/"); // Find the end of an alignment
116 p = new Regex("(\\S+)\\/(\\d+)\\-(\\d+)"); // split sequence id in
118 s = new Regex("(\\S+)\\s+(\\S*)\\s+(.*)"); // Parses annotation subtype
119 r = new Regex("#=(G[FSRC]?)\\s+(.*)"); // Finds any annotation line
120 x = new Regex("(\\S+)\\s+(\\S+)"); // split id from sequence
122 // Convert all bracket types to parentheses (necessary for passing to VARNA)
123 Regex openparen = new Regex("(<|\\[)", "(");
124 Regex closeparen = new Regex("(>|\\])", ")");
126 // Detect if file is RNA by looking for bracket types
127 Regex detectbrackets = new Regex("(<|>|\\[|\\]|\\(|\\))");
134 openparen.optimize();
135 closeparen.optimize();
137 while ((line = nextLine()) != null)
139 if (line.length() == 0)
143 if (rend.search(line))
145 // End of the alignment, pass stuff back
146 this.noSeqs = seqs.size();
148 String propety = null;
149 Regex pf = new Regex("PF[0-9]{5}(.*)"); // Finds AC for Pfam
150 Regex rf = new Regex("RF[0-9]{5}(.*)"); // Finds AC for Rfam
151 if (getAlignmentProperty("AC") != null)
153 String dbType = getAlignmentProperty("AC").toString();
154 if (pf.search(dbType))
158 else if (rf.search(dbType))
163 // logger.debug("Number of sequences: " + this.noSeqs);
164 Enumeration accs = seqs.keys();
165 while (accs.hasMoreElements())
167 String acc = (String) accs.nextElement();
168 // logger.debug("Processing sequence " + acc);
169 String seq = (String) seqs.remove(acc);
170 if (maxLength < seq.length())
172 maxLength = seq.length();
178 * Retrieve hash of annotations for this accession Associate
179 * Annotation with accession
181 Hashtable accAnnotations = null;
183 if (seqAnn != null && seqAnn.containsKey(acc))
185 accAnnotations = (Hashtable) seqAnn.remove(acc);
186 // TODO: add structures to sequence
189 // Split accession in id and from/to
192 sid = p.stringMatched(1);
193 start = Integer.parseInt(p.stringMatched(2));
194 end = Integer.parseInt(p.stringMatched(3));
196 // logger.debug(sid + ", " + start + ", " + end);
198 Sequence seqO = new Sequence(sid, seq, start, end);
199 // Add Description (if any)
200 if (accAnnotations != null && accAnnotations.containsKey("DE"))
202 String desc = (String) accAnnotations.get("DE");
203 seqO.setDescription((desc == null) ? "" : desc);
208 // Add DB References (if any)
209 if (accAnnotations != null && accAnnotations.containsKey("DR"))
211 String dbr = (String) accAnnotations.get("DR");
212 if (dbr != null && dbr.indexOf(";") > -1)
214 String src = dbr.substring(0, dbr.indexOf(";"));
215 String acn = dbr.substring(dbr.indexOf(";") + 1);
216 jalview.util.DBRefUtils.parseToDbRef(seqO, src, "0", acn);
220 if (accAnnotations != null && accAnnotations.containsKey("AC") && propety != null)
222 String dbr = (String) accAnnotations.get("AC");
225 String src = propety;
226 String acn = dbr.toString();
227 jalview.util.DBRefUtils.parseToDbRef(seqO, src, "0", acn);
232 Hashtable features = null;
233 // We need to adjust the positions of all features to account for gaps
236 features = (Hashtable) accAnnotations.remove("features");
237 } catch (java.lang.NullPointerException e)
239 // loggerwarn("Getting Features for " + acc + ": " +
243 // if we have features
244 if (features != null)
246 int posmap[] = seqO.findPositionMap();
247 Enumeration i = features.keys();
248 while (i.hasMoreElements())
250 // TODO: parse out secondary structure annotation as annotation
252 // TODO: parse out scores as annotation row
253 // TODO: map coding region to core jalview feature types
254 String type = i.nextElement().toString();
255 Hashtable content = (Hashtable) features.remove(type);
257 // add alignment annotation for this feature
258 String key = type2id(type);
261 if (accAnnotations != null && accAnnotations.containsKey(key))
263 Vector vv = (Vector) accAnnotations.get(key);
264 for (int ii = 0; ii < vv.size(); ii++)
266 AlignmentAnnotation an = (AlignmentAnnotation) vv.elementAt(ii);
267 seqO.addAlignmentAnnotation(an);
272 Enumeration j = content.keys();
273 while (j.hasMoreElements())
275 String desc = j.nextElement().toString();
276 String ns = content.get(desc).toString();
277 char[] byChar = ns.toCharArray();
278 for (int k = 0; k < byChar.length; k++)
281 if (!(c == ' ' || c == '_' || c == '-' || c == '.')) // PFAM
288 int new_pos = posmap[k]; // look up nearest seqeunce
289 // position to this column
290 SequenceFeature feat = new SequenceFeature(type, desc,
291 new_pos, new_pos, 0f, null);
293 seqO.addSequenceFeature(feat);
303 // logger.debug("Adding seq " + acc + " from " + start + " to " + end
305 this.seqs.addElement(seqO);
307 return; // finished parsing this segment of source
309 else if (!r.search(line))
311 // System.err.println("Found sequence line: " + line);
313 // Split sequence in sequence and accession parts
316 // logger.error("Could not parse sequence line: " + line);
317 throw new IOException("Could not parse sequence line: " + line);
319 String ns = (String) seqs.get(x.stringMatched(1));
324 ns += x.stringMatched(2);
326 seqs.put(x.stringMatched(1), ns);
330 String annType = r.stringMatched(1);
331 String annContent = r.stringMatched(2);
333 // System.err.println("type:" + annType + " content: " + annContent);
335 if (annType.equals("GF"))
338 * Generic per-File annotation, free text Magic features: #=GF NH
339 * <tree in New Hampshire eXtended format> #=GF TN <Unique identifier
340 * for the next tree> Pfam descriptions: 7. DESCRIPTION OF FIELDS
342 * Compulsory fields: ------------------
344 * AC Accession number: Accession number in form PFxxxxx.version or
345 * PBxxxxxx. ID Identification: One word name for family. DE
346 * Definition: Short description of family. AU Author: Authors of the
347 * entry. SE Source of seed: The source suggesting the seed members
348 * belong to one family. GA Gathering method: Search threshold to
349 * build the full alignment. TC Trusted Cutoff: Lowest sequence score
350 * and domain score of match in the full alignment. NC Noise Cutoff:
351 * Highest sequence score and domain score of match not in full
352 * alignment. TP Type: Type of family -- presently Family, Domain,
353 * Motif or Repeat. SQ Sequence: Number of sequences in alignment. AM
354 * Alignment Method The order ls and fs hits are aligned to the model
355 * to build the full align. // End of alignment.
357 * Optional fields: ----------------
359 * DC Database Comment: Comment about database reference. DR Database
360 * Reference: Reference to external database. RC Reference Comment:
361 * Comment about literature reference. RN Reference Number: Reference
362 * Number. RM Reference Medline: Eight digit medline UI number. RT
363 * Reference Title: Reference Title. RA Reference Author: Reference
364 * Author RL Reference Location: Journal location. PI Previous
365 * identifier: Record of all previous ID lines. KW Keywords: Keywords.
366 * CC Comment: Comments. NE Pfam accession: Indicates a nested domain.
367 * NL Location: Location of nested domains - sequence ID, start and
370 * Obsolete fields: ----------- AL Alignment method of seed: The
371 * method used to align the seed members.
373 // Let's save the annotations, maybe we'll be able to do something
374 // with them later...
375 Regex an = new Regex("(\\w+)\\s*(.*)");
376 if (an.search(annContent))
378 if (an.stringMatched(1).equals("NH"))
380 treeString.append(an.stringMatched(2));
382 else if (an.stringMatched(1).equals("TN"))
384 if (treeString.length() > 0)
386 if (treeName == null)
388 treeName = "Tree " + (getTreeCount() + 1);
390 addNewickTree(treeName, treeString.toString());
392 treeName = an.stringMatched(2);
393 treeString = new StringBuffer();
395 setAlignmentProperty(an.stringMatched(1), an.stringMatched(2));
398 else if (annType.equals("GS"))
400 // Generic per-Sequence annotation, free text
402 * Pfam uses these features: Feature Description ---------------------
403 * ----------- AC <accession> ACcession number DE <freetext>
404 * DEscription DR <db>; <accession>; Database Reference OS <organism>
405 * OrganiSm (species) OC <clade> Organism Classification (clade, etc.)
406 * LO <look> Look (Color, etc.)
408 if (s.search(annContent))
410 String acc = s.stringMatched(1);
411 String type = s.stringMatched(2);
412 String content = s.stringMatched(3);
413 // TODO: store DR in a vector.
414 // TODO: store AC according to generic file db annotation.
416 if (seqAnn.containsKey(acc))
418 ann = (Hashtable) seqAnn.get(acc);
422 ann = new Hashtable();
424 ann.put(type, content);
425 seqAnn.put(acc, ann);
429 throw new IOException("Error parsing " + line);
432 else if (annType.equals("GC"))
434 // Generic per-Column annotation, exactly 1 char per column
435 // always need a label.
436 if (x.search(annContent))
438 // parse out and create alignment annotation directly.
439 parseAnnotationRow(annotations, x.stringMatched(1),
443 else if (annType.equals("GR"))
445 // Generic per-Sequence AND per-Column markup, exactly 1 char per
448 * Feature Description Markup letters ------- -----------
449 * -------------- SS Secondary Structure [HGIEBTSCX] SA Surface
450 * Accessibility [0-9X] (0=0%-10%; ...; 9=90%-100%) TM TransMembrane
451 * [Mio] PP Posterior Probability [0-9*] (0=0.00-0.05; 1=0.05-0.15;
452 * *=0.95-1.00) LI LIgand binding [*] AS Active Site [*] IN INtron (in
455 if (s.search(annContent))
457 String acc = s.stringMatched(1);
458 String type = s.stringMatched(2);
459 String seq = new String(s.stringMatched(3));
460 String description = null;
461 // Check for additional information about the current annotation
462 // We use a simple string tokenizer here for speed
463 StringTokenizer sep = new StringTokenizer(seq, " \t");
464 description = sep.nextToken();
465 if (sep.hasMoreTokens())
467 seq = sep.nextToken();
472 description = new String();
474 // sequence id with from-to fields
477 // Get an object with all the annotations for this sequence
478 if (seqAnn.containsKey(acc))
480 // logger.debug("Found annotations for " + acc);
481 ann = (Hashtable) seqAnn.get(acc);
485 // logger.debug("Creating new annotations holder for " + acc);
486 ann = new Hashtable();
487 seqAnn.put(acc, ann);
489 // TODO test structure, call parseAnnotationRow with vector from
490 // hashtable for specific sequence
492 // Get an object with all the content for an annotation
493 if (ann.containsKey("features"))
495 // logger.debug("Found features for " + acc);
496 features = (Hashtable) ann.get("features");
500 // logger.debug("Creating new features holder for " + acc);
501 features = new Hashtable();
502 ann.put("features", features);
506 if (features.containsKey(this.id2type(type)))
508 // logger.debug("Found content for " + this.id2type(type));
509 content = (Hashtable) features.get(this.id2type(type));
513 // logger.debug("Creating new content holder for " +
514 // this.id2type(type));
515 content = new Hashtable();
516 features.put(this.id2type(type), content);
518 String ns = (String) content.get(description);
524 content.put(description, ns);
526 if (seqAnn.containsKey(acc))
528 strucAnn = (Hashtable) seqAnn.get(acc);
532 strucAnn = new Hashtable();
535 Vector newStruc = new Vector();
536 parseAnnotationRow(newStruc, type, ns);
537 strucAnn.put(type, newStruc);
538 seqAnn.put(acc, strucAnn);
543 .println("Warning - couldn't parse sequence annotation row line:\n"
545 // throw new IOException("Error parsing " + line);
550 throw new IOException("Unknown annotation detected: " + annType
555 if (treeString.length() > 0)
557 if (treeName == null)
559 treeName = "Tree " + (1 + getTreeCount());
561 addNewickTree(treeName, treeString.toString());
565 protected static AlignmentAnnotation parseAnnotationRow(
566 Vector annotation, String label, String annots)
568 String convert1, convert2 = null;
570 // Convert all bracket types to parentheses
571 Regex openparen = new Regex("(<|\\[)", "(");
572 Regex closeparen = new Regex("(>|\\])", ")");
574 // Detect if file is RNA by looking for bracket types
575 Regex detectbrackets = new Regex("(<|>|\\[|\\]|\\(|\\))");
577 convert1 = openparen.replaceAll(annots);
578 convert2 = closeparen.replaceAll(convert1);
582 if (label.contains("_cons")) {
583 type = (label.indexOf("_cons") == label.length() - 5) ? label
584 .substring(0, label.length() - 5) : label;
587 type = id2type(type);
588 if (type.equals("secondary structure"))
592 // decide on secondary structure or not.
593 Annotation[] els = new Annotation[annots.length()];
594 for (int i = 0; i < annots.length(); i++)
596 String pos = annots.substring(i, i + 1);
598 ann = new Annotation(pos, "", ' ', 0f); // 0f is 'valid' null - will not
602 if (detectbrackets.search(pos))
604 ann.secondaryStructure = jalview.schemes.ResidueProperties
605 .getRNASecStrucState(pos).charAt(0);
609 ann.secondaryStructure = jalview.schemes.ResidueProperties
610 .getDssp3state(pos).charAt(0);
613 if (ann.secondaryStructure == pos.charAt(0) || pos.charAt(0) == 'C')
615 ann.displayCharacter = ""; // null; // " ";
619 ann.displayCharacter = " " + ann.displayCharacter;
625 AlignmentAnnotation annot = null;
626 Enumeration e = annotation.elements();
627 while (e.hasMoreElements())
629 annot = (AlignmentAnnotation) e.nextElement();
630 if (annot.label.equals(type))
636 annot = new AlignmentAnnotation(type, type, els);
637 annotation.addElement(annot);
641 Annotation[] anns = new Annotation[annot.annotations.length
643 System.arraycopy(annot.annotations, 0, anns, 0,
644 annot.annotations.length);
645 System.arraycopy(els, 0, anns, annot.annotations.length, els.length);
646 annot.annotations = anns;
647 // System.out.println("else: ");
652 public String print(SequenceI[] s)
654 // find max length of id
658 Hashtable dataRef = null;
659 while ((in < s.length) && (s[in] != null))
661 String tmp = printId(s[in]);
662 if (s[in].getSequence().length > max)
664 max = s[in].getSequence().length;
667 if (tmp.length() > maxid)
669 maxid = tmp.length();
671 if (s[in].getDBRef() != null)
673 for (int idb = 0; idb < s[in].getDBRef().length; idb++)
676 dataRef = new Hashtable();
678 String datAs1 = s[in].getDBRef()[idb].getSource().toString() + " ; " +s[in].getDBRef()[idb].getAccessionId().toString();
679 dataRef.put(tmp, datAs1);
687 // output database type
688 if (al.getProperties() != null)
690 if (!al.getProperties().isEmpty())
692 Enumeration key = al.getProperties().keys();
693 Enumeration val = al.getProperties().elements();
694 while (key.hasMoreElements())
696 out.append("#=GF " + key.nextElement() + " " + val.nextElement());
702 // output database accessions
705 Enumeration en = dataRef.keys();
706 while (en.hasMoreElements())
708 Object idd = en.nextElement();
709 String type = (String) dataRef.remove(idd);
710 out.append(new Format("%-" + (maxid - 2) + "s").form("#=GS " +idd.toString() + " "));
711 if (type.contains("PFAM") || type.contains("RFAM") )
714 out.append(" AC " + type.substring(type.indexOf(";") + 1));
717 out.append(" DR " + type + " ");
723 // output annotations
724 while (i < s.length && s[i] != null)
726 if (s[i].getDatasetSequence() != null)
728 SequenceI ds = s[i].getDatasetSequence();
729 AlignmentAnnotation[] alAnot;
732 alAnot = s[i].getAnnotation();
736 for (int j = 0; j < alAnot.length; j++)
738 if (ds.getSequenceFeatures() != null)
740 feature = ds.getSequenceFeatures()[0].type;
742 String key = type2id(feature);
748 // out.append("#=GR ");
749 out.append(new Format("%-" + maxid + "s").form("#=GR " + printId(s[i]) + " " + key + " "));
750 ann = alAnot[j].annotations;
752 for (int k = 0; k < ann.length; k++)
755 String ch = (annot == null) ? Character.toString(s[i].getCharAt(k)) : annot.displayCharacter;
756 if (ch.length() == 0)
758 if (key.equals("SS")) {
759 char ll = annot.secondaryStructure;
760 seq = (Character.toString(ll).equals(" ")) ? seq + "C" : seq + ll;
764 } else if (ch.length() == 1) {
766 } else if (ch.length() > 1) {
767 seq += ch.charAt(1) ;
776 out.append(new Format("%-" + maxid + "s").form(printId(s[i])+" "));
777 out.append(s[i].getSequenceAsString());
782 // alignment annotation
783 AlignmentAnnotation aa;
784 if (al.getAlignmentAnnotation() != null)
786 for (int ia = 0; ia < al.getAlignmentAnnotation().length; ia++)
788 aa = al.getAlignmentAnnotation()[ia];
789 if (aa.autoCalculated || !aa.visible)
796 if (aa.label.equals("seq"))
799 label = type2id(aa.label.toLowerCase())+"_cons";
804 out.append(new Format("%-" + maxid + "s").form("#=GC " + label+" "));
805 for (int j = 0; j < aa.annotations.length; j++)
807 String ch = (aa.annotations[j] == null) ? "-" : aa.annotations[j].displayCharacter ;
808 if (ch.length() == 0)
810 char ll = aa.annotations[j].secondaryStructure;
811 if (Character.toString(ll).equals(" "))
815 } else if (ch.length() == 1) {
817 } else if (ch.length() > 1) {
818 seq += ch.charAt(1) ;
825 return out.toString();
828 public String print()
830 out = new StringBuffer();
831 out.append("# STOCKHOLM 1.0");
833 print(getSeqsAsArray());
837 return out.toString();
840 private static Hashtable typeIds = null;
845 typeIds = new Hashtable();
846 typeIds.put("SS", "secondary structure");
847 typeIds.put("SA", "surface accessibility");
848 typeIds.put("TM", "transmembrane");
849 typeIds.put("PP", "posterior probability");
850 typeIds.put("LI", "ligand binding");
851 typeIds.put("AS", "active site");
852 typeIds.put("IN", "intron");
853 typeIds.put("IR", "interacting residue");
854 typeIds.put("AC", "accession");
855 typeIds.put("OS", "organism");
856 typeIds.put("CL", "class");
857 typeIds.put("DE", "description");
858 typeIds.put("DR", "reference");
859 typeIds.put("LO", "look");
860 typeIds.put("RF", "reference positions");
865 protected static String id2type(String id)
867 if (typeIds.containsKey(id))
869 return (String) typeIds.get(id);
871 System.err.println("Warning : Unknown Stockholm annotation type code "
876 protected static String type2id(String type)
879 Enumeration e = typeIds.keys();
880 while (e.hasMoreElements())
882 Object ll = e.nextElement();
883 if (typeIds.get(ll).toString().equals(type))
893 System.err.println("Warning : Unknown Stockholm annotation type: "
898 * //ssline is complete secondary structure line private AlignmentAnnotation
899 * addHelices(Vector annotation, String label, String ssline) {
901 * // decide on secondary structure or not. Annotation[] els = new
902 * Annotation[ssline.length()]; for (int i = 0; i < ssline.length(); i++) {
903 * String pos = ssline.substring(i, i + 1); Annotation ann; ann = new
904 * Annotation(pos, "", ' ', 0f); // 0f is 'valid' null - will not
906 * ann.secondaryStructure =
907 * jalview.schemes.ResidueProperties.getRNAssState(pos).charAt(0);
909 * ann.displayCharacter = "x" + ann.displayCharacter;
911 * System.out.println(ann.displayCharacter);
913 * els[i] = ann; } AlignmentAnnotation helicesAnnot = null; Enumeration e =
914 * annotation.elements(); while (e.hasMoreElements()) { helicesAnnot =
915 * (AlignmentAnnotation) e.nextElement(); if (helicesAnnot.label.equals(type))
916 * break; helicesAnnot = null; } if (helicesAnnot == null) { helicesAnnot =
917 * new AlignmentAnnotation(type, type, els);
918 * annotation.addElement(helicesAnnot); } else { Annotation[] anns = new
919 * Annotation[helicesAnnot.annotations.length + els.length];
920 * System.arraycopy(helicesAnnot.annotations, 0, anns, 0,
921 * helicesAnnot.annotations.length); System.arraycopy(els, 0, anns,
922 * helicesAnnot.annotations.length, els.length); helicesAnnot.annotations =
925 * helicesAnnot.features = Rna.GetBasePairs(ssline);
926 * Rna.HelixMap(helicesAnnot.features);
929 * return helicesAnnot; }