8.6. Python API¶
This section provides MindOpt Python API reference. Contents of the Python API are the following:
- 8.6.1. Global functions
- 8.6.2. MindoptError
- 8.6.3. tuplelist
- 8.6.4. tupledict
- 8.6.5. Var
- 8.6.6. MVar
- 8.6.7. PsdVar
- 8.6.8. Constr
- 8.6.9. QConstr
- 8.6.10. SOS
- 8.6.11. GenConstr
- 8.6.12. MConstr
- 8.6.13. MQConstr
- 8.6.14. PsdConstr
- 8.6.15. TempConstr
- 8.6.16. Column
- 8.6.17. LinExpr
- 8.6.18. QuadExpr
- 8.6.19. MLinExpr
- 8.6.20. MQuadExpr
- 8.6.21. PsdExpr
- 8.6.22. Env
- 8.6.23. Model
8.6.24. Examples¶
Diet problem
There are many different kinds of food, each of which can provide various nutrients. How should we make decisions regarding food intake to minimize the amount spent on purchasing food while ensuring that the daily nutritional requirements of the human body are met?
Sets
Food set \(F\)
Nutrient set \(N\)
Parameters
The content of nutrient \(i \in N\) in one unit of food \(j\) is \(a_{ij}\) .
The cost of obtaining one unit of food \(j \in F\) is \(c_j\) .
Decision Variables
\(x_j\) is the amount of food \(j \in F\) that a person consumes daily.
Objective Function
Minimize the total procurement cost of food: \(\text{minimize}~ \sum_{j \in F} c_{j} x_j\) .
Constraints
The nutritional requirement for each nutrient \(i \in N\) must lie between the minimum value \(n_{\min,i}\) and the maximum value \(n_{\max,i}\) : \(n_{\min,i} \le \sum_{j \in F} a_{ij} x_j \le n_{\max,i}, ~~\forall i \in N\) .
from mindoptpy import *
req = \
{
# requirement: ( lower bound, upper bound)
"Cal" : ( 2000, MDO.INFINITY),
"Carbo" : ( 350, 375),
"Protein" : ( 55, MDO.INFINITY),
"VitA" : ( 100, MDO.INFINITY),
"VitC" : ( 100, MDO.INFINITY),
"Calc" : ( 100, MDO.INFINITY),
"Iron" : ( 100, MDO.INFINITY),
"Volume" : (-MDO.INFINITY, 75)
}
food = \
{
# food : ( lower bound, upper bound, cost)
"Cheeseburger" : ( 0, MDO.INFINITY, 1.84),
"HamSandwich" : ( 0, MDO.INFINITY, 2.19),
"Hamburger" : ( 0, MDO.INFINITY, 1.84),
"FishSandwich" : ( 0, MDO.INFINITY, 1.44),
"ChickenSandwich" : ( 0, MDO.INFINITY, 2.29),
"Fries" : ( 0, MDO.INFINITY, 0.77),
"SausageBiscuit" : ( 0, MDO.INFINITY, 1.29),
"LowfatMilk" : ( 0, MDO.INFINITY, 0.60),
"OrangeJuice" : ( 0, MDO.INFINITY, 0.72)
}
req_value = \
{
# (requirement, food ) : value
( "Cal", "Cheeseburger" ) : 510,
( "Cal", "HamSandwich" ) : 370,
( "Cal", "Hamburger" ) : 500,
( "Cal", "FishSandwich" ) : 370,
( "Cal", "ChickenSandwich" ) : 400,
( "Cal", "Fries" ) : 220,
( "Cal", "SausageBiscuit" ) : 345,
( "Cal", "LowfatMilk" ) : 110,
( "Cal", "OrangeJuice" ) : 80,
( "Carbo", "Cheeseburger" ) : 34,
( "Carbo", "HamSandwich" ) : 35,
( "Carbo", "Hamburger" ) : 42,
( "Carbo", "FishSandwich" ) : 38,
( "Carbo", "ChickenSandwich" ) : 42,
( "Carbo", "Fries" ) : 26,
( "Carbo", "SausageBiscuit" ) : 27,
( "Carbo", "LowfatMilk" ) : 12,
( "Carbo", "OrangeJuice" ) : 20,
( "Protein", "Cheeseburger" ) : 28,
( "Protein", "HamSandwich" ) : 24,
( "Protein", "Hamburger" ) : 25,
( "Protein", "FishSandwich" ) : 14,
( "Protein", "ChickenSandwich" ) : 31,
( "Protein", "Fries" ) : 3,
( "Protein", "SausageBiscuit" ) : 15,
( "Protein", "LowfatMilk" ) : 9,
( "Protein", "OrangeJuice" ) : 1,
( "VitA", "Cheeseburger" ) : 15,
( "VitA", "HamSandwich" ) : 15,
( "VitA", "Hamburger" ) : 6,
( "VitA", "FishSandwich" ) : 2,
( "VitA", "ChickenSandwich" ) : 8,
( "VitA", "Fries" ) : 0,
( "VitA", "SausageBiscuit" ) : 4,
( "VitA", "LowfatMilk" ) : 10,
( "VitA", "OrangeJuice" ) : 2,
( "VitC", "Cheeseburger" ) : 6,
( "VitC", "HamSandwich" ) : 10,
( "VitC", "Hamburger" ) : 2,
( "VitC", "FishSandwich" ) : 0,
( "VitC", "ChickenSandwich" ) : 15,
( "VitC", "Fries" ) : 15,
( "VitC", "SausageBiscuit" ) : 0,
( "VitC", "OrangeJuice" ) : 4,
( "VitC", "LowfatMilk" ) : 120,
( "Calc", "Cheeseburger" ) : 30,
( "Calc", "HamSandwich" ) : 20,
( "Calc", "Hamburger" ) : 25,
( "Calc", "FishSandwich" ) : 15,
( "Calc", "ChickenSandwich" ) : 15,
( "Calc", "Fries" ) : 0,
( "Calc", "SausageBiscuit" ) : 20,
( "Calc", "LowfatMilk" ) : 30,
( "Calc", "OrangeJuice" ) : 2,
( "Iron", "Cheeseburger" ) : 20,
( "Iron", "HamSandwich" ) : 20,
( "Iron", "Hamburger" ) : 20,
( "Iron", "FishSandwich" ) : 10,
( "Iron", "ChickenSandwich" ) : 8,
( "Iron", "Fries" ) : 2,
( "Iron", "SausageBiscuit" ) : 15,
( "Iron", "LowfatMilk" ) : 0,
( "Iron", "OrangeJuice" ) : 2,
( "Volume", "Cheeseburger" ) : 4,
( "Volume", "HamSandwich" ) : 7.5,
( "Volume", "Hamburger" ) : 3.5,
( "Volume", "FishSandwich" ) : 5,
( "Volume", "ChickenSandwich" ) : 7.3,
( "Volume", "Fries" ) : 2.6,
( "Volume", "SausageBiscuit" ) : 4.1,
( "Volume", "LowfatMilk" ) : 8,
( "Volume", "OrangeJuice" ) : 12
}
# Create a model
m = Model()
# Add Variables
variable = {}
for food_name, food_data in food.items():
variable[food_name] = m.addVar(
lb=food_data[0], ub=food_data[1], vtype=MDO.CONTINUOUS, name=food_name
)
# Add Constraints
# Ensure that the intake of each nutrient is above the given lower bound and below the given upper bound
cons = {}
for req_name, req_data in req.items():
cons[req_name] = m.addRange(
quicksum(
variable[food_name] * req_value[(req_name, food_name)]
for food_name in food.keys()
),
req_data[0],
req_data[1],
)
# Add Objective Function
objective = quicksum(variable[i] * food[i][2] for i in food.keys())
m.setObjective(objective, MDO.MINIMIZE)
m.optimize()
# Print Result
for i in variable:
print("Amount of " + i + " intake :" + str(variable[i].X))
print("Total meal cost : " + str(objective.getValue()))
for req_name, req_data in req.items():
print(
"Final intake amount of "
+ req_name
+ ": "
+ str(
quicksum(
variable[food_name] * req_value[(req_name, food_name)]
for food_name in food.keys()
).getValue()
)
)
Facility problem
Currently, there are two shopping malls, and the locations of the malls have already been determined. There are several alternative locations for constructing warehouses, whose coordinates and construction costs are known. We assume that the transportation cost from the warehouses to the shopping malls is independent of the quantity of goods but is related to the distance between them. Please find the minimum cost scheme for warehouse construction and transportation.
Sets
Alternative Warehouses \(F\)
Shopping Malls \(M\)
Parameters
The transportation cost from warehouse \(i \in F\) to shopping mall \(j \in M\) is \(a_{ij}\) .
The cost for constructing warehouse \(i \in F\) is \(c_i\) .
The demand for goods at shopping mall \(j \in M\) is \(d_j\) .
Decision Variables
\(x_i\) indicates whether a warehouse is constructed at alternative location \(i \in F\) . It can take a value of 0 or 1, where 0 means not to build and 1 means to build.
\(y_{ij}\) represents the quantity of goods transported from warehouse \(i \in F\) to shopping mall \(j \in M\) .
Objective Function
Minimize the combined cost of warehouse construction and goods transportation:
\(\text{minimize}~ \sum_{i\in F} c_{i}x_i + \sum_{i\in F,j \in M} a_{ij}y_{ij}\)
Constraints
\(\sum_{i\in F} y_{ij} = d_{j}, ~~ \forall j\in M\)
\(x_i d_j - \sum_{k\in M} y_{ik} = 0, ~~ \forall i \in F, j \in M\)
from mindoptpy import *
import math
# The objective of this example is to find the minimum cost solution for warehouse construction and transportation
# There are two shopping malls with fixed locations at (0, 1.7) and (1.4, 2.9), requiring 100 and 200 units of goods weight.
market_info = tupledict([((0, 1.7), 100), ((1.4, 2.9), 200)])
market_keys = list(market_info.keys())
market_num = len(market_info)
# Optional location and construction cost of warehouses
facilities_info = tupledict(
[
((0, 1), 3),
((0, 2), 1),
((1, 0), 1.5),
((1, 1), 1.3),
((1, 2), 1.8),
((2, 0), 1.6),
((2, 1), 1.1),
((2, 2), 1.9),
]
)
facilities_keys = list(facilities_info.keys())
facilities_num = len(facilities_info)
transport_fee_per_m = 1.23
# Create a model
m = Model("Facilities")
# Add Variables
# x represents whether a warehouse is built at this location
x = m.addVars(len(facilities_info), vtype=MDO.BINARY)
# y represents the amount of goods transported from warehouse j to shopping center i.
# The type of values is CONTINUOUS
# The lower bound of 0 represents that it is not possible to transport less than 0 units of goods from warehouse j to shopping center i
provide_quantity = [(i, j) for j in range(facilities_num) for i in range(market_num)]
y = m.addVars(provide_quantity, lb=0, vtype=MDO.CONTINUOUS)
# Add Constraints
# Constraint 1 : ensure that all demand of the shopping centers is satisfied
m.addConstrs(
(
quicksum(y[(i, j)] for j in range(facilities_num))
== market_info[market_keys[i]]
for i in range(market_num)
),
name="is_satisfy",
)
# Constraint 2 : If this warehouse is not constructed, the amount of goods transported from this location must be 0
m.addConstrs(
(
y[(i, j)] / market_info[market_keys[i]] <= x[j]
for i in range(market_num)
for j in range(facilities_num)
),
name="is_built",
)
# Add Objective Function: Minimize the sum of transportation costs and facility construction costs"。
# Assume that the transportation cost from A to B depends only on the distance and is independent of the weight of the goods
def transportation_fee(pos1, pos2):
x1 = pos1[0] - pos2[0]
x2 = pos1[1] - pos2[1]
return math.sqrt(x1 * x1 + x2 * x2) ** 0.5 * transport_fee_per_m
objective1 = quicksum(
x[(i, j)] * facilities_info[facilities_keys[j]] for j in range(facilities_num)
)
objective2 = quicksum(
y[j] * transportation_fee(market_keys[i], facilities_keys[j])
for j in range(facilities_num)
for i in range(market_num)
)
m.setObjective(objective1+objective2, MDO.MINIMIZE)
# Start Optimizing
m.optimize()
# Print Result
for i in x:
if x[i].X:
print(
"A warehouse should build at No."
+ str(i + 1)
+ " location at "
+ str(facilities_keys[i])
)
for j in range(market_num):
print(
"This warehouse transport "
+ str(y[(j, i)].X)
+ " units of goods to "
+ str(j)
+ "supermarkets"
)
WorkForce problem
In a week, the number of workers needed by the factory varies each day. It is currently known how much each worker earns per day and the dates on which they can attend work. The goal is to calculate how to schedule the workers in order to meet the factory’s operational requirements while minimizing wage costs.
Sets:
Days of the week \(D = 1, 2, 3, \ldots, 7\)
Number of workers needed by the factory \(N\)
Workers \(S\)
Parameters:
The number of workers needed by the factory on day \(i \in D\) is \(n_i\) .
The daily wage of worker \(j \in S\) is \(s_j\) .
A sequence indicating the available working times for workers, totaling \(T\) pairs of (worker, day) denoted as \((d_i, t_i)\) , where \(d_i \in S\) and \(t_i \in D\) , for \(i = 1, 2, 3, \ldots, T\) .
Objective Function:
Minimize the total wages paid: \(\text{minimize}~ \sum_{i=1}^{T} x_i s_{d_i}\)
Decision Variables:
\(x_i (i = 1, 2, 3, \ldots, T)\) indicates whether the worker in the available working time sequence shows up on that day. Its values must be 0 or 1, where 0 indicates the worker does not attend, and 1 indicates the worker does attend.
Constraints:
\(\sum_{d_i=r} x_i = n_{r}, ~~\forall r\in D\)
from mindoptpy import *
# Number of required workers for each day
day_name, workers_per_day = multidict(
{
"Monday": 3,
"Tuesday": 1,
"Wednesday": 4,
"Thursday": 2,
"Friday": 1,
"Saturday": 3,
"Sunday": 3,
}
)
# Daily wage of each worker
workers, pay = multidict(
{
"Xiaoming": 13,
"Huahua": 10,
"HongHong": 11,
"Dahua": 8,
"Lihua": 9,
"Niuniu": 14,
"Gouzi": 14,
}
)
# Available days for each worker
availability = tuplelist(
[
("Xiaoming", "Tuesday"),
("Xiaoming", "Wednesday"),
("Xiaoming", "Friday"),
("Xiaoming", "Sunday"),
("Huahua", "Monday"),
("Huahua", "Tuesday"),
("Huahua", "Friday"),
("Huahua", "Saturday"),
("HongHong", "Wednesday"),
("HongHong", "Thursday"),
("HongHong", "Friday"),
("HongHong", "Sunday"),
("Dahua", "Tuesday"),
("Dahua", "Wednesday"),
("Dahua", "Friday"),
("Dahua", "Saturday"),
("Lihua", "Monday"),
("Lihua", "Tuesday"),
("Lihua", "Wednesday"),
("Lihua", "Thursday"),
("Lihua", "Friday"),
("Lihua", "Sunday"),
("Niuniu", "Monday"),
("Niuniu", "Tuesday"),
("Niuniu", "Wednesday"),
("Niuniu", "Saturday"),
("Gouzi", "Monday"),
("Gouzi", "Tuesday"),
("Gouzi", "Wednesday"),
("Gouzi", "Friday"),
("Gouzi", "Saturday"),
("Gouzi", "Sunday"),
]
)
# Create a model
m = Model('WorkForce')
# Add Variables
# x[(worker, day)] represents whether this worker is scheduled for this day.
# Using worker-day pair to initialize variables ensure that each person works only at the time they are available
x = m.addVars(availability, vtype=MDO.BINARY, name="schedule")
# Add Constraints
# Constraint : ensure that each day has enough workforce
c1 = m.addConstrs((x.sum("*", day) == workers_per_day[day] for day in day_name))
# Add Objective Function
objective = quicksum(
pay[worker_day[0]] * x[(worker_day[0], worker_day[1])]
for worker_day in availability
)
m.setObjective(objective, MDO.MINIMIZE)
# Start Optimizing
m.optimize()
# Print Result
for worker, day in availability:
if x[(worker, day)].X:
print(worker + " should work at " + day)
print("The total cost is " + str(objective.getValue()))