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