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