How to use the nlp.model.nlpmodel.NLPModel function in nlp

To help you get started, we’ve selected a few nlp examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github PythonOptimizers / NLP.py / tests / tools / test_dercheck.py View on Github external
model = Rosenbrock(request.param)
    x = np.ones(model.nvar)
    x[1::2] = -1
    dcheck = DerivativeChecker(model, x, tol=1.0e-4)
    dcheck.check()
    dcheck.check(cheap_check=True, hess=False)
    return dcheck


def test_rosenbrock(rosenbrock_checker):
    assert (len(rosenbrock_checker.grad_errs) == 0)
    assert (len(rosenbrock_checker.hess_errs) == 0)
    assert (len(rosenbrock_checker.cheap_grad_errs) == 0)


class Erroneous(NLPModel):

    def __init__(self, nvar, **kwargs):
        kwargs.pop("m", None)
        super(Erroneous, self).__init__(nvar, m=1, **kwargs)

    def obj(self, x):
        return 0.5 * np.dot(x, x)

    def grad(self, x):
        g = x.copy()
        g[0] += 1  # error: should be x[0].
        return g

    def hess(self, x, *args, **kwargs):
        obj_weight = kwargs.get('obj_weight', 1.0)
        H = np.eye(self.nvar)
github PythonOptimizers / NLP.py / nlp / model / cysparsemodel.py View on Github external
try:
    from cysparse.sparse.ll_mat import LLSparseMatrix
    import cysparse.common_types.cysparse_types as types
except:
    print "CySparse is not installed!"

from nlp.model.nlpmodel import NLPModel
from nlp.model.snlp import SlackModel
from nlp.model.qnmodel import QuasiNewtonModel
from pykrylov.linop import CysparseLinearOperator
import numpy as np


class CySparseNLPModel(NLPModel):
    """
    An `NLPModel` where sparse matrices are returned as CySparse matrices.
    The `NLPModel`'s `jac` and `hess` methods should return sparse
    Jacobian and Hessian in coordinate format: (vals, rows, cols).
    """

    def hess(self, *args, **kwargs):
        """Evaluate Lagrangian Hessian at (x, z).

        Note that `rows`, `cols` and `vals` must represent a LOWER triangular
        sparse matrix in the coordinate format (COO).
        """
        vals, rows, cols = super(CySparseNLPModel, self).hess(*args, **kwargs)
        H = LLSparseMatrix(size=self.nvar, size_hint=vals.size,
                           store_symmetric=True, itype=types.INT64_T,
                           dtype=types.FLOAT64_T)
github PythonOptimizers / NLP.py / nlp / model / scipymodel.py View on Github external
def __init__(self, model, **kwargs):
        if not isinstance(model, NLPModel):
            raise TypeError("The model in `model` should be a `NLPModel`"
                            "or a derived class of it.")
        super(SciPySlackModel, self).__init__(model)
github PythonOptimizers / NLP.py / nlp / model / pysparsemodel.py View on Github external
try:
    from pysparse.sparse import PysparseMatrix as psp
except ImportError:
    print "PySparse is not installed!"

from nlp.model.nlpmodel import NLPModel
from nlp.model.snlp import SlackModel
from nlp.model.qnmodel import QuasiNewtonModel
from pykrylov.linop.linop import PysparseLinearOperator

import numpy as np


class PySparseNLPModel(NLPModel):
    """An `NLPModel` where sparse matrices are returned in PySparse format.

    The `NLPModel`'s `jac` and `hess` methods should return that sparse
    Jacobian and Hessian in coordinate format: (vals, rows, cols).
    """

    def hess(self, *args, **kwargs):
        """Evaluate Lagrangian Hessian at (x, z)."""
        vals, rows, cols = super(PySparseNLPModel, self).hess(*args, **kwargs)
        H = psp(size=self.nvar, sizeHint=vals.size, symmetric=True)
        H.put(vals, rows, cols)
        return H

    def jac(self, *args, **kwargs):
        """Evaluate constraints Jacobian at x."""
        vals, rows, cols = super(PySparseNLPModel,
github PythonOptimizers / NLP.py / nlp / optimize / cqp.py View on Github external
bot += model.nrangeC
            self.tLL = range(bot, bot + model.nlowerB)
            bot += model.nlowerB
            self.tLR = range(bot, bot + model.nrangeB)
            bot += model.nrangeB
            self.tUU = range(bot, bot + model.nupperB)
            bot += model.nupperB
            self.tUR = range(bot, bot + model.nrangeB)

            n = model.n + n_con_low + n_con_upp + n_var_low + n_var_upp
            m = model.m + model.nrangeC + n_var_low + n_var_upp
            Lvar = np.zeros(n)
            Lvar[:model.n] = -np.inf * np.ones(model.n)
            Uvar = np.inf * np.ones(n)

        NLPModel.__init__(self, n=n, m=m, name='slack-' + model.name,
                          Lvar=Lvar, Uvar=Uvar, Lcon=np.zeros(m))

        # Redefine primal and dual initial guesses
        self.x0 = np.empty(self.n)
        self.x0[:model.n] = model.x0[:]
        self.x0[model.n:] = 0

        self.pi0 = np.empty(self.m)
        self.pi0[:model.m] = model.pi0[:]
        self.pi0[model.m:] = 0
        return
github PythonOptimizers / NLP.py / nlp / model / snlp.py View on Github external
# -*- coding: utf-8 -*-
"""A slack framework for NLP.py."""


import numpy as np
from nlp.model.nlpmodel import NLPModel

__docformat__ = 'restructuredtext'


class SlackModel(NLPModel):
    u"""General framework for converting a nonlinear optimization problem to a
    form using slack variables.

    Original problem::

         cᴸ ≤ c(x)
              c(x) ≤ cᵁ
        cᴿᴸ ≤ c(x) ≤ cᴿᵁ
              c(x) = cᴱ
          l ≤   x  ≤ u

    is transformed to::

        c(x) - sᴸ = 0
        c(x) - sᵁ = 0
        c(x) - sᴿ = 0
github PythonOptimizers / NLP.py / nlp / model / scipymodel.py View on Github external
"""Models with sparse matrices in SciPy coordinate (COO) format."""

from scipy import sparse as sp

from nlp.model.nlpmodel import NLPModel
from nlp.model.amplmodel import AmplModel
from nlp.model.snlp import SlackModel
from nlp.model.qnmodel import QuasiNewtonModel
from pykrylov.linop.linop import linop_from_ndarray
import numpy as np


class SciPyNLPModel(NLPModel):
    """`NLPModel` with sparse matrices in SciPy coordinate (COO) format.

    The `NLPModel`'s :meth:`jac` and :meth:`hess` methods
    should return that sparse Jacobian and Hessian in coordinate format:
    (vals, rows, cols).
    """

    def hess(self, *args, **kwargs):
        """Evaluate Lagrangian Hessian."""
        vals, rows, cols = super(SciPyNLPModel, self).hess(*args, **kwargs)
        return sp.coo_matrix((vals, (rows, cols)),
                             shape=(self.nvar, self.nvar))

    def jac(self, *args, **kwargs):
        """Evaluate sparse constraints Jacobian."""
        if self.ncon == 0:  # SciPy cannot create sparse matrix of size 0.
github PythonOptimizers / NLP.py / nlp / model / qnmodel.py View on Github external
"""Models with quasi-Newton Hessian approximation."""

from nlp.model.nlpmodel import NLPModel

__docformat__ = 'restructuredtext'


class QuasiNewtonModel(NLPModel):
    """`NLPModel with a quasi-Newton Hessian approximation."""

    def __init__(self, *args, **kwargs):
        """Instantiate a model with quasi-Newton Hessian approximation.

        :keywords:
            :H: the `class` of a quasi-Newton linear operator.
                This keyword is mandatory.

        Keywords accepted by the quasi-Newton class will be passed
        directly to its constructor.
        """
        super(QuasiNewtonModel, self).__init__(*args, **kwargs)
        qn_cls = kwargs.pop('H')
        self._H = qn_cls(self.nvar, **kwargs)
github PythonOptimizers / NLP.py / nlp / optimize / cqp.py View on Github external
from hsl.solvers.pyma27 import PyMa27Solver as LBLContext
from hsl.scaling.mc29 import mc29ad
from pykrylov.linop import PysparseLinearOperator
from nlp.tools.norms import norm2, norm_infty, normest
from nlp.tools.timing import cputime
import logging

# for slack model
from nlp.model.nlpmodel import NLPModel
from nlp.model.qnmodel import QuasiNewtonModel
from pysparse.sparse.pysparseMatrix import PysparseMatrix
import numpy as np


# CQP needs equality constraints and bounds on variables as s>=0
class SlackModel(NLPModel):
    """Framework for converting an optimization problem to a form using slacks.

    In the latter problem, the only inequality constraints are bounds on
    the slack variables. The other constraints are (typically) nonlinear
    equalities.

    The order of variables in the transformed problem is as follows:

    1. x, the original problem variables.

    2. sL = [ sLL | sLR ], sLL being the slack variables corresponding to
       general constraints with a lower bound only, and sLR being the slack
       variables corresponding to the 'lower' side of range constraints.

    3. sU = [ sUU | sUR ], sUU being the slack variables corresponding to
       general constraints with an upper bound only, and sUR being the slack
github PythonOptimizers / NLP.py / nlp / model / linemodel.py View on Github external
# -*- coding: utf-8 -*-
"""Restriction of models to lines."""

from nlp.model.nlpmodel import NLPModel
from nlp.tools.utils import where, Min, Max
import numpy as np


class C1LineModel(NLPModel):
    u"""Restriction of a C¹ model to a line.

    An instance of this class is a model representing the original model
    restricted to the line x + td. More precisely, if the original objective
    is f: ℝⁿ → ℝ, then, given x ∈ ℝⁿ and d ∈ ℝⁿ (d≠0) a fixed direction, the
    objective of the restricted model is ϕ: ℝ → ℝ defined by

        ϕ(t) := f(x + td).

    Similarly, if the original constraints are c: ℝⁿ → ℝᵐ, the constraints of
    the restricted model are γ: ℝ → ℝᵐ defined by

        γ(t) := c(x + td).

    The functions f and c are only assumed to be C¹, i.e., only values and
    first derivatives of ϕ and γ are defined.