rxn4chemistry package

Submodules

rxn4chemistry.callbacks module

Callbacks for IBM RXN for Chemistry API.

rxn4chemistry.callbacks.automatic_retrosynthesis_results_on_success(response: requests.models.Response) → dict

Process the successful response of an automatic retrosyntesis result request.

Parameters

response (requests.models.Response) – response from an API request.

Returns

dictionary representing the response.

Return type

dict

rxn4chemistry.callbacks.default_on_success(response: requests.models.Response) → dict

Process the successful response.

Parameters

response (requests.models.Response) – response from an API request.

Returns

dictionary representing the response.

Return type

dict

rxn4chemistry.callbacks.paragraph_to_actions_on_success(response: requests.models.Response) → dict

Process the successful response of a paragraph to actions request.

Parameters

response (requests.models.Response) – response from an API request.

Returns

dictionary representing the response.

Return type

dict

rxn4chemistry.callbacks.predict_reaction_batch_on_success(response: requests.models.Response) → dict

Process the successful response of requests returning predict reaction batch results.

Parameters

response (requests.models.Response) – response from an API request.

Returns

dictionary representing the response.

Return type

dict

rxn4chemistry.callbacks.prediction_id_on_success(response: requests.models.Response) → dict

Process the successful response of requests returning a prediction identifier.

Parameters

response (requests.models.Response) – response from an API request.

Returns

dictionary representing the response.

Return type

dict

rxn4chemistry.callbacks.retrosynthesis_sequence_pdf(response: requests.models.Response) → dict

Process the successful response of .pdf retrosynthesis sequence report retrieval.

Parameters

response (requests.models.Response) – response from an API request.

Returns

dictionary representing the response.

Return type

dict

rxn4chemistry.callbacks.synthesis_analysis_report_pdf(response: requests.models.Response) → dict

Process the successful response of .pdf spectrometer report retrieval.

Parameters

response (requests.models.Response) – response from an API request.

Returns

dictionary representing the response.

Return type

dict

rxn4chemistry.callbacks.synthesis_execution_id_on_success(response: requests.models.Response) → dict

Process the successful response of requests returning a synthesis execution identifier.

Parameters

response (requests.models.Response) – response from an API request.

Returns

dictionary representing the response.

Return type

dict

rxn4chemistry.callbacks.synthesis_execution_status_on_success(response: requests.models.Response) → dict

Process the successful response of requests returning a synthesis execution status.

Parameters

response (requests.models.Response) – response from an API request.

Returns

dictionary representing the response.

Return type

dict

rxn4chemistry.callbacks.synthesis_id_on_success(response: requests.models.Response) → dict

Process the successful response of requests returning a synthesis identifier.

Parameters

response (requests.models.Response) – response from an API request.

Returns

dictionary representing the response.

Return type

dict

rxn4chemistry.callbacks.synthesis_on_success(response: requests.models.Response) → dict

Process the successful response of requests returning a synthesis procedure.

Parameters

response (requests.models.Response) – response from an API request.

Returns

dictionary representing the response.

Return type

dict

rxn4chemistry.callbacks.task_id_on_success(response: requests.models.Response) → dict

Process the successful response of requests returning a task identifier.

Parameters

response (requests.models.Response) – response from an API request.

Returns

dictionary representing the response.

Return type

dict

rxn4chemistry.core module

Core IBM RXN for Chemistry API module.

class rxn4chemistry.core.RXN4ChemistryWrapper(api_key: str, project_id: Optional[str] = None, base_url: Optional[str] = None)

Bases: object

Python wrapper for IBM RXN for Chemistry to access the REST API requests.

create_project(name: str, invitations: list = [], set_project: bool = True) → requests.models.Response

Create new project on platform and set the project id, which is required to predict chemical reactions.

Parameters
  • name (str) – name of the project.

  • invitations (list, optional) – list of invitations for the project. Defaults to [], a.k.a. no invitations.

  • set_project (bool, optional) – wheter the created project is set. Defaults to True.

Returns

dictionary built from the JSON response. Empty in case of errors.

Return type

dict

Examples

Create a project using the wrapper:

>>> rxn4chemistry_wrapper.create_project('test')
create_synthesis_from_sequence(sequence_id: str, ai_model: str = '2020-10-20') → requests.models.Response

Create a new synthesis from a sequence identifier.

A sequence id can be retrieved from the results of an automated retrosynthesis prediction.

Parameters
  • sequence_id (str) – a sequence identifier returned by predict_automatic_retrosynthesis_results.

  • ai_model (str, optional) – model release. Defaults to ‘2020-10-20’.

Returns

dictionary containing the synthesis identifier and the

response.

Return type

dict

Examples

Create a synthesis by providing the desired sequence identifier:

>>> response = rxn4chemistry_wrapper.create_synthesis_from_sequence(
    '5dd273618sid4897af'
)
get_node_actions()

Return a list of dictionaries describing the actions for a specific node in a synthesis tree. All the automatically generated fields are filtered out and returns only the editable fields for each dictionary.

Parameters
  • synthesis_id (str) – a synthesis identifier returned by create_synthesis_from_sequence() method.

  • node_id (str) – the ‘id’ field of a specific node in the synthesis tree

Returns

List of dictionaries of all the actions in the specific

node, simplified to only include editable fields.

Return type

List[Dict]

Examples

Return the list of actions for the given synthesis and node identifier:

>>> result = rxn4chemistry_wrapper.get_node_actions(
    synthesis_id='5dd273618sid4897af', node_id='5z7f6bgz6g95gcbh'
)
get_predict_automatic_retrosynthesis_results(prediction_id: str) → requests.models.Response

Get the predict automatic retrosynthesis results for a prediction_id.

Parameters

prediction_id (str) – prediction identifier.

Returns

dictionary containing the prediction results.

Return type

dict

Examples

Get results from an automatic retrosynthesis prediction by providing the prediction identifier:

>>> rxn4chemistry_wrapper.get_predict_automatic_retrosynthesis_results(
    response['response']['payload']['id']
    # or response['prediction_id']
)
{...}
get_predict_reaction_batch_results(task_id: str) → requests.models.Response

Get the predict reaction batch results for a task_id.

Parameters

task_id (str) – task identifier.

Returns

dictionary containing the prediction results.

Return type

dict

Examples

Get results from a reaction prediction by providing the prediction identifier:

>>> rxn4chemistry_wrapper.get_predict_reaction_batch_results(
    response["task_id"]
)
{...}
get_predict_reaction_results(prediction_id: str) → requests.models.Response

Get the predict reaction results for a prediction_id.

Parameters

prediction_id (str) – prediction identifier.

Returns

dictionary containing the prediction results.

Return type

dict

Examples

Get results from a reaction prediction by providing the prediction identifier:

>>> rxn4chemistry_wrapper.get_predict_reaction_results(
    response['response']['payload']['id']
    # or response['prediction_id']
)
{...}
get_retrosynthesis_sequence_pdf(prediction_id: str, sequence_id: str) → requests.models.Response

Get the .pdf report for a given retrosynthesis sequence.

Parameters
  • prediction_id (str) – prediction identifier.

  • sequence_id (str) – sequence identifier.

Returns

dictionary containing the .pdf report.

Return type

dict

Examples

Get a .pdf report providing the prediction identifier and a sequence identifier:

>>> rxn4chemistry_wrapper.get_retrosynthesis_sequence_pdf(
    response['response']['payload']['id'],
    '5e788ae548260b770105ecf4'
)
{...}
get_synthesis_execution(synthesis_id: str) → requests.models.Response

Get a synthesis procedure based on its identifier.

The provided synthesis identifier can be obtained as a previous step by calling the create_synthesis_from_sequence() method.

Parameters

synthesis_id (str) – a synthesis identifier returned by create_synthesis_from_sequence() method.

Returns

dictionary containing the the response.

Return type

dict

Examples

Retrieve a synthesis procedure by providing the desired sequence identifier:

>>> response = rxn4chemistry_wrapper.get_synthesis(
    '5dd273618sid4897af'
)
get_synthesis_execution_plan()

Return the synthesis tree for the given synthesis_id for an execution.

This is a simplified version of get_synthesis_status which only includes synthesis related information and no meta data. It also returns a flattened list of all the actions involved in every step of the sequence.

Parameters

synthesis_id (str) – a synthesis identifier returned by create_synthesis_from_sequence() method.

Returns

A dictionary representation of the synthesis

tree and a flattened list containing all actions of the entire synthesis represented as dictionaries.

Return type

Tuple[Dict, List, List]

Examples

Return the flattened list of actions for the given synthesis identifier:

>>> result = rxn4chemistry_wrapper.get_synthesis_execution_plan(
    synthesis_id='5dd273618sid4897af'
)
get_synthesis_plan()

Return the synthesis tree for the given synthesis_id.

This is a simplified version of get_synthesis_status which only includes synthesis related information and no meta data. It also returns a flattened list of all the actions involved in every step of the sequence.

Parameters

synthesis_id (str) – a synthesis identifier returned by create_synthesis_from_sequence() method.

Returns

A dictionary representation of the synthesis

tree and a flattened list containing all actions of the entire synthesis represented as dictionaries.

Return type

Tuple[Dict, List, List]

Examples

Return the flattened list of actions for the given synthesis identifier:

>>> result = rxn4chemistry_wrapper.get_synthesis_plan(
    synthesis_id='5dd273618sid4897af'
)
get_synthesis_procedure(synthesis_id: str) → requests.models.Response

Get a synthesis procedure based on its identifier.

The provided synthesis identifier can be obtained as a previous step by calling the create_synthesis_from_sequence() method.

Parameters

synthesis_id (str) – a synthesis identifier returned by create_synthesis_from_sequence() method.

Returns

dictionary containing the the response.

Return type

dict

Examples

Retrieve a synthesis procedure by providing the desired sequence identifier:

>>> response = rxn4chemistry_wrapper.get_synthesis(
    '5dd273618sid4897af'
)
get_synthesis_status(synthesis_id: str) → requests.models.Response

Get the status of a given synthesis execution based on its identifier.

The provided synthesis identifier can be obtained as a previous step by calling the create_synthesis_from_sequence() method.

Parameters

synthesis_id (str) – a synthesis identifier returned by create_synthesis_from_sequence() method.

Returns

dictionary containing the the response.

Return type

dict

Examples

Get a synthesis execution statu by providing the desired sequence identifier:

>>> response = rxn4chemistry_wrapper.get_synthesis_status(
    '5dd273618sid4897af'
)
list_all_attempts_in_project(project_id: Optional[str] = None, page: int = 0, size: int = 8, ascending_creation_order: bool = True) → requests.models.Response

Get a list of all the forward prediction attempts in the set project.

Parameters
  • project_id (str, optional) – project identifier. Defaults to None, a.k.a., use the currently set project.

  • page (int, optional) – page to list attempts from. Defaults to 0.

  • size (int, optional) – number of elements per page. Defaults to 8.

  • ascending_creation_order (bool, optional) – sort attempts by ascending creation date. Defaults to True.

Returns

dictionary listing the attempts.

Return type

dict

Examples

Retrieve all the forward reaction prediction attempts for currently

set project identifier:

>>> rxn4chemistry_wrapper.list_all_attempts_in_project()
{...}
list_all_projects() → requests.models.Response

Get a list of all projects.

Returns

dictionary listing the projects.

Return type

dict

Examples

Retrieve all the projects for the API key used to construct the wrapper:

>>> rxn4chemistry_wrapper.list_all_projects()
{...}
list_all_retro_attempts_in_project(project_id: Optional[str] = None, page: int = 0, size: int = 8, ascending_creation_order: bool = True) → requests.models.Response

Get a list of all the retrosynthesis attempts in the set project.

Parameters
  • project_id (str, optional) – project identifier. Defaults to None, a.k.a., use the currently set project.

  • page (int, optional) – page to list attempts from. Defaults to 0.

  • size (int, optional) – number of elements per page. Defaults to 8.

  • ascending_creation_order (bool, optional) – sort attempts by ascending creation date. Defaults to True.

Returns

dictionary listing the retrosynthesis attempts.

Return type

dict

Examples

Retrieve all the retrosynthesis attempts for currently set project

identifier:

>>> rxn4chemistry_wrapper.list_all_retro_attempts_in_project()
{...}
paragraph_to_actions(paragraph: str) → requests.models.Response

Get the actions from a paragraph describing a recipe.

Parameters

paragraph (str) – paragraph describing a recipe.

Returns

dictionary containing the actions.

Return type

dict

Examples

Get actions from a paragraph:

>>> 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']
predict_automatic_retrosynthesis(product: str, availability_pricing_threshold: int = 0, available_smiles: Optional[str] = None, exclude_smiles: Optional[str] = None, exclude_substructures: Optional[str] = None, exclude_target_molecule: bool = True, fap: float = 0.6, max_steps: int = 3, nbeams: int = 10, pruning_steps: int = 2, ai_model: str = '2020-07-01') → requests.models.Response

Launch automated retrosynthesis prediction given a product SMILES.

Parameters
  • product (str) – a prouct SMILES.

  • availability_pricing_threshold (int, optional) – maximum price in USD per g/ml of commercially available compounds that will be considered available precursors for the retrosynthesis. Defaults to 0, a.k.a., no threshold.

  • available_smiles (str, optional) – SMILES of molecules available as precursors. Defaults to None, a.k.a., use the default ones. Multiple molecules can be provided separating them via “.”.

  • exclude_smiles (str, optional) – SMILES of molecules to exclude from the set of precursors. Defaults to None, a.k.a., no excluded molecules. Multiple molecules can be provided separating them via “.”.

  • exclude_substructures (str, optional) – SMILES of substructures to exclude from precursors Defaults to None, a.k.a., no excluded substructures. Multiple molecules can be provided separating them via “.”.

  • exclude_target_molecule (bool, optional) – whether the product has to be excluded. Defaults to True.

  • fap (float, optional) – forward acceptance probability. Every retrosynthetic step is evaluated with the forward prediction model. The step is retained if the 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) – maximum number of beams exploring the hyper-tree. Defaults to 10.

  • pruning_steps (int, optional) – number of interval steps to prune the explored hyper-tree. Defaults to 2.

  • ai_model (str, optional) – model release. Defaults to ‘2020-07-01’.

Returns

dictionary containing the prediction identifier and the response.

Return type

dict

Raises

ValueError – in case self.project_id is not set.

Examples

Predict a retrosynthesis by providing the product SMILES:

>>> response = rxn4chemistry_wrapper.predict_automatic_retrosynthesis(
    'Brc1c2ccccc2c(Br)c2ccccc12'
)
predict_reaction(precursors: str, prediction_id: Optional[str] = None, ai_model: str = '2020-08-10') → requests.models.Response

Launch prediction given precursors SMILES.

Parameters
  • precursors (str) – precursor SMILES separated with a ‘.’.

  • prediction_id (str, optional) – prediction identifier. Defaults to None, a.k.a., run an independent prediction.

  • ai_model (str, optional) – model release. Defaults to ‘2020-08-10’.

Returns

dictionary containing the prediction identifier and the response.

Return type

dict

Raises

ValueError – in case self.project_id is not set.

Examples

Predict a reaction by providing the reaction SMILES:

>>> response = rxn4chemistry_wrapper.predict_reaction(
    'BrBr.c1ccc2cc3ccccc3cc2c1'
)
predict_reaction_batch()

Launch prediction given precursors SMILES.

Parameters
  • precursors (List[str]) – list of precursor SMILES separated with a ‘.’.

  • ai_model (str, optional) – model release. Defaults to ‘2020-08-10’.

Returns

dictionary containing the response.

Return type

dict

Raises

ValueError – in case self.project_id is not set.

Examples

Predict a reaction by providing the reaction SMILES and get task identifier and status:

>>> response = rxn4chemistry_wrapper.predict_reaction_batch(
    ['BrBr.c1ccc2cc3ccccc3cc2c1', 'Cl.c1ccc2cc3ccccc3cc2c1']
)
set_api_key(api_key: str)

Set the API key.

This method also rebuilds the headers.

Parameters

api_key (str) – an API key to access the service.

Examples

Set an API key:

>>> rxn4chemistry_wrapper.set_api_key('API_KEY')
set_base_url(base_url: str) → None

Set base url for the RXN for Chemistry service.

Parameters

base_url (str) – base url for the service to set.

set_project(project_id: str)

Set project using the project id.

The project_id can also be found in the url of the project.

Parameters

project_id (str) – project identifier.

Examples

Set a project for the wrapper instantiated:

>>> rxn4chemistry_wrapper.set_project('PROJECT_ID')
start_synthesis(synthesis_id: str) → requests.models.Response

Start a synthesis on either on the robot or on the simulator.

A robot (or simulator) key must be active in the user account in order for the query to be successful. The provided synthesis identifier can be obtained as a previous step by calling the create_synthesis_from_sequence() method.

Parameters

synthesis_id (str) – a synthesis identifier returned by create_synthesis_from_sequence() method.

Returns

dictionary containing the response.

Return type

dict

Examples

Start the synthesis with a given identifier:

>>> response = rxn4chemistry_wrapper.start_synthesis(
    synthesis_id='5dd273618sid4897af'
)
update_node_actions()

Update the list of actions for a specific node. The given actions will completely replace the existing actions for this node in the tree.

Parameters
  • synthesis_id (str) – a synthesis identifier returned by create_synthesis_from_sequence() method.

  • node_id (str) – the ‘id’ field of a specific node in the synthesis tree

  • actions (List[Dict[str, Any]) – A list of actions which will completely replace the existing actions for this node.

Returns

dictionary containing the .pdf report.

Return type

dict

Examples

Update the list of actions for the given synthesis and node identifier:

>>> result = rxn4chemistry_wrapper.update_node_actions(
        synthesis_id='5dd273618sid4897af',
        node_id='5z7f6bgz6g95gcbh',
        actions=[
            {
                'name': 'add',
                "content": {
                    "atmosphere": None,
                    "duration": None,
                    "temperature": None,
                    "dropwise": {
                      "value": False,
                      "quantity": None,
                      "unit": None
                    },
                    "material": {
                      "value": "ethanol",
                      "quantity": {
                        "value": 10,
                        "unit": "ml"
                      },
                      "unit": None
                    }
                },
            }
        ]
    )
rxn4chemistry.core.post_order_tree_traversal()

rxn4chemistry.decorators module

Decorators for IBM RXN for Chemistry API.

exception rxn4chemistry.decorators.RequestTimeoutNotElapsed

Bases: RuntimeError

Exception raised when the timeout between requests has not elapsed.

exception rxn4chemistry.decorators.RequestsPerMinuteExceeded

Bases: RuntimeError

Exception raised when too many requests are sent in a minute.

rxn4chemistry.decorators.ibm_rxn_api_limits(function: Callable) → Callable

Decorator to handle the limits in the RXN API.

Parameters

function (Callable) – function to decorate.

Raises
Returns

a function wrapped with the decorator.

Return type

Callable

rxn4chemistry.decorators.response_handling(function: Optional[Callable] = None, success_status_code: int = 200, on_success: Callable = <function default_on_success>) → Callable

Decorator to handle request responses.

Parameters
  • function (Callable, optional) – function to decorate.

  • success_status_code (int) – status expected on success.

  • on_success (Callable) – function to call on success.

Returns

a function wrapped with the decorator.

Return type

Callable

rxn4chemistry.urls module

URL routes for IBM RXN for Chemistry API.

class rxn4chemistry.urls.RXN4ChemistryRoutes(base_url: Optional[str] = None, api_version: str = 'v1')

Bases: object

Routes for RXN for Chemistry service.

property base_url

Get the base url for the RXN for Chemistry service.

Returns

base url for the service.

Return type

str

Module contents

rxn4chemistry initialization.