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