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