JAL-1620 version bump and release notes
[jalview.git] / test / jalview / io / StockholmFileTest.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.2b1)
3  * Copyright (C) 2014 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.junit.Assert.assertEquals;
24 import static org.junit.Assert.assertNotNull;
25 import static org.junit.Assert.assertTrue;
26 import jalview.datamodel.Alignment;
27 import jalview.datamodel.AlignmentAnnotation;
28 import jalview.datamodel.AlignmentI;
29 import jalview.datamodel.Annotation;
30 import jalview.datamodel.SequenceFeature;
31 import jalview.datamodel.SequenceI;
32
33 import java.io.File;
34 import java.util.BitSet;
35 import java.util.HashMap;
36 import java.util.Map;
37
38 import org.junit.Test;
39
40 public class StockholmFileTest
41 {
42
43   static String PfamFile = "examples/PF00111_seed.stk",
44           RfamFile = "examples/RF00031_folded.stk";
45
46   @Test
47   public void pfamFileIO() throws Exception
48   {
49     testFileIOwithFormat(new File(PfamFile), "STH", -1, 0);
50   }
51
52   @Test
53   public void pfamFileDataExtraction() throws Exception
54   {
55     AppletFormatAdapter af = new AppletFormatAdapter();
56     AlignmentI al = af.readFile(PfamFile, af.FILE,
57             new IdentifyFile().Identify(PfamFile, af.FILE));
58     int numpdb = 0;
59     for (SequenceI sq : al.getSequences())
60     {
61       if (sq.getPDBId() != null)
62       {
63         numpdb += sq.getPDBId().size();
64       }
65     }
66     assertTrue(
67             "PF00111 seed alignment has at least 1 PDB file, but the reader found none.",
68             numpdb > 0);
69   }
70
71   @Test
72   public void rfamFileIO() throws Exception
73   {
74     testFileIOwithFormat(new File(RfamFile), "STH", 2, 1);
75   }
76
77   /**
78    * test alignment data in given file can be imported, exported and reimported
79    * with no dataloss
80    * 
81    * @param f
82    *          - source datafile (IdentifyFile.identify() should work with it)
83    * @param ioformat
84    *          - label for IO class used to write and read back in the data from
85    *          f
86    */
87   public static void testFileIOwithFormat(File f, String ioformat,
88           int naliannot, int nminseqann)
89   {
90     System.out.println("Reading file: " + f);
91     String ff = f.getPath();
92     try
93     {
94       AppletFormatAdapter rf = new AppletFormatAdapter();
95
96       Alignment al = rf.readFile(ff, AppletFormatAdapter.FILE,
97               new IdentifyFile().Identify(ff, AppletFormatAdapter.FILE));
98
99       assertNotNull("Couldn't read supplied alignment data.", al);
100
101       // make sure dataset is initialised ? not sure about this
102       for (int i = 0; i < al.getSequencesArray().length; ++i)
103       {
104         al.getSequenceAt(i).setDatasetSequence(al.getSequenceAt(i));
105       }
106       String outputfile = rf.formatSequences(ioformat, al, true);
107       System.out.println("Output file in '" + ioformat + "':\n"
108               + outputfile + "\n<<EOF\n");
109       // test for consistency in io
110       Alignment al_input = new AppletFormatAdapter().readFile(outputfile,
111               AppletFormatAdapter.PASTE, ioformat);
112       assertNotNull("Couldn't parse reimported alignment data.", al_input);
113
114       String identifyoutput = new IdentifyFile().Identify(outputfile,
115               AppletFormatAdapter.PASTE);
116       assertNotNull("Identify routine failed for outputformat " + ioformat,
117               identifyoutput);
118       assertTrue(
119               "Identify routine could not recognise output generated by '"
120                       + ioformat + "' writer",
121               ioformat.equals(identifyoutput));
122       testAlignmentEquivalence(al, al_input);
123       int numaliannot = 0, numsqswithali = 0;
124       for (AlignmentAnnotation ala : al_input.getAlignmentAnnotation())
125       {
126         if (ala.sequenceRef == null)
127         {
128           numaliannot++;
129         }
130         else
131         {
132           numsqswithali++;
133         }
134       }
135       if (naliannot > -1)
136       {
137         assertEquals("Number of alignment annotations", naliannot,
138               numaliannot);
139       }
140
141       assertTrue(
142               "Number of sequence associated annotations wasn't at least "
143                       + nminseqann, numsqswithali >= nminseqann);
144
145     } catch (Exception e)
146     {
147       e.printStackTrace();
148       assertTrue("Couln't format the alignment for output file.", false);
149     }
150   }
151
152   /**
153    * assert alignment equivalence
154    * 
155    * @param al
156    *          'original'
157    * @param al_input
158    *          'secondary' or generated alignment from some datapreserving
159    *          transformation
160    */
161   public static void testAlignmentEquivalence(AlignmentI al,
162           AlignmentI al_input)
163   {
164     assertNotNull("Original alignment was null", al);
165     assertNotNull("Generated alignment was null", al_input);
166
167     assertTrue(
168             "Alignment dimension mismatch: originl contains "
169                     + al.getHeight() + " and generated has "
170                     + al_input.getHeight() + " sequences; original has "
171                     + al.getWidth() + " and generated has "
172                     + al_input.getWidth() + " columns.",
173             al.getHeight() == al_input.getHeight()
174                     && al.getWidth() == al_input.getWidth());
175
176     // check Alignment annotation
177     AlignmentAnnotation[] aa_new = al_input.getAlignmentAnnotation();
178     AlignmentAnnotation[] aa_original = al.getAlignmentAnnotation();
179
180     // note - at moment we do not distinguish between alignment without any
181     // annotation rows and alignment with no annotation row vector
182     // we might want to revise this in future
183     int aa_new_size = (aa_new == null ? 0 : aa_new.length), aa_original_size = (aa_original == null ? 0
184             : aa_original.length);
185     Map<Integer, java.util.BitSet> orig_groups = new HashMap<Integer, java.util.BitSet>(), new_groups = new HashMap<Integer, java.util.BitSet>();
186
187     if (aa_new != null && aa_original != null)
188     {
189       for (int i = 0; i < aa_original.length; i++)
190       {
191         if (aa_new.length > i)
192         {
193           assertTrue("Different alignment annotation at position " + i,
194                   equalss(aa_original[i], aa_new[i]));
195           // compare graphGroup or graph properties - needed to verify JAL-1299
196           assertTrue("Graph type not identical.",
197                   aa_original[i].graph == aa_new[i].graph);
198           assertTrue("Visibility not identical.",
199                   aa_original[i].visible == aa_new[i].visible);
200           assertTrue(
201                   "Threshold line not identical.",
202                   aa_original[i].threshold == null ? aa_new[i].threshold == null
203                           : aa_original[i].threshold
204                                   .equals(aa_new[i].threshold));
205           // graphGroup may differ, but pattern should be the same
206           Integer o_ggrp = new Integer(aa_original[i].graphGroup + 2), n_ggrp = new Integer(
207                   aa_new[i].graphGroup + 2);
208           BitSet orig_g = orig_groups.get(o_ggrp), new_g = new_groups
209                   .get(n_ggrp);
210           if (orig_g == null)
211           {
212             orig_groups.put(o_ggrp, orig_g = new BitSet());
213           }
214           if (new_g == null)
215           {
216             new_groups.put(n_ggrp, new_g = new BitSet());
217           }
218           assertTrue("Graph Group pattern differs at annotation " + i,
219                   orig_g.equals(new_g));
220           orig_g.set(i);
221           new_g.set(i);
222         }
223         else
224         {
225           System.err.println("No matching annotation row for "
226                   + aa_original[i].toString());
227         }
228       }
229     }
230     assertTrue(
231             "Generated and imported alignment have different annotation sets ("
232                     + aa_new_size + " != " + aa_original_size + ")",
233             aa_new_size == aa_original_size);
234
235     // check sequences, annotation and features
236     SequenceI[] seq_original = new SequenceI[al.getSequencesArray().length];
237     seq_original = al.getSequencesArray();
238     SequenceI[] seq_new = new SequenceI[al_input.getSequencesArray().length];
239     seq_new = al_input.getSequencesArray();
240     SequenceFeature[] sequenceFeatures_original, sequenceFeatures_new;
241     AlignmentAnnotation annot_original, annot_new;
242     //
243     for (int i = 0; i < al.getSequencesArray().length; i++)
244     {
245       String name = seq_original[i].getName();
246       int start = seq_original[i].getStart();
247       int end = seq_original[i].getEnd();
248       System.out.println("Check sequence: " + name + "/" + start + "-"
249               + end);
250
251       // search equal sequence
252       for (int in = 0; in < al_input.getSequencesArray().length; in++)
253       {
254         if (name.equals(seq_new[in].getName())
255                 && start == seq_new[in].getStart()
256                 && end == seq_new[in].getEnd())
257         {
258           String ss_original = seq_original[i].getSequenceAsString();
259           String ss_new = seq_new[in].getSequenceAsString();
260           assertTrue("The sequences " + name + "/" + start + "-" + end
261                   + " are not equal", ss_original.equals(ss_new));
262
263           assertTrue(
264                   "Sequence Features were not equivalent",
265                   (seq_original[i].getSequenceFeatures() == null && seq_new[in]
266                           .getSequenceFeatures() == null)
267                           || (seq_original[i].getSequenceFeatures() != null && seq_new[in]
268                                   .getSequenceFeatures() != null));
269           // compare sequence features
270           if (seq_original[i].getSequenceFeatures() != null
271                   && seq_new[in].getSequenceFeatures() != null)
272           {
273             System.out.println("There are feature!!!");
274             sequenceFeatures_original = new SequenceFeature[seq_original[i]
275                     .getSequenceFeatures().length];
276             sequenceFeatures_original = seq_original[i]
277                     .getSequenceFeatures();
278             sequenceFeatures_new = new SequenceFeature[seq_new[in]
279                     .getSequenceFeatures().length];
280             sequenceFeatures_new = seq_new[in].getSequenceFeatures();
281
282             assertTrue("different number of features", seq_original[i]
283                     .getSequenceFeatures().length == seq_new[in]
284                     .getSequenceFeatures().length);
285
286             for (int feat = 0; feat < seq_original[i].getSequenceFeatures().length; feat++)
287             {
288               assertTrue("Different features",
289                       sequenceFeatures_original[feat]
290                               .equals(sequenceFeatures_new[feat]));
291             }
292           }
293           // compare alignment annotation
294           if (al.getSequenceAt(i).getAnnotation() != null
295                   && al_input.getSequenceAt(in).getAnnotation() != null)
296           {
297             for (int j = 0; j < al.getSequenceAt(i).getAnnotation().length; j++)
298             {
299               if (al.getSequenceAt(i).getAnnotation()[j] != null
300                       && al_input.getSequenceAt(in).getAnnotation()[j] != null)
301               {
302                 annot_original = al.getSequenceAt(i).getAnnotation()[j];
303                 annot_new = al_input.getSequenceAt(in).getAnnotation()[j];
304                 assertTrue("Different annotation elements",
305                         equalss(annot_original, annot_new));
306               }
307             }
308           }
309           else if (al.getSequenceAt(i).getAnnotation() == null
310                   && al_input.getSequenceAt(in).getAnnotation() == null)
311           {
312             System.out.println("No annotations");
313           }
314           else if (al.getSequenceAt(i).getAnnotation() != null
315                   && al_input.getSequenceAt(in).getAnnotation() == null)
316           {
317             assertTrue("Annotations differed between sequences ("
318                     + al.getSequenceAt(i).getName() + ") and ("
319                     + al_input.getSequenceAt(i).getName() + ")", false);
320           }
321           break;
322         }
323       }
324     }
325   }
326
327   /*
328    * compare annotations
329    */
330   private static boolean equalss(AlignmentAnnotation annot_or,
331           AlignmentAnnotation annot_new)
332   {
333     if (annot_or.annotations.length != annot_new.annotations.length)
334     {
335       System.err.println("Different lengths for annotation row elements: "
336               + annot_or.annotations.length + "!="
337               + annot_new.annotations.length);
338       return false;
339     }
340     for (int i = 0; i < annot_or.annotations.length; i++)
341     {
342       Annotation an_or = annot_or.annotations[i], an_new = annot_new.annotations[i];
343       if (an_or != null && an_new != null)
344       {
345         if (!an_or.displayCharacter.trim().equals(
346                 an_new.displayCharacter.trim())
347                 || !("" + an_or.secondaryStructure).trim().equals(
348                         ("" + an_new.secondaryStructure).trim())
349                 || (an_or.description != an_new.description && (an_or.description == null
350                         || an_new.description == null || !an_or.description
351                           .equals(an_new.description))))
352         {
353           System.err.println("Annotation Element Mismatch\nElement " + i
354                   + " in original: " + annot_or.annotations[i].toString()
355                   + "\nElement " + i + " in new: "
356                   + annot_new.annotations[i].toString());
357           return false;
358         }
359       }
360       else if (annot_or.annotations[i] == null
361               && annot_new.annotations[i] == null)
362       {
363         continue;
364       }
365       else
366       {
367         System.err.println("Annotation Element Mismatch\nElement "
368                 + i
369                 + " in original: "
370                 + (annot_or.annotations[i] == null ? "is null"
371                         : annot_or.annotations[i].toString())
372                 + "\nElement "
373                 + i
374                 + " in new: "
375                 + (annot_new.annotations[i] == null ? "is null"
376                         : annot_new.annotations[i].toString()));
377         return false;
378       }
379     }
380     return true;
381   }
382 }