当前位置:网站首页>[gurobi] establishment of simple model
[gurobi] establishment of simple model
2022-07-04 07:40:00 【Can't learn WOW】
special Gurobi Extended object tuplelist and tupledict
In the modeling process , It is often necessary to select subscript data , Different subscripts are combined . There are two ways to deal with this .
(1) The whole cycle , Multidimensional subscripts mean multiple loops + if Conditions
Such a treatment method is inefficient
(2) Use special Gurobi Extended object TupleList and TupleDict
Python Tuple It is similar to the list , The difference is that the elements of a tuple cannot be modified
tuplelist, It means taking List Containers , The content is Tuple type
for example
Cites = [ (‘A’,‘B’) , (‘A’,‘C’) , (‘B’,‘C’) , (‘B’,‘D’) , (‘C’,‘D’)]
Take this for example ,Cites Indicates the connection between two cities
Need to find to A All connections at the beginning of the city
All circulation methods :
Use Gurobi TupleList Of select Method :
First we need to introduce Gurobi The expansion pack, , Reuse select Method :
Finally, we can take a look at Spyder Type display of :
and TupleDict It means ,Dictionary The container of , But the key is Tuple type
A commonly used function multidict() establish tuplelist and tupledict A shortcut to
In fact, it's easy to see ,cites The element of is the value of the key ,supply Is the first element of the key addition , and demand Is the second element of the key plus
Python grammar : establish list( List of analytical LIst Comprehension)
(1)
(2)
(3)
Python grammar :Generator( generator )
Gurobi Adopted in quicksum, More efficient
for example :
obj = quicksum(cost[i,j]*x[i,j] for i,j in arcs)
This expression is a bit like addition ∑
Gurobi Modeling process
The first example in the tutorial :
use Gurobi, Import expansion pack
Build a model m
Add variables
3,4 Express x yes 3 dimension * 4 dimension
vtype Represents the type of the variable :GRB.BINARY It's binary
name Variable name
Add constraints
Write the contents of the document directly :
Gurobi (gurobi The variables of are generally tupledict type ) Of prod function : It is used to multiply variables and coefficients and accumulate
The following two expressions are equivalent :(x and cost Have the same key value )x It's a variable. cost It's a coefficient
obj = quicksum(cost[i,j] * x[i,j] for i,j in arcs)
obj = x.prod(cost)
Specific modeling process
m.Model() Build a model framework
Add variables
Set the objective function
Set constraints
Set the set of subscripts
Index or search some of the following tables
Add, subtract, multiply, divide
Comparative symbols
Gurobi Modeling examples 1
# Import gurobi package
from gurobipy import *
try:
# Create a new model
m = gurobipy.Model("class_1_1")
# Add variables
x = m.addVar(vtype = GRB.BINARY,name ="x")
y = m.addVar(vtype = GRB.BINARY,name ="y")
z = m.addVar(vtype = GRB.BINARY,name ="z")
# Set the target
m.setObjective(x + y +2*z,GRB.MAXIMIZE)
# Add restrictions
m.addConstr(x + 2*y + 3*z <=4,"c0")
m.addConstr(x + y >= 1)
# Perform optimization
m.optimize()
# Results show
# View variable values
# A variable called VarName Variable value is X
for v in m.getVars():
print('%s %g' % (v.VarName, v.X))
# Just check the value of the objective function , use ObjVal
print('Obj: %g' % m.ObjVal)
except GurobiError as e:
print('Error code '+ str(e.errno) + ' : '+ str(e))
except AttributeError:
print('Encountered an attribute error')
Gurobi Modeling examples 2
There are upper and lower limits of nutrient absorption every day .
that Gurobi The search form of can be
Nutrient types can be used tuplelist Storage
[‘calories’, ‘protein’, ‘fat’, ‘sodium’]
The minimum daily intake of various nutrients can be tupledict Storage
{‘calories’: 1800, ‘protein’: 91, ‘fat’: 0, ‘sodium’: 0}
The maximum daily intake of various nutrients is also used tupledict Storage
{‘calories’: 2200, ‘protein’: 1e+100, ‘fat’: 65, ‘sodium’: 1779}
At this point, we can use the function multidict function
# There are upper and lower limits of nutrient absorption every day
categories, minNutrition, maxNutrition = multidict({
'calories':[1800, 2200],
'protein':[91,GRB.INFINITY],
'fat':[0,65],
'sodium':[0,1779]
})
The price of food per unit weight is different
Similarly, we want to get a list of food , At the same time, I want to get the price of the food , So for the unit food price , You can also use multidict function
foods,cost = multidict({
'hamburger': 2.49,
'chicken': 2.89,
'hot dog': 1.50,
'fries': 1.89,
'macaroni': 2.09,
'pizza': 1.99,
'salad': 2.49,
'milk': 0.89,
'ice cream': 1.59
})
Different nutritional components of unit food are different
It can be expressed through two-dimensional keys
(‘ food ’,‘ Nutrition category ’): Component content ;
nutritionValues = {
('hamburger', 'calories'): 410,
('hamburger', 'protein'): 24,
('hamburger', 'fat'): 26,
('hamburger', 'sodium'): 730,
('chicken', 'calories'): 420,
('chicken', 'protein'): 32,
('chicken', 'fat'): 10,
('chicken', 'sodium'): 1190,
('hot dog', 'calories'): 560,
('hot dog', 'protein'): 20,
('hot dog', 'fat'): 32,
('hot dog', 'sodium'): 1800,
('fries', 'calories'): 380,
('fries', 'protein'): 4,
('fries', 'fat'): 19,
('fries', 'sodium'): 270,
('macaroni', 'calories'): 320,
('macaroni', 'protein'): 12,
('macaroni', 'fat'): 10,
('macaroni', 'sodium'): 930,
('pizza', 'calories'): 320,
('pizza', 'protein'): 15,
('pizza', 'fat'): 12,
('pizza', 'sodium'): 820,
('salad', 'calories'): 320,
('salad', 'protein'): 31,
('salad', 'fat'): 12,
('salad', 'sodium'): 1230,
('milk', 'calories'): 100,
('milk', 'protein'): 8,
('milk', 'fat'): 2.5,
('milk', 'sodium'): 125,
('ice cream', 'calories'): 330,
('ice cream', 'protein'): 8,
('ice cream', 'fat'): 10,
('ice cream', 'sodium'): 180}
Add variables
The variable should be the number of purchases of each food
buy = m.addVars(foods, name = “buy”)
buy The categories of are tupledict, and key The type of tuplelist.
Explain it. ,Awaiting model update, When adding variables , We need to do the model to update
So there is no
Dictionary is another variable container model , And can store any type of object .
that key Name for each product , and value We can regard it as the quantity of this commodity
Set the objective function : Cost the least
m.setObjective(quicksum(cost[f]*buy[f] for f in foods),GRB.MINIMIZE)
This kind of writing is easier to understand
When the elements with the same subscript are multiplied , It can be used Gurobi Of prod function .
m.setObjective(cost.prod(buy), GRB.MINIMIZE)
Set constraints : The daily intake of various nutrients is between the upper and lower limits
m.addConstrs((quicksum(nutritionValues[f,c] * buy[f] for f in foods) == [minNutrition, maxNutrition] for c in categories),“con”)
Results show
def PrintSolution():
if m.status == GRB.OPTIMAL:# If the optimal solution is found
print('Cost %g' % m.ObjVal)
for f in foods:
if buy[f].x > 0.0001:# Here we have to pay attention to buy[f] Dega .x Indicates its value
print('%s %g'%(f,buy[f].x))
else:
print('No solution')
PrintSolution()
边栏推荐
- Book list | as the technical support Party of the Winter Olympics, Alibaba cloud's technology is written in these books!
- 大学阶段总结
- Zephyr study notes 2, scheduling
- JVM -- class loading process and runtime data area
- Transition technology from IPv4 to IPv6
- Boosting the Performance of Video Compression Artifact Reduction with Reference Frame Proposals and
- Rhcsa the next day
- Project 1 household accounting software (goal + demand description + code explanation + basic fund and revenue and expenditure details record + realization of keyboard access)
- Chain ide -- the infrastructure of the metauniverse
- [network security] what is emergency response? What indicators should you pay attention to in emergency response?
猜你喜欢
节点基础~节点操作
[network security] what is emergency response? What indicators should you pay attention to in emergency response?
JVM -- class loading process and runtime data area
Used on windows Bat file startup project
University stage summary
深入浅出:了解时序数据库 InfluxDB
Zephyr Learning note 2, Scheduling
How to send mail with Jianmu Ci
在所有SwiftUI版本(1.0-4.0)中原生实现Charts图表视图之思路
Unity 从Inspector界面打开资源管理器选择并记录文件路径
随机推荐
MySQL error resolution - error 1261 (01000): row 1 doesn't contain data for all columns
Flask 常用组件
21个战略性目标实例,推动你的公司快速发展
Literature collation and thesis reading methods
System architecture design of circle of friends
How to write a summary of the work to promote the implementation of OKR?
[untitled] notice on holding "2022 traditional fermented food and modern brewing technology"
Unity 从Inspector界面打开资源管理器选择并记录文件路径
University stage summary
It's healthy to drink medicinal wine like this. Are you drinking it right
Guoguo took you to write a linked list, and the primary school students said it was good after reading it
BasicVSR++: Improving Video Super-Resolutionwith Enhanced Propagation and Alignment
Rhcsa day 3
Easy to understand: understand the time series database incluxdb
Transition technology from IPv4 to IPv6
Practice (9-12 Lectures)
Enter the year, month, and determine the number of days
Adaptive spatiotemporal fusion of multi-target networks for compressed video perception enhancement
L1-021 important words three times (5 points)
The frost peel off the purple dragon scale, and the xiariba people will talk about database SQL optimization and the principle of indexing (primary / secondary / clustered / non clustered)