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