CS代写 MGTA613A-Python/Class3-Python

Business Problem:¶
Suppose you are scheduling the weekly production plan of a product for 12 weeks. The demand of the product, unit production cost, and production capacity for each week are given. Inventory holding costs are assessed at the end of each week. Holding cost per unit is invariant from week to week. There are 500 units of inventory available at the beginning of the first week. No shortage is allowed. Model the problem as an LP.

Copyright By PowCoder代写 加微信 powcoder

T: the set of time periods (weeks)$={1,2,…, 12}$

Parameters¶
$h$: unit holding cost
$p$: production capacity per month
$s_0$: the initial inventory
$c_t$: unit production cost in week $t\in T$
$d_t$: demand of week $t\in T$

Decision varibales¶
$x_t$: amount produced in week $t\in T$
$s_t$: inventory at the end of week $t\in T$

$$\begin{array}{rll}
\text{min} \quad &\sum_{t\in T}(c_tx_t + hs_t) \\
\text{s.t.} \quad & I_0+x_1-d_1=s_1 \\[5pt]
& s_{t-1}+x_t-d_t=s_t & t\in T\setminus\{1\}\\[5pt]
& x_t\leq p & t\in T\\[5pt]
& x_t,s_t \geq 0
\end{array}

# Read data from a file, create a model, and solve it.

import numpy as np
import pandas as pd
from gurobipy import *

# Find out your current working directory
print(os.getcwd())

/Users/brostami/Desktop/MGTA613A-Python/Class3-Python

# Read data files
data_prod = pd.read_csv(‘Data/Model4-input_data.csv’,header=0)

period demand production_cost production_capacity
0 1 3300 150 6400
1 2 3300 150 6400
2 3 4500 140 6800
3 4 6100 140 6800
4 5 5100 150 6400
5 6 9000 135 7000
6 7 9700 135 7000
7 8 8200 135 7000
8 9 7900 135 6800
9 10 5700 140 6800
10 11 4500 140 6800
11 12 4200 140 6400

data_param = pd.read_csv(‘Data/Model4-parameters.csv’,header=0)
data_param

attribute value
0 holding_cost 8
1 initial_inventory 500

T=data_prod[‘period’]

Name: period, dtype: int64

# Create thes sets and parameters
def ReadInstance(data_prod, data_param):

data_prod_np = data_prod.to_numpy()
size1 = data_prod_np.shape
print (“size1: “, size1[0], size1[1])

for i in range(size1[0]):
if int(data_prod_np[i][0]) not in T:
T.add(int(data_prod_np[i][0]))

for i in T:

for i in T:
d[i]=data_prod_np[i-1][1]

for i in T:
c[i]=data_prod_np[i-1][2]

for i in T:
p[i]=data_prod_np[i-1][3]

data_param_np = data_param.to_numpy()
size2 = data_param_np.shape
print (“size2: “, size2[0], size2[1])

I0=data_param_np[1][1]
h=data_param_np[0][1]

return T, T1, d, c, p, I0,h

#Read function to load the parameters
T, T1, d, c, p, I0,h= ReadInstance(data_prod, data_param)

size1: 12 4
size2: 2 2

# Create optimization model
m = Model(‘Production’)

# Create variables
x = m.addVars(T, obj=c, name=”production”)
s = m.addVars(T, obj=h, name=”inventory”)

# inventory balance constraints
m.addConstr(
(I0+x[1]-d[1] == s[1]), “balance0”)

m.addConstrs(
(s[t-1]+x[t]-d[t] == s[t] for t in T1), “balance”)

{2: ,
3: ,
4: ,
5: ,
6: ,
7: ,
8: ,
9: ,
10: ,
11: ,
12: }

# Capacity constraints
m.addConstrs(
(x[t] <= p[t] for t in T), "capacity") {1: ,
2: ,
3: ,
4: ,
5: ,
6: ,
7: ,
8: ,
9: ,
10: ,
11: ,
12: }

m.write(m.ModelName + ‘.lp’)

Warning: variables 0 and 24 have the same name “production[1]”
Warning: to let Gurobi read it back, use rlp format

# Compute optimal solution
m.optimize()

Gurobi Optimizer version 9.0.0 build v9.0.0rc2 (mac64)
Optimize a model with 24 rows, 48 columns and 47 nonzeros
Model fingerprint: 0xceb37c6a
Coefficient statistics:
Matrix range [1e+00, 1e+00]
Objective range [8e+00, 2e+02]
Bounds range [0e+00, 0e+00]
RHS range [3e+03, 1e+04]
Presolve removed 20 rows and 39 columns
Presolve time: 0.01s
Presolved: 4 rows, 9 columns, 12 nonzeros

Iteration Objective Primal Inf. Dual Inf. Time
0 7.7783441e+06 2.038013e+03 0.000000e+00 0s
6 1.0183400e+07 0.000000e+00 0.000000e+00 0s

Solved in 6 iterations and 0.01 seconds
Optimal objective 1.018340000e+07

# Print runtime
runtime = m.Runtime
print(“The run time is %f” % runtime)

The run time is 0.011206

# Print solution
if m.status == GRB.OPTIMAL:
production_sol = m.getAttr(‘x’, x)
inventory_sol = m.getAttr(‘x’, s)

for t in T:
print(‘\nOptimal production and inventory for week %s: %g and %f ‘ % (t, production_sol[t], inventory_sol[t]))

Optimal production and inventory for week 1: 2800 and 0.000000

Optimal production and inventory for week 2: 6000 and 2700.000000

Optimal production and inventory for week 3: 6800 and 5000.000000

Optimal production and inventory for week 4: 6800 and 5700.000000

Optimal production and inventory for week 5: 6400 and 7000.000000

Optimal production and inventory for week 6: 7000 and 5000.000000

Optimal production and inventory for week 7: 7000 and 2300.000000

Optimal production and inventory for week 8: 7000 and 1100.000000

Optimal production and inventory for week 9: 6800 and 0.000000

Optimal production and inventory for week 10: 5700 and 0.000000

Optimal production and inventory for week 11: 4500 and 0.000000

Optimal production and inventory for week 12: 4200 and 0.000000

# Print Objective value
print(‘Objective value: %s’ % m.objVal)

Objective value: 10183400.0

help(GRB.Attr)

Attributes are used throughout the Gurobi interface to query and
modify model properties. You refer to them as you would any
other object attribute. For example, “print model.numConstrs”
prints the number of constraints in a model. You can assign new values to
some attributes (e.g., model.ModelName = “New”), while others can only
be queried. Note that attribute modification is handled in a lazy fashion,
so you won’t see the effect of a change until after the next call to
Model.update() or Model.optimize().

Capitalization is ignored in Gurobi attribute names, so
model.numConstrs and model.NumConstrs are equivalent.

Gurobi attributes can be grouped into the following categories:

General model attributes (e.g., model.numConstrs):

numConstrs: Number of constraints
numVars: Number of variables
numSOS: Number of SOS constraints
numQConstrs: Number of quadrtic constraints
numGenConstrs: Number of general constraints
numNZs: Number of non-zero coefficients
numQNZs: Number of non-zero quadratic objective coefficients
numIntVars: Number of integer variables (including binary variables)
numBinVars: Number of binary variables
modelName: Model name
modelSense: Model sense: minimization (1) or maximization (-1)
objCon: Constant offset for objective function
objVal: Objective value for current solution
objBound: Best available lower bound on solution objective
poolObjBound: Bound on objective for undiscovered solutions
poolObjVal: Retrieve the objective value of an alternate MIP solution
MIPGap: Current relative MIP optimality gap
runtime: Runtime (in seconds) for most recent optimization
Status: Current status of model (help(GRB) gives a list of codes)
solCount: Number of stored solutions
iterCount: Number of simplex iterations performed
nodeCount: Number of branch-and-cut nodes explored
barIterCount: Number of barrier iterations performed
isMIP: Indicates whether the model is MIP (1) or not (0)
isQP: Indicates whether the model has a quadratic objective
isQCP: Indicates whether the model has quadratic constraints
isMultiObj: Indicates whether the model has multiple objectives
IISMinimal: Is computed IIS minimal?
kappa: Condition number of current LP basis
maxCoeff: Maximum constraint coefficient (in absolute value)
minCoeff: Minimum non-zero constraint coefficient (in absolute value)
maxBound: Maximum finite variable bound (in absolute value)
minBound: Minimum non-zero variable bound (in absolute value)
maxObjCoeff: Maximum objective coefficient (in absolute value)
minObjCoeff: Minimum objective coefficient (in absolute value)
maxRHS: Maximum linear constraint right-hand side (in absolute value)
minRHS: Minimum linear constraint right-hand side (in absolute value)
maxQCRHS: Maximum quadratic constraint right-hand side (in absolute value)
minQCRHS: Minimum quadratic constraint right-hand side (in absolute value)
maxQCCoeff: Maximum quadratic constraint coefficient in quadratic part (in absolute value)
minQCCoeff: Minimum non-zero quadratic constraint coefficient in quadratic part (in absolute value)
maxQCLCoeff: Maximum quadratic constraint coefficient in linear part (in absolute value)
minQCLCoeff: Minimum non-zero quadratic constraint coefficient in linear part (in absolute value)
maxQObjCoeff: Maximum quadratic objective coefficient (in absolute value)
minQObjCoeff: Minimum quadratic objective coefficient (in absolute value)
farkasProof: Infeasible amount for Farkas proof for infeasible models
numStart: number of MIP starts

Variable attributes (e.g., var.lb):

lb: Lower bound
ub: Upper bound
obj: Objective coefficient
vType: Variable type (GRB.CONTINUOUS, GRB.BINARY, GRB.INTEGER,
GRB.SEMICONT, or GRB.SEMIINT)
varName: Variable name
x: Solution value
rc: Reduced cost
xn: Solution value in alternate MIP solution
start: Start vector (use GRB.UNDEFINED to leave a value unspecified)
vBasis: Basis status
varHintVal: Variable hint value
varHintPri: Variable hint priority
branchPriority: Variable branch priority
partition: Variable partition
IISLB: Does LB participate in IIS? (for infeasible models)
IISUB: Does UB participate in IIS? (for infeasible models)
SAObjLow: Smallest objective coefficient for which basis remains optimal
SAObjUp: Largest objective coefficient for which basis remains optimal
SALBLow: Smallest lower bound for which basis remains optimal
SALBUp: Largest lower bound for which basis remains optimal
SAUBLow: Smallest upper bound for which basis remains optimal
SAUBUp: Largest upper bound for which basis remains optimal
unbdRay: Unbounded ray
pStart: Primal solution (for warm-starting simplex)
preFixVal: The value of the variable (for variables fixed by presolve)
varPreStat: Status of variable in presolved model
VTag: Tag string for variables (each defined variable tag MUST be unique)

Constraint attributes (e.g., constr.sense):

sense: Constraint sense
rhs: Constraint right-hand side value
constrName: Constraint name
pi: Dual value
slack: Constraint slack
cBasis: Basis status
lazy: Lazy constraint flag
IISConstr: Does constraint participate in IIS? (for infeasible models)
SARHSLow: Smallest RHS value for which basis remains optimal
SARHSUp: Largest RHS value for which basis remains optimal
farkasDual: Farkas dual for infeasible models
dStart: Dual solution (for warm-starting simplex)
CTag: Tag string for constraints (each defined constraint tag MUST be unique)

SOS (e.g., sos.IISSOS):

IISSOS: Does SOS participate in IIS? (for infeasible models)

Quadratic constraint attributes (e.g., qc.sense):

QCsense: Quadratic constraint sense
QCrhs: Quadratic constraint right-hand side value
QCname: Quadratic constraint name
IISQConstr: Does QC participate in IIS? (for infeasible models)
QCpi: Dual value
QCslack: Quadratic constraint slack
QCTag: Tag string for quadratic constraints (each defined
quadratic constraint tag MUST be unique)

GenConstr (e.g., genconstr.IISGenConstr):

GenConstrType: General constraint type (e.g., GRB.GENCONSTR_MAX)
GenConstrName: General constraint name
IISGenConstr: Does general constraint participate in IIS? (for infeasible models)

GenConstr (only for function constraints)

FuncPieceError: error allowed for PWL translation
FuncPieceLength: piece length for PWL translation
FuncPieceRatio: control whether to link function values or to have
pieces below or above the function
FuncPieces: control PWL translation whether to use equal piece length,
to limit error or to limit the total number of pieces

Solution quality (e.g., model.constrVio):

You generally access quality information through Model.printQuality().
Please refer to the Attributes section of the Gurobi Reference Manual for
the full list of quality attributes.

Multi-objectives

ObjN: objectives of multi-objectives
ObjNCon: constant terms of multi-objectives
ObjNPriority: priorities of multi-objectives
ObjNWeight: weights of multi-objectives
ObjNRelTol: relative tolerances of multi-objectives
ObjNAbsTol: absolute tolerances of multi-objectives
ObjNVal: objective value for multi-objectives
ObjNName: names of multi-objectives
NumObj: number of multi-objectives

Multi-scenarios

ScenNLB: modification to lower bound vector in current scenario
ScenNUB: modification to upper bound vector in current scenario
ScenNObj: modification to objective coefficient vector in current scenario
ScenNRHS: modification to right hand side vector in current scenario
ScenNName: name of current scenario
ScenNX: value in current solution of current scenario
ScenNObjBound: objective bound of current scenario
ScenNObjVal: objective value of current solution of current scenario
NumScenarios: number of scenarios in multi-scenario model

Batch Objects

BatchErrorCode: Last error code for this batch request
BatchErrorMessage: Last error string for this batch request
BatchID: String ID for this batch request
BatchStatus: Current status of batch request (help(GRB) gives a list of codes)

# Print Dual solutions
duals = m.getAttr(“Pi”, m.getConstrs())
print(‘dual solutions: %s’ % duals)

dual solutions: [150.0, 150.0, 158.0, 166.0, 174.0, 182.0, 190.0, 198.0, 206.0, 140.0, 140.0, 140.0, 0.0, 0.0, -18.0, -26.0, -24.0, -47.0, -55.0, -63.0, -71.0, 0.0, 0.0, 0.0]

程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com