'Function minimization with non-linear constraints using scipy.optimize.minimize 'SLSQP' method Error

I'm trying to minimize a maximum likelihood function with non linear constraints:

    #Maximum Likelihood
import math
from scipy import optimize

#Define functions

#K-generalized exponential
def exp_k(x,k):
    e=(math.sqrt(1+(k**2)*(x**2))+(k*x))**(1/k)
    return e
#Beta (for non-linear equality constraint)
def beta(theta):
    a=theta[0]
    b=theta[1]
    k=theta[2]
    B=(1/(2*k))*((math.gamma(1/a)*math.gamma((1/(2*k))-(1/(2*a)))))/(((k+a*(math.gamma((1/(2*k))+(1/(2*a))))))**a)-b
    return B
#Beta's pdf
def p(x,theta):
    a=theta[0]
    b=theta[1]
    k=theta[1]
    pdf=(a*b*(x**(a-1))*exp_k(-b*(x**a),k))/math.sqrt(1+(k**2)*(b**2)*(x**(2*a)))
    return pdf
#Maximum likelihood logaritmic function 
def max_likelh(theta):
    x=[0.001960784,0.096078431,0.194117647,0.292156863,0.390196078,0.488235294,
    0.58627451,0.684313725,0.782352941,0.880392157,0.978431373,1.174509804,
    1.370588235,1.566666667,1.762745098,1.958823529,2.154901961,2.743137255,
    3.331372549,3.919607843,5.882352941]
    w=[0.078155633,0.06292445,0.131394783,0.32198121,1.010524004,0.925629323,
    0.889101147,0.840841293,0.815564861,0.73600276,0.634737057,0.516167129,
    0.333792876,0.255670572,0.17205571,0.090707194,0.039736612,0.014291316,
    0.002790717,0.002189501,0]
    l=0
    for i in range(len(x)):
        l=l+((math.log(p(x[i],theta),math.e))**w[i])
    return l

#OPTIMIZATION
#Boundaries (alpha, beta, kapa)
bnds = ((0, None),(0,None),(0,0.99999))

#Constraints
cons ={'type': 'eq', 'fun': beta}

#First parameter estimation
x0=[1,1,0.5]

#Optimize
res = scipy.optimize.minimize(max_likelh, x0, method='SLSQP', bounds=bnds, constraints=cons)
res.theta

I get these two errors:

TypeError: can't convert complex to float

ValueError: Objective function must return a scalar

What am I doing wrong to get a complex number? All the values in the sqrts are supposed to be positive.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source