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.datamodel.AlignmentAnnotation;
27 import jalview.datamodel.AlignmentI;
28 import jalview.datamodel.Annotation;
29 import jalview.datamodel.DBRefEntry;
30 import jalview.datamodel.Mapping;
31 import jalview.datamodel.Sequence;
32 import jalview.datamodel.SequenceFeature;
33 import jalview.datamodel.SequenceI;
34 import jalview.util.Format;
35 import jalview.util.MessageManager;
37 import java.io.BufferedReader;
38 import java.io.FileReader;
39 import java.io.IOException;
40 import java.util.ArrayList;
41 import java.util.Enumeration;
42 import java.util.Hashtable;
43 import java.util.LinkedHashMap;
44 import java.util.List;
46 import java.util.StringTokenizer;
47 import java.util.Vector;
49 import com.stevesoft.pat.Regex;
51 import fr.orsay.lri.varna.exceptions.ExceptionUnmatchedClosingParentheses;
52 import fr.orsay.lri.varna.factories.RNAFactory;
53 import fr.orsay.lri.varna.models.rna.RNA;
55 // import org.apache.log4j.*;
58 * This class is supposed to parse a Stockholm format file into Jalview There
59 * are TODOs in this class: we do not know what the database source and version
60 * is for the file when parsing the #GS= AC tag which associates accessions with
61 * sequences. Database references are also not parsed correctly: a separate
62 * reference string parser must be added to parse the database reference form
63 * into Jalview's local representation.
65 * @author bsb at sanger.ac.uk
66 * @author Natasha Shersnev (Dundee, UK) (Stockholm file writer)
67 * @author Lauren Lui (UCSC, USA) (RNA secondary structure annotation import as
69 * @author Anne Menard (Paris, FR) (VARNA parsing of Stockholm file data)
70 * @version 0.3 + jalview mods
73 public class StockholmFile extends AlignFile
75 // static Logger logger = Logger.getLogger("jalview.io.StockholmFile");
76 protected ArrayList<RNA> result;
78 StringBuffer out; // output buffer
82 public StockholmFile()
87 * Creates a new StockholmFile object for output.
89 public StockholmFile(AlignmentI al)
94 public StockholmFile(String inFile, DataSourceType sourceType)
97 super(inFile, sourceType);
100 public StockholmFile(FileParse source) throws IOException
106 public void initData()
112 * Parse a file in Stockholm format into Jalview's data model using VARNA
114 * @throws IOException
115 * If there is an error with the input file
117 public void parse_with_VARNA(java.io.File inFile) throws IOException
119 FileReader fr = null;
120 fr = new FileReader(inFile);
122 BufferedReader r = new BufferedReader(fr);
126 result = RNAFactory.loadSecStrStockholm(r);
127 } catch (ExceptionUnmatchedClosingParentheses umcp)
129 errormessage = "Unmatched parentheses in annotation. Aborting ("
130 + umcp.getMessage() + ")";
131 throw new IOException(umcp);
133 // DEBUG System.out.println("this is the secondary scructure:"
135 SequenceI[] seqs = new SequenceI[result.size()];
137 for (int i = 0; i < result.size(); i++)
139 // DEBUG System.err.println("Processing i'th sequence in Stockholm file")
140 RNA current = result.get(i);
142 String seq = current.getSeq();
143 String rna = current.getStructDBN(true);
144 // DEBUG System.out.println(seq);
145 // DEBUG System.err.println(rna);
147 int end = seq.length() - 1;
148 id = safeName(getDataName());
149 seqs[i] = new Sequence(id, seq, begin, end);
150 String[] annot = new String[rna.length()];
151 Annotation[] ann = new Annotation[rna.length()];
152 for (int j = 0; j < rna.length(); j++)
154 annot[j] = rna.substring(j, j + 1);
158 for (int k = 0; k < rna.length(); k++)
160 ann[k] = new Annotation(annot[k], "",
161 jalview.schemes.ResidueProperties.getRNASecStrucState(
162 annot[k]).charAt(0), 0f);
165 AlignmentAnnotation align = new AlignmentAnnotation("Sec. str.",
166 current.getID(), ann);
168 seqs[i].addAlignmentAnnotation(align);
169 seqs[i].setRNA(result.get(i));
170 this.annotations.addElement(align);
177 * Parse a file in Stockholm format into Jalview's data model. The file has to
178 * be passed at construction time
180 * @throws IOException
181 * If there is an error with the input file
184 public void parse() throws IOException
186 StringBuffer treeString = new StringBuffer();
187 String treeName = null;
188 // --------------- Variable Definitions -------------------
192 Hashtable seqAnn = new Hashtable(); // Sequence related annotations
193 LinkedHashMap<String, String> seqs = new LinkedHashMap<String, String>();
194 Regex p, r, rend, s, x;
195 // Temporary line for processing RNA annotation
196 // String RNAannot = "";
198 // ------------------ Parsing File ----------------------
199 // First, we have to check that this file has STOCKHOLM format, i.e. the
200 // first line must match
202 r = new Regex("# STOCKHOLM ([\\d\\.]+)");
203 if (!r.search(nextLine()))
205 throw new IOException(
207 .getString("exception.stockholm_invalid_format"));
211 version = r.stringMatched(1);
213 // logger.debug("Stockholm version: " + version);
216 // We define some Regexes here that will be used regularily later
217 rend = new Regex("^\\s*\\/\\/"); // Find the end of an alignment
218 p = new Regex("(\\S+)\\/(\\d+)\\-(\\d+)"); // split sequence id in
220 s = new Regex("(\\S+)\\s+(\\S*)\\s+(.*)"); // Parses annotation subtype
221 r = new Regex("#=(G[FSRC]?)\\s+(.*)"); // Finds any annotation line
222 x = new Regex("(\\S+)\\s+(\\S+)"); // split id from sequence
224 // Convert all bracket types to parentheses (necessary for passing to VARNA)
225 Regex openparen = new Regex("(<|\\[)", "(");
226 Regex closeparen = new Regex("(>|\\])", ")");
228 // Detect if file is RNA by looking for bracket types
229 Regex detectbrackets = new Regex("(<|>|\\[|\\]|\\(|\\))");
236 openparen.optimize();
237 closeparen.optimize();
239 while ((line = nextLine()) != null)
241 if (line.length() == 0)
245 if (rend.search(line))
247 // End of the alignment, pass stuff back
248 this.noSeqs = seqs.size();
250 String seqdb, dbsource = null;
251 Regex pf = new Regex("PF[0-9]{5}(.*)"); // Finds AC for Pfam
252 Regex rf = new Regex("RF[0-9]{5}(.*)"); // Finds AC for Rfam
253 if (getAlignmentProperty("AC") != null)
255 String dbType = getAlignmentProperty("AC").toString();
256 if (pf.search(dbType))
258 // PFAM Alignment - so references are typically from Uniprot
261 else if (rf.search(dbType))
266 // logger.debug("Number of sequences: " + this.noSeqs);
267 for (Map.Entry<String, String> skey : seqs.entrySet())
269 // logger.debug("Processing sequence " + acc);
270 String acc = skey.getKey();
271 String seq = skey.getValue();
272 if (maxLength < seq.length())
274 maxLength = seq.length();
280 * Retrieve hash of annotations for this accession Associate
281 * Annotation with accession
283 Hashtable accAnnotations = null;
285 if (seqAnn != null && seqAnn.containsKey(acc))
287 accAnnotations = (Hashtable) seqAnn.remove(acc);
288 // TODO: add structures to sequence
291 // Split accession in id and from/to
294 sid = p.stringMatched(1);
295 start = Integer.parseInt(p.stringMatched(2));
296 end = Integer.parseInt(p.stringMatched(3));
298 // logger.debug(sid + ", " + start + ", " + end);
300 Sequence seqO = new Sequence(sid, seq, start, end);
301 // Add Description (if any)
302 if (accAnnotations != null && accAnnotations.containsKey("DE"))
304 String desc = (String) accAnnotations.get("DE");
305 seqO.setDescription((desc == null) ? "" : desc);
307 // Add DB References (if any)
308 if (accAnnotations != null && accAnnotations.containsKey("DR"))
310 String dbr = (String) accAnnotations.get("DR");
311 if (dbr != null && dbr.indexOf(";") > -1)
313 String src = dbr.substring(0, dbr.indexOf(";"));
314 String acn = dbr.substring(dbr.indexOf(";") + 1);
315 jalview.util.DBRefUtils.parseToDbRef(seqO, src, "0", acn);
319 if (accAnnotations != null && accAnnotations.containsKey("AC"))
321 if (dbsource != null)
323 String dbr = (String) accAnnotations.get("AC");
326 // we could get very clever here - but for now - just try to
327 // guess accession type from source of alignment plus structure
329 guessDatabaseFor(seqO, dbr, dbsource);
333 // else - do what ? add the data anyway and prompt the user to
334 // specify what references these are ?
337 Hashtable features = null;
338 // We need to adjust the positions of all features to account for gaps
341 features = (Hashtable) accAnnotations.remove("features");
342 } catch (java.lang.NullPointerException e)
344 // loggerwarn("Getting Features for " + acc + ": " +
348 // if we have features
349 if (features != null)
351 int posmap[] = seqO.findPositionMap();
352 Enumeration i = features.keys();
353 while (i.hasMoreElements())
355 // TODO: parse out secondary structure annotation as annotation
357 // TODO: parse out scores as annotation row
358 // TODO: map coding region to core jalview feature types
359 String type = i.nextElement().toString();
360 Hashtable content = (Hashtable) features.remove(type);
362 // add alignment annotation for this feature
363 String key = type2id(type);
366 if (accAnnotations != null
367 && accAnnotations.containsKey(key))
369 Vector vv = (Vector) accAnnotations.get(key);
370 for (int ii = 0; ii < vv.size(); ii++)
372 AlignmentAnnotation an = (AlignmentAnnotation) vv
374 seqO.addAlignmentAnnotation(an);
380 Enumeration j = content.keys();
381 while (j.hasMoreElements())
383 String desc = j.nextElement().toString();
384 String ns = content.get(desc).toString();
385 char[] byChar = ns.toCharArray();
386 for (int k = 0; k < byChar.length; k++)
389 if (!(c == ' ' || c == '_' || c == '-' || c == '.')) // PFAM
396 int new_pos = posmap[k]; // look up nearest seqeunce
397 // position to this column
398 SequenceFeature feat = new SequenceFeature(type, desc,
399 new_pos, new_pos, 0f, null);
401 seqO.addSequenceFeature(feat);
411 // logger.debug("Adding seq " + acc + " from " + start + " to " + end
413 this.seqs.addElement(seqO);
415 return; // finished parsing this segment of source
417 else if (!r.search(line))
419 // System.err.println("Found sequence line: " + line);
421 // Split sequence in sequence and accession parts
424 // logger.error("Could not parse sequence line: " + line);
425 throw new IOException(MessageManager.formatMessage(
426 "exception.couldnt_parse_sequence_line",
427 new String[] { line }));
429 String ns = seqs.get(x.stringMatched(1));
434 ns += x.stringMatched(2);
436 seqs.put(x.stringMatched(1), ns);
440 String annType = r.stringMatched(1);
441 String annContent = r.stringMatched(2);
443 // System.err.println("type:" + annType + " content: " + annContent);
445 if (annType.equals("GF"))
448 * Generic per-File annotation, free text Magic features: #=GF NH
449 * <tree in New Hampshire eXtended format> #=GF TN <Unique identifier
450 * for the next tree> Pfam descriptions: 7. DESCRIPTION OF FIELDS
452 * Compulsory fields: ------------------
454 * AC Accession number: Accession number in form PFxxxxx.version or
455 * PBxxxxxx. ID Identification: One word name for family. DE
456 * Definition: Short description of family. AU Author: Authors of the
457 * entry. SE Source of seed: The source suggesting the seed members
458 * belong to one family. GA Gathering method: Search threshold to
459 * build the full alignment. TC Trusted Cutoff: Lowest sequence score
460 * and domain score of match in the full alignment. NC Noise Cutoff:
461 * Highest sequence score and domain score of match not in full
462 * alignment. TP Type: Type of family -- presently Family, Domain,
463 * Motif or Repeat. SQ Sequence: Number of sequences in alignment. AM
464 * Alignment Method The order ls and fs hits are aligned to the model
465 * to build the full align. // End of alignment.
467 * Optional fields: ----------------
469 * DC Database Comment: Comment about database reference. DR Database
470 * Reference: Reference to external database. RC Reference Comment:
471 * Comment about literature reference. RN Reference Number: Reference
472 * Number. RM Reference Medline: Eight digit medline UI number. RT
473 * Reference Title: Reference Title. RA Reference Author: Reference
474 * Author RL Reference Location: Journal location. PI Previous
475 * identifier: Record of all previous ID lines. KW Keywords: Keywords.
476 * CC Comment: Comments. NE Pfam accession: Indicates a nested domain.
477 * NL Location: Location of nested domains - sequence ID, start and
480 * Obsolete fields: ----------- AL Alignment method of seed: The
481 * method used to align the seed members.
483 // Let's save the annotations, maybe we'll be able to do something
484 // with them later...
485 Regex an = new Regex("(\\w+)\\s*(.*)");
486 if (an.search(annContent))
488 if (an.stringMatched(1).equals("NH"))
490 treeString.append(an.stringMatched(2));
492 else if (an.stringMatched(1).equals("TN"))
494 if (treeString.length() > 0)
496 if (treeName == null)
498 treeName = "Tree " + (getTreeCount() + 1);
500 addNewickTree(treeName, treeString.toString());
502 treeName = an.stringMatched(2);
503 treeString = new StringBuffer();
505 setAlignmentProperty(an.stringMatched(1), an.stringMatched(2));
508 else if (annType.equals("GS"))
510 // Generic per-Sequence annotation, free text
512 * Pfam uses these features: Feature Description ---------------------
513 * ----------- AC <accession> ACcession number DE <freetext>
514 * DEscription DR <db>; <accession>; Database Reference OS <organism>
515 * OrganiSm (species) OC <clade> Organism Classification (clade, etc.)
516 * LO <look> Look (Color, etc.)
518 if (s.search(annContent))
520 String acc = s.stringMatched(1);
521 String type = s.stringMatched(2);
522 String content = s.stringMatched(3);
523 // TODO: store DR in a vector.
524 // TODO: store AC according to generic file db annotation.
526 if (seqAnn.containsKey(acc))
528 ann = (Hashtable) seqAnn.get(acc);
532 ann = new Hashtable();
534 ann.put(type, content);
535 seqAnn.put(acc, ann);
539 // throw new IOException(MessageManager.formatMessage(
540 // "exception.error_parsing_line", new String[] { line }));
541 System.err.println(">> missing annotation: " + line);
544 else if (annType.equals("GC"))
546 // Generic per-Column annotation, exactly 1 char per column
547 // always need a label.
548 if (x.search(annContent))
550 // parse out and create alignment annotation directly.
551 parseAnnotationRow(annotations, x.stringMatched(1),
555 else if (annType.equals("GR"))
557 // Generic per-Sequence AND per-Column markup, exactly 1 char per
560 * Feature Description Markup letters ------- -----------
561 * -------------- SS Secondary Structure [HGIEBTSCX] SA Surface
562 * Accessibility [0-9X] (0=0%-10%; ...; 9=90%-100%) TM TransMembrane
563 * [Mio] PP Posterior Probability [0-9*] (0=0.00-0.05; 1=0.05-0.15;
564 * *=0.95-1.00) LI LIgand binding [*] AS Active Site [*] IN INtron (in
567 if (s.search(annContent))
569 String acc = s.stringMatched(1);
570 String type = s.stringMatched(2);
571 String seq = new String(s.stringMatched(3));
572 String description = null;
573 // Check for additional information about the current annotation
574 // We use a simple string tokenizer here for speed
575 StringTokenizer sep = new StringTokenizer(seq, " \t");
576 description = sep.nextToken();
577 if (sep.hasMoreTokens())
579 seq = sep.nextToken();
584 description = new String();
586 // sequence id with from-to fields
589 // Get an object with all the annotations for this sequence
590 if (seqAnn.containsKey(acc))
592 // logger.debug("Found annotations for " + acc);
593 ann = (Hashtable) seqAnn.get(acc);
597 // logger.debug("Creating new annotations holder for " + acc);
598 ann = new Hashtable();
599 seqAnn.put(acc, ann);
601 // TODO test structure, call parseAnnotationRow with vector from
602 // hashtable for specific sequence
604 // Get an object with all the content for an annotation
605 if (ann.containsKey("features"))
607 // logger.debug("Found features for " + acc);
608 features = (Hashtable) ann.get("features");
612 // logger.debug("Creating new features holder for " + acc);
613 features = new Hashtable();
614 ann.put("features", features);
618 if (features.containsKey(this.id2type(type)))
620 // logger.debug("Found content for " + this.id2type(type));
621 content = (Hashtable) features.get(this.id2type(type));
625 // logger.debug("Creating new content holder for " +
626 // this.id2type(type));
627 content = new Hashtable();
628 features.put(this.id2type(type), content);
630 String ns = (String) content.get(description);
636 content.put(description, ns);
638 // if(type.equals("SS")){
640 if (seqAnn.containsKey(acc))
642 strucAnn = (Hashtable) seqAnn.get(acc);
646 strucAnn = new Hashtable();
649 Vector<AlignmentAnnotation> newStruc = new Vector<AlignmentAnnotation>();
650 parseAnnotationRow(newStruc, type, ns);
651 for (AlignmentAnnotation alan : newStruc)
653 alan.visible = false;
655 // annotations.addAll(newStruc);
656 strucAnn.put(type, newStruc);
657 seqAnn.put(acc, strucAnn);
663 .println("Warning - couldn't parse sequence annotation row line:\n"
665 // throw new IOException("Error parsing " + line);
670 throw new IOException(MessageManager.formatMessage(
671 "exception.unknown_annotation_detected", new String[] {
672 annType, annContent }));
676 if (treeString.length() > 0)
678 if (treeName == null)
680 treeName = "Tree " + (1 + getTreeCount());
682 addNewickTree(treeName, treeString.toString());
687 * Demangle an accession string and guess the originating sequence database
688 * for a given sequence
691 * sequence to be annotated
693 * Accession string for sequence
695 * source database for alignment (PFAM or RFAM)
697 private void guessDatabaseFor(Sequence seqO, String dbr, String dbsource)
699 DBRefEntry dbrf = null;
700 List<DBRefEntry> dbrs = new ArrayList<DBRefEntry>();
701 String seqdb = "Unknown", sdbac = "" + dbr;
702 int st = -1, en = -1, p;
703 if ((st = sdbac.indexOf("/")) > -1)
705 String num, range = sdbac.substring(st + 1);
706 sdbac = sdbac.substring(0, st);
707 if ((p = range.indexOf("-")) > -1)
710 if (p < range.length())
712 num = range.substring(p).trim();
715 en = Integer.parseInt(num);
716 } catch (NumberFormatException x)
718 // could warn here that index is invalid
727 num = range.substring(0, p).trim();
730 st = Integer.parseInt(num);
731 } catch (NumberFormatException x)
733 // could warn here that index is invalid
737 if (dbsource.equals("PFAM"))
740 if (sdbac.indexOf(".") > -1)
742 // strip of last subdomain
743 sdbac = sdbac.substring(0, sdbac.indexOf("."));
744 dbrf = jalview.util.DBRefUtils.parseToDbRef(seqO, seqdb, dbsource,
751 dbrf = jalview.util.DBRefUtils.parseToDbRef(seqO, dbsource, dbsource,
760 seqdb = "EMBL"; // total guess - could be ENA, or something else these
762 if (sdbac.indexOf(".") > -1)
764 // strip off last subdomain
765 sdbac = sdbac.substring(0, sdbac.indexOf("."));
766 dbrf = jalview.util.DBRefUtils.parseToDbRef(seqO, seqdb, dbsource,
774 dbrf = jalview.util.DBRefUtils.parseToDbRef(seqO, dbsource, dbsource,
781 if (st != -1 && en != -1)
783 for (DBRefEntry d : dbrs)
785 jalview.util.MapList mp = new jalview.util.MapList(new int[] {
786 seqO.getStart(), seqO.getEnd() }, new int[] { st, en }, 1, 1);
787 jalview.datamodel.Mapping mping = new Mapping(mp);
793 protected static AlignmentAnnotation parseAnnotationRow(
794 Vector annotation, String label, String annots)
796 String convert1, convert2 = null;
798 // Convert all bracket types to parentheses
799 Regex openparen = new Regex("(<|\\[)", "(");
800 Regex closeparen = new Regex("(>|\\])", ")");
802 // Detect if file is RNA by looking for bracket types
803 Regex detectbrackets = new Regex("(<|>|\\[|\\]|\\(|\\))");
805 convert1 = openparen.replaceAll(annots);
806 convert2 = closeparen.replaceAll(convert1);
810 if (label.contains("_cons"))
812 type = (label.indexOf("_cons") == label.length() - 5) ? label
813 .substring(0, label.length() - 5) : label;
816 type = id2type(type);
817 if (type.equals("secondary structure"))
821 // decide on secondary structure or not.
822 Annotation[] els = new Annotation[annots.length()];
823 for (int i = 0; i < annots.length(); i++)
825 String pos = annots.substring(i, i + 1);
827 ann = new Annotation(pos, "", ' ', 0f); // 0f is 'valid' null - will not
831 // if (" .-_".indexOf(pos) == -1)
833 if (detectbrackets.search(pos))
835 ann.secondaryStructure = jalview.schemes.ResidueProperties
836 .getRNASecStrucState(pos).charAt(0);
840 ann.secondaryStructure = jalview.schemes.ResidueProperties
841 .getDssp3state(pos).charAt(0);
844 if (ann.secondaryStructure == pos.charAt(0))
846 ann.displayCharacter = ""; // null; // " ";
850 ann.displayCharacter = " " + ann.displayCharacter;
858 AlignmentAnnotation annot = null;
859 Enumeration e = annotation.elements();
860 while (e.hasMoreElements())
862 annot = (AlignmentAnnotation) e.nextElement();
863 if (annot.label.equals(type))
871 annot = new AlignmentAnnotation(type, type, els);
872 annotation.addElement(annot);
876 Annotation[] anns = new Annotation[annot.annotations.length
878 System.arraycopy(annot.annotations, 0, anns, 0,
879 annot.annotations.length);
880 System.arraycopy(els, 0, anns, annot.annotations.length, els.length);
881 annot.annotations = anns;
882 // System.out.println("else: ");
887 public String print(SequenceI[] s)
889 // find max length of id
893 Hashtable dataRef = null;
894 while ((in < s.length) && (s[in] != null))
896 String tmp = printId(s[in]);
897 if (s[in].getSequence().length > max)
899 max = s[in].getSequence().length;
902 if (tmp.length() > maxid)
904 maxid = tmp.length();
906 if (s[in].getDBRefs() != null)
908 for (int idb = 0; idb < s[in].getDBRefs().length; idb++)
912 dataRef = new Hashtable();
915 String datAs1 = s[in].getDBRefs()[idb].getSource().toString()
917 + s[in].getDBRefs()[idb].getAccessionId().toString();
918 dataRef.put(tmp, datAs1);
926 // output database type
927 if (al.getProperties() != null)
929 if (!al.getProperties().isEmpty())
931 Enumeration key = al.getProperties().keys();
932 Enumeration val = al.getProperties().elements();
933 while (key.hasMoreElements())
935 out.append("#=GF " + key.nextElement() + " " + val.nextElement());
941 // output database accessions
944 Enumeration en = dataRef.keys();
945 while (en.hasMoreElements())
947 Object idd = en.nextElement();
948 String type = (String) dataRef.remove(idd);
949 out.append(new Format("%-" + (maxid - 2) + "s").form("#=GS "
950 + idd.toString() + " "));
951 if (type.contains("PFAM") || type.contains("RFAM"))
954 out.append(" AC " + type.substring(type.indexOf(";") + 1));
958 out.append(" DR " + type + " ");
964 // output annotations
965 while (i < s.length && s[i] != null)
967 if (s[i].getDatasetSequence() != null)
969 SequenceI ds = s[i].getDatasetSequence();
970 AlignmentAnnotation[] alAnot;
973 alAnot = s[i].getAnnotation();
977 for (int j = 0; j < alAnot.length; j++)
979 if (ds.getSequenceFeatures() != null)
981 feature = ds.getSequenceFeatures()[0].type;
983 // ?bug - feature may still have previous loop value
984 String key = type2id(feature);
991 // out.append("#=GR ");
992 out.append(new Format("%-" + maxid + "s").form("#=GR "
993 + printId(s[i]) + " " + key + " "));
994 ann = alAnot[j].annotations;
995 boolean isrna = alAnot[j].isValidStruc();
997 for (int k = 0; k < ann.length; k++)
999 seq += outputCharacter(key, k, isrna, ann, s[i]);
1002 out.append(newline);
1007 out.append(new Format("%-" + maxid + "s").form(printId(s[i]) + " "));
1008 out.append(s[i].getSequenceAsString());
1009 out.append(newline);
1013 // alignment annotation
1014 AlignmentAnnotation aa;
1015 if (al.getAlignmentAnnotation() != null)
1017 for (int ia = 0; ia < al.getAlignmentAnnotation().length; ia++)
1019 aa = al.getAlignmentAnnotation()[ia];
1020 if (aa.autoCalculated || !aa.visible || aa.sequenceRef != null)
1027 if (aa.label.equals("seq"))
1033 key = type2id(aa.label.toLowerCase());
1040 label = key + "_cons";
1047 label = label.replace(" ", "_");
1049 out.append(new Format("%-" + maxid + "s").form("#=GC " + label
1051 boolean isrna = aa.isValidStruc();
1052 for (int j = 0; j < aa.annotations.length; j++)
1054 seq += outputCharacter(key, j, isrna, aa.annotations, null);
1057 out.append(newline);
1060 return out.toString();
1064 * add an annotation character to the output row
1073 private char outputCharacter(String key, int k, boolean isrna,
1074 Annotation[] ann, SequenceI sequenceI)
1077 Annotation annot = ann[k];
1078 String ch = (annot == null) ? ((sequenceI == null) ? "-" : Character
1079 .toString(sequenceI.getCharAt(k))) : annot.displayCharacter;
1080 if (key != null && key.equals("SS"))
1084 // sensible gap character if one is available or make one up
1085 return sequenceI == null ? '-' : sequenceI.getCharAt(k);
1089 // valid secondary structure AND no alternative label (e.g. ' B')
1090 if (annot.secondaryStructure > ' ' && ch.length() < 2)
1092 return annot.secondaryStructure;
1097 if (ch.length() == 0)
1101 else if (ch.length() == 1)
1105 else if (ch.length() > 1)
1113 public String print()
1115 out = new StringBuffer();
1116 out.append("# STOCKHOLM 1.0");
1117 out.append(newline);
1118 print(getSeqsAsArray());
1121 out.append(newline);
1122 return out.toString();
1125 private static Hashtable typeIds = null;
1128 if (typeIds == null)
1130 typeIds = new Hashtable();
1131 typeIds.put("SS", "secondary structure");
1132 typeIds.put("SA", "surface accessibility");
1133 typeIds.put("TM", "transmembrane");
1134 typeIds.put("PP", "posterior probability");
1135 typeIds.put("LI", "ligand binding");
1136 typeIds.put("AS", "active site");
1137 typeIds.put("IN", "intron");
1138 typeIds.put("IR", "interacting residue");
1139 typeIds.put("AC", "accession");
1140 typeIds.put("OS", "organism");
1141 typeIds.put("CL", "class");
1142 typeIds.put("DE", "description");
1143 typeIds.put("DR", "reference");
1144 typeIds.put("LO", "look");
1145 typeIds.put("RF", "reference positions");
1150 protected static String id2type(String id)
1152 if (typeIds.containsKey(id))
1154 return (String) typeIds.get(id);
1156 System.err.println("Warning : Unknown Stockholm annotation type code "
1161 protected static String type2id(String type)
1164 Enumeration e = typeIds.keys();
1165 while (e.hasMoreElements())
1167 Object ll = e.nextElement();
1168 if (typeIds.get(ll).toString().equals(type))
1178 System.err.println("Warning : Unknown Stockholm annotation type: "
1184 * make a friendly ID string.
1187 * @return truncated dataName to after last '/'
1189 private String safeName(String dataName)
1192 while ((b = dataName.indexOf("/")) > -1 && b < dataName.length())
1194 dataName = dataName.substring(b + 1).trim();
1197 int e = (dataName.length() - dataName.indexOf(".")) + 1;
1198 dataName = dataName.substring(1, e).trim();