math
math

Reputation: 2022

in python 3.4 how to hand over multiple arguments to constraint function in minimize

I would like to minimize the following function

def lower_bound(x, mu, r, sigma):
    mu_h = mu_hat(x, mu, r)
    sigma_h = sigma_hat(x, sigma)
    gauss = np.polynomial.hermite.hermgauss(10)
    return (1 + mu_h + math.sqrt(2) * sigma_h * min(gauss))

where mu_hat and sigma_hat are some simple helper function for certain calculations. I have the following constraints:

cons = ({"type": "ineq",
             "fun": lambda x, mu, r: mu_hat(x, mu, r),
             "args": (arg_dic,)},
            {"type": "ineq",
             "fun": lambda x, mu,: -sigma_hat(x, mu),
             "args": (mu,)},
            {"type": "ineq",
             "fun": lambda x: x},
            {"type": "ineq",
             "fun": lambda x: 1-np.dot(np.ones(x.size), x)})

where arg_dic the dictionary of additional arguments

arg_dic = {"mu": mu, "sigma": sigma, "r": r}

However, when I try to run the following

minimize(lower_bound, x0=bounds[t-1, 0],
                        args=(arg_dic, ),
                        constraints=cons)

I get the error (in pdb): TypeError: <lambda>() missing 1 required positional argument: 'r'. But everything is defined. If you print the dictionaries and variables all have a certain value. What is going wrong here?

Upvotes: 0

Views: 543

Answers (1)

John Zwinck
John Zwinck

Reputation: 249133

In scipy.minimize() the args is a tuple of arguments which are passed to the objective function. In your case, that function is:

def lower_bound(x, mu, r, sigma)

And you call it like this:

arg_dic = {"mu": mu, "sigma": sigma, "r": r}
args=(arg_dic, )

The problem is that you are passing a 1-tuple, which becomes x, and no other arguments. Instead, you should do this:

args=(mu, sigma, r)

Similarly, you need to fix your constraints, e.g.:

cons = ({"type": "ineq",
         "fun": lambda x, mu, r: mu_hat(x, mu, r),
         "args": (mu, r)},

Which can be simplified by removing the useless lambda:

cons = ({"type": "ineq",
         "fun": mu_hat,
         "args": (mu, r)},

Upvotes: 1

Related Questions