Python3+Gurobi使用教程(一)

Stella981
• 阅读 435

Gurobi使用教程

###1.Gurobi使用的一般框架

from gurobipy import *
try:
    m=Model('modelname')
        
except GurobiError:
    print('Error reported')

###2.Gurobi读取数据求解 假设给定三个文件,分别是categories.txt,foodcost.txt以及nutritionvalues.txt,分别存放每天营养摄取的上限和下限,每种食物的价格以及每种食物所含的营养成分,其中categories.txt中的数据如下(注意文件最后有换行):

calories 1800 2200
protein 91 1.00E+100
fat 0 65
sodium 0 1779

读取该文件的代码如下:

file = open("./categories.txt","r")   #设置文件对象
nutrition=[]
maxNut={}
minNut={}
for line in file.readlines():                          #依次读取每行  
    line = line.strip('')                             #去掉每行头尾空白  
    line = line[:-1]     #去掉换行符,也可以不去,这样最后一个数据要求也要换行
    str1=line.split(" ")[0]
    nutrition.append(str1)
    str2=line.split(" ")[1]
    minNut[str1]=float(str2)
    str3=line.split(" ")[2]
    maxNut[str1]=float(str3)
    
    
print(nutrition)
print(minNut)
print(maxNut)
print(minNut['fat'])
[print(minNut[x]) for x in nutrition]
file.close() 

foodcost.txt中的数据如下(文件最后有换行):

hamburger 2.49
chicken 2.89
hotdog 1.50
fries 1.89
macaroni 2.09
pizza 1.99
salad 2.49
milk 0.89
icecream 1.59

读取该文件的代码如下:

file = open("./foodcost.txt","r")   #设置文件对象
food=[]
cost={}
for line in file.readlines():                          #依次读取每行  
    line = line.strip('')                             #去掉每行头尾空白  
    line = line[:-1]     #去掉换行符,也可以不去,这样最后一个数据要求也要换行
    print("读取的数据为: %s" % (line))
    str1=line.split(" ")[0]
    food.append(str1)
    str2=line.split(" ")[1]
    cost[str1]=float(str2)
print(cost)
file.close() 

nutritionvalues.txt中的数据如下(文件最后有换行)

410
420
560
380
320
320
320
100
330
24
32
20
4
12
15
31
8
8
26
10
32
19
10
12
12
2.5
10
730
1190
1800
270
930
820
1230
125
180

读取该文件的代码如下:

file = open("./nutritionvalues.txt","r")   #设置文件对象
nutritionval=[]
food=['hamburger','chicken','hotdog','fries','macaroni','pizza','salad','milk','icecream']
for line in file.readlines():                          #依次读取每行  
    line = line.strip('')                             #去掉每行头尾空白  
    line = line[:-1]     #去掉换行符,也可以不去,这样最后一个数据要求也要换行
    print("读取的数据为: %s" % (line))
    str1=line.split(" ")[0]
    nutritionval.append(str1)
print(nutritionval)
nutritionvalue={}
i=0
for x in nutrition:
    for y in food:    
        nutritionvalue[y,x]=float(nutritionval[i])
        i=i+1
        print(nutritionvalue[y,x])
for x in food:
    for y in nutrition:
        print(nutritionvalue[x,y])
file.close() 

因此最后程序为

from gurobipy import *
import numpy as np
file = open("./categories.txt","r")   #设置文件对象
nutrition=[]
maxNut={}
minNut={}
for line in file.readlines():                          #依次读取每行  
    line = line.strip('')                             #去掉每行头尾空白  
    line = line[:-1]     #去掉换行符,也可以不去,这样最后一个数据要求也要换行
    str1=line.split(" ")[0]
    nutrition.append(str1)
    str2=line.split(" ")[1]
    minNut[str1]=float(str2)
    str3=line.split(" ")[2]
    maxNut[str1]=float(str3)

file.close() 


file = open("./foodcost.txt","r")   #设置文件对象
food=[]
cost={}
for line in file.readlines():                          #依次读取每行  
    line = line.strip('')                             #去掉每行头尾空白  
    line = line[:-1]     #去掉换行符,也可以不去,这样最后一个数据要求也要换行
    str1=line.split(" ")[0]
    food.append(str1)
    str2=line.split(" ")[1]
    cost[str1]=float(str2)

file.close() 

file = open("./nutritionvalues.txt","r")   #设置文件对象

nutritionval=[]
food=['hamburger','chicken','hotdog','fries','macaroni','pizza','salad','milk','icecream']
for line in file.readlines():                          #依次读取每行  
    line = line.strip('')                             #去掉每行头尾空白  
    line = line[:-1]     #去掉换行符,也可以不去,这样最后一个数据要求也要换行
    str1=line.split(" ")[0]
    nutritionval.append(str1)

nutritionvalue={}
i=0
for x in nutrition:
    for y in food:    
        nutritionvalue[y,x]=float(nutritionval[i])
        i=i+1

file.close() 

def printSolution():
    if m.status == GRB.Status.OPTIMAL:
        print('\nCost: %g' % m.objVal)
        print('\nBuy:')
        buyx = m.getAttr('x', buy)
        for f in food:
            if buy[f].x > 0.0001:
                print('%s%g' % (f, buyx[f]))
    else:
        print('No solution')




try:
    m=Model('modelname')
    buy=m.addVars(food,name="buy")
    m.setObjective(buy.prod(cost),GRB.MINIMIZE)
    m.addConstrs(
            (quicksum(nutritionvalue[f,c]*buy[f] for f in food)==
            [minNut[c],maxNut[c]]
            for c in nutrition),"_"
            )
    m.write("diet.lp")#写入lp文件
    m.optimize()
    printSolution()
except GurobiError:
    print('Error reported')
点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Karen110 Karen110
2年前
一篇文章带你了解JavaScript日期
日期对象允许您使用日期(年、月、日、小时、分钟、秒和毫秒)。一、JavaScript的日期格式一个JavaScript日期可以写为一个字符串:ThuFeb02201909:59:51GMT0800(中国标准时间)或者是一个数字:1486000791164写数字的日期,指定的毫秒数自1970年1月1日00:00:00到现在。1\.显示日期使用
Jacquelyn38 Jacquelyn38
2年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
待兔 待兔
2年前
HashMap的使用教程
HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22
Souleigh ✨ Souleigh ✨
2年前
前端性能优化 - 雅虎军规
无论是在工作中,还是在面试中,web前端性能的优化都是很重要的,那么我们进行优化需要从哪些方面入手呢?可以遵循雅虎的前端优化35条军规,这样对于优化有一个比较清晰的方向.35条军规1.尽量减少HTTP请求个数——须权衡2.使用CDN(内容分发网络)3.为文件头指定Expires或CacheControl,使内容具有缓存性。4.避免空的
Wesley13 Wesley13
2年前
Java爬虫之JSoup使用教程
title:Java爬虫之JSoup使用教程date:201812248:00:000800update:201812248:00:000800author:mecover:https://imgblog.csdnimg.cn/20181224144920712(https://www.oschin
Stella981 Stella981
2年前
FFmpeg使用教程(一)
ffmpeg是一个开源的音视频转码工具,它提供了录制、转换以及流化音视频的完整解决方案,可以转码、压制、提取、截取、合并、录屏等。一、下载FFmpeg下载地址:http://ffmpeg.zeranoe.com/builds/(https://www.oschina.net/action/GoToLink?urlhttps%3A%2F
Easter79 Easter79
2年前
Twitter的分布式自增ID算法snowflake (Java版)
概述分布式系统中,有一些需要使用全局唯一ID的场景,这种时候为了防止ID冲突可以使用36位的UUID,但是UUID有一些缺点,首先他相对比较长,另外UUID一般是无序的。有些时候我们希望能使用一种简单一些的ID,并且希望ID能够按照时间有序生成。而twitter的snowflake解决了这种需求,最初Twitter把存储系统从MySQL迁移
Stella981 Stella981
2年前
HQChart使用教程1
@TOC(快速创建一个K线图页面)效果图!在这里插入图片描述(https://imgblog.csdnimg.cn/20190516213202367.png?xossprocessimage/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4
为什么mysql不推荐使用雪花ID作为主键
作者:毛辰飞背景在mysql中设计表的时候,mysql官方推荐不要使用uuid或者不连续不重复的雪花id(long形且唯一),而是推荐连续自增的主键id,官方的推荐是auto_increment,那么为什么不建议采用uuid,使用uuid究