JAL-2154 - rejig test pass code for breadth-first (or top down) repetition of fetch...
[jalview.git] / test / jalview / io / CrossRef2xmlTests.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 jalview.analysis.CrossRef;
24 import jalview.api.AlignmentViewPanel;
25 import jalview.datamodel.AlignedCodonFrame;
26 import jalview.datamodel.AlignmentI;
27 import jalview.datamodel.AlignmentTest;
28 import jalview.datamodel.SequenceI;
29 import jalview.gui.AlignFrame;
30 import jalview.gui.CrossRefAction;
31 import jalview.gui.Desktop;
32 import jalview.gui.Jalview2XML;
33
34 import java.io.File;
35 import java.io.IOException;
36 import java.util.ArrayList;
37 import java.util.HashMap;
38 import java.util.List;
39
40 import org.testng.Assert;
41 import org.testng.annotations.Test;
42
43 @Test(singleThreaded = true)
44 public class CrossRef2xmlTests extends Jalview2xmlBase
45 {
46
47   /**
48    * test store and recovery of expanded views
49    * 
50    * @throws Exception
51    */
52   @Test(groups = { "Operational" }, enabled = true)
53   public void testRetrieveAndShowCrossref() throws Exception
54   {
55     // for every set of db queries
56     // retrieve db query
57     // verify presence of expected xrefs
58     // show xrefs - verify expected type of frame is shown for each xref
59     // show xrefs again
60     // - verify original -> xref -> xref(original) recovers frame containing at
61     // least the first retrieved sequence
62     // store
63     // 1. whole project
64     // 2. individual frames
65     // 3. load each one back and verify
66     // . aligned sequences (.toString() )
67     // . xrefs (.toString() )
68     // . codonframes
69     //
70     //
71     HashMap<String, String> dbtoviewBit = new HashMap<String, String>();
72     List<String> keyseq = new ArrayList<String>();
73     HashMap<String, File> savedProjects = new HashMap<String, File>();
74
75     for (String[] did : new String[][] { { "UNIPROT", "P01731" } })
76     {
77       // pass counters - 0 - first pass, 1 means retrieve project rather than
78       // perform action
79       int pass1 = 0, pass2 = 0, pass3 = 0;
80       // each do loop performs two iterations in the first outer loop pass, but
81       // only performs one iteration on the second outer loop
82       // ie. pass 1 = 0 {pass 2= 0 { pass 3 = 0,1 }, pass 2=1 { pass 3 = 0 }}, 1
83       // { pass 2 = 0 { pass 3 = 0 } }
84       do
85       {
86         String first = did[0] + " " + did[1];
87         AlignFrame af = null;
88         boolean dna;
89         AlignmentI retral;
90         AlignmentI dataset;
91         SequenceI[] seqs;
92         List<String> ptypes = null;
93         if (pass1 == 0)
94         {
95           // retrieve dbref
96
97           keyseq.add(first);
98
99           af = jalview.gui.SequenceFetcher.fetchAndShow(did[0], did[1])
100                   .get(0);
101           Assert.assertTrue(af != null, "Didn't retrieve " + first);
102
103           // verify references for retrieved data
104           AlignmentTest.assertAlignmentDatasetRefs(af.getViewport()
105                   .getAlignment(), "Pass (" + pass1 + "," + pass2 + ","
106                   + pass3 + "): Fetch " + first + ":");
107           dna = af.getViewport().getAlignment().isNucleotide();
108           retral = af.getViewport().getAlignment();
109           dataset = retral.getDataset();
110           seqs = retral.getSequencesArray();
111
112         }
113         else
114         {
115           Desktop.instance.closeAll_actionPerformed(null);
116           // recover stored project
117           af = new FileLoader(false).LoadFileWaitTillLoaded(savedProjects
118                   .get(first).toString(), FormatAdapter.FILE);
119           System.out.println("Recovered view for '" + first + "' from '"
120                   + savedProjects.get(first).toString() + "'");
121           dna = af.getViewport().getAlignment().isNucleotide();
122           retral = af.getViewport().getAlignment();
123           dataset = retral.getDataset();
124           seqs = retral.getSequencesArray();
125
126           // verify references for recovered data
127           AlignmentTest.assertAlignmentDatasetRefs(af.getViewport()
128                   .getAlignment(), "Pass (" + pass1 + "," + pass2 + ","
129                   + pass3 + "): Recover " + first + ":");
130
131         }
132
133         // store project on first pass, compare next pass
134         stringify(dbtoviewBit, savedProjects, first, af.alignPanel);
135
136         ptypes = (seqs == null || seqs.length == 0) ? null : new CrossRef(
137                 seqs, dataset).findXrefSourcesForSequences(dna);
138
139         // start of pass2: retrieve each cross-ref for fetched or restored
140         // project.
141         do // first cross ref and recover crossref loop
142         {
143
144           for (String db : ptypes)
145           {
146             // counter for splitframe views retrieved via crossref
147             int firstcr_ap = 0;
148             // build next key so we an retrieve all views
149             String nextxref = first + " -> " + db + "{" + firstcr_ap + "}";
150             // perform crossref action, or retrieve stored project
151             List<AlignmentViewPanel> cra_views = new ArrayList<AlignmentViewPanel>();
152             CrossRefAction cra = null;
153             
154             if (pass2 == 0)
155             { // retrieve and show cross-refs in this thread
156               cra = new CrossRefAction(af, seqs, dna, db);
157               cra.run();
158               Assert.assertTrue(cra.getXrefViews().size() > 0,
159                       "No crossrefs retrieved for " + db);
160               cra_views = cra.getXrefViews();
161             }
162             else
163             {
164               Desktop.instance.closeAll_actionPerformed(null);
165               pass3 = 0;
166               // recover stored project
167               AlignFrame af2 = new FileLoader(false)
168                       .LoadFileWaitTillLoaded(savedProjects.get(nextxref)
169                               .toString(), FormatAdapter.FILE);
170               System.out.println("Recovered view for '" + nextxref
171                       + "' from '" + savedProjects.get(nextxref).toString()
172                       + "'");
173               // gymnastics to recover the alignPanel/Complementary alignPanel
174               if (af2.getViewport().isNucleotide())
175               {
176                 // top view, then bottom
177                 cra_views.add(af2.getViewport().getAlignPanel());
178                 cra_views.add(((jalview.gui.AlignViewport) af2
179                         .getViewport().getCodingComplement())
180                         .getAlignPanel());
181
182               }
183               else
184               {
185                 // bottom view, then top
186                 cra_views.add(((jalview.gui.AlignViewport) af2
187                         .getViewport().getCodingComplement())
188                         .getAlignPanel());
189                 cra_views.add(af2.getViewport().getAlignPanel());
190
191               }
192             }
193             HashMap<String, List<String>> xrptypes = new HashMap<String, List<String>>();
194             // first save/verify views.
195             for (AlignmentViewPanel avp : cra_views)
196             {
197               nextxref = first + " -> " + db + "{" + firstcr_ap++ + "}";
198               // verify references for this panel
199               AlignmentTest.assertAlignmentDatasetRefs(avp.getAlignment(),
200                       "Pass (" + pass1 + "," + pass2 + "," + pass3
201                               + "): before start of pass3: " + nextxref
202                               + ":");
203
204               SequenceI[] xrseqs = avp.getAlignment().getSequencesArray();
205
206               List<String> _xrptypes = (seqs == null || seqs.length == 0) ? null
207                       : new CrossRef(xrseqs, dataset)
208                               .findXrefSourcesForSequences(avp
209                                       .getAlignViewport().isNucleotide());
210               
211               stringify(dbtoviewBit, savedProjects, nextxref, avp);
212               xrptypes.put(nextxref, _xrptypes);
213
214             }
215
216             // now do the second xref pass starting from either saved or just
217             // recovered split pane, in sequence
218             do // retrieve second set of cross refs or recover and verify
219             {
220               firstcr_ap = 0;
221               for (AlignmentViewPanel avp : cra_views)
222               {
223                 nextxref = first + " -> " + db + "{" + firstcr_ap++ + "}";
224                 for (String xrefdb : xrptypes.get(nextxref))
225                 {
226                   List<AlignmentViewPanel> cra_views2 = new ArrayList<AlignmentViewPanel>();
227                   int q = 0;
228                   String nextnextxref = nextxref
229                           + " -> " + xrefdb + "{" + q + "}";
230
231                   if (pass3 == 0)
232                   {
233
234                     SequenceI[] xrseqs = avp.getAlignment()
235                             .getSequencesArray();
236                     AlignFrame nextaf = Desktop.getAlignFrameFor(avp
237                             .getAlignViewport());
238
239                     cra = new CrossRefAction(nextaf, xrseqs, avp
240                             .getAlignViewport().isNucleotide(), xrefdb);
241                     cra.run();
242                     Assert.assertTrue(
243                             cra.getXrefViews().size() > 0,
244                             "No crossrefs found for '" + nextnextxref
245                                     + "' to " + xrefdb + " via '"
246                                     + nextaf.getTitle() + "'");
247                     cra_views2 = cra.getXrefViews();
248                   }
249                   else
250                   {
251                     Desktop.instance.closeAll_actionPerformed(null);
252                     // recover stored project
253                     AlignFrame af2 = new FileLoader(false)
254                             .LoadFileWaitTillLoaded(
255                                     savedProjects.get(nextnextxref)
256                                             .toString(), FormatAdapter.FILE);
257                     System.out.println("Recovered view for '"
258                             + nextnextxref + "' from '"
259                             + savedProjects.get(nextnextxref).toString()
260                             + "'");
261                     // gymnastics to recover the alignPanel/Complementary
262                     // alignPanel
263                     if (af2.getViewport().isNucleotide())
264                     {
265                       // top view, then bottom
266                       cra_views2.add(af2.getViewport().getAlignPanel());
267                       cra_views2.add(((jalview.gui.AlignViewport) af2
268                               .getViewport().getCodingComplement())
269                               .getAlignPanel());
270
271                     }
272                     else
273                     {
274                       // bottom view, then top
275                       cra_views2.add(((jalview.gui.AlignViewport) af2
276                               .getViewport().getCodingComplement())
277                               .getAlignPanel());
278                       cra_views2.add(af2.getViewport().getAlignPanel());
279                     }
280                     Assert.assertEquals(cra_views2.size(), 2);
281                     Assert.assertNotNull(cra_views2.get(0));
282                     Assert.assertNotNull(cra_views2.get(1));
283                   }
284
285                   for (AlignmentViewPanel nextavp : cra_views2)
286                   {
287                     nextnextxref = nextxref
288                             + " -> " + xrefdb + "{" + q++ + "}";
289
290                     // verify references for this panel
291                     AlignmentTest.assertAlignmentDatasetRefs(
292                             nextavp.getAlignment(), "" + "Pass (" + pass1
293                                     + "," + pass2 + "): For "
294                                     + nextnextxref + ":");
295
296                     stringify(dbtoviewBit, savedProjects, nextnextxref,
297                             nextavp);
298                     keyseq.add(nextnextxref);
299                   }
300                 } // end of loop around showing all xrefdb for crossrf2
301
302               } // end of loop around all viewpanels from crossrf1
303             } while (pass2 == 2 && pass3++ < 2);
304             // fetchdb->crossref1->crossref-2->verify for xrefs we
305             // either loop twice when pass2=0, or just once when pass2=1
306             // (recovered project from previous crossref)
307
308           } // end of loop over db-xrefs for crossref-2
309
310           // fetchdb-->crossref1
311           // for each xref we try to retrieve xref, store and verify when
312           // pass1=0, or just retrieve and verify when pass1=1
313         } while (pass1 == 1 && pass2++ < 2);
314         // fetchdb
315         // for each ref we
316         // loop twice: first, do the retrieve, second recover from saved project
317
318         // increment pass counters, so we repeat traversal starting from the
319         // oldest saved project first.
320         if (pass1 == 0)
321         {
322           // verify stored projects for first set of cross references
323           pass1 = 1;
324           // and verify cross-references retrieved from stored projects
325           pass2 = 0;
326           pass3 = 0;
327         }
328         else
329         {
330           // verify stored projects for second set of cross references
331           pass2 = 1;
332           // and verify cross-references retrievable from those stored projects.
333           pass3 = 0;
334         }
335       } while (pass3 < 2);
336     }
337   }
338
339   /**
340    * first time called, record strings derived from alignment and
341    * alignedcodonframes, and save view to a project file. Second time called,
342    * compare strings to existing ones. org.testng.Assert.assertTrue on
343    * stringmatch
344    * 
345    * @param dbtoviewBit
346    *          map between xrefpath and view string
347    * @param savedProjects
348    *          - map from xrefpath to saved project filename (createTempFile)
349    * @param xrefpath
350    *          - xrefpath - unique ID for this context (composed of sequence of
351    *          db-fetch/cross-ref actions preceeding state)
352    * @param avp
353    *          - viewpanel to store (for viewpanels in splitframe, the same
354    *          project should be written for both panels, only one needs
355    *          recovering for comparison on the next stringify call, but each
356    *          viewpanel needs to be called with a distinct xrefpath to ensure
357    *          each one's strings are compared)
358    */
359   private void stringify(HashMap<String, String> dbtoviewBit,
360           HashMap<String, File> savedProjects, String xrefpath,
361           AlignmentViewPanel avp)
362   {
363     if (savedProjects != null)
364     {
365       if (savedProjects.get(xrefpath) == null)
366       {
367         // write a project file for this view. On the second pass, this will be
368         // recovered and cross-references verified
369         try
370         {
371           File prfile = File.createTempFile("crossRefTest", ".jvp");
372           AlignFrame af = Desktop.getAlignFrameFor(avp.getAlignViewport());
373           new Jalview2XML(false).saveAlignment(af, prfile.toString(),
374                   af.getTitle());
375           System.out.println("Written view from '" + xrefpath + "' as '"
376                   + prfile.getAbsolutePath() + "'");
377           savedProjects.put(xrefpath, prfile);
378         } catch (IOException q)
379         {
380           Assert.fail("Unexpected IO Exception", q);
381         }
382       }
383       else
384       {
385         System.out.println("Stringify check on view from '" + xrefpath
386                 + "' [ possibly retrieved from '"
387                 + savedProjects.get(xrefpath).getAbsolutePath() + "' ]");
388
389       }
390     }
391
392     StringBuilder sbr = new StringBuilder();
393     sbr.append(avp.getAlignment().toString());
394     sbr.append("\n");
395     sbr.append("<End of alignment>");
396     sbr.append("\n");
397     sbr.append(avp.getAlignment().getDataset());
398     sbr.append("\n");
399     sbr.append("<End of dataset>");
400     sbr.append("\n");
401     int p = 0;
402     if (avp.getAlignment().getCodonFrames() != null)
403     {
404       for (AlignedCodonFrame ac : avp.getAlignment().getCodonFrames())
405       {
406         sbr.append("<AlignedCodonFrame " + p++ + ">");
407         sbr.append("\n");
408         sbr.append(ac.toString());
409         sbr.append("\n");
410       }
411     }
412     String dbt = dbtoviewBit.get(xrefpath);
413     if (dbt == null)
414     {
415       dbtoviewBit.put(xrefpath, sbr.toString());
416     }
417     else
418     {
419       Assert.assertEquals(sbr.toString(), dbt, "stringify mismatch for "
420               + xrefpath);
421     }
422   }
423 }