package jalview.ext.archaeopteryx; import jalview.ext.forester.io.UtilityMethods; import jalview.ext.treeviewer.LoadedTreeAssociationI; import jalview.ext.treeviewer.LoadedTreeSequenceAssociation; import jalview.ext.treeviewer.TreeFrameI; import jalview.ext.treeviewer.TreeI; import jalview.ext.treeviewer.TreeViewerUtils; import jalview.gui.Desktop; import jalview.gui.JvOptionPane; import jalview.util.MessageManager; import jalview.viewmodel.AlignmentViewport; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import org.forester.archaeopteryx.AptxUtil; import org.forester.archaeopteryx.Configuration; import org.forester.archaeopteryx.webservices.PhylogeniesWebserviceClient; import org.forester.archaeopteryx.webservices.WebserviceUtil; import org.forester.io.parsers.PhylogenyParser; import org.forester.io.parsers.nexus.NexusPhylogeniesParser; import org.forester.io.parsers.nhx.NHXParser; import org.forester.io.parsers.phyloxml.PhyloXmlDataFormatException; import org.forester.io.parsers.phyloxml.PhyloXmlParser; import org.forester.io.parsers.tol.TolParser; import org.forester.io.parsers.util.ParserUtils; import org.forester.phylogeny.Phylogeny; import org.forester.phylogeny.PhylogenyMethods; import org.forester.phylogeny.data.Identifier; import org.forester.util.ForesterUtil; /** * Static class for creating Archaeopteryx tree viewer instances from calculated * trees and letting them be bound to Jalview. * * @author kjvanderheide * */ public final class AptxInit { public final static InputStream CONFIG_LOC = AptxInit.class .getResourceAsStream("/_aptx_jalview_configuration_file.txt"); public final static Configuration APTX_CONFIG = new Configuration( CONFIG_LOC, false, false); static { APTX_CONFIG.setBaseFontSize(Desktop.instance.getFont().getSize()); APTX_CONFIG .setBaseFontFamilyName(Desktop.instance.getFont().getFamily()); } private final static boolean VALIDATE_PHYLOXML_XSD = APTX_CONFIG .isValidatePhyloXmlAgainstSchema(); private final static boolean REPLACE_NHX_UNDERSCORES = APTX_CONFIG .isReplaceUnderscoresInNhParsing(); private final static boolean INTERNAL_NUMBERS_AS_CONFIDENCE = APTX_CONFIG .isInternalNumberAreConfidenceForNhParsing(); private final static boolean MIDPOINT_REROOT = APTX_CONFIG .isMidpointReroot(); private final static NHXParser.TAXONOMY_EXTRACTION TAXONOMY_EXTRACTION = APTX_CONFIG .getTaxonomyExtraction(); public static TreeFrameI createInstanceFromNhx(String treeTitle, String nhxString, AlignmentViewport viewport) throws IOException { if (Desktop.instance != null) { Desktop.instance.startLoading(treeTitle); } Phylogeny aptxPhylogeny = Phylogeny .createInstanceFromNhxString(nhxString); aptxPhylogeny.setName(treeTitle); TreeFrameI aptxFrame = createAptxFrame(aptxPhylogeny, viewport, treeTitle); if (Desktop.instance != null) { Desktop.instance.stopLoading(); } return aptxFrame; } /** * Refactored from Archaeopteryx.main * * @param filePath * @param viewport * @return * @throws IOException * @throws FileNotFoundException */ public static TreeFrameI[] createInstancesFromFile(File treeFile, AlignmentViewport viewport) throws FileNotFoundException, IOException { TreeFrameI[] aptxFrames = null; if (UtilityMethods.canForesterReadFile(treeFile)) { if (Desktop.instance != null) { Desktop.instance.startLoading(treeFile.getCanonicalPath()); } boolean nhx_or_nexus = false; final PhylogenyParser parser = ParserUtils .createParserDependingOnFileType(treeFile, VALIDATE_PHYLOXML_XSD); if (parser instanceof NHXParser) { nhx_or_nexus = true; final NHXParser nhx = (NHXParser) parser; nhx.setReplaceUnderscores(REPLACE_NHX_UNDERSCORES); nhx.setIgnoreQuotes(false); nhx.setTaxonomyExtraction(TAXONOMY_EXTRACTION); } else if (parser instanceof NexusPhylogeniesParser) { nhx_or_nexus = true; final NexusPhylogeniesParser nex = (NexusPhylogeniesParser) parser; nex.setReplaceUnderscores(REPLACE_NHX_UNDERSCORES); nex.setIgnoreQuotes(false); } else if (parser instanceof PhyloXmlParser) { if (VALIDATE_PHYLOXML_XSD == false) { JvOptionPane.showInternalMessageDialog(Desktop.desktop, MessageManager.getString("error.phyloxml_validation"), MessageManager.getString("label.file_open_error"), JvOptionPane.WARNING_MESSAGE); } } Phylogeny[] trees = PhylogenyMethods.readPhylogenies(parser, treeFile); aptxFrames = new TreeFrameI[trees.length]; for (int i = 0; i < trees.length; i++) { Phylogeny aptxPhylogeny = trees[i]; if (nhx_or_nexus && INTERNAL_NUMBERS_AS_CONFIDENCE) { PhylogenyMethods .transferInternalNodeNamesToConfidence(aptxPhylogeny, ""); } String treeTitle = treeFile.getName() + "[" + i + "]"; aptxPhylogeny.setName(treeTitle); aptxFrames[i] = createAptxFrame(aptxPhylogeny, viewport, treeTitle); } if (Desktop.instance != null) { Desktop.instance.stopLoading(); } } return aptxFrames; } public static TreeFrameI[] createInstancesFromFile( String filePath, AlignmentViewport viewport) throws FileNotFoundException, IOException { File treeFile = new File(filePath); return createInstancesFromFile(treeFile, viewport); } public static TreeFrameI[] createInstancesFromUrl(URL treeUrl, AlignmentViewport viewport) throws FileNotFoundException, IOException, RuntimeException { String treeTitle = treeUrl.getFile(); if (Desktop.instance != null) { Desktop.instance.startLoading(treeTitle); } Phylogeny[] trees = AptxUtil.readPhylogeniesFromUrl(treeUrl, VALIDATE_PHYLOXML_XSD, REPLACE_NHX_UNDERSCORES, INTERNAL_NUMBERS_AS_CONFIDENCE, TAXONOMY_EXTRACTION, MIDPOINT_REROOT); TreeFrameI[] aptxFrames = new TreeFrameI[trees.length]; for (int i = 0; i < trees.length; i++) { Phylogeny aptxTree = trees[i]; aptxFrames[i] = createAptxFrame(aptxTree, viewport, treeTitle); } if (Desktop.instance != null) { Desktop.instance.stopLoading(); } return aptxFrames; } /** * Refactored from Forester's UrlTreeReader, this can be more efficient * * @param databaseIndex * @param viewport * @return */ public static TreeFrameI[] createInstancesFromDb( PhylogeniesWebserviceClient treeDbClient, String identifier, AlignmentViewport viewport) { URL url = null; Phylogeny[] trees = null; TreeFrameI[] aptxFrames = null; if ((identifier != null) && (identifier.trim().length() > 0)) { if (Desktop.instance != null) { Desktop.instance.startLoading(identifier); } identifier = identifier.trim(); if (treeDbClient.isQueryInteger()) { identifier = identifier.replaceAll("^\\D+", ""); int id; try { id = Integer.parseInt(identifier); } catch (final NumberFormatException e) { JvOptionPane.showInternalMessageDialog(Desktop.desktop, MessageManager.formatMessage( "error.database_id_has_letters", new String[] { identifier }), MessageManager.getString("label.invalid_url"), JvOptionPane.ERROR_MESSAGE); return new TreeFrameI[0]; } identifier = id + ""; } boolean exception = false; try { String url_str = treeDbClient.getUrl(); url_str = url_str.replaceFirst( PhylogeniesWebserviceClient.QUERY_PLACEHOLDER, identifier); url = new URL(url_str); PhylogenyParser parser = null; switch (treeDbClient.getReturnFormat()) { case TOL_XML_RESPONSE: parser = new TolParser(); break; case NEXUS: parser = new NexusPhylogeniesParser(); ((NexusPhylogeniesParser) parser).setReplaceUnderscores(true); break; case TREEBASE_TREE: parser = new NexusPhylogeniesParser(); ((NexusPhylogeniesParser) parser).setReplaceUnderscores(true); ((NexusPhylogeniesParser) parser) .setTaxonomyExtraction(NHXParser.TAXONOMY_EXTRACTION.NO); break; case TREEBASE_STUDY: parser = new NexusPhylogeniesParser(); ((NexusPhylogeniesParser) parser).setReplaceUnderscores(true); ((NexusPhylogeniesParser) parser) .setTaxonomyExtraction(NHXParser.TAXONOMY_EXTRACTION.NO); break; case NH: parser = new NHXParser(); ((NHXParser) parser) .setTaxonomyExtraction(NHXParser.TAXONOMY_EXTRACTION.NO); ((NHXParser) parser).setReplaceUnderscores(true); ((NHXParser) parser).setGuessRootedness(true); break; case NH_EXTRACT_TAXONOMY: parser = new NHXParser(); ((NHXParser) parser).setTaxonomyExtraction( NHXParser.TAXONOMY_EXTRACTION.AGGRESSIVE); ((NHXParser) parser).setReplaceUnderscores(false); ((NHXParser) parser).setGuessRootedness(true); break; case PFAM: parser = new NHXParser(); ((NHXParser) parser).setTaxonomyExtraction( NHXParser.TAXONOMY_EXTRACTION.PFAM_STYLE_STRICT); ((NHXParser) parser).setReplaceUnderscores(false); ((NHXParser) parser).setGuessRootedness(true); break; case NHX: parser = new NHXParser(); ((NHXParser) parser) .setTaxonomyExtraction(NHXParser.TAXONOMY_EXTRACTION.NO); ((NHXParser) parser).setReplaceUnderscores(false); ((NHXParser) parser).setGuessRootedness(true); break; case PHYLOXML: parser = PhyloXmlParser.createPhyloXmlParserXsdValidating(); break; default: throw new IllegalArgumentException( "unknown format: " + treeDbClient.getReturnFormat()); } // // if (_main_frame.getMainPanel().getCurrentTreePanel() != null) // { // _main_frame.getMainPanel().getCurrentTreePanel().setWaitCursor(); // } // else // { // _main_frame.getMainPanel().setWaitCursor(); // } trees = ForesterUtil.readPhylogeniesFromUrl(url, parser); aptxFrames = new TreeFrameI[trees.length]; } catch (final MalformedURLException e) { exception = true; JvOptionPane.showInternalMessageDialog(Desktop.desktop, MessageManager.formatMessage( "exception.unable_to_launch_url", new String[] { url.toString() }), MessageManager.getString("label.invalid_url"), JvOptionPane.ERROR_MESSAGE); System.err.println(e.getLocalizedMessage()); } catch (final IOException e) { exception = true; JvOptionPane.showInternalMessageDialog(Desktop.desktop, "Could not read from " + url + "\n" + e.getLocalizedMessage(), "Failed to read tree from " + treeDbClient.getName() + " for " + identifier, JvOptionPane.ERROR_MESSAGE); System.err.println(e.getLocalizedMessage()); } catch (final NumberFormatException e) { exception = true; JvOptionPane.showInternalMessageDialog(Desktop.desktop, "Could not read from " + url + "\n" + e.getLocalizedMessage(), "Failed to read tree from " + treeDbClient.getName() + " for " + identifier, JvOptionPane.ERROR_MESSAGE); System.err.println(e.getLocalizedMessage()); } catch (final Exception e) { exception = true; e.printStackTrace(); JvOptionPane.showInternalMessageDialog(Desktop.desktop, e.getLocalizedMessage(), "Unexpected Exception", JvOptionPane.ERROR_MESSAGE); System.err.println(e.getLocalizedMessage()); } if ((trees != null) && (trees.length > 0)) { int i = 0; for (final Phylogeny aptxTree : trees) { if (!aptxTree.isEmpty()) { if (treeDbClient.getName().equals(WebserviceUtil.TREE_FAM_NAME)) { aptxTree.setRerootable(false); aptxTree.setRooted(true); } if (treeDbClient.getProcessingInstructions() != null) { try { WebserviceUtil.processInstructions(treeDbClient, aptxTree); } catch (final PhyloXmlDataFormatException e) { JvOptionPane.showInternalMessageDialog(Desktop.desktop, "Error:\n" + e.getLocalizedMessage(), "Error", JvOptionPane.ERROR_MESSAGE); } } if (treeDbClient.getNodeField() != null) { try { PhylogenyMethods.transferNodeNameToField(aptxTree, treeDbClient.getNodeField(), false); } catch (final PhyloXmlDataFormatException e) { JvOptionPane.showInternalMessageDialog(Desktop.desktop, "Error:\n" + e.getLocalizedMessage(), "Error", JvOptionPane.ERROR_MESSAGE); } } aptxTree.setIdentifier( new Identifier(identifier, treeDbClient.getName())); // _main_frame.getJMenuBar().remove(_main_frame.getHelpMenu()); // _main_frame.getMenuBarOfExternalTreeFrameI() // .add(_main_frame.getHelpMenu()); // _main_frame.getMainPanel().addExternalTreeIInNewTab(ExternalTreeI, // _main_frame.getConfiguration(), // new File(url.getFile()).getName(), url.toString()); TreeFrameI aptxApp = createAptxFrame(aptxTree, viewport, url.getFile()); String my_name_for_file = ""; if (!ForesterUtil.isEmpty(aptxTree.getName())) { my_name_for_file = new String(aptxTree.getName()) .replaceAll(" ", "_"); } else if (aptxTree.getIdentifier() != null) { final StringBuffer sb = new StringBuffer(); if (!ForesterUtil .isEmpty(aptxTree.getIdentifier().getProvider())) { sb.append(aptxTree.getIdentifier().getProvider()); sb.append("_"); } sb.append(aptxTree.getIdentifier().getValue()); my_name_for_file = new String( sb.toString().replaceAll(" ", "_")); } aptxApp.getTreePanel() .setTreeFile(new File(my_name_for_file)); // AptxUtil.lookAtSomeTreePropertiesForAptxControlSettings( // aptxTree, aptxApp.getMainPanel().getControlPanel(), // APTX_CONFIG); aptxApp.getTreeControls().displayEntireTree(); aptxApp.enableMultipleTrees(); aptxFrames[i++] = aptxApp; } } } else if (!exception) // ..what? { JvOptionPane.showMessageDialog(null, ForesterUtil.wordWrap( "Failed to read in tree(s) from [" + url + "]", 80), "Error", JvOptionPane.ERROR_MESSAGE); } if ((trees != null) && (trees.length > 0)) { try { JvOptionPane.showMessageDialog(null, ForesterUtil.wordWrap("Successfully read in " + trees.length + " tree(s) from [" + url + "]", 80), "Success", JvOptionPane.INFORMATION_MESSAGE); } catch (final Exception e) { // Not important if this fails, do nothing. } } } if (Desktop.instance != null) { Desktop.instance.stopLoading(); } return aptxFrames; } public static TreeFrameI createAptxFrame(TreeI aptxTree, AlignmentViewport jalviewAlignport, String treeTitle) { validateConfig(APTX_CONFIG); TreeFrameI aptxApp = aptxTree .createTreeViewerFromTree(treeTitle); TreeI jalviewTree = aptxApp.getTree(); LoadedTreeAssociationI bindAptxNodes = new LoadedTreeSequenceAssociation( jalviewAlignport.getAlignment().getSequencesArray(), jalviewTree); bindAptxNodes.associateNodesToSequences(); TreeViewerUtils.associateNodesWithJalviewSequences(aptxApp, jalviewAlignport, bindAptxNodes.getAlignmentWithNodes(), bindAptxNodes.getNodesWithAlignment()); TreeViewerUtils.addTreeViewFrameToJalview(aptxApp, 400, 500); // adaptAptxGui(aptxApp); //moved to AptxFrame return aptxApp; } protected static TreeFrameI createAptxFrame( final Phylogeny aptxTree, final AlignmentViewport jalviewAlignport, String treeTitle) { validateConfig(APTX_CONFIG); TreeFrameI aptxApp = new AptxFrame(aptxTree, APTX_CONFIG, treeTitle); TreeI jalviewTree = aptxApp.getTree(); LoadedTreeAssociationI bindAptxNodes = new LoadedTreeSequenceAssociation( jalviewAlignport.getAlignment().getSequencesArray(), jalviewTree); bindAptxNodes.associateNodesToSequences(); TreeViewerUtils.associateNodesWithJalviewSequences(aptxApp, jalviewAlignport, bindAptxNodes.getAlignmentWithNodes(), bindAptxNodes.getNodesWithAlignment()); TreeViewerUtils.addTreeViewFrameToJalview(aptxApp, 400, 500); return aptxApp; } private static boolean validateConfig(Configuration aptxConfig) { if (aptxConfig == null || aptxConfig.isCouldReadConfigFile() == false) { int keepGoing = JvOptionPane.showConfirmDialog(Desktop.desktop, MessageManager.getString("label.aptx_config_not_found"), MessageManager.formatMessage("label.couldnt_locate", new String[] { "_aptx_jalview_configuration_file" }), JvOptionPane.YES_NO_CANCEL_OPTION); if (keepGoing == JvOptionPane.CANCEL_OPTION || keepGoing == JvOptionPane.CLOSED_OPTION || keepGoing == JvOptionPane.NO_OPTION) { return false; } } return true; } }