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