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