JAL-2847 start of cleaning up db loading code
[jalview.git] / src / jalview / ext / archaeopteryx / AptxInit.java
1 package jalview.ext.archaeopteryx;
2
3 import jalview.analysis.TreeBuilder;
4 import jalview.datamodel.SequenceI;
5 import jalview.ext.treeviewer.ExternalTreeBuilderI;
6 import jalview.ext.treeviewer.ExternalTreeViewerBindingI;
7 import jalview.gui.Desktop;
8 import jalview.gui.JvOptionPane;
9 import jalview.util.MessageManager;
10 import jalview.viewmodel.AlignmentViewport;
11
12 import java.awt.Dimension;
13 import java.io.File;
14 import java.io.FileNotFoundException;
15 import java.io.IOException;
16 import java.net.MalformedURLException;
17 import java.net.URL;
18 import java.util.Map;
19
20 import org.forester.archaeopteryx.AptxUtil;
21 import org.forester.archaeopteryx.Archaeopteryx;
22 import org.forester.archaeopteryx.Configuration;
23 import org.forester.archaeopteryx.MainFrame;
24 import org.forester.archaeopteryx.webservices.PhylogeniesWebserviceClient;
25 import org.forester.archaeopteryx.webservices.WebserviceUtil;
26 import org.forester.archaeopteryx.webservices.WebservicesManager;
27 import org.forester.io.parsers.PhylogenyParser;
28 import org.forester.io.parsers.nexus.NexusPhylogeniesParser;
29 import org.forester.io.parsers.nhx.NHXParser;
30 import org.forester.io.parsers.phyloxml.PhyloXmlDataFormatException;
31 import org.forester.io.parsers.phyloxml.PhyloXmlParser;
32 import org.forester.io.parsers.tol.TolParser;
33 import org.forester.io.parsers.util.ParserUtils;
34 import org.forester.phylogeny.Phylogeny;
35 import org.forester.phylogeny.PhylogenyMethods;
36 import org.forester.phylogeny.PhylogenyNode;
37 import org.forester.phylogeny.data.Identifier;
38 import org.forester.util.ForesterUtil;
39
40 /**
41  * Static class for creating Archaeopteryx tree viewer instances from calculated
42  * trees and letting them be bound to Jalview.
43  * 
44  * @author kjvanderheide
45  *
46  */
47 public final class AptxInit
48 {
49
50   private final static Configuration APTX_CONFIG = new Configuration(
51           "_aptx_jalview_configuration_file", false, false, false);
52
53   private final static boolean VALIDATE_PHYLOXML_XSD = APTX_CONFIG
54           .isValidatePhyloXmlAgainstSchema();
55
56   private final static boolean REPLACE_NHX_UNDERSCORES = APTX_CONFIG
57           .isReplaceUnderscoresInNhParsing();
58
59   private final static boolean INTERNAL_NUMBERS_AS_CONFIDENCE = APTX_CONFIG
60           .isInternalNumberAreConfidenceForNhParsing();
61
62   private final static boolean MIDPOINT_REROOT = APTX_CONFIG
63           .isMidpointReroot();
64
65   private final static NHXParser.TAXONOMY_EXTRACTION TAXONOMY_EXTRACTION = APTX_CONFIG
66           .getTaxonomyExtraction();
67
68
69
70   public static MainFrame createInstanceFromCalculation(
71           final TreeBuilder calculatedTree)
72   {
73     ExternalTreeBuilderI<Phylogeny, PhylogenyNode> aptxTreeBuilder = new AptxTreeBuilder(
74             calculatedTree);
75
76     Phylogeny aptxTree = aptxTreeBuilder.buildTree();
77
78     MainFrame aptxApp = createAptxFrame(aptxTree,
79             calculatedTree.getAvport(), null);
80             
81     return aptxApp;
82   }
83
84   /**
85    * Refactored from Archaeopteryx.main
86    * 
87    * @param filePath
88    * @param viewport
89    * @return
90    * @throws IOException
91    * @throws FileNotFoundException
92    */
93   public static MainFrame[] createInstancesFromFile(String filePath,
94           AlignmentViewport viewport)
95           throws FileNotFoundException, IOException
96   {
97     File treeFile = new File(filePath);
98     final String err = ForesterUtil.isReadableFile(treeFile);
99     if (!ForesterUtil.isEmpty(err))
100     {
101       JvOptionPane.showMessageDialog(Desktop.desktop, err,
102               MessageManager.getString("label.problem_reading_tree_file"),
103               JvOptionPane.WARNING_MESSAGE);
104     }
105
106     if (Desktop.instance != null)
107     {
108       Desktop.instance.startLoading(filePath);
109     }
110     boolean nhx_or_nexus = false;
111     final PhylogenyParser parser = ParserUtils.createParserDependingOnFileType(
112             treeFile, VALIDATE_PHYLOXML_XSD);
113     if (parser instanceof NHXParser)
114     {
115       nhx_or_nexus = true;
116       final NHXParser nhx = (NHXParser) parser;
117       nhx.setReplaceUnderscores(REPLACE_NHX_UNDERSCORES);
118       nhx.setIgnoreQuotes(false);
119       nhx.setTaxonomyExtraction(TAXONOMY_EXTRACTION);
120     }
121     else if (parser instanceof NexusPhylogeniesParser)
122     {
123       nhx_or_nexus = true;
124       final NexusPhylogeniesParser nex = (NexusPhylogeniesParser) parser;
125       nex.setReplaceUnderscores(REPLACE_NHX_UNDERSCORES);
126       nex.setIgnoreQuotes(false);
127     }
128 //    else if (p instanceof PhyloXmlParser)
129 //    {
130 //      MainFrameApplication.warnIfNotPhyloXmlValidation(APTX_CONFIG);
131 //    }
132     Phylogeny[] trees = PhylogenyMethods.readPhylogenies(parser, treeFile);
133     MainFrame[] aptxFrames = new MainFrame[trees.length];
134     String treeTitle = treeFile.getName();
135
136     for (int i = 0; i < trees.length; i++)
137       {
138       Phylogeny tree = trees[i];
139
140       if (nhx_or_nexus && INTERNAL_NUMBERS_AS_CONFIDENCE)
141       {
142         PhylogenyMethods.transferInternalNodeNamesToConfidence(tree, "");
143       }
144       aptxFrames[i] = createAptxFrame(tree, viewport, treeTitle);
145
146     }
147     if (Desktop.instance != null)
148     {
149       Desktop.instance.stopLoading();
150     }
151     return aptxFrames;
152     }
153
154
155   public static MainFrame[] createInstancesFromUrl(URL treeUrl,
156           AlignmentViewport viewport)
157           throws FileNotFoundException, IOException, RuntimeException
158   {
159     
160     String treeTitle = treeUrl.getFile();
161     if (Desktop.instance != null)
162     {
163       Desktop.instance.startLoading(treeTitle);
164     }
165     Phylogeny[] trees = AptxUtil.readPhylogeniesFromUrl(treeUrl,
166             VALIDATE_PHYLOXML_XSD,
167              REPLACE_NHX_UNDERSCORES, INTERNAL_NUMBERS_AS_CONFIDENCE,
168             TAXONOMY_EXTRACTION, MIDPOINT_REROOT);
169
170     MainFrame[] aptxFrames = new MainFrame[trees.length];
171     for (int i = 0; i < trees.length; i++)
172     {
173       Phylogeny tree = trees[i];
174       aptxFrames[i] = createAptxFrame(tree, viewport, treeTitle);
175     }
176
177     if (Desktop.instance != null)
178     {
179       Desktop.instance.stopLoading();
180     }
181
182     return aptxFrames;
183
184   }
185
186   /**
187    * Refactored from Forester's UrlTreeReader, this can be more efficient
188    * 
189    * @param databaseIndex
190    * @param viewport
191    * @return
192    */
193   public static MainFrame[] createInstancesFromDb(int databaseIndex,
194           AlignmentViewport viewport)
195   {
196
197     URL url = null;
198     Phylogeny[] trees = null;
199     final WebservicesManager webservices_manager = WebservicesManager
200             .getInstance();
201     final PhylogeniesWebserviceClient client = webservices_manager
202             .getAvailablePhylogeniesWebserviceClient(databaseIndex);
203     String identifier = JvOptionPane.showInternalInputDialog(
204             Desktop.desktop,
205             client.getInstructions() + "\n(Reference: "
206                     + client.getReference() + ")",
207             client.getDescription(), JvOptionPane.QUESTION_MESSAGE);
208
209     if ((identifier != null) && (identifier.trim().length() > 0))
210     {
211       if (Desktop.instance != null)
212       {
213         Desktop.instance.startLoading(identifier);
214       }
215
216       identifier = identifier.trim();
217       if (client.isQueryInteger())
218       {
219         identifier = identifier.replaceAll("^\\D+", "");
220
221         int id;
222         try
223         {
224           id = Integer.parseInt(identifier);
225         } catch (final NumberFormatException e)
226         {
227           JvOptionPane.showInternalMessageDialog(Desktop.desktop,
228                   "Identifier is expected to be a number",
229                   "Can not open URL", JvOptionPane.ERROR_MESSAGE);
230           return new MainFrame[0];
231         }
232         identifier = id + "";
233       }
234       boolean exception = false;
235       try
236       {
237         String url_str = client.getUrl();
238         url_str = url_str.replaceFirst(
239                 PhylogeniesWebserviceClient.QUERY_PLACEHOLDER, identifier);
240         url = new URL(url_str);
241         PhylogenyParser parser = null;
242         switch (client.getReturnFormat())
243         {
244         case TOL_XML_RESPONSE:
245           parser = new TolParser();
246           break;
247         case NEXUS:
248           parser = new NexusPhylogeniesParser();
249           ((NexusPhylogeniesParser) parser).setReplaceUnderscores(true);
250           break;
251         case TREEBASE_TREE:
252           parser = new NexusPhylogeniesParser();
253           ((NexusPhylogeniesParser) parser).setReplaceUnderscores(true);
254           ((NexusPhylogeniesParser) parser)
255                   .setTaxonomyExtraction(NHXParser.TAXONOMY_EXTRACTION.NO);
256           break;
257         case TREEBASE_STUDY:
258           parser = new NexusPhylogeniesParser();
259           ((NexusPhylogeniesParser) parser).setReplaceUnderscores(true);
260           ((NexusPhylogeniesParser) parser)
261                   .setTaxonomyExtraction(NHXParser.TAXONOMY_EXTRACTION.NO);
262           break;
263         case NH:
264           parser = new NHXParser();
265           ((NHXParser) parser)
266                   .setTaxonomyExtraction(NHXParser.TAXONOMY_EXTRACTION.NO);
267           ((NHXParser) parser).setReplaceUnderscores(true);
268           ((NHXParser) parser).setGuessRootedness(true);
269           break;
270         case NH_EXTRACT_TAXONOMY:
271           parser = new NHXParser();
272           ((NHXParser) parser).setTaxonomyExtraction(
273                   NHXParser.TAXONOMY_EXTRACTION.AGGRESSIVE);
274           ((NHXParser) parser).setReplaceUnderscores(false);
275           ((NHXParser) parser).setGuessRootedness(true);
276           break;
277         case PFAM:
278           parser = new NHXParser();
279           ((NHXParser) parser).setTaxonomyExtraction(
280                   NHXParser.TAXONOMY_EXTRACTION.PFAM_STYLE_STRICT);
281           ((NHXParser) parser).setReplaceUnderscores(false);
282           ((NHXParser) parser).setGuessRootedness(true);
283           break;
284         case NHX:
285           parser = new NHXParser();
286           ((NHXParser) parser)
287                   .setTaxonomyExtraction(NHXParser.TAXONOMY_EXTRACTION.NO);
288           ((NHXParser) parser).setReplaceUnderscores(false);
289           ((NHXParser) parser).setGuessRootedness(true);
290           break;
291         case PHYLOXML:
292           parser = PhyloXmlParser.createPhyloXmlParserXsdValidating();
293           break;
294         default:
295           throw new IllegalArgumentException(
296                   "unknown format: " + client.getReturnFormat());
297         }
298         //
299         // if (_main_frame.getMainPanel().getCurrentTreePanel() != null)
300         // {
301         // _main_frame.getMainPanel().getCurrentTreePanel().setWaitCursor();
302         // }
303         // else
304         // {
305         // _main_frame.getMainPanel().setWaitCursor();
306         // }
307         trees = ForesterUtil.readPhylogeniesFromUrl(url, parser);
308       } catch (final MalformedURLException e)
309       {
310         exception = true;
311         JvOptionPane.showInternalMessageDialog(Desktop.desktop,
312                 "Malformed URL: " + url + "\n" + e.getLocalizedMessage(),
313                 "Malformed URL", JvOptionPane.ERROR_MESSAGE);
314       } catch (final IOException e)
315       {
316         exception = true;
317         JvOptionPane.showInternalMessageDialog(Desktop.desktop,
318                 "Could not read from " + url + "\n"
319                         + e.getLocalizedMessage(),
320                 "Failed to read tree from " + client.getName() + " for "
321                         + identifier,
322                 JvOptionPane.ERROR_MESSAGE);
323       } catch (final NumberFormatException e)
324       {
325         exception = true;
326         JvOptionPane.showInternalMessageDialog(Desktop.desktop,
327                 "Could not read from " + url + "\n"
328                         + e.getLocalizedMessage(),
329                 "Failed to read tree from " + client.getName() + " for "
330                         + identifier,
331                 JvOptionPane.ERROR_MESSAGE);
332       } catch (final Exception e)
333       {
334         exception = true;
335         e.printStackTrace();
336         JvOptionPane.showInternalMessageDialog(Desktop.desktop,
337                 e.getLocalizedMessage(), "Unexpected Exception",
338                 JvOptionPane.ERROR_MESSAGE);
339       } finally
340       {
341         // if (_main_frame.getCurrentTreePanel() != null)
342         // {
343         // _main_frame.getCurrentTreePanel().setArrowCursor();
344         // }
345         // else
346         // {
347         // _main_frame.getMainPanel().setArrowCursor();
348         // }
349       }
350       if ((trees != null) && (trees.length > 0))
351       {
352         for (final Phylogeny phylogeny : trees)
353         {
354           if (!phylogeny.isEmpty())
355           {
356             if (client.getName().equals(WebserviceUtil.TREE_FAM_NAME))
357             {
358               phylogeny.setRerootable(false);
359               phylogeny.setRooted(true);
360             }
361             if (client.getProcessingInstructions() != null)
362             {
363               try
364               {
365                 WebserviceUtil.processInstructions(client, phylogeny);
366               } catch (final PhyloXmlDataFormatException e)
367               {
368                 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
369                         "Error:\n" + e.getLocalizedMessage(), "Error",
370                         JvOptionPane.ERROR_MESSAGE);
371               }
372             }
373             if (client.getNodeField() != null)
374             {
375               try
376               {
377                 PhylogenyMethods.transferNodeNameToField(phylogeny,
378                         client.getNodeField(), false);
379               } catch (final PhyloXmlDataFormatException e)
380               {
381                 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
382                         "Error:\n" + e.getLocalizedMessage(), "Error",
383                         JvOptionPane.ERROR_MESSAGE);
384               }
385             }
386             phylogeny.setIdentifier(
387                     new Identifier(identifier, client.getName()));
388             // _main_frame.getJMenuBar().remove(_main_frame.getHelpMenu());
389             // _main_frame.getMenuBarOfMainFrame()
390             // .add(_main_frame.getHelpMenu());
391             // _main_frame.getMainPanel().addPhylogenyInNewTab(phylogeny,
392             // _main_frame.getConfiguration(),
393             // new File(url.getFile()).getName(), url.toString());
394
395             MainFrame aptxApp = createAptxFrame(phylogeny, viewport,
396                     url.getFile());
397             String my_name_for_file = "";
398             if (!ForesterUtil.isEmpty(phylogeny.getName()))
399             {
400               my_name_for_file = new String(phylogeny.getName())
401                       .replaceAll(" ", "_");
402             }
403             else if (phylogeny.getIdentifier() != null)
404             {
405               final StringBuffer sb = new StringBuffer();
406               if (!ForesterUtil
407                       .isEmpty(phylogeny.getIdentifier().getProvider()))
408               {
409                 sb.append(phylogeny.getIdentifier().getProvider());
410                 sb.append("_");
411               }
412               sb.append(phylogeny.getIdentifier().getValue());
413               my_name_for_file = new String(
414                       sb.toString().replaceAll(" ", "_"));
415             }
416             // _main_frame.getMainPanel().getCurrentTreePanel()
417             // .setTreeFile(new File(my_name_for_file));
418             AptxUtil.lookAtSomeTreePropertiesForAptxControlSettings(
419                     phylogeny, aptxApp.getMainPanel().getControlPanel(),
420                     APTX_CONFIG);
421             // _main_frame.getMainPanel().getControlPanel().showWhole();
422
423             aptxApp.activateSaveAllIfNeeded();
424           }
425         }
426       }
427       else if (!exception)
428       {
429         JvOptionPane.showMessageDialog(null,
430                 ForesterUtil.wordWrap(
431                         "Failed to read in tree(s) from [" + url + "]", 80),
432                 "Error", JvOptionPane.ERROR_MESSAGE);
433       }
434       if ((trees != null) && (trees.length > 0))
435       {
436         try
437         {
438           JvOptionPane.showMessageDialog(null,
439                   ForesterUtil.wordWrap("Successfully read in "
440                           + trees.length + " tree(s) from [" + url + "]",
441                           80),
442                   "Success", JvOptionPane.INFORMATION_MESSAGE);
443         } catch (final Exception e)
444         {
445           // Not important if this fails, do nothing.
446         }
447         // _main_frame.getContentPane().repaint();
448       }
449     }
450
451     System.gc();
452
453
454     if (Desktop.instance != null)
455     {
456       Desktop.instance.stopLoading();
457     }
458     return null;
459
460
461   }
462
463
464
465
466
467   public static MainFrame createAptxFrame(
468           final Phylogeny aptxTree,
469           final AlignmentViewport jalviewAlignport, String treeTitle)
470   {
471     MainFrame aptxApp = Archaeopteryx.createApplication(aptxTree,
472             APTX_CONFIG, treeTitle);
473
474     LoadedTreeSequenceAssociation bindAptxNodes = new LoadedTreeSequenceAssociation(
475             jalviewAlignport.getAlignment().getSequencesArray(), aptxTree);
476     bindAptxNodes.associateLeavesToSequences();
477
478     bindNodesToJalviewSequences(aptxApp, jalviewAlignport,
479             bindAptxNodes.getAlignmentWithNodes(),
480             bindAptxNodes.getNodesWithAlignment());
481     bindTreeViewFrameToJalview(aptxApp);
482
483     return aptxApp;
484   }
485
486   // private static void addPartitioningSlider(MainFrame aptxFrame)
487   // {
488   // JSlider slider = new JSlider();
489   //
490   //
491   // }
492
493   public static ExternalTreeViewerBindingI<?> bindNodesToJalviewSequences(
494           final MainFrame aptxApp,
495           final AlignmentViewport jalviewAlignViewport,
496           final Map<SequenceI, PhylogenyNode> alignMappedToNodes,
497           final Map<PhylogenyNode, SequenceI> nodesMappedToAlign)
498   {
499     return new JalviewBinding(aptxApp, jalviewAlignViewport,
500             alignMappedToNodes, nodesMappedToAlign);
501   }
502
503
504   public static MainFrame bindTreeViewFrameToJalview(
505           final MainFrame aptxApp)
506   {
507     int width = 400;
508     int height = 550;
509     aptxApp.setMinimumSize(new Dimension(width, height));
510     // aptxApp.setFont(Desktop.instance.getFont());
511     // aptxApp.getMainPanel().setFont(Desktop.instance.getFont());
512
513     Desktop.addInternalFrame(aptxApp, "Archaeopteryx Tree View", true,
514             width, height, true, true);
515
516     return aptxApp;
517
518   }
519
520
521
522 }