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