2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
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
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
22 * This extension was written by Benjamin Schuster-Boeckler at sanger.ac.uk
26 import jalview.analysis.Rna;
27 import jalview.datamodel.AlignmentAnnotation;
28 import jalview.datamodel.AlignmentI;
29 import jalview.datamodel.Annotation;
30 import jalview.datamodel.DBRefEntry;
31 import jalview.datamodel.DBRefSource;
32 import jalview.datamodel.Mapping;
33 import jalview.datamodel.Sequence;
34 import jalview.datamodel.SequenceFeature;
35 import jalview.datamodel.SequenceI;
36 import jalview.schemes.ResidueProperties;
37 import jalview.util.Comparison;
38 import jalview.util.Format;
39 import jalview.util.MessageManager;
41 import java.io.BufferedReader;
42 import java.io.FileReader;
43 import java.io.IOException;
44 import java.util.ArrayList;
45 import java.util.Enumeration;
46 import java.util.HashMap;
47 import java.util.Hashtable;
48 import java.util.LinkedHashMap;
49 import java.util.List;
51 import java.util.Map.Entry;
52 import java.util.Vector;
54 import com.stevesoft.pat.Regex;
56 import fr.orsay.lri.varna.exceptions.ExceptionUnmatchedClosingParentheses;
57 import fr.orsay.lri.varna.factories.RNAFactory;
58 import fr.orsay.lri.varna.models.rna.RNA;
60 // import org.apache.log4j.*;
63 * This class is supposed to parse a Stockholm format file into Jalview There
64 * are TODOs in this class: we do not know what the database source and version
65 * is for the file when parsing the #GS= AC tag which associates accessions with
66 * sequences. Database references are also not parsed correctly: a separate
67 * reference string parser must be added to parse the database reference form
68 * into Jalview's local representation.
70 * @author bsb at sanger.ac.uk
71 * @author Natasha Shersnev (Dundee, UK) (Stockholm file writer)
72 * @author Lauren Lui (UCSC, USA) (RNA secondary structure annotation import as
74 * @author Anne Menard (Paris, FR) (VARNA parsing of Stockholm file data)
75 * @version 0.3 + jalview mods
78 public class StockholmFile extends AlignFile
80 private static final String ANNOTATION = "annotation";
82 private static final char UNDERSCORE = '_';
84 // private static final Regex OPEN_PAREN = new Regex("(<|\\[)", "(");
85 // private static final Regex CLOSE_PAREN = new Regex("(>|\\])", ")");
87 public static final Regex DETECT_BRACKETS = new Regex(
88 "(<|>|\\[|\\]|\\(|\\)|\\{|\\})");
91 * lookup table of Stockholm 'feature' (annotation) types
92 * see http://sonnhammer.sbc.su.se/Stockholm.html
94 private static Map<String, String> featureTypes = null;
98 featureTypes = new HashMap<>();
99 featureTypes.put("SS", "Secondary Structure");
100 featureTypes.put("SA", "Surface Accessibility");
101 featureTypes.put("TM", "transmembrane");
102 featureTypes.put("PP", "Posterior Probability");
103 featureTypes.put("LI", "ligand binding");
104 featureTypes.put("AS", "active site");
105 featureTypes.put("IN", "intron");
106 featureTypes.put("IR", "interacting residue");
107 featureTypes.put("AC", "accession");
108 featureTypes.put("OS", "organism");
109 featureTypes.put("CL", "class");
110 featureTypes.put("DE", "description");
111 featureTypes.put("DR", "reference");
112 featureTypes.put("LO", "look");
113 featureTypes.put("RF", "Reference Positions");
116 private AlignmentI al;
118 public StockholmFile()
123 * Creates a new StockholmFile object for output
125 public StockholmFile(AlignmentI al)
130 public StockholmFile(String inFile, DataSourceType type)
136 public StockholmFile(FileParse source) throws IOException
142 * Answers the readable description for a (case-sensitive) annotation type
143 * code, for example "Reference Positions" for "RF". Returns the type code if
144 * no description is found.
149 public static String typeToDescription(String id)
151 if (featureTypes.containsKey(id))
153 return featureTypes.get(id);
156 "Warning : Unknown Stockholm annotation type code " + id);
161 * Answers the annotation type code for a (non-case-sensitive) readable
162 * description, for example "RF" for "Reference Positions" (or null if not
168 public static String descriptionToType(String description)
170 for (Entry<String, String> entry : featureTypes.entrySet())
172 if (entry.getValue().equalsIgnoreCase(description))
174 return entry.getKey();
178 "Warning : Unknown Stockholm annotation type: " + description);
183 public void initData()
189 * Parse a file in Stockholm format into Jalview's data model using VARNA
191 * @throws IOException
192 * If there is an error with the input file
194 public void parse_with_VARNA(java.io.File inFile) throws IOException
196 FileReader fr = null;
197 fr = new FileReader(inFile);
199 BufferedReader r = new BufferedReader(fr);
200 List<RNA> result = null;
203 result = RNAFactory.loadSecStrStockholm(r);
204 } catch (ExceptionUnmatchedClosingParentheses umcp)
206 errormessage = "Unmatched parentheses in annotation. Aborting ("
207 + umcp.getMessage() + ")";
208 throw new IOException(umcp);
210 // DEBUG System.out.println("this is the secondary scructure:"
212 SequenceI[] seqs = new SequenceI[result.size()];
214 for (int i = 0; i < result.size(); i++)
216 // DEBUG System.err.println("Processing i'th sequence in Stockholm file")
217 RNA current = result.get(i);
219 String seq = current.getSeq();
220 String rna = current.getStructDBN(true);
221 // DEBUG System.out.println(seq);
222 // DEBUG System.err.println(rna);
224 int end = seq.length() - 1;
225 id = safeName(getDataName());
226 seqs[i] = new Sequence(id, seq, begin, end);
227 String[] annot = new String[rna.length()];
228 Annotation[] ann = new Annotation[rna.length()];
229 for (int j = 0; j < rna.length(); j++)
231 annot[j] = rna.substring(j, j + 1);
235 for (int k = 0; k < rna.length(); k++)
237 ann[k] = new Annotation(annot[k], "",
238 Rna.getRNASecStrucState(annot[k]).charAt(0), 0f);
241 AlignmentAnnotation align = new AlignmentAnnotation("Sec. str.",
242 current.getID(), ann);
244 seqs[i].addAlignmentAnnotation(align);
245 seqs[i].setRNA(result.get(i));
246 this.annotations.addElement(align);
253 * Parse a file in Stockholm format into Jalview's data model. The file has to
254 * be passed at construction time
256 * @throws IOException
257 * If there is an error with the input file
260 public void parse() throws IOException
262 StringBuffer treeString = new StringBuffer();
263 String treeName = null;
264 // --------------- Variable Definitions -------------------
268 Hashtable seqAnn = new Hashtable(); // Sequence related annotations
269 LinkedHashMap<String, String> seqs = new LinkedHashMap<>();
270 Regex p, r, rend, s, x;
271 // Temporary line for processing RNA annotation
272 // String RNAannot = "";
274 // ------------------ Parsing File ----------------------
275 // First, we have to check that this file has STOCKHOLM format, i.e. the
276 // first line must match
278 r = new Regex("# STOCKHOLM ([\\d\\.]+)");
279 if (!r.search(nextLine()))
281 throw new IOException(MessageManager
282 .getString("exception.stockholm_invalid_format"));
286 version = r.stringMatched(1);
288 // logger.debug("Stockholm version: " + version);
291 // We define some Regexes here that will be used regularly later
292 rend = new Regex("^\\s*\\/\\/"); // Find the end of an alignment
293 p = new Regex("(\\S+)\\/(\\d+)\\-(\\d+)"); // split sequence id in
295 s = new Regex("(\\S+)\\s+(\\S*)\\s+(.*)"); // Parses annotation subtype
296 r = new Regex("#=(G[FSRC]?)\\s+(.*)"); // Finds any annotation line
297 x = new Regex("(\\S+)\\s+(\\S+)"); // split id from sequence
299 // Convert all bracket types to parentheses (necessary for passing to VARNA)
300 Regex openparen = new Regex("(<|\\[)", "(");
301 Regex closeparen = new Regex("(>|\\])", ")");
303 // Detect if file is RNA by looking for bracket types
304 // Regex detectbrackets = new Regex("(<|>|\\[|\\]|\\(|\\))");
311 openparen.optimize();
312 closeparen.optimize();
314 while ((line = nextLine()) != null)
316 if (line.length() == 0)
320 if (rend.search(line))
322 // End of the alignment, pass stuff back
323 this.noSeqs = seqs.size();
325 String seqdb, dbsource = null;
326 Regex pf = new Regex("PF[0-9]{5}(.*)"); // Finds AC for Pfam
327 Regex rf = new Regex("RF[0-9]{5}(.*)"); // Finds AC for Rfam
328 if (getAlignmentProperty("AC") != null)
330 String dbType = getAlignmentProperty("AC").toString();
331 if (pf.search(dbType))
333 // PFAM Alignment - so references are typically from Uniprot
336 else if (rf.search(dbType))
341 // logger.debug("Number of sequences: " + this.noSeqs);
342 for (Map.Entry<String, String> skey : seqs.entrySet())
344 // logger.debug("Processing sequence " + acc);
345 String acc = skey.getKey();
346 String seq = skey.getValue();
347 if (maxLength < seq.length())
349 maxLength = seq.length();
355 * Retrieve hash of annotations for this accession Associate
356 * Annotation with accession
358 Hashtable accAnnotations = null;
360 if (seqAnn != null && seqAnn.containsKey(acc))
362 accAnnotations = (Hashtable) seqAnn.remove(acc);
363 // TODO: add structures to sequence
366 // Split accession in id and from/to
369 sid = p.stringMatched(1);
370 start = Integer.parseInt(p.stringMatched(2));
371 end = Integer.parseInt(p.stringMatched(3));
373 // logger.debug(sid + ", " + start + ", " + end);
375 Sequence seqO = new Sequence(sid, seq, start, end);
376 // Add Description (if any)
377 if (accAnnotations != null && accAnnotations.containsKey("DE"))
379 String desc = (String) accAnnotations.get("DE");
380 seqO.setDescription((desc == null) ? "" : desc);
382 // Add DB References (if any)
383 if (accAnnotations != null && accAnnotations.containsKey("DR"))
385 String dbr = (String) accAnnotations.get("DR");
386 if (dbr != null && dbr.indexOf(";") > -1)
388 String src = dbr.substring(0, dbr.indexOf(";"));
389 String acn = dbr.substring(dbr.indexOf(";") + 1);
390 jalview.util.DBRefUtils.parseToDbRef(seqO, src, "0", acn);
394 if (accAnnotations != null && accAnnotations.containsKey("AC"))
396 if (dbsource != null)
398 String dbr = (String) accAnnotations.get("AC");
401 // we could get very clever here - but for now - just try to
402 // guess accession type from source of alignment plus structure
404 guessDatabaseFor(seqO, dbr, dbsource);
408 // else - do what ? add the data anyway and prompt the user to
409 // specify what references these are ?
412 Hashtable features = null;
413 // We need to adjust the positions of all features to account for gaps
416 features = (Hashtable) accAnnotations.remove("features");
417 } catch (java.lang.NullPointerException e)
419 // loggerwarn("Getting Features for " + acc + ": " +
423 // if we have features
424 if (features != null)
426 int posmap[] = seqO.findPositionMap();
427 Enumeration i = features.keys();
428 while (i.hasMoreElements())
430 // TODO: parse out secondary structure annotation as annotation
432 // TODO: parse out scores as annotation row
433 // TODO: map coding region to core jalview feature types
434 String type = i.nextElement().toString();
435 Hashtable content = (Hashtable) features.remove(type);
437 // add alignment annotation for this feature
438 String key = descriptionToType(type);
441 * have we added annotation rows for this type ?
443 boolean annotsAdded = false;
446 if (accAnnotations != null
447 && accAnnotations.containsKey(key))
449 Vector vv = (Vector) accAnnotations.get(key);
450 for (int ii = 0; ii < vv.size(); ii++)
453 AlignmentAnnotation an = (AlignmentAnnotation) vv
455 seqO.addAlignmentAnnotation(an);
461 Enumeration j = content.keys();
462 while (j.hasMoreElements())
464 String desc = j.nextElement().toString();
465 if (ANNOTATION.equals(desc) && annotsAdded)
467 // don't add features if we already added an annotation row
470 String ns = content.get(desc).toString();
471 char[] byChar = ns.toCharArray();
472 for (int k = 0; k < byChar.length; k++)
475 if (!(c == ' ' || c == '_' || c == '-' || c == '.')) // PFAM
482 int new_pos = posmap[k]; // look up nearest seqeunce
483 // position to this column
484 SequenceFeature feat = new SequenceFeature(type, desc,
485 new_pos, new_pos, null);
487 seqO.addSequenceFeature(feat);
497 // logger.debug("Adding seq " + acc + " from " + start + " to " + end
499 this.seqs.addElement(seqO);
501 return; // finished parsing this segment of source
503 else if (!r.search(line))
505 // System.err.println("Found sequence line: " + line);
507 // Split sequence in sequence and accession parts
510 // logger.error("Could not parse sequence line: " + line);
511 throw new IOException(MessageManager.formatMessage(
512 "exception.couldnt_parse_sequence_line", new String[]
515 String ns = seqs.get(x.stringMatched(1));
520 ns += x.stringMatched(2);
522 seqs.put(x.stringMatched(1), ns);
526 String annType = r.stringMatched(1);
527 String annContent = r.stringMatched(2);
529 // System.err.println("type:" + annType + " content: " + annContent);
531 if (annType.equals("GF"))
534 * Generic per-File annotation, free text Magic features: #=GF NH
535 * <tree in New Hampshire eXtended format> #=GF TN <Unique identifier
536 * for the next tree> Pfam descriptions: 7. DESCRIPTION OF FIELDS
538 * Compulsory fields: ------------------
540 * AC Accession number: Accession number in form PFxxxxx.version or
541 * PBxxxxxx. ID Identification: One word name for family. DE
542 * Definition: Short description of family. AU Author: Authors of the
543 * entry. SE Source of seed: The source suggesting the seed members
544 * belong to one family. GA Gathering method: Search threshold to
545 * build the full alignment. TC Trusted Cutoff: Lowest sequence score
546 * and domain score of match in the full alignment. NC Noise Cutoff:
547 * Highest sequence score and domain score of match not in full
548 * alignment. TP Type: Type of family -- presently Family, Domain,
549 * Motif or Repeat. SQ Sequence: Number of sequences in alignment. AM
550 * Alignment Method The order ls and fs hits are aligned to the model
551 * to build the full align. // End of alignment.
553 * Optional fields: ----------------
555 * DC Database Comment: Comment about database reference. DR Database
556 * Reference: Reference to external database. RC Reference Comment:
557 * Comment about literature reference. RN Reference Number: Reference
558 * Number. RM Reference Medline: Eight digit medline UI number. RT
559 * Reference Title: Reference Title. RA Reference Author: Reference
560 * Author RL Reference Location: Journal location. PI Previous
561 * identifier: Record of all previous ID lines. KW Keywords: Keywords.
562 * CC Comment: Comments. NE Pfam accession: Indicates a nested domain.
563 * NL Location: Location of nested domains - sequence ID, start and
566 * Obsolete fields: ----------- AL Alignment method of seed: The
567 * method used to align the seed members.
569 // Let's save the annotations, maybe we'll be able to do something
570 // with them later...
571 Regex an = new Regex("(\\w+)\\s*(.*)");
572 if (an.search(annContent))
574 if (an.stringMatched(1).equals("NH"))
576 treeString.append(an.stringMatched(2));
578 else if (an.stringMatched(1).equals("TN"))
580 if (treeString.length() > 0)
582 if (treeName == null)
584 treeName = "Tree " + (getTreeCount() + 1);
586 addNewickTree(treeName, treeString.toString());
588 treeName = an.stringMatched(2);
589 treeString = new StringBuffer();
591 setAlignmentProperty(an.stringMatched(1), an.stringMatched(2));
594 else if (annType.equals("GS"))
596 // Generic per-Sequence annotation, free text
598 * Pfam uses these features: Feature Description ---------------------
599 * ----------- AC <accession> ACcession number DE <freetext>
600 * DEscription DR <db>; <accession>; Database Reference OS <organism>
601 * OrganiSm (species) OC <clade> Organism Classification (clade, etc.)
602 * LO <look> Look (Color, etc.)
604 if (s.search(annContent))
606 String acc = s.stringMatched(1);
607 String type = s.stringMatched(2);
608 String content = s.stringMatched(3);
609 // TODO: store DR in a vector.
610 // TODO: store AC according to generic file db annotation.
612 if (seqAnn.containsKey(acc))
614 ann = (Hashtable) seqAnn.get(acc);
618 ann = new Hashtable();
620 ann.put(type, content);
621 seqAnn.put(acc, ann);
625 // throw new IOException("Error parsing " + line);
626 System.err.println(">> missing annotation: " + line);
629 else if (annType.equals("GC"))
631 // Generic per-Column annotation, exactly 1 char per column
632 // always need a label.
633 if (x.search(annContent))
635 // parse out and create alignment annotation directly.
636 parseAnnotationRow(annotations, x.stringMatched(1),
640 else if (annType.equals("GR"))
642 // Generic per-Sequence AND per-Column markup, exactly 1 char per
645 * Feature Description Markup letters ------- -----------
646 * -------------- SS Secondary Structure [HGIEBTSCX] SA Surface
647 * Accessibility [0-9X] (0=0%-10%; ...; 9=90%-100%) TM TransMembrane
648 * [Mio] PP Posterior Probability [0-9*] (0=0.00-0.05; 1=0.05-0.15;
649 * *=0.95-1.00) LI LIgand binding [*] AS Active Site [*] IN INtron (in
652 if (s.search(annContent))
654 String acc = s.stringMatched(1);
655 String type = s.stringMatched(2);
656 String oseq = s.stringMatched(3);
658 * copy of annotation field that may be processed into whitespace chunks
660 String seq = new String(oseq);
663 // Get an object with all the annotations for this sequence
664 if (seqAnn.containsKey(acc))
666 // logger.debug("Found annotations for " + acc);
667 ann = (Hashtable) seqAnn.get(acc);
671 // logger.debug("Creating new annotations holder for " + acc);
672 ann = new Hashtable();
673 seqAnn.put(acc, ann);
676 // // start of block for appending annotation lines for wrapped
678 // TODO test structure, call parseAnnotationRow with vector from
679 // hashtable for specific sequence
682 // Get an object with all the content for an annotation
683 if (ann.containsKey("features"))
685 // logger.debug("Found features for " + acc);
686 features = (Hashtable) ann.get("features");
690 // logger.debug("Creating new features holder for " + acc);
691 features = new Hashtable();
692 ann.put("features", features);
696 if (features.containsKey(StockholmFile.typeToDescription(type)))
698 // logger.debug("Found content for " + this.id2type(type));
699 content = (Hashtable) features
700 .get(StockholmFile.typeToDescription(type));
704 // logger.debug("Creating new content holder for " +
705 // this.id2type(type));
706 content = new Hashtable();
707 features.put(StockholmFile.typeToDescription(type), content);
709 String ns = (String) content.get(ANNOTATION);
715 // finally, append the annotation line
717 content.put(ANNOTATION, ns);
718 // // end of wrapped annotation block.
719 // // Now a new row is created with the current set of data
722 if (seqAnn.containsKey(acc))
724 strucAnn = (Hashtable) seqAnn.get(acc);
728 strucAnn = new Hashtable();
731 Vector<AlignmentAnnotation> newStruc = new Vector<>();
732 parseAnnotationRow(newStruc, type, ns);
733 for (AlignmentAnnotation alan : newStruc)
735 alan.visible = false;
737 // new annotation overwrites any existing annotation...
739 strucAnn.put(type, newStruc);
740 seqAnn.put(acc, strucAnn);
746 "Warning - couldn't parse sequence annotation row line:\n"
748 // throw new IOException("Error parsing " + line);
753 throw new IOException(MessageManager.formatMessage(
754 "exception.unknown_annotation_detected", new String[]
755 { annType, annContent }));
759 if (treeString.length() > 0)
761 if (treeName == null)
763 treeName = "Tree " + (1 + getTreeCount());
765 addNewickTree(treeName, treeString.toString());
770 * Demangle an accession string and guess the originating sequence database
771 * for a given sequence
774 * sequence to be annotated
776 * Accession string for sequence
778 * source database for alignment (PFAM or RFAM)
780 private void guessDatabaseFor(Sequence seqO, String dbr, String dbsource)
782 DBRefEntry dbrf = null;
783 List<DBRefEntry> dbrs = new ArrayList<>();
784 String seqdb = "Unknown", sdbac = "" + dbr;
785 int st = -1, en = -1, p;
786 if ((st = sdbac.indexOf("/")) > -1)
788 String num, range = sdbac.substring(st + 1);
789 sdbac = sdbac.substring(0, st);
790 if ((p = range.indexOf("-")) > -1)
793 if (p < range.length())
795 num = range.substring(p).trim();
798 en = Integer.parseInt(num);
799 } catch (NumberFormatException x)
801 // could warn here that index is invalid
810 num = range.substring(0, p).trim();
813 st = Integer.parseInt(num);
814 } catch (NumberFormatException x)
816 // could warn here that index is invalid
820 if (dbsource.equals("PFAM"))
823 if (sdbac.indexOf(".") > -1)
825 // strip of last subdomain
826 sdbac = sdbac.substring(0, sdbac.indexOf("."));
827 dbrf = jalview.util.DBRefUtils.parseToDbRef(seqO, seqdb, dbsource,
834 dbrf = jalview.util.DBRefUtils.parseToDbRef(seqO, dbsource, dbsource,
843 seqdb = "EMBL"; // total guess - could be ENA, or something else these
845 if (sdbac.indexOf(".") > -1)
847 // strip off last subdomain
848 sdbac = sdbac.substring(0, sdbac.indexOf("."));
849 dbrf = jalview.util.DBRefUtils.parseToDbRef(seqO, seqdb, dbsource,
857 dbrf = jalview.util.DBRefUtils.parseToDbRef(seqO, dbsource, dbsource,
864 if (st != -1 && en != -1)
866 for (DBRefEntry d : dbrs)
868 jalview.util.MapList mp = new jalview.util.MapList(
870 { seqO.getStart(), seqO.getEnd() }, new int[] { st, en }, 1,
872 jalview.datamodel.Mapping mping = new Mapping(mp);
878 protected static AlignmentAnnotation parseAnnotationRow(
879 Vector<AlignmentAnnotation> annotation, String label,
882 // String convert1 = OPEN_PAREN.replaceAll(annots);
883 // String convert2 = CLOSE_PAREN.replaceAll(convert1);
884 // annots = convert2;
887 if (label.contains("_cons"))
889 type = (label.indexOf("_cons") == label.length() - 5)
890 ? label.substring(0, label.length() - 5)
893 boolean ss = false, posterior = false;
894 type = typeToDescription(type);
895 if (type.equalsIgnoreCase("secondary structure"))
899 if (type.equalsIgnoreCase("posterior probability"))
903 // decide on secondary structure or not.
904 Annotation[] els = new Annotation[annots.length()];
905 for (int i = 0; i < annots.length(); i++)
907 String pos = annots.substring(i, i + 1);
908 if (UNDERSCORE == pos.charAt(0))
913 ann = new Annotation(pos, "", ' ', 0f); // 0f is 'valid' null - will not
917 // if (" .-_".indexOf(pos) == -1)
919 if (DETECT_BRACKETS.search(pos))
921 ann.secondaryStructure = Rna.getRNASecStrucState(pos).charAt(0);
922 ann.displayCharacter = "" + pos.charAt(0);
926 ann.secondaryStructure = ResidueProperties.getDssp3state(pos)
929 if (ann.secondaryStructure == pos.charAt(0))
931 ann.displayCharacter = ""; // null; // " ";
935 ann.displayCharacter = " " + ann.displayCharacter;
941 if (posterior && !ann.isWhitespace()
942 && !Comparison.isGap(pos.charAt(0)))
945 // symbol encodes values - 0..*==0..10
946 if (pos.charAt(0) == '*')
952 val = pos.charAt(0) - '0';
963 AlignmentAnnotation annot = null;
964 Enumeration<AlignmentAnnotation> e = annotation.elements();
965 while (e.hasMoreElements())
967 annot = e.nextElement();
968 if (annot.label.equals(type))
976 annot = new AlignmentAnnotation(type, type, els);
977 annotation.addElement(annot);
981 Annotation[] anns = new Annotation[annot.annotations.length
983 System.arraycopy(annot.annotations, 0, anns, 0,
984 annot.annotations.length);
985 System.arraycopy(els, 0, anns, annot.annotations.length, els.length);
986 annot.annotations = anns;
987 // System.out.println("else: ");
993 public String print(final SequenceI[] sequences, boolean jvSuffix)
995 StringBuilder out = new StringBuilder();
996 out.append("# STOCKHOLM 1.0");
1000 for (SequenceI seq : sequences)
1004 String formattedId = printId(seq, jvSuffix);
1005 maxIdWidth = Math.max(maxIdWidth, formattedId.length());
1011 * generic alignment properties
1013 Hashtable props = al.getProperties();
1016 for (Object key : props.keySet())
1018 out.append(String.format("#=GF %s %s", key.toString(),
1019 props.get(key).toString()));
1020 out.append(newline);
1025 * output database accessions as #=GS (per sequence annotation)
1026 * PFAM or RFAM are output as AC <accession number>
1027 * others are output as DR <dbname> ; <accession>
1029 Format formatter = new Format("%-" + (maxIdWidth - 2) + "s");
1030 for (SequenceI seq : sequences)
1034 DBRefEntry[] dbRefs = seq.getDBRefs();
1037 String idField = formatter
1038 .form("#=GS " + printId(seq, jvSuffix) + " ");
1039 for (DBRefEntry dbRef : dbRefs)
1041 out.append(idField);
1042 printDbRef(out, dbRef);
1049 * output annotations
1051 for (SequenceI seq : sequences)
1055 AlignmentAnnotation[] alAnot = seq.getAnnotation();
1058 for (int j = 0; j < alAnot.length; j++)
1060 AlignmentAnnotation ann = alAnot[j];
1061 String key = descriptionToType(ann.label);
1062 boolean isrna = ann.isValidStruc();
1066 * output as secondary structure if there is
1067 * RNA secondary structure on the annotation
1076 out.append(new Format("%-" + maxIdWidth + "s").form(
1077 "#=GR " + printId(seq, jvSuffix) + " " + key + " "));
1078 Annotation[] anns = ann.annotations;
1079 StringBuilder seqString = new StringBuilder();
1080 for (int k = 0; k < anns.length; k++)
1083 .append(getAnnotationCharacter(key, k, anns[k], seq));
1085 out.append(seqString.toString());
1086 out.append(newline);
1090 out.append(new Format("%-" + maxIdWidth + "s")
1091 .form(printId(seq, jvSuffix) + " "));
1092 out.append(seq.getSequenceAsString());
1093 out.append(newline);
1098 * output alignment annotation (but not auto-calculated or sequence-related)
1100 if (al.getAlignmentAnnotation() != null)
1102 for (int ia = 0; ia < al.getAlignmentAnnotation().length; ia++)
1104 AlignmentAnnotation aa = al.getAlignmentAnnotation()[ia];
1105 if (aa.autoCalculated || !aa.visible || aa.sequenceRef != null)
1109 String label = aa.label;
1111 if (aa.label.equals("seq"))
1117 key = descriptionToType(aa.label);
1118 if ("RF".equals(key))
1122 else if (key != null)
1124 label = key + "_cons";
1127 label = label.replace(" ", "_");
1130 new Format("%-" + maxIdWidth + "s")
1131 .form("#=GC " + label + " "));
1132 StringBuilder sb = new StringBuilder(aa.annotations.length);
1133 for (int j = 0; j < aa.annotations.length; j++)
1136 getAnnotationCharacter(key, j, aa.annotations[j], null));
1138 out.append(sb.toString());
1139 out.append(newline);
1144 out.append(newline);
1146 return out.toString();
1150 * A helper method that appends a formatted dbref to the output buffer
1155 protected void printDbRef(StringBuilder out, DBRefEntry dbRef)
1157 String db = dbRef.getSource();
1158 String acc = dbRef.getAccessionId();
1159 if (DBRefSource.PFAM.equalsIgnoreCase(db)
1160 || DBRefSource.RFAM.equalsIgnoreCase(db))
1162 out.append(" AC " + acc);
1166 out.append(" DR " + db + " ; " + acc);
1168 out.append(newline);
1172 * Returns an annotation character to add to the output row
1180 static char getAnnotationCharacter(String key, int k, Annotation annot,
1181 SequenceI sequenceI)
1184 String ch = (annot == null)
1185 ? ((sequenceI == null) ? "-"
1186 : Character.toString(sequenceI.getCharAt(k)))
1187 : annot.displayCharacter;
1188 if (key != null && key.equals("SS"))
1192 // Stockholm format requires underscore, not space
1197 // valid secondary structure AND no alternative label (e.g. ' B')
1198 if (annot.secondaryStructure > ' ' && ch.length() < 2)
1200 return annot.secondaryStructure;
1205 if (ch.length() == 0)
1209 else if (ch.length() == 1)
1213 else if (ch.length() > 1)
1221 * make a friendly ID string.
1224 * @return truncated dataName to after last '/'
1226 private String safeName(String dataName)
1229 while ((b = dataName.indexOf("/")) > -1 && b < dataName.length())
1231 dataName = dataName.substring(b + 1).trim();
1234 int e = (dataName.length() - dataName.indexOf(".")) + 1;
1235 dataName = dataName.substring(1, e).trim();