Viimu
Viimu

Reputation: 11

TypeError: list indices must be integers or slices, not LpVariable

I'm learning python coding and also using pulp to do LP optimization. I have a function that I need to maximize, but looks like python/pulp won't let my variable browse through list.

turbiinit_lista = [0,1,2,3]

prob = LpProblem("Vesivoima", LpMaximize)
k = LpVariable("Test", 0, 3, LpInteger)

maximize this function

prob += (10*turbiinit_lista[k])-50-(350*turbiinit_lista[k])


prob.writeLP("Vesivoima.lp")
prob.solve()

This is just a simplification of my messy code, but it gives you the idea of my problem.

So is it possible to browses through the list for optimal variable values?

Upvotes: 0

Views: 728

Answers (1)

kabdulla
kabdulla

Reputation: 5419

Welcome to SO! As @Erwin has pointed out you cannot use a decision variable to index into a python list or array.

However you can use a MILP via the pulp library to select from a list of possible values.

There are a few ways to do this - one is to introduce a list of binary variables to indicate whether each of the options is chosen (variable takes value 1) or not (variable takes value 0), and enforce that exactly one of them must be true.

Using this approach your problem would become the following. Note that choose_vars are a list of binary decision variables which track which of the list of options is selected, and chosen_value is a continuous variable which is constrained to be the chosen value.

from pulp import *
turbiinit_lista = [1.1,2.2,3.3,4.4]
n = len(turbiinit_lista)
N = range(n)

prob = LpProblem("Vesivoima", LpMaximize)
choose_vars = LpVariable.dicts("choose_%s", N, 0, 1, cat="Integer")
choosen_value = LpVariable("choosen")

prob += (10*choosen_value-50-(350*choosen_value))
prob += choosen_value == lpSum([turbiinit_lista[i]*choose_vars[i] for i in N])
prob += lpSum([choose_vars[i] for i in N]) == 1

prob.writeLP("Vesivoima.lp")
prob.solve()

choose_vars_soln = [choose_vars[i].varValue for i in N]
print("choose_vars_soln: " + str(choose_vars_soln))
print("choosen_value: " + str(choosen_value.varValue))

Which outputs:

choose_vars_soln: [1.0, 0.0, 0.0, 0.0]
choosen_value: 1.1

Upvotes: 2

Related Questions