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;
51 import java.util.Locale;
53 import java.util.Vector;
55 import com.stevesoft.pat.Regex;
57 import fr.orsay.lri.varna.exceptions.ExceptionUnmatchedClosingParentheses;
58 import fr.orsay.lri.varna.factories.RNAFactory;
59 import fr.orsay.lri.varna.models.rna.RNA;
62 * This class is supposed to parse a Stockholm format file into Jalview There
63 * are TODOs in this class: we do not know what the database source and version
64 * is for the file when parsing the #GS= AC tag which associates accessions with
65 * sequences. Database references are also not parsed correctly: a separate
66 * reference string parser must be added to parse the database reference form
67 * into Jalview's local representation.
69 * @author bsb at sanger.ac.uk
70 * @author Natasha Shersnev (Dundee, UK) (Stockholm file writer)
71 * @author Lauren Lui (UCSC, USA) (RNA secondary structure annotation import as
73 * @author Anne Menard (Paris, FR) (VARNA parsing of Stockholm file data)
74 * @version 0.3 + jalview mods
77 public class StockholmFile extends AlignFile
79 private static final String ANNOTATION = "annotation";
81 private static final char UNDERSCORE = '_';
83 // WUSS extended symbols. Avoid ambiguity with protein SS annotations by using NOT_RNASS first.
85 public static final String RNASS_BRACKETS = "<>[](){}AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz";
87 public static final int REGEX_STOCKHOLM = 0;
89 public static final int REGEX_BRACKETS = 1;
90 // use the following regex to decide an annotations (whole) line is NOT an RNA
91 // SS (it contains only E,H,e,h and other non-brace/non-alpha chars)
92 public static final int REGEX_NOT_RNASS = 2;
94 private static final int REGEX_ANNOTATION = 3;
96 private static final int REGEX_PFAM = 4;
98 private static final int REGEX_RFAM = 5;
100 private static final int REGEX_ALIGN_END = 6;
102 private static final int REGEX_SPLIT_ID = 7;
104 private static final int REGEX_SUBTYPE = 8;
106 private static final int REGEX_ANNOTATION_LINE = 9;
108 private static final int REGEX_REMOVE_ID = 10;
110 private static final int REGEX_OPEN_PAREN = 11;
112 private static final int REGEX_CLOSE_PAREN = 12;
114 public static final int REGEX_MAX = 13;
116 private static Regex REGEX[] = new Regex[REGEX_MAX];
119 * Centralize all actual Regex instantialization in Platform.
120 * // JBPNote: Why is this 'centralisation' better ?
124 private static Regex getRegex(int id)
126 if (REGEX[id] == null)
128 String pat = null, pat2 = null;
131 case REGEX_STOCKHOLM:
132 pat = "# STOCKHOLM ([\\d\\.]+)";
135 // for reference; not used
136 pat = "(<|>|\\[|\\]|\\(|\\)|\\{|\\})";
138 case REGEX_NOT_RNASS:
139 pat = "^[^<>[\\](){}ADFJ-RUVWYZadfj-ruvwyz]*$"; // update 2.11.2
141 case REGEX_ANNOTATION:
142 pat = "(\\w+)\\s*(.*)";
145 pat = "PF[0-9]{5}(.*)";
148 pat = "RF[0-9]{5}(.*)";
150 case REGEX_ALIGN_END:
154 pat = "(\\S+)\\/(\\d+)\\-(\\d+)";
157 pat = "(\\S+)\\s+(\\S*)\\s+(.*)";
159 case REGEX_ANNOTATION_LINE:
160 pat = "#=(G[FSRC]?)\\s+(.*)";
162 case REGEX_REMOVE_ID:
163 pat = "(\\S+)\\s+(\\S+)";
165 case REGEX_OPEN_PAREN:
169 case REGEX_CLOSE_PAREN:
176 REGEX[id] = Platform.newRegex(pat, pat2);
181 StringBuffer out; // output buffer
183 private AlignmentI al;
185 public StockholmFile()
190 * Creates a new StockholmFile object for output
192 public StockholmFile(AlignmentI al)
197 public StockholmFile(String inFile, DataSourceType type)
203 public StockholmFile(FileParse source) throws IOException
209 public void initData()
215 * Parse a file in Stockholm format into Jalview's data model using VARNA
217 * @throws IOException
218 * If there is an error with the input file
220 public void parse_with_VARNA(java.io.File inFile) throws IOException
222 FileReader fr = null;
223 fr = new FileReader(inFile);
225 BufferedReader r = new BufferedReader(fr);
226 List<RNA> result = null;
229 result = RNAFactory.loadSecStrStockholm(r);
230 } catch (ExceptionUnmatchedClosingParentheses umcp)
232 errormessage = "Unmatched parentheses in annotation. Aborting ("
233 + umcp.getMessage() + ")";
234 throw new IOException(umcp);
236 // DEBUG System.out.println("this is the secondary scructure:"
238 SequenceI[] seqs = new SequenceI[result.size()];
240 for (int i = 0; i < result.size(); i++)
242 // DEBUG System.err.println("Processing i'th sequence in Stockholm file")
243 RNA current = result.get(i);
245 String seq = current.getSeq();
246 String rna = current.getStructDBN(true);
247 // DEBUG System.out.println(seq);
248 // DEBUG System.err.println(rna);
250 int end = seq.length() - 1;
251 id = safeName(getDataName());
252 seqs[i] = new Sequence(id, seq, begin, end);
253 String[] annot = new String[rna.length()];
254 Annotation[] ann = new Annotation[rna.length()];
255 for (int j = 0; j < rna.length(); j++)
257 annot[j] = rna.substring(j, j + 1);
261 for (int k = 0; k < rna.length(); k++)
263 ann[k] = new Annotation(annot[k], "",
264 Rna.getRNASecStrucState(annot[k]).charAt(0), 0f);
267 AlignmentAnnotation align = new AlignmentAnnotation("Sec. str.",
268 current.getID(), ann);
270 seqs[i].addAlignmentAnnotation(align);
271 seqs[i].setRNA(result.get(i));
272 this.annotations.addElement(align);
279 * Parse a file in Stockholm format into Jalview's data model. The file has to
280 * be passed at construction time
282 * @throws IOException
283 * If there is an error with the input file
286 public void parse() throws IOException
288 StringBuffer treeString = new StringBuffer();
289 String treeName = null;
290 // --------------- Variable Definitions -------------------
294 Hashtable seqAnn = new Hashtable(); // Sequence related annotations
295 LinkedHashMap<String, String> seqs = new LinkedHashMap<>();
296 Regex p, r, rend, s, x;
297 // Temporary line for processing RNA annotation
298 // String RNAannot = "";
300 // ------------------ Parsing File ----------------------
301 // First, we have to check that this file has STOCKHOLM format, i.e. the
302 // first line must match
304 r = getRegex(REGEX_STOCKHOLM);
305 if (!r.search(nextLine()))
307 throw new IOException(MessageManager
308 .getString("exception.stockholm_invalid_format"));
312 version = r.stringMatched(1);
314 // logger.debug("Stockholm version: " + version);
317 // We define some Regexes here that will be used regularily later
318 rend = getRegex(REGEX_ALIGN_END);//"^\\s*\\/\\/"); // Find the end of an alignment
319 p = getRegex(REGEX_SPLIT_ID);//"(\\S+)\\/(\\d+)\\-(\\d+)"); // split sequence id in
321 s = getRegex(REGEX_SUBTYPE);// "(\\S+)\\s+(\\S*)\\s+(.*)"); // Parses
322 // annotation subtype
323 r = getRegex(REGEX_ANNOTATION_LINE);// "#=(G[FSRC]?)\\s+(.*)"); // Finds any
325 x = getRegex(REGEX_REMOVE_ID);// "(\\S+)\\s+(\\S+)"); // split id from
328 // Convert all bracket types to parentheses (necessary for passing to VARNA)
329 Regex openparen = getRegex(REGEX_OPEN_PAREN);//"(<|\\[)", "(");
330 Regex closeparen = getRegex(REGEX_CLOSE_PAREN);//"(>|\\])", ")");
332 // // Detect if file is RNA by looking for bracket types
333 // Regex detectbrackets = new Regex("(<|>|\\[|\\]|\\(|\\))");
340 openparen.optimize();
341 closeparen.optimize();
343 while ((line = nextLine()) != null)
345 if (line.length() == 0)
349 if (rend.search(line))
351 // End of the alignment, pass stuff back
352 this.noSeqs = seqs.size();
354 String dbsource = null;
355 Regex pf = getRegex(REGEX_PFAM); // Finds AC for Pfam
356 Regex rf = getRegex(REGEX_RFAM); // Finds AC for Rfam
357 if (getAlignmentProperty("AC") != null)
359 String dbType = getAlignmentProperty("AC").toString();
360 if (pf.search(dbType))
362 // PFAM Alignment - so references are typically from Uniprot
365 else if (rf.search(dbType))
370 // logger.debug("Number of sequences: " + this.noSeqs);
371 for (Map.Entry<String, String> skey : seqs.entrySet())
373 // logger.debug("Processing sequence " + acc);
374 String acc = skey.getKey();
375 String seq = skey.getValue();
376 if (maxLength < seq.length())
378 maxLength = seq.length();
384 * Retrieve hash of annotations for this accession Associate
385 * Annotation with accession
387 Hashtable accAnnotations = null;
389 if (seqAnn != null && seqAnn.containsKey(acc))
391 accAnnotations = (Hashtable) seqAnn.remove(acc);
392 // TODO: add structures to sequence
395 // Split accession in id and from/to
398 sid = p.stringMatched(1);
399 start = Integer.parseInt(p.stringMatched(2));
400 end = Integer.parseInt(p.stringMatched(3));
402 // logger.debug(sid + ", " + start + ", " + end);
404 Sequence seqO = new Sequence(sid, seq, start, end);
405 // Add Description (if any)
406 if (accAnnotations != null && accAnnotations.containsKey("DE"))
408 String desc = (String) accAnnotations.get("DE");
409 seqO.setDescription((desc == null) ? "" : desc);
411 // Add DB References (if any)
412 if (accAnnotations != null && accAnnotations.containsKey("DR"))
414 String dbr = (String) accAnnotations.get("DR");
415 if (dbr != null && dbr.indexOf(";") > -1)
417 String src = dbr.substring(0, dbr.indexOf(";"));
418 String acn = dbr.substring(dbr.indexOf(";") + 1);
419 jalview.util.DBRefUtils.parseToDbRef(seqO, src, "0", acn);
423 if (accAnnotations != null && accAnnotations.containsKey("AC"))
425 String dbr = (String) accAnnotations.get("AC");
428 // we could get very clever here - but for now - just try to
429 // guess accession type from type of sequence, source of alignment plus
432 guessDatabaseFor(seqO, dbr, dbsource);
434 // else - do what ? add the data anyway and prompt the user to
435 // specify what references these are ?
438 Hashtable features = null;
439 // We need to adjust the positions of all features to account for gaps
442 features = (Hashtable) accAnnotations.remove("features");
443 } catch (java.lang.NullPointerException e)
445 // loggerwarn("Getting Features for " + acc + ": " +
449 // if we have features
450 if (features != null)
452 int posmap[] = seqO.findPositionMap();
453 Enumeration i = features.keys();
454 while (i.hasMoreElements())
456 // TODO: parse out secondary structure annotation as annotation
458 // TODO: parse out scores as annotation row
459 // TODO: map coding region to core jalview feature types
460 String type = i.nextElement().toString();
461 Hashtable content = (Hashtable) features.remove(type);
463 // add alignment annotation for this feature
464 String key = type2id(type);
467 * have we added annotation rows for this type ?
469 boolean annotsAdded = false;
472 if (accAnnotations != null
473 && accAnnotations.containsKey(key))
475 Vector vv = (Vector) accAnnotations.get(key);
476 for (int ii = 0; ii < vv.size(); ii++)
479 AlignmentAnnotation an = (AlignmentAnnotation) vv
481 seqO.addAlignmentAnnotation(an);
487 Enumeration j = content.keys();
488 while (j.hasMoreElements())
490 String desc = j.nextElement().toString();
491 if (ANNOTATION.equals(desc) && annotsAdded)
493 // don't add features if we already added an annotation row
496 String ns = content.get(desc).toString();
497 char[] byChar = ns.toCharArray();
498 for (int k = 0; k < byChar.length; k++)
501 if (!(c == ' ' || c == '_' || c == '-' || c == '.')) // PFAM
508 int new_pos = posmap[k]; // look up nearest seqeunce
509 // position to this column
510 SequenceFeature feat = new SequenceFeature(type, desc,
511 new_pos, new_pos, null);
513 seqO.addSequenceFeature(feat);
523 // logger.debug("Adding seq " + acc + " from " + start + " to " + end
525 this.seqs.addElement(seqO);
527 return; // finished parsing this segment of source
529 else if (!r.search(line))
531 // System.err.println("Found sequence line: " + line);
533 // Split sequence in sequence and accession parts
536 // logger.error("Could not parse sequence line: " + line);
537 throw new IOException(MessageManager.formatMessage(
538 "exception.couldnt_parse_sequence_line", new String[]
541 String ns = seqs.get(x.stringMatched(1));
546 ns += x.stringMatched(2);
548 seqs.put(x.stringMatched(1), ns);
552 String annType = r.stringMatched(1);
553 String annContent = r.stringMatched(2);
555 // System.err.println("type:" + annType + " content: " + annContent);
557 if (annType.equals("GF"))
560 * Generic per-File annotation, free text Magic features: #=GF NH
561 * <tree in New Hampshire eXtended format> #=GF TN <Unique identifier
562 * for the next tree> Pfam descriptions: 7. DESCRIPTION OF FIELDS
564 * Compulsory fields: ------------------
566 * AC Accession number: Accession number in form PFxxxxx.version or
567 * PBxxxxxx. ID Identification: One word name for family. DE
568 * Definition: Short description of family. AU Author: Authors of the
569 * entry. SE Source of seed: The source suggesting the seed members
570 * belong to one family. GA Gathering method: Search threshold to
571 * build the full alignment. TC Trusted Cutoff: Lowest sequence score
572 * and domain score of match in the full alignment. NC Noise Cutoff:
573 * Highest sequence score and domain score of match not in full
574 * alignment. TP Type: Type of family -- presently Family, Domain,
575 * Motif or Repeat. SQ Sequence: Number of sequences in alignment. AM
576 * Alignment Method The order ls and fs hits are aligned to the model
577 * to build the full align. // End of alignment.
579 * Optional fields: ----------------
581 * DC Database Comment: Comment about database reference. DR Database
582 * Reference: Reference to external database. RC Reference Comment:
583 * Comment about literature reference. RN Reference Number: Reference
584 * Number. RM Reference Medline: Eight digit medline UI number. RT
585 * Reference Title: Reference Title. RA Reference Author: Reference
586 * Author RL Reference Location: Journal location. PI Previous
587 * identifier: Record of all previous ID lines. KW Keywords: Keywords.
588 * CC Comment: Comments. NE Pfam accession: Indicates a nested domain.
589 * NL Location: Location of nested domains - sequence ID, start and
592 * Obsolete fields: ----------- AL Alignment method of seed: The
593 * method used to align the seed members.
595 // Let's save the annotations, maybe we'll be able to do something
596 // with them later...
597 Regex an = getRegex(REGEX_ANNOTATION);
598 if (an.search(annContent))
600 if (an.stringMatched(1).equals("NH"))
602 treeString.append(an.stringMatched(2));
604 else if (an.stringMatched(1).equals("TN"))
606 if (treeString.length() > 0)
608 if (treeName == null)
610 treeName = "Tree " + (getTreeCount() + 1);
612 addNewickTree(treeName, treeString.toString());
614 treeName = an.stringMatched(2);
615 treeString = new StringBuffer();
617 // TODO: JAL-3532 - this is where GF comments and database references are lost
618 // suggest overriding this method for Stockholm files to catch and properly
619 // process CC, DR etc into multivalued properties
620 setAlignmentProperty(an.stringMatched(1), an.stringMatched(2));
623 else if (annType.equals("GS"))
625 // Generic per-Sequence annotation, free text
627 * Pfam uses these features: Feature Description ---------------------
628 * ----------- AC <accession> ACcession number DE <freetext>
629 * DEscription DR <db>; <accession>; Database Reference OS <organism>
630 * OrganiSm (species) OC <clade> Organism Classification (clade, etc.)
631 * LO <look> Look (Color, etc.)
633 if (s.search(annContent))
635 String acc = s.stringMatched(1);
636 String type = s.stringMatched(2);
637 String content = s.stringMatched(3);
638 // TODO: store DR in a vector.
639 // TODO: store AC according to generic file db annotation.
641 if (seqAnn.containsKey(acc))
643 ann = (Hashtable) seqAnn.get(acc);
647 ann = new Hashtable();
649 ann.put(type, content);
650 seqAnn.put(acc, ann);
654 // throw new IOException("Error parsing " + line);
655 System.err.println(">> missing annotation: " + line);
658 else if (annType.equals("GC"))
660 // Generic per-Column annotation, exactly 1 char per column
661 // always need a label.
662 if (x.search(annContent))
664 // parse out and create alignment annotation directly.
665 parseAnnotationRow(annotations, x.stringMatched(1),
669 else if (annType.equals("GR"))
671 // Generic per-Sequence AND per-Column markup, exactly 1 char per
674 * Feature Description Markup letters ------- -----------
675 * -------------- SS Secondary Structure [HGIEBTSCX] SA Surface
676 * Accessibility [0-9X] (0=0%-10%; ...; 9=90%-100%) TM TransMembrane
677 * [Mio] PP Posterior Probability [0-9*] (0=0.00-0.05; 1=0.05-0.15;
678 * *=0.95-1.00) LI LIgand binding [*] AS Active Site [*] IN INtron (in
681 if (s.search(annContent))
683 String acc = s.stringMatched(1);
684 String type = s.stringMatched(2);
685 String oseq = s.stringMatched(3);
687 * copy of annotation field that may be processed into whitespace chunks
689 String seq = new String(oseq);
692 // Get an object with all the annotations for this sequence
693 if (seqAnn.containsKey(acc))
695 // logger.debug("Found annotations for " + acc);
696 ann = (Hashtable) seqAnn.get(acc);
700 // logger.debug("Creating new annotations holder for " + acc);
701 ann = new Hashtable();
702 seqAnn.put(acc, ann);
705 // // start of block for appending annotation lines for wrapped
707 // TODO test structure, call parseAnnotationRow with vector from
708 // hashtable for specific sequence
711 // Get an object with all the content for an annotation
712 if (ann.containsKey("features"))
714 // logger.debug("Found features for " + acc);
715 features = (Hashtable) ann.get("features");
719 // logger.debug("Creating new features holder for " + acc);
720 features = new Hashtable();
721 ann.put("features", features);
725 if (features.containsKey(this.id2type(type)))
727 // logger.debug("Found content for " + this.id2type(type));
728 content = (Hashtable) features
729 .get(this.id2type(type));
733 // logger.debug("Creating new content holder for " +
734 // this.id2type(type));
735 content = new Hashtable();
736 features.put(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;
918 // String convert1 = OPEN_PAREN.replaceAll(annots);
919 // String convert2 = CLOSE_PAREN.replaceAll(convert1);
920 // annots = convert2;
923 if (label.contains("_cons"))
925 type = (label.indexOf("_cons") == label.length() - 5)
926 ? label.substring(0, label.length() - 5)
929 boolean ss = false, posterior = false;
930 type = id2type(type);
932 boolean isrnass = false;
933 if (type.equalsIgnoreCase("secondary structure"))
936 isrnass = !getRegex(REGEX_NOT_RNASS).search(annots); // sorry about the double
938 // here (it's easier for dealing with
939 // other non-alpha-non-brace chars)
941 if (type.equalsIgnoreCase("posterior probability"))
945 // decide on secondary structure or not.
946 Annotation[] els = new Annotation[annots.length()];
947 for (int i = 0; i < annots.length(); i++)
949 String pos = annots.substring(i, i + 1);
950 // TODO 2.12 release: verify this Stockholm IO behaviour change in release notes
951 if (UNDERSCORE == pos.charAt(0))
956 ann = new Annotation(pos, "", ' ', 0f); // 0f is 'valid' null - will not
960 // if (" .-_".indexOf(pos) == -1)
962 if (isrnass && RNASS_BRACKETS.indexOf(pos) >= 0)
964 ann.secondaryStructure = Rna.getRNASecStrucState(pos).charAt(0);
965 ann.displayCharacter = "" + pos.charAt(0);
969 ann.secondaryStructure = ResidueProperties.getDssp3state(pos)
972 if (ann.secondaryStructure == pos.charAt(0))
974 ann.displayCharacter = ""; // null; // " ";
978 ann.displayCharacter = " " + ann.displayCharacter;
984 if (posterior && !ann.isWhitespace()
985 && !Comparison.isGap(pos.charAt(0)))
988 // symbol encodes values - 0..*==0..10
989 if (pos.charAt(0) == '*')
995 val = pos.charAt(0) - '0';
1006 AlignmentAnnotation annot = null;
1007 Enumeration<AlignmentAnnotation> e = annotation.elements();
1008 while (e.hasMoreElements())
1010 annot = e.nextElement();
1011 if (annot.label.equals(type))
1019 annot = new AlignmentAnnotation(type, type, els);
1020 annotation.addElement(annot);
1024 Annotation[] anns = new Annotation[annot.annotations.length
1026 System.arraycopy(annot.annotations, 0, anns, 0,
1027 annot.annotations.length);
1028 System.arraycopy(els, 0, anns, annot.annotations.length, els.length);
1029 annot.annotations = anns;
1030 // System.out.println("else: ");
1035 private String dbref_to_ac_record(DBRefEntry ref)
1037 return ref.getSource().toString() + " ; "
1038 + ref.getAccessionId().toString();
1041 public String print(SequenceI[] s, boolean jvSuffix)
1043 out = new StringBuffer();
1044 out.append("# STOCKHOLM 1.0");
1045 out.append(newline);
1047 // find max length of id
1051 int slen = s.length;
1053 Hashtable<String, String> dataRef = null;
1054 boolean isAA = s[in].isProtein();
1055 while ((in < slen) && ((seq = s[in]) != null))
1057 String tmp = printId(seq, jvSuffix);
1058 max = Math.max(max, seq.getLength());
1060 if (tmp.length() > maxid)
1062 maxid = tmp.length();
1064 List<DBRefEntry> seqrefs = seq.getDBRefs();
1066 if (seqrefs != null && (ndb = seqrefs.size()) > 0)
1068 if (dataRef == null)
1070 dataRef = new Hashtable<>();
1072 List<DBRefEntry> primrefs = seq.getPrimaryDBRefs();
1073 if (primrefs.size() >= 1)
1075 dataRef.put(tmp, dbref_to_ac_record(primrefs.get(0)));
1079 for (int idb = 0; idb < ndb; idb++)
1081 DBRefEntry dbref = seqrefs.get(idb);
1082 dataRef.put(tmp, dbref_to_ac_record(dbref));
1083 // if we put in a uniprot or EMBL record then we're done:
1084 if ((isAA ? DBRefSource.UNIPROT : DBRefSource.EMBL)
1085 .equals(DBRefUtils.getCanonicalName(dbref.getSource())))
1097 // output database type
1098 if (al.getProperties() != null)
1100 if (!al.getProperties().isEmpty())
1102 Enumeration key = al.getProperties().keys();
1103 Enumeration val = al.getProperties().elements();
1104 while (key.hasMoreElements())
1106 out.append("#=GF " + key.nextElement() + " " + val.nextElement());
1107 out.append(newline);
1112 // output database accessions
1113 if (dataRef != null)
1115 Enumeration<String> en = dataRef.keys();
1116 while (en.hasMoreElements())
1118 Object idd = en.nextElement();
1119 String type = dataRef.remove(idd);
1120 out.append(new Format("%-" + (maxid - 2) + "s")
1121 .form("#=GS " + idd.toString() + " "));
1122 if (isAA && type.contains("UNIPROT")
1123 || (!isAA && type.contains("EMBL")))
1126 out.append(" AC " + type.substring(type.indexOf(";") + 1));
1130 out.append(" DR " + type + " ");
1132 out.append(newline);
1136 // output annotations
1137 while (i < slen && (seq = s[i]) != null)
1139 AlignmentAnnotation[] alAnot = seq.getAnnotation();
1143 for (int j = 0; j < alAnot.length; j++)
1146 if (alAnot[j].annotations != null)
1148 String key = type2id(alAnot[j].label);
1149 boolean isrna = alAnot[j].isValidStruc();
1153 // hardwire to secondary structure if there is RNA secondary
1154 // structure on the annotation
1162 // out.append("#=GR ");
1163 out.append(new Format("%-" + maxid + "s").form(
1164 "#=GR " + printId(s[i], jvSuffix) + " " + key + " "));
1165 ann = alAnot[j].annotations;
1167 for (int k = 0; k < ann.length; k++)
1169 sseq += outputCharacter(key, k, isrna, ann, s[i]);
1172 out.append(newline);
1177 out.append(new Format("%-" + maxid + "s")
1178 .form(printId(seq, jvSuffix) + " "));
1179 out.append(seq.getSequenceAsString());
1180 out.append(newline);
1184 // alignment annotation
1185 AlignmentAnnotation aa;
1186 AlignmentAnnotation[] an = al.getAlignmentAnnotation();
1189 for (int ia = 0, na = an.length; ia < na; ia++)
1192 if (aa.autoCalculated || !aa.visible || aa.sequenceRef != null)
1199 if (aa.label.equals("seq"))
1205 key = type2id(aa.label.toLowerCase(Locale.ROOT));
1212 label = key + "_cons";
1219 label = label.replace(" ", "_");
1222 new Format("%-" + maxid + "s").form("#=GC " + label + " "));
1223 boolean isrna = aa.isValidStruc();
1224 for (int j = 0, nj = aa.annotations.length; j < nj; j++)
1226 sseq += outputCharacter(key, j, isrna, aa.annotations, null);
1229 out.append(newline);
1234 out.append(newline);
1236 return out.toString();
1240 * add an annotation character to the output row
1249 private char outputCharacter(String key, int k, boolean isrna,
1250 Annotation[] ann, SequenceI sequenceI)
1253 Annotation annot = ann[k];
1254 String ch = (annot == null)
1255 ? ((sequenceI == null) ? "-"
1256 : Character.toString(sequenceI.getCharAt(k)))
1257 : (annot.displayCharacter == null
1258 ? String.valueOf(annot.secondaryStructure)
1259 : annot.displayCharacter);
1264 if (key != null && key.equals("SS"))
1266 char ssannotchar = ' ';
1267 boolean charset = false;
1270 // sensible gap character
1276 // valid secondary structure AND no alternative label (e.g. ' B')
1277 if (annot.secondaryStructure > ' ' && ch.length() < 2)
1279 ssannotchar = annot.secondaryStructure;
1285 return (ssannotchar == ' ' && isrna) ? '.' : ssannotchar;
1289 if (ch.length() == 0)
1293 else if (ch.length() == 1)
1297 else if (ch.length() > 1)
1302 return (seq == ' ' && key != null && key.equals("SS") && isrna) ? '.'
1307 * make a friendly ID string.
1310 * @return truncated dataName to after last '/'
1312 private String safeName(String dataName)
1315 while ((b = dataName.indexOf("/")) > -1 && b < dataName.length())
1317 dataName = dataName.substring(b + 1).trim();
1320 int e = (dataName.length() - dataName.indexOf(".")) + 1;
1321 dataName = dataName.substring(1, e).trim();
1326 public String print()
1328 out = new StringBuffer();
1329 out.append("# STOCKHOLM 1.0");
1330 out.append(newline);
1331 print(getSeqsAsArray(), false);
1334 out.append(newline);
1335 return out.toString();
1338 private static Hashtable typeIds = null;
1342 if (typeIds == null)
1344 typeIds = new Hashtable();
1345 typeIds.put("SS", "Secondary Structure");
1346 typeIds.put("SA", "Surface Accessibility");
1347 typeIds.put("TM", "transmembrane");
1348 typeIds.put("PP", "Posterior Probability");
1349 typeIds.put("LI", "ligand binding");
1350 typeIds.put("AS", "active site");
1351 typeIds.put("IN", "intron");
1352 typeIds.put("IR", "interacting residue");
1353 typeIds.put("AC", "accession");
1354 typeIds.put("OS", "organism");
1355 typeIds.put("CL", "class");
1356 typeIds.put("DE", "description");
1357 typeIds.put("DR", "reference");
1358 typeIds.put("LO", "look");
1359 typeIds.put("RF", "Reference Positions");
1365 protected static String id2type(String id)
1367 if (typeIds.containsKey(id))
1369 return (String) typeIds.get(id);
1372 "Warning : Unknown Stockholm annotation type code " + id);
1376 protected static String type2id(String type)
1379 Enumeration e = typeIds.keys();
1380 while (e.hasMoreElements())
1382 Object ll = e.nextElement();
1383 if (typeIds.get(ll).toString().equalsIgnoreCase(type))
1394 "Warning : Unknown Stockholm annotation type: " + type);