当前位置:网站首页>[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()
边栏推荐
猜你喜欢

A real penetration test

博客停更声明

Zephyr Learning note 2, Scheduling

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

提升复杂场景三维重建精度 | 基于PaddleSeg分割无人机遥感影像

MySQL中的文本处理函数整理,收藏速查

Used on windows Bat file startup project

两年前美国芯片扭捏着不卖芯片,如今芯片堆积如山祈求中国帮忙

Book list | as the technical support Party of the Winter Olympics, Alibaba cloud's technology is written in these books!

谷歌官方回应:我们没有放弃TensorFlow,未来与JAX并肩发展
随机推荐
Zephyr learning notes 1, threads
Devops Practice Guide - reading notes (long text alarm)
How to reset IntelliSense in vs Code- How to reset intellisense in VS Code?
[Gurobi] 简单模型的建立
How to use MOS tube to realize the anti reverse connection circuit of power supply
Transition technology from IPv4 to IPv6
Google's official response: we have not given up tensorflow and will develop side by side with Jax in the future
L1-021 important words three times (5 points)
Introduction to sap commerce cloud B2B organization function
Improve the accuracy of 3D reconstruction of complex scenes | segmentation of UAV Remote Sensing Images Based on paddleseg
节点基础~节点操作
Introduction to rce in attack and defense world
NLP literature reading summary
Enter the year, month, and determine the number of days
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)
Activiti常见操作数据表关系
jdbc连接es查询的时候,有遇到下面这种情况的大神嘛?
人生规划(Flag)
Take you to master the formatter of visual studio code
Node foundation ~ node operation