2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
22 * This extension was written by Benjamin Schuster-Boeckler at sanger.ac.uk
26 import jalview.analysis.Rna;
27 import jalview.datamodel.AlignmentAnnotation;
28 import jalview.datamodel.AlignmentI;
29 import jalview.datamodel.Annotation;
30 import jalview.datamodel.DBRefEntry;
31 import jalview.datamodel.Mapping;
32 import jalview.datamodel.Sequence;
33 import jalview.datamodel.SequenceFeature;
34 import jalview.datamodel.SequenceI;
35 import jalview.schemes.ResidueProperties;
36 import jalview.util.Comparison;
37 import jalview.util.Format;
38 import jalview.util.MessageManager;
40 import java.io.BufferedReader;
41 import java.io.FileReader;
42 import java.io.IOException;
43 import java.util.ArrayList;
44 import java.util.Enumeration;
45 import java.util.Hashtable;
46 import java.util.LinkedHashMap;
47 import java.util.List;
49 import java.util.Vector;
51 import com.stevesoft.pat.Regex;
53 import fr.orsay.lri.varna.exceptions.ExceptionUnmatchedClosingParentheses;
54 import fr.orsay.lri.varna.factories.RNAFactory;
55 import fr.orsay.lri.varna.models.rna.RNA;
57 // import org.apache.log4j.*;
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 public static final String RNASS_BRACKETS = "<>[]() {}AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz";
88 StringBuffer out; // output buffer
92 public StockholmFile()
97 * Creates a new StockholmFile object for output.
99 public StockholmFile(AlignmentI al)
104 public StockholmFile(String inFile, DataSourceType type)
110 public StockholmFile(FileParse source) throws IOException
116 public void initData()
122 * Parse a file in Stockholm format into Jalview's data model using VARNA
124 * @throws IOException
125 * If there is an error with the input file
127 public void parse_with_VARNA(java.io.File inFile) throws IOException
129 FileReader fr = null;
130 fr = new FileReader(inFile);
132 BufferedReader r = new BufferedReader(fr);
133 List<RNA> result = null;
136 result = RNAFactory.loadSecStrStockholm(r);
137 } catch (ExceptionUnmatchedClosingParentheses umcp)
139 errormessage = "Unmatched parentheses in annotation. Aborting ("
140 + umcp.getMessage() + ")";
141 throw new IOException(umcp);
143 // DEBUG System.out.println("this is the secondary scructure:"
145 SequenceI[] seqs = new SequenceI[result.size()];
147 for (int i = 0; i < result.size(); i++)
149 // DEBUG System.err.println("Processing i'th sequence in Stockholm file")
150 RNA current = result.get(i);
152 String seq = current.getSeq();
153 String rna = current.getStructDBN(true);
154 // DEBUG System.out.println(seq);
155 // DEBUG System.err.println(rna);
157 int end = seq.length() - 1;
158 id = safeName(getDataName());
159 seqs[i] = new Sequence(id, seq, begin, end);
160 String[] annot = new String[rna.length()];
161 Annotation[] ann = new Annotation[rna.length()];
162 for (int j = 0; j < rna.length(); j++)
164 annot[j] = rna.substring(j, j + 1);
168 for (int k = 0; k < rna.length(); k++)
170 ann[k] = new Annotation(annot[k], "",
171 Rna.getRNASecStrucState(annot[k]).charAt(0), 0f);
174 AlignmentAnnotation align = new AlignmentAnnotation("Sec. str.",
175 current.getID(), ann);
177 seqs[i].addAlignmentAnnotation(align);
178 seqs[i].setRNA(result.get(i));
179 this.annotations.addElement(align);
186 * Parse a file in Stockholm format into Jalview's data model. The file has to
187 * be passed at construction time
189 * @throws IOException
190 * If there is an error with the input file
193 public void parse() throws IOException
195 StringBuffer treeString = new StringBuffer();
196 String treeName = null;
197 // --------------- Variable Definitions -------------------
201 Hashtable seqAnn = new Hashtable(); // Sequence related annotations
202 LinkedHashMap<String, String> seqs = new LinkedHashMap<>();
203 Regex p, r, rend, s, x;
204 // Temporary line for processing RNA annotation
205 // String RNAannot = "";
207 // ------------------ Parsing File ----------------------
208 // First, we have to check that this file has STOCKHOLM format, i.e. the
209 // first line must match
211 r = new Regex("# STOCKHOLM ([\\d\\.]+)");
212 if (!r.search(nextLine()))
214 throw new IOException(MessageManager
215 .getString("exception.stockholm_invalid_format"));
219 version = r.stringMatched(1);
221 // logger.debug("Stockholm version: " + version);
224 // We define some Regexes here that will be used regularily later
225 rend = new Regex("^\\s*\\/\\/"); // Find the end of an alignment
226 p = new Regex("(\\S+)\\/(\\d+)\\-(\\d+)"); // split sequence id in
228 s = new Regex("(\\S+)\\s+(\\S*)\\s+(.*)"); // Parses annotation subtype
229 r = new Regex("#=(G[FSRC]?)\\s+(.*)"); // Finds any annotation line
230 x = new Regex("(\\S+)\\s+(\\S+)"); // split id from sequence
232 // Convert all bracket types to parentheses (necessary for passing to VARNA)
233 Regex openparen = new Regex("(<|\\[)", "(");
234 Regex closeparen = new Regex("(>|\\])", ")");
236 // Detect if file is RNA by looking for bracket types
237 Regex detectbrackets = new Regex("(<|>|\\[|\\]|\\(|\\))");
244 openparen.optimize();
245 closeparen.optimize();
247 while ((line = nextLine()) != null)
249 if (line.length() == 0)
253 if (rend.search(line))
255 // End of the alignment, pass stuff back
256 this.noSeqs = seqs.size();
258 String seqdb, dbsource = null;
259 Regex pf = new Regex("PF[0-9]{5}(.*)"); // Finds AC for Pfam
260 Regex rf = new Regex("RF[0-9]{5}(.*)"); // Finds AC for Rfam
261 if (getAlignmentProperty("AC") != null)
263 String dbType = getAlignmentProperty("AC").toString();
264 if (pf.search(dbType))
266 // PFAM Alignment - so references are typically from Uniprot
269 else if (rf.search(dbType))
274 // logger.debug("Number of sequences: " + this.noSeqs);
275 for (Map.Entry<String, String> skey : seqs.entrySet())
277 // logger.debug("Processing sequence " + acc);
278 String acc = skey.getKey();
279 String seq = skey.getValue();
280 if (maxLength < seq.length())
282 maxLength = seq.length();
288 * Retrieve hash of annotations for this accession Associate
289 * Annotation with accession
291 Hashtable accAnnotations = null;
293 if (seqAnn != null && seqAnn.containsKey(acc))
295 accAnnotations = (Hashtable) seqAnn.remove(acc);
296 // TODO: add structures to sequence
299 // Split accession in id and from/to
302 sid = p.stringMatched(1);
303 start = Integer.parseInt(p.stringMatched(2));
304 end = Integer.parseInt(p.stringMatched(3));
306 // logger.debug(sid + ", " + start + ", " + end);
308 Sequence seqO = new Sequence(sid, seq, start, end);
309 // Add Description (if any)
310 if (accAnnotations != null && accAnnotations.containsKey("DE"))
312 String desc = (String) accAnnotations.get("DE");
313 seqO.setDescription((desc == null) ? "" : desc);
315 // Add DB References (if any)
316 if (accAnnotations != null && accAnnotations.containsKey("DR"))
318 String dbr = (String) accAnnotations.get("DR");
319 if (dbr != null && dbr.indexOf(";") > -1)
321 String src = dbr.substring(0, dbr.indexOf(";"));
322 String acn = dbr.substring(dbr.indexOf(";") + 1);
323 jalview.util.DBRefUtils.parseToDbRef(seqO, src, "0", acn);
327 if (accAnnotations != null && accAnnotations.containsKey("AC"))
329 if (dbsource != null)
331 String dbr = (String) accAnnotations.get("AC");
334 // we could get very clever here - but for now - just try to
335 // guess accession type from source of alignment plus structure
337 guessDatabaseFor(seqO, dbr, dbsource);
341 // else - do what ? add the data anyway and prompt the user to
342 // specify what references these are ?
345 Hashtable features = null;
346 // We need to adjust the positions of all features to account for gaps
349 features = (Hashtable) accAnnotations.remove("features");
350 } catch (java.lang.NullPointerException e)
352 // loggerwarn("Getting Features for " + acc + ": " +
356 // if we have features
357 if (features != null)
359 int posmap[] = seqO.findPositionMap();
360 Enumeration i = features.keys();
361 while (i.hasMoreElements())
363 // TODO: parse out secondary structure annotation as annotation
365 // TODO: parse out scores as annotation row
366 // TODO: map coding region to core jalview feature types
367 String type = i.nextElement().toString();
368 Hashtable content = (Hashtable) features.remove(type);
370 // add alignment annotation for this feature
371 String key = type2id(type);
374 * have we added annotation rows for this type ?
376 boolean annotsAdded = false;
379 if (accAnnotations != null
380 && accAnnotations.containsKey(key))
382 Vector vv = (Vector) accAnnotations.get(key);
383 for (int ii = 0; ii < vv.size(); ii++)
386 AlignmentAnnotation an = (AlignmentAnnotation) vv
388 seqO.addAlignmentAnnotation(an);
394 Enumeration j = content.keys();
395 while (j.hasMoreElements())
397 String desc = j.nextElement().toString();
398 if (ANNOTATION.equals(desc) && annotsAdded)
400 // don't add features if we already added an annotation row
403 String ns = content.get(desc).toString();
404 char[] byChar = ns.toCharArray();
405 for (int k = 0; k < byChar.length; k++)
408 if (!(c == ' ' || c == '_' || c == '-' || c == '.')) // PFAM
415 int new_pos = posmap[k]; // look up nearest seqeunce
416 // position to this column
417 SequenceFeature feat = new SequenceFeature(type, desc,
418 new_pos, new_pos, null);
420 seqO.addSequenceFeature(feat);
430 // logger.debug("Adding seq " + acc + " from " + start + " to " + end
432 this.seqs.addElement(seqO);
434 return; // finished parsing this segment of source
436 else if (!r.search(line))
438 // System.err.println("Found sequence line: " + line);
440 // Split sequence in sequence and accession parts
443 // logger.error("Could not parse sequence line: " + line);
444 throw new IOException(MessageManager.formatMessage(
445 "exception.couldnt_parse_sequence_line", new String[]
448 String ns = seqs.get(x.stringMatched(1));
453 ns += x.stringMatched(2);
455 seqs.put(x.stringMatched(1), ns);
459 String annType = r.stringMatched(1);
460 String annContent = r.stringMatched(2);
462 // System.err.println("type:" + annType + " content: " + annContent);
464 if (annType.equals("GF"))
467 * Generic per-File annotation, free text Magic features: #=GF NH
468 * <tree in New Hampshire eXtended format> #=GF TN <Unique identifier
469 * for the next tree> Pfam descriptions: 7. DESCRIPTION OF FIELDS
471 * Compulsory fields: ------------------
473 * AC Accession number: Accession number in form PFxxxxx.version or
474 * PBxxxxxx. ID Identification: One word name for family. DE
475 * Definition: Short description of family. AU Author: Authors of the
476 * entry. SE Source of seed: The source suggesting the seed members
477 * belong to one family. GA Gathering method: Search threshold to
478 * build the full alignment. TC Trusted Cutoff: Lowest sequence score
479 * and domain score of match in the full alignment. NC Noise Cutoff:
480 * Highest sequence score and domain score of match not in full
481 * alignment. TP Type: Type of family -- presently Family, Domain,
482 * Motif or Repeat. SQ Sequence: Number of sequences in alignment. AM
483 * Alignment Method The order ls and fs hits are aligned to the model
484 * to build the full align. // End of alignment.
486 * Optional fields: ----------------
488 * DC Database Comment: Comment about database reference. DR Database
489 * Reference: Reference to external database. RC Reference Comment:
490 * Comment about literature reference. RN Reference Number: Reference
491 * Number. RM Reference Medline: Eight digit medline UI number. RT
492 * Reference Title: Reference Title. RA Reference Author: Reference
493 * Author RL Reference Location: Journal location. PI Previous
494 * identifier: Record of all previous ID lines. KW Keywords: Keywords.
495 * CC Comment: Comments. NE Pfam accession: Indicates a nested domain.
496 * NL Location: Location of nested domains - sequence ID, start and
499 * Obsolete fields: ----------- AL Alignment method of seed: The
500 * method used to align the seed members.
502 // Let's save the annotations, maybe we'll be able to do something
503 // with them later...
504 Regex an = new Regex("(\\w+)\\s*(.*)");
505 if (an.search(annContent))
507 if (an.stringMatched(1).equals("NH"))
509 treeString.append(an.stringMatched(2));
511 else if (an.stringMatched(1).equals("TN"))
513 if (treeString.length() > 0)
515 if (treeName == null)
517 treeName = "Tree " + (getTreeCount() + 1);
519 addNewickTree(treeName, treeString.toString());
521 treeName = an.stringMatched(2);
522 treeString = new StringBuffer();
524 setAlignmentProperty(an.stringMatched(1), an.stringMatched(2));
527 else if (annType.equals("GS"))
529 // Generic per-Sequence annotation, free text
531 * Pfam uses these features: Feature Description ---------------------
532 * ----------- AC <accession> ACcession number DE <freetext>
533 * DEscription DR <db>; <accession>; Database Reference OS <organism>
534 * OrganiSm (species) OC <clade> Organism Classification (clade, etc.)
535 * LO <look> Look (Color, etc.)
537 if (s.search(annContent))
539 String acc = s.stringMatched(1);
540 String type = s.stringMatched(2);
541 String content = s.stringMatched(3);
542 // TODO: store DR in a vector.
543 // TODO: store AC according to generic file db annotation.
545 if (seqAnn.containsKey(acc))
547 ann = (Hashtable) seqAnn.get(acc);
551 ann = new Hashtable();
553 ann.put(type, content);
554 seqAnn.put(acc, ann);
558 // throw new IOException("Error parsing " + line);
559 System.err.println(">> missing annotation: " + line);
562 else if (annType.equals("GC"))
564 // Generic per-Column annotation, exactly 1 char per column
565 // always need a label.
566 if (x.search(annContent))
568 // parse out and create alignment annotation directly.
569 parseAnnotationRow(annotations, x.stringMatched(1),
573 else if (annType.equals("GR"))
575 // Generic per-Sequence AND per-Column markup, exactly 1 char per
578 * Feature Description Markup letters ------- -----------
579 * -------------- SS Secondary Structure [HGIEBTSCX] SA Surface
580 * Accessibility [0-9X] (0=0%-10%; ...; 9=90%-100%) TM TransMembrane
581 * [Mio] PP Posterior Probability [0-9*] (0=0.00-0.05; 1=0.05-0.15;
582 * *=0.95-1.00) LI LIgand binding [*] AS Active Site [*] IN INtron (in
585 if (s.search(annContent))
587 String acc = s.stringMatched(1);
588 String type = s.stringMatched(2);
589 String oseq = s.stringMatched(3);
591 * copy of annotation field that may be processed into whitespace chunks
593 String seq = new String(oseq);
596 // Get an object with all the annotations for this sequence
597 if (seqAnn.containsKey(acc))
599 // logger.debug("Found annotations for " + acc);
600 ann = (Hashtable) seqAnn.get(acc);
604 // logger.debug("Creating new annotations holder for " + acc);
605 ann = new Hashtable();
606 seqAnn.put(acc, ann);
609 // // start of block for appending annotation lines for wrapped
611 // TODO test structure, call parseAnnotationRow with vector from
612 // hashtable for specific sequence
615 // Get an object with all the content for an annotation
616 if (ann.containsKey("features"))
618 // logger.debug("Found features for " + acc);
619 features = (Hashtable) ann.get("features");
623 // logger.debug("Creating new features holder for " + acc);
624 features = new Hashtable();
625 ann.put("features", features);
629 if (features.containsKey(this.id2type(type)))
631 // logger.debug("Found content for " + this.id2type(type));
632 content = (Hashtable) features.get(this.id2type(type));
636 // logger.debug("Creating new content holder for " +
637 // this.id2type(type));
638 content = new Hashtable();
639 features.put(this.id2type(type), content);
641 String ns = (String) content.get(ANNOTATION);
647 // finally, append the annotation line
649 content.put(ANNOTATION, ns);
650 // // end of wrapped annotation block.
651 // // Now a new row is created with the current set of data
654 if (seqAnn.containsKey(acc))
656 strucAnn = (Hashtable) seqAnn.get(acc);
660 strucAnn = new Hashtable();
663 Vector<AlignmentAnnotation> newStruc = new Vector<>();
664 parseAnnotationRow(newStruc, type, ns);
665 for (AlignmentAnnotation alan : newStruc)
667 alan.visible = false;
669 // new annotation overwrites any existing annotation...
671 strucAnn.put(type, newStruc);
672 seqAnn.put(acc, strucAnn);
678 "Warning - couldn't parse sequence annotation row line:\n"
680 // throw new IOException("Error parsing " + line);
685 throw new IOException(MessageManager.formatMessage(
686 "exception.unknown_annotation_detected", new String[]
687 { annType, annContent }));
691 if (treeString.length() > 0)
693 if (treeName == null)
695 treeName = "Tree " + (1 + getTreeCount());
697 addNewickTree(treeName, treeString.toString());
702 * Demangle an accession string and guess the originating sequence database
703 * for a given sequence
706 * sequence to be annotated
708 * Accession string for sequence
710 * source database for alignment (PFAM or RFAM)
712 private void guessDatabaseFor(Sequence seqO, String dbr, String dbsource)
714 DBRefEntry dbrf = null;
715 List<DBRefEntry> dbrs = new ArrayList<>();
716 String seqdb = "Unknown", sdbac = "" + dbr;
717 int st = -1, en = -1, p;
718 if ((st = sdbac.indexOf("/")) > -1)
720 String num, range = sdbac.substring(st + 1);
721 sdbac = sdbac.substring(0, st);
722 if ((p = range.indexOf("-")) > -1)
725 if (p < range.length())
727 num = range.substring(p).trim();
730 en = Integer.parseInt(num);
731 } catch (NumberFormatException x)
733 // could warn here that index is invalid
742 num = range.substring(0, p).trim();
745 st = Integer.parseInt(num);
746 } catch (NumberFormatException x)
748 // could warn here that index is invalid
752 if (dbsource.equals("PFAM"))
755 if (sdbac.indexOf(".") > -1)
757 // strip of last subdomain
758 sdbac = sdbac.substring(0, sdbac.indexOf("."));
759 dbrf = jalview.util.DBRefUtils.parseToDbRef(seqO, seqdb, dbsource,
766 dbrf = jalview.util.DBRefUtils.parseToDbRef(seqO, dbsource, dbsource,
775 seqdb = "EMBL"; // total guess - could be ENA, or something else these
777 if (sdbac.indexOf(".") > -1)
779 // strip off last subdomain
780 sdbac = sdbac.substring(0, sdbac.indexOf("."));
781 dbrf = jalview.util.DBRefUtils.parseToDbRef(seqO, seqdb, dbsource,
789 dbrf = jalview.util.DBRefUtils.parseToDbRef(seqO, dbsource, dbsource,
796 if (st != -1 && en != -1)
798 for (DBRefEntry d : dbrs)
800 jalview.util.MapList mp = new jalview.util.MapList(
802 { seqO.getStart(), seqO.getEnd() }, new int[] { st, en }, 1,
804 jalview.datamodel.Mapping mping = new Mapping(mp);
810 protected static AlignmentAnnotation parseAnnotationRow(
811 Vector<AlignmentAnnotation> annotation, String label,
814 String convert1, convert2 = null;
816 // convert1 = OPEN_PAREN.replaceAll(annots);
817 // convert2 = CLOSE_PAREN.replaceAll(convert1);
818 // annots = convert2;
822 "*** parseAnnotationRow called with\n annotation='"
823 + annotation + "'\n label='" + label
824 + "'\n annots='" + annots + "'");
827 if (label.contains("_cons"))
829 type = (label.indexOf("_cons") == label.length() - 5)
830 ? label.substring(0, label.length() - 5)
833 boolean ss = false, posterior = false;
834 type = id2type(type);
836 boolean isrnass = false;
837 if (type.equalsIgnoreCase("secondary structure"))
840 isrnass = DETECT_BRACKETS.search(annots);
842 if (type.equalsIgnoreCase("posterior probability"))
846 // decide on secondary structure or not.
847 Annotation[] els = new Annotation[annots.length()];
848 for (int i = 0; i < annots.length(); i++)
850 String pos = annots.substring(i, i + 1);
852 ann = new Annotation(pos, "", ' ', 0f); // 0f is 'valid' null - will not
856 // if (" .-_".indexOf(pos) == -1)
858 if (isrnass && RNASS_BRACKETS.indexOf(pos) >= 0)
860 ann.secondaryStructure = Rna.getRNASecStrucState(pos).charAt(0);
861 ann.displayCharacter = "" + pos.charAt(0);
865 ann.secondaryStructure = ResidueProperties.getDssp3state(pos)
868 if (ann.secondaryStructure == pos.charAt(0))
870 ann.displayCharacter = ""; // null; // " ";
874 ann.displayCharacter = " " + ann.displayCharacter;
880 if (posterior && !ann.isWhitespace()
881 && !Comparison.isGap(pos.charAt(0)))
884 // symbol encodes values - 0..*==0..10
885 if (pos.charAt(0) == '*')
891 val = pos.charAt(0) - '0';
902 AlignmentAnnotation annot = null;
903 Enumeration<AlignmentAnnotation> e = annotation.elements();
904 while (e.hasMoreElements())
906 annot = e.nextElement();
907 if (annot.label.equals(type))
915 annot = new AlignmentAnnotation(type, type, els);
916 annotation.addElement(annot);
920 Annotation[] anns = new Annotation[annot.annotations.length
922 System.arraycopy(annot.annotations, 0, anns, 0,
923 annot.annotations.length);
924 System.arraycopy(els, 0, anns, annot.annotations.length, els.length);
925 annot.annotations = anns;
926 // System.out.println("else: ");
932 public String print(SequenceI[] s, boolean jvSuffix)
934 out = new StringBuffer();
935 out.append("# STOCKHOLM 1.0");
938 // find max length of id
942 Hashtable dataRef = null;
943 while ((in < s.length) && (s[in] != null))
945 String tmp = printId(s[in], jvSuffix);
946 max = Math.max(max, s[in].getLength());
948 if (tmp.length() > maxid)
950 maxid = tmp.length();
952 if (s[in].getDBRefs() != null)
954 for (int idb = 0; idb < s[in].getDBRefs().length; idb++)
958 dataRef = new Hashtable();
961 String datAs1 = s[in].getDBRefs()[idb].getSource().toString()
963 + s[in].getDBRefs()[idb].getAccessionId().toString();
964 dataRef.put(tmp, datAs1);
972 // output database type
973 if (al.getProperties() != null)
975 if (!al.getProperties().isEmpty())
977 Enumeration key = al.getProperties().keys();
978 Enumeration val = al.getProperties().elements();
979 while (key.hasMoreElements())
981 out.append("#=GF " + key.nextElement() + " " + val.nextElement());
987 // output database accessions
990 Enumeration en = dataRef.keys();
991 while (en.hasMoreElements())
993 Object idd = en.nextElement();
994 String type = (String) dataRef.remove(idd);
995 out.append(new Format("%-" + (maxid - 2) + "s")
996 .form("#=GS " + idd.toString() + " "));
997 if (type.contains("PFAM") || type.contains("RFAM"))
1000 out.append(" AC " + type.substring(type.indexOf(";") + 1));
1004 out.append(" DR " + type + " ");
1006 out.append(newline);
1010 // output annotations
1011 while (i < s.length && s[i] != null)
1013 AlignmentAnnotation[] alAnot = s[i].getAnnotation();
1017 for (int j = 0; j < alAnot.length; j++)
1020 String key = type2id(alAnot[j].label);
1021 boolean isrna = alAnot[j].isValidStruc();
1023 System.out.println("SEQUENCE " + i + "/" + s.length + " ISRNA="
1027 // hardwire to secondary structure if there is RNA secondary
1028 // structure on the annotation
1037 // out.append("#=GR ");
1038 out.append(new Format("%-" + maxid + "s").form(
1039 "#=GR " + printId(s[i], jvSuffix) + " " + key + " "));
1040 ann = alAnot[j].annotations;
1042 for (int k = 0; k < ann.length; k++)
1044 seq += outputCharacter(key, k, isrna, ann, s[i]);
1047 System.out.println("APPENDING SEQ: KEY=" + key + " ISRNA=" + isrna
1048 + ".\n" + "SEQ=" + seq + "\n");
1050 out.append(newline);
1054 out.append(new Format("%-" + maxid + "s")
1055 .form(printId(s[i], jvSuffix) + " "));
1056 out.append(s[i].getSequenceAsString());
1058 System.out.println("ALSO APPENDING " + s[i].getSequenceAsString());
1059 out.append(newline);
1063 // alignment annotation
1064 AlignmentAnnotation aa;
1065 if (al.getAlignmentAnnotation() != null)
1067 for (int ia = 0; ia < al.getAlignmentAnnotation().length; ia++)
1069 aa = al.getAlignmentAnnotation()[ia];
1070 if (aa.autoCalculated || !aa.visible || aa.sequenceRef != null)
1077 if (aa.label.equals("seq"))
1083 key = type2id(aa.label.toLowerCase());
1090 label = key + "_cons";
1097 label = label.replace(" ", "_");
1100 new Format("%-" + maxid + "s").form("#=GC " + label + " "));
1101 boolean isrna = aa.isValidStruc();
1102 for (int j = 0; j < aa.annotations.length; j++)
1104 seq += outputCharacter(key, j, isrna, aa.annotations, null);
1109 "PRINTING SEQ: KEY=" + key + " ISRNA=" + isrna + ".\n"
1110 + "SEQ=" + seq + "\n");
1113 out.append(newline);
1118 out.append(newline);
1120 return out.toString();
1124 * add an annotation character to the output row
1133 private char outputCharacter(String key, int k, boolean isrna,
1134 Annotation[] ann, SequenceI sequenceI)
1137 Annotation annot = ann[k];
1138 String ch = (annot == null)
1139 ? ((sequenceI == null) ? "-"
1140 : Character.toString(sequenceI.getCharAt(k)))
1141 : annot.displayCharacter;
1142 if (key != null && key.equals("SS"))
1144 char ssannotchar = ' ';
1145 boolean charset = false;
1148 // sensible gap character
1154 // valid secondary structure AND no alternative label (e.g. ' B')
1155 if (annot.secondaryStructure > ' ' && ch.length() < 2)
1157 ssannotchar = annot.secondaryStructure;
1163 if (ssannotchar == ' ' && isrna)
1171 if (ch.length() == 0)
1175 else if (ch.length() == 1)
1179 else if (ch.length() > 1)
1184 return (seq == ' ' && key != null && key.equals("SS") && isrna) ? '.'
1188 public String print()
1190 out = new StringBuffer();
1191 out.append("# STOCKHOLM 1.0");
1192 out.append(newline);
1193 print(getSeqsAsArray(), false);
1196 out.append(newline);
1197 return out.toString();
1200 private static Hashtable typeIds = null;
1204 if (typeIds == null)
1206 typeIds = new Hashtable();
1207 typeIds.put("SS", "Secondary Structure");
1208 typeIds.put("SA", "Surface Accessibility");
1209 typeIds.put("TM", "transmembrane");
1210 typeIds.put("PP", "Posterior Probability");
1211 typeIds.put("LI", "ligand binding");
1212 typeIds.put("AS", "active site");
1213 typeIds.put("IN", "intron");
1214 typeIds.put("IR", "interacting residue");
1215 typeIds.put("AC", "accession");
1216 typeIds.put("OS", "organism");
1217 typeIds.put("CL", "class");
1218 typeIds.put("DE", "description");
1219 typeIds.put("DR", "reference");
1220 typeIds.put("LO", "look");
1221 typeIds.put("RF", "Reference Positions");
1226 protected static String id2type(String id)
1228 if (typeIds.containsKey(id))
1230 return (String) typeIds.get(id);
1233 "Warning : Unknown Stockholm annotation type code " + id);
1237 protected static String type2id(String type)
1240 Enumeration e = typeIds.keys();
1241 while (e.hasMoreElements())
1243 Object ll = e.nextElement();
1244 if (typeIds.get(ll).toString().equalsIgnoreCase(type))
1255 "Warning : Unknown Stockholm annotation type: " + type);
1260 * make a friendly ID string.
1263 * @return truncated dataName to after last '/'
1265 private String safeName(String dataName)
1268 while ((b = dataName.indexOf("/")) > -1 && b < dataName.length())
1270 dataName = dataName.substring(b + 1).trim();
1273 int e = (dataName.length() - dataName.indexOf(".")) + 1;
1274 dataName = dataName.substring(1, e).trim();