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