Updated with latest from mchmmer branch
[jalview.git] / test / jalview / io / StockholmFileTest.java
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 package jalview.io;
22
23 import static org.testng.AssertJUnit.assertEquals;
24 import static org.testng.AssertJUnit.assertNotNull;
25 import static org.testng.AssertJUnit.assertNull;
26 import static org.testng.AssertJUnit.assertTrue;
27 import static org.testng.AssertJUnit.fail;
28
29 import jalview.datamodel.Alignment;
30 import jalview.datamodel.AlignmentAnnotation;
31 import jalview.datamodel.AlignmentI;
32 import jalview.datamodel.Annotation;
33 import jalview.datamodel.DBRefEntry;
34 import jalview.datamodel.Sequence;
35 import jalview.datamodel.SequenceFeature;
36 import jalview.datamodel.SequenceI;
37 import jalview.gui.JvOptionPane;
38
39 import java.io.File;
40 import java.io.IOException;
41 import java.util.Arrays;
42 import java.util.BitSet;
43 import java.util.HashMap;
44 import java.util.List;
45 import java.util.Map;
46
47 import org.testng.Assert;
48 import org.testng.annotations.BeforeClass;
49 import org.testng.annotations.Test;
50
51 public class StockholmFileTest
52 {
53
54   @BeforeClass(alwaysRun = true)
55   public void setUpJvOptionPane()
56   {
57     JvOptionPane.setInteractiveMode(false);
58     JvOptionPane.setMockResponse(JvOptionPane.CANCEL_OPTION);
59   }
60
61   static String PfamFile = "examples/PF00111_seed.stk",
62           RfamFile = "examples/RF00031_folded.stk";
63
64   @Test(groups = { "Functional" })
65   public void pfamFileIO() throws Exception
66   {
67     testFileIOwithFormat(new File(PfamFile), FileFormat.Stockholm, -1, 0,
68             false, false, false);
69   }
70
71   @Test(groups = { "Functional" })
72   public void pfamFileDataExtraction() throws Exception
73   {
74     AppletFormatAdapter af = new AppletFormatAdapter();
75     AlignmentI al = af.readFile(PfamFile, DataSourceType.FILE,
76             new IdentifyFile().identify(PfamFile, DataSourceType.FILE));
77     int numpdb = 0;
78     for (SequenceI sq : al.getSequences())
79     {
80       if (sq.getAllPDBEntries() != null)
81       {
82         numpdb += sq.getAllPDBEntries().size();
83       }
84     }
85     assertTrue(
86             "PF00111 seed alignment has at least 1 PDB file, but the reader found none.",
87             numpdb > 0);
88   }
89
90   @Test(groups = { "Functional" })
91   public void rfamFileIO() throws Exception
92   {
93     testFileIOwithFormat(new File(RfamFile), FileFormat.Stockholm, 2, 1,
94             false, false, false);
95   }
96
97   /**
98    * test alignment data in given file can be imported, exported and reimported
99    * with no dataloss
100    * 
101    * @param f
102    *          - source datafile (IdentifyFile.identify() should work with it)
103    * @param ioformat
104    *          - label for IO class used to write and read back in the data from
105    *          f
106    * @param ignoreFeatures
107    * @param ignoreRowVisibility
108    * @param allowNullAnnotations
109    */
110
111   public static void testFileIOwithFormat(File f, FileFormatI ioformat,
112           int naliannot, int nminseqann, boolean ignoreFeatures,
113           boolean ignoreRowVisibility, boolean allowNullAnnotations)
114   {
115     System.out.println("Reading file: " + f);
116     String ff = f.getPath();
117     try
118     {
119       AppletFormatAdapter rf = new AppletFormatAdapter();
120
121       AlignmentI al = rf.readFile(ff, DataSourceType.FILE,
122               new IdentifyFile().identify(ff, DataSourceType.FILE));
123
124       assertNotNull("Couldn't read supplied alignment data.", al);
125
126       // make sure dataset is initialised ? not sure about this
127       for (int i = 0; i < al.getSequencesArray().length; ++i)
128       {
129         al.getSequenceAt(i).createDatasetSequence();
130       }
131       String outputfile = rf.formatSequences(ioformat, al, true);
132       System.out.println("Output file in '" + ioformat + "':\n"
133               + outputfile + "\n<<EOF\n");
134       // test for consistency in io
135       AlignmentI al_input = new AppletFormatAdapter().readFile(outputfile,
136               DataSourceType.PASTE, ioformat);
137       assertNotNull("Couldn't parse reimported alignment data.", al_input);
138
139       FileFormatI identifyoutput = new IdentifyFile().identify(outputfile,
140               DataSourceType.PASTE);
141       assertNotNull("Identify routine failed for outputformat " + ioformat,
142               identifyoutput);
143       assertTrue(
144               "Identify routine could not recognise output generated by '"
145                       + ioformat + "' writer",
146               ioformat.equals(identifyoutput));
147       testAlignmentEquivalence(al, al_input, ignoreFeatures,
148               ignoreRowVisibility, allowNullAnnotations);
149       int numaliannot = 0, numsqswithali = 0;
150       for (AlignmentAnnotation ala : al_input.getAlignmentAnnotation())
151       {
152         if (ala.sequenceRef == null)
153         {
154           numaliannot++;
155         }
156         else
157         {
158           numsqswithali++;
159         }
160       }
161       if (naliannot > -1)
162       {
163         assertEquals("Number of alignment annotations", naliannot,
164                 numaliannot);
165       }
166
167       assertTrue(
168               "Number of sequence associated annotations wasn't at least "
169                       + nminseqann, numsqswithali >= nminseqann);
170
171     } catch (Exception e)
172     {
173       e.printStackTrace();
174       assertTrue("Couln't format the alignment for output file.", false);
175     }
176   }
177
178   /**
179    * assert alignment equivalence
180    * 
181    * @param al
182    *          'original'
183    * @param al_input
184    *          'secondary' or generated alignment from some datapreserving
185    *          transformation
186    * @param ignoreFeatures
187    *          when true, differences in sequence feature annotation are ignored
188    */
189   public static void testAlignmentEquivalence(AlignmentI al,
190           AlignmentI al_input, boolean ignoreFeatures)
191   {
192     testAlignmentEquivalence(al, al_input, ignoreFeatures, false, false);
193   }
194
195   /**
196    * assert alignment equivalence - uses special comparators for RNA structure
197    * annotation rows.
198    * 
199    * @param al
200    *          'original'
201    * @param al_input
202    *          'secondary' or generated alignment from some datapreserving
203    *          transformation
204    * @param ignoreFeatures
205    *          when true, differences in sequence feature annotation are ignored
206    * 
207    * @param ignoreRowVisibility
208    *          when true, do not fail if there are differences in the visibility
209    *          of annotation rows
210    * @param allowNullAnnotation
211    *          when true, positions in alignment annotation that are null will be
212    *          considered equal to positions containing annotation where
213    *          Annotation.isWhitespace() returns true.
214    * 
215    */
216   public static void testAlignmentEquivalence(AlignmentI al,
217           AlignmentI al_input, boolean ignoreFeatures,
218           boolean ignoreRowVisibility, boolean allowNullAnnotation)
219   {
220     assertNotNull("Original alignment was null", al);
221     assertNotNull("Generated alignment was null", al_input);
222
223     assertTrue("Alignment dimension mismatch: original: " + al.getHeight()
224             + "x" + al.getWidth() + ", generated: " + al_input.getHeight()
225             + "x" + al_input.getWidth(),
226             al.getHeight() == al_input.getHeight()
227                     && al.getWidth() == al_input.getWidth());
228
229     // check Alignment annotation
230     AlignmentAnnotation[] aa_new = al_input.getAlignmentAnnotation();
231     AlignmentAnnotation[] aa_original = al.getAlignmentAnnotation();
232
233     // note - at moment we do not distinguish between alignment without any
234     // annotation rows and alignment with no annotation row vector
235     // we might want to revise this in future
236     int aa_new_size = (aa_new == null ? 0 : aa_new.length);
237     int aa_original_size = (aa_original == null ? 0 : aa_original.length);
238     Map<Integer, BitSet> orig_groups = new HashMap<>();
239     Map<Integer, BitSet> new_groups = new HashMap<>();
240
241     if (aa_new != null && aa_original != null)
242     {
243       for (int i = 0; i < aa_original.length; i++)
244       {
245         if (aa_new.length > i)
246         {
247           assertEqualSecondaryStructure(
248                   "Different alignment annotation at position " + i,
249                   aa_original[i], aa_new[i], allowNullAnnotation);
250           // compare graphGroup or graph properties - needed to verify JAL-1299
251           assertEquals("Graph type not identical.", aa_original[i].graph,
252                   aa_new[i].graph);
253           if (!ignoreRowVisibility)
254           {
255             assertEquals("Visibility not identical.",
256                     aa_original[i].visible,
257                   aa_new[i].visible);
258           }
259           assertEquals("Threshold line not identical.",
260                   aa_original[i].threshold, aa_new[i].threshold);
261           // graphGroup may differ, but pattern should be the same
262           Integer o_ggrp = new Integer(aa_original[i].graphGroup + 2);
263           Integer n_ggrp = new Integer(aa_new[i].graphGroup + 2);
264           BitSet orig_g = orig_groups.get(o_ggrp);
265           BitSet new_g = new_groups.get(n_ggrp);
266           if (orig_g == null)
267           {
268             orig_groups.put(o_ggrp, orig_g = new BitSet());
269           }
270           if (new_g == null)
271           {
272             new_groups.put(n_ggrp, new_g = new BitSet());
273           }
274           assertEquals("Graph Group pattern differs at annotation " + i,
275                   orig_g, new_g);
276           orig_g.set(i);
277           new_g.set(i);
278         }
279         else
280         {
281           System.err.println("No matching annotation row for "
282                   + aa_original[i].toString());
283         }
284       }
285     }
286     assertEquals(
287             "Generated and imported alignment have different annotation sets",
288             aa_original_size, aa_new_size);
289
290     // check sequences, annotation and features
291     SequenceI[] seq_original = new SequenceI[al.getSequencesArray().length];
292     seq_original = al.getSequencesArray();
293     SequenceI[] seq_new = new SequenceI[al_input.getSequencesArray().length];
294     seq_new = al_input.getSequencesArray();
295     List<SequenceFeature> sequenceFeatures_original;
296     List<SequenceFeature> sequenceFeatures_new;
297     AlignmentAnnotation annot_original, annot_new;
298     //
299     for (int i = 0; i < al.getSequencesArray().length; i++)
300     {
301       String name = seq_original[i].getName();
302       int start = seq_original[i].getStart();
303       int end = seq_original[i].getEnd();
304       System.out.println("Check sequence: " + name + "/" + start + "-"
305               + end);
306
307       // search equal sequence
308       for (int in = 0; in < al_input.getSequencesArray().length; in++)
309       {
310         if (name.equals(seq_new[in].getName())
311                 && start == seq_new[in].getStart()
312                 && end == seq_new[in].getEnd())
313         {
314           String ss_original = seq_original[i].getSequenceAsString();
315           String ss_new = seq_new[in].getSequenceAsString();
316           assertEquals("The sequences " + name + "/" + start + "-" + end
317                   + " are not equal", ss_original, ss_new);
318
319           assertTrue(
320                   "Sequence Features were not equivalent"
321                           + (ignoreFeatures ? " ignoring." : ""),
322                   ignoreFeatures
323                           || (seq_original[i].getSequenceFeatures() == null && seq_new[in]
324                                   .getSequenceFeatures() == null)
325                           || (seq_original[i].getSequenceFeatures() != null && seq_new[in]
326                                   .getSequenceFeatures() != null));
327           // compare sequence features
328           if (seq_original[i].getSequenceFeatures() != null
329                   && seq_new[in].getSequenceFeatures() != null)
330           {
331             System.out.println("There are feature!!!");
332             sequenceFeatures_original = seq_original[i]
333                     .getSequenceFeatures();
334             sequenceFeatures_new = seq_new[in].getSequenceFeatures();
335
336             assertEquals("different number of features", seq_original[i]
337                     .getSequenceFeatures().size(), seq_new[in]
338                     .getSequenceFeatures().size());
339
340             for (int feat = 0; feat < seq_original[i].getSequenceFeatures()
341                     .size(); feat++)
342             {
343               assertEquals("Different features",
344                       sequenceFeatures_original.get(feat),
345                       sequenceFeatures_new.get(feat));
346             }
347           }
348           // compare alignment annotation
349           if (al.getSequenceAt(i).getAnnotation() != null
350                   && al_input.getSequenceAt(in).getAnnotation() != null)
351           {
352             for (int j = 0; j < al.getSequenceAt(i).getAnnotation().length; j++)
353             {
354               if (al.getSequenceAt(i).getAnnotation()[j] != null
355                       && al_input.getSequenceAt(in).getAnnotation()[j] != null)
356               {
357                 annot_original = al.getSequenceAt(i).getAnnotation()[j];
358                 annot_new = al_input.getSequenceAt(in).getAnnotation()[j];
359                 assertEqualSecondaryStructure(
360                         "Different annotation elements", annot_original,
361                         annot_new, allowNullAnnotation);
362               }
363             }
364           }
365           else if (al.getSequenceAt(i).getAnnotation() == null
366                   && al_input.getSequenceAt(in).getAnnotation() == null)
367           {
368             System.out.println("No annotations");
369           }
370           else if (al.getSequenceAt(i).getAnnotation() != null
371                   && al_input.getSequenceAt(in).getAnnotation() == null)
372           {
373             fail("Annotations differed between sequences ("
374                     + al.getSequenceAt(i).getName() + ") and ("
375                     + al_input.getSequenceAt(i).getName() + ")");
376           }
377           break;
378         }
379       }
380     }
381   }
382
383   /**
384    * compare two annotation rows, with special support for secondary structure
385    * comparison. With RNA, only the value and the secondaryStructure symbols are
386    * compared, displayCharacter and description are ignored. Annotations where
387    * Annotation.isWhitespace() is true are always considered equal.
388    * 
389    * @param message
390    *          - not actually used yet..
391    * @param annot_or
392    *          - the original annotation
393    * @param annot_new
394    *          - the one compared to the original annotation
395    * @param allowNullEquivalence
396    *          when true, positions in alignment annotation that are null will be
397    *          considered equal to non-null positions for which
398    *          Annotation.isWhitespace() is true.
399    */
400   private static void assertEqualSecondaryStructure(String message,
401           AlignmentAnnotation annot_or, AlignmentAnnotation annot_new,
402           boolean allowNullEqivalence)
403   {
404     // TODO: test to cover this assert behaves correctly for all allowed
405     // variations of secondary structure annotation row equivalence
406     if (annot_or.annotations.length != annot_new.annotations.length)
407     {
408       fail("Different lengths for annotation row elements: "
409               + annot_or.annotations.length + "!="
410               + annot_new.annotations.length);
411     }
412     boolean isRna = annot_or.isRNA();
413     assertTrue("Expected " + (isRna ? " valid RNA " : " no RNA ")
414             + " secondary structure in the row.",
415             isRna == annot_new.isRNA());
416     for (int i = 0; i < annot_or.annotations.length; i++)
417     {
418       Annotation an_or = annot_or.annotations[i], an_new = annot_new.annotations[i];
419       if (an_or != null && an_new != null)
420       {
421
422         if (isRna)
423         {
424           if (an_or.secondaryStructure != an_new.secondaryStructure
425                   || ((Float.isNaN(an_or.value) != Float
426                           .isNaN(an_new.value)) || an_or.value != an_new.value))
427           {
428             fail("Different RNA secondary structure at column " + i
429                     + " expected: [" + annot_or.annotations[i].toString()
430                     + "] but got: [" + annot_new.annotations[i].toString()
431                     + "]");
432           }
433         }
434         else
435         {
436           // not RNA secondary structure, so expect all elements to match...
437           if ((an_or.isWhitespace() != an_new.isWhitespace())
438                   || !an_or.displayCharacter.trim().equals(
439                   an_new.displayCharacter.trim())
440                   || !("" + an_or.secondaryStructure).trim().equals(
441                           ("" + an_new.secondaryStructure).trim())
442                   || (an_or.description != an_new.description && !((an_or.description == null && an_new.description
443                           .trim().length() == 0)
444                           || (an_new.description == null && an_or.description
445                                   .trim().length() == 0) || an_or.description
446                           .trim().equals(an_new.description.trim())))
447                   || !((Float.isNaN(an_or.value) && Float
448                           .isNaN(an_new.value)) || an_or.value == an_new.value))
449           {
450             fail("Annotation Element Mismatch\nElement " + i
451                     + " in original: " + annot_or.annotations[i].toString()
452                     + "\nElement " + i + " in new: "
453                     + annot_new.annotations[i].toString());
454           }
455         }
456       }
457       else if (annot_or.annotations[i] == null
458               && annot_new.annotations[i] == null)
459       {
460         continue;
461       }
462       else
463       {
464         if (allowNullEqivalence)
465         {
466           if (an_or != null && an_or.isWhitespace())
467
468           {
469             continue;
470           }
471           if (an_new != null && an_new.isWhitespace())
472           {
473             continue;
474           }
475         }
476         // need also to test for null in one, non-SS annotation in other...
477         fail("Annotation Element Mismatch\nElement " + i + " in original: "
478                 + (an_or == null ? "is null" : an_or.toString())
479                 + "\nElement " + i + " in new: "
480                 + (an_new == null ? "is null" : an_new.toString()));
481       }
482     }
483   }
484
485   /**
486    * @see assertEqualSecondaryStructure - test if two secondary structure
487    *      annotations are not equal
488    * @param message
489    * @param an_orig
490    * @param an_new
491    * @param allowNullEquivalence
492    */
493   public static void assertNotEqualSecondaryStructure(String message,
494           AlignmentAnnotation an_orig, AlignmentAnnotation an_new,
495           boolean allowNullEquivalence)
496   {
497     boolean thrown = false;
498     try
499     {
500       assertEqualSecondaryStructure("", an_orig, an_new,
501               allowNullEquivalence);
502     } catch (AssertionError af)
503     {
504       thrown = true;
505     }
506     if (!thrown)
507     {
508       fail("Expected difference for [" + an_orig + "] and [" + an_new + "]");
509     }
510   }
511   private AlignmentAnnotation makeAnnot(Annotation ae)
512   {
513     return new AlignmentAnnotation("label", "description", new Annotation[]
514     { ae });
515   }
516
517   @Test(groups={"Functional"})
518   public void testAnnotationEquivalence()
519   {
520     AlignmentAnnotation one = makeAnnot(new Annotation("", "", ' ', 1));
521     AlignmentAnnotation anotherOne = makeAnnot(new Annotation("", "", ' ',
522             1));
523     AlignmentAnnotation sheet = makeAnnot(new Annotation("","",'E',0f));
524     AlignmentAnnotation anotherSheet = makeAnnot(new Annotation("","",'E',0f)); 
525     AlignmentAnnotation sheetWithLabel = makeAnnot(new Annotation("1", "",
526             'E', 0f));
527     AlignmentAnnotation anotherSheetWithLabel = makeAnnot(new Annotation(
528             "1", "", 'E', 0f));
529     AlignmentAnnotation rnaNoDC = makeAnnot(new Annotation("","",'<',0f));
530     AlignmentAnnotation anotherRnaNoDC = makeAnnot(new Annotation("","",'<',0f));
531     AlignmentAnnotation rnaWithDC = makeAnnot(new Annotation("B", "", '<',
532             0f));
533     AlignmentAnnotation anotherRnaWithDC = makeAnnot(new Annotation("B",
534             "", '<', 0f));
535     
536     // check self equivalence
537     for (boolean allowNull : new boolean[] { true, false })
538     {
539       assertEqualSecondaryStructure("Should be equal", one, anotherOne,
540               allowNull);
541       assertEqualSecondaryStructure("Should be equal", sheet, anotherSheet,
542               allowNull);
543       assertEqualSecondaryStructure("Should be equal", sheetWithLabel,
544               anotherSheetWithLabel, allowNull);
545       assertEqualSecondaryStructure("Should be equal", rnaNoDC,
546               anotherRnaNoDC, allowNull);
547       assertEqualSecondaryStructure("Should be equal", rnaWithDC,
548               anotherRnaWithDC, allowNull);
549       // display character doesn't matter for RNA structure (for 2.10.2)
550       assertEqualSecondaryStructure("Should be equal", rnaWithDC, rnaNoDC,
551               allowNull);
552       assertEqualSecondaryStructure("Should be equal", rnaNoDC, rnaWithDC,
553               allowNull);
554     }
555
556     // verify others are different
557     List<AlignmentAnnotation> aaSet = Arrays.asList(one, sheet,
558             sheetWithLabel, rnaWithDC);
559     for (int p = 0; p < aaSet.size(); p++)
560     {
561       for (int q = 0; q < aaSet.size(); q++)
562       {
563         if (p != q)
564         {
565           assertNotEqualSecondaryStructure("Should be different",
566                     aaSet.get(p), aaSet.get(q), false);
567         }
568         else
569         {
570           assertEqualSecondaryStructure("Should be same", aaSet.get(p),
571                   aaSet.get(q), false);
572           assertEqualSecondaryStructure("Should be same", aaSet.get(p),
573                   aaSet.get(q), true);
574           assertNotEqualSecondaryStructure(
575                   "Should be different to empty anot", aaSet.get(p),
576                   makeAnnot(Annotation.EMPTY_ANNOTATION), false);
577           assertNotEqualSecondaryStructure(
578                   "Should be different to empty annot",
579                   makeAnnot(Annotation.EMPTY_ANNOTATION), aaSet.get(q),
580                   true);
581           assertNotEqualSecondaryStructure("Should be different to null",
582                   aaSet.get(p), makeAnnot(null), false);
583           assertNotEqualSecondaryStructure("Should be different to null",
584                   makeAnnot(null), aaSet.get(q), true);
585         }
586       }
587     }
588
589     // test null
590
591   }
592
593   String aliFile = ">Dm\nAAACCCUUUUACACACGGGAAAGGG";
594   String annFile = "JALVIEW_ANNOTATION\n# Created: Thu May 04 11:16:52 BST 2017\n\n"
595           + "SEQUENCE_REF\tDm\nNO_GRAPH\tsecondary structure\tsecondary structure\t"
596           + "(|(|(|(|, .|, .|, .|, .|)|)|)|)|\t0.0\nROWPROPERTIES\t"
597           + "secondary structure\tscaletofit=true\tshowalllabs=true\tcentrelabs=false";
598
599   String annFileCurlyWuss = "JALVIEW_ANNOTATION\n# Created: Thu May 04 11:16:52 BST 2017\n\n"
600           + "SEQUENCE_REF\tDm\nNO_GRAPH\tsecondary structure\tsecondary structure\t"
601           + "(|(|(|(||{|{||{|{||)|)|)|)||}|}|}|}|\t0.0\nROWPROPERTIES\t"
602           + "secondary structure\tscaletofit=true\tshowalllabs=true\tcentrelabs=false";
603   String annFileFullWuss = "JALVIEW_ANNOTATION\n# Created: Thu May 04 11:16:52 BST 2017\n\n"
604           + "SEQUENCE_REF\tDm\nNO_GRAPH\tsecondary structure\tsecondary structure\t"
605           + "(|(|(|(||{|{||[|[||)|)|)|)||}|}|]|]|\t0.0\nROWPROPERTIES\t"
606           + "secondary structure\tscaletofit=true\tshowalllabs=true\tcentrelabs=false";
607
608   @Test(groups = { "Functional" })
609   public void secondaryStructureForRNASequence() throws Exception
610   {
611     roundTripSSForRNA(aliFile, annFile);
612   }
613
614   @Test(groups = { "Functional" })
615   public void curlyWUSSsecondaryStructureForRNASequence() throws Exception
616   {
617     roundTripSSForRNA(aliFile, annFileCurlyWuss);
618   }
619
620   @Test(groups = { "Functional" })
621   public void fullWUSSsecondaryStructureForRNASequence() throws Exception
622   {
623     roundTripSSForRNA(aliFile, annFileFullWuss);
624   }
625
626   @Test(groups = { "Functional" })
627   public void detectWussBrackets()
628   {
629     for (char ch : new char[] { '{', '}', '[', ']', '(', ')', '<', '>' })
630     {
631       Assert.assertTrue(StockholmFile.DETECT_BRACKETS.matchAt("" + ch, 0),
632               "Didn't recognise " + ch + " as a WUSS bracket");
633     }
634     for (char ch : new char[] { '@', '!', 'V', 'Q', '*', ' ', '-', '.' })
635     {
636       Assert.assertFalse(StockholmFile.DETECT_BRACKETS.matchAt("" + ch, 0),
637               "Shouldn't recognise " + ch + " as a WUSS bracket");
638     }
639   }
640   private static void roundTripSSForRNA(String aliFile, String annFile)
641           throws Exception
642   {
643     AlignmentI al = new AppletFormatAdapter().readFile(aliFile,
644             DataSourceType.PASTE, jalview.io.FileFormat.Fasta);
645     AnnotationFile aaf = new AnnotationFile();
646     aaf.readAnnotationFile(al, annFile, DataSourceType.PASTE);
647     al.getAlignmentAnnotation()[0].visible = true;
648
649     // TODO: create a better 'save as <format>' pattern
650     StockholmFile sf = new StockholmFile(al);
651
652     String stockholmFile = sf.print(al.getSequencesArray(), true);
653
654     AlignmentI newAl = new AppletFormatAdapter().readFile(stockholmFile,
655             DataSourceType.PASTE, jalview.io.FileFormat.Stockholm);
656     // AlignmentUtils.showOrHideSequenceAnnotations(newAl.getViewport()
657     // .getAlignment(), Arrays.asList("Secondary Structure"), newAl
658     // .getViewport().getAlignment().getSequences(), true, true);
659     testAlignmentEquivalence(al, newAl, true, true, true);
660
661   }
662
663   @Test(groups = { "Functional" })
664   public void testTypeToDescription()
665   {
666     assertEquals("Secondary Structure",
667             StockholmFile.typeToDescription("SS"));
668     assertEquals("Surface Accessibility",
669             StockholmFile.typeToDescription("SA"));
670     assertEquals("transmembrane", StockholmFile.typeToDescription("TM"));
671     assertEquals("Posterior Probability",
672             StockholmFile.typeToDescription("PP"));
673     assertEquals("ligand binding", StockholmFile.typeToDescription("LI"));
674     assertEquals("active site", StockholmFile.typeToDescription("AS"));
675     assertEquals("intron", StockholmFile.typeToDescription("IN"));
676     assertEquals("interacting residue",
677             StockholmFile.typeToDescription("IR"));
678     assertEquals("accession", StockholmFile.typeToDescription("AC"));
679     assertEquals("organism", StockholmFile.typeToDescription("OS"));
680     assertEquals("class", StockholmFile.typeToDescription("CL"));
681     assertEquals("description", StockholmFile.typeToDescription("DE"));
682     assertEquals("reference", StockholmFile.typeToDescription("DR"));
683     assertEquals("look", StockholmFile.typeToDescription("LO"));
684     assertEquals("Reference Positions",
685             StockholmFile.typeToDescription("RF"));
686
687     // case-sensitive:
688     assertEquals("Rf", StockholmFile.typeToDescription("Rf"));
689     assertEquals("junk", StockholmFile.typeToDescription("junk"));
690     assertEquals("", StockholmFile.typeToDescription(""));
691     assertNull(StockholmFile.typeToDescription(null));
692   }
693
694   @Test(groups = { "Functional" })
695   public void testDescriptionToType()
696   {
697     assertEquals("SS",
698             StockholmFile.descriptionToType("Secondary Structure"));
699     assertEquals("SA",
700             StockholmFile.descriptionToType("Surface Accessibility"));
701     assertEquals("TM", StockholmFile.descriptionToType("transmembrane"));
702
703     // test is not case-sensitive:
704     assertEquals("SS",
705             StockholmFile.descriptionToType("secondary structure"));
706
707     // test is white-space sensitive:
708     assertNull(StockholmFile.descriptionToType("secondary structure "));
709
710     assertNull(StockholmFile.descriptionToType("any old junk"));
711     assertNull(StockholmFile.descriptionToType(""));
712     assertNull(StockholmFile.descriptionToType(null));
713   }
714
715   @Test(groups = { "Functional" })
716   public void testPrint()
717   {
718     SequenceI seq1 = new Sequence("seq1", "LKMF-RS-Q");
719     SequenceI seq2 = new Sequence("seq2/10-15", "RRS-LIP-");
720     SequenceI[] seqs = new SequenceI[] { seq1, seq2 };
721     AlignmentI al = new Alignment(seqs);
722
723     StockholmFile testee = new StockholmFile(al);
724
725     /*
726      * basic output (sequences only): 
727      * sequence ids are padded with 9 spaces more than the widest id
728      */
729     String output = testee.print(seqs, true);
730     String expected = "# STOCKHOLM 1.0\n" + "seq1/1-7           LKMF-RS-Q\n"
731             + "seq2/10-15         RRS-LIP-\n//\n";
732     assertEquals(expected, output);
733     
734     /*
735      * add some dbrefs
736      */
737     seq1.addDBRef(new DBRefEntry("PFAM", "1", "PF00111"));
738     seq1.addDBRef(new DBRefEntry("UNIPROT", "1", "P83527"));
739     seq2.addDBRef(new DBRefEntry("RFAM", "1", "AY119185.1"));
740     seq2.addDBRef(new DBRefEntry("EMBL", "1", "AF125575"));
741     output = testee.print(seqs, true);
742     // PFAM and RFAM dbrefs should be output as AC, others as DR
743     expected = "# STOCKHOLM 1.0\n" + "#=GS seq1/1-7     AC PF00111\n"
744             + "#=GS seq1/1-7     DR UNIPROT ; P83527\n"
745             + "#=GS seq2/10-15   AC AY119185.1\n"
746             + "#=GS seq2/10-15   DR EMBL ; AF125575\n"
747             + "seq1/1-7           LKMF-RS-Q\n"
748             + "seq2/10-15         RRS-LIP-\n//\n";
749     assertEquals(expected, output);
750
751     /*
752      * add some sequence and alignment annotation
753      */
754     Annotation[] anns = new Annotation[5];
755     for (int i = 0; i < anns.length; i++)
756     {
757       anns[i] = new Annotation(String.valueOf((char) ('B' + i)),
758               "Desc " + i,
759               (char) ('C' + i), i + 3);
760     }
761
762     // expect "secondary structure" to be output as #=GR seqid SS
763     // using the secondary structure character (CDEFG) not display char (BCDEF)
764     AlignmentAnnotation aa1 = new AlignmentAnnotation("secondary structure",
765             "ssdesc", anns);
766     aa1.sequenceRef = seq1;
767     seq1.addAlignmentAnnotation(aa1);
768     al.addAnnotation(aa1);
769
770     // "sec structure" should not be output as no corresponding feature id
771     AlignmentAnnotation aa2 = new AlignmentAnnotation("sec structure",
772             "ssdesc", anns);
773     aa2.sequenceRef = seq2;
774     seq2.addAlignmentAnnotation(aa2);
775     al.addAnnotation(aa2);
776
777     // alignment annotation for Reference Positions: output as #=GC RF
778     AlignmentAnnotation aa3 = new AlignmentAnnotation("reference positions",
779             "refpos", anns);
780     al.addAnnotation(aa3);
781
782     // 'seq' annotation: output as seq_cons
783     AlignmentAnnotation aa4 = new AlignmentAnnotation("seq", "seqdesc",
784             anns);
785     al.addAnnotation(aa4);
786
787     // 'intron' annotation: output as IN_cons
788     AlignmentAnnotation aa5 = new AlignmentAnnotation("intron",
789             "introndesc", anns);
790     al.addAnnotation(aa5);
791
792     // 'binding site' annotation: output as binding_site
793     AlignmentAnnotation aa6 = new AlignmentAnnotation("binding site",
794             "bindingdesc", anns);
795     al.addAnnotation(aa6);
796
797     // 'autocalc' annotation should not be output
798     AlignmentAnnotation aa7 = new AlignmentAnnotation("Consensus",
799             "consensusdesc", anns);
800     aa7.autoCalculated = true;
801     al.addAnnotation(aa7);
802
803     // hidden annotation should not be output
804     AlignmentAnnotation aa8 = new AlignmentAnnotation("domains",
805             "domaindesc", anns);
806     aa8.visible = false;
807     al.addAnnotation(aa8);
808
809     output = testee.print(seqs, true);
810     //@formatter:off
811     expected = 
812             "# STOCKHOLM 1.0\n" 
813             + "#=GS seq1/1-7     AC PF00111\n"
814             + "#=GS seq1/1-7     DR UNIPROT ; P83527\n"
815             + "#=GS seq2/10-15   AC AY119185.1\n"
816             + "#=GS seq2/10-15   DR EMBL ; AF125575\n"
817             + "#=GR seq1/1-7 SS   CDEFG\n"
818             + "seq1/1-7           LKMF-RS-Q\n"
819             + "seq2/10-15         RRS-LIP-\n" 
820             + "#=GC RF            BCDEF\n" + "#=GC seq_cons      BCDEF\n"
821             + "#=GC IN_cons       BCDEF\n" + "#=GC binding_site  BCDEF\n"
822             + "//\n";
823     //@formatter:on
824     assertEquals(expected, output);
825   }
826
827   @Test(groups = "Functional")
828   public void testGetAnnotationCharacter()
829   {
830     SequenceI seq = new Sequence("seq", "abc--def-");
831
832     Annotation[] ann = new Annotation[8];
833     ann[1] = new Annotation("Z", "desc", 'E', 1f);
834     ann[2] = new Annotation("Q", "desc", ' ', 1f);
835     ann[4] = new Annotation("", "desc", 'E', 1f);
836     ann[6] = new Annotation("ZH", "desc", 'E', 1f);
837
838     /*
839      * null annotation in column (not Secondary Structure annotation)
840      * should answer sequence character, or '-' if null sequence
841      */
842     assertEquals('-',
843             StockholmFile.getAnnotationCharacter("RF", 0, ann[0], null));
844     assertEquals('d',
845             StockholmFile.getAnnotationCharacter("RF", 5, ann[5], seq));
846     assertEquals('-',
847             StockholmFile.getAnnotationCharacter("RF", 8, null, seq));
848
849     /*
850      * null annotation in column (SS annotation) should answer underscore
851      */
852     assertEquals('_',
853             StockholmFile.getAnnotationCharacter("SS", 0, ann[0], seq));
854
855     /*
856      * SS secondary structure symbol
857      */
858     assertEquals('E',
859             StockholmFile.getAnnotationCharacter("SS", 1, ann[1], seq));
860
861     /*
862      * no SS symbol, use label instead 
863      */
864     assertEquals('Q',
865             StockholmFile.getAnnotationCharacter("SS", 2, ann[2], seq));
866
867     /*
868      * SS with 2 character label - second character overrides SS symbol 
869      */
870     assertEquals('H',
871             StockholmFile.getAnnotationCharacter("SS", 6, ann[6], seq));
872
873     /*
874      * empty display character, not SS - answers '.'
875      */
876     assertEquals('.',
877             StockholmFile.getAnnotationCharacter("RF", 4, ann[4], seq));
878   }
879
880   /**
881    * Test to verify that gaps are input/output as underscore in STO annotation
882    * 
883    * @throws IOException
884    */
885   @Test(groups = "Functional")
886   public void testRoundtripWithGaps() throws IOException
887   {
888     /*
889      * small extract from RF00031_folded.stk
890      */
891     // @formatter:off
892     String stoData = 
893             "# STOCKHOLM 1.0\n" +
894             "#=GR B.taurus.4 SS .._((.))_\n" +
895             "B.taurus.4         AC.UGCGU.\n" +
896             "#=GR B.taurus.5 SS ..((_._))\n" +
897             "B.taurus.5         ACUU.G.CG\n" +
898         "//\n";
899     // @formatter:on
900     StockholmFile parser = new StockholmFile(stoData, DataSourceType.PASTE);
901     SequenceI[] seqs = parser.getSeqsAsArray();
902     assertEquals(2, seqs.length);
903
904     /*
905      * B.taurus.4 has a trailing gap
906      * rendered as underscore in Stockholm annotation
907      */
908     assertEquals("AC.UGCGU.", seqs[0].getSequenceAsString());
909     AlignmentAnnotation[] anns = seqs[0].getAnnotation();
910     assertEquals(1, anns.length);
911     AlignmentAnnotation taurus4SS = anns[0];
912     assertEquals(9, taurus4SS.annotations.length);
913     assertEquals(" .", taurus4SS.annotations[0].displayCharacter);
914     assertNull(taurus4SS.annotations[2]); // gapped position
915     assertNull(taurus4SS.annotations[8]); // gapped position
916     assertEquals('(', taurus4SS.annotations[3].secondaryStructure);
917     assertEquals("(", taurus4SS.annotations[3].displayCharacter);
918     assertEquals(')', taurus4SS.annotations[7].secondaryStructure);
919
920     /*
921      * output as Stockholm and verify it matches the original input
922      * (gaps output as underscore in annotation lines)
923      * note: roundtrip test works with the input lines ordered as above;
924      * can also parse in other orders, but then input doesn't match output
925      */
926     AlignmentFileWriterI afile = FileFormat.Stockholm
927             .getWriter(new Alignment(seqs));
928     String output = afile.print(seqs, false);
929     assertEquals(stoData, output);
930   }
931 }