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