RepoPeft-data / oracle_context_cache /MolecularAI__aizynthfinder.json
nanigock's picture
Upload folder using huggingface_hub
cd15502 verified
{"repo": "MolecularAI/aizynthfinder", "n_pairs": 200, "version": "v2_function_scoped", "contexts": {"tests/retrostar/test_retrostar_nodes.py::103": {"resolved_imports": ["aizynthfinder/search/retrostar/nodes.py", "aizynthfinder/chem/serialization.py", "aizynthfinder/search/andor_trees.py"], "used_names": ["MoleculeDeserializer", "MoleculeNode", "MoleculeSerializer"], "enclosing_function": "test_serialization_deserialization", "extracted_code": "# Source: aizynthfinder/search/retrostar/nodes.py\nclass MoleculeNode(TreeNodeMixin):\n \"\"\"\n An OR node representing a molecule\n\n :ivar cost: the cost of synthesizing the molecule\n :ivar expandable: if True, this node is part of the frontier\n :ivar mol: the molecule represented by the node\n :ivar in_stock: if True the molecule is in stock and hence should not be expanded\n :ivar parent: the parent of the node\n :ivar solved: if True the molecule is in stock or at least one child node is solved\n :ivar value: the current rn(m|T)\n\n :param mol: the molecule to be represented by the node\n :param config: the configuration of the search\n :param parent: the parent of the node, optional\n \"\"\"\n\n def __init__(\n self,\n mol: TreeMolecule,\n config: Configuration,\n molecule_cost: MoleculeCost,\n parent: Optional[ReactionNode] = None,\n ) -> None:\n self.mol = mol\n self._config = config\n self.molecule_cost = molecule_cost\n self.cost = self.molecule_cost(mol)\n self.value = self.cost\n self.in_stock = mol in config.stock\n self.parent = parent\n\n self._children: List[ReactionNode] = []\n self.solved = self.in_stock\n # Makes it unexpandable if we have reached maximum depth\n self.expandable = self.mol.transform < self._config.search.max_transforms\n\n if self.in_stock:\n self.expandable = False\n self.value = 0\n\n @classmethod\n def create_root(\n cls, smiles: str, config: Configuration, molecule_cost: MoleculeCost\n ) -> \"MoleculeNode\":\n \"\"\"\n Create a root node for a tree using a SMILES.\n\n :param smiles: the SMILES representation of the root state\n :param config: settings of the tree search algorithm\n :return: the created node\n \"\"\"\n mol = TreeMolecule(parent=None, transform=0, smiles=smiles)\n return MoleculeNode(mol=mol, config=config, molecule_cost=molecule_cost)\n\n @classmethod\n def from_dict(\n cls,\n dict_: StrDict,\n config: Configuration,\n molecules: MoleculeDeserializer,\n molecule_cost: MoleculeCost,\n parent: Optional[ReactionNode] = None,\n ) -> \"MoleculeNode\":\n \"\"\"\n Create a new node from a dictionary, i.e. deserialization\n\n :param dict_: the serialized node\n :param config: settings of the tree search algorithm\n :param molecules: the deserialized molecules\n :param parent: the parent node\n :return: a deserialized node\n \"\"\"\n mol = molecules.get_tree_molecules([dict_[\"mol\"]])[0]\n node = MoleculeNode(mol, config, molecule_cost, parent)\n node.molecule_cost = molecule_cost\n for attr in [\"cost\", \"expandable\", \"value\"]:\n setattr(node, attr, dict_[attr])\n node.children = [\n ReactionNode.from_dict(\n child, config, molecules, node.molecule_cost, parent=node\n )\n for child in dict_[\"children\"]\n ]\n return node\n\n @property # type: ignore\n def children(self) -> List[ReactionNode]: # type: ignore\n \"\"\"Gives the reaction children nodes\"\"\"\n return self._children\n\n @children.setter\n def children(self, value: List[ReactionNode]) -> None:\n self._children = value\n\n @property\n def target_value(self) -> float:\n \"\"\"\n The V_t(m|T) value,\n the current cost of the tree containing this node\n\n :return: the value\n \"\"\"\n if self.parent:\n return self.parent.target_value\n return self.value\n\n @property\n def prop(self) -> StrDict:\n return {\"solved\": self.solved, \"mol\": self.mol}\n\n def add_stub(self, cost: float, reaction: RetroReaction) -> Sequence[MoleculeNode]:\n \"\"\"\n Add a stub / sub-tree to this node\n\n :param cost: the cost of the reaction\n :param reaction: the reaction creating the stub\n :return: list of all newly added molecular nodes\n \"\"\"\n reactants = reaction.reactants[reaction.index]\n if not reactants:\n return []\n\n ancestors = self.ancestors()\n for mol in reactants:\n if mol in ancestors:\n return []\n\n rxn_node = ReactionNode.create_stub(\n cost=cost,\n reaction=reaction,\n parent=self,\n config=self._config,\n )\n self._children.append(rxn_node)\n\n return rxn_node.children\n\n def ancestors(self) -> Set[TreeMolecule]:\n \"\"\"\n Return the ancestors of this node\n\n :return: the ancestors\n :rtype: set\n \"\"\"\n if not self.parent:\n return {self.mol}\n\n ancestors = self.parent.parent.ancestors()\n ancestors.add(self.mol)\n return ancestors\n\n def close(self) -> float:\n \"\"\"\n Updates the values of this node after expanding it.\n\n :return: the delta V value\n :rtype: float\n \"\"\"\n self.solved = any(child.solved for child in self.children)\n if self.children:\n new_value = np.min([child.value for child in self.children])\n else:\n new_value = np.inf\n\n v_delta = new_value - self.value\n self.value = new_value\n\n self.expandable = False\n return v_delta\n\n def serialize(self, molecule_store: MoleculeSerializer) -> StrDict:\n \"\"\"\n Serialize the node object to a dictionary\n\n :param molecule_store: the serialized molecules\n :return: the serialized node\n \"\"\"\n dict_ = {attr: getattr(self, attr) for attr in [\"cost\", \"expandable\", \"value\"]}\n dict_[\"mol\"] = molecule_store[self.mol]\n dict_[\"children\"] = [child.serialize(molecule_store) for child in self.children]\n return dict_\n\n def update(self, solved: bool) -> None:\n \"\"\"\n Update the node as part of the update algorithm,\n calling the `update()` method of its parent if available.\n\n :param solved: if the child node was solved\n \"\"\"\n new_value = np.min([child.value for child in self.children])\n new_solv = self.solved or solved\n updated = (self.value != new_value) or (self.solved != new_solv)\n\n v_delta = new_value - self.value\n self.value = new_value\n self.solved = new_solv\n\n if updated and self.parent:\n self.parent.update(v_delta, from_mol=self.mol)\n\n\n# Source: aizynthfinder/chem/serialization.py\nclass MoleculeSerializer:\n \"\"\"\n Utility class for serializing molecules\n\n The id of the molecule to be serialized can be obtained with:\n\n .. code-block::\n\n serializer = MoleculeSerializer()\n mol = Molecule(smiles=\"CCCO\")\n idx = serializer[mol]\n\n which will take care of the serialization of the molecule.\n \"\"\"\n\n def __init__(self) -> None:\n self._store: Dict[int, Any] = {}\n\n def __getitem__(self, mol: Optional[aizynthfinder.chem.Molecule]) -> Optional[int]:\n if mol is None:\n return None\n\n id_ = id(mol)\n if id_ not in self._store:\n self._add_mol(mol)\n return id_\n\n @property\n def store(self) -> Dict[int, Any]:\n \"\"\"Return all serialized molecules as a dictionary\"\"\"\n return self._store\n\n def _add_mol(self, mol: aizynthfinder.chem.Molecule) -> None:\n id_ = id(mol)\n dict_ = {\"smiles\": mol.smiles, \"class\": mol.__class__.__name__}\n if isinstance(mol, aizynthfinder.chem.TreeMolecule):\n dict_[\"parent\"] = self[mol.parent]\n dict_[\"transform\"] = mol.transform\n if not mol.parent:\n dict_[\"smiles\"] = mol.original_smiles\n else:\n dict_[\"smiles\"] = mol.mapped_smiles\n self._store[id_] = dict_\n\nclass MoleculeDeserializer:\n \"\"\"\n Utility class for deserializing molecules.\n The serialized molecules are created upon instantiation of the class.\n\n The deserialized molecules can be obtained with:\n\n .. code-block::\n\n deserializer = MoleculeDeserializer()\n mol = deserializer[idx]\n\n \"\"\"\n\n def __init__(self, store: Dict[int, Any]) -> None:\n self._objects: Dict[int, Any] = {}\n self._create_molecules(store)\n\n def __getitem__(self, id_: Optional[int]) -> Optional[aizynthfinder.chem.Molecule]:\n if id_ is None:\n return None\n return self._objects[id_]\n\n def get_tree_molecules(\n self, ids: Sequence[int]\n ) -> Sequence[aizynthfinder.chem.TreeMolecule]:\n \"\"\"\n Return multiple deserialized tree molecules\n\n :param ids: the list of IDs to deserialize\n :return: the molecule objects\n \"\"\"\n objects = []\n for id_ in ids:\n obj = self[id_]\n if obj is None or not isinstance(obj, aizynthfinder.chem.TreeMolecule):\n raise ValueError(f\"Failed to deserialize molecule with id {id_}\")\n objects.append(obj)\n return objects\n\n def _create_molecules(self, store: dict) -> None:\n for id_, spec in store.items():\n if isinstance(id_, str):\n id_ = int(id_)\n\n cls = spec[\"class\"]\n if \"parent\" in spec:\n spec[\"parent\"] = self[spec[\"parent\"]]\n\n kwargs = dict(spec)\n del kwargs[\"class\"]\n self._objects[id_] = getattr(aizynthfinder.chem, cls)(**kwargs)", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 9488}, "tests/dfpn/test_search.py::42": {"resolved_imports": ["aizynthfinder/search/dfpn/search_tree.py"], "used_names": ["SearchTree", "pytest"], "enclosing_function": "test_search", "extracted_code": "# Source: aizynthfinder/search/dfpn/search_tree.py\nclass SearchTree(AndOrSearchTreeBase):\n \"\"\"\n Encapsulation of the Depth-First Proof-Number (DFPN) search algorithm.\n\n This algorithm does not support:\n 1. Filter policy\n 2. Serialization and deserialization\n\n :ivar config: settings of the tree search algorithm\n :ivar root: the root node\n\n :param config: settings of the tree search algorithm\n :param root_smiles: the root will be set to a node representing this molecule, defaults to None\n \"\"\"\n\n def __init__(\n self, config: Configuration, root_smiles: Optional[str] = None\n ) -> None:\n super().__init__(config, root_smiles)\n self._mol_nodes: List[MoleculeNode] = []\n self._logger = logger()\n self._root_smiles = root_smiles\n if root_smiles:\n self.root: Optional[MoleculeNode] = MoleculeNode.create_root(\n root_smiles, config, self\n )\n self._mol_nodes.append(self.root)\n else:\n self.root = None\n\n self._routes: List[ReactionTree] = []\n self._frontier: Optional[Union[MoleculeNode, ReactionNode]] = None\n self._initiated = False\n\n self.profiling = {\n \"expansion_calls\": 0,\n \"reactants_generations\": 0,\n }\n\n @property\n def mol_nodes(self) -> Sequence[MoleculeNode]: # type: ignore\n \"\"\"Return the molecule nodes of the tree\"\"\"\n return self._mol_nodes\n\n def one_iteration(self) -> bool:\n \"\"\"\n Perform one iteration of expansion.\n\n If possible expand the frontier node twice, i.e. expanding an OR\n node and then and AND node. If frontier not expandable step up in the\n tree and find a new frontier to expand.\n\n If a solution is found, mask that tree for exploration and start over.\n\n :raises StopIteration: if the search should be pre-maturely terminated\n :return: if a solution was found\n :rtype: bool\n \"\"\"\n if not self._initiated:\n if self.root is None:\n raise ValueError(\"Root is undefined. Cannot make an iteration\")\n\n self._routes = []\n self._frontier = self.root\n assert self.root is not None\n\n while True:\n # Expand frontier, should be OR node\n assert isinstance(self._frontier, MoleculeNode)\n expanded_or = self._search_step()\n expanded_and = False\n if self._frontier:\n # Expand frontier again, this time an AND node\n assert isinstance(self._frontier, ReactionNode)\n expanded_and = self._search_step()\n if (\n expanded_or\n or expanded_and\n or self._frontier is None\n or self._frontier is self.root\n ):\n break\n\n found_solution = any(child.proven for child in self.root.children)\n if self._frontier is self.root:\n self.root.reset()\n\n if self._frontier is None:\n raise StopIteration()\n\n return found_solution\n\n def routes(self) -> List[ReactionTree]:\n \"\"\"\n Extracts and returns routes from the AND/OR tree\n\n :return: the routes\n \"\"\"\n if self.root is None:\n return []\n if not self._routes:\n self._routes = SplitAndOrTree(self.root, self.config.stock).routes\n return self._routes\n\n def _search_step(self) -> bool:\n assert self._frontier is not None\n expanded = False\n if self._frontier.expandable:\n self._frontier.expand()\n expanded = True\n if isinstance(self._frontier, ReactionNode):\n self._mol_nodes.extend(self._frontier.children)\n\n self._frontier.update()\n if not self._frontier.explorable():\n self._frontier = self._frontier.parent\n return False\n\n child = self._frontier.promising_child()\n if not child:\n self._frontier = self._frontier.parent\n return False\n\n self._frontier = child\n return expanded", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 4155}, "tests/retrostar/test_retrostar_nodes.py::40": {"resolved_imports": ["aizynthfinder/search/retrostar/nodes.py", "aizynthfinder/chem/serialization.py", "aizynthfinder/search/andor_trees.py"], "used_names": [], "enclosing_function": "test_create_stub", "extracted_code": "", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 0}, "tests/retrostar/test_retrostar_cost.py::45": {"resolved_imports": ["aizynthfinder/chem/__init__.py", "aizynthfinder/search/retrostar/cost.py"], "used_names": ["Molecule", "MoleculeCost", "pytest"], "enclosing_function": "test_molecule_cost_retrostar", "extracted_code": "# Source: aizynthfinder/chem/__init__.py\n\"\"\"\nfrom aizynthfinder.chem.mol import (\n Molecule,\n MoleculeException,\n TreeMolecule,\n UniqueMolecule,\n none_molecule,\n)\nfrom aizynthfinder.chem.reaction import (\n FixedRetroReaction,\n RetroReaction,\n SmilesBasedRetroReaction,\n\nfrom aizynthfinder.chem.mol import (\n Molecule,\n MoleculeException,\n TreeMolecule,\n UniqueMolecule,\n none_molecule,\n)\nfrom aizynthfinder.chem.reaction import (\n FixedRetroReaction,\n RetroReaction,\n SmilesBasedRetroReaction,\n TemplatedRetroReaction,\n\n Molecule,\n MoleculeException,\n TreeMolecule,\n UniqueMolecule,\n none_molecule,\n)\nfrom aizynthfinder.chem.reaction import (\n FixedRetroReaction,\n RetroReaction,\n SmilesBasedRetroReaction,\n TemplatedRetroReaction,\n hash_reactions,\n\n MoleculeException,\n TreeMolecule,\n UniqueMolecule,\n none_molecule,\n)\nfrom aizynthfinder.chem.reaction import (\n FixedRetroReaction,\n RetroReaction,\n SmilesBasedRetroReaction,\n TemplatedRetroReaction,\n hash_reactions,\n)\n\n)\nfrom aizynthfinder.chem.serialization import (\n MoleculeDeserializer,\n MoleculeSerializer,\n deserialize_action,\n serialize_action,\n)\n\n\n# Source: aizynthfinder/search/retrostar/cost.py\nclass MoleculeCost:\n \"\"\"\n A class to compute the molecule cost.\n\n The cost to be computed is taken from the input config. If no `molecule_cost` is\n set, assigns ZeroMoleculeCost as the `cost` by default. The `molecule_cost` can be\n set as a dictionary in config under `search` in the following format:\n 'algorithm': 'retrostar'\n 'algorithm_config': {\n 'molecule_cost': {\n 'cost': name of the search cost class or custom_package.custom_model.CustomClass,\n other settings or params\n }\n }\n\n The cost can be computed by calling the instantiated class with a molecule.\n\n .. code-block::\n\n calculator = MyCost(config)\n cost = calculator.calculate(molecule)\n\n :param config: the configuration of the tree search\n \"\"\"\n\n def __init__(self, config: Configuration) -> None:\n self._config = config\n if \"molecule_cost\" not in self._config.search.algorithm_config:\n self._config.search.algorithm_config[\"molecule_cost\"] = {\n \"cost\": \"ZeroMoleculeCost\"\n }\n kwargs = self._config.search.algorithm_config[\"molecule_cost\"].copy()\n\n cls = load_dynamic_class(kwargs[\"cost\"], retrostar_cost_module)\n del kwargs[\"cost\"]\n\n self.molecule_cost = cls(**kwargs) if kwargs else cls()\n\n def __call__(self, mol: Molecule) -> float:\n return self.molecule_cost.calculate(mol)", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 2698}, "tests/dfpn/test_nodes.py::46": {"resolved_imports": ["aizynthfinder/search/dfpn/nodes.py", "aizynthfinder/search/dfpn/__init__.py"], "used_names": ["BIG_INT"], "enclosing_function": "test_promising_child", "extracted_code": "# Source: aizynthfinder/search/dfpn/nodes.py\nBIG_INT = int(1e10)", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 64}, "tests/test_reactiontree.py::20": {"resolved_imports": ["aizynthfinder/reactiontree.py"], "used_names": [], "enclosing_function": "test_mcts_route_to_reactiontree", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/retrostar/test_retrostar_nodes.py::37": {"resolved_imports": ["aizynthfinder/search/retrostar/nodes.py", "aizynthfinder/chem/serialization.py", "aizynthfinder/search/andor_trees.py"], "used_names": [], "enclosing_function": "test_create_stub", "extracted_code": "", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 0}, "tests/breadth_first/test_nodes.py::33": {"resolved_imports": ["aizynthfinder/search/breadth_first/nodes.py", "aizynthfinder/chem/serialization.py"], "used_names": [], "enclosing_function": "test_create_stub", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/chem/test_serialization.py::83": {"resolved_imports": ["aizynthfinder/chem/serialization.py", "aizynthfinder/chem/__init__.py"], "used_names": ["MoleculeDeserializer", "MoleculeSerializer", "TreeMolecule"], "enclosing_function": "test_chaining", "extracted_code": "# Source: aizynthfinder/chem/serialization.py\nclass MoleculeSerializer:\n \"\"\"\n Utility class for serializing molecules\n\n The id of the molecule to be serialized can be obtained with:\n\n .. code-block::\n\n serializer = MoleculeSerializer()\n mol = Molecule(smiles=\"CCCO\")\n idx = serializer[mol]\n\n which will take care of the serialization of the molecule.\n \"\"\"\n\n def __init__(self) -> None:\n self._store: Dict[int, Any] = {}\n\n def __getitem__(self, mol: Optional[aizynthfinder.chem.Molecule]) -> Optional[int]:\n if mol is None:\n return None\n\n id_ = id(mol)\n if id_ not in self._store:\n self._add_mol(mol)\n return id_\n\n @property\n def store(self) -> Dict[int, Any]:\n \"\"\"Return all serialized molecules as a dictionary\"\"\"\n return self._store\n\n def _add_mol(self, mol: aizynthfinder.chem.Molecule) -> None:\n id_ = id(mol)\n dict_ = {\"smiles\": mol.smiles, \"class\": mol.__class__.__name__}\n if isinstance(mol, aizynthfinder.chem.TreeMolecule):\n dict_[\"parent\"] = self[mol.parent]\n dict_[\"transform\"] = mol.transform\n if not mol.parent:\n dict_[\"smiles\"] = mol.original_smiles\n else:\n dict_[\"smiles\"] = mol.mapped_smiles\n self._store[id_] = dict_\n\nclass MoleculeDeserializer:\n \"\"\"\n Utility class for deserializing molecules.\n The serialized molecules are created upon instantiation of the class.\n\n The deserialized molecules can be obtained with:\n\n .. code-block::\n\n deserializer = MoleculeDeserializer()\n mol = deserializer[idx]\n\n \"\"\"\n\n def __init__(self, store: Dict[int, Any]) -> None:\n self._objects: Dict[int, Any] = {}\n self._create_molecules(store)\n\n def __getitem__(self, id_: Optional[int]) -> Optional[aizynthfinder.chem.Molecule]:\n if id_ is None:\n return None\n return self._objects[id_]\n\n def get_tree_molecules(\n self, ids: Sequence[int]\n ) -> Sequence[aizynthfinder.chem.TreeMolecule]:\n \"\"\"\n Return multiple deserialized tree molecules\n\n :param ids: the list of IDs to deserialize\n :return: the molecule objects\n \"\"\"\n objects = []\n for id_ in ids:\n obj = self[id_]\n if obj is None or not isinstance(obj, aizynthfinder.chem.TreeMolecule):\n raise ValueError(f\"Failed to deserialize molecule with id {id_}\")\n objects.append(obj)\n return objects\n\n def _create_molecules(self, store: dict) -> None:\n for id_, spec in store.items():\n if isinstance(id_, str):\n id_ = int(id_)\n\n cls = spec[\"class\"]\n if \"parent\" in spec:\n spec[\"parent\"] = self[spec[\"parent\"]]\n\n kwargs = dict(spec)\n del kwargs[\"class\"]\n self._objects[id_] = getattr(aizynthfinder.chem, cls)(**kwargs)\n\n\n# Source: aizynthfinder/chem/__init__.py\n Molecule,\n MoleculeException,\n TreeMolecule,\n UniqueMolecule,\n none_molecule,\n)\nfrom aizynthfinder.chem.reaction import (\n FixedRetroReaction,\n RetroReaction,\n SmilesBasedRetroReaction,\n TemplatedRetroReaction,\n hash_reactions,", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 3289}, "tests/context/test_mcts_config.py::48": {"resolved_imports": ["aizynthfinder/aizynthfinder.py", "aizynthfinder/context/config.py", "aizynthfinder/context/stock/__init__.py"], "used_names": ["Configuration"], "enclosing_function": "test_load_from_file", "extracted_code": "# Source: aizynthfinder/context/config.py\nclass Configuration:\n \"\"\"\n Encapsulating the settings of the tree search, including the policy,\n the stock, the loaded scorers and various parameters.\n \"\"\"\n\n search: _SearchConfiguration = field(default_factory=_SearchConfiguration)\n post_processing: _PostprocessingConfiguration = field(\n default_factory=_PostprocessingConfiguration\n )\n stock: Stock = field(init=False)\n expansion_policy: ExpansionPolicy = field(init=False)\n filter_policy: FilterPolicy = field(init=False)\n scorers: ScorerCollection = field(init=False)\n\n def __post_init__(self) -> None:\n self.stock = Stock()\n self.expansion_policy = ExpansionPolicy(self)\n self.filter_policy = FilterPolicy(self)\n self.scorers = ScorerCollection(self)\n self._logger = logger()\n\n def __eq__(self, other: Any) -> bool:\n if not isinstance(other, Configuration):\n return False\n for key, setting in vars(self).items():\n if isinstance(setting, (int, float, str, bool, list)):\n if (\n vars(self)[key] != vars(other)[key]\n or self.search != other.search\n or self.post_processing != other.post_processing\n ):\n return False\n return True\n\n @classmethod\n def from_dict(cls, source: StrDict) -> \"Configuration\":\n \"\"\"\n Loads a configuration from a dictionary structure.\n The parameters not set in the dictionary are taken from the default values.\n The policies and stocks specified are directly loaded.\n\n :param source: the dictionary source\n :return: a Configuration object with settings from the source\n \"\"\"\n expansion_config = source.pop(\"expansion\", {})\n filter_config = source.pop(\"filter\", {})\n stock_config = source.pop(\"stock\", {})\n scorer_config = source.pop(\"scorer\", {})\n\n config_obj = Configuration()\n config_obj._update_from_config(dict(source))\n\n config_obj.expansion_policy.load_from_config(**expansion_config)\n config_obj.filter_policy.load_from_config(**filter_config)\n config_obj.stock.load_from_config(**stock_config)\n config_obj.scorers.create_default_scorers()\n config_obj.scorers.load_from_config(**scorer_config)\n\n return config_obj\n\n @classmethod\n def from_file(cls, filename: str) -> \"Configuration\":\n \"\"\"\n Loads a configuration from a yaml file.\n The parameters not set in the yaml file are taken from the default values.\n The policies and stocks specified in the yaml file are directly loaded.\n The parameters in the yaml file may also contain environment variables as\n values.\n\n :param filename: the path to a yaml file\n :return: a Configuration object with settings from the yaml file\n :raises:\n ValueError: if parameter's value expects an environment variable that\n does not exist in the current environment\n \"\"\"\n with open(filename, \"r\") as fileobj:\n txt = fileobj.read()\n environ_var = re.findall(r\"\\$\\{.+?\\}\", txt)\n for item in environ_var:\n if item[2:-1] not in os.environ:\n raise ValueError(f\"'{item[2:-1]}' not in environment variables\")\n txt = txt.replace(item, os.environ[item[2:-1]])\n _config = yaml.load(txt, Loader=yaml.SafeLoader)\n return Configuration.from_dict(_config)\n\n def _update_from_config(self, config: StrDict) -> None:\n self.post_processing = _PostprocessingConfiguration(\n **config.pop(\"post_processing\", {})\n )\n\n search_config = config.pop(\"search\", {})\n for setting, value in search_config.items():\n if value is None:\n continue\n if not hasattr(self.search, setting):\n raise AttributeError(f\"Could not find attribute to set: {setting}\")\n if setting.endswith(\"_bonds\"):\n if not isinstance(value, list):\n raise ValueError(\"Bond settings need to be lists\")\n value = _handle_bond_pair_tuples(value) if value else []\n if setting == \"algorithm_config\":\n if not isinstance(value, dict):\n raise ValueError(\"algorithm_config settings need to be dictionary\")\n self.search.algorithm_config.update(value)\n else:\n setattr(self.search, setting, value)", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 4568}, "tests/utils/test_image.py::28": {"resolved_imports": ["aizynthfinder/utils/__init__.py", "aizynthfinder/utils/image.py", "aizynthfinder/chem/__init__.py"], "used_names": ["TreeMolecule", "image", "os"], "enclosing_function": "test_save_molecule_images", "extracted_code": "# Source: aizynthfinder/chem/__init__.py\n Molecule,\n MoleculeException,\n TreeMolecule,\n UniqueMolecule,\n none_molecule,\n)\nfrom aizynthfinder.chem.reaction import (\n FixedRetroReaction,\n RetroReaction,\n SmilesBasedRetroReaction,\n TemplatedRetroReaction,\n hash_reactions,", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 299}, "tests/chem/test_reaction.py::239": {"resolved_imports": ["aizynthfinder/chem/__init__.py"], "used_names": ["TemplatedRetroReaction", "TreeMolecule"], "enclosing_function": "test_mapped_atom_bonds_rdkit", "extracted_code": "# Source: aizynthfinder/chem/__init__.py\n Molecule,\n MoleculeException,\n TreeMolecule,\n UniqueMolecule,\n none_molecule,\n)\nfrom aizynthfinder.chem.reaction import (\n FixedRetroReaction,\n RetroReaction,\n SmilesBasedRetroReaction,\n TemplatedRetroReaction,\n hash_reactions,\n\n RetroReaction,\n SmilesBasedRetroReaction,\n TemplatedRetroReaction,\n hash_reactions,\n)\nfrom aizynthfinder.chem.serialization import (\n MoleculeDeserializer,\n MoleculeSerializer,\n deserialize_action,\n serialize_action,\n)", "n_imports_parsed": 1, "n_files_resolved": 1, "n_chars_extracted": 544}, "tests/mcts/test_serialization.py::109": {"resolved_imports": ["aizynthfinder/chem/__init__.py", "aizynthfinder/chem/serialization.py", "aizynthfinder/search/mcts/__init__.py"], "used_names": ["MctsNode", "MoleculeDeserializer", "MoleculeSerializer"], "enclosing_function": "test_deserialize_node", "extracted_code": "# Source: aizynthfinder/chem/serialization.py\nclass MoleculeSerializer:\n \"\"\"\n Utility class for serializing molecules\n\n The id of the molecule to be serialized can be obtained with:\n\n .. code-block::\n\n serializer = MoleculeSerializer()\n mol = Molecule(smiles=\"CCCO\")\n idx = serializer[mol]\n\n which will take care of the serialization of the molecule.\n \"\"\"\n\n def __init__(self) -> None:\n self._store: Dict[int, Any] = {}\n\n def __getitem__(self, mol: Optional[aizynthfinder.chem.Molecule]) -> Optional[int]:\n if mol is None:\n return None\n\n id_ = id(mol)\n if id_ not in self._store:\n self._add_mol(mol)\n return id_\n\n @property\n def store(self) -> Dict[int, Any]:\n \"\"\"Return all serialized molecules as a dictionary\"\"\"\n return self._store\n\n def _add_mol(self, mol: aizynthfinder.chem.Molecule) -> None:\n id_ = id(mol)\n dict_ = {\"smiles\": mol.smiles, \"class\": mol.__class__.__name__}\n if isinstance(mol, aizynthfinder.chem.TreeMolecule):\n dict_[\"parent\"] = self[mol.parent]\n dict_[\"transform\"] = mol.transform\n if not mol.parent:\n dict_[\"smiles\"] = mol.original_smiles\n else:\n dict_[\"smiles\"] = mol.mapped_smiles\n self._store[id_] = dict_\n\nclass MoleculeDeserializer:\n \"\"\"\n Utility class for deserializing molecules.\n The serialized molecules are created upon instantiation of the class.\n\n The deserialized molecules can be obtained with:\n\n .. code-block::\n\n deserializer = MoleculeDeserializer()\n mol = deserializer[idx]\n\n \"\"\"\n\n def __init__(self, store: Dict[int, Any]) -> None:\n self._objects: Dict[int, Any] = {}\n self._create_molecules(store)\n\n def __getitem__(self, id_: Optional[int]) -> Optional[aizynthfinder.chem.Molecule]:\n if id_ is None:\n return None\n return self._objects[id_]\n\n def get_tree_molecules(\n self, ids: Sequence[int]\n ) -> Sequence[aizynthfinder.chem.TreeMolecule]:\n \"\"\"\n Return multiple deserialized tree molecules\n\n :param ids: the list of IDs to deserialize\n :return: the molecule objects\n \"\"\"\n objects = []\n for id_ in ids:\n obj = self[id_]\n if obj is None or not isinstance(obj, aizynthfinder.chem.TreeMolecule):\n raise ValueError(f\"Failed to deserialize molecule with id {id_}\")\n objects.append(obj)\n return objects\n\n def _create_molecules(self, store: dict) -> None:\n for id_, spec in store.items():\n if isinstance(id_, str):\n id_ = int(id_)\n\n cls = spec[\"class\"]\n if \"parent\" in spec:\n spec[\"parent\"] = self[spec[\"parent\"]]\n\n kwargs = dict(spec)\n del kwargs[\"class\"]\n self._objects[id_] = getattr(aizynthfinder.chem, cls)(**kwargs)\n\n\n# Source: aizynthfinder/search/mcts/__init__.py\n\"\"\" Sub-package containing MCTS routines\n\"\"\"\nfrom aizynthfinder.search.mcts.node import MctsNode\nfrom aizynthfinder.search.mcts.search import MctsSearchTree\nfrom aizynthfinder.search.mcts.state import MctsState", "n_imports_parsed": 3, "n_files_resolved": 3, "n_chars_extracted": 3248}, "tests/context/test_stock.py::489": {"resolved_imports": ["aizynthfinder/chem/__init__.py", "aizynthfinder/context/stock/__init__.py", "aizynthfinder/context/stock/queries.py", "aizynthfinder/tools/make_stock.py"], "used_names": ["extract_smiles_from_module", "sys"], "enclosing_function": "test_extract_smiles_from_module", "extracted_code": "# Source: aizynthfinder/tools/make_stock.py\ndef extract_smiles_from_module(files: List[str]) -> _StrIterator:\n \"\"\"\n Extract SMILES by loading a custom module, containing\n the function ``extract_smiles``.\n\n The first element of the input argument is taken as the module name.\n The other elements are taken as input to the ``extract_smiles`` method\n\n The SMILES are yielded to save memory.\n \"\"\"\n module_name = files.pop(0)\n module = importlib.import_module(module_name)\n if not files:\n for smiles in module.extract_smiles(): # type: ignore # pylint: disable=R1737\n yield smiles\n else:\n for filename in files:\n print(f\"Processing {filename}\", flush=True)\n for smiles in module.extract_smiles(filename): # type: ignore # pylint: disable=R1737\n yield smiles", "n_imports_parsed": 7, "n_files_resolved": 4, "n_chars_extracted": 851}, "tests/mcts/test_tree.py::15": {"resolved_imports": [], "used_names": [], "enclosing_function": "test_select_leaf", "extracted_code": "", "n_imports_parsed": 0, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/retrostar/test_retrostar_nodes.py::109": {"resolved_imports": ["aizynthfinder/search/retrostar/nodes.py", "aizynthfinder/chem/serialization.py", "aizynthfinder/search/andor_trees.py"], "used_names": ["MoleculeDeserializer", "MoleculeNode", "MoleculeSerializer"], "enclosing_function": "test_serialization_deserialization", "extracted_code": "# Source: aizynthfinder/search/retrostar/nodes.py\nclass MoleculeNode(TreeNodeMixin):\n \"\"\"\n An OR node representing a molecule\n\n :ivar cost: the cost of synthesizing the molecule\n :ivar expandable: if True, this node is part of the frontier\n :ivar mol: the molecule represented by the node\n :ivar in_stock: if True the molecule is in stock and hence should not be expanded\n :ivar parent: the parent of the node\n :ivar solved: if True the molecule is in stock or at least one child node is solved\n :ivar value: the current rn(m|T)\n\n :param mol: the molecule to be represented by the node\n :param config: the configuration of the search\n :param parent: the parent of the node, optional\n \"\"\"\n\n def __init__(\n self,\n mol: TreeMolecule,\n config: Configuration,\n molecule_cost: MoleculeCost,\n parent: Optional[ReactionNode] = None,\n ) -> None:\n self.mol = mol\n self._config = config\n self.molecule_cost = molecule_cost\n self.cost = self.molecule_cost(mol)\n self.value = self.cost\n self.in_stock = mol in config.stock\n self.parent = parent\n\n self._children: List[ReactionNode] = []\n self.solved = self.in_stock\n # Makes it unexpandable if we have reached maximum depth\n self.expandable = self.mol.transform < self._config.search.max_transforms\n\n if self.in_stock:\n self.expandable = False\n self.value = 0\n\n @classmethod\n def create_root(\n cls, smiles: str, config: Configuration, molecule_cost: MoleculeCost\n ) -> \"MoleculeNode\":\n \"\"\"\n Create a root node for a tree using a SMILES.\n\n :param smiles: the SMILES representation of the root state\n :param config: settings of the tree search algorithm\n :return: the created node\n \"\"\"\n mol = TreeMolecule(parent=None, transform=0, smiles=smiles)\n return MoleculeNode(mol=mol, config=config, molecule_cost=molecule_cost)\n\n @classmethod\n def from_dict(\n cls,\n dict_: StrDict,\n config: Configuration,\n molecules: MoleculeDeserializer,\n molecule_cost: MoleculeCost,\n parent: Optional[ReactionNode] = None,\n ) -> \"MoleculeNode\":\n \"\"\"\n Create a new node from a dictionary, i.e. deserialization\n\n :param dict_: the serialized node\n :param config: settings of the tree search algorithm\n :param molecules: the deserialized molecules\n :param parent: the parent node\n :return: a deserialized node\n \"\"\"\n mol = molecules.get_tree_molecules([dict_[\"mol\"]])[0]\n node = MoleculeNode(mol, config, molecule_cost, parent)\n node.molecule_cost = molecule_cost\n for attr in [\"cost\", \"expandable\", \"value\"]:\n setattr(node, attr, dict_[attr])\n node.children = [\n ReactionNode.from_dict(\n child, config, molecules, node.molecule_cost, parent=node\n )\n for child in dict_[\"children\"]\n ]\n return node\n\n @property # type: ignore\n def children(self) -> List[ReactionNode]: # type: ignore\n \"\"\"Gives the reaction children nodes\"\"\"\n return self._children\n\n @children.setter\n def children(self, value: List[ReactionNode]) -> None:\n self._children = value\n\n @property\n def target_value(self) -> float:\n \"\"\"\n The V_t(m|T) value,\n the current cost of the tree containing this node\n\n :return: the value\n \"\"\"\n if self.parent:\n return self.parent.target_value\n return self.value\n\n @property\n def prop(self) -> StrDict:\n return {\"solved\": self.solved, \"mol\": self.mol}\n\n def add_stub(self, cost: float, reaction: RetroReaction) -> Sequence[MoleculeNode]:\n \"\"\"\n Add a stub / sub-tree to this node\n\n :param cost: the cost of the reaction\n :param reaction: the reaction creating the stub\n :return: list of all newly added molecular nodes\n \"\"\"\n reactants = reaction.reactants[reaction.index]\n if not reactants:\n return []\n\n ancestors = self.ancestors()\n for mol in reactants:\n if mol in ancestors:\n return []\n\n rxn_node = ReactionNode.create_stub(\n cost=cost,\n reaction=reaction,\n parent=self,\n config=self._config,\n )\n self._children.append(rxn_node)\n\n return rxn_node.children\n\n def ancestors(self) -> Set[TreeMolecule]:\n \"\"\"\n Return the ancestors of this node\n\n :return: the ancestors\n :rtype: set\n \"\"\"\n if not self.parent:\n return {self.mol}\n\n ancestors = self.parent.parent.ancestors()\n ancestors.add(self.mol)\n return ancestors\n\n def close(self) -> float:\n \"\"\"\n Updates the values of this node after expanding it.\n\n :return: the delta V value\n :rtype: float\n \"\"\"\n self.solved = any(child.solved for child in self.children)\n if self.children:\n new_value = np.min([child.value for child in self.children])\n else:\n new_value = np.inf\n\n v_delta = new_value - self.value\n self.value = new_value\n\n self.expandable = False\n return v_delta\n\n def serialize(self, molecule_store: MoleculeSerializer) -> StrDict:\n \"\"\"\n Serialize the node object to a dictionary\n\n :param molecule_store: the serialized molecules\n :return: the serialized node\n \"\"\"\n dict_ = {attr: getattr(self, attr) for attr in [\"cost\", \"expandable\", \"value\"]}\n dict_[\"mol\"] = molecule_store[self.mol]\n dict_[\"children\"] = [child.serialize(molecule_store) for child in self.children]\n return dict_\n\n def update(self, solved: bool) -> None:\n \"\"\"\n Update the node as part of the update algorithm,\n calling the `update()` method of its parent if available.\n\n :param solved: if the child node was solved\n \"\"\"\n new_value = np.min([child.value for child in self.children])\n new_solv = self.solved or solved\n updated = (self.value != new_value) or (self.solved != new_solv)\n\n v_delta = new_value - self.value\n self.value = new_value\n self.solved = new_solv\n\n if updated and self.parent:\n self.parent.update(v_delta, from_mol=self.mol)\n\n\n# Source: aizynthfinder/chem/serialization.py\nclass MoleculeSerializer:\n \"\"\"\n Utility class for serializing molecules\n\n The id of the molecule to be serialized can be obtained with:\n\n .. code-block::\n\n serializer = MoleculeSerializer()\n mol = Molecule(smiles=\"CCCO\")\n idx = serializer[mol]\n\n which will take care of the serialization of the molecule.\n \"\"\"\n\n def __init__(self) -> None:\n self._store: Dict[int, Any] = {}\n\n def __getitem__(self, mol: Optional[aizynthfinder.chem.Molecule]) -> Optional[int]:\n if mol is None:\n return None\n\n id_ = id(mol)\n if id_ not in self._store:\n self._add_mol(mol)\n return id_\n\n @property\n def store(self) -> Dict[int, Any]:\n \"\"\"Return all serialized molecules as a dictionary\"\"\"\n return self._store\n\n def _add_mol(self, mol: aizynthfinder.chem.Molecule) -> None:\n id_ = id(mol)\n dict_ = {\"smiles\": mol.smiles, \"class\": mol.__class__.__name__}\n if isinstance(mol, aizynthfinder.chem.TreeMolecule):\n dict_[\"parent\"] = self[mol.parent]\n dict_[\"transform\"] = mol.transform\n if not mol.parent:\n dict_[\"smiles\"] = mol.original_smiles\n else:\n dict_[\"smiles\"] = mol.mapped_smiles\n self._store[id_] = dict_\n\nclass MoleculeDeserializer:\n \"\"\"\n Utility class for deserializing molecules.\n The serialized molecules are created upon instantiation of the class.\n\n The deserialized molecules can be obtained with:\n\n .. code-block::\n\n deserializer = MoleculeDeserializer()\n mol = deserializer[idx]\n\n \"\"\"\n\n def __init__(self, store: Dict[int, Any]) -> None:\n self._objects: Dict[int, Any] = {}\n self._create_molecules(store)\n\n def __getitem__(self, id_: Optional[int]) -> Optional[aizynthfinder.chem.Molecule]:\n if id_ is None:\n return None\n return self._objects[id_]\n\n def get_tree_molecules(\n self, ids: Sequence[int]\n ) -> Sequence[aizynthfinder.chem.TreeMolecule]:\n \"\"\"\n Return multiple deserialized tree molecules\n\n :param ids: the list of IDs to deserialize\n :return: the molecule objects\n \"\"\"\n objects = []\n for id_ in ids:\n obj = self[id_]\n if obj is None or not isinstance(obj, aizynthfinder.chem.TreeMolecule):\n raise ValueError(f\"Failed to deserialize molecule with id {id_}\")\n objects.append(obj)\n return objects\n\n def _create_molecules(self, store: dict) -> None:\n for id_, spec in store.items():\n if isinstance(id_, str):\n id_ = int(id_)\n\n cls = spec[\"class\"]\n if \"parent\" in spec:\n spec[\"parent\"] = self[spec[\"parent\"]]\n\n kwargs = dict(spec)\n del kwargs[\"class\"]\n self._objects[id_] = getattr(aizynthfinder.chem, cls)(**kwargs)", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 9488}, "tests/chem/test_serialization.py::70": {"resolved_imports": ["aizynthfinder/chem/serialization.py", "aizynthfinder/chem/__init__.py"], "used_names": ["MoleculeDeserializer"], "enclosing_function": "test_deserialize_tree_mols", "extracted_code": "# Source: aizynthfinder/chem/serialization.py\nclass MoleculeDeserializer:\n \"\"\"\n Utility class for deserializing molecules.\n The serialized molecules are created upon instantiation of the class.\n\n The deserialized molecules can be obtained with:\n\n .. code-block::\n\n deserializer = MoleculeDeserializer()\n mol = deserializer[idx]\n\n \"\"\"\n\n def __init__(self, store: Dict[int, Any]) -> None:\n self._objects: Dict[int, Any] = {}\n self._create_molecules(store)\n\n def __getitem__(self, id_: Optional[int]) -> Optional[aizynthfinder.chem.Molecule]:\n if id_ is None:\n return None\n return self._objects[id_]\n\n def get_tree_molecules(\n self, ids: Sequence[int]\n ) -> Sequence[aizynthfinder.chem.TreeMolecule]:\n \"\"\"\n Return multiple deserialized tree molecules\n\n :param ids: the list of IDs to deserialize\n :return: the molecule objects\n \"\"\"\n objects = []\n for id_ in ids:\n obj = self[id_]\n if obj is None or not isinstance(obj, aizynthfinder.chem.TreeMolecule):\n raise ValueError(f\"Failed to deserialize molecule with id {id_}\")\n objects.append(obj)\n return objects\n\n def _create_molecules(self, store: dict) -> None:\n for id_, spec in store.items():\n if isinstance(id_, str):\n id_ = int(id_)\n\n cls = spec[\"class\"]\n if \"parent\" in spec:\n spec[\"parent\"] = self[spec[\"parent\"]]\n\n kwargs = dict(spec)\n del kwargs[\"class\"]\n self._objects[id_] = getattr(aizynthfinder.chem, cls)(**kwargs)", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 1671}, "tests/mcts/test_multiobjective.py::87": {"resolved_imports": ["aizynthfinder/search/mcts/node.py", "aizynthfinder/search/mcts/__init__.py"], "used_names": ["MctsSearchTree"], "enclosing_function": "test_setup_weighted_sum_tree", "extracted_code": "# Source: aizynthfinder/search/mcts/__init__.py\n\"\"\"\nfrom aizynthfinder.search.mcts.node import MctsNode\nfrom aizynthfinder.search.mcts.search import MctsSearchTree\nfrom aizynthfinder.search.mcts.state import MctsState", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 217}, "tests/test_cli.py::430": {"resolved_imports": ["aizynthfinder/analysis/__init__.py", "aizynthfinder/chem/__init__.py", "aizynthfinder/interfaces/__init__.py", "aizynthfinder/interfaces/aizynthapp.py", "aizynthfinder/interfaces/aizynthcli.py", "aizynthfinder/reactiontree.py", "aizynthfinder/tools/cat_output.py", "aizynthfinder/tools/download_public_data.py", "aizynthfinder/tools/make_stock.py"], "used_names": ["glob", "os", "yaml"], "enclosing_function": "test_download_public_data", "extracted_code": "", "n_imports_parsed": 17, "n_files_resolved": 9, "n_chars_extracted": 0}, "tests/utils/test_file_utils.py::126": {"resolved_imports": ["aizynthfinder/utils/files.py"], "used_names": ["cat_datafiles", "gzip", "json", "os"], "enclosing_function": "test_cat_hdf_trees", "extracted_code": "# Source: aizynthfinder/utils/files.py\ndef cat_datafiles(\n input_files: List[str], output_name: str, trees_name: Optional[str] = None\n) -> None:\n \"\"\"\n Concatenate hdf5 or json datafiles\n\n if `tree_name` is given, will take out the `trees` column\n from the tables and save it to a gzipped-json file.\n\n :param input_files: the paths to the files to concatenate\n :param output_name: the name of the concatenated file\n :param trees_name: the name of the concatenated trees\n \"\"\"\n data = read_datafile(input_files[0])\n if \"trees\" not in data.columns:\n trees_name = None\n\n if trees_name:\n columns = list(data.columns)\n columns.remove(\"trees\")\n trees = list(data[\"trees\"].values)\n data = data[columns]\n\n for filename in input_files[1:]:\n new_data = read_datafile(filename)\n if trees_name:\n trees.extend(new_data[\"trees\"].values)\n new_data = new_data[columns]\n data = pd.concat([data, new_data])\n\n save_datafile(data.reset_index(drop=True), output_name)\n if trees_name:\n if not trees_name.endswith(\".gz\"):\n trees_name += \".gz\"\n with gzip.open(trees_name, \"wt\", encoding=\"UTF-8\") as fileobj:\n json.dump(trees, fileobj)", "n_imports_parsed": 6, "n_files_resolved": 1, "n_chars_extracted": 1267}, "tests/utils/test_file_utils.py::61": {"resolved_imports": ["aizynthfinder/utils/files.py"], "used_names": ["os", "split_file"], "enclosing_function": "test_split_file_odd", "extracted_code": "# Source: aizynthfinder/utils/files.py\ndef split_file(filename: str, nparts: int) -> List[str]:\n \"\"\"\n Split the content of a text file into a given number of temporary files\n\n :param filename: the path to the file to split\n :param nparts: the number of parts to create\n :return: list of filenames of the parts\n \"\"\"\n with open(filename, \"r\") as fileobj:\n lines = fileobj.read().splitlines()\n\n filenames = []\n batch_size, remainder = divmod(len(lines), nparts)\n stop = 0\n for part in range(1, nparts + 1):\n start = stop\n stop += batch_size + 1 if part <= remainder else batch_size\n filenames.append(tempfile.mktemp())\n with open(filenames[-1], \"w\") as fileobj:\n fileobj.write(\"\\n\".join(lines[start:stop]))\n return filenames", "n_imports_parsed": 6, "n_files_resolved": 1, "n_chars_extracted": 803}, "tests/test_analysis.py::33": {"resolved_imports": ["aizynthfinder/analysis/__init__.py", "aizynthfinder/analysis/routes.py", "aizynthfinder/analysis/utils.py", "aizynthfinder/reactiontree.py", "aizynthfinder/search/mcts/__init__.py", "aizynthfinder/context/scoring/__init__.py"], "used_names": ["RouteSelectionArguments"], "enclosing_function": "test_sort_nodes_multiobjective", "extracted_code": "# Source: aizynthfinder/analysis/utils.py\nclass RouteSelectionArguments:\n \"\"\"\n Selection arguments for the tree analysis class\n\n If `return_all` is False, it will return at least `nmin` routes and if routes have the same\n score it will return them as well up to `nmax` routes.\n\n If `return_all` is True, it will return all solved routes if there is at least one is solved, otherwise\n the `nmin` and `nmax` will be used.\n \"\"\"\n\n nmin: int = 5\n nmax: int = 25\n return_all: bool = False", "n_imports_parsed": 10, "n_files_resolved": 6, "n_chars_extracted": 512}, "tests/test_reactiontree.py::186": {"resolved_imports": ["aizynthfinder/reactiontree.py"], "used_names": ["ReactionTree"], "enclosing_function": "test_reactiontree_child_reactions", "extracted_code": "# Source: aizynthfinder/reactiontree.py\nclass ReactionTree:\n \"\"\"\n Encapsulation of a bipartite reaction tree of a single route.\n The nodes consists of either FixedRetroReaction or UniqueMolecule objects.\n\n The reaction tree is initialized at instantiation and is not supposed to\n be updated.\n\n :ivar graph: the bipartite graph\n :ivar is_solved: if all of the leaf nodes are in stock\n :ivar root: the root of the tree\n :ivar created_at_iteration: iteration the reaction tree was created\n \"\"\"\n\n def __init__(self) -> None:\n self.graph = nx.DiGraph()\n self.root = none_molecule()\n self.is_solved: bool = False\n self.created_at_iteration: Optional[int] = None\n\n @classmethod\n def from_dict(cls, tree_dict: StrDict) -> \"ReactionTree\":\n \"\"\"\n Create a new ReactionTree by parsing a dictionary.\n\n This is supposed to be the opposite of ``to_dict``,\n but because that format loses information, the returned\n object is not a full copy as the stock will only contain\n the list of molecules marked as ``in_stock`` in the dictionary.\n\n The returned object should be sufficient to e.g. generate an image of the route.\n\n :param tree_dict: the dictionary representation\n :returns: the reaction tree\n \"\"\"\n return ReactionTreeFromDict(tree_dict).tree\n\n @property\n def metadata(self) -> StrDict:\n \"\"\"Return a dicitionary with route metadata\"\"\"\n return {\n \"created_at_iteration\": self.created_at_iteration,\n \"is_solved\": self.is_solved,\n }\n\n def child_reactions(self, reaction: FixedRetroReaction) -> List[FixedRetroReaction]:\n \"\"\"\n Return the child reactions of a reaction node in the tree.\n\n :param reaction: the query node (reaction)\n :return: child reactions\n \"\"\"\n child_molecule_nodes = self.graph.successors(reaction)\n reaction_nodes = []\n for molecule_node in child_molecule_nodes:\n reaction_nodes.extend(list(self.graph.successors(molecule_node)))\n return reaction_nodes\n\n def depth(self, node: Union[UniqueMolecule, FixedRetroReaction]) -> int:\n \"\"\"\n Return the depth of a node in the route\n\n :param node: the query node\n :return: the depth\n \"\"\"\n return self.graph.nodes[node].get(\"depth\", -1)\n\n def distance_to(self, other: \"ReactionTree\") -> float:\n \"\"\"\n Calculate the distance to another reaction tree\n\n This is a simple distance based on a route similarity\n\n :param other: the reaction tree to compare to\n :return: the distance between the routes\n \"\"\"\n route1 = read_aizynthfinder_dict(self.to_dict())\n route2 = read_aizynthfinder_dict(other.to_dict())\n return 1.0 - float(simple_route_similarity([route1, route2])[0, 1])\n\n def hash_key(self) -> str:\n \"\"\"\n Calculates a hash code for the tree using the sha224 hash function recursively\n\n :return: the hash key\n \"\"\"\n return self._hash_func(self.root)\n\n def in_stock(self, node: Union[UniqueMolecule, FixedRetroReaction]) -> bool:\n \"\"\"\n Return if a node in the route is in stock\n\n Note that is a property set on creation and as such is not updated.\n\n :param node: the query node\n :return: if the molecule is in stock\n \"\"\"\n return self.graph.nodes[node].get(\"in_stock\", False)\n\n def is_branched(self) -> bool:\n \"\"\"\n Returns if the route is branched\n\n i.e. checks if the maximum depth is not equal to the number\n of reactions.\n \"\"\"\n nsteps = len(list(self.reactions()))\n max_depth = max(self.depth(leaf) for leaf in self.leafs())\n return nsteps != max_depth // 2\n\n def leafs(self) -> Iterable[UniqueMolecule]:\n \"\"\"\n Generates the molecules nodes of the reaction tree that has no predecessors,\n i.e. molecules that has not been broken down\n\n :yield: the next leaf molecule in the tree\n \"\"\"\n for node in self.graph:\n if isinstance(node, UniqueMolecule) and not self.graph[node]:\n yield node\n\n def molecules(self) -> Iterable[UniqueMolecule]:\n \"\"\"\n Generates the molecule nodes of the reaction tree\n\n :yield: the next molecule in the tree\n \"\"\"\n for node in self.graph:\n if isinstance(node, UniqueMolecule):\n yield node\n\n def parent_molecule(self, mol: UniqueMolecule) -> UniqueMolecule:\n \"\"\"Returns the parent molecule within the reaction tree.\n :param mol: the query node (molecule)\n :return: the parent molecule\n \"\"\"\n if mol is self.root:\n raise ValueError(\"Root molecule does not have any parent node.\")\n\n parent_reaction = list(self.graph.predecessors(mol))[0]\n parent_molecule = list(self.graph.predecessors(parent_reaction))[0]\n return parent_molecule\n\n def reactions(self) -> Iterable[FixedRetroReaction]:\n \"\"\"\n Generates the reaction nodes of the reaction tree\n\n :yield: the next reaction in the tree\n \"\"\"\n for node in self.graph:\n if not isinstance(node, Molecule):\n yield node\n\n def subtrees(self) -> Iterable[ReactionTree]:\n \"\"\"\n Generates the subtrees of this reaction tree a\n subtree is a reaction treee starting at a molecule node that has children.\n\n :yield: the next subtree\n \"\"\"\n\n def create_subtree(root_node):\n subtree = ReactionTree()\n subtree.root = root_node\n subtree.graph = dfs_tree(self.graph, root_node)\n for node in subtree.graph:\n prop = dict(self.graph.nodes[node])\n prop[\"depth\"] -= self.graph.nodes[root_node].get(\"depth\", 0)\n if \"transform\" in prop:\n prop[\"transform\"] -= self.graph.nodes[root_node].get(\"transform\", 0)\n subtree.graph.nodes[node].update(prop)\n subtree.is_solved = all(subtree.in_stock(node) for node in subtree.leafs())\n return subtree\n\n for node in self.molecules():\n if node is not self.root and self.graph[node]:\n yield create_subtree(node)\n\n def to_dict(self, include_metadata=False) -> StrDict:\n \"\"\"\n Returns the reaction tree as a dictionary in a pre-defined format.\n :param include_metadata: if True include metadata\n :return: the reaction tree\n \"\"\"\n return self._build_dict(self.root, include_metadata=include_metadata)\n\n def to_image(\n self,\n in_stock_colors: Optional[FrameColors] = None,\n show_all: bool = True,\n ) -> PilImage:\n \"\"\"\n Return a pictorial representation of the route\n\n :param in_stock_colors: the colors around molecules, defaults to {True: \"green\", False: \"orange\"}\n :param show_all: if True, also show nodes that are marked as hidden\n :return: the image of the route\n \"\"\"\n factory = RouteImageFactory(\n self.to_dict(), in_stock_colors=in_stock_colors, show_all=show_all\n )\n return factory.image\n\n def to_json(self, include_metadata=False) -> str:\n \"\"\"\n Returns the reaction tree as a JSON string in a pre-defined format.\n\n :return: the reaction tree\n \"\"\"\n return json.dumps(\n self.to_dict(include_metadata=include_metadata), sort_keys=False, indent=2\n )\n\n def _build_dict(\n self,\n node: Union[UniqueMolecule, FixedRetroReaction],\n dict_: Optional[StrDict] = None,\n include_metadata=False,\n ) -> StrDict:\n if dict_ is None:\n dict_ = {}\n\n if node is self.root and include_metadata:\n dict_[\"route_metadata\"] = self.metadata\n\n dict_[\"type\"] = \"mol\" if isinstance(node, Molecule) else \"reaction\"\n dict_[\"hide\"] = self.graph.nodes[node].get(\"hide\", False)\n dict_[\"smiles\"] = node.smiles\n if isinstance(node, UniqueMolecule):\n dict_[\"is_chemical\"] = True\n dict_[\"in_stock\"] = self.in_stock(node)\n elif isinstance(node, FixedRetroReaction):\n dict_[\"is_reaction\"] = True\n dict_[\"metadata\"] = dict(node.metadata)\n else:\n raise ValueError(\n f\"This is an invalid reaction tree. Unknown node type {type(node)}\"\n )\n\n dict_[\"children\"] = []\n\n children = list(self.graph.successors(node))\n if isinstance(node, FixedRetroReaction):\n children.sort(key=operator.attrgetter(\"weight\"))\n for child in children:\n child_dict = self._build_dict(child)\n dict_[\"children\"].append(child_dict)\n\n if not dict_[\"children\"]:\n del dict_[\"children\"]\n return dict_\n\n def _hash_func(self, node: Union[FixedRetroReaction, UniqueMolecule]) -> str:\n if isinstance(node, UniqueMolecule):\n hash_ = hashlib.sha224(node.inchi_key.encode())\n else:\n hash_ = hashlib.sha224(node.hash_key().encode())\n child_hashes = sorted(\n self._hash_func(child) for child in self.graph.successors(node)\n )\n for child_hash in child_hashes:\n hash_.update(child_hash.encode())\n return hash_.hexdigest()", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 9443}, "tests/test_finder.py::134": {"resolved_imports": ["aizynthfinder/aizynthfinder.py"], "used_names": [], "enclosing_function": "test_non_broken_frozen_bond_filter", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/retrostar/test_retrostar_nodes.py::115": {"resolved_imports": ["aizynthfinder/search/retrostar/nodes.py", "aizynthfinder/chem/serialization.py", "aizynthfinder/search/andor_trees.py"], "used_names": ["MoleculeDeserializer", "MoleculeNode", "MoleculeSerializer"], "enclosing_function": "test_serialization_deserialization", "extracted_code": "# Source: aizynthfinder/search/retrostar/nodes.py\nclass MoleculeNode(TreeNodeMixin):\n \"\"\"\n An OR node representing a molecule\n\n :ivar cost: the cost of synthesizing the molecule\n :ivar expandable: if True, this node is part of the frontier\n :ivar mol: the molecule represented by the node\n :ivar in_stock: if True the molecule is in stock and hence should not be expanded\n :ivar parent: the parent of the node\n :ivar solved: if True the molecule is in stock or at least one child node is solved\n :ivar value: the current rn(m|T)\n\n :param mol: the molecule to be represented by the node\n :param config: the configuration of the search\n :param parent: the parent of the node, optional\n \"\"\"\n\n def __init__(\n self,\n mol: TreeMolecule,\n config: Configuration,\n molecule_cost: MoleculeCost,\n parent: Optional[ReactionNode] = None,\n ) -> None:\n self.mol = mol\n self._config = config\n self.molecule_cost = molecule_cost\n self.cost = self.molecule_cost(mol)\n self.value = self.cost\n self.in_stock = mol in config.stock\n self.parent = parent\n\n self._children: List[ReactionNode] = []\n self.solved = self.in_stock\n # Makes it unexpandable if we have reached maximum depth\n self.expandable = self.mol.transform < self._config.search.max_transforms\n\n if self.in_stock:\n self.expandable = False\n self.value = 0\n\n @classmethod\n def create_root(\n cls, smiles: str, config: Configuration, molecule_cost: MoleculeCost\n ) -> \"MoleculeNode\":\n \"\"\"\n Create a root node for a tree using a SMILES.\n\n :param smiles: the SMILES representation of the root state\n :param config: settings of the tree search algorithm\n :return: the created node\n \"\"\"\n mol = TreeMolecule(parent=None, transform=0, smiles=smiles)\n return MoleculeNode(mol=mol, config=config, molecule_cost=molecule_cost)\n\n @classmethod\n def from_dict(\n cls,\n dict_: StrDict,\n config: Configuration,\n molecules: MoleculeDeserializer,\n molecule_cost: MoleculeCost,\n parent: Optional[ReactionNode] = None,\n ) -> \"MoleculeNode\":\n \"\"\"\n Create a new node from a dictionary, i.e. deserialization\n\n :param dict_: the serialized node\n :param config: settings of the tree search algorithm\n :param molecules: the deserialized molecules\n :param parent: the parent node\n :return: a deserialized node\n \"\"\"\n mol = molecules.get_tree_molecules([dict_[\"mol\"]])[0]\n node = MoleculeNode(mol, config, molecule_cost, parent)\n node.molecule_cost = molecule_cost\n for attr in [\"cost\", \"expandable\", \"value\"]:\n setattr(node, attr, dict_[attr])\n node.children = [\n ReactionNode.from_dict(\n child, config, molecules, node.molecule_cost, parent=node\n )\n for child in dict_[\"children\"]\n ]\n return node\n\n @property # type: ignore\n def children(self) -> List[ReactionNode]: # type: ignore\n \"\"\"Gives the reaction children nodes\"\"\"\n return self._children\n\n @children.setter\n def children(self, value: List[ReactionNode]) -> None:\n self._children = value\n\n @property\n def target_value(self) -> float:\n \"\"\"\n The V_t(m|T) value,\n the current cost of the tree containing this node\n\n :return: the value\n \"\"\"\n if self.parent:\n return self.parent.target_value\n return self.value\n\n @property\n def prop(self) -> StrDict:\n return {\"solved\": self.solved, \"mol\": self.mol}\n\n def add_stub(self, cost: float, reaction: RetroReaction) -> Sequence[MoleculeNode]:\n \"\"\"\n Add a stub / sub-tree to this node\n\n :param cost: the cost of the reaction\n :param reaction: the reaction creating the stub\n :return: list of all newly added molecular nodes\n \"\"\"\n reactants = reaction.reactants[reaction.index]\n if not reactants:\n return []\n\n ancestors = self.ancestors()\n for mol in reactants:\n if mol in ancestors:\n return []\n\n rxn_node = ReactionNode.create_stub(\n cost=cost,\n reaction=reaction,\n parent=self,\n config=self._config,\n )\n self._children.append(rxn_node)\n\n return rxn_node.children\n\n def ancestors(self) -> Set[TreeMolecule]:\n \"\"\"\n Return the ancestors of this node\n\n :return: the ancestors\n :rtype: set\n \"\"\"\n if not self.parent:\n return {self.mol}\n\n ancestors = self.parent.parent.ancestors()\n ancestors.add(self.mol)\n return ancestors\n\n def close(self) -> float:\n \"\"\"\n Updates the values of this node after expanding it.\n\n :return: the delta V value\n :rtype: float\n \"\"\"\n self.solved = any(child.solved for child in self.children)\n if self.children:\n new_value = np.min([child.value for child in self.children])\n else:\n new_value = np.inf\n\n v_delta = new_value - self.value\n self.value = new_value\n\n self.expandable = False\n return v_delta\n\n def serialize(self, molecule_store: MoleculeSerializer) -> StrDict:\n \"\"\"\n Serialize the node object to a dictionary\n\n :param molecule_store: the serialized molecules\n :return: the serialized node\n \"\"\"\n dict_ = {attr: getattr(self, attr) for attr in [\"cost\", \"expandable\", \"value\"]}\n dict_[\"mol\"] = molecule_store[self.mol]\n dict_[\"children\"] = [child.serialize(molecule_store) for child in self.children]\n return dict_\n\n def update(self, solved: bool) -> None:\n \"\"\"\n Update the node as part of the update algorithm,\n calling the `update()` method of its parent if available.\n\n :param solved: if the child node was solved\n \"\"\"\n new_value = np.min([child.value for child in self.children])\n new_solv = self.solved or solved\n updated = (self.value != new_value) or (self.solved != new_solv)\n\n v_delta = new_value - self.value\n self.value = new_value\n self.solved = new_solv\n\n if updated and self.parent:\n self.parent.update(v_delta, from_mol=self.mol)\n\n\n# Source: aizynthfinder/chem/serialization.py\nclass MoleculeSerializer:\n \"\"\"\n Utility class for serializing molecules\n\n The id of the molecule to be serialized can be obtained with:\n\n .. code-block::\n\n serializer = MoleculeSerializer()\n mol = Molecule(smiles=\"CCCO\")\n idx = serializer[mol]\n\n which will take care of the serialization of the molecule.\n \"\"\"\n\n def __init__(self) -> None:\n self._store: Dict[int, Any] = {}\n\n def __getitem__(self, mol: Optional[aizynthfinder.chem.Molecule]) -> Optional[int]:\n if mol is None:\n return None\n\n id_ = id(mol)\n if id_ not in self._store:\n self._add_mol(mol)\n return id_\n\n @property\n def store(self) -> Dict[int, Any]:\n \"\"\"Return all serialized molecules as a dictionary\"\"\"\n return self._store\n\n def _add_mol(self, mol: aizynthfinder.chem.Molecule) -> None:\n id_ = id(mol)\n dict_ = {\"smiles\": mol.smiles, \"class\": mol.__class__.__name__}\n if isinstance(mol, aizynthfinder.chem.TreeMolecule):\n dict_[\"parent\"] = self[mol.parent]\n dict_[\"transform\"] = mol.transform\n if not mol.parent:\n dict_[\"smiles\"] = mol.original_smiles\n else:\n dict_[\"smiles\"] = mol.mapped_smiles\n self._store[id_] = dict_\n\nclass MoleculeDeserializer:\n \"\"\"\n Utility class for deserializing molecules.\n The serialized molecules are created upon instantiation of the class.\n\n The deserialized molecules can be obtained with:\n\n .. code-block::\n\n deserializer = MoleculeDeserializer()\n mol = deserializer[idx]\n\n \"\"\"\n\n def __init__(self, store: Dict[int, Any]) -> None:\n self._objects: Dict[int, Any] = {}\n self._create_molecules(store)\n\n def __getitem__(self, id_: Optional[int]) -> Optional[aizynthfinder.chem.Molecule]:\n if id_ is None:\n return None\n return self._objects[id_]\n\n def get_tree_molecules(\n self, ids: Sequence[int]\n ) -> Sequence[aizynthfinder.chem.TreeMolecule]:\n \"\"\"\n Return multiple deserialized tree molecules\n\n :param ids: the list of IDs to deserialize\n :return: the molecule objects\n \"\"\"\n objects = []\n for id_ in ids:\n obj = self[id_]\n if obj is None or not isinstance(obj, aizynthfinder.chem.TreeMolecule):\n raise ValueError(f\"Failed to deserialize molecule with id {id_}\")\n objects.append(obj)\n return objects\n\n def _create_molecules(self, store: dict) -> None:\n for id_, spec in store.items():\n if isinstance(id_, str):\n id_ = int(id_)\n\n cls = spec[\"class\"]\n if \"parent\" in spec:\n spec[\"parent\"] = self[spec[\"parent\"]]\n\n kwargs = dict(spec)\n del kwargs[\"class\"]\n self._objects[id_] = getattr(aizynthfinder.chem, cls)(**kwargs)", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 9488}, "tests/test_expander.py::11": {"resolved_imports": ["aizynthfinder/aizynthfinder.py"], "used_names": ["AiZynthExpander"], "enclosing_function": "test_expander_defaults", "extracted_code": "# Source: aizynthfinder/aizynthfinder.py\nclass AiZynthExpander:\n \"\"\"\n Public API to the AiZynthFinder expansion and filter policies\n\n If instantiated with the path to a yaml file or dictionary of settings\n the stocks and policy networks are loaded directly.\n Otherwise, the user is responsible for loading them prior to\n executing the tree search.\n\n :ivar config: the configuration of the search\n :ivar expansion_policy: the expansion policy model\n :ivar filter_policy: the filter policy model\n\n :param configfile: the path to yaml file with configuration (has priority over configdict), defaults to None\n :param configdict: the config as a dictionary source, defaults to None\n \"\"\"\n\n def __init__(\n self, configfile: Optional[str] = None, configdict: Optional[StrDict] = None\n ) -> None:\n self._logger = logger()\n\n if configfile:\n self.config = Configuration.from_file(configfile)\n elif configdict:\n self.config = Configuration.from_dict(configdict)\n else:\n self.config = Configuration()\n\n self.expansion_policy = self.config.expansion_policy\n self.filter_policy = self.config.filter_policy\n self.stats: StrDict = {}\n\n def do_expansion(\n self,\n smiles: str,\n return_n: int = 5,\n filter_func: Optional[Callable[[RetroReaction], bool]] = None,\n ) -> List[Tuple[FixedRetroReaction, ...]]:\n \"\"\"\n Do the expansion of the given molecule returning a list of\n reaction tuples. Each tuple in the list contains reactions\n producing the same reactants. Hence, nested structure of the\n return value is way to group reactions.\n\n If filter policy is setup, the probability of the reactions are\n added as metadata to the reaction.\n\n The additional filter functions makes it possible to do customized\n filtering. The callable should take as only argument a `RetroReaction`\n object and return True if the reaction can be kept or False if it should\n be removed.\n\n :param smiles: the SMILES string of the target molecule\n :param return_n: the length of the return list\n :param filter_func: an additional filter function\n :return: the grouped reactions\n \"\"\"\n self.stats = {\"non-applicable\": 0}\n\n mol = TreeMolecule(parent=None, smiles=smiles)\n actions, _ = self.expansion_policy.get_actions([mol])\n results: Dict[Tuple[str, ...], List[FixedRetroReaction]] = defaultdict(list)\n for action in actions:\n reactants = action.reactants\n if not reactants:\n self.stats[\"non-applicable\"] += 1\n continue\n if filter_func and not filter_func(action):\n continue\n for name in self.filter_policy.selection or []:\n if hasattr(self.filter_policy[name], \"feasibility\"):\n _, feasibility_prob = self.filter_policy[name].feasibility(action)\n action.metadata[\"feasibility\"] = float(feasibility_prob)\n break\n action.metadata[\"expansion_rank\"] = len(results) + 1\n unique_key = tuple(sorted(mol.inchi_key for mol in reactants[0]))\n if unique_key not in results and len(results) >= return_n:\n continue\n rxn = next(ReactionTreeFromExpansion(action).tree.reactions()) # type: ignore\n results[unique_key].append(rxn)\n return [tuple(reactions) for reactions in results.values()]", "n_imports_parsed": 1, "n_files_resolved": 1, "n_chars_extracted": 3579}, "tests/utils/test_file_utils.py::145": {"resolved_imports": ["aizynthfinder/utils/files.py"], "used_names": ["pytest", "read_datafile", "save_datafile"], "enclosing_function": "test_save_load_datafile_roundtrip", "extracted_code": "# Source: aizynthfinder/utils/files.py\ndef read_datafile(filename: Union[str, Path]) -> pd.DataFrame:\n \"\"\"\n Read aizynth output from disc in either .hdf5 or .json format\n\n :param filename: the path to the data\n :return: the loaded data\n \"\"\"\n filename_str = str(filename)\n if filename_str.endswith(\".hdf5\") or filename_str.endswith(\".hdf\"):\n return pd.read_hdf(filename, \"table\")\n return pd.read_json(filename, orient=\"table\")\n\ndef save_datafile(data: pd.DataFrame, filename: Union[str, Path]) -> None:\n \"\"\"\n Save the given data to disc in either .hdf5 or .json format\n\n :param data: the data to save\n :param filename: the path to the data\n \"\"\"\n filename_str = str(filename)\n if filename_str.endswith(\".hdf5\") or filename_str.endswith(\".hdf\"):\n with warnings.catch_warnings(): # This wil suppress a PerformanceWarning\n warnings.simplefilter(\"ignore\")\n data.to_hdf(filename, key=\"table\")\n else:\n data.to_json(filename, orient=\"table\")", "n_imports_parsed": 6, "n_files_resolved": 1, "n_chars_extracted": 1024}, "tests/retrostar/test_retrostar.py::107": {"resolved_imports": ["aizynthfinder/search/retrostar/search_tree.py", "aizynthfinder/chem/serialization.py"], "used_names": ["MoleculeSerializer", "SearchTree"], "enclosing_function": "test_serialization_deserialization", "extracted_code": "# Source: aizynthfinder/search/retrostar/search_tree.py\nclass SearchTree(AndOrSearchTreeBase):\n \"\"\"\n Encapsulation of the Retro* search tree (an AND/OR tree).\n\n :ivar config: settings of the tree search algorithm\n :ivar root: the root node\n\n :param config: settings of the tree search algorithm\n :param root_smiles: the root will be set to a node representing this molecule, defaults to None\n \"\"\"\n\n def __init__(\n self, config: Configuration, root_smiles: Optional[str] = None\n ) -> None:\n super().__init__(config, root_smiles)\n self._mol_nodes: List[MoleculeNode] = []\n self._logger = logger()\n self.molecule_cost = MoleculeCost(config)\n\n if root_smiles:\n self.root: Optional[MoleculeNode] = MoleculeNode.create_root(\n root_smiles, config, self.molecule_cost\n )\n self._mol_nodes.append(self.root)\n else:\n self.root = None\n\n self._routes: List[ReactionTree] = []\n\n self.profiling = {\n \"expansion_calls\": 0,\n \"reactants_generations\": 0,\n }\n\n @classmethod\n def from_json(cls, filename: str, config: Configuration) -> SearchTree:\n \"\"\"\n Create a new search tree by deserialization from a JSON file\n\n :param filename: the path to the JSON node\n :param config: the configuration of the search tree\n :return: a deserialized tree\n \"\"\"\n\n def _find_mol_nodes(node):\n for child_ in node.children:\n tree._mol_nodes.append(child_) # pylint: disable=protected-access\n for grandchild in child_.children:\n _find_mol_nodes(grandchild)\n\n tree = cls(config)\n with open(filename, \"r\") as fileobj:\n dict_ = json.load(fileobj)\n mol_deser = MoleculeDeserializer(dict_[\"molecules\"])\n tree.root = MoleculeNode.from_dict(\n dict_[\"tree\"], config, mol_deser, tree.molecule_cost\n )\n tree._mol_nodes.append(tree.root) # pylint: disable=protected-access\n for child in tree.root.children:\n _find_mol_nodes(child)\n return tree\n\n @property\n def mol_nodes(self) -> Sequence[MoleculeNode]: # type: ignore\n \"\"\"Return the molecule nodes of the tree\"\"\"\n return self._mol_nodes\n\n def one_iteration(self) -> bool:\n \"\"\"\n Perform one iteration of\n 1. Selection\n 2. Expansion\n 3. Update\n\n :raises StopIteration: if the search should be pre-maturely terminated\n :return: if a solution was found\n :rtype: bool\n \"\"\"\n if self.root is None:\n raise ValueError(\"Root is undefined. Cannot make an iteration\")\n\n self._routes = []\n\n next_node = self._select()\n\n if not next_node:\n self._logger.debug(\"No expandable nodes in Retro* iteration\")\n raise StopIteration\n\n self._expand(next_node)\n\n if not next_node.children:\n next_node.expandable = False\n\n self._update(next_node)\n\n return self.root.solved\n\n def routes(self) -> List[ReactionTree]:\n \"\"\"\n Extracts and returns routes from the AND/OR tree\n\n :return: the routes\n \"\"\"\n if self.root is None:\n return []\n if not self._routes:\n self._routes = SplitAndOrTree(self.root, self.config.stock).routes\n return self._routes\n\n def serialize(self, filename: str) -> None:\n \"\"\"\n Seralize the search tree to a JSON file\n\n :param filename: the path to the JSON file\n :type filename: str\n \"\"\"\n if self.root is None:\n raise ValueError(\"Cannot serialize tree as root is not defined\")\n\n mol_ser = MoleculeSerializer()\n dict_ = {\"tree\": self.root.serialize(mol_ser), \"molecules\": mol_ser.store}\n with open(filename, \"w\") as fileobj:\n json.dump(dict_, fileobj, indent=2)\n\n def _expand(self, node: MoleculeNode) -> None:\n reactions, priors = self.config.expansion_policy([node.mol])\n self.profiling[\"expansion_calls\"] += 1\n\n if not reactions:\n return\n\n costs = -np.log(np.clip(priors, 1e-3, 1.0))\n reactions_to_expand = []\n reaction_costs = []\n for reaction, cost in zip(reactions, costs):\n try:\n self.profiling[\"reactants_generations\"] += 1\n _ = reaction.reactants\n except: # pylint: disable=bare-except\n continue\n if not reaction.reactants:\n continue\n for idx, _ in enumerate(reaction.reactants):\n rxn_copy = reaction.copy(idx)\n if self._filter_reaction(rxn_copy):\n continue\n reactions_to_expand.append(rxn_copy)\n reaction_costs.append(cost)\n\n for cost, rxn in zip(reaction_costs, reactions_to_expand):\n new_nodes = node.add_stub(cost, rxn)\n self._mol_nodes.extend(new_nodes)\n\n def _filter_reaction(self, reaction: RetroReaction) -> bool:\n if not self.config.filter_policy.selection:\n return False\n try:\n self.config.filter_policy(reaction)\n except RejectionException as err:\n self._logger.debug(str(err))\n return True\n return False\n\n def _select(self) -> Optional[MoleculeNode]:\n scores = np.asarray(\n [\n node.target_value if node.expandable else np.inf\n for node in self._mol_nodes\n ]\n )\n\n if scores.min() == np.inf:\n return None\n\n return self._mol_nodes[int(np.argmin(scores))]\n\n @staticmethod\n def _update(node: MoleculeNode) -> None:\n v_delta = node.close()\n if node.parent and np.isfinite(v_delta):\n node.parent.update(v_delta, from_mol=node.mol)\n\n\n# Source: aizynthfinder/chem/serialization.py\nclass MoleculeSerializer:\n \"\"\"\n Utility class for serializing molecules\n\n The id of the molecule to be serialized can be obtained with:\n\n .. code-block::\n\n serializer = MoleculeSerializer()\n mol = Molecule(smiles=\"CCCO\")\n idx = serializer[mol]\n\n which will take care of the serialization of the molecule.\n \"\"\"\n\n def __init__(self) -> None:\n self._store: Dict[int, Any] = {}\n\n def __getitem__(self, mol: Optional[aizynthfinder.chem.Molecule]) -> Optional[int]:\n if mol is None:\n return None\n\n id_ = id(mol)\n if id_ not in self._store:\n self._add_mol(mol)\n return id_\n\n @property\n def store(self) -> Dict[int, Any]:\n \"\"\"Return all serialized molecules as a dictionary\"\"\"\n return self._store\n\n def _add_mol(self, mol: aizynthfinder.chem.Molecule) -> None:\n id_ = id(mol)\n dict_ = {\"smiles\": mol.smiles, \"class\": mol.__class__.__name__}\n if isinstance(mol, aizynthfinder.chem.TreeMolecule):\n dict_[\"parent\"] = self[mol.parent]\n dict_[\"transform\"] = mol.transform\n if not mol.parent:\n dict_[\"smiles\"] = mol.original_smiles\n else:\n dict_[\"smiles\"] = mol.mapped_smiles\n self._store[id_] = dict_", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 7318}, "tests/utils/test_file_utils.py::46": {"resolved_imports": ["aizynthfinder/utils/files.py"], "used_names": ["os", "split_file"], "enclosing_function": "test_split_file_even", "extracted_code": "# Source: aizynthfinder/utils/files.py\ndef split_file(filename: str, nparts: int) -> List[str]:\n \"\"\"\n Split the content of a text file into a given number of temporary files\n\n :param filename: the path to the file to split\n :param nparts: the number of parts to create\n :return: list of filenames of the parts\n \"\"\"\n with open(filename, \"r\") as fileobj:\n lines = fileobj.read().splitlines()\n\n filenames = []\n batch_size, remainder = divmod(len(lines), nparts)\n stop = 0\n for part in range(1, nparts + 1):\n start = stop\n stop += batch_size + 1 if part <= remainder else batch_size\n filenames.append(tempfile.mktemp())\n with open(filenames[-1], \"w\") as fileobj:\n fileobj.write(\"\\n\".join(lines[start:stop]))\n return filenames", "n_imports_parsed": 6, "n_files_resolved": 1, "n_chars_extracted": 803}, "tests/chem/test_reaction.py::91": {"resolved_imports": ["aizynthfinder/chem/__init__.py"], "used_names": ["SmilesBasedRetroReaction", "TreeMolecule"], "enclosing_function": "test_smiles_based_retroreaction", "extracted_code": "# Source: aizynthfinder/chem/__init__.py\n Molecule,\n MoleculeException,\n TreeMolecule,\n UniqueMolecule,\n none_molecule,\n)\nfrom aizynthfinder.chem.reaction import (\n FixedRetroReaction,\n RetroReaction,\n SmilesBasedRetroReaction,\n TemplatedRetroReaction,\n hash_reactions,\n\n FixedRetroReaction,\n RetroReaction,\n SmilesBasedRetroReaction,\n TemplatedRetroReaction,\n hash_reactions,\n)\nfrom aizynthfinder.chem.serialization import (\n MoleculeDeserializer,\n MoleculeSerializer,\n deserialize_action,\n serialize_action,\n)", "n_imports_parsed": 1, "n_files_resolved": 1, "n_chars_extracted": 568}, "tests/test_finder.py::98": {"resolved_imports": ["aizynthfinder/aizynthfinder.py"], "used_names": [], "enclosing_function": "test_broken_frozen_bond_filter", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/mcts/test_tree.py::40": {"resolved_imports": [], "used_names": [], "enclosing_function": "test_route_to_node", "extracted_code": "", "n_imports_parsed": 0, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/retrostar/test_retrostar.py::52": {"resolved_imports": ["aizynthfinder/search/retrostar/search_tree.py", "aizynthfinder/chem/serialization.py"], "used_names": [], "enclosing_function": "test_one_expansion_with_finder", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/context/test_expansion_strategies.py::92": {"resolved_imports": ["aizynthfinder/chem/__init__.py", "aizynthfinder/context/policy/__init__.py", "aizynthfinder/utils/exceptions.py"], "used_names": ["MultiExpansionStrategy", "TreeMolecule"], "enclosing_function": "test_weighted_multi_expansion_strategy", "extracted_code": "# Source: aizynthfinder/chem/__init__.py\n Molecule,\n MoleculeException,\n TreeMolecule,\n UniqueMolecule,\n none_molecule,\n)\nfrom aizynthfinder.chem.reaction import (\n FixedRetroReaction,\n RetroReaction,\n SmilesBasedRetroReaction,\n TemplatedRetroReaction,\n hash_reactions,\n\n\n# Source: aizynthfinder/context/policy/__init__.py\nfrom aizynthfinder.context.policy.expansion_strategies import (\n ExpansionStrategy,\n MultiExpansionStrategy,\n TemplateBasedDirectExpansionStrategy,\n TemplateBasedExpansionStrategy,\n)\nfrom aizynthfinder.context.policy.filter_strategies import (\n BondFilter,\n FilterStrategy,\n FrozenSubstructureFilter,\n QuickKerasFilter,\n ReactantsCountFilter,", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 722}, "tests/context/test_collection.py::31": {"resolved_imports": ["aizynthfinder/context/collection.py"], "used_names": [], "enclosing_function": "test_add_single_item", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/utils/test_dynamic_loading.py::43": {"resolved_imports": ["aizynthfinder/utils/loading.py"], "used_names": ["load_dynamic_class", "pytest"], "enclosing_function": "test_incorrect_class", "extracted_code": "# Source: aizynthfinder/utils/loading.py\ndef load_dynamic_class(\n name_spec: str,\n default_module: Optional[str] = None,\n exception_cls: Any = ValueError,\n) -> Any:\n \"\"\"\n Load an object from a dynamic specification.\n\n The specification can be either:\n ClassName, in-case the module name is taken from the `default_module` argument\n or\n package_name.module_name.ClassName, in-case the module is taken as `package_name.module_name`\n\n :param name_spec: the class specification\n :param default_module: the default module\n :param exception_cls: the exception class to raise on exception\n :return: the loaded class\n \"\"\"\n if \".\" not in name_spec:\n name = name_spec\n if not default_module:\n raise exception_cls(\n \"Must provide default_module argument if not given in name_spec\"\n )\n module_name = default_module\n else:\n module_name, name = name_spec.rsplit(\".\", maxsplit=1)\n\n try:\n loaded_module = importlib.import_module(module_name)\n except ImportError:\n raise exception_cls(f\"Unable to load module: {module_name}\")\n\n if not hasattr(loaded_module, name):\n raise exception_cls(\n f\"Module ({module_name}) does not have a class called {name}\"\n )\n\n return getattr(loaded_module, name)", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 1345}, "tests/context/test_stock.py::119": {"resolved_imports": ["aizynthfinder/chem/__init__.py", "aizynthfinder/context/stock/__init__.py", "aizynthfinder/context/stock/queries.py", "aizynthfinder/tools/make_stock.py"], "used_names": ["Molecule"], "enclosing_function": "test_mol_in_stock", "extracted_code": "# Source: aizynthfinder/chem/__init__.py\n\"\"\"\nfrom aizynthfinder.chem.mol import (\n Molecule,\n MoleculeException,\n TreeMolecule,\n UniqueMolecule,\n none_molecule,\n)\nfrom aizynthfinder.chem.reaction import (\n FixedRetroReaction,\n RetroReaction,\n SmilesBasedRetroReaction,\n\nfrom aizynthfinder.chem.mol import (\n Molecule,\n MoleculeException,\n TreeMolecule,\n UniqueMolecule,\n none_molecule,\n)\nfrom aizynthfinder.chem.reaction import (\n FixedRetroReaction,\n RetroReaction,\n SmilesBasedRetroReaction,\n TemplatedRetroReaction,\n\n Molecule,\n MoleculeException,\n TreeMolecule,\n UniqueMolecule,\n none_molecule,\n)\nfrom aizynthfinder.chem.reaction import (\n FixedRetroReaction,\n RetroReaction,\n SmilesBasedRetroReaction,\n TemplatedRetroReaction,\n hash_reactions,\n\n MoleculeException,\n TreeMolecule,\n UniqueMolecule,\n none_molecule,\n)\nfrom aizynthfinder.chem.reaction import (\n FixedRetroReaction,\n RetroReaction,\n SmilesBasedRetroReaction,\n TemplatedRetroReaction,\n hash_reactions,\n)\n\n)\nfrom aizynthfinder.chem.serialization import (\n MoleculeDeserializer,\n MoleculeSerializer,\n deserialize_action,\n serialize_action,\n)", "n_imports_parsed": 7, "n_files_resolved": 4, "n_chars_extracted": 1225}, "tests/retrostar/test_retrostar_nodes.py::104": {"resolved_imports": ["aizynthfinder/search/retrostar/nodes.py", "aizynthfinder/chem/serialization.py", "aizynthfinder/search/andor_trees.py"], "used_names": ["MoleculeDeserializer", "MoleculeNode", "MoleculeSerializer"], "enclosing_function": "test_serialization_deserialization", "extracted_code": "# Source: aizynthfinder/search/retrostar/nodes.py\nclass MoleculeNode(TreeNodeMixin):\n \"\"\"\n An OR node representing a molecule\n\n :ivar cost: the cost of synthesizing the molecule\n :ivar expandable: if True, this node is part of the frontier\n :ivar mol: the molecule represented by the node\n :ivar in_stock: if True the molecule is in stock and hence should not be expanded\n :ivar parent: the parent of the node\n :ivar solved: if True the molecule is in stock or at least one child node is solved\n :ivar value: the current rn(m|T)\n\n :param mol: the molecule to be represented by the node\n :param config: the configuration of the search\n :param parent: the parent of the node, optional\n \"\"\"\n\n def __init__(\n self,\n mol: TreeMolecule,\n config: Configuration,\n molecule_cost: MoleculeCost,\n parent: Optional[ReactionNode] = None,\n ) -> None:\n self.mol = mol\n self._config = config\n self.molecule_cost = molecule_cost\n self.cost = self.molecule_cost(mol)\n self.value = self.cost\n self.in_stock = mol in config.stock\n self.parent = parent\n\n self._children: List[ReactionNode] = []\n self.solved = self.in_stock\n # Makes it unexpandable if we have reached maximum depth\n self.expandable = self.mol.transform < self._config.search.max_transforms\n\n if self.in_stock:\n self.expandable = False\n self.value = 0\n\n @classmethod\n def create_root(\n cls, smiles: str, config: Configuration, molecule_cost: MoleculeCost\n ) -> \"MoleculeNode\":\n \"\"\"\n Create a root node for a tree using a SMILES.\n\n :param smiles: the SMILES representation of the root state\n :param config: settings of the tree search algorithm\n :return: the created node\n \"\"\"\n mol = TreeMolecule(parent=None, transform=0, smiles=smiles)\n return MoleculeNode(mol=mol, config=config, molecule_cost=molecule_cost)\n\n @classmethod\n def from_dict(\n cls,\n dict_: StrDict,\n config: Configuration,\n molecules: MoleculeDeserializer,\n molecule_cost: MoleculeCost,\n parent: Optional[ReactionNode] = None,\n ) -> \"MoleculeNode\":\n \"\"\"\n Create a new node from a dictionary, i.e. deserialization\n\n :param dict_: the serialized node\n :param config: settings of the tree search algorithm\n :param molecules: the deserialized molecules\n :param parent: the parent node\n :return: a deserialized node\n \"\"\"\n mol = molecules.get_tree_molecules([dict_[\"mol\"]])[0]\n node = MoleculeNode(mol, config, molecule_cost, parent)\n node.molecule_cost = molecule_cost\n for attr in [\"cost\", \"expandable\", \"value\"]:\n setattr(node, attr, dict_[attr])\n node.children = [\n ReactionNode.from_dict(\n child, config, molecules, node.molecule_cost, parent=node\n )\n for child in dict_[\"children\"]\n ]\n return node\n\n @property # type: ignore\n def children(self) -> List[ReactionNode]: # type: ignore\n \"\"\"Gives the reaction children nodes\"\"\"\n return self._children\n\n @children.setter\n def children(self, value: List[ReactionNode]) -> None:\n self._children = value\n\n @property\n def target_value(self) -> float:\n \"\"\"\n The V_t(m|T) value,\n the current cost of the tree containing this node\n\n :return: the value\n \"\"\"\n if self.parent:\n return self.parent.target_value\n return self.value\n\n @property\n def prop(self) -> StrDict:\n return {\"solved\": self.solved, \"mol\": self.mol}\n\n def add_stub(self, cost: float, reaction: RetroReaction) -> Sequence[MoleculeNode]:\n \"\"\"\n Add a stub / sub-tree to this node\n\n :param cost: the cost of the reaction\n :param reaction: the reaction creating the stub\n :return: list of all newly added molecular nodes\n \"\"\"\n reactants = reaction.reactants[reaction.index]\n if not reactants:\n return []\n\n ancestors = self.ancestors()\n for mol in reactants:\n if mol in ancestors:\n return []\n\n rxn_node = ReactionNode.create_stub(\n cost=cost,\n reaction=reaction,\n parent=self,\n config=self._config,\n )\n self._children.append(rxn_node)\n\n return rxn_node.children\n\n def ancestors(self) -> Set[TreeMolecule]:\n \"\"\"\n Return the ancestors of this node\n\n :return: the ancestors\n :rtype: set\n \"\"\"\n if not self.parent:\n return {self.mol}\n\n ancestors = self.parent.parent.ancestors()\n ancestors.add(self.mol)\n return ancestors\n\n def close(self) -> float:\n \"\"\"\n Updates the values of this node after expanding it.\n\n :return: the delta V value\n :rtype: float\n \"\"\"\n self.solved = any(child.solved for child in self.children)\n if self.children:\n new_value = np.min([child.value for child in self.children])\n else:\n new_value = np.inf\n\n v_delta = new_value - self.value\n self.value = new_value\n\n self.expandable = False\n return v_delta\n\n def serialize(self, molecule_store: MoleculeSerializer) -> StrDict:\n \"\"\"\n Serialize the node object to a dictionary\n\n :param molecule_store: the serialized molecules\n :return: the serialized node\n \"\"\"\n dict_ = {attr: getattr(self, attr) for attr in [\"cost\", \"expandable\", \"value\"]}\n dict_[\"mol\"] = molecule_store[self.mol]\n dict_[\"children\"] = [child.serialize(molecule_store) for child in self.children]\n return dict_\n\n def update(self, solved: bool) -> None:\n \"\"\"\n Update the node as part of the update algorithm,\n calling the `update()` method of its parent if available.\n\n :param solved: if the child node was solved\n \"\"\"\n new_value = np.min([child.value for child in self.children])\n new_solv = self.solved or solved\n updated = (self.value != new_value) or (self.solved != new_solv)\n\n v_delta = new_value - self.value\n self.value = new_value\n self.solved = new_solv\n\n if updated and self.parent:\n self.parent.update(v_delta, from_mol=self.mol)\n\n\n# Source: aizynthfinder/chem/serialization.py\nclass MoleculeSerializer:\n \"\"\"\n Utility class for serializing molecules\n\n The id of the molecule to be serialized can be obtained with:\n\n .. code-block::\n\n serializer = MoleculeSerializer()\n mol = Molecule(smiles=\"CCCO\")\n idx = serializer[mol]\n\n which will take care of the serialization of the molecule.\n \"\"\"\n\n def __init__(self) -> None:\n self._store: Dict[int, Any] = {}\n\n def __getitem__(self, mol: Optional[aizynthfinder.chem.Molecule]) -> Optional[int]:\n if mol is None:\n return None\n\n id_ = id(mol)\n if id_ not in self._store:\n self._add_mol(mol)\n return id_\n\n @property\n def store(self) -> Dict[int, Any]:\n \"\"\"Return all serialized molecules as a dictionary\"\"\"\n return self._store\n\n def _add_mol(self, mol: aizynthfinder.chem.Molecule) -> None:\n id_ = id(mol)\n dict_ = {\"smiles\": mol.smiles, \"class\": mol.__class__.__name__}\n if isinstance(mol, aizynthfinder.chem.TreeMolecule):\n dict_[\"parent\"] = self[mol.parent]\n dict_[\"transform\"] = mol.transform\n if not mol.parent:\n dict_[\"smiles\"] = mol.original_smiles\n else:\n dict_[\"smiles\"] = mol.mapped_smiles\n self._store[id_] = dict_\n\nclass MoleculeDeserializer:\n \"\"\"\n Utility class for deserializing molecules.\n The serialized molecules are created upon instantiation of the class.\n\n The deserialized molecules can be obtained with:\n\n .. code-block::\n\n deserializer = MoleculeDeserializer()\n mol = deserializer[idx]\n\n \"\"\"\n\n def __init__(self, store: Dict[int, Any]) -> None:\n self._objects: Dict[int, Any] = {}\n self._create_molecules(store)\n\n def __getitem__(self, id_: Optional[int]) -> Optional[aizynthfinder.chem.Molecule]:\n if id_ is None:\n return None\n return self._objects[id_]\n\n def get_tree_molecules(\n self, ids: Sequence[int]\n ) -> Sequence[aizynthfinder.chem.TreeMolecule]:\n \"\"\"\n Return multiple deserialized tree molecules\n\n :param ids: the list of IDs to deserialize\n :return: the molecule objects\n \"\"\"\n objects = []\n for id_ in ids:\n obj = self[id_]\n if obj is None or not isinstance(obj, aizynthfinder.chem.TreeMolecule):\n raise ValueError(f\"Failed to deserialize molecule with id {id_}\")\n objects.append(obj)\n return objects\n\n def _create_molecules(self, store: dict) -> None:\n for id_, spec in store.items():\n if isinstance(id_, str):\n id_ = int(id_)\n\n cls = spec[\"class\"]\n if \"parent\" in spec:\n spec[\"parent\"] = self[spec[\"parent\"]]\n\n kwargs = dict(spec)\n del kwargs[\"class\"]\n self._objects[id_] = getattr(aizynthfinder.chem, cls)(**kwargs)", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 9488}, "tests/context/test_score.py::88": {"resolved_imports": ["aizynthfinder/chem/__init__.py", "aizynthfinder/context/config.py", "aizynthfinder/context/scoring/__init__.py", "aizynthfinder/reactiontree.py", "aizynthfinder/search/mcts/__init__.py"], "used_names": ["AverageTemplateOccurrenceScorer"], "enclosing_function": "test_template_occurrence_scorer_no_metadata", "extracted_code": "# Source: aizynthfinder/context/scoring/__init__.py\n)\nfrom aizynthfinder.context.scoring.scorers_reactions import (\n AverageTemplateOccurrenceScorer,\n MaxTransformScorer,\n NumberOfReactionsScorer,\n ReactionClassMembershipScorer,\n ReactionClassRankScorer,\n)\nfrom aizynthfinder.utils.exceptions import ScorerException", "n_imports_parsed": 8, "n_files_resolved": 5, "n_chars_extracted": 330}, "tests/mcts/test_node.py::80": {"resolved_imports": [], "used_names": [], "enclosing_function": "test_promising_child_of_root", "extracted_code": "", "n_imports_parsed": 0, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/mcts/test_multiobjective.py::71": {"resolved_imports": ["aizynthfinder/search/mcts/node.py", "aizynthfinder/search/mcts/__init__.py"], "used_names": [], "enclosing_function": "test_backpropagate", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/retrostar/test_retrostar_nodes.py::38": {"resolved_imports": ["aizynthfinder/search/retrostar/nodes.py", "aizynthfinder/chem/serialization.py", "aizynthfinder/search/andor_trees.py"], "used_names": [], "enclosing_function": "test_create_stub", "extracted_code": "", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 0}, "tests/test_analysis.py::101": {"resolved_imports": ["aizynthfinder/analysis/__init__.py", "aizynthfinder/analysis/routes.py", "aizynthfinder/analysis/utils.py", "aizynthfinder/reactiontree.py", "aizynthfinder/search/mcts/__init__.py", "aizynthfinder/context/scoring/__init__.py"], "used_names": ["NumberOfReactionsScorer"], "enclosing_function": "test_tree_statistics", "extracted_code": "# Source: aizynthfinder/context/scoring/__init__.py\n AverageTemplateOccurrenceScorer,\n MaxTransformScorer,\n NumberOfReactionsScorer,\n ReactionClassMembershipScorer,\n ReactionClassRankScorer,\n)\nfrom aizynthfinder.utils.exceptions import ScorerException", "n_imports_parsed": 10, "n_files_resolved": 6, "n_chars_extracted": 266}, "tests/chem/test_serialization.py::50": {"resolved_imports": ["aizynthfinder/chem/serialization.py", "aizynthfinder/chem/__init__.py"], "used_names": ["MoleculeDeserializer"], "enclosing_function": "test_deserialize_single_mol", "extracted_code": "# Source: aizynthfinder/chem/serialization.py\nclass MoleculeDeserializer:\n \"\"\"\n Utility class for deserializing molecules.\n The serialized molecules are created upon instantiation of the class.\n\n The deserialized molecules can be obtained with:\n\n .. code-block::\n\n deserializer = MoleculeDeserializer()\n mol = deserializer[idx]\n\n \"\"\"\n\n def __init__(self, store: Dict[int, Any]) -> None:\n self._objects: Dict[int, Any] = {}\n self._create_molecules(store)\n\n def __getitem__(self, id_: Optional[int]) -> Optional[aizynthfinder.chem.Molecule]:\n if id_ is None:\n return None\n return self._objects[id_]\n\n def get_tree_molecules(\n self, ids: Sequence[int]\n ) -> Sequence[aizynthfinder.chem.TreeMolecule]:\n \"\"\"\n Return multiple deserialized tree molecules\n\n :param ids: the list of IDs to deserialize\n :return: the molecule objects\n \"\"\"\n objects = []\n for id_ in ids:\n obj = self[id_]\n if obj is None or not isinstance(obj, aizynthfinder.chem.TreeMolecule):\n raise ValueError(f\"Failed to deserialize molecule with id {id_}\")\n objects.append(obj)\n return objects\n\n def _create_molecules(self, store: dict) -> None:\n for id_, spec in store.items():\n if isinstance(id_, str):\n id_ = int(id_)\n\n cls = spec[\"class\"]\n if \"parent\" in spec:\n spec[\"parent\"] = self[spec[\"parent\"]]\n\n kwargs = dict(spec)\n del kwargs[\"class\"]\n self._objects[id_] = getattr(aizynthfinder.chem, cls)(**kwargs)", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 1671}, "tests/mcts/test_tree.py::50": {"resolved_imports": [], "used_names": [], "enclosing_function": "test_create_graph", "extracted_code": "", "n_imports_parsed": 0, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/breadth_first/test_search.py::102": {"resolved_imports": ["aizynthfinder/search/breadth_first/search_tree.py"], "used_names": ["SearchTree", "random"], "enclosing_function": "test_routes", "extracted_code": "# Source: aizynthfinder/search/breadth_first/search_tree.py\nclass SearchTree(AndOrSearchTreeBase):\n \"\"\"\n Encapsulation of the a breadth-first exhaustive search algorithm\n\n :ivar config: settings of the tree search algorithm\n :ivar root: the root node\n\n :param config: settings of the tree search algorithm\n :param root_smiles: the root will be set to a node representing this molecule, defaults to None\n \"\"\"\n\n def __init__(\n self, config: Configuration, root_smiles: Optional[str] = None\n ) -> None:\n super().__init__(config, root_smiles)\n self._mol_nodes: List[MoleculeNode] = []\n self._added_mol_nodes: List[MoleculeNode] = []\n self._logger = logger()\n\n if root_smiles:\n self.root: Optional[MoleculeNode] = MoleculeNode.create_root(\n root_smiles, config\n )\n self._mol_nodes.append(self.root)\n else:\n self.root = None\n\n self._routes: List[ReactionTree] = []\n\n self.profiling = {\n \"expansion_calls\": 0,\n \"reactants_generations\": 0,\n }\n\n @classmethod\n def from_json(cls, filename: str, config: Configuration) -> SearchTree:\n \"\"\"\n Create a new search tree by deserialization from a JSON file\n\n :param filename: the path to the JSON node\n :param config: the configuration of the search tree\n :return: a deserialized tree\n \"\"\"\n\n def _find_mol_nodes(node):\n for child_ in node.children:\n tree._mol_nodes.append(child_) # pylint: disable=protected-access\n for grandchild in child_.children:\n _find_mol_nodes(grandchild)\n\n tree = cls(config)\n with open(filename, \"r\") as fileobj:\n dict_ = json.load(fileobj)\n mol_deser = MoleculeDeserializer(dict_[\"molecules\"])\n tree.root = MoleculeNode.from_dict(dict_[\"tree\"], config, mol_deser)\n tree._mol_nodes.append(tree.root) # pylint: disable=protected-access\n for child in tree.root.children:\n _find_mol_nodes(child)\n return tree\n\n @property\n def mol_nodes(self) -> Sequence[MoleculeNode]: # type: ignore\n \"\"\"Return the molecule nodes of the tree\"\"\"\n return self._mol_nodes\n\n def one_iteration(self) -> bool:\n \"\"\"\n Perform one iteration expansion.\n Expands all expandable molecule nodes in the tree, which should be\n on the same depth of the tree.\n\n :raises StopIteration: if the search should be pre-maturely terminated\n :return: if a solution was found\n :rtype: bool\n \"\"\"\n if self.root is None:\n raise ValueError(\"Root is undefined. Cannot make an iteration\")\n\n self._routes = []\n self._added_mol_nodes = []\n\n for next_node in self._mol_nodes:\n if next_node.expandable:\n self._expand(next_node)\n\n if not self._added_mol_nodes:\n self._logger.debug(\"No new nodes added in breadth-first iteration\")\n raise StopIteration\n\n self._mol_nodes.extend(self._added_mol_nodes)\n solved = all(node.in_stock for node in self._mol_nodes if not node.children)\n return solved\n\n def routes(self) -> List[ReactionTree]:\n \"\"\"\n Extracts and returns routes from the AND/OR tree\n\n :return: the routes\n \"\"\"\n if self.root is None:\n return []\n if not self._routes:\n self._routes = SplitAndOrTree(self.root, self.config.stock).routes\n return self._routes\n\n def serialize(self, filename: str) -> None:\n \"\"\"\n Seralize the search tree to a JSON file\n\n :param filename: the path to the JSON file\n :type filename: str\n \"\"\"\n if self.root is None:\n raise ValueError(\"Cannot serialize tree as root is not defined\")\n\n mol_ser = MoleculeSerializer()\n dict_ = {\"tree\": self.root.serialize(mol_ser), \"molecules\": mol_ser.store}\n with open(filename, \"w\") as fileobj:\n json.dump(dict_, fileobj, indent=2)\n\n def _expand(self, node: MoleculeNode) -> None:\n node.expandable = False\n reactions, _ = self.config.expansion_policy([node.mol])\n self.profiling[\"expansion_calls\"] += 1\n\n if not reactions:\n return\n\n reactions_to_expand = []\n for reaction in reactions:\n try:\n self.profiling[\"reactants_generations\"] += 1\n _ = reaction.reactants\n except: # pylint: disable=bare-except\n continue\n if not reaction.reactants:\n continue\n for idx, _ in enumerate(reaction.reactants):\n rxn_copy = reaction.copy(idx)\n reactions_to_expand.append(rxn_copy)\n\n for rxn in reactions_to_expand:\n new_nodes = node.add_stub(rxn)\n self._added_mol_nodes.extend(new_nodes)", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 4982}, "tests/chem/test_serialization.py::71": {"resolved_imports": ["aizynthfinder/chem/serialization.py", "aizynthfinder/chem/__init__.py"], "used_names": ["MoleculeDeserializer"], "enclosing_function": "test_deserialize_tree_mols", "extracted_code": "# Source: aizynthfinder/chem/serialization.py\nclass MoleculeDeserializer:\n \"\"\"\n Utility class for deserializing molecules.\n The serialized molecules are created upon instantiation of the class.\n\n The deserialized molecules can be obtained with:\n\n .. code-block::\n\n deserializer = MoleculeDeserializer()\n mol = deserializer[idx]\n\n \"\"\"\n\n def __init__(self, store: Dict[int, Any]) -> None:\n self._objects: Dict[int, Any] = {}\n self._create_molecules(store)\n\n def __getitem__(self, id_: Optional[int]) -> Optional[aizynthfinder.chem.Molecule]:\n if id_ is None:\n return None\n return self._objects[id_]\n\n def get_tree_molecules(\n self, ids: Sequence[int]\n ) -> Sequence[aizynthfinder.chem.TreeMolecule]:\n \"\"\"\n Return multiple deserialized tree molecules\n\n :param ids: the list of IDs to deserialize\n :return: the molecule objects\n \"\"\"\n objects = []\n for id_ in ids:\n obj = self[id_]\n if obj is None or not isinstance(obj, aizynthfinder.chem.TreeMolecule):\n raise ValueError(f\"Failed to deserialize molecule with id {id_}\")\n objects.append(obj)\n return objects\n\n def _create_molecules(self, store: dict) -> None:\n for id_, spec in store.items():\n if isinstance(id_, str):\n id_ = int(id_)\n\n cls = spec[\"class\"]\n if \"parent\" in spec:\n spec[\"parent\"] = self[spec[\"parent\"]]\n\n kwargs = dict(spec)\n del kwargs[\"class\"]\n self._objects[id_] = getattr(aizynthfinder.chem, cls)(**kwargs)", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 1671}, "tests/mcts/test_serialization.py::39": {"resolved_imports": ["aizynthfinder/chem/__init__.py", "aizynthfinder/chem/serialization.py", "aizynthfinder/search/mcts/__init__.py"], "used_names": ["MoleculeSerializer"], "enclosing_function": "test_serialize_node", "extracted_code": "# Source: aizynthfinder/chem/serialization.py\nclass MoleculeSerializer:\n \"\"\"\n Utility class for serializing molecules\n\n The id of the molecule to be serialized can be obtained with:\n\n .. code-block::\n\n serializer = MoleculeSerializer()\n mol = Molecule(smiles=\"CCCO\")\n idx = serializer[mol]\n\n which will take care of the serialization of the molecule.\n \"\"\"\n\n def __init__(self) -> None:\n self._store: Dict[int, Any] = {}\n\n def __getitem__(self, mol: Optional[aizynthfinder.chem.Molecule]) -> Optional[int]:\n if mol is None:\n return None\n\n id_ = id(mol)\n if id_ not in self._store:\n self._add_mol(mol)\n return id_\n\n @property\n def store(self) -> Dict[int, Any]:\n \"\"\"Return all serialized molecules as a dictionary\"\"\"\n return self._store\n\n def _add_mol(self, mol: aizynthfinder.chem.Molecule) -> None:\n id_ = id(mol)\n dict_ = {\"smiles\": mol.smiles, \"class\": mol.__class__.__name__}\n if isinstance(mol, aizynthfinder.chem.TreeMolecule):\n dict_[\"parent\"] = self[mol.parent]\n dict_[\"transform\"] = mol.transform\n if not mol.parent:\n dict_[\"smiles\"] = mol.original_smiles\n else:\n dict_[\"smiles\"] = mol.mapped_smiles\n self._store[id_] = dict_", "n_imports_parsed": 3, "n_files_resolved": 3, "n_chars_extracted": 1360}, "tests/chem/test_serialization.py::68": {"resolved_imports": ["aizynthfinder/chem/serialization.py", "aizynthfinder/chem/__init__.py"], "used_names": ["MoleculeDeserializer"], "enclosing_function": "test_deserialize_tree_mols", "extracted_code": "# Source: aizynthfinder/chem/serialization.py\nclass MoleculeDeserializer:\n \"\"\"\n Utility class for deserializing molecules.\n The serialized molecules are created upon instantiation of the class.\n\n The deserialized molecules can be obtained with:\n\n .. code-block::\n\n deserializer = MoleculeDeserializer()\n mol = deserializer[idx]\n\n \"\"\"\n\n def __init__(self, store: Dict[int, Any]) -> None:\n self._objects: Dict[int, Any] = {}\n self._create_molecules(store)\n\n def __getitem__(self, id_: Optional[int]) -> Optional[aizynthfinder.chem.Molecule]:\n if id_ is None:\n return None\n return self._objects[id_]\n\n def get_tree_molecules(\n self, ids: Sequence[int]\n ) -> Sequence[aizynthfinder.chem.TreeMolecule]:\n \"\"\"\n Return multiple deserialized tree molecules\n\n :param ids: the list of IDs to deserialize\n :return: the molecule objects\n \"\"\"\n objects = []\n for id_ in ids:\n obj = self[id_]\n if obj is None or not isinstance(obj, aizynthfinder.chem.TreeMolecule):\n raise ValueError(f\"Failed to deserialize molecule with id {id_}\")\n objects.append(obj)\n return objects\n\n def _create_molecules(self, store: dict) -> None:\n for id_, spec in store.items():\n if isinstance(id_, str):\n id_ = int(id_)\n\n cls = spec[\"class\"]\n if \"parent\" in spec:\n spec[\"parent\"] = self[spec[\"parent\"]]\n\n kwargs = dict(spec)\n del kwargs[\"class\"]\n self._objects[id_] = getattr(aizynthfinder.chem, cls)(**kwargs)", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 1671}, "tests/context/test_collection.py::176": {"resolved_imports": ["aizynthfinder/context/collection.py"], "used_names": [], "enclosing_function": "test_select_single_collection", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/retrostar/test_retrostar.py::13": {"resolved_imports": ["aizynthfinder/search/retrostar/search_tree.py", "aizynthfinder/chem/serialization.py"], "used_names": [], "enclosing_function": "test_one_iteration", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/breadth_first/test_nodes.py::75": {"resolved_imports": ["aizynthfinder/search/breadth_first/nodes.py", "aizynthfinder/chem/serialization.py"], "used_names": ["MoleculeDeserializer", "MoleculeNode", "MoleculeSerializer"], "enclosing_function": "test_serialization_deserialization", "extracted_code": "# Source: aizynthfinder/search/breadth_first/nodes.py\nclass MoleculeNode(TreeNodeMixin):\n \"\"\"\n An OR node representing a molecule\n\n :ivar expandable: if True, this node is part of the frontier\n :ivar mol: the molecule represented by the node\n :ivar in_stock: if True the molecule is in stock and hence should not be expanded\n :ivar parent: the parent of the node\n\n :param mol: the molecule to be represented by the node\n :param config: the configuration of the search\n :param parent: the parent of the node, optional\n \"\"\"\n\n def __init__(\n self,\n mol: TreeMolecule,\n config: Configuration,\n parent: Optional[ReactionNode] = None,\n ) -> None:\n self.mol = mol\n self._config = config\n self.in_stock = mol in config.stock\n self.parent = parent\n\n self._children: List[ReactionNode] = []\n # Makes it unexpandable if we have reached maximum depth\n self.expandable = self.mol.transform < self._config.search.max_transforms\n\n if self.in_stock:\n self.expandable = False\n\n @classmethod\n def create_root(cls, smiles: str, config: Configuration) -> \"MoleculeNode\":\n \"\"\"\n Create a root node for a tree using a SMILES.\n\n :param smiles: the SMILES representation of the root state\n :param config: settings of the tree search algorithm\n :return: the created node\n \"\"\"\n mol = TreeMolecule(parent=None, transform=0, smiles=smiles)\n return MoleculeNode(mol=mol, config=config)\n\n @classmethod\n def from_dict(\n cls,\n dict_: StrDict,\n config: Configuration,\n molecules: MoleculeDeserializer,\n parent: Optional[ReactionNode] = None,\n ) -> \"MoleculeNode\":\n \"\"\"\n Create a new node from a dictionary, i.e. deserialization\n\n :param dict_: the serialized node\n :param config: settings of the tree search algorithm\n :param molecules: the deserialized molecules\n :param parent: the parent node\n :return: a deserialized node\n \"\"\"\n mol = molecules.get_tree_molecules([dict_[\"mol\"]])[0]\n node = MoleculeNode(mol, config, parent)\n node.expandable = dict_[\"expandable\"]\n node.children = [\n ReactionNode.from_dict(child, config, molecules, parent=node)\n for child in dict_[\"children\"]\n ]\n return node\n\n @property # type: ignore\n def children(self) -> List[ReactionNode]: # type: ignore\n \"\"\"Gives the reaction children nodes\"\"\"\n return self._children\n\n @children.setter\n def children(self, value: List[ReactionNode]) -> None:\n self._children = value\n\n @property\n def prop(self) -> StrDict:\n return {\"solved\": self.in_stock, \"mol\": self.mol}\n\n def add_stub(self, reaction: RetroReaction) -> Sequence[MoleculeNode]:\n \"\"\"\n Add a stub / sub-tree to this node\n\n :param reaction: the reaction creating the stub\n :return: list of all newly added molecular nodes\n \"\"\"\n reactants = reaction.reactants[reaction.index]\n if not reactants:\n return []\n\n ancestors = self.ancestors()\n for mol in reactants:\n if mol in ancestors:\n return []\n\n rxn_node = ReactionNode.create_stub(\n reaction=reaction, parent=self, config=self._config\n )\n self._children.append(rxn_node)\n\n return rxn_node.children\n\n def ancestors(self) -> Set[TreeMolecule]:\n \"\"\"\n Return the ancestors of this node\n\n :return: the ancestors\n :rtype: set\n \"\"\"\n if not self.parent:\n return {self.mol}\n\n ancestors = self.parent.parent.ancestors()\n ancestors.add(self.mol)\n return ancestors\n\n def serialize(self, molecule_store: MoleculeSerializer) -> StrDict:\n \"\"\"\n Serialize the node object to a dictionary\n\n :param molecule_store: the serialized molecules\n :return: the serialized node\n \"\"\"\n dict_: StrDict = {\"expandable\": self.expandable}\n dict_[\"mol\"] = molecule_store[self.mol]\n dict_[\"children\"] = [child.serialize(molecule_store) for child in self.children]\n return dict_\n\n\n# Source: aizynthfinder/chem/serialization.py\nclass MoleculeSerializer:\n \"\"\"\n Utility class for serializing molecules\n\n The id of the molecule to be serialized can be obtained with:\n\n .. code-block::\n\n serializer = MoleculeSerializer()\n mol = Molecule(smiles=\"CCCO\")\n idx = serializer[mol]\n\n which will take care of the serialization of the molecule.\n \"\"\"\n\n def __init__(self) -> None:\n self._store: Dict[int, Any] = {}\n\n def __getitem__(self, mol: Optional[aizynthfinder.chem.Molecule]) -> Optional[int]:\n if mol is None:\n return None\n\n id_ = id(mol)\n if id_ not in self._store:\n self._add_mol(mol)\n return id_\n\n @property\n def store(self) -> Dict[int, Any]:\n \"\"\"Return all serialized molecules as a dictionary\"\"\"\n return self._store\n\n def _add_mol(self, mol: aizynthfinder.chem.Molecule) -> None:\n id_ = id(mol)\n dict_ = {\"smiles\": mol.smiles, \"class\": mol.__class__.__name__}\n if isinstance(mol, aizynthfinder.chem.TreeMolecule):\n dict_[\"parent\"] = self[mol.parent]\n dict_[\"transform\"] = mol.transform\n if not mol.parent:\n dict_[\"smiles\"] = mol.original_smiles\n else:\n dict_[\"smiles\"] = mol.mapped_smiles\n self._store[id_] = dict_\n\nclass MoleculeDeserializer:\n \"\"\"\n Utility class for deserializing molecules.\n The serialized molecules are created upon instantiation of the class.\n\n The deserialized molecules can be obtained with:\n\n .. code-block::\n\n deserializer = MoleculeDeserializer()\n mol = deserializer[idx]\n\n \"\"\"\n\n def __init__(self, store: Dict[int, Any]) -> None:\n self._objects: Dict[int, Any] = {}\n self._create_molecules(store)\n\n def __getitem__(self, id_: Optional[int]) -> Optional[aizynthfinder.chem.Molecule]:\n if id_ is None:\n return None\n return self._objects[id_]\n\n def get_tree_molecules(\n self, ids: Sequence[int]\n ) -> Sequence[aizynthfinder.chem.TreeMolecule]:\n \"\"\"\n Return multiple deserialized tree molecules\n\n :param ids: the list of IDs to deserialize\n :return: the molecule objects\n \"\"\"\n objects = []\n for id_ in ids:\n obj = self[id_]\n if obj is None or not isinstance(obj, aizynthfinder.chem.TreeMolecule):\n raise ValueError(f\"Failed to deserialize molecule with id {id_}\")\n objects.append(obj)\n return objects\n\n def _create_molecules(self, store: dict) -> None:\n for id_, spec in store.items():\n if isinstance(id_, str):\n id_ = int(id_)\n\n cls = spec[\"class\"]\n if \"parent\" in spec:\n spec[\"parent\"] = self[spec[\"parent\"]]\n\n kwargs = dict(spec)\n del kwargs[\"class\"]\n self._objects[id_] = getattr(aizynthfinder.chem, cls)(**kwargs)", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 7265}, "tests/chem/test_reaction.py::122": {"resolved_imports": ["aizynthfinder/chem/__init__.py"], "used_names": ["FixedRetroReaction", "UniqueMolecule"], "enclosing_function": "test_create_fixed_reaction", "extracted_code": "# Source: aizynthfinder/chem/__init__.py\n MoleculeException,\n TreeMolecule,\n UniqueMolecule,\n none_molecule,\n)\nfrom aizynthfinder.chem.reaction import (\n FixedRetroReaction,\n RetroReaction,\n SmilesBasedRetroReaction,\n TemplatedRetroReaction,\n hash_reactions,\n)\n\n)\nfrom aizynthfinder.chem.reaction import (\n FixedRetroReaction,\n RetroReaction,\n SmilesBasedRetroReaction,\n TemplatedRetroReaction,\n hash_reactions,\n)\nfrom aizynthfinder.chem.serialization import (\n MoleculeDeserializer,\n MoleculeSerializer,\n deserialize_action,", "n_imports_parsed": 1, "n_files_resolved": 1, "n_chars_extracted": 576}, "tests/utils/test_file_utils.py::62": {"resolved_imports": ["aizynthfinder/utils/files.py"], "used_names": ["os", "split_file"], "enclosing_function": "test_split_file_odd", "extracted_code": "# Source: aizynthfinder/utils/files.py\ndef split_file(filename: str, nparts: int) -> List[str]:\n \"\"\"\n Split the content of a text file into a given number of temporary files\n\n :param filename: the path to the file to split\n :param nparts: the number of parts to create\n :return: list of filenames of the parts\n \"\"\"\n with open(filename, \"r\") as fileobj:\n lines = fileobj.read().splitlines()\n\n filenames = []\n batch_size, remainder = divmod(len(lines), nparts)\n stop = 0\n for part in range(1, nparts + 1):\n start = stop\n stop += batch_size + 1 if part <= remainder else batch_size\n filenames.append(tempfile.mktemp())\n with open(filenames[-1], \"w\") as fileobj:\n fileobj.write(\"\\n\".join(lines[start:stop]))\n return filenames", "n_imports_parsed": 6, "n_files_resolved": 1, "n_chars_extracted": 803}, "tests/context/test_stock.py::37": {"resolved_imports": ["aizynthfinder/chem/__init__.py", "aizynthfinder/context/stock/__init__.py", "aizynthfinder/context/stock/queries.py", "aizynthfinder/tools/make_stock.py"], "used_names": [], "enclosing_function": "test_load_csv_stock", "extracted_code": "", "n_imports_parsed": 7, "n_files_resolved": 4, "n_chars_extracted": 0}, "tests/chem/test_reaction.py::199": {"resolved_imports": ["aizynthfinder/chem/__init__.py"], "used_names": ["SmilesBasedRetroReaction", "TreeMolecule"], "enclosing_function": "test_mapped_atom_bonds", "extracted_code": "# Source: aizynthfinder/chem/__init__.py\n Molecule,\n MoleculeException,\n TreeMolecule,\n UniqueMolecule,\n none_molecule,\n)\nfrom aizynthfinder.chem.reaction import (\n FixedRetroReaction,\n RetroReaction,\n SmilesBasedRetroReaction,\n TemplatedRetroReaction,\n hash_reactions,\n\n FixedRetroReaction,\n RetroReaction,\n SmilesBasedRetroReaction,\n TemplatedRetroReaction,\n hash_reactions,\n)\nfrom aizynthfinder.chem.serialization import (\n MoleculeDeserializer,\n MoleculeSerializer,\n deserialize_action,\n serialize_action,\n)", "n_imports_parsed": 1, "n_files_resolved": 1, "n_chars_extracted": 568}, "tests/chem/test_reaction.py::168": {"resolved_imports": ["aizynthfinder/chem/__init__.py"], "used_names": ["FixedRetroReaction", "SmilesBasedRetroReaction", "UniqueMolecule"], "enclosing_function": "test_fixed_retroreaction_to_smiles_based_retroreaction_no_metadata", "extracted_code": "# Source: aizynthfinder/chem/__init__.py\n MoleculeException,\n TreeMolecule,\n UniqueMolecule,\n none_molecule,\n)\nfrom aizynthfinder.chem.reaction import (\n FixedRetroReaction,\n RetroReaction,\n SmilesBasedRetroReaction,\n TemplatedRetroReaction,\n hash_reactions,\n)\n\n)\nfrom aizynthfinder.chem.reaction import (\n FixedRetroReaction,\n RetroReaction,\n SmilesBasedRetroReaction,\n TemplatedRetroReaction,\n hash_reactions,\n)\nfrom aizynthfinder.chem.serialization import (\n MoleculeDeserializer,\n MoleculeSerializer,\n deserialize_action,\n\n FixedRetroReaction,\n RetroReaction,\n SmilesBasedRetroReaction,\n TemplatedRetroReaction,\n hash_reactions,\n)\nfrom aizynthfinder.chem.serialization import (\n MoleculeDeserializer,\n MoleculeSerializer,\n deserialize_action,\n serialize_action,\n)", "n_imports_parsed": 1, "n_files_resolved": 1, "n_chars_extracted": 845}, "tests/mcts/test_multiobjective.py::72": {"resolved_imports": ["aizynthfinder/search/mcts/node.py", "aizynthfinder/search/mcts/__init__.py"], "used_names": [], "enclosing_function": "test_backpropagate", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/context/test_expansion_strategies.py::195": {"resolved_imports": ["aizynthfinder/chem/__init__.py", "aizynthfinder/context/policy/__init__.py", "aizynthfinder/utils/exceptions.py"], "used_names": ["TemplateBasedExpansionStrategy"], "enclosing_function": "test_load_templated_expansion_strategy_from_csv", "extracted_code": "# Source: aizynthfinder/context/policy/__init__.py\n MultiExpansionStrategy,\n TemplateBasedDirectExpansionStrategy,\n TemplateBasedExpansionStrategy,\n)\nfrom aizynthfinder.context.policy.filter_strategies import (\n BondFilter,\n FilterStrategy,\n FrozenSubstructureFilter,\n QuickKerasFilter,\n ReactantsCountFilter,\n)\nfrom aizynthfinder.context.policy.policies import ExpansionPolicy, FilterPolicy", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 415}, "tests/test_analysis.py::62": {"resolved_imports": ["aizynthfinder/analysis/__init__.py", "aizynthfinder/analysis/routes.py", "aizynthfinder/analysis/utils.py", "aizynthfinder/reactiontree.py", "aizynthfinder/search/mcts/__init__.py", "aizynthfinder/context/scoring/__init__.py"], "used_names": ["NumberOfReactionsScorer"], "enclosing_function": "test_sort_nodes_scorer", "extracted_code": "# Source: aizynthfinder/context/scoring/__init__.py\n AverageTemplateOccurrenceScorer,\n MaxTransformScorer,\n NumberOfReactionsScorer,\n ReactionClassMembershipScorer,\n ReactionClassRankScorer,\n)\nfrom aizynthfinder.utils.exceptions import ScorerException", "n_imports_parsed": 10, "n_files_resolved": 6, "n_chars_extracted": 266}, "tests/retrostar/test_retrostar_nodes.py::136": {"resolved_imports": ["aizynthfinder/search/retrostar/nodes.py", "aizynthfinder/chem/serialization.py", "aizynthfinder/search/andor_trees.py"], "used_names": ["ReactionTreeFromAndOrTrace"], "enclosing_function": "test_conversion_to_reaction_tree", "extracted_code": "# Source: aizynthfinder/search/andor_trees.py\nclass ReactionTreeFromAndOrTrace(ReactionTreeLoader):\n \"\"\"Creates a reaction tree object from an AND/OR Trace\"\"\"\n\n def _load(self, andor_trace: nx.DiGraph, stock: Stock) -> None: # type: ignore\n \"\"\"\n :param andor_trace: the trace graph\n :param stock: stock object\n \"\"\"\n self._stock = stock\n self._trace_graph = andor_trace\n self._trace_root = self._find_root()\n\n self._add_node(\n self._unique_mol(self._trace_root.prop[\"mol\"]),\n depth=0,\n transform=0,\n in_stock=self._trace_root.prop[\"mol\"] in self._stock,\n )\n for node1, node2 in andor_trace.edges():\n if \"reaction\" in node2.prop and not andor_trace[node2]:\n continue\n rt_node1 = self._make_rt_node(node1)\n rt_node2 = self._make_rt_node(node2)\n self.tree.graph.add_edge(rt_node1, rt_node2)\n\n def _add_node_with_depth(\n self, node: Union[UniqueMolecule, FixedRetroReaction], base_node: TreeNodeMixin\n ) -> None:\n if node in self.tree.graph:\n return\n\n depth = nx.shortest_path_length(self._trace_graph, self._trace_root, base_node)\n if isinstance(node, UniqueMolecule):\n self._add_node(\n node, depth=depth, transform=depth // 2, in_stock=node in self._stock\n )\n else:\n self._add_node(node, depth=depth)\n\n def _find_root(self) -> TreeNodeMixin:\n for node, degree in self._trace_graph.in_degree(): # type: ignore\n if degree == 0:\n return node\n raise ValueError(\"Could not find root!\")\n\n def _make_rt_node(\n self, node: TreeNodeMixin\n ) -> Union[UniqueMolecule, FixedRetroReaction]:\n if \"mol\" in node.prop:\n unique_obj = self._unique_mol(node.prop[\"mol\"])\n self._add_node_with_depth(unique_obj, node)\n return unique_obj\n\n reaction_obj = self._unique_reaction(node.prop[\"reaction\"])\n reaction_obj.reactants = (\n tuple(self._unique_mol(child.prop[\"mol\"]) for child in node.children),\n )\n self._add_node_with_depth(reaction_obj, node)\n return reaction_obj", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 2267}, "tests/context/test_collection.py::23": {"resolved_imports": ["aizynthfinder/context/collection.py"], "used_names": [], "enclosing_function": "test_empty_collection", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/mcts/test_serialization.py::16": {"resolved_imports": ["aizynthfinder/chem/__init__.py", "aizynthfinder/chem/serialization.py", "aizynthfinder/search/mcts/__init__.py"], "used_names": ["MctsNode", "MctsState", "MoleculeDeserializer", "MoleculeSerializer", "TreeMolecule"], "enclosing_function": "test_serialize_deserialize_state", "extracted_code": "# Source: aizynthfinder/chem/__init__.py\n Molecule,\n MoleculeException,\n TreeMolecule,\n UniqueMolecule,\n none_molecule,\n)\nfrom aizynthfinder.chem.reaction import (\n FixedRetroReaction,\n RetroReaction,\n SmilesBasedRetroReaction,\n TemplatedRetroReaction,\n hash_reactions,\n\n\n# Source: aizynthfinder/chem/serialization.py\nclass MoleculeSerializer:\n \"\"\"\n Utility class for serializing molecules\n\n The id of the molecule to be serialized can be obtained with:\n\n .. code-block::\n\n serializer = MoleculeSerializer()\n mol = Molecule(smiles=\"CCCO\")\n idx = serializer[mol]\n\n which will take care of the serialization of the molecule.\n \"\"\"\n\n def __init__(self) -> None:\n self._store: Dict[int, Any] = {}\n\n def __getitem__(self, mol: Optional[aizynthfinder.chem.Molecule]) -> Optional[int]:\n if mol is None:\n return None\n\n id_ = id(mol)\n if id_ not in self._store:\n self._add_mol(mol)\n return id_\n\n @property\n def store(self) -> Dict[int, Any]:\n \"\"\"Return all serialized molecules as a dictionary\"\"\"\n return self._store\n\n def _add_mol(self, mol: aizynthfinder.chem.Molecule) -> None:\n id_ = id(mol)\n dict_ = {\"smiles\": mol.smiles, \"class\": mol.__class__.__name__}\n if isinstance(mol, aizynthfinder.chem.TreeMolecule):\n dict_[\"parent\"] = self[mol.parent]\n dict_[\"transform\"] = mol.transform\n if not mol.parent:\n dict_[\"smiles\"] = mol.original_smiles\n else:\n dict_[\"smiles\"] = mol.mapped_smiles\n self._store[id_] = dict_\n\nclass MoleculeDeserializer:\n \"\"\"\n Utility class for deserializing molecules.\n The serialized molecules are created upon instantiation of the class.\n\n The deserialized molecules can be obtained with:\n\n .. code-block::\n\n deserializer = MoleculeDeserializer()\n mol = deserializer[idx]\n\n \"\"\"\n\n def __init__(self, store: Dict[int, Any]) -> None:\n self._objects: Dict[int, Any] = {}\n self._create_molecules(store)\n\n def __getitem__(self, id_: Optional[int]) -> Optional[aizynthfinder.chem.Molecule]:\n if id_ is None:\n return None\n return self._objects[id_]\n\n def get_tree_molecules(\n self, ids: Sequence[int]\n ) -> Sequence[aizynthfinder.chem.TreeMolecule]:\n \"\"\"\n Return multiple deserialized tree molecules\n\n :param ids: the list of IDs to deserialize\n :return: the molecule objects\n \"\"\"\n objects = []\n for id_ in ids:\n obj = self[id_]\n if obj is None or not isinstance(obj, aizynthfinder.chem.TreeMolecule):\n raise ValueError(f\"Failed to deserialize molecule with id {id_}\")\n objects.append(obj)\n return objects\n\n def _create_molecules(self, store: dict) -> None:\n for id_, spec in store.items():\n if isinstance(id_, str):\n id_ = int(id_)\n\n cls = spec[\"class\"]\n if \"parent\" in spec:\n spec[\"parent\"] = self[spec[\"parent\"]]\n\n kwargs = dict(spec)\n del kwargs[\"class\"]\n self._objects[id_] = getattr(aizynthfinder.chem, cls)(**kwargs)\n\n\n# Source: aizynthfinder/search/mcts/__init__.py\n\"\"\" Sub-package containing MCTS routines\n\"\"\"\nfrom aizynthfinder.search.mcts.node import MctsNode\nfrom aizynthfinder.search.mcts.search import MctsSearchTree\nfrom aizynthfinder.search.mcts.state import MctsState\n\nfrom aizynthfinder.search.mcts.node import MctsNode\nfrom aizynthfinder.search.mcts.search import MctsSearchTree\nfrom aizynthfinder.search.mcts.state import MctsState", "n_imports_parsed": 3, "n_files_resolved": 3, "n_chars_extracted": 3717}, "tests/mcts/test_reward.py::84": {"resolved_imports": ["aizynthfinder/analysis/__init__.py", "aizynthfinder/context/scoring/__init__.py", "aizynthfinder/search/mcts/__init__.py"], "used_names": ["NumberOfReactionsScorer", "StateScorer", "TreeAnalysis"], "enclosing_function": "test_custom_reward", "extracted_code": "# Source: aizynthfinder/analysis/__init__.py\n\"\"\" Sub-package containing analysis routines\n\"\"\"\nfrom aizynthfinder.analysis.tree_analysis import TreeAnalysis # isort: skip\nfrom aizynthfinder.analysis.routes import RouteCollection\nfrom aizynthfinder.analysis.utils import RouteSelectionArguments\n\n\n# Source: aizynthfinder/context/scoring/__init__.py\n RouteCostScorer,\n RouteSimilarityScorer,\n StateScorer,\n)\nfrom aizynthfinder.context.scoring.scorers_base import Scorer\nfrom aizynthfinder.context.scoring.scorers_mols import (\n DeltaSyntheticComplexityScorer,\n FractionInSourceStockScorer,\n FractionInStockScorer,\n FractionOfIntermediatesInStockScorer,\n NumberOfPrecursorsInStockScorer,\n NumberOfPrecursorsScorer,\n\n AverageTemplateOccurrenceScorer,\n MaxTransformScorer,\n NumberOfReactionsScorer,\n ReactionClassMembershipScorer,\n ReactionClassRankScorer,\n)\nfrom aizynthfinder.utils.exceptions import ScorerException", "n_imports_parsed": 3, "n_files_resolved": 3, "n_chars_extracted": 954}, "tests/retrostar/test_retrostar.py::65": {"resolved_imports": ["aizynthfinder/search/retrostar/search_tree.py", "aizynthfinder/chem/serialization.py"], "used_names": [], "enclosing_function": "test_one_expansion_with_finder", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/mcts/test_multiobjective.py::44": {"resolved_imports": ["aizynthfinder/search/mcts/node.py", "aizynthfinder/search/mcts/__init__.py"], "used_names": [], "enclosing_function": "test_expand_root_node", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/mcts/test_tree.py::37": {"resolved_imports": [], "used_names": [], "enclosing_function": "test_route_to_node", "extracted_code": "", "n_imports_parsed": 0, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/context/test_mcts_config.py::45": {"resolved_imports": ["aizynthfinder/aizynthfinder.py", "aizynthfinder/context/config.py", "aizynthfinder/context/stock/__init__.py"], "used_names": ["Configuration"], "enclosing_function": "test_load_from_file", "extracted_code": "# Source: aizynthfinder/context/config.py\nclass Configuration:\n \"\"\"\n Encapsulating the settings of the tree search, including the policy,\n the stock, the loaded scorers and various parameters.\n \"\"\"\n\n search: _SearchConfiguration = field(default_factory=_SearchConfiguration)\n post_processing: _PostprocessingConfiguration = field(\n default_factory=_PostprocessingConfiguration\n )\n stock: Stock = field(init=False)\n expansion_policy: ExpansionPolicy = field(init=False)\n filter_policy: FilterPolicy = field(init=False)\n scorers: ScorerCollection = field(init=False)\n\n def __post_init__(self) -> None:\n self.stock = Stock()\n self.expansion_policy = ExpansionPolicy(self)\n self.filter_policy = FilterPolicy(self)\n self.scorers = ScorerCollection(self)\n self._logger = logger()\n\n def __eq__(self, other: Any) -> bool:\n if not isinstance(other, Configuration):\n return False\n for key, setting in vars(self).items():\n if isinstance(setting, (int, float, str, bool, list)):\n if (\n vars(self)[key] != vars(other)[key]\n or self.search != other.search\n or self.post_processing != other.post_processing\n ):\n return False\n return True\n\n @classmethod\n def from_dict(cls, source: StrDict) -> \"Configuration\":\n \"\"\"\n Loads a configuration from a dictionary structure.\n The parameters not set in the dictionary are taken from the default values.\n The policies and stocks specified are directly loaded.\n\n :param source: the dictionary source\n :return: a Configuration object with settings from the source\n \"\"\"\n expansion_config = source.pop(\"expansion\", {})\n filter_config = source.pop(\"filter\", {})\n stock_config = source.pop(\"stock\", {})\n scorer_config = source.pop(\"scorer\", {})\n\n config_obj = Configuration()\n config_obj._update_from_config(dict(source))\n\n config_obj.expansion_policy.load_from_config(**expansion_config)\n config_obj.filter_policy.load_from_config(**filter_config)\n config_obj.stock.load_from_config(**stock_config)\n config_obj.scorers.create_default_scorers()\n config_obj.scorers.load_from_config(**scorer_config)\n\n return config_obj\n\n @classmethod\n def from_file(cls, filename: str) -> \"Configuration\":\n \"\"\"\n Loads a configuration from a yaml file.\n The parameters not set in the yaml file are taken from the default values.\n The policies and stocks specified in the yaml file are directly loaded.\n The parameters in the yaml file may also contain environment variables as\n values.\n\n :param filename: the path to a yaml file\n :return: a Configuration object with settings from the yaml file\n :raises:\n ValueError: if parameter's value expects an environment variable that\n does not exist in the current environment\n \"\"\"\n with open(filename, \"r\") as fileobj:\n txt = fileobj.read()\n environ_var = re.findall(r\"\\$\\{.+?\\}\", txt)\n for item in environ_var:\n if item[2:-1] not in os.environ:\n raise ValueError(f\"'{item[2:-1]}' not in environment variables\")\n txt = txt.replace(item, os.environ[item[2:-1]])\n _config = yaml.load(txt, Loader=yaml.SafeLoader)\n return Configuration.from_dict(_config)\n\n def _update_from_config(self, config: StrDict) -> None:\n self.post_processing = _PostprocessingConfiguration(\n **config.pop(\"post_processing\", {})\n )\n\n search_config = config.pop(\"search\", {})\n for setting, value in search_config.items():\n if value is None:\n continue\n if not hasattr(self.search, setting):\n raise AttributeError(f\"Could not find attribute to set: {setting}\")\n if setting.endswith(\"_bonds\"):\n if not isinstance(value, list):\n raise ValueError(\"Bond settings need to be lists\")\n value = _handle_bond_pair_tuples(value) if value else []\n if setting == \"algorithm_config\":\n if not isinstance(value, dict):\n raise ValueError(\"algorithm_config settings need to be dictionary\")\n self.search.algorithm_config.update(value)\n else:\n setattr(self.search, setting, value)", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 4568}, "tests/mcts/test_node.py::78": {"resolved_imports": [], "used_names": [], "enclosing_function": "test_promising_child_of_root", "extracted_code": "", "n_imports_parsed": 0, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/mcts/test_multiobjective.py::40": {"resolved_imports": ["aizynthfinder/search/mcts/node.py", "aizynthfinder/search/mcts/__init__.py"], "used_names": [], "enclosing_function": "test_expand_root_node", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/context/test_collection.py::166": {"resolved_imports": ["aizynthfinder/context/collection.py"], "used_names": [], "enclosing_function": "test_empty_single_collection", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/breadth_first/test_search.py::70": {"resolved_imports": ["aizynthfinder/search/breadth_first/search_tree.py"], "used_names": ["SearchTree", "pytest"], "enclosing_function": "test_search_incomplete", "extracted_code": "# Source: aizynthfinder/search/breadth_first/search_tree.py\nclass SearchTree(AndOrSearchTreeBase):\n \"\"\"\n Encapsulation of the a breadth-first exhaustive search algorithm\n\n :ivar config: settings of the tree search algorithm\n :ivar root: the root node\n\n :param config: settings of the tree search algorithm\n :param root_smiles: the root will be set to a node representing this molecule, defaults to None\n \"\"\"\n\n def __init__(\n self, config: Configuration, root_smiles: Optional[str] = None\n ) -> None:\n super().__init__(config, root_smiles)\n self._mol_nodes: List[MoleculeNode] = []\n self._added_mol_nodes: List[MoleculeNode] = []\n self._logger = logger()\n\n if root_smiles:\n self.root: Optional[MoleculeNode] = MoleculeNode.create_root(\n root_smiles, config\n )\n self._mol_nodes.append(self.root)\n else:\n self.root = None\n\n self._routes: List[ReactionTree] = []\n\n self.profiling = {\n \"expansion_calls\": 0,\n \"reactants_generations\": 0,\n }\n\n @classmethod\n def from_json(cls, filename: str, config: Configuration) -> SearchTree:\n \"\"\"\n Create a new search tree by deserialization from a JSON file\n\n :param filename: the path to the JSON node\n :param config: the configuration of the search tree\n :return: a deserialized tree\n \"\"\"\n\n def _find_mol_nodes(node):\n for child_ in node.children:\n tree._mol_nodes.append(child_) # pylint: disable=protected-access\n for grandchild in child_.children:\n _find_mol_nodes(grandchild)\n\n tree = cls(config)\n with open(filename, \"r\") as fileobj:\n dict_ = json.load(fileobj)\n mol_deser = MoleculeDeserializer(dict_[\"molecules\"])\n tree.root = MoleculeNode.from_dict(dict_[\"tree\"], config, mol_deser)\n tree._mol_nodes.append(tree.root) # pylint: disable=protected-access\n for child in tree.root.children:\n _find_mol_nodes(child)\n return tree\n\n @property\n def mol_nodes(self) -> Sequence[MoleculeNode]: # type: ignore\n \"\"\"Return the molecule nodes of the tree\"\"\"\n return self._mol_nodes\n\n def one_iteration(self) -> bool:\n \"\"\"\n Perform one iteration expansion.\n Expands all expandable molecule nodes in the tree, which should be\n on the same depth of the tree.\n\n :raises StopIteration: if the search should be pre-maturely terminated\n :return: if a solution was found\n :rtype: bool\n \"\"\"\n if self.root is None:\n raise ValueError(\"Root is undefined. Cannot make an iteration\")\n\n self._routes = []\n self._added_mol_nodes = []\n\n for next_node in self._mol_nodes:\n if next_node.expandable:\n self._expand(next_node)\n\n if not self._added_mol_nodes:\n self._logger.debug(\"No new nodes added in breadth-first iteration\")\n raise StopIteration\n\n self._mol_nodes.extend(self._added_mol_nodes)\n solved = all(node.in_stock for node in self._mol_nodes if not node.children)\n return solved\n\n def routes(self) -> List[ReactionTree]:\n \"\"\"\n Extracts and returns routes from the AND/OR tree\n\n :return: the routes\n \"\"\"\n if self.root is None:\n return []\n if not self._routes:\n self._routes = SplitAndOrTree(self.root, self.config.stock).routes\n return self._routes\n\n def serialize(self, filename: str) -> None:\n \"\"\"\n Seralize the search tree to a JSON file\n\n :param filename: the path to the JSON file\n :type filename: str\n \"\"\"\n if self.root is None:\n raise ValueError(\"Cannot serialize tree as root is not defined\")\n\n mol_ser = MoleculeSerializer()\n dict_ = {\"tree\": self.root.serialize(mol_ser), \"molecules\": mol_ser.store}\n with open(filename, \"w\") as fileobj:\n json.dump(dict_, fileobj, indent=2)\n\n def _expand(self, node: MoleculeNode) -> None:\n node.expandable = False\n reactions, _ = self.config.expansion_policy([node.mol])\n self.profiling[\"expansion_calls\"] += 1\n\n if not reactions:\n return\n\n reactions_to_expand = []\n for reaction in reactions:\n try:\n self.profiling[\"reactants_generations\"] += 1\n _ = reaction.reactants\n except: # pylint: disable=bare-except\n continue\n if not reaction.reactants:\n continue\n for idx, _ in enumerate(reaction.reactants):\n rxn_copy = reaction.copy(idx)\n reactions_to_expand.append(rxn_copy)\n\n for rxn in reactions_to_expand:\n new_nodes = node.add_stub(rxn)\n self._added_mol_nodes.extend(new_nodes)", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 4982}, "tests/mcts/test_serialization.py::110": {"resolved_imports": ["aizynthfinder/chem/__init__.py", "aizynthfinder/chem/serialization.py", "aizynthfinder/search/mcts/__init__.py"], "used_names": ["MctsNode", "MoleculeDeserializer", "MoleculeSerializer"], "enclosing_function": "test_deserialize_node", "extracted_code": "# Source: aizynthfinder/chem/serialization.py\nclass MoleculeSerializer:\n \"\"\"\n Utility class for serializing molecules\n\n The id of the molecule to be serialized can be obtained with:\n\n .. code-block::\n\n serializer = MoleculeSerializer()\n mol = Molecule(smiles=\"CCCO\")\n idx = serializer[mol]\n\n which will take care of the serialization of the molecule.\n \"\"\"\n\n def __init__(self) -> None:\n self._store: Dict[int, Any] = {}\n\n def __getitem__(self, mol: Optional[aizynthfinder.chem.Molecule]) -> Optional[int]:\n if mol is None:\n return None\n\n id_ = id(mol)\n if id_ not in self._store:\n self._add_mol(mol)\n return id_\n\n @property\n def store(self) -> Dict[int, Any]:\n \"\"\"Return all serialized molecules as a dictionary\"\"\"\n return self._store\n\n def _add_mol(self, mol: aizynthfinder.chem.Molecule) -> None:\n id_ = id(mol)\n dict_ = {\"smiles\": mol.smiles, \"class\": mol.__class__.__name__}\n if isinstance(mol, aizynthfinder.chem.TreeMolecule):\n dict_[\"parent\"] = self[mol.parent]\n dict_[\"transform\"] = mol.transform\n if not mol.parent:\n dict_[\"smiles\"] = mol.original_smiles\n else:\n dict_[\"smiles\"] = mol.mapped_smiles\n self._store[id_] = dict_\n\nclass MoleculeDeserializer:\n \"\"\"\n Utility class for deserializing molecules.\n The serialized molecules are created upon instantiation of the class.\n\n The deserialized molecules can be obtained with:\n\n .. code-block::\n\n deserializer = MoleculeDeserializer()\n mol = deserializer[idx]\n\n \"\"\"\n\n def __init__(self, store: Dict[int, Any]) -> None:\n self._objects: Dict[int, Any] = {}\n self._create_molecules(store)\n\n def __getitem__(self, id_: Optional[int]) -> Optional[aizynthfinder.chem.Molecule]:\n if id_ is None:\n return None\n return self._objects[id_]\n\n def get_tree_molecules(\n self, ids: Sequence[int]\n ) -> Sequence[aizynthfinder.chem.TreeMolecule]:\n \"\"\"\n Return multiple deserialized tree molecules\n\n :param ids: the list of IDs to deserialize\n :return: the molecule objects\n \"\"\"\n objects = []\n for id_ in ids:\n obj = self[id_]\n if obj is None or not isinstance(obj, aizynthfinder.chem.TreeMolecule):\n raise ValueError(f\"Failed to deserialize molecule with id {id_}\")\n objects.append(obj)\n return objects\n\n def _create_molecules(self, store: dict) -> None:\n for id_, spec in store.items():\n if isinstance(id_, str):\n id_ = int(id_)\n\n cls = spec[\"class\"]\n if \"parent\" in spec:\n spec[\"parent\"] = self[spec[\"parent\"]]\n\n kwargs = dict(spec)\n del kwargs[\"class\"]\n self._objects[id_] = getattr(aizynthfinder.chem, cls)(**kwargs)\n\n\n# Source: aizynthfinder/search/mcts/__init__.py\n\"\"\" Sub-package containing MCTS routines\n\"\"\"\nfrom aizynthfinder.search.mcts.node import MctsNode\nfrom aizynthfinder.search.mcts.search import MctsSearchTree\nfrom aizynthfinder.search.mcts.state import MctsState", "n_imports_parsed": 3, "n_files_resolved": 3, "n_chars_extracted": 3248}, "tests/context/test_collection.py::140": {"resolved_imports": ["aizynthfinder/context/collection.py"], "used_names": [], "enclosing_function": "test_deselect_all", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/utils/test_image.py::46": {"resolved_imports": ["aizynthfinder/utils/__init__.py", "aizynthfinder/utils/image.py", "aizynthfinder/chem/__init__.py"], "used_names": ["TarFile", "image", "os"], "enclosing_function": "test_visjs_page", "extracted_code": "", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 0}, "tests/utils/test_external_tf_models.py::125": {"resolved_imports": ["aizynthfinder/utils/models.py"], "used_names": ["ExternalModelViaREST", "SUPPORT_EXTERNAL_APIS", "pytest"], "enclosing_function": "test_predict_tf_rest_model", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/breadth_first/test_nodes.py::68": {"resolved_imports": ["aizynthfinder/search/breadth_first/nodes.py", "aizynthfinder/chem/serialization.py"], "used_names": ["MoleculeDeserializer", "MoleculeNode", "MoleculeSerializer"], "enclosing_function": "test_serialization_deserialization", "extracted_code": "# Source: aizynthfinder/search/breadth_first/nodes.py\nclass MoleculeNode(TreeNodeMixin):\n \"\"\"\n An OR node representing a molecule\n\n :ivar expandable: if True, this node is part of the frontier\n :ivar mol: the molecule represented by the node\n :ivar in_stock: if True the molecule is in stock and hence should not be expanded\n :ivar parent: the parent of the node\n\n :param mol: the molecule to be represented by the node\n :param config: the configuration of the search\n :param parent: the parent of the node, optional\n \"\"\"\n\n def __init__(\n self,\n mol: TreeMolecule,\n config: Configuration,\n parent: Optional[ReactionNode] = None,\n ) -> None:\n self.mol = mol\n self._config = config\n self.in_stock = mol in config.stock\n self.parent = parent\n\n self._children: List[ReactionNode] = []\n # Makes it unexpandable if we have reached maximum depth\n self.expandable = self.mol.transform < self._config.search.max_transforms\n\n if self.in_stock:\n self.expandable = False\n\n @classmethod\n def create_root(cls, smiles: str, config: Configuration) -> \"MoleculeNode\":\n \"\"\"\n Create a root node for a tree using a SMILES.\n\n :param smiles: the SMILES representation of the root state\n :param config: settings of the tree search algorithm\n :return: the created node\n \"\"\"\n mol = TreeMolecule(parent=None, transform=0, smiles=smiles)\n return MoleculeNode(mol=mol, config=config)\n\n @classmethod\n def from_dict(\n cls,\n dict_: StrDict,\n config: Configuration,\n molecules: MoleculeDeserializer,\n parent: Optional[ReactionNode] = None,\n ) -> \"MoleculeNode\":\n \"\"\"\n Create a new node from a dictionary, i.e. deserialization\n\n :param dict_: the serialized node\n :param config: settings of the tree search algorithm\n :param molecules: the deserialized molecules\n :param parent: the parent node\n :return: a deserialized node\n \"\"\"\n mol = molecules.get_tree_molecules([dict_[\"mol\"]])[0]\n node = MoleculeNode(mol, config, parent)\n node.expandable = dict_[\"expandable\"]\n node.children = [\n ReactionNode.from_dict(child, config, molecules, parent=node)\n for child in dict_[\"children\"]\n ]\n return node\n\n @property # type: ignore\n def children(self) -> List[ReactionNode]: # type: ignore\n \"\"\"Gives the reaction children nodes\"\"\"\n return self._children\n\n @children.setter\n def children(self, value: List[ReactionNode]) -> None:\n self._children = value\n\n @property\n def prop(self) -> StrDict:\n return {\"solved\": self.in_stock, \"mol\": self.mol}\n\n def add_stub(self, reaction: RetroReaction) -> Sequence[MoleculeNode]:\n \"\"\"\n Add a stub / sub-tree to this node\n\n :param reaction: the reaction creating the stub\n :return: list of all newly added molecular nodes\n \"\"\"\n reactants = reaction.reactants[reaction.index]\n if not reactants:\n return []\n\n ancestors = self.ancestors()\n for mol in reactants:\n if mol in ancestors:\n return []\n\n rxn_node = ReactionNode.create_stub(\n reaction=reaction, parent=self, config=self._config\n )\n self._children.append(rxn_node)\n\n return rxn_node.children\n\n def ancestors(self) -> Set[TreeMolecule]:\n \"\"\"\n Return the ancestors of this node\n\n :return: the ancestors\n :rtype: set\n \"\"\"\n if not self.parent:\n return {self.mol}\n\n ancestors = self.parent.parent.ancestors()\n ancestors.add(self.mol)\n return ancestors\n\n def serialize(self, molecule_store: MoleculeSerializer) -> StrDict:\n \"\"\"\n Serialize the node object to a dictionary\n\n :param molecule_store: the serialized molecules\n :return: the serialized node\n \"\"\"\n dict_: StrDict = {\"expandable\": self.expandable}\n dict_[\"mol\"] = molecule_store[self.mol]\n dict_[\"children\"] = [child.serialize(molecule_store) for child in self.children]\n return dict_\n\n\n# Source: aizynthfinder/chem/serialization.py\nclass MoleculeSerializer:\n \"\"\"\n Utility class for serializing molecules\n\n The id of the molecule to be serialized can be obtained with:\n\n .. code-block::\n\n serializer = MoleculeSerializer()\n mol = Molecule(smiles=\"CCCO\")\n idx = serializer[mol]\n\n which will take care of the serialization of the molecule.\n \"\"\"\n\n def __init__(self) -> None:\n self._store: Dict[int, Any] = {}\n\n def __getitem__(self, mol: Optional[aizynthfinder.chem.Molecule]) -> Optional[int]:\n if mol is None:\n return None\n\n id_ = id(mol)\n if id_ not in self._store:\n self._add_mol(mol)\n return id_\n\n @property\n def store(self) -> Dict[int, Any]:\n \"\"\"Return all serialized molecules as a dictionary\"\"\"\n return self._store\n\n def _add_mol(self, mol: aizynthfinder.chem.Molecule) -> None:\n id_ = id(mol)\n dict_ = {\"smiles\": mol.smiles, \"class\": mol.__class__.__name__}\n if isinstance(mol, aizynthfinder.chem.TreeMolecule):\n dict_[\"parent\"] = self[mol.parent]\n dict_[\"transform\"] = mol.transform\n if not mol.parent:\n dict_[\"smiles\"] = mol.original_smiles\n else:\n dict_[\"smiles\"] = mol.mapped_smiles\n self._store[id_] = dict_\n\nclass MoleculeDeserializer:\n \"\"\"\n Utility class for deserializing molecules.\n The serialized molecules are created upon instantiation of the class.\n\n The deserialized molecules can be obtained with:\n\n .. code-block::\n\n deserializer = MoleculeDeserializer()\n mol = deserializer[idx]\n\n \"\"\"\n\n def __init__(self, store: Dict[int, Any]) -> None:\n self._objects: Dict[int, Any] = {}\n self._create_molecules(store)\n\n def __getitem__(self, id_: Optional[int]) -> Optional[aizynthfinder.chem.Molecule]:\n if id_ is None:\n return None\n return self._objects[id_]\n\n def get_tree_molecules(\n self, ids: Sequence[int]\n ) -> Sequence[aizynthfinder.chem.TreeMolecule]:\n \"\"\"\n Return multiple deserialized tree molecules\n\n :param ids: the list of IDs to deserialize\n :return: the molecule objects\n \"\"\"\n objects = []\n for id_ in ids:\n obj = self[id_]\n if obj is None or not isinstance(obj, aizynthfinder.chem.TreeMolecule):\n raise ValueError(f\"Failed to deserialize molecule with id {id_}\")\n objects.append(obj)\n return objects\n\n def _create_molecules(self, store: dict) -> None:\n for id_, spec in store.items():\n if isinstance(id_, str):\n id_ = int(id_)\n\n cls = spec[\"class\"]\n if \"parent\" in spec:\n spec[\"parent\"] = self[spec[\"parent\"]]\n\n kwargs = dict(spec)\n del kwargs[\"class\"]\n self._objects[id_] = getattr(aizynthfinder.chem, cls)(**kwargs)", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 7265}, "tests/chem/test_reaction.py::16": {"resolved_imports": ["aizynthfinder/chem/__init__.py"], "used_names": [], "enclosing_function": "test_retro_reaction", "extracted_code": "", "n_imports_parsed": 1, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/mcts/test_serialization.py::15": {"resolved_imports": ["aizynthfinder/chem/__init__.py", "aizynthfinder/chem/serialization.py", "aizynthfinder/search/mcts/__init__.py"], "used_names": ["MctsNode", "MctsState", "MoleculeDeserializer", "MoleculeSerializer", "TreeMolecule"], "enclosing_function": "test_serialize_deserialize_state", "extracted_code": "# Source: aizynthfinder/chem/__init__.py\n Molecule,\n MoleculeException,\n TreeMolecule,\n UniqueMolecule,\n none_molecule,\n)\nfrom aizynthfinder.chem.reaction import (\n FixedRetroReaction,\n RetroReaction,\n SmilesBasedRetroReaction,\n TemplatedRetroReaction,\n hash_reactions,\n\n\n# Source: aizynthfinder/chem/serialization.py\nclass MoleculeSerializer:\n \"\"\"\n Utility class for serializing molecules\n\n The id of the molecule to be serialized can be obtained with:\n\n .. code-block::\n\n serializer = MoleculeSerializer()\n mol = Molecule(smiles=\"CCCO\")\n idx = serializer[mol]\n\n which will take care of the serialization of the molecule.\n \"\"\"\n\n def __init__(self) -> None:\n self._store: Dict[int, Any] = {}\n\n def __getitem__(self, mol: Optional[aizynthfinder.chem.Molecule]) -> Optional[int]:\n if mol is None:\n return None\n\n id_ = id(mol)\n if id_ not in self._store:\n self._add_mol(mol)\n return id_\n\n @property\n def store(self) -> Dict[int, Any]:\n \"\"\"Return all serialized molecules as a dictionary\"\"\"\n return self._store\n\n def _add_mol(self, mol: aizynthfinder.chem.Molecule) -> None:\n id_ = id(mol)\n dict_ = {\"smiles\": mol.smiles, \"class\": mol.__class__.__name__}\n if isinstance(mol, aizynthfinder.chem.TreeMolecule):\n dict_[\"parent\"] = self[mol.parent]\n dict_[\"transform\"] = mol.transform\n if not mol.parent:\n dict_[\"smiles\"] = mol.original_smiles\n else:\n dict_[\"smiles\"] = mol.mapped_smiles\n self._store[id_] = dict_\n\nclass MoleculeDeserializer:\n \"\"\"\n Utility class for deserializing molecules.\n The serialized molecules are created upon instantiation of the class.\n\n The deserialized molecules can be obtained with:\n\n .. code-block::\n\n deserializer = MoleculeDeserializer()\n mol = deserializer[idx]\n\n \"\"\"\n\n def __init__(self, store: Dict[int, Any]) -> None:\n self._objects: Dict[int, Any] = {}\n self._create_molecules(store)\n\n def __getitem__(self, id_: Optional[int]) -> Optional[aizynthfinder.chem.Molecule]:\n if id_ is None:\n return None\n return self._objects[id_]\n\n def get_tree_molecules(\n self, ids: Sequence[int]\n ) -> Sequence[aizynthfinder.chem.TreeMolecule]:\n \"\"\"\n Return multiple deserialized tree molecules\n\n :param ids: the list of IDs to deserialize\n :return: the molecule objects\n \"\"\"\n objects = []\n for id_ in ids:\n obj = self[id_]\n if obj is None or not isinstance(obj, aizynthfinder.chem.TreeMolecule):\n raise ValueError(f\"Failed to deserialize molecule with id {id_}\")\n objects.append(obj)\n return objects\n\n def _create_molecules(self, store: dict) -> None:\n for id_, spec in store.items():\n if isinstance(id_, str):\n id_ = int(id_)\n\n cls = spec[\"class\"]\n if \"parent\" in spec:\n spec[\"parent\"] = self[spec[\"parent\"]]\n\n kwargs = dict(spec)\n del kwargs[\"class\"]\n self._objects[id_] = getattr(aizynthfinder.chem, cls)(**kwargs)\n\n\n# Source: aizynthfinder/search/mcts/__init__.py\n\"\"\" Sub-package containing MCTS routines\n\"\"\"\nfrom aizynthfinder.search.mcts.node import MctsNode\nfrom aizynthfinder.search.mcts.search import MctsSearchTree\nfrom aizynthfinder.search.mcts.state import MctsState\n\nfrom aizynthfinder.search.mcts.node import MctsNode\nfrom aizynthfinder.search.mcts.search import MctsSearchTree\nfrom aizynthfinder.search.mcts.state import MctsState", "n_imports_parsed": 3, "n_files_resolved": 3, "n_chars_extracted": 3717}, "tests/mcts/test_tree.py::39": {"resolved_imports": [], "used_names": [], "enclosing_function": "test_route_to_node", "extracted_code": "", "n_imports_parsed": 0, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/context/test_collection.py::32": {"resolved_imports": ["aizynthfinder/context/collection.py"], "used_names": [], "enclosing_function": "test_add_single_item", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/test_reactiontree.py::65": {"resolved_imports": ["aizynthfinder/reactiontree.py"], "used_names": [], "enclosing_function": "test_route_node_depth_from_mcts", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/context/test_expansion_strategies.py::163": {"resolved_imports": ["aizynthfinder/chem/__init__.py", "aizynthfinder/context/policy/__init__.py", "aizynthfinder/utils/exceptions.py"], "used_names": [], "enclosing_function": "test_load_templated_expansion_strategy", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 0}, "tests/test_cli.py::164": {"resolved_imports": ["aizynthfinder/analysis/__init__.py", "aizynthfinder/chem/__init__.py", "aizynthfinder/interfaces/__init__.py", "aizynthfinder/interfaces/aizynthapp.py", "aizynthfinder/interfaces/aizynthcli.py", "aizynthfinder/reactiontree.py", "aizynthfinder/tools/cat_output.py", "aizynthfinder/tools/download_public_data.py", "aizynthfinder/tools/make_stock.py"], "used_names": [], "enclosing_function": "test_cli_single_smiles", "extracted_code": "", "n_imports_parsed": 17, "n_files_resolved": 9, "n_chars_extracted": 0}, "tests/context/test_score.py::99": {"resolved_imports": ["aizynthfinder/chem/__init__.py", "aizynthfinder/context/config.py", "aizynthfinder/context/scoring/__init__.py", "aizynthfinder/reactiontree.py", "aizynthfinder/search/mcts/__init__.py"], "used_names": ["AverageTemplateOccurrenceScorer"], "enclosing_function": "test_template_occurrence_scorer", "extracted_code": "# Source: aizynthfinder/context/scoring/__init__.py\n)\nfrom aizynthfinder.context.scoring.scorers_reactions import (\n AverageTemplateOccurrenceScorer,\n MaxTransformScorer,\n NumberOfReactionsScorer,\n ReactionClassMembershipScorer,\n ReactionClassRankScorer,\n)\nfrom aizynthfinder.utils.exceptions import ScorerException", "n_imports_parsed": 8, "n_files_resolved": 5, "n_chars_extracted": 330}, "tests/context/test_expansion_strategies.py::47": {"resolved_imports": ["aizynthfinder/chem/__init__.py", "aizynthfinder/context/policy/__init__.py", "aizynthfinder/utils/exceptions.py"], "used_names": ["MultiExpansionStrategy", "TreeMolecule"], "enclosing_function": "test_multi_expansion_strategy", "extracted_code": "# Source: aizynthfinder/chem/__init__.py\n Molecule,\n MoleculeException,\n TreeMolecule,\n UniqueMolecule,\n none_molecule,\n)\nfrom aizynthfinder.chem.reaction import (\n FixedRetroReaction,\n RetroReaction,\n SmilesBasedRetroReaction,\n TemplatedRetroReaction,\n hash_reactions,\n\n\n# Source: aizynthfinder/context/policy/__init__.py\nfrom aizynthfinder.context.policy.expansion_strategies import (\n ExpansionStrategy,\n MultiExpansionStrategy,\n TemplateBasedDirectExpansionStrategy,\n TemplateBasedExpansionStrategy,\n)\nfrom aizynthfinder.context.policy.filter_strategies import (\n BondFilter,\n FilterStrategy,\n FrozenSubstructureFilter,\n QuickKerasFilter,\n ReactantsCountFilter,", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 722}, "tests/context/test_collection.py::180": {"resolved_imports": ["aizynthfinder/context/collection.py"], "used_names": [], "enclosing_function": "test_select_single_collection", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/context/test_policy.py::118": {"resolved_imports": ["aizynthfinder/chem/__init__.py", "aizynthfinder/context/policy/__init__.py", "aizynthfinder/utils/exceptions.py"], "used_names": ["PolicyException", "TreeMolecule", "pytest"], "enclosing_function": "test_get_actions", "extracted_code": "# Source: aizynthfinder/chem/__init__.py\n Molecule,\n MoleculeException,\n TreeMolecule,\n UniqueMolecule,\n none_molecule,\n)\nfrom aizynthfinder.chem.reaction import (\n FixedRetroReaction,\n RetroReaction,\n SmilesBasedRetroReaction,\n TemplatedRetroReaction,\n hash_reactions,\n\n\n# Source: aizynthfinder/utils/exceptions.py\nclass PolicyException(Exception):\n \"\"\"An exception raised by policy classes\"\"\"", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 427}, "tests/test_reactiontree.py::62": {"resolved_imports": ["aizynthfinder/reactiontree.py"], "used_names": [], "enclosing_function": "test_route_node_depth_from_mcts", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/mcts/test_serialization.py::26": {"resolved_imports": ["aizynthfinder/chem/__init__.py", "aizynthfinder/chem/serialization.py", "aizynthfinder/search/mcts/__init__.py"], "used_names": ["MctsNode", "MctsState", "MoleculeDeserializer", "MoleculeSerializer", "TreeMolecule"], "enclosing_function": "test_serialize_deserialize_state", "extracted_code": "# Source: aizynthfinder/chem/__init__.py\n Molecule,\n MoleculeException,\n TreeMolecule,\n UniqueMolecule,\n none_molecule,\n)\nfrom aizynthfinder.chem.reaction import (\n FixedRetroReaction,\n RetroReaction,\n SmilesBasedRetroReaction,\n TemplatedRetroReaction,\n hash_reactions,\n\n\n# Source: aizynthfinder/chem/serialization.py\nclass MoleculeSerializer:\n \"\"\"\n Utility class for serializing molecules\n\n The id of the molecule to be serialized can be obtained with:\n\n .. code-block::\n\n serializer = MoleculeSerializer()\n mol = Molecule(smiles=\"CCCO\")\n idx = serializer[mol]\n\n which will take care of the serialization of the molecule.\n \"\"\"\n\n def __init__(self) -> None:\n self._store: Dict[int, Any] = {}\n\n def __getitem__(self, mol: Optional[aizynthfinder.chem.Molecule]) -> Optional[int]:\n if mol is None:\n return None\n\n id_ = id(mol)\n if id_ not in self._store:\n self._add_mol(mol)\n return id_\n\n @property\n def store(self) -> Dict[int, Any]:\n \"\"\"Return all serialized molecules as a dictionary\"\"\"\n return self._store\n\n def _add_mol(self, mol: aizynthfinder.chem.Molecule) -> None:\n id_ = id(mol)\n dict_ = {\"smiles\": mol.smiles, \"class\": mol.__class__.__name__}\n if isinstance(mol, aizynthfinder.chem.TreeMolecule):\n dict_[\"parent\"] = self[mol.parent]\n dict_[\"transform\"] = mol.transform\n if not mol.parent:\n dict_[\"smiles\"] = mol.original_smiles\n else:\n dict_[\"smiles\"] = mol.mapped_smiles\n self._store[id_] = dict_\n\nclass MoleculeDeserializer:\n \"\"\"\n Utility class for deserializing molecules.\n The serialized molecules are created upon instantiation of the class.\n\n The deserialized molecules can be obtained with:\n\n .. code-block::\n\n deserializer = MoleculeDeserializer()\n mol = deserializer[idx]\n\n \"\"\"\n\n def __init__(self, store: Dict[int, Any]) -> None:\n self._objects: Dict[int, Any] = {}\n self._create_molecules(store)\n\n def __getitem__(self, id_: Optional[int]) -> Optional[aizynthfinder.chem.Molecule]:\n if id_ is None:\n return None\n return self._objects[id_]\n\n def get_tree_molecules(\n self, ids: Sequence[int]\n ) -> Sequence[aizynthfinder.chem.TreeMolecule]:\n \"\"\"\n Return multiple deserialized tree molecules\n\n :param ids: the list of IDs to deserialize\n :return: the molecule objects\n \"\"\"\n objects = []\n for id_ in ids:\n obj = self[id_]\n if obj is None or not isinstance(obj, aizynthfinder.chem.TreeMolecule):\n raise ValueError(f\"Failed to deserialize molecule with id {id_}\")\n objects.append(obj)\n return objects\n\n def _create_molecules(self, store: dict) -> None:\n for id_, spec in store.items():\n if isinstance(id_, str):\n id_ = int(id_)\n\n cls = spec[\"class\"]\n if \"parent\" in spec:\n spec[\"parent\"] = self[spec[\"parent\"]]\n\n kwargs = dict(spec)\n del kwargs[\"class\"]\n self._objects[id_] = getattr(aizynthfinder.chem, cls)(**kwargs)\n\n\n# Source: aizynthfinder/search/mcts/__init__.py\n\"\"\" Sub-package containing MCTS routines\n\"\"\"\nfrom aizynthfinder.search.mcts.node import MctsNode\nfrom aizynthfinder.search.mcts.search import MctsSearchTree\nfrom aizynthfinder.search.mcts.state import MctsState\n\nfrom aizynthfinder.search.mcts.node import MctsNode\nfrom aizynthfinder.search.mcts.search import MctsSearchTree\nfrom aizynthfinder.search.mcts.state import MctsState", "n_imports_parsed": 3, "n_files_resolved": 3, "n_chars_extracted": 3717}, "tests/breadth_first/test_nodes.py::71": {"resolved_imports": ["aizynthfinder/search/breadth_first/nodes.py", "aizynthfinder/chem/serialization.py"], "used_names": ["MoleculeDeserializer", "MoleculeNode", "MoleculeSerializer"], "enclosing_function": "test_serialization_deserialization", "extracted_code": "# Source: aizynthfinder/search/breadth_first/nodes.py\nclass MoleculeNode(TreeNodeMixin):\n \"\"\"\n An OR node representing a molecule\n\n :ivar expandable: if True, this node is part of the frontier\n :ivar mol: the molecule represented by the node\n :ivar in_stock: if True the molecule is in stock and hence should not be expanded\n :ivar parent: the parent of the node\n\n :param mol: the molecule to be represented by the node\n :param config: the configuration of the search\n :param parent: the parent of the node, optional\n \"\"\"\n\n def __init__(\n self,\n mol: TreeMolecule,\n config: Configuration,\n parent: Optional[ReactionNode] = None,\n ) -> None:\n self.mol = mol\n self._config = config\n self.in_stock = mol in config.stock\n self.parent = parent\n\n self._children: List[ReactionNode] = []\n # Makes it unexpandable if we have reached maximum depth\n self.expandable = self.mol.transform < self._config.search.max_transforms\n\n if self.in_stock:\n self.expandable = False\n\n @classmethod\n def create_root(cls, smiles: str, config: Configuration) -> \"MoleculeNode\":\n \"\"\"\n Create a root node for a tree using a SMILES.\n\n :param smiles: the SMILES representation of the root state\n :param config: settings of the tree search algorithm\n :return: the created node\n \"\"\"\n mol = TreeMolecule(parent=None, transform=0, smiles=smiles)\n return MoleculeNode(mol=mol, config=config)\n\n @classmethod\n def from_dict(\n cls,\n dict_: StrDict,\n config: Configuration,\n molecules: MoleculeDeserializer,\n parent: Optional[ReactionNode] = None,\n ) -> \"MoleculeNode\":\n \"\"\"\n Create a new node from a dictionary, i.e. deserialization\n\n :param dict_: the serialized node\n :param config: settings of the tree search algorithm\n :param molecules: the deserialized molecules\n :param parent: the parent node\n :return: a deserialized node\n \"\"\"\n mol = molecules.get_tree_molecules([dict_[\"mol\"]])[0]\n node = MoleculeNode(mol, config, parent)\n node.expandable = dict_[\"expandable\"]\n node.children = [\n ReactionNode.from_dict(child, config, molecules, parent=node)\n for child in dict_[\"children\"]\n ]\n return node\n\n @property # type: ignore\n def children(self) -> List[ReactionNode]: # type: ignore\n \"\"\"Gives the reaction children nodes\"\"\"\n return self._children\n\n @children.setter\n def children(self, value: List[ReactionNode]) -> None:\n self._children = value\n\n @property\n def prop(self) -> StrDict:\n return {\"solved\": self.in_stock, \"mol\": self.mol}\n\n def add_stub(self, reaction: RetroReaction) -> Sequence[MoleculeNode]:\n \"\"\"\n Add a stub / sub-tree to this node\n\n :param reaction: the reaction creating the stub\n :return: list of all newly added molecular nodes\n \"\"\"\n reactants = reaction.reactants[reaction.index]\n if not reactants:\n return []\n\n ancestors = self.ancestors()\n for mol in reactants:\n if mol in ancestors:\n return []\n\n rxn_node = ReactionNode.create_stub(\n reaction=reaction, parent=self, config=self._config\n )\n self._children.append(rxn_node)\n\n return rxn_node.children\n\n def ancestors(self) -> Set[TreeMolecule]:\n \"\"\"\n Return the ancestors of this node\n\n :return: the ancestors\n :rtype: set\n \"\"\"\n if not self.parent:\n return {self.mol}\n\n ancestors = self.parent.parent.ancestors()\n ancestors.add(self.mol)\n return ancestors\n\n def serialize(self, molecule_store: MoleculeSerializer) -> StrDict:\n \"\"\"\n Serialize the node object to a dictionary\n\n :param molecule_store: the serialized molecules\n :return: the serialized node\n \"\"\"\n dict_: StrDict = {\"expandable\": self.expandable}\n dict_[\"mol\"] = molecule_store[self.mol]\n dict_[\"children\"] = [child.serialize(molecule_store) for child in self.children]\n return dict_\n\n\n# Source: aizynthfinder/chem/serialization.py\nclass MoleculeSerializer:\n \"\"\"\n Utility class for serializing molecules\n\n The id of the molecule to be serialized can be obtained with:\n\n .. code-block::\n\n serializer = MoleculeSerializer()\n mol = Molecule(smiles=\"CCCO\")\n idx = serializer[mol]\n\n which will take care of the serialization of the molecule.\n \"\"\"\n\n def __init__(self) -> None:\n self._store: Dict[int, Any] = {}\n\n def __getitem__(self, mol: Optional[aizynthfinder.chem.Molecule]) -> Optional[int]:\n if mol is None:\n return None\n\n id_ = id(mol)\n if id_ not in self._store:\n self._add_mol(mol)\n return id_\n\n @property\n def store(self) -> Dict[int, Any]:\n \"\"\"Return all serialized molecules as a dictionary\"\"\"\n return self._store\n\n def _add_mol(self, mol: aizynthfinder.chem.Molecule) -> None:\n id_ = id(mol)\n dict_ = {\"smiles\": mol.smiles, \"class\": mol.__class__.__name__}\n if isinstance(mol, aizynthfinder.chem.TreeMolecule):\n dict_[\"parent\"] = self[mol.parent]\n dict_[\"transform\"] = mol.transform\n if not mol.parent:\n dict_[\"smiles\"] = mol.original_smiles\n else:\n dict_[\"smiles\"] = mol.mapped_smiles\n self._store[id_] = dict_\n\nclass MoleculeDeserializer:\n \"\"\"\n Utility class for deserializing molecules.\n The serialized molecules are created upon instantiation of the class.\n\n The deserialized molecules can be obtained with:\n\n .. code-block::\n\n deserializer = MoleculeDeserializer()\n mol = deserializer[idx]\n\n \"\"\"\n\n def __init__(self, store: Dict[int, Any]) -> None:\n self._objects: Dict[int, Any] = {}\n self._create_molecules(store)\n\n def __getitem__(self, id_: Optional[int]) -> Optional[aizynthfinder.chem.Molecule]:\n if id_ is None:\n return None\n return self._objects[id_]\n\n def get_tree_molecules(\n self, ids: Sequence[int]\n ) -> Sequence[aizynthfinder.chem.TreeMolecule]:\n \"\"\"\n Return multiple deserialized tree molecules\n\n :param ids: the list of IDs to deserialize\n :return: the molecule objects\n \"\"\"\n objects = []\n for id_ in ids:\n obj = self[id_]\n if obj is None or not isinstance(obj, aizynthfinder.chem.TreeMolecule):\n raise ValueError(f\"Failed to deserialize molecule with id {id_}\")\n objects.append(obj)\n return objects\n\n def _create_molecules(self, store: dict) -> None:\n for id_, spec in store.items():\n if isinstance(id_, str):\n id_ = int(id_)\n\n cls = spec[\"class\"]\n if \"parent\" in spec:\n spec[\"parent\"] = self[spec[\"parent\"]]\n\n kwargs = dict(spec)\n del kwargs[\"class\"]\n self._objects[id_] = getattr(aizynthfinder.chem, cls)(**kwargs)", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 7265}, "tests/mcts/test_reward.py::116": {"resolved_imports": ["aizynthfinder/analysis/__init__.py", "aizynthfinder/context/scoring/__init__.py", "aizynthfinder/search/mcts/__init__.py"], "used_names": ["MctsSearchTree", "NumberOfReactionsScorer"], "enclosing_function": "test_reward_node_backward_compatibility", "extracted_code": "# Source: aizynthfinder/context/scoring/__init__.py\n AverageTemplateOccurrenceScorer,\n MaxTransformScorer,\n NumberOfReactionsScorer,\n ReactionClassMembershipScorer,\n ReactionClassRankScorer,\n)\nfrom aizynthfinder.utils.exceptions import ScorerException\n\n\n# Source: aizynthfinder/search/mcts/__init__.py\n\"\"\"\nfrom aizynthfinder.search.mcts.node import MctsNode\nfrom aizynthfinder.search.mcts.search import MctsSearchTree\nfrom aizynthfinder.search.mcts.state import MctsState", "n_imports_parsed": 3, "n_files_resolved": 3, "n_chars_extracted": 486}, "tests/context/test_mcts_config.py::132": {"resolved_imports": ["aizynthfinder/aizynthfinder.py", "aizynthfinder/context/config.py", "aizynthfinder/context/stock/__init__.py"], "used_names": ["Configuration"], "enclosing_function": "test_load_stock", "extracted_code": "# Source: aizynthfinder/context/config.py\nclass Configuration:\n \"\"\"\n Encapsulating the settings of the tree search, including the policy,\n the stock, the loaded scorers and various parameters.\n \"\"\"\n\n search: _SearchConfiguration = field(default_factory=_SearchConfiguration)\n post_processing: _PostprocessingConfiguration = field(\n default_factory=_PostprocessingConfiguration\n )\n stock: Stock = field(init=False)\n expansion_policy: ExpansionPolicy = field(init=False)\n filter_policy: FilterPolicy = field(init=False)\n scorers: ScorerCollection = field(init=False)\n\n def __post_init__(self) -> None:\n self.stock = Stock()\n self.expansion_policy = ExpansionPolicy(self)\n self.filter_policy = FilterPolicy(self)\n self.scorers = ScorerCollection(self)\n self._logger = logger()\n\n def __eq__(self, other: Any) -> bool:\n if not isinstance(other, Configuration):\n return False\n for key, setting in vars(self).items():\n if isinstance(setting, (int, float, str, bool, list)):\n if (\n vars(self)[key] != vars(other)[key]\n or self.search != other.search\n or self.post_processing != other.post_processing\n ):\n return False\n return True\n\n @classmethod\n def from_dict(cls, source: StrDict) -> \"Configuration\":\n \"\"\"\n Loads a configuration from a dictionary structure.\n The parameters not set in the dictionary are taken from the default values.\n The policies and stocks specified are directly loaded.\n\n :param source: the dictionary source\n :return: a Configuration object with settings from the source\n \"\"\"\n expansion_config = source.pop(\"expansion\", {})\n filter_config = source.pop(\"filter\", {})\n stock_config = source.pop(\"stock\", {})\n scorer_config = source.pop(\"scorer\", {})\n\n config_obj = Configuration()\n config_obj._update_from_config(dict(source))\n\n config_obj.expansion_policy.load_from_config(**expansion_config)\n config_obj.filter_policy.load_from_config(**filter_config)\n config_obj.stock.load_from_config(**stock_config)\n config_obj.scorers.create_default_scorers()\n config_obj.scorers.load_from_config(**scorer_config)\n\n return config_obj\n\n @classmethod\n def from_file(cls, filename: str) -> \"Configuration\":\n \"\"\"\n Loads a configuration from a yaml file.\n The parameters not set in the yaml file are taken from the default values.\n The policies and stocks specified in the yaml file are directly loaded.\n The parameters in the yaml file may also contain environment variables as\n values.\n\n :param filename: the path to a yaml file\n :return: a Configuration object with settings from the yaml file\n :raises:\n ValueError: if parameter's value expects an environment variable that\n does not exist in the current environment\n \"\"\"\n with open(filename, \"r\") as fileobj:\n txt = fileobj.read()\n environ_var = re.findall(r\"\\$\\{.+?\\}\", txt)\n for item in environ_var:\n if item[2:-1] not in os.environ:\n raise ValueError(f\"'{item[2:-1]}' not in environment variables\")\n txt = txt.replace(item, os.environ[item[2:-1]])\n _config = yaml.load(txt, Loader=yaml.SafeLoader)\n return Configuration.from_dict(_config)\n\n def _update_from_config(self, config: StrDict) -> None:\n self.post_processing = _PostprocessingConfiguration(\n **config.pop(\"post_processing\", {})\n )\n\n search_config = config.pop(\"search\", {})\n for setting, value in search_config.items():\n if value is None:\n continue\n if not hasattr(self.search, setting):\n raise AttributeError(f\"Could not find attribute to set: {setting}\")\n if setting.endswith(\"_bonds\"):\n if not isinstance(value, list):\n raise ValueError(\"Bond settings need to be lists\")\n value = _handle_bond_pair_tuples(value) if value else []\n if setting == \"algorithm_config\":\n if not isinstance(value, dict):\n raise ValueError(\"algorithm_config settings need to be dictionary\")\n self.search.algorithm_config.update(value)\n else:\n setattr(self.search, setting, value)", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 4568}, "tests/breadth_first/test_search.py::26": {"resolved_imports": ["aizynthfinder/search/breadth_first/search_tree.py"], "used_names": ["SearchTree", "pytest"], "enclosing_function": "test_one_iteration", "extracted_code": "# Source: aizynthfinder/search/breadth_first/search_tree.py\nclass SearchTree(AndOrSearchTreeBase):\n \"\"\"\n Encapsulation of the a breadth-first exhaustive search algorithm\n\n :ivar config: settings of the tree search algorithm\n :ivar root: the root node\n\n :param config: settings of the tree search algorithm\n :param root_smiles: the root will be set to a node representing this molecule, defaults to None\n \"\"\"\n\n def __init__(\n self, config: Configuration, root_smiles: Optional[str] = None\n ) -> None:\n super().__init__(config, root_smiles)\n self._mol_nodes: List[MoleculeNode] = []\n self._added_mol_nodes: List[MoleculeNode] = []\n self._logger = logger()\n\n if root_smiles:\n self.root: Optional[MoleculeNode] = MoleculeNode.create_root(\n root_smiles, config\n )\n self._mol_nodes.append(self.root)\n else:\n self.root = None\n\n self._routes: List[ReactionTree] = []\n\n self.profiling = {\n \"expansion_calls\": 0,\n \"reactants_generations\": 0,\n }\n\n @classmethod\n def from_json(cls, filename: str, config: Configuration) -> SearchTree:\n \"\"\"\n Create a new search tree by deserialization from a JSON file\n\n :param filename: the path to the JSON node\n :param config: the configuration of the search tree\n :return: a deserialized tree\n \"\"\"\n\n def _find_mol_nodes(node):\n for child_ in node.children:\n tree._mol_nodes.append(child_) # pylint: disable=protected-access\n for grandchild in child_.children:\n _find_mol_nodes(grandchild)\n\n tree = cls(config)\n with open(filename, \"r\") as fileobj:\n dict_ = json.load(fileobj)\n mol_deser = MoleculeDeserializer(dict_[\"molecules\"])\n tree.root = MoleculeNode.from_dict(dict_[\"tree\"], config, mol_deser)\n tree._mol_nodes.append(tree.root) # pylint: disable=protected-access\n for child in tree.root.children:\n _find_mol_nodes(child)\n return tree\n\n @property\n def mol_nodes(self) -> Sequence[MoleculeNode]: # type: ignore\n \"\"\"Return the molecule nodes of the tree\"\"\"\n return self._mol_nodes\n\n def one_iteration(self) -> bool:\n \"\"\"\n Perform one iteration expansion.\n Expands all expandable molecule nodes in the tree, which should be\n on the same depth of the tree.\n\n :raises StopIteration: if the search should be pre-maturely terminated\n :return: if a solution was found\n :rtype: bool\n \"\"\"\n if self.root is None:\n raise ValueError(\"Root is undefined. Cannot make an iteration\")\n\n self._routes = []\n self._added_mol_nodes = []\n\n for next_node in self._mol_nodes:\n if next_node.expandable:\n self._expand(next_node)\n\n if not self._added_mol_nodes:\n self._logger.debug(\"No new nodes added in breadth-first iteration\")\n raise StopIteration\n\n self._mol_nodes.extend(self._added_mol_nodes)\n solved = all(node.in_stock for node in self._mol_nodes if not node.children)\n return solved\n\n def routes(self) -> List[ReactionTree]:\n \"\"\"\n Extracts and returns routes from the AND/OR tree\n\n :return: the routes\n \"\"\"\n if self.root is None:\n return []\n if not self._routes:\n self._routes = SplitAndOrTree(self.root, self.config.stock).routes\n return self._routes\n\n def serialize(self, filename: str) -> None:\n \"\"\"\n Seralize the search tree to a JSON file\n\n :param filename: the path to the JSON file\n :type filename: str\n \"\"\"\n if self.root is None:\n raise ValueError(\"Cannot serialize tree as root is not defined\")\n\n mol_ser = MoleculeSerializer()\n dict_ = {\"tree\": self.root.serialize(mol_ser), \"molecules\": mol_ser.store}\n with open(filename, \"w\") as fileobj:\n json.dump(dict_, fileobj, indent=2)\n\n def _expand(self, node: MoleculeNode) -> None:\n node.expandable = False\n reactions, _ = self.config.expansion_policy([node.mol])\n self.profiling[\"expansion_calls\"] += 1\n\n if not reactions:\n return\n\n reactions_to_expand = []\n for reaction in reactions:\n try:\n self.profiling[\"reactants_generations\"] += 1\n _ = reaction.reactants\n except: # pylint: disable=bare-except\n continue\n if not reaction.reactants:\n continue\n for idx, _ in enumerate(reaction.reactants):\n rxn_copy = reaction.copy(idx)\n reactions_to_expand.append(rxn_copy)\n\n for rxn in reactions_to_expand:\n new_nodes = node.add_stub(rxn)\n self._added_mol_nodes.extend(new_nodes)", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 4982}, "tests/context/test_score.py::154": {"resolved_imports": ["aizynthfinder/chem/__init__.py", "aizynthfinder/context/config.py", "aizynthfinder/context/scoring/__init__.py", "aizynthfinder/reactiontree.py", "aizynthfinder/search/mcts/__init__.py"], "used_names": ["FractionInSourceStockScorer", "FractionInStockScorer", "MaxTransformScorer", "MctsSearchTree", "NumberOfPrecursorsInStockScorer", "NumberOfPrecursorsScorer", "NumberOfReactionsScorer", "PriceSumScorer", "RouteCostScorer", "StateScorer", "pytest"], "enclosing_function": "test_scorers_one_mcts_node", "extracted_code": "# Source: aizynthfinder/context/scoring/__init__.py\n CombinedScorer,\n DeepSetScorer,\n RouteCostScorer,\n RouteSimilarityScorer,\n StateScorer,\n)\nfrom aizynthfinder.context.scoring.scorers_base import Scorer\nfrom aizynthfinder.context.scoring.scorers_mols import (\n DeltaSyntheticComplexityScorer,\n FractionInSourceStockScorer,\n FractionInStockScorer,\n FractionOfIntermediatesInStockScorer,\n\n RouteCostScorer,\n RouteSimilarityScorer,\n StateScorer,\n)\nfrom aizynthfinder.context.scoring.scorers_base import Scorer\nfrom aizynthfinder.context.scoring.scorers_mols import (\n DeltaSyntheticComplexityScorer,\n FractionInSourceStockScorer,\n FractionInStockScorer,\n FractionOfIntermediatesInStockScorer,\n NumberOfPrecursorsInStockScorer,\n NumberOfPrecursorsScorer,\n\nfrom aizynthfinder.context.scoring.scorers_mols import (\n DeltaSyntheticComplexityScorer,\n FractionInSourceStockScorer,\n FractionInStockScorer,\n FractionOfIntermediatesInStockScorer,\n NumberOfPrecursorsInStockScorer,\n NumberOfPrecursorsScorer,\n PriceSumScorer,\n StockAvailabilityScorer,\n)\nfrom aizynthfinder.context.scoring.scorers_reactions import (\n AverageTemplateOccurrenceScorer,\n\n DeltaSyntheticComplexityScorer,\n FractionInSourceStockScorer,\n FractionInStockScorer,\n FractionOfIntermediatesInStockScorer,\n NumberOfPrecursorsInStockScorer,\n NumberOfPrecursorsScorer,\n PriceSumScorer,\n StockAvailabilityScorer,\n)\nfrom aizynthfinder.context.scoring.scorers_reactions import (\n AverageTemplateOccurrenceScorer,\n MaxTransformScorer,\n\n FractionInStockScorer,\n FractionOfIntermediatesInStockScorer,\n NumberOfPrecursorsInStockScorer,\n NumberOfPrecursorsScorer,\n PriceSumScorer,\n StockAvailabilityScorer,\n)\nfrom aizynthfinder.context.scoring.scorers_reactions import (\n AverageTemplateOccurrenceScorer,\n MaxTransformScorer,\n NumberOfReactionsScorer,\n ReactionClassMembershipScorer,\n\n\n# Source: aizynthfinder/search/mcts/__init__.py\n\"\"\"\nfrom aizynthfinder.search.mcts.node import MctsNode\nfrom aizynthfinder.search.mcts.search import MctsSearchTree\nfrom aizynthfinder.search.mcts.state import MctsState", "n_imports_parsed": 8, "n_files_resolved": 5, "n_chars_extracted": 2194}, "tests/mcts/test_multiobjective.py::88": {"resolved_imports": ["aizynthfinder/search/mcts/node.py", "aizynthfinder/search/mcts/__init__.py"], "used_names": ["MctsSearchTree"], "enclosing_function": "test_setup_weighted_sum_tree", "extracted_code": "# Source: aizynthfinder/search/mcts/__init__.py\n\"\"\"\nfrom aizynthfinder.search.mcts.node import MctsNode\nfrom aizynthfinder.search.mcts.search import MctsSearchTree\nfrom aizynthfinder.search.mcts.state import MctsState", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 217}, "tests/mcts/test_tree.py::26": {"resolved_imports": [], "used_names": [], "enclosing_function": "test_backpropagation", "extracted_code": "", "n_imports_parsed": 0, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/breadth_first/test_nodes.py::67": {"resolved_imports": ["aizynthfinder/search/breadth_first/nodes.py", "aizynthfinder/chem/serialization.py"], "used_names": ["MoleculeDeserializer", "MoleculeNode", "MoleculeSerializer"], "enclosing_function": "test_serialization_deserialization", "extracted_code": "# Source: aizynthfinder/search/breadth_first/nodes.py\nclass MoleculeNode(TreeNodeMixin):\n \"\"\"\n An OR node representing a molecule\n\n :ivar expandable: if True, this node is part of the frontier\n :ivar mol: the molecule represented by the node\n :ivar in_stock: if True the molecule is in stock and hence should not be expanded\n :ivar parent: the parent of the node\n\n :param mol: the molecule to be represented by the node\n :param config: the configuration of the search\n :param parent: the parent of the node, optional\n \"\"\"\n\n def __init__(\n self,\n mol: TreeMolecule,\n config: Configuration,\n parent: Optional[ReactionNode] = None,\n ) -> None:\n self.mol = mol\n self._config = config\n self.in_stock = mol in config.stock\n self.parent = parent\n\n self._children: List[ReactionNode] = []\n # Makes it unexpandable if we have reached maximum depth\n self.expandable = self.mol.transform < self._config.search.max_transforms\n\n if self.in_stock:\n self.expandable = False\n\n @classmethod\n def create_root(cls, smiles: str, config: Configuration) -> \"MoleculeNode\":\n \"\"\"\n Create a root node for a tree using a SMILES.\n\n :param smiles: the SMILES representation of the root state\n :param config: settings of the tree search algorithm\n :return: the created node\n \"\"\"\n mol = TreeMolecule(parent=None, transform=0, smiles=smiles)\n return MoleculeNode(mol=mol, config=config)\n\n @classmethod\n def from_dict(\n cls,\n dict_: StrDict,\n config: Configuration,\n molecules: MoleculeDeserializer,\n parent: Optional[ReactionNode] = None,\n ) -> \"MoleculeNode\":\n \"\"\"\n Create a new node from a dictionary, i.e. deserialization\n\n :param dict_: the serialized node\n :param config: settings of the tree search algorithm\n :param molecules: the deserialized molecules\n :param parent: the parent node\n :return: a deserialized node\n \"\"\"\n mol = molecules.get_tree_molecules([dict_[\"mol\"]])[0]\n node = MoleculeNode(mol, config, parent)\n node.expandable = dict_[\"expandable\"]\n node.children = [\n ReactionNode.from_dict(child, config, molecules, parent=node)\n for child in dict_[\"children\"]\n ]\n return node\n\n @property # type: ignore\n def children(self) -> List[ReactionNode]: # type: ignore\n \"\"\"Gives the reaction children nodes\"\"\"\n return self._children\n\n @children.setter\n def children(self, value: List[ReactionNode]) -> None:\n self._children = value\n\n @property\n def prop(self) -> StrDict:\n return {\"solved\": self.in_stock, \"mol\": self.mol}\n\n def add_stub(self, reaction: RetroReaction) -> Sequence[MoleculeNode]:\n \"\"\"\n Add a stub / sub-tree to this node\n\n :param reaction: the reaction creating the stub\n :return: list of all newly added molecular nodes\n \"\"\"\n reactants = reaction.reactants[reaction.index]\n if not reactants:\n return []\n\n ancestors = self.ancestors()\n for mol in reactants:\n if mol in ancestors:\n return []\n\n rxn_node = ReactionNode.create_stub(\n reaction=reaction, parent=self, config=self._config\n )\n self._children.append(rxn_node)\n\n return rxn_node.children\n\n def ancestors(self) -> Set[TreeMolecule]:\n \"\"\"\n Return the ancestors of this node\n\n :return: the ancestors\n :rtype: set\n \"\"\"\n if not self.parent:\n return {self.mol}\n\n ancestors = self.parent.parent.ancestors()\n ancestors.add(self.mol)\n return ancestors\n\n def serialize(self, molecule_store: MoleculeSerializer) -> StrDict:\n \"\"\"\n Serialize the node object to a dictionary\n\n :param molecule_store: the serialized molecules\n :return: the serialized node\n \"\"\"\n dict_: StrDict = {\"expandable\": self.expandable}\n dict_[\"mol\"] = molecule_store[self.mol]\n dict_[\"children\"] = [child.serialize(molecule_store) for child in self.children]\n return dict_\n\n\n# Source: aizynthfinder/chem/serialization.py\nclass MoleculeSerializer:\n \"\"\"\n Utility class for serializing molecules\n\n The id of the molecule to be serialized can be obtained with:\n\n .. code-block::\n\n serializer = MoleculeSerializer()\n mol = Molecule(smiles=\"CCCO\")\n idx = serializer[mol]\n\n which will take care of the serialization of the molecule.\n \"\"\"\n\n def __init__(self) -> None:\n self._store: Dict[int, Any] = {}\n\n def __getitem__(self, mol: Optional[aizynthfinder.chem.Molecule]) -> Optional[int]:\n if mol is None:\n return None\n\n id_ = id(mol)\n if id_ not in self._store:\n self._add_mol(mol)\n return id_\n\n @property\n def store(self) -> Dict[int, Any]:\n \"\"\"Return all serialized molecules as a dictionary\"\"\"\n return self._store\n\n def _add_mol(self, mol: aizynthfinder.chem.Molecule) -> None:\n id_ = id(mol)\n dict_ = {\"smiles\": mol.smiles, \"class\": mol.__class__.__name__}\n if isinstance(mol, aizynthfinder.chem.TreeMolecule):\n dict_[\"parent\"] = self[mol.parent]\n dict_[\"transform\"] = mol.transform\n if not mol.parent:\n dict_[\"smiles\"] = mol.original_smiles\n else:\n dict_[\"smiles\"] = mol.mapped_smiles\n self._store[id_] = dict_\n\nclass MoleculeDeserializer:\n \"\"\"\n Utility class for deserializing molecules.\n The serialized molecules are created upon instantiation of the class.\n\n The deserialized molecules can be obtained with:\n\n .. code-block::\n\n deserializer = MoleculeDeserializer()\n mol = deserializer[idx]\n\n \"\"\"\n\n def __init__(self, store: Dict[int, Any]) -> None:\n self._objects: Dict[int, Any] = {}\n self._create_molecules(store)\n\n def __getitem__(self, id_: Optional[int]) -> Optional[aizynthfinder.chem.Molecule]:\n if id_ is None:\n return None\n return self._objects[id_]\n\n def get_tree_molecules(\n self, ids: Sequence[int]\n ) -> Sequence[aizynthfinder.chem.TreeMolecule]:\n \"\"\"\n Return multiple deserialized tree molecules\n\n :param ids: the list of IDs to deserialize\n :return: the molecule objects\n \"\"\"\n objects = []\n for id_ in ids:\n obj = self[id_]\n if obj is None or not isinstance(obj, aizynthfinder.chem.TreeMolecule):\n raise ValueError(f\"Failed to deserialize molecule with id {id_}\")\n objects.append(obj)\n return objects\n\n def _create_molecules(self, store: dict) -> None:\n for id_, spec in store.items():\n if isinstance(id_, str):\n id_ = int(id_)\n\n cls = spec[\"class\"]\n if \"parent\" in spec:\n spec[\"parent\"] = self[spec[\"parent\"]]\n\n kwargs = dict(spec)\n del kwargs[\"class\"]\n self._objects[id_] = getattr(aizynthfinder.chem, cls)(**kwargs)", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 7265}, "tests/chem/test_reaction.py::92": {"resolved_imports": ["aizynthfinder/chem/__init__.py"], "used_names": ["SmilesBasedRetroReaction", "TreeMolecule"], "enclosing_function": "test_smiles_based_retroreaction", "extracted_code": "# Source: aizynthfinder/chem/__init__.py\n Molecule,\n MoleculeException,\n TreeMolecule,\n UniqueMolecule,\n none_molecule,\n)\nfrom aizynthfinder.chem.reaction import (\n FixedRetroReaction,\n RetroReaction,\n SmilesBasedRetroReaction,\n TemplatedRetroReaction,\n hash_reactions,\n\n FixedRetroReaction,\n RetroReaction,\n SmilesBasedRetroReaction,\n TemplatedRetroReaction,\n hash_reactions,\n)\nfrom aizynthfinder.chem.serialization import (\n MoleculeDeserializer,\n MoleculeSerializer,\n deserialize_action,\n serialize_action,\n)", "n_imports_parsed": 1, "n_files_resolved": 1, "n_chars_extracted": 568}, "tests/context/test_expansion_strategies.py::68": {"resolved_imports": ["aizynthfinder/chem/__init__.py", "aizynthfinder/context/policy/__init__.py", "aizynthfinder/utils/exceptions.py"], "used_names": ["MultiExpansionStrategy", "TreeMolecule"], "enclosing_function": "test_multi_expansion_strategy_wo_additive_expansion", "extracted_code": "# Source: aizynthfinder/chem/__init__.py\n Molecule,\n MoleculeException,\n TreeMolecule,\n UniqueMolecule,\n none_molecule,\n)\nfrom aizynthfinder.chem.reaction import (\n FixedRetroReaction,\n RetroReaction,\n SmilesBasedRetroReaction,\n TemplatedRetroReaction,\n hash_reactions,\n\n\n# Source: aizynthfinder/context/policy/__init__.py\nfrom aizynthfinder.context.policy.expansion_strategies import (\n ExpansionStrategy,\n MultiExpansionStrategy,\n TemplateBasedDirectExpansionStrategy,\n TemplateBasedExpansionStrategy,\n)\nfrom aizynthfinder.context.policy.filter_strategies import (\n BondFilter,\n FilterStrategy,\n FrozenSubstructureFilter,\n QuickKerasFilter,\n ReactantsCountFilter,", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 722}, "tests/context/test_collection.py::22": {"resolved_imports": ["aizynthfinder/context/collection.py"], "used_names": [], "enclosing_function": "test_empty_collection", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/mcts/test_serialization.py::130": {"resolved_imports": ["aizynthfinder/chem/__init__.py", "aizynthfinder/chem/serialization.py", "aizynthfinder/search/mcts/__init__.py"], "used_names": ["MctsSearchTree", "MoleculeSerializer"], "enclosing_function": "test_serialize_deserialize_tree", "extracted_code": "# Source: aizynthfinder/chem/serialization.py\nclass MoleculeSerializer:\n \"\"\"\n Utility class for serializing molecules\n\n The id of the molecule to be serialized can be obtained with:\n\n .. code-block::\n\n serializer = MoleculeSerializer()\n mol = Molecule(smiles=\"CCCO\")\n idx = serializer[mol]\n\n which will take care of the serialization of the molecule.\n \"\"\"\n\n def __init__(self) -> None:\n self._store: Dict[int, Any] = {}\n\n def __getitem__(self, mol: Optional[aizynthfinder.chem.Molecule]) -> Optional[int]:\n if mol is None:\n return None\n\n id_ = id(mol)\n if id_ not in self._store:\n self._add_mol(mol)\n return id_\n\n @property\n def store(self) -> Dict[int, Any]:\n \"\"\"Return all serialized molecules as a dictionary\"\"\"\n return self._store\n\n def _add_mol(self, mol: aizynthfinder.chem.Molecule) -> None:\n id_ = id(mol)\n dict_ = {\"smiles\": mol.smiles, \"class\": mol.__class__.__name__}\n if isinstance(mol, aizynthfinder.chem.TreeMolecule):\n dict_[\"parent\"] = self[mol.parent]\n dict_[\"transform\"] = mol.transform\n if not mol.parent:\n dict_[\"smiles\"] = mol.original_smiles\n else:\n dict_[\"smiles\"] = mol.mapped_smiles\n self._store[id_] = dict_\n\n\n# Source: aizynthfinder/search/mcts/__init__.py\n\"\"\"\nfrom aizynthfinder.search.mcts.node import MctsNode\nfrom aizynthfinder.search.mcts.search import MctsSearchTree\nfrom aizynthfinder.search.mcts.state import MctsState", "n_imports_parsed": 3, "n_files_resolved": 3, "n_chars_extracted": 1580}, "tests/utils/test_file_utils.py::146": {"resolved_imports": ["aizynthfinder/utils/files.py"], "used_names": ["pytest", "read_datafile", "save_datafile"], "enclosing_function": "test_save_load_datafile_roundtrip", "extracted_code": "# Source: aizynthfinder/utils/files.py\ndef read_datafile(filename: Union[str, Path]) -> pd.DataFrame:\n \"\"\"\n Read aizynth output from disc in either .hdf5 or .json format\n\n :param filename: the path to the data\n :return: the loaded data\n \"\"\"\n filename_str = str(filename)\n if filename_str.endswith(\".hdf5\") or filename_str.endswith(\".hdf\"):\n return pd.read_hdf(filename, \"table\")\n return pd.read_json(filename, orient=\"table\")\n\ndef save_datafile(data: pd.DataFrame, filename: Union[str, Path]) -> None:\n \"\"\"\n Save the given data to disc in either .hdf5 or .json format\n\n :param data: the data to save\n :param filename: the path to the data\n \"\"\"\n filename_str = str(filename)\n if filename_str.endswith(\".hdf5\") or filename_str.endswith(\".hdf\"):\n with warnings.catch_warnings(): # This wil suppress a PerformanceWarning\n warnings.simplefilter(\"ignore\")\n data.to_hdf(filename, key=\"table\")\n else:\n data.to_json(filename, orient=\"table\")", "n_imports_parsed": 6, "n_files_resolved": 1, "n_chars_extracted": 1024}, "tests/chem/test_reaction.py::77": {"resolved_imports": ["aizynthfinder/chem/__init__.py"], "used_names": ["TemplatedRetroReaction"], "enclosing_function": "test_retro_reaction_copy", "extracted_code": "# Source: aizynthfinder/chem/__init__.py\n RetroReaction,\n SmilesBasedRetroReaction,\n TemplatedRetroReaction,\n hash_reactions,\n)\nfrom aizynthfinder.chem.serialization import (\n MoleculeDeserializer,\n MoleculeSerializer,\n deserialize_action,\n serialize_action,\n)", "n_imports_parsed": 1, "n_files_resolved": 1, "n_chars_extracted": 284}, "tests/mcts/test_tree.py::38": {"resolved_imports": [], "used_names": [], "enclosing_function": "test_route_to_node", "extracted_code": "", "n_imports_parsed": 0, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_expander.py::12": {"resolved_imports": ["aizynthfinder/aizynthfinder.py"], "used_names": ["AiZynthExpander"], "enclosing_function": "test_expander_defaults", "extracted_code": "# Source: aizynthfinder/aizynthfinder.py\nclass AiZynthExpander:\n \"\"\"\n Public API to the AiZynthFinder expansion and filter policies\n\n If instantiated with the path to a yaml file or dictionary of settings\n the stocks and policy networks are loaded directly.\n Otherwise, the user is responsible for loading them prior to\n executing the tree search.\n\n :ivar config: the configuration of the search\n :ivar expansion_policy: the expansion policy model\n :ivar filter_policy: the filter policy model\n\n :param configfile: the path to yaml file with configuration (has priority over configdict), defaults to None\n :param configdict: the config as a dictionary source, defaults to None\n \"\"\"\n\n def __init__(\n self, configfile: Optional[str] = None, configdict: Optional[StrDict] = None\n ) -> None:\n self._logger = logger()\n\n if configfile:\n self.config = Configuration.from_file(configfile)\n elif configdict:\n self.config = Configuration.from_dict(configdict)\n else:\n self.config = Configuration()\n\n self.expansion_policy = self.config.expansion_policy\n self.filter_policy = self.config.filter_policy\n self.stats: StrDict = {}\n\n def do_expansion(\n self,\n smiles: str,\n return_n: int = 5,\n filter_func: Optional[Callable[[RetroReaction], bool]] = None,\n ) -> List[Tuple[FixedRetroReaction, ...]]:\n \"\"\"\n Do the expansion of the given molecule returning a list of\n reaction tuples. Each tuple in the list contains reactions\n producing the same reactants. Hence, nested structure of the\n return value is way to group reactions.\n\n If filter policy is setup, the probability of the reactions are\n added as metadata to the reaction.\n\n The additional filter functions makes it possible to do customized\n filtering. The callable should take as only argument a `RetroReaction`\n object and return True if the reaction can be kept or False if it should\n be removed.\n\n :param smiles: the SMILES string of the target molecule\n :param return_n: the length of the return list\n :param filter_func: an additional filter function\n :return: the grouped reactions\n \"\"\"\n self.stats = {\"non-applicable\": 0}\n\n mol = TreeMolecule(parent=None, smiles=smiles)\n actions, _ = self.expansion_policy.get_actions([mol])\n results: Dict[Tuple[str, ...], List[FixedRetroReaction]] = defaultdict(list)\n for action in actions:\n reactants = action.reactants\n if not reactants:\n self.stats[\"non-applicable\"] += 1\n continue\n if filter_func and not filter_func(action):\n continue\n for name in self.filter_policy.selection or []:\n if hasattr(self.filter_policy[name], \"feasibility\"):\n _, feasibility_prob = self.filter_policy[name].feasibility(action)\n action.metadata[\"feasibility\"] = float(feasibility_prob)\n break\n action.metadata[\"expansion_rank\"] = len(results) + 1\n unique_key = tuple(sorted(mol.inchi_key for mol in reactants[0]))\n if unique_key not in results and len(results) >= return_n:\n continue\n rxn = next(ReactionTreeFromExpansion(action).tree.reactions()) # type: ignore\n results[unique_key].append(rxn)\n return [tuple(reactions) for reactions in results.values()]", "n_imports_parsed": 1, "n_files_resolved": 1, "n_chars_extracted": 3579}, "tests/mcts/test_node.py::79": {"resolved_imports": [], "used_names": [], "enclosing_function": "test_promising_child_of_root", "extracted_code": "", "n_imports_parsed": 0, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/utils/test_bonds.py::19": {"resolved_imports": ["aizynthfinder/chem/__init__.py", "aizynthfinder/utils/bonds.py"], "used_names": ["BrokenBonds", "SmilesBasedRetroReaction", "TreeMolecule"], "enclosing_function": "test_focussed_bonds_broken", "extracted_code": "# Source: aizynthfinder/chem/__init__.py\n Molecule,\n MoleculeException,\n TreeMolecule,\n UniqueMolecule,\n none_molecule,\n)\nfrom aizynthfinder.chem.reaction import (\n FixedRetroReaction,\n RetroReaction,\n SmilesBasedRetroReaction,\n TemplatedRetroReaction,\n hash_reactions,\n\n FixedRetroReaction,\n RetroReaction,\n SmilesBasedRetroReaction,\n TemplatedRetroReaction,\n hash_reactions,\n)\nfrom aizynthfinder.chem.serialization import (\n MoleculeDeserializer,\n MoleculeSerializer,\n deserialize_action,\n serialize_action,\n)\n\n\n# Source: aizynthfinder/utils/bonds.py\nclass BrokenBonds:\n \"\"\"\n A class to keep track of focussed bonds breaking in a target molecule.\n\n :param focussed_bonds: A list of focussed bond pairs. The bond pairs are represented\n as tuples of size 2. These bond pairs exist in the target molecule's atom bonds.\n \"\"\"\n\n def __init__(self, focussed_bonds: Sequence[Sequence[int]]) -> None:\n self.focussed_bonds = sort_bonds(focussed_bonds)\n self.filtered_focussed_bonds: List[Tuple[int, int]] = []\n\n def __call__(self, reaction: RetroReaction) -> List[Tuple[int, int]]:\n \"\"\"\n Provides a list of focussed bonds that break in any of the molecule's reactants.\n\n :param reaction: A retro reaction.\n :return: A list of all the focussed bonds that broke within the reactants\n that constitute the target molecule.\n \"\"\"\n self.filtered_focussed_bonds = self._get_filtered_focussed_bonds(reaction.mol)\n if not self.filtered_focussed_bonds:\n return []\n\n molecule_bonds = []\n for reactant in reaction.reactants[reaction.index]:\n molecule_bonds += reactant.mapped_atom_bonds\n\n broken_focussed_bonds = self._get_broken_frozen_bonds(\n sort_bonds(molecule_bonds)\n )\n return broken_focussed_bonds\n\n def _get_broken_frozen_bonds(\n self,\n molecule_bonds: List[Tuple[int, int]],\n ) -> List[Tuple[int, int]]:\n broken_focussed_bonds = list(\n set(self.filtered_focussed_bonds) - set(molecule_bonds)\n )\n return broken_focussed_bonds\n\n def _get_filtered_focussed_bonds(\n self, molecule: TreeMolecule\n ) -> List[Tuple[int, int]]:\n molecule_bonds = molecule.mapped_atom_bonds\n atom_maps = [atom_map for bonds in molecule_bonds for atom_map in bonds]\n\n filtered_focussed_bonds = []\n for idx1, idx2 in self.focussed_bonds:\n if idx1 in atom_maps and idx2 in atom_maps:\n filtered_focussed_bonds.append((idx1, idx2))\n return filtered_focussed_bonds", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 2670}, "tests/chem/test_serialization.py::86": {"resolved_imports": ["aizynthfinder/chem/serialization.py", "aizynthfinder/chem/__init__.py"], "used_names": ["MoleculeDeserializer", "MoleculeSerializer", "TreeMolecule"], "enclosing_function": "test_chaining", "extracted_code": "# Source: aizynthfinder/chem/serialization.py\nclass MoleculeSerializer:\n \"\"\"\n Utility class for serializing molecules\n\n The id of the molecule to be serialized can be obtained with:\n\n .. code-block::\n\n serializer = MoleculeSerializer()\n mol = Molecule(smiles=\"CCCO\")\n idx = serializer[mol]\n\n which will take care of the serialization of the molecule.\n \"\"\"\n\n def __init__(self) -> None:\n self._store: Dict[int, Any] = {}\n\n def __getitem__(self, mol: Optional[aizynthfinder.chem.Molecule]) -> Optional[int]:\n if mol is None:\n return None\n\n id_ = id(mol)\n if id_ not in self._store:\n self._add_mol(mol)\n return id_\n\n @property\n def store(self) -> Dict[int, Any]:\n \"\"\"Return all serialized molecules as a dictionary\"\"\"\n return self._store\n\n def _add_mol(self, mol: aizynthfinder.chem.Molecule) -> None:\n id_ = id(mol)\n dict_ = {\"smiles\": mol.smiles, \"class\": mol.__class__.__name__}\n if isinstance(mol, aizynthfinder.chem.TreeMolecule):\n dict_[\"parent\"] = self[mol.parent]\n dict_[\"transform\"] = mol.transform\n if not mol.parent:\n dict_[\"smiles\"] = mol.original_smiles\n else:\n dict_[\"smiles\"] = mol.mapped_smiles\n self._store[id_] = dict_\n\nclass MoleculeDeserializer:\n \"\"\"\n Utility class for deserializing molecules.\n The serialized molecules are created upon instantiation of the class.\n\n The deserialized molecules can be obtained with:\n\n .. code-block::\n\n deserializer = MoleculeDeserializer()\n mol = deserializer[idx]\n\n \"\"\"\n\n def __init__(self, store: Dict[int, Any]) -> None:\n self._objects: Dict[int, Any] = {}\n self._create_molecules(store)\n\n def __getitem__(self, id_: Optional[int]) -> Optional[aizynthfinder.chem.Molecule]:\n if id_ is None:\n return None\n return self._objects[id_]\n\n def get_tree_molecules(\n self, ids: Sequence[int]\n ) -> Sequence[aizynthfinder.chem.TreeMolecule]:\n \"\"\"\n Return multiple deserialized tree molecules\n\n :param ids: the list of IDs to deserialize\n :return: the molecule objects\n \"\"\"\n objects = []\n for id_ in ids:\n obj = self[id_]\n if obj is None or not isinstance(obj, aizynthfinder.chem.TreeMolecule):\n raise ValueError(f\"Failed to deserialize molecule with id {id_}\")\n objects.append(obj)\n return objects\n\n def _create_molecules(self, store: dict) -> None:\n for id_, spec in store.items():\n if isinstance(id_, str):\n id_ = int(id_)\n\n cls = spec[\"class\"]\n if \"parent\" in spec:\n spec[\"parent\"] = self[spec[\"parent\"]]\n\n kwargs = dict(spec)\n del kwargs[\"class\"]\n self._objects[id_] = getattr(aizynthfinder.chem, cls)(**kwargs)\n\n\n# Source: aizynthfinder/chem/__init__.py\n Molecule,\n MoleculeException,\n TreeMolecule,\n UniqueMolecule,\n none_molecule,\n)\nfrom aizynthfinder.chem.reaction import (\n FixedRetroReaction,\n RetroReaction,\n SmilesBasedRetroReaction,\n TemplatedRetroReaction,\n hash_reactions,", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 3289}, "tests/chem/test_mol.py::57": {"resolved_imports": ["aizynthfinder/chem/__init__.py"], "used_names": ["Chem", "Molecule", "MoleculeException", "pytest"], "enclosing_function": "test_sanitize", "extracted_code": "# Source: aizynthfinder/chem/__init__.py\n\"\"\"\nfrom aizynthfinder.chem.mol import (\n Molecule,\n MoleculeException,\n TreeMolecule,\n UniqueMolecule,\n none_molecule,\n)\nfrom aizynthfinder.chem.reaction import (\n FixedRetroReaction,\n RetroReaction,\n SmilesBasedRetroReaction,\n\nfrom aizynthfinder.chem.mol import (\n Molecule,\n MoleculeException,\n TreeMolecule,\n UniqueMolecule,\n none_molecule,\n)\nfrom aizynthfinder.chem.reaction import (\n FixedRetroReaction,\n RetroReaction,\n SmilesBasedRetroReaction,\n TemplatedRetroReaction,\n\n Molecule,\n MoleculeException,\n TreeMolecule,\n UniqueMolecule,\n none_molecule,\n)\nfrom aizynthfinder.chem.reaction import (\n FixedRetroReaction,\n RetroReaction,\n SmilesBasedRetroReaction,\n TemplatedRetroReaction,\n hash_reactions,\n\n MoleculeException,\n TreeMolecule,\n UniqueMolecule,\n none_molecule,\n)\nfrom aizynthfinder.chem.reaction import (\n FixedRetroReaction,\n RetroReaction,\n SmilesBasedRetroReaction,\n TemplatedRetroReaction,\n hash_reactions,\n)\n\n)\nfrom aizynthfinder.chem.serialization import (\n MoleculeDeserializer,\n MoleculeSerializer,\n deserialize_action,\n serialize_action,\n)", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 1225}, "tests/context/test_score.py::188": {"resolved_imports": ["aizynthfinder/chem/__init__.py", "aizynthfinder/context/config.py", "aizynthfinder/context/scoring/__init__.py", "aizynthfinder/reactiontree.py", "aizynthfinder/search/mcts/__init__.py"], "used_names": ["Configuration", "FractionInSourceStockScorer", "FractionInStockScorer", "FractionOfIntermediatesInStockScorer", "MaxTransformScorer", "NumberOfPrecursorsInStockScorer", "NumberOfPrecursorsScorer", "NumberOfReactionsScorer", "PriceSumScorer", "RouteCostScorer", "StateScorer", "pytest"], "enclosing_function": "test_scoring_branched_mcts_tree", "extracted_code": "# Source: aizynthfinder/context/config.py\nclass Configuration:\n \"\"\"\n Encapsulating the settings of the tree search, including the policy,\n the stock, the loaded scorers and various parameters.\n \"\"\"\n\n search: _SearchConfiguration = field(default_factory=_SearchConfiguration)\n post_processing: _PostprocessingConfiguration = field(\n default_factory=_PostprocessingConfiguration\n )\n stock: Stock = field(init=False)\n expansion_policy: ExpansionPolicy = field(init=False)\n filter_policy: FilterPolicy = field(init=False)\n scorers: ScorerCollection = field(init=False)\n\n def __post_init__(self) -> None:\n self.stock = Stock()\n self.expansion_policy = ExpansionPolicy(self)\n self.filter_policy = FilterPolicy(self)\n self.scorers = ScorerCollection(self)\n self._logger = logger()\n\n def __eq__(self, other: Any) -> bool:\n if not isinstance(other, Configuration):\n return False\n for key, setting in vars(self).items():\n if isinstance(setting, (int, float, str, bool, list)):\n if (\n vars(self)[key] != vars(other)[key]\n or self.search != other.search\n or self.post_processing != other.post_processing\n ):\n return False\n return True\n\n @classmethod\n def from_dict(cls, source: StrDict) -> \"Configuration\":\n \"\"\"\n Loads a configuration from a dictionary structure.\n The parameters not set in the dictionary are taken from the default values.\n The policies and stocks specified are directly loaded.\n\n :param source: the dictionary source\n :return: a Configuration object with settings from the source\n \"\"\"\n expansion_config = source.pop(\"expansion\", {})\n filter_config = source.pop(\"filter\", {})\n stock_config = source.pop(\"stock\", {})\n scorer_config = source.pop(\"scorer\", {})\n\n config_obj = Configuration()\n config_obj._update_from_config(dict(source))\n\n config_obj.expansion_policy.load_from_config(**expansion_config)\n config_obj.filter_policy.load_from_config(**filter_config)\n config_obj.stock.load_from_config(**stock_config)\n config_obj.scorers.create_default_scorers()\n config_obj.scorers.load_from_config(**scorer_config)\n\n return config_obj\n\n @classmethod\n def from_file(cls, filename: str) -> \"Configuration\":\n \"\"\"\n Loads a configuration from a yaml file.\n The parameters not set in the yaml file are taken from the default values.\n The policies and stocks specified in the yaml file are directly loaded.\n The parameters in the yaml file may also contain environment variables as\n values.\n\n :param filename: the path to a yaml file\n :return: a Configuration object with settings from the yaml file\n :raises:\n ValueError: if parameter's value expects an environment variable that\n does not exist in the current environment\n \"\"\"\n with open(filename, \"r\") as fileobj:\n txt = fileobj.read()\n environ_var = re.findall(r\"\\$\\{.+?\\}\", txt)\n for item in environ_var:\n if item[2:-1] not in os.environ:\n raise ValueError(f\"'{item[2:-1]}' not in environment variables\")\n txt = txt.replace(item, os.environ[item[2:-1]])\n _config = yaml.load(txt, Loader=yaml.SafeLoader)\n return Configuration.from_dict(_config)\n\n def _update_from_config(self, config: StrDict) -> None:\n self.post_processing = _PostprocessingConfiguration(\n **config.pop(\"post_processing\", {})\n )\n\n search_config = config.pop(\"search\", {})\n for setting, value in search_config.items():\n if value is None:\n continue\n if not hasattr(self.search, setting):\n raise AttributeError(f\"Could not find attribute to set: {setting}\")\n if setting.endswith(\"_bonds\"):\n if not isinstance(value, list):\n raise ValueError(\"Bond settings need to be lists\")\n value = _handle_bond_pair_tuples(value) if value else []\n if setting == \"algorithm_config\":\n if not isinstance(value, dict):\n raise ValueError(\"algorithm_config settings need to be dictionary\")\n self.search.algorithm_config.update(value)\n else:\n setattr(self.search, setting, value)\n\n\n# Source: aizynthfinder/context/scoring/__init__.py\n CombinedScorer,\n DeepSetScorer,\n RouteCostScorer,\n RouteSimilarityScorer,\n StateScorer,\n)\nfrom aizynthfinder.context.scoring.scorers_base import Scorer\nfrom aizynthfinder.context.scoring.scorers_mols import (\n DeltaSyntheticComplexityScorer,\n FractionInSourceStockScorer,\n FractionInStockScorer,\n FractionOfIntermediatesInStockScorer,\n\n RouteCostScorer,\n RouteSimilarityScorer,\n StateScorer,\n)\nfrom aizynthfinder.context.scoring.scorers_base import Scorer\nfrom aizynthfinder.context.scoring.scorers_mols import (\n DeltaSyntheticComplexityScorer,\n FractionInSourceStockScorer,\n FractionInStockScorer,\n FractionOfIntermediatesInStockScorer,\n NumberOfPrecursorsInStockScorer,\n NumberOfPrecursorsScorer,\n\nfrom aizynthfinder.context.scoring.scorers_mols import (\n DeltaSyntheticComplexityScorer,\n FractionInSourceStockScorer,\n FractionInStockScorer,\n FractionOfIntermediatesInStockScorer,\n NumberOfPrecursorsInStockScorer,\n NumberOfPrecursorsScorer,\n PriceSumScorer,\n StockAvailabilityScorer,\n)\nfrom aizynthfinder.context.scoring.scorers_reactions import (\n AverageTemplateOccurrenceScorer,\n\n DeltaSyntheticComplexityScorer,\n FractionInSourceStockScorer,\n FractionInStockScorer,\n FractionOfIntermediatesInStockScorer,\n NumberOfPrecursorsInStockScorer,\n NumberOfPrecursorsScorer,\n PriceSumScorer,\n StockAvailabilityScorer,\n)\nfrom aizynthfinder.context.scoring.scorers_reactions import (\n AverageTemplateOccurrenceScorer,\n MaxTransformScorer,\n\n FractionInSourceStockScorer,\n FractionInStockScorer,\n FractionOfIntermediatesInStockScorer,\n NumberOfPrecursorsInStockScorer,\n NumberOfPrecursorsScorer,\n PriceSumScorer,\n StockAvailabilityScorer,\n)\nfrom aizynthfinder.context.scoring.scorers_reactions import (\n AverageTemplateOccurrenceScorer,\n MaxTransformScorer,\n NumberOfReactionsScorer,", "n_imports_parsed": 8, "n_files_resolved": 5, "n_chars_extracted": 6543}, "tests/test_finder.py::40": {"resolved_imports": ["aizynthfinder/aizynthfinder.py"], "used_names": [], "enclosing_function": "test_dead_end_expansion", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/utils/test_bonds.py::34": {"resolved_imports": ["aizynthfinder/chem/__init__.py", "aizynthfinder/utils/bonds.py"], "used_names": ["BrokenBonds", "SmilesBasedRetroReaction", "TreeMolecule"], "enclosing_function": "test_focussed_bonds_not_broken", "extracted_code": "# Source: aizynthfinder/chem/__init__.py\n Molecule,\n MoleculeException,\n TreeMolecule,\n UniqueMolecule,\n none_molecule,\n)\nfrom aizynthfinder.chem.reaction import (\n FixedRetroReaction,\n RetroReaction,\n SmilesBasedRetroReaction,\n TemplatedRetroReaction,\n hash_reactions,\n\n FixedRetroReaction,\n RetroReaction,\n SmilesBasedRetroReaction,\n TemplatedRetroReaction,\n hash_reactions,\n)\nfrom aizynthfinder.chem.serialization import (\n MoleculeDeserializer,\n MoleculeSerializer,\n deserialize_action,\n serialize_action,\n)\n\n\n# Source: aizynthfinder/utils/bonds.py\nclass BrokenBonds:\n \"\"\"\n A class to keep track of focussed bonds breaking in a target molecule.\n\n :param focussed_bonds: A list of focussed bond pairs. The bond pairs are represented\n as tuples of size 2. These bond pairs exist in the target molecule's atom bonds.\n \"\"\"\n\n def __init__(self, focussed_bonds: Sequence[Sequence[int]]) -> None:\n self.focussed_bonds = sort_bonds(focussed_bonds)\n self.filtered_focussed_bonds: List[Tuple[int, int]] = []\n\n def __call__(self, reaction: RetroReaction) -> List[Tuple[int, int]]:\n \"\"\"\n Provides a list of focussed bonds that break in any of the molecule's reactants.\n\n :param reaction: A retro reaction.\n :return: A list of all the focussed bonds that broke within the reactants\n that constitute the target molecule.\n \"\"\"\n self.filtered_focussed_bonds = self._get_filtered_focussed_bonds(reaction.mol)\n if not self.filtered_focussed_bonds:\n return []\n\n molecule_bonds = []\n for reactant in reaction.reactants[reaction.index]:\n molecule_bonds += reactant.mapped_atom_bonds\n\n broken_focussed_bonds = self._get_broken_frozen_bonds(\n sort_bonds(molecule_bonds)\n )\n return broken_focussed_bonds\n\n def _get_broken_frozen_bonds(\n self,\n molecule_bonds: List[Tuple[int, int]],\n ) -> List[Tuple[int, int]]:\n broken_focussed_bonds = list(\n set(self.filtered_focussed_bonds) - set(molecule_bonds)\n )\n return broken_focussed_bonds\n\n def _get_filtered_focussed_bonds(\n self, molecule: TreeMolecule\n ) -> List[Tuple[int, int]]:\n molecule_bonds = molecule.mapped_atom_bonds\n atom_maps = [atom_map for bonds in molecule_bonds for atom_map in bonds]\n\n filtered_focussed_bonds = []\n for idx1, idx2 in self.focussed_bonds:\n if idx1 in atom_maps and idx2 in atom_maps:\n filtered_focussed_bonds.append((idx1, idx2))\n return filtered_focussed_bonds", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 2670}, "tests/context/test_policy.py::177": {"resolved_imports": ["aizynthfinder/chem/__init__.py", "aizynthfinder/context/policy/__init__.py", "aizynthfinder/utils/exceptions.py"], "used_names": ["TreeMolecule", "pytest"], "enclosing_function": "test_get_actions_using_rdkit", "extracted_code": "# Source: aizynthfinder/chem/__init__.py\n Molecule,\n MoleculeException,\n TreeMolecule,\n UniqueMolecule,\n none_molecule,\n)\nfrom aizynthfinder.chem.reaction import (\n FixedRetroReaction,\n RetroReaction,\n SmilesBasedRetroReaction,\n TemplatedRetroReaction,\n hash_reactions,", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 299}, "tests/utils/test_local_onnx_model.py::22": {"resolved_imports": ["aizynthfinder/utils/__init__.py", "aizynthfinder/utils/models.py"], "used_names": ["models", "pytest_mock"], "enclosing_function": "test_local_onnx_model_length", "extracted_code": "", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/test_cli.py::316": {"resolved_imports": ["aizynthfinder/analysis/__init__.py", "aizynthfinder/chem/__init__.py", "aizynthfinder/interfaces/__init__.py", "aizynthfinder/interfaces/aizynthapp.py", "aizynthfinder/interfaces/aizynthcli.py", "aizynthfinder/reactiontree.py", "aizynthfinder/tools/cat_output.py", "aizynthfinder/tools/download_public_data.py", "aizynthfinder/tools/make_stock.py"], "used_names": [], "enclosing_function": "test_cli_multiple_smiles_unsanitizable", "extracted_code": "", "n_imports_parsed": 17, "n_files_resolved": 9, "n_chars_extracted": 0}, "tests/context/test_policy.py::389": {"resolved_imports": ["aizynthfinder/chem/__init__.py", "aizynthfinder/context/policy/__init__.py", "aizynthfinder/utils/exceptions.py"], "used_names": ["ReactantsCountFilter", "RejectionException", "TemplatedRetroReaction", "TreeMolecule", "pytest"], "enclosing_function": "test_reactants_count_rejection", "extracted_code": "# Source: aizynthfinder/chem/__init__.py\n Molecule,\n MoleculeException,\n TreeMolecule,\n UniqueMolecule,\n none_molecule,\n)\nfrom aizynthfinder.chem.reaction import (\n FixedRetroReaction,\n RetroReaction,\n SmilesBasedRetroReaction,\n TemplatedRetroReaction,\n hash_reactions,\n\n RetroReaction,\n SmilesBasedRetroReaction,\n TemplatedRetroReaction,\n hash_reactions,\n)\nfrom aizynthfinder.chem.serialization import (\n MoleculeDeserializer,\n MoleculeSerializer,\n deserialize_action,\n serialize_action,\n)\n\n\n# Source: aizynthfinder/context/policy/__init__.py\n FrozenSubstructureFilter,\n QuickKerasFilter,\n ReactantsCountFilter,\n)\nfrom aizynthfinder.context.policy.policies import ExpansionPolicy, FilterPolicy\nfrom aizynthfinder.utils.exceptions import PolicyException\n\n\n# Source: aizynthfinder/utils/exceptions.py\nclass RejectionException(Exception):\n \"\"\"An exception raised if a retro action should be rejected\"\"\"", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 966}, "tests/mcts/test_tree.py::7": {"resolved_imports": [], "used_names": [], "enclosing_function": "test_select_leaf_root", "extracted_code": "", "n_imports_parsed": 0, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_reactiontree.py::26": {"resolved_imports": ["aizynthfinder/reactiontree.py"], "used_names": [], "enclosing_function": "test_mcts_route_to_reactiontree", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/test_expander.py::33": {"resolved_imports": ["aizynthfinder/aizynthfinder.py"], "used_names": ["AiZynthExpander"], "enclosing_function": "test_expander_top1", "extracted_code": "# Source: aizynthfinder/aizynthfinder.py\nclass AiZynthExpander:\n \"\"\"\n Public API to the AiZynthFinder expansion and filter policies\n\n If instantiated with the path to a yaml file or dictionary of settings\n the stocks and policy networks are loaded directly.\n Otherwise, the user is responsible for loading them prior to\n executing the tree search.\n\n :ivar config: the configuration of the search\n :ivar expansion_policy: the expansion policy model\n :ivar filter_policy: the filter policy model\n\n :param configfile: the path to yaml file with configuration (has priority over configdict), defaults to None\n :param configdict: the config as a dictionary source, defaults to None\n \"\"\"\n\n def __init__(\n self, configfile: Optional[str] = None, configdict: Optional[StrDict] = None\n ) -> None:\n self._logger = logger()\n\n if configfile:\n self.config = Configuration.from_file(configfile)\n elif configdict:\n self.config = Configuration.from_dict(configdict)\n else:\n self.config = Configuration()\n\n self.expansion_policy = self.config.expansion_policy\n self.filter_policy = self.config.filter_policy\n self.stats: StrDict = {}\n\n def do_expansion(\n self,\n smiles: str,\n return_n: int = 5,\n filter_func: Optional[Callable[[RetroReaction], bool]] = None,\n ) -> List[Tuple[FixedRetroReaction, ...]]:\n \"\"\"\n Do the expansion of the given molecule returning a list of\n reaction tuples. Each tuple in the list contains reactions\n producing the same reactants. Hence, nested structure of the\n return value is way to group reactions.\n\n If filter policy is setup, the probability of the reactions are\n added as metadata to the reaction.\n\n The additional filter functions makes it possible to do customized\n filtering. The callable should take as only argument a `RetroReaction`\n object and return True if the reaction can be kept or False if it should\n be removed.\n\n :param smiles: the SMILES string of the target molecule\n :param return_n: the length of the return list\n :param filter_func: an additional filter function\n :return: the grouped reactions\n \"\"\"\n self.stats = {\"non-applicable\": 0}\n\n mol = TreeMolecule(parent=None, smiles=smiles)\n actions, _ = self.expansion_policy.get_actions([mol])\n results: Dict[Tuple[str, ...], List[FixedRetroReaction]] = defaultdict(list)\n for action in actions:\n reactants = action.reactants\n if not reactants:\n self.stats[\"non-applicable\"] += 1\n continue\n if filter_func and not filter_func(action):\n continue\n for name in self.filter_policy.selection or []:\n if hasattr(self.filter_policy[name], \"feasibility\"):\n _, feasibility_prob = self.filter_policy[name].feasibility(action)\n action.metadata[\"feasibility\"] = float(feasibility_prob)\n break\n action.metadata[\"expansion_rank\"] = len(results) + 1\n unique_key = tuple(sorted(mol.inchi_key for mol in reactants[0]))\n if unique_key not in results and len(results) >= return_n:\n continue\n rxn = next(ReactionTreeFromExpansion(action).tree.reactions()) # type: ignore\n results[unique_key].append(rxn)\n return [tuple(reactions) for reactions in results.values()]", "n_imports_parsed": 1, "n_files_resolved": 1, "n_chars_extracted": 3579}, "tests/utils/test_file_utils.py::47": {"resolved_imports": ["aizynthfinder/utils/files.py"], "used_names": ["os", "split_file"], "enclosing_function": "test_split_file_even", "extracted_code": "# Source: aizynthfinder/utils/files.py\ndef split_file(filename: str, nparts: int) -> List[str]:\n \"\"\"\n Split the content of a text file into a given number of temporary files\n\n :param filename: the path to the file to split\n :param nparts: the number of parts to create\n :return: list of filenames of the parts\n \"\"\"\n with open(filename, \"r\") as fileobj:\n lines = fileobj.read().splitlines()\n\n filenames = []\n batch_size, remainder = divmod(len(lines), nparts)\n stop = 0\n for part in range(1, nparts + 1):\n start = stop\n stop += batch_size + 1 if part <= remainder else batch_size\n filenames.append(tempfile.mktemp())\n with open(filenames[-1], \"w\") as fileobj:\n fileobj.write(\"\\n\".join(lines[start:stop]))\n return filenames", "n_imports_parsed": 6, "n_files_resolved": 1, "n_chars_extracted": 803}, "tests/context/test_mcts_config.py::388": {"resolved_imports": ["aizynthfinder/aizynthfinder.py", "aizynthfinder/context/config.py", "aizynthfinder/context/stock/__init__.py"], "used_names": ["AiZynthFinder"], "enclosing_function": "test_init_search_yaml", "extracted_code": "# Source: aizynthfinder/aizynthfinder.py\nclass AiZynthFinder:\n \"\"\"\n Public API to the aizynthfinder tool\n\n If instantiated with the path to a yaml file or dictionary of settings\n the stocks and policy networks are loaded directly.\n Otherwise, the user is responsible for loading them prior to\n executing the tree search.\n\n :ivar config: the configuration of the search\n :ivar expansion_policy: the expansion policy model\n :ivar filter_policy: the filter policy model\n :ivar stock: the stock\n :ivar scorers: the loaded scores\n :ivar tree: the search tree\n :ivar analysis: the tree analysis\n :ivar routes: the top-ranked routes\n :ivar search_stats: statistics of the latest search\n\n :param configfile: the path to yaml file with configuration (has priority over configdict), defaults to None\n :param configdict: the config as a dictionary source, defaults to None\n \"\"\"\n\n def __init__(\n self, configfile: Optional[str] = None, configdict: Optional[StrDict] = None\n ) -> None:\n self._logger = logger()\n\n if configfile:\n self.config = Configuration.from_file(configfile)\n elif configdict:\n self.config = Configuration.from_dict(configdict)\n else:\n self.config = Configuration()\n\n self.expansion_policy = self.config.expansion_policy\n self.filter_policy = self.config.filter_policy\n self.stock = self.config.stock\n self.scorers = self.config.scorers\n self.tree: Optional[Union[MctsSearchTree, AndOrSearchTreeBase]] = None\n self._target_mol: Optional[Molecule] = None\n self.search_stats: StrDict = dict()\n self.routes = RouteCollection([])\n self.analysis: Optional[TreeAnalysis] = None\n self._num_objectives = len(\n self.config.search.algorithm_config.get(\"search_rewards\", [])\n )\n\n @property\n def target_smiles(self) -> str:\n \"\"\"The SMILES representation of the molecule to predict routes on.\"\"\"\n if not self._target_mol:\n return \"\"\n return self._target_mol.smiles\n\n @target_smiles.setter\n def target_smiles(self, smiles: str) -> None:\n self.target_mol = Molecule(smiles=smiles)\n\n @property\n def target_mol(self) -> Optional[Molecule]:\n \"\"\"The molecule to predict routes on\"\"\"\n return self._target_mol\n\n @target_mol.setter\n def target_mol(self, mol: Molecule) -> None:\n self.tree = None\n self._target_mol = mol\n\n def build_routes(\n self,\n selection: Optional[RouteSelectionArguments] = None,\n scorer: Optional[Union[str, List[str]]] = None,\n ) -> None:\n \"\"\"\n Build reaction routes\n\n This is necessary to call after the tree search has completed in order\n to extract results from the tree search.\n\n :param selection: the selection criteria for the routes\n :param scorer: a reference to the object used to score the nodes, can be a list\n :raises ValueError: if the search tree not initialized\n \"\"\"\n self.analysis = self._setup_analysis(scorer=scorer)\n config_selection = RouteSelectionArguments(\n nmin=self.config.post_processing.min_routes,\n nmax=self.config.post_processing.max_routes,\n return_all=self.config.post_processing.all_routes,\n )\n self.routes = RouteCollection.from_analysis(\n self.analysis, selection or config_selection\n )\n\n def extract_statistics(self) -> StrDict:\n \"\"\"Extracts tree statistics as a dictionary\"\"\"\n if not self.analysis:\n return {}\n stats = {\n \"target\": self.target_smiles,\n \"search_time\": self.search_stats[\"time\"],\n \"first_solution_time\": self.search_stats.get(\"first_solution_time\", 0),\n \"first_solution_iteration\": self.search_stats.get(\n \"first_solution_iteration\", 0\n ),\n }\n stats.update(self.analysis.tree_statistics())\n return stats\n\n def prepare_tree(self) -> None:\n \"\"\"\n Setup the tree for searching\n\n :raises ValueError: if the target molecule was not set\n \"\"\"\n if not self.target_mol:\n raise ValueError(\"No target molecule set\")\n\n try:\n self.target_mol.sanitize()\n except MoleculeException:\n raise ValueError(\"Target molecule unsanitizable\")\n\n self.stock.reset_exclusion_list()\n if (\n self.config.search.exclude_target_from_stock\n and self.target_mol in self.stock\n ):\n self.stock.exclude(self.target_mol)\n self._logger.debug(\"Excluding the target compound from the stock\")\n\n if self.config.search.break_bonds or self.config.search.freeze_bonds:\n self._setup_focussed_bonds(self.target_mol)\n\n self._setup_search_tree()\n self.analysis = None\n self.routes = RouteCollection([])\n self.filter_policy.reset_cache()\n self.expansion_policy.reset_cache()\n\n def stock_info(self) -> StrDict:\n \"\"\"\n Return the stock availability for all leaf nodes in all collected reaction trees\n\n The key of the return dictionary will be the SMILES string of the leaves,\n and the value will be the stock availability\n\n :return: the collected stock information.\n \"\"\"\n if not self.analysis:\n return {}\n _stock_info = {}\n for tree in self.routes.reaction_trees:\n for leaf in tree.leafs():\n if leaf.smiles not in _stock_info:\n _stock_info[leaf.smiles] = self.stock.availability_list(leaf)\n return _stock_info\n\n def tree_search(self, show_progress: bool = False) -> float:\n \"\"\"\n Perform the actual tree search\n\n :param show_progress: if True, shows a progress bar\n :return: the time past in seconds\n \"\"\"\n if not self.tree:\n self.prepare_tree()\n # This is for type checking, prepare_tree is creating it.\n assert self.tree is not None\n self.search_stats = {\"returned_first\": False, \"iterations\": 0}\n\n time0 = time.time()\n i = 1\n self._logger.debug(\"Starting search\")\n time_past = time.time() - time0\n\n if show_progress:\n pbar = tqdm(total=self.config.search.iteration_limit, leave=False)\n\n while (\n time_past < self.config.search.time_limit\n and i <= self.config.search.iteration_limit\n ):\n if show_progress:\n pbar.update(1)\n self.search_stats[\"iterations\"] += 1\n\n try:\n is_solved = self.tree.one_iteration()\n except StopIteration:\n break\n\n if is_solved and \"first_solution_time\" not in self.search_stats:\n self.search_stats[\"first_solution_time\"] = time.time() - time0\n self.search_stats[\"first_solution_iteration\"] = i\n\n if self.config.search.return_first and is_solved:\n self._logger.debug(\"Found first solved route\")\n self.search_stats[\"returned_first\"] = True\n break\n i = i + 1\n time_past = time.time() - time0\n\n if show_progress:\n pbar.close()\n time_past = time.time() - time0\n self._logger.debug(\"Search completed\")\n self.search_stats[\"time\"] = time_past\n return time_past\n\n def _setup_focussed_bonds(self, target_mol: Molecule) -> None:\n \"\"\"\n Setup multi-objective scoring function with 'broken bonds'-scorer and\n add 'frozen bonds'-filter to filter policy.\n\n :param target_mol: the target molecule.\n \"\"\"\n target_mol = TreeMolecule(smiles=target_mol.smiles, parent=None)\n\n bond_filter_key = \"__finder_bond_filter\"\n if self.config.search.freeze_bonds:\n if not target_mol.has_all_focussed_bonds(self.config.search.freeze_bonds):\n raise ValueError(\"Bonds in 'freeze_bond' must exist in target molecule\")\n bond_filter = BondFilter(bond_filter_key, self.config)\n self.filter_policy.load(bond_filter)\n self.filter_policy.select(bond_filter_key, append=True)\n elif (\n self.filter_policy.selection\n and bond_filter_key in self.filter_policy.selection\n ):\n self.filter_policy.deselect(bond_filter_key)\n\n search_rewards = self.config.search.algorithm_config.get(\"search_rewards\")\n if not search_rewards:\n return\n\n if self.config.search.break_bonds and \"broken bonds\" in search_rewards:\n if not target_mol.has_all_focussed_bonds(self.config.search.break_bonds):\n raise ValueError(\"Bonds in 'break_bonds' must exist in target molecule\")\n self.scorers.load(BrokenBondsScorer(self.config))\n self._num_objectives = len(search_rewards)\n\n def _setup_search_tree(self) -> None:\n self._logger.debug(f\"Defining tree root: {self.target_smiles}\")\n if self.config.search.algorithm.lower() == \"mcts\":\n self.tree = MctsSearchTree(\n root_smiles=self.target_smiles, config=self.config\n )\n else:\n cls = load_dynamic_class(self.config.search.algorithm)\n self.tree = cls(root_smiles=self.target_smiles, config=self.config)\n\n def _setup_analysis(\n self,\n scorer: Optional[Union[str, List[str]]],\n ) -> TreeAnalysis:\n \"\"\"Configure TreeAnalysis\n\n :param scorer: a reference to the object used to score the nodes, can be a list\n :returns: the configured TreeAnalysis\n :raises ValueError: if the search tree not initialized\n \"\"\"\n if not self.tree:\n raise ValueError(\"Search tree not initialized\")\n\n if scorer is None:\n scorer_names = self.config.post_processing.route_scorers\n # If not defined, use the same scorer as the search rewards\n if not scorer_names:\n search_rewards = self.config.search.algorithm_config.get(\n \"search_rewards\"\n )\n scorer_names = search_rewards if search_rewards else [\"state score\"]\n\n elif isinstance(scorer, str):\n scorer_names = [scorer]\n else:\n scorer_names = list(scorer)\n\n if \"broken bonds\" in scorer_names:\n # Add broken bonds scorer if required\n self.scorers.load(BrokenBondsScorer(self.config))\n\n scorers = [self.scorers[name] for name in scorer_names]\n\n if self.config.post_processing.scorer_weights:\n scorers = [\n CombinedScorer(\n self.config,\n scorer_names,\n self.config.post_processing.scorer_weights,\n )\n ]\n\n return TreeAnalysis(self.tree, scorers)", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 11003}, "tests/test_finder.py::239": {"resolved_imports": ["aizynthfinder/aizynthfinder.py"], "used_names": [], "enclosing_function": "test_two_expansions_two_children", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/context/test_stock.py::474": {"resolved_imports": ["aizynthfinder/chem/__init__.py", "aizynthfinder/context/stock/__init__.py", "aizynthfinder/context/stock/queries.py", "aizynthfinder/tools/make_stock.py"], "used_names": ["extract_plain_smiles"], "enclosing_function": "test_extract_smiles_from_plain_file", "extracted_code": "# Source: aizynthfinder/tools/make_stock.py\ndef extract_plain_smiles(files: List[str]) -> _StrIterator:\n \"\"\"\n Extract SMILES from plain text files, one SMILES on each line.\n The SMILES are yielded to save memory.\n \"\"\"\n for filename in files:\n print(f\"Processing {filename}\", flush=True)\n with open(filename, \"r\") as fileobj:\n for line in fileobj:\n yield line.strip()", "n_imports_parsed": 7, "n_files_resolved": 4, "n_chars_extracted": 421}, "tests/context/test_mcts_config.py::75": {"resolved_imports": ["aizynthfinder/aizynthfinder.py", "aizynthfinder/context/config.py", "aizynthfinder/context/stock/__init__.py"], "used_names": ["pytest"], "enclosing_function": "test_update_search", "extracted_code": "", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 0}, "tests/utils/test_file_utils.py::48": {"resolved_imports": ["aizynthfinder/utils/files.py"], "used_names": ["os", "split_file"], "enclosing_function": "test_split_file_even", "extracted_code": "# Source: aizynthfinder/utils/files.py\ndef split_file(filename: str, nparts: int) -> List[str]:\n \"\"\"\n Split the content of a text file into a given number of temporary files\n\n :param filename: the path to the file to split\n :param nparts: the number of parts to create\n :return: list of filenames of the parts\n \"\"\"\n with open(filename, \"r\") as fileobj:\n lines = fileobj.read().splitlines()\n\n filenames = []\n batch_size, remainder = divmod(len(lines), nparts)\n stop = 0\n for part in range(1, nparts + 1):\n start = stop\n stop += batch_size + 1 if part <= remainder else batch_size\n filenames.append(tempfile.mktemp())\n with open(filenames[-1], \"w\") as fileobj:\n fileobj.write(\"\\n\".join(lines[start:stop]))\n return filenames", "n_imports_parsed": 6, "n_files_resolved": 1, "n_chars_extracted": 803}, "tests/mcts/test_multiobjective.py::43": {"resolved_imports": ["aizynthfinder/search/mcts/node.py", "aizynthfinder/search/mcts/__init__.py"], "used_names": [], "enclosing_function": "test_expand_root_node", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/retrostar/test_retrostar_nodes.py::139": {"resolved_imports": ["aizynthfinder/search/retrostar/nodes.py", "aizynthfinder/chem/serialization.py", "aizynthfinder/search/andor_trees.py"], "used_names": ["ReactionTreeFromAndOrTrace"], "enclosing_function": "test_conversion_to_reaction_tree", "extracted_code": "# Source: aizynthfinder/search/andor_trees.py\nclass ReactionTreeFromAndOrTrace(ReactionTreeLoader):\n \"\"\"Creates a reaction tree object from an AND/OR Trace\"\"\"\n\n def _load(self, andor_trace: nx.DiGraph, stock: Stock) -> None: # type: ignore\n \"\"\"\n :param andor_trace: the trace graph\n :param stock: stock object\n \"\"\"\n self._stock = stock\n self._trace_graph = andor_trace\n self._trace_root = self._find_root()\n\n self._add_node(\n self._unique_mol(self._trace_root.prop[\"mol\"]),\n depth=0,\n transform=0,\n in_stock=self._trace_root.prop[\"mol\"] in self._stock,\n )\n for node1, node2 in andor_trace.edges():\n if \"reaction\" in node2.prop and not andor_trace[node2]:\n continue\n rt_node1 = self._make_rt_node(node1)\n rt_node2 = self._make_rt_node(node2)\n self.tree.graph.add_edge(rt_node1, rt_node2)\n\n def _add_node_with_depth(\n self, node: Union[UniqueMolecule, FixedRetroReaction], base_node: TreeNodeMixin\n ) -> None:\n if node in self.tree.graph:\n return\n\n depth = nx.shortest_path_length(self._trace_graph, self._trace_root, base_node)\n if isinstance(node, UniqueMolecule):\n self._add_node(\n node, depth=depth, transform=depth // 2, in_stock=node in self._stock\n )\n else:\n self._add_node(node, depth=depth)\n\n def _find_root(self) -> TreeNodeMixin:\n for node, degree in self._trace_graph.in_degree(): # type: ignore\n if degree == 0:\n return node\n raise ValueError(\"Could not find root!\")\n\n def _make_rt_node(\n self, node: TreeNodeMixin\n ) -> Union[UniqueMolecule, FixedRetroReaction]:\n if \"mol\" in node.prop:\n unique_obj = self._unique_mol(node.prop[\"mol\"])\n self._add_node_with_depth(unique_obj, node)\n return unique_obj\n\n reaction_obj = self._unique_reaction(node.prop[\"reaction\"])\n reaction_obj.reactants = (\n tuple(self._unique_mol(child.prop[\"mol\"]) for child in node.children),\n )\n self._add_node_with_depth(reaction_obj, node)\n return reaction_obj", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 2267}, "tests/test_finder.py::300": {"resolved_imports": ["aizynthfinder/aizynthfinder.py"], "used_names": [], "enclosing_function": "test_three_expansions", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/chem/test_serialization.py::17": {"resolved_imports": ["aizynthfinder/chem/serialization.py", "aizynthfinder/chem/__init__.py"], "used_names": ["Molecule", "MoleculeSerializer"], "enclosing_function": "test_add_single_mol", "extracted_code": "# Source: aizynthfinder/chem/serialization.py\nclass MoleculeSerializer:\n \"\"\"\n Utility class for serializing molecules\n\n The id of the molecule to be serialized can be obtained with:\n\n .. code-block::\n\n serializer = MoleculeSerializer()\n mol = Molecule(smiles=\"CCCO\")\n idx = serializer[mol]\n\n which will take care of the serialization of the molecule.\n \"\"\"\n\n def __init__(self) -> None:\n self._store: Dict[int, Any] = {}\n\n def __getitem__(self, mol: Optional[aizynthfinder.chem.Molecule]) -> Optional[int]:\n if mol is None:\n return None\n\n id_ = id(mol)\n if id_ not in self._store:\n self._add_mol(mol)\n return id_\n\n @property\n def store(self) -> Dict[int, Any]:\n \"\"\"Return all serialized molecules as a dictionary\"\"\"\n return self._store\n\n def _add_mol(self, mol: aizynthfinder.chem.Molecule) -> None:\n id_ = id(mol)\n dict_ = {\"smiles\": mol.smiles, \"class\": mol.__class__.__name__}\n if isinstance(mol, aizynthfinder.chem.TreeMolecule):\n dict_[\"parent\"] = self[mol.parent]\n dict_[\"transform\"] = mol.transform\n if not mol.parent:\n dict_[\"smiles\"] = mol.original_smiles\n else:\n dict_[\"smiles\"] = mol.mapped_smiles\n self._store[id_] = dict_\n\n\n# Source: aizynthfinder/chem/__init__.py\n\"\"\"\nfrom aizynthfinder.chem.mol import (\n Molecule,\n MoleculeException,\n TreeMolecule,\n UniqueMolecule,\n none_molecule,\n)\nfrom aizynthfinder.chem.reaction import (\n FixedRetroReaction,\n RetroReaction,\n SmilesBasedRetroReaction,\n\nfrom aizynthfinder.chem.mol import (\n Molecule,\n MoleculeException,\n TreeMolecule,\n UniqueMolecule,\n none_molecule,\n)\nfrom aizynthfinder.chem.reaction import (\n FixedRetroReaction,\n RetroReaction,\n SmilesBasedRetroReaction,\n TemplatedRetroReaction,\n\n Molecule,\n MoleculeException,\n TreeMolecule,\n UniqueMolecule,\n none_molecule,\n)\nfrom aizynthfinder.chem.reaction import (\n FixedRetroReaction,\n RetroReaction,\n SmilesBasedRetroReaction,\n TemplatedRetroReaction,\n hash_reactions,\n\n MoleculeException,\n TreeMolecule,\n UniqueMolecule,\n none_molecule,\n)\nfrom aizynthfinder.chem.reaction import (\n FixedRetroReaction,\n RetroReaction,\n SmilesBasedRetroReaction,\n TemplatedRetroReaction,\n hash_reactions,\n)\n\n)\nfrom aizynthfinder.chem.serialization import (\n MoleculeDeserializer,\n MoleculeSerializer,\n deserialize_action,\n serialize_action,\n)", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 2588}, "tests/test_analysis.py::20": {"resolved_imports": ["aizynthfinder/analysis/__init__.py", "aizynthfinder/analysis/routes.py", "aizynthfinder/analysis/utils.py", "aizynthfinder/reactiontree.py", "aizynthfinder/search/mcts/__init__.py", "aizynthfinder/context/scoring/__init__.py"], "used_names": ["RouteSelectionArguments"], "enclosing_function": "test_sort_nodes", "extracted_code": "# Source: aizynthfinder/analysis/utils.py\nclass RouteSelectionArguments:\n \"\"\"\n Selection arguments for the tree analysis class\n\n If `return_all` is False, it will return at least `nmin` routes and if routes have the same\n score it will return them as well up to `nmax` routes.\n\n If `return_all` is True, it will return all solved routes if there is at least one is solved, otherwise\n the `nmin` and `nmax` will be used.\n \"\"\"\n\n nmin: int = 5\n nmax: int = 25\n return_all: bool = False", "n_imports_parsed": 10, "n_files_resolved": 6, "n_chars_extracted": 512}, "tests/test_reactiontree.py::93": {"resolved_imports": ["aizynthfinder/reactiontree.py"], "used_names": ["ReactionTree"], "enclosing_function": "test_route_node_depth_from_json", "extracted_code": "# Source: aizynthfinder/reactiontree.py\nclass ReactionTree:\n \"\"\"\n Encapsulation of a bipartite reaction tree of a single route.\n The nodes consists of either FixedRetroReaction or UniqueMolecule objects.\n\n The reaction tree is initialized at instantiation and is not supposed to\n be updated.\n\n :ivar graph: the bipartite graph\n :ivar is_solved: if all of the leaf nodes are in stock\n :ivar root: the root of the tree\n :ivar created_at_iteration: iteration the reaction tree was created\n \"\"\"\n\n def __init__(self) -> None:\n self.graph = nx.DiGraph()\n self.root = none_molecule()\n self.is_solved: bool = False\n self.created_at_iteration: Optional[int] = None\n\n @classmethod\n def from_dict(cls, tree_dict: StrDict) -> \"ReactionTree\":\n \"\"\"\n Create a new ReactionTree by parsing a dictionary.\n\n This is supposed to be the opposite of ``to_dict``,\n but because that format loses information, the returned\n object is not a full copy as the stock will only contain\n the list of molecules marked as ``in_stock`` in the dictionary.\n\n The returned object should be sufficient to e.g. generate an image of the route.\n\n :param tree_dict: the dictionary representation\n :returns: the reaction tree\n \"\"\"\n return ReactionTreeFromDict(tree_dict).tree\n\n @property\n def metadata(self) -> StrDict:\n \"\"\"Return a dicitionary with route metadata\"\"\"\n return {\n \"created_at_iteration\": self.created_at_iteration,\n \"is_solved\": self.is_solved,\n }\n\n def child_reactions(self, reaction: FixedRetroReaction) -> List[FixedRetroReaction]:\n \"\"\"\n Return the child reactions of a reaction node in the tree.\n\n :param reaction: the query node (reaction)\n :return: child reactions\n \"\"\"\n child_molecule_nodes = self.graph.successors(reaction)\n reaction_nodes = []\n for molecule_node in child_molecule_nodes:\n reaction_nodes.extend(list(self.graph.successors(molecule_node)))\n return reaction_nodes\n\n def depth(self, node: Union[UniqueMolecule, FixedRetroReaction]) -> int:\n \"\"\"\n Return the depth of a node in the route\n\n :param node: the query node\n :return: the depth\n \"\"\"\n return self.graph.nodes[node].get(\"depth\", -1)\n\n def distance_to(self, other: \"ReactionTree\") -> float:\n \"\"\"\n Calculate the distance to another reaction tree\n\n This is a simple distance based on a route similarity\n\n :param other: the reaction tree to compare to\n :return: the distance between the routes\n \"\"\"\n route1 = read_aizynthfinder_dict(self.to_dict())\n route2 = read_aizynthfinder_dict(other.to_dict())\n return 1.0 - float(simple_route_similarity([route1, route2])[0, 1])\n\n def hash_key(self) -> str:\n \"\"\"\n Calculates a hash code for the tree using the sha224 hash function recursively\n\n :return: the hash key\n \"\"\"\n return self._hash_func(self.root)\n\n def in_stock(self, node: Union[UniqueMolecule, FixedRetroReaction]) -> bool:\n \"\"\"\n Return if a node in the route is in stock\n\n Note that is a property set on creation and as such is not updated.\n\n :param node: the query node\n :return: if the molecule is in stock\n \"\"\"\n return self.graph.nodes[node].get(\"in_stock\", False)\n\n def is_branched(self) -> bool:\n \"\"\"\n Returns if the route is branched\n\n i.e. checks if the maximum depth is not equal to the number\n of reactions.\n \"\"\"\n nsteps = len(list(self.reactions()))\n max_depth = max(self.depth(leaf) for leaf in self.leafs())\n return nsteps != max_depth // 2\n\n def leafs(self) -> Iterable[UniqueMolecule]:\n \"\"\"\n Generates the molecules nodes of the reaction tree that has no predecessors,\n i.e. molecules that has not been broken down\n\n :yield: the next leaf molecule in the tree\n \"\"\"\n for node in self.graph:\n if isinstance(node, UniqueMolecule) and not self.graph[node]:\n yield node\n\n def molecules(self) -> Iterable[UniqueMolecule]:\n \"\"\"\n Generates the molecule nodes of the reaction tree\n\n :yield: the next molecule in the tree\n \"\"\"\n for node in self.graph:\n if isinstance(node, UniqueMolecule):\n yield node\n\n def parent_molecule(self, mol: UniqueMolecule) -> UniqueMolecule:\n \"\"\"Returns the parent molecule within the reaction tree.\n :param mol: the query node (molecule)\n :return: the parent molecule\n \"\"\"\n if mol is self.root:\n raise ValueError(\"Root molecule does not have any parent node.\")\n\n parent_reaction = list(self.graph.predecessors(mol))[0]\n parent_molecule = list(self.graph.predecessors(parent_reaction))[0]\n return parent_molecule\n\n def reactions(self) -> Iterable[FixedRetroReaction]:\n \"\"\"\n Generates the reaction nodes of the reaction tree\n\n :yield: the next reaction in the tree\n \"\"\"\n for node in self.graph:\n if not isinstance(node, Molecule):\n yield node\n\n def subtrees(self) -> Iterable[ReactionTree]:\n \"\"\"\n Generates the subtrees of this reaction tree a\n subtree is a reaction treee starting at a molecule node that has children.\n\n :yield: the next subtree\n \"\"\"\n\n def create_subtree(root_node):\n subtree = ReactionTree()\n subtree.root = root_node\n subtree.graph = dfs_tree(self.graph, root_node)\n for node in subtree.graph:\n prop = dict(self.graph.nodes[node])\n prop[\"depth\"] -= self.graph.nodes[root_node].get(\"depth\", 0)\n if \"transform\" in prop:\n prop[\"transform\"] -= self.graph.nodes[root_node].get(\"transform\", 0)\n subtree.graph.nodes[node].update(prop)\n subtree.is_solved = all(subtree.in_stock(node) for node in subtree.leafs())\n return subtree\n\n for node in self.molecules():\n if node is not self.root and self.graph[node]:\n yield create_subtree(node)\n\n def to_dict(self, include_metadata=False) -> StrDict:\n \"\"\"\n Returns the reaction tree as a dictionary in a pre-defined format.\n :param include_metadata: if True include metadata\n :return: the reaction tree\n \"\"\"\n return self._build_dict(self.root, include_metadata=include_metadata)\n\n def to_image(\n self,\n in_stock_colors: Optional[FrameColors] = None,\n show_all: bool = True,\n ) -> PilImage:\n \"\"\"\n Return a pictorial representation of the route\n\n :param in_stock_colors: the colors around molecules, defaults to {True: \"green\", False: \"orange\"}\n :param show_all: if True, also show nodes that are marked as hidden\n :return: the image of the route\n \"\"\"\n factory = RouteImageFactory(\n self.to_dict(), in_stock_colors=in_stock_colors, show_all=show_all\n )\n return factory.image\n\n def to_json(self, include_metadata=False) -> str:\n \"\"\"\n Returns the reaction tree as a JSON string in a pre-defined format.\n\n :return: the reaction tree\n \"\"\"\n return json.dumps(\n self.to_dict(include_metadata=include_metadata), sort_keys=False, indent=2\n )\n\n def _build_dict(\n self,\n node: Union[UniqueMolecule, FixedRetroReaction],\n dict_: Optional[StrDict] = None,\n include_metadata=False,\n ) -> StrDict:\n if dict_ is None:\n dict_ = {}\n\n if node is self.root and include_metadata:\n dict_[\"route_metadata\"] = self.metadata\n\n dict_[\"type\"] = \"mol\" if isinstance(node, Molecule) else \"reaction\"\n dict_[\"hide\"] = self.graph.nodes[node].get(\"hide\", False)\n dict_[\"smiles\"] = node.smiles\n if isinstance(node, UniqueMolecule):\n dict_[\"is_chemical\"] = True\n dict_[\"in_stock\"] = self.in_stock(node)\n elif isinstance(node, FixedRetroReaction):\n dict_[\"is_reaction\"] = True\n dict_[\"metadata\"] = dict(node.metadata)\n else:\n raise ValueError(\n f\"This is an invalid reaction tree. Unknown node type {type(node)}\"\n )\n\n dict_[\"children\"] = []\n\n children = list(self.graph.successors(node))\n if isinstance(node, FixedRetroReaction):\n children.sort(key=operator.attrgetter(\"weight\"))\n for child in children:\n child_dict = self._build_dict(child)\n dict_[\"children\"].append(child_dict)\n\n if not dict_[\"children\"]:\n del dict_[\"children\"]\n return dict_\n\n def _hash_func(self, node: Union[FixedRetroReaction, UniqueMolecule]) -> str:\n if isinstance(node, UniqueMolecule):\n hash_ = hashlib.sha224(node.inchi_key.encode())\n else:\n hash_ = hashlib.sha224(node.hash_key().encode())\n child_hashes = sorted(\n self._hash_func(child) for child in self.graph.successors(node)\n )\n for child_hash in child_hashes:\n hash_.update(child_hash.encode())\n return hash_.hexdigest()", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 9443}, "tests/mcts/test_serialization.py::28": {"resolved_imports": ["aizynthfinder/chem/__init__.py", "aizynthfinder/chem/serialization.py", "aizynthfinder/search/mcts/__init__.py"], "used_names": ["MctsNode", "MctsState", "MoleculeDeserializer", "MoleculeSerializer", "TreeMolecule"], "enclosing_function": "test_serialize_deserialize_state", "extracted_code": "# Source: aizynthfinder/chem/__init__.py\n Molecule,\n MoleculeException,\n TreeMolecule,\n UniqueMolecule,\n none_molecule,\n)\nfrom aizynthfinder.chem.reaction import (\n FixedRetroReaction,\n RetroReaction,\n SmilesBasedRetroReaction,\n TemplatedRetroReaction,\n hash_reactions,\n\n\n# Source: aizynthfinder/chem/serialization.py\nclass MoleculeSerializer:\n \"\"\"\n Utility class for serializing molecules\n\n The id of the molecule to be serialized can be obtained with:\n\n .. code-block::\n\n serializer = MoleculeSerializer()\n mol = Molecule(smiles=\"CCCO\")\n idx = serializer[mol]\n\n which will take care of the serialization of the molecule.\n \"\"\"\n\n def __init__(self) -> None:\n self._store: Dict[int, Any] = {}\n\n def __getitem__(self, mol: Optional[aizynthfinder.chem.Molecule]) -> Optional[int]:\n if mol is None:\n return None\n\n id_ = id(mol)\n if id_ not in self._store:\n self._add_mol(mol)\n return id_\n\n @property\n def store(self) -> Dict[int, Any]:\n \"\"\"Return all serialized molecules as a dictionary\"\"\"\n return self._store\n\n def _add_mol(self, mol: aizynthfinder.chem.Molecule) -> None:\n id_ = id(mol)\n dict_ = {\"smiles\": mol.smiles, \"class\": mol.__class__.__name__}\n if isinstance(mol, aizynthfinder.chem.TreeMolecule):\n dict_[\"parent\"] = self[mol.parent]\n dict_[\"transform\"] = mol.transform\n if not mol.parent:\n dict_[\"smiles\"] = mol.original_smiles\n else:\n dict_[\"smiles\"] = mol.mapped_smiles\n self._store[id_] = dict_\n\nclass MoleculeDeserializer:\n \"\"\"\n Utility class for deserializing molecules.\n The serialized molecules are created upon instantiation of the class.\n\n The deserialized molecules can be obtained with:\n\n .. code-block::\n\n deserializer = MoleculeDeserializer()\n mol = deserializer[idx]\n\n \"\"\"\n\n def __init__(self, store: Dict[int, Any]) -> None:\n self._objects: Dict[int, Any] = {}\n self._create_molecules(store)\n\n def __getitem__(self, id_: Optional[int]) -> Optional[aizynthfinder.chem.Molecule]:\n if id_ is None:\n return None\n return self._objects[id_]\n\n def get_tree_molecules(\n self, ids: Sequence[int]\n ) -> Sequence[aizynthfinder.chem.TreeMolecule]:\n \"\"\"\n Return multiple deserialized tree molecules\n\n :param ids: the list of IDs to deserialize\n :return: the molecule objects\n \"\"\"\n objects = []\n for id_ in ids:\n obj = self[id_]\n if obj is None or not isinstance(obj, aizynthfinder.chem.TreeMolecule):\n raise ValueError(f\"Failed to deserialize molecule with id {id_}\")\n objects.append(obj)\n return objects\n\n def _create_molecules(self, store: dict) -> None:\n for id_, spec in store.items():\n if isinstance(id_, str):\n id_ = int(id_)\n\n cls = spec[\"class\"]\n if \"parent\" in spec:\n spec[\"parent\"] = self[spec[\"parent\"]]\n\n kwargs = dict(spec)\n del kwargs[\"class\"]\n self._objects[id_] = getattr(aizynthfinder.chem, cls)(**kwargs)\n\n\n# Source: aizynthfinder/search/mcts/__init__.py\n\"\"\" Sub-package containing MCTS routines\n\"\"\"\nfrom aizynthfinder.search.mcts.node import MctsNode\nfrom aizynthfinder.search.mcts.search import MctsSearchTree\nfrom aizynthfinder.search.mcts.state import MctsState\n\nfrom aizynthfinder.search.mcts.node import MctsNode\nfrom aizynthfinder.search.mcts.search import MctsSearchTree\nfrom aizynthfinder.search.mcts.state import MctsState", "n_imports_parsed": 3, "n_files_resolved": 3, "n_chars_extracted": 3717}, "tests/utils/test_bonds.py::33": {"resolved_imports": ["aizynthfinder/chem/__init__.py", "aizynthfinder/utils/bonds.py"], "used_names": ["BrokenBonds", "SmilesBasedRetroReaction", "TreeMolecule"], "enclosing_function": "test_focussed_bonds_not_broken", "extracted_code": "# Source: aizynthfinder/chem/__init__.py\n Molecule,\n MoleculeException,\n TreeMolecule,\n UniqueMolecule,\n none_molecule,\n)\nfrom aizynthfinder.chem.reaction import (\n FixedRetroReaction,\n RetroReaction,\n SmilesBasedRetroReaction,\n TemplatedRetroReaction,\n hash_reactions,\n\n FixedRetroReaction,\n RetroReaction,\n SmilesBasedRetroReaction,\n TemplatedRetroReaction,\n hash_reactions,\n)\nfrom aizynthfinder.chem.serialization import (\n MoleculeDeserializer,\n MoleculeSerializer,\n deserialize_action,\n serialize_action,\n)\n\n\n# Source: aizynthfinder/utils/bonds.py\nclass BrokenBonds:\n \"\"\"\n A class to keep track of focussed bonds breaking in a target molecule.\n\n :param focussed_bonds: A list of focussed bond pairs. The bond pairs are represented\n as tuples of size 2. These bond pairs exist in the target molecule's atom bonds.\n \"\"\"\n\n def __init__(self, focussed_bonds: Sequence[Sequence[int]]) -> None:\n self.focussed_bonds = sort_bonds(focussed_bonds)\n self.filtered_focussed_bonds: List[Tuple[int, int]] = []\n\n def __call__(self, reaction: RetroReaction) -> List[Tuple[int, int]]:\n \"\"\"\n Provides a list of focussed bonds that break in any of the molecule's reactants.\n\n :param reaction: A retro reaction.\n :return: A list of all the focussed bonds that broke within the reactants\n that constitute the target molecule.\n \"\"\"\n self.filtered_focussed_bonds = self._get_filtered_focussed_bonds(reaction.mol)\n if not self.filtered_focussed_bonds:\n return []\n\n molecule_bonds = []\n for reactant in reaction.reactants[reaction.index]:\n molecule_bonds += reactant.mapped_atom_bonds\n\n broken_focussed_bonds = self._get_broken_frozen_bonds(\n sort_bonds(molecule_bonds)\n )\n return broken_focussed_bonds\n\n def _get_broken_frozen_bonds(\n self,\n molecule_bonds: List[Tuple[int, int]],\n ) -> List[Tuple[int, int]]:\n broken_focussed_bonds = list(\n set(self.filtered_focussed_bonds) - set(molecule_bonds)\n )\n return broken_focussed_bonds\n\n def _get_filtered_focussed_bonds(\n self, molecule: TreeMolecule\n ) -> List[Tuple[int, int]]:\n molecule_bonds = molecule.mapped_atom_bonds\n atom_maps = [atom_map for bonds in molecule_bonds for atom_map in bonds]\n\n filtered_focussed_bonds = []\n for idx1, idx2 in self.focussed_bonds:\n if idx1 in atom_maps and idx2 in atom_maps:\n filtered_focussed_bonds.append((idx1, idx2))\n return filtered_focussed_bonds", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 2670}, "tests/retrostar/test_retrostar.py::22": {"resolved_imports": ["aizynthfinder/search/retrostar/search_tree.py", "aizynthfinder/chem/serialization.py"], "used_names": [], "enclosing_function": "test_one_iteration_filter_unfeasible", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/chem/test_serialization.py::28": {"resolved_imports": ["aizynthfinder/chem/serialization.py", "aizynthfinder/chem/__init__.py"], "used_names": ["MoleculeSerializer", "TreeMolecule"], "enclosing_function": "test_add_tree_mol", "extracted_code": "# Source: aizynthfinder/chem/serialization.py\nclass MoleculeSerializer:\n \"\"\"\n Utility class for serializing molecules\n\n The id of the molecule to be serialized can be obtained with:\n\n .. code-block::\n\n serializer = MoleculeSerializer()\n mol = Molecule(smiles=\"CCCO\")\n idx = serializer[mol]\n\n which will take care of the serialization of the molecule.\n \"\"\"\n\n def __init__(self) -> None:\n self._store: Dict[int, Any] = {}\n\n def __getitem__(self, mol: Optional[aizynthfinder.chem.Molecule]) -> Optional[int]:\n if mol is None:\n return None\n\n id_ = id(mol)\n if id_ not in self._store:\n self._add_mol(mol)\n return id_\n\n @property\n def store(self) -> Dict[int, Any]:\n \"\"\"Return all serialized molecules as a dictionary\"\"\"\n return self._store\n\n def _add_mol(self, mol: aizynthfinder.chem.Molecule) -> None:\n id_ = id(mol)\n dict_ = {\"smiles\": mol.smiles, \"class\": mol.__class__.__name__}\n if isinstance(mol, aizynthfinder.chem.TreeMolecule):\n dict_[\"parent\"] = self[mol.parent]\n dict_[\"transform\"] = mol.transform\n if not mol.parent:\n dict_[\"smiles\"] = mol.original_smiles\n else:\n dict_[\"smiles\"] = mol.mapped_smiles\n self._store[id_] = dict_\n\n\n# Source: aizynthfinder/chem/__init__.py\n Molecule,\n MoleculeException,\n TreeMolecule,\n UniqueMolecule,\n none_molecule,\n)\nfrom aizynthfinder.chem.reaction import (\n FixedRetroReaction,\n RetroReaction,\n SmilesBasedRetroReaction,\n TemplatedRetroReaction,\n hash_reactions,", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 1662}, "tests/context/test_policy.py::49": {"resolved_imports": ["aizynthfinder/chem/__init__.py", "aizynthfinder/context/policy/__init__.py", "aizynthfinder/utils/exceptions.py"], "used_names": [], "enclosing_function": "test_load_expansion_policy_from_config_files", "extracted_code": "", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 0}, "tests/context/test_expansion_strategies.py::136": {"resolved_imports": ["aizynthfinder/chem/__init__.py", "aizynthfinder/context/policy/__init__.py", "aizynthfinder/utils/exceptions.py"], "used_names": ["MultiExpansionStrategy", "TreeMolecule"], "enclosing_function": "test_multi_expansion_strategy_cutoff", "extracted_code": "# Source: aizynthfinder/chem/__init__.py\n Molecule,\n MoleculeException,\n TreeMolecule,\n UniqueMolecule,\n none_molecule,\n)\nfrom aizynthfinder.chem.reaction import (\n FixedRetroReaction,\n RetroReaction,\n SmilesBasedRetroReaction,\n TemplatedRetroReaction,\n hash_reactions,\n\n\n# Source: aizynthfinder/context/policy/__init__.py\nfrom aizynthfinder.context.policy.expansion_strategies import (\n ExpansionStrategy,\n MultiExpansionStrategy,\n TemplateBasedDirectExpansionStrategy,\n TemplateBasedExpansionStrategy,\n)\nfrom aizynthfinder.context.policy.filter_strategies import (\n BondFilter,\n FilterStrategy,\n FrozenSubstructureFilter,\n QuickKerasFilter,\n ReactantsCountFilter,", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 722}, "tests/chem/test_serialization.py::85": {"resolved_imports": ["aizynthfinder/chem/serialization.py", "aizynthfinder/chem/__init__.py"], "used_names": ["MoleculeDeserializer", "MoleculeSerializer", "TreeMolecule"], "enclosing_function": "test_chaining", "extracted_code": "# Source: aizynthfinder/chem/serialization.py\nclass MoleculeSerializer:\n \"\"\"\n Utility class for serializing molecules\n\n The id of the molecule to be serialized can be obtained with:\n\n .. code-block::\n\n serializer = MoleculeSerializer()\n mol = Molecule(smiles=\"CCCO\")\n idx = serializer[mol]\n\n which will take care of the serialization of the molecule.\n \"\"\"\n\n def __init__(self) -> None:\n self._store: Dict[int, Any] = {}\n\n def __getitem__(self, mol: Optional[aizynthfinder.chem.Molecule]) -> Optional[int]:\n if mol is None:\n return None\n\n id_ = id(mol)\n if id_ not in self._store:\n self._add_mol(mol)\n return id_\n\n @property\n def store(self) -> Dict[int, Any]:\n \"\"\"Return all serialized molecules as a dictionary\"\"\"\n return self._store\n\n def _add_mol(self, mol: aizynthfinder.chem.Molecule) -> None:\n id_ = id(mol)\n dict_ = {\"smiles\": mol.smiles, \"class\": mol.__class__.__name__}\n if isinstance(mol, aizynthfinder.chem.TreeMolecule):\n dict_[\"parent\"] = self[mol.parent]\n dict_[\"transform\"] = mol.transform\n if not mol.parent:\n dict_[\"smiles\"] = mol.original_smiles\n else:\n dict_[\"smiles\"] = mol.mapped_smiles\n self._store[id_] = dict_\n\nclass MoleculeDeserializer:\n \"\"\"\n Utility class for deserializing molecules.\n The serialized molecules are created upon instantiation of the class.\n\n The deserialized molecules can be obtained with:\n\n .. code-block::\n\n deserializer = MoleculeDeserializer()\n mol = deserializer[idx]\n\n \"\"\"\n\n def __init__(self, store: Dict[int, Any]) -> None:\n self._objects: Dict[int, Any] = {}\n self._create_molecules(store)\n\n def __getitem__(self, id_: Optional[int]) -> Optional[aizynthfinder.chem.Molecule]:\n if id_ is None:\n return None\n return self._objects[id_]\n\n def get_tree_molecules(\n self, ids: Sequence[int]\n ) -> Sequence[aizynthfinder.chem.TreeMolecule]:\n \"\"\"\n Return multiple deserialized tree molecules\n\n :param ids: the list of IDs to deserialize\n :return: the molecule objects\n \"\"\"\n objects = []\n for id_ in ids:\n obj = self[id_]\n if obj is None or not isinstance(obj, aizynthfinder.chem.TreeMolecule):\n raise ValueError(f\"Failed to deserialize molecule with id {id_}\")\n objects.append(obj)\n return objects\n\n def _create_molecules(self, store: dict) -> None:\n for id_, spec in store.items():\n if isinstance(id_, str):\n id_ = int(id_)\n\n cls = spec[\"class\"]\n if \"parent\" in spec:\n spec[\"parent\"] = self[spec[\"parent\"]]\n\n kwargs = dict(spec)\n del kwargs[\"class\"]\n self._objects[id_] = getattr(aizynthfinder.chem, cls)(**kwargs)\n\n\n# Source: aizynthfinder/chem/__init__.py\n Molecule,\n MoleculeException,\n TreeMolecule,\n UniqueMolecule,\n none_molecule,\n)\nfrom aizynthfinder.chem.reaction import (\n FixedRetroReaction,\n RetroReaction,\n SmilesBasedRetroReaction,\n TemplatedRetroReaction,\n hash_reactions,", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 3289}, "tests/test_cli.py::211": {"resolved_imports": ["aizynthfinder/analysis/__init__.py", "aizynthfinder/chem/__init__.py", "aizynthfinder/interfaces/__init__.py", "aizynthfinder/interfaces/aizynthapp.py", "aizynthfinder/interfaces/aizynthcli.py", "aizynthfinder/reactiontree.py", "aizynthfinder/tools/cat_output.py", "aizynthfinder/tools/download_public_data.py", "aizynthfinder/tools/make_stock.py"], "used_names": [], "enclosing_function": "test_cli_multiple_smiles", "extracted_code": "", "n_imports_parsed": 17, "n_files_resolved": 9, "n_chars_extracted": 0}, "tests/chem/test_reaction.py::219": {"resolved_imports": ["aizynthfinder/chem/__init__.py"], "used_names": ["TemplatedRetroReaction", "TreeMolecule"], "enclosing_function": "test_mapped_atom_bonds_rdchiral", "extracted_code": "# Source: aizynthfinder/chem/__init__.py\n Molecule,\n MoleculeException,\n TreeMolecule,\n UniqueMolecule,\n none_molecule,\n)\nfrom aizynthfinder.chem.reaction import (\n FixedRetroReaction,\n RetroReaction,\n SmilesBasedRetroReaction,\n TemplatedRetroReaction,\n hash_reactions,\n\n RetroReaction,\n SmilesBasedRetroReaction,\n TemplatedRetroReaction,\n hash_reactions,\n)\nfrom aizynthfinder.chem.serialization import (\n MoleculeDeserializer,\n MoleculeSerializer,\n deserialize_action,\n serialize_action,\n)", "n_imports_parsed": 1, "n_files_resolved": 1, "n_chars_extracted": 544}, "tests/test_analysis.py::25": {"resolved_imports": ["aizynthfinder/analysis/__init__.py", "aizynthfinder/analysis/routes.py", "aizynthfinder/analysis/utils.py", "aizynthfinder/reactiontree.py", "aizynthfinder/search/mcts/__init__.py", "aizynthfinder/context/scoring/__init__.py"], "used_names": ["RouteSelectionArguments"], "enclosing_function": "test_sort_nodes", "extracted_code": "# Source: aizynthfinder/analysis/utils.py\nclass RouteSelectionArguments:\n \"\"\"\n Selection arguments for the tree analysis class\n\n If `return_all` is False, it will return at least `nmin` routes and if routes have the same\n score it will return them as well up to `nmax` routes.\n\n If `return_all` is True, it will return all solved routes if there is at least one is solved, otherwise\n the `nmin` and `nmax` will be used.\n \"\"\"\n\n nmin: int = 5\n nmax: int = 25\n return_all: bool = False", "n_imports_parsed": 10, "n_files_resolved": 6, "n_chars_extracted": 512}, "tests/retrostar/test_retrostar_nodes.py::142": {"resolved_imports": ["aizynthfinder/search/retrostar/nodes.py", "aizynthfinder/chem/serialization.py", "aizynthfinder/search/andor_trees.py"], "used_names": ["ReactionTreeFromAndOrTrace"], "enclosing_function": "test_conversion_to_reaction_tree", "extracted_code": "# Source: aizynthfinder/search/andor_trees.py\nclass ReactionTreeFromAndOrTrace(ReactionTreeLoader):\n \"\"\"Creates a reaction tree object from an AND/OR Trace\"\"\"\n\n def _load(self, andor_trace: nx.DiGraph, stock: Stock) -> None: # type: ignore\n \"\"\"\n :param andor_trace: the trace graph\n :param stock: stock object\n \"\"\"\n self._stock = stock\n self._trace_graph = andor_trace\n self._trace_root = self._find_root()\n\n self._add_node(\n self._unique_mol(self._trace_root.prop[\"mol\"]),\n depth=0,\n transform=0,\n in_stock=self._trace_root.prop[\"mol\"] in self._stock,\n )\n for node1, node2 in andor_trace.edges():\n if \"reaction\" in node2.prop and not andor_trace[node2]:\n continue\n rt_node1 = self._make_rt_node(node1)\n rt_node2 = self._make_rt_node(node2)\n self.tree.graph.add_edge(rt_node1, rt_node2)\n\n def _add_node_with_depth(\n self, node: Union[UniqueMolecule, FixedRetroReaction], base_node: TreeNodeMixin\n ) -> None:\n if node in self.tree.graph:\n return\n\n depth = nx.shortest_path_length(self._trace_graph, self._trace_root, base_node)\n if isinstance(node, UniqueMolecule):\n self._add_node(\n node, depth=depth, transform=depth // 2, in_stock=node in self._stock\n )\n else:\n self._add_node(node, depth=depth)\n\n def _find_root(self) -> TreeNodeMixin:\n for node, degree in self._trace_graph.in_degree(): # type: ignore\n if degree == 0:\n return node\n raise ValueError(\"Could not find root!\")\n\n def _make_rt_node(\n self, node: TreeNodeMixin\n ) -> Union[UniqueMolecule, FixedRetroReaction]:\n if \"mol\" in node.prop:\n unique_obj = self._unique_mol(node.prop[\"mol\"])\n self._add_node_with_depth(unique_obj, node)\n return unique_obj\n\n reaction_obj = self._unique_reaction(node.prop[\"reaction\"])\n reaction_obj.reactants = (\n tuple(self._unique_mol(child.prop[\"mol\"]) for child in node.children),\n )\n self._add_node_with_depth(reaction_obj, node)\n return reaction_obj", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 2267}, "tests/retrostar/test_retrostar.py::90": {"resolved_imports": ["aizynthfinder/search/retrostar/search_tree.py", "aizynthfinder/chem/serialization.py"], "used_names": ["MoleculeSerializer", "SearchTree"], "enclosing_function": "test_serialization_deserialization", "extracted_code": "# Source: aizynthfinder/search/retrostar/search_tree.py\nclass SearchTree(AndOrSearchTreeBase):\n \"\"\"\n Encapsulation of the Retro* search tree (an AND/OR tree).\n\n :ivar config: settings of the tree search algorithm\n :ivar root: the root node\n\n :param config: settings of the tree search algorithm\n :param root_smiles: the root will be set to a node representing this molecule, defaults to None\n \"\"\"\n\n def __init__(\n self, config: Configuration, root_smiles: Optional[str] = None\n ) -> None:\n super().__init__(config, root_smiles)\n self._mol_nodes: List[MoleculeNode] = []\n self._logger = logger()\n self.molecule_cost = MoleculeCost(config)\n\n if root_smiles:\n self.root: Optional[MoleculeNode] = MoleculeNode.create_root(\n root_smiles, config, self.molecule_cost\n )\n self._mol_nodes.append(self.root)\n else:\n self.root = None\n\n self._routes: List[ReactionTree] = []\n\n self.profiling = {\n \"expansion_calls\": 0,\n \"reactants_generations\": 0,\n }\n\n @classmethod\n def from_json(cls, filename: str, config: Configuration) -> SearchTree:\n \"\"\"\n Create a new search tree by deserialization from a JSON file\n\n :param filename: the path to the JSON node\n :param config: the configuration of the search tree\n :return: a deserialized tree\n \"\"\"\n\n def _find_mol_nodes(node):\n for child_ in node.children:\n tree._mol_nodes.append(child_) # pylint: disable=protected-access\n for grandchild in child_.children:\n _find_mol_nodes(grandchild)\n\n tree = cls(config)\n with open(filename, \"r\") as fileobj:\n dict_ = json.load(fileobj)\n mol_deser = MoleculeDeserializer(dict_[\"molecules\"])\n tree.root = MoleculeNode.from_dict(\n dict_[\"tree\"], config, mol_deser, tree.molecule_cost\n )\n tree._mol_nodes.append(tree.root) # pylint: disable=protected-access\n for child in tree.root.children:\n _find_mol_nodes(child)\n return tree\n\n @property\n def mol_nodes(self) -> Sequence[MoleculeNode]: # type: ignore\n \"\"\"Return the molecule nodes of the tree\"\"\"\n return self._mol_nodes\n\n def one_iteration(self) -> bool:\n \"\"\"\n Perform one iteration of\n 1. Selection\n 2. Expansion\n 3. Update\n\n :raises StopIteration: if the search should be pre-maturely terminated\n :return: if a solution was found\n :rtype: bool\n \"\"\"\n if self.root is None:\n raise ValueError(\"Root is undefined. Cannot make an iteration\")\n\n self._routes = []\n\n next_node = self._select()\n\n if not next_node:\n self._logger.debug(\"No expandable nodes in Retro* iteration\")\n raise StopIteration\n\n self._expand(next_node)\n\n if not next_node.children:\n next_node.expandable = False\n\n self._update(next_node)\n\n return self.root.solved\n\n def routes(self) -> List[ReactionTree]:\n \"\"\"\n Extracts and returns routes from the AND/OR tree\n\n :return: the routes\n \"\"\"\n if self.root is None:\n return []\n if not self._routes:\n self._routes = SplitAndOrTree(self.root, self.config.stock).routes\n return self._routes\n\n def serialize(self, filename: str) -> None:\n \"\"\"\n Seralize the search tree to a JSON file\n\n :param filename: the path to the JSON file\n :type filename: str\n \"\"\"\n if self.root is None:\n raise ValueError(\"Cannot serialize tree as root is not defined\")\n\n mol_ser = MoleculeSerializer()\n dict_ = {\"tree\": self.root.serialize(mol_ser), \"molecules\": mol_ser.store}\n with open(filename, \"w\") as fileobj:\n json.dump(dict_, fileobj, indent=2)\n\n def _expand(self, node: MoleculeNode) -> None:\n reactions, priors = self.config.expansion_policy([node.mol])\n self.profiling[\"expansion_calls\"] += 1\n\n if not reactions:\n return\n\n costs = -np.log(np.clip(priors, 1e-3, 1.0))\n reactions_to_expand = []\n reaction_costs = []\n for reaction, cost in zip(reactions, costs):\n try:\n self.profiling[\"reactants_generations\"] += 1\n _ = reaction.reactants\n except: # pylint: disable=bare-except\n continue\n if not reaction.reactants:\n continue\n for idx, _ in enumerate(reaction.reactants):\n rxn_copy = reaction.copy(idx)\n if self._filter_reaction(rxn_copy):\n continue\n reactions_to_expand.append(rxn_copy)\n reaction_costs.append(cost)\n\n for cost, rxn in zip(reaction_costs, reactions_to_expand):\n new_nodes = node.add_stub(cost, rxn)\n self._mol_nodes.extend(new_nodes)\n\n def _filter_reaction(self, reaction: RetroReaction) -> bool:\n if not self.config.filter_policy.selection:\n return False\n try:\n self.config.filter_policy(reaction)\n except RejectionException as err:\n self._logger.debug(str(err))\n return True\n return False\n\n def _select(self) -> Optional[MoleculeNode]:\n scores = np.asarray(\n [\n node.target_value if node.expandable else np.inf\n for node in self._mol_nodes\n ]\n )\n\n if scores.min() == np.inf:\n return None\n\n return self._mol_nodes[int(np.argmin(scores))]\n\n @staticmethod\n def _update(node: MoleculeNode) -> None:\n v_delta = node.close()\n if node.parent and np.isfinite(v_delta):\n node.parent.update(v_delta, from_mol=node.mol)\n\n\n# Source: aizynthfinder/chem/serialization.py\nclass MoleculeSerializer:\n \"\"\"\n Utility class for serializing molecules\n\n The id of the molecule to be serialized can be obtained with:\n\n .. code-block::\n\n serializer = MoleculeSerializer()\n mol = Molecule(smiles=\"CCCO\")\n idx = serializer[mol]\n\n which will take care of the serialization of the molecule.\n \"\"\"\n\n def __init__(self) -> None:\n self._store: Dict[int, Any] = {}\n\n def __getitem__(self, mol: Optional[aizynthfinder.chem.Molecule]) -> Optional[int]:\n if mol is None:\n return None\n\n id_ = id(mol)\n if id_ not in self._store:\n self._add_mol(mol)\n return id_\n\n @property\n def store(self) -> Dict[int, Any]:\n \"\"\"Return all serialized molecules as a dictionary\"\"\"\n return self._store\n\n def _add_mol(self, mol: aizynthfinder.chem.Molecule) -> None:\n id_ = id(mol)\n dict_ = {\"smiles\": mol.smiles, \"class\": mol.__class__.__name__}\n if isinstance(mol, aizynthfinder.chem.TreeMolecule):\n dict_[\"parent\"] = self[mol.parent]\n dict_[\"transform\"] = mol.transform\n if not mol.parent:\n dict_[\"smiles\"] = mol.original_smiles\n else:\n dict_[\"smiles\"] = mol.mapped_smiles\n self._store[id_] = dict_", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 7318}, "tests/context/test_collection.py::40": {"resolved_imports": ["aizynthfinder/context/collection.py"], "used_names": ["pytest"], "enclosing_function": "test_get_item", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/test_reactiontree.py::23": {"resolved_imports": ["aizynthfinder/reactiontree.py"], "used_names": [], "enclosing_function": "test_mcts_route_to_reactiontree", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/test_cli.py::440": {"resolved_imports": ["aizynthfinder/analysis/__init__.py", "aizynthfinder/chem/__init__.py", "aizynthfinder/interfaces/__init__.py", "aizynthfinder/interfaces/aizynthapp.py", "aizynthfinder/interfaces/aizynthcli.py", "aizynthfinder/reactiontree.py", "aizynthfinder/tools/cat_output.py", "aizynthfinder/tools/download_public_data.py", "aizynthfinder/tools/make_stock.py"], "used_names": ["glob", "os", "yaml"], "enclosing_function": "test_download_public_data", "extracted_code": "", "n_imports_parsed": 17, "n_files_resolved": 9, "n_chars_extracted": 0}, "tests/mcts/test_tree.py::36": {"resolved_imports": [], "used_names": [], "enclosing_function": "test_route_to_node", "extracted_code": "", "n_imports_parsed": 0, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/utils/test_file_utils.py::63": {"resolved_imports": ["aizynthfinder/utils/files.py"], "used_names": ["os", "split_file"], "enclosing_function": "test_split_file_odd", "extracted_code": "# Source: aizynthfinder/utils/files.py\ndef split_file(filename: str, nparts: int) -> List[str]:\n \"\"\"\n Split the content of a text file into a given number of temporary files\n\n :param filename: the path to the file to split\n :param nparts: the number of parts to create\n :return: list of filenames of the parts\n \"\"\"\n with open(filename, \"r\") as fileobj:\n lines = fileobj.read().splitlines()\n\n filenames = []\n batch_size, remainder = divmod(len(lines), nparts)\n stop = 0\n for part in range(1, nparts + 1):\n start = stop\n stop += batch_size + 1 if part <= remainder else batch_size\n filenames.append(tempfile.mktemp())\n with open(filenames[-1], \"w\") as fileobj:\n fileobj.write(\"\\n\".join(lines[start:stop]))\n return filenames", "n_imports_parsed": 6, "n_files_resolved": 1, "n_chars_extracted": 803}, "tests/retrostar/test_retrostar_nodes.py::105": {"resolved_imports": ["aizynthfinder/search/retrostar/nodes.py", "aizynthfinder/chem/serialization.py", "aizynthfinder/search/andor_trees.py"], "used_names": ["MoleculeDeserializer", "MoleculeNode", "MoleculeSerializer"], "enclosing_function": "test_serialization_deserialization", "extracted_code": "# Source: aizynthfinder/search/retrostar/nodes.py\nclass MoleculeNode(TreeNodeMixin):\n \"\"\"\n An OR node representing a molecule\n\n :ivar cost: the cost of synthesizing the molecule\n :ivar expandable: if True, this node is part of the frontier\n :ivar mol: the molecule represented by the node\n :ivar in_stock: if True the molecule is in stock and hence should not be expanded\n :ivar parent: the parent of the node\n :ivar solved: if True the molecule is in stock or at least one child node is solved\n :ivar value: the current rn(m|T)\n\n :param mol: the molecule to be represented by the node\n :param config: the configuration of the search\n :param parent: the parent of the node, optional\n \"\"\"\n\n def __init__(\n self,\n mol: TreeMolecule,\n config: Configuration,\n molecule_cost: MoleculeCost,\n parent: Optional[ReactionNode] = None,\n ) -> None:\n self.mol = mol\n self._config = config\n self.molecule_cost = molecule_cost\n self.cost = self.molecule_cost(mol)\n self.value = self.cost\n self.in_stock = mol in config.stock\n self.parent = parent\n\n self._children: List[ReactionNode] = []\n self.solved = self.in_stock\n # Makes it unexpandable if we have reached maximum depth\n self.expandable = self.mol.transform < self._config.search.max_transforms\n\n if self.in_stock:\n self.expandable = False\n self.value = 0\n\n @classmethod\n def create_root(\n cls, smiles: str, config: Configuration, molecule_cost: MoleculeCost\n ) -> \"MoleculeNode\":\n \"\"\"\n Create a root node for a tree using a SMILES.\n\n :param smiles: the SMILES representation of the root state\n :param config: settings of the tree search algorithm\n :return: the created node\n \"\"\"\n mol = TreeMolecule(parent=None, transform=0, smiles=smiles)\n return MoleculeNode(mol=mol, config=config, molecule_cost=molecule_cost)\n\n @classmethod\n def from_dict(\n cls,\n dict_: StrDict,\n config: Configuration,\n molecules: MoleculeDeserializer,\n molecule_cost: MoleculeCost,\n parent: Optional[ReactionNode] = None,\n ) -> \"MoleculeNode\":\n \"\"\"\n Create a new node from a dictionary, i.e. deserialization\n\n :param dict_: the serialized node\n :param config: settings of the tree search algorithm\n :param molecules: the deserialized molecules\n :param parent: the parent node\n :return: a deserialized node\n \"\"\"\n mol = molecules.get_tree_molecules([dict_[\"mol\"]])[0]\n node = MoleculeNode(mol, config, molecule_cost, parent)\n node.molecule_cost = molecule_cost\n for attr in [\"cost\", \"expandable\", \"value\"]:\n setattr(node, attr, dict_[attr])\n node.children = [\n ReactionNode.from_dict(\n child, config, molecules, node.molecule_cost, parent=node\n )\n for child in dict_[\"children\"]\n ]\n return node\n\n @property # type: ignore\n def children(self) -> List[ReactionNode]: # type: ignore\n \"\"\"Gives the reaction children nodes\"\"\"\n return self._children\n\n @children.setter\n def children(self, value: List[ReactionNode]) -> None:\n self._children = value\n\n @property\n def target_value(self) -> float:\n \"\"\"\n The V_t(m|T) value,\n the current cost of the tree containing this node\n\n :return: the value\n \"\"\"\n if self.parent:\n return self.parent.target_value\n return self.value\n\n @property\n def prop(self) -> StrDict:\n return {\"solved\": self.solved, \"mol\": self.mol}\n\n def add_stub(self, cost: float, reaction: RetroReaction) -> Sequence[MoleculeNode]:\n \"\"\"\n Add a stub / sub-tree to this node\n\n :param cost: the cost of the reaction\n :param reaction: the reaction creating the stub\n :return: list of all newly added molecular nodes\n \"\"\"\n reactants = reaction.reactants[reaction.index]\n if not reactants:\n return []\n\n ancestors = self.ancestors()\n for mol in reactants:\n if mol in ancestors:\n return []\n\n rxn_node = ReactionNode.create_stub(\n cost=cost,\n reaction=reaction,\n parent=self,\n config=self._config,\n )\n self._children.append(rxn_node)\n\n return rxn_node.children\n\n def ancestors(self) -> Set[TreeMolecule]:\n \"\"\"\n Return the ancestors of this node\n\n :return: the ancestors\n :rtype: set\n \"\"\"\n if not self.parent:\n return {self.mol}\n\n ancestors = self.parent.parent.ancestors()\n ancestors.add(self.mol)\n return ancestors\n\n def close(self) -> float:\n \"\"\"\n Updates the values of this node after expanding it.\n\n :return: the delta V value\n :rtype: float\n \"\"\"\n self.solved = any(child.solved for child in self.children)\n if self.children:\n new_value = np.min([child.value for child in self.children])\n else:\n new_value = np.inf\n\n v_delta = new_value - self.value\n self.value = new_value\n\n self.expandable = False\n return v_delta\n\n def serialize(self, molecule_store: MoleculeSerializer) -> StrDict:\n \"\"\"\n Serialize the node object to a dictionary\n\n :param molecule_store: the serialized molecules\n :return: the serialized node\n \"\"\"\n dict_ = {attr: getattr(self, attr) for attr in [\"cost\", \"expandable\", \"value\"]}\n dict_[\"mol\"] = molecule_store[self.mol]\n dict_[\"children\"] = [child.serialize(molecule_store) for child in self.children]\n return dict_\n\n def update(self, solved: bool) -> None:\n \"\"\"\n Update the node as part of the update algorithm,\n calling the `update()` method of its parent if available.\n\n :param solved: if the child node was solved\n \"\"\"\n new_value = np.min([child.value for child in self.children])\n new_solv = self.solved or solved\n updated = (self.value != new_value) or (self.solved != new_solv)\n\n v_delta = new_value - self.value\n self.value = new_value\n self.solved = new_solv\n\n if updated and self.parent:\n self.parent.update(v_delta, from_mol=self.mol)\n\n\n# Source: aizynthfinder/chem/serialization.py\nclass MoleculeSerializer:\n \"\"\"\n Utility class for serializing molecules\n\n The id of the molecule to be serialized can be obtained with:\n\n .. code-block::\n\n serializer = MoleculeSerializer()\n mol = Molecule(smiles=\"CCCO\")\n idx = serializer[mol]\n\n which will take care of the serialization of the molecule.\n \"\"\"\n\n def __init__(self) -> None:\n self._store: Dict[int, Any] = {}\n\n def __getitem__(self, mol: Optional[aizynthfinder.chem.Molecule]) -> Optional[int]:\n if mol is None:\n return None\n\n id_ = id(mol)\n if id_ not in self._store:\n self._add_mol(mol)\n return id_\n\n @property\n def store(self) -> Dict[int, Any]:\n \"\"\"Return all serialized molecules as a dictionary\"\"\"\n return self._store\n\n def _add_mol(self, mol: aizynthfinder.chem.Molecule) -> None:\n id_ = id(mol)\n dict_ = {\"smiles\": mol.smiles, \"class\": mol.__class__.__name__}\n if isinstance(mol, aizynthfinder.chem.TreeMolecule):\n dict_[\"parent\"] = self[mol.parent]\n dict_[\"transform\"] = mol.transform\n if not mol.parent:\n dict_[\"smiles\"] = mol.original_smiles\n else:\n dict_[\"smiles\"] = mol.mapped_smiles\n self._store[id_] = dict_\n\nclass MoleculeDeserializer:\n \"\"\"\n Utility class for deserializing molecules.\n The serialized molecules are created upon instantiation of the class.\n\n The deserialized molecules can be obtained with:\n\n .. code-block::\n\n deserializer = MoleculeDeserializer()\n mol = deserializer[idx]\n\n \"\"\"\n\n def __init__(self, store: Dict[int, Any]) -> None:\n self._objects: Dict[int, Any] = {}\n self._create_molecules(store)\n\n def __getitem__(self, id_: Optional[int]) -> Optional[aizynthfinder.chem.Molecule]:\n if id_ is None:\n return None\n return self._objects[id_]\n\n def get_tree_molecules(\n self, ids: Sequence[int]\n ) -> Sequence[aizynthfinder.chem.TreeMolecule]:\n \"\"\"\n Return multiple deserialized tree molecules\n\n :param ids: the list of IDs to deserialize\n :return: the molecule objects\n \"\"\"\n objects = []\n for id_ in ids:\n obj = self[id_]\n if obj is None or not isinstance(obj, aizynthfinder.chem.TreeMolecule):\n raise ValueError(f\"Failed to deserialize molecule with id {id_}\")\n objects.append(obj)\n return objects\n\n def _create_molecules(self, store: dict) -> None:\n for id_, spec in store.items():\n if isinstance(id_, str):\n id_ = int(id_)\n\n cls = spec[\"class\"]\n if \"parent\" in spec:\n spec[\"parent\"] = self[spec[\"parent\"]]\n\n kwargs = dict(spec)\n del kwargs[\"class\"]\n self._objects[id_] = getattr(aizynthfinder.chem, cls)(**kwargs)", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 9488}, "tests/test_analysis.py::52": {"resolved_imports": ["aizynthfinder/analysis/__init__.py", "aizynthfinder/analysis/routes.py", "aizynthfinder/analysis/utils.py", "aizynthfinder/reactiontree.py", "aizynthfinder/search/mcts/__init__.py", "aizynthfinder/context/scoring/__init__.py"], "used_names": ["RouteSelectionArguments"], "enclosing_function": "test_sort_nodes_return_all", "extracted_code": "# Source: aizynthfinder/analysis/utils.py\nclass RouteSelectionArguments:\n \"\"\"\n Selection arguments for the tree analysis class\n\n If `return_all` is False, it will return at least `nmin` routes and if routes have the same\n score it will return them as well up to `nmax` routes.\n\n If `return_all` is True, it will return all solved routes if there is at least one is solved, otherwise\n the `nmin` and `nmax` will be used.\n \"\"\"\n\n nmin: int = 5\n nmax: int = 25\n return_all: bool = False", "n_imports_parsed": 10, "n_files_resolved": 6, "n_chars_extracted": 512}, "tests/breadth_first/test_nodes.py::72": {"resolved_imports": ["aizynthfinder/search/breadth_first/nodes.py", "aizynthfinder/chem/serialization.py"], "used_names": ["MoleculeDeserializer", "MoleculeNode", "MoleculeSerializer"], "enclosing_function": "test_serialization_deserialization", "extracted_code": "# Source: aizynthfinder/search/breadth_first/nodes.py\nclass MoleculeNode(TreeNodeMixin):\n \"\"\"\n An OR node representing a molecule\n\n :ivar expandable: if True, this node is part of the frontier\n :ivar mol: the molecule represented by the node\n :ivar in_stock: if True the molecule is in stock and hence should not be expanded\n :ivar parent: the parent of the node\n\n :param mol: the molecule to be represented by the node\n :param config: the configuration of the search\n :param parent: the parent of the node, optional\n \"\"\"\n\n def __init__(\n self,\n mol: TreeMolecule,\n config: Configuration,\n parent: Optional[ReactionNode] = None,\n ) -> None:\n self.mol = mol\n self._config = config\n self.in_stock = mol in config.stock\n self.parent = parent\n\n self._children: List[ReactionNode] = []\n # Makes it unexpandable if we have reached maximum depth\n self.expandable = self.mol.transform < self._config.search.max_transforms\n\n if self.in_stock:\n self.expandable = False\n\n @classmethod\n def create_root(cls, smiles: str, config: Configuration) -> \"MoleculeNode\":\n \"\"\"\n Create a root node for a tree using a SMILES.\n\n :param smiles: the SMILES representation of the root state\n :param config: settings of the tree search algorithm\n :return: the created node\n \"\"\"\n mol = TreeMolecule(parent=None, transform=0, smiles=smiles)\n return MoleculeNode(mol=mol, config=config)\n\n @classmethod\n def from_dict(\n cls,\n dict_: StrDict,\n config: Configuration,\n molecules: MoleculeDeserializer,\n parent: Optional[ReactionNode] = None,\n ) -> \"MoleculeNode\":\n \"\"\"\n Create a new node from a dictionary, i.e. deserialization\n\n :param dict_: the serialized node\n :param config: settings of the tree search algorithm\n :param molecules: the deserialized molecules\n :param parent: the parent node\n :return: a deserialized node\n \"\"\"\n mol = molecules.get_tree_molecules([dict_[\"mol\"]])[0]\n node = MoleculeNode(mol, config, parent)\n node.expandable = dict_[\"expandable\"]\n node.children = [\n ReactionNode.from_dict(child, config, molecules, parent=node)\n for child in dict_[\"children\"]\n ]\n return node\n\n @property # type: ignore\n def children(self) -> List[ReactionNode]: # type: ignore\n \"\"\"Gives the reaction children nodes\"\"\"\n return self._children\n\n @children.setter\n def children(self, value: List[ReactionNode]) -> None:\n self._children = value\n\n @property\n def prop(self) -> StrDict:\n return {\"solved\": self.in_stock, \"mol\": self.mol}\n\n def add_stub(self, reaction: RetroReaction) -> Sequence[MoleculeNode]:\n \"\"\"\n Add a stub / sub-tree to this node\n\n :param reaction: the reaction creating the stub\n :return: list of all newly added molecular nodes\n \"\"\"\n reactants = reaction.reactants[reaction.index]\n if not reactants:\n return []\n\n ancestors = self.ancestors()\n for mol in reactants:\n if mol in ancestors:\n return []\n\n rxn_node = ReactionNode.create_stub(\n reaction=reaction, parent=self, config=self._config\n )\n self._children.append(rxn_node)\n\n return rxn_node.children\n\n def ancestors(self) -> Set[TreeMolecule]:\n \"\"\"\n Return the ancestors of this node\n\n :return: the ancestors\n :rtype: set\n \"\"\"\n if not self.parent:\n return {self.mol}\n\n ancestors = self.parent.parent.ancestors()\n ancestors.add(self.mol)\n return ancestors\n\n def serialize(self, molecule_store: MoleculeSerializer) -> StrDict:\n \"\"\"\n Serialize the node object to a dictionary\n\n :param molecule_store: the serialized molecules\n :return: the serialized node\n \"\"\"\n dict_: StrDict = {\"expandable\": self.expandable}\n dict_[\"mol\"] = molecule_store[self.mol]\n dict_[\"children\"] = [child.serialize(molecule_store) for child in self.children]\n return dict_\n\n\n# Source: aizynthfinder/chem/serialization.py\nclass MoleculeSerializer:\n \"\"\"\n Utility class for serializing molecules\n\n The id of the molecule to be serialized can be obtained with:\n\n .. code-block::\n\n serializer = MoleculeSerializer()\n mol = Molecule(smiles=\"CCCO\")\n idx = serializer[mol]\n\n which will take care of the serialization of the molecule.\n \"\"\"\n\n def __init__(self) -> None:\n self._store: Dict[int, Any] = {}\n\n def __getitem__(self, mol: Optional[aizynthfinder.chem.Molecule]) -> Optional[int]:\n if mol is None:\n return None\n\n id_ = id(mol)\n if id_ not in self._store:\n self._add_mol(mol)\n return id_\n\n @property\n def store(self) -> Dict[int, Any]:\n \"\"\"Return all serialized molecules as a dictionary\"\"\"\n return self._store\n\n def _add_mol(self, mol: aizynthfinder.chem.Molecule) -> None:\n id_ = id(mol)\n dict_ = {\"smiles\": mol.smiles, \"class\": mol.__class__.__name__}\n if isinstance(mol, aizynthfinder.chem.TreeMolecule):\n dict_[\"parent\"] = self[mol.parent]\n dict_[\"transform\"] = mol.transform\n if not mol.parent:\n dict_[\"smiles\"] = mol.original_smiles\n else:\n dict_[\"smiles\"] = mol.mapped_smiles\n self._store[id_] = dict_\n\nclass MoleculeDeserializer:\n \"\"\"\n Utility class for deserializing molecules.\n The serialized molecules are created upon instantiation of the class.\n\n The deserialized molecules can be obtained with:\n\n .. code-block::\n\n deserializer = MoleculeDeserializer()\n mol = deserializer[idx]\n\n \"\"\"\n\n def __init__(self, store: Dict[int, Any]) -> None:\n self._objects: Dict[int, Any] = {}\n self._create_molecules(store)\n\n def __getitem__(self, id_: Optional[int]) -> Optional[aizynthfinder.chem.Molecule]:\n if id_ is None:\n return None\n return self._objects[id_]\n\n def get_tree_molecules(\n self, ids: Sequence[int]\n ) -> Sequence[aizynthfinder.chem.TreeMolecule]:\n \"\"\"\n Return multiple deserialized tree molecules\n\n :param ids: the list of IDs to deserialize\n :return: the molecule objects\n \"\"\"\n objects = []\n for id_ in ids:\n obj = self[id_]\n if obj is None or not isinstance(obj, aizynthfinder.chem.TreeMolecule):\n raise ValueError(f\"Failed to deserialize molecule with id {id_}\")\n objects.append(obj)\n return objects\n\n def _create_molecules(self, store: dict) -> None:\n for id_, spec in store.items():\n if isinstance(id_, str):\n id_ = int(id_)\n\n cls = spec[\"class\"]\n if \"parent\" in spec:\n spec[\"parent\"] = self[spec[\"parent\"]]\n\n kwargs = dict(spec)\n del kwargs[\"class\"]\n self._objects[id_] = getattr(aizynthfinder.chem, cls)(**kwargs)", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 7265}, "tests/mcts/test_multiobjective.py::102": {"resolved_imports": ["aizynthfinder/search/mcts/node.py", "aizynthfinder/search/mcts/__init__.py"], "used_names": ["MctsSearchTree"], "enclosing_function": "test_setup_mo_tree", "extracted_code": "# Source: aizynthfinder/search/mcts/__init__.py\n\"\"\"\nfrom aizynthfinder.search.mcts.node import MctsNode\nfrom aizynthfinder.search.mcts.search import MctsSearchTree\nfrom aizynthfinder.search.mcts.state import MctsState", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 217}, "tests/retrostar/test_retrostar_nodes.py::13": {"resolved_imports": ["aizynthfinder/search/retrostar/nodes.py", "aizynthfinder/chem/serialization.py", "aizynthfinder/search/andor_trees.py"], "used_names": [], "enclosing_function": "test_create_root_node", "extracted_code": "", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 0}, "tests/utils/test_file_utils.py::144": {"resolved_imports": ["aizynthfinder/utils/files.py"], "used_names": ["pytest", "read_datafile", "save_datafile"], "enclosing_function": "test_save_load_datafile_roundtrip", "extracted_code": "# Source: aizynthfinder/utils/files.py\ndef read_datafile(filename: Union[str, Path]) -> pd.DataFrame:\n \"\"\"\n Read aizynth output from disc in either .hdf5 or .json format\n\n :param filename: the path to the data\n :return: the loaded data\n \"\"\"\n filename_str = str(filename)\n if filename_str.endswith(\".hdf5\") or filename_str.endswith(\".hdf\"):\n return pd.read_hdf(filename, \"table\")\n return pd.read_json(filename, orient=\"table\")\n\ndef save_datafile(data: pd.DataFrame, filename: Union[str, Path]) -> None:\n \"\"\"\n Save the given data to disc in either .hdf5 or .json format\n\n :param data: the data to save\n :param filename: the path to the data\n \"\"\"\n filename_str = str(filename)\n if filename_str.endswith(\".hdf5\") or filename_str.endswith(\".hdf\"):\n with warnings.catch_warnings(): # This wil suppress a PerformanceWarning\n warnings.simplefilter(\"ignore\")\n data.to_hdf(filename, key=\"table\")\n else:\n data.to_json(filename, orient=\"table\")", "n_imports_parsed": 6, "n_files_resolved": 1, "n_chars_extracted": 1024}, "tests/chem/test_serialization.py::8": {"resolved_imports": ["aizynthfinder/chem/serialization.py", "aizynthfinder/chem/__init__.py"], "used_names": ["MoleculeSerializer"], "enclosing_function": "test_empty_store", "extracted_code": "# Source: aizynthfinder/chem/serialization.py\nclass MoleculeSerializer:\n \"\"\"\n Utility class for serializing molecules\n\n The id of the molecule to be serialized can be obtained with:\n\n .. code-block::\n\n serializer = MoleculeSerializer()\n mol = Molecule(smiles=\"CCCO\")\n idx = serializer[mol]\n\n which will take care of the serialization of the molecule.\n \"\"\"\n\n def __init__(self) -> None:\n self._store: Dict[int, Any] = {}\n\n def __getitem__(self, mol: Optional[aizynthfinder.chem.Molecule]) -> Optional[int]:\n if mol is None:\n return None\n\n id_ = id(mol)\n if id_ not in self._store:\n self._add_mol(mol)\n return id_\n\n @property\n def store(self) -> Dict[int, Any]:\n \"\"\"Return all serialized molecules as a dictionary\"\"\"\n return self._store\n\n def _add_mol(self, mol: aizynthfinder.chem.Molecule) -> None:\n id_ = id(mol)\n dict_ = {\"smiles\": mol.smiles, \"class\": mol.__class__.__name__}\n if isinstance(mol, aizynthfinder.chem.TreeMolecule):\n dict_[\"parent\"] = self[mol.parent]\n dict_[\"transform\"] = mol.transform\n if not mol.parent:\n dict_[\"smiles\"] = mol.original_smiles\n else:\n dict_[\"smiles\"] = mol.mapped_smiles\n self._store[id_] = dict_", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 1360}, "tests/dfpn/test_nodes.py::21": {"resolved_imports": ["aizynthfinder/search/dfpn/nodes.py", "aizynthfinder/search/dfpn/__init__.py"], "used_names": [], "enclosing_function": "test_create_root_node", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/chem/test_reaction.py::90": {"resolved_imports": ["aizynthfinder/chem/__init__.py"], "used_names": ["SmilesBasedRetroReaction", "TreeMolecule"], "enclosing_function": "test_smiles_based_retroreaction", "extracted_code": "# Source: aizynthfinder/chem/__init__.py\n Molecule,\n MoleculeException,\n TreeMolecule,\n UniqueMolecule,\n none_molecule,\n)\nfrom aizynthfinder.chem.reaction import (\n FixedRetroReaction,\n RetroReaction,\n SmilesBasedRetroReaction,\n TemplatedRetroReaction,\n hash_reactions,\n\n FixedRetroReaction,\n RetroReaction,\n SmilesBasedRetroReaction,\n TemplatedRetroReaction,\n hash_reactions,\n)\nfrom aizynthfinder.chem.serialization import (\n MoleculeDeserializer,\n MoleculeSerializer,\n deserialize_action,\n serialize_action,\n)", "n_imports_parsed": 1, "n_files_resolved": 1, "n_chars_extracted": 568}, "tests/context/test_collection.py::73": {"resolved_imports": ["aizynthfinder/context/collection.py"], "used_names": ["pytest"], "enclosing_function": "test_select_single_item", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/utils/test_file_utils.py::92": {"resolved_imports": ["aizynthfinder/utils/files.py"], "used_names": ["cat_datafiles"], "enclosing_function": "test_cat_hdf", "extracted_code": "# Source: aizynthfinder/utils/files.py\ndef cat_datafiles(\n input_files: List[str], output_name: str, trees_name: Optional[str] = None\n) -> None:\n \"\"\"\n Concatenate hdf5 or json datafiles\n\n if `tree_name` is given, will take out the `trees` column\n from the tables and save it to a gzipped-json file.\n\n :param input_files: the paths to the files to concatenate\n :param output_name: the name of the concatenated file\n :param trees_name: the name of the concatenated trees\n \"\"\"\n data = read_datafile(input_files[0])\n if \"trees\" not in data.columns:\n trees_name = None\n\n if trees_name:\n columns = list(data.columns)\n columns.remove(\"trees\")\n trees = list(data[\"trees\"].values)\n data = data[columns]\n\n for filename in input_files[1:]:\n new_data = read_datafile(filename)\n if trees_name:\n trees.extend(new_data[\"trees\"].values)\n new_data = new_data[columns]\n data = pd.concat([data, new_data])\n\n save_datafile(data.reset_index(drop=True), output_name)\n if trees_name:\n if not trees_name.endswith(\".gz\"):\n trees_name += \".gz\"\n with gzip.open(trees_name, \"wt\", encoding=\"UTF-8\") as fileobj:\n json.dump(trees, fileobj)", "n_imports_parsed": 6, "n_files_resolved": 1, "n_chars_extracted": 1267}, "tests/breadth_first/test_nodes.py::18": {"resolved_imports": ["aizynthfinder/search/breadth_first/nodes.py", "aizynthfinder/chem/serialization.py"], "used_names": [], "enclosing_function": "test_create_root_node", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/mcts/test_multiobjective.py::75": {"resolved_imports": ["aizynthfinder/search/mcts/node.py", "aizynthfinder/search/mcts/__init__.py"], "used_names": [], "enclosing_function": "test_backpropagate", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/mcts/test_node.py::20": {"resolved_imports": [], "used_names": [], "enclosing_function": "test_expand_root_node", "extracted_code": "", "n_imports_parsed": 0, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/context/test_policy.py::155": {"resolved_imports": ["aizynthfinder/chem/__init__.py", "aizynthfinder/context/policy/__init__.py", "aizynthfinder/utils/exceptions.py"], "used_names": ["TreeMolecule"], "enclosing_function": "test_get_actions_two_policies", "extracted_code": "# Source: aizynthfinder/chem/__init__.py\n Molecule,\n MoleculeException,\n TreeMolecule,\n UniqueMolecule,\n none_molecule,\n)\nfrom aizynthfinder.chem.reaction import (\n FixedRetroReaction,\n RetroReaction,\n SmilesBasedRetroReaction,\n TemplatedRetroReaction,\n hash_reactions,", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 299}, "tests/context/test_expansion_strategies.py::147": {"resolved_imports": ["aizynthfinder/chem/__init__.py", "aizynthfinder/context/policy/__init__.py", "aizynthfinder/utils/exceptions.py"], "used_names": ["MultiExpansionStrategy", "TreeMolecule"], "enclosing_function": "test_multi_expansion_strategy_cutoff", "extracted_code": "# Source: aizynthfinder/chem/__init__.py\n Molecule,\n MoleculeException,\n TreeMolecule,\n UniqueMolecule,\n none_molecule,\n)\nfrom aizynthfinder.chem.reaction import (\n FixedRetroReaction,\n RetroReaction,\n SmilesBasedRetroReaction,\n TemplatedRetroReaction,\n hash_reactions,\n\n\n# Source: aizynthfinder/context/policy/__init__.py\nfrom aizynthfinder.context.policy.expansion_strategies import (\n ExpansionStrategy,\n MultiExpansionStrategy,\n TemplateBasedDirectExpansionStrategy,\n TemplateBasedExpansionStrategy,\n)\nfrom aizynthfinder.context.policy.filter_strategies import (\n BondFilter,\n FilterStrategy,\n FrozenSubstructureFilter,\n QuickKerasFilter,\n ReactantsCountFilter,", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 722}, "tests/test_analysis.py::108": {"resolved_imports": ["aizynthfinder/analysis/__init__.py", "aizynthfinder/analysis/routes.py", "aizynthfinder/analysis/utils.py", "aizynthfinder/reactiontree.py", "aizynthfinder/search/mcts/__init__.py", "aizynthfinder/context/scoring/__init__.py"], "used_names": ["NumberOfReactionsScorer"], "enclosing_function": "test_tree_statistics", "extracted_code": "# Source: aizynthfinder/context/scoring/__init__.py\n AverageTemplateOccurrenceScorer,\n MaxTransformScorer,\n NumberOfReactionsScorer,\n ReactionClassMembershipScorer,\n ReactionClassRankScorer,\n)\nfrom aizynthfinder.utils.exceptions import ScorerException", "n_imports_parsed": 10, "n_files_resolved": 6, "n_chars_extracted": 266}, "tests/test_cli.py::390": {"resolved_imports": ["aizynthfinder/analysis/__init__.py", "aizynthfinder/chem/__init__.py", "aizynthfinder/interfaces/__init__.py", "aizynthfinder/interfaces/aizynthapp.py", "aizynthfinder/interfaces/aizynthcli.py", "aizynthfinder/reactiontree.py", "aizynthfinder/tools/cat_output.py", "aizynthfinder/tools/download_public_data.py", "aizynthfinder/tools/make_stock.py"], "used_names": [], "enclosing_function": "test_make_stock_from_plain_file", "extracted_code": "", "n_imports_parsed": 17, "n_files_resolved": 9, "n_chars_extracted": 0}, "tests/context/test_policy.py::104": {"resolved_imports": ["aizynthfinder/chem/__init__.py", "aizynthfinder/context/policy/__init__.py", "aizynthfinder/utils/exceptions.py"], "used_names": ["PolicyException", "TreeMolecule", "pytest"], "enclosing_function": "test_get_actions", "extracted_code": "# Source: aizynthfinder/chem/__init__.py\n Molecule,\n MoleculeException,\n TreeMolecule,\n UniqueMolecule,\n none_molecule,\n)\nfrom aizynthfinder.chem.reaction import (\n FixedRetroReaction,\n RetroReaction,\n SmilesBasedRetroReaction,\n TemplatedRetroReaction,\n hash_reactions,\n\n\n# Source: aizynthfinder/utils/exceptions.py\nclass PolicyException(Exception):\n \"\"\"An exception raised by policy classes\"\"\"", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 427}, "tests/retrostar/test_retrostar_nodes.py::12": {"resolved_imports": ["aizynthfinder/search/retrostar/nodes.py", "aizynthfinder/chem/serialization.py", "aizynthfinder/search/andor_trees.py"], "used_names": [], "enclosing_function": "test_create_root_node", "extracted_code": "", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 0}, "tests/chem/test_mol.py::17": {"resolved_imports": ["aizynthfinder/chem/__init__.py"], "used_names": ["Chem", "Molecule"], "enclosing_function": "test_create_with_mol", "extracted_code": "# Source: aizynthfinder/chem/__init__.py\n\"\"\"\nfrom aizynthfinder.chem.mol import (\n Molecule,\n MoleculeException,\n TreeMolecule,\n UniqueMolecule,\n none_molecule,\n)\nfrom aizynthfinder.chem.reaction import (\n FixedRetroReaction,\n RetroReaction,\n SmilesBasedRetroReaction,\n\nfrom aizynthfinder.chem.mol import (\n Molecule,\n MoleculeException,\n TreeMolecule,\n UniqueMolecule,\n none_molecule,\n)\nfrom aizynthfinder.chem.reaction import (\n FixedRetroReaction,\n RetroReaction,\n SmilesBasedRetroReaction,\n TemplatedRetroReaction,\n\n Molecule,\n MoleculeException,\n TreeMolecule,\n UniqueMolecule,\n none_molecule,\n)\nfrom aizynthfinder.chem.reaction import (\n FixedRetroReaction,\n RetroReaction,\n SmilesBasedRetroReaction,\n TemplatedRetroReaction,\n hash_reactions,\n\n MoleculeException,\n TreeMolecule,\n UniqueMolecule,\n none_molecule,\n)\nfrom aizynthfinder.chem.reaction import (\n FixedRetroReaction,\n RetroReaction,\n SmilesBasedRetroReaction,\n TemplatedRetroReaction,\n hash_reactions,\n)\n\n)\nfrom aizynthfinder.chem.serialization import (\n MoleculeDeserializer,\n MoleculeSerializer,\n deserialize_action,\n serialize_action,\n)", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 1225}, "tests/test_cli.py::135": {"resolved_imports": ["aizynthfinder/analysis/__init__.py", "aizynthfinder/chem/__init__.py", "aizynthfinder/interfaces/__init__.py", "aizynthfinder/interfaces/aizynthapp.py", "aizynthfinder/interfaces/aizynthcli.py", "aizynthfinder/reactiontree.py", "aizynthfinder/tools/cat_output.py", "aizynthfinder/tools/download_public_data.py", "aizynthfinder/tools/make_stock.py"], "used_names": [], "enclosing_function": "test_app_main_no_output", "extracted_code": "", "n_imports_parsed": 17, "n_files_resolved": 9, "n_chars_extracted": 0}, "tests/dfpn/test_nodes.py::48": {"resolved_imports": ["aizynthfinder/search/dfpn/nodes.py", "aizynthfinder/search/dfpn/__init__.py"], "used_names": ["BIG_INT"], "enclosing_function": "test_promising_child", "extracted_code": "# Source: aizynthfinder/search/dfpn/nodes.py\nBIG_INT = int(1e10)", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 64}, "tests/dfpn/test_search.py::30": {"resolved_imports": ["aizynthfinder/search/dfpn/search_tree.py"], "used_names": ["SearchTree", "pytest"], "enclosing_function": "test_search", "extracted_code": "# Source: aizynthfinder/search/dfpn/search_tree.py\nclass SearchTree(AndOrSearchTreeBase):\n \"\"\"\n Encapsulation of the Depth-First Proof-Number (DFPN) search algorithm.\n\n This algorithm does not support:\n 1. Filter policy\n 2. Serialization and deserialization\n\n :ivar config: settings of the tree search algorithm\n :ivar root: the root node\n\n :param config: settings of the tree search algorithm\n :param root_smiles: the root will be set to a node representing this molecule, defaults to None\n \"\"\"\n\n def __init__(\n self, config: Configuration, root_smiles: Optional[str] = None\n ) -> None:\n super().__init__(config, root_smiles)\n self._mol_nodes: List[MoleculeNode] = []\n self._logger = logger()\n self._root_smiles = root_smiles\n if root_smiles:\n self.root: Optional[MoleculeNode] = MoleculeNode.create_root(\n root_smiles, config, self\n )\n self._mol_nodes.append(self.root)\n else:\n self.root = None\n\n self._routes: List[ReactionTree] = []\n self._frontier: Optional[Union[MoleculeNode, ReactionNode]] = None\n self._initiated = False\n\n self.profiling = {\n \"expansion_calls\": 0,\n \"reactants_generations\": 0,\n }\n\n @property\n def mol_nodes(self) -> Sequence[MoleculeNode]: # type: ignore\n \"\"\"Return the molecule nodes of the tree\"\"\"\n return self._mol_nodes\n\n def one_iteration(self) -> bool:\n \"\"\"\n Perform one iteration of expansion.\n\n If possible expand the frontier node twice, i.e. expanding an OR\n node and then and AND node. If frontier not expandable step up in the\n tree and find a new frontier to expand.\n\n If a solution is found, mask that tree for exploration and start over.\n\n :raises StopIteration: if the search should be pre-maturely terminated\n :return: if a solution was found\n :rtype: bool\n \"\"\"\n if not self._initiated:\n if self.root is None:\n raise ValueError(\"Root is undefined. Cannot make an iteration\")\n\n self._routes = []\n self._frontier = self.root\n assert self.root is not None\n\n while True:\n # Expand frontier, should be OR node\n assert isinstance(self._frontier, MoleculeNode)\n expanded_or = self._search_step()\n expanded_and = False\n if self._frontier:\n # Expand frontier again, this time an AND node\n assert isinstance(self._frontier, ReactionNode)\n expanded_and = self._search_step()\n if (\n expanded_or\n or expanded_and\n or self._frontier is None\n or self._frontier is self.root\n ):\n break\n\n found_solution = any(child.proven for child in self.root.children)\n if self._frontier is self.root:\n self.root.reset()\n\n if self._frontier is None:\n raise StopIteration()\n\n return found_solution\n\n def routes(self) -> List[ReactionTree]:\n \"\"\"\n Extracts and returns routes from the AND/OR tree\n\n :return: the routes\n \"\"\"\n if self.root is None:\n return []\n if not self._routes:\n self._routes = SplitAndOrTree(self.root, self.config.stock).routes\n return self._routes\n\n def _search_step(self) -> bool:\n assert self._frontier is not None\n expanded = False\n if self._frontier.expandable:\n self._frontier.expand()\n expanded = True\n if isinstance(self._frontier, ReactionNode):\n self._mol_nodes.extend(self._frontier.children)\n\n self._frontier.update()\n if not self._frontier.explorable():\n self._frontier = self._frontier.parent\n return False\n\n child = self._frontier.promising_child()\n if not child:\n self._frontier = self._frontier.parent\n return False\n\n self._frontier = child\n return expanded", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 4155}, "tests/chem/test_mol.py::100": {"resolved_imports": ["aizynthfinder/chem/__init__.py"], "used_names": ["Molecule"], "enclosing_function": "test_chiral_fingerprint", "extracted_code": "# Source: aizynthfinder/chem/__init__.py\n\"\"\"\nfrom aizynthfinder.chem.mol import (\n Molecule,\n MoleculeException,\n TreeMolecule,\n UniqueMolecule,\n none_molecule,\n)\nfrom aizynthfinder.chem.reaction import (\n FixedRetroReaction,\n RetroReaction,\n SmilesBasedRetroReaction,\n\nfrom aizynthfinder.chem.mol import (\n Molecule,\n MoleculeException,\n TreeMolecule,\n UniqueMolecule,\n none_molecule,\n)\nfrom aizynthfinder.chem.reaction import (\n FixedRetroReaction,\n RetroReaction,\n SmilesBasedRetroReaction,\n TemplatedRetroReaction,\n\n Molecule,\n MoleculeException,\n TreeMolecule,\n UniqueMolecule,\n none_molecule,\n)\nfrom aizynthfinder.chem.reaction import (\n FixedRetroReaction,\n RetroReaction,\n SmilesBasedRetroReaction,\n TemplatedRetroReaction,\n hash_reactions,\n\n MoleculeException,\n TreeMolecule,\n UniqueMolecule,\n none_molecule,\n)\nfrom aizynthfinder.chem.reaction import (\n FixedRetroReaction,\n RetroReaction,\n SmilesBasedRetroReaction,\n TemplatedRetroReaction,\n hash_reactions,\n)\n\n)\nfrom aizynthfinder.chem.serialization import (\n MoleculeDeserializer,\n MoleculeSerializer,\n deserialize_action,\n serialize_action,\n)", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 1225}, "tests/context/test_policy.py::112": {"resolved_imports": ["aizynthfinder/chem/__init__.py", "aizynthfinder/context/policy/__init__.py", "aizynthfinder/utils/exceptions.py"], "used_names": ["PolicyException", "TreeMolecule", "pytest"], "enclosing_function": "test_get_actions", "extracted_code": "# Source: aizynthfinder/chem/__init__.py\n Molecule,\n MoleculeException,\n TreeMolecule,\n UniqueMolecule,\n none_molecule,\n)\nfrom aizynthfinder.chem.reaction import (\n FixedRetroReaction,\n RetroReaction,\n SmilesBasedRetroReaction,\n TemplatedRetroReaction,\n hash_reactions,\n\n\n# Source: aizynthfinder/utils/exceptions.py\nclass PolicyException(Exception):\n \"\"\"An exception raised by policy classes\"\"\"", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 427}, "tests/breadth_first/test_search.py::30": {"resolved_imports": ["aizynthfinder/search/breadth_first/search_tree.py"], "used_names": ["SearchTree", "pytest"], "enclosing_function": "test_one_iteration", "extracted_code": "# Source: aizynthfinder/search/breadth_first/search_tree.py\nclass SearchTree(AndOrSearchTreeBase):\n \"\"\"\n Encapsulation of the a breadth-first exhaustive search algorithm\n\n :ivar config: settings of the tree search algorithm\n :ivar root: the root node\n\n :param config: settings of the tree search algorithm\n :param root_smiles: the root will be set to a node representing this molecule, defaults to None\n \"\"\"\n\n def __init__(\n self, config: Configuration, root_smiles: Optional[str] = None\n ) -> None:\n super().__init__(config, root_smiles)\n self._mol_nodes: List[MoleculeNode] = []\n self._added_mol_nodes: List[MoleculeNode] = []\n self._logger = logger()\n\n if root_smiles:\n self.root: Optional[MoleculeNode] = MoleculeNode.create_root(\n root_smiles, config\n )\n self._mol_nodes.append(self.root)\n else:\n self.root = None\n\n self._routes: List[ReactionTree] = []\n\n self.profiling = {\n \"expansion_calls\": 0,\n \"reactants_generations\": 0,\n }\n\n @classmethod\n def from_json(cls, filename: str, config: Configuration) -> SearchTree:\n \"\"\"\n Create a new search tree by deserialization from a JSON file\n\n :param filename: the path to the JSON node\n :param config: the configuration of the search tree\n :return: a deserialized tree\n \"\"\"\n\n def _find_mol_nodes(node):\n for child_ in node.children:\n tree._mol_nodes.append(child_) # pylint: disable=protected-access\n for grandchild in child_.children:\n _find_mol_nodes(grandchild)\n\n tree = cls(config)\n with open(filename, \"r\") as fileobj:\n dict_ = json.load(fileobj)\n mol_deser = MoleculeDeserializer(dict_[\"molecules\"])\n tree.root = MoleculeNode.from_dict(dict_[\"tree\"], config, mol_deser)\n tree._mol_nodes.append(tree.root) # pylint: disable=protected-access\n for child in tree.root.children:\n _find_mol_nodes(child)\n return tree\n\n @property\n def mol_nodes(self) -> Sequence[MoleculeNode]: # type: ignore\n \"\"\"Return the molecule nodes of the tree\"\"\"\n return self._mol_nodes\n\n def one_iteration(self) -> bool:\n \"\"\"\n Perform one iteration expansion.\n Expands all expandable molecule nodes in the tree, which should be\n on the same depth of the tree.\n\n :raises StopIteration: if the search should be pre-maturely terminated\n :return: if a solution was found\n :rtype: bool\n \"\"\"\n if self.root is None:\n raise ValueError(\"Root is undefined. Cannot make an iteration\")\n\n self._routes = []\n self._added_mol_nodes = []\n\n for next_node in self._mol_nodes:\n if next_node.expandable:\n self._expand(next_node)\n\n if not self._added_mol_nodes:\n self._logger.debug(\"No new nodes added in breadth-first iteration\")\n raise StopIteration\n\n self._mol_nodes.extend(self._added_mol_nodes)\n solved = all(node.in_stock for node in self._mol_nodes if not node.children)\n return solved\n\n def routes(self) -> List[ReactionTree]:\n \"\"\"\n Extracts and returns routes from the AND/OR tree\n\n :return: the routes\n \"\"\"\n if self.root is None:\n return []\n if not self._routes:\n self._routes = SplitAndOrTree(self.root, self.config.stock).routes\n return self._routes\n\n def serialize(self, filename: str) -> None:\n \"\"\"\n Seralize the search tree to a JSON file\n\n :param filename: the path to the JSON file\n :type filename: str\n \"\"\"\n if self.root is None:\n raise ValueError(\"Cannot serialize tree as root is not defined\")\n\n mol_ser = MoleculeSerializer()\n dict_ = {\"tree\": self.root.serialize(mol_ser), \"molecules\": mol_ser.store}\n with open(filename, \"w\") as fileobj:\n json.dump(dict_, fileobj, indent=2)\n\n def _expand(self, node: MoleculeNode) -> None:\n node.expandable = False\n reactions, _ = self.config.expansion_policy([node.mol])\n self.profiling[\"expansion_calls\"] += 1\n\n if not reactions:\n return\n\n reactions_to_expand = []\n for reaction in reactions:\n try:\n self.profiling[\"reactants_generations\"] += 1\n _ = reaction.reactants\n except: # pylint: disable=bare-except\n continue\n if not reaction.reactants:\n continue\n for idx, _ in enumerate(reaction.reactants):\n rxn_copy = reaction.copy(idx)\n reactions_to_expand.append(rxn_copy)\n\n for rxn in reactions_to_expand:\n new_nodes = node.add_stub(rxn)\n self._added_mol_nodes.extend(new_nodes)", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 4982}, "tests/breadth_first/test_nodes.py::31": {"resolved_imports": ["aizynthfinder/search/breadth_first/nodes.py", "aizynthfinder/chem/serialization.py"], "used_names": [], "enclosing_function": "test_create_stub", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/mcts/test_tree.py::49": {"resolved_imports": [], "used_names": [], "enclosing_function": "test_create_graph", "extracted_code": "", "n_imports_parsed": 0, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_cli.py::443": {"resolved_imports": ["aizynthfinder/analysis/__init__.py", "aizynthfinder/chem/__init__.py", "aizynthfinder/interfaces/__init__.py", "aizynthfinder/interfaces/aizynthapp.py", "aizynthfinder/interfaces/aizynthcli.py", "aizynthfinder/reactiontree.py", "aizynthfinder/tools/cat_output.py", "aizynthfinder/tools/download_public_data.py", "aizynthfinder/tools/make_stock.py"], "used_names": ["glob", "os", "yaml"], "enclosing_function": "test_download_public_data", "extracted_code": "", "n_imports_parsed": 17, "n_files_resolved": 9, "n_chars_extracted": 0}, "tests/context/test_score.py::187": {"resolved_imports": ["aizynthfinder/chem/__init__.py", "aizynthfinder/context/config.py", "aizynthfinder/context/scoring/__init__.py", "aizynthfinder/reactiontree.py", "aizynthfinder/search/mcts/__init__.py"], "used_names": ["Configuration", "FractionInSourceStockScorer", "FractionInStockScorer", "FractionOfIntermediatesInStockScorer", "MaxTransformScorer", "NumberOfPrecursorsInStockScorer", "NumberOfPrecursorsScorer", "NumberOfReactionsScorer", "PriceSumScorer", "RouteCostScorer", "StateScorer", "pytest"], "enclosing_function": "test_scoring_branched_mcts_tree", "extracted_code": "# Source: aizynthfinder/context/config.py\nclass Configuration:\n \"\"\"\n Encapsulating the settings of the tree search, including the policy,\n the stock, the loaded scorers and various parameters.\n \"\"\"\n\n search: _SearchConfiguration = field(default_factory=_SearchConfiguration)\n post_processing: _PostprocessingConfiguration = field(\n default_factory=_PostprocessingConfiguration\n )\n stock: Stock = field(init=False)\n expansion_policy: ExpansionPolicy = field(init=False)\n filter_policy: FilterPolicy = field(init=False)\n scorers: ScorerCollection = field(init=False)\n\n def __post_init__(self) -> None:\n self.stock = Stock()\n self.expansion_policy = ExpansionPolicy(self)\n self.filter_policy = FilterPolicy(self)\n self.scorers = ScorerCollection(self)\n self._logger = logger()\n\n def __eq__(self, other: Any) -> bool:\n if not isinstance(other, Configuration):\n return False\n for key, setting in vars(self).items():\n if isinstance(setting, (int, float, str, bool, list)):\n if (\n vars(self)[key] != vars(other)[key]\n or self.search != other.search\n or self.post_processing != other.post_processing\n ):\n return False\n return True\n\n @classmethod\n def from_dict(cls, source: StrDict) -> \"Configuration\":\n \"\"\"\n Loads a configuration from a dictionary structure.\n The parameters not set in the dictionary are taken from the default values.\n The policies and stocks specified are directly loaded.\n\n :param source: the dictionary source\n :return: a Configuration object with settings from the source\n \"\"\"\n expansion_config = source.pop(\"expansion\", {})\n filter_config = source.pop(\"filter\", {})\n stock_config = source.pop(\"stock\", {})\n scorer_config = source.pop(\"scorer\", {})\n\n config_obj = Configuration()\n config_obj._update_from_config(dict(source))\n\n config_obj.expansion_policy.load_from_config(**expansion_config)\n config_obj.filter_policy.load_from_config(**filter_config)\n config_obj.stock.load_from_config(**stock_config)\n config_obj.scorers.create_default_scorers()\n config_obj.scorers.load_from_config(**scorer_config)\n\n return config_obj\n\n @classmethod\n def from_file(cls, filename: str) -> \"Configuration\":\n \"\"\"\n Loads a configuration from a yaml file.\n The parameters not set in the yaml file are taken from the default values.\n The policies and stocks specified in the yaml file are directly loaded.\n The parameters in the yaml file may also contain environment variables as\n values.\n\n :param filename: the path to a yaml file\n :return: a Configuration object with settings from the yaml file\n :raises:\n ValueError: if parameter's value expects an environment variable that\n does not exist in the current environment\n \"\"\"\n with open(filename, \"r\") as fileobj:\n txt = fileobj.read()\n environ_var = re.findall(r\"\\$\\{.+?\\}\", txt)\n for item in environ_var:\n if item[2:-1] not in os.environ:\n raise ValueError(f\"'{item[2:-1]}' not in environment variables\")\n txt = txt.replace(item, os.environ[item[2:-1]])\n _config = yaml.load(txt, Loader=yaml.SafeLoader)\n return Configuration.from_dict(_config)\n\n def _update_from_config(self, config: StrDict) -> None:\n self.post_processing = _PostprocessingConfiguration(\n **config.pop(\"post_processing\", {})\n )\n\n search_config = config.pop(\"search\", {})\n for setting, value in search_config.items():\n if value is None:\n continue\n if not hasattr(self.search, setting):\n raise AttributeError(f\"Could not find attribute to set: {setting}\")\n if setting.endswith(\"_bonds\"):\n if not isinstance(value, list):\n raise ValueError(\"Bond settings need to be lists\")\n value = _handle_bond_pair_tuples(value) if value else []\n if setting == \"algorithm_config\":\n if not isinstance(value, dict):\n raise ValueError(\"algorithm_config settings need to be dictionary\")\n self.search.algorithm_config.update(value)\n else:\n setattr(self.search, setting, value)\n\n\n# Source: aizynthfinder/context/scoring/__init__.py\n CombinedScorer,\n DeepSetScorer,\n RouteCostScorer,\n RouteSimilarityScorer,\n StateScorer,\n)\nfrom aizynthfinder.context.scoring.scorers_base import Scorer\nfrom aizynthfinder.context.scoring.scorers_mols import (\n DeltaSyntheticComplexityScorer,\n FractionInSourceStockScorer,\n FractionInStockScorer,\n FractionOfIntermediatesInStockScorer,\n\n RouteCostScorer,\n RouteSimilarityScorer,\n StateScorer,\n)\nfrom aizynthfinder.context.scoring.scorers_base import Scorer\nfrom aizynthfinder.context.scoring.scorers_mols import (\n DeltaSyntheticComplexityScorer,\n FractionInSourceStockScorer,\n FractionInStockScorer,\n FractionOfIntermediatesInStockScorer,\n NumberOfPrecursorsInStockScorer,\n NumberOfPrecursorsScorer,\n\nfrom aizynthfinder.context.scoring.scorers_mols import (\n DeltaSyntheticComplexityScorer,\n FractionInSourceStockScorer,\n FractionInStockScorer,\n FractionOfIntermediatesInStockScorer,\n NumberOfPrecursorsInStockScorer,\n NumberOfPrecursorsScorer,\n PriceSumScorer,\n StockAvailabilityScorer,\n)\nfrom aizynthfinder.context.scoring.scorers_reactions import (\n AverageTemplateOccurrenceScorer,\n\n DeltaSyntheticComplexityScorer,\n FractionInSourceStockScorer,\n FractionInStockScorer,\n FractionOfIntermediatesInStockScorer,\n NumberOfPrecursorsInStockScorer,\n NumberOfPrecursorsScorer,\n PriceSumScorer,\n StockAvailabilityScorer,\n)\nfrom aizynthfinder.context.scoring.scorers_reactions import (\n AverageTemplateOccurrenceScorer,\n MaxTransformScorer,\n\n FractionInSourceStockScorer,\n FractionInStockScorer,\n FractionOfIntermediatesInStockScorer,\n NumberOfPrecursorsInStockScorer,\n NumberOfPrecursorsScorer,\n PriceSumScorer,\n StockAvailabilityScorer,\n)\nfrom aizynthfinder.context.scoring.scorers_reactions import (\n AverageTemplateOccurrenceScorer,\n MaxTransformScorer,\n NumberOfReactionsScorer,", "n_imports_parsed": 8, "n_files_resolved": 5, "n_chars_extracted": 6543}, "tests/chem/test_mol.py::64": {"resolved_imports": ["aizynthfinder/chem/__init__.py"], "used_names": ["Molecule"], "enclosing_function": "test_equality", "extracted_code": "# Source: aizynthfinder/chem/__init__.py\n\"\"\"\nfrom aizynthfinder.chem.mol import (\n Molecule,\n MoleculeException,\n TreeMolecule,\n UniqueMolecule,\n none_molecule,\n)\nfrom aizynthfinder.chem.reaction import (\n FixedRetroReaction,\n RetroReaction,\n SmilesBasedRetroReaction,\n\nfrom aizynthfinder.chem.mol import (\n Molecule,\n MoleculeException,\n TreeMolecule,\n UniqueMolecule,\n none_molecule,\n)\nfrom aizynthfinder.chem.reaction import (\n FixedRetroReaction,\n RetroReaction,\n SmilesBasedRetroReaction,\n TemplatedRetroReaction,\n\n Molecule,\n MoleculeException,\n TreeMolecule,\n UniqueMolecule,\n none_molecule,\n)\nfrom aizynthfinder.chem.reaction import (\n FixedRetroReaction,\n RetroReaction,\n SmilesBasedRetroReaction,\n TemplatedRetroReaction,\n hash_reactions,\n\n MoleculeException,\n TreeMolecule,\n UniqueMolecule,\n none_molecule,\n)\nfrom aizynthfinder.chem.reaction import (\n FixedRetroReaction,\n RetroReaction,\n SmilesBasedRetroReaction,\n TemplatedRetroReaction,\n hash_reactions,\n)\n\n)\nfrom aizynthfinder.chem.serialization import (\n MoleculeDeserializer,\n MoleculeSerializer,\n deserialize_action,\n serialize_action,\n)", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 1225}, "tests/breadth_first/test_nodes.py::30": {"resolved_imports": ["aizynthfinder/search/breadth_first/nodes.py", "aizynthfinder/chem/serialization.py"], "used_names": [], "enclosing_function": "test_create_stub", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/dfpn/test_search.py::39": {"resolved_imports": ["aizynthfinder/search/dfpn/search_tree.py"], "used_names": ["SearchTree", "pytest"], "enclosing_function": "test_search", "extracted_code": "# Source: aizynthfinder/search/dfpn/search_tree.py\nclass SearchTree(AndOrSearchTreeBase):\n \"\"\"\n Encapsulation of the Depth-First Proof-Number (DFPN) search algorithm.\n\n This algorithm does not support:\n 1. Filter policy\n 2. Serialization and deserialization\n\n :ivar config: settings of the tree search algorithm\n :ivar root: the root node\n\n :param config: settings of the tree search algorithm\n :param root_smiles: the root will be set to a node representing this molecule, defaults to None\n \"\"\"\n\n def __init__(\n self, config: Configuration, root_smiles: Optional[str] = None\n ) -> None:\n super().__init__(config, root_smiles)\n self._mol_nodes: List[MoleculeNode] = []\n self._logger = logger()\n self._root_smiles = root_smiles\n if root_smiles:\n self.root: Optional[MoleculeNode] = MoleculeNode.create_root(\n root_smiles, config, self\n )\n self._mol_nodes.append(self.root)\n else:\n self.root = None\n\n self._routes: List[ReactionTree] = []\n self._frontier: Optional[Union[MoleculeNode, ReactionNode]] = None\n self._initiated = False\n\n self.profiling = {\n \"expansion_calls\": 0,\n \"reactants_generations\": 0,\n }\n\n @property\n def mol_nodes(self) -> Sequence[MoleculeNode]: # type: ignore\n \"\"\"Return the molecule nodes of the tree\"\"\"\n return self._mol_nodes\n\n def one_iteration(self) -> bool:\n \"\"\"\n Perform one iteration of expansion.\n\n If possible expand the frontier node twice, i.e. expanding an OR\n node and then and AND node. If frontier not expandable step up in the\n tree and find a new frontier to expand.\n\n If a solution is found, mask that tree for exploration and start over.\n\n :raises StopIteration: if the search should be pre-maturely terminated\n :return: if a solution was found\n :rtype: bool\n \"\"\"\n if not self._initiated:\n if self.root is None:\n raise ValueError(\"Root is undefined. Cannot make an iteration\")\n\n self._routes = []\n self._frontier = self.root\n assert self.root is not None\n\n while True:\n # Expand frontier, should be OR node\n assert isinstance(self._frontier, MoleculeNode)\n expanded_or = self._search_step()\n expanded_and = False\n if self._frontier:\n # Expand frontier again, this time an AND node\n assert isinstance(self._frontier, ReactionNode)\n expanded_and = self._search_step()\n if (\n expanded_or\n or expanded_and\n or self._frontier is None\n or self._frontier is self.root\n ):\n break\n\n found_solution = any(child.proven for child in self.root.children)\n if self._frontier is self.root:\n self.root.reset()\n\n if self._frontier is None:\n raise StopIteration()\n\n return found_solution\n\n def routes(self) -> List[ReactionTree]:\n \"\"\"\n Extracts and returns routes from the AND/OR tree\n\n :return: the routes\n \"\"\"\n if self.root is None:\n return []\n if not self._routes:\n self._routes = SplitAndOrTree(self.root, self.config.stock).routes\n return self._routes\n\n def _search_step(self) -> bool:\n assert self._frontier is not None\n expanded = False\n if self._frontier.expandable:\n self._frontier.expand()\n expanded = True\n if isinstance(self._frontier, ReactionNode):\n self._mol_nodes.extend(self._frontier.children)\n\n self._frontier.update()\n if not self._frontier.explorable():\n self._frontier = self._frontier.parent\n return False\n\n child = self._frontier.promising_child()\n if not child:\n self._frontier = self._frontier.parent\n return False\n\n self._frontier = child\n return expanded", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 4155}, "tests/retrostar/test_retrostar.py::51": {"resolved_imports": ["aizynthfinder/search/retrostar/search_tree.py", "aizynthfinder/chem/serialization.py"], "used_names": [], "enclosing_function": "test_one_expansion_with_finder", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/retrostar/test_retrostar.py::12": {"resolved_imports": ["aizynthfinder/search/retrostar/search_tree.py", "aizynthfinder/chem/serialization.py"], "used_names": [], "enclosing_function": "test_one_iteration", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/utils/test_scscore.py::22": {"resolved_imports": ["aizynthfinder/utils/sc_score.py"], "used_names": ["Chem", "SCScore", "pickle", "pytest"], "enclosing_function": "test_scscore", "extracted_code": "# Source: aizynthfinder/utils/sc_score.py\nclass SCScore:\n \"\"\"\n Encapsulation of the SCScore model\n\n Re-write of the SCScorer from the scscorer package\n\n The predictions of the score is made with a sanitized instance of an RDKit molecule\n\n .. code-block::\n\n mol = Molecule(smiles=\"CCC\", sanitize=True)\n scscorer = SCScorer(\"path_to_model\")\n score = scscorer(mol.rd_mol)\n\n The model provided when creating the scorer object should be pickled tuple.\n The first item of the tuple should be a list of the model weights for each layer.\n The second item of the tuple should be a list of the model biases for each layer.\n\n :param model_path: the filename of the model weights and biases\n :param fingerprint_length: the number of bits in the fingerprint\n :param fingerprint_radius: the radius of the fingerprint\n \"\"\"\n\n def __init__(\n self,\n model_path: str,\n fingerprint_length: int = 1024,\n fingerprint_radius: int = 2,\n ) -> None:\n self._fingerprint_length = fingerprint_length\n self._fingerprint_radius = fingerprint_radius\n self._weights, self._biases = self._load_model(model_path)\n self.score_scale = 5.0\n\n def __call__(self, rd_mol: RdMol) -> float:\n fingerprint = self._make_fingerprint(rd_mol)\n normalized_score = self.forward(fingerprint)\n sc_score = (1 + (self.score_scale - 1) * normalized_score)[0]\n return sc_score\n\n # pylint: disable=invalid-name\n def forward(self, x: np.ndarray) -> np.ndarray:\n \"\"\"Forward pass with dense neural network\"\"\"\n for weights, bias in zip(self._weights[:-1], self._biases[:-1]):\n x = dense_layer_forward_pass(x, weights, bias, rectified_linear_unit)\n return dense_layer_forward_pass(x, self._weights[-1], self._biases[-1], sigmoid)\n\n def _load_model(\n self, model_path: str\n ) -> Tuple[Sequence[np.ndarray], Sequence[np.ndarray]]:\n \"\"\"Returns neural network model parameters.\"\"\"\n with open(model_path, \"rb\") as fileobj:\n weights, biases = pickle.load(fileobj)\n\n weights = [np.asarray(item) for item in weights]\n biases = [np.asarray(item) for item in biases]\n return weights, biases\n\n def _make_fingerprint(self, rd_mol: RdMol) -> np.ndarray:\n \"\"\"Returns the molecule's Morgan fingerprint\"\"\"\n fp_vec = AllChem.GetMorganFingerprintAsBitVect(\n rd_mol,\n self._fingerprint_radius,\n nBits=self._fingerprint_length,\n useChirality=True,\n )\n return np.array(\n fp_vec,\n dtype=bool,\n )", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 2661}, "tests/dfpn/test_nodes.py::47": {"resolved_imports": ["aizynthfinder/search/dfpn/nodes.py", "aizynthfinder/search/dfpn/__init__.py"], "used_names": ["BIG_INT"], "enclosing_function": "test_promising_child", "extracted_code": "# Source: aizynthfinder/search/dfpn/nodes.py\nBIG_INT = int(1e10)", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 64}, "tests/context/test_mcts_config.py::200": {"resolved_imports": ["aizynthfinder/aizynthfinder.py", "aizynthfinder/context/config.py", "aizynthfinder/context/stock/__init__.py"], "used_names": ["Configuration"], "enclosing_function": "test_load_stop_criteria", "extracted_code": "# Source: aizynthfinder/context/config.py\nclass Configuration:\n \"\"\"\n Encapsulating the settings of the tree search, including the policy,\n the stock, the loaded scorers and various parameters.\n \"\"\"\n\n search: _SearchConfiguration = field(default_factory=_SearchConfiguration)\n post_processing: _PostprocessingConfiguration = field(\n default_factory=_PostprocessingConfiguration\n )\n stock: Stock = field(init=False)\n expansion_policy: ExpansionPolicy = field(init=False)\n filter_policy: FilterPolicy = field(init=False)\n scorers: ScorerCollection = field(init=False)\n\n def __post_init__(self) -> None:\n self.stock = Stock()\n self.expansion_policy = ExpansionPolicy(self)\n self.filter_policy = FilterPolicy(self)\n self.scorers = ScorerCollection(self)\n self._logger = logger()\n\n def __eq__(self, other: Any) -> bool:\n if not isinstance(other, Configuration):\n return False\n for key, setting in vars(self).items():\n if isinstance(setting, (int, float, str, bool, list)):\n if (\n vars(self)[key] != vars(other)[key]\n or self.search != other.search\n or self.post_processing != other.post_processing\n ):\n return False\n return True\n\n @classmethod\n def from_dict(cls, source: StrDict) -> \"Configuration\":\n \"\"\"\n Loads a configuration from a dictionary structure.\n The parameters not set in the dictionary are taken from the default values.\n The policies and stocks specified are directly loaded.\n\n :param source: the dictionary source\n :return: a Configuration object with settings from the source\n \"\"\"\n expansion_config = source.pop(\"expansion\", {})\n filter_config = source.pop(\"filter\", {})\n stock_config = source.pop(\"stock\", {})\n scorer_config = source.pop(\"scorer\", {})\n\n config_obj = Configuration()\n config_obj._update_from_config(dict(source))\n\n config_obj.expansion_policy.load_from_config(**expansion_config)\n config_obj.filter_policy.load_from_config(**filter_config)\n config_obj.stock.load_from_config(**stock_config)\n config_obj.scorers.create_default_scorers()\n config_obj.scorers.load_from_config(**scorer_config)\n\n return config_obj\n\n @classmethod\n def from_file(cls, filename: str) -> \"Configuration\":\n \"\"\"\n Loads a configuration from a yaml file.\n The parameters not set in the yaml file are taken from the default values.\n The policies and stocks specified in the yaml file are directly loaded.\n The parameters in the yaml file may also contain environment variables as\n values.\n\n :param filename: the path to a yaml file\n :return: a Configuration object with settings from the yaml file\n :raises:\n ValueError: if parameter's value expects an environment variable that\n does not exist in the current environment\n \"\"\"\n with open(filename, \"r\") as fileobj:\n txt = fileobj.read()\n environ_var = re.findall(r\"\\$\\{.+?\\}\", txt)\n for item in environ_var:\n if item[2:-1] not in os.environ:\n raise ValueError(f\"'{item[2:-1]}' not in environment variables\")\n txt = txt.replace(item, os.environ[item[2:-1]])\n _config = yaml.load(txt, Loader=yaml.SafeLoader)\n return Configuration.from_dict(_config)\n\n def _update_from_config(self, config: StrDict) -> None:\n self.post_processing = _PostprocessingConfiguration(\n **config.pop(\"post_processing\", {})\n )\n\n search_config = config.pop(\"search\", {})\n for setting, value in search_config.items():\n if value is None:\n continue\n if not hasattr(self.search, setting):\n raise AttributeError(f\"Could not find attribute to set: {setting}\")\n if setting.endswith(\"_bonds\"):\n if not isinstance(value, list):\n raise ValueError(\"Bond settings need to be lists\")\n value = _handle_bond_pair_tuples(value) if value else []\n if setting == \"algorithm_config\":\n if not isinstance(value, dict):\n raise ValueError(\"algorithm_config settings need to be dictionary\")\n self.search.algorithm_config.update(value)\n else:\n setattr(self.search, setting, value)", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 4568}, "tests/chem/test_serialization.py::67": {"resolved_imports": ["aizynthfinder/chem/serialization.py", "aizynthfinder/chem/__init__.py"], "used_names": ["MoleculeDeserializer"], "enclosing_function": "test_deserialize_tree_mols", "extracted_code": "# Source: aizynthfinder/chem/serialization.py\nclass MoleculeDeserializer:\n \"\"\"\n Utility class for deserializing molecules.\n The serialized molecules are created upon instantiation of the class.\n\n The deserialized molecules can be obtained with:\n\n .. code-block::\n\n deserializer = MoleculeDeserializer()\n mol = deserializer[idx]\n\n \"\"\"\n\n def __init__(self, store: Dict[int, Any]) -> None:\n self._objects: Dict[int, Any] = {}\n self._create_molecules(store)\n\n def __getitem__(self, id_: Optional[int]) -> Optional[aizynthfinder.chem.Molecule]:\n if id_ is None:\n return None\n return self._objects[id_]\n\n def get_tree_molecules(\n self, ids: Sequence[int]\n ) -> Sequence[aizynthfinder.chem.TreeMolecule]:\n \"\"\"\n Return multiple deserialized tree molecules\n\n :param ids: the list of IDs to deserialize\n :return: the molecule objects\n \"\"\"\n objects = []\n for id_ in ids:\n obj = self[id_]\n if obj is None or not isinstance(obj, aizynthfinder.chem.TreeMolecule):\n raise ValueError(f\"Failed to deserialize molecule with id {id_}\")\n objects.append(obj)\n return objects\n\n def _create_molecules(self, store: dict) -> None:\n for id_, spec in store.items():\n if isinstance(id_, str):\n id_ = int(id_)\n\n cls = spec[\"class\"]\n if \"parent\" in spec:\n spec[\"parent\"] = self[spec[\"parent\"]]\n\n kwargs = dict(spec)\n del kwargs[\"class\"]\n self._objects[id_] = getattr(aizynthfinder.chem, cls)(**kwargs)", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 1671}, "tests/chem/test_reaction.py::75": {"resolved_imports": ["aizynthfinder/chem/__init__.py"], "used_names": ["TemplatedRetroReaction"], "enclosing_function": "test_retro_reaction_copy", "extracted_code": "# Source: aizynthfinder/chem/__init__.py\n RetroReaction,\n SmilesBasedRetroReaction,\n TemplatedRetroReaction,\n hash_reactions,\n)\nfrom aizynthfinder.chem.serialization import (\n MoleculeDeserializer,\n MoleculeSerializer,\n deserialize_action,\n serialize_action,\n)", "n_imports_parsed": 1, "n_files_resolved": 1, "n_chars_extracted": 284}, "tests/mcts/test_reward.py::23": {"resolved_imports": ["aizynthfinder/analysis/__init__.py", "aizynthfinder/context/scoring/__init__.py", "aizynthfinder/search/mcts/__init__.py"], "used_names": ["NumberOfReactionsScorer", "StateScorer"], "enclosing_function": "test_reward_node", "extracted_code": "# Source: aizynthfinder/context/scoring/__init__.py\n RouteCostScorer,\n RouteSimilarityScorer,\n StateScorer,\n)\nfrom aizynthfinder.context.scoring.scorers_base import Scorer\nfrom aizynthfinder.context.scoring.scorers_mols import (\n DeltaSyntheticComplexityScorer,\n FractionInSourceStockScorer,\n FractionInStockScorer,\n FractionOfIntermediatesInStockScorer,\n NumberOfPrecursorsInStockScorer,\n NumberOfPrecursorsScorer,\n\n AverageTemplateOccurrenceScorer,\n MaxTransformScorer,\n NumberOfReactionsScorer,\n ReactionClassMembershipScorer,\n ReactionClassRankScorer,\n)\nfrom aizynthfinder.utils.exceptions import ScorerException", "n_imports_parsed": 3, "n_files_resolved": 3, "n_chars_extracted": 658}, "tests/breadth_first/test_search.py::42": {"resolved_imports": ["aizynthfinder/search/breadth_first/search_tree.py"], "used_names": ["SearchTree", "pytest"], "enclosing_function": "test_one_iteration", "extracted_code": "# Source: aizynthfinder/search/breadth_first/search_tree.py\nclass SearchTree(AndOrSearchTreeBase):\n \"\"\"\n Encapsulation of the a breadth-first exhaustive search algorithm\n\n :ivar config: settings of the tree search algorithm\n :ivar root: the root node\n\n :param config: settings of the tree search algorithm\n :param root_smiles: the root will be set to a node representing this molecule, defaults to None\n \"\"\"\n\n def __init__(\n self, config: Configuration, root_smiles: Optional[str] = None\n ) -> None:\n super().__init__(config, root_smiles)\n self._mol_nodes: List[MoleculeNode] = []\n self._added_mol_nodes: List[MoleculeNode] = []\n self._logger = logger()\n\n if root_smiles:\n self.root: Optional[MoleculeNode] = MoleculeNode.create_root(\n root_smiles, config\n )\n self._mol_nodes.append(self.root)\n else:\n self.root = None\n\n self._routes: List[ReactionTree] = []\n\n self.profiling = {\n \"expansion_calls\": 0,\n \"reactants_generations\": 0,\n }\n\n @classmethod\n def from_json(cls, filename: str, config: Configuration) -> SearchTree:\n \"\"\"\n Create a new search tree by deserialization from a JSON file\n\n :param filename: the path to the JSON node\n :param config: the configuration of the search tree\n :return: a deserialized tree\n \"\"\"\n\n def _find_mol_nodes(node):\n for child_ in node.children:\n tree._mol_nodes.append(child_) # pylint: disable=protected-access\n for grandchild in child_.children:\n _find_mol_nodes(grandchild)\n\n tree = cls(config)\n with open(filename, \"r\") as fileobj:\n dict_ = json.load(fileobj)\n mol_deser = MoleculeDeserializer(dict_[\"molecules\"])\n tree.root = MoleculeNode.from_dict(dict_[\"tree\"], config, mol_deser)\n tree._mol_nodes.append(tree.root) # pylint: disable=protected-access\n for child in tree.root.children:\n _find_mol_nodes(child)\n return tree\n\n @property\n def mol_nodes(self) -> Sequence[MoleculeNode]: # type: ignore\n \"\"\"Return the molecule nodes of the tree\"\"\"\n return self._mol_nodes\n\n def one_iteration(self) -> bool:\n \"\"\"\n Perform one iteration expansion.\n Expands all expandable molecule nodes in the tree, which should be\n on the same depth of the tree.\n\n :raises StopIteration: if the search should be pre-maturely terminated\n :return: if a solution was found\n :rtype: bool\n \"\"\"\n if self.root is None:\n raise ValueError(\"Root is undefined. Cannot make an iteration\")\n\n self._routes = []\n self._added_mol_nodes = []\n\n for next_node in self._mol_nodes:\n if next_node.expandable:\n self._expand(next_node)\n\n if not self._added_mol_nodes:\n self._logger.debug(\"No new nodes added in breadth-first iteration\")\n raise StopIteration\n\n self._mol_nodes.extend(self._added_mol_nodes)\n solved = all(node.in_stock for node in self._mol_nodes if not node.children)\n return solved\n\n def routes(self) -> List[ReactionTree]:\n \"\"\"\n Extracts and returns routes from the AND/OR tree\n\n :return: the routes\n \"\"\"\n if self.root is None:\n return []\n if not self._routes:\n self._routes = SplitAndOrTree(self.root, self.config.stock).routes\n return self._routes\n\n def serialize(self, filename: str) -> None:\n \"\"\"\n Seralize the search tree to a JSON file\n\n :param filename: the path to the JSON file\n :type filename: str\n \"\"\"\n if self.root is None:\n raise ValueError(\"Cannot serialize tree as root is not defined\")\n\n mol_ser = MoleculeSerializer()\n dict_ = {\"tree\": self.root.serialize(mol_ser), \"molecules\": mol_ser.store}\n with open(filename, \"w\") as fileobj:\n json.dump(dict_, fileobj, indent=2)\n\n def _expand(self, node: MoleculeNode) -> None:\n node.expandable = False\n reactions, _ = self.config.expansion_policy([node.mol])\n self.profiling[\"expansion_calls\"] += 1\n\n if not reactions:\n return\n\n reactions_to_expand = []\n for reaction in reactions:\n try:\n self.profiling[\"reactants_generations\"] += 1\n _ = reaction.reactants\n except: # pylint: disable=bare-except\n continue\n if not reaction.reactants:\n continue\n for idx, _ in enumerate(reaction.reactants):\n rxn_copy = reaction.copy(idx)\n reactions_to_expand.append(rxn_copy)\n\n for rxn in reactions_to_expand:\n new_nodes = node.add_stub(rxn)\n self._added_mol_nodes.extend(new_nodes)", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 4982}, "tests/chem/test_serialization.py::29": {"resolved_imports": ["aizynthfinder/chem/serialization.py", "aizynthfinder/chem/__init__.py"], "used_names": ["MoleculeSerializer", "TreeMolecule"], "enclosing_function": "test_add_tree_mol", "extracted_code": "# Source: aizynthfinder/chem/serialization.py\nclass MoleculeSerializer:\n \"\"\"\n Utility class for serializing molecules\n\n The id of the molecule to be serialized can be obtained with:\n\n .. code-block::\n\n serializer = MoleculeSerializer()\n mol = Molecule(smiles=\"CCCO\")\n idx = serializer[mol]\n\n which will take care of the serialization of the molecule.\n \"\"\"\n\n def __init__(self) -> None:\n self._store: Dict[int, Any] = {}\n\n def __getitem__(self, mol: Optional[aizynthfinder.chem.Molecule]) -> Optional[int]:\n if mol is None:\n return None\n\n id_ = id(mol)\n if id_ not in self._store:\n self._add_mol(mol)\n return id_\n\n @property\n def store(self) -> Dict[int, Any]:\n \"\"\"Return all serialized molecules as a dictionary\"\"\"\n return self._store\n\n def _add_mol(self, mol: aizynthfinder.chem.Molecule) -> None:\n id_ = id(mol)\n dict_ = {\"smiles\": mol.smiles, \"class\": mol.__class__.__name__}\n if isinstance(mol, aizynthfinder.chem.TreeMolecule):\n dict_[\"parent\"] = self[mol.parent]\n dict_[\"transform\"] = mol.transform\n if not mol.parent:\n dict_[\"smiles\"] = mol.original_smiles\n else:\n dict_[\"smiles\"] = mol.mapped_smiles\n self._store[id_] = dict_\n\n\n# Source: aizynthfinder/chem/__init__.py\n Molecule,\n MoleculeException,\n TreeMolecule,\n UniqueMolecule,\n none_molecule,\n)\nfrom aizynthfinder.chem.reaction import (\n FixedRetroReaction,\n RetroReaction,\n SmilesBasedRetroReaction,\n TemplatedRetroReaction,\n hash_reactions,", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 1662}, "tests/test_cli.py::133": {"resolved_imports": ["aizynthfinder/analysis/__init__.py", "aizynthfinder/chem/__init__.py", "aizynthfinder/interfaces/__init__.py", "aizynthfinder/interfaces/aizynthapp.py", "aizynthfinder/interfaces/aizynthcli.py", "aizynthfinder/reactiontree.py", "aizynthfinder/tools/cat_output.py", "aizynthfinder/tools/download_public_data.py", "aizynthfinder/tools/make_stock.py"], "used_names": [], "enclosing_function": "test_app_main_no_output", "extracted_code": "", "n_imports_parsed": 17, "n_files_resolved": 9, "n_chars_extracted": 0}, "tests/chem/test_serialization.py::84": {"resolved_imports": ["aizynthfinder/chem/serialization.py", "aizynthfinder/chem/__init__.py"], "used_names": ["MoleculeDeserializer", "MoleculeSerializer", "TreeMolecule"], "enclosing_function": "test_chaining", "extracted_code": "# Source: aizynthfinder/chem/serialization.py\nclass MoleculeSerializer:\n \"\"\"\n Utility class for serializing molecules\n\n The id of the molecule to be serialized can be obtained with:\n\n .. code-block::\n\n serializer = MoleculeSerializer()\n mol = Molecule(smiles=\"CCCO\")\n idx = serializer[mol]\n\n which will take care of the serialization of the molecule.\n \"\"\"\n\n def __init__(self) -> None:\n self._store: Dict[int, Any] = {}\n\n def __getitem__(self, mol: Optional[aizynthfinder.chem.Molecule]) -> Optional[int]:\n if mol is None:\n return None\n\n id_ = id(mol)\n if id_ not in self._store:\n self._add_mol(mol)\n return id_\n\n @property\n def store(self) -> Dict[int, Any]:\n \"\"\"Return all serialized molecules as a dictionary\"\"\"\n return self._store\n\n def _add_mol(self, mol: aizynthfinder.chem.Molecule) -> None:\n id_ = id(mol)\n dict_ = {\"smiles\": mol.smiles, \"class\": mol.__class__.__name__}\n if isinstance(mol, aizynthfinder.chem.TreeMolecule):\n dict_[\"parent\"] = self[mol.parent]\n dict_[\"transform\"] = mol.transform\n if not mol.parent:\n dict_[\"smiles\"] = mol.original_smiles\n else:\n dict_[\"smiles\"] = mol.mapped_smiles\n self._store[id_] = dict_\n\nclass MoleculeDeserializer:\n \"\"\"\n Utility class for deserializing molecules.\n The serialized molecules are created upon instantiation of the class.\n\n The deserialized molecules can be obtained with:\n\n .. code-block::\n\n deserializer = MoleculeDeserializer()\n mol = deserializer[idx]\n\n \"\"\"\n\n def __init__(self, store: Dict[int, Any]) -> None:\n self._objects: Dict[int, Any] = {}\n self._create_molecules(store)\n\n def __getitem__(self, id_: Optional[int]) -> Optional[aizynthfinder.chem.Molecule]:\n if id_ is None:\n return None\n return self._objects[id_]\n\n def get_tree_molecules(\n self, ids: Sequence[int]\n ) -> Sequence[aizynthfinder.chem.TreeMolecule]:\n \"\"\"\n Return multiple deserialized tree molecules\n\n :param ids: the list of IDs to deserialize\n :return: the molecule objects\n \"\"\"\n objects = []\n for id_ in ids:\n obj = self[id_]\n if obj is None or not isinstance(obj, aizynthfinder.chem.TreeMolecule):\n raise ValueError(f\"Failed to deserialize molecule with id {id_}\")\n objects.append(obj)\n return objects\n\n def _create_molecules(self, store: dict) -> None:\n for id_, spec in store.items():\n if isinstance(id_, str):\n id_ = int(id_)\n\n cls = spec[\"class\"]\n if \"parent\" in spec:\n spec[\"parent\"] = self[spec[\"parent\"]]\n\n kwargs = dict(spec)\n del kwargs[\"class\"]\n self._objects[id_] = getattr(aizynthfinder.chem, cls)(**kwargs)\n\n\n# Source: aizynthfinder/chem/__init__.py\n Molecule,\n MoleculeException,\n TreeMolecule,\n UniqueMolecule,\n none_molecule,\n)\nfrom aizynthfinder.chem.reaction import (\n FixedRetroReaction,\n RetroReaction,\n SmilesBasedRetroReaction,\n TemplatedRetroReaction,\n hash_reactions,", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 3289}, "tests/dfpn/test_nodes.py::61": {"resolved_imports": ["aizynthfinder/search/dfpn/nodes.py", "aizynthfinder/search/dfpn/__init__.py"], "used_names": [], "enclosing_function": "test_expand_reaction_node", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/context/test_policy.py::230": {"resolved_imports": ["aizynthfinder/chem/__init__.py", "aizynthfinder/context/policy/__init__.py", "aizynthfinder/utils/exceptions.py"], "used_names": ["TreeMolecule"], "enclosing_function": "test_template_based_expansion_caching", "extracted_code": "# Source: aizynthfinder/chem/__init__.py\n Molecule,\n MoleculeException,\n TreeMolecule,\n UniqueMolecule,\n none_molecule,\n)\nfrom aizynthfinder.chem.reaction import (\n FixedRetroReaction,\n RetroReaction,\n SmilesBasedRetroReaction,\n TemplatedRetroReaction,\n hash_reactions,", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 299}, "tests/chem/test_mol.py::41": {"resolved_imports": ["aizynthfinder/chem/__init__.py"], "used_names": ["Molecule"], "enclosing_function": "test_fingerprint", "extracted_code": "# Source: aizynthfinder/chem/__init__.py\n\"\"\"\nfrom aizynthfinder.chem.mol import (\n Molecule,\n MoleculeException,\n TreeMolecule,\n UniqueMolecule,\n none_molecule,\n)\nfrom aizynthfinder.chem.reaction import (\n FixedRetroReaction,\n RetroReaction,\n SmilesBasedRetroReaction,\n\nfrom aizynthfinder.chem.mol import (\n Molecule,\n MoleculeException,\n TreeMolecule,\n UniqueMolecule,\n none_molecule,\n)\nfrom aizynthfinder.chem.reaction import (\n FixedRetroReaction,\n RetroReaction,\n SmilesBasedRetroReaction,\n TemplatedRetroReaction,\n\n Molecule,\n MoleculeException,\n TreeMolecule,\n UniqueMolecule,\n none_molecule,\n)\nfrom aizynthfinder.chem.reaction import (\n FixedRetroReaction,\n RetroReaction,\n SmilesBasedRetroReaction,\n TemplatedRetroReaction,\n hash_reactions,\n\n MoleculeException,\n TreeMolecule,\n UniqueMolecule,\n none_molecule,\n)\nfrom aizynthfinder.chem.reaction import (\n FixedRetroReaction,\n RetroReaction,\n SmilesBasedRetroReaction,\n TemplatedRetroReaction,\n hash_reactions,\n)\n\n)\nfrom aizynthfinder.chem.serialization import (\n MoleculeDeserializer,\n MoleculeSerializer,\n deserialize_action,\n serialize_action,\n)", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 1225}, "tests/retrostar/test_retrostar.py::106": {"resolved_imports": ["aizynthfinder/search/retrostar/search_tree.py", "aizynthfinder/chem/serialization.py"], "used_names": ["MoleculeSerializer", "SearchTree"], "enclosing_function": "test_serialization_deserialization", "extracted_code": "# Source: aizynthfinder/search/retrostar/search_tree.py\nclass SearchTree(AndOrSearchTreeBase):\n \"\"\"\n Encapsulation of the Retro* search tree (an AND/OR tree).\n\n :ivar config: settings of the tree search algorithm\n :ivar root: the root node\n\n :param config: settings of the tree search algorithm\n :param root_smiles: the root will be set to a node representing this molecule, defaults to None\n \"\"\"\n\n def __init__(\n self, config: Configuration, root_smiles: Optional[str] = None\n ) -> None:\n super().__init__(config, root_smiles)\n self._mol_nodes: List[MoleculeNode] = []\n self._logger = logger()\n self.molecule_cost = MoleculeCost(config)\n\n if root_smiles:\n self.root: Optional[MoleculeNode] = MoleculeNode.create_root(\n root_smiles, config, self.molecule_cost\n )\n self._mol_nodes.append(self.root)\n else:\n self.root = None\n\n self._routes: List[ReactionTree] = []\n\n self.profiling = {\n \"expansion_calls\": 0,\n \"reactants_generations\": 0,\n }\n\n @classmethod\n def from_json(cls, filename: str, config: Configuration) -> SearchTree:\n \"\"\"\n Create a new search tree by deserialization from a JSON file\n\n :param filename: the path to the JSON node\n :param config: the configuration of the search tree\n :return: a deserialized tree\n \"\"\"\n\n def _find_mol_nodes(node):\n for child_ in node.children:\n tree._mol_nodes.append(child_) # pylint: disable=protected-access\n for grandchild in child_.children:\n _find_mol_nodes(grandchild)\n\n tree = cls(config)\n with open(filename, \"r\") as fileobj:\n dict_ = json.load(fileobj)\n mol_deser = MoleculeDeserializer(dict_[\"molecules\"])\n tree.root = MoleculeNode.from_dict(\n dict_[\"tree\"], config, mol_deser, tree.molecule_cost\n )\n tree._mol_nodes.append(tree.root) # pylint: disable=protected-access\n for child in tree.root.children:\n _find_mol_nodes(child)\n return tree\n\n @property\n def mol_nodes(self) -> Sequence[MoleculeNode]: # type: ignore\n \"\"\"Return the molecule nodes of the tree\"\"\"\n return self._mol_nodes\n\n def one_iteration(self) -> bool:\n \"\"\"\n Perform one iteration of\n 1. Selection\n 2. Expansion\n 3. Update\n\n :raises StopIteration: if the search should be pre-maturely terminated\n :return: if a solution was found\n :rtype: bool\n \"\"\"\n if self.root is None:\n raise ValueError(\"Root is undefined. Cannot make an iteration\")\n\n self._routes = []\n\n next_node = self._select()\n\n if not next_node:\n self._logger.debug(\"No expandable nodes in Retro* iteration\")\n raise StopIteration\n\n self._expand(next_node)\n\n if not next_node.children:\n next_node.expandable = False\n\n self._update(next_node)\n\n return self.root.solved\n\n def routes(self) -> List[ReactionTree]:\n \"\"\"\n Extracts and returns routes from the AND/OR tree\n\n :return: the routes\n \"\"\"\n if self.root is None:\n return []\n if not self._routes:\n self._routes = SplitAndOrTree(self.root, self.config.stock).routes\n return self._routes\n\n def serialize(self, filename: str) -> None:\n \"\"\"\n Seralize the search tree to a JSON file\n\n :param filename: the path to the JSON file\n :type filename: str\n \"\"\"\n if self.root is None:\n raise ValueError(\"Cannot serialize tree as root is not defined\")\n\n mol_ser = MoleculeSerializer()\n dict_ = {\"tree\": self.root.serialize(mol_ser), \"molecules\": mol_ser.store}\n with open(filename, \"w\") as fileobj:\n json.dump(dict_, fileobj, indent=2)\n\n def _expand(self, node: MoleculeNode) -> None:\n reactions, priors = self.config.expansion_policy([node.mol])\n self.profiling[\"expansion_calls\"] += 1\n\n if not reactions:\n return\n\n costs = -np.log(np.clip(priors, 1e-3, 1.0))\n reactions_to_expand = []\n reaction_costs = []\n for reaction, cost in zip(reactions, costs):\n try:\n self.profiling[\"reactants_generations\"] += 1\n _ = reaction.reactants\n except: # pylint: disable=bare-except\n continue\n if not reaction.reactants:\n continue\n for idx, _ in enumerate(reaction.reactants):\n rxn_copy = reaction.copy(idx)\n if self._filter_reaction(rxn_copy):\n continue\n reactions_to_expand.append(rxn_copy)\n reaction_costs.append(cost)\n\n for cost, rxn in zip(reaction_costs, reactions_to_expand):\n new_nodes = node.add_stub(cost, rxn)\n self._mol_nodes.extend(new_nodes)\n\n def _filter_reaction(self, reaction: RetroReaction) -> bool:\n if not self.config.filter_policy.selection:\n return False\n try:\n self.config.filter_policy(reaction)\n except RejectionException as err:\n self._logger.debug(str(err))\n return True\n return False\n\n def _select(self) -> Optional[MoleculeNode]:\n scores = np.asarray(\n [\n node.target_value if node.expandable else np.inf\n for node in self._mol_nodes\n ]\n )\n\n if scores.min() == np.inf:\n return None\n\n return self._mol_nodes[int(np.argmin(scores))]\n\n @staticmethod\n def _update(node: MoleculeNode) -> None:\n v_delta = node.close()\n if node.parent and np.isfinite(v_delta):\n node.parent.update(v_delta, from_mol=node.mol)\n\n\n# Source: aizynthfinder/chem/serialization.py\nclass MoleculeSerializer:\n \"\"\"\n Utility class for serializing molecules\n\n The id of the molecule to be serialized can be obtained with:\n\n .. code-block::\n\n serializer = MoleculeSerializer()\n mol = Molecule(smiles=\"CCCO\")\n idx = serializer[mol]\n\n which will take care of the serialization of the molecule.\n \"\"\"\n\n def __init__(self) -> None:\n self._store: Dict[int, Any] = {}\n\n def __getitem__(self, mol: Optional[aizynthfinder.chem.Molecule]) -> Optional[int]:\n if mol is None:\n return None\n\n id_ = id(mol)\n if id_ not in self._store:\n self._add_mol(mol)\n return id_\n\n @property\n def store(self) -> Dict[int, Any]:\n \"\"\"Return all serialized molecules as a dictionary\"\"\"\n return self._store\n\n def _add_mol(self, mol: aizynthfinder.chem.Molecule) -> None:\n id_ = id(mol)\n dict_ = {\"smiles\": mol.smiles, \"class\": mol.__class__.__name__}\n if isinstance(mol, aizynthfinder.chem.TreeMolecule):\n dict_[\"parent\"] = self[mol.parent]\n dict_[\"transform\"] = mol.transform\n if not mol.parent:\n dict_[\"smiles\"] = mol.original_smiles\n else:\n dict_[\"smiles\"] = mol.mapped_smiles\n self._store[id_] = dict_", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 7318}, "tests/test_finder.py::37": {"resolved_imports": ["aizynthfinder/aizynthfinder.py"], "used_names": [], "enclosing_function": "test_dead_end_expansion", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 0}}}