Beispiel #1
0
def main():
    model = create_model()
    nlp = PyomoNLP(model)

    # initial guesses
    x = nlp.init_primals()
    lam = nlp.init_duals()

    nlp.set_primals(x)
    nlp.set_duals(lam)

    # NLP function evaluations
    f = nlp.evaluate_objective()
    print("Objective Function\n", f)
    df = nlp.evaluate_grad_objective()
    print("Gradient of Objective Function:\n", df)
    c = nlp.evaluate_constraints()
    print("Constraint Values:\n", c)
    c_eq = nlp.evaluate_eq_constraints()
    print("Equality Constraint Values:\n", c_eq)
    c_ineq = nlp.evaluate_ineq_constraints()
    print("Inequality Constraint Values:\n", c_ineq)
    jac = nlp.evaluate_jacobian()
    print("Jacobian of Constraints:\n", jac.toarray())
    jac_eq = nlp.evaluate_jacobian_eq()
    print("Jacobian of Equality Constraints:\n", jac_eq.toarray())
    jac_ineq = nlp.evaluate_jacobian_ineq()
    print("Jacobian of Inequality Constraints:\n", jac_ineq.toarray())
    hess_lag = nlp.evaluate_hessian_lag()
    print("Hessian of Lagrangian\n", hess_lag.toarray())
def get_condition_number(model):
    if isinstance(model, pyo.Block):
        if len(list(model.component_data_objects(pyo.Objective,
                                                 active=True))) == 0:
            model._obj = pyo.Objective(expr=0.0)
        nlp = PyomoNLP(model)
        jacobian = nlp.evaluate_jacobian()
        model.del_component(model._obj)
    elif isinstance(model, sps.coo_matrix):
        jacobian = model
    else:
        raise ValueError()
    if jacobian.shape == (1, 1):
        return 1.0
    else:
        # HACK: Use dense linear algebra for minimum singular value
        #jjt = jacobian.dot(jacobian.transpose())
        #jjt_dense = jjt.toarray()
        #sv, _ = np.linalg.eig(jjt_dense)
        _, smin, _ = sps.linalg.svds(jacobian,
                                     k=24,
                                     which="SM",
                                     solver="lobpcg")
        _, smax, _ = sps.linalg.svds(jacobian,
                                     k=1,
                                     which="LM",
                                     solver="lobpcg")
        cond = smax[0] / smin[0]
        return cond
def test_have_pynumero(model):
    assert PyomoNLP is not None
    nlp = PyomoNLP(model)
    f = nlp.evaluate_objective()
    assert f == pytest.approx(-504.0)

    jac = nlp.evaluate_jacobian().toarray()
    assert jac[0][0] == pytest.approx(0)
    assert jac[0][1] == pytest.approx(8)
    assert jac[0][2] == pytest.approx(1)
    assert jac[1][0] == pytest.approx(8)
    assert jac[1][1] == pytest.approx(0)
    assert jac[1][2] == pytest.approx(1)
Beispiel #4
0
def main(show_plot=True):
    if show_plot:
        import matplotlib.pylab as plt

    instance = create_problem(0.0, 10.0)
    # Discretize model using Orthogonal Collocation
    discretizer = pyo.TransformationFactory('dae.collocation')
    discretizer.apply_to(instance, nfe=100, ncp=3, scheme='LAGRANGE-RADAU')
    discretizer.reduce_collocation_points(instance,
                                          var=instance.u,
                                          ncp=1,
                                          contset=instance.t)

    # Interface pyomo model with nlp
    nlp = PyomoNLP(instance)
    x = nlp.create_new_vector('primals')
    x.fill(1.0)
    nlp.set_primals(x)

    lam = nlp.create_new_vector('duals')
    lam.fill(1.0)
    nlp.set_duals(lam)

    # Evaluate jacobian
    jac = nlp.evaluate_jacobian()
    if show_plot:
        plt.spy(jac)
        plt.title('Jacobian of the constraints\n')
        plt.show()

    # Evaluate hessian of the lagrangian
    hess_lag = nlp.evaluate_hessian_lag()
    if show_plot:
        plt.spy(hess_lag)
        plt.title('Hessian of the Lagrangian function\n')
        plt.show()

    # Build KKT matrix
    kkt = BlockMatrix(2, 2)
    kkt.set_block(0, 0, hess_lag)
    kkt.set_block(1, 0, jac)
    kkt.set_block(0, 1, jac.transpose())
    if show_plot:
        plt.spy(kkt.tocoo())
        plt.title('KKT system\n')
        plt.show()
Beispiel #5
0
    def test_compare_evaluations(self):
        A1 = 5
        A2 = 10
        c1 = 3
        c2 = 4
        N = 6
        dt = 1

        m = create_pyomo_model(A1, A2, c1, c2, N, dt)
        solver = pyo.SolverFactory('ipopt')
        solver.options['linear_solver'] = 'mumps'
        status = solver.solve(m, tee=False)
        m_nlp = PyomoNLP(m)

        mex = create_pyomo_external_grey_box_model(A1, A2, c1, c2, N, dt)
        # mex_nlp = PyomoGreyBoxNLP(mex)
        mex_nlp = PyomoNLPWithGreyBoxBlocks(mex)

        # get the variable and constraint order and create the maps
        # reliable order independent comparisons
        m_x_order = m_nlp.primals_names()
        m_c_order = m_nlp.constraint_names()
        mex_x_order = mex_nlp.primals_names()
        mex_c_order = mex_nlp.constraint_names()

        x1list = [
            'h1[0]', 'h1[1]', 'h1[2]', 'h1[3]', 'h1[4]', 'h1[5]', 'h2[0]',
            'h2[1]', 'h2[2]', 'h2[3]', 'h2[4]', 'h2[5]', 'F1[1]', 'F1[2]',
            'F1[3]', 'F1[4]', 'F1[5]', 'F2[1]', 'F2[2]', 'F2[3]', 'F2[4]',
            'F2[5]', 'F12[0]', 'F12[1]', 'F12[2]', 'F12[3]', 'F12[4]',
            'F12[5]', 'Fo[0]', 'Fo[1]', 'Fo[2]', 'Fo[3]', 'Fo[4]', 'Fo[5]'
        ]
        x2list = [
            'egb.inputs[h1_0]', 'egb.inputs[h1_1]', 'egb.inputs[h1_2]',
            'egb.inputs[h1_3]', 'egb.inputs[h1_4]', 'egb.inputs[h1_5]',
            'egb.inputs[h2_0]', 'egb.inputs[h2_1]', 'egb.inputs[h2_2]',
            'egb.inputs[h2_3]', 'egb.inputs[h2_4]', 'egb.inputs[h2_5]',
            'egb.inputs[F1_1]', 'egb.inputs[F1_2]', 'egb.inputs[F1_3]',
            'egb.inputs[F1_4]', 'egb.inputs[F1_5]', 'egb.inputs[F2_1]',
            'egb.inputs[F2_2]', 'egb.inputs[F2_3]', 'egb.inputs[F2_4]',
            'egb.inputs[F2_5]', 'egb.outputs[F12_0]', 'egb.outputs[F12_1]',
            'egb.outputs[F12_2]', 'egb.outputs[F12_3]', 'egb.outputs[F12_4]',
            'egb.outputs[F12_5]', 'egb.outputs[Fo_0]', 'egb.outputs[Fo_1]',
            'egb.outputs[Fo_2]', 'egb.outputs[Fo_3]', 'egb.outputs[Fo_4]',
            'egb.outputs[Fo_5]'
        ]
        x1_x2_map = dict(zip(x1list, x2list))
        x1idx_x2idx_map = {
            i: mex_x_order.index(x1_x2_map[m_x_order[i]])
            for i in range(len(m_x_order))
        }

        c1list = [
            'h1bal[1]', 'h1bal[2]', 'h1bal[3]', 'h1bal[4]', 'h1bal[5]',
            'h2bal[1]', 'h2bal[2]', 'h2bal[3]', 'h2bal[4]', 'h2bal[5]',
            'F12con[0]', 'F12con[1]', 'F12con[2]', 'F12con[3]', 'F12con[4]',
            'F12con[5]', 'Focon[0]', 'Focon[1]', 'Focon[2]', 'Focon[3]',
            'Focon[4]', 'Focon[5]', 'min_inflow[1]', 'min_inflow[2]',
            'min_inflow[3]', 'min_inflow[4]', 'min_inflow[5]',
            'max_outflow[0]', 'max_outflow[1]', 'max_outflow[2]',
            'max_outflow[3]', 'max_outflow[4]', 'max_outflow[5]', 'h10', 'h20'
        ]
        c2list = [
            'egb.h1bal_1', 'egb.h1bal_2', 'egb.h1bal_3', 'egb.h1bal_4',
            'egb.h1bal_5', 'egb.h2bal_1', 'egb.h2bal_2', 'egb.h2bal_3',
            'egb.h2bal_4', 'egb.h2bal_5', 'egb.output_constraints[F12_0]',
            'egb.output_constraints[F12_1]', 'egb.output_constraints[F12_2]',
            'egb.output_constraints[F12_3]', 'egb.output_constraints[F12_4]',
            'egb.output_constraints[F12_5]', 'egb.output_constraints[Fo_0]',
            'egb.output_constraints[Fo_1]', 'egb.output_constraints[Fo_2]',
            'egb.output_constraints[Fo_3]', 'egb.output_constraints[Fo_4]',
            'egb.output_constraints[Fo_5]', 'min_inflow[1]', 'min_inflow[2]',
            'min_inflow[3]', 'min_inflow[4]', 'min_inflow[5]',
            'max_outflow[0]', 'max_outflow[1]', 'max_outflow[2]',
            'max_outflow[3]', 'max_outflow[4]', 'max_outflow[5]', 'h10', 'h20'
        ]
        c1_c2_map = dict(zip(c1list, c2list))
        c1idx_c2idx_map = {
            i: mex_c_order.index(c1_c2_map[m_c_order[i]])
            for i in range(len(m_c_order))
        }

        # get the primals from m and put them in the correct order for mex
        m_x = m_nlp.get_primals()
        mex_x = np.zeros(len(m_x))
        for i in range(len(m_x)):
            mex_x[x1idx_x2idx_map[i]] = m_x[i]

        # get the duals from m and put them in the correct order for mex
        m_lam = m_nlp.get_duals()
        mex_lam = np.zeros(len(m_lam))
        for i in range(len(m_x)):
            mex_lam[c1idx_c2idx_map[i]] = m_lam[i]

        mex_nlp.set_primals(mex_x)
        mex_nlp.set_duals(mex_lam)

        m_obj = m_nlp.evaluate_objective()
        mex_obj = mex_nlp.evaluate_objective()
        self.assertAlmostEqual(m_obj, mex_obj, places=4)

        m_gobj = m_nlp.evaluate_grad_objective()
        mex_gobj = mex_nlp.evaluate_grad_objective()
        check_vectors_specific_order(self, m_gobj, m_x_order, mex_gobj,
                                     mex_x_order, x1_x2_map)

        m_c = m_nlp.evaluate_constraints()
        mex_c = mex_nlp.evaluate_constraints()
        check_vectors_specific_order(self, m_c, m_c_order, mex_c, mex_c_order,
                                     c1_c2_map)

        m_j = m_nlp.evaluate_jacobian()
        mex_j = mex_nlp.evaluate_jacobian().todense()
        check_sparse_matrix_specific_order(self, m_j, m_c_order, m_x_order,
                                           mex_j, mex_c_order, mex_x_order,
                                           c1_c2_map, x1_x2_map)

        m_h = m_nlp.evaluate_hessian_lag()
        mex_h = mex_nlp.evaluate_hessian_lag()
        check_sparse_matrix_specific_order(self, m_h, m_x_order, m_x_order,
                                           mex_h, mex_x_order, mex_x_order,
                                           x1_x2_map, x1_x2_map)

        mex_h = 0 * mex_h
        mex_nlp.evaluate_hessian_lag(out=mex_h)
        check_sparse_matrix_specific_order(self, m_h, m_x_order, m_x_order,
                                           mex_h, mex_x_order, mex_x_order,
                                           x1_x2_map, x1_x2_map)
Beispiel #6
0
def constraint_autoscale_large_jac(m,
                                   ignore_constraint_scaling=False,
                                   ignore_variable_scaling=False,
                                   max_grad=100,
                                   min_scale=1e-6,
                                   no_scale=False):
    """Automatically scale constraints based on the Jacobian.  This function
    immitates Ipopt's default constraint scaling.  This scales constraints down
    to avoid extremely large values in the Jacobian

    Args:
        m: model to scale
        ignore_constraint_scaling: ignore existing constraint scaling
        ignore_variable_scaling: ignore existing variable scaling
        max_grad: maximum value in Jacobian after scaling, subject to minimum
            scaling factor restriction.
        min_scale: minimum scaling factor allowed, keeps constraints from being
            scaled too much.
        no_scale: just calculate the Jacobian and scaled Jacobian, don't scale
            anything
    """
    # Pynumero requires an objective, but I don't, so let's see if we have one
    n_obj = 0
    for c in m.component_data_objects(pyo.Objective, active=True):
        n_obj += 1
    # Add an objective if there isn't one
    if n_obj == 0:
        dummy_objective_name = unique_component_name(m, "objective")
        setattr(m, dummy_objective_name, pyo.Objective(expr=0))
    # Create NLP and calculate the objective
    nlp = PyomoNLP(m)
    jac = nlp.evaluate_jacobian().tocsr()
    # Get lists of varibles and constraints to translate Jacobian indexes
    clist = nlp.get_pyomo_constraints()
    vlist = nlp.get_pyomo_variables()
    # Create a scaled Jacobian to account for variable scaling, for now ignore
    # constraint scaling
    jac_scaled = jac.copy()
    for i in range(len(clist)):
        for j in jac_scaled[i].indices:
            v = vlist[j]
            if ignore_variable_scaling:
                sv = 1
            else:
                sv = get_scaling_factor(v, default=1)
            jac_scaled[i, j] = jac_scaled[i, j] / sv
    # calculate constraint scale factors
    for i in range(len(clist)):
        c = clist[i]
        sc = get_scaling_factor(c, default=1)
        if not no_scale:
            if (ignore_constraint_scaling or get_scaling_factor(c) is None):
                row = jac_scaled[i]
                for d in row.indices:
                    row[0, d] = abs(row[0, d])
                mg = row.max()
                if mg > max_grad:
                    sc = max(min_scale, max_grad / mg)
                set_scaling_factor(c, sc)
        for j in jac_scaled[i].indices:
            # update the scaled jacobian
            jac_scaled[i, j] = jac_scaled[i, j] * sc
    # delete dummy objective
    if n_obj == 0:
        delattr(m, dummy_objective_name)
    return jac, jac_scaled, nlp
Beispiel #7
0
    return sol[nlp.n_primals():nlp.n_primals() + nlp.n_constraints()]


#################################################################
m = create_model(4.5, 1.0)
opt = pyo.SolverFactory('ipopt')
results = opt.solve(m, tee=True)

#################################################################
nlp = PyomoNLP(m)
x = nlp.init_primals()
y = compute_init_lam(nlp, x=x)
nlp.set_primals(x)
nlp.set_duals(y)

J = nlp.evaluate_jacobian()
H = nlp.evaluate_hessian_lag()

M = BlockSymMatrix(2)
M[0, 0] = H
M[1, 0] = J

Np = BlockMatrix(2, 1)
Np[0, 0] = nlp.extract_submatrix_hessian_lag(
    pyomo_variables_rows=nlp.get_pyomo_variables(),
    pyomo_variables_cols=[m.eta1, m.eta2])
Np[1, 0] = nlp.extract_submatrix_jacobian(
    pyomo_variables=[m.eta1, m.eta2],
    pyomo_constraints=nlp.get_pyomo_constraints())

ds = spsolve(M.tocsc(), Np.tocsc())
Beispiel #8
0
class PyomoExternalCyIpoptProblem(CyIpoptProblemInterface):
    def __init__(self, pyomo_model, ex_input_output_model, inputs, outputs,
                 outputs_eqn_scaling=None):
        """
        Create an instance of this class to pass as a problem to CyIpopt.

        Parameters
        ----------
        pyomo_model : ConcreteModel
           The ConcreteModel representing the Pyomo part of the problem. This
           model must contain Pyomo variables for the inputs and the outputs.

        ex_input_output_model : ExternalInputOutputModel
           An instance of a derived class (from ExternalInputOutputModel) that provides
           the methods to compute the outputs and the derivatives.

        inputs : list of Pyomo variables (_VarData)
           The Pyomo model needs to have variables to represent the inputs to the 
           external model. This is the list of those input variables in the order 
           that corresponds to the input_values vector provided in the set_inputs call.

        outputs : list of Pyomo variables (_VarData)
          The Pyomo model needs to have variables to represent the outputs from the
          external model. This is the list of those output variables in the order
          that corresponds to the numpy array returned from the evaluate_outputs call.

        outputs_eqn_scaling : list or array-like or None
          This sets the value of scaling parameters for the additional
          output equations that are generated. No scaling is done if this
          is set to None.
        """
        self._pyomo_model = pyomo_model
        self._ex_io_model = ex_input_output_model

        # verify that the inputs and outputs were passed correctly
        self._inputs = [v for v in inputs]
        for v in self._inputs:
            if not isinstance(v, _VarData):
                raise RuntimeError('Argument inputs passed to PyomoExternalCyIpoptProblem must be'
                                   ' a list of VarData objects. Note: if you have an indexed variable, pass'
                                   ' each index as a separate entry in the list (e.g., inputs=[m.x[1], m.x[2]]).')

        self._outputs = [v for v in outputs]
        for v in self._outputs:
            if not isinstance(v, _VarData):
                raise RuntimeError('Argument outputs passed to PyomoExternalCyIpoptProblem must be'
                                   ' a list of VarData objects. Note: if you have an indexed variable, pass'
                                   ' each index as a separate entry in the list (e.g., inputs=[m.x[1], m.x[2]]).')

        # we need to add a dummy variable and constraint to the pyomo_nlp
        # to make sure it does not remove variables that do not
        # appear in the pyomo part of the model - also ensure unique name in case model
        # is used in more than one instance of this class
        # ToDo: Improve this by convincing Pyomo not to remove the inputs and outputs
        dummy_var_name = unique_component_name(self._pyomo_model, '_dummy_variable_CyIpoptPyomoExNLP')
        dummy_var = Var()
        setattr(self._pyomo_model, dummy_var_name, dummy_var)
        dummy_con_name = unique_component_name(self._pyomo_model, '_dummy_constraint_CyIpoptPyomoExNLP')
        dummy_con = Constraint(
            expr = getattr(self._pyomo_model, dummy_var_name) == \
               sum(v for v in self._inputs) + sum(v for v in self._outputs)
            )
        setattr(self._pyomo_model, dummy_con_name, dummy_con)

        # initialize the dummy var to the right hand side
        dummy_var_value = 0
        for v in self._inputs:
            if v.value is not None:
                dummy_var_value += value(v)
        for v in self._outputs:
            if v.value is not None:
                dummy_var_value += value(v)
        dummy_var.value = dummy_var_value

        # make an nlp interface from the pyomo model
        self._pyomo_nlp = PyomoNLP(self._pyomo_model)
        
        # create initial value vectors for primals and duals
        init_primals = self._pyomo_nlp.init_primals()
        init_duals_pyomo = self._pyomo_nlp.init_duals()
        if np.any(np.isnan(init_duals_pyomo)):
            # set initial values to 1 for any entries that we don't get
            # (typically, all are set, or none are set)
            init_duals_pyomo[np.isnan(init_duals_pyomo)] = 1.0
        init_duals_ex = np.ones(len(self._outputs), dtype=np.float64)
        init_duals = BlockVector(2)
        init_duals.set_block(0, init_duals_pyomo)
        init_duals.set_block(1, init_duals_ex)

        # build the map from inputs and outputs to the full x vector
        self._input_columns = self._pyomo_nlp.get_primal_indices(self._inputs)
        #self._input_x_mask = np.zeros(self._pyomo_nlp.n_primals(), dtype=np.float64)
        #self._input_x_mask[self._input_columns] = 1.0
        self._output_columns = self._pyomo_nlp.get_primal_indices(self._outputs)
        #self._output_x_mask = np.zeros(self._pyomo_nlp.n_primals(), dtype=np.float64)
        #self._output_x_mask[self._output_columns] = 1.0
        
        # create caches for primals and duals
        self._cached_primals = init_primals.copy()
        self._cached_duals = init_duals.clone(copy=True)
        self._cached_obj_factor = 1.0

        # set the initial values for the pyomo primals and duals
        self._pyomo_nlp.set_primals(self._cached_primals)
        self._pyomo_nlp.set_duals(self._cached_duals.get_block(0))
        # set the initial values for the external inputs
        ex_inputs = self._ex_io_inputs_from_full_primals(self._cached_primals)
        self._ex_io_model.set_inputs(ex_inputs)

        # create the lower and upper bounds for the complete problem
        pyomo_nlp_con_lb = self._pyomo_nlp.constraints_lb()
        ex_con_lb = np.zeros(len(self._outputs), dtype=np.float64)
        self._gL = np.concatenate((pyomo_nlp_con_lb, ex_con_lb))
        pyomo_nlp_con_ub = self._pyomo_nlp.constraints_ub()
        ex_con_ub = np.zeros(len(self._outputs), dtype=np.float64)
        self._gU = np.concatenate((pyomo_nlp_con_ub, ex_con_ub))

        # create the scaling parameters if they are provided
        self._obj_scaling = self._pyomo_nlp.get_obj_scaling()
        self._primals_scaling = self._pyomo_nlp.get_primals_scaling()
        pyomo_constraints_scaling = self._pyomo_nlp.get_constraints_scaling()
        self._constraints_scaling = None
        # check if we need constraint scaling, and if so, add in the
        # outputs_eqn_scaling
        if pyomo_constraints_scaling is not None or outputs_eqn_scaling is not None:
            if pyomo_constraints_scaling is None:
                pyomo_constraints_scaling = np.ones(self._pyomo_nlp.n_primals(), dtype=np.float64)
            if outputs_eqn_scaling is None:
                outputs_eqn_scaling = np.ones(len(self._outputs), dtype=np.float64)
            if type(outputs_eqn_scaling) is list:
                outputs_eqn_scaling = np.asarray(outputs_eqn_scaling, dtype=np.float64)
            self._constraints_scaling = np.concatenate((pyomo_constraints_scaling,
                                                       outputs_eqn_scaling))

        ### setup the jacobian structures
        self._jac_pyomo = self._pyomo_nlp.evaluate_jacobian()

        # We will be mapping the dense external jacobian (doutputs/dinputs)
        # to the correct columns from the full x vector
        ex_start_row = self._pyomo_nlp.n_constraints()

        jac_ex = self._ex_io_model.evaluate_derivatives()

        # the jacobian returned from the external model is in the
        # space of the external model only. We need to shift
        # the rows down and shift the columns appropriately
        jac_ex_irows = np.copy(jac_ex.row)
        jac_ex_irows += ex_start_row
        jac_ex_jcols = np.copy(jac_ex.col)
        for z,col in enumerate(jac_ex_jcols):
            jac_ex_jcols[z] = self._input_columns[col]
        jac_ex_data = np.copy(jac_ex.data)

        # CDL: this code was for the dense version of evaluate_derivatives
        # for i in range(len(self._outputs)):
        #     for j in range(len(self._inputs)):
        #         jac_ex_irows.append(ex_start_row + i)
        #         jac_ex_jcols.append(self._input_columns[j])
        #         jac_ex_data.append(jac_ex[i,j])

        jac_ex_output_irows = list()
        jac_ex_output_jcols = list()
        jac_ex_output_data = list()

        # add the jac for output variables from the extra equations
        for i in range(len(self._outputs)):
           jac_ex_output_irows.append(ex_start_row + i)
           jac_ex_output_jcols.append(self._output_columns[i])
           jac_ex_output_data.append(-1.0)

        self._full_jac_irows = np.concatenate((self._jac_pyomo.row, jac_ex_irows, jac_ex_output_irows))
        self._full_jac_jcols = np.concatenate((self._jac_pyomo.col, jac_ex_jcols, jac_ex_output_jcols))
        self._full_jac_data = np.concatenate((self._jac_pyomo.data, jac_ex_data, jac_ex_output_data))

        # currently, this interface does not do anything with Hessians

    def load_x_into_pyomo(self, primals):
        """
        Use this method to load a numpy array of values into the corresponding
        Pyomo variables (e.g., the solution from CyIpopt)

        Parameters
        ----------
        primals : numpy array
           The array of values that will be given to the Pyomo variables. The
           order of this array is the same as the order in the PyomoNLP created
           internally.
        """
        pyomo_variables = self._pyomo_nlp.get_pyomo_variables()
        for i,v in enumerate(primals):
            pyomo_variables[i].set_value(v)

    def _set_primals_if_necessary(self, primals):
        if not np.array_equal(primals, self._cached_primals):
            self._pyomo_nlp.set_primals(primals)
            ex_inputs = self._ex_io_inputs_from_full_primals(primals)
            self._ex_io_model.set_inputs(ex_inputs)
            self._cached_primals = primals.copy()

    def _set_duals_if_necessary(self, duals):
        if not np.array_equal(duals, self._cached_duals):
            self._cached_duals.copy_from(duals)
            self._pyomo_nlp.set_duals(self._cached_duals.get_block(0))

    def _set_obj_factor_if_necessary(self, obj_factor):
        if obj_factor != self._cached_obj_factor:
            self._pyomo_nlp.set_obj_factor(obj_factor)
            self._cached_obj_factor = obj_factor

    def x_init(self):
        return self._pyomo_nlp.init_primals()

    def x_lb(self):
        return self._pyomo_nlp.primals_lb()
    
    def x_ub(self):
        return self._pyomo_nlp.primals_ub()

    def g_lb(self):
        return self._gL.copy()

    def g_ub(self):
        return self._gU.copy()

    def scaling_factors(self):
        return self._obj_scaling, self._primals_scaling, self._constraints_scaling

    def objective(self, primals):
        self._set_primals_if_necessary(primals)
        return self._pyomo_nlp.evaluate_objective()

    def gradient(self, primals):
        self._set_primals_if_necessary(primals)
        return self._pyomo_nlp.evaluate_grad_objective()

    def constraints(self, primals):
        self._set_primals_if_necessary(primals)
        pyomo_constraints = self._pyomo_nlp.evaluate_constraints()
        ex_io_outputs = self._ex_io_model.evaluate_outputs()
        ex_io_constraints = ex_io_outputs - self._ex_io_outputs_from_full_primals(primals)
        constraints = BlockVector(2)
        constraints.set_block(0, pyomo_constraints)
        constraints.set_block(1, ex_io_constraints)
        return constraints.flatten()

    def jacobianstructure(self):
        return self._full_jac_irows, self._full_jac_jcols
        
    def jacobian(self, primals):
        self._set_primals_if_necessary(primals)
        self._pyomo_nlp.evaluate_jacobian(out=self._jac_pyomo)
        pyomo_data = self._jac_pyomo.data
        ex_io_deriv = self._ex_io_model.evaluate_derivatives()
        # CDL: dense version: ex_io_deriv = self._ex_io_model.evaluate_derivatives().flatten('C')
        self._full_jac_data[0:len(pyomo_data)] = pyomo_data
        self._full_jac_data[len(pyomo_data):len(pyomo_data)+len(ex_io_deriv.data)] = ex_io_deriv.data
        # CDL: dense version: self._full_jac_data[len(pyomo_data):len(pyomo_data)+len(ex_io_deriv)] = ex_io_deriv

        # the -1s for the output variables should still be  here
        return self._full_jac_data

    def hessianstructure(self):
        return np.zeros(0), np.zeros(0)
        #raise NotImplementedError('No Hessians for now')

    def hessian(self, x, y, obj_factor):
        raise NotImplementedError('No Hessians for now')

    def _ex_io_inputs_from_full_primals(self, primals):
        return primals[self._input_columns]
        #return np.compress(self._input_x_mask, primals)

    def _ex_io_outputs_from_full_primals(self, primals):
        return primals[self._output_columns]
        #return  np.compress(self._output_x_mask, primals)

    
        
            
Beispiel #9
0
print("Number of equality constraints: {:>14d}".format(nlp.n_eq_constraints()))
print("Number of inequality constraints: {:>11d}".format(
    nlp.n_ineq_constraints()))
print("Total number of constraints: {:>17d}".format(nlp.n_constraints()))
print("Number of nnz in Jacobian: {:>20d}".format(nlp.nnz_jacobian()))
print("Number of nnz in hessian of Lagrange: {:>8d}".format(
    nlp.nnz_hessian_lag()))

x = nlp.init_primals().copy()
y = nlp.create_new_vector('duals')
y.fill(1.0)
nlp.set_primals(x)
nlp.set_duals(y)

# Evaluate jacobian of all constraints
jac_full = nlp.evaluate_jacobian()
plt.spy(jac_full)
plt.title('Jacobian of the all constraints\n')
plt.show()

# Evaluate jacobian of the equality constraints
jac = nlp.evaluate_jacobian_eq()
plt.title('Jacobian of the equality constraints\n')
plt.spy(jac)
plt.show()

# Evaluate jacobian of the inequality constraints
jac = nlp.evaluate_jacobian_ineq()
plt.title('Jacobian of the inequality constraints\n')
plt.spy(jac)
plt.show()