I am trying to find the shortest path in the following graph from G to C and I wrote the following code to accomplish that.
First I give the equations and constraints I believe I should use:
We maximize dc subject to:
db-da <= 8
df-da <= 10
dc-db <= 4
dd-dc <= 3
de-dd <= 25
df-dd <= 18
dd-de <= 9
dg-de <= 7
da-df <= 5
db-df <= 7
dc-df <= 3
de-df <= 2
dd-dg <= 2
dh-dg <= 3
da-dh <= 4
db-dh <= 9
import numpy as np
import scipy as scp
from scipy.optimize import minimize
a,b,c,d,e,f,g,h = 0,1,2,3,4,5,6,7
def objective(x, sign = -1.0):
return sign*x[c]
def c1(x, sign = -1.0):
return sign*(x[b]-x[a]-8)
def c2(x, sign = -1.0):
return sign*(x[f]-x[a]-10)
def c3(x, sign = -1.0):
return sign*(x[c]-x[b]-4)
def c4(x, sign = -1.0):
return sign*(x[d]-x[c]-3)
def c5(x, sign = -1.0):
return sign*(x[e]-x[d]-25)
def c6(x, sign = -1.0):
return sign*(x[f]-x[d]-18)
def c7(x, sign = -1.0):
return sign*(x[d]-x[e]-9)
def c8(x, sign = -1.0):
return sign*(x[g]-x[e]-7)
def c9(x, sign = -1.0):
return sign*(x[a]-x[f]-5)
def c10(x, sign = -1.0):
return sign*(x[b]-x[f]-7)
def c11(x, sign = -1.0):
return sign*(x[c]-x[f]-3)
def c12(x, sign = -1.0):
return sign*(x[e]-x[f]-2)
def c13(x, sign = -1.0):
return sign*(x[d]-x[g]-2)
def c14(x, sign = -1.0):
return sign*(x[h]-x[g]-3)
def c15(x, sign = -1.0):
return sign*(x[a]-x[h]-4)
def c16(x, sign = -1.0):
return sign*(x[b]-x[h]-9)
def c17(x, sign = -1.0):
return x[g]
cs = [c1,c2,c3,c4,c5,c6,c7,c8,c9,c10,c11,c12,c13,c14,c15,c16,c17]
x0 = [0 for i in range(8)]
b = (0,None)
bs = tuple([b for i in range(8)])
cons = []
for i in range(16):
cons.append({'type': 'ineq', 'fun':cs[i]})
cons.append({'type': 'eq', 'fun':c17})
sol = minimize(objective, x0, method = 'SLSQP', bounds=bs, constraints=cons)
for val in sol['x']:
print(round(val))
It is possible to merely use algebra to solve for each of the variables but it is supposed to be efficient to use LP to do it instead.
I believe just by a manual trace through the graph that the optimal path is G-H-B-C with a total cost of 16. However, the code above indicates that the optimal path is G-H-A-F-C with costs that make sense until they don't: 3-4-1-3. It says that the optimal path length is 11. It seems so close to a valid answer, except that it thinks you can go from A to F with a cost of 1.
[Edit: I just noticed I missed the edge from B to E but it doesn't seem to matter, and indeed when I add it in the algorithm's answer doesn't change.]