Build a simple model
To start, you'll solve a simple optimization problem with Pyoframe.
Problem statement
Imagine you're a vegetarian hesitating between tofu and chickpeas as a source of protein for tomorrow's dinner. You'd like to spend as little money as possible while still consuming at least 50 grams of protein. How many blocks of tofu ($4 each, 18g of protein) and cans of chickpeas ($3 each, 15g of protein) should you buy?
Click on the buttons below to understand the code, and then run it on your computer.
import pyoframe as pf
m = pf.Model()
# You can buy tofu or chickpeas
m.tofu_blocks = pf.Variable(lb=0, vtype="integer") # (1)!
m.chickpea_cans = pf.Variable(lb=0, vtype="integer")
# You want to minimize your cost
m.minimize = 4 * m.tofu_blocks + 3 * m.chickpea_cans # (2)!
# But still consume enough protein
m.protein_constraint = 18 * m.tofu_blocks + 15 * m.chickpea_cans >= 50 # (3)!
m.optimize() # (4)!
print("Tofu blocks:", m.tofu_blocks.solution)
print("Chickpea cans:", m.chickpea_cans.solution)
-
lb=0
set a lower bound so that you can't buy negative amounts of tofu.vtype="integer"
ensures that you can't buy a fraction of a block. -
minimize
andmaximize
are reserved variable names that can be used to set the objective. - Pyoframe constraints are easily created with the
<=
,>=
, or==
operators. - Pyoframe automatically detects the solver you have installed; no need to specify it!
After running the code you should get:
On the next page, you'll integrate DataFrames into your solution.
Comments