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