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