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