I'm trying to implement a Python function that could solve a minimization problem. I am used to do it with Excel Solver "binary constraint" function and Evolutionary solving method.
The objective function could take, for example, the form:
3*x[0]+4*x[1]+5*x[2]+5*x[3]-12
Where 12 is a changing constant. The purpose of this is to reach the closest value to 0. The key thing is that all x's should be either 0 or 1. All x's could be positive or negative, same for the constant.
I have tried Scipy like follows:
import numpy as np
from scipy.optimize import minimize
def objective(x):
return 3*x[0]+4*x[1]+5*x[2]+5*x[3]
def cons1(x):
return 3*x[0]+4*x[1]+5*x[2]+5*x[3]-12
# initial guesses
n = 4
x0 = np.zeros(n)
x0[0] = 1.0
x0[1] = 1.0
x0[2] = 1.0
x0[3] = 1.0
# show initial objective
print('Initial Objective: ' + str(objective(x0)))
# optimize
b = (0.0,1.0)
bnds = (b, b, b, b)
con1 = {'type':'eq', 'fun':cons1}
cons= [con1]
solution = minimize(objective,x0,method='SLSQP',\
bounds=bnds, constraints=cons)
x = solution.x
# show final objective
print('Final Objective: ' + str(objective(x)))
# print solution
print('Solution')
print('x1 = ' + str(x[0]))
print('x2 = ' + str(x[1]))
print('x3 = ' + str(x[2]))
print('x4 = ' + str(x[3]))
Which yields:
Initial Objective: 17.0
Final Objective: 11.999999999999996
Solution
x1 = 0.799999999999997
x2 = 0.7333333333333341
x3 = 0.6666666666666663
x4 = 0.6666666666666681
I think I am missing some parameter or configuration