Merge branch 'releases/Release_2_10_4_Branch'
[jalview.git] / test / jalview / io / Jalview2xmlTests.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.assertEquals;
24 import static org.testng.Assert.assertFalse;
25 import static org.testng.Assert.assertNotNull;
26 import static org.testng.Assert.assertSame;
27 import static org.testng.Assert.assertTrue;
28
29 import jalview.api.AlignViewportI;
30 import jalview.api.AlignmentViewPanel;
31 import jalview.api.ViewStyleI;
32 import jalview.datamodel.AlignmentAnnotation;
33 import jalview.datamodel.AlignmentI;
34 import jalview.datamodel.HiddenSequences;
35 import jalview.datamodel.PDBEntry;
36 import jalview.datamodel.PDBEntry.Type;
37 import jalview.datamodel.SequenceCollectionI;
38 import jalview.datamodel.SequenceGroup;
39 import jalview.datamodel.SequenceI;
40 import jalview.gui.AlignFrame;
41 import jalview.gui.AlignViewport;
42 import jalview.gui.AlignmentPanel;
43 import jalview.gui.Desktop;
44 import jalview.gui.Jalview2XML;
45 import jalview.gui.JvOptionPane;
46 import jalview.gui.PopupMenu;
47 import jalview.gui.SliderPanel;
48 import jalview.renderer.ResidueShaderI;
49 import jalview.schemes.AnnotationColourGradient;
50 import jalview.schemes.BuriedColourScheme;
51 import jalview.schemes.ColourSchemeI;
52 import jalview.schemes.ColourSchemeProperty;
53 import jalview.schemes.JalviewColourScheme;
54 import jalview.schemes.RNAHelicesColour;
55 import jalview.schemes.StrandColourScheme;
56 import jalview.schemes.TCoffeeColourScheme;
57 import jalview.structure.StructureImportSettings;
58 import jalview.viewmodel.AlignmentViewport;
59
60 import java.io.File;
61 import java.io.IOException;
62 import java.util.ArrayList;
63 import java.util.HashMap;
64 import java.util.List;
65 import java.util.Map;
66
67 import org.testng.Assert;
68 import org.testng.AssertJUnit;
69 import org.testng.annotations.BeforeClass;
70 import org.testng.annotations.Test;
71
72 @Test(singleThreaded = true)
73 public class Jalview2xmlTests extends Jalview2xmlBase
74 {
75
76   @Override
77   @BeforeClass(alwaysRun = true)
78   public void setUpJvOptionPane()
79   {
80     JvOptionPane.setInteractiveMode(false);
81     JvOptionPane.setMockResponse(JvOptionPane.CANCEL_OPTION);
82   }
83
84   @Test(groups = { "Functional" })
85   public void testRNAStructureRecovery() throws Exception
86   {
87     String inFile = "examples/RF00031_folded.stk";
88     String tfile = File.createTempFile("JalviewTest", ".jvp")
89             .getAbsolutePath();
90     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(inFile,
91             DataSourceType.FILE);
92     assertNotNull(af, "Didn't read input file " + inFile);
93     int olddsann = countDsAnn(af.getViewport());
94     assertTrue(olddsann > 0, "Didn't find any dataset annotations");
95     af.changeColour_actionPerformed(JalviewColourScheme.RNAHelices
96             .toString());
97     assertTrue(
98             af.getViewport().getGlobalColourScheme() instanceof RNAHelicesColour,
99             "Couldn't apply RNA helices colourscheme");
100     assertTrue(af.saveAlignment(tfile, FileFormat.Jalview),
101             "Failed to store as a project.");
102     af.closeMenuItem_actionPerformed(true);
103     af = null;
104     af = new FileLoader()
105             .LoadFileWaitTillLoaded(tfile, DataSourceType.FILE);
106     assertNotNull(af, "Failed to import new project");
107     int newdsann = countDsAnn(af.getViewport());
108     assertEquals(olddsann, newdsann,
109             "Differing numbers of dataset sequence annotation\nOriginally "
110                     + olddsann + " and now " + newdsann);
111     System.out
112             .println("Read in same number of annotations as originally present ("
113                     + olddsann + ")");
114     assertTrue(
115
116     af.getViewport().getGlobalColourScheme() instanceof RNAHelicesColour,
117             "RNA helices colourscheme was not applied on import.");
118   }
119
120   @Test(groups = { "Functional" })
121   public void testTCoffeeScores() throws Exception
122   {
123     String inFile = "examples/uniref50.fa", inAnnot = "examples/uniref50.score_ascii";
124     String tfile = File.createTempFile("JalviewTest", ".jvp")
125             .getAbsolutePath();
126     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(inFile,
127             DataSourceType.FILE);
128     assertNotNull(af, "Didn't read input file " + inFile);
129     af.loadJalviewDataFile(inAnnot, DataSourceType.FILE, null, null);
130     assertSame(af.getViewport().getGlobalColourScheme().getClass(),
131             TCoffeeColourScheme.class, "Didn't set T-coffee colourscheme");
132     assertNotNull(ColourSchemeProperty.getColourScheme(af.getViewport()
133             .getAlignment(), af.getViewport().getGlobalColourScheme()
134             .getSchemeName()), "Recognise T-Coffee score from string");
135
136     assertTrue(af.saveAlignment(tfile, FileFormat.Jalview),
137             "Failed to store as a project.");
138     af.closeMenuItem_actionPerformed(true);
139     af = null;
140     af = new FileLoader()
141             .LoadFileWaitTillLoaded(tfile, DataSourceType.FILE);
142     assertNotNull(af, "Failed to import new project");
143     assertSame(af.getViewport().getGlobalColourScheme().getClass(),
144             TCoffeeColourScheme.class,
145             "Didn't set T-coffee colourscheme for imported project.");
146     System.out
147             .println("T-Coffee score shading successfully recovered from project.");
148   }
149
150   @Test(groups = { "Functional" })
151   public void testColourByAnnotScores() throws Exception
152   {
153     String inFile = "examples/uniref50.fa", inAnnot = "examples/testdata/uniref50_iupred.jva";
154     String tfile = File.createTempFile("JalviewTest", ".jvp")
155             .getAbsolutePath();
156     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(inFile,
157             DataSourceType.FILE);
158     assertNotNull(af, "Didn't read input file " + inFile);
159     af.loadJalviewDataFile(inAnnot, DataSourceType.FILE, null, null);
160     AlignmentAnnotation[] aa = af.getViewport().getAlignment()
161             .getSequenceAt(0).getAnnotation("IUPredWS (Short)");
162     assertTrue(
163
164     aa != null && aa.length > 0,
165             "Didn't find any IUPred annotation to use to shade alignment.");
166     AnnotationColourGradient cs = new AnnotationColourGradient(aa[0], null,
167             AnnotationColourGradient.ABOVE_THRESHOLD);
168     AnnotationColourGradient gcs = new AnnotationColourGradient(aa[0],
169             null, AnnotationColourGradient.BELOW_THRESHOLD);
170     cs.setSeqAssociated(true);
171     gcs.setSeqAssociated(true);
172     af.changeColour(cs);
173     SequenceGroup sg = new SequenceGroup();
174     sg.setStartRes(57);
175     sg.setEndRes(92);
176     sg.cs.setColourScheme(gcs);
177     af.getViewport().getAlignment().addGroup(sg);
178     sg.addSequence(af.getViewport().getAlignment().getSequenceAt(1), false);
179     sg.addSequence(af.getViewport().getAlignment().getSequenceAt(2), true);
180     af.alignPanel.alignmentChanged();
181     assertTrue(af.saveAlignment(tfile, FileFormat.Jalview),
182             "Failed to store as a project.");
183     af.closeMenuItem_actionPerformed(true);
184     af = null;
185     af = new FileLoader()
186             .LoadFileWaitTillLoaded(tfile, DataSourceType.FILE);
187     assertNotNull(af, "Failed to import new project");
188
189     // check for group and alignment colourschemes
190
191     ColourSchemeI _rcs = af.getViewport().getGlobalColourScheme();
192     ColourSchemeI _rgcs = af.getViewport().getAlignment().getGroups()
193             .get(0).getColourScheme();
194     assertNotNull(_rcs, "Didn't recover global colourscheme");
195     assertTrue(_rcs instanceof AnnotationColourGradient,
196             "Didn't recover annotation colour global scheme");
197     AnnotationColourGradient __rcs = (AnnotationColourGradient) _rcs;
198     assertTrue(__rcs.isSeqAssociated(),
199             "Annotation colourscheme wasn't sequence associated");
200
201     boolean diffseqcols = false, diffgseqcols = false;
202     SequenceI[] sqs = af.getViewport().getAlignment().getSequencesArray();
203     for (int p = 0, pSize = af.getViewport().getAlignment().getWidth(); p < pSize
204             && (!diffseqcols || !diffgseqcols); p++)
205     {
206       if (_rcs.findColour(sqs[0].getCharAt(p), p, sqs[0], null, 0f) != _rcs
207               .findColour(sqs[5].getCharAt(p), p, sqs[5], null, 0f))
208       {
209         diffseqcols = true;
210       }
211     }
212     assertTrue(diffseqcols, "Got Different sequence colours");
213     System.out
214             .println("Per sequence colourscheme (Background) successfully applied and recovered.");
215
216     assertNotNull(_rgcs, "Didn't recover group colourscheme");
217     assertTrue(_rgcs instanceof AnnotationColourGradient,
218             "Didn't recover annotation colour group colourscheme");
219     __rcs = (AnnotationColourGradient) _rgcs;
220     assertTrue(__rcs.isSeqAssociated(),
221             "Group Annotation colourscheme wasn't sequence associated");
222
223     for (int p = 0, pSize = af.getViewport().getAlignment().getWidth(); p < pSize
224             && (!diffseqcols || !diffgseqcols); p++)
225     {
226       if (_rgcs.findColour(sqs[1].getCharAt(p), p, sqs[1], null, 0f) != _rgcs
227               .findColour(sqs[2].getCharAt(p), p, sqs[2], null, 0f))
228       {
229         diffgseqcols = true;
230       }
231     }
232     assertTrue(diffgseqcols, "Got Different group sequence colours");
233     System.out
234             .println("Per sequence (Group) colourscheme successfully applied and recovered.");
235   }
236
237   @Test(groups = { "Functional" })
238   public void gatherViewsHere() throws Exception
239   {
240     int origCount = Desktop.getAlignFrames() == null ? 0 : Desktop
241             .getAlignFrames().length;
242     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(
243             "examples/exampleFile_2_7.jar", DataSourceType.FILE);
244     assertNotNull(af, "Didn't read in the example file correctly.");
245     assertTrue(Desktop.getAlignFrames().length == 1 + origCount,
246             "Didn't gather the views in the example file.");
247
248   }
249
250   /**
251    * Test for JAL-2223 - multiple mappings in View Mapping report
252    * 
253    * @throws Exception
254    */
255   @Test(groups = { "Functional" })
256   public void noDuplicatePdbMappingsMade() throws Exception
257   {
258     StructureImportSettings.setProcessSecondaryStructure(true);
259     StructureImportSettings.setVisibleChainAnnotation(true);
260     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(
261             "examples/exampleFile_2_7.jar", DataSourceType.FILE);
262     assertNotNull(af, "Didn't read in the example file correctly.");
263
264     // locate Jmol viewer
265     // count number of PDB mappings the structure selection manager holds -
266     String pdbFile = af.getCurrentView().getStructureSelectionManager()
267             .findFileForPDBId("1A70");
268     assertEquals(
269             af.getCurrentView().getStructureSelectionManager()
270                     .getMapping(pdbFile).length,
271             2, "Expected only two mappings for 1A70");
272
273   }
274
275   @Test(groups = { "Functional" })
276   public void viewRefPdbAnnotation() throws Exception
277   {
278     StructureImportSettings.setProcessSecondaryStructure(true);
279     StructureImportSettings.setVisibleChainAnnotation(true);
280     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(
281             "examples/exampleFile_2_7.jar", DataSourceType.FILE);
282     assertNotNull(af, "Didn't read in the example file correctly.");
283     AlignmentViewPanel sps = null;
284     for (AlignmentViewPanel ap : af.alignPanel.alignFrame.getAlignPanels())
285     {
286       if ("Spinach Feredoxin Structure".equals(ap.getViewName()))
287       {
288         sps = ap;
289         break;
290       }
291     }
292     assertNotNull(sps, "Couldn't find the structure view");
293     AlignmentAnnotation refan = null;
294     for (AlignmentAnnotation ra : sps.getAlignment()
295             .getAlignmentAnnotation())
296     {
297       if (ra.graph != 0)
298       {
299         refan = ra;
300         break;
301       }
302     }
303     assertNotNull(refan, "Annotation secondary structure not found.");
304     SequenceI sq = sps.getAlignment().findName("1A70|");
305     assertNotNull(sq, "Couldn't find 1a70 null chain");
306     // compare the manually added temperature factor annotation
307     // to the track automatically transferred from the pdb structure on load
308     assertNotNull(sq.getDatasetSequence().getAnnotation(),
309             "1a70 has no annotation");
310     for (AlignmentAnnotation ala : sq.getDatasetSequence().getAnnotation())
311     {
312       AlignmentAnnotation alaa;
313       sq.addAlignmentAnnotation(alaa = new AlignmentAnnotation(ala));
314       alaa.adjustForAlignment();
315       if (ala.graph == refan.graph)
316       {
317         for (int p = 0; p < ala.annotations.length; p++)
318         {
319           sq.findPosition(p);
320           try
321           {
322             assertTrue(
323                     (alaa.annotations[p] == null && refan.annotations[p] == null)
324                             || alaa.annotations[p].value == refan.annotations[p].value,
325                     "Mismatch at alignment position " + p);
326           } catch (NullPointerException q)
327           {
328             Assert.fail("Mismatch of alignment annotations at position "
329                     + p + " Ref seq ann: " + refan.annotations[p]
330                     + " alignment " + alaa.annotations[p]);
331           }
332         }
333       }
334     }
335
336   }
337
338   @Test(groups = { "Functional" })
339   public void testCopyViewSettings() throws Exception
340   {
341     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(
342             "examples/exampleFile_2_7.jar", DataSourceType.FILE);
343     assertNotNull(af, "Didn't read in the example file correctly.");
344     AlignmentViewPanel sps = null, groups = null;
345     for (AlignmentViewPanel ap : af.alignPanel.alignFrame.getAlignPanels())
346     {
347       if ("Spinach Feredoxin Structure".equals(ap.getViewName()))
348       {
349         sps = ap;
350       }
351       if (ap.getViewName().contains("MAFFT"))
352       {
353         groups = ap;
354       }
355     }
356     assertNotNull(sps, "Couldn't find the structure view");
357     assertNotNull(groups, "Couldn't find the MAFFT view");
358
359     ViewStyleI structureStyle = sps.getAlignViewport().getViewStyle();
360     ViewStyleI groupStyle = groups.getAlignViewport().getViewStyle();
361     AssertJUnit.assertFalse(structureStyle.sameStyle(groupStyle));
362
363     groups.getAlignViewport().setViewStyle(structureStyle);
364     AssertJUnit.assertFalse(groupStyle.sameStyle(groups.getAlignViewport()
365             .getViewStyle()));
366     Assert.assertTrue(structureStyle.sameStyle(groups.getAlignViewport()
367             .getViewStyle()));
368
369   }
370
371   /**
372    * test store and recovery of expanded views
373    * 
374    * @throws Exception
375    */
376   @Test(groups = { "Functional" }, enabled = true)
377   public void testStoreAndRecoverExpandedviews() throws Exception
378   {
379     Desktop.instance.closeAll_actionPerformed(null);
380
381     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(
382             "examples/exampleFile_2_7.jar", DataSourceType.FILE);
383     Assert.assertEquals(Desktop.getAlignFrames().length, 1);
384     String afid = af.getViewport().getSequenceSetId();
385
386     // check FileLoader returned a reference to the one alignFrame that is
387     // actually on the Desktop
388     assertSame(
389             af,
390             Desktop.getAlignFrameFor(af.getViewport()),
391             "Jalview2XML.loadAlignFrame() didn't return correct AlignFrame reference for multiple view window");
392
393     Desktop.explodeViews(af);
394
395     int oldviews = Desktop.getAlignFrames().length;
396     Assert.assertEquals(Desktop.getAlignFrames().length,
397             Desktop.getAlignmentPanels(afid).length);
398     File tfile = File.createTempFile("testStoreAndRecoverExpanded", ".jvp");
399     try
400     {
401       new Jalview2XML(false).saveState(tfile);
402     } catch (Error e)
403     {
404       Assert.fail("Didn't save the expanded view state", e);
405     } catch (Exception e)
406     {
407       Assert.fail("Didn't save the expanded view state", e);
408     }
409     Desktop.instance.closeAll_actionPerformed(null);
410     if (Desktop.getAlignFrames() != null)
411     {
412       Assert.assertEquals(Desktop.getAlignFrames().length, 0);
413     }
414     af = new FileLoader().LoadFileWaitTillLoaded(tfile.getAbsolutePath(),
415             DataSourceType.FILE);
416     Assert.assertNotNull(af);
417     Assert.assertEquals(
418             Desktop.getAlignFrames().length,
419             Desktop.getAlignmentPanels(af.getViewport().getSequenceSetId()).length);
420     Assert.assertEquals(
421             Desktop.getAlignmentPanels(af.getViewport().getSequenceSetId()).length,
422             oldviews);
423   }
424
425   /**
426    * Test save and reload of a project with a different representative sequence
427    * in each view.
428    * 
429    * @throws Exception
430    */
431   @Test(groups = { "Functional" })
432   public void testStoreAndRecoverReferenceSeqSettings() throws Exception
433   {
434     Desktop.instance.closeAll_actionPerformed(null);
435     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(
436             "examples/exampleFile_2_7.jar", DataSourceType.FILE);
437     assertNotNull(af, "Didn't read in the example file correctly.");
438     String afid = af.getViewport().getSequenceSetId();
439
440     // remember reference sequence for each panel
441     Map<String, SequenceI> refseqs = new HashMap<>();
442
443     /*
444      * mark sequence 2, 3, 4.. in panels 1, 2, 3...
445      * as reference sequence for itself and the preceding sequence
446      */
447     int n = 1;
448     for (AlignmentViewPanel ap : Desktop.getAlignmentPanels(afid))
449     {
450       AlignViewportI av = ap.getAlignViewport();
451       AlignmentI alignment = ap.getAlignment();
452       int repIndex = n % alignment.getHeight();
453       SequenceI rep = alignment.getSequenceAt(repIndex);
454       refseqs.put(ap.getViewName(), rep);
455
456       // code from mark/unmark sequence as reference in jalview.gui.PopupMenu
457       // todo refactor this to an alignment view controller
458       av.setDisplayReferenceSeq(true);
459       av.setColourByReferenceSeq(true);
460       av.getAlignment().setSeqrep(rep);
461
462       n++;
463     }
464     File tfile = File.createTempFile("testStoreAndRecoverReferenceSeq",
465             ".jvp");
466     try
467     {
468       new Jalview2XML(false).saveState(tfile);
469     } catch (Throwable e)
470     {
471       Assert.fail("Didn't save the expanded view state", e);
472     }
473     Desktop.instance.closeAll_actionPerformed(null);
474     if (Desktop.getAlignFrames() != null)
475     {
476       Assert.assertEquals(Desktop.getAlignFrames().length, 0);
477     }
478
479     af = new FileLoader().LoadFileWaitTillLoaded(tfile.getAbsolutePath(),
480             DataSourceType.FILE);
481     afid = af.getViewport().getSequenceSetId();
482
483     for (AlignmentViewPanel ap : Desktop.getAlignmentPanels(afid))
484     {
485       // check representative
486       AlignmentI alignment = ap.getAlignment();
487       SequenceI rep = alignment.getSeqrep();
488       Assert.assertNotNull(rep,
489               "Couldn't restore sequence representative from project");
490       // can't use a strong equals here, because by definition, the sequence IDs
491       // will be different.
492       // could set vamsas session save/restore flag to preserve IDs across
493       // load/saves.
494       Assert.assertEquals(refseqs.get(ap.getViewName()).toString(),
495               rep.toString(),
496               "Representative wasn't the same when recovered.");
497       Assert.assertTrue(ap.getAlignViewport().isDisplayReferenceSeq(),
498               "Display reference sequence view setting not set.");
499       Assert.assertTrue(ap.getAlignViewport().isColourByReferenceSeq(),
500               "Colour By Reference Seq view setting not set.");
501     }
502   }
503
504   @Test(groups = { "Functional" })
505   public void testIsVersionStringLaterThan()
506   {
507     /*
508      * No version / development / test / autobuild is leniently assumed to be
509      * compatible
510      */
511     assertTrue(Jalview2XML.isVersionStringLaterThan(null, null));
512     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3", null));
513     assertTrue(Jalview2XML.isVersionStringLaterThan(null, "2.8.3"));
514     assertTrue(Jalview2XML.isVersionStringLaterThan(null,
515             "Development Build"));
516     assertTrue(Jalview2XML.isVersionStringLaterThan(null,
517             "DEVELOPMENT BUILD"));
518     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3",
519             "Development Build"));
520     assertTrue(Jalview2XML.isVersionStringLaterThan(null, "Test"));
521     assertTrue(Jalview2XML.isVersionStringLaterThan(null, "TEST"));
522     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3", "Test"));
523     assertTrue(Jalview2XML
524             .isVersionStringLaterThan(null, "Automated Build"));
525     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3",
526             "Automated Build"));
527     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3",
528             "AUTOMATED BUILD"));
529
530     /*
531      * same version returns true i.e. compatible
532      */
533     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8", "2.8"));
534     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3", "2.8.3"));
535     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3b1", "2.8.3b1"));
536     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3B1", "2.8.3b1"));
537     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3b1", "2.8.3B1"));
538
539     /*
540      * later version returns true
541      */
542     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3", "2.8.4"));
543     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3", "2.9"));
544     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3", "2.9.2"));
545     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8", "2.8.3"));
546     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3", "2.8.3b1"));
547
548     /*
549      * earlier version returns false
550      */
551     assertFalse(Jalview2XML.isVersionStringLaterThan("2.8.3", "2.8"));
552     assertFalse(Jalview2XML.isVersionStringLaterThan("2.8.4", "2.8.3"));
553     assertFalse(Jalview2XML.isVersionStringLaterThan("2.8.3b1", "2.8.3"));
554     assertFalse(Jalview2XML.isVersionStringLaterThan("2.8.3", "2.8.2b1"));
555     assertFalse(Jalview2XML.isVersionStringLaterThan("2.8.0b2", "2.8.0b1"));
556   }
557
558   /**
559    * Test save and reload of a project with a different sequence group (and
560    * representative sequence) in each view.
561    * 
562    * @throws Exception
563    */
564   @Test(groups = { "Functional" })
565   public void testStoreAndRecoverGroupRepSeqs() throws Exception
566   {
567     Desktop.instance.closeAll_actionPerformed(null);
568     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(
569             "examples/uniref50.fa", DataSourceType.FILE);
570     assertNotNull(af, "Didn't read in the example file correctly.");
571     String afid = af.getViewport().getSequenceSetId();
572     // make a second view of the alignment
573     af.newView_actionPerformed(null);
574
575     /*
576      * remember representative and hidden sequences marked 
577      * on each panel
578      */
579     Map<String, SequenceI> repSeqs = new HashMap<>();
580     Map<String, List<String>> hiddenSeqNames = new HashMap<>();
581
582     /*
583      * mark sequence 2, 3, 4.. in panels 1, 2, 3...
584      * as reference sequence for itself and the preceding sequence
585      */
586     int n = 1;
587     for (AlignmentViewPanel ap : Desktop.getAlignmentPanels(afid))
588     {
589       AlignViewportI av = ap.getAlignViewport();
590       AlignmentI alignment = ap.getAlignment();
591       int repIndex = n % alignment.getHeight();
592       // ensure at least one preceding sequence i.e. index >= 1
593       repIndex = Math.max(repIndex, 1);
594       SequenceI repSeq = alignment.getSequenceAt(repIndex);
595       repSeqs.put(ap.getViewName(), repSeq);
596       List<String> hiddenNames = new ArrayList<>();
597       hiddenSeqNames.put(ap.getViewName(), hiddenNames);
598
599       /*
600        * have rep sequence represent itself and the one before it
601        * this hides the group (except for the rep seq)
602        */
603       SequenceGroup sg = new SequenceGroup();
604       sg.addSequence(repSeq, false);
605       SequenceI precedingSeq = alignment.getSequenceAt(repIndex - 1);
606       sg.addSequence(precedingSeq, false);
607       sg.setSeqrep(repSeq);
608       assertTrue(sg.getSequences().contains(repSeq));
609       assertTrue(sg.getSequences().contains(precedingSeq));
610       av.setSelectionGroup(sg);
611       assertSame(repSeq, sg.getSeqrep());
612
613       /*
614        * represent group with sequence adds to a map of hidden rep sequences
615        * (it does not create a group on the alignment) 
616        */
617       ((AlignmentViewport) av).hideSequences(repSeq, true);
618       assertSame(repSeq, sg.getSeqrep());
619       assertTrue(sg.getSequences().contains(repSeq));
620       assertTrue(sg.getSequences().contains(precedingSeq));
621       assertTrue(alignment.getGroups().isEmpty(), "alignment has groups");
622       Map<SequenceI, SequenceCollectionI> hiddenRepSeqsMap = av
623               .getHiddenRepSequences();
624       assertNotNull(hiddenRepSeqsMap);
625       assertEquals(1, hiddenRepSeqsMap.size());
626       assertSame(sg, hiddenRepSeqsMap.get(repSeq));
627       assertTrue(alignment.getHiddenSequences().isHidden(precedingSeq));
628       assertFalse(alignment.getHiddenSequences().isHidden(repSeq));
629       hiddenNames.add(precedingSeq.getName());
630
631       n++;
632     }
633     File tfile = File
634             .createTempFile("testStoreAndRecoverGroupReps", ".jvp");
635     try
636     {
637       new Jalview2XML(false).saveState(tfile);
638     } catch (Throwable e)
639     {
640       Assert.fail("Didn't save the expanded view state", e);
641     }
642     Desktop.instance.closeAll_actionPerformed(null);
643     if (Desktop.getAlignFrames() != null)
644     {
645       Assert.assertEquals(Desktop.getAlignFrames().length, 0);
646     }
647
648     af = new FileLoader().LoadFileWaitTillLoaded(tfile.getAbsolutePath(),
649             DataSourceType.FILE);
650     afid = af.getViewport().getSequenceSetId();
651
652     for (AlignmentViewPanel ap : Desktop.getAlignmentPanels(afid))
653     {
654       String viewName = ap.getViewName();
655       AlignViewportI av = ap.getAlignViewport();
656       AlignmentI alignment = ap.getAlignment();
657       List<SequenceGroup> groups = alignment.getGroups();
658       assertNotNull(groups);
659       assertTrue(groups.isEmpty(), "Alignment has groups");
660       Map<SequenceI, SequenceCollectionI> hiddenRepSeqsMap = av
661               .getHiddenRepSequences();
662       assertNotNull(hiddenRepSeqsMap, "No hidden represented sequences");
663       assertEquals(1, hiddenRepSeqsMap.size());
664       assertEquals(repSeqs.get(viewName).getDisplayId(true),
665               hiddenRepSeqsMap.keySet().iterator().next()
666                       .getDisplayId(true));
667
668       /*
669        * verify hidden sequences in restored panel
670        */
671       List<String> hidden = hiddenSeqNames.get(ap.getViewName());
672       HiddenSequences hs = alignment.getHiddenSequences();
673       assertEquals(
674               hidden.size(),
675               hs.getSize(),
676               "wrong number of restored hidden sequences in "
677                       + ap.getViewName());
678     }
679   }
680
681   /**
682    * Test save and reload of PDBEntry in Jalview project
683    * 
684    * @throws Exception
685    */
686   @Test(groups = { "Functional" })
687   public void testStoreAndRecoverPDBEntry() throws Exception
688   {
689     Desktop.instance.closeAll_actionPerformed(null);
690     String exampleFile = "examples/3W5V.pdb";
691     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(exampleFile,
692             DataSourceType.FILE);
693     assertNotNull(af, "Didn't read in the example file correctly.");
694     String afid = af.getViewport().getSequenceSetId();
695
696     AlignmentPanel[] alignPanels = Desktop.getAlignmentPanels(afid);
697     System.out.println();
698     AlignmentViewPanel ap = alignPanels[0];
699     String tfileBase = new File(".").getAbsolutePath().replace(".", "");
700     String testFile = tfileBase + exampleFile;
701     AlignmentI alignment = ap.getAlignment();
702     System.out.println("blah");
703     SequenceI[] seqs = alignment.getSequencesArray();
704     Assert.assertNotNull(seqs[0]);
705     Assert.assertNotNull(seqs[1]);
706     Assert.assertNotNull(seqs[2]);
707     Assert.assertNotNull(seqs[3]);
708     Assert.assertNotNull(seqs[0].getDatasetSequence());
709     Assert.assertNotNull(seqs[1].getDatasetSequence());
710     Assert.assertNotNull(seqs[2].getDatasetSequence());
711     Assert.assertNotNull(seqs[3].getDatasetSequence());
712     PDBEntry[] pdbEntries = new PDBEntry[4];
713     pdbEntries[0] = new PDBEntry("3W5V", "A", Type.PDB, testFile);
714     pdbEntries[1] = new PDBEntry("3W5V", "B", Type.PDB, testFile);
715     pdbEntries[2] = new PDBEntry("3W5V", "C", Type.PDB, testFile);
716     pdbEntries[3] = new PDBEntry("3W5V", "D", Type.PDB, testFile);
717     Assert.assertEquals(seqs[0].getDatasetSequence().getAllPDBEntries()
718             .get(0), pdbEntries[0]);
719     Assert.assertEquals(seqs[1].getDatasetSequence().getAllPDBEntries()
720             .get(0), pdbEntries[1]);
721     Assert.assertEquals(seqs[2].getDatasetSequence().getAllPDBEntries()
722             .get(0), pdbEntries[2]);
723     Assert.assertEquals(seqs[3].getDatasetSequence().getAllPDBEntries()
724             .get(0), pdbEntries[3]);
725
726     File tfile = File.createTempFile("testStoreAndRecoverPDBEntry", ".jvp");
727     try
728     {
729       new Jalview2XML(false).saveState(tfile);
730     } catch (Throwable e)
731     {
732       Assert.fail("Didn't save the state", e);
733     }
734     Desktop.instance.closeAll_actionPerformed(null);
735     if (Desktop.getAlignFrames() != null)
736     {
737       Assert.assertEquals(Desktop.getAlignFrames().length, 0);
738     }
739
740     AlignFrame restoredFrame = new FileLoader().LoadFileWaitTillLoaded(
741             tfile.getAbsolutePath(), DataSourceType.FILE);
742     String rfid = restoredFrame.getViewport().getSequenceSetId();
743     AlignmentPanel[] rAlignPanels = Desktop.getAlignmentPanels(rfid);
744     AlignmentViewPanel rap = rAlignPanels[0];
745     AlignmentI rAlignment = rap.getAlignment();
746     System.out.println("blah");
747     SequenceI[] rseqs = rAlignment.getSequencesArray();
748     Assert.assertNotNull(rseqs[0]);
749     Assert.assertNotNull(rseqs[1]);
750     Assert.assertNotNull(rseqs[2]);
751     Assert.assertNotNull(rseqs[3]);
752     Assert.assertNotNull(rseqs[0].getDatasetSequence());
753     Assert.assertNotNull(rseqs[1].getDatasetSequence());
754     Assert.assertNotNull(rseqs[2].getDatasetSequence());
755     Assert.assertNotNull(rseqs[3].getDatasetSequence());
756
757     // The Asserts below are expected to fail until the PDB chainCode is
758     // recoverable from a Jalview projects
759     for (int chain = 0; chain < 4; chain++)
760     {
761       PDBEntry recov = rseqs[chain].getDatasetSequence().getAllPDBEntries()
762               .get(0);
763       PDBEntry expected = pdbEntries[chain];
764       Assert.assertEquals(recov.getId(), expected.getId(),
765               "Mismatch PDB ID");
766       Assert.assertEquals(recov.getChainCode(), expected.getChainCode(),
767               "Mismatch PDB ID");
768       Assert.assertEquals(recov.getType(), expected.getType(),
769               "Mismatch PDBEntry 'Type'");
770       Assert.assertNotNull(recov.getFile(),
771               "Recovered PDBEntry should have a non-null file entry");
772     }
773   }
774
775   /**
776    * Configure an alignment and a sub-group each with distinct colour schemes,
777    * Conservation and PID thresholds, and confirm these are restored from the
778    * saved project.
779    * 
780    * @throws IOException
781    */
782   @Test(groups = { "Functional" })
783   public void testStoreAndRecoverColourThresholds() throws IOException
784   {
785     Desktop.instance.closeAll_actionPerformed(null);
786     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(
787             "examples/uniref50.fa", DataSourceType.FILE);
788
789     AlignViewport av = af.getViewport();
790     AlignmentI al = av.getAlignment();
791
792     /*
793      * Colour alignment by Buried Index, Above 10% PID, By Conservation 20%
794      */
795     af.changeColour_actionPerformed(JalviewColourScheme.Buried.toString());
796     assertTrue(av.getGlobalColourScheme() instanceof BuriedColourScheme);
797     af.abovePIDThreshold_actionPerformed(true);
798     SliderPanel sp = SliderPanel.getSliderPanel();
799     assertFalse(sp.isForConservation());
800     sp.valueChanged(10);
801     af.conservationMenuItem_actionPerformed(true);
802     sp = SliderPanel.getSliderPanel();
803     assertTrue(sp.isForConservation());
804     sp.valueChanged(20);
805     ResidueShaderI rs = av.getResidueShading();
806     assertEquals(rs.getThreshold(), 10);
807     assertTrue(rs.conservationApplied());
808     assertEquals(rs.getConservationInc(), 20);
809
810     /*
811      * create a group with Strand colouring, 30% Conservation
812      * and 40% PID threshold
813      */
814     SequenceGroup sg = new SequenceGroup();
815     sg.addSequence(al.getSequenceAt(0), false);
816     sg.setStartRes(15);
817     sg.setEndRes(25);
818     av.setSelectionGroup(sg);
819     PopupMenu popupMenu = new PopupMenu(af.alignPanel, null, null);
820     popupMenu.changeColour_actionPerformed(JalviewColourScheme.Strand
821             .toString());
822     assertTrue(sg.getColourScheme() instanceof StrandColourScheme);
823     assertEquals(al.getGroups().size(), 1);
824     assertSame(al.getGroups().get(0), sg);
825     popupMenu.conservationMenuItem_actionPerformed(true);
826     sp = SliderPanel.getSliderPanel();
827     assertTrue(sp.isForConservation());
828     sp.valueChanged(30);
829     popupMenu.abovePIDColour_actionPerformed(true);
830     sp = SliderPanel.getSliderPanel();
831     assertFalse(sp.isForConservation());
832     sp.valueChanged(40);
833     assertTrue(sg.getGroupColourScheme().conservationApplied());
834     assertEquals(sg.getGroupColourScheme().getConservationInc(), 30);
835     assertEquals(sg.getGroupColourScheme().getThreshold(), 40);
836
837     /*
838      * save project, close windows, reload project, verify
839      */
840     File tfile = File.createTempFile("testStoreAndRecoverColourThresholds",
841             ".jvp");
842     tfile.deleteOnExit();
843     new Jalview2XML(false).saveState(tfile);
844     Desktop.instance.closeAll_actionPerformed(null);
845     af = new FileLoader().LoadFileWaitTillLoaded(tfile.getAbsolutePath(),
846             DataSourceType.FILE);
847     Assert.assertNotNull(af, "Failed to reload project");
848
849     /*
850      * verify alignment (background) colouring
851      */
852     rs = af.getViewport().getResidueShading();
853     assertTrue(rs.getColourScheme() instanceof BuriedColourScheme);
854     assertEquals(rs.getThreshold(), 10);
855     assertTrue(rs.conservationApplied());
856     assertEquals(rs.getConservationInc(), 20);
857
858     /*
859      * verify group colouring
860      */
861     assertEquals(1, af.getViewport().getAlignment().getGroups().size(), 1);
862     rs = af.getViewport().getAlignment().getGroups().get(0)
863             .getGroupColourScheme();
864     assertTrue(rs.getColourScheme() instanceof StrandColourScheme);
865     assertEquals(rs.getThreshold(), 40);
866     assertTrue(rs.conservationApplied());
867     assertEquals(rs.getConservationInc(), 30);
868   }
869 }