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