JAL-3365 expand range of allowed DSSP secondary structure symbols in Stockholm files
[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     boolean expectProteinSS = !al.isNucleotide();
278     assertTrue(
279             "Alignments not both "
280                     + (al.isNucleotide() ? "nucleotide" : "protein"),
281             al_input.isNucleotide() == al.isNucleotide());
282
283     // note - at moment we do not distinguish between alignment without any
284     // annotation rows and alignment with no annotation row vector
285     // we might want to revise this in future
286     int aa_new_size = (aa_new == null ? 0 : aa_new.length);
287     int aa_original_size = (aa_original == null ? 0 : aa_original.length);
288     Map<Integer, BitSet> orig_groups = new HashMap<>();
289     Map<Integer, BitSet> new_groups = new HashMap<>();
290
291     if (aa_new != null && aa_original != null)
292     {
293       for (int i = 0; i < aa_original.length; i++)
294       {
295         if (aa_new.length > i)
296         {
297           assertEqualSecondaryStructure(
298                   "Different alignment annotation at position " + i,
299                   aa_original[i], aa_new[i], allowNullAnnotation);
300           if (aa_original[i].hasIcons)
301           {
302             assertTrue(
303                     "Secondary structure expected to be "
304                             + (expectProteinSS ? "protein" : "nucleotide"),
305                     expectProteinSS == !aa_original[i].isRNA());
306           }
307           // compare graphGroup or graph properties - needed to verify JAL-1299
308           assertEquals("Graph type not identical.", aa_original[i].graph,
309                   aa_new[i].graph);
310           if (!ignoreRowVisibility)
311           {
312             assertEquals("Visibility not identical.",
313                     aa_original[i].visible, aa_new[i].visible);
314           }
315           assertEquals("Threshold line not identical.",
316                   aa_original[i].threshold, aa_new[i].threshold);
317           // graphGroup may differ, but pattern should be the same
318           Integer o_ggrp = Integer.valueOf(aa_original[i].graphGroup + 2);
319           Integer n_ggrp = Integer.valueOf(aa_new[i].graphGroup + 2);
320           BitSet orig_g = orig_groups.get(o_ggrp);
321           BitSet new_g = new_groups.get(n_ggrp);
322           if (orig_g == null)
323           {
324             orig_groups.put(o_ggrp, orig_g = new BitSet());
325           }
326           if (new_g == null)
327           {
328             new_groups.put(n_ggrp, new_g = new BitSet());
329           }
330           assertEquals("Graph Group pattern differs at annotation " + i,
331                   orig_g, new_g);
332           orig_g.set(i);
333           new_g.set(i);
334         }
335         else
336         {
337           System.err.println("No matching annotation row for "
338                   + aa_original[i].toString());
339         }
340       }
341     }
342     assertEquals(
343             "Generated and imported alignment have different annotation sets",
344             aa_original_size, aa_new_size);
345
346     // check sequences, annotation and features
347     SequenceI[] seq_original = new SequenceI[al.getSequencesArray().length];
348     seq_original = al.getSequencesArray();
349     SequenceI[] seq_new = new SequenceI[al_input
350             .getSequencesArray().length];
351     seq_new = al_input.getSequencesArray();
352     List<SequenceFeature> sequenceFeatures_original;
353     List<SequenceFeature> sequenceFeatures_new;
354     AlignmentAnnotation annot_original, annot_new;
355     //
356     for (int i = 0; i < al.getSequencesArray().length; i++)
357     {
358       String name = seq_original[i].getName();
359       int start = seq_original[i].getStart();
360       int end = seq_original[i].getEnd();
361       System.out
362               .println("Check sequence: " + name + "/" + start + "-" + end);
363
364       // search equal sequence
365       for (int in = 0; in < al_input.getSequencesArray().length; in++)
366       {
367         if (name.equals(seq_new[in].getName())
368                 && start == seq_new[in].getStart()
369                 && end == seq_new[in].getEnd())
370         {
371           String ss_original = seq_original[i].getSequenceAsString();
372           String ss_new = seq_new[in].getSequenceAsString();
373           assertEquals("The sequences " + name + "/" + start + "-" + end
374                   + " are not equal", ss_original, ss_new);
375
376           assertTrue(
377                   "Sequence Features were not equivalent"
378                           + (ignoreFeatures ? " ignoring." : ""),
379                   ignoreFeatures
380                           || (seq_original[i].getSequenceFeatures() == null
381                                   && seq_new[in]
382                                           .getSequenceFeatures() == null)
383                           || (seq_original[i].getSequenceFeatures() != null
384                                   && seq_new[in]
385                                           .getSequenceFeatures() != null));
386           // compare sequence features
387           if (seq_original[i].getSequenceFeatures() != null
388                   && seq_new[in].getSequenceFeatures() != null)
389           {
390             System.out.println("There are feature!!!");
391             sequenceFeatures_original = seq_original[i]
392                     .getSequenceFeatures();
393             sequenceFeatures_new = seq_new[in].getSequenceFeatures();
394
395             assertEquals("different number of features",
396                     seq_original[i].getSequenceFeatures().size(),
397                     seq_new[in].getSequenceFeatures().size());
398
399             for (int feat = 0; feat < seq_original[i].getSequenceFeatures()
400                     .size(); feat++)
401             {
402               assertEquals("Different features",
403                       sequenceFeatures_original.get(feat),
404                       sequenceFeatures_new.get(feat));
405             }
406           }
407           // compare alignment annotation
408           if (al.getSequenceAt(i).getAnnotation() != null
409                   && al_input.getSequenceAt(in).getAnnotation() != null)
410           {
411             for (int j = 0; j < al.getSequenceAt(i)
412                     .getAnnotation().length; j++)
413             {
414               if (al.getSequenceAt(i).getAnnotation()[j] != null && al_input
415                       .getSequenceAt(in).getAnnotation()[j] != null)
416               {
417                 annot_original = al.getSequenceAt(i).getAnnotation()[j];
418                 annot_new = al_input.getSequenceAt(in).getAnnotation()[j];
419                 assertEqualSecondaryStructure(
420                         "Different annotation elements", annot_original,
421                         annot_new, allowNullAnnotation);
422               }
423             }
424           }
425           else if (al.getSequenceAt(i).getAnnotation() == null
426                   && al_input.getSequenceAt(in).getAnnotation() == null)
427           {
428             System.out.println("No annotations");
429           }
430           else if (al.getSequenceAt(i).getAnnotation() != null
431                   && al_input.getSequenceAt(in).getAnnotation() == null)
432           {
433             fail("Annotations differed between sequences ("
434                     + al.getSequenceAt(i).getName() + ") and ("
435                     + al_input.getSequenceAt(i).getName() + ")");
436           }
437           break;
438         }
439       }
440     }
441   }
442
443   /**
444    * compare two annotation rows, with special support for secondary structure
445    * comparison. With RNA, only the value and the secondaryStructure symbols are
446    * compared, displayCharacter and description are ignored. Annotations where
447    * Annotation.isWhitespace() is true are always considered equal.
448    * 
449    * @param message
450    *          - not actually used yet..
451    * @param annot_or
452    *          - the original annotation
453    * @param annot_new
454    *          - the one compared to the original annotation
455    * @param allowNullEquivalence
456    *          when true, positions in alignment annotation that are null will be
457    *          considered equal to non-null positions for which
458    *          Annotation.isWhitespace() is true.
459    */
460   private static void assertEqualSecondaryStructure(String message,
461           AlignmentAnnotation annot_or, AlignmentAnnotation annot_new,
462           boolean allowNullEqivalence)
463   {
464     // TODO: test to cover this assert behaves correctly for all allowed
465     // variations of secondary structure annotation row equivalence
466     if (annot_or.annotations.length != annot_new.annotations.length)
467     {
468       fail("Different lengths for annotation row elements: "
469               + annot_or.annotations.length + "!="
470               + annot_new.annotations.length);
471     }
472     boolean isRna = annot_or.isRNA();
473     assertTrue(
474             "Expected " + (isRna ? " valid RNA " : " no RNA ")
475                     + " secondary structure in the row.",
476             isRna == annot_new.isRNA());
477     for (int i = 0; i < annot_or.annotations.length; i++)
478     {
479       Annotation an_or = annot_or.annotations[i],
480               an_new = annot_new.annotations[i];
481       if (an_or != null && an_new != null)
482       {
483
484         if (isRna)
485         {
486           if (an_or.secondaryStructure != an_new.secondaryStructure
487                   || ((Float.isNaN(an_or.value) != Float
488                           .isNaN(an_new.value))
489                           || an_or.value != an_new.value))
490           {
491             fail("Different RNA secondary structure at column " + i
492                     + " expected: [" + annot_or.annotations[i].toString()
493                     + "] but got: [" + annot_new.annotations[i].toString()
494                     + "]");
495           }
496         }
497         else
498         {
499           // not RNA secondary structure, so expect all elements to match...
500           if ((an_or.isWhitespace() != an_new.isWhitespace())
501                   || !an_or.displayCharacter.trim()
502                           .equals(an_new.displayCharacter.trim())
503                   || !("" + an_or.secondaryStructure).trim()
504                           .equals(("" + an_new.secondaryStructure).trim())
505                   || (an_or.description != an_new.description
506                           && !((an_or.description == null
507                                   && an_new.description.trim()
508                                           .length() == 0)
509                                   || (an_new.description == null
510                                           && an_or.description.trim()
511                                                   .length() == 0)
512                                   || an_or.description.trim().equals(
513                                           an_new.description.trim())))
514                   || !((Float.isNaN(an_or.value)
515                           && Float.isNaN(an_new.value))
516                           || an_or.value == an_new.value))
517           {
518             fail("Annotation Element Mismatch\nElement " + i
519                     + " in original: " + annot_or.annotations[i].toString()
520                     + "\nElement " + i + " in new: "
521                     + annot_new.annotations[i].toString());
522           }
523         }
524       }
525       else if (annot_or.annotations[i] == null
526               && annot_new.annotations[i] == null)
527       {
528         continue;
529       }
530       else
531       {
532         if (allowNullEqivalence)
533         {
534           if (an_or != null && an_or.isWhitespace())
535
536           {
537             continue;
538           }
539           if (an_new != null && an_new.isWhitespace())
540           {
541             continue;
542           }
543         }
544         // need also to test for null in one, non-SS annotation in other...
545         fail("Annotation Element Mismatch\nElement " + i + " in original: "
546                 + (an_or == null ? "is null" : an_or.toString())
547                 + "\nElement " + i + " in new: "
548                 + (an_new == null ? "is null" : an_new.toString()));
549       }
550     }
551   }
552
553   /**
554    * @see assertEqualSecondaryStructure - test if two secondary structure
555    *      annotations are not equal
556    * @param message
557    * @param an_orig
558    * @param an_new
559    * @param allowNullEquivalence
560    */
561   public static void assertNotEqualSecondaryStructure(String message,
562           AlignmentAnnotation an_orig, AlignmentAnnotation an_new,
563           boolean allowNullEquivalence)
564   {
565     boolean thrown = false;
566     try
567     {
568       assertEqualSecondaryStructure("", an_orig, an_new,
569               allowNullEquivalence);
570     } catch (AssertionError af)
571     {
572       thrown = true;
573     }
574     if (!thrown)
575     {
576       fail("Expected difference for [" + an_orig + "] and [" + an_new
577               + "]");
578     }
579   }
580
581   private AlignmentAnnotation makeAnnot(Annotation ae)
582   {
583     return new AlignmentAnnotation("label", "description",
584             new Annotation[]
585             { ae });
586   }
587
588   @Test(groups = { "Functional" })
589   public void testAnnotationEquivalence()
590   {
591     AlignmentAnnotation one = makeAnnot(new Annotation("", "", ' ', 1));
592     AlignmentAnnotation anotherOne = makeAnnot(
593             new Annotation("", "", ' ', 1));
594     AlignmentAnnotation sheet = makeAnnot(new Annotation("", "", 'E', 0f));
595     AlignmentAnnotation anotherSheet = makeAnnot(
596             new Annotation("", "", 'E', 0f));
597     AlignmentAnnotation sheetWithLabel = makeAnnot(
598             new Annotation("1", "", 'E', 0f));
599     AlignmentAnnotation anotherSheetWithLabel = makeAnnot(
600             new Annotation("1", "", 'E', 0f));
601     AlignmentAnnotation rnaNoDC = makeAnnot(
602             new Annotation("", "", '<', 0f));
603     AlignmentAnnotation anotherRnaNoDC = makeAnnot(
604             new Annotation("", "", '<', 0f));
605     AlignmentAnnotation rnaWithDC = makeAnnot(
606             new Annotation("B", "", '<', 0f));
607     AlignmentAnnotation anotherRnaWithDC = makeAnnot(
608             new Annotation("B", "", '<', 0f));
609
610     // check self equivalence
611     for (boolean allowNull : new boolean[] { true, false })
612     {
613       assertEqualSecondaryStructure("Should be equal", one, anotherOne,
614               allowNull);
615       assertEqualSecondaryStructure("Should be equal", sheet, anotherSheet,
616               allowNull);
617       assertEqualSecondaryStructure("Should be equal", sheetWithLabel,
618               anotherSheetWithLabel, allowNull);
619       assertEqualSecondaryStructure("Should be equal", rnaNoDC,
620               anotherRnaNoDC, allowNull);
621       assertEqualSecondaryStructure("Should be equal", rnaWithDC,
622               anotherRnaWithDC, allowNull);
623       // display character doesn't matter for RNA structure (for 2.10.2)
624       assertEqualSecondaryStructure("Should be equal", rnaWithDC, rnaNoDC,
625               allowNull);
626       assertEqualSecondaryStructure("Should be equal", rnaNoDC, rnaWithDC,
627               allowNull);
628     }
629
630     // verify others are different
631     List<AlignmentAnnotation> aaSet = Arrays.asList(one, sheet,
632             sheetWithLabel, rnaWithDC);
633     for (int p = 0; p < aaSet.size(); p++)
634     {
635       for (int q = 0; q < aaSet.size(); q++)
636       {
637         if (p != q)
638         {
639           assertNotEqualSecondaryStructure("Should be different",
640                   aaSet.get(p), aaSet.get(q), false);
641         }
642         else
643         {
644           assertEqualSecondaryStructure("Should be same", aaSet.get(p),
645                   aaSet.get(q), false);
646           assertEqualSecondaryStructure("Should be same", aaSet.get(p),
647                   aaSet.get(q), true);
648           assertNotEqualSecondaryStructure(
649                   "Should be different to empty anot", aaSet.get(p),
650                   makeAnnot(Annotation.EMPTY_ANNOTATION), false);
651           assertNotEqualSecondaryStructure(
652                   "Should be different to empty annot",
653                   makeAnnot(Annotation.EMPTY_ANNOTATION), aaSet.get(q),
654                   true);
655           assertNotEqualSecondaryStructure("Should be different to null",
656                   aaSet.get(p), makeAnnot(null), false);
657           assertNotEqualSecondaryStructure("Should be different to null",
658                   makeAnnot(null), aaSet.get(q), true);
659         }
660       }
661     }
662
663     // test null
664
665   }
666
667   String aliFile = ">Dm\nAAACCCUUUUACACACGGGAAAGGG";
668
669   String annFile = "JALVIEW_ANNOTATION\n# Created: Thu May 04 11:16:52 BST 2017\n\n"
670           + "SEQUENCE_REF\tDm\nNO_GRAPH\tsecondary structure\tsecondary structure\t"
671           + "(|(|(|(|, .|, .|, .|, .|)|)|)|)|\t0.0\nROWPROPERTIES\t"
672           + "secondary structure\tscaletofit=true\tshowalllabs=true\tcentrelabs=false";
673
674   String annFileCurlyWuss = "JALVIEW_ANNOTATION\n# Created: Thu May 04 11:16:52 BST 2017\n\n"
675           + "SEQUENCE_REF\tDm\nNO_GRAPH\tsecondary structure\tsecondary structure\t"
676           + "(|(|(|(||{|{||{|{||)|)|)|)||}|}|}|}|\t0.0\nROWPROPERTIES\t"
677           + "secondary structure\tscaletofit=true\tshowalllabs=true\tcentrelabs=false";
678
679   String annFileFullWuss = "JALVIEW_ANNOTATION\n# Created: Thu May 04 11:16:52 BST 2017\n\n"
680           + "SEQUENCE_REF\tDm\nNO_GRAPH\tsecondary structure\tsecondary structure\t"
681           + "(|(|(|(||{|{||[|[||)|)|)|)||}|}|]|]|\t0.0\nROWPROPERTIES\t"
682           + "secondary structure\tscaletofit=true\tshowalllabs=true\tcentrelabs=false";
683
684   @Test(groups = { "Functional" })
685   public void secondaryStructureForRNASequence() throws Exception
686   {
687     roundTripSSForRNA(aliFile, annFile);
688   }
689
690   @Test(groups = { "Functional" })
691   public void curlyWUSSsecondaryStructureForRNASequence() throws Exception
692   {
693     roundTripSSForRNA(aliFile, annFileCurlyWuss);
694   }
695
696   @Test(groups = { "Functional" })
697   public void fullWUSSsecondaryStructureForRNASequence() throws Exception
698   {
699     roundTripSSForRNA(aliFile, annFileFullWuss);
700   }
701
702   @Test(groups = { "Functional" })
703   public void detectWussBrackets()
704   {
705     for (char ch : new char[] { '{', '}', '[', ']', '(', ')', '<', '>' })
706     {
707       Assert.assertTrue(StockholmFile.RNASS_BRACKETS.indexOf(ch) >= 0,
708               "Didn't recognise '" + ch + "' as a WUSS bracket");
709     }
710     for (char ch : new char[] { '@', '!', '*', ' ', '-', '.' })
711     {
712       Assert.assertFalse(StockholmFile.RNASS_BRACKETS.indexOf(ch) >= 0,
713               "Shouldn't recognise '" + ch + "' as a WUSS bracket");
714     }
715   }
716
717   private static void roundTripSSForRNA(String aliFile, String annFile)
718           throws Exception
719   {
720     AlignmentI al = new AppletFormatAdapter().readFile(aliFile,
721             DataSourceType.PASTE, jalview.io.FileFormat.Fasta);
722     AnnotationFile aaf = new AnnotationFile();
723     aaf.readAnnotationFile(al, annFile, DataSourceType.PASTE);
724     al.getAlignmentAnnotation()[0].visible = true;
725
726     // TODO: create a better 'save as <format>' pattern
727     StockholmFile sf = new StockholmFile(al);
728
729     String stockholmFile = sf.print(al.getSequencesArray(), true);
730
731     AlignmentI newAl = new AppletFormatAdapter().readFile(stockholmFile,
732             DataSourceType.PASTE, jalview.io.FileFormat.Stockholm);
733     // AlignmentUtils.showOrHideSequenceAnnotations(newAl.getViewport()
734     // .getAlignment(), Arrays.asList("Secondary Structure"), newAl
735     // .getViewport().getAlignment().getSequences(), true, true);
736     testAlignmentEquivalence(al, newAl, true, true, true);
737
738   }
739
740   // this is the single sequence alignment and the SS annotations equivalent to
741   // the ones in file RnaSSTestFile
742   String aliFileRnaSS = ">Test.sequence/1-14\n" + "GUACAAAAAAAAAA";
743
744   String annFileRnaSSAlphaChars = "JALVIEW_ANNOTATION\n"
745           + "# Created: Thu Aug 02 14:54:57 BST 2018\n" + "\n"
746           + "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"
747           + "\n"
748           + "ROWPROPERTIES\tSecondary Structure\tscaletofit=true\tshowalllabs=true\tcentrelabs=false\n"
749           + "\n" + "\n" + "ALIGNMENT\tID=RNA.SS.TEST\tTP=RNA;";
750
751   String wrongAnnFileRnaSSAlphaChars = "JALVIEW_ANNOTATION\n"
752           + "# Created: Thu Aug 02 14:54:57 BST 2018\n" + "\n"
753           + "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"
754           + "\n"
755           + "ROWPROPERTIES\tSecondary Structure\tscaletofit=true\tshowalllabs=true\tcentrelabs=false\n"
756           + "\n" + "\n" + "ALIGNMENT\tID=RNA.SS.TEST\tTP=RNA;";
757
758   @Test(groups = { "Functional" })
759   public void stockholmFileRnaSSAlphaChars() throws Exception
760   {
761     AppletFormatAdapter af = new AppletFormatAdapter();
762     AlignmentI al = af.readFile(RnaSSTestFile, DataSourceType.FILE,
763             jalview.io.FileFormat.Stockholm);
764     Iterable<AlignmentAnnotation> aai = al.findAnnotations(null, null,
765             "Secondary Structure");
766     AlignmentAnnotation aa = aai.iterator().next();
767     Assert.assertTrue(aa.isRNA(),
768             "'" + RnaSSTestFile + "' not recognised as RNA SS");
769     Assert.assertTrue(aa.isValidStruc(),
770             "'" + RnaSSTestFile + "' not recognised as valid structure");
771     Annotation[] as = aa.annotations;
772     char[] As = new char[as.length];
773     for (int i = 0; i < as.length; i++)
774     {
775       As[i] = as[i].secondaryStructure;
776     }
777     char[] shouldBe = { '<', '(', 'E', 'H', 'B', 'h', 'e', 'b', '(', 'E',
778         ')', 'e', ')', '>' };
779     Assert.assertTrue(Arrays.equals(As, shouldBe), "Annotation is "
780             + new String(As) + " but should be " + new String(shouldBe));
781
782     // this should result in the same RNA SS Annotations
783     AlignmentI newAl = new AppletFormatAdapter().readFile(aliFileRnaSS,
784             DataSourceType.PASTE, jalview.io.FileFormat.Fasta);
785     AnnotationFile aaf = new AnnotationFile();
786     aaf.readAnnotationFile(newAl, annFileRnaSSAlphaChars,
787             DataSourceType.PASTE);
788
789     Assert.assertTrue(
790             testRnaSSAnnotationsEquivalent(al.getAlignmentAnnotation()[0],
791                     newAl.getAlignmentAnnotation()[0]),
792             "RNA SS Annotations SHOULD be pair-wise equivalent (but apparently aren't): \n"
793                     + "RNA SS A 1:" + al.getAlignmentAnnotation()[0] + "\n"
794                     + "RNA SS A 2:" + newAl.getAlignmentAnnotation()[0]);
795
796     // this should NOT result in the same RNA SS Annotations
797     newAl = new AppletFormatAdapter().readFile(aliFileRnaSS,
798             DataSourceType.PASTE, jalview.io.FileFormat.Fasta);
799     aaf = new AnnotationFile();
800     aaf.readAnnotationFile(newAl, wrongAnnFileRnaSSAlphaChars,
801             DataSourceType.PASTE);
802
803     boolean mismatch = testRnaSSAnnotationsEquivalent(
804             al.getAlignmentAnnotation()[0],
805             newAl.getAlignmentAnnotation()[0]);
806     Assert.assertFalse(mismatch,
807             "RNA SS Annotations SHOULD NOT be pair-wise equivalent (but apparently are): \n"
808                     + "RNA SS A 1:" + al.getAlignmentAnnotation()[0] + "\n"
809                     + "RNA SS A 2:" + newAl.getAlignmentAnnotation()[0]);
810   }
811
812   private static boolean testRnaSSAnnotationsEquivalent(
813           AlignmentAnnotation a1, AlignmentAnnotation a2)
814   {
815     return a1.rnaSecondaryStructureEquivalent(a2);
816   }
817
818   String annFileRnaSSWithSpaceChars = "JALVIEW_ANNOTATION\n"
819           + "# Created: Thu Aug 02 14:54:57 BST 2018\n" + "\n"
820           + "NO_GRAPH\tSecondary Structure\tSecondary Structure\t<,<|.,.|H,H| , |B,B|h,h| , |b,b|(,(|E,E|.,.|e,e|),)|>,>|\t2.0\n"
821           + "\n"
822           + "ROWPROPERTIES\tSecondary Structure\tscaletofit=true\tshowalllabs=true\tcentrelabs=false\n"
823           + "\n" + "\n" + "ALIGNMENT\tID=RNA.SS.TEST\tTP=RNA;";
824
825   String annFileRnaSSWithoutSpaceChars = "JALVIEW_ANNOTATION\n"
826           + "# Created: Thu Aug 02 14:54:57 BST 2018\n" + "\n"
827           + "NO_GRAPH\tSecondary Structure\tSecondary Structure\t<,<|.,.|H,H|.,.|B,B|h,h|.,.|b,b|(,(|E,E|.,.|e,e|),)|>,>|\t2.0\n"
828           + "\n"
829           + "ROWPROPERTIES\tSecondary Structure\tscaletofit=true\tshowalllabs=true\tcentrelabs=false\n"
830           + "\n" + "\n" + "ALIGNMENT\tID=RNA.SS.TEST\tTP=RNA;";
831
832   String wrongAnnFileRnaSSWithoutSpaceChars = "JALVIEW_ANNOTATION\n"
833           + "# Created: Thu Aug 02 14:54:57 BST 2018\n" + "\n"
834           + "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"
835           + "\n"
836           + "ROWPROPERTIES\tSecondary Structure\tscaletofit=true\tshowalllabs=true\tcentrelabs=false\n"
837           + "\n" + "\n" + "ALIGNMENT\tID=RNA.SS.TEST\tTP=RNA;";
838
839   @Test(groups = { "Functional" })
840   public void stockholmFileRnaSSSpaceChars() throws Exception
841   {
842     AlignmentI alWithSpaces = new AppletFormatAdapter().readFile(
843             aliFileRnaSS, DataSourceType.PASTE,
844             jalview.io.FileFormat.Fasta);
845     AnnotationFile afWithSpaces = new AnnotationFile();
846     afWithSpaces.readAnnotationFile(alWithSpaces,
847             annFileRnaSSWithSpaceChars, DataSourceType.PASTE);
848
849     Iterable<AlignmentAnnotation> aaiWithSpaces = alWithSpaces
850             .findAnnotations(null, null, "Secondary Structure");
851     AlignmentAnnotation aaWithSpaces = aaiWithSpaces.iterator().next();
852     Assert.assertTrue(aaWithSpaces.isRNA(),
853             "'" + aaWithSpaces + "' not recognised as RNA SS");
854     Assert.assertTrue(aaWithSpaces.isValidStruc(),
855             "'" + aaWithSpaces + "' not recognised as valid structure");
856     Annotation[] annWithSpaces = aaWithSpaces.annotations;
857     char[] As = new char[annWithSpaces.length];
858     for (int i = 0; i < annWithSpaces.length; i++)
859     {
860       As[i] = annWithSpaces[i].secondaryStructure;
861     }
862     // check all spaces and dots are spaces in the internal representation
863     char[] shouldBe = { '<', ' ', 'H', ' ', 'B', 'h', ' ', 'b', '(', 'E',
864         ' ', 'e', ')', '>' };
865     Assert.assertTrue(Arrays.equals(As, shouldBe), "Annotation is "
866             + new String(As) + " but should be " + new String(shouldBe));
867
868     // this should result in the same RNA SS Annotations
869     AlignmentI alWithoutSpaces = new AppletFormatAdapter().readFile(
870             aliFileRnaSS, DataSourceType.PASTE,
871             jalview.io.FileFormat.Fasta);
872     AnnotationFile afWithoutSpaces = new AnnotationFile();
873     afWithoutSpaces.readAnnotationFile(alWithoutSpaces,
874             annFileRnaSSWithoutSpaceChars, DataSourceType.PASTE);
875
876     Assert.assertTrue(
877             testRnaSSAnnotationsEquivalent(
878                     alWithSpaces.getAlignmentAnnotation()[0],
879                     alWithoutSpaces.getAlignmentAnnotation()[0]),
880             "RNA SS Annotations SHOULD be pair-wise equivalent (but apparently aren't): \n"
881                     + "RNA SS A 1:"
882                     + alWithSpaces.getAlignmentAnnotation()[0]
883                             .getRnaSecondaryStructure()
884                     + "\n" + "RNA SS A 2:"
885                     + alWithoutSpaces.getAlignmentAnnotation()[0]
886                             .getRnaSecondaryStructure());
887
888     // this should NOT result in the same RNA SS Annotations
889     AlignmentI wrongAlWithoutSpaces = new AppletFormatAdapter().readFile(
890             aliFileRnaSS, DataSourceType.PASTE,
891             jalview.io.FileFormat.Fasta);
892     AnnotationFile wrongAfWithoutSpaces = new AnnotationFile();
893     wrongAfWithoutSpaces.readAnnotationFile(wrongAlWithoutSpaces,
894             wrongAnnFileRnaSSWithoutSpaceChars, DataSourceType.PASTE);
895
896     Assert.assertFalse(
897             testRnaSSAnnotationsEquivalent(
898                     alWithSpaces.getAlignmentAnnotation()[0],
899                     wrongAlWithoutSpaces.getAlignmentAnnotation()[0]),
900             "RNA SS Annotations SHOULD NOT be pair-wise equivalent (but apparently are): \n"
901                     + "RNA SS A 1:"
902                     + alWithSpaces.getAlignmentAnnotation()[0]
903                             .getRnaSecondaryStructure()
904                     + "\n" + "RNA SS A 2:"
905                     + wrongAlWithoutSpaces.getAlignmentAnnotation()[0]
906                             .getRnaSecondaryStructure());
907
908     // check no spaces in the output
909     // TODO: create a better 'save as <format>' pattern
910     alWithSpaces.getAlignmentAnnotation()[0].visible = true;
911     StockholmFile sf = new StockholmFile(alWithSpaces);
912
913     String stockholmFile = sf.print(alWithSpaces.getSequencesArray(), true);
914     Pattern noSpacesInRnaSSAnnotation = Pattern
915             .compile("\\n#=GC SS_cons\\s+\\S{14}\\n");
916     Matcher m = noSpacesInRnaSSAnnotation.matcher(stockholmFile);
917     boolean matches = m.find();
918     Assert.assertTrue(matches,
919             "StockholmFile output does not contain expected output (may contain spaces):\n"
920                     + stockholmFile);
921
922   }
923 }