JAL-2446 merged to spike branch
[jalview.git] / test / jalview / io / 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.io;
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.assertSame;
27 import static org.testng.Assert.assertTrue;
28
29 import jalview.api.AlignViewportI;
30 import jalview.api.AlignmentViewPanel;
31 import jalview.api.ViewStyleI;
32 import jalview.datamodel.AlignmentAnnotation;
33 import jalview.datamodel.AlignmentI;
34 import jalview.datamodel.HiddenSequences;
35 import jalview.datamodel.PDBEntry;
36 import jalview.datamodel.PDBEntry.Type;
37 import jalview.datamodel.SequenceCollectionI;
38 import jalview.datamodel.SequenceGroup;
39 import jalview.datamodel.SequenceI;
40 import jalview.gui.AlignFrame;
41 import jalview.gui.AlignViewport;
42 import jalview.gui.AlignmentPanel;
43 import jalview.gui.Desktop;
44 import jalview.gui.Jalview2XML;
45 import jalview.gui.JvOptionPane;
46 import jalview.gui.PopupMenu;
47 import jalview.gui.SliderPanel;
48 import jalview.renderer.ResidueShaderI;
49 import jalview.schemes.AnnotationColourGradient;
50 import jalview.schemes.BuriedColourScheme;
51 import jalview.schemes.ColourSchemeI;
52 import jalview.schemes.ColourSchemeProperty;
53 import jalview.schemes.JalviewColourScheme;
54 import jalview.schemes.RNAHelicesColour;
55 import jalview.schemes.StrandColourScheme;
56 import jalview.schemes.TCoffeeColourScheme;
57 import jalview.structure.StructureImportSettings;
58 import jalview.viewmodel.AlignmentViewport;
59
60 import java.io.File;
61 import java.io.IOException;
62 import java.util.ArrayList;
63 import java.util.HashMap;
64 import java.util.List;
65 import java.util.Map;
66
67 import org.testng.Assert;
68 import org.testng.AssertJUnit;
69 import org.testng.annotations.BeforeClass;
70 import org.testng.annotations.Test;
71
72 @Test(singleThreaded = true)
73 public class Jalview2xmlTests extends Jalview2xmlBase
74 {
75
76   @Override
77   @BeforeClass(alwaysRun = true)
78   public void setUpJvOptionPane()
79   {
80     JvOptionPane.setInteractiveMode(false);
81     JvOptionPane.setMockResponse(JvOptionPane.CANCEL_OPTION);
82   }
83
84   @Test(groups = { "Functional" })
85   public void testRNAStructureRecovery() throws Exception
86   {
87     String inFile = "examples/RF00031_folded.stk";
88     String tfile = File.createTempFile("JalviewTest", ".jvp")
89             .getAbsolutePath();
90     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(inFile,
91             DataSourceType.FILE);
92     assertNotNull(af, "Didn't read input file " + inFile);
93     int olddsann = countDsAnn(af.getViewport());
94     assertTrue(olddsann > 0, "Didn't find any dataset annotations");
95     af.changeColour_actionPerformed(JalviewColourScheme.RNAHelices
96             .toString());
97     assertTrue(
98             af.getViewport().getGlobalColourScheme() instanceof RNAHelicesColour,
99             "Couldn't apply RNA helices colourscheme");
100     assertTrue(af.saveAlignment(tfile, FileFormat.Jalview),
101             "Failed to store as a project.");
102     af.closeMenuItem_actionPerformed(true);
103     af = null;
104     af = new FileLoader()
105             .LoadFileWaitTillLoaded(tfile, DataSourceType.FILE);
106     assertNotNull(af, "Failed to import new project");
107     int newdsann = countDsAnn(af.getViewport());
108     assertEquals(olddsann, newdsann,
109             "Differing numbers of dataset sequence annotation\nOriginally "
110                     + olddsann + " and now " + newdsann);
111     System.out
112             .println("Read in same number of annotations as originally present ("
113                     + olddsann + ")");
114     assertTrue(
115
116     af.getViewport().getGlobalColourScheme() instanceof RNAHelicesColour,
117             "RNA helices colourscheme was not applied on import.");
118   }
119
120   @Test(groups = { "Functional" })
121   public void testTCoffeeScores() throws Exception
122   {
123     String inFile = "examples/uniref50.fa", inAnnot = "examples/uniref50.score_ascii";
124     String tfile = File.createTempFile("JalviewTest", ".jvp")
125             .getAbsolutePath();
126     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(inFile,
127             DataSourceType.FILE);
128     assertNotNull(af, "Didn't read input file " + inFile);
129     af.loadJalviewDataFile(inAnnot, DataSourceType.FILE, null, null);
130     assertSame(af.getViewport().getGlobalColourScheme().getClass(),
131             TCoffeeColourScheme.class, "Didn't set T-coffee colourscheme");
132     assertNotNull(ColourSchemeProperty.getColourScheme(af.getViewport()
133             .getAlignment(), af.getViewport().getGlobalColourScheme()
134             .getSchemeName()), "Recognise T-Coffee score from string");
135
136     assertTrue(af.saveAlignment(tfile, FileFormat.Jalview),
137             "Failed to store as a project.");
138     af.closeMenuItem_actionPerformed(true);
139     af = null;
140     af = new FileLoader()
141             .LoadFileWaitTillLoaded(tfile, DataSourceType.FILE);
142     assertNotNull(af, "Failed to import new project");
143     assertSame(af.getViewport().getGlobalColourScheme().getClass(),
144             TCoffeeColourScheme.class,
145             "Didn't set T-coffee colourscheme for imported project.");
146     System.out
147             .println("T-Coffee score shading successfully recovered from project.");
148   }
149
150   @Test(groups = { "Functional" })
151   public void testColourByAnnotScores() throws Exception
152   {
153     String inFile = "examples/uniref50.fa", inAnnot = "examples/testdata/uniref50_iupred.jva";
154     String tfile = File.createTempFile("JalviewTest", ".jvp")
155             .getAbsolutePath();
156     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(inFile,
157             DataSourceType.FILE);
158     assertNotNull(af, "Didn't read input file " + inFile);
159     af.loadJalviewDataFile(inAnnot, DataSourceType.FILE, null, null);
160     AlignmentAnnotation[] aa = af.getViewport().getAlignment()
161             .getSequenceAt(0).getAnnotation("IUPredWS (Short)");
162     assertTrue(
163
164     aa != null && aa.length > 0,
165             "Didn't find any IUPred annotation to use to shade alignment.");
166     AnnotationColourGradient cs = new AnnotationColourGradient(aa[0], null,
167             AnnotationColourGradient.ABOVE_THRESHOLD);
168     AnnotationColourGradient gcs = new AnnotationColourGradient(aa[0],
169             null, AnnotationColourGradient.BELOW_THRESHOLD);
170     cs.setSeqAssociated(true);
171     gcs.setSeqAssociated(true);
172     af.changeColour(cs);
173     SequenceGroup sg = new SequenceGroup();
174     sg.setStartRes(57);
175     sg.setEndRes(92);
176     sg.cs.setColourScheme(gcs);
177     af.getViewport().getAlignment().addGroup(sg);
178     sg.addSequence(af.getViewport().getAlignment().getSequenceAt(1), false);
179     sg.addSequence(af.getViewport().getAlignment().getSequenceAt(2), true);
180     af.alignPanel.alignmentChanged();
181     assertTrue(af.saveAlignment(tfile, FileFormat.Jalview),
182             "Failed to store as a project.");
183     af.closeMenuItem_actionPerformed(true);
184     af = null;
185     af = new FileLoader()
186             .LoadFileWaitTillLoaded(tfile, DataSourceType.FILE);
187     assertNotNull(af, "Failed to import new project");
188
189     // check for group and alignment colourschemes
190
191     ColourSchemeI _rcs = af.getViewport().getGlobalColourScheme();
192     ColourSchemeI _rgcs = af.getViewport().getAlignment().getGroups()
193             .get(0).getColourScheme();
194     assertNotNull(_rcs, "Didn't recover global colourscheme");
195     assertTrue(_rcs instanceof AnnotationColourGradient,
196             "Didn't recover annotation colour global scheme");
197     AnnotationColourGradient __rcs = (AnnotationColourGradient) _rcs;
198     assertTrue(__rcs.isSeqAssociated(),
199             "Annotation colourscheme wasn't sequence associated");
200
201     boolean diffseqcols = false, diffgseqcols = false;
202     SequenceI[] sqs = af.getViewport().getAlignment().getSequencesArray();
203     for (int p = 0, pSize = af.getViewport().getAlignment().getWidth(); p < pSize
204             && (!diffseqcols || !diffgseqcols); p++)
205     {
206       if (_rcs.findColour(sqs[0].getCharAt(p), p, sqs[0], null, 0f) != _rcs
207               .findColour(sqs[5].getCharAt(p), p, sqs[5], null, 0f))
208       {
209         diffseqcols = true;
210       }
211     }
212     assertTrue(diffseqcols, "Got Different sequence colours");
213     System.out
214             .println("Per sequence colourscheme (Background) successfully applied and recovered.");
215
216     assertNotNull(_rgcs, "Didn't recover group colourscheme");
217     assertTrue(_rgcs instanceof AnnotationColourGradient,
218             "Didn't recover annotation colour group colourscheme");
219     __rcs = (AnnotationColourGradient) _rgcs;
220     assertTrue(__rcs.isSeqAssociated(),
221             "Group Annotation colourscheme wasn't sequence associated");
222
223     for (int p = 0, pSize = af.getViewport().getAlignment().getWidth(); p < pSize
224             && (!diffseqcols || !diffgseqcols); p++)
225     {
226       if (_rgcs.findColour(sqs[1].getCharAt(p), p, sqs[1], null, 0f) != _rgcs
227               .findColour(sqs[2].getCharAt(p), p, sqs[2], null, 0f))
228       {
229         diffgseqcols = true;
230       }
231     }
232     assertTrue(diffgseqcols, "Got Different group sequence colours");
233     System.out
234             .println("Per sequence (Group) colourscheme successfully applied and recovered.");
235   }
236
237   @Test(groups = { "Functional" })
238   public void gatherViewsHere() throws Exception
239   {
240     int origCount = Desktop.getAlignFrames() == null ? 0 : Desktop
241             .getAlignFrames().length;
242     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(
243             "examples/exampleFile_2_7.jar", DataSourceType.FILE);
244     assertNotNull(af, "Didn't read in the example file correctly.");
245     assertTrue(Desktop.getAlignFrames().length == 1 + origCount,
246             "Didn't gather the views in the example file.");
247
248   }
249
250   @Test(groups = { "Functional" })
251   public void viewRefPdbAnnotation() throws Exception
252   {
253     StructureImportSettings.setProcessSecondaryStructure(true);
254     StructureImportSettings.setVisibleChainAnnotation(true);
255     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(
256             "examples/exampleFile_2_7.jar", DataSourceType.FILE);
257     assertNotNull(af, "Didn't read in the example file correctly.");
258     AlignmentViewPanel sps = null;
259     for (AlignmentViewPanel ap : af.alignPanel.alignFrame.getAlignPanels())
260     {
261       if ("Spinach Feredoxin Structure".equals(ap.getViewName()))
262       {
263         sps = ap;
264         break;
265       }
266     }
267     assertNotNull(sps, "Couldn't find the structure view");
268     AlignmentAnnotation refan = null;
269     for (AlignmentAnnotation ra : sps.getAlignment()
270             .getAlignmentAnnotation())
271     {
272       if (ra.graph != 0)
273       {
274         refan = ra;
275         break;
276       }
277     }
278     assertNotNull(refan, "Annotation secondary structure not found.");
279     SequenceI sq = sps.getAlignment().findName("1A70|");
280     assertNotNull(sq, "Couldn't find 1a70 null chain");
281     // compare the manually added temperature factor annotation
282     // to the track automatically transferred from the pdb structure on load
283     assertNotNull(sq.getDatasetSequence().getAnnotation(),
284             "1a70 has no annotation");
285     for (AlignmentAnnotation ala : sq.getDatasetSequence().getAnnotation())
286     {
287       AlignmentAnnotation alaa;
288       sq.addAlignmentAnnotation(alaa = new AlignmentAnnotation(ala));
289       alaa.adjustForAlignment();
290       if (ala.graph == refan.graph)
291       {
292         for (int p = 0; p < ala.annotations.length; p++)
293         {
294           sq.findPosition(p);
295           try
296           {
297             assertTrue(
298                     (alaa.annotations[p] == null && refan.annotations[p] == null)
299                             || alaa.annotations[p].value == refan.annotations[p].value,
300                     "Mismatch at alignment position " + p);
301           } catch (NullPointerException q)
302           {
303             Assert.fail("Mismatch of alignment annotations at position "
304                     + p + " Ref seq ann: " + refan.annotations[p]
305                     + " alignment " + alaa.annotations[p]);
306           }
307         }
308       }
309     }
310
311   }
312
313   @Test(groups = { "Functional" })
314   public void testCopyViewSettings() throws Exception
315   {
316     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(
317             "examples/exampleFile_2_7.jar", DataSourceType.FILE);
318     assertNotNull(af, "Didn't read in the example file correctly.");
319     AlignmentViewPanel sps = null, groups = null;
320     for (AlignmentViewPanel ap : af.alignPanel.alignFrame.getAlignPanels())
321     {
322       if ("Spinach Feredoxin Structure".equals(ap.getViewName()))
323       {
324         sps = ap;
325       }
326       if (ap.getViewName().contains("MAFFT"))
327       {
328         groups = ap;
329       }
330     }
331     assertNotNull(sps, "Couldn't find the structure view");
332     assertNotNull(groups, "Couldn't find the MAFFT view");
333
334     ViewStyleI structureStyle = sps.getAlignViewport().getViewStyle();
335     ViewStyleI groupStyle = groups.getAlignViewport().getViewStyle();
336     AssertJUnit.assertFalse(structureStyle.sameStyle(groupStyle));
337
338     groups.getAlignViewport().setViewStyle(structureStyle);
339     AssertJUnit.assertFalse(groupStyle.sameStyle(groups.getAlignViewport()
340             .getViewStyle()));
341     Assert.assertTrue(structureStyle.sameStyle(groups.getAlignViewport()
342             .getViewStyle()));
343
344   }
345
346   /**
347    * test store and recovery of expanded views
348    * 
349    * @throws Exception
350    */
351   @Test(groups = { "Functional" }, enabled = true)
352   public void testStoreAndRecoverExpandedviews() throws Exception
353   {
354     Desktop.instance.closeAll_actionPerformed(null);
355
356     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(
357             "examples/exampleFile_2_7.jar", DataSourceType.FILE);
358     Assert.assertEquals(Desktop.getAlignFrames().length, 1);
359     String afid = af.getViewport().getSequenceSetId();
360
361     // check FileLoader returned a reference to the one alignFrame that is
362     // actually on the Desktop
363     assertSame(
364             af,
365             Desktop.getAlignFrameFor(af.getViewport()),
366             "Jalview2XML.loadAlignFrame() didn't return correct AlignFrame reference for multiple view window");
367
368     Desktop.explodeViews(af);
369
370     int oldviews = Desktop.getAlignFrames().length;
371     Assert.assertEquals(Desktop.getAlignFrames().length,
372             Desktop.getAlignmentPanels(afid).length);
373     File tfile = File.createTempFile("testStoreAndRecoverExpanded", ".jvp");
374     try
375     {
376       new Jalview2XML(false).saveState(tfile);
377     } catch (Error e)
378     {
379       Assert.fail("Didn't save the expanded view state", e);
380     } catch (Exception e)
381     {
382       Assert.fail("Didn't save the expanded view state", e);
383     }
384     Desktop.instance.closeAll_actionPerformed(null);
385     if (Desktop.getAlignFrames() != null)
386     {
387       Assert.assertEquals(Desktop.getAlignFrames().length, 0);
388     }
389     af = new FileLoader().LoadFileWaitTillLoaded(tfile.getAbsolutePath(),
390             DataSourceType.FILE);
391     Assert.assertNotNull(af);
392     Assert.assertEquals(
393             Desktop.getAlignFrames().length,
394             Desktop.getAlignmentPanels(af.getViewport().getSequenceSetId()).length);
395     Assert.assertEquals(
396             Desktop.getAlignmentPanels(af.getViewport().getSequenceSetId()).length,
397             oldviews);
398   }
399
400   /**
401    * Test save and reload of a project with a different representative sequence
402    * in each view.
403    * 
404    * @throws Exception
405    */
406   @Test(groups = { "Functional" })
407   public void testStoreAndRecoverReferenceSeqSettings() throws Exception
408   {
409     Desktop.instance.closeAll_actionPerformed(null);
410     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(
411             "examples/exampleFile_2_7.jar", DataSourceType.FILE);
412     assertNotNull(af, "Didn't read in the example file correctly.");
413     String afid = af.getViewport().getSequenceSetId();
414
415     // remember reference sequence for each panel
416     Map<String, SequenceI> refseqs = new HashMap<String, SequenceI>();
417
418     /*
419      * mark sequence 2, 3, 4.. in panels 1, 2, 3...
420      * as reference sequence for itself and the preceding sequence
421      */
422     int n = 1;
423     for (AlignmentViewPanel ap : Desktop.getAlignmentPanels(afid))
424     {
425       AlignViewportI av = ap.getAlignViewport();
426       AlignmentI alignment = ap.getAlignment();
427       int repIndex = n % alignment.getHeight();
428       SequenceI rep = alignment.getSequenceAt(repIndex);
429       refseqs.put(ap.getViewName(), rep);
430
431       // code from mark/unmark sequence as reference in jalview.gui.PopupMenu
432       // todo refactor this to an alignment view controller
433       av.setDisplayReferenceSeq(true);
434       av.setColourByReferenceSeq(true);
435       av.getAlignment().setSeqrep(rep);
436
437       n++;
438     }
439     File tfile = File.createTempFile("testStoreAndRecoverReferenceSeq",
440             ".jvp");
441     try
442     {
443       new Jalview2XML(false).saveState(tfile);
444     } catch (Throwable e)
445     {
446       Assert.fail("Didn't save the expanded view state", e);
447     }
448     Desktop.instance.closeAll_actionPerformed(null);
449     if (Desktop.getAlignFrames() != null)
450     {
451       Assert.assertEquals(Desktop.getAlignFrames().length, 0);
452     }
453
454     af = new FileLoader().LoadFileWaitTillLoaded(tfile.getAbsolutePath(),
455             DataSourceType.FILE);
456     afid = af.getViewport().getSequenceSetId();
457
458     for (AlignmentViewPanel ap : Desktop.getAlignmentPanels(afid))
459     {
460       // check representative
461       AlignmentI alignment = ap.getAlignment();
462       SequenceI rep = alignment.getSeqrep();
463       Assert.assertNotNull(rep,
464               "Couldn't restore sequence representative from project");
465       // can't use a strong equals here, because by definition, the sequence IDs
466       // will be different.
467       // could set vamsas session save/restore flag to preserve IDs across
468       // load/saves.
469       Assert.assertEquals(refseqs.get(ap.getViewName()).toString(),
470               rep.toString(),
471               "Representative wasn't the same when recovered.");
472       Assert.assertTrue(ap.getAlignViewport().isDisplayReferenceSeq(),
473               "Display reference sequence view setting not set.");
474       Assert.assertTrue(ap.getAlignViewport().isColourByReferenceSeq(),
475               "Colour By Reference Seq view setting not set.");
476     }
477   }
478
479   @Test(groups = { "Functional" })
480   public void testIsVersionStringLaterThan()
481   {
482     /*
483      * No version / development / test / autobuild is leniently assumed to be
484      * compatible
485      */
486     assertTrue(Jalview2XML.isVersionStringLaterThan(null, null));
487     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3", null));
488     assertTrue(Jalview2XML.isVersionStringLaterThan(null, "2.8.3"));
489     assertTrue(Jalview2XML.isVersionStringLaterThan(null,
490             "Development Build"));
491     assertTrue(Jalview2XML.isVersionStringLaterThan(null,
492             "DEVELOPMENT BUILD"));
493     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3",
494             "Development Build"));
495     assertTrue(Jalview2XML.isVersionStringLaterThan(null, "Test"));
496     assertTrue(Jalview2XML.isVersionStringLaterThan(null, "TEST"));
497     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3", "Test"));
498     assertTrue(Jalview2XML
499             .isVersionStringLaterThan(null, "Automated Build"));
500     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3",
501             "Automated Build"));
502     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3",
503             "AUTOMATED BUILD"));
504
505     /*
506      * same version returns true i.e. compatible
507      */
508     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8", "2.8"));
509     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3", "2.8.3"));
510     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3b1", "2.8.3b1"));
511     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3B1", "2.8.3b1"));
512     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3b1", "2.8.3B1"));
513
514     /*
515      * later version returns true
516      */
517     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3", "2.8.4"));
518     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3", "2.9"));
519     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3", "2.9.2"));
520     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8", "2.8.3"));
521     assertTrue(Jalview2XML.isVersionStringLaterThan("2.8.3", "2.8.3b1"));
522
523     /*
524      * earlier version returns false
525      */
526     assertFalse(Jalview2XML.isVersionStringLaterThan("2.8.3", "2.8"));
527     assertFalse(Jalview2XML.isVersionStringLaterThan("2.8.4", "2.8.3"));
528     assertFalse(Jalview2XML.isVersionStringLaterThan("2.8.3b1", "2.8.3"));
529     assertFalse(Jalview2XML.isVersionStringLaterThan("2.8.3", "2.8.2b1"));
530     assertFalse(Jalview2XML.isVersionStringLaterThan("2.8.0b2", "2.8.0b1"));
531   }
532
533   /**
534    * Test save and reload of a project with a different sequence group (and
535    * representative sequence) in each view.
536    * 
537    * @throws Exception
538    */
539   @Test(groups = { "Functional" })
540   public void testStoreAndRecoverGroupRepSeqs() throws Exception
541   {
542     Desktop.instance.closeAll_actionPerformed(null);
543     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(
544             "examples/uniref50.fa", DataSourceType.FILE);
545     assertNotNull(af, "Didn't read in the example file correctly.");
546     String afid = af.getViewport().getSequenceSetId();
547     // make a second view of the alignment
548     af.newView_actionPerformed(null);
549
550     /*
551      * remember representative and hidden sequences marked 
552      * on each panel
553      */
554     Map<String, SequenceI> repSeqs = new HashMap<String, SequenceI>();
555     Map<String, List<String>> hiddenSeqNames = new HashMap<String, List<String>>();
556
557     /*
558      * mark sequence 2, 3, 4.. in panels 1, 2, 3...
559      * as reference sequence for itself and the preceding sequence
560      */
561     int n = 1;
562     for (AlignmentViewPanel ap : Desktop.getAlignmentPanels(afid))
563     {
564       AlignViewportI av = ap.getAlignViewport();
565       AlignmentI alignment = ap.getAlignment();
566       int repIndex = n % alignment.getHeight();
567       // ensure at least one preceding sequence i.e. index >= 1
568       repIndex = Math.max(repIndex, 1);
569       SequenceI repSeq = alignment.getSequenceAt(repIndex);
570       repSeqs.put(ap.getViewName(), repSeq);
571       List<String> hiddenNames = new ArrayList<String>();
572       hiddenSeqNames.put(ap.getViewName(), hiddenNames);
573
574       /*
575        * have rep sequence represent itself and the one before it
576        * this hides the group (except for the rep seq)
577        */
578       SequenceGroup sg = new SequenceGroup();
579       sg.addSequence(repSeq, false);
580       SequenceI precedingSeq = alignment.getSequenceAt(repIndex - 1);
581       sg.addSequence(precedingSeq, false);
582       sg.setSeqrep(repSeq);
583       assertTrue(sg.getSequences().contains(repSeq));
584       assertTrue(sg.getSequences().contains(precedingSeq));
585       av.setSelectionGroup(sg);
586       assertSame(repSeq, sg.getSeqrep());
587
588       /*
589        * represent group with sequence adds to a map of hidden rep sequences
590        * (it does not create a group on the alignment) 
591        */
592       ((AlignmentViewport) av).hideSequences(repSeq, true);
593       assertSame(repSeq, sg.getSeqrep());
594       assertTrue(sg.getSequences().contains(repSeq));
595       assertTrue(sg.getSequences().contains(precedingSeq));
596       assertTrue(alignment.getGroups().isEmpty(), "alignment has groups");
597       Map<SequenceI, SequenceCollectionI> hiddenRepSeqsMap = av
598               .getHiddenRepSequences();
599       assertNotNull(hiddenRepSeqsMap);
600       assertEquals(1, hiddenRepSeqsMap.size());
601       assertSame(sg, hiddenRepSeqsMap.get(repSeq));
602       assertTrue(alignment.getHiddenSequences().isHidden(precedingSeq));
603       assertFalse(alignment.getHiddenSequences().isHidden(repSeq));
604       hiddenNames.add(precedingSeq.getName());
605
606       n++;
607     }
608     File tfile = File
609             .createTempFile("testStoreAndRecoverGroupReps", ".jvp");
610     try
611     {
612       new Jalview2XML(false).saveState(tfile);
613     } catch (Throwable e)
614     {
615       Assert.fail("Didn't save the expanded view state", e);
616     }
617     Desktop.instance.closeAll_actionPerformed(null);
618     if (Desktop.getAlignFrames() != null)
619     {
620       Assert.assertEquals(Desktop.getAlignFrames().length, 0);
621     }
622
623     af = new FileLoader().LoadFileWaitTillLoaded(tfile.getAbsolutePath(),
624             DataSourceType.FILE);
625     afid = af.getViewport().getSequenceSetId();
626
627     for (AlignmentViewPanel ap : Desktop.getAlignmentPanels(afid))
628     {
629       String viewName = ap.getViewName();
630       AlignViewportI av = ap.getAlignViewport();
631       AlignmentI alignment = ap.getAlignment();
632       List<SequenceGroup> groups = alignment.getGroups();
633       assertNotNull(groups);
634       assertTrue(groups.isEmpty(), "Alignment has groups");
635       Map<SequenceI, SequenceCollectionI> hiddenRepSeqsMap = av
636               .getHiddenRepSequences();
637       assertNotNull(hiddenRepSeqsMap, "No hidden represented sequences");
638       assertEquals(1, hiddenRepSeqsMap.size());
639       assertEquals(repSeqs.get(viewName).getDisplayId(true),
640               hiddenRepSeqsMap.keySet().iterator().next()
641                       .getDisplayId(true));
642
643       /*
644        * verify hidden sequences in restored panel
645        */
646       List<String> hidden = hiddenSeqNames.get(ap.getViewName());
647       HiddenSequences hs = alignment.getHiddenSequences();
648       assertEquals(
649               hidden.size(),
650               hs.getSize(),
651               "wrong number of restored hidden sequences in "
652                       + ap.getViewName());
653     }
654   }
655
656   /**
657    * Test save and reload of PDBEntry in Jalview project
658    * 
659    * @throws Exception
660    */
661   @Test(groups = { "Functional" })
662   public void testStoreAndRecoverPDBEntry() throws Exception
663   {
664     Desktop.instance.closeAll_actionPerformed(null);
665     String exampleFile = "examples/3W5V.pdb";
666     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(exampleFile,
667             DataSourceType.FILE);
668     assertNotNull(af, "Didn't read in the example file correctly.");
669     String afid = af.getViewport().getSequenceSetId();
670
671     AlignmentPanel[] alignPanels = Desktop.getAlignmentPanels(afid);
672     System.out.println();
673     AlignmentViewPanel ap = alignPanels[0];
674     String tfileBase = new File(".").getAbsolutePath().replace(".", "");
675     String testFile = tfileBase + exampleFile;
676     AlignmentI alignment = ap.getAlignment();
677     System.out.println("blah");
678     SequenceI[] seqs = alignment.getSequencesArray();
679     Assert.assertNotNull(seqs[0]);
680     Assert.assertNotNull(seqs[1]);
681     Assert.assertNotNull(seqs[2]);
682     Assert.assertNotNull(seqs[3]);
683     Assert.assertNotNull(seqs[0].getDatasetSequence());
684     Assert.assertNotNull(seqs[1].getDatasetSequence());
685     Assert.assertNotNull(seqs[2].getDatasetSequence());
686     Assert.assertNotNull(seqs[3].getDatasetSequence());
687     PDBEntry[] pdbEntries = new PDBEntry[4];
688     pdbEntries[0] = new PDBEntry("3W5V", "A", Type.PDB, testFile);
689     pdbEntries[1] = new PDBEntry("3W5V", "B", Type.PDB, testFile);
690     pdbEntries[2] = new PDBEntry("3W5V", "C", Type.PDB, testFile);
691     pdbEntries[3] = new PDBEntry("3W5V", "D", Type.PDB, testFile);
692     Assert.assertEquals(seqs[0].getDatasetSequence().getAllPDBEntries()
693             .get(0), pdbEntries[0]);
694     Assert.assertEquals(seqs[1].getDatasetSequence().getAllPDBEntries()
695             .get(0), pdbEntries[1]);
696     Assert.assertEquals(seqs[2].getDatasetSequence().getAllPDBEntries()
697             .get(0), pdbEntries[2]);
698     Assert.assertEquals(seqs[3].getDatasetSequence().getAllPDBEntries()
699             .get(0), pdbEntries[3]);
700
701     File tfile = File.createTempFile("testStoreAndRecoverPDBEntry", ".jvp");
702     try
703     {
704       new Jalview2XML(false).saveState(tfile);
705     } catch (Throwable e)
706     {
707       Assert.fail("Didn't save the state", e);
708     }
709     Desktop.instance.closeAll_actionPerformed(null);
710     if (Desktop.getAlignFrames() != null)
711     {
712       Assert.assertEquals(Desktop.getAlignFrames().length, 0);
713     }
714
715     AlignFrame restoredFrame = new FileLoader().LoadFileWaitTillLoaded(
716             tfile.getAbsolutePath(), DataSourceType.FILE);
717     String rfid = restoredFrame.getViewport().getSequenceSetId();
718     AlignmentPanel[] rAlignPanels = Desktop.getAlignmentPanels(rfid);
719     AlignmentViewPanel rap = rAlignPanels[0];
720     AlignmentI rAlignment = rap.getAlignment();
721     System.out.println("blah");
722     SequenceI[] rseqs = rAlignment.getSequencesArray();
723     Assert.assertNotNull(rseqs[0]);
724     Assert.assertNotNull(rseqs[1]);
725     Assert.assertNotNull(rseqs[2]);
726     Assert.assertNotNull(rseqs[3]);
727     Assert.assertNotNull(rseqs[0].getDatasetSequence());
728     Assert.assertNotNull(rseqs[1].getDatasetSequence());
729     Assert.assertNotNull(rseqs[2].getDatasetSequence());
730     Assert.assertNotNull(rseqs[3].getDatasetSequence());
731
732     // The Asserts below are expected to fail until the PDB chainCode is
733     // recoverable from a Jalview projects
734     for (int chain = 0; chain < 4; chain++)
735     {
736       PDBEntry recov = rseqs[chain].getDatasetSequence().getAllPDBEntries()
737               .get(0);
738       PDBEntry expected = pdbEntries[chain];
739       Assert.assertEquals(recov.getId(), expected.getId(),
740               "Mismatch PDB ID");
741       Assert.assertEquals(recov.getChainCode(), expected.getChainCode(),
742               "Mismatch PDB ID");
743       Assert.assertEquals(recov.getType(), expected.getType(),
744               "Mismatch PDBEntry 'Type'");
745       Assert.assertNotNull(recov.getFile(),
746               "Recovered PDBEntry should have a non-null file entry");
747     }
748   }
749
750   /**
751    * Configure an alignment and a sub-group each with distinct colour schemes,
752    * Conservation and PID thresholds, and confirm these are restored from the
753    * saved project.
754    * 
755    * @throws IOException
756    */
757   @Test(groups = { "Functional" })
758   public void testStoreAndRecoverColourThresholds() throws IOException
759   {
760     Desktop.instance.closeAll_actionPerformed(null);
761     AlignFrame af = new FileLoader().LoadFileWaitTillLoaded(
762             "examples/uniref50.fa", DataSourceType.FILE);
763
764     AlignViewport av = af.getViewport();
765     AlignmentI al = av.getAlignment();
766
767     /*
768      * Colour alignment by Buried Index, Above 10% PID, By Conservation 20%
769      */
770     af.changeColour_actionPerformed(JalviewColourScheme.Buried.toString());
771     assertTrue(av.getGlobalColourScheme() instanceof BuriedColourScheme);
772     af.abovePIDThreshold_actionPerformed(true);
773     SliderPanel sp = SliderPanel.getSliderPanel();
774     assertFalse(sp.isForConservation());
775     sp.valueChanged(10);
776     af.conservationMenuItem_actionPerformed(true);
777     sp = SliderPanel.getSliderPanel();
778     assertTrue(sp.isForConservation());
779     sp.valueChanged(20);
780     ResidueShaderI rs = av.getResidueShading();
781     assertEquals(rs.getThreshold(), 10);
782     assertTrue(rs.conservationApplied());
783     assertEquals(rs.getConservationInc(), 20);
784
785     /*
786      * create a group with Strand colouring, 30% Conservation
787      * and 40% PID threshold
788      */
789     SequenceGroup sg = new SequenceGroup();
790     sg.addSequence(al.getSequenceAt(0), false);
791     sg.setStartRes(15);
792     sg.setEndRes(25);
793     av.setSelectionGroup(sg);
794     PopupMenu popupMenu = new PopupMenu(af.alignPanel, null, null);
795     popupMenu.changeColour_actionPerformed(JalviewColourScheme.Strand
796             .toString());
797     assertTrue(sg.getColourScheme() instanceof StrandColourScheme);
798     assertEquals(al.getGroups().size(), 1);
799     assertSame(al.getGroups().get(0), sg);
800     popupMenu.conservationMenuItem_actionPerformed(true);
801     sp = SliderPanel.getSliderPanel();
802     assertTrue(sp.isForConservation());
803     sp.valueChanged(30);
804     popupMenu.abovePIDColour_actionPerformed(true);
805     sp = SliderPanel.getSliderPanel();
806     assertFalse(sp.isForConservation());
807     sp.valueChanged(40);
808     assertTrue(sg.getGroupColourScheme().conservationApplied());
809     assertEquals(sg.getGroupColourScheme().getConservationInc(), 30);
810     assertEquals(sg.getGroupColourScheme().getThreshold(), 40);
811
812     /*
813      * save project, close windows, reload project, verify
814      */
815     File tfile = File.createTempFile("testStoreAndRecoverColourThresholds",
816             ".jvp");
817     tfile.deleteOnExit();
818     new Jalview2XML(false).saveState(tfile);
819     Desktop.instance.closeAll_actionPerformed(null);
820     af = new FileLoader().LoadFileWaitTillLoaded(tfile.getAbsolutePath(),
821             DataSourceType.FILE);
822     Assert.assertNotNull(af, "Failed to reload project");
823
824     /*
825      * verify alignment (background) colouring
826      */
827     rs = af.getViewport().getResidueShading();
828     assertTrue(rs.getColourScheme() instanceof BuriedColourScheme);
829     assertEquals(rs.getThreshold(), 10);
830     assertTrue(rs.conservationApplied());
831     assertEquals(rs.getConservationInc(), 20);
832
833     /*
834      * verify group colouring
835      */
836     assertEquals(1, af.getViewport().getAlignment().getGroups().size(), 1);
837     rs = af.getViewport().getAlignment().getGroups().get(0)
838             .getGroupColourScheme();
839     assertTrue(rs.getColourScheme() instanceof StrandColourScheme);
840     assertEquals(rs.getThreshold(), 40);
841     assertTrue(rs.conservationApplied());
842     assertEquals(rs.getConservationInc(), 30);
843   }
844 }