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.io.BufferedReader;
27 import java.io.FileReader;
28 import java.io.IOException;
29 import java.util.ArrayList;
30 import java.util.Enumeration;
31 import java.util.Hashtable;
32 import java.util.LinkedHashMap;
33 import java.util.List;
35 import java.util.Vector;
37 import com.stevesoft.pat.Regex;
39 import fr.orsay.lri.varna.exceptions.ExceptionUnmatchedClosingParentheses;
40 import fr.orsay.lri.varna.factories.RNAFactory;
41 import fr.orsay.lri.varna.models.rna.RNA;
42 import jalview.analysis.Rna;
43 import jalview.datamodel.AlignmentAnnotation;
44 import jalview.datamodel.AlignmentI;
45 import jalview.datamodel.Annotation;
46 import jalview.datamodel.DBRefEntry;
47 import jalview.datamodel.DBRefSource;
48 import jalview.datamodel.Mapping;
49 import jalview.datamodel.Sequence;
50 import jalview.datamodel.SequenceFeature;
51 import jalview.datamodel.SequenceI;
52 import jalview.schemes.ResidueProperties;
53 import jalview.util.Comparison;
54 import jalview.util.DBRefUtils;
55 import jalview.util.Format;
56 import jalview.util.MessageManager;
58 // import org.apache.log4j.*;
61 * This class is supposed to parse a Stockholm format file into Jalview There
62 * are TODOs in this class: we do not know what the database source and version
63 * is for the file when parsing the #GS= AC tag which associates accessions with
64 * sequences. Database references are also not parsed correctly: a separate
65 * reference string parser must be added to parse the database reference form
66 * into Jalview's local representation.
68 * @author bsb at sanger.ac.uk
69 * @author Natasha Shersnev (Dundee, UK) (Stockholm file writer)
70 * @author Lauren Lui (UCSC, USA) (RNA secondary structure annotation import as
72 * @author Anne Menard (Paris, FR) (VARNA parsing of Stockholm file data)
73 * @version 0.3 + jalview mods
76 public class StockholmFile extends AlignFile
78 private static final String ANNOTATION = "annotation";
80 // private static final Regex OPEN_PAREN = new Regex("(<|\\[)", "(");
82 // private static final Regex CLOSE_PAREN = new Regex("(>|\\])", ")");
84 public static final Regex DETECT_BRACKETS = new Regex(
85 "(<|>|\\[|\\]|\\(|\\)|\\{|\\})");
87 // WUSS extended symbols. Avoid ambiguity with protein SS annotations by using NOT_RNASS first.
88 public static final String RNASS_BRACKETS = "<>[](){}AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz";
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 private static final Regex NOT_RNASS = new Regex(
93 "^[^<>[\\](){}A-DF-Za-df-z]*$");
95 StringBuffer out; // output buffer
99 public StockholmFile()
104 * Creates a new StockholmFile object for output.
106 public StockholmFile(AlignmentI al)
111 public StockholmFile(String inFile, DataSourceType type)
117 public StockholmFile(FileParse source) throws IOException
123 public void initData()
129 * Parse a file in Stockholm format into Jalview's data model using VARNA
131 * @throws IOException
132 * If there is an error with the input file
134 public void parse_with_VARNA(java.io.File inFile) throws IOException
136 FileReader fr = null;
137 fr = new FileReader(inFile);
139 BufferedReader r = new BufferedReader(fr);
140 List<RNA> result = null;
143 result = RNAFactory.loadSecStrStockholm(r);
144 } catch (ExceptionUnmatchedClosingParentheses umcp)
146 errormessage = "Unmatched parentheses in annotation. Aborting ("
147 + umcp.getMessage() + ")";
148 throw new IOException(umcp);
150 // DEBUG System.out.println("this is the secondary scructure:"
152 SequenceI[] seqs = new SequenceI[result.size()];
154 for (int i = 0; i < result.size(); i++)
156 // DEBUG System.err.println("Processing i'th sequence in Stockholm file")
157 RNA current = result.get(i);
159 String seq = current.getSeq();
160 String rna = current.getStructDBN(true);
161 // DEBUG System.out.println(seq);
162 // DEBUG System.err.println(rna);
164 int end = seq.length() - 1;
165 id = safeName(getDataName());
166 seqs[i] = new Sequence(id, seq, begin, end);
167 String[] annot = new String[rna.length()];
168 Annotation[] ann = new Annotation[rna.length()];
169 for (int j = 0; j < rna.length(); j++)
171 annot[j] = rna.substring(j, j + 1);
175 for (int k = 0; k < rna.length(); k++)
177 ann[k] = new Annotation(annot[k], "",
178 Rna.getRNASecStrucState(annot[k]).charAt(0), 0f);
181 AlignmentAnnotation align = new AlignmentAnnotation("Sec. str.",
182 current.getID(), ann);
184 seqs[i].addAlignmentAnnotation(align);
185 seqs[i].setRNA(result.get(i));
186 this.annotations.addElement(align);
193 * Parse a file in Stockholm format into Jalview's data model. The file has to
194 * be passed at construction time
196 * @throws IOException
197 * If there is an error with the input file
200 public void parse() throws IOException
202 StringBuffer treeString = new StringBuffer();
203 String treeName = null;
204 // --------------- Variable Definitions -------------------
208 Hashtable seqAnn = new Hashtable(); // Sequence related annotations
209 LinkedHashMap<String, String> seqs = new LinkedHashMap<>();
210 Regex p, r, rend, s, x;
211 // Temporary line for processing RNA annotation
212 // String RNAannot = "";
214 // ------------------ Parsing File ----------------------
215 // First, we have to check that this file has STOCKHOLM format, i.e. the
216 // first line must match
218 r = new Regex("# STOCKHOLM ([\\d\\.]+)");
219 if (!r.search(nextLine()))
221 throw new IOException(MessageManager
222 .getString("exception.stockholm_invalid_format"));
226 version = r.stringMatched(1);
228 // logger.debug("Stockholm version: " + version);
231 // We define some Regexes here that will be used regularily later
232 rend = new Regex("^\\s*\\/\\/"); // Find the end of an alignment
233 p = new Regex("(\\S+)\\/(\\d+)\\-(\\d+)"); // split sequence id in
235 s = new Regex("(\\S+)\\s+(\\S*)\\s+(.*)"); // Parses annotation subtype
236 r = new Regex("#=(G[FSRC]?)\\s+(.*)"); // Finds any annotation line
237 x = new Regex("(\\S+)\\s+(\\S+)"); // split id from sequence
239 // Convert all bracket types to parentheses (necessary for passing to VARNA)
240 Regex openparen = new Regex("(<|\\[)", "(");
241 Regex closeparen = new Regex("(>|\\])", ")");
243 // // Detect if file is RNA by looking for bracket types
244 // Regex detectbrackets = new Regex("(<|>|\\[|\\]|\\(|\\))");
251 openparen.optimize();
252 closeparen.optimize();
254 while ((line = nextLine()) != null)
256 if (line.length() == 0)
260 if (rend.search(line))
262 // End of the alignment, pass stuff back
263 this.noSeqs = seqs.size();
265 String dbsource = null;
266 Regex pf = new Regex("PF[0-9]{5}(.*)"); // Finds AC for Pfam
267 Regex rf = new Regex("RF[0-9]{5}(.*)"); // Finds AC for Rfam
268 if (getAlignmentProperty("AC") != null)
270 String dbType = getAlignmentProperty("AC").toString();
271 if (pf.search(dbType))
273 // PFAM Alignment - so references are typically from Uniprot
276 else if (rf.search(dbType))
281 // logger.debug("Number of sequences: " + this.noSeqs);
282 for (Map.Entry<String, String> skey : seqs.entrySet())
284 // logger.debug("Processing sequence " + acc);
285 String acc = skey.getKey();
286 String seq = skey.getValue();
287 if (maxLength < seq.length())
289 maxLength = seq.length();
295 * Retrieve hash of annotations for this accession Associate
296 * Annotation with accession
298 Hashtable accAnnotations = null;
300 if (seqAnn != null && seqAnn.containsKey(acc))
302 accAnnotations = (Hashtable) seqAnn.remove(acc);
303 // TODO: add structures to sequence
306 // Split accession in id and from/to
309 sid = p.stringMatched(1);
310 start = Integer.parseInt(p.stringMatched(2));
311 end = Integer.parseInt(p.stringMatched(3));
313 // logger.debug(sid + ", " + start + ", " + end);
315 Sequence seqO = new Sequence(sid, seq, start, end);
316 // Add Description (if any)
317 if (accAnnotations != null && accAnnotations.containsKey("DE"))
319 String desc = (String) accAnnotations.get("DE");
320 seqO.setDescription((desc == null) ? "" : desc);
322 // Add DB References (if any)
323 if (accAnnotations != null && accAnnotations.containsKey("DR"))
325 String dbr = (String) accAnnotations.get("DR");
326 if (dbr != null && dbr.indexOf(";") > -1)
328 String src = dbr.substring(0, dbr.indexOf(";"));
329 String acn = dbr.substring(dbr.indexOf(";") + 1);
330 jalview.util.DBRefUtils.parseToDbRef(seqO, src, "0", acn);
334 if (accAnnotations != null && accAnnotations.containsKey("AC"))
336 String dbr = (String) accAnnotations.get("AC");
339 // we could get very clever here - but for now - just try to
340 // guess accession type from type of sequence, source of alignment plus
343 guessDatabaseFor(seqO, dbr, dbsource);
345 // else - do what ? add the data anyway and prompt the user to
346 // specify what references these are ?
349 Hashtable features = null;
350 // We need to adjust the positions of all features to account for gaps
353 features = (Hashtable) accAnnotations.remove("features");
354 } catch (java.lang.NullPointerException e)
356 // loggerwarn("Getting Features for " + acc + ": " +
360 // if we have features
361 if (features != null)
363 int posmap[] = seqO.findPositionMap();
364 Enumeration i = features.keys();
365 while (i.hasMoreElements())
367 // TODO: parse out secondary structure annotation as annotation
369 // TODO: parse out scores as annotation row
370 // TODO: map coding region to core jalview feature types
371 String type = i.nextElement().toString();
372 Hashtable content = (Hashtable) features.remove(type);
374 // add alignment annotation for this feature
375 String key = type2id(type);
378 * have we added annotation rows for this type ?
380 boolean annotsAdded = false;
383 if (accAnnotations != null
384 && accAnnotations.containsKey(key))
386 Vector vv = (Vector) accAnnotations.get(key);
387 for (int ii = 0; ii < vv.size(); ii++)
390 AlignmentAnnotation an = (AlignmentAnnotation) vv
392 seqO.addAlignmentAnnotation(an);
398 Enumeration j = content.keys();
399 while (j.hasMoreElements())
401 String desc = j.nextElement().toString();
402 if (ANNOTATION.equals(desc) && annotsAdded)
404 // don't add features if we already added an annotation row
407 String ns = content.get(desc).toString();
408 char[] byChar = ns.toCharArray();
409 for (int k = 0; k < byChar.length; k++)
412 if (!(c == ' ' || c == '_' || c == '-' || c == '.')) // PFAM
419 int new_pos = posmap[k]; // look up nearest seqeunce
420 // position to this column
421 SequenceFeature feat = new SequenceFeature(type, desc,
422 new_pos, new_pos, null);
424 seqO.addSequenceFeature(feat);
434 // logger.debug("Adding seq " + acc + " from " + start + " to " + end
436 this.seqs.addElement(seqO);
438 return; // finished parsing this segment of source
440 else if (!r.search(line))
442 // System.err.println("Found sequence line: " + line);
444 // Split sequence in sequence and accession parts
447 // logger.error("Could not parse sequence line: " + line);
448 throw new IOException(MessageManager.formatMessage(
449 "exception.couldnt_parse_sequence_line", new String[]
452 String ns = seqs.get(x.stringMatched(1));
457 ns += x.stringMatched(2);
459 seqs.put(x.stringMatched(1), ns);
463 String annType = r.stringMatched(1);
464 String annContent = r.stringMatched(2);
466 // System.err.println("type:" + annType + " content: " + annContent);
468 if (annType.equals("GF"))
471 * Generic per-File annotation, free text Magic features: #=GF NH
472 * <tree in New Hampshire eXtended format> #=GF TN <Unique identifier
473 * for the next tree> Pfam descriptions: 7. DESCRIPTION OF FIELDS
475 * Compulsory fields: ------------------
477 * AC Accession number: Accession number in form PFxxxxx.version or
478 * PBxxxxxx. ID Identification: One word name for family. DE
479 * Definition: Short description of family. AU Author: Authors of the
480 * entry. SE Source of seed: The source suggesting the seed members
481 * belong to one family. GA Gathering method: Search threshold to
482 * build the full alignment. TC Trusted Cutoff: Lowest sequence score
483 * and domain score of match in the full alignment. NC Noise Cutoff:
484 * Highest sequence score and domain score of match not in full
485 * alignment. TP Type: Type of family -- presently Family, Domain,
486 * Motif or Repeat. SQ Sequence: Number of sequences in alignment. AM
487 * Alignment Method The order ls and fs hits are aligned to the model
488 * to build the full align. // End of alignment.
490 * Optional fields: ----------------
492 * DC Database Comment: Comment about database reference. DR Database
493 * Reference: Reference to external database. RC Reference Comment:
494 * Comment about literature reference. RN Reference Number: Reference
495 * Number. RM Reference Medline: Eight digit medline UI number. RT
496 * Reference Title: Reference Title. RA Reference Author: Reference
497 * Author RL Reference Location: Journal location. PI Previous
498 * identifier: Record of all previous ID lines. KW Keywords: Keywords.
499 * CC Comment: Comments. NE Pfam accession: Indicates a nested domain.
500 * NL Location: Location of nested domains - sequence ID, start and
503 * Obsolete fields: ----------- AL Alignment method of seed: The
504 * method used to align the seed members.
506 // Let's save the annotations, maybe we'll be able to do something
507 // with them later...
508 Regex an = new Regex("(\\w+)\\s*(.*)");
509 if (an.search(annContent))
511 if (an.stringMatched(1).equals("NH"))
513 treeString.append(an.stringMatched(2));
515 else if (an.stringMatched(1).equals("TN"))
517 if (treeString.length() > 0)
519 if (treeName == null)
521 treeName = "Tree " + (getTreeCount() + 1);
523 addNewickTree(treeName, treeString.toString());
525 treeName = an.stringMatched(2);
526 treeString = new StringBuffer();
528 // TODO: JAL-3532 - this is where GF comments and database references are lost
529 // suggest overriding this method for Stockholm files to catch and properly
530 // process CC, DR etc into multivalued properties
531 setAlignmentProperty(an.stringMatched(1), an.stringMatched(2));
534 else if (annType.equals("GS"))
536 // Generic per-Sequence annotation, free text
538 * Pfam uses these features: Feature Description ---------------------
539 * ----------- AC <accession> ACcession number DE <freetext>
540 * DEscription DR <db>; <accession>; Database Reference OS <organism>
541 * OrganiSm (species) OC <clade> Organism Classification (clade, etc.)
542 * LO <look> Look (Color, etc.)
544 if (s.search(annContent))
546 String acc = s.stringMatched(1);
547 String type = s.stringMatched(2);
548 String content = s.stringMatched(3);
549 // TODO: store DR in a vector.
550 // TODO: store AC according to generic file db annotation.
552 if (seqAnn.containsKey(acc))
554 ann = (Hashtable) seqAnn.get(acc);
558 ann = new Hashtable();
560 ann.put(type, content);
561 seqAnn.put(acc, ann);
565 // throw new IOException("Error parsing " + line);
566 System.err.println(">> missing annotation: " + line);
569 else if (annType.equals("GC"))
571 // Generic per-Column annotation, exactly 1 char per column
572 // always need a label.
573 if (x.search(annContent))
575 // parse out and create alignment annotation directly.
576 parseAnnotationRow(annotations, x.stringMatched(1),
580 else if (annType.equals("GR"))
582 // Generic per-Sequence AND per-Column markup, exactly 1 char per
585 * Feature Description Markup letters ------- -----------
586 * -------------- SS Secondary Structure [HGIEBTSCX] SA Surface
587 * Accessibility [0-9X] (0=0%-10%; ...; 9=90%-100%) TM TransMembrane
588 * [Mio] PP Posterior Probability [0-9*] (0=0.00-0.05; 1=0.05-0.15;
589 * *=0.95-1.00) LI LIgand binding [*] AS Active Site [*] IN INtron (in
592 if (s.search(annContent))
594 String acc = s.stringMatched(1);
595 String type = s.stringMatched(2);
596 String oseq = s.stringMatched(3);
598 * copy of annotation field that may be processed into whitespace chunks
600 String seq = new String(oseq);
603 // Get an object with all the annotations for this sequence
604 if (seqAnn.containsKey(acc))
606 // logger.debug("Found annotations for " + acc);
607 ann = (Hashtable) seqAnn.get(acc);
611 // logger.debug("Creating new annotations holder for " + acc);
612 ann = new Hashtable();
613 seqAnn.put(acc, ann);
616 // // start of block for appending annotation lines for wrapped
618 // TODO test structure, call parseAnnotationRow with vector from
619 // hashtable for specific sequence
622 // Get an object with all the content for an annotation
623 if (ann.containsKey("features"))
625 // logger.debug("Found features for " + acc);
626 features = (Hashtable) ann.get("features");
630 // logger.debug("Creating new features holder for " + acc);
631 features = new Hashtable();
632 ann.put("features", features);
636 if (features.containsKey(this.id2type(type)))
638 // logger.debug("Found content for " + this.id2type(type));
639 content = (Hashtable) features.get(this.id2type(type));
643 // logger.debug("Creating new content holder for " +
644 // this.id2type(type));
645 content = new Hashtable();
646 features.put(this.id2type(type), content);
648 String ns = (String) content.get(ANNOTATION);
654 // finally, append the annotation line
656 content.put(ANNOTATION, ns);
657 // // end of wrapped annotation block.
658 // // Now a new row is created with the current set of data
661 if (seqAnn.containsKey(acc))
663 strucAnn = (Hashtable) seqAnn.get(acc);
667 strucAnn = new Hashtable();
670 Vector<AlignmentAnnotation> newStruc = new Vector<>();
671 parseAnnotationRow(newStruc, type, ns);
672 for (AlignmentAnnotation alan : newStruc)
674 alan.visible = false;
676 // new annotation overwrites any existing annotation...
678 strucAnn.put(type, newStruc);
679 seqAnn.put(acc, strucAnn);
685 "Warning - couldn't parse sequence annotation row line:\n"
687 // throw new IOException("Error parsing " + line);
692 throw new IOException(MessageManager.formatMessage(
693 "exception.unknown_annotation_detected", new String[]
694 { annType, annContent }));
698 if (treeString.length() > 0)
700 if (treeName == null)
702 treeName = "Tree " + (1 + getTreeCount());
704 addNewickTree(treeName, treeString.toString());
709 * Demangle an accession string and guess the originating sequence database
710 * for a given sequence
713 * sequence to be annotated
715 * Accession string for sequence
717 * source database for alignment (PFAM or RFAM)
719 private void guessDatabaseFor(Sequence seqO, String dbr, String dbsource)
721 DBRefEntry dbrf = null;
722 List<DBRefEntry> dbrs = new ArrayList<>();
723 String seqdb = "Unknown", sdbac = "" + dbr;
724 int st = -1, en = -1, p;
725 if ((st = sdbac.indexOf("/")) > -1)
727 String num, range = sdbac.substring(st + 1);
728 sdbac = sdbac.substring(0, st);
729 if ((p = range.indexOf("-")) > -1)
732 if (p < range.length())
734 num = range.substring(p).trim();
737 en = Integer.parseInt(num);
738 } catch (NumberFormatException x)
740 // could warn here that index is invalid
749 num = range.substring(0, p).trim();
752 st = Integer.parseInt(num);
753 } catch (NumberFormatException x)
755 // could warn here that index is invalid
759 if (dbsource == null)
761 // make up an origin based on whether the sequence looks like it is nucleotide
763 dbsource = (seqO.isProtein()) ? "PFAM" : "RFAM";
765 if (dbsource.equals("PFAM"))
768 if (sdbac.indexOf(".") > -1)
770 // strip of last subdomain
771 sdbac = sdbac.substring(0, sdbac.indexOf("."));
772 dbrf = jalview.util.DBRefUtils.parseToDbRef(seqO, seqdb, dbsource,
779 dbrf = jalview.util.DBRefUtils.parseToDbRef(seqO, dbsource, dbsource,
788 seqdb = "EMBL"; // total guess - could be ENA, or something else these
790 if (sdbac.indexOf(".") > -1)
792 // strip off last subdomain
793 sdbac = sdbac.substring(0, sdbac.indexOf("."));
794 dbrf = jalview.util.DBRefUtils.parseToDbRef(seqO, seqdb, dbsource,
802 dbrf = jalview.util.DBRefUtils.parseToDbRef(seqO, dbsource, dbsource,
809 if (st != -1 && en != -1)
811 for (DBRefEntry d : dbrs)
813 jalview.util.MapList mp = new jalview.util.MapList(
815 { seqO.getStart(), seqO.getEnd() }, new int[] { st, en }, 1,
817 jalview.datamodel.Mapping mping = new Mapping(mp);
823 protected static AlignmentAnnotation parseAnnotationRow(
824 Vector<AlignmentAnnotation> annotation, String label,
827 String convert1, convert2 = null;
829 // convert1 = OPEN_PAREN.replaceAll(annots);
830 // convert2 = CLOSE_PAREN.replaceAll(convert1);
831 // annots = convert2;
834 if (label.contains("_cons"))
836 type = (label.indexOf("_cons") == label.length() - 5)
837 ? label.substring(0, label.length() - 5)
840 boolean ss = false, posterior = false;
841 type = id2type(type);
843 boolean isrnass = false;
844 if (type.equalsIgnoreCase("secondary structure"))
847 isrnass = !NOT_RNASS.search(annots); // sorry about the double negative
848 // here (it's easier for dealing with
849 // other non-alpha-non-brace chars)
851 if (type.equalsIgnoreCase("posterior probability"))
855 // decide on secondary structure or not.
856 Annotation[] els = new Annotation[annots.length()];
857 for (int i = 0; i < annots.length(); i++)
859 String pos = annots.substring(i, i + 1);
861 ann = new Annotation(pos, "", ' ', 0f); // 0f is 'valid' null - will not
865 // if (" .-_".indexOf(pos) == -1)
867 if (isrnass && RNASS_BRACKETS.indexOf(pos) >= 0)
869 ann.secondaryStructure = Rna.getRNASecStrucState(pos).charAt(0);
870 ann.displayCharacter = "" + pos.charAt(0);
874 ann.secondaryStructure = ResidueProperties.getDssp3state(pos)
877 if (ann.secondaryStructure == pos.charAt(0))
879 ann.displayCharacter = ""; // null; // " ";
883 ann.displayCharacter = " " + ann.displayCharacter;
889 if (posterior && !ann.isWhitespace()
890 && !Comparison.isGap(pos.charAt(0)))
893 // symbol encodes values - 0..*==0..10
894 if (pos.charAt(0) == '*')
900 val = pos.charAt(0) - '0';
911 AlignmentAnnotation annot = null;
912 Enumeration<AlignmentAnnotation> e = annotation.elements();
913 while (e.hasMoreElements())
915 annot = e.nextElement();
916 if (annot.label.equals(type))
924 annot = new AlignmentAnnotation(type, type, els);
925 annotation.addElement(annot);
929 Annotation[] anns = new Annotation[annot.annotations.length
931 System.arraycopy(annot.annotations, 0, anns, 0,
932 annot.annotations.length);
933 System.arraycopy(els, 0, anns, annot.annotations.length, els.length);
934 annot.annotations = anns;
935 // System.out.println("else: ");
940 private String dbref_to_ac_record(DBRefEntry ref)
942 return ref.getSource().toString() + " ; "
943 + ref.getAccessionId().toString();
946 public String print(SequenceI[] s, boolean jvSuffix)
948 out = new StringBuffer();
949 out.append("# STOCKHOLM 1.0");
952 // find max length of id
958 Hashtable<String, String> dataRef = null;
959 boolean isAA = s[in].isProtein();
960 while ((in < slen) && ((seq = s[in]) != null))
962 String tmp = printId(seq, jvSuffix);
963 max = Math.max(max, seq.getLength());
965 if (tmp.length() > maxid)
967 maxid = tmp.length();
969 List<DBRefEntry> seqrefs = seq.getDBRefs();
971 if (seqrefs != null && (ndb = seqrefs.size()) > 0)
975 dataRef = new Hashtable<>();
977 List<DBRefEntry> primrefs = seq.getPrimaryDBRefs();
978 if (primrefs.size() >= 1)
980 dataRef.put(tmp, dbref_to_ac_record(primrefs.get(0)));
984 for (int idb = 0; idb < seq.getDBRefs().size(); idb++)
986 DBRefEntry dbref = seq.getDBRefs().get(idb);
987 dataRef.put(tmp, dbref_to_ac_record(dbref));
988 // if we put in a uniprot or EMBL record then we're done:
989 if (isAA && DBRefSource.UNIPROT
990 .equals(DBRefUtils.getCanonicalName(dbref.getSource())))
994 if (!isAA && DBRefSource.EMBL
995 .equals(DBRefUtils.getCanonicalName(dbref.getSource())))
1007 // output database type
1008 if (al.getProperties() != null)
1010 if (!al.getProperties().isEmpty())
1012 Enumeration key = al.getProperties().keys();
1013 Enumeration val = al.getProperties().elements();
1014 while (key.hasMoreElements())
1016 out.append("#=GF " + key.nextElement() + " " + val.nextElement());
1017 out.append(newline);
1022 // output database accessions
1023 if (dataRef != null)
1025 Enumeration<String> en = dataRef.keys();
1026 while (en.hasMoreElements())
1028 Object idd = en.nextElement();
1029 String type = dataRef.remove(idd);
1030 out.append(new Format("%-" + (maxid - 2) + "s")
1031 .form("#=GS " + idd.toString() + " "));
1032 if (isAA && type.contains("UNIPROT")
1033 || (!isAA && type.contains("EMBL")))
1036 out.append(" AC " + type.substring(type.indexOf(";") + 1));
1040 out.append(" DR " + type + " ");
1042 out.append(newline);
1046 // output annotations
1047 while (i < slen && (seq = s[i]) != null)
1049 AlignmentAnnotation[] alAnot = seq.getAnnotation();
1053 for (int j = 0, nj = alAnot.length; j < nj; j++)
1056 String key = type2id(alAnot[j].label);
1057 boolean isrna = alAnot[j].isValidStruc();
1061 // hardwire to secondary structure if there is RNA secondary
1062 // structure on the annotation
1071 // out.append("#=GR ");
1072 out.append(new Format("%-" + maxid + "s").form(
1073 "#=GR " + printId(seq, jvSuffix) + " " + key + " "));
1074 ann = alAnot[j].annotations;
1076 for (int k = 0, nk = ann.length; k < nk; k++)
1078 sseq += outputCharacter(key, k, isrna, ann, seq);
1081 out.append(newline);
1085 out.append(new Format("%-" + maxid + "s")
1086 .form(printId(seq, jvSuffix) + " "));
1087 out.append(seq.getSequenceAsString());
1088 out.append(newline);
1092 // alignment annotation
1093 AlignmentAnnotation aa;
1094 AlignmentAnnotation[] an = al.getAlignmentAnnotation();
1097 for (int ia = 0, na = an.length; ia < na; ia++)
1100 if (aa.autoCalculated || !aa.visible || aa.sequenceRef != null)
1107 if (aa.label.equals("seq"))
1113 key = type2id(aa.label.toLowerCase());
1120 label = key + "_cons";
1127 label = label.replace(" ", "_");
1130 new Format("%-" + maxid + "s").form("#=GC " + label + " "));
1131 boolean isrna = aa.isValidStruc();
1132 for (int j = 0, nj = aa.annotations.length; j < nj; j++)
1134 sseq += outputCharacter(key, j, isrna, aa.annotations, null);
1137 out.append(newline);
1142 out.append(newline);
1144 return out.toString();
1148 * add an annotation character to the output row
1157 private char outputCharacter(String key, int k, boolean isrna,
1158 Annotation[] ann, SequenceI sequenceI)
1161 Annotation annot = ann[k];
1162 String ch = (annot == null)
1163 ? ((sequenceI == null) ? "-"
1164 : Character.toString(sequenceI.getCharAt(k)))
1165 : (annot.displayCharacter == null
1166 ? String.valueOf(annot.secondaryStructure)
1167 : annot.displayCharacter);
1172 if (key != null && key.equals("SS"))
1174 char ssannotchar = ' ';
1175 boolean charset = false;
1178 // sensible gap character
1184 // valid secondary structure AND no alternative label (e.g. ' B')
1185 if (annot.secondaryStructure > ' ' && ch.length() < 2)
1187 ssannotchar = annot.secondaryStructure;
1193 return (ssannotchar == ' ' && isrna) ? '.' : ssannotchar;
1197 if (ch.length() == 0)
1201 else if (ch.length() == 1)
1205 else if (ch.length() > 1)
1210 return (seq == ' ' && key != null && key.equals("SS") && isrna) ? '.'
1214 public String print()
1216 out = new StringBuffer();
1217 out.append("# STOCKHOLM 1.0");
1218 out.append(newline);
1219 print(getSeqsAsArray(), false);
1222 out.append(newline);
1223 return out.toString();
1226 private static Hashtable typeIds = null;
1230 if (typeIds == null)
1232 typeIds = new Hashtable();
1233 typeIds.put("SS", "Secondary Structure");
1234 typeIds.put("SA", "Surface Accessibility");
1235 typeIds.put("TM", "transmembrane");
1236 typeIds.put("PP", "Posterior Probability");
1237 typeIds.put("LI", "ligand binding");
1238 typeIds.put("AS", "active site");
1239 typeIds.put("IN", "intron");
1240 typeIds.put("IR", "interacting residue");
1241 typeIds.put("AC", "accession");
1242 typeIds.put("OS", "organism");
1243 typeIds.put("CL", "class");
1244 typeIds.put("DE", "description");
1245 typeIds.put("DR", "reference");
1246 typeIds.put("LO", "look");
1247 typeIds.put("RF", "Reference Positions");
1252 protected static String id2type(String id)
1254 if (typeIds.containsKey(id))
1256 return (String) typeIds.get(id);
1259 "Warning : Unknown Stockholm annotation type code " + id);
1263 protected static String type2id(String type)
1266 Enumeration e = typeIds.keys();
1267 while (e.hasMoreElements())
1269 Object ll = e.nextElement();
1270 if (typeIds.get(ll).toString().equalsIgnoreCase(type))
1281 "Warning : Unknown Stockholm annotation type: " + type);
1286 * make a friendly ID string.
1289 * @return truncated dataName to after last '/'
1291 private String safeName(String dataName)
1294 while ((b = dataName.indexOf("/")) > -1 && b < dataName.length())
1296 dataName = dataName.substring(b + 1).trim();
1299 int e = (dataName.length() - dataName.indexOf(".")) + 1;
1300 dataName = dataName.substring(1, e).trim();