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