### Core Installation using pip Source: https://github.com/microsoft/syntheseus/blob/main/docs/installation.md Installs the core version of Syntheseus using pip. This is suitable for building and benchmarking models. ```bash conda env create -f environment.yml conda activate syntheseus pip install syntheseus ``` -------------------------------- ### Installing Syntheseus without Dependencies Source: https://github.com/microsoft/syntheseus/blob/main/docs/installation.md Installs Syntheseus in editable mode without any dependencies. Manual installation of required dependencies will be necessary. ```bash pip install -e . --no-dependencies ``` -------------------------------- ### Full Installation from GitHub Source: https://github.com/microsoft/syntheseus/blob/main/docs/installation.md Installs the full version of Syntheseus from GitHub using pip in editable mode, including all optional dependencies. ```bash conda env create -f environment_full.yml conda activate syntheseus-full pip install -e ".[all]" ``` -------------------------------- ### Install syntheseus-paroutes Source: https://github.com/microsoft/syntheseus/blob/main/docs/tutorials/paroutes_benchmark.ipynb Install the third-party wrapper for the PaRoutes benchmark using pip. ```bash pip install syntheseus-paroutes ``` -------------------------------- ### Installing a Subset of Dependencies Source: https://github.com/microsoft/syntheseus/blob/main/docs/installation.md Installs Syntheseus with a specific subset of dependencies, such as LocalRetro and RootAligned, by specifying them in the pip install command. ```bash pip install -e ".[local-retro,root-aligned]" ``` -------------------------------- ### Core Installation from GitHub Source: https://github.com/microsoft/syntheseus/blob/main/docs/installation.md Installs the core version of Syntheseus directly from GitHub using pip in editable mode. This provides the latest changes. ```bash conda env create -f environment.yml conda activate syntheseus pip install -e . ``` -------------------------------- ### Create example molecules Source: https://github.com/microsoft/syntheseus/blob/main/docs/tutorials/paroutes_benchmark.ipynb Create benzene and decane molecules for testing purposes. `make_rdkit_mol=False` is used to avoid RDKit dependency for this example. ```python benzene = Molecule("c1ccccc1", make_rdkit_mol=False) decane = Molecule("C"*10, make_rdkit_mol=False) benzene, decane ``` -------------------------------- ### Install Syntheseus via Pip Source: https://github.com/microsoft/syntheseus/blob/main/README.md Install the Syntheseus package using pip, with support for all optional features. ```bash pip install "syntheseus[all]" ``` -------------------------------- ### JSONL Data Format Example Source: https://github.com/microsoft/syntheseus/blob/main/docs/cli/eval_single_step.md This example shows the structure of a single reaction entry in a JSONL file. The evaluation script uses reactant and product SMILES for metrics. ```json {"reactants": [{"smiles": "Cc1ccc(Br)cc1"}, {"smiles": "Cc1ccc(B(O)O)cc1"}], "products": [{"smiles": "Cc1ccc(-c2ccc(C)cc2)cc1"}]} ``` -------------------------------- ### Configure and Run Retro* Search Source: https://github.com/microsoft/syntheseus/blob/main/docs/tutorials/custom_model.ipynb Set up the Retro* search algorithm with the custom model, a molecule inventory, and various limits (iterations, model calls, time). This example uses a constant node evaluator and reaction model log probability for cost calculation. ```python from syntheseus.search.analysis.route_extraction import ( iter_routes_time_order, ) from syntheseus.search.mol_inventory import SmilesListInventory from syntheseus.search.algorithms.best_first.retro_star import ( RetroStarSearch ) from syntheseus.search.node_evaluation.common import ( ConstantNodeEvaluator, ReactionModelLogProbCost, ) def get_routes(model): search_algorithm = RetroStarSearch( reaction_model=model, mol_inventory=SmilesListInventory(smiles_list=["C"]), limit_iterations=100, # max number of algorithm iterations limit_reaction_model_calls=100, # max number of model calls time_limit_s=60.0, # max runtime in seconds value_function=ConstantNodeEvaluator(0.0), and_node_cost_fn=ReactionModelLogProbCost(), ) output_graph, _ = search_algorithm.run_from_mol( Molecule("CCCCCCCC") ) routes = list( iter_routes_time_order(output_graph, max_routes=100) ) print(f"Found {len(routes)} routes") return output_graph, routes ``` -------------------------------- ### Install Syntheseus with Full Extras Source: https://github.com/microsoft/syntheseus/blob/main/README.md Use this command to create a Conda environment with all necessary dependencies for Syntheseus, including specific PyTorch versions. ```bash conda env create -f environment_full.yml conda activate syntheseus-full ``` -------------------------------- ### Cloning the Syntheseus Repository Source: https://github.com/microsoft/syntheseus/blob/main/docs/installation.md Clones the Syntheseus repository from GitHub to install directly from source. ```bash git clone https://github.com/microsoft/syntheseus.git cd syntheseus ``` -------------------------------- ### Run Multi-Step Synthesis Search Source: https://github.com/microsoft/syntheseus/blob/main/docs/tutorials/quick_start.ipynb Execute the multi-step synthesis search algorithm starting from a target molecule. This explores possible reaction pathways. ```python output_graph, _ = search_algorithm.run_from_mol(test_mol) ``` -------------------------------- ### SMILES Data Format Example Source: https://github.com/microsoft/syntheseus/blob/main/docs/cli/eval_single_step.md This example shows the compact SMILES format for reaction data, where each line represents a reaction. Data is processed similarly to the CSV format. ```text [cH:1]1[cH:2][c:3]([CH3:4])[cH:5][cH:6][c:7]1Br.B(O)(O)[c:8]1[cH:9][cH:10][c:11]([CH3:12])[cH:13][cH:14]1>>[cH:1]1[cH:2][c:3]([CH3:4])[cH:5][cH:6][c:7]1[c:8]2[cH:14][cH:13][c:11]([CH3:12])[cH:10][cH:9]2 ``` -------------------------------- ### Get Routes with Unbalanced Model and Visualize Source: https://github.com/microsoft/syntheseus/blob/main/docs/tutorials/custom_model.ipynb Obtain synthesis routes using the `ToyModelUnbalanced` with caching enabled and visualize the first route found. This confirms that the 'maximally unbalanced' route is prioritized. ```python output_graph, routes = get_routes( ToyModelUnbalanced(use_cache=True) ) visualize_andor( output_graph, filename=f"route_first_unbalanced.pdf", nodes=routes[0], ) ``` -------------------------------- ### CSV Data Format Example Source: https://github.com/microsoft/syntheseus/blob/main/docs/cli/eval_single_step.md This example demonstrates the CSV format for reaction data, commonly used for USPTO data. The script extracts reaction SMILES from the 'reactants>reagents>production' column. ```csv id,class,reactants>reagents>production ID,UNK,[cH:1]1[cH:2][c:3]([CH3:4])[cH:5][cH:6][c:7]1Br.B(O)(O)[c:8]1[cH:9][cH:10][c:11]([CH3:12])[cH:13][cH:14]1>>[cH:1]1[cH:2][c:3]([CH3:4])[cH:5][cH:6][c:7]1[c:8]2[cH:14][cH:13][c:11]([CH3:12])[cH:10][cH:9]2 ``` -------------------------------- ### Get First Solution Time Source: https://github.com/microsoft/syntheseus/blob/main/docs/tutorials/paroutes_benchmark.ipynb Compute and print the first solution time for each algorithm using the get_first_solution_time function. ```python from syntheseus.search.analysis.solution_time import get_first_solution_time for alg_name, graph in alg_name_to_graph.items(): print(f"{alg_name} first solution: {get_first_solution_time(graph)}") ``` -------------------------------- ### Get RetroChimeraModel Directory Source: https://github.com/microsoft/syntheseus/blob/main/docs/tutorials/quick_start.ipynb Print the directory where the RetroChimera model checkpoint is stored. This is useful for verifying the cache location. ```python print(model.model_dir) ``` -------------------------------- ### Define a Toy BackwardReactionModel Source: https://github.com/microsoft/syntheseus/blob/main/docs/tutorials/custom_model.ipynb Implement a custom model by inheriting from BackwardReactionModel and overriding the _get_reactions method. This example model handles molecules that are chains of carbon atoms. ```python from typing import Sequence from syntheseus import Bag, Molecule, SingleProductReaction class ToyModel(BackwardReactionModel): def _get_reactions( self, inputs: list[Molecule], num_results: int ) -> list[Sequence[SingleProductReaction]]: return [ self._get_reactions_single(mol)[:num_results] for mol in inputs ] def _get_reaction_score(self, i: int, n_atoms: int) -> float: # Give higher score to reactions which break the input into # equal-sized pieces. return float(min(i, n_atoms - i)) def _get_reactions_single( self, mol: Molecule ) -> Sequence[SingleProductReaction]: n = len(mol.smiles) if mol.smiles != n * "C": return [] scores = [self._get_reaction_score(i, n) for i in range(1, n)] score_total = sum(scores) probs = [score / score_total for score in scores] reactions = [] for i, prob in zip(range(1, n), probs): reactant_1 = Molecule(i * "C") reactant_2 = Molecule((n - i) * "C") reactions.append( SingleProductReaction( reactants=Bag([reactant_1, reactant_2]), product=mol, metadata={"probability": prob}, ) ) return sorted( reactions, key=lambda r: r.metadata["probability"], reverse=True, ) ``` -------------------------------- ### Get Target Molecule SMILES Source: https://github.com/microsoft/syntheseus/blob/main/docs/tutorials/paroutes_benchmark.ipynb Retrieves the RDKit molecule object for a target molecule using its SMILES string. ```python target_mol = Molecule(test_smiles[100]) target_mol.rdkit_mol ``` -------------------------------- ### Set up Multi-Step Search Components Source: https://github.com/microsoft/syntheseus/blob/main/docs/tutorials/quick_start.ipynb Initialize the necessary components for a multi-step synthesis search: a reaction model with caching, a molecule inventory, and a search algorithm (AndOr_BreadthFirstSearch). ```python from syntheseus.search.mol_inventory import SmilesListInventory from syntheseus.search.algorithms.breadth_first import ( AndOr_BreadthFirstSearch ) # Set up a reaction model with caching enabled. Number of reactions # to request from the model at each step of the search needs to be # provided at construction time. model = RetroChimeraModel(use_cache=True, default_num_results=3) # Dummy inventory with just two purchasable molecules. inventory = SmilesListInventory( smiles_list=[ "COB(OC)OC", "CCCCOB(OCCCC)OCCCC", "COc1ccc(Br)cc1", "Fc1ccc(I)cc1", ] ) search_algorithm = AndOr_BreadthFirstSearch( reaction_model=model, mol_inventory=inventory, limit_iterations=10, # max number of algorithm iterations limit_reaction_model_calls=10, # max number of model calls time_limit_s=30.0 # max runtime in seconds ) ``` -------------------------------- ### Import core Syntheseus modules Source: https://github.com/microsoft/syntheseus/blob/main/docs/tutorials/paroutes_benchmark.ipynb Import necessary modules for working with molecules and reactions in Syntheseus. ```python from __future__ import annotations import math from pprint import pprint ``` ```python from syntheseus import Molecule, SingleProductReaction ``` -------------------------------- ### Initialize ReactionModelLogProbCost Source: https://github.com/microsoft/syntheseus/blob/main/docs/tutorials/paroutes_benchmark.ipynb Initializes the ReactionModelLogProbCost for use in the RetroStar algorithm. Set normalize to False to use raw probabilities. ```python and_node_cost_fn = ReactionModelLogProbCost(normalize=False) ``` -------------------------------- ### Initialize RetroChimeraModel Source: https://github.com/microsoft/syntheseus/blob/main/docs/tutorials/quick_start.ipynb Load the RetroChimera model. If no model directory is specified, a default checkpoint will be downloaded and cached. ```python from syntheseus import Molecule from syntheseus.reaction_prediction.inference import RetroChimeraModel test_mol = Molecule("COc1ccc(-c2ccc(F)cc2)cc1") model = RetroChimeraModel() ``` -------------------------------- ### Run Single-step Evaluation Source: https://github.com/microsoft/syntheseus/blob/main/docs/cli/eval_single_step.md This command initiates the single-step evaluation process. Ensure to replace placeholders like [DATA_DIR] with your specific paths and configurations. ```bash syntheseus eval-single-step \ data_dir=[DATA_DIR] \ fold=[TRAIN, VAL or TEST] \ model_class=[MODEL_CLASS] \ model_dir=[MODEL_DIR] ``` -------------------------------- ### Configure MCTS Search Algorithm Source: https://github.com/microsoft/syntheseus/blob/main/docs/tutorials/paroutes_benchmark.ipynb Initializes the MolSetMCTS algorithm with the reaction model, inventory, reward function, value function, policy, and resource limits. ```python from syntheseus.search.algorithms.mcts.base import pucb_bound from syntheseus.search.algorithms.mcts.molset import MolSetMCTS mcts_alg = MolSetMCTS( reaction_model=reaction_model, mol_inventory=inventory, reward_function=mcts_reward_function, value_function=mcts_value_function, policy=mcts_policy, limit_reaction_model_calls=RXN_MODEL_CALL_LIMIT, bound_constant=100.0, bound_function=pucb_bound, time_limit_s=TIME_LIMIT_S, ) ``` -------------------------------- ### Basic Syntheseus Search Command Source: https://github.com/microsoft/syntheseus/blob/main/docs/cli/search.md Use this command to initiate a molecular search. Provide paths to your SMILES files for search targets and the purchasable molecule inventory, along with the model class and directory. Set a time limit in seconds for each target search. ```bash syntheseus search \ search_targets_file=[SMILES_FILE_WITH_SEARCH_TARGETS] \ inventory_smiles_file=[SMILES_FILE_WITH_PURCHASABLE_MOLECULES] \ model_class=[MODEL_CLASS] \ model_dir=[MODEL_DIR] \ time_limit_s=[NUMBER_OF_SECONDS_PER_TARGET] ``` -------------------------------- ### Import Retro-star algorithm components Source: https://github.com/microsoft/syntheseus/blob/main/docs/tutorials/paroutes_benchmark.ipynb Import the Retro-star search algorithm and necessary graph node types from Syntheseus. ```python from syntheseus.search.algorithms.best_first import retro_star from syntheseus.search.graph.and_or import AndNode, OrNode, AndOrGraph from syntheseus.search.node_evaluation.common import ReactionModelLogProbCost ``` -------------------------------- ### Load PaRoutes inventory Source: https://github.com/microsoft/syntheseus/blob/main/docs/tutorials/paroutes_benchmark.ipynb Load the PaRoutes inventory and print its size and the first few purchasable molecules. ```python # Load inventory and print some info from syntheseus_paroutes import PaRoutesInventory inventory = PaRoutesInventory(n=PAROUTES_N) print(f"Size of inventory: {len(inventory)}") print("First few molecules in inventory:") pprint(list(inventory.to_purchasable_mols())[:5]) ``` -------------------------------- ### Visualize Synthesis Routes Source: https://github.com/microsoft/syntheseus/blob/main/docs/tutorials/quick_start.ipynb Generate PDF visualizations for the extracted synthesis routes. This provides a graphical representation of the reaction pathways. ```python from syntheseus.search.visualization import visualize_andor for idx, route in enumerate(routes): visualize_andor( output_graph, filename=f"route_{idx + 1}.pdf", nodes=route ) ``` -------------------------------- ### Initialize ReactionModelProbPolicy for MCTS Source: https://github.com/microsoft/syntheseus/blob/main/docs/tutorials/paroutes_benchmark.ipynb Configures the policy for MCTS using softmax values from the reaction model, scaled by temperature and normalized. ```python mcts_policy = ReactionModelProbPolicy(normalize=True, temperature=3.0) ``` -------------------------------- ### Import BackwardReactionModel Source: https://github.com/microsoft/syntheseus/blob/main/docs/tutorials/custom_model.ipynb Import the necessary base class for creating custom backward reaction models. ```python from syntheseus import BackwardReactionModel ``` -------------------------------- ### Create Algorithm Name to Graph Mapping Source: https://github.com/microsoft/syntheseus/blob/main/docs/tutorials/paroutes_benchmark.ipynb Creates a dictionary to easily access the search graphs generated by RetroStar and MCTS algorithms. ```python alg_name_to_graph = { "retro star": retro_star_search_graph, "mcts": mcts_search_graph, } ``` -------------------------------- ### Configure RetroStar Search Algorithm Source: https://github.com/microsoft/syntheseus/blob/main/docs/tutorials/paroutes_benchmark.ipynb Configures and initializes the RetroStar search algorithm with specified reaction model, inventory, cost functions, value function, and resource limits. ```python retro_star_alg = retro_star.RetroStarSearch( reaction_model=reaction_model, mol_inventory=inventory, or_node_cost_fn=or_node_cost_fn, and_node_cost_fn=and_node_cost_fn, value_function=retro_star_value_function, limit_reaction_model_calls=RXN_MODEL_CALL_LIMIT, time_limit_s=TIME_LIMIT_S, ) ``` -------------------------------- ### Visualize Synthesis Routes Source: https://github.com/microsoft/syntheseus/blob/main/docs/tutorials/paroutes_benchmark.ipynb Visualize the first extracted route for 'retro star' using visualize_andor and for 'mcts' using visualize_molset. ```python # The routes can be visualized with the code below. from syntheseus.search import visualization visualization.visualize_andor( alg_name_to_graph["retro star"], filename="retro star route.pdf", nodes=alg_name_to_routes["retro star"][0] ) visualization.visualize_molset( alg_name_to_graph["mcts"], filename="mcts route.pdf", nodes=alg_name_to_routes["mcts"][0] ) ``` -------------------------------- ### Extract Synthesis Routes Source: https://github.com/microsoft/syntheseus/blob/main/docs/tutorials/paroutes_benchmark.ipynb Extract a limited number of minimum cost synthesis routes (up to 10,000) for each algorithm and store them. The '%%time' magic command measures execution time. ```python %%time from syntheseus.search.analysis import route_extraction alg_name_to_routes = dict() for alg_name, graph in alg_name_to_graph.items(): routes = list(route_extraction.iter_routes_cost_order(graph, 10_000)) print(f"Found {len(routes)} routes for {alg_name}", flush=True) alg_name_to_routes[alg_name] = routes del routes ``` -------------------------------- ### Initialize ConstantNodeEvaluator for RetroStar Source: https://github.com/microsoft/syntheseus/blob/main/docs/tutorials/paroutes_benchmark.ipynb Sets up a constant value function for the RetroStar algorithm, representing the most optimistic search (retro*-0). ```python from syntheseus.search.node_evaluation.common import ConstantNodeEvaluator retro_star_value_function = ConstantNodeEvaluator(0.0) ``` -------------------------------- ### Instantiate and Test Custom Model Source: https://github.com/microsoft/syntheseus/blob/main/docs/tutorials/custom_model.ipynb Create an instance of the custom model and test its predictions with a sample molecule. The `__call__` method is used for model invocation, allowing Syntheseus to manage caching and deduplication. ```python model = ToyModel() def print_predictions(model, smiles: str): [reactions] = model([Molecule(smiles)]) for reaction in reactions: probability = reaction.metadata["probability"] print(f"{reaction} (probability: {probability:.3f})") print_predictions(model, "CCCC") ``` -------------------------------- ### Compare Multiple Reaction Models Source: https://github.com/microsoft/syntheseus/blob/main/docs/tutorials/quick_start.ipynb Iterate through a list of different reaction models, predict reactions for the same test molecule, and print the top prediction from each. This is useful for comparing model performance. ```python from syntheseus.reaction_prediction.inference import * models = [ ChemformerModel(), Graph2EditsModel(), LocalRetroModel(), MEGANModel(), MHNreactModel(), RetroChimeraModel(), RetroChimeraEditModel(), RetroChimeraDeNovoModel(), RetroKNNModel(), RootAlignedModel(), ] for model in models: # When interested in very few predictions (e.g. one), it may be # useful to set `num_results > 1`, as this will cause e.g. # larger beam size for models based on beam search. [results] = model([test_mol], num_results=5) top_prediction = results[0].reactants print(f"{model.name + ':':12} {mols_to_str(top_prediction)}") ``` -------------------------------- ### Load PaRoutes reaction model Source: https://github.com/microsoft/syntheseus/blob/main/docs/tutorials/paroutes_benchmark.ipynb Load the PaRoutes reaction model. `use_cache=True` is important for performance during search. ```python # Load reaction model (same model for both `n`) from syntheseus_paroutes import PaRoutesModel reaction_model = PaRoutesModel( use_cache=True # IMPORTANT, since it will be used for search ) print("First few predicted reactions for decane:\n") pprint(list(map(str, reaction_model([decane], num_results=3)[0]))) print("\n\n\nFirst few predicted reactions for benzene:\n") pprint(list(map(str, reaction_model([benzene], num_results=3)[0]))) ``` -------------------------------- ### Load target SMILES list Source: https://github.com/microsoft/syntheseus/blob/main/docs/tutorials/paroutes_benchmark.ipynb Load the list of target SMILES for the benchmark and print the count and first few entries. ```python # Load test smiles from syntheseus_paroutes import get_target_smiles_list test_smiles = get_target_smiles_list(n=PAROUTES_N) print(f"Number of test SMILES: {len(test_smiles)}") print("First test SMILES:") pprint(test_smiles[:5]) ``` -------------------------------- ### Initialize ConstantNodeEvaluator for MCTS Value Function Source: https://github.com/microsoft/syntheseus/blob/main/docs/tutorials/paroutes_benchmark.ipynb Sets up a constant value function for MCTS, estimating rewards attainable from a state. A value of 0.5 is used as a demonstration. ```python mcts_value_function = ConstantNodeEvaluator(0.5) ``` -------------------------------- ### Run RetroStar Algorithm Source: https://github.com/microsoft/syntheseus/blob/main/docs/tutorials/paroutes_benchmark.ipynb Executes the RetroStar search algorithm from a target molecule, resetting the reaction model cache beforehand for a fair comparison. ```python retro_star_alg.reset() retro_star_search_graph, _ = retro_star_alg.run_from_mol(target_mol) ``` -------------------------------- ### Import MCTS Node and Graph Classes Source: https://github.com/microsoft/syntheseus/blob/main/docs/tutorials/paroutes_benchmark.ipynb Imports necessary classes for MCTS, including MolSetNode and MolSetGraph, for building the search graph. ```python from syntheseus.search.graph.molset import MolSetNode, MolSetGraph from syntheseus.search.node_evaluation.common import ReactionModelProbPolicy ``` -------------------------------- ### Visualize Synthesis Routes Source: https://github.com/microsoft/syntheseus/blob/main/docs/tutorials/custom_model.ipynb Visualize the first and last routes found by the search algorithm using `visualize_andor`. This function requires the output graph and the nodes representing the route. It helps in understanding the exploration strategy of the search. ```python from syntheseus.search.visualization import visualize_andor for name, idx in [("first", 0), ("last", -1)]: visualize_andor( output_graph, filename=f"route_{name}.pdf", nodes=routes[idx] ) ``` -------------------------------- ### Run MCTS Algorithm Source: https://github.com/microsoft/syntheseus/blob/main/docs/tutorials/paroutes_benchmark.ipynb Executes the MCTS algorithm from a target molecule, resetting the reaction model cache beforehand for a fair comparison. ```python mcts_alg.reset() mcts_search_graph, _ = mcts_alg.run_from_mol(target_mol) ``` -------------------------------- ### Initialize HasSolutionValueFunction for MCTS Reward Source: https://github.com/microsoft/syntheseus/blob/main/docs/tutorials/paroutes_benchmark.ipynb Sets up the reward function for MCTS, assigning a reward of 1.0 if a state is solved (all molecules purchasable) and 0.0 otherwise. ```python from syntheseus.search.node_evaluation.common import HasSolutionValueFunction mcts_reward_function = HasSolutionValueFunction() ``` -------------------------------- ### Execute Search with Cached Model Source: https://github.com/microsoft/syntheseus/blob/main/docs/tutorials/custom_model.ipynb Instantiate the custom model with caching enabled and then run the `get_routes` function to perform a multi-step search. This demonstrates how caching affects the number of model calls. ```python model = ToyModel(use_cache=True) output_graph, routes = get_routes(model) ``` -------------------------------- ### Run Pytest with Coverage Source: https://github.com/microsoft/syntheseus/blob/main/README.md Execute Pytest to run all tests and generate a code coverage report for the Syntheseus library. ```bash python -m pytest --cov syntheseus/tests ``` -------------------------------- ### Calculate Solution Time Source: https://github.com/microsoft/syntheseus/blob/main/docs/tutorials/paroutes_benchmark.ipynb Measure the wallclock time or number of calls to the reaction model for each node's creation time relative to the root node. ```python for graph in alg_name_to_graph.values(): for node in graph.nodes(): # Wallclock time: difference between this node's # creation time and that of the root node node.data["analysis_time"] = ( node.creation_time - graph.root_node.creation_time ).total_seconds() # Could alternatively use number of calls to reaction model # node.data["analysis_time"] = node.data["num_calls_rxn_model"] ``` -------------------------------- ### Extract and Count Synthesis Routes Source: https://github.com/microsoft/syntheseus/blob/main/docs/tutorials/quick_start.ipynb Extract complete synthesis routes from the search graph in chronological order and print the number of reactions in each route. This helps in identifying feasible synthesis plans. ```python from syntheseus.search.analysis.route_extraction import ( iter_routes_time_order, ) from syntheseus.search.graph.and_or import AndNode # Extract the routes in the order they were found. routes = list(iter_routes_time_order(output_graph, max_routes=10)) for idx, route in enumerate(routes): num_reactions = len({n for n in route if isinstance(n, AndNode)}) print(f"Route {idx + 1} consists of {num_reactions} reactions") ``` -------------------------------- ### Save Search Results Source: https://github.com/microsoft/syntheseus/blob/main/docs/tutorials/paroutes_benchmark.ipynb Saves the generated search graphs for both RetroStar and MCTS algorithms as pickle files for later analysis. ```python import pickle for graph, alg_name in [ (retro_star_search_graph, "retro star"), (mcts_search_graph, "mcts") ]: print(f"{alg_name} graph size: {len(graph)}") with open(f"search-results-{alg_name}.pkl", "wb") as f: pickle.dump(graph, f) ``` -------------------------------- ### Define search algorithm constants Source: https://github.com/microsoft/syntheseus/blob/main/docs/tutorials/paroutes_benchmark.ipynb Define constants for the reaction model call limit and time limit in seconds for search algorithms. ```python # Some constants for all algorithms RXN_MODEL_CALL_LIMIT = 100 TIME_LIMIT_S = 300 ``` -------------------------------- ### Implement Unbalanced Split Model Source: https://github.com/microsoft/syntheseus/blob/main/docs/tutorials/custom_model.ipynb Create a custom model `ToyModelUnbalanced` that inherits from `ToyModel` and overrides `_get_reaction_score` to strongly prefer unbalanced splits. This demonstrates how to modify search behavior by altering scoring mechanisms. ```python class ToyModelUnbalanced(ToyModel): def _get_reaction_score(self, i: int, n_atoms: int) -> float: score = super()._get_reaction_score(i, n_atoms) return (1.0 / score) ** 4.0 ``` -------------------------------- ### Check Model Call Count Source: https://github.com/microsoft/syntheseus/blob/main/docs/tutorials/custom_model.ipynb After running the search, query the model instance to determine how many times the reaction model was actually called, illustrating the impact of caching. ```python model.num_calls() ``` -------------------------------- ### Print Predictions with Unbalanced Model Source: https://github.com/microsoft/syntheseus/blob/main/docs/tutorials/custom_model.ipynb Use `print_predictions` to display the synthesis routes generated by the `ToyModelUnbalanced`. This shows the effect of the modified scoring on the predicted reaction probabilities. ```python print_predictions(ToyModelUnbalanced(), "CCCCCCCC") ``` -------------------------------- ### Predict Reactions with RetroChimeraModel Source: https://github.com/microsoft/syntheseus/blob/main/docs/tutorials/quick_start.ipynb Query the RetroChimera model for reaction predictions for a given molecule. The `num_results` parameter controls how many predictions are returned. ```python def mols_to_str(mols) -> str: return " + ".join([mol.smiles for mol in mols]) def print_results(results) -> None: for idx, prediction in enumerate(results): print(f"{idx + 1}: " + mols_to_str(prediction.reactants)) [results] = model([test_mol], num_results=5) print_results(results) ``` -------------------------------- ### Define Retro-star AndNode cost function Source: https://github.com/microsoft/syntheseus/blob/main/docs/tutorials/paroutes_benchmark.ipynb Define the cost function for AndNodes (reactions) in Retro-star. The cost is based on the -log(softmax) of the reaction model output, with a minimum threshold. ```python # 2: AndNode cost function # We will follow the original paper and define the cost of the # reaction as the -log(softmax) of the reaction model output, # thresholded at a minimum value. We use the built-in ``` -------------------------------- ### Count Explored Nodes in Search Graph Source: https://github.com/microsoft/syntheseus/blob/main/docs/tutorials/quick_start.ipynb Print the total number of nodes explored by the synthesis search algorithm. This indicates the breadth of the search. ```python print(f"Explored {len(output_graph)} nodes") ``` -------------------------------- ### Assign Route Costs Source: https://github.com/microsoft/syntheseus/blob/main/docs/tutorials/paroutes_benchmark.ipynb Assign a route cost of 1.0 to reaction nodes (AndNodes and MolSetNodes) and 0.0 to others. This cost is used to identify minimum cost routes. ```python for graph in alg_name_to_graph.values(): for node in graph.nodes(): if isinstance(node, (AndNode, MolSetNode)): node.data["route_cost"] = 1.0 else: node.data["route_cost"] = 0.0 ``` -------------------------------- ### Syntheseus BibTeX Citation Source: https://github.com/microsoft/syntheseus/blob/main/README.md BibTeX entry for citing the Syntheseus package in academic publications, referencing the associated paper from Faraday Discussions. ```bibtex @article{maziarz2024re, title={Re-evaluating retrosynthesis algorithms with syntheseus}, author={Maziarz, Krzysztof and Tripp, Austin and Liu, Guoqing and Stanley, Megan and Xie, Shufang and Gainski, Piotr and Seidl, Philipp and Segler, Marwin}, journal={Faraday Discussions}, year={2024}, publisher={Royal Society of Chemistry} } ``` -------------------------------- ### Calculate Route Diversity Source: https://github.com/microsoft/syntheseus/blob/main/docs/tutorials/paroutes_benchmark.ipynb Estimate the packing number of route sets using reaction Jaccard distance to find distinct routes with no common reactions. ```python from syntheseus.search.analysis import diversity for alg_name, graph in alg_name_to_graph.items(): route_objects = [ graph.to_synthesis_graph(nodes) for nodes in alg_name_to_routes[alg_name] ] packing_set = diversity.estimate_packing_number( routes=route_objects, distance_metric=diversity.reaction_jaccard_distance, radius=0.999 # because comparison uses ">", not ">=" ) print(f"{alg_name}: number of distinct routes = {len(packing_set)}") ``` -------------------------------- ### Define Retro-star OrNode cost function Source: https://github.com/microsoft/syntheseus/blob/main/docs/tutorials/paroutes_benchmark.ipynb Define the cost function for OrNodes (molecules) in Retro-star. Molecules are assigned a cost of 0 if purchasable, and infinity otherwise, following the original paper. ```python # 1: OrNode cost function. # We will follow the original paper and give molecules a # cost of 0 if they are purchasable, and a cost of infinity # otherwise. This class is provided as a default in retro_star. # If purchasable molecules have non-zero costs then a different # cost function could be used. or_node_cost_fn = retro_star.MolIsPurchasableCost() ``` -------------------------------- ### Count Model Calls with Cache Source: https://github.com/microsoft/syntheseus/blob/main/docs/tutorials/custom_model.ipynb Use `model.num_calls(count_cache=True)` to count all calls made to the model, including those that hit the cache. This helps in understanding the efficiency of caching mechanisms. ```python model.num_calls(count_cache=True) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.