当前位置:网站首页>[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()
边栏推荐
- 时序数据库 InfluxDB 2.2 初探
- OKR vs. KPI 一次搞清楚这两大概念!
- Basic DOS commands
- 节点基础~节点操作
- Detailed introduction to the big changes of Xcode 14
- This article is enough for learning advanced mysql
- Is l1-029 too fat (5 points)
- Would you like to go? Go! Don't hesitate if you like it
- Go learning notes - constants
- [Mori city] random talk on GIS data (I)
猜你喜欢

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)

There is no Chinese prompt below when inputting text in win10 Microsoft Pinyin input method

L1-027 rental (20 points)

Technical experts from large factories: common thinking models in architecture design

Oceanbase is the leader in the magic quadrant of China's database in 2021

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

大厂技术专家:架构设计中常用的思维模型

Rhcsa day 3

The cloud native programming challenge ended, and Alibaba cloud launched the first white paper on application liveliness technology in the field of cloud native

A real penetration test
随机推荐
Blue Bridge Cup Quick sort (code completion)
手写简易版flexible.js以及源码分析
OKR vs. KPI 一次搞清楚这两大概念!
Transition technology from IPv4 to IPv6
Devops Practice Guide - reading notes (long text alarm)
MySQL error resolution - error 1261 (01000): row 1 doesn't contain data for all columns
Distributed transaction management DTM: the little helper behind "buy buy buy"
MySQL 数据库 - 函数 约束 多表查询 事务
Take you to master the formatter of visual studio code
Node foundation ~ node operation
BUUCTF(3)
大厂技术专家:架构设计中常用的思维模型
MYCAT middleware installation and use
Activiti常见操作数据表关系
L1-021 important words three times (5 points)
[real case] how to deal with the failure of message consumption?
Thesis learning -- time series similarity query method based on extreme point characteristics
Docker install MySQL
L1-030 one gang one (15 points)
How to buy financial products in 2022?