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("(<|\\[)", "(");
86 private static final Regex CLOSE_PAREN = new Regex("(>|\\])", ")");
88 // private static final Regex OPEN_PAREN = new Regex("(<|\\[)", "(");
89 // private static final Regex CLOSE_PAREN = new Regex("(>|\\])", ")");
91 public static final Regex DETECT_BRACKETS = new Regex(
92 "(<|>|\\[|\\]|\\(|\\)|\\{|\\})");
94 // WUSS extended symbols. Avoid ambiguity with protein SS annotations by using NOT_RNASS first.
95 public static final String RNASS_BRACKETS = "<>[](){}AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz";
97 // use the following regex to decide an annotations (whole) line is NOT an RNA
98 // SS (it contains only E,H,e,h and other non-brace/non-alpha chars)
99 private static final Regex NOT_RNASS = new Regex(
100 "^[^<>[\\](){}A-DF-Za-df-z]*$");
102 StringBuffer out; // output buffer
104 private AlignmentI al;
106 public StockholmFile()
111 * Creates a new StockholmFile object for output
113 public StockholmFile(AlignmentI al)
118 public StockholmFile(String inFile, DataSourceType type)
124 public StockholmFile(FileParse source) throws IOException
130 public void initData()
136 * Parse a file in Stockholm format into Jalview's data model using VARNA
138 * @throws IOException
139 * If there is an error with the input file
141 public void parse_with_VARNA(java.io.File inFile) throws IOException
143 FileReader fr = null;
144 fr = new FileReader(inFile);
146 BufferedReader r = new BufferedReader(fr);
147 List<RNA> result = null;
150 result = RNAFactory.loadSecStrStockholm(r);
151 } catch (ExceptionUnmatchedClosingParentheses umcp)
153 errormessage = "Unmatched parentheses in annotation. Aborting ("
154 + umcp.getMessage() + ")";
155 throw new IOException(umcp);
157 // DEBUG System.out.println("this is the secondary scructure:"
159 SequenceI[] seqs = new SequenceI[result.size()];
161 for (int i = 0; i < result.size(); i++)
163 // DEBUG System.err.println("Processing i'th sequence in Stockholm file")
164 RNA current = result.get(i);
166 String seq = current.getSeq();
167 String rna = current.getStructDBN(true);
168 // DEBUG System.out.println(seq);
169 // DEBUG System.err.println(rna);
171 int end = seq.length() - 1;
172 id = safeName(getDataName());
173 seqs[i] = new Sequence(id, seq, begin, end);
174 String[] annot = new String[rna.length()];
175 Annotation[] ann = new Annotation[rna.length()];
176 for (int j = 0; j < rna.length(); j++)
178 annot[j] = rna.substring(j, j + 1);
182 for (int k = 0; k < rna.length(); k++)
184 ann[k] = new Annotation(annot[k], "",
185 Rna.getRNASecStrucState(annot[k]).charAt(0), 0f);
188 AlignmentAnnotation align = new AlignmentAnnotation("Sec. str.",
189 current.getID(), ann);
191 seqs[i].addAlignmentAnnotation(align);
192 seqs[i].setRNA(result.get(i));
193 this.annotations.addElement(align);
200 * Parse a file in Stockholm format into Jalview's data model. The file has to
201 * be passed at construction time
203 * @throws IOException
204 * If there is an error with the input file
207 public void parse() throws IOException
209 StringBuffer treeString = new StringBuffer();
210 String treeName = null;
211 // --------------- Variable Definitions -------------------
215 Hashtable seqAnn = new Hashtable(); // Sequence related annotations
216 LinkedHashMap<String, String> seqs = new LinkedHashMap<>();
217 Regex p, r, rend, s, x;
218 // Temporary line for processing RNA annotation
219 // String RNAannot = "";
221 // ------------------ Parsing File ----------------------
222 // First, we have to check that this file has STOCKHOLM format, i.e. the
223 // first line must match
225 r = new Regex("# STOCKHOLM ([\\d\\.]+)");
226 if (!r.search(nextLine()))
228 throw new IOException(MessageManager
229 .getString("exception.stockholm_invalid_format"));
233 version = r.stringMatched(1);
235 // logger.debug("Stockholm version: " + version);
238 // We define some Regexes here that will be used regularly later
239 rend = new Regex("^\\s*\\/\\/"); // Find the end of an alignment
240 p = new Regex("(\\S+)\\/(\\d+)\\-(\\d+)"); // split sequence id in
242 s = new Regex("(\\S+)\\s+(\\S*)\\s+(.*)"); // Parses annotation subtype
243 r = new Regex("#=(G[FSRC]?)\\s+(.*)"); // Finds any annotation line
244 x = new Regex("(\\S+)\\s+(\\S+)"); // split id from sequence
246 // Convert all bracket types to parentheses (necessary for passing to VARNA)
247 Regex openparen = new Regex("(<|\\[)", "(");
248 Regex closeparen = new Regex("(>|\\])", ")");
250 // Detect if file is RNA by looking for bracket types
251 Regex detectbrackets = new Regex("(<|>|\\[|\\]|\\(|\\))");
258 openparen.optimize();
259 closeparen.optimize();
261 while ((line = nextLine()) != null)
263 if (line.length() == 0)
267 if (rend.search(line))
269 // End of the alignment, pass stuff back
270 this.noSeqs = seqs.size();
272 String seqdb, dbsource = null;
273 Regex pf = new Regex("PF[0-9]{5}(.*)"); // Finds AC for Pfam
274 Regex rf = new Regex("RF[0-9]{5}(.*)"); // Finds AC for Rfam
275 if (getAlignmentProperty("AC") != null)
277 String dbType = getAlignmentProperty("AC").toString();
278 if (pf.search(dbType))
280 // PFAM Alignment - so references are typically from Uniprot
283 else if (rf.search(dbType))
288 // logger.debug("Number of sequences: " + this.noSeqs);
289 for (Map.Entry<String, String> skey : seqs.entrySet())
291 // logger.debug("Processing sequence " + acc);
292 String acc = skey.getKey();
293 String seq = skey.getValue();
294 if (maxLength < seq.length())
296 maxLength = seq.length();
302 * Retrieve hash of annotations for this accession Associate
303 * Annotation with accession
305 Hashtable accAnnotations = null;
307 if (seqAnn != null && seqAnn.containsKey(acc))
309 accAnnotations = (Hashtable) seqAnn.remove(acc);
310 // TODO: add structures to sequence
313 // Split accession in id and from/to
316 sid = p.stringMatched(1);
317 start = Integer.parseInt(p.stringMatched(2));
318 end = Integer.parseInt(p.stringMatched(3));
320 // logger.debug(sid + ", " + start + ", " + end);
322 Sequence seqO = new Sequence(sid, seq, start, end);
323 // Add Description (if any)
324 if (accAnnotations != null && accAnnotations.containsKey("DE"))
326 String desc = (String) accAnnotations.get("DE");
327 seqO.setDescription((desc == null) ? "" : desc);
329 // Add DB References (if any)
330 if (accAnnotations != null && accAnnotations.containsKey("DR"))
332 String dbr = (String) accAnnotations.get("DR");
333 if (dbr != null && dbr.indexOf(";") > -1)
335 String src = dbr.substring(0, dbr.indexOf(";"));
336 String acn = dbr.substring(dbr.indexOf(";") + 1);
337 jalview.util.DBRefUtils.parseToDbRef(seqO, src, "0", acn);
341 if (accAnnotations != null && accAnnotations.containsKey("AC"))
343 if (dbsource != null)
345 String dbr = (String) accAnnotations.get("AC");
348 // we could get very clever here - but for now - just try to
349 // guess accession type from source of alignment plus structure
351 guessDatabaseFor(seqO, dbr, dbsource);
355 // else - do what ? add the data anyway and prompt the user to
356 // specify what references these are ?
359 Hashtable features = null;
360 // We need to adjust the positions of all features to account for gaps
363 features = (Hashtable) accAnnotations.remove("features");
364 } catch (java.lang.NullPointerException e)
366 // loggerwarn("Getting Features for " + acc + ": " +
370 // if we have features
371 if (features != null)
373 int posmap[] = seqO.findPositionMap();
374 Enumeration i = features.keys();
375 while (i.hasMoreElements())
377 // TODO: parse out secondary structure annotation as annotation
379 // TODO: parse out scores as annotation row
380 // TODO: map coding region to core jalview feature types
381 String type = i.nextElement().toString();
382 Hashtable content = (Hashtable) features.remove(type);
384 // add alignment annotation for this feature
385 String key = type2id(type);
388 * have we added annotation rows for this type ?
390 boolean annotsAdded = false;
393 if (accAnnotations != null
394 && accAnnotations.containsKey(key))
396 Vector vv = (Vector) accAnnotations.get(key);
397 for (int ii = 0; ii < vv.size(); ii++)
400 AlignmentAnnotation an = (AlignmentAnnotation) vv
402 seqO.addAlignmentAnnotation(an);
408 Enumeration j = content.keys();
409 while (j.hasMoreElements())
411 String desc = j.nextElement().toString();
412 if (ANNOTATION.equals(desc) && annotsAdded)
414 // don't add features if we already added an annotation row
417 String ns = content.get(desc).toString();
418 char[] byChar = ns.toCharArray();
419 for (int k = 0; k < byChar.length; k++)
422 if (!(c == ' ' || c == '_' || c == '-' || c == '.')) // PFAM
429 int new_pos = posmap[k]; // look up nearest seqeunce
430 // position to this column
431 SequenceFeature feat = new SequenceFeature(type, desc,
432 new_pos, new_pos, null);
434 seqO.addSequenceFeature(feat);
444 // logger.debug("Adding seq " + acc + " from " + start + " to " + end
446 this.seqs.addElement(seqO);
448 return; // finished parsing this segment of source
450 else if (!r.search(line))
452 // System.err.println("Found sequence line: " + line);
454 // Split sequence in sequence and accession parts
457 // logger.error("Could not parse sequence line: " + line);
458 throw new IOException(MessageManager.formatMessage(
459 "exception.couldnt_parse_sequence_line", new String[]
462 String ns = seqs.get(x.stringMatched(1));
467 ns += x.stringMatched(2);
469 seqs.put(x.stringMatched(1), ns);
473 String annType = r.stringMatched(1);
474 String annContent = r.stringMatched(2);
476 // System.err.println("type:" + annType + " content: " + annContent);
478 if (annType.equals("GF"))
481 * Generic per-File annotation, free text Magic features: #=GF NH
482 * <tree in New Hampshire eXtended format> #=GF TN <Unique identifier
483 * for the next tree> Pfam descriptions: 7. DESCRIPTION OF FIELDS
485 * Compulsory fields: ------------------
487 * AC Accession number: Accession number in form PFxxxxx.version or
488 * PBxxxxxx. ID Identification: One word name for family. DE
489 * Definition: Short description of family. AU Author: Authors of the
490 * entry. SE Source of seed: The source suggesting the seed members
491 * belong to one family. GA Gathering method: Search threshold to
492 * build the full alignment. TC Trusted Cutoff: Lowest sequence score
493 * and domain score of match in the full alignment. NC Noise Cutoff:
494 * Highest sequence score and domain score of match not in full
495 * alignment. TP Type: Type of family -- presently Family, Domain,
496 * Motif or Repeat. SQ Sequence: Number of sequences in alignment. AM
497 * Alignment Method The order ls and fs hits are aligned to the model
498 * to build the full align. // End of alignment.
500 * Optional fields: ----------------
502 * DC Database Comment: Comment about database reference. DR Database
503 * Reference: Reference to external database. RC Reference Comment:
504 * Comment about literature reference. RN Reference Number: Reference
505 * Number. RM Reference Medline: Eight digit medline UI number. RT
506 * Reference Title: Reference Title. RA Reference Author: Reference
507 * Author RL Reference Location: Journal location. PI Previous
508 * identifier: Record of all previous ID lines. KW Keywords: Keywords.
509 * CC Comment: Comments. NE Pfam accession: Indicates a nested domain.
510 * NL Location: Location of nested domains - sequence ID, start and
513 * Obsolete fields: ----------- AL Alignment method of seed: The
514 * method used to align the seed members.
516 // Let's save the annotations, maybe we'll be able to do something
517 // with them later...
518 Regex an = new Regex("(\\w+)\\s*(.*)");
519 if (an.search(annContent))
521 if (an.stringMatched(1).equals("NH"))
523 treeString.append(an.stringMatched(2));
525 else if (an.stringMatched(1).equals("TN"))
527 if (treeString.length() > 0)
529 if (treeName == null)
531 treeName = "Tree " + (getTreeCount() + 1);
533 addNewickTree(treeName, treeString.toString());
535 treeName = an.stringMatched(2);
536 treeString = new StringBuffer();
538 setAlignmentProperty(an.stringMatched(1), an.stringMatched(2));
541 else if (annType.equals("GS"))
543 // Generic per-Sequence annotation, free text
545 * Pfam uses these features: Feature Description ---------------------
546 * ----------- AC <accession> ACcession number DE <freetext>
547 * DEscription DR <db>; <accession>; Database Reference OS <organism>
548 * OrganiSm (species) OC <clade> Organism Classification (clade, etc.)
549 * LO <look> Look (Color, etc.)
551 if (s.search(annContent))
553 String acc = s.stringMatched(1);
554 String type = s.stringMatched(2);
555 String content = s.stringMatched(3);
556 // TODO: store DR in a vector.
557 // TODO: store AC according to generic file db annotation.
559 if (seqAnn.containsKey(acc))
561 ann = (Hashtable) seqAnn.get(acc);
565 ann = new Hashtable();
567 ann.put(type, content);
568 seqAnn.put(acc, ann);
572 // throw new IOException("Error parsing " + line);
573 System.err.println(">> missing annotation: " + line);
576 else if (annType.equals("GC"))
578 // Generic per-Column annotation, exactly 1 char per column
579 // always need a label.
580 if (x.search(annContent))
582 // parse out and create alignment annotation directly.
583 parseAnnotationRow(annotations, x.stringMatched(1),
587 else if (annType.equals("GR"))
589 // Generic per-Sequence AND per-Column markup, exactly 1 char per
592 * Feature Description Markup letters ------- -----------
593 * -------------- SS Secondary Structure [HGIEBTSCX] SA Surface
594 * Accessibility [0-9X] (0=0%-10%; ...; 9=90%-100%) TM TransMembrane
595 * [Mio] PP Posterior Probability [0-9*] (0=0.00-0.05; 1=0.05-0.15;
596 * *=0.95-1.00) LI LIgand binding [*] AS Active Site [*] IN INtron (in
599 if (s.search(annContent))
601 String acc = s.stringMatched(1);
602 String type = s.stringMatched(2);
603 String oseq = s.stringMatched(3);
605 * copy of annotation field that may be processed into whitespace chunks
607 String seq = new String(oseq);
610 // Get an object with all the annotations for this sequence
611 if (seqAnn.containsKey(acc))
613 // logger.debug("Found annotations for " + acc);
614 ann = (Hashtable) seqAnn.get(acc);
618 // logger.debug("Creating new annotations holder for " + acc);
619 ann = new Hashtable();
620 seqAnn.put(acc, ann);
623 // // start of block for appending annotation lines for wrapped
625 // TODO test structure, call parseAnnotationRow with vector from
626 // hashtable for specific sequence
629 // Get an object with all the content for an annotation
630 if (ann.containsKey("features"))
632 // logger.debug("Found features for " + acc);
633 features = (Hashtable) ann.get("features");
637 // logger.debug("Creating new features holder for " + acc);
638 features = new Hashtable();
639 ann.put("features", features);
643 if (features.containsKey(this.id2type(type)))
645 // logger.debug("Found content for " + this.id2type(type));
646 content = (Hashtable) features
647 .get(this.id2type(type));
651 // logger.debug("Creating new content holder for " +
652 // this.id2type(type));
653 content = new Hashtable();
654 features.put(id2type(type), content);
656 String ns = (String) content.get(ANNOTATION);
662 // finally, append the annotation line
664 content.put(ANNOTATION, ns);
665 // // end of wrapped annotation block.
666 // // Now a new row is created with the current set of data
669 if (seqAnn.containsKey(acc))
671 strucAnn = (Hashtable) seqAnn.get(acc);
675 strucAnn = new Hashtable();
678 Vector<AlignmentAnnotation> newStruc = new Vector<>();
679 parseAnnotationRow(newStruc, type, ns);
680 for (AlignmentAnnotation alan : newStruc)
682 alan.visible = false;
684 // new annotation overwrites any existing annotation...
686 strucAnn.put(type, newStruc);
687 seqAnn.put(acc, strucAnn);
693 "Warning - couldn't parse sequence annotation row line:\n"
695 // throw new IOException("Error parsing " + line);
700 throw new IOException(MessageManager.formatMessage(
701 "exception.unknown_annotation_detected", new String[]
702 { annType, annContent }));
706 if (treeString.length() > 0)
708 if (treeName == null)
710 treeName = "Tree " + (1 + getTreeCount());
712 addNewickTree(treeName, treeString.toString());
717 * Demangle an accession string and guess the originating sequence database
718 * for a given sequence
721 * sequence to be annotated
723 * Accession string for sequence
725 * source database for alignment (PFAM or RFAM)
727 private void guessDatabaseFor(Sequence seqO, String dbr, String dbsource)
729 DBRefEntry dbrf = null;
730 List<DBRefEntry> dbrs = new ArrayList<>();
731 String seqdb = "Unknown", sdbac = "" + dbr;
732 int st = -1, en = -1, p;
733 if ((st = sdbac.indexOf("/")) > -1)
735 String num, range = sdbac.substring(st + 1);
736 sdbac = sdbac.substring(0, st);
737 if ((p = range.indexOf("-")) > -1)
740 if (p < range.length())
742 num = range.substring(p).trim();
745 en = Integer.parseInt(num);
746 } catch (NumberFormatException x)
748 // could warn here that index is invalid
757 num = range.substring(0, p).trim();
760 st = Integer.parseInt(num);
761 } catch (NumberFormatException x)
763 // could warn here that index is invalid
767 if (dbsource.equals("PFAM"))
770 if (sdbac.indexOf(".") > -1)
772 // strip of last subdomain
773 sdbac = sdbac.substring(0, sdbac.indexOf("."));
774 dbrf = jalview.util.DBRefUtils.parseToDbRef(seqO, seqdb, dbsource,
781 dbrf = jalview.util.DBRefUtils.parseToDbRef(seqO, dbsource, dbsource,
790 seqdb = "EMBL"; // total guess - could be ENA, or something else these
792 if (sdbac.indexOf(".") > -1)
794 // strip off last subdomain
795 sdbac = sdbac.substring(0, sdbac.indexOf("."));
796 dbrf = jalview.util.DBRefUtils.parseToDbRef(seqO, seqdb, dbsource,
804 dbrf = jalview.util.DBRefUtils.parseToDbRef(seqO, dbsource, dbsource,
811 if (st != -1 && en != -1)
813 for (DBRefEntry d : dbrs)
815 jalview.util.MapList mp = new jalview.util.MapList(
817 { seqO.getStart(), seqO.getEnd() }, new int[] { st, en }, 1,
819 jalview.datamodel.Mapping mping = new Mapping(mp);
825 protected static AlignmentAnnotation parseAnnotationRow(
826 Vector<AlignmentAnnotation> annotation, String label,
829 String convert1, convert2 = null;
830 // String convert1 = OPEN_PAREN.replaceAll(annots);
831 // String convert2 = CLOSE_PAREN.replaceAll(convert1);
832 // annots = convert2;
835 if (label.contains("_cons"))
837 type = (label.indexOf("_cons") == label.length() - 5)
838 ? label.substring(0, label.length() - 5)
841 boolean ss = false, posterior = false;
842 type = id2type(type);
844 boolean isrnass = false;
846 if (type.equalsIgnoreCase("secondary structure"))
849 isrnass = !NOT_RNASS.search(annots); // sorry about the double negative
850 // here (it's easier for dealing with
851 // other non-alpha-non-brace chars)
853 if (type.equalsIgnoreCase("posterior probability"))
857 // decide on secondary structure or not.
858 Annotation[] els = new Annotation[annots.length()];
859 for (int i = 0; i < annots.length(); i++)
861 String pos = annots.substring(i, i + 1);
862 if (UNDERSCORE == pos.charAt(0))
867 ann = new Annotation(pos, "", ' ', 0f); // 0f is 'valid' null - will not
871 // if (" .-_".indexOf(pos) == -1)
873 if (isrnass && RNASS_BRACKETS.indexOf(pos) >= 0)
875 ann.secondaryStructure = Rna.getRNASecStrucState(pos).charAt(0);
876 ann.displayCharacter = "" + pos.charAt(0);
880 ann.secondaryStructure = ResidueProperties.getDssp3state(pos)
883 if (ann.secondaryStructure == pos.charAt(0))
885 ann.displayCharacter = ""; // null; // " ";
889 ann.displayCharacter = " " + ann.displayCharacter;
895 if (posterior && !ann.isWhitespace()
896 && !Comparison.isGap(pos.charAt(0)))
899 // symbol encodes values - 0..*==0..10
900 if (pos.charAt(0) == '*')
906 val = pos.charAt(0) - '0';
917 AlignmentAnnotation annot = null;
918 Enumeration<AlignmentAnnotation> e = annotation.elements();
919 while (e.hasMoreElements())
921 annot = e.nextElement();
922 if (annot.label.equals(type))
930 annot = new AlignmentAnnotation(type, type, els);
931 annotation.addElement(annot);
935 Annotation[] anns = new Annotation[annot.annotations.length
937 System.arraycopy(annot.annotations, 0, anns, 0,
938 annot.annotations.length);
939 System.arraycopy(els, 0, anns, annot.annotations.length, els.length);
940 annot.annotations = anns;
941 // System.out.println("else: ");
947 public String print(SequenceI[] s, boolean jvSuffix)
949 out = new StringBuffer();
950 out.append("# STOCKHOLM 1.0");
953 // find max length of id
957 Hashtable dataRef = null;
958 while ((in < s.length) && (s[in] != null))
960 String tmp = printId(s[in], jvSuffix);
961 max = Math.max(max, s[in].getLength());
963 if (tmp.length() > maxid)
965 maxid = tmp.length();
967 if (s[in].getDBRefs() != null)
969 for (int idb = 0; idb < s[in].getDBRefs().length; idb++)
973 dataRef = new Hashtable();
976 String datAs1 = s[in].getDBRefs()[idb].getSource().toString()
978 + s[in].getDBRefs()[idb].getAccessionId().toString();
979 dataRef.put(tmp, datAs1);
987 // output database type
988 if (al.getProperties() != null)
990 if (!al.getProperties().isEmpty())
992 Enumeration key = al.getProperties().keys();
993 Enumeration val = al.getProperties().elements();
994 while (key.hasMoreElements())
996 out.append("#=GF " + key.nextElement() + " " + val.nextElement());
1002 // output database accessions
1003 if (dataRef != null)
1005 Enumeration en = dataRef.keys();
1006 while (en.hasMoreElements())
1008 Object idd = en.nextElement();
1009 String type = (String) dataRef.remove(idd);
1010 out.append(new Format("%-" + (maxid - 2) + "s")
1011 .form("#=GS " + idd.toString() + " "));
1012 if (type.contains("PFAM") || type.contains("RFAM"))
1015 out.append(" AC " + type.substring(type.indexOf(";") + 1));
1019 out.append(" DR " + type + " ");
1021 out.append(newline);
1025 // output annotations
1026 while (i < s.length && s[i] != null)
1028 AlignmentAnnotation[] alAnot = s[i].getAnnotation();
1032 for (int j = 0; j < alAnot.length; j++)
1035 String key = type2id(alAnot[j].label);
1036 boolean isrna = alAnot[j].isValidStruc();
1040 // hardwire to secondary structure if there is RNA secondary
1041 // structure on the annotation
1050 // out.append("#=GR ");
1051 out.append(new Format("%-" + maxid + "s").form(
1052 "#=GR " + printId(s[i], jvSuffix) + " " + key + " "));
1053 ann = alAnot[j].annotations;
1055 for (int k = 0; k < ann.length; k++)
1057 seq += outputCharacter(key, k, isrna, ann, s[i]);
1060 out.append(newline);
1064 out.append(new Format("%-" + maxid + "s")
1065 .form(printId(s[i], jvSuffix) + " "));
1066 out.append(s[i].getSequenceAsString());
1067 out.append(newline);
1071 // alignment annotation
1072 AlignmentAnnotation aa;
1073 if (al.getAlignmentAnnotation() != null)
1075 for (int ia = 0; ia < al.getAlignmentAnnotation().length; ia++)
1077 aa = al.getAlignmentAnnotation()[ia];
1078 if (aa.autoCalculated || !aa.visible || aa.sequenceRef != null)
1085 if (aa.label.equals("seq"))
1091 key = type2id(aa.label.toLowerCase());
1098 label = key + "_cons";
1105 label = label.replace(" ", "_");
1108 new Format("%-" + maxid + "s").form("#=GC " + label + " "));
1109 boolean isrna = aa.isValidStruc();
1110 for (int j = 0; j < aa.annotations.length; j++)
1112 seq += outputCharacter(key, j, isrna, aa.annotations, null);
1115 out.append(newline);
1120 out.append(newline);
1122 return out.toString();
1127 * add an annotation character to the output row
1136 private char outputCharacter(String key, int k, boolean isrna,
1137 Annotation[] ann, SequenceI sequenceI)
1140 Annotation annot = ann[k];
1141 String ch = (annot == null)
1142 ? ((sequenceI == null) ? "-"
1143 : Character.toString(sequenceI.getCharAt(k)))
1144 : (annot.displayCharacter == null
1145 ? String.valueOf(annot.secondaryStructure)
1146 : annot.displayCharacter);
1151 if (key != null && key.equals("SS"))
1153 char ssannotchar = ' ';
1154 boolean charset = false;
1157 // sensible gap character
1163 // valid secondary structure AND no alternative label (e.g. ' B')
1164 if (annot.secondaryStructure > ' ' && ch.length() < 2)
1166 ssannotchar = annot.secondaryStructure;
1172 return (ssannotchar == ' ' && isrna) ? '.' : ssannotchar;
1176 if (ch.length() == 0)
1180 else if (ch.length() == 1)
1184 else if (ch.length() > 1)
1189 return (seq == ' ' && key != null && key.equals("SS") && isrna) ? '.'
1194 * make a friendly ID string.
1197 * @return truncated dataName to after last '/'
1199 private String safeName(String dataName)
1202 while ((b = dataName.indexOf("/")) > -1 && b < dataName.length())
1204 dataName = dataName.substring(b + 1).trim();
1207 int e = (dataName.length() - dataName.indexOf(".")) + 1;
1208 dataName = dataName.substring(1, e).trim();
1213 public String print()
1215 out = new StringBuffer();
1216 out.append("# STOCKHOLM 1.0");
1217 out.append(newline);
1218 print(getSeqsAsArray(), false);
1221 out.append(newline);
1222 return out.toString();
1225 private static Hashtable typeIds = null;
1229 if (typeIds == null)
1231 typeIds = new Hashtable();
1232 typeIds.put("SS", "Secondary Structure");
1233 typeIds.put("SA", "Surface Accessibility");
1234 typeIds.put("TM", "transmembrane");
1235 typeIds.put("PP", "Posterior Probability");
1236 typeIds.put("LI", "ligand binding");
1237 typeIds.put("AS", "active site");
1238 typeIds.put("IN", "intron");
1239 typeIds.put("IR", "interacting residue");
1240 typeIds.put("AC", "accession");
1241 typeIds.put("OS", "organism");
1242 typeIds.put("CL", "class");
1243 typeIds.put("DE", "description");
1244 typeIds.put("DR", "reference");
1245 typeIds.put("LO", "look");
1246 typeIds.put("RF", "Reference Positions");
1251 protected static String id2type(String id)
1253 if (typeIds.containsKey(id))
1255 return (String) typeIds.get(id);
1258 "Warning : Unknown Stockholm annotation type code " + id);
1262 protected static String type2id(String type)
1265 Enumeration e = typeIds.keys();
1266 while (e.hasMoreElements())
1268 Object ll = e.nextElement();
1269 if (typeIds.get(ll).toString().equalsIgnoreCase(type))
1280 "Warning : Unknown Stockholm annotation type: " + type);