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