Skip to content

Instantly share code, notes, and snippets.

@smellslikeml
Created April 27, 2020 20:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save smellslikeml/239006b5331d88472250d9ae07636c78 to your computer and use it in GitHub Desktop.
Save smellslikeml/239006b5331d88472250d9ae07636c78 to your computer and use it in GitHub Desktop.
# http://index-of.es/Varios-2/Practical%20Python%20AI%20Projects%20Mathemathical%20Models%20of%20Optimization%20Problems%20with%20Google%20OR-Tools.pdf
# coding: utf-8
"""
Example code for solving the transshipment problem. (pg. 111)
Input is an NxN numpy matrix (referenced here as D)
where row N is the demand and column N is the supply for each location 0 through N-1.
To solve, call the solve_model() function with matrix D as the input.
"""
import numpy as np
from ortools.linear_solver import pywraplp
def ObjVal(x):
return x.Objective().Value()
def SolVal(x):
if type(x) is not list:
return 0 if x is None else x if isinstance(x, (int, float)) else x.SolutionValue() if x.Integer() is False else int(x.SolutionValue())
elif type(x) is list:
return [SolVal(e) for e in x]
def newSolver(name):
return pywraplp.Solver(name,\
pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING)
def solve_model(D):
s = newSolver('Transshipmentuproblem')
n = len(D[0]) - 1
B = sum([D[-1][j] for j in range(n)])
G = [[s.NumVar(0, B if D[i][j] else 0, '') for j in range(n)] for i in range(n)]
for i in range(n):
s.Add(sum(G[i][j] for j in range(n)) - sum(G[j][i] for j in range(n)) == D[i][-1] - D[-1][i])
Cost = s.Sum(G[i][j]*D[i][j] for i in range(n) for j in range(n))
s.Minimize(Cost)
rc = s.Solve()
return rc, ObjVal(s), SolVal(G)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment