JAL-2154 fix looping structure so for a particular pass (either 2-pass: retrieve...
[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         if (pass1 == 0)
91         {
92           // retrieve dbref
93
94           keyseq.add(first);
95
96           af = jalview.gui.SequenceFetcher.fetchAndShow(did[0], did[1])
97                   .get(0);
98           assertTrue("Didn't retrieve " + first, af != null);
99
100           // verify references for retrieved data
101           AlignmentTest.assertAlignmentDatasetRefs(af.getViewport()
102                   .getAlignment(), "Pass (" + pass1 + "," + pass2 + ","
103                   + pass3 + "): Fetch " + first + ":");
104
105           // store project to recover on next pass
106           stringify(dbtoviewBit, savedProjects, first, af.alignPanel);
107         }
108         else
109         {
110           Desktop.instance.closeAll_actionPerformed(null);
111           // recover stored project
112           af = new FileLoader(false).LoadFileWaitTillLoaded(savedProjects
113                   .get(first).toString(), FormatAdapter.FILE);
114
115           // verify references for recovered data
116           AlignmentTest.assertAlignmentDatasetRefs(af.getViewport()
117                   .getAlignment(), "Pass (" + pass1 + "," + pass2 + ","
118                   + pass3 + "): Recover " + first + ":");
119
120         }
121
122         boolean dna = af.getViewport().getAlignment().isNucleotide();
123         AlignmentI retral = af.getViewport().getAlignment();
124         AlignmentI dataset = retral.getDataset();
125         SequenceI[] seqs = retral.getSequencesArray();
126         List<String> ptypes = (seqs == null || seqs.length == 0) ? null
127                 : new CrossRef(seqs, dataset)
128                         .findXrefSourcesForSequences(dna);
129
130         pass2 = 0;
131         do // second cross ref and recover crossref loop
132         {
133         for (String db : ptypes)
134         {
135             // counter for splitframe views retrieved via crossref
136             int p = 0;
137             // build next key so we an retrieve all views
138             String nextxref = first + " -> " + db + "{" + p + "}";
139             // perform crossref action, or retrieve stored project
140             List<AlignmentViewPanel> cra_views = new ArrayList<AlignmentViewPanel>();
141             CrossRefAction cra = null;
142             if (pass2 == 0)
143             { // retrieve and show cross-refs in this thread
144               cra = new CrossRefAction(af, seqs, dna, db);
145               cra.run();
146               Assert.assertTrue(cra.getXrefViews().size() > 0,
147                       "No crossrefs retrieved for " + db);
148               cra_views = cra.getXrefViews();
149             }
150             else
151             {
152               Desktop.instance.closeAll_actionPerformed(null);
153               // recover stored project
154               AlignFrame af2 = new FileLoader(false)
155                       .LoadFileWaitTillLoaded(savedProjects.get(nextxref)
156                               .toString(), FormatAdapter.FILE);
157               // gymnastics to recover the alignPanel/Complementary alignPanel
158               if (af2.getViewport().isNucleotide())
159               {
160                 // top view, then bottom
161                 cra_views.add(af2.getViewport().getAlignPanel());
162                 cra_views.add(((jalview.gui.AlignViewport) af2
163                         .getViewport().getCodingComplement())
164                         .getAlignPanel());
165
166               }
167               else
168               {
169                 // bottom view, then top
170                 cra_views.add(((jalview.gui.AlignViewport) af2
171                         .getViewport().getCodingComplement())
172                         .getAlignPanel());
173                 cra_views.add(af2.getViewport().getAlignPanel());
174
175               }
176             }
177             for (AlignmentViewPanel avp : cra_views)
178             {
179               nextxref = first + " -> " + db + "{" + p++ + "}";
180
181               // verify references for this panel
182               AlignmentTest.assertAlignmentDatasetRefs(avp.getAlignment(),
183                       "" + "Pass (" + pass1 + "," + pass2 + "): For "
184                               + nextxref + ":");
185
186               SequenceI[] xrseqs = avp.getAlignment().getSequencesArray();
187
188               stringify(dbtoviewBit, savedProjects, nextxref, avp);
189               keyseq.add(nextxref);
190
191               List<String> xrptypes = (seqs == null || seqs.length == 0) ? null
192                       : new CrossRef(xrseqs, dataset)
193                               .findXrefSourcesForSequences(avp
194                                       .getAlignViewport().isNucleotide());
195               pass3 = 0;
196               do // 3rd cross ref and recover crossref loop
197               {
198                 for (String xrefdb : xrptypes)
199                 {
200                   List<AlignmentViewPanel> cra_views2 = new ArrayList<AlignmentViewPanel>();
201                   int q = 0;
202                   String nextnextxref = "{" + p + "}" + nextxref + " -> "
203                           + xrefdb + "{" + q + "}";
204
205                   if (pass3 == 0)
206                   {
207
208                     AlignFrame nextaf = Desktop.getAlignFrameFor(avp
209                             .getAlignViewport());
210
211                     cra = new CrossRefAction(nextaf, xrseqs, avp
212                             .getAlignViewport().isNucleotide(), xrefdb);
213                     cra.run();
214                     Assert.assertTrue(cra.getXrefViews().size() > 0,
215                             "No crossrefs found for '" + nextxref + "' to "
216                                     + xrefdb + " via '" + nextaf.getTitle()
217                                     + "'");
218                     cra_views2 = cra.getXrefViews();
219                   }
220                   else
221                   {
222                     Desktop.instance.closeAll_actionPerformed(null);
223                     // recover stored project
224                     AlignFrame af2 = new FileLoader(false)
225                             .LoadFileWaitTillLoaded(
226                                     savedProjects.get(nextnextxref)
227                                             .toString(), FormatAdapter.FILE);
228                     // gymnastics to recover the alignPanel/Complementary
229                     // alignPanel
230                     if (af2.getViewport().isNucleotide())
231                     {
232                       // top view, then bottom
233                       cra_views2.add(af2.getViewport().getAlignPanel());
234                       cra_views2.add(((jalview.gui.AlignViewport) af2
235                               .getViewport().getCodingComplement())
236                               .getAlignPanel());
237
238                     }
239                     else
240                     {
241                       // bottom view, then top
242                       cra_views2.add(((jalview.gui.AlignViewport) af2
243                               .getViewport().getCodingComplement())
244                               .getAlignPanel());
245                       cra_views2.add(af2.getViewport().getAlignPanel());
246                     }
247                     Assert.assertEquals(cra_views2.size(), 2);
248                     Assert.assertNotNull(cra_views2.get(0));
249                     Assert.assertNotNull(cra_views2.get(1));
250                   }
251
252                   for (AlignmentViewPanel nextavp : cra_views2)
253                   {
254                     nextnextxref = "{" + p + "}" + nextxref + " -> "
255                             + xrefdb + "{" + q++ + "}";
256
257                     // verify references for this panel
258                     AlignmentTest.assertAlignmentDatasetRefs(
259                             nextavp.getAlignment(), "" + "Pass (" + pass1
260                                     + "," + pass2 + "): For "
261                                     + nextnextxref + ":");
262
263                     stringify(dbtoviewBit, savedProjects, nextnextxref,
264                             nextavp);
265                     keyseq.add(nextnextxref);
266                   }
267                 } // end of loop around showing all xrefdb for crossrf2
268                 // fetchdb->crossref1->crossref-2->verify for xrefs we
269                 // either loop twice when pass2=0, or just once when pass2=1
270                 // (recovered project from previous crossref)
271               } while (pass3++ < 2 && pass2 < 1);
272             }
273         }
274           // fetchdb-->crossref1
275           // for each xref we try to retrieve xref, store and verify when
276           // pass1=0, or just retrieve and verify when pass1=1
277         } while (pass2++ < 2 && pass1 < 1);
278         // fetchdb
279         // for each ref we
280         // loop twice: first, do the retrieve, second recover from saved project
281       } while (++pass1 < 2);
282     }
283   }
284
285   /**
286    * first time called, record strings derived from alignment and
287    * alignedcodonframes, and save view to a project file. Second time called,
288    * compare strings to existing ones. org.testng.Assert.assertTrue on
289    * stringmatch
290    * 
291    * @param dbtoviewBit
292    *          map between xrefpath and view string
293    * @param savedProjects
294    *          - map from xrefpath to saved project filename (createTempFile)
295    * @param xrefpath
296    *          - xrefpath - unique ID for this context (composed of sequence of
297    *          db-fetch/cross-ref actions preceeding state)
298    * @param avp
299    *          - viewpanel to store (for viewpanels in splitframe, the same
300    *          project should be written for both panels, only one needs
301    *          recovering for comparison on the next stringify call, but each
302    *          viewpanel needs to be called with a distinct xrefpath to ensure
303    *          each one's strings are compared)
304    */
305   private void stringify(HashMap<String, String> dbtoviewBit,
306           HashMap<String, File> savedProjects, String xrefpath,
307           AlignmentViewPanel avp)
308   {
309     if (savedProjects != null)
310     {
311       if (savedProjects.get(xrefpath) == null)
312       {
313         // write a project file for this view. On the second pass, this will be
314         // recovered and cross-references verified
315         try
316         {
317           File prfile = File.createTempFile("crossRefTest", ".jvp");
318           AlignFrame af = Desktop.getAlignFrameFor(avp.getAlignViewport());
319           new Jalview2XML(false).saveAlignment(af, prfile.toString(),
320                   af.getTitle());
321           System.out.println("Written view from '" + xrefpath + "' as '"
322                   + prfile.getAbsolutePath() + "'");
323           savedProjects.put(xrefpath, prfile);
324         } catch (IOException q)
325         {
326           Assert.fail("Unexpected IO Exception", q);
327         }
328       }
329       else
330       {
331         System.out.println("Stringify check on view from '" + xrefpath
332                 + "' [ possibly retrieved from '"
333                 + savedProjects.get(xrefpath).getAbsolutePath() + "' ]");
334
335       }
336     }
337
338     StringBuilder sbr = new StringBuilder();
339     sbr.append(avp.getAlignment().toString());
340     sbr.append("\n");
341     sbr.append("<End of alignment>");
342     sbr.append("\n");
343     sbr.append(avp.getAlignment().getDataset());
344     sbr.append("\n");
345     sbr.append("<End of dataset>");
346     sbr.append("\n");
347     int p = 0;
348     if (avp.getAlignment().getCodonFrames() != null)
349     {
350       for (AlignedCodonFrame ac : avp.getAlignment().getCodonFrames())
351       {
352         sbr.append("<AlignedCodonFrame " + p++ + ">");
353         sbr.append("\n");
354         sbr.append(ac.toString());
355         sbr.append("\n");
356       }
357     }
358     String dbt = dbtoviewBit.get(xrefpath);
359     if (dbt == null)
360     {
361       dbtoviewBit.put(xrefpath, sbr.toString());
362     }
363     else
364     {
365       Assert.assertEquals(sbr.toString(), dbt, "stringify mismatch for "
366               + xrefpath);
367     }
368   }
369 }