当前位置:网站首页>[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()
边栏推荐
- Handwritten easy version flexible JS and source code analysis
- Oracle stored procedures and functions
- Unity 从Inspector界面打开资源管理器选择并记录文件路径
- Relations courantes de la fiche de données d'exploitation pour les activités
- Rapidjson reading and writing JSON files
- Easy to understand: understand the time series database incluxdb
- Xcode 14之大变化详细介绍
- MySQL 数据库 - 函数 约束 多表查询 事务
- Detailed introduction to the big changes of Xcode 14
- BUUCTF(4)
猜你喜欢

Amd RX 7000 Series graphics card product line exposure: two generations of core and process mix and match

Summary of MySQL common judgment functions!! Have you used it
![[kubernetes series] kubesphere is installed on kubernetes](/img/2b/eb39cf78b3bb9908b01f279e2f9958.png)
[kubernetes series] kubesphere is installed on kubernetes

Zhanrui tankbang | jointly build, cooperate and win-win zhanrui core ecology

Heap concept in JVM

The idea of implementing charts chart view in all swiftui versions (1.0-4.0) was born

论文学习——基于极值点特征的时间序列相似性查询方法

时序数据库 InfluxDB 2.2 初探

在所有SwiftUI版本(1.0-4.0)中原生实现Charts图表视图之思路
![[Mori city] random talk on GIS data (I)](/img/e4/2a2ceb10a2c0285cdd0c922f827930.png)
[Mori city] random talk on GIS data (I)
随机推荐
Directory of tornado
Adaptive spatiotemporal fusion of multi-target networks for compressed video perception enhancement
I was pressed for the draft, so let's talk about how long links can be as efficient as short links in the development of mobile terminals
SQL foundation 9 [grouping data]
BUUCTF(3)
Detailed introduction to the big changes of Xcode 14
It's healthy to drink medicinal wine like this. Are you drinking it right
[web security] nodejs prototype chain pollution analysis
Improve the accuracy of 3D reconstruction of complex scenes | segmentation of UAV Remote Sensing Images Based on paddleseg
L1-027 rental (20 points)
Life planning (flag)
两年前美国芯片扭捏着不卖芯片,如今芯片堆积如山祈求中国帮忙
The IP bound to the socket is inaddr_ The meaning of any htonl (inaddr_any) (0.0.0.0 all addresses, uncertain addresses, arbitrary addresses)
MYCAT middleware installation and use
zabbix监控系统部署
Enter the year, month, and determine the number of days
Handwritten easy version flexible JS and source code analysis
NLP literature reading summary
Rhcsa the next day
Oracle-存储过程与函数