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 java.util.Locale;
28 import java.io.BufferedReader;
29 import java.io.FileReader;
30 import java.io.IOException;
31 import java.util.ArrayList;
32 import java.util.Enumeration;
33 import java.util.Hashtable;
34 import java.util.LinkedHashMap;
35 import java.util.List;
37 import java.util.Map.Entry;
38 import java.util.Vector;
40 import com.stevesoft.pat.Regex;
42 import fr.orsay.lri.varna.exceptions.ExceptionUnmatchedClosingParentheses;
43 import fr.orsay.lri.varna.factories.RNAFactory;
44 import fr.orsay.lri.varna.models.rna.RNA;
45 import jalview.analysis.Rna;
46 import jalview.datamodel.AlignmentAnnotation;
47 import jalview.datamodel.AlignmentI;
48 import jalview.datamodel.Annotation;
49 import jalview.datamodel.DBRefEntry;
50 import jalview.datamodel.DBRefSource;
51 import jalview.datamodel.Mapping;
52 import jalview.datamodel.Sequence;
53 import jalview.datamodel.SequenceFeature;
54 import jalview.datamodel.SequenceI;
55 import jalview.schemes.ResidueProperties;
56 import jalview.util.Comparison;
57 import jalview.util.DBRefUtils;
58 import jalview.util.Format;
59 import jalview.util.MessageManager;
61 // import org.apache.log4j.*;
64 * This class is supposed to parse a Stockholm format file into Jalview There
65 * are TODOs in this class: we do not know what the database source and version
66 * is for the file when parsing the #GS= AC tag which associates accessions with
67 * sequences. Database references are also not parsed correctly: a separate
68 * reference string parser must be added to parse the database reference form
69 * into Jalview's local representation.
71 * @author bsb at sanger.ac.uk
72 * @author Natasha Shersnev (Dundee, UK) (Stockholm file writer)
73 * @author Lauren Lui (UCSC, USA) (RNA secondary structure annotation import as
75 * @author Anne Menard (Paris, FR) (VARNA parsing of Stockholm file data)
76 * @version 0.3 + jalview mods
79 public class StockholmFile extends AlignFile
81 private static final String ANNOTATION = "annotation";
83 // private static final Regex OPEN_PAREN = new Regex("(<|\\[)", "(");
85 // private static final Regex CLOSE_PAREN = new Regex("(>|\\])", ")");
87 public static final Regex DETECT_BRACKETS = new Regex(
88 "(<|>|\\[|\\]|\\(|\\)|\\{|\\})");
90 // WUSS extended symbols. Avoid ambiguity with protein SS annotations by using NOT_RNASS first.
91 public static final String RNASS_BRACKETS = "<>[](){}AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz";
93 // use the following regex to decide an annotations (whole) line is NOT an RNA
94 // SS (it contains only E,H,e,h and other non-brace/non-alpha chars)
95 private static final Regex NOT_RNASS = new Regex(
96 "^[^<>[\\](){}A-DF-Za-df-z]*$");
98 StringBuffer out; // output buffer
102 public StockholmFile()
107 * Creates a new StockholmFile object for output.
109 public StockholmFile(AlignmentI al)
114 public StockholmFile(String inFile, DataSourceType type)
120 public StockholmFile(FileParse source) throws IOException
126 public void initData()
132 * Parse a file in Stockholm format into Jalview's data model using VARNA
134 * @throws IOException
135 * If there is an error with the input file
137 public void parse_with_VARNA(java.io.File inFile) throws IOException
139 FileReader fr = null;
140 fr = new FileReader(inFile);
142 BufferedReader r = new BufferedReader(fr);
143 List<RNA> result = null;
146 result = RNAFactory.loadSecStrStockholm(r);
147 } catch (ExceptionUnmatchedClosingParentheses umcp)
149 errormessage = "Unmatched parentheses in annotation. Aborting ("
150 + umcp.getMessage() + ")";
151 throw new IOException(umcp);
153 // DEBUG System.out.println("this is the secondary scructure:"
155 SequenceI[] seqs = new SequenceI[result.size()];
157 for (int i = 0; i < result.size(); i++)
159 // DEBUG System.err.println("Processing i'th sequence in Stockholm file")
160 RNA current = result.get(i);
162 String seq = current.getSeq();
163 String rna = current.getStructDBN(true);
164 // DEBUG System.out.println(seq);
165 // DEBUG System.err.println(rna);
167 int end = seq.length() - 1;
168 id = safeName(getDataName());
169 seqs[i] = new Sequence(id, seq, begin, end);
170 String[] annot = new String[rna.length()];
171 Annotation[] ann = new Annotation[rna.length()];
172 for (int j = 0; j < rna.length(); j++)
174 annot[j] = rna.substring(j, j + 1);
178 for (int k = 0; k < rna.length(); k++)
180 ann[k] = new Annotation(annot[k], "",
181 Rna.getRNASecStrucState(annot[k]).charAt(0), 0f);
184 AlignmentAnnotation align = new AlignmentAnnotation("Sec. str.",
185 current.getID(), ann);
187 seqs[i].addAlignmentAnnotation(align);
188 seqs[i].setRNA(result.get(i));
189 this.annotations.addElement(align);
196 * Parse a file in Stockholm format into Jalview's data model. The file has to
197 * be passed at construction time
199 * @throws IOException
200 * If there is an error with the input file
203 public void parse() throws IOException
205 StringBuffer treeString = new StringBuffer();
206 String treeName = null;
207 // --------------- Variable Definitions -------------------
211 Hashtable seqAnn = new Hashtable(); // Sequence related annotations
212 LinkedHashMap<String, String> seqs = new LinkedHashMap<>();
213 Regex p, r, rend, s, x;
214 // Temporary line for processing RNA annotation
215 // String RNAannot = "";
217 // ------------------ Parsing File ----------------------
218 // First, we have to check that this file has STOCKHOLM format, i.e. the
219 // first line must match
221 r = new Regex("# STOCKHOLM ([\\d\\.]+)");
222 if (!r.search(nextLine()))
224 throw new IOException(MessageManager
225 .getString("exception.stockholm_invalid_format"));
229 version = r.stringMatched(1);
231 // logger.debug("Stockholm version: " + version);
234 // We define some Regexes here that will be used regularily later
235 rend = new Regex("^\\s*\\/\\/"); // Find the end of an alignment
236 p = new Regex("(\\S+)\\/(\\d+)\\-(\\d+)"); // split sequence id in
238 s = new Regex("(\\S+)\\s+(\\S*)\\s+(.*)"); // Parses annotation subtype
239 r = new Regex("#=(G[FSRC]?)\\s+(.*)"); // Finds any annotation line
240 x = new Regex("(\\S+)\\s+(\\S+)"); // split id from sequence
242 // Convert all bracket types to parentheses (necessary for passing to VARNA)
243 Regex openparen = new Regex("(<|\\[)", "(");
244 Regex closeparen = new Regex("(>|\\])", ")");
246 // // Detect if file is RNA by looking for bracket types
247 // Regex detectbrackets = new Regex("(<|>|\\[|\\]|\\(|\\))");
254 openparen.optimize();
255 closeparen.optimize();
257 while ((line = nextLine()) != null)
259 if (line.length() == 0)
263 if (rend.search(line))
265 // End of the alignment, pass stuff back
266 this.noSeqs = seqs.size();
268 String dbsource = null;
269 Regex pf = new Regex("PF[0-9]{5}(.*)"); // Finds AC for Pfam
270 Regex rf = new Regex("RF[0-9]{5}(.*)"); // Finds AC for Rfam
271 if (getAlignmentProperty("AC") != null)
273 String dbType = getAlignmentProperty("AC").toString();
274 if (pf.search(dbType))
276 // PFAM Alignment - so references are typically from Uniprot
279 else if (rf.search(dbType))
284 // logger.debug("Number of sequences: " + this.noSeqs);
285 for (Map.Entry<String, String> skey : seqs.entrySet())
287 // logger.debug("Processing sequence " + acc);
288 String acc = skey.getKey();
289 String seq = skey.getValue();
290 if (maxLength < seq.length())
292 maxLength = seq.length();
298 * Retrieve hash of annotations for this accession Associate
299 * Annotation with accession
301 Hashtable accAnnotations = null;
303 if (seqAnn != null && seqAnn.containsKey(acc))
305 accAnnotations = (Hashtable) seqAnn.remove(acc);
306 // TODO: add structures to sequence
309 // Split accession in id and from/to
312 sid = p.stringMatched(1);
313 start = Integer.parseInt(p.stringMatched(2));
314 end = Integer.parseInt(p.stringMatched(3));
316 // logger.debug(sid + ", " + start + ", " + end);
318 Sequence seqO = new Sequence(sid, seq, start, end);
319 // Add Description (if any)
320 if (accAnnotations != null && accAnnotations.containsKey("DE"))
322 String desc = (String) accAnnotations.get("DE");
323 seqO.setDescription((desc == null) ? "" : desc);
325 // Add DB References (if any)
326 if (accAnnotations != null && accAnnotations.containsKey("DR"))
328 String dbr = (String) accAnnotations.get("DR");
329 if (dbr != null && dbr.indexOf(";") > -1)
331 String src = dbr.substring(0, dbr.indexOf(";"));
332 String acn = dbr.substring(dbr.indexOf(";") + 1);
333 jalview.util.DBRefUtils.parseToDbRef(seqO, src, "0", acn);
337 if (accAnnotations != null && accAnnotations.containsKey("AC"))
339 String dbr = (String) accAnnotations.get("AC");
342 // we could get very clever here - but for now - just try to
343 // guess accession type from type of sequence, source of alignment plus
346 guessDatabaseFor(seqO, dbr, dbsource);
348 // else - do what ? add the data anyway and prompt the user to
349 // specify what references these are ?
352 Hashtable features = null;
353 // We need to adjust the positions of all features to account for gaps
356 features = (Hashtable) accAnnotations.remove("features");
357 } catch (java.lang.NullPointerException e)
359 // loggerwarn("Getting Features for " + acc + ": " +
363 // if we have features
364 if (features != null)
366 int posmap[] = seqO.findPositionMap();
367 Enumeration i = features.keys();
368 while (i.hasMoreElements())
370 // TODO: parse out secondary structure annotation as annotation
372 // TODO: parse out scores as annotation row
373 // TODO: map coding region to core jalview feature types
374 String type = i.nextElement().toString();
375 Hashtable content = (Hashtable) features.remove(type);
377 // add alignment annotation for this feature
378 String key = type2id(type);
381 * have we added annotation rows for this type ?
383 boolean annotsAdded = false;
386 if (accAnnotations != null
387 && accAnnotations.containsKey(key))
389 Vector vv = (Vector) accAnnotations.get(key);
390 for (int ii = 0; ii < vv.size(); ii++)
393 AlignmentAnnotation an = (AlignmentAnnotation) vv
395 seqO.addAlignmentAnnotation(an);
401 Enumeration j = content.keys();
402 while (j.hasMoreElements())
404 String desc = j.nextElement().toString();
405 if (ANNOTATION.equals(desc) && annotsAdded)
407 // don't add features if we already added an annotation row
410 String ns = content.get(desc).toString();
411 char[] byChar = ns.toCharArray();
412 for (int k = 0; k < byChar.length; k++)
415 if (!(c == ' ' || c == '_' || c == '-' || c == '.')) // PFAM
422 int new_pos = posmap[k]; // look up nearest seqeunce
423 // position to this column
424 SequenceFeature feat = new SequenceFeature(type, desc,
425 new_pos, new_pos, null);
427 seqO.addSequenceFeature(feat);
437 // logger.debug("Adding seq " + acc + " from " + start + " to " + end
439 this.seqs.addElement(seqO);
441 return; // finished parsing this segment of source
443 else if (!r.search(line))
445 // System.err.println("Found sequence line: " + line);
447 // Split sequence in sequence and accession parts
450 // logger.error("Could not parse sequence line: " + line);
451 throw new IOException(MessageManager.formatMessage(
452 "exception.couldnt_parse_sequence_line", new String[]
455 String ns = seqs.get(x.stringMatched(1));
460 ns += x.stringMatched(2);
462 seqs.put(x.stringMatched(1), ns);
466 String annType = r.stringMatched(1);
467 String annContent = r.stringMatched(2);
469 // System.err.println("type:" + annType + " content: " + annContent);
471 if (annType.equals("GF"))
474 * Generic per-File annotation, free text Magic features: #=GF NH
475 * <tree in New Hampshire eXtended format> #=GF TN <Unique identifier
476 * for the next tree> Pfam descriptions: 7. DESCRIPTION OF FIELDS
478 * Compulsory fields: ------------------
480 * AC Accession number: Accession number in form PFxxxxx.version or
481 * PBxxxxxx. ID Identification: One word name for family. DE
482 * Definition: Short description of family. AU Author: Authors of the
483 * entry. SE Source of seed: The source suggesting the seed members
484 * belong to one family. GA Gathering method: Search threshold to
485 * build the full alignment. TC Trusted Cutoff: Lowest sequence score
486 * and domain score of match in the full alignment. NC Noise Cutoff:
487 * Highest sequence score and domain score of match not in full
488 * alignment. TP Type: Type of family -- presently Family, Domain,
489 * Motif or Repeat. SQ Sequence: Number of sequences in alignment. AM
490 * Alignment Method The order ls and fs hits are aligned to the model
491 * to build the full align. // End of alignment.
493 * Optional fields: ----------------
495 * DC Database Comment: Comment about database reference. DR Database
496 * Reference: Reference to external database. RC Reference Comment:
497 * Comment about literature reference. RN Reference Number: Reference
498 * Number. RM Reference Medline: Eight digit medline UI number. RT
499 * Reference Title: Reference Title. RA Reference Author: Reference
500 * Author RL Reference Location: Journal location. PI Previous
501 * identifier: Record of all previous ID lines. KW Keywords: Keywords.
502 * CC Comment: Comments. NE Pfam accession: Indicates a nested domain.
503 * NL Location: Location of nested domains - sequence ID, start and
506 * Obsolete fields: ----------- AL Alignment method of seed: The
507 * method used to align the seed members.
509 // Let's save the annotations, maybe we'll be able to do something
510 // with them later...
511 Regex an = new Regex("(\\w+)\\s*(.*)");
512 if (an.search(annContent))
514 if (an.stringMatched(1).equals("NH"))
516 treeString.append(an.stringMatched(2));
518 else if (an.stringMatched(1).equals("TN"))
520 if (treeString.length() > 0)
522 if (treeName == null)
524 treeName = "Tree " + (getTreeCount() + 1);
526 addNewickTree(treeName, treeString.toString());
528 treeName = an.stringMatched(2);
529 treeString = new StringBuffer();
531 // TODO: JAL-3532 - this is where GF comments and database references are lost
532 // suggest overriding this method for Stockholm files to catch and properly
533 // process CC, DR etc into multivalued properties
534 setAlignmentProperty(an.stringMatched(1), an.stringMatched(2));
537 else if (annType.equals("GS"))
539 // Generic per-Sequence annotation, free text
541 * Pfam uses these features: Feature Description ---------------------
542 * ----------- AC <accession> ACcession number DE <freetext>
543 * DEscription DR <db>; <accession>; Database Reference OS <organism>
544 * OrganiSm (species) OC <clade> Organism Classification (clade, etc.)
545 * LO <look> Look (Color, etc.)
547 if (s.search(annContent))
549 String acc = s.stringMatched(1);
550 String type = s.stringMatched(2);
551 String content = s.stringMatched(3);
552 // TODO: store DR in a vector.
553 // TODO: store AC according to generic file db annotation.
555 if (seqAnn.containsKey(acc))
557 ann = (Hashtable) seqAnn.get(acc);
561 ann = new Hashtable();
563 ann.put(type, content);
564 seqAnn.put(acc, ann);
568 // throw new IOException("Error parsing " + line);
569 System.err.println(">> missing annotation: " + line);
572 else if (annType.equals("GC"))
574 // Generic per-Column annotation, exactly 1 char per column
575 // always need a label.
576 if (x.search(annContent))
578 // parse out and create alignment annotation directly.
579 parseAnnotationRow(annotations, x.stringMatched(1),
583 else if (annType.equals("GR"))
585 // Generic per-Sequence AND per-Column markup, exactly 1 char per
588 * Feature Description Markup letters ------- -----------
589 * -------------- SS Secondary Structure [HGIEBTSCX] SA Surface
590 * Accessibility [0-9X] (0=0%-10%; ...; 9=90%-100%) TM TransMembrane
591 * [Mio] PP Posterior Probability [0-9*] (0=0.00-0.05; 1=0.05-0.15;
592 * *=0.95-1.00) LI LIgand binding [*] AS Active Site [*] IN INtron (in
595 if (s.search(annContent))
597 String acc = s.stringMatched(1);
598 String type = s.stringMatched(2);
599 String oseq = s.stringMatched(3);
601 * copy of annotation field that may be processed into whitespace chunks
603 String seq = new String(oseq);
606 // Get an object with all the annotations for this sequence
607 if (seqAnn.containsKey(acc))
609 // logger.debug("Found annotations for " + acc);
610 ann = (Hashtable) seqAnn.get(acc);
614 // logger.debug("Creating new annotations holder for " + acc);
615 ann = new Hashtable();
616 seqAnn.put(acc, ann);
619 // // start of block for appending annotation lines for wrapped
621 // TODO test structure, call parseAnnotationRow with vector from
622 // hashtable for specific sequence
625 // Get an object with all the content for an annotation
626 if (ann.containsKey("features"))
628 // logger.debug("Found features for " + acc);
629 features = (Hashtable) ann.get("features");
633 // logger.debug("Creating new features holder for " + acc);
634 features = new Hashtable();
635 ann.put("features", features);
639 if (features.containsKey(this.id2type(type)))
641 // logger.debug("Found content for " + this.id2type(type));
642 content = (Hashtable) features.get(this.id2type(type));
646 // logger.debug("Creating new content holder for " +
647 // this.id2type(type));
648 content = new Hashtable();
649 features.put(this.id2type(type), content);
651 String ns = (String) content.get(ANNOTATION);
657 // finally, append the annotation line
659 content.put(ANNOTATION, ns);
660 // // end of wrapped annotation block.
661 // // Now a new row is created with the current set of data
664 if (seqAnn.containsKey(acc))
666 strucAnn = (Hashtable) seqAnn.get(acc);
670 strucAnn = new Hashtable();
673 Vector<AlignmentAnnotation> newStruc = new Vector<>();
674 parseAnnotationRow(newStruc, type, ns);
675 for (AlignmentAnnotation alan : newStruc)
677 alan.visible = false;
679 // new annotation overwrites any existing annotation...
681 strucAnn.put(type, newStruc);
682 seqAnn.put(acc, strucAnn);
688 "Warning - couldn't parse sequence annotation row line:\n"
690 // throw new IOException("Error parsing " + line);
695 throw new IOException(MessageManager.formatMessage(
696 "exception.unknown_annotation_detected", new String[]
697 { annType, annContent }));
701 if (treeString.length() > 0)
703 if (treeName == null)
705 treeName = "Tree " + (1 + getTreeCount());
707 addNewickTree(treeName, treeString.toString());
712 * Demangle an accession string and guess the originating sequence database
713 * for a given sequence
716 * sequence to be annotated
718 * Accession string for sequence
720 * source database for alignment (PFAM or RFAM)
722 private void guessDatabaseFor(Sequence seqO, String dbr, String dbsource)
724 DBRefEntry dbrf = null;
725 List<DBRefEntry> dbrs = new ArrayList<>();
726 String seqdb = "Unknown", sdbac = "" + dbr;
727 int st = -1, en = -1, p;
728 if ((st = sdbac.indexOf("/")) > -1)
730 String num, range = sdbac.substring(st + 1);
731 sdbac = sdbac.substring(0, st);
732 if ((p = range.indexOf("-")) > -1)
735 if (p < range.length())
737 num = range.substring(p).trim();
740 en = Integer.parseInt(num);
741 } catch (NumberFormatException x)
743 // could warn here that index is invalid
752 num = range.substring(0, p).trim();
755 st = Integer.parseInt(num);
756 } catch (NumberFormatException x)
758 // could warn here that index is invalid
762 if (dbsource == null)
764 // make up an origin based on whether the sequence looks like it is nucleotide
766 dbsource = (seqO.isProtein()) ? "PFAM" : "RFAM";
768 if (dbsource.equals("PFAM"))
771 if (sdbac.indexOf(".") > -1)
773 // strip of last subdomain
774 sdbac = sdbac.substring(0, sdbac.indexOf("."));
775 dbrf = jalview.util.DBRefUtils.parseToDbRef(seqO, seqdb, dbsource,
782 dbrf = jalview.util.DBRefUtils.parseToDbRef(seqO, dbsource, dbsource,
791 seqdb = "EMBL"; // total guess - could be ENA, or something else these
793 if (sdbac.indexOf(".") > -1)
795 // strip off last subdomain
796 sdbac = sdbac.substring(0, sdbac.indexOf("."));
797 dbrf = jalview.util.DBRefUtils.parseToDbRef(seqO, seqdb, dbsource,
805 dbrf = jalview.util.DBRefUtils.parseToDbRef(seqO, dbsource, dbsource,
812 if (st != -1 && en != -1)
814 for (DBRefEntry d : dbrs)
816 jalview.util.MapList mp = new jalview.util.MapList(
818 { seqO.getStart(), seqO.getEnd() }, new int[] { st, en }, 1,
820 jalview.datamodel.Mapping mping = new Mapping(mp);
826 protected static AlignmentAnnotation parseAnnotationRow(
827 Vector<AlignmentAnnotation> annotation, String label,
830 String convert1, convert2 = null;
832 // convert1 = OPEN_PAREN.replaceAll(annots);
833 // convert2 = CLOSE_PAREN.replaceAll(convert1);
834 // annots = convert2;
837 if (label.contains("_cons"))
839 type = (label.indexOf("_cons") == label.length() - 5)
840 ? label.substring(0, label.length() - 5)
843 boolean ss = false, posterior = false;
844 type = id2type(type);
846 boolean isrnass = false;
847 if (type.equalsIgnoreCase("secondary structure"))
850 isrnass = !NOT_RNASS.search(annots); // sorry about the double negative
851 // here (it's easier for dealing with
852 // other non-alpha-non-brace chars)
854 if (type.equalsIgnoreCase("posterior probability"))
858 // decide on secondary structure or not.
859 Annotation[] els = new Annotation[annots.length()];
860 for (int i = 0; i < annots.length(); i++)
862 String pos = annots.substring(i, i + 1);
864 ann = new Annotation(pos, "", ' ', 0f); // 0f is 'valid' null - will not
868 // if (" .-_".indexOf(pos) == -1)
870 if (isrnass && RNASS_BRACKETS.indexOf(pos) >= 0)
872 ann.secondaryStructure = Rna.getRNASecStrucState(pos).charAt(0);
873 ann.displayCharacter = "" + pos.charAt(0);
877 ann.secondaryStructure = ResidueProperties.getDssp3state(pos)
880 if (ann.secondaryStructure == pos.charAt(0))
882 ann.displayCharacter = ""; // null; // " ";
886 ann.displayCharacter = " " + ann.displayCharacter;
892 if (posterior && !ann.isWhitespace()
893 && !Comparison.isGap(pos.charAt(0)))
896 // symbol encodes values - 0..*==0..10
897 if (pos.charAt(0) == '*')
903 val = pos.charAt(0) - '0';
914 AlignmentAnnotation annot = null;
915 Enumeration<AlignmentAnnotation> e = annotation.elements();
916 while (e.hasMoreElements())
918 annot = e.nextElement();
919 if (annot.label.equals(type))
927 annot = new AlignmentAnnotation(type, type, els);
928 annotation.addElement(annot);
932 Annotation[] anns = new Annotation[annot.annotations.length
934 System.arraycopy(annot.annotations, 0, anns, 0,
935 annot.annotations.length);
936 System.arraycopy(els, 0, anns, annot.annotations.length, els.length);
937 annot.annotations = anns;
938 // System.out.println("else: ");
943 private String dbref_to_ac_record(DBRefEntry ref)
945 return ref.getSource().toString() + " ; "
946 + ref.getAccessionId().toString();
949 public String print(SequenceI[] s, boolean jvSuffix)
951 out = new StringBuffer();
952 out.append("# STOCKHOLM 1.0");
955 // find max length of id
961 Hashtable<String, String> dataRef = null;
962 boolean isAA = s[in].isProtein();
963 while ((in < slen) && ((seq = s[in]) != null))
965 String tmp = printId(seq, jvSuffix);
966 max = Math.max(max, seq.getLength());
968 if (tmp.length() > maxid)
970 maxid = tmp.length();
972 List<DBRefEntry> seqrefs = seq.getDBRefs();
974 if (seqrefs != null && (ndb = seqrefs.size()) > 0)
978 dataRef = new Hashtable<>();
980 List<DBRefEntry> primrefs = seq.getPrimaryDBRefs();
981 if (primrefs.size() >= 1)
983 dataRef.put(tmp, dbref_to_ac_record(primrefs.get(0)));
987 for (int idb = 0; idb < seq.getDBRefs().size(); idb++)
989 DBRefEntry dbref = seq.getDBRefs().get(idb);
990 dataRef.put(tmp, dbref_to_ac_record(dbref));
991 // if we put in a uniprot or EMBL record then we're done:
992 if (isAA && DBRefSource.UNIPROT
993 .equals(DBRefUtils.getCanonicalName(dbref.getSource())))
997 if (!isAA && DBRefSource.EMBL
998 .equals(DBRefUtils.getCanonicalName(dbref.getSource())))
1010 // output database type
1011 if (al.getProperties() != null)
1013 for (Entry<Object, Object> prop : al.getProperties().entrySet())
1015 out.append("#=GF " + prop.getKey().toString() + " "
1016 + prop.getValue().toString());
1017 out.append(newline);
1021 // output database accessions
1022 if (dataRef != null)
1024 Enumeration<String> en = dataRef.keys();
1025 while (en.hasMoreElements())
1027 Object idd = en.nextElement();
1028 String type = dataRef.remove(idd);
1029 out.append(new Format("%-" + (maxid - 2) + "s")
1030 .form("#=GS " + idd.toString() + " "));
1031 if (isAA && type.contains("UNIPROT")
1032 || (!isAA && type.contains("EMBL")))
1035 out.append(" AC " + type.substring(type.indexOf(";") + 1));
1039 out.append(" DR " + type + " ");
1041 out.append(newline);
1045 // output annotations
1046 while (i < slen && (seq = s[i]) != null)
1048 AlignmentAnnotation[] alAnot = seq.getAnnotation();
1052 for (int j = 0, nj = alAnot.length; j < nj; j++)
1055 String key = type2id(alAnot[j].label);
1056 boolean isrna = alAnot[j].isValidStruc();
1060 // hardwire to secondary structure if there is RNA secondary
1061 // structure on the annotation
1070 // out.append("#=GR ");
1071 out.append(new Format("%-" + maxid + "s").form(
1072 "#=GR " + printId(seq, jvSuffix) + " " + key + " "));
1073 ann = alAnot[j].annotations;
1075 for (int k = 0, nk = ann.length; k < nk; k++)
1077 sseq += outputCharacter(key, k, isrna, ann, seq);
1080 out.append(newline);
1084 out.append(new Format("%-" + maxid + "s")
1085 .form(printId(seq, jvSuffix) + " "));
1086 out.append(seq.getSequenceAsString());
1087 out.append(newline);
1091 // alignment annotation
1092 AlignmentAnnotation aa;
1093 AlignmentAnnotation[] an = al.getAlignmentAnnotation();
1096 for (int ia = 0, na = an.length; ia < na; ia++)
1099 if (aa.autoCalculated || !aa.visible || aa.sequenceRef != null)
1106 if (aa.label.equals("seq"))
1112 key = type2id(aa.label.toLowerCase(Locale.ROOT));
1119 label = key + "_cons";
1126 label = label.replace(" ", "_");
1129 new Format("%-" + maxid + "s").form("#=GC " + label + " "));
1130 boolean isrna = aa.isValidStruc();
1131 for (int j = 0, nj = aa.annotations.length; j < nj; j++)
1133 sseq += outputCharacter(key, j, isrna, aa.annotations, null);
1136 out.append(newline);
1141 out.append(newline);
1143 return out.toString();
1147 * add an annotation character to the output row
1156 private char outputCharacter(String key, int k, boolean isrna,
1157 Annotation[] ann, SequenceI sequenceI)
1160 Annotation annot = ann[k];
1161 String ch = (annot == null)
1162 ? ((sequenceI == null) ? "-"
1163 : Character.toString(sequenceI.getCharAt(k)))
1164 : (annot.displayCharacter == null
1165 ? String.valueOf(annot.secondaryStructure)
1166 : annot.displayCharacter);
1171 if (key != null && key.equals("SS"))
1173 char ssannotchar = ' ';
1174 boolean charset = false;
1177 // sensible gap character
1183 // valid secondary structure AND no alternative label (e.g. ' B')
1184 if (annot.secondaryStructure > ' ' && ch.length() < 2)
1186 ssannotchar = annot.secondaryStructure;
1192 return (ssannotchar == ' ' && isrna) ? '.' : ssannotchar;
1196 if (ch.length() == 0)
1200 else if (ch.length() == 1)
1204 else if (ch.length() > 1)
1209 return (seq == ' ' && key != null && key.equals("SS") && isrna) ? '.'
1213 public String print()
1215 out = new StringBuffer();
1216 out.append("# STOCKHOLM 1.0");
1217 out.append(newline);
1218 print(getSeqsAsArray(), false);
1221 out.append(newline);
1222 return out.toString();
1225 private static Hashtable typeIds = null;
1229 if (typeIds == null)
1231 typeIds = new Hashtable();
1232 typeIds.put("SS", "Secondary Structure");
1233 typeIds.put("SA", "Surface Accessibility");
1234 typeIds.put("TM", "transmembrane");
1235 typeIds.put("PP", "Posterior Probability");
1236 typeIds.put("LI", "ligand binding");
1237 typeIds.put("AS", "active site");
1238 typeIds.put("IN", "intron");
1239 typeIds.put("IR", "interacting residue");
1240 typeIds.put("AC", "accession");
1241 typeIds.put("OS", "organism");
1242 typeIds.put("CL", "class");
1243 typeIds.put("DE", "description");
1244 typeIds.put("DR", "reference");
1245 typeIds.put("LO", "look");
1246 typeIds.put("RF", "Reference Positions");
1251 protected static String id2type(String id)
1253 if (typeIds.containsKey(id))
1255 return (String) typeIds.get(id);
1258 "Warning : Unknown Stockholm annotation type code " + id);
1262 protected static String type2id(String type)
1265 Enumeration e = typeIds.keys();
1266 while (e.hasMoreElements())
1268 Object ll = e.nextElement();
1269 if (typeIds.get(ll).toString().equalsIgnoreCase(type))
1280 "Warning : Unknown Stockholm annotation type: " + type);
1285 * make a friendly ID string.
1288 * @return truncated dataName to after last '/'
1290 private String safeName(String dataName)
1293 while ((b = dataName.indexOf("/")) > -1 && b < dataName.length())
1295 dataName = dataName.substring(b + 1).trim();
1298 int e = (dataName.length() - dataName.indexOf(".")) + 1;
1299 dataName = dataName.substring(1, e).trim();