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 private static final char UNDERSCORE = '_';
84 // WUSS extended symbols. Avoid ambiguity with protein SS annotations by using NOT_RNASS first.
86 public static final String RNASS_BRACKETS = "<>[](){}AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz";
88 public static final int REGEX_STOCKHOLM = 0;
90 public static final int REGEX_BRACKETS = 1;
92 // use the following regex to decide an annotations (whole) line is NOT an RNA
93 // SS (it contains only E,H,e,h and other non-brace/non-alpha chars)
94 public static final int REGEX_NOT_RNASS = 2;
96 private static final int REGEX_ANNOTATION = 3;
98 private static final int REGEX_PFAM = 4;
100 private static final int REGEX_RFAM = 5;
102 private static final int REGEX_ALIGN_END = 6;
104 private static final int REGEX_SPLIT_ID = 7;
106 private static final int REGEX_SUBTYPE = 8;
108 private static final int REGEX_ANNOTATION_LINE = 9;
110 private static final int REGEX_REMOVE_ID = 10;
112 private static final int REGEX_OPEN_PAREN = 11;
114 private static final int REGEX_CLOSE_PAREN = 12;
116 public static final int REGEX_MAX = 13;
118 private static Regex REGEX[] = new Regex[REGEX_MAX];
121 * Centralize all actual Regex instantialization in Platform.
122 * // JBPNote: Why is this 'centralisation' better ?
126 private static Regex getRegex(int id)
128 if (REGEX[id] == null)
130 String pat = null, pat2 = null;
133 case REGEX_STOCKHOLM:
134 pat = "# STOCKHOLM ([\\d\\.]+)";
137 // for reference; not used
138 pat = "(<|>|\\[|\\]|\\(|\\)|\\{|\\})";
140 case REGEX_NOT_RNASS:
141 pat = "^[^<>[\\](){}A-DF-Za-df-z]*$";
143 case REGEX_ANNOTATION:
144 pat = "(\\w+)\\s*(.*)";
147 pat = "PF[0-9]{5}(.*)";
150 pat = "RF[0-9]{5}(.*)";
152 case REGEX_ALIGN_END:
156 pat = "(\\S+)\\/(\\d+)\\-(\\d+)";
159 pat = "(\\S+)\\s+(\\S*)\\s+(.*)";
161 case REGEX_ANNOTATION_LINE:
162 pat = "#=(G[FSRC]?)\\s+(.*)";
164 case REGEX_REMOVE_ID:
165 pat = "(\\S+)\\s+(\\S+)";
167 case REGEX_OPEN_PAREN:
171 case REGEX_CLOSE_PAREN:
178 REGEX[id] = Platform.newRegex(pat, pat2);
183 StringBuffer out; // output buffer
185 private AlignmentI al;
187 public StockholmFile()
192 * Creates a new StockholmFile object for output
194 public StockholmFile(AlignmentI al)
199 public StockholmFile(String inFile, DataSourceType type)
205 public StockholmFile(FileParse source) throws IOException
211 public void initData()
217 * Parse a file in Stockholm format into Jalview's data model using VARNA
219 * @throws IOException
220 * If there is an error with the input file
222 public void parse_with_VARNA(java.io.File inFile) throws IOException
224 FileReader fr = null;
225 fr = new FileReader(inFile);
227 BufferedReader r = new BufferedReader(fr);
228 List<RNA> result = null;
231 result = RNAFactory.loadSecStrStockholm(r);
232 } catch (ExceptionUnmatchedClosingParentheses umcp)
234 errormessage = "Unmatched parentheses in annotation. Aborting ("
235 + umcp.getMessage() + ")";
236 throw new IOException(umcp);
238 // DEBUG System.out.println("this is the secondary scructure:"
240 SequenceI[] seqs = new SequenceI[result.size()];
242 for (int i = 0; i < result.size(); i++)
244 // DEBUG System.err.println("Processing i'th sequence in Stockholm file")
245 RNA current = result.get(i);
247 String seq = current.getSeq();
248 String rna = current.getStructDBN(true);
249 // DEBUG System.out.println(seq);
250 // DEBUG System.err.println(rna);
252 int end = seq.length() - 1;
253 id = safeName(getDataName());
254 seqs[i] = new Sequence(id, seq, begin, end);
255 String[] annot = new String[rna.length()];
256 Annotation[] ann = new Annotation[rna.length()];
257 for (int j = 0; j < rna.length(); j++)
259 annot[j] = rna.substring(j, j + 1);
263 for (int k = 0; k < rna.length(); k++)
265 ann[k] = new Annotation(annot[k], "",
266 Rna.getRNASecStrucState(annot[k]).charAt(0), 0f);
269 AlignmentAnnotation align = new AlignmentAnnotation("Sec. str.",
270 current.getID(), ann);
272 seqs[i].addAlignmentAnnotation(align);
273 seqs[i].setRNA(result.get(i));
274 this.annotations.addElement(align);
281 * Parse a file in Stockholm format into Jalview's data model. The file has to
282 * be passed at construction time
284 * @throws IOException
285 * If there is an error with the input file
288 public void parse() throws IOException
290 StringBuffer treeString = new StringBuffer();
291 String treeName = null;
292 // --------------- Variable Definitions -------------------
296 Hashtable seqAnn = new Hashtable(); // Sequence related annotations
297 LinkedHashMap<String, String> seqs = new LinkedHashMap<>();
298 Regex p, r, rend, s, x;
299 // Temporary line for processing RNA annotation
300 // String RNAannot = "";
302 // ------------------ Parsing File ----------------------
303 // First, we have to check that this file has STOCKHOLM format, i.e. the
304 // first line must match
306 r = getRegex(REGEX_STOCKHOLM);
307 if (!r.search(nextLine()))
309 throw new IOException(MessageManager
310 .getString("exception.stockholm_invalid_format"));
314 version = r.stringMatched(1);
316 // logger.debug("Stockholm version: " + version);
319 // We define some Regexes here that will be used regularily later
320 rend = getRegex(REGEX_ALIGN_END);//"^\\s*\\/\\/"); // Find the end of an alignment
321 p = getRegex(REGEX_SPLIT_ID);//"(\\S+)\\/(\\d+)\\-(\\d+)"); // split sequence id in
323 s = getRegex(REGEX_SUBTYPE);// "(\\S+)\\s+(\\S*)\\s+(.*)"); // Parses
324 // annotation subtype
325 r = getRegex(REGEX_ANNOTATION_LINE);// "#=(G[FSRC]?)\\s+(.*)"); // Finds any
327 x = getRegex(REGEX_REMOVE_ID);// "(\\S+)\\s+(\\S+)"); // split id from
330 // Convert all bracket types to parentheses (necessary for passing to VARNA)
331 Regex openparen = getRegex(REGEX_OPEN_PAREN);//"(<|\\[)", "(");
332 Regex closeparen = getRegex(REGEX_CLOSE_PAREN);//"(>|\\])", ")");
334 // // Detect if file is RNA by looking for bracket types
335 // Regex detectbrackets = getRegex("(<|>|\\[|\\]|\\(|\\))");
342 openparen.optimize();
343 closeparen.optimize();
345 while ((line = nextLine()) != null)
347 if (line.length() == 0)
351 if (rend.search(line))
353 // End of the alignment, pass stuff back
354 this.noSeqs = seqs.size();
356 String dbsource = null;
357 Regex pf = getRegex(REGEX_PFAM); // Finds AC for Pfam
358 Regex rf = getRegex(REGEX_RFAM); // Finds AC for Rfam
359 if (getAlignmentProperty("AC") != null)
361 String dbType = getAlignmentProperty("AC").toString();
362 if (pf.search(dbType))
364 // PFAM Alignment - so references are typically from Uniprot
367 else if (rf.search(dbType))
372 // logger.debug("Number of sequences: " + this.noSeqs);
373 for (Map.Entry<String, String> skey : seqs.entrySet())
375 // logger.debug("Processing sequence " + acc);
376 String acc = skey.getKey();
377 String seq = skey.getValue();
378 if (maxLength < seq.length())
380 maxLength = seq.length();
386 * Retrieve hash of annotations for this accession Associate
387 * Annotation with accession
389 Hashtable accAnnotations = null;
391 if (seqAnn != null && seqAnn.containsKey(acc))
393 accAnnotations = (Hashtable) seqAnn.remove(acc);
394 // TODO: add structures to sequence
397 // Split accession in id and from/to
400 sid = p.stringMatched(1);
401 start = Integer.parseInt(p.stringMatched(2));
402 end = Integer.parseInt(p.stringMatched(3));
404 // logger.debug(sid + ", " + start + ", " + end);
406 Sequence seqO = new Sequence(sid, seq, start, end);
407 // Add Description (if any)
408 if (accAnnotations != null && accAnnotations.containsKey("DE"))
410 String desc = (String) accAnnotations.get("DE");
411 seqO.setDescription((desc == null) ? "" : desc);
413 // Add DB References (if any)
414 if (accAnnotations != null && accAnnotations.containsKey("DR"))
416 String dbr = (String) accAnnotations.get("DR");
417 if (dbr != null && dbr.indexOf(";") > -1)
419 String src = dbr.substring(0, dbr.indexOf(";"));
420 String acn = dbr.substring(dbr.indexOf(";") + 1);
421 jalview.util.DBRefUtils.parseToDbRef(seqO, src, "0", acn);
425 if (accAnnotations != null && accAnnotations.containsKey("AC"))
427 String dbr = (String) accAnnotations.get("AC");
430 // we could get very clever here - but for now - just try to
431 // guess accession type from type of sequence, source of alignment plus
434 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 // TODO: JAL-3532 - this is where GF comments and database references are lost
620 // suggest overriding this method for Stockholm files to catch and properly
621 // process CC, DR etc into multivalued properties
622 setAlignmentProperty(an.stringMatched(1), an.stringMatched(2));
625 else if (annType.equals("GS"))
627 // Generic per-Sequence annotation, free text
629 * Pfam uses these features: Feature Description ---------------------
630 * ----------- AC <accession> ACcession number DE <freetext>
631 * DEscription DR <db>; <accession>; Database Reference OS <organism>
632 * OrganiSm (species) OC <clade> Organism Classification (clade, etc.)
633 * LO <look> Look (Color, etc.)
635 if (s.search(annContent))
637 String acc = s.stringMatched(1);
638 String type = s.stringMatched(2);
639 String content = s.stringMatched(3);
640 // TODO: store DR in a vector.
641 // TODO: store AC according to generic file db annotation.
643 if (seqAnn.containsKey(acc))
645 ann = (Hashtable) seqAnn.get(acc);
649 ann = new Hashtable();
651 ann.put(type, content);
652 seqAnn.put(acc, ann);
656 // throw new IOException("Error parsing " + line);
657 System.err.println(">> missing annotation: " + line);
660 else if (annType.equals("GC"))
662 // Generic per-Column annotation, exactly 1 char per column
663 // always need a label.
664 if (x.search(annContent))
666 // parse out and create alignment annotation directly.
667 parseAnnotationRow(annotations, x.stringMatched(1),
671 else if (annType.equals("GR"))
673 // Generic per-Sequence AND per-Column markup, exactly 1 char per
676 * Feature Description Markup letters ------- -----------
677 * -------------- SS Secondary Structure [HGIEBTSCX] SA Surface
678 * Accessibility [0-9X] (0=0%-10%; ...; 9=90%-100%) TM TransMembrane
679 * [Mio] PP Posterior Probability [0-9*] (0=0.00-0.05; 1=0.05-0.15;
680 * *=0.95-1.00) LI LIgand binding [*] AS Active Site [*] IN INtron (in
683 if (s.search(annContent))
685 String acc = s.stringMatched(1);
686 String type = s.stringMatched(2);
687 String oseq = s.stringMatched(3);
689 * copy of annotation field that may be processed into whitespace chunks
691 String seq = new String(oseq);
694 // Get an object with all the annotations for this sequence
695 if (seqAnn.containsKey(acc))
697 // logger.debug("Found annotations for " + acc);
698 ann = (Hashtable) seqAnn.get(acc);
702 // logger.debug("Creating new annotations holder for " + acc);
703 ann = new Hashtable();
704 seqAnn.put(acc, ann);
707 // // start of block for appending annotation lines for wrapped
709 // TODO test structure, call parseAnnotationRow with vector from
710 // hashtable for specific sequence
713 // Get an object with all the content for an annotation
714 if (ann.containsKey("features"))
716 // logger.debug("Found features for " + acc);
717 features = (Hashtable) ann.get("features");
721 // logger.debug("Creating new features holder for " + acc);
722 features = new Hashtable();
723 ann.put("features", features);
727 if (features.containsKey(this.id2type(type)))
729 // logger.debug("Found content for " + this.id2type(type));
730 content = (Hashtable) features
731 .get(this.id2type(type));
735 // logger.debug("Creating new content holder for " +
736 // this.id2type(type));
737 content = new Hashtable();
738 features.put(id2type(type), content);
740 String ns = (String) content.get(ANNOTATION);
746 // finally, append the annotation line
748 content.put(ANNOTATION, ns);
749 // // end of wrapped annotation block.
750 // // Now a new row is created with the current set of data
753 if (seqAnn.containsKey(acc))
755 strucAnn = (Hashtable) seqAnn.get(acc);
759 strucAnn = new Hashtable();
762 Vector<AlignmentAnnotation> newStruc = new Vector<>();
763 parseAnnotationRow(newStruc, type, ns);
764 for (AlignmentAnnotation alan : newStruc)
766 alan.visible = false;
768 // new annotation overwrites any existing annotation...
770 strucAnn.put(type, newStruc);
771 seqAnn.put(acc, strucAnn);
777 "Warning - couldn't parse sequence annotation row line:\n"
779 // throw new IOException("Error parsing " + line);
784 throw new IOException(MessageManager.formatMessage(
785 "exception.unknown_annotation_detected", new String[]
786 { annType, annContent }));
790 if (treeString.length() > 0)
792 if (treeName == null)
794 treeName = "Tree " + (1 + getTreeCount());
796 addNewickTree(treeName, treeString.toString());
801 * Demangle an accession string and guess the originating sequence database
802 * for a given sequence
805 * sequence to be annotated
807 * Accession string for sequence
809 * source database for alignment (PFAM or RFAM)
811 private void guessDatabaseFor(Sequence seqO, String dbr, String dbsource)
813 DBRefEntry dbrf = null;
814 List<DBRefEntry> dbrs = new ArrayList<>();
815 String seqdb = "Unknown", sdbac = "" + dbr;
816 int st = -1, en = -1, p;
817 if ((st = sdbac.indexOf("/")) > -1)
819 String num, range = sdbac.substring(st + 1);
820 sdbac = sdbac.substring(0, st);
821 if ((p = range.indexOf("-")) > -1)
824 if (p < range.length())
826 num = range.substring(p).trim();
829 en = Integer.parseInt(num);
830 } catch (NumberFormatException x)
832 // could warn here that index is invalid
841 num = range.substring(0, p).trim();
844 st = Integer.parseInt(num);
845 } catch (NumberFormatException x)
847 // could warn here that index is invalid
851 if (dbsource == null)
853 // make up an origin based on whether the sequence looks like it is nucleotide
855 dbsource = (seqO.isProtein()) ? "PFAM" : "RFAM";
857 if (dbsource.equals("PFAM"))
860 if (sdbac.indexOf(".") > -1)
862 // strip of last subdomain
863 sdbac = sdbac.substring(0, sdbac.indexOf("."));
864 dbrf = jalview.util.DBRefUtils.parseToDbRef(seqO, seqdb, dbsource,
871 dbrf = jalview.util.DBRefUtils.parseToDbRef(seqO, dbsource, dbsource,
880 seqdb = "EMBL"; // total guess - could be ENA, or something else these
882 if (sdbac.indexOf(".") > -1)
884 // strip off last subdomain
885 sdbac = sdbac.substring(0, sdbac.indexOf("."));
886 dbrf = jalview.util.DBRefUtils.parseToDbRef(seqO, seqdb, dbsource,
894 dbrf = jalview.util.DBRefUtils.parseToDbRef(seqO, dbsource, dbsource,
901 if (st != -1 && en != -1)
903 for (DBRefEntry d : dbrs)
905 jalview.util.MapList mp = new jalview.util.MapList(
907 { seqO.getStart(), seqO.getEnd() }, new int[] { st, en }, 1,
909 jalview.datamodel.Mapping mping = new Mapping(mp);
915 protected static AlignmentAnnotation parseAnnotationRow(
916 Vector<AlignmentAnnotation> annotation, String label,
919 String convert1, convert2 = null;
920 // String convert1 = OPEN_PAREN.replaceAll(annots);
921 // String convert2 = CLOSE_PAREN.replaceAll(convert1);
922 // annots = convert2;
925 if (label.contains("_cons"))
927 type = (label.indexOf("_cons") == label.length() - 5)
928 ? label.substring(0, label.length() - 5)
931 boolean ss = false, posterior = false;
932 type = id2type(type);
934 boolean isrnass = false;
936 if (type.equalsIgnoreCase("secondary structure"))
939 isrnass = !getRegex(REGEX_NOT_RNASS).search(annots); // sorry about the double
941 // here (it's easier for dealing with
942 // other non-alpha-non-brace chars)
944 if (type.equalsIgnoreCase("posterior probability"))
948 // decide on secondary structure or not.
949 Annotation[] els = new Annotation[annots.length()];
950 for (int i = 0; i < annots.length(); i++)
952 String pos = annots.substring(i, i + 1);
953 if (UNDERSCORE == pos.charAt(0))
958 ann = new Annotation(pos, "", ' ', 0f); // 0f is 'valid' null - will not
962 // if (" .-_".indexOf(pos) == -1)
964 if (isrnass && RNASS_BRACKETS.indexOf(pos) >= 0)
966 ann.secondaryStructure = Rna.getRNASecStrucState(pos).charAt(0);
967 ann.displayCharacter = "" + pos.charAt(0);
971 ann.secondaryStructure = ResidueProperties.getDssp3state(pos)
974 if (ann.secondaryStructure == pos.charAt(0))
976 ann.displayCharacter = ""; // null; // " ";
980 ann.displayCharacter = " " + ann.displayCharacter;
986 if (posterior && !ann.isWhitespace()
987 && !Comparison.isGap(pos.charAt(0)))
990 // symbol encodes values - 0..*==0..10
991 if (pos.charAt(0) == '*')
997 val = pos.charAt(0) - '0';
1008 AlignmentAnnotation annot = null;
1009 Enumeration<AlignmentAnnotation> e = annotation.elements();
1010 while (e.hasMoreElements())
1012 annot = e.nextElement();
1013 if (annot.label.equals(type))
1021 annot = new AlignmentAnnotation(type, type, els);
1022 annotation.addElement(annot);
1026 Annotation[] anns = new Annotation[annot.annotations.length
1028 System.arraycopy(annot.annotations, 0, anns, 0,
1029 annot.annotations.length);
1030 System.arraycopy(els, 0, anns, annot.annotations.length, els.length);
1031 annot.annotations = anns;
1032 // System.out.println("else: ");
1037 private String dbref_to_ac_record(DBRefEntry ref)
1039 return ref.getSource().toString() + " ; "
1040 + ref.getAccessionId().toString();
1044 public String print(SequenceI[] s, boolean jvSuffix)
1046 out = new StringBuffer();
1047 out.append("# STOCKHOLM 1.0");
1048 out.append(newline);
1050 // find max length of id
1054 int slen = s.length;
1056 Hashtable<String, String> dataRef = null;
1057 boolean isAA = s[in].isProtein();
1058 while ((in < slen) && ((seq = s[in]) != null))
1060 String tmp = printId(seq, jvSuffix);
1061 max = Math.max(max, seq.getLength());
1063 if (tmp.length() > maxid)
1065 maxid = tmp.length();
1067 List<DBRefEntry> seqrefs = seq.getDBRefs();
1069 if (seqrefs != null && (ndb = seqrefs.size()) > 0)
1071 if (dataRef == null)
1073 dataRef = new Hashtable<>();
1075 List<DBRefEntry> primrefs = seq.getPrimaryDBRefs();
1076 if (primrefs.size() >= 1)
1078 dataRef.put(tmp, dbref_to_ac_record(primrefs.get(0)));
1082 for (int idb = 0; idb < ndb; idb++)
1084 DBRefEntry dbref = seqrefs.get(idb);
1085 dataRef.put(tmp, dbref_to_ac_record(dbref));
1086 // if we put in a uniprot or EMBL record then we're done:
1087 if ((isAA ? DBRefSource.UNIPROT : DBRefSource.EMBL)
1088 .equals(DBRefUtils.getCanonicalName(dbref.getSource())))
1100 // output database type
1101 if (al.getProperties() != null)
1103 if (!al.getProperties().isEmpty())
1105 Enumeration key = al.getProperties().keys();
1106 Enumeration val = al.getProperties().elements();
1107 while (key.hasMoreElements())
1109 out.append("#=GF " + key.nextElement() + " " + val.nextElement());
1110 out.append(newline);
1115 // output database accessions
1116 if (dataRef != null)
1118 Enumeration<String> en = dataRef.keys();
1119 while (en.hasMoreElements())
1121 Object idd = en.nextElement();
1122 String type = dataRef.remove(idd);
1123 out.append(new Format("%-" + (maxid - 2) + "s")
1124 .form("#=GS " + idd.toString() + " "));
1125 if (isAA && type.contains("UNIPROT")
1126 || (!isAA && type.contains("EMBL")))
1129 out.append(" AC " + type.substring(type.indexOf(";") + 1));
1133 out.append(" DR " + type + " ");
1135 out.append(newline);
1139 // output annotations
1140 while (i < slen && (seq = s[i]) != null)
1142 AlignmentAnnotation[] alAnot = seq.getAnnotation();
1146 for (int j = 0; j < alAnot.length; j++)
1148 if (alAnot[j].annotations != null)
1150 String key = type2id(alAnot[j].label);
1151 boolean isrna = alAnot[j].isValidStruc();
1155 // hardwire to secondary structure if there is RNA secondary
1156 // structure on the annotation
1164 // out.append("#=GR ");
1165 out.append(new Format("%-" + maxid + "s").form(
1166 "#=GR " + printId(s[i], jvSuffix) + " " + key + " "));
1167 ann = alAnot[j].annotations;
1169 for (int k = 0; k < ann.length; k++)
1171 sseq += outputCharacter(key, k, isrna, ann, s[i]);
1174 out.append(newline);
1180 out.append(new Format("%-" + maxid + "s")
1181 .form(printId(seq, jvSuffix) + " "));
1182 out.append(seq.getSequenceAsString());
1183 out.append(newline);
1187 // alignment annotation
1188 AlignmentAnnotation aa;
1189 AlignmentAnnotation[] an = al.getAlignmentAnnotation();
1192 for (int ia = 0, na = an.length; ia < na; ia++)
1195 if (aa.autoCalculated || !aa.visible || aa.sequenceRef != null)
1202 if (aa.label.equals("seq"))
1208 key = type2id(aa.label.toLowerCase());
1215 label = key + "_cons";
1222 label = label.replace(" ", "_");
1225 new Format("%-" + maxid + "s").form("#=GC " + label + " "));
1226 boolean isrna = aa.isValidStruc();
1227 for (int j = 0, nj = aa.annotations.length; j < nj; j++)
1229 sseq += outputCharacter(key, j, isrna, aa.annotations, null);
1232 out.append(newline);
1237 out.append(newline);
1239 return out.toString();
1244 * add an annotation character to the output row
1253 private char outputCharacter(String key, int k, boolean isrna,
1254 Annotation[] ann, SequenceI sequenceI)
1257 Annotation annot = ann[k];
1258 String ch = (annot == null)
1259 ? ((sequenceI == null) ? "-"
1260 : Character.toString(sequenceI.getCharAt(k)))
1261 : (annot.displayCharacter == null
1262 ? String.valueOf(annot.secondaryStructure)
1263 : annot.displayCharacter);
1268 if (key != null && key.equals("SS"))
1270 char ssannotchar = ' ';
1271 boolean charset = false;
1274 // sensible gap character
1280 // valid secondary structure AND no alternative label (e.g. ' B')
1281 if (annot.secondaryStructure > ' ' && ch.length() < 2)
1283 ssannotchar = annot.secondaryStructure;
1289 return (ssannotchar == ' ' && isrna) ? '.' : ssannotchar;
1293 if (ch.length() == 0)
1297 else if (ch.length() == 1)
1301 else if (ch.length() > 1)
1306 return (seq == ' ' && key != null && key.equals("SS") && isrna) ? '.'
1311 * make a friendly ID string.
1314 * @return truncated dataName to after last '/'
1316 private String safeName(String dataName)
1319 while ((b = dataName.indexOf("/")) > -1 && b < dataName.length())
1321 dataName = dataName.substring(b + 1).trim();
1324 int e = (dataName.length() - dataName.indexOf(".")) + 1;
1325 dataName = dataName.substring(1, e).trim();
1330 public String print()
1332 out = new StringBuffer();
1333 out.append("# STOCKHOLM 1.0");
1334 out.append(newline);
1335 print(getSeqsAsArray(), false);
1338 out.append(newline);
1339 return out.toString();
1342 private static Hashtable typeIds = null;
1346 if (typeIds == null)
1348 typeIds = new Hashtable();
1349 typeIds.put("SS", "Secondary Structure");
1350 typeIds.put("SA", "Surface Accessibility");
1351 typeIds.put("TM", "transmembrane");
1352 typeIds.put("PP", "Posterior Probability");
1353 typeIds.put("LI", "ligand binding");
1354 typeIds.put("AS", "active site");
1355 typeIds.put("IN", "intron");
1356 typeIds.put("IR", "interacting residue");
1357 typeIds.put("AC", "accession");
1358 typeIds.put("OS", "organism");
1359 typeIds.put("CL", "class");
1360 typeIds.put("DE", "description");
1361 typeIds.put("DR", "reference");
1362 typeIds.put("LO", "look");
1363 typeIds.put("RF", "Reference Positions");
1368 protected static String id2type(String id)
1370 if (typeIds.containsKey(id))
1372 return (String) typeIds.get(id);
1375 "Warning : Unknown Stockholm annotation type code " + id);
1379 protected static String type2id(String type)
1382 Enumeration e = typeIds.keys();
1383 while (e.hasMoreElements())
1385 Object ll = e.nextElement();
1386 if (typeIds.get(ll).toString().equalsIgnoreCase(type))
1397 "Warning : Unknown Stockholm annotation type: " + type);