84af3e41982fd5077c94be1be3ff1f6dd5804309
[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.assertNotSame;
27 import static org.testng.Assert.assertNull;
28 import static org.testng.Assert.assertSame;
29 import static org.testng.Assert.assertTrue;
30
31 import java.awt.Color;
32 import java.awt.Rectangle;
33 import java.io.File;
34 import java.io.IOException;
35 import java.util.ArrayList;
36 import java.util.HashMap;
37 import java.util.List;
38 import java.util.Locale;
39 import java.util.Map;
40
41 import javax.swing.JInternalFrame;
42
43 import org.testng.Assert;
44 import org.testng.AssertJUnit;
45 import org.testng.annotations.BeforeClass;
46 import org.testng.annotations.Test;
47
48 import jalview.analysis.scoremodels.SimilarityParams;
49 import jalview.api.AlignViewportI;
50 import jalview.api.AlignmentViewPanel;
51 import jalview.api.FeatureColourI;
52 import jalview.api.ViewStyleI;
53 import jalview.bin.Cache;
54 import jalview.datamodel.AlignmentAnnotation;
55 import jalview.datamodel.AlignmentI;
56 import jalview.datamodel.Annotation;
57 import jalview.datamodel.ContactListI;
58 import jalview.datamodel.ContactMatrixI;
59 import jalview.datamodel.DBRefEntry;
60 import jalview.datamodel.GeneLocus;
61 import jalview.datamodel.HiddenSequences;
62 import jalview.datamodel.Mapping;
63 import jalview.datamodel.PDBEntry;
64 import jalview.datamodel.PDBEntry.Type;
65 import jalview.datamodel.Sequence.DBModList;
66 import jalview.datamodel.SequenceCollectionI;
67 import jalview.datamodel.SequenceFeature;
68 import jalview.datamodel.SequenceGroup;
69 import jalview.datamodel.SequenceI;
70 import jalview.datamodel.features.FeatureMatcher;
71 import jalview.datamodel.features.FeatureMatcherSet;
72 import jalview.datamodel.features.FeatureMatcherSetI;
73 import jalview.gui.AlignFrame;
74 import jalview.gui.AlignViewport;
75 import jalview.gui.AlignmentPanel;
76 import jalview.gui.Desktop;
77 import jalview.gui.JvOptionPane;
78 import jalview.gui.OverviewPanel;
79 import jalview.gui.PCAPanel;
80 import jalview.gui.PopupMenu;
81 import jalview.gui.Preferences;
82 import jalview.gui.SliderPanel;
83 import jalview.io.DataSourceType;
84 import jalview.io.FileFormat;
85 import jalview.io.FileLoader;
86 import jalview.io.Jalview2xmlBase;
87 import jalview.renderer.ResidueShaderI;
88 import jalview.schemes.AnnotationColourGradient;
89 import jalview.schemes.BuriedColourScheme;
90 import jalview.schemes.ColourSchemeI;
91 import jalview.schemes.ColourSchemeProperty;
92 import jalview.schemes.FeatureColour;
93 import jalview.schemes.JalviewColourScheme;
94 import jalview.schemes.RNAHelicesColour;
95 import jalview.schemes.StrandColourScheme;
96 import jalview.schemes.TCoffeeColourScheme;
97 import jalview.structure.StructureImportSettings;
98 import jalview.util.MapList;
99 import jalview.util.matcher.Condition;
100 import jalview.viewmodel.AlignmentViewport;
101 import jalview.viewmodel.seqfeatures.FeatureRendererModel;
102 import jalview.ws.datamodel.alphafold.PAEContactMatrix;
103
104 @Test(singleThreaded = true)
105 public class Jalview2xmlTests extends Jalview2xmlBase
106 {
107
108   @Override
109   @BeforeClass(alwaysRun = true)
110   public void setUpJvOptionPane()
111   {
112     JvOptionPane.setInteractiveMode(false);
113     JvOptionPane.setMockResponse(JvOptionPane.CANCEL_OPTION);
114   }
115
116   @Test(groups = { "Functional" })
117   public void testRNAStructureRecovery() throws Exception
118   {
119     String inFile = "examples/RF00031_folded.stk";
120     String tfile = File.createTempFile("JalviewTest", ".jvp")
121             .getAbsolutePath();
122     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(inFile,
123             DataSourceType.FILE);
124     assertNotNull(af, "Didn't read input file " + inFile);
125     int olddsann = countDsAnn(af.getViewport());
126     assertTrue(olddsann > 0, "Didn't find any dataset annotations");
127     af.changeColour_actionPerformed(
128             JalviewColourScheme.RNAHelices.toString());
129     assertTrue(
130             af.getViewport()
131                     .getGlobalColourScheme() instanceof RNAHelicesColour,
132             "Couldn't apply RNA helices colourscheme");
133     af.saveAlignment(tfile, FileFormat.Jalview);
134     assertTrue(af.isSaveAlignmentSuccessful(),
135             "Failed to store as a project.");
136     af.closeMenuItem_actionPerformed(true);
137     af = null;
138     af = new FileLoader().LoadFileWaitTillLoaded(tfile,
139             DataSourceType.FILE);
140     assertNotNull(af, "Failed to import new project");
141     int newdsann = countDsAnn(af.getViewport());
142     assertEquals(olddsann, newdsann,
143             "Differing numbers of dataset sequence annotation\nOriginally "
144                     + olddsann + " and now " + newdsann);
145     System.out.println(
146             "Read in same number of annotations as originally present ("
147                     + olddsann + ")");
148     assertTrue(
149
150             af.getViewport()
151                     .getGlobalColourScheme() instanceof RNAHelicesColour,
152             "RNA helices colourscheme was not applied on import.");
153   }
154
155   @Test(groups = { "Functional" })
156   public void testTCoffeeScores() throws Exception
157   {
158     String inFile = "examples/uniref50.fa",
159             inAnnot = "examples/uniref50.score_ascii";
160     String tfile = File.createTempFile("JalviewTest", ".jvp")
161             .getAbsolutePath();
162     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(inFile,
163             DataSourceType.FILE);
164     assertNotNull(af, "Didn't read input file " + inFile);
165     af.loadJalviewDataFile(inAnnot, DataSourceType.FILE, null, null);
166     AlignViewport viewport = af.getViewport();
167     assertSame(viewport.getGlobalColourScheme().getClass(),
168             TCoffeeColourScheme.class, "Didn't set T-coffee colourscheme");
169     assertNotNull(
170             ColourSchemeProperty.getColourScheme(viewport,
171                     viewport.getAlignment(),
172                     viewport.getGlobalColourScheme().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,
246             pSize = af.getViewport().getAlignment().getWidth(); p < pSize
247                     && (!diffseqcols || !diffgseqcols); p++)
248     {
249       if (_rcs.findColour(sqs[0].getCharAt(p), p, sqs[0], null, 0f) != _rcs
250               .findColour(sqs[5].getCharAt(p), p, sqs[5], null, 0f))
251       {
252         diffseqcols = true;
253       }
254     }
255     assertTrue(diffseqcols, "Got Different sequence colours");
256     System.out.println(
257             "Per sequence colourscheme (Background) successfully applied and recovered.");
258
259     assertNotNull(_rgcs, "Didn't recover group colourscheme");
260     assertTrue(_rgcs instanceof AnnotationColourGradient,
261             "Didn't recover annotation colour group colourscheme");
262     __rcs = (AnnotationColourGradient) _rgcs;
263     assertTrue(__rcs.isSeqAssociated(),
264             "Group Annotation colourscheme wasn't sequence associated");
265
266     for (int p = 0,
267             pSize = af.getViewport().getAlignment().getWidth(); p < pSize
268                     && (!diffseqcols || !diffgseqcols); p++)
269     {
270       if (_rgcs.findColour(sqs[1].getCharAt(p), p, sqs[1], null,
271               0f) != _rgcs.findColour(sqs[2].getCharAt(p), p, sqs[2], null,
272                       0f))
273       {
274         diffgseqcols = true;
275       }
276     }
277     assertTrue(diffgseqcols, "Got Different group sequence colours");
278     System.out.println(
279             "Per sequence (Group) colourscheme successfully applied and recovered.");
280   }
281
282   @Test(groups = { "Functional" })
283   public void gatherViewsHere() throws Exception
284   {
285     int origCount = Desktop.getAlignFrames() == null ? 0
286             : Desktop.getAlignFrames().length;
287     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(
288             "examples/exampleFile_2_7.jar", DataSourceType.FILE);
289     assertNotNull(af, "Didn't read in the example file correctly.");
290     assertTrue(Desktop.getAlignFrames().length == 1 + origCount,
291             "Didn't gather the views in the example file.");
292
293   }
294
295   /**
296    * Test for JAL-2223 - multiple mappings in View Mapping report
297    * 
298    * @throws Exception
299    */
300   @Test(groups = { "Functional" })
301   public void noDuplicatePdbMappingsMade() throws Exception
302   {
303     StructureImportSettings.setProcessSecondaryStructure(true);
304     StructureImportSettings.setVisibleChainAnnotation(true);
305     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(
306             "examples/exampleFile_2_7.jar", DataSourceType.FILE);
307     assertNotNull(af, "Didn't read in the example file correctly.");
308
309     // locate Jmol viewer
310     // count number of PDB mappings the structure selection manager holds -
311     String pdbFile = af.getCurrentView().getStructureSelectionManager()
312             .findFileForPDBId("1A70");
313     assertEquals(
314             af.getCurrentView().getStructureSelectionManager()
315                     .getMapping(pdbFile).length,
316             2, "Expected only two mappings for 1A70");
317
318   }
319
320   @Test(groups = { "Functional" })
321   public void viewRefPdbAnnotation() throws Exception
322   {
323     StructureImportSettings.setProcessSecondaryStructure(true);
324     StructureImportSettings.setVisibleChainAnnotation(true);
325     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(
326             "examples/exampleFile_2_7.jar", DataSourceType.FILE);
327     assertNotNull(af, "Didn't read in the example file correctly.");
328     AlignmentViewPanel sps = null;
329     for (AlignmentViewPanel ap : af.alignPanel.alignFrame.getAlignPanels())
330     {
331       if ("Spinach Feredoxin Structure".equals(ap.getViewName()))
332       {
333         sps = ap;
334         break;
335       }
336     }
337     assertNotNull(sps, "Couldn't find the structure view");
338     AlignmentAnnotation refan = null;
339     for (AlignmentAnnotation ra : sps.getAlignment()
340             .getAlignmentAnnotation())
341     {
342       if (ra.graph != 0)
343       {
344         refan = ra;
345         break;
346       }
347     }
348     assertNotNull(refan, "Annotation secondary structure not found.");
349     SequenceI sq = sps.getAlignment().findName("1A70|");
350     assertNotNull(sq, "Couldn't find 1a70 null chain");
351     // compare the manually added temperature factor annotation
352     // to the track automatically transferred from the pdb structure on load
353     assertNotNull(sq.getDatasetSequence().getAnnotation(),
354             "1a70 has no annotation");
355     for (AlignmentAnnotation ala : sq.getDatasetSequence().getAnnotation())
356     {
357       AlignmentAnnotation alaa;
358       sq.addAlignmentAnnotation(alaa = new AlignmentAnnotation(ala));
359       alaa.adjustForAlignment();
360       if (ala.graph == refan.graph)
361       {
362         for (int p = 0; p < ala.annotations.length; p++)
363         {
364           sq.findPosition(p);
365           try
366           {
367             assertTrue((alaa.annotations[p] == null
368                     && refan.annotations[p] == null)
369                     || alaa.annotations[p].value == refan.annotations[p].value,
370                     "Mismatch at alignment position " + p);
371           } catch (NullPointerException q)
372           {
373             Assert.fail("Mismatch of alignment annotations at position " + p
374                     + " Ref seq ann: " + refan.annotations[p]
375                     + " alignment " + alaa.annotations[p]);
376           }
377         }
378       }
379     }
380
381   }
382
383   @Test(groups = { "Functional" })
384   public void testCopyViewSettings() throws Exception
385   {
386     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(
387             "examples/exampleFile_2_7.jar", DataSourceType.FILE);
388     assertNotNull(af, "Didn't read in the example file correctly.");
389     AlignmentViewPanel sps = null, groups = null;
390     for (AlignmentViewPanel ap : af.alignPanel.alignFrame.getAlignPanels())
391     {
392       if ("Spinach Feredoxin Structure".equals(ap.getViewName()))
393       {
394         sps = ap;
395       }
396       if (ap.getViewName().contains("MAFFT"))
397       {
398         groups = ap;
399       }
400     }
401     assertNotNull(sps, "Couldn't find the structure view");
402     assertNotNull(groups, "Couldn't find the MAFFT view");
403
404     ViewStyleI structureStyle = sps.getAlignViewport().getViewStyle();
405     ViewStyleI groupStyle = groups.getAlignViewport().getViewStyle();
406     AssertJUnit.assertFalse(structureStyle.sameStyle(groupStyle));
407
408     groups.getAlignViewport().setViewStyle(structureStyle);
409     AssertJUnit.assertFalse(
410             groupStyle.sameStyle(groups.getAlignViewport().getViewStyle()));
411     Assert.assertTrue(structureStyle
412             .sameStyle(groups.getAlignViewport().getViewStyle()));
413
414   }
415
416   /**
417    * test store and recovery of expanded views
418    * 
419    * @throws Exception
420    */
421   @Test(groups = { "Functional" }, enabled = true)
422   public void testStoreAndRecoverExpandedviews() throws Exception
423   {
424     Desktop.instance.closeAll_actionPerformed(null);
425
426     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(
427             "examples/exampleFile_2_7.jar", DataSourceType.FILE);
428     Assert.assertEquals(Desktop.getAlignFrames().length, 1);
429     String afid = af.getViewport().getSequenceSetId();
430
431     // check FileLoader returned a reference to the one alignFrame that is
432     // actually on the Desktop
433     assertSame(af, Desktop.getAlignFrameFor(af.getViewport()),
434             "Jalview2XML.loadAlignFrame() didn't return correct AlignFrame reference for multiple view window");
435
436     Desktop.explodeViews(af);
437
438     int oldviews = Desktop.getAlignFrames().length;
439     Assert.assertEquals(Desktop.getAlignFrames().length,
440             Desktop.getAlignmentPanels(afid).length);
441     File tfile = File.createTempFile("testStoreAndRecoverExpanded", ".jvp");
442     try
443     {
444       new Jalview2XML(false).saveState(tfile);
445     } catch (Error e)
446     {
447       Assert.fail("Didn't save the expanded view state", e);
448     } catch (Exception e)
449     {
450       Assert.fail("Didn't save the expanded view state", e);
451     }
452     Desktop.instance.closeAll_actionPerformed(null);
453     if (Desktop.getAlignFrames() != null)
454     {
455       Assert.assertEquals(Desktop.getAlignFrames().length, 0);
456     }
457     af = new FileLoader().LoadFileWaitTillLoaded(tfile.getAbsolutePath(),
458             DataSourceType.FILE);
459     Assert.assertNotNull(af);
460     Assert.assertEquals(Desktop.getAlignFrames().length,
461             Desktop.getAlignmentPanels(
462                     af.getViewport().getSequenceSetId()).length);
463     Assert.assertEquals(Desktop
464             .getAlignmentPanels(af.getViewport().getSequenceSetId()).length,
465             oldviews);
466   }
467
468   /**
469    * Test save and reload of a project with a different representative sequence
470    * in each view.
471    * 
472    * @throws Exception
473    */
474   @Test(groups = { "Functional" })
475   public void testStoreAndRecoverReferenceSeqSettings() throws Exception
476   {
477     Desktop.instance.closeAll_actionPerformed(null);
478     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(
479             "examples/exampleFile_2_7.jar", DataSourceType.FILE);
480     assertNotNull(af, "Didn't read in the example file correctly.");
481     String afid = af.getViewport().getSequenceSetId();
482
483     // remember reference sequence for each panel
484     Map<String, SequenceI> refseqs = new HashMap<>();
485
486     /*
487      * mark sequence 2, 3, 4.. in panels 1, 2, 3...
488      * as reference sequence for itself and the preceding sequence
489      */
490     int n = 1;
491     for (AlignmentViewPanel ap : Desktop.getAlignmentPanels(afid))
492     {
493       AlignViewportI av = ap.getAlignViewport();
494       AlignmentI alignment = ap.getAlignment();
495       int repIndex = n % alignment.getHeight();
496       SequenceI rep = alignment.getSequenceAt(repIndex);
497       refseqs.put(ap.getViewName(), rep);
498
499       // code from mark/unmark sequence as reference in jalview.gui.PopupMenu
500       // todo refactor this to an alignment view controller
501       av.setDisplayReferenceSeq(true);
502       av.setColourByReferenceSeq(true);
503       av.getAlignment().setSeqrep(rep);
504
505       n++;
506     }
507     File tfile = File.createTempFile("testStoreAndRecoverReferenceSeq",
508             ".jvp");
509     try
510     {
511       new Jalview2XML(false).saveState(tfile);
512     } catch (Throwable e)
513     {
514       Assert.fail("Didn't save the expanded view state", e);
515     }
516     Desktop.instance.closeAll_actionPerformed(null);
517     if (Desktop.getAlignFrames() != null)
518     {
519       Assert.assertEquals(Desktop.getAlignFrames().length, 0);
520     }
521
522     af = new FileLoader().LoadFileWaitTillLoaded(tfile.getAbsolutePath(),
523             DataSourceType.FILE);
524     afid = af.getViewport().getSequenceSetId();
525
526     for (AlignmentViewPanel ap : Desktop.getAlignmentPanels(afid))
527     {
528       // check representative
529       AlignmentI alignment = ap.getAlignment();
530       SequenceI rep = alignment.getSeqrep();
531       Assert.assertNotNull(rep,
532               "Couldn't restore sequence representative from project");
533       // can't use a strong equals here, because by definition, the sequence IDs
534       // will be different.
535       // could set vamsas session save/restore flag to preserve IDs across
536       // load/saves.
537       Assert.assertEquals(refseqs.get(ap.getViewName()).toString(),
538               rep.toString(),
539               "Representative wasn't the same when recovered.");
540       Assert.assertTrue(ap.getAlignViewport().isDisplayReferenceSeq(),
541               "Display reference sequence view setting not set.");
542       Assert.assertTrue(ap.getAlignViewport().isColourByReferenceSeq(),
543               "Colour By Reference Seq view setting not set.");
544     }
545   }
546
547   @Test(groups = { "Functional" })
548   public void testIsVersionStringLaterThan()
549   {
550     /*
551      * No version / development / test / autobuild is leniently assumed to be
552      * compatible
553      */
554     assertTrue(Jalview2XML.isVersionStringLaterThan(null, null));
555     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3", null));
556     assertTrue(Jalview2XML.isVersionStringLaterThan(null, "2.8.3"));
557     assertTrue(Jalview2XML.isVersionStringLaterThan(null,
558             "Development Build"));
559     assertTrue(Jalview2XML.isVersionStringLaterThan(null,
560             "DEVELOPMENT BUILD"));
561     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3",
562             "Development Build"));
563     assertTrue(Jalview2XML.isVersionStringLaterThan(null, "Test"));
564     assertTrue(Jalview2XML.isVersionStringLaterThan(null, "TEST"));
565     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3", "Test"));
566     assertTrue(
567             Jalview2XML.isVersionStringLaterThan(null, "Automated Build"));
568     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3",
569             "Automated Build"));
570     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3",
571             "AUTOMATED BUILD"));
572
573     /*
574      * same version returns true i.e. compatible
575      */
576     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8", "2.8"));
577     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3", "2.8.3"));
578     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3b1", "2.8.3b1"));
579     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3B1", "2.8.3b1"));
580     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3b1", "2.8.3B1"));
581
582     /*
583      * later version returns true
584      */
585     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3", "2.8.4"));
586     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3", "2.9"));
587     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3", "2.9.2"));
588     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8", "2.8.3"));
589     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3", "2.8.3b1"));
590
591     /*
592      * earlier version returns false
593      */
594     assertFalse(Jalview2XML.isVersionStringLaterThan("2.8.3", "2.8"));
595     assertFalse(Jalview2XML.isVersionStringLaterThan("2.8.4", "2.8.3"));
596     assertFalse(Jalview2XML.isVersionStringLaterThan("2.8.3b1", "2.8.3"));
597     assertFalse(Jalview2XML.isVersionStringLaterThan("2.8.3", "2.8.2b1"));
598     assertFalse(Jalview2XML.isVersionStringLaterThan("2.8.0b2", "2.8.0b1"));
599     /*
600      * test for patch release versions
601      */
602     assertFalse(Jalview2XML.isVersionStringLaterThan("2.11.3.0", "2.11.2"));
603     assertTrue(Jalview2XML.isVersionStringLaterThan("2.11.3.0","2.11.4"));
604     assertFalse(Jalview2XML.isVersionStringLaterThan("2.12.2.0b1","2.12.2.0"));
605     assertFalse(Jalview2XML.isVersionStringLaterThan("2.12.2.3","2.12.2.2"));
606
607   }
608
609   /**
610    * Test save and reload of a project with a different sequence group (and
611    * representative sequence) in each view.
612    * 
613    * @throws Exception
614    */
615   @Test(groups = { "Functional" })
616   public void testStoreAndRecoverGroupRepSeqs() throws Exception
617   {
618     Desktop.instance.closeAll_actionPerformed(null);
619     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(
620             "examples/uniref50.fa", DataSourceType.FILE);
621     assertNotNull(af, "Didn't read in the example file correctly.");
622     String afid = af.getViewport().getSequenceSetId();
623     // make a second view of the alignment
624     af.newView_actionPerformed(null);
625
626     /*
627      * remember representative and hidden sequences marked 
628      * on each panel
629      */
630     Map<String, SequenceI> repSeqs = new HashMap<>();
631     Map<String, List<String>> hiddenSeqNames = new HashMap<>();
632
633     /*
634      * mark sequence 2, 3, 4.. in panels 1, 2, 3...
635      * as reference sequence for itself and the preceding sequence
636      */
637     int n = 1;
638     for (AlignmentViewPanel ap : Desktop.getAlignmentPanels(afid))
639     {
640       AlignViewportI av = ap.getAlignViewport();
641       AlignmentI alignment = ap.getAlignment();
642       int repIndex = n % alignment.getHeight();
643       // ensure at least one preceding sequence i.e. index >= 1
644       repIndex = Math.max(repIndex, 1);
645       SequenceI repSeq = alignment.getSequenceAt(repIndex);
646       repSeqs.put(ap.getViewName(), repSeq);
647       List<String> hiddenNames = new ArrayList<>();
648       hiddenSeqNames.put(ap.getViewName(), hiddenNames);
649
650       /*
651        * have rep sequence represent itself and the one before it
652        * this hides the group (except for the rep seq)
653        */
654       SequenceGroup sg = new SequenceGroup();
655       sg.addSequence(repSeq, false);
656       SequenceI precedingSeq = alignment.getSequenceAt(repIndex - 1);
657       sg.addSequence(precedingSeq, false);
658       sg.setSeqrep(repSeq);
659       assertTrue(sg.getSequences().contains(repSeq));
660       assertTrue(sg.getSequences().contains(precedingSeq));
661       av.setSelectionGroup(sg);
662       assertSame(repSeq, sg.getSeqrep());
663
664       /*
665        * represent group with sequence adds to a map of hidden rep sequences
666        * (it does not create a group on the alignment) 
667        */
668       ((AlignmentViewport) av).hideSequences(repSeq, true);
669       assertSame(repSeq, sg.getSeqrep());
670       assertTrue(sg.getSequences().contains(repSeq));
671       assertTrue(sg.getSequences().contains(precedingSeq));
672       assertTrue(alignment.getGroups().isEmpty(), "alignment has groups");
673       Map<SequenceI, SequenceCollectionI> hiddenRepSeqsMap = av
674               .getHiddenRepSequences();
675       assertNotNull(hiddenRepSeqsMap);
676       assertEquals(1, hiddenRepSeqsMap.size());
677       assertSame(sg, hiddenRepSeqsMap.get(repSeq));
678       assertTrue(alignment.getHiddenSequences().isHidden(precedingSeq));
679       assertFalse(alignment.getHiddenSequences().isHidden(repSeq));
680       hiddenNames.add(precedingSeq.getName());
681
682       n++;
683     }
684     File tfile = File.createTempFile("testStoreAndRecoverGroupReps",
685             ".jvp");
686     try
687     {
688       new Jalview2XML(false).saveState(tfile);
689     } catch (Throwable e)
690     {
691       Assert.fail("Didn't save the expanded view state", e);
692     }
693     Desktop.instance.closeAll_actionPerformed(null);
694     if (Desktop.getAlignFrames() != null)
695     {
696       Assert.assertEquals(Desktop.getAlignFrames().length, 0);
697     }
698
699     af = new FileLoader().LoadFileWaitTillLoaded(tfile.getAbsolutePath(),
700             DataSourceType.FILE);
701     afid = af.getViewport().getSequenceSetId();
702
703     for (AlignmentViewPanel ap : Desktop.getAlignmentPanels(afid))
704     {
705       String viewName = ap.getViewName();
706       AlignViewportI av = ap.getAlignViewport();
707       AlignmentI alignment = ap.getAlignment();
708       List<SequenceGroup> groups = alignment.getGroups();
709       assertNotNull(groups);
710       assertTrue(groups.isEmpty(), "Alignment has groups");
711       Map<SequenceI, SequenceCollectionI> hiddenRepSeqsMap = av
712               .getHiddenRepSequences();
713       assertNotNull(hiddenRepSeqsMap, "No hidden represented sequences");
714       assertEquals(1, hiddenRepSeqsMap.size());
715       assertEquals(repSeqs.get(viewName).getDisplayId(true),
716               hiddenRepSeqsMap.keySet().iterator().next()
717                       .getDisplayId(true));
718
719       /*
720        * verify hidden sequences in restored panel
721        */
722       List<String> hidden = hiddenSeqNames.get(ap.getViewName());
723       HiddenSequences hs = alignment.getHiddenSequences();
724       assertEquals(hidden.size(), hs.getSize(),
725               "wrong number of restored hidden sequences in "
726                       + ap.getViewName());
727     }
728   }
729
730   /**
731    * Test save and reload of PDBEntry in Jalview project
732    * 
733    * @throws Exception
734    */
735   @Test(groups = { "Functional" })
736   public void testStoreAndRecoverPDBEntry() throws Exception
737   {
738     Desktop.instance.closeAll_actionPerformed(null);
739     String exampleFile = "examples/3W5V.pdb";
740     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(exampleFile,
741             DataSourceType.FILE);
742     assertNotNull(af, "Didn't read in the example file correctly.");
743     String afid = af.getViewport().getSequenceSetId();
744
745     AlignmentPanel[] alignPanels = Desktop.getAlignmentPanels(afid);
746     System.out.println();
747     AlignmentViewPanel ap = alignPanels[0];
748     String tfileBase = new File(".").getAbsolutePath().replace(".", "");
749     String testFile = tfileBase + exampleFile;
750     AlignmentI alignment = ap.getAlignment();
751     System.out.println("blah");
752     SequenceI[] seqs = alignment.getSequencesArray();
753     Assert.assertNotNull(seqs[0]);
754     Assert.assertNotNull(seqs[1]);
755     Assert.assertNotNull(seqs[2]);
756     Assert.assertNotNull(seqs[3]);
757     Assert.assertNotNull(seqs[0].getDatasetSequence());
758     Assert.assertNotNull(seqs[1].getDatasetSequence());
759     Assert.assertNotNull(seqs[2].getDatasetSequence());
760     Assert.assertNotNull(seqs[3].getDatasetSequence());
761     PDBEntry[] pdbEntries = new PDBEntry[4];
762     pdbEntries[0] = new PDBEntry("3W5V", "A", Type.PDB, testFile);
763     pdbEntries[1] = new PDBEntry("3W5V", "B", Type.PDB, testFile);
764     pdbEntries[2] = new PDBEntry("3W5V", "C", Type.PDB, testFile);
765     pdbEntries[3] = new PDBEntry("3W5V", "D", Type.PDB, testFile);
766     Assert.assertEquals(
767             seqs[0].getDatasetSequence().getAllPDBEntries().get(0),
768             pdbEntries[0]);
769     Assert.assertEquals(
770             seqs[1].getDatasetSequence().getAllPDBEntries().get(0),
771             pdbEntries[1]);
772     Assert.assertEquals(
773             seqs[2].getDatasetSequence().getAllPDBEntries().get(0),
774             pdbEntries[2]);
775     Assert.assertEquals(
776             seqs[3].getDatasetSequence().getAllPDBEntries().get(0),
777             pdbEntries[3]);
778
779     File tfile = File.createTempFile("testStoreAndRecoverPDBEntry", ".jvp");
780     try
781     {
782       new Jalview2XML(false).saveState(tfile);
783     } catch (Throwable e)
784     {
785       Assert.fail("Didn't save the state", e);
786     }
787     Desktop.instance.closeAll_actionPerformed(null);
788     if (Desktop.getAlignFrames() != null)
789     {
790       Assert.assertEquals(Desktop.getAlignFrames().length, 0);
791     }
792
793     AlignFrame restoredFrame = new FileLoader().LoadFileWaitTillLoaded(
794             tfile.getAbsolutePath(), DataSourceType.FILE);
795     String rfid = restoredFrame.getViewport().getSequenceSetId();
796     AlignmentPanel[] rAlignPanels = Desktop.getAlignmentPanels(rfid);
797     AlignmentViewPanel rap = rAlignPanels[0];
798     AlignmentI rAlignment = rap.getAlignment();
799     System.out.println("blah");
800     SequenceI[] rseqs = rAlignment.getSequencesArray();
801     Assert.assertNotNull(rseqs[0]);
802     Assert.assertNotNull(rseqs[1]);
803     Assert.assertNotNull(rseqs[2]);
804     Assert.assertNotNull(rseqs[3]);
805     Assert.assertNotNull(rseqs[0].getDatasetSequence());
806     Assert.assertNotNull(rseqs[1].getDatasetSequence());
807     Assert.assertNotNull(rseqs[2].getDatasetSequence());
808     Assert.assertNotNull(rseqs[3].getDatasetSequence());
809
810     // The Asserts below are expected to fail until the PDB chainCode is
811     // recoverable from a Jalview projects
812     for (int chain = 0; chain < 4; chain++)
813     {
814       PDBEntry recov = rseqs[chain].getDatasetSequence().getAllPDBEntries()
815               .get(0);
816       PDBEntry expected = pdbEntries[chain];
817       Assert.assertEquals(recov.getId(), expected.getId(),
818               "Mismatch PDB ID");
819       Assert.assertEquals(recov.getChainCode(), expected.getChainCode(),
820               "Mismatch PDB ID");
821       Assert.assertEquals(recov.getType(), expected.getType(),
822               "Mismatch PDBEntry 'Type'");
823       Assert.assertNotNull(recov.getFile(),
824               "Recovered PDBEntry should have a non-null file entry");
825       Assert.assertEquals(
826               recov.getFile().toLowerCase(Locale.ENGLISH)
827                       .lastIndexOf("pdb"),
828               recov.getFile().length() - 3,
829               "Recovered PDBEntry file should have PDB suffix");
830     }
831   }
832
833   /**
834    * Configure an alignment and a sub-group each with distinct colour schemes,
835    * Conservation and PID thresholds, and confirm these are restored from the
836    * saved project.
837    * 
838    * @throws IOException
839    */
840   @Test(groups = { "Functional" })
841   public void testStoreAndRecoverAnnotationRowElementColours()
842           throws IOException
843   {
844     Desktop.instance.closeAll_actionPerformed(null);
845     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded("SEQ\tMNQ",
846             DataSourceType.PASTE);
847
848     AlignViewport av = af.getViewport();
849     AlignmentI al = av.getAlignment();
850     SequenceI fsq;
851     fsq = al.getSequenceAt(0);
852     Annotation annots[] = new Annotation[fsq.getLength()];
853     AlignmentAnnotation ala = new AlignmentAnnotation("Colour", "Annots",
854             annots);
855     annots[0] = new Annotation(1.0f);
856     annots[1] = new Annotation(2.0f);
857     annots[2] = new Annotation(3.0f);
858     annots[0].colour = Color.RED;
859     annots[1].colour = Color.GREEN;
860     annots[2].colour = Color.BLUE;
861     ala.validateRangeAndDisplay();
862     al.getSequenceAt(0).addAlignmentAnnotation(ala);
863     al.addAnnotation(ala);
864     /*
865      * and colour by annotation
866      */
867     AnnotationColourGradient acg = new AnnotationColourGradient(ala,
868             af.alignPanel.av.getGlobalColourScheme(), 0);
869     acg.setSeqAssociated(true);
870     acg.setPredefinedColours(true);
871     af.changeColour(acg);
872     Color seqcol[] = new Color[3];
873     for (int iStart=fsq.findIndex(fsq.getStart()),i=0;i<3;i++) {
874       seqcol[i] = af.alignPanel.getSeqPanel().seqCanvas.getSequenceRenderer().getResidueColour(fsq, iStart+i, null);
875     }
876     /*
877      * save project, close windows, reload project, verify
878      */
879     File tfile = File.createTempFile(
880             "testStoreAndRecoverAnnotRowElemColors", ".jvp");
881     tfile.deleteOnExit();
882     new Jalview2XML(false).saveState(tfile);
883     //Desktop.instance.closeAll_actionPerformed(null);
884     af = new FileLoader().LoadFileWaitTillLoaded(tfile.getAbsolutePath(),
885             DataSourceType.FILE);
886     Assert.assertNotNull(af, "Failed to reload project");
887     /*
888      * verify alignment annotation has colors
889      */
890     av = af.getViewport();
891     
892     ColourSchemeI loadedCscheme = av.getGlobalColourScheme();
893     Assert.assertTrue(loadedCscheme instanceof AnnotationColourGradient,"Didn't apply Annotation colour gradient");
894     acg = (AnnotationColourGradient) loadedCscheme;
895     assertTrue(acg.isSeqAssociated());
896     assertTrue(acg.isPredefinedColours());
897
898     al = av.getAlignment();
899     fsq = al.getSequenceAt(0);
900     ala = fsq.getAnnotation()[0];
901     Assert.assertNotNull(ala, "No annotation row recovered");
902     Assert.assertNotNull(ala.annotations);
903     for (int iStart = al.getSequenceAt(0)
904             .findIndex(al.getSequenceAt(0).getStart()), i = 0; i < 3; i++)
905     {
906       Assert.assertTrue(ala.annotations[i].colour!=null);
907       Assert.assertTrue(ala.annotations[i].colour.equals(annots[i].colour));
908       Color newseqcol = af.alignPanel.getSeqPanel().seqCanvas.getSequenceRenderer().getResidueColour(fsq, iStart+i, null);
909       Assert.assertTrue(seqcol[i].equals(newseqcol),"Sequence shading is different");
910
911     }
912     
913   }
914
915   /**
916    * Configure an alignment and a sub-group each with distinct colour schemes,
917    * Conservation and PID thresholds, and confirm these are restored from the
918    * saved project.
919    * 
920    * @throws IOException
921    */
922   @Test(groups = { "Functional" })
923   public void testStoreAndRecoverColourThresholds() throws IOException
924   {
925     Desktop.instance.closeAll_actionPerformed(null);
926     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(
927             "examples/uniref50.fa", DataSourceType.FILE);
928
929     AlignViewport av = af.getViewport();
930     AlignmentI al = av.getAlignment();
931
932     /*
933      * Colour alignment by Buried Index, Above 10% PID, By Conservation 20%
934      */
935     av.setColourAppliesToAllGroups(false);
936     af.changeColour_actionPerformed(JalviewColourScheme.Buried.toString());
937     assertTrue(av.getGlobalColourScheme() instanceof BuriedColourScheme);
938     af.abovePIDThreshold_actionPerformed(true);
939     SliderPanel sp = SliderPanel.getSliderPanel();
940     assertFalse(sp.isForConservation());
941     sp.valueChanged(10);
942     af.conservationMenuItem_actionPerformed(true);
943     sp = SliderPanel.getSliderPanel();
944     assertTrue(sp.isForConservation());
945     sp.valueChanged(20);
946     ResidueShaderI rs = av.getResidueShading();
947     assertEquals(rs.getThreshold(), 10);
948     assertTrue(rs.conservationApplied());
949     assertEquals(rs.getConservationInc(), 20);
950
951     /*
952      * create a group with Strand colouring, 30% Conservation
953      * and 40% PID threshold
954      * (notice menu action applies to selection group even if mouse click
955      * is at a sequence not in the group)
956      */
957     SequenceGroup sg = new SequenceGroup();
958     sg.addSequence(al.getSequenceAt(0), false);
959     sg.setStartRes(15);
960     sg.setEndRes(25);
961     av.setSelectionGroup(sg);
962     PopupMenu popupMenu = new PopupMenu(af.alignPanel, al.getSequenceAt(2),
963             null);
964     popupMenu.changeColour_actionPerformed(
965             JalviewColourScheme.Strand.toString());
966     assertTrue(sg.getColourScheme() instanceof StrandColourScheme);
967     assertEquals(al.getGroups().size(), 1);
968     assertSame(al.getGroups().get(0), sg);
969     popupMenu.conservationMenuItem_actionPerformed(true);
970     sp = SliderPanel.getSliderPanel();
971     assertTrue(sp.isForConservation());
972     sp.valueChanged(30);
973     popupMenu.abovePIDColour_actionPerformed(true);
974     sp = SliderPanel.getSliderPanel();
975     assertFalse(sp.isForConservation());
976     sp.valueChanged(40);
977     assertTrue(sg.getGroupColourScheme().conservationApplied());
978     assertEquals(sg.getGroupColourScheme().getConservationInc(), 30);
979     assertEquals(sg.getGroupColourScheme().getThreshold(), 40);
980
981     /*
982      * save project, close windows, reload project, verify
983      */
984     File tfile = File.createTempFile("testStoreAndRecoverColourThresholds",
985             ".jvp");
986     tfile.deleteOnExit();
987     new Jalview2XML(false).saveState(tfile);
988     Desktop.instance.closeAll_actionPerformed(null);
989     af = new FileLoader().LoadFileWaitTillLoaded(tfile.getAbsolutePath(),
990             DataSourceType.FILE);
991     Assert.assertNotNull(af, "Failed to reload project");
992
993     /*
994      * verify alignment (background) colouring
995      */
996     rs = af.getViewport().getResidueShading();
997     assertTrue(rs.getColourScheme() instanceof BuriedColourScheme);
998     assertEquals(rs.getThreshold(), 10);
999     assertTrue(rs.conservationApplied());
1000     assertEquals(rs.getConservationInc(), 20);
1001
1002     /*
1003      * verify group colouring
1004      */
1005     assertEquals(1, af.getViewport().getAlignment().getGroups().size(), 1);
1006     rs = af.getViewport().getAlignment().getGroups().get(0)
1007             .getGroupColourScheme();
1008     assertTrue(rs.getColourScheme() instanceof StrandColourScheme);
1009     assertEquals(rs.getThreshold(), 40);
1010     assertTrue(rs.conservationApplied());
1011     assertEquals(rs.getConservationInc(), 30);
1012   }
1013
1014   /**
1015    * Test save and reload of feature colour schemes and filter settings
1016    * 
1017    * @throws IOException
1018    */
1019   @Test(groups = { "Functional" })
1020   public void testSaveLoadFeatureColoursAndFilters() throws IOException
1021   {
1022     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(
1023             ">Seq1\nACDEFGHIKLM", DataSourceType.PASTE);
1024     SequenceI seq1 = af.getViewport().getAlignment().getSequenceAt(0);
1025
1026     /*
1027      * add some features to the sequence
1028      */
1029     int score = 1;
1030     addFeatures(seq1, "type1", score++);
1031     addFeatures(seq1, "type2", score++);
1032     addFeatures(seq1, "type3", score++);
1033     addFeatures(seq1, "type4", score++);
1034     addFeatures(seq1, "type5", score++);
1035
1036     /*
1037      * set colour schemes for features
1038      */
1039     FeatureRendererModel fr = af.getFeatureRenderer();
1040     fr.findAllFeatures(true);
1041
1042     // type1: red
1043     fr.setColour("type1", new FeatureColour(Color.red));
1044
1045     // type2: by label
1046     FeatureColourI byLabel = new FeatureColour();
1047     byLabel.setColourByLabel(true);
1048     fr.setColour("type2", byLabel);
1049
1050     // type3: by score above threshold
1051     FeatureColourI byScore = new FeatureColour(null, Color.BLACK,
1052             Color.BLUE, null, 1, 10);
1053     byScore.setAboveThreshold(true);
1054     byScore.setThreshold(2f);
1055     fr.setColour("type3", byScore);
1056
1057     // type4: by attribute AF
1058     FeatureColourI byAF = new FeatureColour();
1059     byAF.setColourByLabel(true);
1060     byAF.setAttributeName("AF");
1061     fr.setColour("type4", byAF);
1062
1063     // type5: by attribute CSQ:PolyPhen below threshold
1064     FeatureColourI byPolyPhen = new FeatureColour(null, Color.BLACK,
1065             Color.BLUE, null, 1, 10);
1066     byPolyPhen.setBelowThreshold(true);
1067     byPolyPhen.setThreshold(3f);
1068     byPolyPhen.setAttributeName("CSQ", "PolyPhen");
1069     fr.setColour("type5", byPolyPhen);
1070
1071     /*
1072      * set filters for feature types
1073      */
1074
1075     // filter type1 features by (label contains "x")
1076     FeatureMatcherSetI filterByX = new FeatureMatcherSet();
1077     filterByX.and(FeatureMatcher.byLabel(Condition.Contains, "x"));
1078     fr.setFeatureFilter("type1", filterByX);
1079
1080     // filter type2 features by (score <= 2.4 and score > 1.1)
1081     FeatureMatcherSetI filterByScore = new FeatureMatcherSet();
1082     filterByScore.and(FeatureMatcher.byScore(Condition.LE, "2.4"));
1083     filterByScore.and(FeatureMatcher.byScore(Condition.GT, "1.1"));
1084     fr.setFeatureFilter("type2", filterByScore);
1085
1086     // filter type3 features by (AF contains X OR CSQ:PolyPhen != 0)
1087     FeatureMatcherSetI filterByXY = new FeatureMatcherSet();
1088     filterByXY
1089             .and(FeatureMatcher.byAttribute(Condition.Contains, "X", "AF"));
1090     filterByXY.or(FeatureMatcher.byAttribute(Condition.NE, "0", "CSQ",
1091             "PolyPhen"));
1092     fr.setFeatureFilter("type3", filterByXY);
1093
1094     /*
1095      * save as Jalview project
1096      */
1097     File tfile = File.createTempFile("JalviewTest", ".jvp");
1098     tfile.deleteOnExit();
1099     String filePath = tfile.getAbsolutePath();
1100     af.saveAlignment(filePath, FileFormat.Jalview);
1101     assertTrue(af.isSaveAlignmentSuccessful(),
1102             "Failed to store as a project.");
1103
1104     /*
1105      * close current alignment and load the saved project
1106      */
1107     af.closeMenuItem_actionPerformed(true);
1108     af = null;
1109     af = new FileLoader().LoadFileWaitTillLoaded(filePath,
1110             DataSourceType.FILE);
1111     assertNotNull(af, "Failed to import new project");
1112
1113     /*
1114      * verify restored feature colour schemes and filters
1115      */
1116     fr = af.getFeatureRenderer();
1117     FeatureColourI fc = fr.getFeatureStyle("type1");
1118     assertTrue(fc.isSimpleColour());
1119     assertEquals(fc.getColour(), Color.red);
1120     fc = fr.getFeatureStyle("type2");
1121     assertTrue(fc.isColourByLabel());
1122     fc = fr.getFeatureStyle("type3");
1123     assertTrue(fc.isGraduatedColour());
1124     assertNull(fc.getAttributeName());
1125     assertTrue(fc.isAboveThreshold());
1126     assertEquals(fc.getThreshold(), 2f);
1127     fc = fr.getFeatureStyle("type4");
1128     assertTrue(fc.isColourByLabel());
1129     assertTrue(fc.isColourByAttribute());
1130     assertEquals(fc.getAttributeName(), new String[] { "AF" });
1131     fc = fr.getFeatureStyle("type5");
1132     assertTrue(fc.isGraduatedColour());
1133     assertTrue(fc.isColourByAttribute());
1134     assertEquals(fc.getAttributeName(), new String[] { "CSQ", "PolyPhen" });
1135     assertTrue(fc.isBelowThreshold());
1136     assertEquals(fc.getThreshold(), 3f);
1137
1138     assertEquals(fr.getFeatureFilter("type1").toStableString(),
1139             "Label Contains x");
1140     assertEquals(fr.getFeatureFilter("type2").toStableString(),
1141             "(Score LE 2.4) AND (Score GT 1.1)");
1142     assertEquals(fr.getFeatureFilter("type3").toStableString(),
1143             "(AF Contains X) OR (CSQ:PolyPhen NE 0)");
1144   }
1145
1146   private void addFeature(SequenceI seq, String featureType, int score)
1147   {
1148     SequenceFeature sf = new SequenceFeature(featureType, "desc", 1, 2,
1149             score, "grp");
1150     sf.setValue("AF", score);
1151     sf.setValue("CSQ", new HashMap<String, String>()
1152     {
1153       {
1154         put("PolyPhen", Integer.toString(score));
1155       }
1156     });
1157     seq.addSequenceFeature(sf);
1158   }
1159
1160   /**
1161    * Adds two features of the given type to the given sequence, also setting the
1162    * score as the value of attribute "AF" and sub-attribute "CSQ:PolyPhen"
1163    * 
1164    * @param seq
1165    * @param featureType
1166    * @param score
1167    */
1168   private void addFeatures(SequenceI seq, String featureType, int score)
1169   {
1170     addFeature(seq, featureType, score++);
1171     addFeature(seq, featureType, score);
1172   }
1173
1174   /**
1175    * pre 2.11 - jalview 2.10 erroneously created new dataset entries for each
1176    * view (JAL-3171) this test ensures we can import and merge those views
1177    */
1178   @Test(groups = { "Functional" })
1179   public void testMergeDatasetsforViews() throws IOException
1180   {
1181     // simple project - two views on one alignment
1182     AlignFrame af = new FileLoader(false).LoadFileWaitTillLoaded(
1183             "examples/testdata/projects/twoViews.jvp", DataSourceType.FILE);
1184     assertNotNull(af);
1185     assertTrue(af.getAlignPanels().size() > 1);
1186     verifyDs(af);
1187   }
1188
1189   /**
1190    * pre 2.11 - jalview 2.10 erroneously created new dataset entries for each
1191    * view (JAL-3171) this test ensures we can import and merge those views This
1192    * is a more complex project
1193    */
1194   @Test(groups = { "Functional" })
1195   public void testMergeDatasetsforManyViews() throws IOException
1196   {
1197     Desktop.instance.closeAll_actionPerformed(null);
1198
1199     // complex project - one dataset, several views on several alignments
1200     AlignFrame af = new FileLoader(false).LoadFileWaitTillLoaded(
1201             "examples/testdata/projects/manyViews.jvp",
1202             DataSourceType.FILE);
1203     assertNotNull(af);
1204
1205     AlignmentI ds = null;
1206     for (AlignFrame alignFrame : Desktop.getAlignFrames())
1207     {
1208       if (ds == null)
1209       {
1210         ds = verifyDs(alignFrame);
1211       }
1212       else
1213       {
1214         // check that this frame's dataset matches the last
1215         assertTrue(ds == verifyDs(alignFrame));
1216       }
1217     }
1218   }
1219
1220   private AlignmentI verifyDs(AlignFrame af)
1221   {
1222     AlignmentI ds = null;
1223     for (AlignmentViewPanel ap : af.getAlignPanels())
1224     {
1225       if (ds == null)
1226       {
1227         ds = ap.getAlignment().getDataset();
1228       }
1229       else
1230       {
1231         assertTrue(ap.getAlignment().getDataset() == ds,
1232                 "Dataset was not the same for imported 2.10.5 project with several alignment views");
1233       }
1234     }
1235     return ds;
1236   }
1237
1238   @Test(groups = "Functional")
1239   public void testPcaViewAssociation() throws IOException
1240   {
1241     Desktop.instance.closeAll_actionPerformed(null);
1242     final String PCAVIEWNAME = "With PCA";
1243     // create a new tempfile
1244     File tempfile = File.createTempFile("jvPCAviewAssoc", "jvp");
1245
1246     {
1247       String exampleFile = "examples/uniref50.fa";
1248       AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(exampleFile,
1249               DataSourceType.FILE);
1250       assertNotNull(af, "Didn't read in the example file correctly.");
1251       AlignmentPanel origView = (AlignmentPanel) af.getAlignPanels().get(0);
1252       AlignmentPanel newview = af.newView(PCAVIEWNAME, true);
1253       // create another for good measure
1254       af.newView("Not the PCA View", true);
1255       PCAPanel pcaPanel = new PCAPanel(origView, "BLOSUM62",
1256               new SimilarityParams(true, true, true, false));
1257       // we're in the test exec thread, so we can just run synchronously here
1258       pcaPanel.run();
1259
1260       // now switch the linked view
1261       pcaPanel.selectAssociatedView(newview);
1262
1263       assertTrue(pcaPanel.getAlignViewport() == newview.getAlignViewport(),
1264               "PCA should be associated with 'With PCA' view: test is broken");
1265
1266       // now save and reload project
1267       Jalview2XML jv2xml = new jalview.project.Jalview2XML(false);
1268       tempfile.delete();
1269       jv2xml.saveState(tempfile);
1270       assertTrue(jv2xml.errorMessage == null,
1271               "Failed to save dummy project with PCA: test broken");
1272     }
1273
1274     // load again.
1275     Desktop.instance.closeAll_actionPerformed(null);
1276     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(
1277             tempfile.getCanonicalPath(), DataSourceType.FILE);
1278     JInternalFrame[] frames = Desktop.instance.getAllFrames();
1279     // PCA and the tabbed alignment view should be the only two windows on the
1280     // desktop
1281     assertEquals(frames.length, 2,
1282             "PCA and the tabbed alignment view should be the only two windows on the desktop");
1283     PCAPanel pcaPanel = (PCAPanel) frames[frames[0] == af ? 1 : 0];
1284
1285     AlignmentViewPanel restoredNewView = null;
1286     for (AlignmentViewPanel alignpanel : Desktop.getAlignmentPanels(null))
1287     {
1288       if (alignpanel.getAlignViewport() == pcaPanel.getAlignViewport())
1289       {
1290         restoredNewView = alignpanel;
1291       }
1292     }
1293     assertEquals(restoredNewView.getViewName(), PCAVIEWNAME);
1294     assertTrue(
1295             restoredNewView.getAlignViewport() == pcaPanel
1296                     .getAlignViewport(),
1297             "Didn't restore correct view association for the PCA view");
1298   }
1299
1300   /**
1301    * Test save and reload of DBRefEntry including GeneLocus in project
1302    * 
1303    * @throws Exception
1304    */
1305   @Test(groups = { "Functional" })
1306   public void testStoreAndRecoverGeneLocus() throws Exception
1307   {
1308     Desktop.instance.closeAll_actionPerformed(null);
1309     String seqData = ">P30419\nACDE\n>X1235\nGCCTGTGACGAA";
1310     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(seqData,
1311             DataSourceType.PASTE);
1312     assertNotNull(af, "Didn't read in the example file correctly.");
1313
1314     AlignmentViewPanel ap = Desktop.getAlignmentPanels(null)[0];
1315     SequenceI pep = ap.getAlignment().getSequenceAt(0);
1316     SequenceI cds = ap.getAlignment().getSequenceAt(1);
1317
1318     /*
1319      * give 'protein' a dbref to self, a dbref with map to CDS,
1320      * and a dbref with map to gene 'locus'
1321      */
1322     DBRefEntry dbref1 = new DBRefEntry("Uniprot", "1", "P30419", null);
1323     pep.addDBRef(dbref1);
1324     Mapping cdsmap = new Mapping(cds,
1325             new MapList(new int[]
1326             { 1, 4 }, new int[] { 1, 12 }, 1, 3));
1327     DBRefEntry dbref2 = new DBRefEntry("EMBLCDS", "2", "X1235", cdsmap);
1328     pep.addDBRef(dbref2);
1329     Mapping locusmap = new Mapping(null,
1330             new MapList(new int[]
1331             { 1, 4 }, new int[] { 2674123, 2674135 }, 1, 3));
1332     DBRefEntry dbref3 = new GeneLocus("human", "GRCh38", "5", locusmap);
1333     pep.addDBRef(dbref3);
1334
1335     File tfile = File.createTempFile("testStoreAndRecoverGeneLocus",
1336             ".jvp");
1337     try
1338     {
1339       new Jalview2XML(false).saveState(tfile);
1340     } catch (Throwable e)
1341     {
1342       Assert.fail("Didn't save the state", e);
1343     }
1344     Desktop.instance.closeAll_actionPerformed(null);
1345
1346     new FileLoader().LoadFileWaitTillLoaded(tfile.getAbsolutePath(),
1347             DataSourceType.FILE);
1348     AlignmentViewPanel rap = Desktop.getAlignmentPanels(null)[0];
1349     SequenceI rpep = rap.getAlignment().getSequenceAt(0);
1350     DBModList<DBRefEntry> dbrefs = rpep.getDBRefs();
1351     assertEquals(rpep.getName(), "P30419");
1352     assertEquals(dbrefs.size(), 3);
1353     DBRefEntry dbRef = dbrefs.get(0);
1354     assertFalse(dbRef instanceof GeneLocus);
1355     assertNull(dbRef.getMap());
1356     assertEquals(dbRef, dbref1);
1357
1358     /*
1359      * restored dbrefs with mapping have a different 'map to'
1360      * sequence but otherwise match the original dbrefs
1361      */
1362     dbRef = dbrefs.get(1);
1363     assertFalse(dbRef instanceof GeneLocus);
1364     assertTrue(dbRef.equalRef(dbref2));
1365     assertNotNull(dbRef.getMap());
1366     SequenceI rcds = rap.getAlignment().getSequenceAt(1);
1367     assertSame(dbRef.getMap().getTo(), rcds);
1368     // compare MapList but not map.to
1369     assertEquals(dbRef.getMap().getMap(), dbref2.getMap().getMap());
1370
1371     /*
1372      * GeneLocus map.to is null so can compare Mapping objects
1373      */
1374     dbRef = dbrefs.get(2);
1375     assertTrue(dbRef instanceof GeneLocus);
1376     assertEquals(dbRef, dbref3);
1377   }
1378
1379   /**
1380    * test store and recovery of Overview windows
1381    * 
1382    * @throws Exception
1383    */
1384   @Test(groups = { "Functional" }, enabled = true)
1385   public void testStoreAndRecoverOverview() throws Exception
1386   {
1387     Desktop.instance.closeAll_actionPerformed(null);
1388
1389     Cache.setProperty("SHOW_OVERVIEW", "false");
1390     Cache.setProperty(Preferences.USE_LEGACY_GAP, "false");
1391     Cache.setColourProperty(Preferences.GAP_COLOUR, Color.green);
1392     Cache.setColourProperty(Preferences.HIDDEN_COLOUR, Color.yellow);
1393     Cache.setProperty(Preferences.SHOW_OV_HIDDEN_AT_START, "true");
1394
1395     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(
1396             "examples/uniref50.fa", DataSourceType.FILE);
1397
1398     /*
1399      * open and resize / reposition overview 
1400      */
1401     af.overviewMenuItem_actionPerformed(null);
1402     OverviewPanel ov1 = af.alignPanel.getOverviewPanel();
1403     assertNotNull(ov1);
1404     ov1.setFrameBounds(20, 30, 200, 400);
1405     assertEquals(ov1.getTitle(), "Overview examples/uniref50.fa");
1406     assertTrue(ov1.isShowHiddenRegions());
1407
1408     /*
1409      * open a New View and its Overview and reposition it
1410      */
1411     af.newView_actionPerformed(null);
1412     af.overviewMenuItem_actionPerformed(null);
1413     OverviewPanel ov2 = af.alignPanel.getOverviewPanel();
1414     assertNotNull(ov2);
1415     assertNotSame(ov1, ov2);
1416     ov2.setFrameBounds(25, 35, 205, 405);
1417     assertEquals(ov1.getTitle(), "Overview examples/uniref50.fa Original");
1418     assertEquals(ov2.getTitle(), "Overview examples/uniref50.fa View 1");
1419
1420     File tfile = File.createTempFile("testStoreAndRecoverOverview", ".jvp");
1421     new Jalview2XML(false).saveState(tfile);
1422     Desktop.instance.closeAll_actionPerformed(null);
1423
1424     /*
1425      * change preferences (should _not_ affect reloaded Overviews)
1426      */
1427     Cache.setProperty("SHOW_OVERVIEW", "true");
1428     Cache.setProperty(Preferences.USE_LEGACY_GAP, "true");
1429     Cache.setColourProperty(Preferences.GAP_COLOUR, Color.blue);
1430     Cache.setColourProperty(Preferences.HIDDEN_COLOUR, Color.orange);
1431     Cache.setProperty(Preferences.SHOW_OV_HIDDEN_AT_START, "false");
1432
1433     af = new FileLoader().LoadFileWaitTillLoaded(tfile.getAbsolutePath(),
1434             DataSourceType.FILE);
1435
1436     /*
1437      * workaround: explicitly select View 1 (not in focus after restore)
1438      */
1439     af.tabSelectionChanged(1);
1440
1441     /*
1442      * verify restored overview for View 1
1443      */
1444     ov2 = af.alignPanel.getOverviewPanel();
1445     assertEquals(ov2.getCanvas().getGapColour(), Color.green);
1446     // 'non-legacy' colouring uses white for non-gapped residues
1447     assertEquals(ov2.getCanvas().getResidueColour(), Color.white);
1448     assertEquals(ov2.getCanvas().getHiddenColour(), Color.yellow);
1449     assertEquals(ov2.getTitle(), "Overview examples/uniref50.fa View 1");
1450     assertEquals(ov2.getFrameBounds(), new Rectangle(25, 35, 205, 405));
1451     assertTrue(ov2.isShowHiddenRegions());
1452
1453     /*
1454      * verify restored overview for Original view
1455      */
1456     af.tabSelectionChanged(0);
1457     ov1 = af.alignPanel.getOverviewPanel();
1458     assertEquals(ov1.getCanvas().getGapColour(), Color.green);
1459     // 'non-legacy' colouring uses white for non-gapped residues
1460     assertEquals(ov1.getCanvas().getResidueColour(), Color.white);
1461     assertEquals(ov1.getCanvas().getHiddenColour(), Color.yellow);
1462     assertEquals(ov1.getTitle(), "Overview examples/uniref50.fa Original");
1463     assertEquals(ov1.getFrameBounds(), new Rectangle(20, 30, 200, 400));
1464     assertTrue(ov1.isShowHiddenRegions());
1465   }
1466
1467   /**
1468    * Test that a view with no Overview is restored with no Overview, even if
1469    * 'Open Overview' is selected in Preferences
1470    * 
1471    * @throws Exception
1472    */
1473   @Test(groups = { "Functional" }, enabled = true)
1474   public void testStoreAndRecoverNoOverview() throws Exception
1475   {
1476     Cache.setProperty("SHOW_OVERVIEW", "false");
1477     Desktop.instance.closeAll_actionPerformed(null);
1478     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(
1479             ">seq1\nMATRSQFLVNF\n", DataSourceType.PASTE);
1480
1481     File tfile = File.createTempFile("testStoreAndRecoverOverview", ".jvp");
1482     new Jalview2XML(false).saveState(tfile);
1483     Desktop.instance.closeAll_actionPerformed(null);
1484
1485     Cache.setProperty("SHOW_OVERVIEW", "true");
1486     af = new FileLoader().LoadFileWaitTillLoaded(tfile.getAbsolutePath(),
1487             DataSourceType.FILE);
1488
1489     assertNull(af.alignPanel.getOverviewPanel());
1490   }
1491
1492   /**
1493    * Test that a view from an older version of Jalview is restored with Overview automatically shown when the preference is set
1494    * 
1495    * @throws Exception
1496    */
1497   @Test(groups = { "Functional" }, enabled = true)
1498   public void testAutoShowOverviewForLegacyProjects() throws Exception
1499   {
1500     Desktop.instance.closeAll_actionPerformed(null);
1501     Cache.setProperty("SHOW_OVERVIEW", "true");
1502     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(
1503             "examples/exampleFile.jvp", DataSourceType.FILE);
1504
1505     Cache.setProperty("SHOW_OVERVIEW", "false");
1506     assertNotNull(af.alignPanel.getOverviewPanel());
1507   }
1508
1509   /**
1510    * Test that loading example.jvp, doing some stuff, then hitting reload
1511    * doesn't leave the modified window still open
1512    * 
1513    * See JAL-4127 - interactively performing the same actions and reloading
1514    * works fine, but programmatically they do not
1515    * 
1516    * @throws Exception
1517    */
1518   @Test(groups = {"Functional"}, enabled=false)
1519   public void testReloadActuallyReloads() throws Exception
1520   {
1521     Desktop.instance.closeAll_actionPerformed(null);
1522     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(
1523             "examples/exampleFile.jvp", DataSourceType.FILE);
1524     af.getViewport().getColumnSelection().addElement(3);
1525     af.hideSelColumns_actionPerformed(null);
1526     af.newView("new", true);
1527     af.reload_actionPerformed(null);
1528     Thread.sleep(30);
1529     // af exists still but isn't shown
1530     assertTrue(af.isClosed());
1531   }
1532
1533   @Test(groups = { "Functional" })
1534   public void testPAEsaveRestore() throws Exception
1535   {
1536     Desktop.instance.closeAll_actionPerformed(null);
1537     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(
1538             ">seq1\nMATRSQFLVNF\n", DataSourceType.PASTE);
1539     AlignmentI al = af.getViewport().getAlignment();
1540     SequenceI sq = al.getSequenceAt(0);
1541     int i = sq.getLength();
1542     float[][] paevals = new float[i][i];
1543     for (i = i - 1; i >= 0; i--)
1544     {
1545       for (int j = 0; j <= i; j++)
1546       {
1547         paevals[i][j] = ((i - j < 2)
1548                 || ((i > 1 && i < 5) && (j > 1 && i < 5))) ? 1 : 0f;
1549         paevals[j][i] = paevals[i][j];
1550       }
1551     }
1552     PAEContactMatrix dummyMat = new PAEContactMatrix(sq, paevals);
1553     AlignmentAnnotation paeCm = sq.addContactList(dummyMat);
1554     al.addAnnotation(paeCm);
1555     File tfile = File.createTempFile("testStoreAndRecoverPAEmatrix",
1556             ".jvp");
1557     new Jalview2XML(false).saveState(tfile);
1558     Desktop.instance.closeAll_actionPerformed(null);
1559
1560     af = new FileLoader().LoadFileWaitTillLoaded(tfile.getAbsolutePath(),
1561             DataSourceType.FILE);
1562     AlignmentI newAl = af.getViewport().getAlignment();
1563     SequenceI newSeq = newAl.getSequenceAt(0);
1564     // check annotation of the expected type exists
1565     Assert.assertEquals(newSeq.getAnnotation().length, 1);
1566     Assert.assertEquals(newSeq.getAnnotation()[0].graph, paeCm.graph);
1567
1568     // check a contact matrix was recovered
1569     Assert.assertEquals(newSeq.getContactMaps().size(), 1);
1570     // and can be found for the annotation
1571     ContactMatrixI restoredMat = al
1572             .getContactMatrixFor(newSeq.getAnnotation()[0]);
1573     Assert.assertNotNull(restoredMat);
1574     for (i = sq.getLength() - 1; i >= 0; i--)
1575     {
1576       ContactListI oldCM = dummyMat.getContactList(i),
1577               newCM = restoredMat.getContactList(i);
1578       for (int j = oldCM.getContactHeight(); j >= 0; j--)
1579       {
1580         Assert.assertEquals(oldCM.getContactAt(j), newCM.getContactAt(j));
1581       }
1582     }
1583   }
1584
1585 }