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