JAL-3053
[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.assertTrue;
26 import static org.testng.AssertJUnit.fail;
27
28 import jalview.datamodel.AlignmentAnnotation;
29 import jalview.datamodel.AlignmentI;
30 import jalview.datamodel.Annotation;
31 import jalview.datamodel.SequenceFeature;
32 import jalview.datamodel.SequenceI;
33 import jalview.gui.JvOptionPane;
34
35 import java.io.File;
36 import java.util.Arrays;
37 import java.util.BitSet;
38 import java.util.HashMap;
39 import java.util.List;
40 import java.util.Map;
41
42 import org.testng.Assert;
43 import org.testng.annotations.BeforeClass;
44 import org.testng.annotations.Test;
45
46 public class StockholmFileTest
47 {
48
49   @BeforeClass(alwaysRun = true)
50   public void setUpJvOptionPane()
51   {
52     JvOptionPane.setInteractiveMode(false);
53     JvOptionPane.setMockResponse(JvOptionPane.CANCEL_OPTION);
54   }
55
56   static String PfamFile = "examples/PF00111_seed.stk",
57           RfamFile = "examples/RF00031_folded.stk",
58           RnaSSTestFile = "examples/rna_ss_test.stk";
59
60   @Test(groups = { "Functional" })
61   public void pfamFileIO() throws Exception
62   {
63     testFileIOwithFormat(new File(PfamFile), FileFormat.Stockholm, -1, 0,
64             false, false, false);
65   }
66
67   @Test(groups = { "Functional" })
68   public void pfamFileDataExtraction() throws Exception
69   {
70     AppletFormatAdapter af = new AppletFormatAdapter();
71     AlignmentI al = af.readFile(PfamFile, DataSourceType.FILE,
72             new IdentifyFile().identify(PfamFile, DataSourceType.FILE));
73     int numpdb = 0;
74     for (SequenceI sq : al.getSequences())
75     {
76       if (sq.getAllPDBEntries() != null)
77       {
78         numpdb += sq.getAllPDBEntries().size();
79       }
80     }
81     assertTrue(
82             "PF00111 seed alignment has at least 1 PDB file, but the reader found none.",
83             numpdb > 0);
84   }
85
86   @Test(groups = { "Functional" })
87   public void rfamFileIO() throws Exception
88   {
89     testFileIOwithFormat(new File(RfamFile), FileFormat.Stockholm, 2, 1,
90             false, false, false);
91   }
92
93   /**
94    * test alignment data in given file can be imported, exported and reimported
95    * with no dataloss
96    * 
97    * @param f
98    *          - source datafile (IdentifyFile.identify() should work with it)
99    * @param ioformat
100    *          - label for IO class used to write and read back in the data from
101    *          f
102    * @param ignoreFeatures
103    * @param ignoreRowVisibility
104    * @param allowNullAnnotations
105    */
106
107   public static void testFileIOwithFormat(File f, FileFormatI ioformat,
108           int naliannot, int nminseqann, boolean ignoreFeatures,
109           boolean ignoreRowVisibility, boolean allowNullAnnotations)
110   {
111     System.out.println("Reading file: " + f);
112     String ff = f.getPath();
113     try
114     {
115       AppletFormatAdapter rf = new AppletFormatAdapter();
116
117       AlignmentI al = rf.readFile(ff, DataSourceType.FILE,
118               new IdentifyFile().identify(ff, DataSourceType.FILE));
119
120       assertNotNull("Couldn't read supplied alignment data.", al);
121
122       // make sure dataset is initialised ? not sure about this
123       for (int i = 0; i < al.getSequencesArray().length; ++i)
124       {
125         al.getSequenceAt(i).createDatasetSequence();
126       }
127       String outputfile = rf.formatSequences(ioformat, al, true);
128       System.out.println("Output file in '" + ioformat + "':\n"
129               + outputfile + "\n<<EOF\n");
130       // test for consistency in io
131       AlignmentI al_input = new AppletFormatAdapter().readFile(outputfile,
132               DataSourceType.PASTE, ioformat);
133       assertNotNull("Couldn't parse reimported alignment data.", al_input);
134
135       FileFormatI identifyoutput = new IdentifyFile().identify(outputfile,
136               DataSourceType.PASTE);
137       assertNotNull("Identify routine failed for outputformat " + ioformat,
138               identifyoutput);
139       assertTrue(
140               "Identify routine could not recognise output generated by '"
141                       + ioformat + "' writer",
142               ioformat.equals(identifyoutput));
143       testAlignmentEquivalence(al, al_input, ignoreFeatures,
144               ignoreRowVisibility, allowNullAnnotations);
145       int numaliannot = 0, numsqswithali = 0;
146       for (AlignmentAnnotation ala : al_input.getAlignmentAnnotation())
147       {
148         if (ala.sequenceRef == null)
149         {
150           numaliannot++;
151         }
152         else
153         {
154           numsqswithali++;
155         }
156       }
157       if (naliannot > -1)
158       {
159         assertEquals("Number of alignment annotations", naliannot,
160                 numaliannot);
161       }
162
163       assertTrue(
164               "Number of sequence associated annotations wasn't at least "
165                       + nminseqann, numsqswithali >= nminseqann);
166
167     } catch (Exception e)
168     {
169       e.printStackTrace();
170       assertTrue("Couln't format the alignment for output file.", false);
171     }
172   }
173
174   /**
175    * assert alignment equivalence
176    * 
177    * @param al
178    *          'original'
179    * @param al_input
180    *          'secondary' or generated alignment from some datapreserving
181    *          transformation
182    * @param ignoreFeatures
183    *          when true, differences in sequence feature annotation are ignored
184    */
185   public static void testAlignmentEquivalence(AlignmentI al,
186           AlignmentI al_input, boolean ignoreFeatures)
187   {
188     testAlignmentEquivalence(al, al_input, ignoreFeatures, false, false);
189   }
190
191   /**
192    * assert alignment equivalence - uses special comparators for RNA structure
193    * annotation rows.
194    * 
195    * @param al
196    *          'original'
197    * @param al_input
198    *          'secondary' or generated alignment from some datapreserving
199    *          transformation
200    * @param ignoreFeatures
201    *          when true, differences in sequence feature annotation are ignored
202    * 
203    * @param ignoreRowVisibility
204    *          when true, do not fail if there are differences in the visibility
205    *          of annotation rows
206    * @param allowNullAnnotation
207    *          when true, positions in alignment annotation that are null will be
208    *          considered equal to positions containing annotation where
209    *          Annotation.isWhitespace() returns true.
210    * 
211    */
212   public static void testAlignmentEquivalence(AlignmentI al,
213           AlignmentI al_input, boolean ignoreFeatures,
214           boolean ignoreRowVisibility, boolean allowNullAnnotation)
215   {
216     assertNotNull("Original alignment was null", al);
217     assertNotNull("Generated alignment was null", al_input);
218
219     assertTrue("Alignment dimension mismatch: original: " + al.getHeight()
220             + "x" + al.getWidth() + ", generated: " + al_input.getHeight()
221             + "x" + al_input.getWidth(),
222             al.getHeight() == al_input.getHeight()
223                     && al.getWidth() == al_input.getWidth());
224
225     // check Alignment annotation
226     AlignmentAnnotation[] aa_new = al_input.getAlignmentAnnotation();
227     AlignmentAnnotation[] aa_original = al.getAlignmentAnnotation();
228
229     // note - at moment we do not distinguish between alignment without any
230     // annotation rows and alignment with no annotation row vector
231     // we might want to revise this in future
232     int aa_new_size = (aa_new == null ? 0 : aa_new.length);
233     int aa_original_size = (aa_original == null ? 0 : aa_original.length);
234     Map<Integer, BitSet> orig_groups = new HashMap<>();
235     Map<Integer, BitSet> new_groups = new HashMap<>();
236
237     if (aa_new != null && aa_original != null)
238     {
239       for (int i = 0; i < aa_original.length; i++)
240       {
241         if (aa_new.length > i)
242         {
243           assertEqualSecondaryStructure(
244                   "Different alignment annotation at position " + i,
245                   aa_original[i], aa_new[i], allowNullAnnotation);
246           // compare graphGroup or graph properties - needed to verify JAL-1299
247           assertEquals("Graph type not identical.", aa_original[i].graph,
248                   aa_new[i].graph);
249           if (!ignoreRowVisibility)
250           {
251             assertEquals("Visibility not identical.",
252                     aa_original[i].visible,
253                   aa_new[i].visible);
254           }
255           assertEquals("Threshold line not identical.",
256                   aa_original[i].threshold, aa_new[i].threshold);
257           // graphGroup may differ, but pattern should be the same
258           Integer o_ggrp = new Integer(aa_original[i].graphGroup + 2);
259           Integer n_ggrp = new Integer(aa_new[i].graphGroup + 2);
260           BitSet orig_g = orig_groups.get(o_ggrp);
261           BitSet new_g = new_groups.get(n_ggrp);
262           if (orig_g == null)
263           {
264             orig_groups.put(o_ggrp, orig_g = new BitSet());
265           }
266           if (new_g == null)
267           {
268             new_groups.put(n_ggrp, new_g = new BitSet());
269           }
270           assertEquals("Graph Group pattern differs at annotation " + i,
271                   orig_g, new_g);
272           orig_g.set(i);
273           new_g.set(i);
274         }
275         else
276         {
277           System.err.println("No matching annotation row for "
278                   + aa_original[i].toString());
279         }
280       }
281     }
282     assertEquals(
283             "Generated and imported alignment have different annotation sets",
284             aa_original_size, aa_new_size);
285
286     // check sequences, annotation and features
287     SequenceI[] seq_original = new SequenceI[al.getSequencesArray().length];
288     seq_original = al.getSequencesArray();
289     SequenceI[] seq_new = new SequenceI[al_input.getSequencesArray().length];
290     seq_new = al_input.getSequencesArray();
291     List<SequenceFeature> sequenceFeatures_original;
292     List<SequenceFeature> sequenceFeatures_new;
293     AlignmentAnnotation annot_original, annot_new;
294     //
295     for (int i = 0; i < al.getSequencesArray().length; i++)
296     {
297       String name = seq_original[i].getName();
298       int start = seq_original[i].getStart();
299       int end = seq_original[i].getEnd();
300       System.out.println("Check sequence: " + name + "/" + start + "-"
301               + end);
302
303       // search equal sequence
304       for (int in = 0; in < al_input.getSequencesArray().length; in++)
305       {
306         if (name.equals(seq_new[in].getName())
307                 && start == seq_new[in].getStart()
308                 && end == seq_new[in].getEnd())
309         {
310           String ss_original = seq_original[i].getSequenceAsString();
311           String ss_new = seq_new[in].getSequenceAsString();
312           assertEquals("The sequences " + name + "/" + start + "-" + end
313                   + " are not equal", ss_original, ss_new);
314
315           assertTrue(
316                   "Sequence Features were not equivalent"
317                           + (ignoreFeatures ? " ignoring." : ""),
318                   ignoreFeatures
319                           || (seq_original[i].getSequenceFeatures() == null && seq_new[in]
320                                   .getSequenceFeatures() == null)
321                           || (seq_original[i].getSequenceFeatures() != null && seq_new[in]
322                                   .getSequenceFeatures() != null));
323           // compare sequence features
324           if (seq_original[i].getSequenceFeatures() != null
325                   && seq_new[in].getSequenceFeatures() != null)
326           {
327             System.out.println("There are feature!!!");
328             sequenceFeatures_original = seq_original[i]
329                     .getSequenceFeatures();
330             sequenceFeatures_new = seq_new[in].getSequenceFeatures();
331
332             assertEquals("different number of features", seq_original[i]
333                     .getSequenceFeatures().size(), seq_new[in]
334                     .getSequenceFeatures().size());
335
336             for (int feat = 0; feat < seq_original[i].getSequenceFeatures()
337                     .size(); feat++)
338             {
339               assertEquals("Different features",
340                       sequenceFeatures_original.get(feat),
341                       sequenceFeatures_new.get(feat));
342             }
343           }
344           // compare alignment annotation
345           if (al.getSequenceAt(i).getAnnotation() != null
346                   && al_input.getSequenceAt(in).getAnnotation() != null)
347           {
348             for (int j = 0; j < al.getSequenceAt(i).getAnnotation().length; j++)
349             {
350               if (al.getSequenceAt(i).getAnnotation()[j] != null
351                       && al_input.getSequenceAt(in).getAnnotation()[j] != null)
352               {
353                 annot_original = al.getSequenceAt(i).getAnnotation()[j];
354                 annot_new = al_input.getSequenceAt(in).getAnnotation()[j];
355                 assertEqualSecondaryStructure(
356                         "Different annotation elements", annot_original,
357                         annot_new, allowNullAnnotation);
358               }
359             }
360           }
361           else if (al.getSequenceAt(i).getAnnotation() == null
362                   && al_input.getSequenceAt(in).getAnnotation() == null)
363           {
364             System.out.println("No annotations");
365           }
366           else if (al.getSequenceAt(i).getAnnotation() != null
367                   && al_input.getSequenceAt(in).getAnnotation() == null)
368           {
369             fail("Annotations differed between sequences ("
370                     + al.getSequenceAt(i).getName() + ") and ("
371                     + al_input.getSequenceAt(i).getName() + ")");
372           }
373           break;
374         }
375       }
376     }
377   }
378
379   /**
380    * compare two annotation rows, with special support for secondary structure
381    * comparison. With RNA, only the value and the secondaryStructure symbols are
382    * compared, displayCharacter and description are ignored. Annotations where
383    * Annotation.isWhitespace() is true are always considered equal.
384    * 
385    * @param message
386    *          - not actually used yet..
387    * @param annot_or
388    *          - the original annotation
389    * @param annot_new
390    *          - the one compared to the original annotation
391    * @param allowNullEquivalence
392    *          when true, positions in alignment annotation that are null will be
393    *          considered equal to non-null positions for which
394    *          Annotation.isWhitespace() is true.
395    */
396   private static void assertEqualSecondaryStructure(String message,
397           AlignmentAnnotation annot_or, AlignmentAnnotation annot_new,
398           boolean allowNullEqivalence)
399   {
400     // TODO: test to cover this assert behaves correctly for all allowed
401     // variations of secondary structure annotation row equivalence
402     if (annot_or.annotations.length != annot_new.annotations.length)
403     {
404       fail("Different lengths for annotation row elements: "
405               + annot_or.annotations.length + "!="
406               + annot_new.annotations.length);
407     }
408     boolean isRna = annot_or.isRNA();
409     assertTrue("Expected " + (isRna ? " valid RNA " : " no RNA ")
410             + " secondary structure in the row.",
411             isRna == annot_new.isRNA());
412     for (int i = 0; i < annot_or.annotations.length; i++)
413     {
414       Annotation an_or = annot_or.annotations[i], an_new = annot_new.annotations[i];
415       if (an_or != null && an_new != null)
416       {
417
418         if (isRna)
419         {
420           if (an_or.secondaryStructure != an_new.secondaryStructure
421                   || ((Float.isNaN(an_or.value) != Float
422                           .isNaN(an_new.value)) || an_or.value != an_new.value))
423           {
424             fail("Different RNA secondary structure at column " + i
425                     + " expected: [" + annot_or.annotations[i].toString()
426                     + "] but got: [" + annot_new.annotations[i].toString()
427                     + "]");
428           }
429         }
430         else
431         {
432           // not RNA secondary structure, so expect all elements to match...
433           if ((an_or.isWhitespace() != an_new.isWhitespace())
434                   || !an_or.displayCharacter.trim().equals(
435                   an_new.displayCharacter.trim())
436                   || !("" + an_or.secondaryStructure).trim().equals(
437                           ("" + an_new.secondaryStructure).trim())
438                   || (an_or.description != an_new.description && !((an_or.description == null && an_new.description
439                           .trim().length() == 0)
440                           || (an_new.description == null && an_or.description
441                                   .trim().length() == 0) || an_or.description
442                           .trim().equals(an_new.description.trim())))
443                   || !((Float.isNaN(an_or.value) && Float
444                           .isNaN(an_new.value)) || an_or.value == an_new.value))
445           {
446             fail("Annotation Element Mismatch\nElement " + i
447                     + " in original: " + annot_or.annotations[i].toString()
448                     + "\nElement " + i + " in new: "
449                     + annot_new.annotations[i].toString());
450           }
451         }
452       }
453       else if (annot_or.annotations[i] == null
454               && annot_new.annotations[i] == null)
455       {
456         continue;
457       }
458       else
459       {
460         if (allowNullEqivalence)
461         {
462           if (an_or != null && an_or.isWhitespace())
463
464           {
465             continue;
466           }
467           if (an_new != null && an_new.isWhitespace())
468           {
469             continue;
470           }
471         }
472         // need also to test for null in one, non-SS annotation in other...
473         fail("Annotation Element Mismatch\nElement " + i + " in original: "
474                 + (an_or == null ? "is null" : an_or.toString())
475                 + "\nElement " + i + " in new: "
476                 + (an_new == null ? "is null" : an_new.toString()));
477       }
478     }
479   }
480
481   /**
482    * @see assertEqualSecondaryStructure - test if two secondary structure
483    *      annotations are not equal
484    * @param message
485    * @param an_orig
486    * @param an_new
487    * @param allowNullEquivalence
488    */
489   public static void assertNotEqualSecondaryStructure(String message,
490           AlignmentAnnotation an_orig, AlignmentAnnotation an_new,
491           boolean allowNullEquivalence)
492   {
493     boolean thrown = false;
494     try
495     {
496       assertEqualSecondaryStructure("", an_orig, an_new,
497               allowNullEquivalence);
498     } catch (AssertionError af)
499     {
500       thrown = true;
501     }
502     if (!thrown)
503     {
504       fail("Expected difference for [" + an_orig + "] and [" + an_new + "]");
505     }
506   }
507   private AlignmentAnnotation makeAnnot(Annotation ae)
508   {
509     return new AlignmentAnnotation("label", "description", new Annotation[]
510     { ae });
511   }
512
513   @Test(groups={"Functional"})
514   public void testAnnotationEquivalence()
515   {
516     AlignmentAnnotation one = makeAnnot(new Annotation("", "", ' ', 1));
517     AlignmentAnnotation anotherOne = makeAnnot(new Annotation("", "", ' ',
518             1));
519     AlignmentAnnotation sheet = makeAnnot(new Annotation("","",'E',0f));
520     AlignmentAnnotation anotherSheet = makeAnnot(new Annotation("","",'E',0f)); 
521     AlignmentAnnotation sheetWithLabel = makeAnnot(new Annotation("1", "",
522             'E', 0f));
523     AlignmentAnnotation anotherSheetWithLabel = makeAnnot(new Annotation(
524             "1", "", 'E', 0f));
525     AlignmentAnnotation rnaNoDC = makeAnnot(new Annotation("","",'<',0f));
526     AlignmentAnnotation anotherRnaNoDC = makeAnnot(new Annotation("","",'<',0f));
527     AlignmentAnnotation rnaWithDC = makeAnnot(new Annotation("B", "", '<',
528             0f));
529     AlignmentAnnotation anotherRnaWithDC = makeAnnot(new Annotation("B",
530             "", '<', 0f));
531     
532     // check self equivalence
533     for (boolean allowNull : new boolean[] { true, false })
534     {
535       assertEqualSecondaryStructure("Should be equal", one, anotherOne,
536               allowNull);
537       assertEqualSecondaryStructure("Should be equal", sheet, anotherSheet,
538               allowNull);
539       assertEqualSecondaryStructure("Should be equal", sheetWithLabel,
540               anotherSheetWithLabel, allowNull);
541       assertEqualSecondaryStructure("Should be equal", rnaNoDC,
542               anotherRnaNoDC, allowNull);
543       assertEqualSecondaryStructure("Should be equal", rnaWithDC,
544               anotherRnaWithDC, allowNull);
545       // display character doesn't matter for RNA structure (for 2.10.2)
546       assertEqualSecondaryStructure("Should be equal", rnaWithDC, rnaNoDC,
547               allowNull);
548       assertEqualSecondaryStructure("Should be equal", rnaNoDC, rnaWithDC,
549               allowNull);
550     }
551
552     // verify others are different
553     List<AlignmentAnnotation> aaSet = Arrays.asList(one, sheet,
554             sheetWithLabel, rnaWithDC);
555     for (int p = 0; p < aaSet.size(); p++)
556     {
557       for (int q = 0; q < aaSet.size(); q++)
558       {
559         if (p != q)
560         {
561           assertNotEqualSecondaryStructure("Should be different",
562                     aaSet.get(p), aaSet.get(q), false);
563         }
564         else
565         {
566           assertEqualSecondaryStructure("Should be same", aaSet.get(p),
567                   aaSet.get(q), false);
568           assertEqualSecondaryStructure("Should be same", aaSet.get(p),
569                   aaSet.get(q), true);
570           assertNotEqualSecondaryStructure(
571                   "Should be different to empty anot", aaSet.get(p),
572                   makeAnnot(Annotation.EMPTY_ANNOTATION), false);
573           assertNotEqualSecondaryStructure(
574                   "Should be different to empty annot",
575                   makeAnnot(Annotation.EMPTY_ANNOTATION), aaSet.get(q),
576                   true);
577           assertNotEqualSecondaryStructure("Should be different to null",
578                   aaSet.get(p), makeAnnot(null), false);
579           assertNotEqualSecondaryStructure("Should be different to null",
580                   makeAnnot(null), aaSet.get(q), true);
581         }
582       }
583     }
584
585     // test null
586
587   }
588
589   String aliFile = ">Dm\nAAACCCUUUUACACACGGGAAAGGG";
590   String annFile = "JALVIEW_ANNOTATION\n# Created: Thu May 04 11:16:52 BST 2017\n\n"
591           + "SEQUENCE_REF\tDm\nNO_GRAPH\tsecondary structure\tsecondary structure\t"
592           + "(|(|(|(|, .|, .|, .|, .|)|)|)|)|\t0.0\nROWPROPERTIES\t"
593           + "secondary structure\tscaletofit=true\tshowalllabs=true\tcentrelabs=false";
594
595   String annFileCurlyWuss = "JALVIEW_ANNOTATION\n# Created: Thu May 04 11:16:52 BST 2017\n\n"
596           + "SEQUENCE_REF\tDm\nNO_GRAPH\tsecondary structure\tsecondary structure\t"
597           + "(|(|(|(||{|{||{|{||)|)|)|)||}|}|}|}|\t0.0\nROWPROPERTIES\t"
598           + "secondary structure\tscaletofit=true\tshowalllabs=true\tcentrelabs=false";
599   String annFileFullWuss = "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
604   @Test(groups = { "Functional" })
605   public void secondaryStructureForRNASequence() throws Exception
606   {
607     roundTripSSForRNA(aliFile, annFile);
608   }
609
610   @Test(groups = { "Functional" })
611   public void curlyWUSSsecondaryStructureForRNASequence() throws Exception
612   {
613     roundTripSSForRNA(aliFile, annFileCurlyWuss);
614   }
615
616   @Test(groups = { "Functional" })
617   public void fullWUSSsecondaryStructureForRNASequence() throws Exception
618   {
619     roundTripSSForRNA(aliFile, annFileFullWuss);
620   }
621
622   @Test(groups = { "Functional" })
623   public void detectWussBrackets()
624   {
625     for (char ch : new char[] { '{', '}', '[', ']', '(', ')', '<', '>' })
626     {
627       Assert.assertTrue(StockholmFile.RNASS_BRACKETS.indexOf(ch) >= 0,
628               "Didn't recognise '" + ch + "' as a WUSS bracket");
629     }
630     for (char ch : new char[] { '@', '!', '*', ' ', '-', '.' })
631     {
632       Assert.assertFalse(StockholmFile.RNASS_BRACKETS.indexOf(ch) >= 0,
633               "Shouldn't recognise '" + ch + "' as a WUSS bracket");
634     }
635   }
636   private static void roundTripSSForRNA(String aliFile, String annFile)
637           throws Exception
638   {
639     AlignmentI al = new AppletFormatAdapter().readFile(aliFile,
640             DataSourceType.PASTE, jalview.io.FileFormat.Fasta);
641     AnnotationFile aaf = new AnnotationFile();
642     aaf.readAnnotationFile(al, annFile, DataSourceType.PASTE);
643     al.getAlignmentAnnotation()[0].visible = true;
644
645     // TODO: create a better 'save as <format>' pattern
646     StockholmFile sf = new StockholmFile(al);
647
648     String stockholmFile = sf.print(al.getSequencesArray(), true);
649
650     AlignmentI newAl = new AppletFormatAdapter().readFile(stockholmFile,
651             DataSourceType.PASTE, jalview.io.FileFormat.Stockholm);
652     // AlignmentUtils.showOrHideSequenceAnnotations(newAl.getViewport()
653     // .getAlignment(), Arrays.asList("Secondary Structure"), newAl
654     // .getViewport().getAlignment().getSequences(), true, true);
655     testAlignmentEquivalence(al, newAl, true, true, true);
656
657   }
658
659   // this is the single sequence alignment and the SS annotations equivalent to
660   // the ones in file RnaSSTestFile
661   String aliFileRnaSSAlphaChars = ">Test.sequence/1-14\n"
662           + "GUACAAAAAAAAAA";
663   String annFileRnaSSAlphaChars = "JALVIEW_ANNOTATION\n"
664           + "# Created: Thu Aug 02 14:54:57 BST 2018\n" + "\n"
665           + "NO_GRAPH\tSecondary Structure\tSecondary Structure\t<,<|(,(|E,E|H,H|B,B|h,h|e,e|b,b|(,(|E,E|),)|e,e|),)|>,>|\t2.0\n"
666           + "\n"
667           + "ROWPROPERTIES\tSecondary Structure\tscaletofit=true\tshowalllabs=true\tcentrelabs=false\n"
668           + "\n" + "\n" + "ALIGNMENT\tID=RNA.SS.TEST\tTP=RNA;";
669   String wrongAnnFileRnaSSAlphaChars = "JALVIEW_ANNOTATION\n"
670           + "# Created: Thu Aug 02 14:54:57 BST 2018\n" + "\n"
671           + "NO_GRAPH\tSecondary Structure\tSecondary Structure\t<,<|(,(|H,H|E,E|B,B|h,h|e,e|b,b|(,(|E,E|),)|e,e|),)|>,>|\t2.0\n"
672           + "\n"
673           + "ROWPROPERTIES\tSecondary Structure\tscaletofit=true\tshowalllabs=true\tcentrelabs=false\n"
674           + "\n" + "\n" + "ALIGNMENT\tID=RNA.SS.TEST\tTP=RNA;";
675   @Test(groups = { "Functional" })
676   public void stockholmFileRnaSSAlphaChars() throws Exception
677   {
678     AppletFormatAdapter af = new AppletFormatAdapter();
679     AlignmentI al = af.readFile(RnaSSTestFile, DataSourceType.FILE,
680             jalview.io.FileFormat.Stockholm);
681     Iterable<AlignmentAnnotation> aai = al.findAnnotations(null, null,
682             "Secondary Structure");
683     AlignmentAnnotation aa = aai.iterator().next();
684     Assert.assertTrue(aa.isRNA(),
685             "'" + RnaSSTestFile + "' not recognised as RNA SS");
686     Assert.assertTrue(aa.isValidStruc(),
687             "'" + RnaSSTestFile + "' not recognised as valid structure");
688     Annotation[] as = aa.annotations;
689     char[] As = new char[as.length];
690     for (int i = 0; i < as.length; i++)
691     {
692       As[i] = as[i].secondaryStructure;
693     }
694     char[] shouldBe = { '<', '(', 'E', 'H', 'B', 'h', 'e', 'b', '(', 'E',
695         ')', 'e', ')', '>' };
696     Assert.assertTrue(
697             Arrays.equals(As, shouldBe),
698             "Annotation is " + new String(As) + " but should be "
699                     + new String(shouldBe));
700
701     // this should result in the same RNA SS Annotations
702     AlignmentI newAl = new AppletFormatAdapter().readFile(
703             aliFileRnaSSAlphaChars,
704             DataSourceType.PASTE, jalview.io.FileFormat.Fasta);
705     AnnotationFile aaf = new AnnotationFile();
706     aaf.readAnnotationFile(newAl, annFileRnaSSAlphaChars,
707             DataSourceType.PASTE);
708
709     Assert.assertTrue(
710             testRnaSSAnnotationsEquivalent(al.getAlignmentAnnotation()[0],
711                     newAl.getAlignmentAnnotation()[0]));
712
713     // this should NOT result in the same RNA SS Annotations
714     newAl = new AppletFormatAdapter().readFile(
715             aliFileRnaSSAlphaChars, DataSourceType.PASTE,
716             jalview.io.FileFormat.Fasta);
717     aaf = new AnnotationFile();
718     aaf.readAnnotationFile(newAl, wrongAnnFileRnaSSAlphaChars,
719             DataSourceType.PASTE);
720
721     boolean mismatch = testRnaSSAnnotationsEquivalent(al.getAlignmentAnnotation()[0],
722             newAl.getAlignmentAnnotation()[0]);
723     Assert.assertFalse( mismatch );
724   }
725
726   private static boolean testRnaSSAnnotationsEquivalent(
727           AlignmentAnnotation a1,
728           AlignmentAnnotation a2)
729   {
730     return a1.rnaSecondaryStructureEquivalent(a2);
731   }
732
733 }