Exemple #1
0
def test_incorrect_class():
    bad_class = "ReactionTreee"
    with pytest.raises(ValueError, match=bad_class):
        load_dynamic_class(f"aizynthfinder.reactiontree.{bad_class}")

    with pytest.raises(MyException, match=bad_class):
        load_dynamic_class(f"aizynthfinder.reactiontree.{bad_class}",
                           exception_cls=MyException)
Exemple #2
0
def test_incorrect_module():
    bad_module = "aizynthfinder.rt."
    with pytest.raises(ValueError, match=bad_module):
        load_dynamic_class(f"{bad_module}.ReactionTree")

    with pytest.raises(MyException, match=bad_module):
        load_dynamic_class(f"{bad_module}.ReactionTree",
                           exception_cls=MyException)
Exemple #3
0
    def load_from_config(self, **config: Any) -> None:
        """
        Load one or more filter policy from a configuration

        The format should be
        files:
            key: path_to_model
        or
        quick-filter:
            key: path_to_model
        or
        custom_package.custom_model.CustomClass:
            key:
                param1: value1
                param2: value2

        :param config: the configuration
        """
        files_spec = config.get("files", config.get("quick-filter", {}))
        for key, modelfile in files_spec.items():
            strategy = QuickKerasFilter(key, self._config, source=modelfile)
            self.load(strategy)

        # Load policies specifying a module and class, e.g. package.module.MyStrategyClass
        for strategy_spec, strategy_config in config.items():
            if strategy_spec in ["files", "quick-filter"]:
                continue
            cls = load_dynamic_class(strategy_spec, filter_strategy_module,
                                     PolicyException)
            for key, policy_spec in strategy_config.items():
                obj = cls(key, self._config, **(policy_spec or {}))
                self.load(obj)
Exemple #4
0
    def load_from_config(self, **config: Any) -> None:
        """
        Load stocks from a configuration

        The key can be "files" in case stocks are loaded from a file
        The key can be "mongodb" in case a ``MongoDbInchiKeyQuery`` object is instantiated
        The key can be "stop_criteria" in case the config is given to the `set_stop_criteria` method
        The key can point to a custom stock class, e.g. ``mypackage.mymodule.MyStock``
        in case this stock object is instantiated

        :param config: the configuration
        """
        known_keys = ["files", "mongodb", "stop_criteria"]
        if "stop_criteria" in config:
            self.set_stop_criteria(config["stop_criteria"])

        for key, stockfile in config.get("files", {}).items():
            self.load(stockfile, key)

        if "mongodb" in config:
            query_obj = MongoDbInchiKeyQuery(**(config["mongodb"] or {}))
            self.load(query_obj, "mongodb_stock")

        # Load stocks specifying a module and class, e.g. package.module.MyQueryClass
        for name, stock_config in config.items():
            if name in known_keys or name.find(".") == -1:
                continue

            try:
                query_cls = load_dynamic_class(name)
            except ValueError as err:
                self._logger.warning(str(err))
            else:
                query_obj = query_cls(**(stock_config or {}))
                self.load(query_obj, query_cls.__name__)
 def _setup_search_tree(self):
     self._logger.debug("Defining tree root: %s" % self.target_smiles)
     if self.config.search_algorithm.lower() == "mcts":
         self.tree = MctsSearchTree(root_smiles=self.target_smiles,
                                    config=self.config)
     else:
         cls = load_dynamic_class(self.config.search_algorithm)
         self.tree: AndOrSearchTreeBase = cls(
             root_smiles=self.target_smiles, config=self.config)
def deserialize_action(
    dict_: StrDict, molecule_store: MoleculeDeserializer
) -> RetroReaction:
    """
    Deserialize a retrosynthesis action

    :param dict_: the (re)action as a dictionary
    :param molecule_store: the molecule deserialization object
    :return: the created action object
    """
    mol_spec = dict_.pop("mol")
    mol = molecule_store.get_tree_molecules([mol_spec])[0]
    try:
        class_spec = dict_.pop("class")
    except KeyError:
        class_spec = "aizynthfinder.chem.TemplatedRetroReaction"
    cls = load_dynamic_class(class_spec)
    return cls(mol, **dict_)
Exemple #7
0
    def load_from_config(self, **costs_config: Any) -> None:
        """
        Load one or more cost models from a configuration

        The format should be:
            key: config_for_model

        :param costs_config: the configuration
        """
        for name_spec, scorer_config in costs_config.items():
            if name_spec in self._aliases:
                cls = self._aliases[name_spec]
            else:
                cls = load_dynamic_class(name_spec, costs_module,
                                         CostException)
            obj = cls(**(scorer_config or {}))
            config_str = (f" from configuration '{scorer_config}'"
                          if scorer_config else "")
            self._logger.info(f"Loaded cost: '{repr(obj)}'{config_str}")
            self._items[repr(obj)] = obj
    def load_from_config(self, **scorers_config: Any) -> None:
        """
        Load one or several scorers from a configuration dictionary

        The keys are the name of scorer class. If a scorer is not
        defined in the ``aizynthfinder.context.scoring`` module, the module
        name can be appended, e.g. ``mypackage.scoring.AwesomeScore``.

        The values of the configuration is passed directly to the scorer
        class along with the ``config`` parameter.

        :raises ScorerException: if module or class could not be found
        """
        for name_spec, scorer_config in scorers_config.items():
            config_str = (f" from configuration '{scorer_config}'"
                          if scorer_config else "")
            cls = load_dynamic_class(name_spec, scorers_module,
                                     ScorerException)
            obj = cls(self._config, **(scorer_config or {}))
            self._logger.info(f"Loaded scorer: '{repr(obj)}'{config_str}")
            self._items[repr(obj)] = obj
Exemple #9
0
    def load_from_config(self, **config: Any) -> None:
        """
        Load one or more expansion policy from a configuration

        The format should be
        files:
            key:
                - path_to_model
                - path_to_templates
        or
        template-based:
            key:
                - path_to_model
                - path_to_templates
        or
        custom_package.custom_model.CustomClass:
            key:
                param1: value1
                param2: value2

        :param config: the configuration
        """
        files_spec = config.get("files", config.get("template-based", {}))
        for key, policy_spec in files_spec.items():
            modelfile, templatefile = policy_spec
            strategy = TemplateBasedExpansionStrategy(
                key, self._config, source=modelfile, templatefile=templatefile)
            self.load(strategy)

        # Load policies specifying a module and class, e.g. package.module.MyStrategyClass
        for strategy_spec, strategy_config in config.items():
            if strategy_spec in ["files", "template-based"]:
                continue
            cls = load_dynamic_class(strategy_spec, expansion_strategy_module,
                                     PolicyException)
            for key, policy_spec in strategy_config.items():
                obj = cls(key, self._config, **(policy_spec or {}))
                self.load(obj)
Exemple #10
0
def test_simple():
    cls = load_dynamic_class("aizynthfinder.reactiontree.ReactionTree")

    assert cls.__name__ == "ReactionTree"
Exemple #11
0
def test_no_default_module():
    with pytest.raises(ValueError, match="default_module"):
        load_dynamic_class("ReactionTree")

    with pytest.raises(MyException, match="default_module"):
        load_dynamic_class("ReactionTree", exception_cls=MyException)
Exemple #12
0
def test_default_module():
    cls = load_dynamic_class("ReactionTree",
                             default_module="aizynthfinder.reactiontree")

    assert cls.__name__ == "ReactionTree"