Clover icon

Coverage Report

  1. Project Clover database Thu Dec 4 2025 16:11:35 GMT
  2. Package jalview.io

File StockholmFile.java

 

Coverage histogram

../../img/srcFileCovDistChart8.png
20% of files have more coverage

Code metrics

256
530
18
1
1,410
1,020
192
0.36
29.44
18
10.67

Classes

Class Line # Actions
StockholmFile 77 530 192
0.7748756477.5%
 

Contributing tests

This file is covered by 24 tests. .

Source view

1    /*
2    * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3    * Copyright (C) $$Year-Rel$$ The Jalview Authors
4    *
5    * This file is part of Jalview.
6    *
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.
11    *
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.
16    *
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.
20    */
21    /*
22    * This extension was written by Benjamin Schuster-Boeckler at sanger.ac.uk
23    */
24    package jalview.io;
25   
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.DBRefSource;
32    import jalview.datamodel.Mapping;
33    import jalview.datamodel.Sequence;
34    import jalview.datamodel.SequenceFeature;
35    import jalview.datamodel.SequenceI;
36    import jalview.schemes.ResidueProperties;
37    import jalview.util.Comparison;
38    import jalview.util.DBRefUtils;
39    import jalview.util.Format;
40    import jalview.util.MessageManager;
41    import jalview.util.Platform;
42   
43    import java.io.BufferedReader;
44    import java.io.FileReader;
45    import java.io.IOException;
46    import java.util.ArrayList;
47    import java.util.Enumeration;
48    import java.util.Hashtable;
49    import java.util.LinkedHashMap;
50    import java.util.List;
51    import java.util.Locale;
52    import java.util.Map;
53    import java.util.Vector;
54   
55    import com.stevesoft.pat.Regex;
56   
57    import fr.orsay.lri.varna.exceptions.ExceptionUnmatchedClosingParentheses;
58    import fr.orsay.lri.varna.factories.RNAFactory;
59    import fr.orsay.lri.varna.models.rna.RNA;
60   
61    /**
62    * This class is supposed to parse a Stockholm format file into Jalview There
63    * are TODOs in this class: we do not know what the database source and version
64    * is for the file when parsing the #GS= AC tag which associates accessions with
65    * sequences. Database references are also not parsed correctly: a separate
66    * reference string parser must be added to parse the database reference form
67    * into Jalview's local representation.
68    *
69    * @author bsb at sanger.ac.uk
70    * @author Natasha Shersnev (Dundee, UK) (Stockholm file writer)
71    * @author Lauren Lui (UCSC, USA) (RNA secondary structure annotation import as
72    * stockholm)
73    * @author Anne Menard (Paris, FR) (VARNA parsing of Stockholm file data)
74    * @version 0.3 + jalview mods
75    *
76    */
 
77    public class StockholmFile extends AlignFile
78    {
79    private static final String ANNOTATION = "annotation";
80   
81    private static final char UNDERSCORE = '_';
82   
83    // WUSS extended symbols. Avoid ambiguity with protein SS annotations by using NOT_RNASS first.
84   
85    public static final String RNASS_BRACKETS = "<>[](){}AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz";
86   
87    public static final int REGEX_STOCKHOLM = 0;
88   
89    public static final int REGEX_BRACKETS = 1;
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    public static final int REGEX_NOT_RNASS = 2;
93   
94    private static final int REGEX_ANNOTATION = 3;
95   
96    private static final int REGEX_PFAM = 4;
97   
98    private static final int REGEX_RFAM = 5;
99   
100    private static final int REGEX_ALIGN_END = 6;
101   
102    private static final int REGEX_SPLIT_ID = 7;
103   
104    private static final int REGEX_SUBTYPE = 8;
105   
106    private static final int REGEX_ANNOTATION_LINE = 9;
107   
108    private static final int REGEX_REMOVE_ID = 10;
109   
110    private static final int REGEX_OPEN_PAREN = 11;
111   
112    private static final int REGEX_CLOSE_PAREN = 12;
113   
114    public static final int REGEX_MAX = 13;
115   
116    private static Regex REGEX[] = new Regex[REGEX_MAX];
117   
118    /**
119    * Centralize all actual Regex instantialization in Platform.
120    * // JBPNote: Why is this 'centralisation' better ?
121    * @param id
122    * @return
123    */
 
124  955 toggle private static Regex getRegex(int id)
125    {
126  955 if (REGEX[id] == null)
127    {
128  12 String pat = null, pat2 = null;
129  12 switch (id)
130    {
131  1 case REGEX_STOCKHOLM:
132  1 pat = "# STOCKHOLM ([\\d\\.]+)";
133  1 break;
134  0 case REGEX_BRACKETS:
135    // for reference; not used
136  0 pat = "(<|>|\\[|\\]|\\(|\\)|\\{|\\})";
137  0 break;
138  1 case REGEX_NOT_RNASS:
139  1 pat = "^[^<>[\\](){}ADFJ-RUVWYZadfj-ruvwyz]*$"; // update 2.11.2
140  1 break;
141  1 case REGEX_ANNOTATION:
142  1 pat = "(\\w+)\\s*(.*)";
143  1 break;
144  1 case REGEX_PFAM:
145  1 pat = "PF[0-9]{5}(.*)";
146  1 break;
147  1 case REGEX_RFAM:
148  1 pat = "RF[0-9]{5}(.*)";
149  1 break;
150  1 case REGEX_ALIGN_END:
151  1 pat = "^\\s*\\/\\/";
152  1 break;
153  1 case REGEX_SPLIT_ID:
154  1 pat = "(\\S+)\\/(\\d+)\\-(\\d+)";
155  1 break;
156  1 case REGEX_SUBTYPE:
157  1 pat = "(\\S+)\\s+(\\S*)\\s+(.*)";
158  1 break;
159  1 case REGEX_ANNOTATION_LINE:
160  1 pat = "#=(G[FSRC]?)\\s+(.*)";
161  1 break;
162  1 case REGEX_REMOVE_ID:
163  1 pat = "(\\S+)\\s+(\\S+)";
164  1 break;
165  1 case REGEX_OPEN_PAREN:
166  1 pat = "(<|\\[)";
167  1 pat2 = "(";
168  1 break;
169  1 case REGEX_CLOSE_PAREN:
170  1 pat = "(>|\\])";
171  1 pat2 = ")";
172  1 break;
173  0 default:
174  0 return null;
175    }
176  12 REGEX[id] = Platform.newRegex(pat, pat2);
177    }
178  955 return REGEX[id];
179    }
180   
181    StringBuffer out; // output buffer
182   
183    private AlignmentI al;
184   
 
185  0 toggle public StockholmFile()
186    {
187    }
188   
189    /**
190    * Creates a new StockholmFile object for output
191    */
 
192  60 toggle public StockholmFile(AlignmentI al)
193    {
194  60 this.al = al;
195    }
196   
 
197  0 toggle public StockholmFile(String inFile, DataSourceType type)
198    throws IOException
199    {
200  0 super(inFile, type);
201    }
202   
 
203  47 toggle public StockholmFile(FileParse source) throws IOException
204    {
205  47 super(source);
206    }
207   
 
208  107 toggle @Override
209    public void initData()
210    {
211  107 super.initData();
212    }
213   
214    /**
215    * Parse a file in Stockholm format into Jalview's data model using VARNA
216    *
217    * @throws IOException
218    * If there is an error with the input file
219    */
 
220  0 toggle public void parse_with_VARNA(java.io.File inFile) throws IOException
221    {
222  0 FileReader fr = null;
223  0 fr = new FileReader(inFile);
224   
225  0 BufferedReader r = new BufferedReader(fr);
226  0 List<RNA> result = null;
227  0 try
228    {
229  0 result = RNAFactory.loadSecStrStockholm(r);
230    } catch (ExceptionUnmatchedClosingParentheses umcp)
231    {
232  0 errormessage = "Unmatched parentheses in annotation. Aborting ("
233    + umcp.getMessage() + ")";
234  0 throw new IOException(umcp);
235    }
236    // DEBUG jalview.bin.Console.outPrintln("this is the secondary scructure:"
237    // +result.size());
238  0 SequenceI[] seqs = new SequenceI[result.size()];
239  0 String id = null;
240  0 for (int i = 0; i < result.size(); i++)
241    {
242    // DEBUG jalview.bin.Console.errPrintln("Processing i'th sequence in
243    // Stockholm file")
244  0 RNA current = result.get(i);
245   
246  0 String seq = current.getSeq();
247  0 String rna = current.getStructDBN(true);
248    // DEBUG jalview.bin.Console.outPrintln(seq);
249    // DEBUG jalview.bin.Console.errPrintln(rna);
250  0 int begin = 0;
251  0 int end = seq.length() - 1;
252  0 id = safeName(getDataName());
253  0 seqs[i] = new Sequence(id, seq, begin, end);
254  0 String[] annot = new String[rna.length()];
255  0 Annotation[] ann = new Annotation[rna.length()];
256  0 for (int j = 0; j < rna.length(); j++)
257    {
258  0 annot[j] = rna.substring(j, j + 1);
259   
260    }
261   
262  0 for (int k = 0; k < rna.length(); k++)
263    {
264  0 ann[k] = new Annotation(annot[k], "",
265    Rna.getRNASecStrucState(annot[k]).charAt(0), 0f);
266   
267    }
268  0 AlignmentAnnotation align = new AlignmentAnnotation("Sec. str.",
269    current.getID(), ann);
270   
271  0 seqs[i].addAlignmentAnnotation(align);
272  0 seqs[i].setRNA(result.get(i));
273  0 this.annotations.addElement(align);
274    }
275  0 this.setSeqs(seqs);
276   
277    }
278   
279    /**
280    * Parse a file in Stockholm format into Jalview's data model. The file has to
281    * be passed at construction time
282    *
283    * @throws IOException
284    * If there is an error with the input file
285    */
 
286  47 toggle @Override
287    public void parse() throws IOException
288    {
289  47 StringBuffer treeString = new StringBuffer();
290  47 String treeName = null;
291    // --------------- Variable Definitions -------------------
292  47 String line;
293  47 String version;
294    // String id;
295  47 Hashtable seqAnn = new Hashtable(); // Sequence related annotations
296  47 LinkedHashMap<String, String> seqs = new LinkedHashMap<>();
297  47 Regex p, r, rend, s, x;
298    // Temporary line for processing RNA annotation
299    // String RNAannot = "";
300   
301    // ------------------ Parsing File ----------------------
302    // First, we have to check that this file has STOCKHOLM format, i.e. the
303    // first line must match
304   
305  47 r = getRegex(REGEX_STOCKHOLM);
306  47 if (!r.search(nextLine()))
307    {
308  0 throw new IOException(
309    MessageManager.getString("exception.stockholm_invalid_format")
310    + " (" + r + ")");
311    }
312    else
313    {
314  47 version = r.stringMatched(1);
315   
316    // logger.debug("Stockholm version: " + version);
317    }
318   
319    // We define some Regexes here that will be used regularily later
320  47 rend = getRegex(REGEX_ALIGN_END);//"^\\s*\\/\\/"); // Find the end of an alignment
321  47 p = getRegex(REGEX_SPLIT_ID);//"(\\S+)\\/(\\d+)\\-(\\d+)"); // split sequence id in
322    // id/from/to
323  47 s = getRegex(REGEX_SUBTYPE);// "(\\S+)\\s+(\\S*)\\s+(.*)"); // Parses
324    // annotation subtype
325  47 r = getRegex(REGEX_ANNOTATION_LINE);// "#=(G[FSRC]?)\\s+(.*)"); // Finds any
326    // annotation line
327  47 x = getRegex(REGEX_REMOVE_ID);// "(\\S+)\\s+(\\S+)"); // split id from
328    // sequence
329   
330    // Convert all bracket types to parentheses (necessary for passing to VARNA)
331  47 Regex openparen = getRegex(REGEX_OPEN_PAREN);//"(<|\\[)", "(");
332  47 Regex closeparen = getRegex(REGEX_CLOSE_PAREN);//"(>|\\])", ")");
333   
334    // // Detect if file is RNA by looking for bracket types
335    // Regex detectbrackets = new Regex("(<|>|\\[|\\]|\\(|\\))");
336   
337  47 rend.optimize();
338  47 p.optimize();
339  47 s.optimize();
340  47 r.optimize();
341  47 x.optimize();
342  47 openparen.optimize();
343  47 closeparen.optimize();
344   
345  ? while ((line = nextLine()) != null)
346    {
347  2532 if (line.length() == 0)
348    {
349  6 continue;
350    }
351  2526 if (rend.search(line))
352    {
353    // End of the alignment, pass stuff back
354  47 this.noSeqs = seqs.size();
355   
356  47 String dbsource = null;
357  47 Regex pf = getRegex(REGEX_PFAM); // Finds AC for Pfam
358  47 Regex rf = getRegex(REGEX_RFAM); // Finds AC for Rfam
359  47 if (getAlignmentProperty("AC") != null)
360    {
361  6 String dbType = getAlignmentProperty("AC").toString();
362  6 if (pf.search(dbType))
363    {
364    // PFAM Alignment - so references are typically from Uniprot
365  3 dbsource = "PFAM";
366    }
367  3 else if (rf.search(dbType))
368    {
369  3 dbsource = "RFAM";
370    }
371    }
372    // logger.debug("Number of sequences: " + this.noSeqs);
373  47 for (Map.Entry<String, String> skey : seqs.entrySet())
374    {
375    // logger.debug("Processing sequence " + acc);
376  923 String acc = skey.getKey();
377  923 String seq = skey.getValue();
378  923 if (maxLength < seq.length())
379    {
380  47 maxLength = seq.length();
381    }
382  923 int start = 1;
383  923 int end = -1;
384  923 String sid = acc;
385    /*
386    * Retrieve hash of annotations for this accession Associate
387    * Annotation with accession
388    */
389  923 Hashtable accAnnotations = null;
390   
391  923 if (seqAnn != null && seqAnn.containsKey(acc))
392    {
393  922 accAnnotations = (Hashtable) seqAnn.remove(acc);
394    // TODO: add structures to sequence
395    }
396   
397    // Split accession in id and from/to
398  923 if (p.search(acc))
399    {
400  684 sid = p.stringMatched(1);
401  684 start = Integer.parseInt(p.stringMatched(2));
402  684 end = Integer.parseInt(p.stringMatched(3));
403    }
404    // logger.debug(sid + ", " + start + ", " + end);
405   
406  923 Sequence seqO = new Sequence(sid, seq, start, end);
407    // Add Description (if any)
408  923 if (accAnnotations != null && accAnnotations.containsKey("DE"))
409    {
410  16 String desc = (String) accAnnotations.get("DE");
411  16 seqO.setDescription((desc == null) ? "" : desc);
412    }
413    // Add DB References (if any)
414  923 if (accAnnotations != null && accAnnotations.containsKey("DR"))
415    {
416  26 String dbr = (String) accAnnotations.get("DR");
417  26 if (dbr != null && dbr.indexOf(";") > -1)
418    {
419  26 String src = dbr.substring(0, dbr.indexOf(";"));
420  26 String acn = dbr.substring(dbr.indexOf(";") + 1);
421  26 jalview.util.DBRefUtils.parseToDbRef(seqO, src, "0", acn);
422    }
423    }
424   
425  923 if (accAnnotations != null && accAnnotations.containsKey("AC"))
426    {
427  901 String dbr = (String) accAnnotations.get("AC");
428  901 if (dbr != null)
429    {
430    // we could get very clever here - but for now - just try to
431    // guess accession type from type of sequence, source of alignment plus
432    // structure
433    // of accession
434  901 guessDatabaseFor(seqO, dbr, dbsource);
435    }
436    // else - do what ? add the data anyway and prompt the user to
437    // specify what references these are ?
438    }
439   
440  923 Hashtable features = null;
441    // We need to adjust the positions of all features to account for gaps
442  923 try
443    {
444  923 features = (Hashtable) accAnnotations.remove("features");
445    } catch (java.lang.NullPointerException e)
446    {
447    // loggerwarn("Getting Features for " + acc + ": " +
448    // e.getMessage());
449    // continue;
450    }
451    // if we have features
452  923 if (features != null)
453    {
454  326 int posmap[] = seqO.findPositionMap();
455  326 Enumeration i = features.keys();
456  652 while (i.hasMoreElements())
457    {
458    // TODO: parse out secondary structure annotation as annotation
459    // row
460    // TODO: parse out scores as annotation row
461    // TODO: map coding region to core jalview feature types
462  326 String type = i.nextElement().toString();
463  326 Hashtable content = (Hashtable) features.remove(type);
464   
465    // add alignment annotation for this feature
466  326 String key = type2id(type);
467   
468    /*
469    * have we added annotation rows for this type ?
470    */
471  326 boolean annotsAdded = false;
472  326 if (key != null)
473    {
474  326 if (accAnnotations != null
475    && accAnnotations.containsKey(key))
476    {
477  326 Vector vv = (Vector) accAnnotations.get(key);
478  652 for (int ii = 0; ii < vv.size(); ii++)
479    {
480  326 annotsAdded = true;
481  326 AlignmentAnnotation an = (AlignmentAnnotation) vv
482    .elementAt(ii);
483  326 seqO.addAlignmentAnnotation(an);
484  326 annotations.add(an);
485    }
486    }
487    }
488   
489  326 Enumeration j = content.keys();
490  652 while (j.hasMoreElements())
491    {
492  326 String desc = j.nextElement().toString();
493  326 if (ANNOTATION.equals(desc) && annotsAdded)
494    {
495    // don't add features if we already added an annotation row
496  326 continue;
497    }
498  0 String ns = content.get(desc).toString();
499  0 char[] byChar = ns.toCharArray();
500  0 for (int k = 0; k < byChar.length; k++)
501    {
502  0 char c = byChar[k];
503  0 if (!(c == ' ' || c == '_' || c == '-' || c == '.')) // PFAM
504    // uses
505    // '.'
506    // for
507    // feature
508    // background
509    {
510  0 int new_pos = posmap[k]; // look up nearest seqeunce
511    // position to this column
512  0 SequenceFeature feat = new SequenceFeature(type, desc,
513    new_pos, new_pos, null);
514   
515  0 seqO.addSequenceFeature(feat);
516    }
517    }
518    }
519   
520    }
521   
522    }
523    // garbage collect
524   
525    // logger.debug("Adding seq " + acc + " from " + start + " to " + end
526    // + ": " + seq);
527  923 this.seqs.addElement(seqO);
528    }
529  47 return; // finished parsing this segment of source
530    }
531  2479 else if (!r.search(line))
532    {
533    // jalview.bin.Console.errPrintln("Found sequence line: " + line);
534   
535    // Split sequence in sequence and accession parts
536  923 if (!x.search(line))
537    {
538    // logger.error("Could not parse sequence line: " + line);
539  0 throw new IOException(MessageManager.formatMessage(
540    "exception.couldnt_parse_sequence_line", new String[]
541    { line }));
542    }
543  923 String ns = seqs.get(x.stringMatched(1));
544  923 if (ns == null)
545    {
546  923 ns = "";
547    }
548  923 ns += x.stringMatched(2);
549   
550  923 seqs.put(x.stringMatched(1), ns);
551    }
552    else
553    {
554  1556 String annType = r.stringMatched(1);
555  1556 String annContent = r.stringMatched(2);
556   
557    // jalview.bin.Console.errPrintln("type:" + annType + " content: " +
558    // annContent);
559   
560  1556 if (annType.equals("GF"))
561    {
562    /*
563    * Generic per-File annotation, free text Magic features: #=GF NH
564    * <tree in New Hampshire eXtended format> #=GF TN <Unique identifier
565    * for the next tree> Pfam descriptions: 7. DESCRIPTION OF FIELDS
566    *
567    * Compulsory fields: ------------------
568    *
569    * AC Accession number: Accession number in form PFxxxxx.version or
570    * PBxxxxxx. ID Identification: One word name for family. DE
571    * Definition: Short description of family. AU Author: Authors of the
572    * entry. SE Source of seed: The source suggesting the seed members
573    * belong to one family. GA Gathering method: Search threshold to
574    * build the full alignment. TC Trusted Cutoff: Lowest sequence score
575    * and domain score of match in the full alignment. NC Noise Cutoff:
576    * Highest sequence score and domain score of match not in full
577    * alignment. TP Type: Type of family -- presently Family, Domain,
578    * Motif or Repeat. SQ Sequence: Number of sequences in alignment. AM
579    * Alignment Method The order ls and fs hits are aligned to the model
580    * to build the full align. // End of alignment.
581    *
582    * Optional fields: ----------------
583    *
584    * DC Database Comment: Comment about database reference. DR Database
585    * Reference: Reference to external database. RC Reference Comment:
586    * Comment about literature reference. RN Reference Number: Reference
587    * Number. RM Reference Medline: Eight digit medline UI number. RT
588    * Reference Title: Reference Title. RA Reference Author: Reference
589    * Author RL Reference Location: Journal location. PI Previous
590    * identifier: Record of all previous ID lines. KW Keywords: Keywords.
591    * CC Comment: Comments. NE Pfam accession: Indicates a nested domain.
592    * NL Location: Location of nested domains - sequence ID, start and
593    * end of insert.
594    *
595    * Obsolete fields: ----------- AL Alignment method of seed: The
596    * method used to align the seed members.
597    */
598    // Let's save the annotations, maybe we'll be able to do something
599    // with them later...
600  152 Regex an = getRegex(REGEX_ANNOTATION);
601  152 if (an.search(annContent))
602    {
603  152 if (an.stringMatched(1).equals("NH"))
604    {
605  0 treeString.append(an.stringMatched(2));
606    }
607  152 else if (an.stringMatched(1).equals("TN"))
608    {
609  0 if (treeString.length() > 0)
610    {
611  0 if (treeName == null)
612    {
613  0 treeName = "Tree " + (getTreeCount() + 1);
614    }
615  0 addNewickTree(treeName, treeString.toString());
616    }
617  0 treeName = an.stringMatched(2);
618  0 treeString = new StringBuffer();
619    }
620    // TODO: JAL-3532 - this is where GF comments and database references are lost
621    // suggest overriding this method for Stockholm files to catch and properly
622    // process CC, DR etc into multivalued properties
623  152 setAlignmentProperty(an.stringMatched(1), an.stringMatched(2));
624    }
625    }
626  1404 else if (annType.equals("GS"))
627    {
628    // Generic per-Sequence annotation, free text
629    /*
630    * Pfam uses these features: Feature Description ---------------------
631    * ----------- AC <accession> ACcession number DE <freetext>
632    * DEscription DR <db>; <accession>; Database Reference OS <organism>
633    * OrganiSm (species) OC <clade> Organism Classification (clade, etc.)
634    * LO <look> Look (Color, etc.)
635    */
636  1065 if (s.search(annContent))
637    {
638  1065 String acc = s.stringMatched(1);
639  1065 String type = s.stringMatched(2);
640  1065 String content = s.stringMatched(3);
641    // TODO: store DR in a vector.
642    // TODO: store AC according to generic file db annotation.
643  1065 Hashtable ann;
644  1065 if (seqAnn.containsKey(acc))
645    {
646  148 ann = (Hashtable) seqAnn.get(acc);
647    }
648    else
649    {
650  917 ann = new Hashtable();
651    }
652  1065 ann.put(type, content);
653  1065 seqAnn.put(acc, ann);
654    }
655    else
656    {
657    // throw new IOException("Error parsing " + line);
658  0 jalview.bin.Console
659    .errPrintln(">> missing annotation: " + line);
660    }
661    }
662  339 else if (annType.equals("GC"))
663    {
664    // Generic per-Column annotation, exactly 1 char per column
665    // always need a label.
666  13 if (x.search(annContent))
667    {
668    // parse out and create alignment annotation directly.
669  13 parseAnnotationRow(annotations, x.stringMatched(1),
670    x.stringMatched(2));
671    }
672    }
673  326 else if (annType.equals("GR"))
674    {
675    // Generic per-Sequence AND per-Column markup, exactly 1 char per
676    // column
677    /*
678    * Feature Description Markup letters ------- -----------
679    * -------------- SS Secondary Structure [HGIEBTSCX] SA Surface
680    * Accessibility [0-9X] (0=0%-10%; ...; 9=90%-100%) TM TransMembrane
681    * [Mio] PP Posterior Probability [0-9*] (0=0.00-0.05; 1=0.05-0.15;
682    * *=0.95-1.00) LI LIgand binding [*] AS Active Site [*] IN INtron (in
683    * or after) [0-2]
684    */
685  326 if (s.search(annContent))
686    {
687  326 String acc = s.stringMatched(1);
688  326 String type = s.stringMatched(2);
689  326 String oseq = s.stringMatched(3);
690    /*
691    * copy of annotation field that may be processed into whitespace chunks
692    */
693  326 String seq = new String(oseq);
694   
695  326 Hashtable ann;
696    // Get an object with all the annotations for this sequence
697  326 if (seqAnn.containsKey(acc))
698    {
699    // logger.debug("Found annotations for " + acc);
700  321 ann = (Hashtable) seqAnn.get(acc);
701    }
702    else
703    {
704    // logger.debug("Creating new annotations holder for " + acc);
705  5 ann = new Hashtable();
706  5 seqAnn.put(acc, ann);
707    }
708   
709    // // start of block for appending annotation lines for wrapped
710    // stokchholm file
711    // TODO test structure, call parseAnnotationRow with vector from
712    // hashtable for specific sequence
713   
714  326 Hashtable features;
715    // Get an object with all the content for an annotation
716  326 if (ann.containsKey("features"))
717    {
718    // logger.debug("Found features for " + acc);
719  0 features = (Hashtable) ann.get("features");
720    }
721    else
722    {
723    // logger.debug("Creating new features holder for " + acc);
724  326 features = new Hashtable();
725  326 ann.put("features", features);
726    }
727   
728  326 Hashtable content;
729  326 if (features.containsKey(this.id2type(type)))
730    {
731    // logger.debug("Found content for " + this.id2type(type));
732  0 content = (Hashtable) features
733    .get(this.id2type(type));
734    }
735    else
736    {
737    // logger.debug("Creating new content holder for " +
738    // this.id2type(type));
739  326 content = new Hashtable();
740  326 features.put(id2type(type), content);
741    }
742  326 String ns = (String) content.get(ANNOTATION);
743   
744  326 if (ns == null)
745    {
746  326 ns = "";
747    }
748    // finally, append the annotation line
749  326 ns += seq;
750  326 content.put(ANNOTATION, ns);
751    // // end of wrapped annotation block.
752    // // Now a new row is created with the current set of data
753   
754  326 Hashtable strucAnn;
755  326 if (seqAnn.containsKey(acc))
756    {
757  326 strucAnn = (Hashtable) seqAnn.get(acc);
758    }
759    else
760    {
761  0 strucAnn = new Hashtable();
762    }
763   
764  326 Vector<AlignmentAnnotation> newStruc = new Vector<>();
765  326 parseAnnotationRow(newStruc, type, ns);
766  326 for (AlignmentAnnotation alan : newStruc)
767    {
768  326 alan.visible = false;
769    }
770    // new annotation overwrites any existing annotation...
771   
772  326 strucAnn.put(type, newStruc);
773  326 seqAnn.put(acc, strucAnn);
774    }
775    // }
776    else
777    {
778  0 jalview.bin.Console.errPrintln(
779    "Warning - couldn't parse sequence annotation row line:\n"
780    + line);
781    // throw new IOException("Error parsing " + line);
782    }
783    }
784    else
785    {
786  0 throw new IOException(MessageManager.formatMessage(
787    "exception.unknown_annotation_detected", new String[]
788    { annType, annContent }));
789    }
790    }
791    }
792  0 if (treeString.length() > 0)
793    {
794  0 if (treeName == null)
795    {
796  0 treeName = "Tree " + (1 + getTreeCount());
797    }
798  0 addNewickTree(treeName, treeString.toString());
799    }
800    }
801   
802    /**
803    * Demangle an accession string and guess the originating sequence database
804    * for a given sequence
805    *
806    * @param seqO
807    * sequence to be annotated
808    * @param dbr
809    * Accession string for sequence
810    * @param dbsource
811    * source database for alignment (PFAM or RFAM)
812    */
 
813  901 toggle private void guessDatabaseFor(Sequence seqO, String dbr, String dbsource)
814    {
815  901 DBRefEntry dbrf = null;
816  901 List<DBRefEntry> dbrs = new ArrayList<>();
817  901 String seqdb = "Unknown", sdbac = "" + dbr;
818  901 int st = -1, en = -1, p;
819  ? if ((st = sdbac.indexOf("/")) > -1)
820    {
821  221 String num, range = sdbac.substring(st + 1);
822  221 sdbac = sdbac.substring(0, st);
823  ? if ((p = range.indexOf("-")) > -1)
824    {
825  221 p++;
826  221 if (p < range.length())
827    {
828  221 num = range.substring(p).trim();
829  221 try
830    {
831  221 en = Integer.parseInt(num);
832    } catch (NumberFormatException x)
833    {
834    // could warn here that index is invalid
835  0 en = -1;
836    }
837    }
838    }
839    else
840    {
841  0 p = range.length();
842    }
843  221 num = range.substring(0, p).trim();
844  221 try
845    {
846  221 st = Integer.parseInt(num);
847    } catch (NumberFormatException x)
848    {
849    // could warn here that index is invalid
850  221 st = -1;
851    }
852    }
853  901 if (dbsource == null)
854    {
855    // make up an origin based on whether the sequence looks like it is nucleotide
856    // or protein
857  100 dbsource = (seqO.isProtein()) ? "PFAM" : "RFAM";
858    }
859  901 if (dbsource.equals("PFAM"))
860    {
861  619 seqdb = "UNIPROT";
862  619 if (sdbac.indexOf(".") > -1)
863    {
864    // strip of last subdomain
865  412 sdbac = sdbac.substring(0, sdbac.indexOf("."));
866  412 dbrf = jalview.util.DBRefUtils.parseToDbRef(seqO, seqdb, dbsource,
867    sdbac);
868  412 if (dbrf != null)
869    {
870  412 dbrs.add(dbrf);
871    }
872    }
873  619 dbrf = jalview.util.DBRefUtils.parseToDbRef(seqO, dbsource, dbsource,
874    dbr);
875  619 if (dbr != null)
876    {
877  619 dbrs.add(dbrf);
878    }
879    }
880    else
881    {
882  282 seqdb = "EMBL"; // total guess - could be ENA, or something else these
883    // days
884  282 if (sdbac.indexOf(".") > -1)
885    {
886    // strip off last subdomain
887  221 sdbac = sdbac.substring(0, sdbac.indexOf("."));
888  221 dbrf = jalview.util.DBRefUtils.parseToDbRef(seqO, seqdb, dbsource,
889    sdbac);
890  221 if (dbrf != null)
891    {
892  221 dbrs.add(dbrf);
893    }
894    }
895   
896  282 dbrf = jalview.util.DBRefUtils.parseToDbRef(seqO, dbsource, dbsource,
897    dbr);
898  282 if (dbrf != null)
899    {
900  282 dbrs.add(dbrf);
901    }
902    }
903  901 if (st != -1 && en != -1)
904    {
905  0 for (DBRefEntry d : dbrs)
906    {
907  0 jalview.util.MapList mp = new jalview.util.MapList(
908    new int[]
909    { seqO.getStart(), seqO.getEnd() }, new int[] { st, en }, 1,
910    1);
911  0 jalview.datamodel.Mapping mping = new Mapping(mp);
912  0 d.setMap(mping);
913    }
914    }
915    }
916   
 
917  339 toggle protected static AlignmentAnnotation parseAnnotationRow(
918    Vector<AlignmentAnnotation> annotation, String label,
919    String annots)
920    {
921  339 String convert1, convert2 = null;
922    // String convert1 = OPEN_PAREN.replaceAll(annots);
923    // String convert2 = CLOSE_PAREN.replaceAll(convert1);
924    // annots = convert2;
925   
926  339 String type = label;
927  339 if (label.contains("_cons"))
928    {
929  11 type = (label.indexOf("_cons") == label.length() - 5)
930    ? label.substring(0, label.length() - 5)
931    : label;
932    }
933  339 boolean ss = false, posterior = false;
934  339 type = id2type(type);
935   
936  339 boolean isrnass = false;
937  339 if (type.equalsIgnoreCase("secondary structure"))
938    {
939  333 ss = true;
940  333 isrnass = !getRegex(REGEX_NOT_RNASS).search(annots); // sorry about the double
941    // negative
942    // here (it's easier for dealing with
943    // other non-alpha-non-brace chars)
944    }
945  339 if (type.equalsIgnoreCase("posterior probability"))
946    {
947  0 posterior = true;
948    }
949    // decide on secondary structure or not.
950  339 Annotation[] els = new Annotation[annots.length()];
951  26108 for (int i = 0; i < annots.length(); i++)
952    {
953  25769 String pos = annots.substring(i, i + 1);
954    // TODO 2.12 release: verify this Stockholm IO behaviour change in release notes
955  25769 if (UNDERSCORE == pos.charAt(0))
956    {
957  12 pos = " ";
958    }
959  25769 Annotation ann;
960  25769 ann = new Annotation(pos, "", ' ', 0f); // 0f is 'valid' null - will not
961    // be written out
962  25769 if (ss)
963    {
964    // if (" .-_".indexOf(pos) == -1)
965    {
966  25118 if (isrnass && RNASS_BRACKETS.indexOf(pos) >= 0)
967    {
968  8060 ann.secondaryStructure = Rna.getRNASecStrucState(pos).charAt(0);
969  8060 ann.displayCharacter = "" + pos.charAt(0);
970    }
971    else
972    {
973  17058 ann.secondaryStructure = ResidueProperties.getDssp3state(pos)
974    .charAt(0);
975   
976  17058 if (ann.secondaryStructure == pos.charAt(0))
977    {
978  1778 ann.displayCharacter = ""; // null; // " ";
979    }
980    else
981    {
982  15280 ann.displayCharacter = " " + ann.displayCharacter;
983    }
984    }
985    }
986   
987    }
988  25769 if (posterior && !ann.isWhitespace()
989    && !Comparison.isGap(pos.charAt(0)))
990    {
991  0 float val = 0;
992    // symbol encodes values - 0..*==0..10
993  0 if (pos.charAt(0) == '*')
994    {
995  0 val = 10;
996    }
997    else
998    {
999  0 val = pos.charAt(0) - '0';
1000  0 if (val > 9)
1001    {
1002  0 val = 10;
1003    }
1004    }
1005  0 ann.value = val;
1006    }
1007   
1008  25769 els[i] = ann;
1009    }
1010  339 AlignmentAnnotation annot = null;
1011  339 Enumeration<AlignmentAnnotation> e = annotation.elements();
1012  345 while (e.hasMoreElements())
1013    {
1014  6 annot = e.nextElement();
1015  6 if (annot.label.equals(type))
1016    {
1017  0 break;
1018    }
1019  6 annot = null;
1020    }
1021  339 if (annot == null)
1022    {
1023  339 annot = new AlignmentAnnotation(type, type, els);
1024  339 annotation.addElement(annot);
1025    }
1026    else
1027    {
1028  0 Annotation[] anns = new Annotation[annot.annotations.length
1029    + els.length];
1030  0 System.arraycopy(annot.annotations, 0, anns, 0,
1031    annot.annotations.length);
1032  0 System.arraycopy(els, 0, anns, annot.annotations.length, els.length);
1033  0 annot.annotations = anns;
1034    // jalview.bin.Console.outPrintln("else: ");
1035    }
1036  339 return annot;
1037    }
1038   
 
1039  281 toggle private String dbref_to_ac_record(DBRefEntry ref)
1040    {
1041  281 return ref.getSource().toString() + " ; "
1042    + ref.getAccessionId().toString();
1043    }
 
1044  60 toggle @Override
1045    public String print(SequenceI[] s, boolean jvSuffix)
1046    {
1047  60 out = new StringBuffer();
1048  60 out.append("# STOCKHOLM 1.0");
1049  60 out.append(newline);
1050   
1051    // find max length of id
1052  60 int max = 0;
1053  60 int maxid = 0;
1054  60 int in = 0;
1055  60 int slen = s.length;
1056  60 SequenceI seq;
1057  60 Hashtable<String, String> dataRef = null;
1058  60 boolean isAA = s[in].isProtein();
1059  ? while ((in < slen) && ((seq = s[in]) != null))
1060    {
1061  344 String tmp = printId(seq, jvSuffix);
1062  344 max = Math.max(max, seq.getLength());
1063   
1064  344 if (tmp.length() > maxid)
1065    {
1066  65 maxid = tmp.length();
1067    }
1068  344 List<DBRefEntry> seqrefs = seq.getDBRefs();
1069  344 int ndb;
1070  ? if (seqrefs != null && (ndb = seqrefs.size()) > 0)
1071    {
1072  268 if (dataRef == null)
1073    {
1074  3 dataRef = new Hashtable<>();
1075    }
1076  268 List<DBRefEntry> primrefs = seq.getPrimaryDBRefs();
1077  268 if (primrefs.size() >= 1)
1078    {
1079  1 dataRef.put(tmp, dbref_to_ac_record(primrefs.get(0)));
1080    }
1081    else
1082    {
1083  280 for (int idb = 0; idb < ndb; idb++)
1084    {
1085  280 DBRefEntry dbref = seqrefs.get(idb);
1086  280 dataRef.put(tmp, dbref_to_ac_record(dbref));
1087    // if we put in a uniprot or EMBL record then we're done:
1088  280 if ((isAA ? DBRefSource.UNIPROT : DBRefSource.EMBL)
1089    .equals(DBRefUtils.getCanonicalName(dbref.getSource())))
1090    {
1091  267 break;
1092    }
1093    }
1094    }
1095    }
1096  344 in++;
1097    }
1098  60 maxid += 9;
1099  60 int i = 0;
1100   
1101    // output database type
1102  60 if (al.getProperties() != null)
1103    {
1104  3 if (!al.getProperties().isEmpty())
1105    {
1106  3 Enumeration key = al.getProperties().keys();
1107  3 Enumeration val = al.getProperties().elements();
1108  41 while (key.hasMoreElements())
1109    {
1110  38 out.append("#=GF " + key.nextElement() + " " + val.nextElement());
1111  38 out.append(newline);
1112    }
1113    }
1114    }
1115   
1116    // output database accessions
1117  60 if (dataRef != null)
1118    {
1119  3 Enumeration<String> en = dataRef.keys();
1120  271 while (en.hasMoreElements())
1121    {
1122  268 Object idd = en.nextElement();
1123  268 String type = dataRef.remove(idd);
1124  268 out.append(new Format("%-" + (maxid - 2) + "s")
1125    .form("#=GS " + idd.toString() + " "));
1126  268 if (isAA && type.contains("UNIPROT")
1127    || (!isAA && type.contains("EMBL")))
1128    {
1129   
1130  268 out.append(" AC " + type.substring(type.indexOf(";") + 1));
1131    }
1132    else
1133    {
1134  0 out.append(" DR " + type + " ");
1135    }
1136  268 out.append(newline);
1137    }
1138    }
1139   
1140    // output description and annotations
1141   
1142  ? while (i < slen && (seq = s[i]) != null)
1143    {
1144  344 if (seq.getDescription() != null)
1145    {
1146    // out.append("#=GR ");
1147  16 out.append(new Format("%-" + maxid + "s").form("#=GS "
1148    + printId(seq, jvSuffix) + " DE " + seq.getDescription()));
1149  16 out.append(newline);
1150    }
1151   
1152  344 AlignmentAnnotation[] alAnot = seq.getAnnotation();
1153  344 if (alAnot != null)
1154    {
1155  83 Annotation[] ann;
1156  166 for (int j = 0; j < alAnot.length; j++)
1157    {
1158   
1159  83 if (alAnot[j].annotations != null)
1160    {
1161  83 String key = type2id(alAnot[j].label);
1162  83 boolean isrna = alAnot[j].isValidStruc();
1163   
1164  83 if (isrna)
1165    {
1166    // hardwire to secondary structure if there is RNA secondary
1167    // structure on the annotation
1168  66 key = "SS";
1169    }
1170  83 if (key == null)
1171    {
1172  4 continue;
1173    }
1174   
1175    // out.append("#=GR ");
1176  79 out.append(new Format("%-" + maxid + "s").form(
1177    "#=GR " + printId(s[i], jvSuffix) + " " + key + " "));
1178  79 ann = alAnot[j].annotations;
1179  79 String sseq = "";
1180  7982 for (int k = 0; k < ann.length; k++)
1181    {
1182  7903 sseq += outputCharacter(key, k, isrna, ann, s[i]);
1183    }
1184  79 out.append(sseq);
1185  79 out.append(newline);
1186    }
1187    }
1188    }
1189   
1190  344 out.append(new Format("%-" + maxid + "s")
1191    .form(printId(seq, jvSuffix) + " "));
1192  344 out.append(seq.getSequenceAsString());
1193  344 out.append(newline);
1194  344 i++;
1195    }
1196   
1197    // alignment annotation
1198  60 AlignmentAnnotation aa;
1199  60 AlignmentAnnotation[] an = al.getAlignmentAnnotation();
1200  60 if (an != null)
1201    {
1202  272 for (int ia = 0, na = an.length; ia < na; ia++)
1203    {
1204  216 aa = an[ia];
1205  216 if (aa.autoCalculated || !aa.visible || aa.sequenceRef != null)
1206    {
1207  211 continue;
1208    }
1209  5 String sseq = "";
1210  5 String label;
1211  5 String key = "";
1212  5 if (aa.label.equals("seq"))
1213    {
1214  1 label = "seq_cons";
1215    }
1216    else
1217    {
1218  4 key = type2id(aa.label.toLowerCase(Locale.ROOT));
1219  4 if (key == null)
1220    {
1221  0 label = aa.label;
1222    }
1223    else
1224    {
1225  4 label = key + "_cons";
1226    }
1227    }
1228  5 if (label == null)
1229    {
1230  0 label = aa.label;
1231    }
1232  5 label = label.replace(" ", "_");
1233   
1234  5 out.append(
1235    new Format("%-" + maxid + "s").form("#=GC " + label + " "));
1236  5 boolean isrna = aa.isValidStruc();
1237  453 for (int j = 0, nj = aa.annotations.length; j < nj; j++)
1238    {
1239  448 sseq += outputCharacter(key, j, isrna, aa.annotations, null);
1240    }
1241  5 out.append(sseq);
1242  5 out.append(newline);
1243    }
1244    }
1245   
1246  60 out.append("//");
1247  60 out.append(newline);
1248   
1249  60 return out.toString();
1250    }
1251   
1252    /**
1253    * add an annotation character to the output row
1254    *
1255    * @param seq
1256    * @param key
1257    * @param k
1258    * @param isrna
1259    * @param ann
1260    * @param sequenceI
1261    */
 
1262  8351 toggle private char outputCharacter(String key, int k, boolean isrna,
1263    Annotation[] ann, SequenceI sequenceI)
1264    {
1265  8351 char seq = ' ';
1266  8351 Annotation annot = ann[k];
1267  8351 String ch = (annot == null)
1268  2440 ? ((sequenceI == null) ? "-"
1269    : Character.toString(sequenceI.getCharAt(k)))
1270  5911 : (annot.displayCharacter == null
1271    ? String.valueOf(annot.secondaryStructure)
1272    : annot.displayCharacter);
1273  8351 if (ch == null)
1274    {
1275  0 ch = " ";
1276    }
1277  8351 if (key != null && key.equals("SS"))
1278    {
1279  8134 char ssannotchar = ' ';
1280  8134 boolean charset = false;
1281  8134 if (annot == null)
1282    {
1283    // sensible gap character
1284  2440 ssannotchar = ' ';
1285  2440 charset = true;
1286    }
1287    else
1288    {
1289    // valid secondary structure AND no alternative label (e.g. ' B')
1290  5694 if (annot.secondaryStructure > ' ' && ch.length() < 2)
1291    {
1292  3074 ssannotchar = annot.secondaryStructure;
1293  3074 charset = true;
1294    }
1295    }
1296  8134 if (charset)
1297    {
1298  5514 return (ssannotchar == ' ' && isrna) ? '.' : ssannotchar;
1299    }
1300    }
1301   
1302  2837 if (ch.length() == 0)
1303    {
1304  6 seq = '.';
1305    }
1306  2831 else if (ch.length() == 1)
1307    {
1308  454 seq = ch.charAt(0);
1309    }
1310  2377 else if (ch.length() > 1)
1311    {
1312  2377 seq = ch.charAt(1);
1313    }
1314   
1315  2837 return (seq == ' ' && key != null && key.equals("SS") && isrna) ? '.'
1316    : seq;
1317    }
1318   
1319    /**
1320    * make a friendly ID string.
1321    *
1322    * @param dataName
1323    * @return truncated dataName to after last '/'
1324    */
 
1325  0 toggle private String safeName(String dataName)
1326    {
1327  0 int b = 0;
1328  0 while ((b = dataName.indexOf("/")) > -1 && b < dataName.length())
1329    {
1330  0 dataName = dataName.substring(b + 1).trim();
1331   
1332    }
1333  0 int e = (dataName.length() - dataName.indexOf(".")) + 1;
1334  0 dataName = dataName.substring(1, e).trim();
1335  0 return dataName;
1336    }
1337   
1338   
 
1339  0 toggle public String print()
1340    {
1341  0 out = new StringBuffer();
1342  0 out.append("# STOCKHOLM 1.0");
1343  0 out.append(newline);
1344  0 print(getSeqsAsArray(), false);
1345   
1346  0 out.append("//");
1347  0 out.append(newline);
1348  0 return out.toString();
1349    }
1350   
1351    private static Hashtable typeIds = null;
1352   
 
1353  1 toggle static
1354    {
1355  1 if (typeIds == null)
1356    {
1357  1 typeIds = new Hashtable();
1358  1 typeIds.put("SS", "Secondary Structure");
1359  1 typeIds.put("SA", "Surface Accessibility");
1360  1 typeIds.put("TM", "transmembrane");
1361  1 typeIds.put("PP", "Posterior Probability");
1362  1 typeIds.put("LI", "ligand binding");
1363  1 typeIds.put("AS", "active site");
1364  1 typeIds.put("IN", "intron");
1365  1 typeIds.put("IR", "interacting residue");
1366  1 typeIds.put("AC", "accession");
1367  1 typeIds.put("OS", "organism");
1368  1 typeIds.put("CL", "class");
1369  1 typeIds.put("DE", "description");
1370  1 typeIds.put("DR", "reference");
1371  1 typeIds.put("LO", "look");
1372  1 typeIds.put("RF", "Reference Positions");
1373   
1374    }
1375    }
1376   
1377   
 
1378  991 toggle protected static String id2type(String id)
1379    {
1380  991 if (typeIds.containsKey(id))
1381    {
1382  988 return (String) typeIds.get(id);
1383    }
1384  3 jalview.bin.Console.errPrintln(
1385    "Warning : Unknown Stockholm annotation type code " + id);
1386  3 return id;
1387    }
1388   
 
1389  413 toggle protected static String type2id(String type)
1390    {
1391  413 String key = null;
1392  413 Enumeration e = typeIds.keys();
1393  4560 while (e.hasMoreElements())
1394    {
1395  4556 Object ll = e.nextElement();
1396  4556 if (typeIds.get(ll).toString().equalsIgnoreCase(type))
1397    {
1398  409 key = (String) ll;
1399  409 break;
1400    }
1401    }
1402  413 if (key != null)
1403    {
1404  409 return key;
1405    }
1406  4 jalview.bin.Console.errPrintln(
1407    "Warning : Unknown Stockholm annotation type: " + type);
1408  4 return key;
1409    }
1410    }