Toggle navigation
JUPYTER
FAQ
View as Code
View on GitHub
Execute on Binder
Download Notebook
CBE30338
notebooks
Notebook
CBE30338
¶
Chapter 1.0 Getting Started
¶
1.1 Getting Started with Python and Jupyter Notebooks
¶
Summary
Python Libraries
Working with Lists
Working with Dictionaries
Plotting with Matplotlib
Solve Equations using Sympy Library
Markdown Figures
[Screen Shot Jupyter Session](../images/Screen Shot Jupyter Session.png)
Markdown Links
Jupyter Notebook
Step 0: Gain Executable Access to Jupyter Notebooks
Step 1: Start a Jupyter Notebook Session
Step 2: Simple Calculations with Python
Step 3: Where to Learn More
Wakari.io
SageMathCloud
tmpnb.org
Anaconda
Continuum Analytics
this Khan Academy video
Sympy
Introduction to Python for Science
acceptable use policy
Springer
Amazon
github
A Primer on Scientific Programming with Python (Fourth Edition)
github
pycse - Python Computations in Science and Engineering
github repository for pycse
Code Academy on Python
Khan Academy Videos on Python Programming
Python Tutorial
Think Python: How to Think Like a Computer Scientist
Engineering with Python
Notebook Examples
Notebook Gallery
Official Notebook Documentation
Matplotlib
1.2 Python Basics
¶
What I hope you'll get out of this tutorial
Why Python?
Markdown Sidenote
LaTeX Sidenote
Python Basics
Variables
More Complicated Data Types
Using Variables
Importing in Python: Math and plotting
Loops in Python
Additional Resources
Markdown Links
Code Academy
Official Python Reference
Learn Python the Hard Way
1.3 Python Conditionals and Libraries
¶
Conditionals in Python
Functions in Python
Numpy - "The Fundamental Package for Scientific Computing with Python"
Additional Resources
Markdown Links
Code Academy
Official Python Reference
Learn Python the Hard Way
1.4 Python Numeric Integration Revisited
¶
Sidenotes
Code Academy Sidenote
Markdown/Latex Sidenote
Latex Side Note
Hare and Lynx Example
Introduction
Modeling
Programming and Plotting
Step 1: Initialization
Step 2: Default Parameter Values
Step 3: Define the differential equations
Step 4: Integrate Differential Equations
Step 5: Plot
Markdown Figures
http://boredomtherapy.com/wp-content/uploads/2015/12/14-canadian-lynx-paws-cute.jpg
http://www.cbc.ca/kidscbc2/content/contests/cute_snowshoe1.jpg
MainLynx.jpg
Markdown Links
Github's Markdown Guide
Dr. Kantor's Notes
Chapter 2.0 Process Modeling
¶
2.1 Process Variables
¶
Intensive and Entensive Variables
Thermodynamic State
Markdown Links
brake specific fuel consumption (BSFC)
2.2 Gravity Drained Tank
¶
Torricelli's law
Mass Balance for Tank with Constant Cross-Sectional Area
Step-by-Step Approach to Nonlinear Simulation
Step 1. Initialize Jupyter and Python
Step 2. Define parameters
Step 3. Write Functions for the RHS of the Differential Equations
Step 4. Choose an Initial Condition, a Time Grid, and Integrate the Differential Equation
Step 5. Visualize and Analyze Results
Step 6. Adjust and Repeat as Needed
2.3 Blending Tank Simulation
¶
Summary
Basic Simulation of the Blending Tank
Step 1. Initialize Python Workspace
Step 2. Establish Parameter Values
Step 3. Write a function to compute the RHS's of the Differential Equations
Step 4. Set the Initial Conditions, Time Grid, and Integrate
Step 5. Visualize the Solution
Steady State Analysis
2.4 Continuous Product Blending
¶
Preliminary Control Analysis
Degrees of Freedom Analysis
Steady State
Exercise 1. Determine Operating Range
Modeling
Simulation
Step 2. Parameter Values
Step 3. Computing Steady State
Step 4. Process Model Equations
Step 5. Numerical Solution of the Process Model
Step 6. Visualization and Analysis
Exercise 2. Explore Dynamical Behavior
Control Residence Time
Control Concentration
Exercise 3.
Proportional-Integral Control
Exercise 4.
Markdown Figures
[../images/Continuous Mixed Tank.png](../images/Continuous Mixed Tank.png)
2.5 Hare and Lynx Population Dynamics
¶
Summary
Introduction
Historical Data
Population Dynamics
Model Equations
Parameter Values
Simulation using the scipy.odeint()
Step 1. Initialization
Step 2. Establish Parameter Values
Step 3. Write function for the RHS of the Differential Equations
Step 4. Choose Time Grid, Initial Conditions, and Integrate
Step 5. Visualize and Analyze the Solution
Phase Plane
Nullclines
Interactive Simulation
Simulation Function
Stability of a Steady State
2. Stable Focus
3. Stable and Unstable Nodes
Summary
Suggested Exercise
Markdown Links
Snowshoe hare
Canadian lynx
Stenseth, 1997
Zhang, 2007
D. R. Hundley at Whitman College
here
here
2.6 Exothermic Continuous Stirred Tank Reactor
¶
Description
Reaction Kinetics
Model Equations and Parameter Values
Transient Behavior
Effect of Cooling Temperature
Interactive Simulation
Nullclines
Phase Plane Analysis
Suggested Exercises
Markdown Figures
Exothermic Reactor
Tags:
2.7 Fed-Batch Bioreactor
¶
Model Development
Python Implementation
Simulation
2.8 Model Library
¶
Chapter 3.0 Linearization
¶
3.1 Step Response of a Gravity Drained Tank
¶
Mass Balance for Tank with Constant Cross-Sectional Area
Nonlinear Step Response
Linear Approximation of the Step Response
Fit for $K$
Fit for $\tau$
Comparing the linear approximation to the nonlinear simulation
Markdown Links
https://github.com/jckantor/CBE30338
3.2 Linear Approximation of a Process Model
¶
Procedure for a Single Variable System
Example: Gravity Drained Tank
Exercises
3.3 Linear Approximation of a Multivariable Model
¶
Multivariable Systems
Example: Gravity Drained Tanks
Model
Nominal Inputs
Steady State for nominal input
Deviation Variables
Linearization
Summary of the linear model using matrix/vector notation
Exercises
First Order Reaction in a CSTR
Two Gravity Drained Tanks in Series
Isothermal CSTR with second-order reaction
Markdown Figures
Gravity Drained Tanks
3.4 Fitting First Order plus Time Delay to Step Response
¶
Summary
Initializations
First Order plus Time Delay Models
Time Delay
Visualization
Fitting an FOPTD model
Step 1. Shift and scale the experimental data to correspond to a unit step input at time t = 0.
Step 2. Create a function to compute the response of an FOPTD model.
Step 3. Create a function to measure the error between an FOPTD model and the experimental data.
Step 4. Use scipy.optimize.minimize() to find the best fitting FOPTD model.
Step 5. Rescale FOPTD output and compare to experimental data.
3.5 One Compartment Pharmacokinetics
¶
Antibiotics
Model Description
Problem Statement 1
Solution Strategy 1: Simulation from a Known Initial Condition
Step 1. Initialization
Step 2. Enter Parameter Values
Step 3. A Function the RHS of the Differential equation
Step 4. Solution and Visualization
Step 5. Analysis of the Results
Solution Strategy 2: Time-Dependent Input
Analysis of the Results
Problem Statement 2
Solution Strategy 3: Periodic Dosing
Markdown Figures
../images/Pharmaockinetics1.png
../images/nihms-475924-f0001.jpg
../images/Pharmaockinetics2.png
../images/nihms-475924-f0001.jpg
Markdown Links
antibiotic resistance
Levison, Matthew E., and Julie H. Levison. “Pharmacokinetics and Pharmacodynamics of Antibacterial Agents.” Infectious disease clinics of North America 23.4 (2009): 791–vii. PMC. Web. 8 May 2017.
Levison, Matthew E., and Julie H. Levison. “Pharmacokinetics and Pharmacodynamics of Antibacterial Agents.” Infectious disease clinics of North America 23.4 (2009): 791–vii. PMC. Web. 8 May 2017.
3.6 Second Order Models
¶
Step Response
[Overdamped ($\zeta > 1$)](
http://nbviewer.jupyter.org/github/jckantor/CBE30338/blob/master/notebooks/03.06-Second-Order-Models.ipynb#Overdamped-($%5Czeta-%3E-1$
))
[Critically Damped ($\zeta = 1$)](
http://nbviewer.jupyter.org/github/jckantor/CBE30338/blob/master/notebooks/03.06-Second-Order-Models.ipynb#Critically-Damped-($%5Czeta-=-1$
))
[Underdamped ($0 \lt \zeta \lt 1$)](
http://nbviewer.jupyter.org/github/jckantor/CBE30338/blob/master/notebooks/03.06-Second-Order-Models.ipynb#Underdamped-($0-%5Clt-%5Czeta-%5Clt-1$
))
[Undamped ($\zeta = 0$)](
http://nbviewer.jupyter.org/github/jckantor/CBE30338/blob/master/notebooks/03.06-Second-Order-Models.ipynb#Undamped-($%5Czeta-=-0$
))
Simulation
Performance Indicators for Underdamped Systems
Estimating Parameters for an Underdamped System
Starting with a Physical Model
Starting with a Step Response
Markdown Figures
2ndOrder.png
3.7 Interacting Tanks
¶
Problem Statement
Solution
Part a.
Part b.
Further Calculations
Markdown Figures
Image of a two interacting tanks
3.8 Manometer Models and Dynamics
¶
Markdown Links
Model 1. Steady State Response to a Pressure Differential
Model 2. Dynamic Response with Negligible Viscosity
Model 3. Dynamic Response with Viscous Dissipation
Model 4. Second Order System in Standard Form
Model 5. Dynamic Response to Sinusoidal Input
Model 6. State Space Representation
3.9 Modeling and Control of a Campus Outbreak of Coronavirus COVID-19
¶
1. Brief background on the SARS-CoV-2 Coronavirus and COVID-19
Model 1. SIR model for an infectious disease
Readings
Introduction to SIR models
Key Properties of the SIR Model
Simulation
How many people will be infected following an outbreak?
Model 2. SEIR model
Model 3. Mitigation and Social Distancing
Social Distancing Strategies for the Campus
Model 4. Improving the fidelity of the model.
Additional Modeling Opportunities. Transportation, power law kinetics, etc.
Markdown Links
COVID-19
global health emergency by the World Health Organization (WHO)
Coronavirus COVID-19 Global Cases by Johns Hopkins CSSE
WHO Novel Coronavirus (COVID-19) Situation
Cell Press Coronavirus Resource Hub
Lancet COVID-19 Resource Centre
medRxiv preprint server search on COVID-19
New England Journal of Medicine Coverage on Coronavirus (COVID-19)
WHO Database of publications on coronavirus disease (COVID-19)
CDC Social Distancing
Chapter 4.0 PID Control
¶
Implementation
4.1 Implementing PID Controllers with Python Yield Statement
¶
Python Yield Statement
PID Control Implementation
Simulation
Analysis
Markdown Links
here
4.2 PID Control with Setpoint Weighting
¶
Setpoint 'Kick'
Implementation of Setpoint Weighting
Simulation
4.3 PID Control with Bumpless Transfer
¶
Switching from Manual to Automatic Control
Bumpless Transfer
Tracking the Manipulated Variable
Setpoint Tracking
Steady State
4.4 PID Control with Anti-Reset-Windup
¶
Additional Benefits of Tracking the Manipulated Variable
Embedding Anti-Reset Windup inside the Controller
4.5 Realizable PID Control
¶
Example: PID Control with Significant Measurement Noise
Modifying the Derivative Term
Example Revisited
4.6 PID Controller Tuning
¶
PID Reference Implementation
AMIGO Tuning
Ziegler Nichols Tuning
Relay Tuning
4.10 PID Control - Laboratory
¶
PID Control
Exercise 1. Is the transfer from manual to automatic bumpless?
Exercise 2
Tags:
4.11 Implementing PID Control in Nonlinear Simulations
¶
Model
Simulation 1. Same Initial Condition, different values of $q_c$
Simulation 2. Fixed Time Grid
Simulation 3. Proportional-Integral-Derivative Control
Simulation 4. Interactive Controller Tuning
Simulation 5. Using the PIDsim Controller Class
Contents of PIDsim.py
Markdown Figures
Exothermic Reactor
Markdown Links
DISCRETE PID CONTROLLER (PYTHON RECIPE)
ivPID
python-pid_controller
PID Controller
pypid 0.4
PIDController
PID.py
APMonitor.com
4.12 Interactive PID Control Tuning with Ziegler-Nichols
¶
Summary
Notebook Initialization
Block Diagram of the Closed-Loop Control System
Process Transfer Functions
Measurement Transfer Function
Proportional-Integral (PI) Control
Closed-Loop Transfer Functions
Definitions
Interactive Simulation
3. Control Tuning Procedures
Ziegler-Nichols
Tyreus-Luyben
Exercises
Exercise: PID Control
Exercise: Alternative Tuning Rules
References
Markdown Links
Wikipedia page describing the Ziegler-Nichols method
Chapter 5.0 Frequency Domain Control Design
¶
5.1 Getting Started with Transfer Functions
¶
Markdown Links
Python Control Systems Library
Python Control Systems Documentation
Installation
Importing Libraries
Transfer Functions
Step Response of a First Order Transfer Function
Transfer functions in Series
Second Order Transfer Functions
Python Control Systems Library
5.2 Closed-Loop Transfer Functions for Car Cruise Control
¶
Block Diagram for Car Cruise Control
Closed-Loop Transfer Functions
Step Responses
Additional Examples
Internal Model Control
SEMD Figure 11-14
Markdown Figures
Cruise Control Block Diagram
Cruise Control Block Diagram
Internal Model Control
Internal Model Control
Markdown Links
Application: Vehicle Cruise Control
Closed-Loop Transfer Functions
Step Responses
Additional Examples
5.3 Creating Bode Plots
¶
Initializations
Creating Bode Plots
Specify a Transfer Function
Adding Time Delay
Bode Plot using Default Options
Specify Frequency Range
Setting Other Plotting Options
Adding Features to the Bode Plot
Crossover Frequency and Gain at Crossover
Markdown Links
Python Control Systems Library
here
Python Control Systems Library
5.4 Controller Tuning Rules in Frequency Domain
¶
Closed-Loop Transfer Functions
Finding Cross-Over Frequency and Gain at Cross-Over
Computing Ultimate Gain and Period
Ziegler-Nichols Tuning Rules
Interactive Tuning of a PID Controller
Markdown Links
Python Control Systems Library
5.5 Baroreflex as a Linear Control System
¶
Peripheral Arc
P, PI, PD, and PID Control
Ziegler-Nichols Tuning
Proportional-Derivative Control
Internal Model Control Tuning
Measured Physiological Response of Neural Arc
Comparison of ZN Tuned PD Control to the Observed Physiological Response of the Neural arc
Modifications to the PD Controller
Conclusions
References
Markdown Figures
baroreflex system
baroreflex control diagram
Markdown Links
baroreflex
baroreceptors
Python Control Systems Library
Ziegler-Nichols tuning
Chapter 6.0 Optimization
¶
6.1 Unconstrained Scalar Optimization
¶
Example: Reactor for a Series Reaction
Continuous Stirred Tank Reactor
Analytical Solution using Calculus
Numerical Solution using
scipy.minimize_scalar
[Bonus Discussion] Batch Reactor
6.2 Linear Production Model
¶
Example: Production Plan for a Single Product Plant
Mathematical Model
Exercises
Production Plan: Product Y
Exercises
Production Plan: Mixed Product Strategy
Solution using scipy.optimize.linprog
What are the active constraints?
What is the incremental value of labor?
Theory of Constraints
Markdown Links
Pyomo
glpk
scipy.optimize library
6.3 Linear Programming
¶
Example 19.3: Refinery Blending Problem
6.4 Linear Production Model in Pyomo
¶
Installation
Algebraic Modeling Languages
Key Concepts in Pyomo
Example: Linear Production Model with Constraints
Python Lists, Sets, Dictionaries, and Iterators
Data in Matrix/Vector Format
Markdown Links
Pyomo
Anaconda package for Python 3.x
glpk
ipopt
cbc
GAMS
AIMMS
AMPL
FICO XPRESS
YALMIP
CVX
JuMP
Pyomo
6.4 Linear Programming in Pyomo
¶
Starting the Model
6.6 Linear Blending Problem
¶
Problem Statement (Jenchura, 2017)
Solution
Representing Problem Data as a Python Dictionary
Objective Function
Volume Constraint
Product Composition Constraint
Pyomo Model
6.7 Design of a Cold Weather Fuel
¶
Data
Denatured Alcohol
Cold Weather Product Requirements
Optimization Model
Display Composition
Markdown Figures
img/alcohol_stove.jpeg
Markdown Links
manufacturer's product
6.8 Gasoline Blending
¶
Gasoline Product Specifications
Stream Specifications
Blending Model
Display Results
Results for each Stream
Results for each Product
Exercise 1.
Exercise 2.
Exercise 3.
6.99 Pyomo Examples
¶
Example: Nonlinear Optimization of Series Reaction in a Continuous Stirred Tank Reactor
Example 19.3: Linear Programming Refinery
Example: Making Change
Example: Linear Production Model with Constraints with Duals
Chapter 7.0 Simulation and Optimal Control
¶
Available Solvers
Markdown Links
ampl.com
7.1 Simulation and Optimal Control in Pharmacokinetics
¶
Installations and Initialization
A Pharmacokinetics Example
Simulation of Fixed Infusion Rate Strategy
Optimizing the Infusion Strategy
Alternative Objectives
Markdown Links
Google Colaboratory
7.2 Soft Landing a Rocket
¶
Required Installations
Google Colab
Windows PC
Python Initializations
Version 1: Vertical Dynamics of a Rocket with Constant Mass
First attempt at a solution
Land on the surface, not above or below the surface.
Make that a soft landing.
Restrict fuel flow to engine capacity.
Version 2: Rescaled Model
How much fuel is burned?
Minimize fuel consumption.
Version 3: Rocket Model
Markdown Links
Apollo 11 Landing on the Moon, July 20, 1969
SpaceX Falcon Heavy Side Boosters Landing at Kennedy Space Center, February 6, 2018
Blue Origin, November 24, 2014
ampl.com
Apollo 11 Lunar Module
7.3 Simulation in Pyomo
¶
7.4 Simulation of an Exothermic CSTR
¶
Description
Arrehenius Law Kinetics for a First-Order Reaction
Modeling and Parameter Values
Mathematical Model
Pyomo Model
Simulation and Visualization
Simulation
Effect of Cooling Temperature
Markdown Figures
Exothermic Reactor
7.5 First Order System in Pyomo
¶
First-Order Differential Equation with Initial Condition
7.6 Path Planning for a Simple Car
¶
Required Installations
Kinematic Model
Pyomo Model
Accessing Solution Data
Visualizing Car Path
7.7 Transient Heat Transfer in Various Geometries
¶
Preliminary Code
Planar Coordinates
Cylindrical Coordinates
Spherical Coordinates
7.8 Path Constraints
¶
Recoding for Compact Style
Subscripting Equations
Chapter 8.0 Predictive Control
¶
8.1 Zero-Order Hold and Interpolation
¶
Interpolation Function
Demonstration
Chapter 9.0 Discrete Events
¶
9.1 Scheduling State-Task Networks
¶
Example (Kondili, et al., 1993)
Encoding the STN data
Setting a Time Grid
Creating a Pyomo Model
Characterization of Tasks
Characterization of States
Characterization of Units
Pyomo Model
Analysis
Profitability
State Inventories
Unit Assignment
Unit Batch Inventories
Gannt Chart
Trace of Events and States
Markdown Figures
Kondili_1993.png
9.2 State-Task Networks
¶
Description
Exercise
References
Markdown Figures
Kondili_1993.png
9.3 Machine Bottleneck
¶
Markdown Links
Example
Modeling
Pyomo Model
Visualization
Multiple Machines
Appendix A. Additional Python
¶
A.1 Python Library for CBE 30338
¶
Some Python basics
Python functions
Functions are Python objects
Create simple functions with
lambda
Create complex functions with
def
Comprehensions
map
,
filter
,
reduce
CBE30338.plotter()
Markdown Links
Additional Python
Contents
Modular Simulation using Python Generators
A.2 Modular Simulation using Python Generators
¶
Markdown Links
Simulation using scipy.integrate.odeint()
Typical Usage
What's Wrong with That?
Python Generators
Yield Statement
Iterators
Two-way communcation with Generators using Send
Example Application: Modeling Gravity-Drained Tanks with Python Generators
Generator for a Gravity-Drained Tank
Simulation of a Single Tank with Constant Inflow
Simulation of Two Tanks in Series
Simulation of Two Tanks in Series with PI Level Control on the Second Tank
Adding a PI Control Generator
Implementing Cascade Control for Two Tanks in Series with Unmeasured Disturbance
Enhancing Modularity with Class Definitions for Process Units
Gravity-Drained Tank Class
PI Controller Class
Modular Simulation of Cascade Control for Two Tanks in Series
generators and iterators
A.3 Animation in Jupyter Notebooks
¶
Step-by-Step Approach to Animation with Matplotlib
Step 2. Define a function to draw each frame
Step 3. Create the Animation Object
Step 4. Render the Animation
Example: Phase Plane Animation for an Exothermic Stirred-Tank Reactor
Markdown Links
https://github.com/jckantor/CBE30338
Animating the Lorenz System in 3D
Embedding Matplotlib Animations in Jupyter Notebooks
here
A.4 A Modular Approach to Simulation using Python Generators
¶
Markdown Links
https://github.com/jckantor/CBE30338
Simulation using scipy.integrate.odeint()
Typical Usage
What's Wrong with That?
Python Generators
Yield Statement
Iterators
Two-way communcation with Generators using Send
Example Application: Modeling Gravity-Drained Tanks with Python Generators
Generator for a Gravity-Drained Tank
Simulation of a Single Tank with Constant Inflow
Simulation of Two Tanks in Series
Simulation of Two Tanks in Series with PI Level Control on the Second Tank
Adding a PI Control Generator
Implementing Cascade Control for Two Tanks in Series with Unmeasured Disturbance
Enhancing Modularity with Class Definitions for Process Units
Gravity-Drained Tank Class
PI Controller Class
Modular Simulation of Cascade Control for Two Tanks in Series
generators and iterators
Appendix B. Student Projects
¶
B.1 Diabetes: Controlling Blood Glucose Concentrations
¶
Problem Statement
Introduction and Problem
Technology Challenge
Goals and Objectives:
Theoretical Development
The Bergman Model for Type I Diabetes
Exercise Model
Core Model Assumptions
Results and Executable Elements
Import Libraries
Define Model Function for Bergman Model
Define Model Function for Exercise Model
Disturbance Function
Injection Function
Solver Functions for Bergman Model and Exercise Model
Plotting Function
Parameter Values for Bergman Model
Parameter Values for Exercise Model
Parameter Values for the Disturbance Function for Meals
Time and Initial Conditions for the Bergman Minimal Model
Time and Initial Conditions for the Exercise Model
Simulation 1: No Controller Input
Simulation 2: Basal Dose
Simulation 3: High-Concentration Injection Prior to Meal
Simulation 4: High-Concentration Injection and Basal Dose
Simulation 5: PID Control
Simulation 6: PID Control with Basal Dose
Simulation 7: PID Control with Basal Dose and Injection
Simulation 8: Exercise and Meal with no Control
Simulation 9: Exercise and Meal with only Basal Dose
Simulation 10: Exercise and Meal with PID Controller
Simulation 11: Exercise and Meal with PID Controller and Basal Dose
Summary and Conclusion
Appendices
References
Statement of Contributions
B.2 Visual Tracking of an Object with a Drone
¶
Problem Statement
Technology Challenge
Project Goal
Results and Theory
Controller
Image Recognition
PID Control for Object Tracking
Executable Element
Conclusion and Summary
Appendices
A.) TelloCV.py
-TelloCV.py)
B.) Tracker.py
-Tracker.py)