How to minimize one argument of a function using Scipy? - python

I have the following function
def fun(X, alpha, y):
#some stuff
return J, gradient
And I am trying to minimze alpha with this, but nothing happens.
optimized_alpha = sp.optimize.minimize(lambda t: fun(X, t, y), alpha, method="Newton-CG", jac=True)

You can use functools.partial to turn your function to partial function with only one argument. In order to make it work with scipy.optimize.minimize you will need to keep the variable argument at the last position:
def fun(X, y, alpha):
#some stuff
return J, gradient
then:
from functools import partial
optfunc = partial(func, X, y)
optimized_alpha = sp.optimize.minimize(optfunc, alpha, method="Newton-CG", jac=True)

Related

How to compute objective, gradient and hessian within one function and pass it to scipy.optimize.minimize?

According to the docs, if jac is a Boolean and True, then the objective
function fun is assumed to return (f, grad), i.e. the objective value
and the gradient. This is useful to avoid duplicated computations
of terms arising in both the objective and the gradient.
Now I was wondering whether there is an similar option or way to achieve
the same for the hessian hess such that objective function can return
a tuple (f, grad, hess), where hess is the hessian matrix?
Here's a MWE:
import numpy as np
from scipy.optimize import minimize
def obj_and_grad_and_hess(x):
obj = np.exp(x) * x**2
grad = obj + 2*np.exp(x)*x
hess = obj + 4*np.exp(x)*(x) + 2*np.exp(x)
return obj, grad, hess
# res = minimize(obj_and_grad_and_hess, x0=[1.0], jac=True, hess=True)
This question is
similar to this question, where the
jacobian function can return the jacobian and the hessian.
Under the hood, scipy.optimize.minimize uses the MemoizeJac
decorator to handle the jac=True case. The decorator caches the function's return values f and grad each time it is called. By inheriting from this class, you can implement a MemoizeJacHess decorator in the same vein:
from scipy.optimize.optimize import MemoizeJac
class MemoizeJacHess(MemoizeJac):
""" Decorator that caches the return vales of a function returning
(fun, grad, hess) each time it is called. """
def __init__(self, fun):
super().__init__(fun)
self.hess = None
def _compute_if_needed(self, x, *args):
if not np.all(x == self.x) or self._value is None or self.jac is None or self.hess is None:
self.x = np.asarray(x).copy()
self._value, self.jac, self.hess = self.fun(x, *args)
def hessian(self, x, *args):
self._compute_if_needed(x, *args)
return self.hess
However, since there is no support for a hess=True option yet, you have to
use it like this:
obj = MemoizeJacHess(obj_and_grad_and_hess)
grad = obj.derivative
hess = obj.hessian
res = minimize(obj, x0=[1.0], jac=grad, hess=hess)

Curve_fit returning wrong parameters

I've got a little project for my college and I need to write a method which fits an array to some function, here's it's part:
def Linear(self,x,a,b):
return a*x+b
def Quadratic(self, x, a,b,c):
return a*(x**2)+b*x+c
def Sinusoid(self,t, a, gam, omega, phi, offset):
return np.e ** (gam * t) * a * np.sin((2 * np.pi * omega * t) + phi) + offset
def Fit(self, name):
func= getattr(App, name)
self.fit_params, self.covariance_matrix = curve_fit(func, self.t, self.a, maxfev= 100000)
But it returns absolutely wrong values and also doesn't even work for Sinusoid function (ptimizeWarning: Covariance of the parameters could not be estimated warnings.warn('Covariance of the parameters could not be estimated'). I've already checked if it's not an issue with getattr function but it works correctly.
I'm running out of ideas where the issue is.
There are several problems here.
Linear, Quadratic and Sinusoid do not need self, you can define those as staticmethod:
#This is the decorator use to define staticmethod
#staticmethod
def Linear(x,a,b):
return a*x+b
The same applies to other methods (except Fit).
It will help when they are called in the future. When you call them with curve_fit(func,...), for example, if func is Sinusoid, what you are doing is
curve_fit(Sinusoid, ...) and not curve_fit(self.Sinusoid,...). When curve_fit use Sinusoid, the first argument may be understood as the self, therefore, you get and error.
If you define
#staticmethod
def Sinusoid(t, a, gam, omega, phi, offset):
return np.e ** (gam * t) * a * np.sin((2 * np.pi * omega * t) + phi) + offset
a, gam, omega, phi and offset are constants to fit. Therefore, when you call curve_fit, you need to pass this constants as params:
scipy.optimize.curve_fit(f, xdata, ydata, p0=None, sigma=None, absolute_sigma=False, check_finite=True, bounds=- inf, inf, method=None, jac=None, **kwargs)
To clarify: The first argument is the func, the second is your experimental data for x, and the third, is the data for y. And after that all the others kwargs, like maxfev. I don't know if self.a is the data for y, or if you want to set an initial value for a. I'm going to guess you want to set the initial value of a. You need to do it like this: p0=[x1,x2,x3,x4,..., xn] where xi is the initial value of the i-th constant. If you don't pass p0 as an argument to curve_fit, the default value for each constant is going to be 1. But here it comes the last problem:
The diferent functions use a diferent number arguments, so for the first one, Linear, you need to do p0 = [a,1]. For the second, p0 = [a, 1, 1]. And for the last one, the Sinusoid one, p0 = [a, 1, 1, 1, 1]
I don't really know if you can pass p0 = [a] to all of the functions and curve_fit will magically understand. But try so and if curve_fit doesn't let you, use condictionals:
def Fit(self, name):
if func = Linear:
p0 = [a,1]
elif func = Quadratic:
p0 = [a,1,1]
elif func = Sinusoid:
p0 = [a,1,1,1,1]
self.fit_params, self.covariance_matrix = curve_fit(func, self.t, self.y_values, p0=p0, maxfev= 100000)
Where self.y_values is the experimental data as an array-like element.
If self.a is the data for y you can cut all of this mambojambo and let Fit define as it currently is. But don't forguet the #staticmethod in the other functions.
Hope this solves your problem.

How to define two identical classes with different method parameter names?

I'm developing a scientific library where I would define vector functions in the time and frequency domain (linked by FFT). I created a class for vector formulas in the freq domain, and now I'd want to define an identical class for the time domain.
I want that in the time domain, the class functions - although being identical to their frequency-domain twin - have one parameter named t instead of omega. Is there an easier way of achieving this instead of repeated definition of every single method, while maintaining readibility?
My code:
(Note: my classes are much more complicated, and one can't just use the functions as formula.x_func(...) - some checking and etc are included. Also, there are actually 6 components.)
class VecFormula(object):
pass
class FreqFormula(VecFormula):
def __init__(self, x_func, y_func, z_func):
self.x_func = x_func
self.y_func = y_func
self.z_func = z_func
def x(self, x, y, z, omega, params):
return self.x_func(x, y, z, omega, params)
def y(self, x, y, z, omega, params):
return self.y_func(x, y, z, omega, params)
def z(self, x, y, z, omega, params):
return self.z_func(x, y, z, omega, params)
def component(self, comp, x, y, z, omega, params):
if comp == 'x':
return self.x(x, y, z, omega, params)
elif comp == 'y':
return self.y(x, y, z, omega, params)
elif comp == 'z':
return self.z(x, y, z, omega, params)
else:
raise ValueError(f'invalid component: {comp}')
class TimeFormula(FreqFormula):
"same as FreqFormula, but the omega parameter is renamed to t"
def x(self, x, y, z, t, params):
return super(TimeFormula, self).x(x, y, z, t, params)
def y(self, x, y, z, t, params):
return super(TimeFormula, self).y(x, y, z, t, params)
def z(self, x, y, z, t, params):
return super(TimeFormula, self).z(x, y, z, t, params)
def component(self, comp, x, y, z, t, params):
return super(TimeFormula, self).component(x, y, z, t, params)
It is easy to add methods to a class after creation they are just class attributes. The hard part here, is that you need to dynamically create new functions to clone the methods from the original class to be able to change their signature.
It is not the most clear part of Python, and dynamic function creation is not documented in the official reference documentations but can be found on SO: Python: dynamically create function at runtime
So here is a possible way:
# have the new class derive from the common base
class TimeFormula(VecFormula):
"same as FreqFormula, but the omega parameter is renamed to t"
pass
# loop over methods of origina class
for i,j in inspect.getmembers(FreqFormula, inspect.isfunction):
# copy the __init__ special method
if i == '__init__':
setattr(TimeFormula, i, j)
elif i.startswith('__'): continue # ignore all other special attributes
if not j.__qualname__.endswith('.'.join((FreqFormula.__name__, i))):
continue # ignore methods defined in parent classes
# clone the method from the original class
spec = inspect.getfullargspec(j)
newspec = inspect.FullArgSpec(['t' if i == 'omega' else i
for i in spec.args], *spec[1:])
f = types.FunctionType(j.__code__, j.__globals__, i, newspec, j.__closure__)
f.__qualname__ = '.'.join((TimeFormula.__qualname__, i))
# adjust the signature
sig = inspect.signature(j)
if ('omega' in sig.parameters):
f.__signature__ = sig.replace(
parameters = [p.replace(name='t') if name == 'omega' else p
for name, p in sig.parameters.items()])
# and finally insert the new method in the class
setattr(TimeFormula, i, f)
Sounds like you would achieve what you need through the use of class inheritance elegantly.
Please check out class inheritance python documentation or here.

Graphing Scipy optimize.minimize convergence results each iteration?

I would like to perform some tests on my optimisation routine using scipy.optimize.minimize, in particular graphing the convergence (or the rather objective function) each iteration, over multiple tests.
Suppose I have the following linearly constrained quadratic optimisation problem:
minimise: x_i Q_ij x_j + a|x_i|
subject to: sum(x_i) = 1
I can code this as:
def _fun(x, Q, a):
c = np.einsum('i,ij,j->', x, Q, x)
p = np.sum(a * np.abs(x))
return c + p
def _constr(x):
return np.sum(x) - 1
And I will implement the optimisation in scipy as:
x_0 = # some initial vector
x_soln = scipy.optimise.minimize(_fun, x_0, args=(Q, a), method='SLSQP',
constraints={'type': 'eq', 'fun': _constr})
I see that there is a callback argument but which only accepts a single argument of the parameter values at each iteration. How can I utilise this in a more esoteric case where I might have other arguments that need to be supplied to my callback function?
The way I solved this was use a generic callback cache object referenced each time from my callback function. Let's say you want to do 20 tests and plot the objective function after each iteration in the same chart. You will need an outer loop to run 20 tests, but we'll create that later.
First lets create a class that will store all iteration objective function values for us, and a couple extra bits and pieces:
class OpObj(object):
def __init__(self, Q, a):
self.Q, self.a = Q, a
rv = np.random.rand()
self.x_0 = np.array([rv, (1-rv)/2, (1-rv)/2])
self.f = np.full(shape=(500,), fill_value=np.NaN)
self.count = 0
def _fun(self, x):
return _fun(x, self.Q, self.a)
Also lets add a callback function that manipulates that class obj. Don't worry that it has more than one argument for now since we'll fix this later. Just make sure the first parameter is the solution variables.
def cb(xk, obj=None):
obj.f[obj.count] = obj._fun(xk)
obj.count += 1
All this does is use the object's functions and values to update itself, counting the number of iterations each time. This function will be called after each iteration.
Putting this all together all we need is two more things: 1) some matplotlib-ing to do the plot, and fixing the callback to have only one argument. We can do that with a decorator which is exactly what functools partial does. It returns a function with less arguments than the original. So the final code looks like this:
import matplotlib.pyplot as plt
import scipy.optimize as op
import numpy as np
from functools import partial
Q = np.array([[1.0, 0.75, 0.45], [0.75, 1.0, 0.60], [0.45, 0.60, 1.0]])
a = 1.0
def _fun(x, Q, a):
c = np.einsum('i,ij,j->', x, Q, x)
p = np.sum(a * np.abs(x))
return c + p
def _constr(x):
return np.sum(x) - 1
class OpObj(object):
def __init__(self, Q, a):
self.Q, self.a = Q, a
rv = np.random.rand()
self.x_0 = np.array([rv, (1-rv)/2, (1-rv)/2])
self.f = np.full(shape=(500,), fill_value=np.NaN)
self.count = 0
def _fun(self, x):
return _fun(x, self.Q, self.a)
def cb(xk, obj=None):
obj.f[obj.count] = obj._fun(xk)
obj.count += 1
fig, ax = plt.subplots(1,1)
x = np.linspace(1,500,500)
for test in range(20):
op_obj = OpObj(Q, a)
x_soln = op.minimize(_fun, op_obj.x_0, args=(Q, a), method='SLSQP',
constraints={'type': 'eq', 'fun': _constr},
callback=partial(cb, obj=op_obj))
ax.plot(x, op_obj.f)
ax.set_ylim((1.71,1.76))
plt.show()

when doing multi-integral, 'takes 0 positional arguments but 1 was given'

I am doing a multi integral with 4 variables, among them 2 have limits as functions. However the error appears on one of my constant-limit variable. Really cannot figure our why. Many thanks for your advice!
from numpy import sqrt, sin, cos, pi, arcsin, maximum
from sympy.functions.special.delta_functions import Heaviside
from scipy.integrate import nquad
def bmax(x):
return 1.14*10**9/sin(x/2)**(9/7)
def thetal(x,y,z):
return arcsin(3.7*10**15*sqrt(cos(x/2)**2/10**6-1.23*10**10/z+0.003*sin(x/2)**2*(2.51*10**63/sin(x/2)**9/y**7-1))/(z*sin(x/2)**2*cos(x/2)*(2.51*10**63/sin(x/2)**9/y**7-1)))
def rt(x,y):
return 3.69*10**12/(2.5*10**63/sin(x/2)**7*y**7-sin(x/2)**2)
def rd(x,y):
return maximum(1.23*10**10,rt(x,y))
def rl(x,y):
return rd(x,y)*(sqrt(1+5.04*10**16/(rd(x,y)*cos(x/2)**2))-1)/2
def wbound():
return [1.23*10**10,3.1*10**16]
def zbound():
return [10**(-10),pi-10**(-10)]
def ybound(z):
return [0,bmax(z)-10**(-10)]
def xbound(z,y,w):
return [thetal(z,y,w),pi-thetal(z,y,w)]
def f(x,y,z,w):
return [5.77/10**30*sin(z)*sin(z/2)*y*sin(x)*Heaviside(w-rl(z,y))*Heaviside(w-rd(z,y))/w**2]
result = nquad(f, [xbound, ybound,zbound,wbound])
The reason for that error is that although you don't want these bounds to depend on the variables, nquad still passes the variables to the functions you provide to it. So the bound functions have to take the right number of variables:
def wbound():
return [1.23*10**10,3.1*10**16]
def zbound(w_foo):
return [10**(-10),pi-10**(-10)]
def ybound(z, w_foo):
return [0,bmax(z)-10**(-10)]
def xbound(z,y,w):
return [thetal(z,y,w),pi-thetal(z,y,w)]
Now the functions zbound and ybound accept the extra variables but simply ignore them.
I'm not sure about the last bound, xbound(...): Do you want the variables y and z to be flipped? The supposedly correct ordering according to the definition of scipy.integrate.nquad would be
def xbound(y,z,w):
...
Edit: As kazemakase pointed out, the function f should return a float instead of a list so the brackets [...] in the return statement should be removed.
nquad expects a sequence of bounds for its second argument, with a rather stringent syntax.
If the integrand f depends on x, y, z, w and this is the order of definition, the terms in bounds must be, in sequence, xb, yb, zb and wb, where each of the bounds can be either a 2-tuple, e.g., xb = (xmin, xmax)
or a function that returns a 2-tuple.
The critical point is, the arguments of those functions... when we perform the inner integration, in dx, we have available y, z and w for computing the bounds in x, so that it must be
def xb(y,z,w): return(..., ...) — likewise
def yb(z,w): return (..., ...) and
def zb(w): return (..., ...).
The bounds with respect to the last variable of integration must be constant.
To summarize
# DEFINITIONS
def f(x, y, z, w): return .. . # x inner integration, ..., w outer integration
def xb(y,z,w): return (...,...) # or simply xb=(...,...) if it's a constant
def yb(z,w): return (...,...) # or yb=(...,...)
def zb(w): return (...,...) # or zb=(...,...)
wb = (...,...)
# INTEGRATION
result, _ = nquad(f, [xb, yb, zb, wb])

Categories

Resources