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.Mapping;
32 import jalview.datamodel.Sequence;
33 import jalview.datamodel.SequenceFeature;
34 import jalview.datamodel.SequenceI;
35 import jalview.schemes.ResidueProperties;
36 import jalview.util.Comparison;
37 import jalview.util.Format;
38 import jalview.util.MessageManager;
39 import jalview.util.Platform;
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.Hashtable;
47 import java.util.LinkedHashMap;
48 import java.util.List;
50 import java.util.Vector;
52 import com.stevesoft.pat.Regex;
54 import fr.orsay.lri.varna.exceptions.ExceptionUnmatchedClosingParentheses;
55 import fr.orsay.lri.varna.factories.RNAFactory;
56 import fr.orsay.lri.varna.models.rna.RNA;
58 // import org.apache.log4j.*;
61 * This class is supposed to parse a Stockholm format file into Jalview There
62 * are TODOs in this class: we do not know what the database source and version
63 * is for the file when parsing the #GS= AC tag which associates accessions with
64 * sequences. Database references are also not parsed correctly: a separate
65 * reference string parser must be added to parse the database reference form
66 * into Jalview's local representation.
68 * @author bsb at sanger.ac.uk
69 * @author Natasha Shersnev (Dundee, UK) (Stockholm file writer)
70 * @author Lauren Lui (UCSC, USA) (RNA secondary structure annotation import as
72 * @author Anne Menard (Paris, FR) (VARNA parsing of Stockholm file data)
73 * @version 0.3 + jalview mods
76 public class StockholmFile extends AlignFile
78 private static final String ANNOTATION = "annotation";
80 // WUSS extended symbols. Avoid ambiguity with protein SS annotations by using
83 public static final String RNASS_BRACKETS = "<>[](){}AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz";
85 public static final int REGEX_STOCKHOLM = 0;
87 public static final int REGEX_BRACKETS = 1;
89 // use the following regex to decide an annotations (whole) line is NOT an RNA
90 // SS (it contains only E,H,e,h and other non-brace/non-alpha chars)
91 public static final int REGEX_NOT_RNASS = 2;
93 private static final int REGEX_ANNOTATION = 3;
95 private static final int REGEX_PFAM = 4;
97 private static final int REGEX_RFAM = 5;
99 private static final int REGEX_ALIGN_END = 6;
101 private static final int REGEX_SPLIT_ID = 7;
103 private static final int REGEX_SUBTYPE = 8;
105 private static final int REGEX_ANNOTATION_LINE = 9;
107 private static final int REGEX_REMOVE_ID = 10;
109 private static final int REGEX_OPEN_PAREN = 11;
111 private static final int REGEX_CLOSE_PAREN = 12;
113 public static final int REGEX_MAX = 13;
115 private static Regex REGEX[] = new Regex[REGEX_MAX];
118 * Centralize all actual Regex instantialization in Platform.
123 private static Regex getRegex(int id)
125 if (REGEX[id] == null)
127 String pat = null, pat2 = null;
130 case REGEX_STOCKHOLM:
131 pat = "# STOCKHOLM ([\\d\\.]+)";
134 // for reference; not used
135 pat = "(<|>|\\[|\\]|\\(|\\)|\\{|\\})";
137 case REGEX_NOT_RNASS:
138 pat = "^[^<>[\\](){}A-DF-Za-df-z]*$";
140 case REGEX_ANNOTATION:
141 pat = "(\\w+)\\s*(.*)";
144 pat = "PF[0-9]{5}(.*)";
147 pat = "RF[0-9]{5}(.*)";
149 case REGEX_ALIGN_END:
153 pat = "(\\S+)\\/(\\d+)\\-(\\d+)";
156 pat = "(\\S+)\\s+(\\S*)\\s+(.*)";
158 case REGEX_ANNOTATION_LINE:
159 pat = "#=(G[FSRC]?)\\s+(.*)";
161 case REGEX_REMOVE_ID:
162 pat = "(\\S+)\\s+(\\S+)";
164 case REGEX_OPEN_PAREN:
168 case REGEX_CLOSE_PAREN:
175 REGEX[id] = Platform.newRegex(pat, pat2);
180 StringBuffer out; // output buffer
184 public StockholmFile()
189 * Creates a new StockholmFile object for output.
191 public StockholmFile(AlignmentI al)
196 public StockholmFile(String inFile, DataSourceType type)
202 public StockholmFile(FileParse source) throws IOException
208 public void initData()
214 * Parse a file in Stockholm format into Jalview's data model using VARNA
216 * @throws IOException
217 * If there is an error with the input file
219 public void parse_with_VARNA(java.io.File inFile) throws IOException
221 FileReader fr = null;
222 fr = new FileReader(inFile);
224 BufferedReader r = new BufferedReader(fr);
225 List<RNA> result = null;
228 result = RNAFactory.loadSecStrStockholm(r);
229 } catch (ExceptionUnmatchedClosingParentheses umcp)
231 errormessage = "Unmatched parentheses in annotation. Aborting ("
232 + umcp.getMessage() + ")";
233 throw new IOException(umcp);
235 // DEBUG System.out.println("this is the secondary scructure:"
237 SequenceI[] seqs = new SequenceI[result.size()];
239 for (int i = 0; i < result.size(); i++)
241 // DEBUG System.err.println("Processing i'th sequence in Stockholm file")
242 RNA current = result.get(i);
244 String seq = current.getSeq();
245 String rna = current.getStructDBN(true);
246 // DEBUG System.out.println(seq);
247 // DEBUG System.err.println(rna);
249 int end = seq.length() - 1;
250 id = safeName(getDataName());
251 seqs[i] = new Sequence(id, seq, begin, end);
252 String[] annot = new String[rna.length()];
253 Annotation[] ann = new Annotation[rna.length()];
254 for (int j = 0; j < rna.length(); j++)
256 annot[j] = rna.substring(j, j + 1);
260 for (int k = 0; k < rna.length(); k++)
262 ann[k] = new Annotation(annot[k], "",
263 Rna.getRNASecStrucState(annot[k]).charAt(0), 0f);
266 AlignmentAnnotation align = new AlignmentAnnotation("Sec. str.",
267 current.getID(), ann);
269 seqs[i].addAlignmentAnnotation(align);
270 seqs[i].setRNA(result.get(i));
271 this.annotations.addElement(align);
278 * Parse a file in Stockholm format into Jalview's data model. The file has to
279 * be passed at construction time
281 * @throws IOException
282 * If there is an error with the input file
285 public void parse() throws IOException
287 StringBuffer treeString = new StringBuffer();
288 String treeName = null;
289 // --------------- Variable Definitions -------------------
293 Hashtable seqAnn = new Hashtable(); // Sequence related annotations
294 LinkedHashMap<String, String> seqs = new LinkedHashMap<>();
295 Regex p, r, rend, s, x;
296 // Temporary line for processing RNA annotation
297 // String RNAannot = "";
299 // ------------------ Parsing File ----------------------
300 // First, we have to check that this file has STOCKHOLM format, i.e. the
301 // first line must match
303 r = getRegex(REGEX_STOCKHOLM);
304 if (!r.search(nextLine()))
306 throw new IOException(MessageManager
307 .getString("exception.stockholm_invalid_format"));
311 version = r.stringMatched(1);
313 // logger.debug("Stockholm version: " + version);
316 // We define some Regexes here that will be used regularily later
317 rend = getRegex(REGEX_ALIGN_END);//"^\\s*\\/\\/"); // Find the end of an alignment
318 p = getRegex(REGEX_SPLIT_ID);//"(\\S+)\\/(\\d+)\\-(\\d+)"); // split sequence id in
320 s = getRegex(REGEX_SUBTYPE);// "(\\S+)\\s+(\\S*)\\s+(.*)"); // Parses
321 // annotation subtype
322 r = getRegex(REGEX_ANNOTATION_LINE);// "#=(G[FSRC]?)\\s+(.*)"); // Finds any
324 x = getRegex(REGEX_REMOVE_ID);// "(\\S+)\\s+(\\S+)"); // split id from
327 // Convert all bracket types to parentheses (necessary for passing to VARNA)
328 Regex openparen = getRegex(REGEX_OPEN_PAREN);//"(<|\\[)", "(");
329 Regex closeparen = getRegex(REGEX_CLOSE_PAREN);//"(>|\\])", ")");
331 // // Detect if file is RNA by looking for bracket types
332 // Regex detectbrackets = getRegex("(<|>|\\[|\\]|\\(|\\))");
339 openparen.optimize();
340 closeparen.optimize();
342 while ((line = nextLine()) != null)
344 if (line.length() == 0)
348 if (rend.search(line))
350 // End of the alignment, pass stuff back
351 this.noSeqs = seqs.size();
353 String dbsource = null;
354 Regex pf = getRegex(REGEX_PFAM); // Finds AC for Pfam
355 Regex rf = getRegex(REGEX_RFAM); // Finds AC for Rfam
356 if (getAlignmentProperty("AC") != null)
358 String dbType = getAlignmentProperty("AC").toString();
359 if (pf.search(dbType))
361 // PFAM Alignment - so references are typically from Uniprot
364 else if (rf.search(dbType))
369 // logger.debug("Number of sequences: " + this.noSeqs);
370 for (Map.Entry<String, String> skey : seqs.entrySet())
372 // logger.debug("Processing sequence " + acc);
373 String acc = skey.getKey();
374 String seq = skey.getValue();
375 if (maxLength < seq.length())
377 maxLength = seq.length();
383 * Retrieve hash of annotations for this accession Associate
384 * Annotation with accession
386 Hashtable accAnnotations = null;
388 if (seqAnn != null && seqAnn.containsKey(acc))
390 accAnnotations = (Hashtable) seqAnn.remove(acc);
391 // TODO: add structures to sequence
394 // Split accession in id and from/to
397 sid = p.stringMatched(1);
398 start = Integer.parseInt(p.stringMatched(2));
399 end = Integer.parseInt(p.stringMatched(3));
401 // logger.debug(sid + ", " + start + ", " + end);
403 Sequence seqO = new Sequence(sid, seq, start, end);
404 // Add Description (if any)
405 if (accAnnotations != null && accAnnotations.containsKey("DE"))
407 String desc = (String) accAnnotations.get("DE");
408 seqO.setDescription((desc == null) ? "" : desc);
410 // Add DB References (if any)
411 if (accAnnotations != null && accAnnotations.containsKey("DR"))
413 String dbr = (String) accAnnotations.get("DR");
414 if (dbr != null && dbr.indexOf(";") > -1)
416 String src = dbr.substring(0, dbr.indexOf(";"));
417 String acn = dbr.substring(dbr.indexOf(";") + 1);
418 jalview.util.DBRefUtils.parseToDbRef(seqO, src, "0", acn);
422 if (accAnnotations != null && accAnnotations.containsKey("AC"))
424 if (dbsource != null)
426 String dbr = (String) accAnnotations.get("AC");
429 // we could get very clever here - but for now - just try to
430 // guess accession type from source of alignment plus structure
432 guessDatabaseFor(seqO, dbr, dbsource);
436 // else - do what ? add the data anyway and prompt the user to
437 // specify what references these are ?
440 Hashtable features = null;
441 // We need to adjust the positions of all features to account for gaps
444 features = (Hashtable) accAnnotations.remove("features");
445 } catch (java.lang.NullPointerException e)
447 // loggerwarn("Getting Features for " + acc + ": " +
451 // if we have features
452 if (features != null)
454 int posmap[] = seqO.findPositionMap();
455 Enumeration i = features.keys();
456 while (i.hasMoreElements())
458 // TODO: parse out secondary structure annotation as annotation
460 // TODO: parse out scores as annotation row
461 // TODO: map coding region to core jalview feature types
462 String type = i.nextElement().toString();
463 Hashtable content = (Hashtable) features.remove(type);
465 // add alignment annotation for this feature
466 String key = type2id(type);
469 * have we added annotation rows for this type ?
471 boolean annotsAdded = false;
474 if (accAnnotations != null
475 && accAnnotations.containsKey(key))
477 Vector vv = (Vector) accAnnotations.get(key);
478 for (int ii = 0; ii < vv.size(); ii++)
481 AlignmentAnnotation an = (AlignmentAnnotation) vv
483 seqO.addAlignmentAnnotation(an);
489 Enumeration j = content.keys();
490 while (j.hasMoreElements())
492 String desc = j.nextElement().toString();
493 if (ANNOTATION.equals(desc) && annotsAdded)
495 // don't add features if we already added an annotation row
498 String ns = content.get(desc).toString();
499 char[] byChar = ns.toCharArray();
500 for (int k = 0; k < byChar.length; k++)
503 if (!(c == ' ' || c == '_' || c == '-' || c == '.')) // PFAM
510 int new_pos = posmap[k]; // look up nearest seqeunce
511 // position to this column
512 SequenceFeature feat = new SequenceFeature(type, desc,
513 new_pos, new_pos, null);
515 seqO.addSequenceFeature(feat);
525 // logger.debug("Adding seq " + acc + " from " + start + " to " + end
527 this.seqs.addElement(seqO);
529 return; // finished parsing this segment of source
531 else if (!r.search(line))
533 // System.err.println("Found sequence line: " + line);
535 // Split sequence in sequence and accession parts
538 // logger.error("Could not parse sequence line: " + line);
539 throw new IOException(MessageManager.formatMessage(
540 "exception.couldnt_parse_sequence_line", new String[]
543 String ns = seqs.get(x.stringMatched(1));
548 ns += x.stringMatched(2);
550 seqs.put(x.stringMatched(1), ns);
554 String annType = r.stringMatched(1);
555 String annContent = r.stringMatched(2);
557 // System.err.println("type:" + annType + " content: " + annContent);
559 if (annType.equals("GF"))
562 * Generic per-File annotation, free text Magic features: #=GF NH
563 * <tree in New Hampshire eXtended format> #=GF TN <Unique identifier
564 * for the next tree> Pfam descriptions: 7. DESCRIPTION OF FIELDS
566 * Compulsory fields: ------------------
568 * AC Accession number: Accession number in form PFxxxxx.version or
569 * PBxxxxxx. ID Identification: One word name for family. DE
570 * Definition: Short description of family. AU Author: Authors of the
571 * entry. SE Source of seed: The source suggesting the seed members
572 * belong to one family. GA Gathering method: Search threshold to
573 * build the full alignment. TC Trusted Cutoff: Lowest sequence score
574 * and domain score of match in the full alignment. NC Noise Cutoff:
575 * Highest sequence score and domain score of match not in full
576 * alignment. TP Type: Type of family -- presently Family, Domain,
577 * Motif or Repeat. SQ Sequence: Number of sequences in alignment. AM
578 * Alignment Method The order ls and fs hits are aligned to the model
579 * to build the full align. // End of alignment.
581 * Optional fields: ----------------
583 * DC Database Comment: Comment about database reference. DR Database
584 * Reference: Reference to external database. RC Reference Comment:
585 * Comment about literature reference. RN Reference Number: Reference
586 * Number. RM Reference Medline: Eight digit medline UI number. RT
587 * Reference Title: Reference Title. RA Reference Author: Reference
588 * Author RL Reference Location: Journal location. PI Previous
589 * identifier: Record of all previous ID lines. KW Keywords: Keywords.
590 * CC Comment: Comments. NE Pfam accession: Indicates a nested domain.
591 * NL Location: Location of nested domains - sequence ID, start and
594 * Obsolete fields: ----------- AL Alignment method of seed: The
595 * method used to align the seed members.
597 // Let's save the annotations, maybe we'll be able to do something
598 // with them later...
599 Regex an = getRegex(REGEX_ANNOTATION);
600 if (an.search(annContent))
602 if (an.stringMatched(1).equals("NH"))
604 treeString.append(an.stringMatched(2));
606 else if (an.stringMatched(1).equals("TN"))
608 if (treeString.length() > 0)
610 if (treeName == null)
612 treeName = "Tree " + (getTreeCount() + 1);
614 addNewickTree(treeName, treeString.toString());
616 treeName = an.stringMatched(2);
617 treeString = new StringBuffer();
619 setAlignmentProperty(an.stringMatched(1), an.stringMatched(2));
622 else if (annType.equals("GS"))
624 // Generic per-Sequence annotation, free text
626 * Pfam uses these features: Feature Description ---------------------
627 * ----------- AC <accession> ACcession number DE <freetext>
628 * DEscription DR <db>; <accession>; Database Reference OS <organism>
629 * OrganiSm (species) OC <clade> Organism Classification (clade, etc.)
630 * LO <look> Look (Color, etc.)
632 if (s.search(annContent))
634 String acc = s.stringMatched(1);
635 String type = s.stringMatched(2);
636 String content = s.stringMatched(3);
637 // TODO: store DR in a vector.
638 // TODO: store AC according to generic file db annotation.
640 if (seqAnn.containsKey(acc))
642 ann = (Hashtable) seqAnn.get(acc);
646 ann = new Hashtable();
648 ann.put(type, content);
649 seqAnn.put(acc, ann);
653 // throw new IOException("Error parsing " + line);
654 System.err.println(">> missing annotation: " + line);
657 else if (annType.equals("GC"))
659 // Generic per-Column annotation, exactly 1 char per column
660 // always need a label.
661 if (x.search(annContent))
663 // parse out and create alignment annotation directly.
664 parseAnnotationRow(annotations, x.stringMatched(1),
668 else if (annType.equals("GR"))
670 // Generic per-Sequence AND per-Column markup, exactly 1 char per
673 * Feature Description Markup letters ------- -----------
674 * -------------- SS Secondary Structure [HGIEBTSCX] SA Surface
675 * Accessibility [0-9X] (0=0%-10%; ...; 9=90%-100%) TM TransMembrane
676 * [Mio] PP Posterior Probability [0-9*] (0=0.00-0.05; 1=0.05-0.15;
677 * *=0.95-1.00) LI LIgand binding [*] AS Active Site [*] IN INtron (in
680 if (s.search(annContent))
682 String acc = s.stringMatched(1);
683 String type = s.stringMatched(2);
684 String oseq = s.stringMatched(3);
686 * copy of annotation field that may be processed into whitespace chunks
688 String seq = new String(oseq);
691 // Get an object with all the annotations for this sequence
692 if (seqAnn.containsKey(acc))
694 // logger.debug("Found annotations for " + acc);
695 ann = (Hashtable) seqAnn.get(acc);
699 // logger.debug("Creating new annotations holder for " + acc);
700 ann = new Hashtable();
701 seqAnn.put(acc, ann);
704 // // start of block for appending annotation lines for wrapped
706 // TODO test structure, call parseAnnotationRow with vector from
707 // hashtable for specific sequence
710 // Get an object with all the content for an annotation
711 if (ann.containsKey("features"))
713 // logger.debug("Found features for " + acc);
714 features = (Hashtable) ann.get("features");
718 // logger.debug("Creating new features holder for " + acc);
719 features = new Hashtable();
720 ann.put("features", features);
724 if (features.containsKey(this.id2type(type)))
726 // logger.debug("Found content for " + this.id2type(type));
727 content = (Hashtable) features.get(this.id2type(type));
731 // logger.debug("Creating new content holder for " +
732 // this.id2type(type));
733 content = new Hashtable();
734 features.put(this.id2type(type), content);
736 String ns = (String) content.get(ANNOTATION);
742 // finally, append the annotation line
744 content.put(ANNOTATION, ns);
745 // // end of wrapped annotation block.
746 // // Now a new row is created with the current set of data
749 if (seqAnn.containsKey(acc))
751 strucAnn = (Hashtable) seqAnn.get(acc);
755 strucAnn = new Hashtable();
758 Vector<AlignmentAnnotation> newStruc = new Vector<>();
759 parseAnnotationRow(newStruc, type, ns);
760 for (AlignmentAnnotation alan : newStruc)
762 alan.visible = false;
764 // new annotation overwrites any existing annotation...
766 strucAnn.put(type, newStruc);
767 seqAnn.put(acc, strucAnn);
773 "Warning - couldn't parse sequence annotation row line:\n"
775 // throw new IOException("Error parsing " + line);
780 throw new IOException(MessageManager.formatMessage(
781 "exception.unknown_annotation_detected", new String[]
782 { annType, annContent }));
786 if (treeString.length() > 0)
788 if (treeName == null)
790 treeName = "Tree " + (1 + getTreeCount());
792 addNewickTree(treeName, treeString.toString());
797 * Demangle an accession string and guess the originating sequence database
798 * for a given sequence
801 * sequence to be annotated
803 * Accession string for sequence
805 * source database for alignment (PFAM or RFAM)
807 private void guessDatabaseFor(Sequence seqO, String dbr, String dbsource)
809 DBRefEntry dbrf = null;
810 List<DBRefEntry> dbrs = new ArrayList<>();
811 String seqdb = "Unknown", sdbac = "" + dbr;
812 int st = -1, en = -1, p;
813 if ((st = sdbac.indexOf("/")) > -1)
815 String num, range = sdbac.substring(st + 1);
816 sdbac = sdbac.substring(0, st);
817 if ((p = range.indexOf("-")) > -1)
820 if (p < range.length())
822 num = range.substring(p).trim();
825 en = Integer.parseInt(num);
826 } catch (NumberFormatException x)
828 // could warn here that index is invalid
837 num = range.substring(0, p).trim();
840 st = Integer.parseInt(num);
841 } catch (NumberFormatException x)
843 // could warn here that index is invalid
847 if (dbsource.equals("PFAM"))
850 if (sdbac.indexOf(".") > -1)
852 // strip of last subdomain
853 sdbac = sdbac.substring(0, sdbac.indexOf("."));
854 dbrf = jalview.util.DBRefUtils.parseToDbRef(seqO, seqdb, dbsource,
861 dbrf = jalview.util.DBRefUtils.parseToDbRef(seqO, dbsource, dbsource,
870 seqdb = "EMBL"; // total guess - could be ENA, or something else these
872 if (sdbac.indexOf(".") > -1)
874 // strip off last subdomain
875 sdbac = sdbac.substring(0, sdbac.indexOf("."));
876 dbrf = jalview.util.DBRefUtils.parseToDbRef(seqO, seqdb, dbsource,
884 dbrf = jalview.util.DBRefUtils.parseToDbRef(seqO, dbsource, dbsource,
891 if (st != -1 && en != -1)
893 for (DBRefEntry d : dbrs)
895 jalview.util.MapList mp = new jalview.util.MapList(
897 { seqO.getStart(), seqO.getEnd() }, new int[] { st, en }, 1,
899 jalview.datamodel.Mapping mping = new Mapping(mp);
905 protected static AlignmentAnnotation parseAnnotationRow(
906 Vector<AlignmentAnnotation> annotation, String label,
909 String convert1, convert2 = null;
911 // convert1 = OPEN_PAREN.replaceAll(annots);
912 // convert2 = CLOSE_PAREN.replaceAll(convert1);
913 // annots = convert2;
916 if (label.contains("_cons"))
918 type = (label.indexOf("_cons") == label.length() - 5)
919 ? label.substring(0, label.length() - 5)
922 boolean ss = false, posterior = false;
923 type = id2type(type);
925 boolean isrnass = false;
926 if (type.equalsIgnoreCase("secondary structure"))
929 isrnass = !getRegex(REGEX_NOT_RNASS).search(annots); // sorry about the double
931 // here (it's easier for dealing with
932 // other non-alpha-non-brace chars)
934 if (type.equalsIgnoreCase("posterior probability"))
938 // decide on secondary structure or not.
939 Annotation[] els = new Annotation[annots.length()];
940 for (int i = 0; i < annots.length(); i++)
942 String pos = annots.substring(i, i + 1);
944 ann = new Annotation(pos, "", ' ', 0f); // 0f is 'valid' null - will not
948 // if (" .-_".indexOf(pos) == -1)
950 if (isrnass && RNASS_BRACKETS.indexOf(pos) >= 0)
952 ann.secondaryStructure = Rna.getRNASecStrucState(pos).charAt(0);
953 ann.displayCharacter = "" + pos.charAt(0);
957 ann.secondaryStructure = ResidueProperties.getDssp3state(pos)
960 if (ann.secondaryStructure == pos.charAt(0))
962 ann.displayCharacter = ""; // null; // " ";
966 ann.displayCharacter = " " + ann.displayCharacter;
972 if (posterior && !ann.isWhitespace()
973 && !Comparison.isGap(pos.charAt(0)))
976 // symbol encodes values - 0..*==0..10
977 if (pos.charAt(0) == '*')
983 val = pos.charAt(0) - '0';
994 AlignmentAnnotation annot = null;
995 Enumeration<AlignmentAnnotation> e = annotation.elements();
996 while (e.hasMoreElements())
998 annot = e.nextElement();
999 if (annot.label.equals(type))
1007 annot = new AlignmentAnnotation(type, type, els);
1008 annotation.addElement(annot);
1012 Annotation[] anns = new Annotation[annot.annotations.length
1014 System.arraycopy(annot.annotations, 0, anns, 0,
1015 annot.annotations.length);
1016 System.arraycopy(els, 0, anns, annot.annotations.length, els.length);
1017 annot.annotations = anns;
1018 // System.out.println("else: ");
1024 public String print(SequenceI[] s, boolean jvSuffix)
1026 out = new StringBuffer();
1027 out.append("# STOCKHOLM 1.0");
1028 out.append(newline);
1030 // find max length of id
1034 int slen = s.length;
1036 Hashtable<String, String> dataRef = null;
1037 while ((in < slen) && ((seq = s[in]) != null))
1039 String tmp = printId(seq, jvSuffix);
1040 max = Math.max(max, seq.getLength());
1042 if (tmp.length() > maxid)
1044 maxid = tmp.length();
1046 List<DBRefEntry> seqrefs = seq.getDBRefs();
1048 if (seqrefs != null && (ndb = seqrefs.size()) > 0)
1050 if (dataRef == null)
1052 dataRef = new Hashtable<>();
1054 for (int idb = 0; idb < ndb; idb++)
1057 DBRefEntry ref = seqrefs.get(idb);
1058 String datAs1 = ref.getSource().toString()
1060 + ref.getAccessionId().toString();
1061 dataRef.put(tmp, datAs1);
1069 // output database type
1070 if (al.getProperties() != null)
1072 if (!al.getProperties().isEmpty())
1074 Enumeration key = al.getProperties().keys();
1075 Enumeration val = al.getProperties().elements();
1076 while (key.hasMoreElements())
1078 out.append("#=GF " + key.nextElement() + " " + val.nextElement());
1079 out.append(newline);
1084 // output database accessions
1085 if (dataRef != null)
1087 Enumeration<String> en = dataRef.keys();
1088 while (en.hasMoreElements())
1090 Object idd = en.nextElement();
1091 String type = dataRef.remove(idd);
1092 out.append(new Format("%-" + (maxid - 2) + "s")
1093 .form("#=GS " + idd.toString() + " "));
1094 if (type.contains("PFAM") || type.contains("RFAM"))
1097 out.append(" AC " + type.substring(type.indexOf(";") + 1));
1101 out.append(" DR " + type + " ");
1103 out.append(newline);
1107 // output annotations
1108 while (i < slen && (seq = s[i]) != null)
1110 AlignmentAnnotation[] alAnot = seq.getAnnotation();
1114 for (int j = 0, nj = alAnot.length; j < nj; j++)
1117 String key = type2id(alAnot[j].label);
1118 boolean isrna = alAnot[j].isValidStruc();
1122 // hardwire to secondary structure if there is RNA secondary
1123 // structure on the annotation
1132 // out.append("#=GR ");
1133 out.append(new Format("%-" + maxid + "s").form(
1134 "#=GR " + printId(seq, jvSuffix) + " " + key + " "));
1135 ann = alAnot[j].annotations;
1137 for (int k = 0, nk = ann.length; k < nk; k++)
1139 sseq += outputCharacter(key, k, isrna, ann, seq);
1142 out.append(newline);
1146 out.append(new Format("%-" + maxid + "s")
1147 .form(printId(seq, jvSuffix) + " "));
1148 out.append(seq.getSequenceAsString());
1149 out.append(newline);
1153 // alignment annotation
1154 AlignmentAnnotation aa;
1155 AlignmentAnnotation[] an = al.getAlignmentAnnotation();
1158 for (int ia = 0, na = an.length; ia < na; ia++)
1161 if (aa.autoCalculated || !aa.visible || aa.sequenceRef != null)
1168 if (aa.label.equals("seq"))
1174 key = type2id(aa.label.toLowerCase());
1181 label = key + "_cons";
1188 label = label.replace(" ", "_");
1191 new Format("%-" + maxid + "s").form("#=GC " + label + " "));
1192 boolean isrna = aa.isValidStruc();
1193 for (int j = 0, nj = aa.annotations.length; j < nj; j++)
1195 sseq += outputCharacter(key, j, isrna, aa.annotations, null);
1198 out.append(newline);
1203 out.append(newline);
1205 return out.toString();
1209 * add an annotation character to the output row
1218 private char outputCharacter(String key, int k, boolean isrna,
1219 Annotation[] ann, SequenceI sequenceI)
1222 Annotation annot = ann[k];
1223 String ch = (annot == null)
1224 ? ((sequenceI == null) ? "-"
1225 : Character.toString(sequenceI.getCharAt(k)))
1226 : (annot.displayCharacter == null
1227 ? String.valueOf(annot.secondaryStructure)
1228 : annot.displayCharacter);
1233 if (key != null && key.equals("SS"))
1235 char ssannotchar = ' ';
1236 boolean charset = false;
1239 // sensible gap character
1245 // valid secondary structure AND no alternative label (e.g. ' B')
1246 if (annot.secondaryStructure > ' ' && ch.length() < 2)
1248 ssannotchar = annot.secondaryStructure;
1254 return (ssannotchar == ' ' && isrna) ? '.' : ssannotchar;
1258 if (ch.length() == 0)
1262 else if (ch.length() == 1)
1266 else if (ch.length() > 1)
1271 return (seq == ' ' && key != null && key.equals("SS") && isrna) ? '.'
1275 public String print()
1277 out = new StringBuffer();
1278 out.append("# STOCKHOLM 1.0");
1279 out.append(newline);
1280 print(getSeqsAsArray(), false);
1283 out.append(newline);
1284 return out.toString();
1287 private static Hashtable typeIds = null;
1291 if (typeIds == null)
1293 typeIds = new Hashtable();
1294 typeIds.put("SS", "Secondary Structure");
1295 typeIds.put("SA", "Surface Accessibility");
1296 typeIds.put("TM", "transmembrane");
1297 typeIds.put("PP", "Posterior Probability");
1298 typeIds.put("LI", "ligand binding");
1299 typeIds.put("AS", "active site");
1300 typeIds.put("IN", "intron");
1301 typeIds.put("IR", "interacting residue");
1302 typeIds.put("AC", "accession");
1303 typeIds.put("OS", "organism");
1304 typeIds.put("CL", "class");
1305 typeIds.put("DE", "description");
1306 typeIds.put("DR", "reference");
1307 typeIds.put("LO", "look");
1308 typeIds.put("RF", "Reference Positions");
1313 protected static String id2type(String id)
1315 if (typeIds.containsKey(id))
1317 return (String) typeIds.get(id);
1320 "Warning : Unknown Stockholm annotation type code " + id);
1324 protected static String type2id(String type)
1327 Enumeration e = typeIds.keys();
1328 while (e.hasMoreElements())
1330 Object ll = e.nextElement();
1331 if (typeIds.get(ll).toString().equalsIgnoreCase(type))
1342 "Warning : Unknown Stockholm annotation type: " + type);
1347 * make a friendly ID string.
1350 * @return truncated dataName to after last '/'
1352 private String safeName(String dataName)
1355 while ((b = dataName.indexOf("/")) > -1 && b < dataName.length())
1357 dataName = dataName.substring(b + 1).trim();
1360 int e = (dataName.length() - dataName.indexOf(".")) + 1;
1361 dataName = dataName.substring(1, e).trim();