Hmm are you trying to fit a least squared model here?
First up there is a bug in pulp you have discovered because
>>> [ vars[u] - vars[v] for (u,v) in ((1,2), (2,3), (3,4)) ]
[1*Var1 + -1*Var2 + 0, 1*Var2 + -1*Var3 + 0, 1*Var3 + -1*Var4 + 0]
And when you sum this Var3 disappears therefore the error :-(
I will put in a fix to this soon
However, as pulp currently does not solve non-linear problems the
following will not work
>>> prob += lpSum( [ (vars[u] - vars[v])**2 for (u,v) in ((1,2), (2,3), (3,4)) ]
as the (vars[u] - vars[v])**2 term is non-linear
however you can use some extra variables to achieve a similar result
to the following (this code will not work but is for illustrative
purposes) This is a 1-norm
>>> prob += lpSum( [ abs(vars[u] - vars[v]) for (u,v) in ((1,2), (2,3), (3,4)) ]
Please note in the code below I would prefer to use LpVariable.matrix
() and LpVariable.dicts() to create the variables rather then the loop
------------------------------
from pulp import *
prob = LpProblem("Minimize absolute difference 1-norm", LpMinimize)
vars = []
for i in range(10):
vars.append(LpVariable("Var%d" % i))
print vars[i]
pairs = ((1,2), (2,3), (3,4))
pairvars = {}
for pair in pairs:
pairvars[pair] = (LpVariable("PairVar(%s,%s)"%pair))
print pairvars[pair]
# objective
prob += lpSum( [ pairvars[pair] for pair in pairs] )
# constraints:
for (u,v) in pairs:
prob += vars[u] - vars[v] <= pairvars[(u,v)]
prob += vars[v] - vars[u] <= pairvars[(u,v)]
print prob
prob.solve()
print "Status:", LpStatus[prob.status]