コード例 #1
0
ファイル: interface.py プロジェクト: wwxFromTju/pymoo
    def __init__(self, algorithm, problem=None, **kwargs):

        if problem is not None:
            self.problem = copy.deepcopy(problem)
        else:
            self.problem = Problem(**kwargs)

        self.algorithm = copy.deepcopy(algorithm)
コード例 #2
0
ファイル: evaluator.py プロジェクト: mbeza/pymoo-1
def set_cv(pop, feasbility=True):
    for ind in pop:
        if ind.G is None:
            ind.CV = np.zeros(1)
        else:
            ind.CV = Problem.calc_constraint_violation(at_least_2d_array(
                ind.G))[0]

    if feasbility:
        set_feasibility(pop)
コード例 #3
0
ファイル: problem.py プロジェクト: Huaxu007/AutoOED
    def __init__(self, config=None):
        # pre-process config
        if config is not None:
            self.config = config
        if 'name' not in self.config:
            self.config['name'] = self.__class__.__name__
        check_config(self.config)

        # initialize continuous problem with transformed config
        PymooProblem.__init__(self, **transform_config(self.config))

        # complete config
        self.config = complete_config(self.config)

        # problem properties
        self.var_name = self.config['var_name']
        self.obj_name = self.config['obj_name']
        self.obj_type = self.config['obj_type']
        self.ref_point = self.config['ref_point']
        self.transformation = get_transformation(self.config)

        # import objective evaluation function
        if self.config['obj_func'] is not None:
            self.evaluate_objective = import_obj_func(self.config['obj_func'],
                                                      self.config['n_var'],
                                                      self.config['n_obj'])

        # import constraint evaluation function
        if self.config['constr_func'] is None:
            if not hasattr(self, 'evaluate_constraint'):
                if self.config['n_constr'] > 0:
                    raise Exception('no constraint function is provided')
                else:
                    self.evaluate_constraint = no_constraint_evaluation
        else:
            self.evaluate_constraint = import_constr_func(
                self.config['constr_func'], self.config['n_var'],
                self.config['n_constr'])
コード例 #4
0
ファイル: so_sqlp.py プロジェクト: abfarr/moo2020
 def _update(self):
     D = self.D
     ind = Individual(X=np.copy(D["X"]), F=np.copy(D["F"]), G=np.copy(-D["G"]))
     ind.CV = Problem.calc_constraint_violation(ind.G[None, :])[0]
     ind.feasible = (ind.CV <= 0)
     self.pop = Population.merge(self.pop, Population.create(ind))
コード例 #5
0
    def evaluate(self, X, *args, return_values_of="auto", return_as_dictionary=False, **kwargs):
        '''
        Evaluate the given problem.

        The function values set as defined in the function.
        The constraint values are meant to be positive if infeasible. A higher positive values means "more" infeasible".
        If they are 0 or negative, they will be considered as feasible what ever their value is.

        Parameters
        ----------
        X : np.array
            A two dimensional matrix where each row is a point to evaluate and each column a variable.
        return_as_dictionary : bool, default=False
            If this is true than only one object, a dictionary, is returned. This contains all the results
            that are defined by return_values_of. Otherwise, by default a tuple as defined is returned.
        return_values_of : list of strings, default='auto'
            You can provide a list of strings which defines the values that are returned. By default it is set to
            "auto" which means depending on the problem the function values or additional the constraint violation (if
            the problem has constraints) are returned. Otherwise, you can provide a list of values to be returned.\n
            Allowed is ["F", "CV", "G", "dF", "dG", "dCV", "feasible"] where the d stands for
            derivative and h stands for hessian matrix.

        Returns
        -------
            A dictionary, if return_as_dictionary enabled, or a list of values as defined in return_values_of.
        '''
        assert self.acquisition.fitted, 'Acquisition function is not fitted before surrogate problem evaluation'

        # call the callback of the problem
        if self.callback is not None:
            self.callback(X)

        # make the array at least 2-d - even if only one row should be evaluated
        only_single_value = len(np.shape(X)) == 1
        X = np.atleast_2d(X)

        # check the dimensionality of the problem and the given input
        if X.shape[1] != self.n_var:
            raise Exception('Input dimension %s are not equal to n_var %s!' % (X.shape[1], self.n_var))

        # automatic return the function values and CV if it has constraints if not defined otherwise
        if type(return_values_of) == str and return_values_of == "auto":
            return_values_of = ["F"]
            if self.n_constr > 0:
                return_values_of.append("CV")

        # all values that are set in the evaluation function
        values_not_set = [val for val in return_values_of if val not in self.evaluation_of]

        # have a look if gradients are not set and try to use autograd and calculate grading if implemented using it
        gradients_not_set = [val for val in values_not_set if val.startswith("d")]

        # whether gradient calculation is necessary or not
        gradient = (len(gradients_not_set) > 0)

        # handle hF (hessian) computation, which is not supported by Pymoo
        hessian = (type(return_values_of) == list and 'hF' in return_values_of)

        # set in the dictionary if the output should be calculated - can be used for the gradient
        out = {}
        for val in return_values_of:
            out[val] = None

        # calculate the output array - either elementwise or not. also consider the gradient
        self._evaluate(X, out, *args, gradient=gradient, hessian=hessian, **kwargs)
        at_least2d(out)

        gradient_of = [key for key, val in out.items()
                            if "d" + key in return_values_of and
                            out.get("d" + key) is None and
                            (type(val) == autograd.numpy.numpy_boxes.ArrayBox)]

        if len(gradient_of) > 0:
            deriv = self._gradient(out, gradient_of)
            out = {**out, **deriv}

        # convert back to conventional numpy arrays - no array box as return type
        for key in out.keys():
            if type(out[key]) == autograd.numpy.numpy_boxes.ArrayBox:
                out[key] = out[key]._value

        # if constraint violation should be returned as well
        if self.n_constr == 0:
            CV = np.zeros([X.shape[0], 1])
        else:
            CV = Problem.calc_constraint_violation(out["G"])

        if "CV" in return_values_of:
            out["CV"] = CV

        # if an additional boolean flag for feasibility should be returned
        if "feasible" in return_values_of:
            out["feasible"] = (CV <= 0)

        # if asked for a value but not set in the evaluation set to None
        for val in return_values_of:
            if val not in out:
                out[val] = None

        # remove the first dimension of the output - in case input was a 1d- vector
        if only_single_value:
            for key in out.keys():
                if out[key] is not None:
                    out[key] = out[key][0, :]

        if return_as_dictionary:
            return out
        else:
            # if just a single value do not return a tuple
            if len(return_values_of) == 1:
                return out[return_values_of[0]]
            else:
                return tuple([out[val] for val in return_values_of])
コード例 #6
0
def set_cv(pop):
    CV = Problem.calc_constraint_violation(pop.get("G"))
    pop.set("CV", CV)