{ "cells": [ { "cell_type": "markdown", "id": "8993fc4a", "metadata": {}, "source": [ "\n", "*This notebook contains material from [CBE60499](https://ndcbe.github.io/CBE60499);\n", "content is available [on Github](git@github.com:ndcbe/CBE60499.git).*\n" ] }, { "cell_type": "markdown", "id": "550b4923", "metadata": {}, "source": [ "\n", "< [2.9 Supplementary material: data for parmest tutorial](https://ndcbe.github.io/CBE60499/02.09-Parmest-generate-data.html) | [Contents](toc.html) | [Tag Index](tag_index.html) | [2.11 Pyomo Homework 2](https://ndcbe.github.io/CBE60499/02.11-Pyomo2.html) >
"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "7b6dea24",
"metadata": {},
"outputs": [],
"source": [
"# IMPORT DATA FILES USED BY THIS NOTEBOOK\n",
"import os, requests\n",
"\n",
"file_links = [(\"data/knapsack_data.csv\", \"https://ndcbe.github.io/CBE60499/data/knapsack_data.csv\")]\n",
"\n",
"# This cell has been added by nbpages. Run this cell to download data files required for this notebook.\n",
"\n",
"for filepath, fileurl in file_links:\n",
" stem, filename = os.path.split(filepath)\n",
" if stem:\n",
" if not os.path.exists(stem):\n",
" os.mkdir(stem)\n",
" if not os.path.isfile(filepath):\n",
" with open(filepath, 'wb') as f:\n",
" response = requests.get(fileurl)\n",
" f.write(response.content)\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbpages": {
"level": 1,
"link": "[2.10 Pyomo Homework 1](https://ndcbe.github.io/CBE60499/02.10-Pyomo1.html#2.10-Pyomo-Homework-1)",
"section": "2.10 Pyomo Homework 1"
}
},
"source": [
"# 2.10 Pyomo Homework 1\n",
"\n",
"**Due Date:** 2/16/2021"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"nbpages": {
"level": 1,
"link": "[2.10 Pyomo Homework 1](https://ndcbe.github.io/CBE60499/02.10-Pyomo1.html#2.10-Pyomo-Homework-1)",
"section": "2.10 Pyomo Homework 1"
}
},
"outputs": [],
"source": [
"# This code cell installs packages on Colab\n",
"\n",
"import sys\n",
"if \"google.colab\" in sys.modules:\n",
" !wget \"https://raw.githubusercontent.com/ndcbe/CBE60499/main/notebooks/helper.py\"\n",
" import helper\n",
" helper.install_idaes()\n",
" helper.install_ipopt()\n",
" helper.install_glpk()\n",
" helper.download_data(['knapsack_data.xlsx','knapsack_data.csv'])"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"nbpages": {
"level": 1,
"link": "[2.10 Pyomo Homework 1](https://ndcbe.github.io/CBE60499/02.10-Pyomo1.html#2.10-Pyomo-Homework-1)",
"section": "2.10 Pyomo Homework 1"
}
},
"outputs": [],
"source": [
"## IMPORT LIBRARIES\n",
"from pyomo.environ import *\n",
"import pandas as pd"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbpages": {
"level": 1,
"link": "[2.10 Pyomo Homework 1](https://ndcbe.github.io/CBE60499/02.10-Pyomo1.html#2.10-Pyomo-Homework-1)",
"section": "2.10 Pyomo Homework 1"
}
},
"source": [
"Special thanks to the Pyomo team for create these excercises as part of their excellent PyomoFest workshop."
]
},
{
"cell_type": "markdown",
"metadata": {
"nbpages": {
"level": 2,
"link": "[2.10.1 Pyomo Fundamentals](https://ndcbe.github.io/CBE60499/02.10-Pyomo1.html#2.10.1-Pyomo-Fundamentals)",
"section": "2.10.1 Pyomo Fundamentals"
}
},
"source": [
"## 2.10.1 Pyomo Fundamentals"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbpages": {
"level": 3,
"link": "[2.10.1.1 Knapsack example](https://ndcbe.github.io/CBE60499/02.10-Pyomo1.html#2.10.1.1-Knapsack-example)",
"section": "2.10.1.1 Knapsack example"
}
},
"source": [
"### 2.10.1.1 Knapsack example\n",
"\n",
"Solve the knapsack problem given below using GLPK and answer the following questions:\n",
"\n",
"1. Which items are acquired in the optimal solution?\n",
"\n",
"2. What is the value of the selected items?"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"nbpages": {
"level": 3,
"link": "[2.10.1.1 Knapsack example](https://ndcbe.github.io/CBE60499/02.10-Pyomo1.html#2.10.1.1-Knapsack-example)",
"section": "2.10.1.1 Knapsack example"
}
},
"outputs": [],
"source": [
"A = ['hammer', 'wrench', 'screwdriver', 'towel']\n",
"b = {'hammer':8, 'wrench':3, 'screwdriver':6, 'towel':11}\n",
"w = {'hammer':5, 'wrench':7, 'screwdriver':4, 'towel':3}\n",
"W_max = 14\n",
"\n",
"model = ConcreteModel()\n",
"model.x = Var( A, within=Binary )\n",
"\n",
"model.obj = Objective(\n",
" expr = sum( b[i]*model.x[i] for i in A ), \n",
" sense = maximize )\n",
"\n",
"model.weight_con = Constraint(\n",
" expr = sum( w[i]*model.x[i] for i in A ) <= W_max )\n",
"\n",
"# YOUR SOLUTION HERE\n",
"\n",
"model.display()"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbpages": {
"level": 3,
"link": "[2.10.1.1 Knapsack example](https://ndcbe.github.io/CBE60499/02.10-Pyomo1.html#2.10.1.1-Knapsack-example)",
"section": "2.10.1.1 Knapsack example"
}
},
"source": [
"**Question Answers**\n",
"\n",
"1. *Fill in here*\n",
"\n",
"2. *Fill in here*"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbpages": {
"level": 3,
"link": "[2.10.1.2 Knapsack example with improve printing](https://ndcbe.github.io/CBE60499/02.10-Pyomo1.html#2.10.1.2-Knapsack-example-with-improve-printing)",
"section": "2.10.1.2 Knapsack example with improve printing"
}
},
"source": [
"### 2.10.1.2 Knapsack example with improve printing\n",
"\n",
"Complete the missing lines in the code below to produce formatted output: print the total weight, the value of the items selected (the objective), and the items acquired in the optimal solution. Note, the Pyomo value function should be used to get the floating point value of Pyomo modeling components (e.g., print(value(model.x[i]))."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"nbpages": {
"level": 3,
"link": "[2.10.1.2 Knapsack example with improve printing](https://ndcbe.github.io/CBE60499/02.10-Pyomo1.html#2.10.1.2-Knapsack-example-with-improve-printing)",
"section": "2.10.1.2 Knapsack example with improve printing"
}
},
"outputs": [],
"source": [
"A = ['hammer', 'wrench', 'screwdriver', 'towel']\n",
"b = {'hammer':8, 'wrench':3, 'screwdriver':6, 'towel':11}\n",
"w = {'hammer':5, 'wrench':7, 'screwdriver':4, 'towel':3}\n",
"W_max = 14\n",
"\n",
"model = ConcreteModel()\n",
"model.x = Var( A, within=Binary )\n",
"\n",
"model.obj = Objective(\n",
" expr = sum( b[i]*model.x[i] for i in A ), \n",
" sense = maximize )\n",
"\n",
"model.weight_con = Constraint(\n",
" expr = sum( w[i]*model.x[i] for i in A ) <= W_max )\n",
"\n",
"opt = SolverFactory('glpk')\n",
"opt_success = opt.solve(model)\n",
"\n",
"total_weight = sum( w[i]*value(model.x[i]) for i in A )\n",
"# YOUR SOLUTION HERE\n",
"print('-------------------------')"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbpages": {
"level": 3,
"link": "[2.10.1.3 Changing data](https://ndcbe.github.io/CBE60499/02.10-Pyomo1.html#2.10.1.3-Changing-data)",
"section": "2.10.1.3 Changing data"
}
},
"source": [
"### 2.10.1.3 Changing data\n",
"\n",
"Using your code from **Question 1.2**, if we were to increase the value of the wrench, at what point would it become selected as part of the optimal solution?"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"nbpages": {
"level": 3,
"link": "[2.10.1.3 Changing data](https://ndcbe.github.io/CBE60499/02.10-Pyomo1.html#2.10.1.3-Changing-data)",
"section": "2.10.1.3 Changing data"
}
},
"outputs": [],
"source": [
"# YOUR SOLUTION HERE"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbpages": {
"level": 3,
"link": "[2.10.1.3 Changing data](https://ndcbe.github.io/CBE60499/02.10-Pyomo1.html#2.10.1.3-Changing-data)",
"section": "2.10.1.3 Changing data"
}
},
"source": [
"**Question Answer**\n",
"\n",
"*Fill in here*"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbpages": {
"level": 3,
"link": "[2.10.1.4 Loading data from Excel](https://ndcbe.github.io/CBE60499/02.10-Pyomo1.html#2.10.1.4-Loading-data-from-Excel)",
"section": "2.10.1.4 Loading data from Excel"
}
},
"source": [
"### 2.10.1.4 Loading data from Excel\n",
"\n",
"In the code above, the data is hardcoded at the top of the file. Instead of hardcoding the data, use Python to load the data from a difference source. You may use Pandas to load data from 'knapsack_data.xlsx' into a dataframe. You will then need to write code to obtain a dictionary from the dataframe."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"nbpages": {
"level": 3,
"link": "[2.10.1.4 Loading data from Excel](https://ndcbe.github.io/CBE60499/02.10-Pyomo1.html#2.10.1.4-Loading-data-from-Excel)",
"section": "2.10.1.4 Loading data from Excel"
}
},
"outputs": [],
"source": [
"df_items = pd.read_excel('./data/knapsack_data.xlsx', sheet_name='data', header=0, index_col=0)\n",
"W_max = 14\n",
"\n",
"A = df_items.index.tolist()\n",
"# YOUR SOLUTION HERE\n",
"\n",
"model = ConcreteModel()\n",
"model.x = Var( A, within=Binary )\n",
"\n",
"model.obj = Objective(\n",
" expr = sum( b[i]*model.x[i] for i in A ), \n",
" sense = maximize )\n",
"\n",
"model.weight_con = Constraint(\n",
" expr = sum( w[i]*model.x[i] for i in A ) <= W_max )\n",
"\n",
"opt = SolverFactory('glpk')\n",
"opt_success = opt.solve(model)\n",
"\n",
"total_weight = sum( w[i]*value(model.x[i]) for i in A )\n",
"print('Total Weight:', total_weight)\n",
"print('Total Benefit:', value(model.obj))\n",
"\n",
"print('%12s %12s' % ('Item', 'Selected'))\n",
"print('=========================')\n",
"for i in A:\n",
" acquired = 'No'\n",
" if value(model.x[i]) >= 0.5:\n",
" acquired = 'Yes'\n",
" print('%12s %12s' % (i, acquired))\n",
"print('-------------------------')"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbpages": {
"level": 3,
"link": "[2.10.1.5 NLP vs. MIP](https://ndcbe.github.io/CBE60499/02.10-Pyomo1.html#2.10.1.5-NLP-vs.-MIP)",
"section": "2.10.1.5 NLP vs. MIP"
}
},
"source": [
"### 2.10.1.5 NLP vs. MIP\n",
"\n",
"Solve the knapsack problem with IPOPT instead of glpk. Print the solution values for model.x. What happened? Why?\n",
"\n",
"*Hint*: Switch `glpk` to `ipopt` in the call to `SolverFactory`."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"nbpages": {
"level": 3,
"link": "[2.10.1.5 NLP vs. MIP](https://ndcbe.github.io/CBE60499/02.10-Pyomo1.html#2.10.1.5-NLP-vs.-MIP)",
"section": "2.10.1.5 NLP vs. MIP"
}
},
"outputs": [],
"source": [
"from pyomo.environ import *\n",
"\n",
"A = ['hammer', 'wrench', 'screwdriver', 'towel']\n",
"b = {'hammer':8, 'wrench':3, 'screwdriver':6, 'towel':11}\n",
"w = {'hammer':5, 'wrench':7, 'screwdriver':4, 'towel':3}\n",
"W_max = 14\n",
"\n",
"model = ConcreteModel()\n",
"model.x = Var( A, within=Binary )\n",
"\n",
"model.obj = Objective(\n",
" expr = sum( b[i]*model.x[i] for i in A ), \n",
" sense = maximize )\n",
"\n",
"model.weight_con = Constraint(\n",
" expr = sum( w[i]*model.x[i] for i in A ) <= W_max )\n",
"\n",
"# YOUR SOLUTION HERE\n",
"opt_success = opt.solve(model)\n",
"\n",
"model.pprint()"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbpages": {
"level": 3,
"link": "[2.10.1.5 NLP vs. MIP](https://ndcbe.github.io/CBE60499/02.10-Pyomo1.html#2.10.1.5-NLP-vs.-MIP)",
"section": "2.10.1.5 NLP vs. MIP"
}
},
"source": [
"**Question Answers**\n",
"\n",
"*Fill in here*"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbpages": {
"level": 2,
"link": "[2.10.2 More Pyomo Fundamentals](https://ndcbe.github.io/CBE60499/02.10-Pyomo1.html#2.10.2-More-Pyomo-Fundamentals)",
"section": "2.10.2 More Pyomo Fundamentals"
}
},
"source": [
"## 2.10.2 More Pyomo Fundamentals"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbpages": {
"level": 3,
"link": "[2.10.2.1 Knapsack problem with rules](https://ndcbe.github.io/CBE60499/02.10-Pyomo1.html#2.10.2.1-Knapsack-problem-with-rules)",
"section": "2.10.2.1 Knapsack problem with rules"
}
},
"source": [
"### 2.10.2.1 Knapsack problem with rules\n",
"\n",
"Rules are important for defining in-dexed constraints, however, they can also be used for single (i.e. scalar) constraints. Reimplement the knapsack model from **Question 1.1** using rules for the objective and the constraints."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"nbpages": {
"level": 3,
"link": "[2.10.2.1 Knapsack problem with rules](https://ndcbe.github.io/CBE60499/02.10-Pyomo1.html#2.10.2.1-Knapsack-problem-with-rules)",
"section": "2.10.2.1 Knapsack problem with rules"
}
},
"outputs": [],
"source": [
"# YOUR SOLUTION HERE"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbpages": {
"level": 3,
"link": "[2.10.2.2 Integer formulation of the knapsack problem](https://ndcbe.github.io/CBE60499/02.10-Pyomo1.html#2.10.2.2-Integer-formulation-of-the-knapsack-problem)",
"section": "2.10.2.2 Integer formulation of the knapsack problem"
}
},
"source": [
"### 2.10.2.2 Integer formulation of the knapsack problem\n",
"\n",
"Consider again the knapsack problem. Assume now that we can acquire multiple items of the same type. In this new formulation, $x_i$ is now an integer variable instead of a binary variable. One way to formulate this problem is as follows:\n",
"\n",
"\n",
"$\\max_{q,x} \\sum_{i\\in{A}}v_ix_i$\n",
"\n",
"s.t. $\\sum_{i\\in{A}}w_ix_i\\leq W_{max}$\n",
"\n",
"$x_i=\\sum_{j=0}^Njq_{i,j}, \\forall i \\in{A}$\n",
"\n",
"$0\\leq x\\leq N$\n",
"\n",
"$q_{i,j} \\in {0,1}, \\forall i \\in A, j \\in {0...N}$\n",
"\n",
"Starting with your code from **Question 2.1**, implement this new formulation and solve. Is the solution surprising?"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"nbpages": {
"level": 3,
"link": "[2.10.2.2 Integer formulation of the knapsack problem](https://ndcbe.github.io/CBE60499/02.10-Pyomo1.html#2.10.2.2-Integer-formulation-of-the-knapsack-problem)",
"section": "2.10.2.2 Integer formulation of the knapsack problem"
}
},
"outputs": [],
"source": [
"# YOUR SOLUTION HERE"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbpages": {
"level": 3,
"link": "[2.10.2.2 Integer formulation of the knapsack problem](https://ndcbe.github.io/CBE60499/02.10-Pyomo1.html#2.10.2.2-Integer-formulation-of-the-knapsack-problem)",
"section": "2.10.2.2 Integer formulation of the knapsack problem"
}
},
"source": [
"**Question Answer**\n",
"\n",
"*Fill in here*"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"nbpages": {
"level": 3,
"link": "[2.10.2.2 Integer formulation of the knapsack problem](https://ndcbe.github.io/CBE60499/02.10-Pyomo1.html#2.10.2.2-Integer-formulation-of-the-knapsack-problem)",
"section": "2.10.2.2 Integer formulation of the knapsack problem"
}
},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"id": "010a484d",
"metadata": {},
"source": [
"\n",
"< [2.9 Supplementary material: data for parmest tutorial](https://ndcbe.github.io/CBE60499/02.09-Parmest-generate-data.html) | [Contents](toc.html) | [Tag Index](tag_index.html) | [2.11 Pyomo Homework 2](https://ndcbe.github.io/CBE60499/02.11-Pyomo2.html) >
"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.6"
}
},
"nbformat": 4,
"nbformat_minor": 2
}