コード例 #1
0
ファイル: gp.py プロジェクト: julesy89/pysurrogate
 def __init__(self):
     Problem.__init__(self)
     self.n_var = n_params
     self.n_constr = 0
     self.n_obj = 1
     self.func = self.evaluate_
     self.xl = 0.01 * np.ones(n_params)
     self.xu = 20 * np.ones(n_params)
コード例 #2
0
ファイル: optimize.py プロジェクト: hihiworld/pymoo
 def __init__(self):
     Problem.__init__(self)
     self.n_var = n_var
     self.n_constr = n_constr
     self.n_obj = n_obj
     self.func = self._evaluate
     self.xl = xl
     self.xu = xu
コード例 #3
0
 def __init__(self, n_var=1, **kwargs):
     Problem.__init__(self, **kwargs)
     self.n_var = n_var
     self.n_constr = 0
     self.n_obj = 1
     self.func = self._evaluate
     self.xl = 0 * np.ones(self.n_var)
     self.xu = 10 * np.ones(self.n_var)
コード例 #4
0
 def __init__(self, n_var, thetaL, thetaU, func_likelihood):
     Problem.__init__(self)
     self.n_var = n_var
     self.n_constr = 0
     self.n_obj = 1
     self.func_likelihood = func_likelihood
     self.func = self.evaluate_
     self.xl = thetaL
     self.xu = thetaU
コード例 #5
0
ファイル: dominator.py プロジェクト: hihiworld/pymoo
    def calc_domination_matrix(F, G):

        if G is None or len(G) == 0:
            constr = np.zeros((F.shape[0], F.shape[0]))
        else:
            # consider the constraint violation
            #CV = Problem.calc_constraint_violation(G)
            #constr = (CV < CV) * 1 + (CV > CV) * -1

            CV = Problem.calc_constraint_violation(G)[:, 0]
            constr = (CV[:, None] < CV) * 1 + (CV[:, None] > CV) * -1

        # look at the obj for dom
        n = F.shape[0]
        L = np.repeat(F, n, axis=0)
        R = np.tile(F, (n, 1))

        smaller = np.reshape(np.any(L < R, axis=1), (n, n))
        larger = np.reshape(np.any(L > R, axis=1), (n, n))

        dom = np.logical_and(smaller, np.logical_not(larger)) * 1 \
              + np.logical_and(larger, np.logical_not(smaller)) * -1

        # if cv equal then look at dom
        M = constr + (constr == 0) * dom
        return M
コード例 #6
0
    def __init__(self, name, n_var, n_obj, k=None):
        Problem.__init__(self)
        self.n_obj = n_obj
        self.n_var = n_var
        self.k = 2 * (self.n_obj - 1) if k is None else k
        self.func = self._evaluate
        self.xl = np.zeros(self.n_var)
        self.xu = np.ones(self.n_var)

        # function used to evaluate
        self.func = self._evaluate

        # the function pointing to the optproblems implementation
        exec('import optproblems.wfg')
        clazz, = eval('optproblems.wfg.%s' % name),
        self._func = clazz(num_objectives=self.n_obj,
                           num_variables=self.n_var,
                           k=self.k)
コード例 #7
0
def minimize(fun, x0):
    n_var = len(x0)
    p = Problem(n_var=n_var, n_obj=1, n_constr=0, xl=-10, xu=10, func=None)

    def evaluate(x):
        f = numpy.zeros((x.shape[0], 1))
        g = numpy.zeros((x.shape[0], 0))

        if x.ndim == 1:
            x = numpy.array([x])
        for i in range(x.shape[0]):
            f[i, :] = fun(x[i, :])[0]
        return f, g

    p.evaluate = evaluate

    # X,F,G = NSGA(pop_size=300).solve(p, 60000)

    # X, F, G = solve_by_de(p)

    print(X)
    print(F)

    return X[0, :]
コード例 #8
0
ファイル: fitness_survival.py プロジェクト: hihiworld/pymoo
    def _do(self, pop, off, size, **kwargs):

        pop.merge(off)

        if pop.F.shape[1] != 1:
            raise ValueError("FitnessSurvival can only used for single objective problems!")

        if pop.G is None or len(pop.G) == 0:
            CV = np.zeros(pop.F.shape[0])
        else:
            CV = Problem.calc_constraint_violation(pop.G)
            CV[CV < 0] = 0.0

        # sort by cv and fitness
        sorted_idx = sorted(range(pop.size()), key=lambda x: (CV[x], pop.F[x]))

        # now truncate the population
        sorted_idx = sorted_idx[:size]
        pop.filter(sorted_idx)
コード例 #9
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
            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
            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.

            Allowed is ["F", "CV", "G", "dF", "dG", "dCV", "hF", "hG", "hCV", "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.

        """
        # make the array at least 2-d - even if only one row should be evaluated
        # only_single_value = len(np.shape(X)) == 1
        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")

        # create the output dictionary for _evaluate to be filled
        out = {}
        for val in return_values_of:
            out[val] = None

        # 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")
        ]

        # if no autograd is necessary for evaluation just traditionally use the evaluation method
        if len(gradients_not_set) == 0:
            self._evaluate(X, out, *args, **kwargs)
            at_least2d(out)

        # 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)

        # 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])
コード例 #10
0
ファイル: algorithm.py プロジェクト: hihiworld/pymoo
    def solve(
        self,
        problem,
        evaluator,
        seed=1,
        return_only_feasible=True,
        return_only_non_dominated=True,
        history=None,
    ):
        """

        Solve a given problem by a given evaluator. The evaluator determines the termination condition and
        can either have a maximum budget, hypervolume or whatever. The problem can be any problem the algorithm
        is able to solve.

        Parameters
        ----------

        problem: class
            Problem to be solved by the algorithm

        evaluator: class
            object that evaluates and saves the number of evaluations and determines the stopping condition

        seed: int
            Random seed for this run. Before the algorithm starts this seed is set.

        return_only_feasible : bool
            If true, only feasible solutions are returned.

        return_only_non_dominated : bool
            If true, only the non dominated solutions are returned. Otherwise, it might be - dependend on the
            algorithm - the final population

        Returns
        -------
        X: matrix
            Design space

        F: matrix
            Objective space

        G: matrix
            Constraint space

        """

        # set the random seed for generator
        pymoo.rand.random.seed(seed)

        # just to be sure also for the others
        seed = pymoo.rand.random.randint(0, 100000)
        random.seed(seed)
        np.random.seed(seed)

        # this allows to provide only an integer instead of an evaluator object
        if not isinstance(evaluator, Evaluator):
            evaluator = Evaluator(evaluator)

        # call the algorithm to solve the problem
        X, F, G = self._solve(problem, evaluator)

        if return_only_feasible:
            if G is not None and G.shape[0] == len(F) and G.shape[1] > 0:
                cv = Problem.calc_constraint_violation(G)[:, 0]
                X = X[cv <= 0, :]
                F = F[cv <= 0, :]
                if G is not None:
                    G = G[cv <= 0, :]

        if return_only_non_dominated:
            idx_non_dom = NonDominatedRank.calc_as_fronts(F, G)[0]
            X = X[idx_non_dom, :]
            F = F[idx_non_dom, :]
            if G is not None:
                G = G[idx_non_dom, :]

        return X, F, G