<commit_before>from __future__ import absolute_import

import numpy as np
try:
    from scipy.optimize import OptimizeResult
except ImportError:
    # in scipy 0.14 Result was renamed to OptimzeResult
    from scipy.optimize import Result
    OptimizeResult = Result

import ipopt
from .jacobian import FunctionWithApproxJacobian


class IpoptProblemWrapper(object):
    def __init__(self, fun, args=(), jac=None, hess=None, hessp=None,
                 constraints=(), eps=1e-8):
        if hess is not None or hessp is not None:
            raise NotImplementedError('Using hessian matrixes is not yet implemented!')
        if jac is None:
            fun = FunctionWithApproxJacobian(fun, epsilon=eps, verbose=False)
            jac = fun.jac
        elif not callable(jac):
            raise NotImplementedError('For now, the jacobian has to be provided!')
        self.fun = fun
        self.jac = jac
        self.args = args
        self._constraint_funs = []
        self._constraint_jacs = []
        self._constraint_args = []
        if isinstance(constraints, dict):
            constraints = (constraints, )
        for con in constraints:
            con_fun = con['fun']
            con_jac = con.get('jac', None)
            if con_jac is None:
                con_fun = FunctionWithApproxJacobian(con_fun, epsilon=eps, verbose=False)
                con_jac = con_fun.jac
            con_args = con.get('args', [])
            self._constraint_funs.append(con_fun)
            self._constraint_jacs.append(con_jac)
            self._constraint_args.append(con_args)

    def objective(self, x):
        return self.fun(x, *self.args)

    def gradient(self, x):
        return self.jac(x, *self.args)  # .T

    def constraints(self, x):
        con_values = []
        for fun, args in zip(self._constraint_funs, self._constraint_args):
            con_values.append(fun(x, *args))
        return np.hstack(con_values)

    def jacobian(self, x):
        con_values = []
        for fun, args in zip(self._constraint_jacs, self._constraint_args):
            con_values.append(fun(x, *args))
        return np.vstack(con_values)


def get_bounds(bounds):
    if bounds is None:
        return None, None
    else:
        lb = [b[0] for b in bounds]
        ub = [b[1] for b in bounds]
        return lb, ub


def get_constraint_bounds(constraints, x0):
    if isinstance(constraints, dict):
        constraints = (constraints, )
    cl = []
    cu = []
    if isinstance(constraints, dict):
        constraints = (constraints, )
    for con in constraints:
        m = len(np.atleast_1d(con['fun'](x0, *con.get('args', []))))
        cl.extend(np.zeros(m))
        if con['type'] == 'eq':
            cu.extend(np.zeros(m))
        elif con['type'] == 'ineq':
            cu.extend(1e19*np.ones(m))
        else:
            raise ValueError(con['type'])
    cl = np.array(cl)
    cu = np.array(cu)

    return cl, cu


def minimize_ipopt(fun, x0, args=(), method=None, jac=None, hess=None, hessp=None,
                   bounds=None, constraints=(), tol=None, callback=None, options=None):

    _x0 = np.atleast_1d(x0)<commit_msg>Better handling of inequality constraints<commit_after>from __future__ import absolute_import

import numpy as np
try:
    from scipy.optimize import OptimizeResult
except ImportError:
    # in scipy 0.14 Result was renamed to OptimzeResult
    from scipy.optimize import Result
    OptimizeResult = Result

import ipopt
from .jacobian import FunctionWithApproxJacobian


class IpoptProblemWrapper(object):
    def __init__(self, fun, args=(), jac=None, hess=None, hessp=None,
                 constraints=(), eps=1e-8):
        if hess is not None or hessp is not None:
            raise NotImplementedError('Using hessian matrixes is not yet implemented!')
        if jac is None:
            fun = FunctionWithApproxJacobian(fun, epsilon=eps, verbose=False)
            jac = fun.jac
        elif not callable(jac):
            raise NotImplementedError('For now, the jacobian has to be provided!')
        self.fun = fun
        self.jac = jac
        self.args = args
        self._constraint_funs = []
        self._constraint_jacs = []
        self._constraint_args = []
        if isinstance(constraints, dict):
            constraints = (constraints, )
        for con in constraints:
            con_fun = con['fun']
            con_jac = con.get('jac', None)
            if con_jac is None:
                con_fun = FunctionWithApproxJacobian(con_fun, epsilon=eps, verbose=False)
                con_jac = con_fun.jac
            con_args = con.get('args', [])
            self._constraint_funs.append(con_fun)
            self._constraint_jacs.append(con_jac)
            self._constraint_args.append(con_args)

    def objective(self, x):
        return self.fun(x, *self.args)

    def gradient(self, x):
        return self.jac(x, *self.args)  # .T

    def constraints(self, x):
        con_values = []
        for fun, args in zip(self._constraint_funs, self._constraint_args):
            con_values.append(fun(x, *args))
        return np.hstack(con_values)

    def jacobian(self, x):
        con_values = []
        for fun, args in zip(self._constraint_jacs, self._constraint_args):
            con_values.append(fun(x, *args))
        return np.vstack(con_values)


def get_bounds(bounds):
    if bounds is None:
        return None, None
    else:
        lb = [b[0] for b in bounds]
        ub = [b[1] for b in bounds]
        return lb, ub


def get_constraint_bounds(constraints, x0, INF=1e19):
    if isinstance(constraints, dict):
        constraints = (constraints, )
    cl = []
    cu = []
    if isinstance(constraints, dict):
        constraints = (constraints, )
    for con in constraints:
        m = len(np.atleast_1d(con['fun'](x0, *con.get('args', []))))
        cl.extend(np.zeros(m))
        if con['type'] == 'eq':
            cu.extend(np.zeros(m))
        elif con['type'] == 'ineq':
            cu.extend(INF*np.ones(m))
        else:
            raise ValueError(con['type'])
    cl = np.array(cl)
    cu = np.array(cu)

    return cl, cu


def minimize_ipopt(fun, x0, args=(), method=None, jac=None, hess=None, hessp=None,
                   bounds=None, constraints=(), tol=None, callback=None, options=None):

    _x0 = np.atleast_1d(x0)
{'fraction_non_alphanumeric': 0.11105852658147973, 'fraction_numerical': 0.00536362202240101, 'mean_word_length': 2.3544973544973544, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4408045', 'n_tokens_mistral': 2052, 'n_tokens_neox': 1986, 'n_words': 496}