Skip to content
27 changes: 21 additions & 6 deletions charge/servers/AiZynthTools.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,11 +57,15 @@ def __init__(self, route):
self.nodes: Dict[int, Node] = {}
self.num_nodes = 0
self._build_path()
self.leaf_nodes = [node_id for node_id, node in self.nodes.items() if node.is_leaf]
self.leaf_nodes = [
node_id for node_id, node in self.nodes.items() if node.is_leaf
]

def _build_path(self):

self.root = Node(node_id=0, smiles=self.route["smiles"], children=[], is_root=True)
self.root = Node(
node_id=0, smiles=self.route["smiles"], children=[], is_root=True
)
self.nodes[0] = self.root
self.num_nodes += 1
reaction_node = self.route["children"][0]
Expand All @@ -86,7 +90,9 @@ def _add_children(self, parent_node, reaction, children):
self.num_nodes += 1
if "children" in child:
reaction_node = child["children"][0]
self._add_children(child_node, reaction_node, reaction_node["children"])
self._add_children(
child_node, reaction_node, reaction_node["children"]
)
else:
child_node.is_leaf = True

Expand Down Expand Up @@ -133,6 +139,7 @@ def is_molecule_synthesizable(smiles: str) -> bool:
"""Checks if a given molecule is synthesizable. First checks if it is
available in a stock database, otherwise runs a retrosynthesis to see if a
synthesis route can be found.

Args:
smiles (str): The SMILES string of the molecule to check.

Expand All @@ -143,7 +150,9 @@ def is_molecule_synthesizable(smiles: str) -> bool:
ValueError: If the molecule is not valid.
"""
if not HAS_AIZYNTHFINDER:
raise ImportError("Please install the aizynthfinder support packages to use this module.")
raise ImportError(
"Please install the aizynthfinder support packages to use this module."
)

logger.info(f"Checking if molecule {smiles} is synthesizable.")

Expand All @@ -163,7 +172,9 @@ def is_molecule_synthesizable(smiles: str) -> bool:
for route in routes:
path = ReactionPath(route=route)
# check if all leaf nodes are purchasable
all_purchasable = all(path.nodes[node_id].purchasable is True for node_id in path.leaf_nodes)
all_purchasable = all(
path.nodes[node_id].purchasable is True for node_id in path.leaf_nodes
)
if all_purchasable:
return True
return False
Expand All @@ -175,13 +186,17 @@ def find_synthesis_routes(smiles: str) -> list[dict]:

Args:
smiles (str): the target molecule in SMILES representation.

Returns:
list[dict]: a list of synthesis routes, each of which is a reaction tree in json/dict format.

Raises:
ValueError: If the molecule is not valid.
"""
if not HAS_AIZYNTHFINDER:
raise ImportError("Please install the aizynthfinder support packages to use this module.")
raise ImportError(
"Please install the aizynthfinder support packages to use this module."
)

logger.info(f"Find a synthesis route for molecule {smiles}.")

Expand Down
Loading