Reputation: 1
I am trying to create a minimization program to find the lowest sum squared errors between a predicted value (r) and actual value (x). I am fitting b_1, b_2 and b_3 to obtain r. I am using the minimize function from scipy.optimize(). I have included bounds for each of the 3 variables which works. I also want to include a constraint where b_1<b_2<b_3. However I tried implementing this and received errors: TypeError: numpy boolean subtract, the -
operator, is not supported, use the bitwise_xor, the ^
operator, or the logical_xor function instead.
Any help would be great!
import numpy as np
import pandas as pd
import sys
import math
import numpy as np
from scipy.optimize import curve_fit
import os
from scipy.optimize import minimize
def psd_fun(c_s):
b_1 = c_s[0]
b_2 = c_s[1]
b_3 = c_s[2]
a = np.arange(-1.0, 1.01, 0.10)
b = np.linspace(-1.0, 5.0, 40)
c = []
x=282.335
p_1 = 0.109
p_2 = 0.102
p_3 = 0.789
pt = 0.440
d1=[]
d2=[]
d3=[]
d12=[]
d22=[]
d32=[]
for i in b:
z=10**i
c += [z]
for i in c:
d1 += [p_1*(1-math.exp(-(i/b_1)))*pt]
d2 += [p_2 * (1 - math.exp(-(i / b_2))) * pt]
d3 += [p_3 * (1 - math.exp(-(i / b_3))) * pt]
for i in range(1,len(d3),1):
d12 += [((d1[i]-d1[i-1])/(p_1*pt)*c[i])]
d22 +=[(d2[i]-d2[i-1])/(p_2*pt)*c[i]]
d32 +=[(d3[i]-d3[i-1])/(p_3*pt)*c[i]]
r = sum(d12)*p_1*pt+sum(d22)*p_2*pt+sum(d32)*p_3*pt
r1 = (r-x)**2
return r1
cons = ({'type': 'ineq', 'fun': lambda c_s: np.array([c_s[0] <= c_s[1]])},
{'type': 'ineq', 'fun': lambda c_s: np.array([c_s[1] <= c_s[2]])})
bnds = ((0.1, 2.5), (15, 500), (400, 10000))
min_res = minimize(psd_fun, [2.5,276,435], bounds = bnds, constraints=cons)
print(min_res)
without using the constraints I obtain:
fun: 3.3969585845074804e-15
hess_inv: <3x3 LbfgsInvHessProduct with dtype=float64>
jac: array([6.68100889e-09, 6.30719417e-09, 5.02965289e-08])
message: 'CONVERGENCE: NORM_OF_PROJECTED_GRADIENT_<=_PGTOL'
nfev: 16
nit: 3
njev: 4
status: 0
success: True
x: array([ 2.5 , 302.27943845, 638.28639494])
Which is fine and what I wanted. However I have some datapoints where the program is not fitting to specifications: b_1<b_2<b_3
Upvotes: 0
Views: 129
Reputation: 7831
I believe that the contraint option can only be used for certain methods (see https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html)
Constraints definition. Only for COBYLA, SLSQP and trust-constr.
Upvotes: 2