### Install from source Source: https://github.com/rxn4chemistry/rxnmapper/blob/main/README.md Clone the repository and install in editable mode. ```bash git clone https://github.com/rxn4chemistry/rxnmapper.git cd rxnmapper pip install -e ".[rdkit]" ``` -------------------------------- ### Install development dependencies Source: https://github.com/rxn4chemistry/rxnmapper/blob/main/DOCUMENTATION.md Install the required packages listed in dev_requirements.txt to prepare the environment. ```console pip install -r dev_requirements.txt ``` -------------------------------- ### Install via pip Source: https://github.com/rxn4chemistry/rxnmapper/blob/main/README.md Install the package using pip. ```bash pip install "rxnmapper[rdkit]" ``` -------------------------------- ### Run test suite Source: https://github.com/rxn4chemistry/rxnmapper/blob/main/README.md Install development dependencies and execute tests. ```bash pip install -e .[dev,rdkit] pytest tests ``` -------------------------------- ### View mapping results Source: https://github.com/rxn4chemistry/rxnmapper/blob/main/README.md Example output structure containing mapped reactions and confidence scores. ```python [{'mapped_rxn': 'CN(C)C=O.F[c:5]1[n:6][cH:7][cH:8][cH:9][c:10]1[F:11].O=C([O-])[O-].[CH3:1][CH:2]([CH3:3])[SH:4].[K+].[K+]>>[CH3:1][CH:2]([CH3:3])[S:4][c:5]1[n:6][cH:7][cH:8][cH:9][c:10]1[F:11]', 'confidence': 0.9565619900376546}, {'mapped_rxn': 'C1COCCO1.CC(C)(C)[O:3][C:2](=[O:1])[CH2:4][O:5][NH:6][C:7](=[O:8])[NH:9][CH2:10][c:11]1[cH:12][cH:13][cH:14][c:15]2[cH:16][cH:17][cH:18][cH:19][c:20]12.Cl>>[O:1]=[C:2]([OH:3])[CH2:4][O:5][NH:6][C:7](=[O:8])[NH:9][CH2:10][c:11]1[cH:12][cH:13][cH:14][c:15]2[cH:16][cH:17][cH:18][cH:19][c:20]12', 'confidence': 0.9704424331552834}] ``` -------------------------------- ### Visualize Mapped Reactions with RDKit Source: https://context7.com/rxn4chemistry/rxnmapper/llms.txt This function takes a reaction SMILES string, maps atoms using RXNMapper, and then visualizes the mapped reaction using RDKit, displaying atom map numbers as annotations. It requires RDKit to be installed. ```python from rxnmapper import RXNMapper from rdkit import Chem from rdkit.Chem import Draw, rdChemReactions from rdkit.Chem.Draw import rdMolDraw2D def draw_mapped_reaction(smiles, width=800, height=300): """Draw a mapped reaction with atom map numbers as annotations.""" rxn = rdChemReactions.ReactionFromSmarts(smiles, useSmiles=True) trxn = rdChemReactions.ChemicalReaction(rxn) # Move atom maps to annotations for display for mol in list(trxn.GetReactants()) + list(trxn.GetProducts()): for atom in mol.GetAtoms(): if atom.GetAtomMapNum(): atom.SetProp("atomNote", str(atom.GetAtomMapNum())) d2d = rdMolDraw2D.MolDraw2DSVG(width, height) d2d.drawOptions().annotationFontScale = 1.5 d2d.DrawReaction(trxn, highlightByReactant=True) d2d.FinishDrawing() return d2d.GetDrawingText() # Map reactions rxn_mapper = RXNMapper() reactions = [ 'CCOCC.C[Mg+].O=Cc1ccc(F)cc1Cl.[Br-]>>CC(O)c1ccc(F)cc1Cl', 'BrCCOCCBr.CCN(C(C)C)C(C)C.CCOC(C)=O.CN(C)C=O.Cl.NCC(F)(F)CO>>OCC(F)(F)CN1CCOCC1' ] results = rxn_mapper.get_attention_guided_atom_maps(reactions) # Visualize each mapped reaction for result in results: svg = draw_mapped_reaction(result['mapped_rxn']) print(f"Confidence: {result['confidence']:.2f}") # Save SVG or display in Jupyter notebook with open('reaction.svg', 'w') as f: f.write(svg) ``` -------------------------------- ### Get Detailed Batch Mapping with Confidence Scores Source: https://context7.com/rxn4chemistry/rxnmapper/llms.txt Use BatchedMapper.map_reactions_with_info to retrieve detailed mapping information, including confidence scores for each reaction. Failed reactions result in an empty dictionary. ```python from rxnmapper import BatchedMapper rxn_mapper = BatchedMapper(batch_size=16) reactions = [ 'BrCCOCCBr.CCN(C(C)C)C(C)C.CCOC(C)=O.CN(C)C=O.Cl.NCC(F)(F)CO>>OCC(F)(F)CN1CCOCC1', 'CC(=O)Cl.c1ccc(N)cc1>>CC(=O)Nc1ccccc1' ] # Get detailed results with confidence scores results = list(rxn_mapper.map_reactions_with_info(reactions, detailed=False)) for i, result in enumerate(results): if result: # Empty dict for failed reactions print(f"Reaction {i + 1}:") print(f" Mapped: {result['mapped_rxn']}") print(f" Confidence: {result['confidence']:.4f}") else: print(f"Reaction {i + 1}: Failed to map") ``` -------------------------------- ### Predict Reaction Source: https://github.com/rxn4chemistry/rxnmapper/blob/main/docs/_modules/rxn4chemistry.html Launches a reaction prediction given the precursors' SMILES. This is useful for predicting the outcome of a reaction based on its starting materials. ```APIDOC ## POST /predict/reaction ### Description Launches prediction given precursors SMILES. ### Method POST ### Endpoint /predict/reaction ### Parameters #### Query Parameters - **prediction_id** (str) - Optional - Prediction identifier. Defaults to None, meaning an independent prediction is run. ### Request Body - **precursors** (str) - Required - A reaction SMILES string representing the precursors. ### Request Example ```json { "precursors": "BrBr.c1ccc2cc3ccccc3cc2c1" } ``` ### Response #### Success Response (200) - **prediction_id** (str) - The identifier for the prediction. - **response** (dict) - The prediction results. #### Response Example ```json { "prediction_id": "some_prediction_id", "response": {} } ``` ### Raises - **ValueError** - In case self.project_id is not set. ``` -------------------------------- ### Get reaction prediction results Source: https://github.com/rxn4chemistry/rxnmapper/blob/main/docs/_modules/rxn4chemistry.html Retrieves results for a specific reaction prediction using its identifier. ```python >>> rxn4chemistry_wrapper.get_predict_reaction_results( response['response']['payload']['id'] # or response['prediction_id'] ) {...} ``` -------------------------------- ### Get Predict Reaction Results Source: https://github.com/rxn4chemistry/rxnmapper/blob/main/docs/_modules/rxn4chemistry.html Retrieves the results of a previously initiated reaction prediction using its unique identifier. ```APIDOC ## GET /api/predict/reaction/results/{prediction_id} ### Description Get the predict reaction results for a prediction_id. ### Method GET ### Endpoint /api/predict/reaction/results/{prediction_id} ### Parameters #### Path Parameters - **prediction_id** (str) - Required - The unique identifier for the prediction. ### Response #### Success Response (200) - **response** (dict) - Dictionary containing the prediction results. ### Response Example ```json { "response": { "payload": { "id": "prediction_id_value" } } } ``` ``` -------------------------------- ### Perform Atom Mapping and Draw Reactions Source: https://github.com/rxn4chemistry/rxnmapper/blob/main/examples/basic_example.ipynb Applies the RXNMapper to the defined reactions to get attention-guided atom maps. It then iterates through the results, displays the mapped reaction as an SVG, and prints the confidence score. Requires the `draw_chemical_reaction` function and `display` from `IPython.display`. ```python outputs = rxn_mapper.get_attention_guided_atom_maps(rxns) for out in outputs: display(SVG(draw_chemical_reaction(out['mapped_rxn'], highlightByReactant=True))) print(f'Confidence: {out["confidence"]:.2f}') ``` -------------------------------- ### Get Atomic Numbers from SMILES Source: https://context7.com/rxn4chemistry/rxnmapper/llms.txt Retrieves the atomic numbers for each atom in a given SMILES string. Useful for understanding the elemental composition of a molecule. ```python from rxnmapper.smiles_utils import get_atom_types_smiles atom_types = get_atom_types_smiles('CCO') print(f"Atom types (atomic numbers): {atom_types}") ``` -------------------------------- ### Get Predict Automatic Retrosynthesis Results Source: https://github.com/rxn4chemistry/rxnmapper/blob/main/docs/_modules/rxn4chemistry.html Retrieves the results of an automatic retrosynthesis prediction using a provided prediction ID. ```APIDOC ## GET /predict/automatic-retrosynthesis/results/{prediction_id} ### Description Get the predict automatic retrosynthesis results for a prediction_id. ### Method GET ### Endpoint /predict/automatic-retrosynthesis/results/{prediction_id} ### Parameters #### Path Parameters - **prediction_id** (str) - Required - Prediction identifier. ### Response #### Success Response (200) - **dict** - Dictionary containing the prediction results. ### Request Example ``` # Assuming 'response' is the result from a previous prediction request # and it contains the prediction_id prediction_id = response['response']['payload']['id'] rxn4chemistry_wrapper.get_predict_automatic_retrosynthesis_results(prediction_id) ``` ### Response Example ```json { "results": [ { "smiles": "CCO.O", "score": 0.95 } ] } ``` ``` -------------------------------- ### Get Adjacency Matrix from SMILES Source: https://context7.com/rxn4chemistry/rxnmapper/llms.txt Generates an adjacency matrix representing the bonding structure of a molecule represented by a SMILES string. This matrix indicates which atoms are bonded to each other. ```python from rxnmapper.smiles_utils import get_adjacency_matrix adj_matrix = get_adjacency_matrix('CCO') print(f"Adjacency matrix:\n{adj_matrix}") ``` -------------------------------- ### Create virtual environment Source: https://github.com/rxn4chemistry/rxnmapper/blob/main/README.md Set up a virtual environment for the project. ```bash python3 -m venv .venv source .venv/bin/activate ``` -------------------------------- ### Create a project with RXN4ChemistryWrapper Source: https://github.com/rxn4chemistry/rxnmapper/blob/main/docs/_modules/rxn4chemistry.html Initializes a new project on the platform using the wrapper instance. ```python >>> rxn4chemistry_wrapper.create_project('test') ``` -------------------------------- ### Generate project documentation Source: https://github.com/rxn4chemistry/rxnmapper/blob/main/DOCUMENTATION.md Navigate to the documentation source directory and execute the build commands for various output formats. ```console cd docs_source/ sh generate_modules_rst.sh # html make html # latex make latex make latexpdf # GitHub pages make github ``` -------------------------------- ### List all projects Source: https://github.com/rxn4chemistry/rxnmapper/blob/main/docs/_modules/rxn4chemistry.html Retrieves all projects associated with the API key used to initialize the wrapper. ```python >>> rxn4chemistry_wrapper.list_all_projects() {...} ``` -------------------------------- ### Create Project Source: https://github.com/rxn4chemistry/rxnmapper/blob/main/docs/_modules/rxn4chemistry.html Allows users to create a new project on the IBM RXN for Chemistry platform. This is often a prerequisite for other operations like predicting chemical reactions. ```APIDOC ## POST /projects ### Description Create new project on platform and set the project id, which is required to predict chemical reactions. ### Method POST ### Endpoint /projects ### Parameters #### Request Body - **name** (str) - Required - Name of the project. - **invitations** (list) - Optional - List of invitations for the project. Defaults to []. - **set_project** (bool) - Optional - Whether the created project is set. Defaults to True. ### Response #### Success Response (200) - **dict** - Dictionary built from the JSON response. Empty in case of errors. ### Request Example ```json { "name": "My New Project", "invitations": ["user1@example.com"], "set_project": true } ``` ### Response Example ```json { "project_id": "123e4567-e89b-12d3-a456-426614174000", "message": "Project created successfully." } ``` ``` -------------------------------- ### Parse recipe paragraph to actions Source: https://github.com/rxn4chemistry/rxnmapper/blob/main/docs/_modules/rxn4chemistry.html Converts a text description of a chemical recipe into a structured list of actions. ```python >>> results = rxn4chemistry_wrapper.paragraph_to_actions( 'To a stirred solution of ' '7-(difluoromethylsulfonyl)-4-fluoro-indan-1-one (110 mg, ' '0.42 mmol) in methanol (4 mL) was added sodium borohydride ' '(24 mg, 0.62 mmol). The reaction mixture was stirred at ' 'ambient temperature for 1 hour. ' ) >>> results['actions'] ['MAKESOLUTION with 7-(difluoromethylsulfonyl)-4-fluoro-indan-1-one (110 mg, 0.42 mmol) and methanol (4 mL)', 'ADD SLN', 'ADD sodium borohydride (24 mg, 0.62 mmol)', 'STIR for 1 hour at ambient temperature'] ``` -------------------------------- ### Perform basic atom mapping Source: https://github.com/rxn4chemistry/rxnmapper/blob/main/README.md Initialize the mapper and process a list of reaction SMILES. ```python from rxnmapper import RXNMapper rxn_mapper = RXNMapper() rxns = ['CC(C)S.CN(C)C=O.Fc1cccnc1F.O=C([O-])[O-].[K+].[K+]>>CC(C)Sc1ncccc1F', 'C1COCCO1.CC(C)(C)OC(=O)CONC(=O)NCc1cccc2ccccc12.Cl>>O=C(O)CONC(=O)NCc1cccc2ccccc12'] results = rxn_mapper.get_attention_guided_atom_maps(rxns) ``` -------------------------------- ### Configure RXNMapper with Custom Parameters Source: https://context7.com/rxn4chemistry/rxnmapper/llms.txt Initialize the mapper with a custom configuration dictionary to specify model paths, types, and attention parameters. ```python from rxnmapper import RXNMapper # Custom configuration options config = { 'model_path': '/path/to/custom/model', # Custom model directory 'model_type': 'albert', # Model type: 'albert', 'bert', or 'roberta' 'attention_multiplier': 90.0, # Multiplier for neighbor attention boosting 'head': 5, # Attention head to use 'layers': [10] # Transformer layers to extract attention from } # Initialize with custom config rxn_mapper = RXNMapper(config=config) # Use the mapper rxn = 'CCOCC.C[Mg+].O=Cc1ccc(F)cc1Cl.[Br-]>>CC(O)c1ccc(F)cc1Cl' result = rxn_mapper.get_attention_guided_atom_maps([rxn])[0] print(f"Mapped: {result['mapped_rxn']}") print(f"Confidence: {result['confidence']:.2f}") ``` -------------------------------- ### Command-Line Script for Dataset Processing (CSV) Source: https://context7.com/rxn4chemistry/rxnmapper/llms.txt Process a CSV file containing reactions using the run_rxnmapper_on_dataset script. Requires a 'rxn' column and allows specifying batch size and canonicalization options. ```bash python scripts/run_rxnmapper_on_dataset.py \ --file_path reactions.csv \ --output_path mapped_reactions.json \ --batch_size 32 \ --canonicalize ``` -------------------------------- ### Paragraph to Actions Source: https://github.com/rxn4chemistry/rxnmapper/blob/main/docs/_modules/rxn4chemistry.html Converts a natural language paragraph describing a chemical recipe into a structured list of actions. ```APIDOC ## POST /api/actions/from-paragraph ### Description Get the actions from a paragraph describing a recipe. ### Method POST ### Endpoint /api/actions/from-paragraph ### Parameters #### Request Body - **paragraph** (str) - Required - The paragraph describing the chemical recipe. ### Request Example ```json { "paragraph": "To a stirred solution of 7-(difluoromethylsulfonyl)-4-fluoro-indan-1-one (110 mg, 0.42 mmol) in methanol (4 mL) was added sodium borohydride (24 mg, 0.62 mmol). The reaction mixture was stirred at ambient temperature for 1 hour." } ``` ### Response #### Success Response (200) - **actions** (list[str]) - A list of structured chemical actions derived from the paragraph. ### Response Example ```json { "actions": [ "MAKESOLUTION with 7-(difluoromethylsulfonyl)-4-fluoro-indan-1-one (110 mg, 0.42 mmol) and methanol (4 mL)", "ADD SLN", "ADD sodium borohydride (24 mg, 0.62 mmol)", "STIR for 1 hour at ambient temperature" ] } ``` ``` -------------------------------- ### List All Projects Source: https://github.com/rxn4chemistry/rxnmapper/blob/main/docs/_modules/rxn4chemistry.html Retrieves a list of all projects associated with the API key. ```APIDOC ## GET /api/projects ### Description Get a list of all projects. ### Method GET ### Endpoint /api/projects ### Response #### Success Response (200) - **response** (dict) - Dictionary listing the projects. ### Response Example ```json { "response": { "projects": [ {...} ] } } ``` ``` -------------------------------- ### Command-Line Script for Dataset Processing (TSV) Source: https://context7.com/rxn4chemistry/rxnmapper/llms.txt Process a TSV file with reactions using the run_rxnmapper_on_dataset script. Use -f for file path, -o for output, -bs for batch size, and --no_canonicalize to disable canonicalization. ```bash python scripts/run_rxnmapper_on_dataset.py \ -f reactions.tsv \ -o output.json \ -bs 16 \ --no_canonicalize ``` -------------------------------- ### rxn4chemistry Module Overview Source: https://github.com/rxn4chemistry/rxnmapper/blob/main/docs/_sources/_modules/rxn4chemistry.rst.txt Overview of the available submodules within the rxn4chemistry package. ```APIDOC ## rxn4chemistry Package Modules ### Description The rxn4chemistry package provides tools for chemical reaction mapping and analysis. It is organized into several key submodules. ### Submodules - **rxn4chemistry.callbacks**: Contains callback definitions for process monitoring. - **rxn4chemistry.core**: Contains the core logic and primary classes for the package. - **rxn4chemistry.decorators**: Contains decorators used for function wrapping and utility logic. - **rxn4chemistry.urls**: Contains URL configurations and endpoint definitions for API interactions. ``` -------------------------------- ### Perform Atom Mapping with RXNMapper Source: https://context7.com/rxn4chemistry/rxnmapper/llms.txt Initialize the RXNMapper and process a list of reaction SMILES to obtain mapped reactions and confidence scores. ```python from rxnmapper import RXNMapper # Initialize the mapper (loads pre-trained model) rxn_mapper = RXNMapper() # Define reaction SMILES (reactants>>products format) reactions = [ 'CC(C)S.CN(C)C=O.Fc1cccnc1F.O=C([O-])[O-].[K+].[K+]>>CC(C)Sc1ncccc1F', 'C1COCCO1.CC(C)(C)OC(=O)CONC(=O)NCc1cccc2ccccc12.Cl>>O=C(O)CONC(=O)NCc1cccc2ccccc12' ] # Get atom-mapped reactions with confidence scores results = rxn_mapper.get_attention_guided_atom_maps(reactions) for result in results: print(f"Mapped reaction: {result['mapped_rxn']}") print(f"Confidence: {result['confidence']:.4f}") print() # Output: # Mapped reaction: CN(C)C=O.F[c:5]1[n:6][cH:7][cH:8][cH:9][c:10]1[F:11].O=C([O-])[O-].[CH3:1][CH:2]([CH3:3])[SH:4].[K+].[K+]>>[CH3:1][CH:2]([CH3:3])[S:4][c:5]1[n:6][cH:7][cH:8][cH:9][c:10]1[F:11] # Confidence: 0.9566 # Mapped reaction: C1COCCO1.CC(C)(C)[O:3][C:2](=[O:1])[CH2:4][O:5][NH:6][C:7](=[O:8])[NH:9][CH2:10][c:11]1[cH:12][cH:13][cH:14][c:15]2[cH:16][cH:17][cH:18][cH:19][c:20]12.Cl>>[O:1]=[C:2]([OH:3])[CH2:4][O:5][NH:6][C:7](=[O:8])[NH:9][CH2:10][c:11]1[cH:12][cH:13][cH:14][c:15]2[cH:16][cH:17][cH:18][cH:19][c:20]12 # Confidence: 0.9704 ``` -------------------------------- ### Initialize RXNMapper Source: https://github.com/rxn4chemistry/rxnmapper/blob/main/examples/basic_example.ipynb Instantiates the RXNMapper object, which will be used for performing atom mapping on chemical reactions. ```python rxn_mapper = RXNMapper() ``` -------------------------------- ### Import RDKit and RXNMapper Libraries Source: https://github.com/rxn4chemistry/rxnmapper/blob/main/examples/basic_example.ipynb Imports essential modules from RDKit for chemical structure manipulation and drawing, along with the RXNMapper library for reaction mapping. ```python from rdkit import Chem from rdkit.Chem import Draw from rdkit.Chem import rdChemReactions from rdkit.Chem.Draw import rdMolDraw2D from rdkit.Chem.Draw import IPythonConsole from IPython.display import SVG, display from rxnmapper import RXNMapper ``` -------------------------------- ### List project attempts Source: https://github.com/rxn4chemistry/rxnmapper/blob/main/docs/_modules/rxn4chemistry.html Retrieves a list of attempts for the currently configured project. ```python >>> rxn4chemistry_wrapper.list_all_attempts_in_project() {...} ``` -------------------------------- ### List All Attempts in Project Source: https://github.com/rxn4chemistry/rxnmapper/blob/main/docs/_modules/rxn4chemistry.html Retrieves a list of all attempts within a specified project. Supports pagination and sorting. ```APIDOC ## GET /api/projects/{project_id}/attempts ### Description Get a list of all the attempts in the set project. ### Method GET ### Endpoint /api/projects/{project_id}/attempts ### Parameters #### Query Parameters - **project_id** (str) - Optional - The identifier for the project. Defaults to the currently set project. - **page** (int) - Optional - The page number to retrieve attempts from. Defaults to 0. - **size** (int) - Optional - The number of attempts to return per page. Defaults to 8. - **ascending_creation_order** (bool) - Optional - Sort attempts by creation date in ascending order. Defaults to True. ### Response #### Success Response (200) - **response** (dict) - Dictionary listing the attempts. ### Response Example ```json { "response": { "attempts": [ {...} ] } } ``` ``` -------------------------------- ### Command-Line Script for Detailed Dataset Output Source: https://context7.com/rxn4chemistry/rxnmapper/llms.txt Generate detailed output, including attention information, when processing a JSON file of reactions using the run_rxnmapper_on_dataset script with the --detailed flag. ```bash python scripts/run_rxnmapper_on_dataset.py \ -f reactions.json \ -o detailed_output.json \ -bs 8 \ --detailed ``` -------------------------------- ### Run RXNMapper on a dataset Source: https://github.com/rxn4chemistry/rxnmapper/blob/main/examples/README.md Executes the RXNMapper script on a specified input file. Requires a CSV, TSV, or JSON file containing a 'rxn' column. ```bash python ../scripts/run_rxnmapper_on_dataset.py \ --file_path example_rxns.csv \ --output_path out.json \ --batch_size 8 ``` -------------------------------- ### Initialize and Use BatchedMapper for Production Source: https://context7.com/rxn4chemistry/rxnmapper/llms.txt Initialize BatchedMapper with custom batch size and model parameters for efficient, error-tolerant batch processing. Invalid reactions are automatically handled. ```python from rxnmapper import BatchedMapper # Initialize with batch size and options rxn_mapper = BatchedMapper( batch_size=32, # Number of reactions per batch model_path=None, # Use default model head=5, # Attention head attention_multiplier=90.0, # Neighbor attention multiplier layer=10, # Transformer layer model_type='albert', # Model type canonicalize=False, # Whether to canonicalize inputs placeholder_for_invalid='>>' # Placeholder for failed mappings ) # Define reactions (including an invalid one) reactions = [ 'CC[O-]~[Na+].BrCC>>CCOCC', 'invalid>>reaction', 'CC(=O)O.CCO>>CC(=O)OCC.O' ] # Get mapped reactions as strings (invalid reactions return placeholder) mapped_rxns = list(rxn_mapper.map_reactions(reactions)) for rxn, mapped in zip(reactions, mapped_rxns): print(f"Input: {rxn}") print(f"Output: {mapped}") print() # Output: # Input: CC[O-]~[Na+].BrCC>>CCOCC # Output: [mapped reaction with atom numbers] # # Input: invalid>>reaction # Output: >> # # Input: CC(=O)O.CCO>>CC(=O)OCC.O # Output: [mapped reaction with atom numbers] ``` -------------------------------- ### Set Project Source: https://github.com/rxn4chemistry/rxnmapper/blob/main/docs/_modules/rxn4chemistry.html Sets the project ID for the current context. The project ID can typically be found in the URL of the project. ```APIDOC ## POST /project ### Description Set project using the project id. The project_id can also be found in the url of the project. ### Method POST ### Endpoint /project ### Request Body - **project_id** (str) - Required - Project identifier. ### Request Example ```json { "project_id": "PROJECT_ID" } ``` ``` -------------------------------- ### Command-Line Script for Dataset Processing Source: https://context7.com/rxn4chemistry/rxnmapper/llms.txt Utilize the provided command-line script to process entire datasets of reactions stored in CSV, TSV, or JSON files. This script automates batching, mapping, and saving results. ```APIDOC ## Command-Line Script for Dataset Processing ### Description Executes RXNMapper on a dataset of reactions provided in a file (CSV, TSV, JSON). Supports various options for batch size, canonicalization, and detailed output. ### Usage ```bash python scripts/run_rxnmapper_on_dataset.py \ --file_path \ --output_path \ [--batch_size ] \ [--canonicalize | --no_canonicalize] \ [--detailed] ``` ### Parameters #### Path Parameters None #### Query Parameters - **--file_path, -f** (str) - Required - Path to the input file containing reactions. - **--output_path, -o** (str) - Required - Path to save the output JSON file. - **--batch_size, -bs** (int) - Optional - Number of reactions to process in each batch. Defaults to a suitable value. - **--canonicalize** - Optional - Flag to enable canonicalization of reactions. - **--no_canonicalize** - Optional - Flag to disable canonicalization of reactions. - **--detailed** - Optional - Flag to enable detailed output, including confidence scores. ### Request Example ```bash # Process a CSV file with reactions (requires 'rxn' column) python scripts/run_rxnmapper_on_dataset.py \ --file_path reactions.csv \ --output_path mapped_reactions.json \ --batch_size 32 \ --canonicalize # Process without canonicalization python scripts/run_rxnmapper_on_dataset.py \ -f reactions.tsv \ -o output.json \ -bs 16 \ --no_canonicalize # Get detailed output with attention information python scripts/run_rxnmapper_on_dataset.py \ -f reactions.json \ -o detailed_output.json \ -bs 8 \ --detailed ``` ### Response #### Success Response (200) A JSON file containing the mapped reactions and associated information (e.g., confidence scores if `--detailed` is used). #### Response Example ```json { "example": "[JSON output of mapped reactions]" } ``` ``` -------------------------------- ### Retrieve Detailed Mapping Output Source: https://context7.com/rxn4chemistry/rxnmapper/llms.txt Enable detailed output mode to access attention matrices, per-atom confidence scores, and mapping vectors. ```python from rxnmapper import RXNMapper rxn_mapper = RXNMapper() reactions = ['CC[O-].[Na+].BrCC>>CCOCC'] # Get detailed output with attention information results = rxn_mapper.get_attention_guided_atom_maps( reactions, zero_set_p=True, # Mask mapped product atoms (default: True) zero_set_r=True, # Mask mapped reactant atoms (default: True) canonicalize_rxns=True, # Canonicalize reactions (default: True) detailed_output=True, # Return detailed mapping info absolute_product_inds=False, # Use relative product atom indices force_layer=None, # Override default layer force_head=None # Override default attention head ) for result in results: print(f"Mapped reaction: {result['mapped_rxn']}") print(f"Overall confidence: {result['confidence']:.4f}") print(f"Mapping vector (product->reactant): {result['pxr_mapping_vector']}") print(f"Per-atom confidences: {result['pxr_confidences']}") print(f"Mapping tuples (product_idx, reactant_idx, conf): {result['mapping_tuples']}") print(f"Tokens: {result['tokens']}") print(f"Attention matrix shape: {result['tokensxtokens_attns'].shape}") ``` -------------------------------- ### Callback Functions Source: https://github.com/rxn4chemistry/rxnmapper/blob/main/docs/_modules/rxn4chemistry.html A collection of callback functions designed to process successful responses from various IBM RXN for Chemistry API endpoints. ```APIDOC ## Callback Functions ### Description Callbacks for IBM RXN for Chemistry API response processing. ### `automatic_retrosynthesis_results_on_success` #### Description Process the successful response of an automatic retrosynthesis result request. #### Parameters - **response** (requests.models.Response) - Required - Response from an API request. #### Returns - **dict** - Dictionary representing the response. ### `default_on_success` #### Description Process the successful response. #### Parameters - **response** (requests.models.Response) - Required - Response from an API request. #### Returns - **dict** - Dictionary representing the response. ### `paragraph_to_actions_on_success` #### Description Process the successful response of a paragraph to actions request. #### Parameters - **response** (requests.models.Response) - Required - Response from an API request. #### Returns - **dict** - Dictionary representing the response. ### `prediction_id_on_success` #### Description Process the successful response of requests returning a prediction identifier. #### Parameters - **response** (requests.models.Response) - Required - Response from an API request. #### Returns - **dict** - Dictionary representing the response. ``` -------------------------------- ### API Rate Limit Handling Source: https://github.com/rxn4chemistry/rxnmapper/blob/main/docs/_modules/rxn4chemistry.html This section details the exceptions related to API rate limits, which are managed by the `ibm_rxn_api_limits` decorator. ```APIDOC ## API Rate Limit Exceptions ### Description Exceptions raised when API rate limits are exceeded or when request timeouts occur. ### Exceptions - **RequestsPerMinuteExceeded** - Description: Raised when too many requests are sent within a one-minute window. - Type: RuntimeError - **RequestTimeoutNotElapsed** - Description: Raised when the timeout period between consecutive requests has not yet elapsed. - Type: RuntimeError ``` -------------------------------- ### Tokenization Utilities Source: https://github.com/rxn4chemistry/rxnmapper/blob/main/docs/_modules/rxnmapper.html Functions for adding special tokens to sequences and converting tokens to strings. ```APIDOC ## add_special_tokens_ids_single_sequence ### Description Adds special tokens to a sequence for sequence classification tasks. A BERT sequence has the following format: [CLS] X [SEP] ### Method Not applicable (function) ### Endpoint Not applicable (function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` ```APIDOC ## add_special_tokens_sequence_pair ### Description Adds special tokens to a sequence pair for sequence classification tasks. A BERT sequence pair has the following format: [CLS] A [SEP] B [SEP] ### Method Not applicable (function) ### Endpoint Not applicable (function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` ```APIDOC ## add_special_tokens_single_sequence ### Description Adds special tokens to a sequence for sequence classification tasks. A BERT sequence has the following format: [CLS] X [SEP] ### Method Not applicable (function) ### Endpoint Not applicable (function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` ```APIDOC ## convert_tokens_to_string ### Description Converts a sequence of tokens (string) into a single string. ### Method Not applicable (function) ### Endpoint Not applicable (function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Predict Reaction with Reaction SMILES Source: https://github.com/rxn4chemistry/rxnmapper/blob/main/docs/_modules/rxn4chemistry.html Launch a reaction prediction by providing the reaction SMILES string. An optional prediction_id can be supplied to group related predictions. ```python response = rxn4chemistry_wrapper.predict_reaction( 'BrBr.c1ccc2cc3ccccc3cc2c1' ) ``` -------------------------------- ### Programmatic Dataset Processing with RXNMapper Source: https://context7.com/rxn4chemistry/rxnmapper/llms.txt Load reactions from a CSV file using pandas, process them in chunks with RXNMapper.get_attention_guided_atom_maps, and save the results to a JSON file. ```python # Input CSV format example (reactions.csv): # rxn # CC(=O)O.CCO>>CC(=O)OCC.O # BrCC.CC[O-].[Na+]>>CCOCC # Programmatic equivalent: import pandas as pd from rxnmapper import RXNMapper from rxn.utilities.containers import chunker # Load reactions df = pd.read_csv('reactions.csv') rxns = df['rxn'].tolist() # Process in batches rxn_mapper = RXNMapper() results = [] batch_size = 32 for rxns_chunk in chunker(rxns, chunk_size=batch_size): results += rxn_mapper.get_attention_guided_atom_maps( rxns_chunk, canonicalize_rxns=True ) # Save results results_df = pd.DataFrame(results) results_df.to_json('mapped_reactions.json') ``` -------------------------------- ### Set Project ID for Wrapper Source: https://github.com/rxn4chemistry/rxnmapper/blob/main/docs/_modules/rxn4chemistry.html Set the project ID for the RXN4Chemistry wrapper. The project ID can typically be found in the URL of your project. ```python rxn4chemistry_wrapper.set_project('PROJECT_ID') ``` -------------------------------- ### RXN4ChemistryWrapper Class Source: https://github.com/rxn4chemistry/rxnmapper/blob/main/docs/_modules/rxn4chemistry.html The RXN4ChemistryWrapper class provides a Python interface to interact with the IBM RXN for Chemistry REST API. It requires an API key for authentication and can optionally be configured with a logger and a project ID. ```APIDOC ## Class RXN4ChemistryWrapper ### Description Python wrapper for IBM RXN for Chemistry to access the REST API requests. ### Parameters - **api_key** (str) - Required - API key for authentication. - **logger** (Optional[logging.Logger]) - Optional - Logger instance for logging. - **project_id** (Optional[str]) - Optional - Project ID to associate requests with. ``` -------------------------------- ### Set API Key for Authentication Source: https://github.com/rxn4chemistry/rxnmapper/blob/main/docs/_modules/rxn4chemistry.html Set the API key for authenticating requests to the IBM RXN for Chemistry service. This method also rebuilds the necessary request headers. ```python rxn4chemistry_wrapper.set_api_key('API_KEY') ``` -------------------------------- ### BatchedMapper.map_reactions_with_info - Detailed Batch Processing Source: https://context7.com/rxn4chemistry/rxnmapper/llms.txt Provides detailed mapping information for each reaction in a batch, including confidence scores. This method is useful for analyzing the quality of the atom mappings. ```APIDOC ## BatchedMapper.map_reactions_with_info ### Description Processes a list of reactions in batches and returns detailed mapping information, including confidence scores. Returns an empty dictionary for reactions that fail to map. ### Method `map_reactions_with_info(reactions: list[str], detailed: bool = False) -> Iterator[dict]` ### Parameters #### Path Parameters None #### Query Parameters - **detailed** (bool) - Optional - If True, returns more detailed information about the mapping process. #### Request Body None ### Request Example ```python from rxnmapper import BatchedMapper rxn_mapper = BatchedMapper(batch_size=16) reactions = [ 'BrCCOCCBr.CCN(C(C)C)C(C)C.CCOC(C)=O.CN(C)C=O.Cl.NCC(F)(F)CO>>OCC(F)(F)CN1CCOCC1', 'CC(=O)Cl.c1ccc(N)cc1>>CC(=O)Nc1ccccc1' ] results = list(rxn_mapper.map_reactions_with_info(reactions, detailed=False)) for i, result in enumerate(results): if result: print(f"Reaction {i + 1}:") print(f" Mapped: {result['mapped_rxn']}") print(f" Confidence: {result['confidence']:.4f}") else: print(f"Reaction {i + 1}: Failed to map") ``` ### Response #### Success Response (200) An iterator yielding dictionaries, where each dictionary contains detailed mapping information for a reaction, including `mapped_rxn` and `confidence`. An empty dictionary is returned for failed reactions. #### Response Example ```json { "example": { "mapped_rxn": "[mapped reaction string]", "confidence": 0.95 } } ``` ``` -------------------------------- ### RXNMapper.convert_batch_to_attns - Extract Raw Attention Matrices Source: https://context7.com/rxn4chemistry/rxnmapper/llms.txt A low-level method to extract raw attention matrices from a batch of reactions. This method does not perform atom mapping and is useful for analyzing the internal workings of the model. ```APIDOC ## RXNMapper.convert_batch_to_attns ### Description Extracts raw attention matrices from a batch of reaction SMILES strings without performing atom mapping. Allows specifying a particular transformer layer and attention head. ### Method `convert_batch_to_attns(reactions: list[str], force_layer: int, force_head: int) -> list[torch.Tensor]` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from rxnmapper import RXNMapper import torch rxn_mapper = RXNMapper() reactions = [ 'CC.O>>CCO', 'CC=O.N>>CC(N)O' ] attention_tensors = rxn_mapper.convert_batch_to_attns( reactions, force_layer=10, force_head=5 ) for i, attn in enumerate(attention_tensors): print(f"Reaction {i + 1}:") print(f" Attention shape: {attn.shape}") print(f" Device: {attn.device}") ``` ### Response #### Success Response (200) A list of PyTorch tensors, where each tensor represents the attention matrix for a reaction. #### Response Example ```json { "example": [ "torch.Tensor of shape (num_tokens, num_tokens)", "torch.Tensor of shape (num_tokens, num_tokens)" ] } ``` ``` -------------------------------- ### Predict Retrosynthesis with SMILES Source: https://github.com/rxn4chemistry/rxnmapper/blob/main/docs/_modules/rxn4chemistry.html Use this method to predict a retrosynthesis by providing the product's SMILES string. Ensure the API key and project ID are set before calling. ```python response = rxn4chemistry_wrapper.predict_automatic_retrosynthesis( 'Brc1c2ccccc2c(Br)c2ccccc12' ) ``` -------------------------------- ### Set API Key Source: https://github.com/rxn4chemistry/rxnmapper/blob/main/docs/_modules/rxn4chemistry.html Sets the API key for authentication. This method also rebuilds the necessary headers for subsequent API requests. ```APIDOC ## POST /api-key ### Description Set the API key. This method also rebuilds the headers. ### Method POST ### Endpoint /api-key ### Request Body - **api_key** (str) - Required - An API key to access the service. ### Request Example ```json { "api_key": "API_KEY" } ``` ``` -------------------------------- ### Tokenize Reaction SMILES for Model Input Source: https://context7.com/rxn4chemistry/rxnmapper/llms.txt Use RXNMapper.tokenize_for_model to convert reaction SMILES strings into token sequences compatible with the transformer model, including special tokens. ```python from rxnmapper import RXNMapper rxn_mapper = RXNMapper() reaction = 'CC(=O)O.CCO>>CC(=O)OCC.O' # Get tokenized representation tokens = rxn_mapper.tokenize_for_model(reaction) print(f"Tokens: {tokens}") # Output: ['[CLS]', 'C', 'C', '(', '=', 'O', ')', 'O', '.', 'C', 'C', 'O', '>>', 'C', 'C', '(', '=', 'O', ')', 'O', 'C', 'C', '.', 'O', '[SEP]'] print(f"Number of tokens: {len(tokens)}") ``` -------------------------------- ### Citation format Source: https://github.com/rxn4chemistry/rxnmapper/blob/main/README.md BibTeX citation for the RXNMapper publication. ```bibtex @article{schwaller2021extraction, title={Extraction of organic chemistry grammar from unsupervised learning of chemical reactions}, author={Schwaller, Philippe and Hoover, Benjamin and Reymond, Jean-Louis and Strobelt, Hendrik and Laino, Teodoro}, journal={Science Advances}, volume={7}, number={15}, pages={eabe4166}, year={2021}, publisher={American Association for the Advancement of Science} } ``` -------------------------------- ### Extract Raw Attention Matrices from Reactions Source: https://context7.com/rxn4chemistry/rxnmapper/llms.txt Utilize RXNMapper.convert_batch_to_attns for low-level access to attention matrices without performing atom mapping. Specify the layer and head for extraction. ```python from rxnmapper import RXNMapper import torch rxn_mapper = RXNMapper() reactions = [ 'CC.O>>CCO', 'CC=O.N>>CC(N)O' ] # Extract attention matrices attention_tensors = rxn_mapper.convert_batch_to_attns( reactions, force_layer=10, # Specific layer to use force_head=5 # Specific attention head ) for i, attn in enumerate(attention_tensors): print(f"Reaction {i + 1}:") print(f" Attention shape: {attn.shape}") # (num_tokens, num_tokens) print(f" Device: {attn.device}") ``` -------------------------------- ### Predict Automatic Retrosynthesis Source: https://github.com/rxn4chemistry/rxnmapper/blob/main/docs/_modules/rxn4chemistry.html Launches an automated retrosynthesis prediction for a given product SMILES string. Allows for customization of precursors and prediction parameters. ```APIDOC ## POST /api/predict/retrosynthesis ### Description Launch automated retrosynthesis prediction given a product SMILES. ### Method POST ### Endpoint /api/predict/retrosynthesis ### Parameters #### Request Body - **product** (str) - Required - A product SMILES string. - **availability_pricing_threshold** (int) - Optional - Maximum price in USD per mg/ml of commercially available compounds that will be considered available precursors. Defaults to 0. - **available_smiles** (str) - Optional - SMILES of molecules available as precursors. Multiple molecules can be provided separating them via ".". Defaults to None. - **exclude_smiles** (str) - Optional - SMILES of molecules to exclude from the set of precursors. Multiple molecules can be provided separating them via ".". Defaults to None. - **exclude_substructures** (str) - Optional - SMILES of substructures to exclude from precursors. Multiple molecules can be provided separating them via ".". Defaults to None. - **exclude_target_molecule** (bool) - Optional - Whether the product itself should be excluded from the precursors. Defaults to True. - **fap** (float) - Optional - Forward acceptance probability. The step is retained if the forward confidence is greater than FAP. Defaults to 0.6. - **max_steps** (int) - Optional - Maximum number of retrosynthetic steps. Defaults to 3. - **nbeams** (int) - Optional - Number of beams for the prediction search. Defaults to 10. - **pruning_steps** (int) - Optional - Number of pruning steps. Defaults to 2. ### Request Example ```json { "product": "CCO", "max_steps": 5, "fap": 0.7 } ``` ### Response #### Success Response (200) - **response** (dict) - Dictionary containing the prediction results, including a prediction ID. ### Response Example ```json { "response": { "payload": { "id": "prediction_id_value" } } } ``` ``` -------------------------------- ### rxnmapper.tokenization_smiles classes Source: https://github.com/rxn4chemistry/rxnmapper/blob/main/docs/_modules/rxnmapper.html Classes for tokenizing SMILES strings using basic regex or BERT-based tokenizers. ```APIDOC ## BasicSmilesTokenizer ### Description Run basic SMILES tokenization using a regex pattern. ## SmilesTokenizer ### Description Constructs a SmilesTokenizer based on the BERT tokenizer architecture. ### Parameters - **vocab_file** (str) - Required - Path to a SMILES character per line vocabulary file. ## add_padding_tokens(token_ids, length, right) ### Description Adds padding tokens to return a sequence of a specific length. ```