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.DBRefUtils;
39 import jalview.util.Format;
40 import jalview.util.MessageManager;
41 import jalview.util.Platform;
43 import java.io.BufferedReader;
44 import java.io.FileReader;
45 import java.io.IOException;
46 import java.util.ArrayList;
47 import java.util.Enumeration;
48 import java.util.Hashtable;
49 import java.util.LinkedHashMap;
50 import java.util.List;
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 // WUSS extended symbols. Avoid ambiguity with protein SS annotations by using
85 public static final String RNASS_BRACKETS = "<>[](){}AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz";
87 public static final int REGEX_STOCKHOLM = 0;
89 public static final int REGEX_BRACKETS = 1;
91 // use the following regex to decide an annotations (whole) line is NOT an RNA
92 // SS (it contains only E,H,e,h and other non-brace/non-alpha chars)
93 public static final int REGEX_NOT_RNASS = 2;
95 private static final int REGEX_ANNOTATION = 3;
97 private static final int REGEX_PFAM = 4;
99 private static final int REGEX_RFAM = 5;
101 private static final int REGEX_ALIGN_END = 6;
103 private static final int REGEX_SPLIT_ID = 7;
105 private static final int REGEX_SUBTYPE = 8;
107 private static final int REGEX_ANNOTATION_LINE = 9;
109 private static final int REGEX_REMOVE_ID = 10;
111 private static final int REGEX_OPEN_PAREN = 11;
113 private static final int REGEX_CLOSE_PAREN = 12;
115 public static final int REGEX_MAX = 13;
117 private static Regex REGEX[] = new Regex[REGEX_MAX];
120 * Centralize all actual Regex instantialization in Platform.
125 private static Regex getRegex(int id)
127 if (REGEX[id] == null)
129 String pat = null, pat2 = null;
132 case REGEX_STOCKHOLM:
133 pat = "# STOCKHOLM ([\\d\\.]+)";
136 // for reference; not used
137 pat = "(<|>|\\[|\\]|\\(|\\)|\\{|\\})";
139 case REGEX_NOT_RNASS:
140 pat = "^[^<>[\\](){}A-DF-Za-df-z]*$";
142 case REGEX_ANNOTATION:
143 pat = "(\\w+)\\s*(.*)";
146 pat = "PF[0-9]{5}(.*)";
149 pat = "RF[0-9]{5}(.*)";
151 case REGEX_ALIGN_END:
155 pat = "(\\S+)\\/(\\d+)\\-(\\d+)";
158 pat = "(\\S+)\\s+(\\S*)\\s+(.*)";
160 case REGEX_ANNOTATION_LINE:
161 pat = "#=(G[FSRC]?)\\s+(.*)";
163 case REGEX_REMOVE_ID:
164 pat = "(\\S+)\\s+(\\S+)";
166 case REGEX_OPEN_PAREN:
170 case REGEX_CLOSE_PAREN:
177 REGEX[id] = Platform.newRegex(pat, pat2);
182 StringBuffer out; // output buffer
186 public StockholmFile()
191 * Creates a new StockholmFile object for output.
193 public StockholmFile(AlignmentI al)
198 public StockholmFile(String inFile, DataSourceType type)
204 public StockholmFile(FileParse source) throws IOException
210 public void initData()
216 * Parse a file in Stockholm format into Jalview's data model using VARNA
218 * @throws IOException
219 * If there is an error with the input file
221 public void parse_with_VARNA(java.io.File inFile) throws IOException
223 FileReader fr = null;
224 fr = new FileReader(inFile);
226 BufferedReader r = new BufferedReader(fr);
227 List<RNA> result = null;
230 result = RNAFactory.loadSecStrStockholm(r);
231 } catch (ExceptionUnmatchedClosingParentheses umcp)
233 errormessage = "Unmatched parentheses in annotation. Aborting ("
234 + umcp.getMessage() + ")";
235 throw new IOException(umcp);
237 // DEBUG System.out.println("this is the secondary scructure:"
239 SequenceI[] seqs = new SequenceI[result.size()];
241 for (int i = 0; i < result.size(); i++)
243 // DEBUG System.err.println("Processing i'th sequence in Stockholm file")
244 RNA current = result.get(i);
246 String seq = current.getSeq();
247 String rna = current.getStructDBN(true);
248 // DEBUG System.out.println(seq);
249 // DEBUG System.err.println(rna);
251 int end = seq.length() - 1;
252 id = safeName(getDataName());
253 seqs[i] = new Sequence(id, seq, begin, end);
254 String[] annot = new String[rna.length()];
255 Annotation[] ann = new Annotation[rna.length()];
256 for (int j = 0; j < rna.length(); j++)
258 annot[j] = rna.substring(j, j + 1);
262 for (int k = 0; k < rna.length(); k++)
264 ann[k] = new Annotation(annot[k], "",
265 Rna.getRNASecStrucState(annot[k]).charAt(0), 0f);
268 AlignmentAnnotation align = new AlignmentAnnotation("Sec. str.",
269 current.getID(), ann);
271 seqs[i].addAlignmentAnnotation(align);
272 seqs[i].setRNA(result.get(i));
273 this.annotations.addElement(align);
280 * Parse a file in Stockholm format into Jalview's data model. The file has to
281 * be passed at construction time
283 * @throws IOException
284 * If there is an error with the input file
287 public void parse() throws IOException
289 StringBuffer treeString = new StringBuffer();
290 String treeName = null;
291 // --------------- Variable Definitions -------------------
295 Hashtable seqAnn = new Hashtable(); // Sequence related annotations
296 LinkedHashMap<String, String> seqs = new LinkedHashMap<>();
297 Regex p, r, rend, s, x;
298 // Temporary line for processing RNA annotation
299 // String RNAannot = "";
301 // ------------------ Parsing File ----------------------
302 // First, we have to check that this file has STOCKHOLM format, i.e. the
303 // first line must match
305 r = getRegex(REGEX_STOCKHOLM);
306 if (!r.search(nextLine()))
308 throw new IOException(MessageManager
309 .getString("exception.stockholm_invalid_format"));
313 version = r.stringMatched(1);
315 // logger.debug("Stockholm version: " + version);
318 // We define some Regexes here that will be used regularily later
319 rend = getRegex(REGEX_ALIGN_END);//"^\\s*\\/\\/"); // Find the end of an alignment
320 p = getRegex(REGEX_SPLIT_ID);//"(\\S+)\\/(\\d+)\\-(\\d+)"); // split sequence id in
322 s = getRegex(REGEX_SUBTYPE);// "(\\S+)\\s+(\\S*)\\s+(.*)"); // Parses
323 // annotation subtype
324 r = getRegex(REGEX_ANNOTATION_LINE);// "#=(G[FSRC]?)\\s+(.*)"); // Finds any
326 x = getRegex(REGEX_REMOVE_ID);// "(\\S+)\\s+(\\S+)"); // split id from
329 // Convert all bracket types to parentheses (necessary for passing to VARNA)
330 Regex openparen = getRegex(REGEX_OPEN_PAREN);//"(<|\\[)", "(");
331 Regex closeparen = getRegex(REGEX_CLOSE_PAREN);//"(>|\\])", ")");
333 // // Detect if file is RNA by looking for bracket types
334 // Regex detectbrackets = getRegex("(<|>|\\[|\\]|\\(|\\))");
341 openparen.optimize();
342 closeparen.optimize();
344 while ((line = nextLine()) != null)
346 if (line.length() == 0)
350 if (rend.search(line))
352 // End of the alignment, pass stuff back
353 this.noSeqs = seqs.size();
355 String dbsource = null;
356 Regex pf = getRegex(REGEX_PFAM); // Finds AC for Pfam
357 Regex rf = getRegex(REGEX_RFAM); // Finds AC for Rfam
358 if (getAlignmentProperty("AC") != null)
360 String dbType = getAlignmentProperty("AC").toString();
361 if (pf.search(dbType))
363 // PFAM Alignment - so references are typically from Uniprot
366 else if (rf.search(dbType))
371 // logger.debug("Number of sequences: " + this.noSeqs);
372 for (Map.Entry<String, String> skey : seqs.entrySet())
374 // logger.debug("Processing sequence " + acc);
375 String acc = skey.getKey();
376 String seq = skey.getValue();
377 if (maxLength < seq.length())
379 maxLength = seq.length();
385 * Retrieve hash of annotations for this accession Associate
386 * Annotation with accession
388 Hashtable accAnnotations = null;
390 if (seqAnn != null && seqAnn.containsKey(acc))
392 accAnnotations = (Hashtable) seqAnn.remove(acc);
393 // TODO: add structures to sequence
396 // Split accession in id and from/to
399 sid = p.stringMatched(1);
400 start = Integer.parseInt(p.stringMatched(2));
401 end = Integer.parseInt(p.stringMatched(3));
403 // logger.debug(sid + ", " + start + ", " + end);
405 Sequence seqO = new Sequence(sid, seq, start, end);
406 // Add Description (if any)
407 if (accAnnotations != null && accAnnotations.containsKey("DE"))
409 String desc = (String) accAnnotations.get("DE");
410 seqO.setDescription((desc == null) ? "" : desc);
412 // Add DB References (if any)
413 if (accAnnotations != null && accAnnotations.containsKey("DR"))
415 String dbr = (String) accAnnotations.get("DR");
416 if (dbr != null && dbr.indexOf(";") > -1)
418 String src = dbr.substring(0, dbr.indexOf(";"));
419 String acn = dbr.substring(dbr.indexOf(";") + 1);
420 jalview.util.DBRefUtils.parseToDbRef(seqO, src, "0", acn);
424 if (accAnnotations != null && accAnnotations.containsKey("AC"))
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 type of sequence, source of alignment plus
433 guessDatabaseFor(seqO, dbr, dbsource);
435 // else - do what ? add the data anyway and prompt the user to
436 // specify what references these are ?
439 Hashtable features = null;
440 // We need to adjust the positions of all features to account for gaps
443 features = (Hashtable) accAnnotations.remove("features");
444 } catch (java.lang.NullPointerException e)
446 // loggerwarn("Getting Features for " + acc + ": " +
450 // if we have features
451 if (features != null)
453 int posmap[] = seqO.findPositionMap();
454 Enumeration i = features.keys();
455 while (i.hasMoreElements())
457 // TODO: parse out secondary structure annotation as annotation
459 // TODO: parse out scores as annotation row
460 // TODO: map coding region to core jalview feature types
461 String type = i.nextElement().toString();
462 Hashtable content = (Hashtable) features.remove(type);
464 // add alignment annotation for this feature
465 String key = type2id(type);
468 * have we added annotation rows for this type ?
470 boolean annotsAdded = false;
473 if (accAnnotations != null
474 && accAnnotations.containsKey(key))
476 Vector vv = (Vector) accAnnotations.get(key);
477 for (int ii = 0; ii < vv.size(); ii++)
480 AlignmentAnnotation an = (AlignmentAnnotation) vv
482 seqO.addAlignmentAnnotation(an);
488 Enumeration j = content.keys();
489 while (j.hasMoreElements())
491 String desc = j.nextElement().toString();
492 if (ANNOTATION.equals(desc) && annotsAdded)
494 // don't add features if we already added an annotation row
497 String ns = content.get(desc).toString();
498 char[] byChar = ns.toCharArray();
499 for (int k = 0; k < byChar.length; k++)
502 if (!(c == ' ' || c == '_' || c == '-' || c == '.')) // PFAM
509 int new_pos = posmap[k]; // look up nearest seqeunce
510 // position to this column
511 SequenceFeature feat = new SequenceFeature(type, desc,
512 new_pos, new_pos, null);
514 seqO.addSequenceFeature(feat);
524 // logger.debug("Adding seq " + acc + " from " + start + " to " + end
526 this.seqs.addElement(seqO);
528 return; // finished parsing this segment of source
530 else if (!r.search(line))
532 // System.err.println("Found sequence line: " + line);
534 // Split sequence in sequence and accession parts
537 // logger.error("Could not parse sequence line: " + line);
538 throw new IOException(MessageManager.formatMessage(
539 "exception.couldnt_parse_sequence_line", new String[]
542 String ns = seqs.get(x.stringMatched(1));
547 ns += x.stringMatched(2);
549 seqs.put(x.stringMatched(1), ns);
553 String annType = r.stringMatched(1);
554 String annContent = r.stringMatched(2);
556 // System.err.println("type:" + annType + " content: " + annContent);
558 if (annType.equals("GF"))
561 * Generic per-File annotation, free text Magic features: #=GF NH
562 * <tree in New Hampshire eXtended format> #=GF TN <Unique identifier
563 * for the next tree> Pfam descriptions: 7. DESCRIPTION OF FIELDS
565 * Compulsory fields: ------------------
567 * AC Accession number: Accession number in form PFxxxxx.version or
568 * PBxxxxxx. ID Identification: One word name for family. DE
569 * Definition: Short description of family. AU Author: Authors of the
570 * entry. SE Source of seed: The source suggesting the seed members
571 * belong to one family. GA Gathering method: Search threshold to
572 * build the full alignment. TC Trusted Cutoff: Lowest sequence score
573 * and domain score of match in the full alignment. NC Noise Cutoff:
574 * Highest sequence score and domain score of match not in full
575 * alignment. TP Type: Type of family -- presently Family, Domain,
576 * Motif or Repeat. SQ Sequence: Number of sequences in alignment. AM
577 * Alignment Method The order ls and fs hits are aligned to the model
578 * to build the full align. // End of alignment.
580 * Optional fields: ----------------
582 * DC Database Comment: Comment about database reference. DR Database
583 * Reference: Reference to external database. RC Reference Comment:
584 * Comment about literature reference. RN Reference Number: Reference
585 * Number. RM Reference Medline: Eight digit medline UI number. RT
586 * Reference Title: Reference Title. RA Reference Author: Reference
587 * Author RL Reference Location: Journal location. PI Previous
588 * identifier: Record of all previous ID lines. KW Keywords: Keywords.
589 * CC Comment: Comments. NE Pfam accession: Indicates a nested domain.
590 * NL Location: Location of nested domains - sequence ID, start and
593 * Obsolete fields: ----------- AL Alignment method of seed: The
594 * method used to align the seed members.
596 // Let's save the annotations, maybe we'll be able to do something
597 // with them later...
598 Regex an = getRegex(REGEX_ANNOTATION);
599 if (an.search(annContent))
601 if (an.stringMatched(1).equals("NH"))
603 treeString.append(an.stringMatched(2));
605 else if (an.stringMatched(1).equals("TN"))
607 if (treeString.length() > 0)
609 if (treeName == null)
611 treeName = "Tree " + (getTreeCount() + 1);
613 addNewickTree(treeName, treeString.toString());
615 treeName = an.stringMatched(2);
616 treeString = new StringBuffer();
618 // TODO: JAL-3532 - this is where GF comments and database references are lost
619 // suggest overriding this method for Stockholm files to catch and properly
620 // process CC, DR etc into multivalued properties
621 setAlignmentProperty(an.stringMatched(1), an.stringMatched(2));
624 else if (annType.equals("GS"))
626 // Generic per-Sequence annotation, free text
628 * Pfam uses these features: Feature Description ---------------------
629 * ----------- AC <accession> ACcession number DE <freetext>
630 * DEscription DR <db>; <accession>; Database Reference OS <organism>
631 * OrganiSm (species) OC <clade> Organism Classification (clade, etc.)
632 * LO <look> Look (Color, etc.)
634 if (s.search(annContent))
636 String acc = s.stringMatched(1);
637 String type = s.stringMatched(2);
638 String content = s.stringMatched(3);
639 // TODO: store DR in a vector.
640 // TODO: store AC according to generic file db annotation.
642 if (seqAnn.containsKey(acc))
644 ann = (Hashtable) seqAnn.get(acc);
648 ann = new Hashtable();
650 ann.put(type, content);
651 seqAnn.put(acc, ann);
655 // throw new IOException("Error parsing " + line);
656 System.err.println(">> missing annotation: " + line);
659 else if (annType.equals("GC"))
661 // Generic per-Column annotation, exactly 1 char per column
662 // always need a label.
663 if (x.search(annContent))
665 // parse out and create alignment annotation directly.
666 parseAnnotationRow(annotations, x.stringMatched(1),
670 else if (annType.equals("GR"))
672 // Generic per-Sequence AND per-Column markup, exactly 1 char per
675 * Feature Description Markup letters ------- -----------
676 * -------------- SS Secondary Structure [HGIEBTSCX] SA Surface
677 * Accessibility [0-9X] (0=0%-10%; ...; 9=90%-100%) TM TransMembrane
678 * [Mio] PP Posterior Probability [0-9*] (0=0.00-0.05; 1=0.05-0.15;
679 * *=0.95-1.00) LI LIgand binding [*] AS Active Site [*] IN INtron (in
682 if (s.search(annContent))
684 String acc = s.stringMatched(1);
685 String type = s.stringMatched(2);
686 String oseq = s.stringMatched(3);
688 * copy of annotation field that may be processed into whitespace chunks
690 String seq = new String(oseq);
693 // Get an object with all the annotations for this sequence
694 if (seqAnn.containsKey(acc))
696 // logger.debug("Found annotations for " + acc);
697 ann = (Hashtable) seqAnn.get(acc);
701 // logger.debug("Creating new annotations holder for " + acc);
702 ann = new Hashtable();
703 seqAnn.put(acc, ann);
706 // // start of block for appending annotation lines for wrapped
708 // TODO test structure, call parseAnnotationRow with vector from
709 // hashtable for specific sequence
712 // Get an object with all the content for an annotation
713 if (ann.containsKey("features"))
715 // logger.debug("Found features for " + acc);
716 features = (Hashtable) ann.get("features");
720 // logger.debug("Creating new features holder for " + acc);
721 features = new Hashtable();
722 ann.put("features", features);
726 if (features.containsKey(this.id2type(type)))
728 // logger.debug("Found content for " + this.id2type(type));
729 content = (Hashtable) features.get(this.id2type(type));
733 // logger.debug("Creating new content holder for " +
734 // this.id2type(type));
735 content = new Hashtable();
736 features.put(this.id2type(type), content);
738 String ns = (String) content.get(ANNOTATION);
744 // finally, append the annotation line
746 content.put(ANNOTATION, ns);
747 // // end of wrapped annotation block.
748 // // Now a new row is created with the current set of data
751 if (seqAnn.containsKey(acc))
753 strucAnn = (Hashtable) seqAnn.get(acc);
757 strucAnn = new Hashtable();
760 Vector<AlignmentAnnotation> newStruc = new Vector<>();
761 parseAnnotationRow(newStruc, type, ns);
762 for (AlignmentAnnotation alan : newStruc)
764 alan.visible = false;
766 // new annotation overwrites any existing annotation...
768 strucAnn.put(type, newStruc);
769 seqAnn.put(acc, strucAnn);
775 "Warning - couldn't parse sequence annotation row line:\n"
777 // throw new IOException("Error parsing " + line);
782 throw new IOException(MessageManager.formatMessage(
783 "exception.unknown_annotation_detected", new String[]
784 { annType, annContent }));
788 if (treeString.length() > 0)
790 if (treeName == null)
792 treeName = "Tree " + (1 + getTreeCount());
794 addNewickTree(treeName, treeString.toString());
799 * Demangle an accession string and guess the originating sequence database
800 * for a given sequence
803 * sequence to be annotated
805 * Accession string for sequence
807 * source database for alignment (PFAM or RFAM)
809 private void guessDatabaseFor(Sequence seqO, String dbr, String dbsource)
811 DBRefEntry dbrf = null;
812 List<DBRefEntry> dbrs = new ArrayList<>();
813 String seqdb = "Unknown", sdbac = "" + dbr;
814 int st = -1, en = -1, p;
815 if ((st = sdbac.indexOf("/")) > -1)
817 String num, range = sdbac.substring(st + 1);
818 sdbac = sdbac.substring(0, st);
819 if ((p = range.indexOf("-")) > -1)
822 if (p < range.length())
824 num = range.substring(p).trim();
827 en = Integer.parseInt(num);
828 } catch (NumberFormatException x)
830 // could warn here that index is invalid
839 num = range.substring(0, p).trim();
842 st = Integer.parseInt(num);
843 } catch (NumberFormatException x)
845 // could warn here that index is invalid
849 if (dbsource == null)
851 // make up an origin based on whether the sequence looks like it is nucleotide
853 dbsource = (seqO.isProtein()) ? "PFAM" : "RFAM";
855 if (dbsource.equals("PFAM"))
858 if (sdbac.indexOf(".") > -1)
860 // strip of last subdomain
861 sdbac = sdbac.substring(0, sdbac.indexOf("."));
862 dbrf = jalview.util.DBRefUtils.parseToDbRef(seqO, seqdb, dbsource,
869 dbrf = jalview.util.DBRefUtils.parseToDbRef(seqO, dbsource, dbsource,
878 seqdb = "EMBL"; // total guess - could be ENA, or something else these
880 if (sdbac.indexOf(".") > -1)
882 // strip off last subdomain
883 sdbac = sdbac.substring(0, sdbac.indexOf("."));
884 dbrf = jalview.util.DBRefUtils.parseToDbRef(seqO, seqdb, dbsource,
892 dbrf = jalview.util.DBRefUtils.parseToDbRef(seqO, dbsource, dbsource,
899 if (st != -1 && en != -1)
901 for (DBRefEntry d : dbrs)
903 jalview.util.MapList mp = new jalview.util.MapList(
905 { seqO.getStart(), seqO.getEnd() }, new int[] { st, en }, 1,
907 jalview.datamodel.Mapping mping = new Mapping(mp);
913 protected static AlignmentAnnotation parseAnnotationRow(
914 Vector<AlignmentAnnotation> annotation, String label,
917 String convert1, convert2 = null;
919 // convert1 = OPEN_PAREN.replaceAll(annots);
920 // convert2 = CLOSE_PAREN.replaceAll(convert1);
921 // annots = convert2;
924 if (label.contains("_cons"))
926 type = (label.indexOf("_cons") == label.length() - 5)
927 ? label.substring(0, label.length() - 5)
930 boolean ss = false, posterior = false;
931 type = id2type(type);
933 boolean isrnass = false;
934 if (type.equalsIgnoreCase("secondary structure"))
937 isrnass = !getRegex(REGEX_NOT_RNASS).search(annots); // sorry about the double
939 // here (it's easier for dealing with
940 // other non-alpha-non-brace chars)
942 if (type.equalsIgnoreCase("posterior probability"))
946 // decide on secondary structure or not.
947 Annotation[] els = new Annotation[annots.length()];
948 for (int i = 0; i < annots.length(); i++)
950 String pos = annots.substring(i, i + 1);
952 ann = new Annotation(pos, "", ' ', 0f); // 0f is 'valid' null - will not
956 // if (" .-_".indexOf(pos) == -1)
958 if (isrnass && RNASS_BRACKETS.indexOf(pos) >= 0)
960 ann.secondaryStructure = Rna.getRNASecStrucState(pos).charAt(0);
961 ann.displayCharacter = "" + pos.charAt(0);
965 ann.secondaryStructure = ResidueProperties.getDssp3state(pos)
968 if (ann.secondaryStructure == pos.charAt(0))
970 ann.displayCharacter = ""; // null; // " ";
974 ann.displayCharacter = " " + ann.displayCharacter;
980 if (posterior && !ann.isWhitespace()
981 && !Comparison.isGap(pos.charAt(0)))
984 // symbol encodes values - 0..*==0..10
985 if (pos.charAt(0) == '*')
991 val = pos.charAt(0) - '0';
1002 AlignmentAnnotation annot = null;
1003 Enumeration<AlignmentAnnotation> e = annotation.elements();
1004 while (e.hasMoreElements())
1006 annot = e.nextElement();
1007 if (annot.label.equals(type))
1015 annot = new AlignmentAnnotation(type, type, els);
1016 annotation.addElement(annot);
1020 Annotation[] anns = new Annotation[annot.annotations.length
1022 System.arraycopy(annot.annotations, 0, anns, 0,
1023 annot.annotations.length);
1024 System.arraycopy(els, 0, anns, annot.annotations.length, els.length);
1025 annot.annotations = anns;
1026 // System.out.println("else: ");
1031 private String dbref_to_ac_record(DBRefEntry ref)
1033 return ref.getSource().toString() + " ; "
1034 + ref.getAccessionId().toString();
1038 public String print(SequenceI[] s, boolean jvSuffix)
1040 out = new StringBuffer();
1041 out.append("# STOCKHOLM 1.0");
1042 out.append(newline);
1044 // find max length of id
1048 int slen = s.length;
1050 Hashtable<String, String> dataRef = null;
1051 boolean isAA = s[in].isProtein();
1052 while ((in < slen) && ((seq = s[in]) != null))
1054 String tmp = printId(seq, jvSuffix);
1055 max = Math.max(max, seq.getLength());
1057 if (tmp.length() > maxid)
1059 maxid = tmp.length();
1061 List<DBRefEntry> seqrefs = seq.getDBRefs();
1063 if (seqrefs != null && (ndb = seqrefs.size()) > 0)
1065 if (dataRef == null)
1067 dataRef = new Hashtable<>();
1069 List<DBRefEntry> primrefs = seq.getPrimaryDBRefs();
1070 if (primrefs.size() >= 1)
1072 dataRef.put(tmp, dbref_to_ac_record(primrefs.get(0)));
1076 for (int idb = 0; idb < ndb; idb++)
1078 DBRefEntry dbref = seqrefs.get(idb);
1079 dataRef.put(tmp, dbref_to_ac_record(dbref));
1080 // if we put in a uniprot or EMBL record then we're done:
1081 if ((isAA ? DBRefSource.UNIPROT : DBRefSource.EMBL)
1082 .equals(DBRefUtils.getCanonicalName(dbref.getSource())))
1094 // output database type
1095 if (al.getProperties() != null)
1097 if (!al.getProperties().isEmpty())
1099 Enumeration key = al.getProperties().keys();
1100 Enumeration val = al.getProperties().elements();
1101 while (key.hasMoreElements())
1103 out.append("#=GF " + key.nextElement() + " " + val.nextElement());
1104 out.append(newline);
1109 // output database accessions
1110 if (dataRef != null)
1112 Enumeration<String> en = dataRef.keys();
1113 while (en.hasMoreElements())
1115 Object idd = en.nextElement();
1116 String type = dataRef.remove(idd);
1117 out.append(new Format("%-" + (maxid - 2) + "s")
1118 .form("#=GS " + idd.toString() + " "));
1119 if (isAA && type.contains("UNIPROT")
1120 || (!isAA && type.contains("EMBL")))
1123 out.append(" AC " + type.substring(type.indexOf(";") + 1));
1127 out.append(" DR " + type + " ");
1129 out.append(newline);
1133 // output annotations
1134 while (i < slen && (seq = s[i]) != null)
1136 AlignmentAnnotation[] alAnot = seq.getAnnotation();
1140 for (int j = 0, nj = alAnot.length; j < nj; j++)
1143 String key = type2id(alAnot[j].label);
1144 boolean isrna = alAnot[j].isValidStruc();
1148 // hardwire to secondary structure if there is RNA secondary
1149 // structure on the annotation
1158 // out.append("#=GR ");
1159 out.append(new Format("%-" + maxid + "s").form(
1160 "#=GR " + printId(seq, jvSuffix) + " " + key + " "));
1161 ann = alAnot[j].annotations;
1163 for (int k = 0, nk = ann.length; k < nk; k++)
1165 sseq += outputCharacter(key, k, isrna, ann, seq);
1168 out.append(newline);
1172 out.append(new Format("%-" + maxid + "s")
1173 .form(printId(seq, jvSuffix) + " "));
1174 out.append(seq.getSequenceAsString());
1175 out.append(newline);
1179 // alignment annotation
1180 AlignmentAnnotation aa;
1181 AlignmentAnnotation[] an = al.getAlignmentAnnotation();
1184 for (int ia = 0, na = an.length; ia < na; ia++)
1187 if (aa.autoCalculated || !aa.visible || aa.sequenceRef != null)
1194 if (aa.label.equals("seq"))
1200 key = type2id(aa.label.toLowerCase());
1207 label = key + "_cons";
1214 label = label.replace(" ", "_");
1217 new Format("%-" + maxid + "s").form("#=GC " + label + " "));
1218 boolean isrna = aa.isValidStruc();
1219 for (int j = 0, nj = aa.annotations.length; j < nj; j++)
1221 sseq += outputCharacter(key, j, isrna, aa.annotations, null);
1224 out.append(newline);
1229 out.append(newline);
1231 return out.toString();
1235 * add an annotation character to the output row
1244 private char outputCharacter(String key, int k, boolean isrna,
1245 Annotation[] ann, SequenceI sequenceI)
1248 Annotation annot = ann[k];
1249 String ch = (annot == null)
1250 ? ((sequenceI == null) ? "-"
1251 : Character.toString(sequenceI.getCharAt(k)))
1252 : (annot.displayCharacter == null
1253 ? String.valueOf(annot.secondaryStructure)
1254 : annot.displayCharacter);
1259 if (key != null && key.equals("SS"))
1261 char ssannotchar = ' ';
1262 boolean charset = false;
1265 // sensible gap character
1271 // valid secondary structure AND no alternative label (e.g. ' B')
1272 if (annot.secondaryStructure > ' ' && ch.length() < 2)
1274 ssannotchar = annot.secondaryStructure;
1280 return (ssannotchar == ' ' && isrna) ? '.' : ssannotchar;
1284 if (ch.length() == 0)
1288 else if (ch.length() == 1)
1292 else if (ch.length() > 1)
1297 return (seq == ' ' && key != null && key.equals("SS") && isrna) ? '.'
1301 public String print()
1303 out = new StringBuffer();
1304 out.append("# STOCKHOLM 1.0");
1305 out.append(newline);
1306 print(getSeqsAsArray(), false);
1309 out.append(newline);
1310 return out.toString();
1313 private static Hashtable typeIds = null;
1317 if (typeIds == null)
1319 typeIds = new Hashtable();
1320 typeIds.put("SS", "Secondary Structure");
1321 typeIds.put("SA", "Surface Accessibility");
1322 typeIds.put("TM", "transmembrane");
1323 typeIds.put("PP", "Posterior Probability");
1324 typeIds.put("LI", "ligand binding");
1325 typeIds.put("AS", "active site");
1326 typeIds.put("IN", "intron");
1327 typeIds.put("IR", "interacting residue");
1328 typeIds.put("AC", "accession");
1329 typeIds.put("OS", "organism");
1330 typeIds.put("CL", "class");
1331 typeIds.put("DE", "description");
1332 typeIds.put("DR", "reference");
1333 typeIds.put("LO", "look");
1334 typeIds.put("RF", "Reference Positions");
1339 protected static String id2type(String id)
1341 if (typeIds.containsKey(id))
1343 return (String) typeIds.get(id);
1346 "Warning : Unknown Stockholm annotation type code " + id);
1350 protected static String type2id(String type)
1353 Enumeration e = typeIds.keys();
1354 while (e.hasMoreElements())
1356 Object ll = e.nextElement();
1357 if (typeIds.get(ll).toString().equalsIgnoreCase(type))
1368 "Warning : Unknown Stockholm annotation type: " + type);
1373 * make a friendly ID string.
1376 * @return truncated dataName to after last '/'
1378 private String safeName(String dataName)
1381 while ((b = dataName.indexOf("/")) > -1 && b < dataName.length())
1383 dataName = dataName.substring(b + 1).trim();
1386 int e = (dataName.length() - dataName.indexOf(".")) + 1;
1387 dataName = dataName.substring(1, e).trim();