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