### Install rxnutils via pip Source: https://molecularai.github.io/reaction_utils/_sources/index.rst.txt Standard installation command for end-users. ```bash pip install reaction-utils ``` -------------------------------- ### Install Metaflow and rxnutils Source: https://molecularai.github.io/reaction_utils/_sources/ord.rst.txt Install Metaflow and the local rxnutils package in the current environment. ```bash python -m pip install metaflow python -m pip install --no-deps --ignore-requires-python . ``` -------------------------------- ### Install rxnmapper environment Source: https://molecularai.github.io/reaction_utils/_sources/ord.rst.txt Create and configure the dedicated environment for rxnmapper. ```bash conda create -n rxnmapper python=3.6 -y conda activate rxnmapper conda install -c rdkit rdkit=2020.03.3.0 python -m pip install rxnmapper ``` -------------------------------- ### Setup developer environment Source: https://molecularai.github.io/reaction_utils/_sources/index.rst.txt Commands to initialize the development environment using conda and poetry. ```bash conda env create -f env-dev.yml conda activate rxn-env poetry install ``` -------------------------------- ### Install pre-commit hooks Source: https://molecularai.github.io/reaction_utils/_sources/index.rst.txt Command to enable pre-commit hooks for the repository. ```bash pre-commit install ``` -------------------------------- ### Install ord-schema Source: https://molecularai.github.io/reaction_utils/_sources/ord.rst.txt Install the ord-schema package within the rxnutils environment. ```bash conda activate rxn-env python -m pip install ord-schema ``` -------------------------------- ### StackColumns YAML Configuration Source: https://molecularai.github.io/reaction_utils/rxnutils.pipeline.actions.html Example configuration for stacking multiple columns into a single new column. ```yaml stack_columns: in_columns: * rsmi_processed * rsmi_inverted_stereo out_column: rsmi_processed ``` -------------------------------- ### StackMultiColumns YAML Configuration Source: https://molecularai.github.io/reaction_utils/rxnutils.pipeline.actions.html Example configuration for stacking target columns on top of stack columns. ```yaml stack_multi_columns: stack_columns: * rsmi_inverted_stereo * PseudoHash_inverted_stereo target_columns: * rsmi_processed * PseudoHash ``` -------------------------------- ### Define Pipeline Actions in YAML Source: https://molecularai.github.io/reaction_utils/_sources/pipeline.rst.txt Example configuration file specifying sequential actions for cleaning USPTO reaction data. ```yaml trim_rxn_smiles: in_column: ReactionSmiles out_column: ReactionSmilesClean remove_unsanitizable: in_column: ReactionSmilesClean out_column: ReactionSmilesClean reagents2reactants: in_column: ReactionSmilesClean out_column: ReactionSmilesClean remove_atom_mapping: in_column: ReactionSmilesClean out_column: ReactionSmilesClean reactantsize: in_column: ReactionSmilesClean productsize: in_column: ReactionSmilesClean query_dataframe1: query: "ReactantSize>0" query_dataframe2: query: "ProductSize>0" query_dataframe3: query: "ReactantSize+ProductSize<200" ``` -------------------------------- ### Example Route Text Format Source: https://molecularai.github.io/reaction_utils/routes.html A simple text file format where each reaction is represented as a reaction SMILES per line, with routes separated by newlines. ```text CC(C)N.Clc1cccc(Nc2ccoc2)n1>>CC(C)Nc1cccc(Nc2ccoc2)n1 Brc1ccoc1.Nc1cccc(Cl)n1>>Clc1cccc(Nc2ccoc2)n1 Nc1cccc(NC(C)C)n1.Brc1ccoc1>>CC(C)Nc1cccc(Nc2ccoc2)n1 CC(C)N.Nc1cccc(Cl)n1>>Nc1cccc(NC(C)C)n1 ``` -------------------------------- ### DropRows YAML Configuration Source: https://molecularai.github.io/reaction_utils/rxnutils.pipeline.actions.html Example configuration for dropping rows based on boolean indicator columns. ```yaml drop_rows: indicator_columns: * is_sanitizable * is_sanitizable2 ``` -------------------------------- ### RenameColumns YAML Configuration Source: https://molecularai.github.io/reaction_utils/rxnutils.pipeline.actions.html Example configuration for renaming existing columns to new names. ```yaml rename_columns: in_columns: * column1 * column2 out_columns: * column1_renamed * column2_renamed ``` -------------------------------- ### QueryDataframe YAML Configuration Source: https://molecularai.github.io/reaction_utils/rxnutils.pipeline.actions.html Example configuration for filtering rows using a pandas-compatible query string. ```yaml query_dataframe: query: has_stereo == True ``` -------------------------------- ### DropColumns YAML Configuration Source: https://molecularai.github.io/reaction_utils/rxnutils.pipeline.actions.html Example configuration for dropping specific columns from a dataframe. ```yaml drop_columns: columns: * NRingChange * RingBondMade ``` -------------------------------- ### Define Reaction SMILES Source: https://molecularai.github.io/reaction_utils/_sources/templates.rst.txt Example of an atom-mapped reaction SMILES string. ```text CCN(CC)CC.CCOCC.Cl[S:3]([CH2:2][CH3:1])(=[O:4])=[O:5].[OH:6][CH2:7][CH2:8][Br:9]>>[CH3:1][CH2:2][S:3](=[O:4])(=[O:5])[O:6][CH2:7][CH2:8][Br:9] ``` -------------------------------- ### Define a SMARTS library JSON format Source: https://molecularai.github.io/reaction_utils/rxnutils.chem.html Example of the expected JSON structure for a SMARTS library file, where keys are pattern names and values are SMARTS strings. ```json { > “ARC”: “[c]”, “ARN3”: “[n;X3]” > } ``` -------------------------------- ### KeepColumns YAML Configuration Source: https://molecularai.github.io/reaction_utils/rxnutils.pipeline.actions.html Example configuration for retaining only specified columns in a dataframe. ```yaml keep_columns: columns: * id * classification * rsmi_processed ``` -------------------------------- ### rxnutils.routes.scoring.route_ranks Source: https://molecularai.github.io/reaction_utils/rxnutils.routes.html Computes the rank of route scores, starting at 1. ```APIDOC ## route_ranks(scores) ### Description Compute the rank of route scores. Rank starts at 1. ### Parameters - **scores** (List[float]) - Required - The route scores. ### Returns - **List[int]** - A list of ranks for each route. ``` -------------------------------- ### rxnutils.chem.rinchi.download_rinchi.main() Source: https://molecularai.github.io/reaction_utils/rxnutils.chem.rinchi.html Checks if the Reaction InChI application is present on the system and downloads it if required. ```APIDOC ## main() ### Description Checks if the Reaction InChI application is present. Downloads it if it is required to do so. ### Returns - **path** (str) - Path of the folder containing the appropriate command line executable based on system type. ``` -------------------------------- ### rxnutils.pipeline.runner.main Source: https://molecularai.github.io/reaction_utils/rxnutils.pipeline.html Entry point for command-line execution of the pipeline. ```APIDOC ## main(args=None) ### Description Function for handling command-line arguments to trigger pipeline execution. ### Parameters - **args** (Sequence[str] | None) - Optional - Command line arguments. ``` -------------------------------- ### Run preparation pipeline Source: https://molecularai.github.io/reaction_utils/ord.html Execute the data preparation pipeline in the rxnutils environment. ```bash conda activate rxn-env python -m rxnutils.data.ord.preparation_pipeline run --nbatches 200 --max-workers 8 --max-num-splits 200 --ord-data ORD_DATA_REPO_PATH ``` -------------------------------- ### Run USPTO preparation pipeline Source: https://molecularai.github.io/reaction_utils/_sources/uspto.rst.txt Executes the data preparation pipeline within the rxnutils environment. ```bash conda activate rxn-env python -m rxnutils.data.uspto.preparation_pipeline run --nbatches 200 --max-workers 8 --max-num-splits 200 ``` -------------------------------- ### Run preparation and mapping pipelines Source: https://molecularai.github.io/reaction_utils/_sources/ord.rst.txt Execute the data preparation and mapping pipelines in their respective environments. ```bash conda activate rxn-env python -m rxnutils.data.ord.preparation_pipeline run --nbatches 200 --max-workers 8 --max-num-splits 200 --ord-data ORD_DATA_REPO_PATH ``` ```bash conda activate rxnmapper python -m rxnutils.data.mapping_pipeline run --data-prefix ord --nbatches 200 --max-workers 8 --max-num-splits 200 ``` -------------------------------- ### molecules_to_images(mols, frame_colors, size=300, draw_kwargs=None) Source: https://molecularai.github.io/reaction_utils/rxnutils.routes.html Creates pretty images of multiple molecules with colored frames, resizing them to be of similar sizes. ```APIDOC ## molecules_to_images(mols, frame_colors, size=300, draw_kwargs=None) ### Description Create pretty images of molecules with a colored frame around each one of them. The molecules will be resized to be of similar sizes. ### Parameters - **mols** (Sequence[Chem.rdchem.Mol]) - Required - The molecules to draw. - **frame_colors** (Sequence[PilColor]) - Required - The color of the frame for each molecule. - **size** (int) - Optional - The sub-image size (default: 300). - **draw_kwargs** (Dict[str, Any]) - Optional - Additional keyword-arguments sent to MolsToGridImage. ### Returns - **List[PilImage]** - The produced images. ``` -------------------------------- ### Run mapping pipeline Source: https://molecularai.github.io/reaction_utils/ord.html Execute the atom-mapping pipeline in the rxnmapper environment. ```bash conda activate rxnmapper python -m rxnutils.data.mapping_pipeline run --data-prefix ord --nbatches 200 --max-workers 8 --max-num-splits 200 ``` -------------------------------- ### Initialize ChemicalReaction Object Source: https://molecularai.github.io/reaction_utils/_sources/templates.rst.txt Create a ChemicalReaction object to encapsulate the reaction and perform curation. ```python from rxnutils.chem.reaction import ChemicalReaction reaction = "CCN(CC)CC.CCOCC.Cl[S:3]([CH2:2][CH3:1])(=[O:4])=[O:5].[OH:6][CH2:7][CH2:8][Br:9]>>[CH3:1][CH2:2][S:3](=[O:4])(=[O:5])[O:6][CH2:7][CH2:8][Br:9]" rxn = ChemicalReaction(reaction) ``` -------------------------------- ### Run USPTO mapping pipeline Source: https://molecularai.github.io/reaction_utils/_sources/uspto.rst.txt Executes the atom-mapping pipeline within the rxnmapper environment. ```bash conda activate rxnmapper python -m rxnutils.data.mapping_pipeline run --data-prefix uspto --nbatches 200 --max-workers 8 --max-num-splits 200 ``` -------------------------------- ### List Available Pipeline Actions Source: https://molecularai.github.io/reaction_utils/_sources/pipeline.rst.txt Command to display all registered actions available for use in the pipeline. ```bash python -m rxnutils.pipeline.runner --list ``` -------------------------------- ### rxnutils.pipeline.base.list_actions Source: https://molecularai.github.io/reaction_utils/rxnutils.pipeline.html Lists all available actions in a table format. ```APIDOC ## rxnutils.pipeline.base.list_actions(short=False) ### Description List all available actions in a nice table. ### Parameters - **short** (bool) - Optional - If True, displays a shortened list. ``` -------------------------------- ### reactions2route(reactions, metadata=None, ignore_stereo=True) Source: https://molecularai.github.io/reaction_utils/rxnutils.routes.html Converts a list of reactions into a retrosynthesis tree. ```APIDOC ## reactions2route(reactions, metadata=None, ignore_stereo=True) ### Description Convert a list of reactions into a retrosynthesis tree based on matching partial InChI keys. ### Parameters - **reactions** (Sequence[str]) - Required - List of reaction SMILES. - **metadata** (Sequence[Dict[str, Any]]) - Optional - List of metadata dictionaries for each reaction. - **ignore_stereo** (bool) - Optional - Whether to ignore stereochemistry when matching reactants and products. ### Returns - **SynthesisRoute** - The created trees. ``` -------------------------------- ### rxnutils.pipeline.base.create_action Source: https://molecularai.github.io/reaction_utils/rxnutils.pipeline.html Creates an action that can be called. ```APIDOC ## rxnutils.pipeline.base.create_action(pretty_name, *args, **kwargs) ### Description Create an action that can be called. ### Parameters - **pretty_name** (str) - Required - The name of the action. - **args** (Any) - Optional - Additional arguments. - **kwargs** (Any) - Optional - Additional keyword arguments. ### Returns - (Callable[[DataFrame], DataFrame]) - The instantiated action. ``` -------------------------------- ### molecule_to_image(mol, frame_color, size=300) Source: https://molecularai.github.io/reaction_utils/rxnutils.routes.html Creates a pretty image of a molecule with a colored frame around it. ```APIDOC ## molecule_to_image(mol, frame_color, size=300) ### Description Create a pretty image of a molecule, with a colored frame around it. ### Parameters - **mol** (Chem.rdchem.Mol) - Required - The molecule to draw. - **frame_color** (PilColor) - Required - The color of the frame. - **size** (int) - Optional - The size of the image (default: 300). ### Returns - **PilImage** - The produced image. ``` -------------------------------- ### SmartsLibrary.load(source) Source: https://molecularai.github.io/reaction_utils/rxnutils.chem.html Loads a SMARTS library from a specified file path or retrieves it from internal storage if the source matches a label. ```APIDOC ## SmartsLibrary.load(source) ### Description Loads a SMARTS library either from the internal storage if the source exists as a label, or creates a new library instance using the source as a file path. ### Parameters - **source** (str) - Required - The label of a stored library or the file path to a SMARTS library. ### Returns - **SmartsLibrary** - The loaded library instance. ``` -------------------------------- ### Assigning Atom Mapping and Reaction Classes Source: https://molecularai.github.io/reaction_utils/routes.html Configure the environment for atom mapping and apply mapping to routes, ensuring consistency across routes. ```python # This can be set on the command-line as well import os os.environ["RXNMAPPER_ENV_PATH"] = "/home/username/miniconda/envs/rxnmapper/" for route in routes: route.assign_atom_mapping(only_rxnmapper=True) routes[1].remap(routes[0]) ``` -------------------------------- ### rxnutils.routes.comparison.simple_bond_forming_similarity(routes) Source: https://molecularai.github.io/reaction_utils/rxnutils.routes.html Calculates pairwise similarity based on formed bond overlap. ```APIDOC ## rxnutils.routes.comparison.simple_bond_forming_similarity(routes) ### Description Calculates the pairwise similarity of a sequence of routes based on the overlap of formed bonds in the reactions. ### Parameters - **routes** (Sequence[SynthesisRoute]) - Required - The sequence of routes to compare. ### Returns - **ndarray** - The pairwise similarity. ``` -------------------------------- ### Define Pipeline Configuration Source: https://molecularai.github.io/reaction_utils/pipeline.html YAML configuration file specifying the sequence of actions to perform on the input data. ```yaml trim_rxn_smiles: in_column: ReactionSmiles out_column: ReactionSmilesClean remove_unsanitizable: in_column: ReactionSmilesClean out_column: ReactionSmilesClean reagents2reactants: in_column: ReactionSmilesClean out_column: ReactionSmilesClean remove_atom_mapping: in_column: ReactionSmilesClean out_column: ReactionSmilesClean reactantsize: in_column: ReactionSmilesClean productsize: in_column: ReactionSmilesClean query_dataframe1: query: "ReactantSize>0" query_dataframe2: query: "ProductSize>0" query_dataframe3: query: "ReactantSize+ProductSize<200" ``` -------------------------------- ### Execute Pipeline via CLI or Python Source: https://molecularai.github.io/reaction_utils/_sources/pipeline.rst.txt Methods to run the defined pipeline using the command line or the Python runner module. ```bash python -m rxnutils.pipeline.runner --pipeline clean_pipeline.yml --data uspto_data.csv --output uspto_cleaned.csv ``` ```python from rxnutils.pipeline.runner import main as validation_runner validation_runner( [ "--pipeline", "clean_pipeline.yml", "--data", "uspto_data.csv", "--output", "uspto_cleaned.csv", ] ) ``` -------------------------------- ### Define reaction routes in a text file Source: https://molecularai.github.io/reaction_utils/_sources/routes.rst.txt Format for storing reaction routes in a text file where each reaction is a SMILES string and routes are separated by newlines. ```text CC(C)N.Clc1cccc(Nc2ccoc2)n1>>CC(C)Nc1cccc(Nc2ccoc2)n1 Brc1ccoc1.Nc1cccc(Cl)n1>>Clc1cccc(Nc2ccoc2)n1 Nc1cccc(NC(C)C)n1.Brc1ccoc1>>CC(C)Nc1cccc(Nc2ccoc2)n1 CC(C)N.Nc1cccc(Cl)n1>>Nc1cccc(NC(C)C)n1 ``` -------------------------------- ### is_complete() Source: https://molecularai.github.io/reaction_utils/rxnutils.chem.html Checks if the reaction is complete by verifying that the product is not among the reactants. ```APIDOC ## is_complete() ### Description Checks that the product is not among the reactants. ### Returns - **bool** - True if the reaction is complete, False otherwise. ``` -------------------------------- ### Generate Template Hashes Source: https://molecularai.github.io/reaction_utils/_sources/templates.rst.txt Create hash strings for a reaction template using different methods. ```python rxn.retro_template.hash_from_bits() >> 'a1727cc9ed68a6411bfd02873c1615c22baa1af4957f14ae942e2c85caf9adb5' rxn.retro_template.hash_from_smarts() >> '4cb9be0738a3a84e7ed4fb661d2efb73c099fc7d6c532a4b294c8d0d' rxn.retro_template.hash_from_smiles() >> '5b2ff2a69fb7bd6a032938e468684773bcc668928b037bbec0ac8335' ``` -------------------------------- ### sanitization_check() Source: https://molecularai.github.io/reaction_utils/rxnutils.chem.html Verifies if the reactant and product molecule objects were successfully created. ```APIDOC ## sanitization_check() ### Description Checks if the reactant and product mol objects can be sanitized in RDKit. ### Returns - **bool** - True if all molecule objects were successfully created, else False. ``` -------------------------------- ### rxnutils.pipeline.base.ReactionActionMixIn Source: https://molecularai.github.io/reaction_utils/rxnutils.pipeline.html Mixin class providing standard routines for splitting and joining reaction SMILES. ```APIDOC ## ReactionActionMixIn.join_lists(reactants_list, reagents_list, products_list) ### Description Join list of components into a reaction SMILES. ### Parameters - **reactants_list** (List[str]) - Required - The list of reactant SMILES. - **reagents_list** (List[str]) - Required - The list of reagent SMILES. - **products_list** (List[str]) - Required - The list of product SMILES. ### Returns - (str) - The concatenated reaction SMILES. ## ReactionActionMixIn.join_smiles(reactants, reagents, products) ### Description Join component SMILES into a reaction SMILES. ### Parameters - **reactants** (str) - Required - The reactant SMILES. - **reagents** (str) - Required - The reagent SMILES. - **products** (str) - Required - The product SMILES. ### Returns - (str) - The concatenated reaction SMILES. ## ReactionActionMixIn.split_lists(row) ### Description Split a reaction SMILES into list of component SMILES. ### Parameters - **row** (Series) - Required - The row with the SMILES. ### Returns - (Tuple[List[str], List[str], List[str]]) - The list of SMILES of the components. ## ReactionActionMixIn.split_smiles(row) ### Description Split a reaction SMILES into components SMILES. ### Parameters - **row** (Series) - Required - The row with the SMILES. ### Returns - (Tuple[str, str, str]) - The SMILES of the components. ``` -------------------------------- ### Apply Template to Molecule Source: https://molecularai.github.io/reaction_utils/_sources/templates.rst.txt Use the retro template to re-generate reactants from a product SMILES. ```python smiles="CCS(=O)(=O)OCCBr" reactant_list = rxn.retro_template.apply(smiles) reactant_list >> (('CCS(=O)(=O)Cl', 'OCCBr'),) ``` -------------------------------- ### Clone ord-data repository Source: https://molecularai.github.io/reaction_utils/_sources/ord.rst.txt Clone the Open Reaction Database data repository. ```bash git clone https://github.com/open-reaction-database/ord-data.git . ``` -------------------------------- ### Compute Morgan Fingerprint Source: https://molecularai.github.io/reaction_utils/_sources/templates.rst.txt Calculate a Morgan fingerprint vector for the reaction template. ```python rxn.retro_template.fingerprint_vector(radius=2, nbits=1024) >> array([0., 0., 0., ..., 0., 0., 0.]) ``` -------------------------------- ### rxnutils.routes.comparison.simple_route_similarity(routes) Source: https://molecularai.github.io/reaction_utils/rxnutils.routes.html Computes the geometric mean of simple bond forming similarity and atom matching bonanza similarity. ```APIDOC ## rxnutils.routes.comparison.simple_route_similarity(routes) ### Description Returns the geometric mean of the simple bond forming similarity, and the atom matching bonanza similarity. ### Parameters - **routes** (Sequence[SynthesisRoute]) - Required - The sequence of routes to compare. ### Returns - **ndarray** - The pairwise similarity. ``` -------------------------------- ### rxnutils.data.batch_utils.nlines Source: https://molecularai.github.io/reaction_utils/rxnutils.data.html Counts and returns the number of lines in a file. ```APIDOC ## nlines(filename) ### Description Count and return the number of lines in a file. ### Parameters - **filename** (str) - Required - The path to the file. ``` -------------------------------- ### ChemicalReaction(smiles, id=None, clean_smiles=True) Source: https://molecularai.github.io/reaction_utils/rxnutils.chem.html Initializes a new ChemicalReaction object representing a chemical reaction. ```APIDOC ## ChemicalReaction(smiles, id=None, clean_smiles=True) ### Description Initializes a representation of a chemical reaction from a SMILES string. ### Parameters - **smiles** (str) - Required - The reaction SMILES string. - **id** (str) - Optional - An optional database ID of the reaction. - **clean_smiles** (bool) - Optional - If True, standardizes the reaction SMILES. ``` -------------------------------- ### ReactionTreeWrapper Source: https://molecularai.github.io/reaction_utils/rxnutils.routes.ted.html A wrapper class for synthesis routes to facilitate distance calculations between reaction trees. ```APIDOC ## Class: ReactionTreeWrapper(route, content=TreeContent.MOLECULES, exhaustive_limit=20, fp_factory=None, dist_func=None) ### Description Wrapper for a reaction tree that provides methods to calculate distances between trees using APTED heuristics. ### Methods - **distance_iter(other, exhaustive_limit=20)**: Iterate over all distances computed between this and another tree. - **distance_to(other, exhaustive_limit=20)**: Calculate the minimum distance from this route to another route. - **distance_to_with_sorting(other)**: Compute the distance to another tree by sorting the children of both trees (not guaranteed to be the minimum distance). ``` -------------------------------- ### rxnutils.data.batch_utils.create_csv_batches Source: https://molecularai.github.io/reaction_utils/rxnutils.data.html Creates batch specifications for reading a split CSV file. ```APIDOC ## create_csv_batches(filename, nbatches, output_filename=None) ### Description Create batches for reading a split CSV-file. The batches are returned as a list of tuples containing (Batch index, Start index, End index). ### Parameters - **filename** (str) - Required - The CSV file to make batches of. - **nbatches** (int) - Required - The number of batches. - **output_filename** (str|None) - Optional - The output filename. ``` -------------------------------- ### generate_reaction_template(radius=1, expand_ring=False, expand_hetero=False) Source: https://molecularai.github.io/reaction_utils/rxnutils.chem.html Extracts the forward (canonical) and retrosynthetic reaction templates. ```APIDOC ## generate_reaction_template(radius=1, expand_ring=False, expand_hetero=False) ### Description Extracts the forward and retro reaction templates with the specified radius and expansion settings. ### Parameters - **radius** (int) - Optional - Number of atoms away from the reaction centre to be extracted. - **expand_ring** (bool) - Optional - If True, includes all atoms in the same ring as the reaction centre. - **expand_hetero** (bool) - Optional - If True, extends the template with all bonded hetero atoms. ### Returns - **Tuple[ReactionTemplate, ReactionTemplate]** - The canonical and retrosynthetic templates. ``` -------------------------------- ### rxnutils.routes.comparison.atom_matching_bonanza_similarity(routes) Source: https://molecularai.github.io/reaction_utils/rxnutils.routes.html Calculates pairwise similarity based on atom-mapping number overlap. ```APIDOC ## rxnutils.routes.comparison.atom_matching_bonanza_similarity(routes) ### Description Calculates the pairwise similarity of a sequence of routes based on the overlap of the atom-mapping numbers of the compounds in the routes. ### Parameters - **routes** (Sequence[SynthesisRoute]) - Required - The sequence of routes to compare. ### Returns - **ndarray** - The pairwise similarity. ``` -------------------------------- ### rxnutils.routes.base.smiles2inchikey(smiles, ignore_stereo=False) Source: https://molecularai.github.io/reaction_utils/rxnutils.routes.html Converts a SMILES string to an InChI key. ```APIDOC ## rxnutils.routes.base.smiles2inchikey(smiles, ignore_stereo=False) ### Description Converts a SMILES to an InChI key. ### Parameters - **smiles** (str) - Required - **ignore_stereo** (bool) - Optional ### Returns - **str** ``` -------------------------------- ### rxnutils.pipeline.runner.run_pipeline Source: https://molecularai.github.io/reaction_utils/rxnutils.pipeline.html Executes a defined pipeline on a provided dataset, applying actions sequentially and optionally saving intermediate results to CSV files. ```APIDOC ## run_pipeline(data, pipeline, filename, save_intermediates=True) ### Description Runs a given pipeline on a dataset. The actions are applied sequentially as defined in the pipeline, and intermediate results are written to separate tab-separated CSV files. ### Parameters - **data** (DataFrame) - Required - The dataset to process. - **pipeline** (Dict[str, Any]) - Required - The action specifications for the pipeline. - **filename** (str) - Required - Path to the final output file. - **save_intermediates** (bool) - Optional - If True, saves intermediate results to files. Defaults to True. ### Returns - **DataFrame** - The dataset after completing the pipeline. ``` -------------------------------- ### SimpleRdkitFingerprint Source: https://molecularai.github.io/reaction_utils/rxnutils.chem.features.html A class for calculating reaction fingerprints using native RDKit featurizers. ```APIDOC ## class SimpleRdkitFingerprint(featurizer, numbits=2048, product_bits=0) ### Description Initializes a reaction featurizer based on native RDKit functions. ### Parameters - **featurizer** (str) - Required - The type of featurizer to use. - **numbits** (int) - Optional - Length of the fingerprint (default: 2048). - **product_bits** (int) - Optional - The number of bits for the product (default: 0). ``` -------------------------------- ### Extract Reaction Template Source: https://molecularai.github.io/reaction_utils/_sources/templates.rst.txt Generate a retro-synthetic reaction template with a specified radius. ```python rxn.generate_reaction_template(radius=1) rxn.retro_template >> rxn.retro_template.smarts >> '[C:2]-[S;H0;D4;+0:1](=[O;D1;H0:3])(=[O;D1;H0:4])-[O;H0;D2;+0:6]-[C:5]>>Cl-[S;H0;D4;+0:1](-[C:2])(=[O;D1;H0:3])=[O;D1;H0:4].[C:5]-[OH;D1;+0:6]' ``` -------------------------------- ### Implement Custom Pipeline Action Source: https://molecularai.github.io/reaction_utils/_sources/pipeline.rst.txt Structure for creating a new pipeline action using the @action and @dataclass decorators. ```python @action @dataclass class ProductSize: """Action for counting product size""" pretty_name: ClassVar[str] = "productsize" in_column: str out_column: str = "ProductSize" def __call__(self, data: pd.DataFrame) -> pd.DataFrame: smiles_col = global_apply(data, self._row_action, axis=1) return data.assign(**{self.out_column: smiles_col}) def __str__(self) -> str: return f"{self.pretty_name} (number of heavy atoms in product)" def _row_action(self, row: pd.Series) -> str: _, _, products = row[self.in_column].split(">") products_mol = Chem.MolFromSmiles(products) if products_mol: product_atom_count = products_mol.GetNumHeavyAtoms() else: product_atom_count = 0 return product_atom_count ``` -------------------------------- ### Reading Routes from Text Files Source: https://molecularai.github.io/reaction_utils/routes.html Use read_reaction_lists to load route objects from a text file containing reaction SMILES. ```python from rxnutils.routes.readers import read_reaction_lists routes = read_reaction_lists("reactions.txt") ``` -------------------------------- ### Inspect Reactants and Agents Source: https://molecularai.github.io/reaction_utils/_sources/templates.rst.txt Access the reactants_list and agents_list properties to see how unmapped reactants are handled. ```python rxn.reactants_list >> ['Cl[S:3]([CH2:2][CH3:1])(=[O:4])=[O:5]', '[OH:6][CH2:7][CH2:8][Br:9]'] rxn.agents_list >> ['CCN(CC)CC', 'CCOCC'] ``` -------------------------------- ### rxnutils.chem.rinchi.rinchi_api.generate_rinchi(reaction_smiles) Source: https://molecularai.github.io/reaction_utils/rxnutils.chem.rinchi.html Generates a Reaction InChI (RInChI) string from a given reaction SMILES string. ```APIDOC ## generate_rinchi(reaction_smiles) ### Description Generate RInChI from Reaction SMILES. ### Parameters - **reaction_smiles** (str) - Required - Reaction SMILES string. ### Returns - **RInChI** (Namedtuple) - The generated RInChI structure. ### Errors - **RInChIError** - Raised when there is an error with RInChI generation. ``` -------------------------------- ### rxnutils.chem.utils.neutralize_molecules Source: https://molecularai.github.io/reaction_utils/rxnutils.chem.html Neutralizes a list of molecules using RDKit routines. ```APIDOC ## neutralize_molecules(smiles_list) ### Description Neutralize a set of molecules using RDKit routines. ### Parameters - **smiles_list** (List[str]) - Required - The molecules as SMILES. ### Response - **Returns** (List[str]) - The neutralized molecules. ``` -------------------------------- ### join_smiles_from_reaction(smiles_list) Source: https://molecularai.github.io/reaction_utils/rxnutils.chem.html Joins a list of SMILES components into a single reaction SMILES part, handling intra-molecular complexes with parentheses. ```APIDOC ## join_smiles_from_reaction(smiles_list) ### Description Join a part of reaction SMILES, e.g. reactants and products into components. Intra-molecular complexes are bracketed with parenthesis. ### Parameters - **smiles_list** (List[str]) - Required - The SMILES components ### Returns - **str** - The joined list ``` -------------------------------- ### ChemformerReactionFeasibilityCalculator Source: https://molecularai.github.io/reaction_utils/rxnutils.routes.chemformer_feasibility.html Interface to the Chemformer API to calculate forward reaction feasibility. ```APIDOC ## ChemformerReactionFeasibilityCalculator(api_url) ### Description Initializes the interface to the Chemformer REST API to calculate forward feasibility of reactions. ### Parameters - **api_url** (str) - Required - The URL to the REST API. ### Usage Once instantiated, the calculator can be called as a function with a list of reaction SMILES to return a dictionary mapping SMILES to feasibility scores. ## load_batch_output(data) ### Description Updates the internal cache with predictions from the chemformer package batch output. ### Parameters - **data** (DataFrame) - Required - The batch output from the chemformer predict function, containing a 'reactants' column. ``` -------------------------------- ### recreate_rsmi(rsmi) Source: https://molecularai.github.io/reaction_utils/rxnutils.chem.html Recreates a reaction SMILES by removing intra-molecular complexes. ```APIDOC ## recreate_rsmi(rsmi) ### Description Recreate Reactions SMILES by removing intra-molecular complexes. ### Parameters - **rsmi** (str) - Required - The original reaction smiles ### Returns - **str** - The updated reaction smiles without intra-molecular complexes ``` -------------------------------- ### rxnutils.chem.utils.get_symmetric_sites Source: https://molecularai.github.io/reaction_utils/rxnutils.chem.html Identifies all symmetric sites (atoms) for a given list of candidate atoms within an RDKit molecule. ```APIDOC ## get_symmetric_sites(mol, candidate_atoms) ### Description Get all symmetric sites (atoms) of each atom in the list of atoms defined by their atomic index. Symmetry is assessed with respect to the molecule. ### Parameters - **mol** (Mol) - Required - RdKit molecule - **candidate_atoms** (List[int]) - Required - Indices of the atoms that will be checked for symmetry. ### Response - **Returns** (List[List[int]]) - A list of all symmetric sites that include the candidate atoms. ``` -------------------------------- ### rxnutils.routes.comparison.route_distances_calculator(model, **kwargs) Source: https://molecularai.github.io/reaction_utils/rxnutils.routes.html Returns a callable to calculate the squared distance matrix for a list of routes. ```APIDOC ## rxnutils.routes.comparison.route_distances_calculator(model, **kwargs) ### Description Return a callable that given a list routes as dictionaries calculate the squared distance matrix. ### Parameters - **model** (str) - Required - The route distance model name. - **kwargs** (Any) - Optional - Additional keyword arguments for the model. ### Returns - **Callable[[Sequence[SynthesisRoute]], ndarray]** - The appropriate route distances calculator. ``` -------------------------------- ### read_reaction_lists(filename) Source: https://molecularai.github.io/reaction_utils/rxnutils.routes.html Reads one or more simple lists of reactions from a file into retrosynthesis trees. ```APIDOC ## read_reaction_lists(filename) ### Description Read one or more simple lists of reactions into one or more retrosynthesis trees. Each list of reactions should be separated by an empty line. ### Parameters - **filename** (str) - Required - The path to the file with the reactions. ### Returns - **List[SynthesisRoute]** - The list of the created trees. ``` -------------------------------- ### reaction_centres(rxn) Source: https://molecularai.github.io/reaction_utils/rxnutils.chem.html Identifies reaction centre atoms by comparing bonding partners in the reactant and product. ```APIDOC ## reaction_centres(rxn) ### Description Return reaction centre atoms, provided that the bonding partners actually change when comparing the environment in the reactant and the product. ### Parameters - **rxn** (ChemicalReaction) - Required - The initialized RDKit reaction ### Returns - **Tuple[List[int], ...]** - Tuple of reaction centre atoms, filtered by connectivity criterion ``` -------------------------------- ### SmartsLibrary.match_smarts(smiles) Source: https://molecularai.github.io/reaction_utils/rxnutils.chem.html Checks the loaded SMARTS library for substructure matches against a given SMILES string. ```APIDOC ## SmartsLibrary.match_smarts(smiles) ### Description Performs a substructure search using the patterns defined in the SMARTS library against the provided query SMILES. ### Parameters - **smiles** (str) - Required - The query SMILES string. ### Returns - **Dict[str, SmartsHit]** - A dictionary mapping SMARTS pattern names to their corresponding SmartsHit objects. ``` -------------------------------- ### preprocess_amino_acids(original_smiles) Source: https://molecularai.github.io/reaction_utils/rxnutils.chem.protection.html Removes all charges from an amino acid SMILES string to prepare it for protection reactions. ```APIDOC ## preprocess_amino_acids(original_smiles) ### Description Removes all charges of the amino acids so that the protection reaction can be applied. ### Parameters - **original_smiles** (str) - Required - The original SMILES string of the amino acid. ### Returns - **str** - The processed SMILES string with charges removed. ``` -------------------------------- ### CondensedGraphReaction Source: https://molecularai.github.io/reaction_utils/rxnutils.chem.html The CondensedGraphReaction class provides methods to analyze reaction properties such as bond changes and chemical distances. ```APIDOC ## class CondensedGraphReaction(reaction) ### Description Represents the Condensed Graph of Reaction (CGR) of a chemical reaction. ### Parameters - **reaction** (ChemicalReaction) - Required - The reaction composed of RDKit molecules. ### Properties - **bonds_broken** (int) - Returns the number of broken bonds in the reaction. - **bonds_changed** (int) - Returns the number of broken or formed bonds in the reaction. - **bonds_formed** (int) - Returns the number of formed bonds in the reaction. - **total_centers** (int) - Returns the number of atom and bond centers in the reaction. ### Methods #### distance_to(other) Returns the chemical distance between two reactions, calculated as the absolute difference between the total number of centers. - **other** (CondensedGraphReaction) - Required - The reaction to compare to. - **Returns** (int) - The computed distance. ``` -------------------------------- ### SCScore Source: https://molecularai.github.io/reaction_utils/rxnutils.chem.features.html Encapsulation of the SCScore model for synthetic complexity scoring using ONNX. ```APIDOC ## class SCScore(model_path, fingerprint_length=1024, fingerprint_radius=2) ### Description Initializes the SCScore model for synthetic complexity scoring. ### Parameters - **model_path** (str) - Required - The filename of the model weights and biases. - **fingerprint_length** (int) - Optional - The number of bits in the fingerprint (default: 1024). - **fingerprint_radius** (int) - Optional - The radius of the fingerprint (default: 2). ``` -------------------------------- ### read_rdf_file(filename) Source: https://molecularai.github.io/reaction_utils/rxnutils.routes.html Reads routes from an RDF file. ```APIDOC ## read_rdf_file(filename) ### Parameters - **filename** (str) - Required - The path to the RDF file. ### Returns - **SynthesisRoute** - The created route. ``` -------------------------------- ### ted_distances_calculator Source: https://molecularai.github.io/reaction_utils/rxnutils.routes.ted.html Computes the TED distance matrix for a sequence of synthesis routes. ```APIDOC ## Function: ted_distances_calculator(routes, content='both', timeout=None) ### Description Compute the TED distances between each pair of routes provided in the sequence. ### Parameters - **routes** (Sequence[SynthesisRoute]) - Required - The routes to calculate pairwise distance on. - **content** (str) - Optional - Determine what part of the synthesis trees to include in the calculation (options: 'molecules', 'reactions', 'both'). Default is 'both'. - **timeout** (int) - Optional - If given, raises an exception if the calculation exceeds the specified timeout. ### Returns - **ndarray** - The square distance matrix. ``` -------------------------------- ### crop_image(img, margin=20) Source: https://molecularai.github.io/reaction_utils/rxnutils.routes.html Crops an image by removing white space around it. ```APIDOC ## crop_image(img, margin=20) ### Description Crop an image by removing white space around it. ### Parameters - **img** (PilImage) - Required - The image to crop. - **margin** (int) - Optional - Padding (default: 20). ### Returns - **PilImage** - The cropped image. ``` -------------------------------- ### retro_template_selectivity() Source: https://molecularai.github.io/reaction_utils/rxnutils.chem.html Calculates the selectivity of the retrosynthetic template. ```APIDOC ## retro_template_selectivity() ### Description Checks whether the recorded reactants belong to the set of generated precursors. ### Returns - **float** - The fraction of generated precursors matching the recorded precursors. ``` -------------------------------- ### SmartsLibrary.detect_reactive_functions(...) Source: https://molecularai.github.io/reaction_utils/rxnutils.chem.html Identifies functional groups that change during a chemical reaction. ```APIDOC ## SmartsLibrary.detect_reactive_functions(reaction, sort=False, add_none=True, none_str='None', target_size=2, max_reactants=None, product_functions=None, reactants_functions=None) ### Description Analyzes a chemical reaction to find reactive functions in the reactants, specifically identifying functional groups that undergo changes. ### Parameters - **reaction** (ChemicalReaction) - Required - The reaction object to analyze. - **sort** (bool) - Optional - Sort reactants alphabetically by reactive function. - **add_none** (bool) - Optional - Add a placeholder string for reactants without hits. - **none_str** (str) - Optional - The placeholder string used for non-matching reactants. - **target_size** (int) - Optional - Desired length of returned lists when adding placeholders. - **max_reactants** (int) - Optional - Maximum allowed number of reactants. - **product_functions** (Dict[str, SmartsHit]) - Optional - Pre-identified SMARTS hits for products. - **reactants_functions** (List[Dict[str, SmartsHit]]) - Optional - Pre-identified SMARTS hits for reactants. ### Returns - **Tuple[Tuple[str, ...], str]** - A tuple containing the identified reactive functions and the reaction SMILES. ``` -------------------------------- ### rxnutils.pipeline.base.action Source: https://molecularai.github.io/reaction_utils/rxnutils.pipeline.html Decorator that registers a callable as a validation action. The action must accept a pandas.DataFrame and return a pandas.DataFrame, and must have a pretty_name attribute. ```APIDOC ## rxnutils.pipeline.base.action(obj) ### Description Decorator that registers a callable as a validation action. An action will be called with a pandas.DataFrame object and return a new pandas.DataFrame object. ### Parameters - **obj** (Callable[[DataFrame], DataFrame]) - Required - The callable to register as an action. ### Returns - (Callable[[DataFrame], DataFrame]) - The same as obj. ``` -------------------------------- ### single_reactant_augmentation(smiles, classification) Source: https://molecularai.github.io/reaction_utils/rxnutils.chem.html Augments a single-reactant reaction SMILES with an additional reagent based on the provided reaction classification. ```APIDOC ## single_reactant_augmentation(smiles, classification) ### Description Augment a single-reactant reaction with an additional reagent if possible based on the classification of the reaction. ### Parameters - **smiles** (str) - The reaction SMILES to augment. - **classification** (str) - The classification of the reaction or an empty string. ### Returns - **str** - The processed SMILES string. ``` -------------------------------- ### AminoAcidProtectionEngine.protect(smiles) Source: https://molecularai.github.io/reaction_utils/rxnutils.chem.protection.html Protects a given amino acid SMILES string using configured reaction rules. ```APIDOC ## AminoAcidProtectionEngine.protect(smiles) ### Description Protect the given SMILES. The SMILES need to have neutralized backbone charges. ### Parameters - **smiles** (str) - Required - The SMILES of an amino acid. ### Returns - **List[ProtectedAminoAcid]** - A list of possible protected amino acids. ``` -------------------------------- ### rxnutils.chem.utils.same_molecule Source: https://molecularai.github.io/reaction_utils/rxnutils.chem.html Tests if two molecules are identical based on substructure matching. ```APIDOC ## same_molecule(mol1, mol2) ### Description Test if two molecules are the same. If mol1 is a substructure of mol2 and vice versa, the molecules are considered to be the same. ### Parameters - **mol1** (Mol) - Required - First molecule - **mol2** (Mol) - Required - Second molecule ### Response - **Returns** (bool) - True if the molecules match. ``` -------------------------------- ### rxnutils.data.batch_utils.combine_csv_batches Source: https://molecularai.github.io/reaction_utils/rxnutils.data.html Combines multiple CSV batch files into one master file and removes the batch files from disk. ```APIDOC ## combine_csv_batches(filename, nbatches) ### Description Combine CSV batches to one master file. The batch files are removed from disk. ### Parameters - **filename** (str) - Required - The filename of the master file. - **nbatches** (int) - Required - The number of batches. ``` -------------------------------- ### ReactionCentreFingerprint Source: https://molecularai.github.io/reaction_utils/rxnutils.chem.features.html A class for calculating reaction centre fingerprints based on RDKit functions. It supports optional concatenation of multiple centers into a single flattened list. ```APIDOC ## class ReactionCentreFingerprint(numbits=1024, max_centers=None) ### Description Initializes a reaction featurizer based on native RDKit functions for reaction centre atoms. ### Parameters - **numbits** (int) - Optional - Length of the fingerprint (default: 1024). - **max_centers** (int | None) - Optional - If provided, concatenates individual fingerprints up to a maximum number of centers. ``` -------------------------------- ### reassign_rsmi_atom_mapping(rsmi, as_smiles=False) Source: https://molecularai.github.io/reaction_utils/rxnutils.chem.html Reassigns a reaction's atom mapping by removing atom maps for atoms in reactants that are not found in the product's atoms. ```APIDOC ## reassign_rsmi_atom_mapping(rsmi, as_smiles=False) ### Description Reassign reaction's atom mapping. Remove atom maps for atoms in reactants and reactants not found in product's atoms. ### Parameters - **rsmi** (str) - Required - Reaction SMILES - **as_smiles** (bool) - Optional - Return reaction SMILES or SMARTS, defaults to False ### Returns - **str** - Reaction SMILES or SMARTS ``` -------------------------------- ### fingerprint_mixed Source: https://molecularai.github.io/reaction_utils/rxnutils.chem.features.html Calculates a mixed fingerprint consisting of ECFP3 and RDKit fingerprints. ```APIDOC ## fingerprint_mixed(mol, numbits) ### Description Calculates a mixed fingerprint where the first half is ECFP3 and the second half is an RDKit fingerprint. ### Parameters - **mol** (Mol) - Required - The molecule to featurize. - **numbits** (int) - Required - The length of the fingerprint. ### Returns - **ndarray** - The calculated mixed fingerprint. ``` -------------------------------- ### split_smiles_from_reaction(smiles) Source: https://molecularai.github.io/reaction_utils/rxnutils.chem.html Splits a part of a reaction SMILES (e.g., reactants or products) into individual components, accounting for intra-molecular complexes. ```APIDOC ## split_smiles_from_reaction(smiles) ### Description Split a part of reaction SMILES, e.g. reactants or products into components. Taking care of intra-molecular complexes. ### Parameters - **smiles** (str) - Required - The SMILES/SMARTS ### Returns - **List[str]** - The individual components ``` -------------------------------- ### update_stock(stock, molfunc) Source: https://molecularai.github.io/reaction_utils/rxnutils.routes.html Updates the in_stock property of molecule nodes within a route. ```APIDOC ## update_stock(stock, molfunc) ### Description Update the in_stock property of the molecule nodes in the route. ### Parameters - **stock** (Set[str]) - Required - The set of SMILES of molecules in stock. - **molfunc** (Callable[[str], str]) - Required - A function that takes a SMILES and returns a string that can be checked against the stock. ### Returns - **None** ``` -------------------------------- ### split_rsmi(rsmi) Source: https://molecularai.github.io/reaction_utils/rxnutils.chem.html Splits a reaction SMILES string into its component SMILES parts. ```APIDOC ## split_rsmi(rsmi) ### Description Split a reaction SMILES into components SMILES. ### Parameters - **rsmi** (str) - Required - The reaction SMILES ### Returns - **Tuple[str, str, str]** - The SMILES of the components ``` -------------------------------- ### rxnutils.chem.utils.get_mol_weight Source: https://molecularai.github.io/reaction_utils/rxnutils.chem.html Calculates the exact molecular weight of a molecule provided as a SMILES string. ```APIDOC ## get_mol_weight(smiles) ### Description Calculate molecule’s exact molecular weight. ### Parameters - **smiles** (str) - Required - Molecule’s SMILES. ### Response - **Returns** (float | None) - Molecule’s exact molecular weight. ``` -------------------------------- ### draw_rounded_rectangle(img, color, arc_size=20) Source: https://molecularai.github.io/reaction_utils/rxnutils.routes.html Draws a rounded rectangle around an image. ```APIDOC ## draw_rounded_rectangle(img, color, arc_size=20) ### Description Draw a rounded rectangle around an image. ### Parameters - **img** (PilImage) - Required - The image to draw upon. - **color** (PilColor) - Required - The color of the rectangle. - **arc_size** (int) - Optional - The size of the corner (default: 20). ### Returns - **PilImage** - The new image. ```