Efficient way to add variables and constraints through Gurobi Python without enumerating through all elements

Nazanin Zinouri

I am learning to build optimization models through Gurobi python and I am having some issues finding the pythonic way of defining decision variables and constraints:

Assuming I have these sets:

time={morning, afternoon, evening};
interval={early,late};
food={burger, banana, apple, orange};

and my decision variable is binary eat[time,interval,food]. However I only have a defined set of possible options as below and cannot enumerate all elements of my sets:

time      interval  food  number  value
morning   early   banana   2      500
morning   early   apple    3      600
afternoon early   burger   1      800
evening    late   orane    2      400

so my eat variables can only be the following:

eat[morning,early,banana]
eat[morning,early,apple]
eat[afternoon,early,burger]
eat[evening,late,orange]

and I cannot do:

eat = m.addVars(time, interval, food, name = "Eat", vtype=GRB.BINARY)

I can do something like:

eat = {}
for row in input.to_dict('records'):
         key = (row['time'], row['interval'],row['food'])
         eat[key] =  m.addVar(name = "Eat", vtype=GRB.BINARY)

But I still have trouble defining my objective which is multiplying number and value and eat and I am looking for a more consistent, elegant way:

obj = quicksum(number[i,j,k]*value[i, j, k] * eat[i, j, k] for i in time 
for j in interval for k in food)

The above will enumerate all which is wrong and I tried something like this:

obj = quicksum(number[key]*value[key] * eat[key] \
                 for key in eat)

which limits it to only defined combinations in the dictionary but then I am struggling with constraints when I have to separate elements of dictionary like below:

m.addConstrs(quicksum(eat[i,j,k] for k in food)==1 for i in time for j in interval)

or something like

m.addConstrs(quicksum(eat[morning,j,banana] ==1) for j in interval)

Sorry for the long questions. Any help from optimization/python experts would be great.

Ioannis

It may help you to make use of the tupledict structure the Gurobi Python API has to store the variables. It has some convenient methods which allow you to sum, multiply or slice variables easily. I provide a complete example below.

from gurobipy import GRB, Model
import numpy as np

tuples = [('morning', 'early', 'banana'),('morning', 'early', 'apple'), 
('afternoon', 'early', 'burger'), ('evening', 'late', 'orane')]

numbers, values = [2, 3, 1, 2], [500, 600, 800, 400]

m = Model('SO52451928')

eat = m.addVars(tuples, name='eat', vtype=GRB.BINARY)

coeffs = np.array(numbers) * np.array(values) # Can be made with regular lists as well
coeffs = dict(zip(tuples, coeffs))

obj = eat.prod(coeffs)
m.setObjective(obj)

# This structure holds the unique combinations of (time, interval) that 
# appear in the data. They are necessary, because they form the set over which
# our constraints are defined
time_intervals = set(zip(*zip(*tuples)[:2]))

constrs = m.addConstrs((
    eat.sum(i, j, '*') == 1 for i, j in time_intervals), name='one_food')

m.write(m.ModelName+'.lp')
m.optimize()

if m.SolCount > 0:
    print(zip(m.getAttr(
    'VarName', m.getVars()), m.getAttr('x', m.getVars())))

I hope this helps!

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

print constraints Gurobi Python

Efficient way to loop through GroupBy DataFrame

not all elements appear when iterating through an Enum in python 3

Get all names in TD elements through console

Is there a way to iterate through an array without using loops?

Coverage matrix to covering constraints in Python Gurobi

How to iterate through a tuple list of lists, and get all elements one by one in python?

python iterate through binary file without lines

Iterate through all the files inside a folder in Python

Constraints aren't being added through updateViewConstraints

Python - add new elements to xml without a root?

How to loop through elements and their sub elements in order add or remove classes — Javascript/jQuery

Any way to invoke this Windows volume up/down window through Python?

Python INI to Dictionary - Loop through all items in section

iterating through elements on the same row

Traverse through object and insert elements

selecting elements through Selenium is not working

Is there any way to show elements from a listview one by one and scroll through them?

PonyORM: What is the most efficient way to add new items to a pony database without knowing which items already exist?

How to iterate through a bash list and get all possible combinations of 2 elements?

Iterate through a subset of a Cartesian product where all elements are selected (near-)equally

Loop through all panels in form

Looping through all the cells in a datagridview

Clearing all JTextFields through Function

loop through all files in a folder

Iterate through all possibilities in Julia

Find all routes through a matrix

Is there a way to use the compareTo() method for a data set, without iterating through each element of the set?

Replace all boolean values in a dict by a corresponding value without looping through dict

TOP 一覧

  1. 1

    モーダルダイアログを自動的に閉じる-サーバーコードが完了したら、Googleスプレッドシートのダイアログを閉じます

  2. 2

    セレンのモデルダイアログからテキストを抽出するにはどうすればよいですか?

  3. 3

    CSSのみを使用して三角形のアニメーションを作成する方法

  4. 4

    ドロップダウンリストで選択したアイテムのQComboBoxスタイル

  5. 5

    ZScalerと証明書の問題により、Dockerを使用できません

  6. 6

    PyCharmリモートインタープリターはプロジェクトタブにサイトパッケージのコンテンツを表示しません

  7. 7

    Windows 10でのUSB入力デバイスの挿入/取り外しの検出

  8. 8

    Excel - count multiple words per cell in a range of cells

  9. 9

    PictureBoxで画像のブレンドを無効にする

  10. 10

    Windows 10 Pro 1709を1803、1809、または1903に更新しますか?

  11. 11

    スタート画面にシャットダウンタイルを追加するにはどうすればよいですか?

  12. 12

    Python / SciPyのピーク検出アルゴリズム

  13. 13

    Luaの文字列から特定の特殊文字を削除するにはどうすればよいですか?

  14. 14

    Pythonを使用して、リストからデータを読み取り、特定の値をElasticsearchにインデックス付けするにはどうすればよいですか?

  15. 15

    LinuxでPySide2(Qt for Python)をインストールするQt Designerはどこにありますか?

  16. 16

    goormIDEは、ターミナルがロードするデフォルトプロジェクトを変更します

  17. 17

    QGISとPostGIS(マップポイント(米国の地図上にraduisを使用した緯度と経度)

  18. 18

    MLでのデータ前処理の背後にある直感

  19. 19

    ターミナルから「入力ソースの変更」ショートカットを設定する

  20. 20

    パンダは異なる名前の列に追加します

  21. 21

    同じクラスの異なるバージョンを使用したクラスローディング:java.lang.LinkageError:名前の重複クラス定義を試行しました

ホットタグ

アーカイブ