This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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