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