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