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

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

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

        self.opt = ParOpt.Optimizer(self.paropt_problem, self.options)

        return
Beispiel #2
0
def paropt_truss(truss, use_hessian=False):
    '''
    Optimize the given truss structure using ParOpt
    '''

    fname = os.path.join(prefix, 'truss_paropt%dx%d.out' % (N, M))
    options = {
        'algorithm': 'ip',
        'qn_subspace_size': 10,
        'abs_res_tol': 1e-6,
        'barrier_strategy': 'complementarity_fraction',
        'use_hvec_product': True,
        'gmres_subspace_size': 25,
        'nk_switch_tol': 1.0,
        'eisenstat_walker_gamma': 0.01,
        'eisenstat_walker_alpha': 0.0,
        'max_gmres_rtol': 1.0,
        'output_level': 1,
        'armijo_constant': 1e-5,
        'output_file': fname
    }

    if use_hessian is False:
        options['use_hvec_product'] = False

    opt = ParOpt.Optimizer(truss, options)
    opt.optimize()

    return opt
Beispiel #3
0
def plot_it_all(problem):
    """
    Plot a carpet plot with the search histories for steepest descent,
    conjugate gradient and BFGS from the same starting point.
    """

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

    for j in range(n):
        for i in range(n):
            fail, fobj, con = problem.evalObjCon([x1[i], x1[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, x1, r, levels)

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

    options = {
        'algorithm': 'tr',
        'tr_init_size': 0.05,
        'tr_min_size': 1e-6,
        'tr_max_size': 10.0,
        'tr_eta': 0.1,
        'tr_adaptive_gamma_update': True,
        'tr_max_iterations': 200
    }

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

        opt = ParOpt.Optimizer(rosen, options)
        opt.optimize()

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

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

    plt.legend()
    plt.axis([xlow, xhigh, xlow, xhigh])
    plt.show()
Beispiel #4
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)

    options = {
        'algorithm': 'ip',
        'abs_res_tol': 1e-8,
        'starting_point_strategy': 'affine_step',
        'barrier_strategy': 'monotone',
        'start_affine_multiplier_min': 0.01,
        'penalty_gamma': 1000.0,
        'qn_subspace_size': 10,
        'qn_type': 'bfgs',
        'output_file': filename}

    if use_tr:
        options = {
            'algorithm': 'tr',
            'tr_init_size': 0.05,
            'tr_min_size': 1e-6,
            'tr_max_size': 10.0,
            'tr_eta': 0.25,
            'tr_adaptive_gamma_update': True,
            'tr_max_iterations': 200,
            'penalty_gamma': 10.0,
            'qn_subspace_size': 10,
            'qn_type': 'bfgs',
            'abs_res_tol': 1e-8,
            'output_file': filename,
            'tr_output_file': os.path.splitext(filename)[0] + '.tr',
            'starting_point_strategy': 'affine_step',
            'barrier_strategy': 'monotone',
            'start_affine_multiplier_min': 0.01}

    opt = ParOpt.Optimizer(problem, options)

    # Set a new starting point
    opt.optimize()
    x, z, zw, zl, zu = opt.getOptimizedPoint()

    return
Beispiel #5
0
def paropt_truss(truss, use_hessian=False, use_tr=False, prefix='results'):
    """
    Optimize the given truss structure using ParOpt
    """

    fname = os.path.join(prefix, 'truss_paropt%dx%d.out' % (N, M))
    options = {
        'algorithm': 'ip',
        'qn_subspace_size': 10,
        'abs_res_tol': 1e-5,
        'norm_type': 'l1',
        'init_barrier_param': 10.0,
        'monotone_barrier_fraction': 0.75,
        'barrier_strategy': 'complementarity_fraction',
        'starting_point_strategy': 'least_squares_multipliers',
        'use_hvec_product': True,
        'gmres_subspace_size': 50,
        'nk_switch_tol': 1e3,
        'eisenstat_walker_gamma': 0.01,
        'eisenstat_walker_alpha': 0.0,
        'max_gmres_rtol': 1.0,
        'output_level': 1,
        'armijo_constant': 1e-5,
        'output_file': fname
    }

    if use_tr:
        options['algorithm'] = 'tr'
        options['abs_res_tol'] = 1e-8
        options['barrier_strategy'] = 'monotone'
        options['tr_max_size'] = 100.0
        options['tr_linfty_tol'] = 1e-5
        options['tr_l1_tol'] = 0.0
        options['tr_max_iterations'] = 2000
        options['tr_penalty_gamma_max'] = 1e6
        options['tr_adaptive_gamma_update'] = True
        options['tr_output_file'] = fname.split('.')[0] + '.tr'

    if use_hessian is False:
        options['use_hvec_product'] = False

    opt = ParOpt.Optimizer(truss, options)
    opt.optimize()

    return opt
Beispiel #6
0
    options = {
        'algorithm': 'tr',
        'tr_init_size': 0.05,
        'tr_min_size': 1e-6,
        'tr_max_size': 10.0,
        'tr_eta': 0.25,
        'tr_infeas_tol': 1e-6,
        'tr_l1_tol': 1e-3,
        'tr_linfty_tol': 0.0,
        'tr_adaptive_gamma_update': True,
        'tr_max_iterations': 1000,
        'penalty_gamma': 10.0,
        'qn_subspace_size': 10,
        'qn_type': 'bfgs',
        'abs_res_tol': 1e-8,
        'starting_point_strategy': 'affine_step',
        'barrier_strategy': 'mehrotra_predictor_corrector',
        'tr_steering_barrier_strategy':
            'mehrotra_predictor_corrector',
        'tr_steering_starting_point_strategy': 'affine_step',
        'use_line_search': False}

    # Set up the optimizer
    opt = ParOpt.Optimizer(problem, options)

    # Set a new starting point
    opt.optimize()
    x, z, zw, zl, zu = opt.getOptimizedPoint()

Beispiel #7
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):
                    """Evaluate the objective and constraint gradients"""
                    gobj, gcon, fail = self.ptr._masterFunc(
                        x[:], ["gobj", "gcon"])
                    g[:] = gobj[:]
                    for i in range(self.m):
                        A[i][:] = -gcon[i][:]
                    return fail

            optTime = MPI.Wtime()

            # Optimize the problem
            problem = Problem(self, n, m, xs, blx, bux)
            optimizer = _ParOpt.Optimizer(problem, self.set_options)
            optimizer.optimize()
            x, z, zw, zl, zu = optimizer.getOptimizedPoint()

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

            # Get the obective function value
            fobj = problem.fobj

            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
Beispiel #8
0
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.
    """

    # Check the problem gradients
    problem.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 = []

        # Set the trust region parameters
        filename = 'paropt.out'

        options = {
            'algorithm': 'ip',
            'abs_res_tol': 1e-8,
            'starting_point_strategy': 'affine_step',
            'barrier_strategy': 'monotone',
            'start_affine_multiplier_min': 0.01,
            'penalty_gamma': 1000.0,
            'qn_subspace_size': 10,
            'qn_type': 'bfgs'
        }

        if use_tr:
            options = {
                'algorithm': 'tr',
                'tr_init_size': 0.05,
                'tr_min_size': 1e-6,
                'tr_max_size': 10.0,
                'tr_eta': 0.25,
                'penalty_gamma': 10.0,
                'qn_subspace_size': 10,
                'qn_type': 'bfgs',
                'abs_res_tol': 1e-8,
                'output_file': filename,
                'tr_output_file': os.path.splitext(filename)[0] + '.tr',
                'starting_point_strategy': 'affine_step',
                'barrier_strategy': 'monotone',
                'start_affine_multiplier_min': 0.01
            }

        opt = ParOpt.Optimizer(problem, options)

        # Set a new starting point
        opt.optimize()
        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()
Beispiel #9
0
        'use_backtracking_alpha': True,
        'output_level': 1,
        'max_major_iters': 1000
    }

    # use trust region algorithm
    if use_tr:
        options = {
            'algorithm': 'tr',
            'qn_type': 'bfgs',
            'abs_res_tol': 1e-8,
            'output_level': 0,
            'use_backtracking_alpha': True,
            'max_major_iters': 100,
            'tr_init_size': 0.1,
            'tr_min_size': 1e-6,
            'tr_max_size': 1.0,
            'tr_eta': 0.25,
            'penalty_gamma': 1.0,
            'tr_adaptive_gamma_update': True,
            'tr_penalty_gamma_max': 1e5,
            'tr_penalty_gamma_min': 1e-5,
            'tr_max_iterations': 500,
            'use_line_search': False
        }

    polygon = Polygon(args.n)
    polygon.checkGradients()
    opt = ParOpt.Optimizer(polygon, options)
    opt.optimize()
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
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)

    options = {
        'algorithm': 'ip',
        'abs_res_tol': 1e-8,
        'starting_point_strategy': 'affine_step',
        'barrier_strategy': 'monotone',
        'start_affine_multiplier_min': 0.01,
        'penalty_gamma': 1000.0,
        'qn_subspace_size': 10,
        'qn_type': 'bfgs',
        'output_file': filename
    }

    if use_tr:
        options = {
            'algorithm': 'tr',
            'tr_init_size': 0.05,
            'tr_min_size': 1e-6,
            'tr_max_size': 10.0,
            'tr_eta': 0.25,
            'tr_adaptive_gamma_update': True,
            'tr_max_iterations': 200,
            'penalty_gamma': 10.0,
            'qn_subspace_size': 10,
            'qn_type': 'bfgs',
            'abs_res_tol': 1e-8,
            'output_file': filename,
            'tr_output_file': os.path.splitext(filename)[0] + '.tr',
            'starting_point_strategy': 'affine_step',
            'barrier_strategy': 'monotone',
            'start_affine_multiplier_min': 0.01
        }

    opt = ParOpt.Optimizer(problem, options)

    # Set a new starting point
    opt.optimize()
    x, z, zw, zl, zu = opt.getOptimizedPoint()

    return x