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