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.Vector;
39 import com.stevesoft.pat.Regex;
41 import fr.orsay.lri.varna.exceptions.ExceptionUnmatchedClosingParentheses;
42 import fr.orsay.lri.varna.factories.RNAFactory;
43 import fr.orsay.lri.varna.models.rna.RNA;
44 import jalview.analysis.Rna;
45 import jalview.datamodel.AlignmentAnnotation;
46 import jalview.datamodel.AlignmentI;
47 import jalview.datamodel.Annotation;
48 import jalview.datamodel.DBRefEntry;
49 import jalview.datamodel.DBRefSource;
50 import jalview.datamodel.Mapping;
51 import jalview.datamodel.Sequence;
52 import jalview.datamodel.SequenceFeature;
53 import jalview.datamodel.SequenceI;
54 import jalview.schemes.ResidueProperties;
55 import jalview.util.Comparison;
56 import jalview.util.DBRefUtils;
57 import jalview.util.Format;
58 import jalview.util.MessageManager;
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 Regex OPEN_PAREN = new Regex("(<|\\[)", "(");
84 // private static final Regex CLOSE_PAREN = new Regex("(>|\\])", ")");
86 public static final Regex DETECT_BRACKETS = new Regex(
87 "(<|>|\\[|\\]|\\(|\\)|\\{|\\})");
89 // WUSS extended symbols. Avoid ambiguity with protein SS annotations by using NOT_RNASS first.
90 public static final String RNASS_BRACKETS = "<>[](){}AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz";
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 private static final Regex NOT_RNASS = new Regex(
95 "^[^<>[\\](){}A-DF-Za-df-z]*$");
97 StringBuffer out; // output buffer
101 public StockholmFile()
106 * Creates a new StockholmFile object for output.
108 public StockholmFile(AlignmentI al)
113 public StockholmFile(String inFile, DataSourceType type)
119 public StockholmFile(FileParse source) throws IOException
125 public void initData()
131 * Parse a file in Stockholm format into Jalview's data model using VARNA
133 * @throws IOException
134 * If there is an error with the input file
136 public void parse_with_VARNA(java.io.File inFile) throws IOException
138 FileReader fr = null;
139 fr = new FileReader(inFile);
141 BufferedReader r = new BufferedReader(fr);
142 List<RNA> result = null;
145 result = RNAFactory.loadSecStrStockholm(r);
146 } catch (ExceptionUnmatchedClosingParentheses umcp)
148 errormessage = "Unmatched parentheses in annotation. Aborting ("
149 + umcp.getMessage() + ")";
150 throw new IOException(umcp);
152 // DEBUG System.out.println("this is the secondary scructure:"
154 SequenceI[] seqs = new SequenceI[result.size()];
156 for (int i = 0; i < result.size(); i++)
158 // DEBUG System.err.println("Processing i'th sequence in Stockholm file")
159 RNA current = result.get(i);
161 String seq = current.getSeq();
162 String rna = current.getStructDBN(true);
163 // DEBUG System.out.println(seq);
164 // DEBUG System.err.println(rna);
166 int end = seq.length() - 1;
167 id = safeName(getDataName());
168 seqs[i] = new Sequence(id, seq, begin, end);
169 String[] annot = new String[rna.length()];
170 Annotation[] ann = new Annotation[rna.length()];
171 for (int j = 0; j < rna.length(); j++)
173 annot[j] = rna.substring(j, j + 1);
177 for (int k = 0; k < rna.length(); k++)
179 ann[k] = new Annotation(annot[k], "",
180 Rna.getRNASecStrucState(annot[k]).charAt(0), 0f);
183 AlignmentAnnotation align = new AlignmentAnnotation("Sec. str.",
184 current.getID(), ann);
186 seqs[i].addAlignmentAnnotation(align);
187 seqs[i].setRNA(result.get(i));
188 this.annotations.addElement(align);
195 * Parse a file in Stockholm format into Jalview's data model. The file has to
196 * be passed at construction time
198 * @throws IOException
199 * If there is an error with the input file
202 public void parse() throws IOException
204 StringBuffer treeString = new StringBuffer();
205 String treeName = null;
206 // --------------- Variable Definitions -------------------
210 Hashtable seqAnn = new Hashtable(); // Sequence related annotations
211 LinkedHashMap<String, String> seqs = new LinkedHashMap<>();
212 Regex p, r, rend, s, x;
213 // Temporary line for processing RNA annotation
214 // String RNAannot = "";
216 // ------------------ Parsing File ----------------------
217 // First, we have to check that this file has STOCKHOLM format, i.e. the
218 // first line must match
220 r = new Regex("# STOCKHOLM ([\\d\\.]+)");
221 if (!r.search(nextLine()))
223 throw new IOException(MessageManager
224 .getString("exception.stockholm_invalid_format"));
228 version = r.stringMatched(1);
230 // logger.debug("Stockholm version: " + version);
233 // We define some Regexes here that will be used regularily later
234 rend = new Regex("^\\s*\\/\\/"); // Find the end of an alignment
235 p = new Regex("(\\S+)\\/(\\d+)\\-(\\d+)"); // split sequence id in
237 s = new Regex("(\\S+)\\s+(\\S*)\\s+(.*)"); // Parses annotation subtype
238 r = new Regex("#=(G[FSRC]?)\\s+(.*)"); // Finds any annotation line
239 x = new Regex("(\\S+)\\s+(\\S+)"); // split id from sequence
241 // Convert all bracket types to parentheses (necessary for passing to VARNA)
242 Regex openparen = new Regex("(<|\\[)", "(");
243 Regex closeparen = new Regex("(>|\\])", ")");
245 // // Detect if file is RNA by looking for bracket types
246 // Regex detectbrackets = new Regex("(<|>|\\[|\\]|\\(|\\))");
253 openparen.optimize();
254 closeparen.optimize();
256 while ((line = nextLine()) != null)
258 if (line.length() == 0)
262 if (rend.search(line))
264 // End of the alignment, pass stuff back
265 this.noSeqs = seqs.size();
267 String dbsource = null;
268 Regex pf = new Regex("PF[0-9]{5}(.*)"); // Finds AC for Pfam
269 Regex rf = new Regex("RF[0-9]{5}(.*)"); // Finds AC for Rfam
270 if (getAlignmentProperty("AC") != null)
272 String dbType = getAlignmentProperty("AC").toString();
273 if (pf.search(dbType))
275 // PFAM Alignment - so references are typically from Uniprot
278 else if (rf.search(dbType))
283 // logger.debug("Number of sequences: " + this.noSeqs);
284 for (Map.Entry<String, String> skey : seqs.entrySet())
286 // logger.debug("Processing sequence " + acc);
287 String acc = skey.getKey();
288 String seq = skey.getValue();
289 if (maxLength < seq.length())
291 maxLength = seq.length();
297 * Retrieve hash of annotations for this accession Associate
298 * Annotation with accession
300 Hashtable accAnnotations = null;
302 if (seqAnn != null && seqAnn.containsKey(acc))
304 accAnnotations = (Hashtable) seqAnn.remove(acc);
305 // TODO: add structures to sequence
308 // Split accession in id and from/to
311 sid = p.stringMatched(1);
312 start = Integer.parseInt(p.stringMatched(2));
313 end = Integer.parseInt(p.stringMatched(3));
315 // logger.debug(sid + ", " + start + ", " + end);
317 Sequence seqO = new Sequence(sid, seq, start, end);
318 // Add Description (if any)
319 if (accAnnotations != null && accAnnotations.containsKey("DE"))
321 String desc = (String) accAnnotations.get("DE");
322 seqO.setDescription((desc == null) ? "" : desc);
324 // Add DB References (if any)
325 if (accAnnotations != null && accAnnotations.containsKey("DR"))
327 String dbr = (String) accAnnotations.get("DR");
328 if (dbr != null && dbr.indexOf(";") > -1)
330 String src = dbr.substring(0, dbr.indexOf(";"));
331 String acn = dbr.substring(dbr.indexOf(";") + 1);
332 jalview.util.DBRefUtils.parseToDbRef(seqO, src, "0", acn);
336 if (accAnnotations != null && accAnnotations.containsKey("AC"))
338 String dbr = (String) accAnnotations.get("AC");
341 // we could get very clever here - but for now - just try to
342 // guess accession type from type of sequence, source of alignment plus
345 guessDatabaseFor(seqO, dbr, dbsource);
347 // else - do what ? add the data anyway and prompt the user to
348 // specify what references these are ?
351 Hashtable features = null;
352 // We need to adjust the positions of all features to account for gaps
355 features = (Hashtable) accAnnotations.remove("features");
356 } catch (java.lang.NullPointerException e)
358 // loggerwarn("Getting Features for " + acc + ": " +
362 // if we have features
363 if (features != null)
365 int posmap[] = seqO.findPositionMap();
366 Enumeration i = features.keys();
367 while (i.hasMoreElements())
369 // TODO: parse out secondary structure annotation as annotation
371 // TODO: parse out scores as annotation row
372 // TODO: map coding region to core jalview feature types
373 String type = i.nextElement().toString();
374 Hashtable content = (Hashtable) features.remove(type);
376 // add alignment annotation for this feature
377 String key = type2id(type);
380 * have we added annotation rows for this type ?
382 boolean annotsAdded = false;
385 if (accAnnotations != null
386 && accAnnotations.containsKey(key))
388 Vector vv = (Vector) accAnnotations.get(key);
389 for (int ii = 0; ii < vv.size(); ii++)
392 AlignmentAnnotation an = (AlignmentAnnotation) vv
394 seqO.addAlignmentAnnotation(an);
400 Enumeration j = content.keys();
401 while (j.hasMoreElements())
403 String desc = j.nextElement().toString();
404 if (ANNOTATION.equals(desc) && annotsAdded)
406 // don't add features if we already added an annotation row
409 String ns = content.get(desc).toString();
410 char[] byChar = ns.toCharArray();
411 for (int k = 0; k < byChar.length; k++)
414 if (!(c == ' ' || c == '_' || c == '-' || c == '.')) // PFAM
421 int new_pos = posmap[k]; // look up nearest seqeunce
422 // position to this column
423 SequenceFeature feat = new SequenceFeature(type, desc,
424 new_pos, new_pos, null);
426 seqO.addSequenceFeature(feat);
436 // logger.debug("Adding seq " + acc + " from " + start + " to " + end
438 this.seqs.addElement(seqO);
440 return; // finished parsing this segment of source
442 else if (!r.search(line))
444 // System.err.println("Found sequence line: " + line);
446 // Split sequence in sequence and accession parts
449 // logger.error("Could not parse sequence line: " + line);
450 throw new IOException(MessageManager.formatMessage(
451 "exception.couldnt_parse_sequence_line", new String[]
454 String ns = seqs.get(x.stringMatched(1));
459 ns += x.stringMatched(2);
461 seqs.put(x.stringMatched(1), ns);
465 String annType = r.stringMatched(1);
466 String annContent = r.stringMatched(2);
468 // System.err.println("type:" + annType + " content: " + annContent);
470 if (annType.equals("GF"))
473 * Generic per-File annotation, free text Magic features: #=GF NH
474 * <tree in New Hampshire eXtended format> #=GF TN <Unique identifier
475 * for the next tree> Pfam descriptions: 7. DESCRIPTION OF FIELDS
477 * Compulsory fields: ------------------
479 * AC Accession number: Accession number in form PFxxxxx.version or
480 * PBxxxxxx. ID Identification: One word name for family. DE
481 * Definition: Short description of family. AU Author: Authors of the
482 * entry. SE Source of seed: The source suggesting the seed members
483 * belong to one family. GA Gathering method: Search threshold to
484 * build the full alignment. TC Trusted Cutoff: Lowest sequence score
485 * and domain score of match in the full alignment. NC Noise Cutoff:
486 * Highest sequence score and domain score of match not in full
487 * alignment. TP Type: Type of family -- presently Family, Domain,
488 * Motif or Repeat. SQ Sequence: Number of sequences in alignment. AM
489 * Alignment Method The order ls and fs hits are aligned to the model
490 * to build the full align. // End of alignment.
492 * Optional fields: ----------------
494 * DC Database Comment: Comment about database reference. DR Database
495 * Reference: Reference to external database. RC Reference Comment:
496 * Comment about literature reference. RN Reference Number: Reference
497 * Number. RM Reference Medline: Eight digit medline UI number. RT
498 * Reference Title: Reference Title. RA Reference Author: Reference
499 * Author RL Reference Location: Journal location. PI Previous
500 * identifier: Record of all previous ID lines. KW Keywords: Keywords.
501 * CC Comment: Comments. NE Pfam accession: Indicates a nested domain.
502 * NL Location: Location of nested domains - sequence ID, start and
505 * Obsolete fields: ----------- AL Alignment method of seed: The
506 * method used to align the seed members.
508 // Let's save the annotations, maybe we'll be able to do something
509 // with them later...
510 Regex an = new Regex("(\\w+)\\s*(.*)");
511 if (an.search(annContent))
513 if (an.stringMatched(1).equals("NH"))
515 treeString.append(an.stringMatched(2));
517 else if (an.stringMatched(1).equals("TN"))
519 if (treeString.length() > 0)
521 if (treeName == null)
523 treeName = "Tree " + (getTreeCount() + 1);
525 addNewickTree(treeName, treeString.toString());
527 treeName = an.stringMatched(2);
528 treeString = new StringBuffer();
530 // TODO: JAL-3532 - this is where GF comments and database references are lost
531 // suggest overriding this method for Stockholm files to catch and properly
532 // process CC, DR etc into multivalued properties
533 setAlignmentProperty(an.stringMatched(1), an.stringMatched(2));
536 else if (annType.equals("GS"))
538 // Generic per-Sequence annotation, free text
540 * Pfam uses these features: Feature Description ---------------------
541 * ----------- AC <accession> ACcession number DE <freetext>
542 * DEscription DR <db>; <accession>; Database Reference OS <organism>
543 * OrganiSm (species) OC <clade> Organism Classification (clade, etc.)
544 * LO <look> Look (Color, etc.)
546 if (s.search(annContent))
548 String acc = s.stringMatched(1);
549 String type = s.stringMatched(2);
550 String content = s.stringMatched(3);
551 // TODO: store DR in a vector.
552 // TODO: store AC according to generic file db annotation.
554 if (seqAnn.containsKey(acc))
556 ann = (Hashtable) seqAnn.get(acc);
560 ann = new Hashtable();
562 ann.put(type, content);
563 seqAnn.put(acc, ann);
567 // throw new IOException("Error parsing " + line);
568 System.err.println(">> missing annotation: " + line);
571 else if (annType.equals("GC"))
573 // Generic per-Column annotation, exactly 1 char per column
574 // always need a label.
575 if (x.search(annContent))
577 // parse out and create alignment annotation directly.
578 parseAnnotationRow(annotations, x.stringMatched(1),
582 else if (annType.equals("GR"))
584 // Generic per-Sequence AND per-Column markup, exactly 1 char per
587 * Feature Description Markup letters ------- -----------
588 * -------------- SS Secondary Structure [HGIEBTSCX] SA Surface
589 * Accessibility [0-9X] (0=0%-10%; ...; 9=90%-100%) TM TransMembrane
590 * [Mio] PP Posterior Probability [0-9*] (0=0.00-0.05; 1=0.05-0.15;
591 * *=0.95-1.00) LI LIgand binding [*] AS Active Site [*] IN INtron (in
594 if (s.search(annContent))
596 String acc = s.stringMatched(1);
597 String type = s.stringMatched(2);
598 String oseq = s.stringMatched(3);
600 * copy of annotation field that may be processed into whitespace chunks
602 String seq = new String(oseq);
605 // Get an object with all the annotations for this sequence
606 if (seqAnn.containsKey(acc))
608 // logger.debug("Found annotations for " + acc);
609 ann = (Hashtable) seqAnn.get(acc);
613 // logger.debug("Creating new annotations holder for " + acc);
614 ann = new Hashtable();
615 seqAnn.put(acc, ann);
618 // // start of block for appending annotation lines for wrapped
620 // TODO test structure, call parseAnnotationRow with vector from
621 // hashtable for specific sequence
624 // Get an object with all the content for an annotation
625 if (ann.containsKey("features"))
627 // logger.debug("Found features for " + acc);
628 features = (Hashtable) ann.get("features");
632 // logger.debug("Creating new features holder for " + acc);
633 features = new Hashtable();
634 ann.put("features", features);
638 if (features.containsKey(this.id2type(type)))
640 // logger.debug("Found content for " + this.id2type(type));
641 content = (Hashtable) features.get(this.id2type(type));
645 // logger.debug("Creating new content holder for " +
646 // this.id2type(type));
647 content = new Hashtable();
648 features.put(this.id2type(type), content);
650 String ns = (String) content.get(ANNOTATION);
656 // finally, append the annotation line
658 content.put(ANNOTATION, ns);
659 // // end of wrapped annotation block.
660 // // Now a new row is created with the current set of data
663 if (seqAnn.containsKey(acc))
665 strucAnn = (Hashtable) seqAnn.get(acc);
669 strucAnn = new Hashtable();
672 Vector<AlignmentAnnotation> newStruc = new Vector<>();
673 parseAnnotationRow(newStruc, type, ns);
674 for (AlignmentAnnotation alan : newStruc)
676 alan.visible = false;
678 // new annotation overwrites any existing annotation...
680 strucAnn.put(type, newStruc);
681 seqAnn.put(acc, strucAnn);
687 "Warning - couldn't parse sequence annotation row line:\n"
689 // throw new IOException("Error parsing " + line);
694 throw new IOException(MessageManager.formatMessage(
695 "exception.unknown_annotation_detected", new String[]
696 { annType, annContent }));
700 if (treeString.length() > 0)
702 if (treeName == null)
704 treeName = "Tree " + (1 + getTreeCount());
706 addNewickTree(treeName, treeString.toString());
711 * Demangle an accession string and guess the originating sequence database
712 * for a given sequence
715 * sequence to be annotated
717 * Accession string for sequence
719 * source database for alignment (PFAM or RFAM)
721 private void guessDatabaseFor(Sequence seqO, String dbr, String dbsource)
723 DBRefEntry dbrf = null;
724 List<DBRefEntry> dbrs = new ArrayList<>();
725 String seqdb = "Unknown", sdbac = "" + dbr;
726 int st = -1, en = -1, p;
727 if ((st = sdbac.indexOf("/")) > -1)
729 String num, range = sdbac.substring(st + 1);
730 sdbac = sdbac.substring(0, st);
731 if ((p = range.indexOf("-")) > -1)
734 if (p < range.length())
736 num = range.substring(p).trim();
739 en = Integer.parseInt(num);
740 } catch (NumberFormatException x)
742 // could warn here that index is invalid
751 num = range.substring(0, p).trim();
754 st = Integer.parseInt(num);
755 } catch (NumberFormatException x)
757 // could warn here that index is invalid
761 if (dbsource == null)
763 // make up an origin based on whether the sequence looks like it is nucleotide
765 dbsource = (seqO.isProtein()) ? "PFAM" : "RFAM";
767 if (dbsource.equals("PFAM"))
770 if (sdbac.indexOf(".") > -1)
772 // strip of last subdomain
773 sdbac = sdbac.substring(0, sdbac.indexOf("."));
774 dbrf = jalview.util.DBRefUtils.parseToDbRef(seqO, seqdb, dbsource,
781 dbrf = jalview.util.DBRefUtils.parseToDbRef(seqO, dbsource, dbsource,
790 seqdb = "EMBL"; // total guess - could be ENA, or something else these
792 if (sdbac.indexOf(".") > -1)
794 // strip off last subdomain
795 sdbac = sdbac.substring(0, sdbac.indexOf("."));
796 dbrf = jalview.util.DBRefUtils.parseToDbRef(seqO, seqdb, dbsource,
804 dbrf = jalview.util.DBRefUtils.parseToDbRef(seqO, dbsource, dbsource,
811 if (st != -1 && en != -1)
813 for (DBRefEntry d : dbrs)
815 jalview.util.MapList mp = new jalview.util.MapList(
817 { seqO.getStart(), seqO.getEnd() }, new int[] { st, en }, 1,
819 jalview.datamodel.Mapping mping = new Mapping(mp);
825 protected static AlignmentAnnotation parseAnnotationRow(
826 Vector<AlignmentAnnotation> annotation, String label,
829 String convert1, convert2 = null;
831 // convert1 = OPEN_PAREN.replaceAll(annots);
832 // convert2 = CLOSE_PAREN.replaceAll(convert1);
833 // annots = convert2;
836 if (label.contains("_cons"))
838 type = (label.indexOf("_cons") == label.length() - 5)
839 ? label.substring(0, label.length() - 5)
842 boolean ss = false, posterior = false;
843 type = id2type(type);
845 boolean isrnass = false;
846 if (type.equalsIgnoreCase("secondary structure"))
849 isrnass = !NOT_RNASS.search(annots); // sorry about the double negative
850 // here (it's easier for dealing with
851 // other non-alpha-non-brace chars)
853 if (type.equalsIgnoreCase("posterior probability"))
857 // decide on secondary structure or not.
858 Annotation[] els = new Annotation[annots.length()];
859 for (int i = 0; i < annots.length(); i++)
861 String pos = annots.substring(i, i + 1);
863 ann = new Annotation(pos, "", ' ', 0f); // 0f is 'valid' null - will not
867 // if (" .-_".indexOf(pos) == -1)
869 if (isrnass && RNASS_BRACKETS.indexOf(pos) >= 0)
871 ann.secondaryStructure = Rna.getRNASecStrucState(pos).charAt(0);
872 ann.displayCharacter = "" + pos.charAt(0);
876 ann.secondaryStructure = ResidueProperties.getDssp3state(pos)
879 if (ann.secondaryStructure == pos.charAt(0))
881 ann.displayCharacter = ""; // null; // " ";
885 ann.displayCharacter = " " + ann.displayCharacter;
891 if (posterior && !ann.isWhitespace()
892 && !Comparison.isGap(pos.charAt(0)))
895 // symbol encodes values - 0..*==0..10
896 if (pos.charAt(0) == '*')
902 val = pos.charAt(0) - '0';
913 AlignmentAnnotation annot = null;
914 Enumeration<AlignmentAnnotation> e = annotation.elements();
915 while (e.hasMoreElements())
917 annot = e.nextElement();
918 if (annot.label.equals(type))
926 annot = new AlignmentAnnotation(type, type, els);
927 annotation.addElement(annot);
931 Annotation[] anns = new Annotation[annot.annotations.length
933 System.arraycopy(annot.annotations, 0, anns, 0,
934 annot.annotations.length);
935 System.arraycopy(els, 0, anns, annot.annotations.length, els.length);
936 annot.annotations = anns;
937 // System.out.println("else: ");
942 private String dbref_to_ac_record(DBRefEntry ref)
944 return ref.getSource().toString() + " ; "
945 + ref.getAccessionId().toString();
948 public String print(SequenceI[] s, boolean jvSuffix)
950 out = new StringBuffer();
951 out.append("# STOCKHOLM 1.0");
954 // find max length of id
960 Hashtable<String, String> dataRef = null;
961 boolean isAA = s[in].isProtein();
962 while ((in < slen) && ((seq = s[in]) != null))
964 String tmp = printId(seq, jvSuffix);
965 max = Math.max(max, seq.getLength());
967 if (tmp.length() > maxid)
969 maxid = tmp.length();
971 List<DBRefEntry> seqrefs = seq.getDBRefs();
973 if (seqrefs != null && (ndb = seqrefs.size()) > 0)
977 dataRef = new Hashtable<>();
979 List<DBRefEntry> primrefs = seq.getPrimaryDBRefs();
980 if (primrefs.size() >= 1)
982 dataRef.put(tmp, dbref_to_ac_record(primrefs.get(0)));
986 for (int idb = 0; idb < seq.getDBRefs().size(); idb++)
988 DBRefEntry dbref = seq.getDBRefs().get(idb);
989 dataRef.put(tmp, dbref_to_ac_record(dbref));
990 // if we put in a uniprot or EMBL record then we're done:
991 if (isAA && DBRefSource.UNIPROT
992 .equals(DBRefUtils.getCanonicalName(dbref.getSource())))
996 if (!isAA && DBRefSource.EMBL
997 .equals(DBRefUtils.getCanonicalName(dbref.getSource())))
1009 // output database type
1010 if (al.getProperties() != null)
1012 if (!al.getProperties().isEmpty())
1014 Enumeration key = al.getProperties().keys();
1015 Enumeration val = al.getProperties().elements();
1016 while (key.hasMoreElements())
1018 out.append("#=GF " + key.nextElement() + " " + val.nextElement());
1019 out.append(newline);
1024 // output database accessions
1025 if (dataRef != null)
1027 Enumeration<String> en = dataRef.keys();
1028 while (en.hasMoreElements())
1030 Object idd = en.nextElement();
1031 String type = dataRef.remove(idd);
1032 out.append(new Format("%-" + (maxid - 2) + "s")
1033 .form("#=GS " + idd.toString() + " "));
1034 if (isAA && type.contains("UNIPROT")
1035 || (!isAA && type.contains("EMBL")))
1038 out.append(" AC " + type.substring(type.indexOf(";") + 1));
1042 out.append(" DR " + type + " ");
1044 out.append(newline);
1048 // output annotations
1049 while (i < slen && (seq = s[i]) != null)
1051 AlignmentAnnotation[] alAnot = seq.getAnnotation();
1055 for (int j = 0, nj = alAnot.length; j < nj; j++)
1058 String key = type2id(alAnot[j].label);
1059 boolean isrna = alAnot[j].isValidStruc();
1063 // hardwire to secondary structure if there is RNA secondary
1064 // structure on the annotation
1073 // out.append("#=GR ");
1074 out.append(new Format("%-" + maxid + "s").form(
1075 "#=GR " + printId(seq, jvSuffix) + " " + key + " "));
1076 ann = alAnot[j].annotations;
1078 for (int k = 0, nk = ann.length; k < nk; k++)
1080 sseq += outputCharacter(key, k, isrna, ann, seq);
1083 out.append(newline);
1087 out.append(new Format("%-" + maxid + "s")
1088 .form(printId(seq, jvSuffix) + " "));
1089 out.append(seq.getSequenceAsString());
1090 out.append(newline);
1094 // alignment annotation
1095 AlignmentAnnotation aa;
1096 AlignmentAnnotation[] an = al.getAlignmentAnnotation();
1099 for (int ia = 0, na = an.length; ia < na; ia++)
1102 if (aa.autoCalculated || !aa.visible || aa.sequenceRef != null)
1109 if (aa.label.equals("seq"))
1115 key = type2id(aa.label.toLowerCase(Locale.ROOT));
1122 label = key + "_cons";
1129 label = label.replace(" ", "_");
1132 new Format("%-" + maxid + "s").form("#=GC " + label + " "));
1133 boolean isrna = aa.isValidStruc();
1134 for (int j = 0, nj = aa.annotations.length; j < nj; j++)
1136 sseq += outputCharacter(key, j, isrna, aa.annotations, null);
1139 out.append(newline);
1144 out.append(newline);
1146 return out.toString();
1150 * add an annotation character to the output row
1159 private char outputCharacter(String key, int k, boolean isrna,
1160 Annotation[] ann, SequenceI sequenceI)
1163 Annotation annot = ann[k];
1164 String ch = (annot == null)
1165 ? ((sequenceI == null) ? "-"
1166 : Character.toString(sequenceI.getCharAt(k)))
1167 : (annot.displayCharacter == null
1168 ? String.valueOf(annot.secondaryStructure)
1169 : annot.displayCharacter);
1174 if (key != null && key.equals("SS"))
1176 char ssannotchar = ' ';
1177 boolean charset = false;
1180 // sensible gap character
1186 // valid secondary structure AND no alternative label (e.g. ' B')
1187 if (annot.secondaryStructure > ' ' && ch.length() < 2)
1189 ssannotchar = annot.secondaryStructure;
1195 return (ssannotchar == ' ' && isrna) ? '.' : ssannotchar;
1199 if (ch.length() == 0)
1203 else if (ch.length() == 1)
1207 else if (ch.length() > 1)
1212 return (seq == ' ' && key != null && key.equals("SS") && isrna) ? '.'
1216 public String print()
1218 out = new StringBuffer();
1219 out.append("# STOCKHOLM 1.0");
1220 out.append(newline);
1221 print(getSeqsAsArray(), false);
1224 out.append(newline);
1225 return out.toString();
1228 private static Hashtable typeIds = null;
1232 if (typeIds == null)
1234 typeIds = new Hashtable();
1235 typeIds.put("SS", "Secondary Structure");
1236 typeIds.put("SA", "Surface Accessibility");
1237 typeIds.put("TM", "transmembrane");
1238 typeIds.put("PP", "Posterior Probability");
1239 typeIds.put("LI", "ligand binding");
1240 typeIds.put("AS", "active site");
1241 typeIds.put("IN", "intron");
1242 typeIds.put("IR", "interacting residue");
1243 typeIds.put("AC", "accession");
1244 typeIds.put("OS", "organism");
1245 typeIds.put("CL", "class");
1246 typeIds.put("DE", "description");
1247 typeIds.put("DR", "reference");
1248 typeIds.put("LO", "look");
1249 typeIds.put("RF", "Reference Positions");
1254 protected static String id2type(String id)
1256 if (typeIds.containsKey(id))
1258 return (String) typeIds.get(id);
1261 "Warning : Unknown Stockholm annotation type code " + id);
1265 protected static String type2id(String type)
1268 Enumeration e = typeIds.keys();
1269 while (e.hasMoreElements())
1271 Object ll = e.nextElement();
1272 if (typeIds.get(ll).toString().equalsIgnoreCase(type))
1283 "Warning : Unknown Stockholm annotation type: " + type);
1288 * make a friendly ID string.
1291 * @return truncated dataName to after last '/'
1293 private String safeName(String dataName)
1296 while ((b = dataName.indexOf("/")) > -1 && b < dataName.length())
1298 dataName = dataName.substring(b + 1).trim();
1301 int e = (dataName.length() - dataName.indexOf(".")) + 1;
1302 dataName = dataName.substring(1, e).trim();