Reputation: 27
I would like to optimise the following code, but I get the error as follows, concerning the 4th line in constraints (I think). Any help would be very appreciated, thanks:
model += A[i] == min(P[i], C[i])
TypeError: '<' not supported between instances of 'int' and 'LpVariable'
P0 = [[1,0,4],[2,0,3],[4,6,2],[5,2,1],[1,0,0]]
x = [2,3,0]
xMax = [14,12,13]
C = [122, 99, 158, 37, 44]
# Instantiate our problem class
model = pulp.LpProblem("Clem", pulp.LpMaximize)
# Construct our decision variable lists
x = pulp.LpVariable.dicts('pInstal', (i for i in range(3)), lowBound = 0, cat = 'Continuous')
tx = pulp.LpVariable('tauxAutoconso', 0)
for i in range(5):
P = pulp.LpVariable.dicts('vectProduction',(i for i in range(5)), lowBound = 0, cat = 'Continuous')
A = pulp.LpVariable.dicts('vectAutoConso',(i for i in range(5)), lowBound = 0, cat = 'Continuous')
# Objective Function
model += tx
# Constraints
for i in range(3):
model += x[i] <= xMax[i]
for i in range(5):
model += P[i] == sum([P0[i][j] * x[j] for j in range(3)])
model += A[i] == min(P[i], C[i])
model += tx == sum(A) / sum(P)
model += sum(x) == sum(C)
# Solve our problem
if pulp.LpStatus[model.status] != 'Optimal':
print('Solution qualité :', pulp.LpStatus[model.status])
Upvotes: 1
Views: 995
Reputation: 16724
I am afraid the constraint
z = min(x,y)
is in general not that easy to handle. Here is a formulation with an extra binary variable δ:
z ≤ x
z ≤ y
z ≥ x - M⋅δ
z ≥ y - M⋅(1-δ)
δ ∈ {0,1}
Here M is a large enough constant. (M can be interpreted as the largest possible distance between x and y).
Sometimes we exploit how the objective is pushing variables. E.g. if the objective is already pushing z upwards, we can drop the greater-than constraints.
Often it is suggested to change the objective to include this. I.e. change the objective from
max obj
to
max obj + α⋅z
for some coefficient α>0. However this is basically changing the problem into something different. The optimal solution of this problem is (in general) not the same as the optimal solution of the model you are trying to solve.
Finally: some advanced solvers have a built-in min() function to make things easier for the modeler. They can also make better decisions on how to reformulate this internally (there are different formulation possible; I have just shown one).
Upvotes: 5