Lab 1: Step Test of a First-Order System#
Your Name:
This notebook outlines a process for fitting a first-order model of a heater/sensor assembly to data taken during a step test. The learning goals for this notebook are:
Read and plot a previously saved step test data using the
Pandas
library.By inspection, identify the gain and dominant time constant of the step test.
Simulate the response of a first-order model to step test.
Through iteration, adjust model parameters to fit the first order model to step test data.
Understand the relationship of model parameters to gain and time constant.
Determine if a first-order model provides an adequate description of the observed response.
Exercise 0. Analyze a Previous Dataset#
First-order lumped model for heater/sensor device.#
We have previously developed a first-order model for one heater/sensor pair on the temperature control lab device. An energy balance gives
where \(T_1\) is the average temperature of heater/sensor one, \(T_{amb}\) is the ambient temperature of the surroundings. The unknown parameters are the heat capacity \(C_p\) and the heat transfer coefficient \(U_a\).
The parameters describing the heat input are as follows:
\(\alpha\) is a system calibration constant The measured value of \(\alpha\) is 0.16 milliwatts per unit of \(P_1\) per percent.
\(P_1\) is a constant integer value in the range 0 to 255 that controls the operating range of heater 1. It is set using the
tclab
library.\(u_1\) is a floating point value in the range 0 to 100 that specify the percentage of available power for heater 1.
For example, if \(P_1 = 255\) and \(u_1 = 100\), then the total applied power is
Reading previously saved experimental data#
A step test was performed where the temperature control laboratory was initially at steady state at ambient temperature. The heater range \(P_1\) was set to 200, then heater 1 was set to 50% of full range with \(\bar{u}_1 = 50\). Temperatures \(T_1\) and \(T_2\) were recorded for 800 seconds. The has been saved to the course Github repository where it can be located with the url
https://raw.githubusercontent.com/ndcbe/controls/main/tclab/data/tclab-data.csv
The following cell reads the step test data using the Pandas
library. The data is stored in a Pandas DataFrame called data
.
import pandas as pd
# parameter values
P1 = 200
U1 = 50
# file location
github_repo = "https://raw.githubusercontent.com/ndcbe/controls/main/"
file_path = "tclab/data/tclab-data.csv"
url = github_repo + file_path
# read file
data = pd.read_csv(url, index_col="Time")
# display the step test data
display(data)
Next we plot the data using the .plot()
method associated with every Pandas DataFrame. The Pandas plot method provides a concise and intuitive means of plotting data.
import matplotlib.pyplot as plt
data.plot(y=["T1", "T2"],
title=f"{P1=}, {U1=}",
xlabel="seconds",
ylabel="deg C",
grid=True,
figsize=(8, 2.5)
)
data.plot(y=["Q1", "Q2"],
title=f"{P1=}, {U1=}",
xlabel="seconds",
ylabel="% of full range",
grid=True,
figsize=(8, 1.5),
ylim=(0, 100)
)
plt.show()
Imagine you printed the plot above on paper. Using the plot, estimate the gain \(K\) and and time constant \(\tau\) from the plot. Hint: Look at your lecture notes. How did we do this for similar in-class example for linear first order systems?
Please typeset your answer and supporting calculations. You can either use Python as a simple calculator or use a scientific calculator. The calculation is not that hard. Do not overthink it.
Answer:
Analytical Solution for a Step Test#
The goal of this assignment is to fit a first-order model to the step test. We use will be use the analytical solution for a first-order model subject to a step change in the input. Then, by trail-and-error, we will find a set of model parameters that provide a good fit to the experimental data. Finally, you will perform this fitting via nonlinear regression.
We start with a first-order model written in gain/time-constant form
where \(x = T_1 - T_{amb}\) and the \(\bar{u}\) is a constant value for the input \(u_1(t)\). The analytical solution consists of two parts
The solution depends on three parameters:
\(x_0\): initial condition
\(K\): steady-state gain
\(\tau\): time constant
The initial condition \(x_0 = 0\) if the step test starts at steady-state. In that case there are two parameters to fit, \(K\) and \(\tau\). The following cell demonstrates the calculation and plotting of the analytical solution.
Graphically Determine the Gain and Time Constant#
import numpy as np
import matplotlib.pyplot as plt
# replace these with your calculation above
# then adjust until the plot visually matches the data
T_amb = 23
x0 = 0
K = 0.7
tau = 200 # seconds
# Add your solution here
# known input
U1 = 50
# compute analytical solution
t = data.index
x = x0*np.exp(-t/tau) + (1 - np.exp(-t/tau))*K*U1
# plotting solution for T1
T1 = x + T_amb
plt.plot(t, T1, t, data["T1"])
plt.legend(["T1 predicted", "T1 measured"])
# dress up the plot
plt.title(f"{x0=} C, {K=} C/%, {tau=} s")
plt.xlabel("seconds")
plt.ylabel("deg C")
plt.grid(True)
Remember to submit Exercise 0 via Gradescope.
Exercise 1. Step Tests and Data Collection#
We will now perform a step test to collect data you analyzed in Exercise 0, but this time using your own TCLab.
Step 1. Verify operation.#
Execute the following cell to verify that you have a working connection to the temperature control lab hardware. This will test for installation of TCLab.py, connection to the Arduino device, and working firmware within the Arduino.
from tclab import TCLab, clock, Historian, Plotter, setup
run_tclab = False
"""
In the labs, we will us "run_tclab" to control whether the TCLab is used.
After you finish the lab experiment, set run_tclab = False.
This way, you can run all the cells without losing your TCLab output.
"""
if run_tclab:
TCLab = setup(connected=True)
lab = TCLab()
print("TCLab Temperatures:", lab.T1, lab.T2)
lab.close()
Step 2. Check for steady state#
As discussed in class, for step testing the device must be initially at steady state. Run the following code to verify the heaters are off and that the temperatures are at a steady ambient temperature.
if run_tclab:
# experimental parameters
tfinal = 30
# perform experiment
with TCLab() as lab:
lab.U1 = 0
lab.U2 = 0
h = Historian(lab.sources)
p = Plotter(h, tfinal)
for t in clock(tfinal):
p.update(t)
Step 3. Step Test#
The step test consists of turning one heater one at 50% power and recording temperature data for at least 1200 seconds. Copy the code from Step 2 into the following cell. Then modify as needed to accomplish the step test with P1 at 200 and using 50% of maximum power.
if run_tclab:
# Add your solution here
Step 4. Save data to a .csv file#
Run the following cell to verify and save your data to a ‘.csv’ file. Be sure you can find and locate the data on your laptop before ending your session. You will need access to this data for subsequent exercises.
import matplotlib.pyplot as plt
import os.path
# Change the filename here
data_file = 'lab1-step-test.csv'
if run_tclab:
t, T1, T2, Q1, Q2 = h.fields
plt.plot(t, T1, t, T2, t, Q1, t, Q2)
plt.legend(['T1','T2','Q1','Q2'])
plt.xlabel('Time / seconds')
plt.grid()
# Set to True to overwrite the file. Default is False
# to safeguard against accidentally rerunning this cell.
overwrite_file = False
if not overwrite_file and os.path.isfile('./'+data_file):
raise FileExistsError(data_file + ' already exisits. Either choose a new filename or set overwrite_file = True.')
elif run_tclab:
h.to_csv(data_file)
print("Successfully saved data to "+data_file)
else:
print("Data not saved. Set run_tclab = True to save the data.")
Exercise 2. Determine First-Order Linear Model From Inspection#
Do the following:
Read the data you saved from your step test.
Plot the results.
Inspecting the plot for \(T_1\), estimate the
gain
time constant
ambient temperature
# Add your solution here
Write your estimates below in this markdown cell.
Answer:
Exercise 3. Fit First-Order Linear Model with Numerical Simulations and Trail-and-Error#
Fill in the function below to plot an analytical solution for the step response of a first-order model in gain/time constant form. Use your estimates of gain, time constant, initial condition, and the input. On the same plot, overlay a plot of the experimental data. Adjust parameter values until you get the a good fit of the model to the experimental data.
Note that you may need to also adjust values of the ambient temperature and initial condition to fit the model.
Report the following:
gain
time constant
ambient temperature
initial condition
# First, create a function to compute the predicted values
import numpy as np
import matplotlib.pyplot as plt
def predict_first_order(data, K, tau, x0 = 0, U1=50, plot=False):
'''
Predict the temperature of a first order system.
Arguments:
t: time (seconds)
x0: initial temperature (deg C)
K: steady state gain (deg C/% U1)
tau: time constant (seconds)
U1: input as a percentage
T_amb: ambient temperature (deg C)
data: dataframe with columns T1, T2, Q1, Q2
plot: True to plot the results
Returns:
T1_pred: predicted temperature (deg C)
'''
# Extract the time index and ambient temperature from
# the Pandas dataframe
t = data.index
T_amb = data["T1"].iloc[0]
# Add your solution here
# Next, set an initial point
# Add your solution here
# Test the function using the initial guess
# Add your solution here
# Adjust the parameters by hand to improve the fit
# Because everyone has their own TCLab and dataset, everyone
# should have a slightly different answer.
# Add your solution here
Exercise 4. Fit First-Order Model via Nonlinear Regression#
Next, you will fit the first-order linear model using nonlinear regression. Hint: You practiced using least_squares
in Homework 1.
from scipy.optimize import least_squares
def first_order_model(p):
'''
Predict the temperature of a first order system.
Arguments:
p: list of parameters [tau, K]
Returns:
T1_pred: predicted temperature (deg C)
'''
# Unpack the parameters
K, tau = p
return predict_first_order(data, K=K, tau=tau, plot=False)
# Add your solution here
# Print the result here with units and a reasonable number of significant digits.
# Add your solution here
# Plot the results
# Add your solution here
How do these results compare to your “by hand” trial-and-error fitting? Write 1 to 3 sentences.
Answer:
Exercise 5. State-Space Model#
A first-order model in gain/time constant form is given by
Where \(x\) is the state variable. Again letting \(x = T_1 - T_{amb}\) and \(u = u_1\) Comparing this model of a first order system to the model given up for the heater/sensor assembly.
Do the following:
Derive expressions for the parameters \(\tau\) and \(K\) in terms of \(C_p\), \(U_a\), \(\alpha\), and \(P_1\).
Assume \(\alpha = 0.16\) milliwatts per unit of \(P1\) per percent. Solve for estimates of \(C_p\) and \(U_a\).
Remember: Everyone has their own TCLab device, which means everyone has their own unique data. As such, everyone should have slightly different calculated values for \(C_p\) and \(U_a\).
Answer:
Exercise 6. Discussion#
Below discuss issues you would face in writing a Python function to automatically fit the model of the heater/sensor assembly to step test data. For each question, please write a few sentences.
How can you measure the quality of fit?
Answer:
How should one handle bad measurements?
Answer:
What parameters should be fit?
Answer:
How can you estimate uncertainty in the estimates of \(C_p\) and \(U_a\)?
Answer:
Is it possible to estimate \(U_a\) from a steady state experiment?
Answer:
Is is possible to estimate \(C_p\) from a steady state experiment?
Answer:
Declarations#
Collaboration: If you worked with any classmates, please give their names here. Describe the nature of the collaboration.
Generative AI: If you used any Generative AI tools, please elaborate here.
Reminder: The written discussions responses must be in your own words. Many of these questions ask about your specific results or are open-ended questions with many reasonable answers. Thus we expect unique responses, analyses, and ideas.
We may use writing analysis software to check for overly similar written responses. You are responsible for reviewing the colaboration policy outlined in the class syllabus to avoid violations of the honor code.