### Start AiZynthFinder Application Source: https://github.com/molecularai/aizynthfinder/blob/master/contrib/notebook.ipynb Initializes and starts the AiZynthApp with a specified configuration file. This is run after installation to launch the application interface. ```python #@title Start application. {display-mode: "form"} from rdkit.Chem.Draw import IPythonConsole from aizynthfinder.interfaces import AiZynthApp application = AiZynthApp("./data/config.yml") ``` -------------------------------- ### Install AiZynthFinder for Developers Source: https://github.com/molecularai/aizynthfinder/blob/master/README.md Clone the repository, create a development environment using env-dev.yml, and install the package in editable mode with all extras. ```bash conda env create -f env-dev.yml conda activate aizynth-dev poetry install --all-extras ``` -------------------------------- ### Install AiZynthFinder and Dependencies Source: https://github.com/molecularai/aizynthfinder/blob/master/contrib/notebook.ipynb Installs the AiZynthFinder package with all optional dependencies, a specific version of Pillow, and downloads public data. This is the initial setup step. ```python #@title Installation -- Run this cell to install AiZynthFinder # This might not install the dependencies that you need #! (AIZ_LATEST_TAG=$(git -c 'versionsort.suffix=-' \ # ls-remote --exit-code --refs --sort='version:refname' --tags https://github.com/MolecularAI/aizynthfinder '*.*.*' \ # | tail --lines=1 \ # | cut -f 3 -d /) \ # && pip install --quiet https://github.com/MolecularAI/aizynthfinder/archive/${AIZ_LATEST_TAG}.tar.gz) !pip install --quiet aizynthfinder[all] !pip install --ignore-installed Pillow==9.0.0 !mkdir --parents data && download_public_data data ``` -------------------------------- ### Get CLI Help Source: https://github.com/molecularai/aizynthfinder/blob/master/docs/cli.rst Display available command-line arguments and their descriptions for the aizynthcli tool. This is useful for understanding all available options and flags. ```bash aizynthcli -h ``` -------------------------------- ### Start Jupyter Notebook Server Source: https://github.com/molecularai/aizynthfinder/blob/master/docs/gui.rst Command to launch the Jupyter Notebook server. This is the first step to access the AIZynthFinder GUI. ```bash jupyter notebook ``` -------------------------------- ### Use Multiple Expansion Policies with aizynthcli Source: https://github.com/molecularai/aizynthfinder/blob/master/docs/howto.rst Command-line example to utilize the configured multiple expansion policies with `aizynthcli`. Ensure the configuration file (`config.yml`) and input SMILES file (`smiles.txt`) are correctly specified. ```bash aizynthcli --smiles smiles.txt --config config.yml --policy multi_expansion_strategy ``` -------------------------------- ### Install AiZynthFinder for End-Users Source: https://github.com/molecularai/aizynthfinder/blob/master/README.md Create a conda environment and install the AiZynthFinder package with all functionalities. ```bash conda create "python>=3.10,<3.13" -n aizynth-env conda activate aizynth-env python -m pip install aizynthfinder[all] ``` -------------------------------- ### Install AiZynthFinder Minimal Package Source: https://github.com/molecularai/aizynthfinder/blob/master/README.md Create a conda environment and install the AiZynthFinder package with essential functionalities. ```bash conda activate aizynth-env python -m pip install aizynthfinder ``` -------------------------------- ### Get Help for Molecule Class and Methods Source: https://github.com/molecularai/aizynthfinder/blob/master/docs/python_interface.rst Access documentation for the Molecule class and its methods, such as 'fingerprint', using the help() function in an interactive Python shell. ```python from aizynthfinder.chem import Molecule help(Molecule) help(Molecule.fingerprint) ``` -------------------------------- ### Configure Retro* Search Algorithm Source: https://github.com/molecularai/aizynthfinder/blob/master/docs/howto.rst Specify Retro* as the search algorithm in the configuration file. This example uses Retro* without a constant-valued oracle function. ```yaml search: algorithm: aizynthfinder.search.retrostar.search_tree.SearchTree ``` -------------------------------- ### Configure Chemformer Expansion Model Source: https://github.com/molecularai/aizynthfinder/blob/master/plugins/README.md Example configuration for using the Chemformer expansion model in AIZynthFinder. Ensure the Chemformer REST API is running and accessible. ```yaml expansion: chemformer: type: expansion_strategies.ChemformerBasedExpansionStrategy url: http://localhost:8000/chemformer-api/predict search: algorithm_config: immediate_instantiation: [chemformer] time_limit: 300 ``` -------------------------------- ### Implement Custom Stock Query Source: https://github.com/molecularai/aizynthfinder/blob/master/docs/stocks.rst Example of a custom stock class implementing the __contains__ method for lookup and subclassing StockQueryMixin. This example checks for a heavy atom count less than 10. ```python from rdkit.Chem import Lipinski from aizynthfinder.context.stock.queries import StockQueryMixin class CriteriaStock(StockQueryMixin): def __contains__(self, mol): return Lipinski.HeavyAtomCount(mol.rd_mol) < 10 ``` -------------------------------- ### Configure ModelZoo Expansion Model Source: https://github.com/molecularai/aizynthfinder/blob/master/plugins/README.md Example configuration for using the ModelZoo expansion model with Chemformer as the external model. Adjust paths to your cloned repositories and model files. ```yaml expansion: chemformer: type: expansion_strategies.ModelZooExpansionStrategy: module_path: /path_to_folder_containing_cloned_repository/modelsmatter_modelzoo/external_models/modelsmatter_chemformer_hpc/ use_gpu: False params: module_path: /path_to_model_file/chemformer_backward.ckpt vocab_path: /path_to_vocab_file/bart_vocab_downstream.txt search: algorithm_config: immediate_instantiation: [chemformer] time_limit: 300 ``` -------------------------------- ### Configure Route Output Limits Source: https://github.com/molecularai/aizynthfinder/blob/master/docs/howto.rst Control the number of routes generated by `aizynthcli` using the `post_processing` section. This example sets a minimum of 25 and a maximum of 50 routes per target. ```yaml post_processing: min_routes: 25 max_routes: 50 ``` -------------------------------- ### Implement Custom Scorer Class Source: https://github.com/molecularai/aizynthfinder/blob/master/docs/scoring.rst Example of implementing a custom scoring function by inheriting from the Scorer class. This scorer calculates the delta number of transforms. ```python from aizynthfinder.context.scoring.scorers import Scorer class DeltaNumberOfTransformsScorer(Scorer): def __repr__(self): return "delta number of transforms" def _score_node(self, node): return self._config.max_transforms - node.state.max_transforms def _score_reaction_tree(self, tree): return self._config.max_transforms - len(list(tree.reactions())) ``` -------------------------------- ### Custom SMILES Extraction Module Source: https://github.com/molecularai/aizynthfinder/blob/master/docs/stocks.rst Example Python module to extract SMILES from files with custom formatting, such as Zinc database downloads with headers. This module yields SMILES strings, skipping the first line and splitting subsequent lines by space. ```python def extract_smiles(filename): with open(filename, "r") as fileobj: for i, line in enumerate(fileobj.readlines()): if i == 0: continue yield line.strip().split(" ")[0] ``` -------------------------------- ### Create Notebook with aizynthapp tool Source: https://github.com/molecularai/aizynthfinder/blob/master/docs/gui.rst Command to automatically create a Jupyter notebook and open it. It requires a configuration file path. ```bash aizynthapp --config config_local.yml ``` -------------------------------- ### Build Documentation with Invoke Source: https://github.com/molecularai/aizynthfinder/blob/master/README.md Generate the HTML documentation using Sphinx via an invoke command. ```bash invoke build-docs ``` -------------------------------- ### Initialize Clustering GUI Source: https://github.com/molecularai/aizynthfinder/blob/master/docs/gui.rst Enables the clustering GUI extension for analyzing search results. Requires the matplotlib backend to be set inline. ```python %matplotlib inline from aizynthfinder.interfaces.gui.clustering import ClusteringGui ClusteringGui.from_app(app) ``` -------------------------------- ### Simple AI-ZynthFinder Configuration Source: https://github.com/molecularai/aizynthfinder/blob/master/docs/configuration.rst Basic configuration for expansion models and stock files. Ensure the specified model and template files exist. ```yaml expansion: full: - uspto_expansion.onnx - uspto_templates.csv.gz stock: zinc: zinc_stock.hdf5 ``` -------------------------------- ### Run Full Tests with Invoke Source: https://github.com/molecularai/aizynthfinder/blob/master/README.md Execute the full test suite as run on the CI server using an invoke command. ```bash invoke full-tests ``` -------------------------------- ### Instantiate AiZynthExpander Source: https://github.com/molecularai/aizynthfinder/blob/master/docs/python_interface.rst Instantiate the AiZynthExpander class with a configuration file to break down molecules into reactants. ```python filename = "config.yml" expander = AiZynthExpander(configfile=filename) expander.expansion_policy.select("uspto") expander.filter_policy.select("uspto") ``` -------------------------------- ### Instantiate AiZynthFinder Source: https://github.com/molecularai/aizynthfinder/blob/master/docs/python_interface.rst Instantiate the AiZynthFinder class by providing the path to a configuration file. ```python filename = "config.yml" finder = AiZynthFinder(configfile=filename) ``` -------------------------------- ### Load Custom Stock in AiZynthApp Source: https://github.com/molecularai/aizynthfinder/blob/master/docs/stocks.rst Demonstrates how to load a custom stock class within the AiZynthApp. The custom stock is instantiated and then loaded into the finder's stock object. ```python from aizynthfinder import AiZynthApp configfile="config_local.yml" app = AiZynthApp(configfile, setup=False) app.finder.stock.load(CriteriaStock(), "criteria") # This loads the custom stock class app.setup() ``` -------------------------------- ### Initialize AiZynthApp in Jupyter Source: https://github.com/molecularai/aizynthfinder/blob/master/docs/index.rst Instantiates the AiZynthApp for the GUI interface within a Jupyter notebook. Requires the path to a configuration file. ```python from aizynthfinder.interfaces import AiZynthApp app = AiZynthApp("/path/to/configfile.yaml") ``` -------------------------------- ### AI-ZynthFinder Configuration with Environment Variables Source: https://github.com/molecularai/aizynthfinder/blob/master/docs/configuration.rst Configuration using environment variables for search parameters. Ensure the corresponding environment variables are set before running. ```yaml search: iteration_limit: ${ITERATION_LIMIT} algorithm_config: C: ${C} time_limit: ${TIME_LIMIT} max_transforms: ${MAX_TRANSFORMS} ``` -------------------------------- ### Generate Images of Reaction Routes Source: https://github.com/molecularai/aizynthfinder/blob/master/docs/cli.rst Create PNG images for the top-ranked reaction routes of the first target compound from the analysis data. This requires the pandas and ReactionTree modules. ```python import pandas as pd from aizynthfinder.reactiontree import ReactionTree data = pd.read_json("output.json.gz", orient="table") all_trees = data.trees.values # This contains a list of all the trees for all the compounds trees_for_first_target = all_trees[0] for itree, tree in enumerate(trees_for_first_target): imagefile = f"route{itree:03d}.png" ReactionTree.from_dict(tree).to_image().save(imagefile) ``` -------------------------------- ### Create MongoDB Stock from SMILES Source: https://github.com/molecularai/aizynthfinder/blob/master/docs/stocks.rst Command-line tool to create a MongoDB stock database from one or more SMILES files. Specify a target name for the database. ```bash smiles2stock --files file1.smi file2.smi --output my_db --target mongo ``` -------------------------------- ### Create HDF5 Stock from SMILES Source: https://github.com/molecularai/aizynthfinder/blob/master/docs/stocks.rst Command-line tool to create an HDF5 stock file from one or more SMILES files. Each line in the input files should contain a single SMILES string. ```bash smiles2stock --files file1.smi file2.smi --output stock.hdf5 ``` -------------------------------- ### Configure Retro* with Oracle Function Source: https://github.com/molecularai/aizynthfinder/blob/master/docs/howto.rst Configure Retro* to use a specific oracle function by providing the molecule cost details, including the model path and fingerprint parameters. ```yaml search: algorithm: aizynthfinder.search.retrostar.search_tree.SearchTree algorithm_config: molecule_cost: cost: aizynthfinder.search.retrostar.cost.RetroStarCost model_path: retrostar_value_model.pickle fingerprint_length: 2048 fingerprint_radius: 2 dropout_rate: 0.1 ``` -------------------------------- ### Select Stock and Policies Source: https://github.com/molecularai/aizynthfinder/blob/master/docs/python_interface.rst Select the desired stock and policies (expansion and filter) for the AiZynthFinder instance. The keys 'zinc' and 'uspto' must correspond to entries in the configuration file. ```python finder.stock.select("zinc") finder.expansion_policy.select("uspto") finder.filter_policy.select("uspto") ``` -------------------------------- ### Configure All Routes Output Source: https://github.com/molecularai/aizynthfinder/blob/master/docs/howto.rst Configure `aizynthcli` to extract all solved routes, falling back to `min_routes` and `max_routes` if a target is unsolved. This ensures maximum data retrieval for solvable targets. ```yaml post_processing: min_routes: 5 max_routes: 10 all_routes: True ``` -------------------------------- ### Import AiZynthFinder Class Source: https://github.com/molecularai/aizynthfinder/blob/master/docs/python_interface.rst Import the main AiZynthFinder class from the aizynthfinder library. ```python from aizynthfinder.aizynthfinder import AiZynthFinder ``` -------------------------------- ### Run AiZynthFinder in Batch Mode Source: https://github.com/molecularai/aizynthfinder/blob/master/docs/index.rst Executes the aizynthcli script for batch-mode tree search. Requires a configuration file and a text file with SMILES strings. ```bash aizynthcli --config config.yml --smiles smiles.txt ``` -------------------------------- ### Download Public Data Source: https://github.com/molecularai/aizynthfinder/blob/master/docs/index.rst Downloads public data for AiZynthFinder. This data includes a trained model and a stock collection. ```bash download_public_data . ``` -------------------------------- ### Configure Multiple Expansion Policies Source: https://github.com/molecularai/aizynthfinder/blob/master/docs/howto.rst Enable the use of multiple expansion policies, such as combining a general USPTO model with a RingBreaker model. The `multi_expansion_strategy` defines how these policies are combined. ```yaml expansion: uspto: - uspto_keras_model.hdf5 - uspto_unique_templates.csv.gz ringbreaker: - uspto_ringbreaker_keras_model.hdf5 - uspto_ringbreaker_unique_templates.csv.gz multi_expansion_strategy: type: aizynthfinder.context.policy.MultiExpansionStrategy expansion_strategies: [uspto, ringbreaker] additive_expansion: True ``` -------------------------------- ### Run Batch Tree Search Source: https://github.com/molecularai/aizynthfinder/blob/master/docs/cli.rst Execute a batch tree search using a configuration file and a SMILES file. Ensure your configuration file specifies paths to policy models and stocks, and the SMILES file contains one SMILES per line. ```bash aizynthcli --config config_local.yml --smiles smiles.txt ``` -------------------------------- ### Download Public Data Source: https://github.com/molecularai/aizynthfinder/blob/master/README.md Download necessary data files (stock, policy networks) for AiZynthFinder to a specified folder and generate a config.yml. ```bash download_public_data my_folder ``` -------------------------------- ### Advanced AI-ZynthFinder Configuration Source: https://github.com/molecularai/aizynthfinder/blob/master/docs/configuration.rst Comprehensive configuration including MCTS search parameters, custom expansion policies, filter models, and stock definitions. Paths to models and templates must be valid. ```yaml search: algorithm: mcts algorithm_config: C: 1.4 default_prior: 0.5 use_prior: True prune_cycles_in_search: True search_rewards: - state score max_transforms: 6 iteration_limit: 100 return_first: false time_limit: 120 exclude_target_from_stock: True break_bonds: [[1, 2], [2, 3]] freeze_bonds: [[3, 4]] break_bonds_operator: or expansion: my_policy: type: template-based model: /path/to/keras/model/weights.hdf5 template: /path/to/hdf5/templates.hdf5 template_column: retro_template cutoff_cumulative: 0.995 cutoff_number: 50 use_rdchiral: True use_remote_models: False my_full_policy: - /path/to/keras/model/weights.hdf5 - /path/to/hdf5/templates.hdf5 filter: uspto: type: quick-filter model: /path/to/keras/model/weights.hdf5 exclude_from_policy: rc filter_cutoff: 0.05 use_remote_models: False uspto_full: /path/to/keras/model/weights.hdf5 stock: buyables: type: inchiset path: /path/to/stock1.hdf5 emolecules: /path/to/stock1.hdf5 ``` -------------------------------- ### Create Pandas DataFrame from Reaction Metadata Source: https://github.com/molecularai/aizynthfinder/blob/master/docs/python_interface.rst Collect metadata from all reactions in the expansion results and organize it into a pandas DataFrame. ```python import pandas as pd metadata = [] for reaction_tuple in reactions: for reaction in reaction_tuple: metadata.append(reaction.metadata) df = pd.DataFrame(metadata) ``` -------------------------------- ### Use Custom SMILES Extractor with smiles2stock Source: https://github.com/molecularai/aizynthfinder/blob/master/docs/stocks.rst Command to create a stock using a custom SMILES extraction module. Ensure the module is in a Python path and specify it using the --source module option. ```bash export PYTHONPATH=`pwd` smiles2stock --files load_zinc file1.smi file2.smi --source module --output stock.hdf5 ``` -------------------------------- ### Run AiZynthFinder with Single SMILES Source: https://github.com/molecularai/aizynthfinder/blob/master/docs/index.rst Executes the aizynthcli script for batch-mode tree search on a single molecule specified directly on the command line. ```bash aizynthcli --config config.yml --smiles "COc1cccc(OC(=O)/C=C/c2cc(OC)c(OC)c(OC)c2)c1" ``` -------------------------------- ### Configure Disconnection-Aware Chemformer Expansion Source: https://github.com/molecularai/aizynthfinder/blob/master/docs/howto.rst Set up a multi-expansion policy that includes a disconnection-aware Chemformer strategy. This requires specifying the Chemformer API URL and other parameters like `n_beams` and `cutoff_number`. ```yaml expansion: standard: type: template-based model: path/to/model template: path/to/templates chemformer_disconnect: type: expansion_strategies.DisconnectionAwareExpansionStrategy url: "http://localhost:8023/chemformer-disconnect-api/predict-disconnection" n_beams: 5 multi_expansion: type: aizynthfinder.context.policy.MultiExpansionStrategy expansion_strategies: [chemformer_disconnect, standard] additive_expansion: True cutoff_number: 50 ``` -------------------------------- ### Configure MongoDB Stock Source: https://github.com/molecularai/aizynthfinder/blob/master/docs/stocks.rst Specify MongoDB connection details and collection for compound lookups. Defaults to localhost, stock_db, and molecules if no options are provided. ```yaml stock: type: mongodb host: user@myurl.com database: database_name collection: compounds ``` -------------------------------- ### Build Routes and Extract Statistics Source: https://github.com/molecularai/aizynthfinder/blob/master/docs/python_interface.rst After the tree search, build the possible routes and extract statistical information about the search results. The build_routes method must be called before analysis. ```python finder.build_routes() stats = finder.extract_statistics() ``` -------------------------------- ### Specify Custom Stock in Configuration Source: https://github.com/molecularai/aizynthfinder/blob/master/docs/stocks.rst Configure AiZynthFinder to use a custom stock class directly from the configuration file. The class must be located in a Python module known to the interpreter. ```yaml stock: type: aizynthfinder.contrib.stocks.CriteriaStock ``` -------------------------------- ### Add Custom Scorer to AiZynthApp Source: https://github.com/molecularai/aizynthfinder/blob/master/docs/scoring.rst Demonstrates how to add a custom scorer to an AiZynthApp instance. This involves creating the scorer object and loading it into the finder's scorers collection. ```python from aizynthfinder.interfaces import AiZynthApp app = AiZynthApp("config_local.yml", setup=False) scorer = DeltaNumberOfTransformsScorer(app.finder.config) app.finder.scorers.load(scorer) app.setup() ``` -------------------------------- ### Run Pytest Tests Source: https://github.com/molecularai/aizynthfinder/blob/master/README.md Execute all tests using the pytest package. ```bash pytest -v ``` -------------------------------- ### Read Output JSON Source: https://github.com/molecularai/aizynthfinder/blob/master/docs/cli.rst Load the default output JSON file generated by aizynthcli into a pandas DataFrame for analysis. This file typically contains statistics and routes for multiple target compounds. ```python import pandas as pd data = pd.read_json("output.json.gz", orient="table") ``` -------------------------------- ### Configure Stop Criteria Source: https://github.com/molecularai/aizynthfinder/blob/master/docs/stocks.rst Define stop criteria for tree search based on price and element counts. Requires the stock query class to support price and amount querying. ```yaml stock: stop_criteria: price: 10 counts: C: 10 ``` -------------------------------- ### Perform Expansion Source: https://github.com/molecularai/aizynthfinder/blob/master/docs/python_interface.rst Perform molecular expansion using the configured expander and a target SMILES string. The filter policy is optional and affects feasibility, not filtering. ```python reactions = expander.do_expansion("Cc1cccc(c1N(CC(=O)Nc2ccc(cc2)c3ncon3)C(=O)C4CCS(=O)(=O)CC4)C") ``` -------------------------------- ### Set Target SMILES and Perform Tree Search Source: https://github.com/molecularai/aizynthfinder/blob/master/docs/python_interface.rst Set the target molecule using its SMILES string and initiate the tree search process. ```python finder.target_smiles = "Cc1cccc(c1N(CC(=O)Nc2ccc(cc2)c3ncon3)C(=O)C4CCS(=O)(=O)CC4)C" finder.tree_search() ``` -------------------------------- ### Configure Bond Constraints for MO-MCTS Source: https://github.com/molecularai/aizynthfinder/blob/master/docs/howto.rst Specify bond constraints for disconnection-aware retrosynthesis. This involves defining `break_bonds` and `freeze_bonds` under the `search` configuration, and including 'broken bonds' in `search_rewards`. ```yaml search: break_bonds: [[1, 2], [3, 4]] freeze_bonds: [] algorithm_config: search_rewards: ["state score", "broken bonds"] ``` -------------------------------- ### Extract Reactants SMILES from Reactions Source: https://github.com/molecularai/aizynthfinder/blob/master/docs/python_interface.rst Iterate through the results of an expansion to extract the SMILES strings of the reactants from each reaction. ```python reactants_smiles = [] for reaction_tuple in reactions: reactants_smiles.append([mol.smiles for mol in reaction_tuple[0].reactants[0]) ``` -------------------------------- ### Configure Route Scorers for MO-Tree Ranking Source: https://github.com/molecularai/aizynthfinder/blob/master/docs/howto.rst Specify route scorers for multi-objective tree ranking and building. This configuration ensures that routes are evaluated based on multiple criteria, such as 'state score' and 'broken bonds'. ```yaml post_processing: route_scorers: ["state score", "broken bonds"] ``` -------------------------------- ### Access Finder and Extract Statistics Source: https://github.com/molecularai/aizynthfinder/blob/master/docs/gui.rst Retrieves the finder object from the app and extracts search statistics. This is used after a tree search has been completed. ```python finder = app.finder stats = finder.extract_statistics() ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.