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.Format;
37 import jalview.util.MessageManager;
39 import java.io.BufferedReader;
40 import java.io.FileReader;
41 import java.io.IOException;
42 import java.util.ArrayList;
43 import java.util.Enumeration;
44 import java.util.Hashtable;
45 import java.util.LinkedHashMap;
46 import java.util.List;
48 import java.util.StringTokenizer;
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 Regex OPEN_PAREN = new Regex("(<|\\[)", "(");
79 private static final Regex CLOSE_PAREN = new Regex("(>|\\])", ")");
81 private static final Regex DETECT_BRACKETS = new Regex(
82 "(<|>|\\[|\\]|\\(|\\))");
84 StringBuffer out; // output buffer
88 public StockholmFile()
93 * Creates a new StockholmFile object for output.
95 public StockholmFile(AlignmentI al)
100 public StockholmFile(String inFile, String type) throws IOException
105 public StockholmFile(FileParse source) throws IOException
111 public void initData()
117 * Parse a file in Stockholm format into Jalview's data model using VARNA
119 * @throws IOException
120 * If there is an error with the input file
122 public void parse_with_VARNA(java.io.File inFile) throws IOException
124 FileReader fr = null;
125 fr = new FileReader(inFile);
127 BufferedReader r = new BufferedReader(fr);
128 List<RNA> result = null;
131 result = RNAFactory.loadSecStrStockholm(r);
132 } catch (ExceptionUnmatchedClosingParentheses umcp)
134 errormessage = "Unmatched parentheses in annotation. Aborting ("
135 + umcp.getMessage() + ")";
136 throw new IOException(umcp);
138 // DEBUG System.out.println("this is the secondary scructure:"
140 SequenceI[] seqs = new SequenceI[result.size()];
142 for (int i = 0; i < result.size(); i++)
144 // DEBUG System.err.println("Processing i'th sequence in Stockholm file")
145 RNA current = result.get(i);
147 String seq = current.getSeq();
148 String rna = current.getStructDBN(true);
149 // DEBUG System.out.println(seq);
150 // DEBUG System.err.println(rna);
152 int end = seq.length() - 1;
153 id = safeName(getDataName());
154 seqs[i] = new Sequence(id, seq, begin, end);
155 String[] annot = new String[rna.length()];
156 Annotation[] ann = new Annotation[rna.length()];
157 for (int j = 0; j < rna.length(); j++)
159 annot[j] = rna.substring(j, j + 1);
163 for (int k = 0; k < rna.length(); k++)
165 ann[k] = new Annotation(annot[k], "", Rna.getRNASecStrucState(
166 annot[k]).charAt(0), 0f);
169 AlignmentAnnotation align = new AlignmentAnnotation("Sec. str.",
170 current.getID(), ann);
172 seqs[i].addAlignmentAnnotation(align);
173 seqs[i].setRNA(result.get(i));
174 this.annotations.addElement(align);
181 * Parse a file in Stockholm format into Jalview's data model. The file has to
182 * be passed at construction time
184 * @throws IOException
185 * If there is an error with the input file
188 public void parse() throws IOException
190 StringBuffer treeString = new StringBuffer();
191 String treeName = null;
192 // --------------- Variable Definitions -------------------
196 Hashtable seqAnn = new Hashtable(); // Sequence related annotations
197 LinkedHashMap<String, String> seqs = new LinkedHashMap<String, String>();
198 Regex p, r, rend, s, x;
199 // Temporary line for processing RNA annotation
200 // String RNAannot = "";
202 // ------------------ Parsing File ----------------------
203 // First, we have to check that this file has STOCKHOLM format, i.e. the
204 // first line must match
206 r = new Regex("# STOCKHOLM ([\\d\\.]+)");
207 if (!r.search(nextLine()))
209 throw new IOException(
211 .getString("exception.stockholm_invalid_format"));
215 version = r.stringMatched(1);
217 // logger.debug("Stockholm version: " + version);
220 // We define some Regexes here that will be used regularily later
221 rend = new Regex("^\\s*\\/\\/"); // Find the end of an alignment
222 p = new Regex("(\\S+)\\/(\\d+)\\-(\\d+)"); // split sequence id in
224 s = new Regex("(\\S+)\\s+(\\S*)\\s+(.*)"); // Parses annotation subtype
225 r = new Regex("#=(G[FSRC]?)\\s+(.*)"); // Finds any annotation line
226 x = new Regex("(\\S+)\\s+(\\S+)"); // split id from sequence
228 // Convert all bracket types to parentheses (necessary for passing to VARNA)
229 Regex openparen = new Regex("(<|\\[)", "(");
230 Regex closeparen = new Regex("(>|\\])", ")");
232 // Detect if file is RNA by looking for bracket types
233 Regex detectbrackets = new Regex("(<|>|\\[|\\]|\\(|\\))");
240 openparen.optimize();
241 closeparen.optimize();
243 while ((line = nextLine()) != null)
245 if (line.length() == 0)
249 if (rend.search(line))
251 // End of the alignment, pass stuff back
252 this.noSeqs = seqs.size();
254 String seqdb, dbsource = null;
255 Regex pf = new Regex("PF[0-9]{5}(.*)"); // Finds AC for Pfam
256 Regex rf = new Regex("RF[0-9]{5}(.*)"); // Finds AC for Rfam
257 if (getAlignmentProperty("AC") != null)
259 String dbType = getAlignmentProperty("AC").toString();
260 if (pf.search(dbType))
262 // PFAM Alignment - so references are typically from Uniprot
265 else if (rf.search(dbType))
270 // logger.debug("Number of sequences: " + this.noSeqs);
271 for (Map.Entry<String, String> skey : seqs.entrySet())
273 // logger.debug("Processing sequence " + acc);
274 String acc = skey.getKey();
275 String seq = skey.getValue();
276 if (maxLength < seq.length())
278 maxLength = seq.length();
284 * Retrieve hash of annotations for this accession Associate
285 * Annotation with accession
287 Hashtable accAnnotations = null;
289 if (seqAnn != null && seqAnn.containsKey(acc))
291 accAnnotations = (Hashtable) seqAnn.remove(acc);
292 // TODO: add structures to sequence
295 // Split accession in id and from/to
298 sid = p.stringMatched(1);
299 start = Integer.parseInt(p.stringMatched(2));
300 end = Integer.parseInt(p.stringMatched(3));
302 // logger.debug(sid + ", " + start + ", " + end);
304 Sequence seqO = new Sequence(sid, seq, start, end);
305 // Add Description (if any)
306 if (accAnnotations != null && accAnnotations.containsKey("DE"))
308 String desc = (String) accAnnotations.get("DE");
309 seqO.setDescription((desc == null) ? "" : desc);
311 // Add DB References (if any)
312 if (accAnnotations != null && accAnnotations.containsKey("DR"))
314 String dbr = (String) accAnnotations.get("DR");
315 if (dbr != null && dbr.indexOf(";") > -1)
317 String src = dbr.substring(0, dbr.indexOf(";"));
318 String acn = dbr.substring(dbr.indexOf(";") + 1);
319 jalview.util.DBRefUtils.parseToDbRef(seqO, src, "0", acn);
323 if (accAnnotations != null && accAnnotations.containsKey("AC"))
325 if (dbsource != null)
327 String dbr = (String) accAnnotations.get("AC");
330 // we could get very clever here - but for now - just try to
331 // guess accession type from source of alignment plus structure
333 guessDatabaseFor(seqO, dbr, dbsource);
337 // else - do what ? add the data anyway and prompt the user to
338 // specify what references these are ?
341 Hashtable features = null;
342 // We need to adjust the positions of all features to account for gaps
345 features = (Hashtable) accAnnotations.remove("features");
346 } catch (java.lang.NullPointerException e)
348 // loggerwarn("Getting Features for " + acc + ": " +
352 // if we have features
353 if (features != null)
355 int posmap[] = seqO.findPositionMap();
356 Enumeration i = features.keys();
357 while (i.hasMoreElements())
359 // TODO: parse out secondary structure annotation as annotation
361 // TODO: parse out scores as annotation row
362 // TODO: map coding region to core jalview feature types
363 String type = i.nextElement().toString();
364 Hashtable content = (Hashtable) features.remove(type);
366 // add alignment annotation for this feature
367 String key = type2id(type);
370 if (accAnnotations != null
371 && accAnnotations.containsKey(key))
373 Vector vv = (Vector) accAnnotations.get(key);
374 for (int ii = 0; ii < vv.size(); ii++)
376 AlignmentAnnotation an = (AlignmentAnnotation) vv
378 seqO.addAlignmentAnnotation(an);
384 Enumeration j = content.keys();
385 while (j.hasMoreElements())
387 String desc = j.nextElement().toString();
388 String ns = content.get(desc).toString();
389 char[] byChar = ns.toCharArray();
390 for (int k = 0; k < byChar.length; k++)
393 if (!(c == ' ' || c == '_' || c == '-' || c == '.')) // PFAM
400 int new_pos = posmap[k]; // look up nearest seqeunce
401 // position to this column
402 SequenceFeature feat = new SequenceFeature(type, desc,
403 new_pos, new_pos, 0f, null);
405 seqO.addSequenceFeature(feat);
415 // logger.debug("Adding seq " + acc + " from " + start + " to " + end
417 this.seqs.addElement(seqO);
419 return; // finished parsing this segment of source
421 else if (!r.search(line))
423 // System.err.println("Found sequence line: " + line);
425 // Split sequence in sequence and accession parts
428 // logger.error("Could not parse sequence line: " + line);
429 throw new IOException(MessageManager.formatMessage(
430 "exception.couldnt_parse_sequence_line",
431 new String[] { line }));
433 String ns = seqs.get(x.stringMatched(1));
438 ns += x.stringMatched(2);
440 seqs.put(x.stringMatched(1), ns);
444 String annType = r.stringMatched(1);
445 String annContent = r.stringMatched(2);
447 // System.err.println("type:" + annType + " content: " + annContent);
449 if (annType.equals("GF"))
452 * Generic per-File annotation, free text Magic features: #=GF NH
453 * <tree in New Hampshire eXtended format> #=GF TN <Unique identifier
454 * for the next tree> Pfam descriptions: 7. DESCRIPTION OF FIELDS
456 * Compulsory fields: ------------------
458 * AC Accession number: Accession number in form PFxxxxx.version or
459 * PBxxxxxx. ID Identification: One word name for family. DE
460 * Definition: Short description of family. AU Author: Authors of the
461 * entry. SE Source of seed: The source suggesting the seed members
462 * belong to one family. GA Gathering method: Search threshold to
463 * build the full alignment. TC Trusted Cutoff: Lowest sequence score
464 * and domain score of match in the full alignment. NC Noise Cutoff:
465 * Highest sequence score and domain score of match not in full
466 * alignment. TP Type: Type of family -- presently Family, Domain,
467 * Motif or Repeat. SQ Sequence: Number of sequences in alignment. AM
468 * Alignment Method The order ls and fs hits are aligned to the model
469 * to build the full align. // End of alignment.
471 * Optional fields: ----------------
473 * DC Database Comment: Comment about database reference. DR Database
474 * Reference: Reference to external database. RC Reference Comment:
475 * Comment about literature reference. RN Reference Number: Reference
476 * Number. RM Reference Medline: Eight digit medline UI number. RT
477 * Reference Title: Reference Title. RA Reference Author: Reference
478 * Author RL Reference Location: Journal location. PI Previous
479 * identifier: Record of all previous ID lines. KW Keywords: Keywords.
480 * CC Comment: Comments. NE Pfam accession: Indicates a nested domain.
481 * NL Location: Location of nested domains - sequence ID, start and
484 * Obsolete fields: ----------- AL Alignment method of seed: The
485 * method used to align the seed members.
487 // Let's save the annotations, maybe we'll be able to do something
488 // with them later...
489 Regex an = new Regex("(\\w+)\\s*(.*)");
490 if (an.search(annContent))
492 if (an.stringMatched(1).equals("NH"))
494 treeString.append(an.stringMatched(2));
496 else if (an.stringMatched(1).equals("TN"))
498 if (treeString.length() > 0)
500 if (treeName == null)
502 treeName = "Tree " + (getTreeCount() + 1);
504 addNewickTree(treeName, treeString.toString());
506 treeName = an.stringMatched(2);
507 treeString = new StringBuffer();
509 setAlignmentProperty(an.stringMatched(1), an.stringMatched(2));
512 else if (annType.equals("GS"))
514 // Generic per-Sequence annotation, free text
516 * Pfam uses these features: Feature Description ---------------------
517 * ----------- AC <accession> ACcession number DE <freetext>
518 * DEscription DR <db>; <accession>; Database Reference OS <organism>
519 * OrganiSm (species) OC <clade> Organism Classification (clade, etc.)
520 * LO <look> Look (Color, etc.)
522 if (s.search(annContent))
524 String acc = s.stringMatched(1);
525 String type = s.stringMatched(2);
526 String content = s.stringMatched(3);
527 // TODO: store DR in a vector.
528 // TODO: store AC according to generic file db annotation.
530 if (seqAnn.containsKey(acc))
532 ann = (Hashtable) seqAnn.get(acc);
536 ann = new Hashtable();
538 ann.put(type, content);
539 seqAnn.put(acc, ann);
543 // throw new IOException(MessageManager.formatMessage(
544 // "exception.error_parsing_line", new String[] { line }));
545 System.err.println(">> missing annotation: " + line);
548 else if (annType.equals("GC"))
550 // Generic per-Column annotation, exactly 1 char per column
551 // always need a label.
552 if (x.search(annContent))
554 // parse out and create alignment annotation directly.
555 parseAnnotationRow(annotations, x.stringMatched(1),
559 else if (annType.equals("GR"))
561 // Generic per-Sequence AND per-Column markup, exactly 1 char per
564 * Feature Description Markup letters ------- -----------
565 * -------------- SS Secondary Structure [HGIEBTSCX] SA Surface
566 * Accessibility [0-9X] (0=0%-10%; ...; 9=90%-100%) TM TransMembrane
567 * [Mio] PP Posterior Probability [0-9*] (0=0.00-0.05; 1=0.05-0.15;
568 * *=0.95-1.00) LI LIgand binding [*] AS Active Site [*] IN INtron (in
571 if (s.search(annContent))
573 String acc = s.stringMatched(1);
574 String type = s.stringMatched(2);
575 String seq = new String(s.stringMatched(3));
576 String description = null;
577 // Check for additional information about the current annotation
578 // We use a simple string tokenizer here for speed
579 StringTokenizer sep = new StringTokenizer(seq, " \t");
580 description = sep.nextToken();
581 if (sep.hasMoreTokens())
583 seq = sep.nextToken();
588 description = new String();
590 // sequence id with from-to fields
593 // Get an object with all the annotations for this sequence
594 if (seqAnn.containsKey(acc))
596 // logger.debug("Found annotations for " + acc);
597 ann = (Hashtable) seqAnn.get(acc);
601 // logger.debug("Creating new annotations holder for " + acc);
602 ann = new Hashtable();
603 seqAnn.put(acc, ann);
605 // TODO test structure, call parseAnnotationRow with vector from
606 // hashtable for specific sequence
608 // Get an object with all the content for an annotation
609 if (ann.containsKey("features"))
611 // logger.debug("Found features for " + acc);
612 features = (Hashtable) ann.get("features");
616 // logger.debug("Creating new features holder for " + acc);
617 features = new Hashtable();
618 ann.put("features", features);
622 if (features.containsKey(this.id2type(type)))
624 // logger.debug("Found content for " + this.id2type(type));
625 content = (Hashtable) features.get(this.id2type(type));
629 // logger.debug("Creating new content holder for " +
630 // this.id2type(type));
631 content = new Hashtable();
632 features.put(this.id2type(type), content);
634 String ns = (String) content.get(description);
640 content.put(description, ns);
642 // if(type.equals("SS")){
644 if (seqAnn.containsKey(acc))
646 strucAnn = (Hashtable) seqAnn.get(acc);
650 strucAnn = new Hashtable();
653 Vector<AlignmentAnnotation> newStruc = new Vector<AlignmentAnnotation>();
654 parseAnnotationRow(newStruc, type, ns);
655 for (AlignmentAnnotation alan : newStruc)
657 alan.visible = false;
659 // annotations.addAll(newStruc);
660 strucAnn.put(type, newStruc);
661 seqAnn.put(acc, strucAnn);
667 .println("Warning - couldn't parse sequence annotation row line:\n"
669 // throw new IOException("Error parsing " + line);
674 throw new IOException(MessageManager.formatMessage(
675 "exception.unknown_annotation_detected", new String[] {
676 annType, annContent }));
680 if (treeString.length() > 0)
682 if (treeName == null)
684 treeName = "Tree " + (1 + getTreeCount());
686 addNewickTree(treeName, treeString.toString());
691 * Demangle an accession string and guess the originating sequence database
692 * for a given sequence
695 * sequence to be annotated
697 * Accession string for sequence
699 * source database for alignment (PFAM or RFAM)
701 private void guessDatabaseFor(Sequence seqO, String dbr, String dbsource)
703 DBRefEntry dbrf = null;
704 List<DBRefEntry> dbrs = new ArrayList<DBRefEntry>();
705 String seqdb = "Unknown", sdbac = "" + dbr;
706 int st = -1, en = -1, p;
707 if ((st = sdbac.indexOf("/")) > -1)
709 String num, range = sdbac.substring(st + 1);
710 sdbac = sdbac.substring(0, st);
711 if ((p = range.indexOf("-")) > -1)
714 if (p < range.length())
716 num = range.substring(p).trim();
719 en = Integer.parseInt(num);
720 } catch (NumberFormatException x)
722 // could warn here that index is invalid
731 num = range.substring(0, p).trim();
734 st = Integer.parseInt(num);
735 } catch (NumberFormatException x)
737 // could warn here that index is invalid
741 if (dbsource.equals("PFAM"))
744 if (sdbac.indexOf(".") > -1)
746 // strip of last subdomain
747 sdbac = sdbac.substring(0, sdbac.indexOf("."));
748 dbrf = jalview.util.DBRefUtils.parseToDbRef(seqO, seqdb, dbsource,
755 dbrf = jalview.util.DBRefUtils.parseToDbRef(seqO, dbsource, dbsource,
764 seqdb = "EMBL"; // total guess - could be ENA, or something else these
766 if (sdbac.indexOf(".") > -1)
768 // strip off last subdomain
769 sdbac = sdbac.substring(0, sdbac.indexOf("."));
770 dbrf = jalview.util.DBRefUtils.parseToDbRef(seqO, seqdb, dbsource,
778 dbrf = jalview.util.DBRefUtils.parseToDbRef(seqO, dbsource, dbsource,
785 if (st != -1 && en != -1)
787 for (DBRefEntry d : dbrs)
789 jalview.util.MapList mp = new jalview.util.MapList(new int[] {
790 seqO.getStart(), seqO.getEnd() }, new int[] { st, en }, 1, 1);
791 jalview.datamodel.Mapping mping = new Mapping(mp);
797 protected static AlignmentAnnotation parseAnnotationRow(
798 Vector<AlignmentAnnotation> annotation, String label,
801 String convert1, convert2 = null;
803 convert1 = OPEN_PAREN.replaceAll(annots);
804 convert2 = CLOSE_PAREN.replaceAll(convert1);
808 if (label.contains("_cons"))
810 type = (label.indexOf("_cons") == label.length() - 5) ? label
811 .substring(0, label.length() - 5) : label;
814 type = id2type(type);
815 if (type.equals("secondary structure"))
819 // decide on secondary structure or not.
820 Annotation[] els = new Annotation[annots.length()];
821 for (int i = 0; i < annots.length(); i++)
823 String pos = annots.substring(i, i + 1);
825 ann = new Annotation(pos, "", ' ', 0f); // 0f is 'valid' null - will not
829 // if (" .-_".indexOf(pos) == -1)
831 if (DETECT_BRACKETS.search(pos))
833 ann.secondaryStructure = Rna.getRNASecStrucState(
838 ann.secondaryStructure = ResidueProperties.getDssp3state(pos)
842 if (ann.secondaryStructure == pos.charAt(0))
844 ann.displayCharacter = ""; // null; // " ";
848 ann.displayCharacter = " " + ann.displayCharacter;
856 AlignmentAnnotation annot = null;
857 Enumeration<AlignmentAnnotation> e = annotation.elements();
858 while (e.hasMoreElements())
860 annot = e.nextElement();
861 if (annot.label.equals(type))
869 annot = new AlignmentAnnotation(type, type, els);
870 annotation.addElement(annot);
874 Annotation[] anns = new Annotation[annot.annotations.length
876 System.arraycopy(annot.annotations, 0, anns, 0,
877 annot.annotations.length);
878 System.arraycopy(els, 0, anns, annot.annotations.length, els.length);
879 annot.annotations = anns;
880 // System.out.println("else: ");
885 public String print(SequenceI[] s)
887 // find max length of id
891 Hashtable dataRef = null;
892 while ((in < s.length) && (s[in] != null))
894 String tmp = printId(s[in]);
895 if (s[in].getSequence().length > max)
897 max = s[in].getSequence().length;
900 if (tmp.length() > maxid)
902 maxid = tmp.length();
904 if (s[in].getDBRefs() != null)
906 for (int idb = 0; idb < s[in].getDBRefs().length; idb++)
910 dataRef = new Hashtable();
913 String datAs1 = s[in].getDBRefs()[idb].getSource().toString()
915 + s[in].getDBRefs()[idb].getAccessionId().toString();
916 dataRef.put(tmp, datAs1);
924 // output database type
925 if (al.getProperties() != null)
927 if (!al.getProperties().isEmpty())
929 Enumeration key = al.getProperties().keys();
930 Enumeration val = al.getProperties().elements();
931 while (key.hasMoreElements())
933 out.append("#=GF " + key.nextElement() + " " + val.nextElement());
939 // output database accessions
942 Enumeration en = dataRef.keys();
943 while (en.hasMoreElements())
945 Object idd = en.nextElement();
946 String type = (String) dataRef.remove(idd);
947 out.append(new Format("%-" + (maxid - 2) + "s").form("#=GS "
948 + idd.toString() + " "));
949 if (type.contains("PFAM") || type.contains("RFAM"))
952 out.append(" AC " + type.substring(type.indexOf(";") + 1));
956 out.append(" DR " + type + " ");
962 // output annotations
963 while (i < s.length && s[i] != null)
965 if (s[i].getDatasetSequence() != null)
967 SequenceI ds = s[i].getDatasetSequence();
968 AlignmentAnnotation[] alAnot;
971 alAnot = s[i].getAnnotation();
975 for (int j = 0; j < alAnot.length; j++)
977 if (ds.getSequenceFeatures() != null)
979 feature = ds.getSequenceFeatures()[0].type;
981 // ?bug - feature may still have previous loop value
982 String key = type2id(feature);
989 // out.append("#=GR ");
990 out.append(new Format("%-" + maxid + "s").form("#=GR "
991 + printId(s[i]) + " " + key + " "));
992 ann = alAnot[j].annotations;
993 boolean isrna = alAnot[j].isValidStruc();
995 for (int k = 0; k < ann.length; k++)
997 seq += outputCharacter(key, k, isrna, ann, s[i]);
1000 out.append(newline);
1005 out.append(new Format("%-" + maxid + "s").form(printId(s[i]) + " "));
1006 out.append(s[i].getSequenceAsString());
1007 out.append(newline);
1011 // alignment annotation
1012 AlignmentAnnotation aa;
1013 if (al.getAlignmentAnnotation() != null)
1015 for (int ia = 0; ia < al.getAlignmentAnnotation().length; ia++)
1017 aa = al.getAlignmentAnnotation()[ia];
1018 if (aa.autoCalculated || !aa.visible || aa.sequenceRef != null)
1025 if (aa.label.equals("seq"))
1031 key = type2id(aa.label.toLowerCase());
1038 label = key + "_cons";
1045 label = label.replace(" ", "_");
1047 out.append(new Format("%-" + maxid + "s").form("#=GC " + label
1049 boolean isrna = aa.isValidStruc();
1050 for (int j = 0; j < aa.annotations.length; j++)
1052 seq += outputCharacter(key, j, isrna, aa.annotations, null);
1055 out.append(newline);
1058 return out.toString();
1062 * add an annotation character to the output row
1071 private char outputCharacter(String key, int k, boolean isrna,
1072 Annotation[] ann, SequenceI sequenceI)
1075 Annotation annot = ann[k];
1076 String ch = (annot == null) ? ((sequenceI == null) ? "-" : Character
1077 .toString(sequenceI.getCharAt(k))) : annot.displayCharacter;
1078 if (key != null && key.equals("SS"))
1082 // sensible gap character if one is available or make one up
1083 return sequenceI == null ? '-' : sequenceI.getCharAt(k);
1087 // valid secondary structure AND no alternative label (e.g. ' B')
1088 if (annot.secondaryStructure > ' ' && ch.length() < 2)
1090 return annot.secondaryStructure;
1095 if (ch.length() == 0)
1099 else if (ch.length() == 1)
1103 else if (ch.length() > 1)
1111 public String print()
1113 out = new StringBuffer();
1114 out.append("# STOCKHOLM 1.0");
1115 out.append(newline);
1116 print(getSeqsAsArray());
1119 out.append(newline);
1120 return out.toString();
1123 private static Hashtable typeIds = null;
1127 if (typeIds == null)
1129 typeIds = new Hashtable();
1130 typeIds.put("SS", "secondary structure");
1131 typeIds.put("SA", "surface accessibility");
1132 typeIds.put("TM", "transmembrane");
1133 typeIds.put("PP", "posterior probability");
1134 typeIds.put("LI", "ligand binding");
1135 typeIds.put("AS", "active site");
1136 typeIds.put("IN", "intron");
1137 typeIds.put("IR", "interacting residue");
1138 typeIds.put("AC", "accession");
1139 typeIds.put("OS", "organism");
1140 typeIds.put("CL", "class");
1141 typeIds.put("DE", "description");
1142 typeIds.put("DR", "reference");
1143 typeIds.put("LO", "look");
1144 typeIds.put("RF", "reference positions");
1149 protected static String id2type(String id)
1151 if (typeIds.containsKey(id))
1153 return (String) typeIds.get(id);
1155 System.err.println("Warning : Unknown Stockholm annotation type code "
1160 protected static String type2id(String type)
1163 Enumeration e = typeIds.keys();
1164 while (e.hasMoreElements())
1166 Object ll = e.nextElement();
1167 if (typeIds.get(ll).toString().equals(type))
1177 System.err.println("Warning : Unknown Stockholm annotation type: "
1183 * make a friendly ID string.
1186 * @return truncated dataName to after last '/'
1188 private String safeName(String dataName)
1191 while ((b = dataName.indexOf("/")) > -1 && b < dataName.length())
1193 dataName = dataName.substring(b + 1).trim();
1196 int e = (dataName.length() - dataName.indexOf(".")) + 1;
1197 dataName = dataName.substring(1, e).trim();