Search code examples
pythonoptimizationscipyscipy-optimizescipy-optimize-minimize

Optimize.Minimize passes 2 arguments to function of 1 argument


I have a problem with optimize.minimize. I will paste the code and explain it after.

def getC(p,q):
    def C1D(l):

        firstTerm = 1/np.sqrt(-(-l + 2*p*(-1+l))*(2 - l + 2*p*(-1+l)))
        secondTerm = firstTerm = 1/np.sqrt(-(-l + 2*q*(-1+l))*(2 - l + 2*q*(-1+l)))

        return 2*l*(firstTerm + secondTerm)
    return C1D

pVal = []
qVal = []
lMinVal = []

for p in np.round(np.linspace(0,1,10,False),3):
    for q in np.round(np.linspace(0,1,10,False),3):
        pVal.append(p)
        qVal.append(q)

        C = getC(p,q)

        def cons_quantum(l):
            return C(l) - 2


        cons = {'type':'ineq', 'fun': cons_quantum}

        opt.minimize(C, 1, cons, bounds=((0,1),))

There's this function 3vars and I am trying to go over some values of p and q (defined in the for loop) and, for each one, I will have a simpler function that is just the C function with p and q fixed. Then, I will minimize this simpler 1-parameter function with a constraint that the function C(l) has to be greater than or equal to 2. (Eventually I will add the line that appends the minimum value of l to the list lMinVal)

My problem is that when I run it, I get the following error:

 File "C:\Users\*****\AppData\Local\Continuum\anaconda3\lib\site-packages\scipy\optimize\optimize.py", line 293, in function_wrapper
    return function(*(wrapper_args + args))

TypeError: C1D() takes 1 positional argument but 2 were given

Solution

  • The third argument of scipy.optimize.optimize is a list of extra arguments passed to the function, not the constraints. You want:

    opt.minimize(C, 1, constraints=cons, bounds=((0,1),))