Exemplo n.º 1
0
    def _get_available_algorithms(self, alg_dir):
        """
        Create a new list of algorithm files from model/algorithms dir.
        Create a dict of {Category: [alg, alg, ...]} that will be used to
        instantiate a specific Algorithm for the current category.
        Create a list of algorithms available for current category.
        Raise an error if no algorithm files were found.

        Args:
            *alg_dir* (str): a directory path for algorithms

        Vars:
            | *found_algs* (list): a filtered list of algorithm file names
            | *ignored*: a regex object, used to filter unnecessary files
            | *imported_algs* (list): a list of imported algorithm files

        Returns:
            | *category_alg_map* (dict): a dict of {Category: [alg, alg, ...]}
            | *alg_names* (list): algorithm list of the current category

        """
        alg_files = os.listdir(alg_dir)
        excluded = r'.*.pyc|__init__|_alg.py|__pycache__|_utility.py|_thread'
        ign = re.compile(excluded)
        found_algs = list(filter(lambda x: not ign.match(x), alg_files))
        if not found_algs:
            raise FileNotFoundError("No algorithm files were found in "
                                    "./model/algorithms")
        # add abs paths
        found_algs_paths = [os.path.join('nefi2', 'model', 'algorithms', alg)
                            for alg in found_algs]
        # import all available algorithm files as modules
        imported_algs = []
        for alg_path in found_algs_paths:
            alg_name = os.path.basename(alg_path).split('.')[0]
            algmod = SourceFileLoader(alg_name, alg_path).load_module()
            try:
                new_alg = algmod.AlgBody()
                new_alg_copy = copy.deepcopy(new_alg)
                imported_algs.append(new_alg_copy)  # instantiating algorithms
            except AttributeError as ex:
                print("AttributeError in _get_available_algorithms()", ex)
                continue
        # assign instantiated algorithms to corresponding categories
        category_alg_map = {self.name: [alg for alg in imported_algs
                                        if self.name == alg.belongs()]}
        alg_names = [alg.get_name() for alg in imported_algs
                     if self.name == alg.belongs()]
        return category_alg_map, alg_names