当前位置:网站首页>[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()
边栏推荐
- The cloud native programming challenge ended, and Alibaba cloud launched the first white paper on application liveliness technology in the field of cloud native
- Introduction to sap commerce cloud B2B organization function
- Zephyr Learning note 2, Scheduling
- Write a thread pool by hand, and take you to learn the implementation principle of ThreadPoolExecutor thread pool
- 21个战略性目标实例,推动你的公司快速发展
- Relations courantes de la fiche de données d'exploitation pour les activités
- Handwritten easy version flexible JS and source code analysis
- 2022-021ARTS:下半年开始
- L1-028 judging prime number (10 points)
- Distributed transaction management DTM: the little helper behind "buy buy buy"
猜你喜欢
Google's official response: we have not given up tensorflow and will develop side by side with Jax in the future
大厂技术专家:架构设计中常用的思维模型
User login function: simple but difficult
果果带你写链表,小学生看了都说好
zabbix 5.0监控客户端
Go learning notes - constants
Unity opens the explorer from the inspector interface, selects and records the file path
谷歌官方回应:我们没有放弃TensorFlow,未来与JAX并肩发展
MySQL中的文本處理函數整理,收藏速查
Solution of running crash caused by node error
随机推荐
[C language] open the door of C
What are the work contents of operation and maintenance engineers? Can you list it in detail?
Project 1 household accounting software (goal + demand description + code explanation + basic fund and revenue and expenditure details record + realization of keyboard access)
博客停更声明
节点基础~节点操作
Zephyr 学习笔记2,Scheduling
Unity opens the explorer from the inspector interface, selects and records the file path
A real penetration test
Leetcode (215) -- the kth largest element in the array
人生规划(Flag)
L1-028 judging prime number (10 points)
Distributed transaction management DTM: the little helper behind "buy buy buy"
时序数据库 InfluxDB 2.2 初探
Zephyr study notes 2, scheduling
两年前美国芯片扭捏着不卖芯片,如今芯片堆积如山祈求中国帮忙
NLP literature reading summary
Zephyr 學習筆記2,Scheduling
tornado项目之路由装饰器
User login function: simple but difficult
Implementation of ZABBIX agent active mode