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;
34 import java.util.Locale;
36 import java.util.Vector;
38 import com.stevesoft.pat.Regex;
40 import fr.orsay.lri.varna.exceptions.ExceptionUnmatchedClosingParentheses;
41 import fr.orsay.lri.varna.factories.RNAFactory;
42 import fr.orsay.lri.varna.models.rna.RNA;
43 import jalview.analysis.Rna;
44 import jalview.datamodel.AlignmentAnnotation;
45 import jalview.datamodel.AlignmentI;
46 import jalview.datamodel.Annotation;
47 import jalview.datamodel.DBRefEntry;
48 import jalview.datamodel.DBRefSource;
49 import jalview.datamodel.Mapping;
50 import jalview.datamodel.Sequence;
51 import jalview.datamodel.SequenceFeature;
52 import jalview.datamodel.SequenceI;
53 import jalview.schemes.ResidueProperties;
54 import jalview.util.Comparison;
55 import jalview.util.DBRefUtils;
56 import jalview.util.Format;
57 import jalview.util.MessageManager;
60 * This class is supposed to parse a Stockholm format file into Jalview There
61 * are TODOs in this class: we do not know what the database source and version
62 * is for the file when parsing the #GS= AC tag which associates accessions with
63 * sequences. Database references are also not parsed correctly: a separate
64 * reference string parser must be added to parse the database reference form
65 * into Jalview's local representation.
67 * @author bsb at sanger.ac.uk
68 * @author Natasha Shersnev (Dundee, UK) (Stockholm file writer)
69 * @author Lauren Lui (UCSC, USA) (RNA secondary structure annotation import as
71 * @author Anne Menard (Paris, FR) (VARNA parsing of Stockholm file data)
72 * @version 0.3 + jalview mods
75 public class StockholmFile extends AlignFile
77 private static final String ANNOTATION = "annotation";
79 // private static final Regex OPEN_PAREN = new Regex("(<|\\[)", "(");
81 // private static final Regex CLOSE_PAREN = new Regex("(>|\\])", ")");
83 public static final Regex DETECT_BRACKETS = new Regex(
84 "(<|>|\\[|\\]|\\(|\\)|\\{|\\})");
86 // WUSS extended symbols. Avoid ambiguity with protein SS annotations by using
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 "^[^<>[\\](){}ADFJ-RUVWYZadfj-ruvwyz]*$");
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 jalview.bin.Console.outPrintln("this is the secondary scructure:"
152 SequenceI[] seqs = new SequenceI[result.size()];
154 for (int i = 0; i < result.size(); i++)
156 // DEBUG jalview.bin.Console.errPrintln("Processing i'th sequence in
158 RNA current = result.get(i);
160 String seq = current.getSeq();
161 String rna = current.getStructDBN(true);
162 // DEBUG jalview.bin.Console.outPrintln(seq);
163 // DEBUG jalview.bin.Console.errPrintln(rna);
165 int end = seq.length() - 1;
166 id = safeName(getDataName());
167 seqs[i] = new Sequence(id, seq, begin, end);
168 String[] annot = new String[rna.length()];
169 Annotation[] ann = new Annotation[rna.length()];
170 for (int j = 0; j < rna.length(); j++)
172 annot[j] = rna.substring(j, j + 1);
176 for (int k = 0; k < rna.length(); k++)
178 ann[k] = new Annotation(annot[k], "",
179 Rna.getRNASecStrucState(annot[k]).charAt(0), 0f);
182 AlignmentAnnotation align = new AlignmentAnnotation("Sec. str.",
183 current.getID(), ann);
185 seqs[i].addAlignmentAnnotation(align);
186 seqs[i].setRNA(result.get(i));
187 this.annotations.addElement(align);
194 * Parse a file in Stockholm format into Jalview's data model. The file has to
195 * be passed at construction time
197 * @throws IOException
198 * If there is an error with the input file
201 public void parse() throws IOException
203 StringBuffer treeString = new StringBuffer();
204 String treeName = null;
205 // --------------- Variable Definitions -------------------
209 Hashtable seqAnn = new Hashtable(); // Sequence related annotations
210 LinkedHashMap<String, String> seqs = new LinkedHashMap<>();
211 Regex p, r, rend, s, x;
212 // Temporary line for processing RNA annotation
213 // String RNAannot = "";
215 // ------------------ Parsing File ----------------------
216 // First, we have to check that this file has STOCKHOLM format, i.e. the
217 // first line must match
219 r = new Regex("# STOCKHOLM ([\\d\\.]+)");
220 if (!r.search(nextLine()))
222 throw new IOException(
223 MessageManager.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
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 // jalview.bin.Console.errPrintln("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 // jalview.bin.Console.errPrintln("type:" + annType + " content: " +
472 if (annType.equals("GF"))
475 * Generic per-File annotation, free text Magic features: #=GF NH
476 * <tree in New Hampshire eXtended format> #=GF TN <Unique identifier
477 * for the next tree> Pfam descriptions: 7. DESCRIPTION OF FIELDS
479 * Compulsory fields: ------------------
481 * AC Accession number: Accession number in form PFxxxxx.version or
482 * PBxxxxxx. ID Identification: One word name for family. DE
483 * Definition: Short description of family. AU Author: Authors of the
484 * entry. SE Source of seed: The source suggesting the seed members
485 * belong to one family. GA Gathering method: Search threshold to
486 * build the full alignment. TC Trusted Cutoff: Lowest sequence score
487 * and domain score of match in the full alignment. NC Noise Cutoff:
488 * Highest sequence score and domain score of match not in full
489 * alignment. TP Type: Type of family -- presently Family, Domain,
490 * Motif or Repeat. SQ Sequence: Number of sequences in alignment. AM
491 * Alignment Method The order ls and fs hits are aligned to the model
492 * to build the full align. // End of alignment.
494 * Optional fields: ----------------
496 * DC Database Comment: Comment about database reference. DR Database
497 * Reference: Reference to external database. RC Reference Comment:
498 * Comment about literature reference. RN Reference Number: Reference
499 * Number. RM Reference Medline: Eight digit medline UI number. RT
500 * Reference Title: Reference Title. RA Reference Author: Reference
501 * Author RL Reference Location: Journal location. PI Previous
502 * identifier: Record of all previous ID lines. KW Keywords: Keywords.
503 * CC Comment: Comments. NE Pfam accession: Indicates a nested domain.
504 * NL Location: Location of nested domains - sequence ID, start and
507 * Obsolete fields: ----------- AL Alignment method of seed: The
508 * method used to align the seed members.
510 // Let's save the annotations, maybe we'll be able to do something
511 // with them later...
512 Regex an = new Regex("(\\w+)\\s*(.*)");
513 if (an.search(annContent))
515 if (an.stringMatched(1).equals("NH"))
517 treeString.append(an.stringMatched(2));
519 else if (an.stringMatched(1).equals("TN"))
521 if (treeString.length() > 0)
523 if (treeName == null)
525 treeName = "Tree " + (getTreeCount() + 1);
527 addNewickTree(treeName, treeString.toString());
529 treeName = an.stringMatched(2);
530 treeString = new StringBuffer();
532 // TODO: JAL-3532 - this is where GF comments and database
533 // references are lost
534 // suggest overriding this method for Stockholm files to catch and
536 // process CC, DR etc into multivalued properties
537 setAlignmentProperty(an.stringMatched(1), an.stringMatched(2));
540 else if (annType.equals("GS"))
542 // Generic per-Sequence annotation, free text
544 * Pfam uses these features: Feature Description ---------------------
545 * ----------- AC <accession> ACcession number DE <freetext>
546 * DEscription DR <db>; <accession>; Database Reference OS <organism>
547 * OrganiSm (species) OC <clade> Organism Classification (clade, etc.)
548 * LO <look> Look (Color, etc.)
550 if (s.search(annContent))
552 String acc = s.stringMatched(1);
553 String type = s.stringMatched(2);
554 String content = s.stringMatched(3);
555 // TODO: store DR in a vector.
556 // TODO: store AC according to generic file db annotation.
558 if (seqAnn.containsKey(acc))
560 ann = (Hashtable) seqAnn.get(acc);
564 ann = new Hashtable();
566 ann.put(type, content);
567 seqAnn.put(acc, ann);
571 // throw new IOException("Error parsing " + line);
573 .errPrintln(">> missing annotation: " + line);
576 else if (annType.equals("GC"))
578 // Generic per-Column annotation, exactly 1 char per column
579 // always need a label.
580 if (x.search(annContent))
582 // parse out and create alignment annotation directly.
583 parseAnnotationRow(annotations, x.stringMatched(1),
587 else if (annType.equals("GR"))
589 // Generic per-Sequence AND per-Column markup, exactly 1 char per
592 * Feature Description Markup letters ------- -----------
593 * -------------- SS Secondary Structure [HGIEBTSCX] SA Surface
594 * Accessibility [0-9X] (0=0%-10%; ...; 9=90%-100%) TM TransMembrane
595 * [Mio] PP Posterior Probability [0-9*] (0=0.00-0.05; 1=0.05-0.15;
596 * *=0.95-1.00) LI LIgand binding [*] AS Active Site [*] IN INtron (in
599 if (s.search(annContent))
601 String acc = s.stringMatched(1);
602 String type = s.stringMatched(2);
603 String oseq = s.stringMatched(3);
605 * copy of annotation field that may be processed into whitespace chunks
607 String seq = new String(oseq);
610 // Get an object with all the annotations for this sequence
611 if (seqAnn.containsKey(acc))
613 // logger.debug("Found annotations for " + acc);
614 ann = (Hashtable) seqAnn.get(acc);
618 // logger.debug("Creating new annotations holder for " + acc);
619 ann = new Hashtable();
620 seqAnn.put(acc, ann);
623 // // start of block for appending annotation lines for wrapped
625 // TODO test structure, call parseAnnotationRow with vector from
626 // hashtable for specific sequence
629 // Get an object with all the content for an annotation
630 if (ann.containsKey("features"))
632 // logger.debug("Found features for " + acc);
633 features = (Hashtable) ann.get("features");
637 // logger.debug("Creating new features holder for " + acc);
638 features = new Hashtable();
639 ann.put("features", features);
643 if (features.containsKey(this.id2type(type)))
645 // logger.debug("Found content for " + this.id2type(type));
646 content = (Hashtable) features.get(this.id2type(type));
650 // logger.debug("Creating new content holder for " +
651 // this.id2type(type));
652 content = new Hashtable();
653 features.put(this.id2type(type), content);
655 String ns = (String) content.get(ANNOTATION);
661 // finally, append the annotation line
663 content.put(ANNOTATION, ns);
664 // // end of wrapped annotation block.
665 // // Now a new row is created with the current set of data
668 if (seqAnn.containsKey(acc))
670 strucAnn = (Hashtable) seqAnn.get(acc);
674 strucAnn = new Hashtable();
677 Vector<AlignmentAnnotation> newStruc = new Vector<>();
678 parseAnnotationRow(newStruc, type, ns);
679 for (AlignmentAnnotation alan : newStruc)
681 alan.visible = false;
683 // new annotation overwrites any existing annotation...
685 strucAnn.put(type, newStruc);
686 seqAnn.put(acc, strucAnn);
691 jalview.bin.Console.errPrintln(
692 "Warning - couldn't parse sequence annotation row line:\n"
694 // throw new IOException("Error parsing " + line);
699 throw new IOException(MessageManager.formatMessage(
700 "exception.unknown_annotation_detected", new String[]
701 { annType, annContent }));
705 if (treeString.length() > 0)
707 if (treeName == null)
709 treeName = "Tree " + (1 + getTreeCount());
711 addNewickTree(treeName, treeString.toString());
716 * Demangle an accession string and guess the originating sequence database
717 * for a given sequence
720 * sequence to be annotated
722 * Accession string for sequence
724 * source database for alignment (PFAM or RFAM)
726 private void guessDatabaseFor(Sequence seqO, String dbr, String dbsource)
728 DBRefEntry dbrf = null;
729 List<DBRefEntry> dbrs = new ArrayList<>();
730 String seqdb = "Unknown", sdbac = "" + dbr;
731 int st = -1, en = -1, p;
732 if ((st = sdbac.indexOf("/")) > -1)
734 String num, range = sdbac.substring(st + 1);
735 sdbac = sdbac.substring(0, st);
736 if ((p = range.indexOf("-")) > -1)
739 if (p < range.length())
741 num = range.substring(p).trim();
744 en = Integer.parseInt(num);
745 } catch (NumberFormatException x)
747 // could warn here that index is invalid
756 num = range.substring(0, p).trim();
759 st = Integer.parseInt(num);
760 } catch (NumberFormatException x)
762 // could warn here that index is invalid
766 if (dbsource == null)
768 // make up an origin based on whether the sequence looks like it is
771 dbsource = (seqO.isProtein()) ? "PFAM" : "RFAM";
773 if (dbsource.equals("PFAM"))
776 if (sdbac.indexOf(".") > -1)
778 // strip of last subdomain
779 sdbac = sdbac.substring(0, sdbac.indexOf("."));
780 dbrf = jalview.util.DBRefUtils.parseToDbRef(seqO, seqdb, dbsource,
787 dbrf = jalview.util.DBRefUtils.parseToDbRef(seqO, dbsource, dbsource,
796 seqdb = "EMBL"; // total guess - could be ENA, or something else these
798 if (sdbac.indexOf(".") > -1)
800 // strip off last subdomain
801 sdbac = sdbac.substring(0, sdbac.indexOf("."));
802 dbrf = jalview.util.DBRefUtils.parseToDbRef(seqO, seqdb, dbsource,
810 dbrf = jalview.util.DBRefUtils.parseToDbRef(seqO, dbsource, dbsource,
817 if (st != -1 && en != -1)
819 for (DBRefEntry d : dbrs)
821 jalview.util.MapList mp = new jalview.util.MapList(
823 { seqO.getStart(), seqO.getEnd() }, new int[] { st, en }, 1,
825 jalview.datamodel.Mapping mping = new Mapping(mp);
831 protected static AlignmentAnnotation parseAnnotationRow(
832 Vector<AlignmentAnnotation> annotation, String label,
835 String convert1, convert2 = null;
837 // convert1 = OPEN_PAREN.replaceAll(annots);
838 // convert2 = CLOSE_PAREN.replaceAll(convert1);
839 // annots = convert2;
842 if (label.contains("_cons"))
844 type = (label.indexOf("_cons") == label.length() - 5)
845 ? label.substring(0, label.length() - 5)
848 boolean ss = false, posterior = false;
849 type = id2type(type);
851 boolean isrnass = false;
852 if (type.equalsIgnoreCase("secondary structure"))
855 isrnass = !NOT_RNASS.search(annots); // sorry about the double negative
856 // here (it's easier for dealing with
857 // other non-alpha-non-brace chars)
859 if (type.equalsIgnoreCase("posterior probability"))
863 // decide on secondary structure or not.
864 Annotation[] els = new Annotation[annots.length()];
865 for (int i = 0; i < annots.length(); i++)
867 String pos = annots.substring(i, i + 1);
869 ann = new Annotation(pos, "", ' ', 0f); // 0f is 'valid' null - will not
873 // if (" .-_".indexOf(pos) == -1)
875 if (isrnass && RNASS_BRACKETS.indexOf(pos) >= 0)
877 ann.secondaryStructure = Rna.getRNASecStrucState(pos).charAt(0);
878 ann.displayCharacter = "" + pos.charAt(0);
882 ann.secondaryStructure = ResidueProperties.getDssp3state(pos)
885 if (ann.secondaryStructure == pos.charAt(0))
887 ann.displayCharacter = ""; // null; // " ";
891 ann.displayCharacter = " " + ann.displayCharacter;
897 if (posterior && !ann.isWhitespace()
898 && !Comparison.isGap(pos.charAt(0)))
901 // symbol encodes values - 0..*==0..10
902 if (pos.charAt(0) == '*')
908 val = pos.charAt(0) - '0';
919 AlignmentAnnotation annot = null;
920 Enumeration<AlignmentAnnotation> e = annotation.elements();
921 while (e.hasMoreElements())
923 annot = e.nextElement();
924 if (annot.label.equals(type))
932 annot = new AlignmentAnnotation(type, type, els);
933 annotation.addElement(annot);
937 Annotation[] anns = new Annotation[annot.annotations.length
939 System.arraycopy(annot.annotations, 0, anns, 0,
940 annot.annotations.length);
941 System.arraycopy(els, 0, anns, annot.annotations.length, els.length);
942 annot.annotations = anns;
943 // jalview.bin.Console.outPrintln("else: ");
948 private String dbref_to_ac_record(DBRefEntry ref)
950 return ref.getSource().toString() + " ; "
951 + ref.getAccessionId().toString();
955 public String print(SequenceI[] s, boolean jvSuffix)
957 out = new StringBuffer();
958 out.append("# STOCKHOLM 1.0");
961 // find max length of id
967 Hashtable<String, String> dataRef = null;
968 boolean isAA = s[in].isProtein();
969 while ((in < slen) && ((seq = s[in]) != null))
971 String tmp = printId(seq, jvSuffix);
972 max = Math.max(max, seq.getLength());
974 if (tmp.length() > maxid)
976 maxid = tmp.length();
978 List<DBRefEntry> seqrefs = seq.getDBRefs();
980 if (seqrefs != null && (ndb = seqrefs.size()) > 0)
984 dataRef = new Hashtable<>();
986 List<DBRefEntry> primrefs = seq.getPrimaryDBRefs();
987 if (primrefs.size() >= 1)
989 dataRef.put(tmp, dbref_to_ac_record(primrefs.get(0)));
993 for (int idb = 0; idb < seq.getDBRefs().size(); idb++)
995 DBRefEntry dbref = seq.getDBRefs().get(idb);
996 dataRef.put(tmp, dbref_to_ac_record(dbref));
997 // if we put in a uniprot or EMBL record then we're done:
998 if (isAA && DBRefSource.UNIPROT
999 .equals(DBRefUtils.getCanonicalName(dbref.getSource())))
1003 if (!isAA && DBRefSource.EMBL
1004 .equals(DBRefUtils.getCanonicalName(dbref.getSource())))
1016 // output database type
1017 if (al.getProperties() != null)
1019 if (!al.getProperties().isEmpty())
1021 Enumeration key = al.getProperties().keys();
1022 Enumeration val = al.getProperties().elements();
1023 while (key.hasMoreElements())
1025 out.append("#=GF " + key.nextElement() + " " + val.nextElement());
1026 out.append(newline);
1031 // output database accessions
1032 if (dataRef != null)
1034 Enumeration<String> en = dataRef.keys();
1035 while (en.hasMoreElements())
1037 Object idd = en.nextElement();
1038 String type = dataRef.remove(idd);
1039 out.append(new Format("%-" + (maxid - 2) + "s")
1040 .form("#=GS " + idd.toString() + " "));
1041 if (isAA && type.contains("UNIPROT")
1042 || (!isAA && type.contains("EMBL")))
1045 out.append(" AC " + type.substring(type.indexOf(";") + 1));
1049 out.append(" DR " + type + " ");
1051 out.append(newline);
1055 // output description and annotations
1057 while (i < slen && (seq = s[i]) != null)
1059 if (seq.getDescription() != null)
1061 // out.append("#=GR ");
1062 out.append(new Format("%-" + maxid + "s").form("#=GS "
1063 + printId(seq, jvSuffix) + " DE " + seq.getDescription()));
1064 out.append(newline);
1067 AlignmentAnnotation[] alAnot = seq.getAnnotation();
1071 for (int j = 0, nj = alAnot.length; j < nj; j++)
1074 String key = type2id(alAnot[j].label);
1075 boolean isrna = alAnot[j].isValidStruc();
1079 // hardwire to secondary structure if there is RNA secondary
1080 // structure on the annotation
1089 // out.append("#=GR ");
1090 out.append(new Format("%-" + maxid + "s").form(
1091 "#=GR " + printId(seq, jvSuffix) + " " + key + " "));
1092 ann = alAnot[j].annotations;
1094 for (int k = 0, nk = ann.length; k < nk; k++)
1096 sseq += outputCharacter(key, k, isrna, ann, seq);
1099 out.append(newline);
1103 out.append(new Format("%-" + maxid + "s")
1104 .form(printId(seq, jvSuffix) + " "));
1105 out.append(seq.getSequenceAsString());
1106 out.append(newline);
1110 // alignment annotation
1111 AlignmentAnnotation aa;
1112 AlignmentAnnotation[] an = al.getAlignmentAnnotation();
1115 for (int ia = 0, na = an.length; ia < na; ia++)
1118 if (aa.autoCalculated || !aa.visible || aa.sequenceRef != null)
1125 if (aa.label.equals("seq"))
1131 key = type2id(aa.label.toLowerCase(Locale.ROOT));
1138 label = key + "_cons";
1145 label = label.replace(" ", "_");
1148 new Format("%-" + maxid + "s").form("#=GC " + label + " "));
1149 boolean isrna = aa.isValidStruc();
1150 for (int j = 0, nj = aa.annotations.length; j < nj; j++)
1152 sseq += outputCharacter(key, j, isrna, aa.annotations, null);
1155 out.append(newline);
1160 out.append(newline);
1162 return out.toString();
1166 * add an annotation character to the output row
1175 private char outputCharacter(String key, int k, boolean isrna,
1176 Annotation[] ann, SequenceI sequenceI)
1179 Annotation annot = ann[k];
1180 String ch = (annot == null)
1181 ? ((sequenceI == null) ? "-"
1182 : Character.toString(sequenceI.getCharAt(k)))
1183 : (annot.displayCharacter == null
1184 ? String.valueOf(annot.secondaryStructure)
1185 : annot.displayCharacter);
1190 if (key != null && key.equals("SS"))
1192 char ssannotchar = ' ';
1193 boolean charset = false;
1196 // sensible gap character
1202 // valid secondary structure AND no alternative label (e.g. ' B')
1203 if (annot.secondaryStructure > ' ' && ch.length() < 2)
1205 ssannotchar = annot.secondaryStructure;
1211 return (ssannotchar == ' ' && isrna) ? '.' : ssannotchar;
1215 if (ch.length() == 0)
1219 else if (ch.length() == 1)
1223 else if (ch.length() > 1)
1228 return (seq == ' ' && key != null && key.equals("SS") && isrna) ? '.'
1232 public String print()
1234 out = new StringBuffer();
1235 out.append("# STOCKHOLM 1.0");
1236 out.append(newline);
1237 print(getSeqsAsArray(), false);
1240 out.append(newline);
1241 return out.toString();
1244 private static Hashtable typeIds = null;
1248 if (typeIds == null)
1250 typeIds = new Hashtable();
1251 typeIds.put("SS", "Secondary Structure");
1252 typeIds.put("SA", "Surface Accessibility");
1253 typeIds.put("TM", "transmembrane");
1254 typeIds.put("PP", "Posterior Probability");
1255 typeIds.put("LI", "ligand binding");
1256 typeIds.put("AS", "active site");
1257 typeIds.put("IN", "intron");
1258 typeIds.put("IR", "interacting residue");
1259 typeIds.put("AC", "accession");
1260 typeIds.put("OS", "organism");
1261 typeIds.put("CL", "class");
1262 typeIds.put("DE", "description");
1263 typeIds.put("DR", "reference");
1264 typeIds.put("LO", "look");
1265 typeIds.put("RF", "Reference Positions");
1270 protected static String id2type(String id)
1272 if (typeIds.containsKey(id))
1274 return (String) typeIds.get(id);
1276 jalview.bin.Console.errPrintln(
1277 "Warning : Unknown Stockholm annotation type code " + id);
1281 protected static String type2id(String type)
1284 Enumeration e = typeIds.keys();
1285 while (e.hasMoreElements())
1287 Object ll = e.nextElement();
1288 if (typeIds.get(ll).toString().equalsIgnoreCase(type))
1298 jalview.bin.Console.errPrintln(
1299 "Warning : Unknown Stockholm annotation type: " + type);
1304 * make a friendly ID string.
1307 * @return truncated dataName to after last '/'
1309 private String safeName(String dataName)
1312 while ((b = dataName.indexOf("/")) > -1 && b < dataName.length())
1314 dataName = dataName.substring(b + 1).trim();
1317 int e = (dataName.length() - dataName.indexOf(".")) + 1;
1318 dataName = dataName.substring(1, e).trim();