示例#1
0
def solve_problem(eigs, filename=None, use_stdout=False, use_tr=False):
    # Get the A matrix
    A = create_random_problem(eigs)

    # Create the other problem data
    b = np.random.uniform(size=len(eigs))
    Acon = np.random.uniform(size=len(eigs))
    bcon = np.random.uniform()

    problem = Quadratic(A, b, Acon, bcon)

    if use_tr:
        # Create the trust region problem
        max_lbfgs = 10
        tr_init_size = 0.05
        tr_min_size = 1e-6
        tr_max_size = 10.0
        tr_eta = 0.25
        tr_penalty_gamma = 10.0

        qn = ParOpt.LBFGS(problem, subspace=max_lbfgs)
        tr = ParOpt.TrustRegion(problem, qn, tr_init_size, tr_min_size,
                                tr_max_size, tr_eta, tr_penalty_gamma)
        tr.setMaxTrustRegionIterations(500)

        # Set up the optimization problem
        tr_opt = ParOpt.InteriorPoint(tr, 10, ParOpt.BFGS)
        if filename is not None and use_stdout is False:
            tr_opt.setOutputFile(filename)

        # Set the tolerances
        tr_opt.setAbsOptimalityTol(1e-8)
        tr_opt.setStartingPointStrategy(ParOpt.AFFINE_STEP)
        tr_opt.setStartAffineStepMultiplierMin(0.01)

        # Set optimization parameters
        tr_opt.setArmijoParam(1e-5)
        tr_opt.setMaxMajorIterations(5000)
        tr_opt.setBarrierPower(2.0)
        tr_opt.setBarrierFraction(0.1)

        # optimize
        tr.setOutputFile(filename + '_tr')
        tr.setPrintLevel(1)
        tr.optimize(tr_opt)
    else:
        # Set up the optimization problem
        max_lbfgs = 10
        opt = ParOpt.InteriorPoint(problem, max_lbfgs, ParOpt.BFGS)
        if filename is not None and use_stdout is False:
            opt.setOutputFile(filename)

        # Set optimization parameters
        opt.setArmijoParam(1e-5)
        opt.setMaxMajorIterations(5000)
        opt.setBarrierPower(2.0)
        opt.setBarrierFraction(0.1)
        opt.optimize()

    return
示例#2
0
def solve_problem(eigs, filename=None, data_type='orthogonal', use_tr=False):
    # Create a random orthogonal Q vector
    if data_type == 'orthogonal':
        B = np.random.uniform(size=(n, n))
        Q, s, v = np.linalg.svd(B)

        # Create a random Affine matrix
        Affine = create_random_spd(eigs)
    else:
        Q = np.random.uniform(size=(n, n))
        Affine = np.diag(1e-3 * np.ones(n))

    # Create the random right-hand-side
    b = np.random.uniform(size=n)

    # Create the constraint data
    Acon = np.random.uniform(size=n)
    bcon = 0.25 * np.sum(Acon)

    # Create the convex problem
    problem = ConvexProblem(Q, Affine, b, Acon, bcon)

    if use_tr:
        # Create the trust region problem
        max_lbfgs = 10
        tr_init_size = 0.05
        tr_min_size = 1e-6
        tr_max_size = 10.0
        tr_eta = 0.1
        tr_penalty_gamma = 10.0

        qn = ParOpt.LBFGS(problem, subspace=max_lbfgs)
        subproblem = ParOpt.QuadraticSubproblem(problem, qn)
        tr = ParOpt.TrustRegion(subproblem, tr_init_size, tr_min_size,
                                tr_max_size, tr_eta, tr_penalty_gamma)
        tr.setMaxTrustRegionIterations(500)

        infeas_tol = 1e-6
        l1_tol = 1e-5
        linfty_tol = 1e-5
        tr.setTrustRegionTolerances(infeas_tol, l1_tol, linfty_tol)

        # Set up the optimization problem
        tr_opt = ParOpt.InteriorPoint(subproblem, 10, ParOpt.BFGS)
        if filename is not None:
            tr_opt.setOutputFile(filename)
            tr.setOutputFile(os.path.splitext(filename)[0] + '.tr')

        # Set the tolerances
        tr_opt.setAbsOptimalityTol(1e-8)
        tr_opt.setStartingPointStrategy(ParOpt.AFFINE_STEP)
        tr_opt.setStartAffineStepMultiplierMin(0.01)

        # Set optimization parameters
        tr_opt.setArmijoParam(1e-5)
        tr_opt.setMaxMajorIterations(5000)
        tr_opt.setBarrierPower(2.0)
        tr_opt.setBarrierFraction(0.1)

        # optimize
        tr.setPrintLevel(1)
        tr.optimize(tr_opt)

        # Get the optimized point from the trust-region subproblem
        x = tr.getOptimizedPoint()
    else:
        # Set up the optimization problem
        max_lbfgs = 50
        opt = ParOpt.InteriorPoint(problem, max_lbfgs, ParOpt.BFGS)
        if filename is not None:
            opt.setOutputFile(filename)

        # Set optimization parameters
        opt.setArmijoParam(1e-5)
        opt.setMaxMajorIterations(5000)
        opt.setBarrierPower(2.0)
        opt.setBarrierFraction(0.1)
        opt.optimize()

        # Get the optimized point
        x, z, zw, zl, zu = opt.getOptimizedPoint()

    return x
示例#3
0
    def __call__(self,
                 optProb,
                 sens=None,
                 sensStep=None,
                 sensMode=None,
                 storeHistory=None,
                 hotStart=None,
                 storeSens=True):
        """
        This is the main routine used to solve the optimization
        problem.

        Parameters
        ----------
        optProb : Optimization or Solution class instance
            This is the complete description of the optimization problem
            to be solved by the optimizer

        sens : str or python Function.
            Specifiy method to compute sensitivities. To
            explictly use pyOptSparse gradient class to do the
            derivatives with finite differenes use \'FD\'. \'sens\'
            may also be \'CS\' which will cause pyOptSpare to compute
            the derivatives using the complex step method. Finally,
            \'sens\' may be a python function handle which is expected
            to compute the sensitivities directly. For expensive
            function evaluations and/or problems with large numbers of
            design variables this is the preferred method.

        sensStep : float
            Set the step size to use for design variables. Defaults to
            1e-6 when sens is \'FD\' and 1e-40j when sens is \'CS\'.

        sensMode : str
            Use \'pgc\' for parallel gradient computations. Only
            available with mpi4py and each objective evaluation is
            otherwise serial

        storeHistory : str
            File name of the history file into which the history of
            this optimization will be stored

        hotStart : str
            File name of the history file to "replay" for the
            optimziation.  The optimization problem used to generate
            the history file specified in \'hotStart\' must be
            **IDENTICAL** to the currently supplied \'optProb\'. By
            identical we mean, **EVERY SINGLE PARAMETER MUST BE
            IDENTICAL**. As soon as he requested evaluation point
            from ParOpt does not match the history, function and
            gradient evaluations revert back to normal evaluations.

        storeSens : bool
            Flag sepcifying if sensitivities are to be stored in hist.
            This is necessay for hot-starting only.
            """

        self.callCounter = 0
        self.storeSens = storeSens

        if len(optProb.constraints) == 0:
            # If the problem is unconstrained, add a dummy constraint.
            self.unconstrained = True
            optProb.dummyConstraint = True

        # Save the optimization problem and finalize constraint
        # jacobian, in general can only do on root proc
        self.optProb = optProb
        self.optProb.finalizeDesignVariables()
        self.optProb.finalizeConstraints()
        self._setInitialCacheValues()
        self._setSens(sens, sensStep, sensMode)
        blx, bux, xs = self._assembleContinuousVariables()
        xs = np.maximum(xs, blx)
        xs = np.minimum(xs, bux)

        # The number of design variables
        n = len(xs)

        oneSided = True

        if self.unconstrained:
            m = 0
        else:
            indices, blc, buc, fact = self.optProb.getOrdering(
                ['ne', 'le', 'ni', 'li'], oneSided=oneSided)
            m = len(indices)
            self.optProb.jacIndices = indices
            self.optProb.fact = fact
            self.optProb.offset = buc

        if self.optProb.comm.rank == 0:
            # Set history/hotstart
            self._setHistory(storeHistory, hotStart)

            class Problem(_ParOpt.Problem):
                def __init__(self, ptr, n, m, xs, blx, bux):
                    super(Problem, self).__init__(MPI.COMM_SELF, n, m)
                    self.ptr = ptr
                    self.n = n
                    self.m = m
                    self.xs = xs
                    self.blx = blx
                    self.bux = bux
                    self.fobj = 0.0
                    return

                def getVarsAndBounds(self, x, lb, ub):
                    '''Get the variable values and bounds'''
                    lb[:] = self.blx
                    ub[:] = self.bux
                    x[:] = self.xs
                    return

                def evalObjCon(self, x):
                    '''Evaluate the objective and constraint values'''
                    fobj, fcon, fail = self.ptr._masterFunc(
                        x[:], ['fobj', 'fcon'])
                    self.fobj = fobj
                    return fail, fobj, -fcon

                def evalObjConGradient(self, x, g, A):
                    gobj, gcon, fail = self.ptr._masterFunc(
                        x[:], ['gobj', 'gcon'])
                    g[:] = gobj[:]
                    for i in range(self.m):
                        A[i][:] = -gcon[i][:]
                    return fail

            # Create the ParOpt problem class
            problem = Problem(self, n, m, xs, blx, bux)

            # Get the algorithm/subspace size parameters
            algorithm = self.getOption('algorithm').lower()
            qn_subspace_size = self.getOption('qn_subspace_size')
            filename = self.getOption('filename')

            optTime = MPI.Wtime()
            if algorithm == 'ip':
                # Create the optimizer
                opt = _ParOpt.InteriorPoint(problem, qn_subspace_size,
                                            _ParOpt.BFGS)

                # Set the ParOpt options
                self._set_paropt_options(opt)

                # Optimize!
                opt.setOutputFile(filename)
                opt.optimize()
            else:
                norm_type = self.getOption('norm_type').lower()

                # Optimality tolerance
                opt_tol = self.getOption('abs_optimality_tol')

                # Trust region algorithm options
                tr_init_size = self.getOption('tr_init_size')
                tr_max_size = self.getOption('tr_max_size')
                tr_min_size = self.getOption('tr_min_size')
                tr_eta = self.getOption('tr_eta')
                tr_penalty_gamma = self.getOption('tr_penalty_gamma')
                tr_opt_abs_tol = self.getOption('tr_abs_optimality_tol')
                tr_max_iterations = self.getOption('tr_max_iterations')

                # Create the quasi-Newton Hessian approximation
                qn = _ParOpt.LBFGS(problem, subspace=qn_subspace_size)

                # Create the trust region problem
                tr = _ParOpt.TrustRegion(problem, qn, tr_init_size,
                                         tr_min_size, tr_max_size, tr_eta,
                                         tr_penalty_gamma)

                # Create the ParOpt problem
                opt = _ParOpt.InteriorPoint(tr, qn_subspace_size,
                                            _ParOpt.NO_HESSIAN_APPROX)

                # Set the ParOpt options
                self._set_paropt_options(opt)

                # Set the output file name
                opt.setOutputFile(filename)

                # Set the penalty parameter internally in the
                # code. These must be consistent between the trust
                # region object and ParOpt.
                opt.setPenaltyGamma(tr_penalty_gamma)

                # Set parameters for ParOpt in the subproblem
                opt.setMaxMajorIterations(tr_max_iterations)
                opt.setAbsOptimalityTol(tr_opt_abs_tol)

                # Don't update the quasi-Newton method
                opt.setQuasiNewton(qn)
                opt.setUseQuasiNewtonUpdates(0)

                # Check the norm type
                if norm_type == 'l1':
                    opt.setNormType(_ParOpt.L1_NORM)
                elif norm_type == 'linfty':
                    opt.setNormType(_ParOpt.INFTY_NORM)
                else:
                    opt.setNormType(_ParOpt.L2_NORM)

                # Initialize the problem
                tr.initialize()

                # Iterate
                max_iterations = self.getOption('max_iterations')
                for i in range(max_iterations):
                    opt.setInitBarrierParameter(100.0)
                    opt.resetDesignAndBounds()
                    opt.optimize()

                    # Get the optimized point
                    x, z, zw, zl, zu = opt.getOptimizedPoint()

                    # Update the trust region method
                    infeas, l1, linfty = tr.update(x, z, zw)

                    if norm_type == 'l1':
                        opt_criteria = (l1 < opt_tol)
                    else:
                        opt_criteria = (linfty < opt_tol)
                    if ((infeas < opt_tol) and opt_criteria):
                        break

            # Set the total opt time
            optTime = MPI.Wtime() - optTime

            # Get the obective function value
            fobj = problem.fobj

            # Get the optimized point
            x, z, zw, zl, zu = opt.getOptimizedPoint()

            # Create the optimization solution
            sol_inform = {}
            sol = self._createSolution(optTime, sol_inform, fobj, x[:])

            # Indicate solution finished
            self.optProb.comm.bcast(-1, root=0)
        else:  # We are not on the root process so go into waiting loop:
            self._waitLoop()
            sol = None

        # Communication solution and return
        sol = self._communicateSolution(sol)

        return sol
示例#4
0
        plt.draw()
        plt.pause(0.001)

        return


if __name__ == '__main__':
    nxelems = 3 * 48
    nyelems = 48
    Lx = 15.0
    Ly = 5.0
    problem = TopoAnalysis(nxelems, nyelems, Lx, Ly, E0=70e3, r0=3)
    problem.checkGradients()

    # Create the quasi-Newton Hessian approximation
    qn = ParOpt.LBFGS(problem, subspace=10)

    # Create the trust region problem
    tr_init_size = 0.02
    tr_min_size = 1e-6
    tr_max_size = 0.05
    tr_eta = 0.2
    tr_penalty_gamma = 10.0
    tr = ParOpt.TrustRegion(problem, qn, tr_init_size, tr_min_size,
                            tr_max_size, tr_eta, tr_penalty_gamma)

    # Set the tolerances
    infeas_tol = 1e-4
    l1_tol = 1e-3
    linfty_tol = 1e-3
    tr.setTrustRegionTolerances(infeas_tol, l1_tol, linfty_tol)
示例#5
0
        problem.addFrequencyConstraint(sigma, num_eigs, ks_weight, offset,
                                       scale, max_lanczos, tol, 0, 0, 0, 0, 0,
                                       TACS.SUM_TWO, track_eigen_iters)

    problem.addConstraints(0, funcs, [-m_fixed], [-1.0 / m_fixed])
    problem.setObjective(obj_array)

    # Initialize the problem and set the prefix
    problem.initialize()
    problem.setPrefix(args.prefix)

    if use_tr:
        # Create the quasi-Newton Hessian approximation
        qn_subspace_size = 25
        qn = ParOpt.LBFGS(problem, subspace=qn_subspace_size)

        # Trust region problem parameters
        tr_size = 0.01
        tr_max_size = 0.02
        tr_min_size = 1e-6
        eta = 0.25
        tr_penalty = 10.0

        # Create the trust region problem
        tr = ParOpt.pyTrustRegion(problem, qn, tr_size, tr_min_size,
                                  tr_max_size, eta, tr_penalty)
        # Create the ParOpt problem
        opt = ParOpt.pyParOpt(tr, qn_subspace_size, ParOpt.NO_HESSIAN_APPROX)
        # Set the penalty parameter internally in the code. These must be
        # consistent between the trust region object and ParOpt.
示例#6
0
文件: examples.py 项目: nwu63/paropt
def plot_it_all(problem, use_tr=False):
    '''
    Plot a carpet plot with the search histories for steepest descent,
    conjugate gradient and BFGS from the same starting point.
    '''

    # Set up the optimization problem
    max_lbfgs = 20
    opt = ParOpt.InteriorPoint(problem, max_lbfgs, ParOpt.BFGS)
    opt.checkGradients(1e-6)

    # Create the data for the carpet plot
    n = 150
    xlow = -4.0
    xhigh = 4.0
    x1 = np.linspace(xlow, xhigh, n)

    ylow = -3.0
    yhigh = 3.0
    x2 = np.linspace(ylow, yhigh, n)
    r = np.zeros((n, n))

    for j in range(n):
        for i in range(n):
            fail, fobj, con = problem.evalObjCon([x1[i], x2[j]])
            r[j, i] = fobj

    # Assign the contour levels
    levels = np.min(r) + np.linspace(0, 1.0, 75)**2 * (np.max(r) - np.min(r))

    # Create the plot
    fig = plt.figure(facecolor='w')
    plt.contour(x1, x2, r, levels)
    plt.plot([0.5 - yhigh, 0.5 - ylow], [yhigh, ylow], '-k')

    colours = [
        '-bo', '-ko', '-co', '-mo', '-yo', '-bx', '-kx', '-cx', '-mx', '-yx'
    ]

    for k in range(len(colours)):
        # Optimize the problem
        problem.x_hist = []

        if use_tr:
            # Create the quasi-Newton Hessian approximation
            qn = ParOpt.LBFGS(problem, subspace=2)

            # Create the trust region problem
            tr_init_size = 0.05
            tr_min_size = 1e-6
            tr_max_size = 10.0
            tr_eta = 0.25
            tr_penalty_gamma = 10.0
            tr = ParOpt.TrustRegion(problem, qn, tr_init_size, tr_min_size,
                                    tr_max_size, tr_eta, tr_penalty_gamma)

            # Set up the optimization problem
            tr_opt = ParOpt.InteriorPoint(tr, 2, ParOpt.BFGS)

            # Optimize
            tr.optimize(tr_opt)

            # Get the optimized point
            x, z, zw, zl, zu = tr_opt.getOptimizedPoint()
        else:
            opt.resetQuasiNewtonHessian()
            opt.setInitBarrierParameter(0.1)
            opt.setUseLineSearch(1)
            opt.optimize()

            # Get the optimized point and print out the data
            x, z, zw, zl, zu = opt.getOptimizedPoint()

        # Copy out the steepest descent points
        popt = np.zeros((2, len(problem.x_hist)))
        for i in range(len(problem.x_hist)):
            popt[0, i] = problem.x_hist[i][0]
            popt[1, i] = problem.x_hist[i][1]

        plt.plot(popt[0, :],
                 popt[1, :],
                 colours[k],
                 label='ParOpt %d' % (popt.shape[1]))
        plt.plot(popt[0, -1], popt[1, -1], '-ro')

        # Print the data to the screen
        g = np.zeros(2)
        A = np.zeros((1, 2))
        problem.evalObjConGradient(x, g, A)

        print('The design variables:    ', x[:])
        print('The multipliers:         ', z[:])
        print('The objective gradient:  ', g[:])
        print('The constraint gradient: ', A[:])

    ax = fig.axes[0]
    ax.set_aspect('equal', 'box')
    plt.legend()
    plt.show()
示例#7
0
def solve_problem(n,
                  ndv,
                  N,
                  rho,
                  filename=None,
                  use_quadratic_approx=True,
                  verify=False):
    problem = SpectralAggregate(n, ndv, rho=rho)

    if verify:
        x0 = np.random.uniform(size=ndv)
        problem.verify_derivatives(x0)

    options = {
        'algorithm': 'tr',
        'tr_init_size': 0.05,
        'tr_min_size': 1e-6,
        'tr_max_size': 10.0,
        'tr_eta': 0.1,
        'tr_output_file': os.path.splitext(filename)[0] + '.tr',
        'tr_penalty_gamma_max': 1e6,
        'tr_adaptive_gamma_update': True,
        'tr_infeas_tol': 1e-6,
        'tr_l1_tol': 5e-4,
        'tr_linfty_tol': 5e-4,
        'tr_max_iterations': 200,
        'output_level': 2,
        'penalty_gamma': 10.0,
        'qn_subspace_size': 10,
        'qn_type': 'bfgs',
        'abs_res_tol': 1e-8,
        'output_file': filename,
        'starting_point_strategy': 'affine_step',
        'barrier_strategy': 'monotone',
        'start_affine_multiplier_min': 0.01
    }

    if use_quadratic_approx:
        options['qn_subspace_size'] = 0
        options['qn_type'] = 'none'

    opt = ParOpt.Optimizer(problem, options)

    if use_quadratic_approx:
        # Create the BFGS approximation
        qn = ParOpt.LBFGS(problem, subspace=10)

        # Create the quadratic eigenvalue approximation object
        approx = ParOptEig.CompactEigenApprox(problem, N)

        # Set up the corresponding quadratic approximation, specifying the index
        # of the eigenvalue constraint
        eig_qn = ParOptEig.EigenQuasiNewton(qn, approx, index=0)

        # Set up the eigenvalue optimization subproblem
        subproblem = ParOptEig.EigenSubproblem(problem, eig_qn)
        subproblem.setUpdateEigenModel(problem.updateModel)

        opt.setTrustRegionSubproblem(subproblem)

    opt.optimize()

    # Get the optimized point from the trust-region subproblem
    x, z, zw, zl, zu = opt.getOptimizedPoint()

    print('max(x) = %15.6e' % (np.max(x[:])))
    print('avg(x) = %15.6e' % (np.average(x[:])))
    print('sum(x) = %15.6e' % (np.sum(x[:])))

    if verify:
        for h in [1e-6, 1e-7, 1e-8, 1e-9, 1e-10]:
            problem.checkGradients(h)
            problem.verify_derivatives(x[:], h)

    return x
示例#8
0
    def __call__(self,
                 optProb,
                 sens=None,
                 sensStep=None,
                 sensMode=None,
                 storeHistory=None,
                 hotStart=None,
                 storeSens=True):
        """
        This is the main routine used to solve the optimization
        problem.

        Parameters
        ----------
        optProb : Optimization or Solution class instance
            This is the complete description of the optimization problem
            to be solved by the optimizer

        sens : str or python Function.
            Specifiy method to compute sensitivities. To
            explictly use pyOptSparse gradient class to do the
            derivatives with finite differenes use \'FD\'. \'sens\'
            may also be \'CS\' which will cause pyOptSpare to compute
            the derivatives using the complex step method. Finally,
            \'sens\' may be a python function handle which is expected
            to compute the sensitivities directly. For expensive
            function evaluations and/or problems with large numbers of
            design variables this is the preferred method.

        sensStep : float
            Set the step size to use for design variables. Defaults to
            1e-6 when sens is \'FD\' and 1e-40j when sens is \'CS\'.

        sensMode : str
            Use \'pgc\' for parallel gradient computations. Only
            available with mpi4py and each objective evaluation is
            otherwise serial

        storeHistory : str
            File name of the history file into which the history of
            this optimization will be stored

        hotStart : str
            File name of the history file to "replay" for the
            optimziation.  The optimization problem used to generate
            the history file specified in \'hotStart\' must be
            **IDENTICAL** to the currently supplied \'optProb\'. By
            identical we mean, **EVERY SINGLE PARAMETER MUST BE
            IDENTICAL**. As soon as he requested evaluation point
            from ParOpt does not match the history, function and
            gradient evaluations revert back to normal evaluations.

        storeSens : bool
            Flag sepcifying if sensitivities are to be stored in hist.
            This is necessay for hot-starting only.
            """

        self.callCounter = 0
        self.storeSens = storeSens

        if len(optProb.constraints) == 0:
            # If the problem is unconstrained, add a dummy constraint.
            self.unconstrained = True
            optProb.dummyConstraint = True

        # Save the optimization problem and finalize constraint
        # jacobian, in general can only do on root proc
        self.optProb = optProb
        self.optProb.finalizeDesignVariables()
        self.optProb.finalizeConstraints()
        self._setInitialCacheValues()
        self._setSens(sens, sensStep, sensMode)
        blx, bux, xs = self._assembleContinuousVariables()
        xs = np.maximum(xs, blx)
        xs = np.minimum(xs, bux)

        # The number of design variables
        n = len(xs)

        oneSided = True

        if self.unconstrained:
            m = 0
        else:
            indices, blc, buc, fact = self.optProb.getOrdering(
                ["ne", "le", "ni", "li"], oneSided=oneSided)
            m = len(indices)
            self.optProb.jacIndices = indices
            self.optProb.fact = fact
            self.optProb.offset = buc

        if self.optProb.comm.rank == 0:
            # Set history/hotstart
            self._setHistory(storeHistory, hotStart)

            class Problem(_ParOpt.Problem):
                def __init__(self, ptr, n, m, xs, blx, bux):
                    super(Problem, self).__init__(MPI.COMM_SELF, n, m)
                    self.ptr = ptr
                    self.n = n
                    self.m = m
                    self.xs = xs
                    self.blx = blx
                    self.bux = bux
                    self.fobj = 0.0
                    return

                def getVarsAndBounds(self, x, lb, ub):
                    """Get the variable values and bounds"""
                    # Find the average distance between lower and upper bound
                    bound_sum = 0.0
                    for i in range(len(x)):
                        if self.blx[i] <= -1e20 or self.bux[i] >= 1e20:
                            bound_sum += 1.0
                        else:
                            bound_sum += self.bux[i] - self.blx[i]
                    bound_sum = bound_sum / len(x)

                    for i in range(len(x)):
                        x[i] = self.xs[i]
                        lb[i] = self.blx[i]
                        ub[i] = self.bux[i]
                        if self.xs[i] <= self.blx[i]:
                            x[i] = self.blx[i] + 0.5 * np.min(
                                (bound_sum, self.bux[i] - self.blx[i]))
                        elif self.xs[i] >= self.bux[i]:
                            x[i] = self.bux[i] - 0.5 * np.min(
                                (bound_sum, self.bux[i] - self.blx[i]))

                    return

                def evalObjCon(self, x):
                    """Evaluate the objective and constraint values"""
                    fobj, fcon, fail = self.ptr._masterFunc(
                        x[:], ["fobj", "fcon"])
                    self.fobj = fobj
                    return fail, fobj, -fcon

                def evalObjConGradient(self, x, g, A):
                    gobj, gcon, fail = self.ptr._masterFunc(
                        x[:], ["gobj", "gcon"])
                    g[:] = gobj[:]
                    for i in range(self.m):
                        A[i][:] = -gcon[i][:]
                    return fail

            # Create the ParOpt problem class
            problem = Problem(self, n, m, xs, blx, bux)

            # Get the algorithm/subspace size parameters
            algorithm = self.getOption("algorithm").lower()
            qn_subspace_size = self.getOption("qn_subspace_size")
            filename = self.getOption("filename")

            optTime = MPI.Wtime()
            if algorithm == "ip":
                # Create the optimizer
                opt = _ParOpt.InteriorPoint(problem, qn_subspace_size,
                                            _ParOpt.BFGS)

                # Set the ParOpt options
                self._set_paropt_options(opt)

                # Optimize!
                opt.setOutputFile(filename)
                opt.optimize()
            else:
                # Optimality tolerance
                opt_tol = self.getOption("abs_optimality_tol")

                # Trust region algorithm options
                tr_init_size = self.getOption("tr_init_size")
                tr_max_size = self.getOption("tr_max_size")
                tr_min_size = self.getOption("tr_min_size")
                tr_eta = self.getOption("tr_eta")
                tr_penalty_gamma = self.getOption("tr_penalty_gamma")
                tr_opt_abs_tol = self.getOption("tr_abs_optimality_tol")
                tr_max_iterations = self.getOption("tr_max_iterations")

                # Create the quasi-Newton Hessian approximation
                qn = _ParOpt.LBFGS(problem, subspace=qn_subspace_size)
                subproblem = _ParOpt.QuadraticSubproblem(problem, qn)

                # Create the trust region problem
                tr = _ParOpt.TrustRegion(subproblem, tr_init_size, tr_min_size,
                                         tr_max_size, tr_eta, tr_penalty_gamma)

                # Create the ParOpt problem
                opt = _ParOpt.InteriorPoint(subproblem, qn_subspace_size,
                                            _ParOpt.NO_HESSIAN_APPROX)

                # Set the ParOpt options
                self._set_paropt_options(opt)

                # Set the output file name
                opt.setOutputFile(filename)
                tr.setOutputFile(os.path.splitext(filename)[0] + ".tr")

                # Use the adaptive penalty update scheme by default
                tr.setAdaptiveGammaUpdate(1)
                tr.setPenaltyGammaMax(1e3)

                # Set parameters for the trust-region algorithm
                tr.setMaxTrustRegionIterations(tr_max_iterations)

                # Set the tolerance
                tr.setTrustRegionTolerances(opt_tol, opt_tol, opt_tol)

                # Set optimality tolerance for the trust region problem
                opt.setAbsOptimalityTol(tr_opt_abs_tol)

                # Optimize the problem
                tr.optimize(opt)

                # Get the optimized point
                x, z, zw, zl, zu = opt.getOptimizedPoint()

            # Set the total opt time
            optTime = MPI.Wtime() - optTime

            # Get the obective function value
            fobj = problem.fobj

            # Get the optimized point
            x, z, zw, zl, zu = opt.getOptimizedPoint()

            if self.storeHistory:
                self.metadata["endTime"] = datetime.datetime.now().strftime(
                    "%Y-%m-%d %H:%M:%S")
                self.metadata["optTime"] = optTime
                self.hist.writeData("metadata", self.metadata)
                self.hist.close()

            # Create the optimization solution. Note that the signs on the multipliers
            # are switch since ParOpt uses a formulation with c(x) >= 0, while pyOpt
            # uses g(x) = -c(x) <= 0. Therefore the multipliers are reversed.
            sol_inform = {}

            # If number of constraints is zero, ParOpt returns z as None.
            # Thus if there is no constraints, should pass an empty list
            # to multipliers instead of z.
            if z is not None:
                sol = self._createSolution(optTime,
                                           sol_inform,
                                           fobj,
                                           x[:],
                                           multipliers=-z)
            else:
                sol = self._createSolution(optTime,
                                           sol_inform,
                                           fobj,
                                           x[:],
                                           multipliers=[])

            # Indicate solution finished
            self.optProb.comm.bcast(-1, root=0)
        else:  # We are not on the root process so go into waiting loop:
            self._waitLoop()
            sol = None

        # Communication solution and return
        sol = self._communicateSolution(sol)

        return sol
示例#9
0
    def _setup_driver(self, problem):
        """
        Prepare the driver for execution.

        This is the final thing to run during setup.

        Parameters
        ----------
        paropt_problem : <Problem>
            Pointer
        """
        # TODO:
        # - logic for different opt algorithms
        # - treat equality constraints

        super(ParOptDriver, self)._setup_driver(problem)
        opt_type = self.options['optimizer']

        # Raise error if multiple objectives are provided
        if len(self._objs) > 1:
            msg = 'ParOpt currently does not support multiple objectives.'
            raise RuntimeError(msg.format(self.__class__.__name__))

        # Set the limited-memory options
        max_qn_subspace = self.options['max_qn_subspace']
        if self.options['qn_type'] == 'BFGS':
            qn_type = ParOpt.BFGS
        elif self.options['qn_type'] == 'SR1':
            qn_type = ParOpt.SR1
        elif self.options['qn_type'] == 'No Hessian approx':
            qn_type = ParOpt.NO_HESSIAN_APPROX
        else:
            qn_type = ParOpt.BFGS

        # Create the ParOptProblem from the OpenMDAO problem
        self.paropt_problem = ParOptProblem(problem)

        # Create the problem
        if opt_type == 'Trust Region':
            # For the trust region method, you have to use a Hessian
            # approximation
            if qn_type == ParOpt.NO_HESSIAN_APPROX:
                qn = ParOpt.BFGS
            if max_qn_subspace < 1:
                max_qn_subspace = 1

            # Create the quasi-Newton method
            qn = ParOpt.LBFGS(self.paropt_problem, subspace=max_qn_subspace)

            # Retrieve the options for the trust region problem
            tr_min_size = self.options['tr_min_size']
            tr_max_size = self.options['tr_max_size']
            tr_eta = self.options['tr_eta']
            tr_penalty_gamma = self.options['tr_penalty_gamma']
            tr_init_size = self.options['tr_init_size']

            # Create the trust region sub-problem
            tr_init_size = min(tr_max_size, max(tr_init_size, tr_min_size))
            tr = ParOpt.TrustRegion(self.paropt_problem, qn, tr_init_size,
                                    tr_min_size, tr_max_size, tr_eta,
                                    tr_penalty_gamma)

            # Set the penalty parameter
            tr.setPenaltyGammaMax(self.options['tr_penalty_gamma_max'])
            tr.setMaxTrustRegionIterations(self.options['tr_max_iterations'])

            # Trust region convergence tolerances
            infeas_tol = self.options['tr_infeas_tol']
            l1_tol = self.options['tr_l1_tol']
            linfty_tol = self.options['tr_linfty_tol']
            tr.setTrustRegionTolerances(infeas_tol, l1_tol, linfty_tol)

            # Trust region output file name
            if self.options['tr_output_file'] is not None:
                tr.setOutputFile(self.options['tr_output_file'])
                tr.setOutputFrequency(self.options['tr_write_output_freq'])

            # Create the interior-point optimizer for the trust region sub-problem
            opt = ParOpt.InteriorPoint(tr, 0, ParOpt.NO_HESSIAN_APPROX)
            self.tr = tr
        else:
            # Create the ParOpt object with the interior point method
            opt = ParOpt.InteriorPoint(self.paropt_problem, max_qn_subspace,
                                       qn_type)

        # Apply the options to ParOpt
        # Currently incomplete
        opt.setAbsOptimalityTol(self.options['tol'])
        opt.setMaxMajorIterations(self.options['maxiter'])
        if self.options['dh']:
            opt.checkGradients(self.options['dh'])

        # Set barrier strategy
        if self.options['barrier_strategy']:
            if self.options['barrier_strategy'] == 'Monotone':
                barrier_strategy = ParOpt.MONOTONE
            elif self.options['barrier_strategy'] == 'Mehrotra':
                barrier_strategy = ParOpt.MEHROTRA
            elif self.options[
                    'barrier_strategy'] == 'Complementarity fraction':
                barrier_strategy = ParOpt.COMPLEMENTARITY_FRACTION
            opt.setBarrierStrategy(barrier_strategy)

        # Set starting point strategy
        if self.options['start_strategy']:
            if self.options['barrier_strategy'] == 'None':
                start_strategy = ParOpt.NO_START_STRATEGY
            elif self.options[
                    'barrier_strategy'] == 'Least squares multipliers':
                start_strategy = ParOpt.LEAST_SQUARES_MULTIPLIERS
            elif self.options['barrier_strategy'] == 'Affine step':
                start_strategy = ParOpt.AFFINE_STEP
            opt.setStartingPointStrategy(start_strategy)

        # Set norm type
        if self.options['norm_type']:
            if self.options['norm_type'] == 'Infinity':
                norm_type = ParOpt.INFTY_NORM
            elif self.options['norm_type'] == 'L1':
                norm_type = ParOpt.L1_NORM
            elif self.options['norm_type'] == 'L2':
                norm_type = ParOpt.L2_NORM
            opt.setBarrierStrategy(norm_type)

        # Set BFGS update strategy
        if self.options['bfgs_update_type']:
            if self.options['bfgs_update_type'] == 'Skip negative':
                bfgs_update_type = ParOpt.SKIP_NEGATIVE_CURVATURE
            elif self.options['bfgs_update_type'] == 'Damped':
                bfgs_update_type = ParOpt.DAMPED_UPDATE
            opt.setBFGSUpdateType(bfgs_update_type)

        if self.options['penalty_gamma']:
            opt.setPenaltyGamma(self.options['penalty_gamma'])

        if self.options['barrier_fraction']:
            opt.setBarrierFraction(self.options['barrier_fraction'])

        if self.options['barrier_power']:
            opt.setBarrierPower(self.options['barrier_power'])

        if self.options['hessian_reset_freq']:
            opt.setHessianResetFrequency(self.options['hessian_reset_freq'])

        if self.options['qn_diag_factor']:
            opt.setQNDiagonalFactor(self.options['qn_diag_factor'])

        if self.options['use_sequential_linear']:
            opt.setSequentialLinearMethod(
                self.options['use_sequential_linear'])

        if self.options['affine_step_multiplier_min']:
            opt.setStartAffineStepMultiplierMin(
                self.options['affine_step_multiplier_min'])

        if self.options['init_barrier_parameter']:
            opt.setInitBarrierParameter(self.options['init_barrier_parameter'])

        if self.options['relative_barrier']:
            opt.setRelativeBarrier(self.options['relative_barrier'])

        if self.options['set_qn']:
            opt.setQuasiNewton(self.options['set_qn'])

        if self.options['qn_updates']:
            opt.setUseQuasiNewtonUpdates(self.options['qn_updates'])

        if self.options['use_line_search']:
            opt.setUseLineSearch(self.options['use_line_search'])

        if self.options['max_ls_iters']:
            opt.setMaxLineSearchIters(self.options['max_ls_iters'])

        if self.options['backtrack_ls']:
            opt.setBacktrackingLineSearch(self.options['backtrack_ls'])

        if self.options['armijo_param']:
            opt.setArmijoParam(self.options['armijo_param'])

        if self.options['penalty_descent_frac']:
            opt.setPenaltyDescentFraction(self.options['penalty_descent_frac'])

        if self.options['min_penalty_param']:
            opt.setMinPenaltyParameter(self.options['min_penalty_param'])

        if self.options['use_hvec_prod']:
            opt.setUseHvecProduct(self.options['use_hvec_prod'])

        if self.options['use_diag_hessian']:
            opt.setUseDiagHessian(self.options['use_diag_hessian'])

        if self.options['use_qn_gmres_precon']:
            opt.setUseQNGMRESPreCon(self.options['use_qn_gmres_precon'])

        if self.options['set_nk_switch_tol']:
            opt.setNKSwitchTolerance(self.options['set_nk_switch_tol'])

        if self.options['eisenstat_walker_param']:
            opt.setEisenstatWalkerParameters(
                self.options['eisenstat_walker_param'][0],
                self.options['eisenstat_walker_param'][1])

        if self.options['gmres_tol']:
            opt.setGMRESTolerances(self.options['gmres_tol'][0],
                                   self.options['gmres_tol'][1])

        if self.options['gmres_subspace_size']:
            opt.setGMRESSubspaceSize(self.options['gmres_subspace_size'])

        if self.options['output_freq']:
            opt.setOutputFrequency(self.options['output_freq'])

        if self.options['output_file']:
            opt.setOutputFile(self.options['output_file'])

        if self.options['major_iter_step_check']:
            opt.setMajorIterStepCheck(self.options['major_iter_step_check'])

        if self.options['output_level']:
            opt.setOutputLevel(self.options['output_level'])

        if self.options['grad_check_freq']:
            opt.setGradCheckFrequency(self.options['grad_check_freq'])

        # This opt object will be used again when 'run' is executed
        self.opt = opt

        return