Skip to content

Instantly share code, notes, and snippets.

@WillianFuks
Created November 15, 2021 17:19
Show Gist options
  • Save WillianFuks/d508d80223f5e7b47493ba0ef181ca91 to your computer and use it in GitHub Desktop.
Save WillianFuks/d508d80223f5e7b47493ba0ef181ca91 to your computer and use it in GitHub Desktop.
import numpy as np
import cvxpy as cx
# Begin with variables
x_shippers = cx.Variable((4, 2), boolean=True, name='shippers')
x_transports = cx.Variable((4, 2), boolean=True, name='transports')
x_docks = cx.Variable((4, 2), boolean=True, name='docks')
# 'y' represents variables that are built by introducing an AND conjunction between
# 2 other variables.
y_docks_and_transp = cx.Variable((4, 4), boolean=True, name="docks AND transportations")
# Data for 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])
# Data for processing AND operations
transport_and_dock_costs = np.array([[50, 70, 0, 60]])
# Mappers
train_map = np.array([1, 0])
destine_shippers_map = np.array([[1, 0], [0, 1]])
dest_ships_arr = destine_shippers_map[containers[:, 1]]
# Mappers for AND variables and constraints
transp_dock_transp_map = np.array([[1, 0, 0, 0], [0, 1, 0, 1]])
dock_dock_transp_map = np.array([[1, 1, 0, 0], [0, 0, 1, 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
constraints.extend([constraint00, constraint01, constraint02])
constraint10 = cx.sum(x_transports, axis=1) == cx.sum(x_shippers, axis=1)
constraint11 = cx.sum(x_transports @ train_map.T) <= 2
x1 = x_transports @ transp_dock_transp_map
x2 = x_docks @ dock_dock_transp_map
constraint12 = y_docks_and_transp >= x1 + x2 - 1
constraint13 = y_docks_and_transp <= x1
constraint14 = y_docks_and_transp <= x2
constraint15 = cx.sum(y_docks_and_transp, axis=1) == cx.sum(x_shippers, axis=1)
constraints.extend([constraint10, constraint11, constraint12, constraint13, constraint14, constraint15])
constraint20 = cx.sum(x_docks, axis=1) == cx.sum(x_shippers, axis=1)
constraints.extend([constraint20])
cost = cx.sum(x_shippers @ shippers_costs.T) + cx.sum(y_docks_and_transp @ transport_and_dock_costs.T) + containers[:, 0].T @ (1 - cx.sum(x_shippers, axis=1))
objective = cx.Minimize(cost)
problem = cx.Problem(objective, constraints)
problem.solve()
print(x_shippers.value)
print(x_transports.value)
print(x_docks.value)
print(y_docks_and_transp.value)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment