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