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