Skip to content

Instantly share code, notes, and snippets.

@yoniLavi
Created September 20, 2024 13:02
Show Gist options
  • Save yoniLavi/78c63d53545f46d1e533e80a55d2753c to your computer and use it in GitHub Desktop.
Save yoniLavi/78c63d53545f46d1e533e80a55d2753c to your computer and use it in GitHub Desktop.
import pulp
import pandas as pd
warehouses = pd.Series({"Dublin": 300, "Cork": 200, "Galway": 200})
targets = pd.Series({"Belfast": 150, "Limerick": 250, "Sligo": 200})
costs = pd.DataFrame({
"Belfast": [16, 14, 13],
"Limerick": [18, 12, 15],
"Sligo": [11, 13, 17]
}, index=["Dublin", "Cork", "Galway"])
# Create the decision variables
vars = pd.DataFrame([[pulp.LpVariable(f"Ship_{w}_{s}", lowBound=0, cat='Integer')
for s in targets.index]
for w in warehouses.index],
index=warehouses.index, columns=targets.index)
# Define the objective function
prob = pulp.LpProblem("Warehouse_Shipping_Problem", pulp.LpMinimize)
prob += pulp.lpSum((vars * costs).values.ravel())
prob.extend(pulp.lpSum(vars.loc[w]) <= warehouses[w] for w in warehouses.index) # Warehouse constraints
prob.extend(vars[s].sum() == targets[s] for s in targets.index) # Target constraints
prob.solve(pulp.PULP_CBC_CMD(msg=False)) # solve without the verbosity
# Output
print("Status:", pulp.LpStatus[prob.status])
print("\nOptimal Shipments:")
shipments = vars.map(lambda v: int(v.varValue))
for w in warehouses.index:
for s in targets.index:
if shipments.loc[w, s] > 0:
print(f"{w} to {s}: {shipments.loc[w, s]}")
print("\nTotal Cost: €", pulp.value(prob.objective))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment