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