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