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