Merge branch 'documentation/JAL-3407_2.11.1_release' into develop
[jalview.git] / test / jalview / project / Jalview2xmlTests.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
7  * Jalview is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License 
9  * as published by the Free Software Foundation, either version 3
10  * of the License, or (at your option) any later version.
11  *  
12  * Jalview is distributed in the hope that it will be useful, but 
13  * WITHOUT ANY WARRANTY; without even the implied warranty 
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
15  * PURPOSE.  See the GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21 package jalview.project;
22
23 import static org.testng.Assert.assertEquals;
24 import static org.testng.Assert.assertFalse;
25 import static org.testng.Assert.assertNotNull;
26 import static org.testng.Assert.assertNull;
27 import static org.testng.Assert.assertSame;
28 import static org.testng.Assert.assertTrue;
29
30 import java.awt.Color;
31 import java.io.File;
32 import java.io.IOException;
33 import java.util.ArrayList;
34 import java.util.HashMap;
35 import java.util.List;
36 import java.util.Map;
37
38 import javax.swing.JInternalFrame;
39
40 import org.testng.Assert;
41 import org.testng.AssertJUnit;
42 import org.testng.annotations.BeforeClass;
43 import org.testng.annotations.Test;
44
45 import jalview.analysis.scoremodels.SimilarityParams;
46 import jalview.api.AlignViewportI;
47 import jalview.api.AlignmentViewPanel;
48 import jalview.api.FeatureColourI;
49 import jalview.api.ViewStyleI;
50 import jalview.datamodel.AlignmentAnnotation;
51 import jalview.datamodel.AlignmentI;
52 import jalview.datamodel.DBRefEntry;
53 import jalview.datamodel.GeneLocus;
54 import jalview.datamodel.HiddenSequences;
55 import jalview.datamodel.Mapping;
56 import jalview.datamodel.PDBEntry;
57 import jalview.datamodel.PDBEntry.Type;
58 import jalview.datamodel.SequenceCollectionI;
59 import jalview.datamodel.SequenceFeature;
60 import jalview.datamodel.SequenceGroup;
61 import jalview.datamodel.SequenceI;
62 import jalview.datamodel.features.FeatureMatcher;
63 import jalview.datamodel.features.FeatureMatcherSet;
64 import jalview.datamodel.features.FeatureMatcherSetI;
65 import jalview.gui.AlignFrame;
66 import jalview.gui.AlignViewport;
67 import jalview.gui.AlignmentPanel;
68 import jalview.gui.Desktop;
69 import jalview.gui.JvOptionPane;
70 import jalview.gui.PCAPanel;
71 import jalview.gui.PopupMenu;
72 import jalview.gui.SliderPanel;
73 import jalview.io.DataSourceType;
74 import jalview.io.FileFormat;
75 import jalview.io.FileLoader;
76 import jalview.io.Jalview2xmlBase;
77 import jalview.renderer.ResidueShaderI;
78 import jalview.schemes.AnnotationColourGradient;
79 import jalview.schemes.BuriedColourScheme;
80 import jalview.schemes.ColourSchemeI;
81 import jalview.schemes.ColourSchemeProperty;
82 import jalview.schemes.FeatureColour;
83 import jalview.schemes.JalviewColourScheme;
84 import jalview.schemes.RNAHelicesColour;
85 import jalview.schemes.StrandColourScheme;
86 import jalview.schemes.TCoffeeColourScheme;
87 import jalview.structure.StructureImportSettings;
88 import jalview.util.MapList;
89 import jalview.util.matcher.Condition;
90 import jalview.viewmodel.AlignmentViewport;
91 import jalview.viewmodel.seqfeatures.FeatureRendererModel;
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      * (notice menu action applies to selection group even if mouse click
846      * is at a sequence not in the group)
847      */
848     SequenceGroup sg = new SequenceGroup();
849     sg.addSequence(al.getSequenceAt(0), false);
850     sg.setStartRes(15);
851     sg.setEndRes(25);
852     av.setSelectionGroup(sg);
853     PopupMenu popupMenu = new PopupMenu(af.alignPanel, al.getSequenceAt(2),
854             null);
855     popupMenu.changeColour_actionPerformed(
856             JalviewColourScheme.Strand.toString());
857     assertTrue(sg.getColourScheme() instanceof StrandColourScheme);
858     assertEquals(al.getGroups().size(), 1);
859     assertSame(al.getGroups().get(0), sg);
860     popupMenu.conservationMenuItem_actionPerformed(true);
861     sp = SliderPanel.getSliderPanel();
862     assertTrue(sp.isForConservation());
863     sp.valueChanged(30);
864     popupMenu.abovePIDColour_actionPerformed(true);
865     sp = SliderPanel.getSliderPanel();
866     assertFalse(sp.isForConservation());
867     sp.valueChanged(40);
868     assertTrue(sg.getGroupColourScheme().conservationApplied());
869     assertEquals(sg.getGroupColourScheme().getConservationInc(), 30);
870     assertEquals(sg.getGroupColourScheme().getThreshold(), 40);
871
872     /*
873      * save project, close windows, reload project, verify
874      */
875     File tfile = File.createTempFile("testStoreAndRecoverColourThresholds",
876             ".jvp");
877     tfile.deleteOnExit();
878     new Jalview2XML(false).saveState(tfile);
879     Desktop.instance.closeAll_actionPerformed(null);
880     af = new FileLoader().LoadFileWaitTillLoaded(tfile.getAbsolutePath(),
881             DataSourceType.FILE);
882     Assert.assertNotNull(af, "Failed to reload project");
883
884     /*
885      * verify alignment (background) colouring
886      */
887     rs = af.getViewport().getResidueShading();
888     assertTrue(rs.getColourScheme() instanceof BuriedColourScheme);
889     assertEquals(rs.getThreshold(), 10);
890     assertTrue(rs.conservationApplied());
891     assertEquals(rs.getConservationInc(), 20);
892
893     /*
894      * verify group colouring
895      */
896     assertEquals(1, af.getViewport().getAlignment().getGroups().size(), 1);
897     rs = af.getViewport().getAlignment().getGroups().get(0)
898             .getGroupColourScheme();
899     assertTrue(rs.getColourScheme() instanceof StrandColourScheme);
900     assertEquals(rs.getThreshold(), 40);
901     assertTrue(rs.conservationApplied());
902     assertEquals(rs.getConservationInc(), 30);
903   }
904
905   /**
906    * Test save and reload of feature colour schemes and filter settings
907    * 
908    * @throws IOException
909    */
910   @Test(groups = { "Functional" })
911   public void testSaveLoadFeatureColoursAndFilters() throws IOException
912   {
913     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(
914             ">Seq1\nACDEFGHIKLM", DataSourceType.PASTE);
915     SequenceI seq1 = af.getViewport().getAlignment().getSequenceAt(0);
916
917     /*
918      * add some features to the sequence
919      */
920     int score = 1;
921     addFeatures(seq1, "type1", score++);
922     addFeatures(seq1, "type2", score++);
923     addFeatures(seq1, "type3", score++);
924     addFeatures(seq1, "type4", score++);
925     addFeatures(seq1, "type5", score++);
926
927     /*
928      * set colour schemes for features
929      */
930     FeatureRendererModel fr = af.getFeatureRenderer();
931     fr.findAllFeatures(true);
932
933     // type1: red
934     fr.setColour("type1", new FeatureColour(Color.red));
935
936     // type2: by label
937     FeatureColourI byLabel = new FeatureColour();
938     byLabel.setColourByLabel(true);
939     fr.setColour("type2", byLabel);
940
941     // type3: by score above threshold
942     FeatureColourI byScore = new FeatureColour(null, Color.BLACK,
943             Color.BLUE, null, 1, 10);
944     byScore.setAboveThreshold(true);
945     byScore.setThreshold(2f);
946     fr.setColour("type3", byScore);
947
948     // type4: by attribute AF
949     FeatureColourI byAF = new FeatureColour();
950     byAF.setColourByLabel(true);
951     byAF.setAttributeName("AF");
952     fr.setColour("type4", byAF);
953
954     // type5: by attribute CSQ:PolyPhen below threshold
955     FeatureColourI byPolyPhen = new FeatureColour(null, Color.BLACK,
956             Color.BLUE, null, 1, 10);
957     byPolyPhen.setBelowThreshold(true);
958     byPolyPhen.setThreshold(3f);
959     byPolyPhen.setAttributeName("CSQ", "PolyPhen");
960     fr.setColour("type5", byPolyPhen);
961
962     /*
963      * set filters for feature types
964      */
965
966     // filter type1 features by (label contains "x")
967     FeatureMatcherSetI filterByX = new FeatureMatcherSet();
968     filterByX.and(FeatureMatcher.byLabel(Condition.Contains, "x"));
969     fr.setFeatureFilter("type1", filterByX);
970
971     // filter type2 features by (score <= 2.4 and score > 1.1)
972     FeatureMatcherSetI filterByScore = new FeatureMatcherSet();
973     filterByScore.and(FeatureMatcher.byScore(Condition.LE, "2.4"));
974     filterByScore.and(FeatureMatcher.byScore(Condition.GT, "1.1"));
975     fr.setFeatureFilter("type2", filterByScore);
976
977     // filter type3 features by (AF contains X OR CSQ:PolyPhen != 0)
978     FeatureMatcherSetI filterByXY = new FeatureMatcherSet();
979     filterByXY
980             .and(FeatureMatcher.byAttribute(Condition.Contains, "X", "AF"));
981     filterByXY.or(FeatureMatcher.byAttribute(Condition.NE, "0", "CSQ",
982             "PolyPhen"));
983     fr.setFeatureFilter("type3", filterByXY);
984
985     /*
986      * save as Jalview project
987      */
988     File tfile = File.createTempFile("JalviewTest", ".jvp");
989     tfile.deleteOnExit();
990     String filePath = tfile.getAbsolutePath();
991     assertTrue(af.saveAlignment(filePath, FileFormat.Jalview),
992             "Failed to store as a project.");
993
994     /*
995      * close current alignment and load the saved project
996      */
997     af.closeMenuItem_actionPerformed(true);
998     af = null;
999     af = new FileLoader().LoadFileWaitTillLoaded(filePath,
1000             DataSourceType.FILE);
1001     assertNotNull(af, "Failed to import new project");
1002
1003     /*
1004      * verify restored feature colour schemes and filters
1005      */
1006     fr = af.getFeatureRenderer();
1007     FeatureColourI fc = fr.getFeatureStyle("type1");
1008     assertTrue(fc.isSimpleColour());
1009     assertEquals(fc.getColour(), Color.red);
1010     fc = fr.getFeatureStyle("type2");
1011     assertTrue(fc.isColourByLabel());
1012     fc = fr.getFeatureStyle("type3");
1013     assertTrue(fc.isGraduatedColour());
1014     assertNull(fc.getAttributeName());
1015     assertTrue(fc.isAboveThreshold());
1016     assertEquals(fc.getThreshold(), 2f);
1017     fc = fr.getFeatureStyle("type4");
1018     assertTrue(fc.isColourByLabel());
1019     assertTrue(fc.isColourByAttribute());
1020     assertEquals(fc.getAttributeName(), new String[] { "AF" });
1021     fc = fr.getFeatureStyle("type5");
1022     assertTrue(fc.isGraduatedColour());
1023     assertTrue(fc.isColourByAttribute());
1024     assertEquals(fc.getAttributeName(), new String[] { "CSQ", "PolyPhen" });
1025     assertTrue(fc.isBelowThreshold());
1026     assertEquals(fc.getThreshold(), 3f);
1027
1028     assertEquals(fr.getFeatureFilter("type1").toStableString(),
1029             "Label Contains x");
1030     assertEquals(fr.getFeatureFilter("type2").toStableString(),
1031             "(Score LE 2.4) AND (Score GT 1.1)");
1032     assertEquals(fr.getFeatureFilter("type3").toStableString(),
1033             "(AF Contains X) OR (CSQ:PolyPhen NE 0)");
1034   }
1035
1036   private void addFeature(SequenceI seq, String featureType, int score)
1037   {
1038     SequenceFeature sf = new SequenceFeature(featureType, "desc", 1, 2,
1039             score, "grp");
1040     sf.setValue("AF", score);
1041     sf.setValue("CSQ", new HashMap<String, String>()
1042     {
1043       {
1044         put("PolyPhen", Integer.toString(score));
1045       }
1046     });
1047     seq.addSequenceFeature(sf);
1048   }
1049
1050   /**
1051    * Adds two features of the given type to the given sequence, also setting the
1052    * score as the value of attribute "AF" and sub-attribute "CSQ:PolyPhen"
1053    * 
1054    * @param seq
1055    * @param featureType
1056    * @param score
1057    */
1058   private void addFeatures(SequenceI seq, String featureType, int score)
1059   {
1060     addFeature(seq, featureType, score++);
1061     addFeature(seq, featureType, score);
1062   }
1063
1064   /**
1065    * pre 2.11 - jalview 2.10 erroneously created new dataset entries for each
1066    * view (JAL-3171) this test ensures we can import and merge those views
1067    */
1068   @Test(groups = { "Functional" })
1069   public void testMergeDatasetsforViews() throws IOException
1070   {
1071     // simple project - two views on one alignment
1072     AlignFrame af = new FileLoader(false).LoadFileWaitTillLoaded(
1073             "examples/testdata/projects/twoViews.jvp", DataSourceType.FILE);
1074     assertNotNull(af);
1075     assertTrue(af.getAlignPanels().size() > 1);
1076     verifyDs(af);
1077   }
1078
1079   /**
1080    * pre 2.11 - jalview 2.10 erroneously created new dataset entries for each
1081    * view (JAL-3171) this test ensures we can import and merge those views This
1082    * is a more complex project
1083    */
1084   @Test(groups = { "Functional" })
1085   public void testMergeDatasetsforManyViews() throws IOException
1086   {
1087     Desktop.instance.closeAll_actionPerformed(null);
1088
1089     // complex project - one dataset, several views on several alignments
1090     AlignFrame af = new FileLoader(false).LoadFileWaitTillLoaded(
1091             "examples/testdata/projects/manyViews.jvp",
1092             DataSourceType.FILE);
1093     assertNotNull(af);
1094
1095     AlignmentI ds = null;
1096     for (AlignFrame alignFrame : Desktop.getAlignFrames())
1097     {
1098       if (ds == null)
1099       {
1100         ds = verifyDs(alignFrame);
1101       }
1102       else
1103       {
1104         // check that this frame's dataset matches the last
1105         assertTrue(ds == verifyDs(alignFrame));
1106       }
1107     }
1108   }
1109
1110   private AlignmentI verifyDs(AlignFrame af)
1111   {
1112     AlignmentI ds = null;
1113     for (AlignmentViewPanel ap : af.getAlignPanels())
1114     {
1115       if (ds == null)
1116       {
1117         ds = ap.getAlignment().getDataset();
1118       }
1119       else
1120       {
1121         assertTrue(ap.getAlignment().getDataset() == ds,
1122                 "Dataset was not the same for imported 2.10.5 project with several alignment views");
1123       }
1124     }
1125     return ds;
1126   }
1127
1128   @Test(groups = "Functional")
1129   public void testPcaViewAssociation() throws IOException
1130   {
1131     Desktop.instance.closeAll_actionPerformed(null);
1132     final String PCAVIEWNAME = "With PCA";
1133     // create a new tempfile
1134     File tempfile = File.createTempFile("jvPCAviewAssoc", "jvp");
1135
1136     {
1137       String exampleFile = "examples/uniref50.fa";
1138       AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(exampleFile,
1139               DataSourceType.FILE);
1140       assertNotNull(af, "Didn't read in the example file correctly.");
1141       AlignmentPanel origView = (AlignmentPanel) af.getAlignPanels().get(0);
1142       AlignmentPanel newview = af.newView(PCAVIEWNAME, true);
1143       // create another for good measure
1144       af.newView("Not the PCA View", true);
1145       PCAPanel pcaPanel = new PCAPanel(origView, "BLOSUM62",
1146               new SimilarityParams(true, true, true, false));
1147       // we're in the test exec thread, so we can just run synchronously here
1148       pcaPanel.run();
1149
1150       // now switch the linked view
1151       pcaPanel.selectAssociatedView(newview);
1152
1153       assertTrue(pcaPanel.getAlignViewport() == newview.getAlignViewport(),
1154               "PCA should be associated with 'With PCA' view: test is broken");
1155
1156       // now save and reload project
1157       Jalview2XML jv2xml = new jalview.project.Jalview2XML(false);
1158       tempfile.delete();
1159       jv2xml.saveState(tempfile);
1160       assertTrue(jv2xml.errorMessage == null,
1161               "Failed to save dummy project with PCA: test broken");
1162     }
1163
1164     // load again.
1165     Desktop.instance.closeAll_actionPerformed(null);
1166     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(
1167             tempfile.getCanonicalPath(), DataSourceType.FILE);
1168     JInternalFrame[] frames = Desktop.instance.getAllFrames();
1169     // PCA and the tabbed alignment view should be the only two windows on the
1170     // desktop
1171     assertEquals(frames.length, 2,
1172             "PCA and the tabbed alignment view should be the only two windows on the desktop");
1173     PCAPanel pcaPanel = (PCAPanel) frames[frames[0] == af ? 1 : 0];
1174
1175     AlignmentViewPanel restoredNewView = null;
1176     for (AlignmentViewPanel alignpanel : Desktop.getAlignmentPanels(null))
1177     {
1178       if (alignpanel.getAlignViewport() == pcaPanel.getAlignViewport())
1179       {
1180         restoredNewView = alignpanel;
1181       }
1182     }
1183     assertEquals(restoredNewView.getViewName(), PCAVIEWNAME);
1184     assertTrue(
1185             restoredNewView.getAlignViewport() == pcaPanel
1186                     .getAlignViewport(),
1187             "Didn't restore correct view association for the PCA view");
1188   }
1189
1190   /**
1191    * Test save and reload of DBRefEntry including GeneLocus in project
1192    * 
1193    * @throws Exception
1194    */
1195   @Test(groups = { "Functional" })
1196   public void testStoreAndRecoverGeneLocus() throws Exception
1197   {
1198     Desktop.instance.closeAll_actionPerformed(null);
1199     String seqData = ">P30419\nACDE\n>X1235\nGCCTGTGACGAA";
1200     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(seqData,
1201             DataSourceType.PASTE);
1202     assertNotNull(af, "Didn't read in the example file correctly.");
1203   
1204     AlignmentViewPanel ap = Desktop.getAlignmentPanels(null)[0];
1205     SequenceI pep = ap.getAlignment().getSequenceAt(0);
1206     SequenceI cds = ap.getAlignment().getSequenceAt(1);
1207
1208     /*
1209      * give 'protein' a dbref to self, a dbref with map to CDS,
1210      * and a dbref with map to gene 'locus'
1211      */
1212     DBRefEntry dbref1 = new DBRefEntry("Uniprot", "1", "P30419", null);
1213     pep.addDBRef(dbref1);
1214     Mapping cdsmap = new Mapping(cds,
1215             new MapList(new int[]
1216             { 1, 4 }, new int[] { 1, 12 }, 1, 3));
1217     DBRefEntry dbref2 = new DBRefEntry("EMBLCDS", "2", "X1235", cdsmap);
1218     pep.addDBRef(dbref2);
1219     Mapping locusmap = new Mapping(null,
1220             new MapList(new int[]
1221             { 1, 4 }, new int[] { 2674123, 2674135 }, 1, 3));
1222     DBRefEntry dbref3 = new GeneLocus("human", "GRCh38", "5", locusmap);
1223     pep.addDBRef(dbref3);
1224
1225     File tfile = File.createTempFile("testStoreAndRecoverGeneLocus",
1226             ".jvp");
1227     try
1228     {
1229       new Jalview2XML(false).saveState(tfile);
1230     } catch (Throwable e)
1231     {
1232       Assert.fail("Didn't save the state", e);
1233     }
1234     Desktop.instance.closeAll_actionPerformed(null);
1235   
1236     new FileLoader().LoadFileWaitTillLoaded(tfile.getAbsolutePath(),
1237             DataSourceType.FILE);
1238     AlignmentViewPanel rap = Desktop.getAlignmentPanels(null)[0];
1239     SequenceI rpep = rap.getAlignment().getSequenceAt(0);
1240     assertEquals(rpep.getName(), "P30419");
1241     DBRefEntry[] dbrefs = rpep.getDBRefs();
1242     assertEquals(dbrefs.length, 3);
1243     DBRefEntry dbRef = dbrefs[0];
1244     assertFalse(dbRef instanceof GeneLocus);
1245     assertNull(dbRef.getMap());
1246     assertEquals(dbRef, dbref1);
1247
1248     /*
1249      * restored dbrefs with mapping have a different 'map to'
1250      * sequence but otherwise match the original dbrefs
1251      */
1252     dbRef = dbrefs[1];
1253     assertFalse(dbRef instanceof GeneLocus);
1254     assertTrue(dbRef.equalRef(dbref2));
1255     assertNotNull(dbRef.getMap());
1256     SequenceI rcds = rap.getAlignment().getSequenceAt(1);
1257     assertSame(dbRef.getMap().getTo(), rcds);
1258     // compare MapList but not map.to
1259     assertEquals(dbRef.getMap().getMap(), dbref2.getMap().getMap());
1260
1261     /*
1262      * GeneLocus map.to is null so can compare Mapping objects
1263      */
1264     dbRef = dbrefs[2];
1265     assertTrue(dbRef instanceof GeneLocus);
1266     assertEquals(dbRef, dbref3);
1267   }
1268 }