Skip to content

Instantly share code, notes, and snippets.

@WillianFuks
Created November 14, 2021 16:29
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 WillianFuks/ae0b5524336c2c8d2a0c301a16c772e1 to your computer and use it in GitHub Desktop.
Save WillianFuks/ae0b5524336c2c8d2a0c301a16c772e1 to your computer and use it in GitHub Desktop.
import numpy as np
import cvxpy as cx
# Begin with the variables that describe the problem
x_shippers = cx.Variable((4, 2), boolean=True, name='shippers')
x_transports = cx.Variable((4, 2), boolean=True, name='transports')
# Data that helps implement the model
containers = np.array([[200, 0], [300, 1], [400, 0], [500, 1]])
shippers_costs = np.array([100, 130])
shippers_spaces = np.array([2, 1])
transport_costs = np.array([50, 70])
# Mappings that works as helpers.
train_map = np.array([1, 0])
destine_shippers_map = np.array([[1, 0], [0, 1]])
dest_ships_arr = destine_shippers_map[containers[:, 1]]
constraints = []
constraint00 = cx.sum(x_shippers, axis=1) <= 1
constraint01 = cx.sum(x_shippers, axis=0) <= shippers_spaces
constraint02 = x_shippers <= dest_ships_arr # Chosen shippers must also attend the destination of the container
constraints.extend([constraint00, constraint01, constraint02])
constraint10 = cx.sum(x_transports, axis=1) == cx.sum(x_shippers, axis=1) # Only transport containers that are assigned to a ship
constraint11 = cx.sum(x_transports @ train_map.T) <= 2 # There's only 2 slots available for trains
constraints.extend([constraint10, constraint11])
# Cost is associated to shippers, transport and containers that will remain in the factory
cost = cx.sum(x_shippers @ shippers_costs.T) + cx.sum(x_transports @ transport_costs.T) + containers[:, 0].T @ (1 - cx.sum(x_shippers, axis=1))
# Run the whole model
objective = cx.Minimize(cost)
problem = cx.Problem(objective, constraints)
problem.solve()
print(x_shippers.value)
print(x_transports.value)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment