Merge branch 'Jalview-JS/develop_j2s_v3_2_9_j11' into Jalview-JS/develop
[jalview.git] / test / jalview / project / 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.project;
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.assertNull;
27 import static org.testng.Assert.assertSame;
28 import static org.testng.Assert.assertTrue;
29
30 import java.awt.Color;
31 import java.io.File;
32 import java.io.IOException;
33 import java.util.ArrayList;
34 import java.util.HashMap;
35 import java.util.List;
36 import java.util.Map;
37
38 import javax.swing.JInternalFrame;
39
40 import org.testng.Assert;
41 import org.testng.AssertJUnit;
42 import org.testng.annotations.AfterMethod;
43 import org.testng.annotations.BeforeClass;
44 import org.testng.annotations.Test;
45
46 import jalview.analysis.scoremodels.SimilarityParams;
47 import jalview.api.AlignViewportI;
48 import jalview.api.AlignmentViewPanel;
49 import jalview.api.FeatureColourI;
50 import jalview.api.ViewStyleI;
51 import jalview.datamodel.AlignmentAnnotation;
52 import jalview.datamodel.AlignmentI;
53 import jalview.datamodel.DBRefEntry;
54 import jalview.datamodel.GeneLocus;
55 import jalview.datamodel.HiddenSequences;
56 import jalview.datamodel.Mapping;
57 import jalview.datamodel.PDBEntry;
58 import jalview.datamodel.PDBEntry.Type;
59 import jalview.datamodel.Sequence.DBModList;
60 import jalview.datamodel.SequenceCollectionI;
61 import jalview.datamodel.SequenceFeature;
62 import jalview.datamodel.SequenceGroup;
63 import jalview.datamodel.SequenceI;
64 import jalview.datamodel.features.FeatureMatcher;
65 import jalview.datamodel.features.FeatureMatcherSet;
66 import jalview.datamodel.features.FeatureMatcherSetI;
67 import jalview.gui.AlignFrame;
68 import jalview.gui.AlignViewport;
69 import jalview.gui.AlignmentPanel;
70 import jalview.gui.Desktop;
71 import jalview.gui.JvOptionPane;
72 import jalview.gui.PCAPanel;
73 import jalview.gui.PopupMenu;
74 import jalview.gui.SliderPanel;
75 import jalview.io.DataSourceType;
76 import jalview.io.FileFormat;
77 import jalview.io.FileLoader;
78 import jalview.io.Jalview2xmlBase;
79 import jalview.renderer.ResidueShaderI;
80 import jalview.schemes.AnnotationColourGradient;
81 import jalview.schemes.BuriedColourScheme;
82 import jalview.schemes.ColourSchemeI;
83 import jalview.schemes.ColourSchemeProperty;
84 import jalview.schemes.FeatureColour;
85 import jalview.schemes.JalviewColourScheme;
86 import jalview.schemes.RNAHelicesColour;
87 import jalview.schemes.StrandColourScheme;
88 import jalview.schemes.TCoffeeColourScheme;
89 import jalview.structure.StructureImportSettings;
90 import jalview.util.MapList;
91 import jalview.util.matcher.Condition;
92 import jalview.viewmodel.AlignmentViewport;
93 import jalview.viewmodel.seqfeatures.FeatureRendererModel;
94
95 @Test(singleThreaded = true)
96 public class Jalview2xmlTests extends Jalview2xmlBase
97 {
98   @AfterMethod(alwaysRun = true)
99   public void tearDown()
100   {
101     Desktop.getInstance().closeAll_actionPerformed(null);
102   }
103
104   @Override
105   @BeforeClass(alwaysRun = true)
106   public void setUpJvOptionPane()
107   {
108     JvOptionPane.setInteractiveMode(false);
109     JvOptionPane.setMockResponse(JvOptionPane.CANCEL_OPTION);
110   }
111
112   @Test(groups = { "Functional" })
113   public void testRNAStructureRecovery() throws Exception
114   {
115     String inFile = "examples/RF00031_folded.stk";
116     String tfile = File.createTempFile("JalviewTest", ".jvp")
117             .getAbsolutePath();
118     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(inFile,
119             DataSourceType.FILE);
120     assertNotNull(af, "Didn't read input file " + inFile);
121     int olddsann = countDsAnn(af.getViewport());
122     assertTrue(olddsann > 0, "Didn't find any dataset annotations");
123     af.changeColour_actionPerformed(
124             JalviewColourScheme.RNAHelices.toString());
125     assertTrue(
126             af.getViewport()
127                     .getGlobalColourScheme() instanceof RNAHelicesColour,
128             "Couldn't apply RNA helices colourscheme");
129     af.saveAlignment(tfile, FileFormat.Jalview);
130     assertTrue(af.isSaveAlignmentSuccessful(),
131             "Failed to store as a project.");
132     af.closeMenuItem_actionPerformed(true);
133     af = null;
134     af = new FileLoader().LoadFileWaitTillLoaded(tfile,
135             DataSourceType.FILE);
136     assertNotNull(af, "Failed to import new project");
137     int newdsann = countDsAnn(af.getViewport());
138     assertEquals(olddsann, newdsann,
139             "Differing numbers of dataset sequence annotation\nOriginally "
140                     + olddsann + " and now " + newdsann);
141     System.out.println(
142             "Read in same number of annotations as originally present ("
143                     + olddsann + ")");
144     assertTrue(
145
146             af.getViewport()
147                     .getGlobalColourScheme() instanceof RNAHelicesColour,
148             "RNA helices colourscheme was not applied on import.");
149   }
150
151   @Test(groups = { "Functional" })
152   public void testTCoffeeScores() throws Exception
153   {
154     String inFile = "examples/uniref50.fa",
155             inAnnot = "examples/uniref50.score_ascii";
156     String tfile = File.createTempFile("JalviewTest", ".jvp")
157             .getAbsolutePath();
158     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(inFile,
159             DataSourceType.FILE);
160     assertNotNull(af, "Didn't read input file " + inFile);
161     af.loadJalviewDataFile(inAnnot, DataSourceType.FILE, null, null);
162     AlignViewport viewport = af.getViewport();
163     assertSame(viewport.getGlobalColourScheme().getClass(),
164             TCoffeeColourScheme.class, "Didn't set T-coffee colourscheme");
165     assertNotNull(
166             ColourSchemeProperty.getColourScheme(viewport,
167                     viewport.getAlignment(),
168                     viewport.getGlobalColourScheme()
169                             .getSchemeName()),
170             "Recognise T-Coffee score from string");
171
172     af.saveAlignment(tfile, FileFormat.Jalview);
173     assertTrue(af.isSaveAlignmentSuccessful(),
174             "Failed to store as a project.");
175     af.closeMenuItem_actionPerformed(true);
176     af = null;
177     af = new FileLoader().LoadFileWaitTillLoaded(tfile,
178             DataSourceType.FILE);
179     assertNotNull(af, "Failed to import new project");
180     assertSame(af.getViewport().getGlobalColourScheme().getClass(),
181             TCoffeeColourScheme.class,
182             "Didn't set T-coffee colourscheme for imported project.");
183     System.out.println(
184             "T-Coffee score shading successfully recovered from project.");
185   }
186
187   @Test(groups = { "Functional" })
188   public void testColourByAnnotScores() throws Exception
189   {
190     String inFile = "examples/uniref50.fa",
191             inAnnot = "examples/testdata/uniref50_iupred.jva";
192     String tfile = File.createTempFile("JalviewTest", ".jvp")
193             .getAbsolutePath();
194     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(inFile,
195             DataSourceType.FILE);
196     assertNotNull(af, "Didn't read input file " + inFile);
197     af.loadJalviewDataFile(inAnnot, DataSourceType.FILE, null, null);
198     AlignmentAnnotation[] aa = af.getViewport().getAlignment()
199             .getSequenceAt(0).getAnnotation("IUPredWS (Short)");
200     assertTrue(
201
202             aa != null && aa.length > 0,
203             "Didn't find any IUPred annotation to use to shade alignment.");
204     AnnotationColourGradient cs = new AnnotationColourGradient(aa[0], null,
205             AnnotationColourGradient.ABOVE_THRESHOLD);
206     AnnotationColourGradient gcs = new AnnotationColourGradient(aa[0], null,
207             AnnotationColourGradient.BELOW_THRESHOLD);
208     cs.setSeqAssociated(true);
209     gcs.setSeqAssociated(true);
210     af.changeColour(cs);
211     SequenceGroup sg = new SequenceGroup();
212     sg.setStartRes(57);
213     sg.setEndRes(92);
214     sg.cs.setColourScheme(gcs);
215     af.getViewport().getAlignment().addGroup(sg);
216     sg.addSequence(af.getViewport().getAlignment().getSequenceAt(1), false);
217     sg.addSequence(af.getViewport().getAlignment().getSequenceAt(2), true);
218     af.alignPanel.alignmentChanged();
219     af.saveAlignment(tfile, FileFormat.Jalview);
220     assertTrue(af.isSaveAlignmentSuccessful(),
221             "Failed to store as a project.");
222     af.closeMenuItem_actionPerformed(true);
223     af = null;
224     af = new FileLoader().LoadFileWaitTillLoaded(tfile,
225             DataSourceType.FILE);
226     assertNotNull(af, "Failed to import new project");
227
228     // check for group and alignment colourschemes
229
230     ColourSchemeI _rcs = af.getViewport().getGlobalColourScheme();
231     ColourSchemeI _rgcs = af.getViewport().getAlignment().getGroups().get(0)
232             .getColourScheme();
233     assertNotNull(_rcs, "Didn't recover global colourscheme");
234     assertTrue(_rcs instanceof AnnotationColourGradient,
235             "Didn't recover annotation colour global scheme");
236     AnnotationColourGradient __rcs = (AnnotationColourGradient) _rcs;
237     assertTrue(__rcs.isSeqAssociated(),
238             "Annotation colourscheme wasn't sequence associated");
239
240     boolean diffseqcols = false, diffgseqcols = false;
241     SequenceI[] sqs = af.getViewport().getAlignment().getSequencesArray();
242     for (int p = 0, pSize = af.getViewport().getAlignment()
243             .getWidth(); p < pSize && (!diffseqcols || !diffgseqcols); p++)
244     {
245       if (_rcs.findColour(sqs[0].getCharAt(p), p, sqs[0], null, 0f) != _rcs
246               .findColour(sqs[5].getCharAt(p), p, sqs[5], null, 0f))
247       {
248         diffseqcols = true;
249       }
250     }
251     assertTrue(diffseqcols, "Got Different sequence colours");
252     System.out.println(
253             "Per sequence colourscheme (Background) successfully applied and recovered.");
254
255     assertNotNull(_rgcs, "Didn't recover group colourscheme");
256     assertTrue(_rgcs instanceof AnnotationColourGradient,
257             "Didn't recover annotation colour group colourscheme");
258     __rcs = (AnnotationColourGradient) _rgcs;
259     assertTrue(__rcs.isSeqAssociated(),
260             "Group Annotation colourscheme wasn't sequence associated");
261
262     for (int p = 0, pSize = af.getViewport().getAlignment()
263             .getWidth(); p < pSize && (!diffseqcols || !diffgseqcols); p++)
264     {
265       if (_rgcs.findColour(sqs[1].getCharAt(p), p, sqs[1], null,
266               0f) != _rgcs.findColour(sqs[2].getCharAt(p), p, sqs[2], null,
267                       0f))
268       {
269         diffgseqcols = true;
270       }
271     }
272     assertTrue(diffgseqcols, "Got Different group sequence colours");
273     System.out.println(
274             "Per sequence (Group) colourscheme successfully applied and recovered.");
275   }
276
277   @Test(groups = { "Functional" })
278   public void gatherViewsHere() throws Exception
279   {
280     int origCount = Desktop.getAlignFrames() == null ? 0
281             : Desktop.getAlignFrames().length;
282     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(
283             "examples/exampleFile_2_7.jar", DataSourceType.FILE);
284     assertNotNull(af, "Didn't read in the example file correctly.");
285     assertEquals(Desktop.getAlignFrames().length,
286             1 + origCount,
287             "Didn't gather the views in the example file.");
288   }
289
290   /**
291    * Test for JAL-2223 - multiple mappings in View Mapping report
292    * 
293    * @throws Exception
294    */
295   @Test(groups = { "Functional" })
296   public void noDuplicatePdbMappingsMade() throws Exception
297   {
298     StructureImportSettings.setProcessSecondaryStructure(true);
299     StructureImportSettings.setVisibleChainAnnotation(true);
300     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(
301             "examples/exampleFile_2_7.jar", DataSourceType.FILE);
302     assertNotNull(af, "Didn't read in the example file correctly.");
303
304     // locate Jmol viewer
305     // count number of PDB mappings the structure selection manager holds -
306     String pdbFile = af.getCurrentView().getStructureSelectionManager()
307             .findFileForPDBId("1A70");
308     assertEquals(
309             af.getCurrentView().getStructureSelectionManager()
310                     .getMapping(pdbFile).length,
311             2, "Expected only two mappings for 1A70");
312
313   }
314
315   @Test(groups = { "Functional" })
316   public void viewRefPdbAnnotation() throws Exception
317   {
318     StructureImportSettings.setProcessSecondaryStructure(true);
319     StructureImportSettings.setVisibleChainAnnotation(true);
320     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(
321             "examples/exampleFile_2_7.jar", DataSourceType.FILE);
322     assertNotNull(af, "Didn't read in the example file correctly.");
323     AlignmentViewPanel sps = null;
324     for (AlignmentViewPanel ap : af.alignPanel.alignFrame.getAlignPanels())
325     {
326       if ("Spinach Feredoxin Structure".equals(ap.getViewName()))
327       {
328         sps = ap;
329         break;
330       }
331     }
332     assertNotNull(sps, "Couldn't find the structure view");
333     AlignmentAnnotation refan = null;
334     for (AlignmentAnnotation ra : sps.getAlignment()
335             .getAlignmentAnnotation())
336     {
337       if (ra.graph != 0)
338       {
339         refan = ra;
340         break;
341       }
342     }
343     assertNotNull(refan, "Annotation secondary structure not found.");
344     SequenceI sq = sps.getAlignment().findName("1A70|");
345     assertNotNull(sq, "Couldn't find 1a70 null chain");
346     // compare the manually added temperature factor annotation
347     // to the track automatically transferred from the pdb structure on load
348     assertNotNull(sq.getDatasetSequence().getAnnotation(),
349             "1a70 has no annotation");
350     for (AlignmentAnnotation ala : sq.getDatasetSequence().getAnnotation())
351     {
352       AlignmentAnnotation alaa;
353       sq.addAlignmentAnnotation(alaa = new AlignmentAnnotation(ala));
354       alaa.adjustForAlignment();
355       if (ala.graph == refan.graph)
356       {
357         for (int p = 0; p < ala.annotations.length; p++)
358         {
359           sq.findPosition(p);
360           try
361           {
362             assertTrue((alaa.annotations[p] == null
363                     && refan.annotations[p] == null)
364                     || alaa.annotations[p].value == refan.annotations[p].value,
365                     "Mismatch at alignment position " + p);
366           } catch (NullPointerException q)
367           {
368             Assert.fail("Mismatch of alignment annotations at position " + p
369                     + " Ref seq ann: " + refan.annotations[p]
370                     + " alignment " + alaa.annotations[p]);
371           }
372         }
373       }
374     }
375
376   }
377
378   @Test(groups = { "Functional" })
379   public void testCopyViewSettings() throws Exception
380   {
381     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(
382             "examples/exampleFile_2_7.jar", DataSourceType.FILE);
383     assertNotNull(af, "Didn't read in the example file correctly.");
384     AlignmentViewPanel sps = null, groups = null;
385     for (AlignmentViewPanel ap : af.alignPanel.alignFrame.getAlignPanels())
386     {
387       if ("Spinach Feredoxin Structure".equals(ap.getViewName()))
388       {
389         sps = ap;
390       }
391       if (ap.getViewName().contains("MAFFT"))
392       {
393         groups = ap;
394       }
395     }
396     assertNotNull(sps, "Couldn't find the structure view");
397     assertNotNull(groups, "Couldn't find the MAFFT view");
398
399     ViewStyleI structureStyle = sps.getAlignViewport().getViewStyle();
400     ViewStyleI groupStyle = groups.getAlignViewport().getViewStyle();
401     AssertJUnit.assertFalse(structureStyle.sameStyle(groupStyle));
402
403     groups.getAlignViewport().setViewStyle(structureStyle);
404     AssertJUnit.assertFalse(
405             groupStyle.sameStyle(groups.getAlignViewport().getViewStyle()));
406     Assert.assertTrue(structureStyle
407             .sameStyle(groups.getAlignViewport().getViewStyle()));
408
409   }
410
411   /**
412    * test store and recovery of expanded views
413    * 
414    * @throws Exception
415    */
416   @Test(groups = { "Functional" }, enabled = true)
417   public void testStoreAndRecoverExpandedviews() throws Exception
418   {
419     Desktop.getInstance().closeAll_actionPerformed(null);
420
421     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(
422             "examples/exampleFile_2_7.jar", DataSourceType.FILE);
423     Assert.assertEquals(Desktop.getAlignFrames().length, 1);
424     String afid = af.getViewport().getSequenceSetId();
425
426     // check FileLoader returned a reference to the one alignFrame that is
427     // actually on the Desktop
428     assertSame(af, Desktop.getAlignFrameFor(af.getViewport()),
429             "Jalview2XML.loadAlignFrame() didn't return correct AlignFrame reference for multiple view window");
430
431     Desktop.explodeViews(af);
432
433     int oldviews = Desktop.getAlignFrames().length;
434     Assert.assertEquals(Desktop.getAlignFrames().length,
435             Desktop.getAlignmentPanels(afid).length);
436     File tfile = File.createTempFile("testStoreAndRecoverExpanded", ".jvp");
437     try
438     {
439       new Jalview2XML(false).saveState(tfile);
440     } catch (Error e)
441     {
442       Assert.fail("Didn't save the expanded view state", e);
443     } catch (Exception e)
444     {
445       Assert.fail("Didn't save the expanded view state", e);
446     }
447     Desktop.getInstance().closeAll_actionPerformed(null);
448     if (Desktop.getAlignFrames() != null)
449     {
450       Assert.assertEquals(Desktop.getAlignFrames().length, 0);
451     }
452     af = new FileLoader().LoadFileWaitTillLoaded(tfile.getAbsolutePath(),
453             DataSourceType.FILE);
454     Assert.assertNotNull(af);
455     Assert.assertEquals(Desktop.getAlignFrames().length,
456             Desktop.getAlignmentPanels(
457                     af.getViewport().getSequenceSetId()).length);
458     Assert.assertEquals(
459             Desktop.getAlignmentPanels(
460                     af.getViewport().getSequenceSetId()).length,
461             oldviews);
462   }
463
464   /**
465    * Test save and reload of a project with a different representative sequence
466    * in each view.
467    * 
468    * @throws Exception
469    */
470   @Test(groups = { "Functional" })
471   public void testStoreAndRecoverReferenceSeqSettings() throws Exception
472   {
473     Desktop.getInstance().closeAll_actionPerformed(null);
474     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(
475             "examples/exampleFile_2_7.jar", DataSourceType.FILE);
476     assertNotNull(af, "Didn't read in the example file correctly.");
477     String afid = af.getViewport().getSequenceSetId();
478
479     // remember reference sequence for each panel
480     Map<String, SequenceI> refseqs = new HashMap<>();
481
482     /*
483      * mark sequence 2, 3, 4.. in panels 1, 2, 3...
484      * as reference sequence for itself and the preceding sequence
485      */
486     int n = 1;
487     for (AlignmentViewPanel ap : Desktop.getAlignmentPanels(afid))
488     {
489       AlignViewportI av = ap.getAlignViewport();
490       AlignmentI alignment = ap.getAlignment();
491       int repIndex = n % alignment.getHeight();
492       SequenceI rep = alignment.getSequenceAt(repIndex);
493       refseqs.put(ap.getViewName(), rep);
494
495       // code from mark/unmark sequence as reference in jalview.gui.PopupMenu
496       // todo refactor this to an alignment view controller
497       av.setDisplayReferenceSeq(true);
498       av.setColourByReferenceSeq(true);
499       av.getAlignment().setSeqrep(rep);
500
501       n++;
502     }
503     File tfile = File.createTempFile("testStoreAndRecoverReferenceSeq",
504             ".jvp");
505     try
506     {
507       new Jalview2XML(false).saveState(tfile);
508     } catch (Throwable e)
509     {
510       Assert.fail("Didn't save the expanded view state", e);
511     }
512     Desktop.getInstance().closeAll_actionPerformed(null);
513     if (Desktop.getAlignFrames() != null)
514     {
515       Assert.assertEquals(Desktop.getAlignFrames().length, 0);
516     }
517
518     af = new FileLoader().LoadFileWaitTillLoaded(tfile.getAbsolutePath(),
519             DataSourceType.FILE);
520     afid = af.getViewport().getSequenceSetId();
521
522     for (AlignmentViewPanel ap : Desktop.getAlignmentPanels(afid))
523     {
524       // check representative
525       AlignmentI alignment = ap.getAlignment();
526       SequenceI rep = alignment.getSeqrep();
527       Assert.assertNotNull(rep,
528               "Couldn't restore sequence representative from project");
529       // can't use a strong equals here, because by definition, the sequence IDs
530       // will be different.
531       // could set vamsas session save/restore flag to preserve IDs across
532       // load/saves.
533       Assert.assertEquals(refseqs.get(ap.getViewName()).toString(),
534               rep.toString(),
535               "Representative wasn't the same when recovered.");
536       Assert.assertTrue(ap.getAlignViewport().isDisplayReferenceSeq(),
537               "Display reference sequence view setting not set.");
538       Assert.assertTrue(ap.getAlignViewport().isColourByReferenceSeq(),
539               "Colour By Reference Seq view setting not set.");
540     }
541   }
542
543   @Test(groups = { "Functional" })
544   public void testIsVersionStringLaterThan()
545   {
546     /*
547      * No version / development / test / autobuild is leniently assumed to be
548      * compatible
549      */
550     assertTrue(Jalview2XML.isVersionStringLaterThan(null, null));
551     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3", null));
552     assertTrue(Jalview2XML.isVersionStringLaterThan(null, "2.8.3"));
553     assertTrue(Jalview2XML.isVersionStringLaterThan(null,
554             "Development Build"));
555     assertTrue(Jalview2XML.isVersionStringLaterThan(null,
556             "DEVELOPMENT BUILD"));
557     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3",
558             "Development Build"));
559     assertTrue(Jalview2XML.isVersionStringLaterThan(null, "Test"));
560     assertTrue(Jalview2XML.isVersionStringLaterThan(null, "TEST"));
561     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3", "Test"));
562     assertTrue(
563             Jalview2XML.isVersionStringLaterThan(null, "Automated Build"));
564     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3",
565             "Automated Build"));
566     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3",
567             "AUTOMATED BUILD"));
568
569     /*
570      * same version returns true i.e. compatible
571      */
572     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8", "2.8"));
573     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3", "2.8.3"));
574     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3b1", "2.8.3b1"));
575     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3B1", "2.8.3b1"));
576     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3b1", "2.8.3B1"));
577
578     /*
579      * later version returns true
580      */
581     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3", "2.8.4"));
582     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3", "2.9"));
583     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3", "2.9.2"));
584     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8", "2.8.3"));
585     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3", "2.8.3b1"));
586
587     /*
588      * earlier version returns false
589      */
590     assertFalse(Jalview2XML.isVersionStringLaterThan("2.8.3", "2.8"));
591     assertFalse(Jalview2XML.isVersionStringLaterThan("2.8.4", "2.8.3"));
592     assertFalse(Jalview2XML.isVersionStringLaterThan("2.8.3b1", "2.8.3"));
593     assertFalse(Jalview2XML.isVersionStringLaterThan("2.8.3", "2.8.2b1"));
594     assertFalse(Jalview2XML.isVersionStringLaterThan("2.8.0b2", "2.8.0b1"));
595   }
596
597   /**
598    * Test save and reload of a project with a different sequence group (and
599    * representative sequence) in each view.
600    * 
601    * @throws Exception
602    */
603   @Test(groups = { "Functional" })
604   public void testStoreAndRecoverGroupRepSeqs() throws Exception
605   {
606     Desktop.getInstance().closeAll_actionPerformed(null);
607     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(
608             "examples/uniref50.fa", DataSourceType.FILE);
609     assertNotNull(af, "Didn't read in the example file correctly.");
610     String afid = af.getViewport().getSequenceSetId();
611     // make a second view of the alignment
612     af.newView_actionPerformed(null);
613
614     /*
615      * remember representative and hidden sequences marked 
616      * on each panel
617      */
618     Map<String, SequenceI> repSeqs = new HashMap<>();
619     Map<String, List<String>> hiddenSeqNames = new HashMap<>();
620
621     /*
622      * mark sequence 2, 3, 4.. in panels 1, 2, 3...
623      * as reference sequence for itself and the preceding sequence
624      */
625     int n = 1;
626     for (AlignmentViewPanel ap : Desktop.getAlignmentPanels(afid))
627     {
628       AlignViewportI av = ap.getAlignViewport();
629       AlignmentI alignment = ap.getAlignment();
630       int repIndex = n % alignment.getHeight();
631       // ensure at least one preceding sequence i.e. index >= 1
632       repIndex = Math.max(repIndex, 1);
633       SequenceI repSeq = alignment.getSequenceAt(repIndex);
634       repSeqs.put(ap.getViewName(), repSeq);
635       List<String> hiddenNames = new ArrayList<>();
636       hiddenSeqNames.put(ap.getViewName(), hiddenNames);
637
638       /*
639        * have rep sequence represent itself and the one before it
640        * this hides the group (except for the rep seq)
641        */
642       SequenceGroup sg = new SequenceGroup();
643       sg.addSequence(repSeq, false);
644       SequenceI precedingSeq = alignment.getSequenceAt(repIndex - 1);
645       sg.addSequence(precedingSeq, false);
646       sg.setSeqrep(repSeq);
647       assertTrue(sg.getSequences().contains(repSeq));
648       assertTrue(sg.getSequences().contains(precedingSeq));
649       av.setSelectionGroup(sg);
650       assertSame(repSeq, sg.getSeqrep());
651
652       /*
653        * represent group with sequence adds to a map of hidden rep sequences
654        * (it does not create a group on the alignment) 
655        */
656       ((AlignmentViewport) av).hideSequences(repSeq, true);
657       assertSame(repSeq, sg.getSeqrep());
658       assertTrue(sg.getSequences().contains(repSeq));
659       assertTrue(sg.getSequences().contains(precedingSeq));
660       assertTrue(alignment.getGroups().isEmpty(), "alignment has groups");
661       Map<SequenceI, SequenceCollectionI> hiddenRepSeqsMap = av
662               .getHiddenRepSequences();
663       assertNotNull(hiddenRepSeqsMap);
664       assertEquals(1, hiddenRepSeqsMap.size());
665       assertSame(sg, hiddenRepSeqsMap.get(repSeq));
666       assertTrue(alignment.getHiddenSequences().isHidden(precedingSeq));
667       assertFalse(alignment.getHiddenSequences().isHidden(repSeq));
668       hiddenNames.add(precedingSeq.getName());
669
670       n++;
671     }
672     File tfile = File.createTempFile("testStoreAndRecoverGroupReps",
673             ".jvp");
674     try
675     {
676       new Jalview2XML(false).saveState(tfile);
677     } catch (Throwable e)
678     {
679       Assert.fail("Didn't save the expanded view state", e);
680     }
681     Desktop.getInstance().closeAll_actionPerformed(null);
682     if (Desktop.getAlignFrames() != null)
683     {
684       Assert.assertEquals(Desktop.getAlignFrames().length, 0);
685     }
686
687     af = new FileLoader().LoadFileWaitTillLoaded(tfile.getAbsolutePath(),
688             DataSourceType.FILE);
689     afid = af.getViewport().getSequenceSetId();
690
691     for (AlignmentViewPanel ap : Desktop.getAlignmentPanels(afid))
692     {
693       String viewName = ap.getViewName();
694       AlignViewportI av = ap.getAlignViewport();
695       AlignmentI alignment = ap.getAlignment();
696       List<SequenceGroup> groups = alignment.getGroups();
697       assertNotNull(groups);
698       assertTrue(groups.isEmpty(), "Alignment has groups");
699       Map<SequenceI, SequenceCollectionI> hiddenRepSeqsMap = av
700               .getHiddenRepSequences();
701       assertNotNull(hiddenRepSeqsMap, "No hidden represented sequences");
702       assertEquals(1, hiddenRepSeqsMap.size());
703       assertEquals(repSeqs.get(viewName).getDisplayId(true),
704               hiddenRepSeqsMap.keySet().iterator().next()
705                       .getDisplayId(true));
706
707       /*
708        * verify hidden sequences in restored panel
709        */
710       List<String> hidden = hiddenSeqNames.get(ap.getViewName());
711       HiddenSequences hs = alignment.getHiddenSequences();
712       assertEquals(hidden.size(), hs.getSize(),
713               "wrong number of restored hidden sequences in "
714                       + ap.getViewName());
715     }
716   }
717
718   /**
719    * Test save and reload of PDBEntry in Jalview project
720    * 
721    * @throws Exception
722    */
723   @Test(groups = { "Functional" })
724   public void testStoreAndRecoverPDBEntry() throws Exception
725   {
726     Desktop.getInstance().closeAll_actionPerformed(null);
727     String exampleFile = "examples/3W5V.pdb";
728     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(exampleFile,
729             DataSourceType.FILE);
730     assertNotNull(af, "Didn't read in the example file correctly.");
731     String afid = af.getViewport().getSequenceSetId();
732
733     AlignmentPanel[] alignPanels = Desktop.getAlignmentPanels(afid);
734     System.out.println();
735     AlignmentViewPanel ap = alignPanels[0];
736     String tfileBase = new File(".").getAbsolutePath().replace(".", "");
737     String testFile = tfileBase + exampleFile;
738     AlignmentI alignment = ap.getAlignment();
739     System.out.println("blah");
740     SequenceI[] seqs = alignment.getSequencesArray();
741     Assert.assertNotNull(seqs[0]);
742     Assert.assertNotNull(seqs[1]);
743     Assert.assertNotNull(seqs[2]);
744     Assert.assertNotNull(seqs[3]);
745     Assert.assertNotNull(seqs[0].getDatasetSequence());
746     Assert.assertNotNull(seqs[1].getDatasetSequence());
747     Assert.assertNotNull(seqs[2].getDatasetSequence());
748     Assert.assertNotNull(seqs[3].getDatasetSequence());
749     PDBEntry[] pdbEntries = new PDBEntry[4];
750     pdbEntries[0] = new PDBEntry("3W5V", "A", Type.PDB, testFile);
751     pdbEntries[1] = new PDBEntry("3W5V", "B", Type.PDB, testFile);
752     pdbEntries[2] = new PDBEntry("3W5V", "C", Type.PDB, testFile);
753     pdbEntries[3] = new PDBEntry("3W5V", "D", Type.PDB, testFile);
754     Assert.assertEquals(
755             seqs[0].getDatasetSequence().getAllPDBEntries().get(0),
756             pdbEntries[0]);
757     Assert.assertEquals(
758             seqs[1].getDatasetSequence().getAllPDBEntries().get(0),
759             pdbEntries[1]);
760     Assert.assertEquals(
761             seqs[2].getDatasetSequence().getAllPDBEntries().get(0),
762             pdbEntries[2]);
763     Assert.assertEquals(
764             seqs[3].getDatasetSequence().getAllPDBEntries().get(0),
765             pdbEntries[3]);
766
767     File tfile = File.createTempFile("testStoreAndRecoverPDBEntry", ".jvp");
768     try
769     {
770       new Jalview2XML(false).saveState(tfile);
771     } catch (Throwable e)
772     {
773       Assert.fail("Didn't save the state", e);
774     }
775     Desktop.getInstance().closeAll_actionPerformed(null);
776     if (Desktop.getAlignFrames() != null)
777     {
778       Assert.assertEquals(Desktop.getAlignFrames().length, 0);
779     }
780
781     AlignFrame restoredFrame = new FileLoader().LoadFileWaitTillLoaded(
782             tfile.getAbsolutePath(), DataSourceType.FILE);
783     String rfid = restoredFrame.getViewport().getSequenceSetId();
784     AlignmentPanel[] rAlignPanels = Desktop.getAlignmentPanels(rfid);
785     AlignmentViewPanel rap = rAlignPanels[0];
786     AlignmentI rAlignment = rap.getAlignment();
787     System.out.println("blah");
788     SequenceI[] rseqs = rAlignment.getSequencesArray();
789     Assert.assertNotNull(rseqs[0]);
790     Assert.assertNotNull(rseqs[1]);
791     Assert.assertNotNull(rseqs[2]);
792     Assert.assertNotNull(rseqs[3]);
793     Assert.assertNotNull(rseqs[0].getDatasetSequence());
794     Assert.assertNotNull(rseqs[1].getDatasetSequence());
795     Assert.assertNotNull(rseqs[2].getDatasetSequence());
796     Assert.assertNotNull(rseqs[3].getDatasetSequence());
797
798     // The Asserts below are expected to fail until the PDB chainCode is
799     // recoverable from a Jalview projects
800     for (int chain = 0; chain < 4; chain++)
801     {
802       PDBEntry recov = rseqs[chain].getDatasetSequence().getAllPDBEntries()
803               .get(0);
804       PDBEntry expected = pdbEntries[chain];
805       Assert.assertEquals(recov.getId(), expected.getId(),
806               "Mismatch PDB ID");
807       Assert.assertEquals(recov.getChainCode(), expected.getChainCode(),
808               "Mismatch PDB ID");
809       Assert.assertEquals(recov.getType(), expected.getType(),
810               "Mismatch PDBEntry 'Type'");
811       Assert.assertNotNull(recov.getFile(),
812               "Recovered PDBEntry should have a non-null file entry");
813     }
814   }
815
816   /**
817    * Configure an alignment and a sub-group each with distinct colour schemes,
818    * Conservation and PID thresholds, and confirm these are restored from the
819    * saved project.
820    * 
821    * @throws IOException
822    */
823   @Test(groups = { "Functional" })
824   public void testStoreAndRecoverColourThresholds() throws IOException
825   {
826     Desktop.getInstance().closeAll_actionPerformed(null);
827     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(
828             "examples/uniref50.fa", DataSourceType.FILE);
829
830     AlignViewport av = af.getViewport();
831     AlignmentI al = av.getAlignment();
832
833     /*
834      * Colour alignment by Buried Index, Above 10% PID, By Conservation 20%
835      */
836     av.setColourAppliesToAllGroups(false);
837     af.changeColour_actionPerformed(JalviewColourScheme.Buried.toString());
838     assertTrue(av.getGlobalColourScheme() instanceof BuriedColourScheme);
839     af.abovePIDThreshold_actionPerformed(true);
840     SliderPanel sp = SliderPanel.getSliderPanel();
841     assertFalse(sp.isForConservation());
842     sp.valueChanged(10);
843     af.conservationMenuItem_actionPerformed(true);
844     sp = SliderPanel.getSliderPanel();
845     assertTrue(sp.isForConservation());
846     sp.valueChanged(20);
847     ResidueShaderI rs = av.getResidueShading();
848     assertEquals(rs.getThreshold(), 10);
849     assertTrue(rs.conservationApplied());
850     assertEquals(rs.getConservationInc(), 20);
851
852     /*
853      * create a group with Strand colouring, 30% Conservation
854      * and 40% PID threshold
855      * (notice menu action applies to selection group even if mouse click
856      * is at a sequence not in the group)
857      */
858     SequenceGroup sg = new SequenceGroup();
859     sg.addSequence(al.getSequenceAt(0), false);
860     sg.setStartRes(15);
861     sg.setEndRes(25);
862     av.setSelectionGroup(sg);
863     PopupMenu popupMenu = new PopupMenu(af.alignPanel, al.getSequenceAt(2),
864             null);
865     popupMenu.changeColour_actionPerformed(
866             JalviewColourScheme.Strand.toString());
867     assertTrue(sg.getColourScheme() instanceof StrandColourScheme);
868     assertEquals(al.getGroups().size(), 1);
869     assertSame(al.getGroups().get(0), sg);
870     popupMenu.conservationMenuItem_actionPerformed(true);
871     sp = SliderPanel.getSliderPanel();
872     assertTrue(sp.isForConservation());
873     sp.valueChanged(30);
874     popupMenu.abovePIDColour_actionPerformed(true);
875     sp = SliderPanel.getSliderPanel();
876     assertFalse(sp.isForConservation());
877     sp.valueChanged(40);
878     assertTrue(sg.getGroupColourScheme().conservationApplied());
879     assertEquals(sg.getGroupColourScheme().getConservationInc(), 30);
880     assertEquals(sg.getGroupColourScheme().getThreshold(), 40);
881
882     /*
883      * save project, close windows, reload project, verify
884      */
885     File tfile = File.createTempFile("testStoreAndRecoverColourThresholds",
886             ".jvp");
887     tfile.deleteOnExit();
888     new Jalview2XML(false).saveState(tfile);
889     Desktop.getInstance().closeAll_actionPerformed(null);
890     af = new FileLoader().LoadFileWaitTillLoaded(tfile.getAbsolutePath(),
891             DataSourceType.FILE);
892     Assert.assertNotNull(af, "Failed to reload project");
893
894     /*
895      * verify alignment (background) colouring
896      */
897     rs = af.getViewport().getResidueShading();
898     assertTrue(rs.getColourScheme() instanceof BuriedColourScheme);
899     assertEquals(rs.getThreshold(), 10);
900     assertTrue(rs.conservationApplied());
901     assertEquals(rs.getConservationInc(), 20);
902
903     /*
904      * verify group colouring
905      */
906     assertEquals(1, af.getViewport().getAlignment().getGroups().size(), 1);
907     rs = af.getViewport().getAlignment().getGroups().get(0)
908             .getGroupColourScheme();
909     assertTrue(rs.getColourScheme() instanceof StrandColourScheme);
910     assertEquals(rs.getThreshold(), 40);
911     assertTrue(rs.conservationApplied());
912     assertEquals(rs.getConservationInc(), 30);
913   }
914
915   /**
916    * Test save and reload of feature colour schemes and filter settings
917    * 
918    * @throws IOException
919    */
920   @Test(groups = { "Functional" })
921   public void testSaveLoadFeatureColoursAndFilters() throws IOException
922   {
923     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(
924             ">Seq1\nACDEFGHIKLM", DataSourceType.PASTE);
925     SequenceI seq1 = af.getViewport().getAlignment().getSequenceAt(0);
926
927     /*
928      * add some features to the sequence
929      */
930     int score = 1;
931     addFeatures(seq1, "type1", score++);
932     addFeatures(seq1, "type2", score++);
933     addFeatures(seq1, "type3", score++);
934     addFeatures(seq1, "type4", score++);
935     addFeatures(seq1, "type5", score++);
936
937     /*
938      * set colour schemes for features
939      */
940     FeatureRendererModel fr = af.getFeatureRenderer();
941     fr.findAllFeatures(true);
942
943     // type1: red
944     fr.setColour("type1", new FeatureColour(Color.red));
945
946     // type2: by label
947     FeatureColourI byLabel = new FeatureColour();
948     byLabel.setColourByLabel(true);
949     fr.setColour("type2", byLabel);
950
951     // type3: by score above threshold
952     FeatureColourI byScore = new FeatureColour(null, Color.BLACK,
953             Color.BLUE, null, 1, 10);
954     byScore.setAboveThreshold(true);
955     byScore.setThreshold(2f);
956     fr.setColour("type3", byScore);
957
958     // type4: by attribute AF
959     FeatureColourI byAF = new FeatureColour();
960     byAF.setColourByLabel(true);
961     byAF.setAttributeName("AF");
962     fr.setColour("type4", byAF);
963
964     // type5: by attribute CSQ:PolyPhen below threshold
965     FeatureColourI byPolyPhen = new FeatureColour(null, Color.BLACK,
966             Color.BLUE, null, 1, 10);
967     byPolyPhen.setBelowThreshold(true);
968     byPolyPhen.setThreshold(3f);
969     byPolyPhen.setAttributeName("CSQ", "PolyPhen");
970     fr.setColour("type5", byPolyPhen);
971
972     /*
973      * set filters for feature types
974      */
975
976     // filter type1 features by (label contains "x")
977     FeatureMatcherSetI filterByX = new FeatureMatcherSet();
978     filterByX.and(FeatureMatcher.byLabel(Condition.Contains, "x"));
979     fr.setFeatureFilter("type1", filterByX);
980
981     // filter type2 features by (score <= 2.4 and score > 1.1)
982     FeatureMatcherSetI filterByScore = new FeatureMatcherSet();
983     filterByScore.and(FeatureMatcher.byScore(Condition.LE, "2.4"));
984     filterByScore.and(FeatureMatcher.byScore(Condition.GT, "1.1"));
985     fr.setFeatureFilter("type2", filterByScore);
986
987     // filter type3 features by (AF contains X OR CSQ:PolyPhen != 0)
988     FeatureMatcherSetI filterByXY = new FeatureMatcherSet();
989     filterByXY
990             .and(FeatureMatcher.byAttribute(Condition.Contains, "X", "AF"));
991     filterByXY.or(FeatureMatcher.byAttribute(Condition.NE, "0", "CSQ",
992             "PolyPhen"));
993     fr.setFeatureFilter("type3", filterByXY);
994
995     /*
996      * save as Jalview project
997      */
998     File tfile = File.createTempFile("JalviewTest", ".jvp");
999     tfile.deleteOnExit();
1000     String filePath = tfile.getAbsolutePath();
1001     af.saveAlignment(filePath, FileFormat.Jalview);
1002     assertTrue(af.isSaveAlignmentSuccessful(),
1003             "Failed to store as a project.");
1004
1005     /*
1006      * close current alignment and load the saved project
1007      */
1008     af.closeMenuItem_actionPerformed(true);
1009     af = null;
1010     af = new FileLoader().LoadFileWaitTillLoaded(filePath,
1011             DataSourceType.FILE);
1012     assertNotNull(af, "Failed to import new project");
1013
1014     /*
1015      * verify restored feature colour schemes and filters
1016      */
1017     fr = af.getFeatureRenderer();
1018     FeatureColourI fc = fr.getFeatureStyle("type1");
1019     assertTrue(fc.isSimpleColour());
1020     assertEquals(fc.getColour(), Color.red);
1021     fc = fr.getFeatureStyle("type2");
1022     assertTrue(fc.isColourByLabel());
1023     fc = fr.getFeatureStyle("type3");
1024     assertTrue(fc.isGraduatedColour());
1025     assertNull(fc.getAttributeName());
1026     assertTrue(fc.isAboveThreshold());
1027     assertEquals(fc.getThreshold(), 2f);
1028     fc = fr.getFeatureStyle("type4");
1029     assertTrue(fc.isColourByLabel());
1030     assertTrue(fc.isColourByAttribute());
1031     assertEquals(fc.getAttributeName(), new String[] { "AF" });
1032     fc = fr.getFeatureStyle("type5");
1033     assertTrue(fc.isGraduatedColour());
1034     assertTrue(fc.isColourByAttribute());
1035     assertEquals(fc.getAttributeName(), new String[] { "CSQ", "PolyPhen" });
1036     assertTrue(fc.isBelowThreshold());
1037     assertEquals(fc.getThreshold(), 3f);
1038
1039     assertEquals(fr.getFeatureFilter("type1").toStableString(),
1040             "Label Contains x");
1041     assertEquals(fr.getFeatureFilter("type2").toStableString(),
1042             "(Score LE 2.4) AND (Score GT 1.1)");
1043     assertEquals(fr.getFeatureFilter("type3").toStableString(),
1044             "(AF Contains X) OR (CSQ:PolyPhen NE 0)");
1045   }
1046
1047   private void addFeature(SequenceI seq, String featureType, int score)
1048   {
1049     SequenceFeature sf = new SequenceFeature(featureType, "desc", 1, 2,
1050             score, "grp");
1051     sf.setValue("AF", score);
1052     sf.setValue("CSQ", new HashMap<String, String>()
1053     {
1054       {
1055         put("PolyPhen", Integer.toString(score));
1056       }
1057     });
1058     seq.addSequenceFeature(sf);
1059   }
1060
1061   /**
1062    * Adds two features of the given type to the given sequence, also setting the
1063    * score as the value of attribute "AF" and sub-attribute "CSQ:PolyPhen"
1064    * 
1065    * @param seq
1066    * @param featureType
1067    * @param score
1068    */
1069   private void addFeatures(SequenceI seq, String featureType, int score)
1070   {
1071     addFeature(seq, featureType, score++);
1072     addFeature(seq, featureType, score);
1073   }
1074
1075   /**
1076    * pre 2.11 - jalview 2.10 erroneously created new dataset entries for each
1077    * view (JAL-3171) this test ensures we can import and merge those views
1078    */
1079   @Test(groups = { "Functional" })
1080   public void testMergeDatasetsforViews() throws IOException
1081   {
1082     // simple project - two views on one alignment
1083     AlignFrame af = new FileLoader(false).LoadFileWaitTillLoaded(
1084             "examples/testdata/projects/twoViews.jvp", DataSourceType.FILE);
1085     assertNotNull(af);
1086     assertTrue(af.getAlignPanels().size() > 1);
1087     verifyDs(af);
1088   }
1089
1090   /**
1091    * pre 2.11 - jalview 2.10 erroneously created new dataset entries for each
1092    * view (JAL-3171) this test ensures we can import and merge those views This
1093    * is a more complex project
1094    */
1095   @Test(groups = { "Functional" })
1096   public void testMergeDatasetsforManyViews() throws IOException
1097   {
1098     Desktop.getInstance().closeAll_actionPerformed(null);
1099
1100     // complex project - one dataset, several views on several alignments
1101     AlignFrame af = new FileLoader(false).LoadFileWaitTillLoaded(
1102             "examples/testdata/projects/manyViews.jvp",
1103             DataSourceType.FILE);
1104     assertNotNull(af);
1105
1106     AlignmentI ds = null;
1107     for (AlignFrame alignFrame : Desktop.getAlignFrames())
1108     {
1109       if (ds == null)
1110       {
1111         ds = verifyDs(alignFrame);
1112       }
1113       else
1114       {
1115         // check that this frame's dataset matches the last
1116         assertTrue(ds == verifyDs(alignFrame));
1117       }
1118     }
1119   }
1120
1121   private AlignmentI verifyDs(AlignFrame af)
1122   {
1123     AlignmentI ds = null;
1124     for (AlignmentViewPanel ap : af.getAlignPanels())
1125     {
1126       if (ds == null)
1127       {
1128         ds = ap.getAlignment().getDataset();
1129       }
1130       else
1131       {
1132         assertTrue(ap.getAlignment().getDataset() == ds,
1133                 "Dataset was not the same for imported 2.10.5 project with several alignment views");
1134       }
1135     }
1136     return ds;
1137   }
1138
1139   @Test(groups = "Functional")
1140   public void testPcaViewAssociation() throws IOException
1141   {
1142     Desktop.getInstance().closeAll_actionPerformed(null);
1143     final String PCAVIEWNAME = "With PCA";
1144     // create a new tempfile
1145     File tempfile = File.createTempFile("jvPCAviewAssoc", "jvp");
1146
1147     {
1148       String exampleFile = "examples/uniref50.fa";
1149       AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(exampleFile,
1150               DataSourceType.FILE);
1151       assertNotNull(af, "Didn't read in the example file correctly.");
1152       AlignmentPanel origView = (AlignmentPanel) af.getAlignPanels().get(0);
1153       AlignmentPanel newview = af.newView(PCAVIEWNAME, true);
1154       // create another for good measure
1155       af.newView("Not the PCA View", true);
1156       PCAPanel pcaPanel = new PCAPanel(origView, "BLOSUM62",
1157               new SimilarityParams(true, true, true, false));
1158       // we're in the test exec thread, so we can just run synchronously here
1159       pcaPanel.run();
1160
1161       // now switch the linked view
1162       pcaPanel.selectAssociatedView(newview);
1163
1164       assertTrue(pcaPanel.getAlignViewport() == newview.getAlignViewport(),
1165               "PCA should be associated with 'With PCA' view: test is broken");
1166
1167       // now save and reload project
1168       Jalview2XML jv2xml = new jalview.project.Jalview2XML(false);
1169       tempfile.delete();
1170       jv2xml.saveState(tempfile);
1171       assertTrue(jv2xml.errorMessage == null,
1172               "Failed to save dummy project with PCA: test broken");
1173     }
1174
1175     // load again.
1176     Desktop.getInstance().closeAll_actionPerformed(null);
1177     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(
1178             tempfile.getCanonicalPath(), DataSourceType.FILE);
1179     JInternalFrame[] frames = Desktop.getInstance().getAllFrames();
1180     // PCA and the tabbed alignment view should be the only two windows on the
1181     // desktop
1182     assertEquals(frames.length, 2,
1183             "PCA and the tabbed alignment view should be the only two windows on the desktop");
1184     PCAPanel pcaPanel = (PCAPanel) frames[frames[0] == af ? 1 : 0];
1185
1186     AlignmentViewPanel restoredNewView = null;
1187     for (AlignmentViewPanel alignpanel : Desktop.getAlignmentPanels(null))
1188     {
1189       if (alignpanel.getAlignViewport() == pcaPanel.getAlignViewport())
1190       {
1191         restoredNewView = alignpanel;
1192       }
1193     }
1194     assertEquals(restoredNewView.getViewName(), PCAVIEWNAME);
1195     assertTrue(
1196             restoredNewView.getAlignViewport() == pcaPanel
1197                     .getAlignViewport(),
1198             "Didn't restore correct view association for the PCA view");
1199   }
1200
1201   /**
1202    * Test save and reload of DBRefEntry including GeneLocus in project
1203    * 
1204    * @throws Exception
1205    */
1206   @Test(groups = { "Functional" })
1207   public void testStoreAndRecoverGeneLocus() throws Exception
1208   {
1209     Desktop.getInstance().closeAll_actionPerformed(null);
1210     String seqData = ">P30419\nACDE\n>X1235\nGCCTGTGACGAA";
1211     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(seqData,
1212             DataSourceType.PASTE);
1213     assertNotNull(af, "Didn't read in the example file correctly.");
1214   
1215     AlignmentViewPanel ap = Desktop.getAlignmentPanels(null)[0];
1216     SequenceI pep = ap.getAlignment().getSequenceAt(0);
1217     SequenceI cds = ap.getAlignment().getSequenceAt(1);
1218
1219     /*
1220      * give 'protein' a dbref to self, a dbref with map to CDS,
1221      * and a dbref with map to gene 'locus'
1222      */
1223     DBRefEntry dbref1 = new DBRefEntry("Uniprot", "1", "P30419", null);
1224     pep.addDBRef(dbref1);
1225     Mapping cdsmap = new Mapping(cds,
1226             new MapList(new int[]
1227             { 1, 4 }, new int[] { 1, 12 }, 1, 3));
1228     DBRefEntry dbref2 = new DBRefEntry("EMBLCDS", "2", "X1235", cdsmap);
1229     pep.addDBRef(dbref2);
1230     Mapping locusmap = new Mapping(null,
1231             new MapList(new int[]
1232             { 1, 4 }, new int[] { 2674123, 2674135 }, 1, 3));
1233     DBRefEntry dbref3 = new GeneLocus("human", "GRCh38", "5", locusmap);
1234     pep.addDBRef(dbref3);
1235
1236     File tfile = File.createTempFile("testStoreAndRecoverGeneLocus",
1237             ".jvp");
1238     try
1239     {
1240       new Jalview2XML(false).saveState(tfile);
1241     } catch (Throwable e)
1242     {
1243       Assert.fail("Didn't save the state", e);
1244     }
1245     Desktop.getInstance().closeAll_actionPerformed(null);
1246   
1247     new FileLoader().LoadFileWaitTillLoaded(tfile.getAbsolutePath(),
1248             DataSourceType.FILE);
1249     AlignmentViewPanel rap = Desktop.getAlignmentPanels(null)[0];
1250     SequenceI rpep = rap.getAlignment().getSequenceAt(0);
1251     DBModList<DBRefEntry> dbrefs = rpep.getDBRefs();
1252     assertEquals(rpep.getName(), "P30419");
1253     assertEquals(dbrefs.size(), 3);
1254     DBRefEntry dbRef = dbrefs.get(0);
1255     assertFalse(dbRef instanceof GeneLocus);
1256     assertNull(dbRef.getMap());
1257     assertEquals(dbRef, dbref1);
1258
1259     /*
1260      * restored dbrefs with mapping have a different 'map to'
1261      * sequence but otherwise match the original dbrefs
1262      */
1263     dbRef = dbrefs.get(1);
1264     assertFalse(dbRef instanceof GeneLocus);
1265     assertTrue(dbRef.equalRef(dbref2));
1266     assertNotNull(dbRef.getMap());
1267     SequenceI rcds = rap.getAlignment().getSequenceAt(1);
1268     assertSame(dbRef.getMap().getTo(), rcds);
1269     // compare MapList but not map.to
1270     assertEquals(dbRef.getMap().getMap(), dbref2.getMap().getMap());
1271
1272     /*
1273      * GeneLocus map.to is null so can compare Mapping objects
1274      */
1275     dbRef = dbrefs.get(2);
1276     assertTrue(dbRef instanceof GeneLocus);
1277     assertEquals(dbRef, dbref3);
1278   }
1279 }