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