Skip to content

Instantly share code, notes, and snippets.

@upadhyan
Created October 19, 2022 04:37
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 upadhyan/0473135e849d167a574c7f9bac5e1426 to your computer and use it in GitHub Desktop.
Save upadhyan/0473135e849d167a574c7f9bac5e1426 to your computer and use it in GitHub Desktop.
Full 2SP Server Farm Code
import numpy as np
import gurobipy as gp
from gurobipy import GRB
## First Stage Constants
i = np.array([6,14,27])
s = np.array([1,5,3])
B = 1000
S = 100
## Second Stage Constants
K = 50 # Number of scenarios
d_xi = np.array([
np.random.normal(70,10,K),
np.random.normal(8,2,K),
np.random.normal(15,4,K)
])
c = np.array([7,18,30])
p = np.array([1.0/K]*K) # Probability of a scenario happening
m = gp.Model("2SP")
m.ModelSense = GRB.MINIMIZE
m.setParam('OutputFlag', 0) # Telling gurobi to not be verbose
m.params.logtoconsole=0
# VARIABLES
## First Stage Decision variable
x = m.addMVar((3,), vtype = GRB.INTEGER, name = "x")
## 2nd stage decision for each potential scenario
y = m.addMVar((3,K), vtype = GRB.INTEGER, name = "y")
### Gurobi automatically sets bounds to (0, inf)
# OBJECTIVE
m.setObjective(i @ x + gp.quicksum(c @ y[:,k] * p[k] for k in range(K)))
# CONSTRAINTS
## Installation Budget
m.addConstr(i @ x <= B)
## Space
m.addConstr(s @ x <= S)
## Meet demand in each scenario
m.addConstrs((
x + y[:,k] >= d_xi[:,k] for k in range(K)
))
# SOLVING
m.optimize()
result = x.x
print(f"Our Server farm will cost ${np.round(m.ObjVal,2)}. We should buy {result[0]} CPUs, {result[1]} GPUs, and {result[2]} TPUs ")
@gedefaye-ie
Copy link

I found it impressive

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment