Exemplo n.º 1
0
    def test_optimise_eq_constrained_function2(self):
        n = 2
        N = 20
        value = 2.0
        X = np.random.uniform(-1.0, 1.0, (N, n))
        # Function values for f and Poly object
        f = self.ObjFun(X)
        fparam = eq.Parameter(distribution='uniform',
                              lower=-1.,
                              upper=1.,
                              order=self.degf)
        fParameters = [fparam for i in range(n)]
        myBasis = eq.Basis('total-order')
        fpoly = eq.Poly(fParameters,
                        myBasis,
                        method='least-squares',
                        sampling_args={
                            'sample-points': X,
                            'sample-outputs': f
                        })
        fpoly.set_model()
        g1Func = lambda x: value - self.ConFun1(x.reshape(1, -1))

        for method in ['trust-constr', 'SLSQP']:
            Opt = eq.Optimisation(method=method)
            Opt.add_objective(poly=fpoly)
            Opt.add_nonlinear_eq_con(custom={'function': g1Func})
            x0 = np.zeros(n)
            sol = Opt.optimise(x0)
            if sol['status'] == 0:
                np.testing.assert_almost_equal(sol['x'].flatten(),
                                               np.array([1.0, 1.0]),
                                               decimal=2)
Exemplo n.º 2
0
    def test_optimise_custom_function_linear_ineq_con2(self):
        n = 2
        N = 20

        X = np.random.uniform(-1.0, 1.0, (N, n))
        # Function values for f and Poly object
        f = self.ObjFun(X)
        fparam = eq.Parameter(distribution='uniform',
                              lower=-1.,
                              upper=1.,
                              order=self.degf)
        fParameters = [fparam for i in range(n)]
        myBasis = eq.Basis('total-order')
        fpoly = eq.Poly(fParameters,
                        myBasis,
                        method='least-squares',
                        sampling_args={
                            'sample-points': X,
                            'sample-outputs': f
                        })
        fpoly.set_model()
        for method in ['COBYLA', 'SLSQP', 'trust-constr']:
            Opt = eq.Optimisation(method=method)
            Opt.add_objective(poly=fpoly)
            Opt.add_linear_ineq_con(np.eye(n), -np.ones(n),
                                    np.inf * np.ones(n))
            x0 = np.random.uniform(-1.0, 1.0, n)
            sol = Opt.optimise(x0)
            if sol['status'] == 0:
                np.testing.assert_almost_equal(sol['x'].flatten(),
                                               np.array([1.0, 1.0]),
                                               decimal=3)
 def test_optimise_omorf_as(self):
     n = 10
     Opt = eq.Optimisation(method='omorf')
     Opt.add_objective(custom={'function': self.ObjFun2})
     x0 = -2 * np.ones(n)
     sol = Opt.optimise(x0, del_k=0.1)
     # print(sol)
     np.testing.assert_almost_equal(sol['fun'], -39.1661656 * n, decimal=4)
 def test_optimise_trustregion_random(self):
     n = 2
     Opt = eq.Optimisation(method='trust-region')
     Opt.add_objective(custom={'function': self.ObjFun1})
     x0 = np.zeros(n)
     sol = Opt.optimise(x0, del_k=0.1, random_initial=True)
     # print(sol)
     np.testing.assert_almost_equal(sol['fun'], 0.0, decimal=4)
 def test_optimise_trustregion_bounds(self):
     n = 2
     Opt = eq.Optimisation(method='trust-region')
     Opt.add_objective(custom={'function': self.ObjFun1})
     Opt.add_bounds(-np.ones(n), np.ones(n))
     x0 = np.zeros(n)
     sol = Opt.optimise(x0)
     # print(sol)
     np.testing.assert_almost_equal(sol['fun'], 0.0, decimal=6)
    def test_optimise_custom_function_bounds_maximise(self):
        n = 2

        for method in ['L-BFGS-B', 'TNC', 'COBYLA', 'SLSQP']:
            Opt = eq.Optimisation(method=method)
            Opt.add_objective(
                custom={'function': lambda x: self.ConFun1(x.reshape(1, -1))},
                maximise=True)
            Opt.add_bounds(-np.ones(n), np.ones(n))
            x0 = np.zeros(n)
            sol = Opt.optimise(x0)
            np.testing.assert_almost_equal(sol['x'].flatten(),
                                           np.array([1.0, 1.0]),
                                           decimal=3)
 def test_optimise_constrained_poly2(self):
     n = 2
     N = 20
     bounds = [0.0, np.inf]
     X = np.random.uniform(-1.0, 1.0, (N, n))
     # Function values for f and Poly object
     f = self.ObjFun1(X)
     fparam = eq.Parameter(distribution='uniform',
                           lower=-1.,
                           upper=1.,
                           order=self.degf)
     fParameters = [fparam for i in range(n)]
     myBasis = eq.Basis('total-order')
     fpoly = eq.Poly(fParameters,
                     myBasis,
                     method='least-squares',
                     sampling_args={
                         'mesh': 'user-defined',
                         'sample-points': X,
                         'sample-outputs': f
                     })
     fpoly.set_model()
     # Active subspace and values for g1
     g1 = self.ConFun1(X)
     g1param = eq.Parameter(distribution='uniform',
                            lower=-1.,
                            upper=1.,
                            order=self.degg1)
     g1Parameters = [g1param for i in range(n)]
     myBasis = eq.Basis('total-order')
     g1poly = eq.Poly(g1Parameters,
                      myBasis,
                      method='least-squares',
                      sampling_args={
                          'mesh': 'user-defined',
                          'sample-points': X,
                          'sample-outputs': g1
                      })
     g1poly.set_model()
     for method in ['trust-constr', 'SLSQP', 'COBYLA']:
         Opt = eq.Optimisation(method=method)
         Opt.add_objective(poly=fpoly)
         Opt.add_bounds(-np.ones(n), np.ones(n))
         Opt.add_nonlinear_ineq_con({'poly': g1poly, 'bounds': bounds})
         x0 = np.zeros(n)
         sol = Opt.optimise(x0)
         if sol['status'] == 0:
             np.testing.assert_almost_equal(sol['x'].flatten(),
                                            np.array([1.0, 1.0]),
                                            decimal=2)
Exemplo n.º 8
0
    def test_optimise_trustregion_maximise_bounds(self):
        n = 2

        def StyblinskiTang(s):
            n = s.size
            f = 0
            for i in range(n):
                f += 0.5 * (s[i]**4 - 16.0 * s[i]**2 + 5.0 * s[i])
            return f

        Opt = eq.Optimisation(method='trust-region')
        Opt.add_objective(custom={'function': StyblinskiTang}, maximise=True)
        Opt.add_bounds(-np.ones(n), np.ones(n))
        x0 = np.zeros(n)
        sol = Opt.optimise(x0)
        np.testing.assert_almost_equal(sol['x'].flatten(),
                                       np.array([0.16, 0.16]),
                                       decimal=2)
    def test_optimise_ineq_constrained_function1(self):
        n = 2
        N = 20
        bounds = [-np.inf, 2.0]
        X = np.random.uniform(-1.0, 1.0, (N, n))
        f = self.ObjFun1(X)
        fparam = eq.Parameter(distribution='uniform',
                              lower=-1.,
                              upper=1.,
                              order=self.degf)
        fParameters = [fparam for i in range(n)]
        myBasis = eq.Basis('total-order')
        fpoly = eq.Poly(fParameters,
                        myBasis,
                        method='least-squares',
                        sampling_args={
                            'mesh': 'user-defined',
                            'sample-points': X,
                            'sample-outputs': f
                        })
        fpoly.set_model()
        g1Func = lambda x: bounds[1] - self.ConFun1(x.reshape(1, -1))
        g1Grad = lambda x: -self.ConFun1_Deriv(x.flatten())
        g1Hess = lambda x: -self.ConFun1_Hess(x.flatten())

        for method in ['trust-constr', 'SLSQP']:
            Opt = eq.Optimisation(method=method)
            Opt.add_objective(poly=fpoly)
            Opt.add_nonlinear_ineq_con(
                custom={
                    'function': g1Func,
                    'jac_function': g1Grad,
                    'hess_function': g1Hess
                })
            Opt.add_linear_eq_con(np.eye(n), np.ones(n))
            x0 = np.zeros(n)
            sol = Opt.optimise(x0)
            if sol['status'] == 0:
                np.testing.assert_almost_equal(sol['x'].flatten(),
                                               np.array([1.0, 1.0]),
                                               decimal=2)
def compare_optimisation(fun, s0, bounds):
    dims = s0.size
    Opt = eq.Optimisation(method='trust-region')
    Opt.add_objective(custom={'function': fun})
    Opt.add_bounds(bounds[0], bounds[1])
    sol = Opt.optimise(s0)
    print(
        "Using the trust-region method, an optimal value of {} was found after {} function evaluations"
        .format(sol['fun'], sol['nfev']))

    bounds_2 = []
    for i in range(dims):
        bounds_2.append((bounds[0][i], bounds[1][i]))
    sol = differential_evolution(fun, bounds_2)
    print(
        "Using differential evolution, an optimal value of {} was found after {} function evaluations"
        .format(sol['fun'], sol['nfev']))

    cons = []
    for factor in range(len(bounds)):
        lower, upper = bounds_2[factor]
        l = {'type': 'ineq', 'fun': lambda x, lb=lower, i=factor: x[i] - lb}
        u = {'type': 'ineq', 'fun': lambda x, ub=upper, i=factor: ub - x[i]}
        cons.append(l)
        cons.append(u)
    sol = minimize(fun,
                   s0,
                   method='COBYLA',
                   constraints=cons,
                   tol=1.0e-8,
                   options={
                       'rhobeg': 1.0,
                       'maxiter': 100000,
                       'disp': False,
                       'catol': 1.0e-8
                   })
    print(
        "Using COBYLA, an optimal value of {} was found after {} function evaluations"
        .format(sol['fun'], sol['nfev']))