Data Collection 4 — Colab Notebook
- Team Name:
[Write in the name of your team.] - Authors:
[Write in the name of the authors of this notebook.] - Cell Number:
[Write in your cell number.] - J-V Apparatus Number:
[Write in the number of your apparatus (JV1, JV2, or JV3) that you used for your measurements.] - EQE Apparatus Number:
[Write in the number of the apparatus (EQE1, EQE2, or EQE3) that you used for your measurements.]
This week you will do the following data analysis:
- Calculate PCE values and uncertainties for all pixels. Write the PCE values, PCE uncertainties, and \(J_{sc}\) values to a CSV file. You have done this analysis in previous Colab notebooks. Please copy, edit, and reuse your code from previous weeks.
- Fit a weighted linear regression to the PCE values for one pixel over time, then compare weighted linear fits for two pixels.
1 PCE Analysis
- Calculate the \(J_{sc}\) and PCE values for each pixel. Remember to follow the uncertainty workflow from Data Collection 2: extract SE values from the raw data, compute \(\delta V_{pmax}\) from the voltage step size, and propagate uncertainties to produce your final CSV with
PCE_uncertainty (%). - Update the PCE plot you made last week to include this week's PCE values and error bars. This figure should now have six time points: baseline data, Data Collection 1, Data Collection 2, break week (TA data), Data Collection 3, and Data Collection 4 (this week). Remember to update the time values for this week's data.
# Use this cell to do your codingIn addition to your plot, paste the contents of your CSV file below so your TA can check your values. It should have the following columns:
Pixel Number | Time (hr) | Jsc (mA/cm^2) | PCE | PCE_uncertainty (%)
Paste your CSV output here.
Question 1: How do your PCE values from this week compare to the values from previous weeks?
Use this cell to answer Question 1
1.1 Introduction to Linear Regression
Linear regression is a statistical method used to model the relationship between variables by fitting a linear equation to observed data. In our case, we want to model how PCE changes over time.
The basic form of a linear regression model is:
\[y = mx + b + \epsilon\]
Where:
- \(y\) is the dependent variable (PCE in our case)
- \(x\) is the independent variable (time in days)
- \(m\) is the slope (rate of change of PCE per day)
- \(b\) is the y-intercept (theoretical initial PCE value)
- \(\epsilon\) represents random error
1.1.1 Understanding Chi-Squared (reminders from lecture)
The chi-squared (χ²) statistic is a powerful tool for evaluating the quality of a fit when we have uncertainties in our measurements. It is applicable to many types of data fitting models, not just a linear fit (which is what we are considering today). It's calculated as:
\[\chi^2 = \sum_{i=1}^{n} \frac{(y_i - \hat{y}_i)^2}{\sigma_i^2}\]
Where:
- \(y_i\) are the observed values
- \(\hat{y}_i\) are the predicted values from our model
- \(\sigma_i\) are the uncertainties in each measurement
The reduced chi-squared (χ²/ν) divides the chi-squared value by the number of degrees of freedom (ν = n - p, where n is the number of data points and p is the number of parameters in the model):
\[\frac{\chi^2}{\nu} = \frac{\chi^2}{n-p}\]
For a good fit with accurate uncertainties:
- χ²/ν ≈ 1: Indicates a good fit with appropriate uncertainties
- χ²/ν < 1: May indicate overestimated uncertainties or overfitting
- χ²/ν > 1: May indicate underestimated uncertainties or a poor model fit
1.1.2 Weighted Linear Regression
In this analysis, we use a weighted linear regression, which takes into account the uncertainties in each measurement. Each data point is weighted by the inverse of the square of its uncertainty (\(1/\sigma^2\)), so points measured with smaller uncertainties have more influence on the fit. This approach provides a more accurate estimate of the slope and intercept — and lets us calculate meaningful values for the chi-squared (\(\chi^{2}\)) and reduced chi-squared (\(\chi^{2}\)/\(\nu\)) to assess the fit quality.
Edit the code below to call your CSV files and select a pixel number (valid: 1,2,3,4,5,6,7,8).
# Weighted Linear Regression for a Single Pixel
# Be sure that you have imported pandas, numpy, and matplotlib
# which you should have already done for the J-V analysis
# Point to your CSVs (put them in the same folder as this notebook)
# Add one entry per week — you should have one CSV file for each data
# collection week. Be sure to update file names to match your dates/cell number.
files = [
"YYYY_MM_DD_jsc_pce_uncertainties_cell###.csv", # baseline
"YYYY_MM_DD_jsc_pce_uncertainties_cell###.csv", # Data Collection 1
"YYYY_MM_DD_jsc_pce_uncertainties_cell###.csv", # Data Collection 2
"YYYY_MM_DD_jsc_pce_uncertainties_cell###.csv", # break week (TA data)
"YYYY_MM_DD_jsc_pce_uncertainties_cell###.csv", # Data Collection 3
"YYYY_MM_DD_jsc_pce_uncertainties_cell###.csv", # Data Collection 4 (this week)
]
df = pd.concat([pd.read_csv(f) for f in files], ignore_index=True)
# Choose one pixel to analyze (valid: 1,2,3,4,5,6,7,8)
pixel_choice = 1 # <-- update this
# build x, y, yerr in the CORRECT units
dfp = df[df["Pixel Number"] == pixel_choice].copy()
if dfp.empty:
raise ValueError(f"No rows found for Pixel {pixel_choice}.")
x = (dfp["Time (hr)"].astype(float) / 24.0).to_numpy() # days elapsed
y = dfp["PCE"].astype(float).to_numpy() # PCE in percent
yerr = dfp["PCE_uncertainty (%)"].astype(float).to_numpy() # absolute % uncertainty
# sort for clean plotting
order = np.argsort(x)
x, y, yerr = x[order], y[order], yerr[order]
# Weighted linear fit: y = m*x + b, weights = 1/σ^2
def weighted_linear_fit(x, y, yerr):
# guard against zero/negative uncertainties
yerr = np.asarray(yerr, float)
mask = (yerr > 0) & np.isfinite(x) & np.isfinite(y)
x, y, yerr = x[mask], y[mask], yerr[mask]
# design matrix with columns [x, 1]
X = np.vstack([x, np.ones_like(x)]).T
w = 1.0 / (yerr**2)
# Apply the weights directly to each row of our data
# rather than creating a large matrix filled mostly with zeros.
# This is mathematically equivalent to multiplying by the full
# weight matrix but is much faster and easier to compute.
XTW = X.T * w
XTWX = XTW @ X
XTWy = XTW @ y
# parameters and (unscaled) covariance
beta = np.linalg.solve(XTWX, XTWy) # [m, b]
cov = np.linalg.inv(XTWX) # covariance up to scale
# residuals and chi-squared
y_fit = X @ beta
resid = y - y_fit
chi2 = np.sum((resid / yerr)**2)
dof = max(len(y) - 2, 1)
chi2_red = chi2 / dof
# scale covariance by reduced chi^2 (robust if σ were misestimated)
cov_scaled = cov * chi2_red
se = np.sqrt(np.diag(cov_scaled)) # [σ_m, σ_b]
m, b = float(beta[0]), float(beta[1])
se_m, se_b = float(se[0]), float(se[1])
return m, b, se_m, se_b, chi2, chi2_red, y_fit, resid
# Assign the output variables from the weighted linear fit function
m, b, se_m, se_b, chi2, chi2_red, y_fit, resid = weighted_linear_fit(x, y, yerr)
# Output fit results
print(f"Pixel {pixel_choice} — Weighted Linear Fit Results")
print(f" Slope (per day): {m:.6f} ± {se_m:.6f}")
print(f" Intercept (%): {b:.3f} ± {se_b:.3f}")
print(f" Chi-squared: {chi2:.3f}")
print(f" Reduced χ²: {chi2_red:.3f}")
# Make a figure with data + weighted fit with error bars
xs = np.linspace(np.nanmin(x), np.nanmax(x), 200) # Create evenly spaced x-values for plotting the fitted line
ys = m * xs + b
plt.figure(figsize=(8,6))
plt.errorbar(x, y, yerr=yerr, fmt='o', capsize=4, label="Data (with uncertainties)")
plt.plot(xs, ys, label=f"Weighted fit: y = {m:.4f}x + {b:.4f}")
plt.xlabel("Days Elapsed"); plt.ylabel("PCE (%)")
plt.title(f"Pixel {pixel_choice}: Weighted Linear Fit (χ²/ν = {chi2_red:.2f})")
plt.grid(True); plt.legend(); plt.tight_layout()
plt.show()1.1.3 Residuals Analysis
Residuals show the difference between observed and predicted values from our model fit:
\[\text{Residual}_i = y_i - \hat{y}_i\]
Analyzing residuals helps us evaluate how well our model fits the data:
- Pattern: Residuals should be randomly scattered around zero for a good model fit
- Magnitude: Residuals should be small relative to the measurement uncertainties
- Trends: Any visible pattern in residuals suggests the model may be missing important features in the data
When we plot residuals with error bars (using our measurement uncertainties), we can visually assess whether:
- The zero line (representing perfect prediction) falls within the error bars of most points
- There are systematic deviations that suggest our model is inadequate
Now, let's calculate the residuals from the weighted linear fit above:
# Residuals plot
plt.figure(figsize=(8,4))
plt.errorbar(x, resid, yerr=yerr, fmt='o', capsize=4, label='Residuals')
plt.axhline(0, color='k', linestyle='--', alpha=0.8)
plt.xlabel("Days Elapsed"); plt.ylabel("Residual (PCE %)")
plt.title(f"Pixel {pixel_choice}: Residuals (χ²/ν = {chi2_red:.2f})")
plt.grid(True); plt.legend(); plt.tight_layout()
plt.show()1.2 Interpretation of Residuals:
- The error bars represent the measurement uncertainties.
- Residuals should be randomly scattered around zero for a good model fit.
- A pattern in residuals suggests that a linear model is not appropriate.
- If the error bars don't typically cross the zero line, this confirms the model is inadequate.
1.3 Is a Linear Model Appropriate?
For reduced chi-squared, recall that:
- χ²/ν ≈ 1: Indicates a good fit with appropriate uncertainties
- χ²/ν < 1: May indicate overestimated uncertainties or overfitting
- χ²/ν > 1: May indicate underestimated uncertainties or a poor model fit
Question 2: Based on the plot of your residuals and your reduced chi-squared value, do you think that we chose the correct model for our analysis? Why or why not?
Use this cell to answer Question 2
There are two PhET simulations that may be useful for you to play around with to see how different curve fitting models apply to your data set. Have some fun with these:
1.4 Two-Pixel Comparison: Are the Slopes the Same?
Your team may want to compare model fits for your Team project. Here, you will fit two different pixels with separate linear regression fits, then compare:
- Each fit's parameters (slope/intercept with uncertainties) and reduced \(\chi^{2}\)
- Whether the slopes are statistically different.
You will use the same weighted linear regression script to get the slope, intercept, and standard errors and then plot both data sets with their error bars (PCE_unc (%)), plus the two fit lines. Then you will compute a simple z-test for slope difference:
z = \(\frac{m_A - m_B}{\sqrt{\sigma_{m_A}^2 + \sigma_{m_B}^2}}\)
As a rule of thumb, \(|z| > 2\) suggests the slopes differ at roughly the 95% confidence level.
Edit the code below with the two pixels you want to compare (valid: 1,2,3,4,5,6,7,8)
# Two pixel comparison
# Choose two pixels to compare (valid: 1,2,3,4,5,6,7,8)
pixel_A, pixel_B = 1, 2 # <-- update this
# build x,y,yerr for each pixel
def extract_pixel(df, pixel):
d = df[df["Pixel Number"] == pixel].copy()
x = (d["Time (hr)"].astype(float) / 24.0).to_numpy()
y = d["PCE"].astype(float).to_numpy()
yerr = d["PCE_uncertainty (%)"].astype(float).to_numpy()
order = np.argsort(x)
return x[order], y[order], yerr[order]
xA, yA, yerrA = extract_pixel(df, pixel_A)
xB, yB, yerrB = extract_pixel(df, pixel_B)
# weighted linear fit
def weighted_linear_fit(x, y, yerr):
yerr = np.asarray(yerr, float)
mask = (yerr > 0) & np.isfinite(x) & np.isfinite(y)
x, y, yerr = x[mask], y[mask], yerr[mask]
X = np.vstack([x, np.ones_like(x)]).T
w = 1.0 / (yerr**2)
XTW = X.T * w
XTWX = XTW @ X
XTWy = XTW @ y
beta = np.linalg.solve(XTWX, XTWy)
cov = np.linalg.inv(XTWX)
yfit = X @ beta
resid = y - yfit
chi2 = np.sum((resid / yerr)**2)
dof = max(len(y) - 2, 1)
chi2_red = chi2 / dof
cov_scaled = cov * chi2_red
se = np.sqrt(np.diag(cov_scaled))
m, b = float(beta[0]), float(beta[1])
se_m, se_b = float(se[0]), float(se[1])
return m, b, se_m, se_b, chi2, chi2_red, yfit, resid
mA, bA, se_mA, se_bA, chi2A, chi2_redA, yfitA, residA = weighted_linear_fit(xA, yA, yerrA)
mB, bB, se_mB, se_bB, chi2B, chi2_redB, yfitB, residB = weighted_linear_fit(xB, yB, yerrB)
# Calculate value from z-test
z = abs(mA - mB) / np.sqrt(se_mA**2 + se_mB**2)
# Plot both fits on one graph
plt.figure(figsize=(8,6))
plt.errorbar(xA, yA, yerr=yerrA, fmt='o', capsize=4, label=f'Pixel {pixel_A} data')
plt.errorbar(xB, yB, yerr=yerrB, fmt='s', capsize=4, label=f'Pixel {pixel_B} data')
xfit = np.linspace(min(np.min(xA), np.min(xB)), max(np.max(xA), np.max(xB)), 200)
plt.plot(xfit, mA*xfit + bA, '-', label=f'Pixel {pixel_A} weighted fit: y = {mA:.4f}x + {bA:.4f}')
plt.plot(xfit, mB*xfit + bB, '--', label=f'Pixel {pixel_B} weighted fit: y = {mB:.4f}x + {bB:.4f}')
plt.xlabel("Days Elapsed")
plt.ylabel("PCE (%)")
plt.title(f"Weighted Linear Fits for Pixels {pixel_A} (χ²/ν = {chi2_redA:.2f}) and {pixel_B} (χ²/ν = {chi2_redB:.2f})")
plt.legend()
plt.grid(True)
plt.tight_layout()
plt.show()
# Output fits and z-test results
print(f"Pixel {pixel_A}: slope = {mA:.6f} ± {se_mA:.6f}, intercept = {bA:.3f} ± {se_bA:.3f}, reduced χ² = {chi2_redA:.3f}")
print(f"Pixel {pixel_B}: slope = {mB:.6f} ± {se_mB:.6f}, intercept = {bB:.3f} ± {se_bB:.3f}, reduced χ² = {chi2_redB:.3f}")
print(f"\nSlope comparison (z-test): z = {z:.2f}")As a rule of thumb, \(|z| > 2\) suggests the slopes differ at roughly the 95% confidence level.
NOTE: Even if two slopes appear "significantly different" by this rule, that conclusion only makes sense if each linear model adequately describes its data. Keep in mind that large reduced chi-squared (χ²/ν) values mean the scatter or non-linearity in the data dominates over the measurement uncertainties, so any small slope differences should be viewed cautiously.
Question 3: What does your z-test result tell you about the relationship between the two slopes?
Use this cell to answer Question 3
1.4.1 Residuals for the Two Fits
After comparing the two regression lines, check the residuals.
# The residual values were calculated in the weight fits above, so you only
# need to create the plot.
plt.figure(figsize=(10,4))
plt.errorbar(xA, residA, yerr=yerrA, fmt='o', capsize=4, label=f'Pixel {pixel_A} residuals')
plt.errorbar(xB, residB, yerr=yerrB, fmt='s', capsize=4, label=f'Pixel {pixel_B} residuals')
plt.axhline(0, color='k', linestyle='--')
plt.xlabel("Days Elapsed")
plt.ylabel("Residual (PCE %)")
plt.title(f"Residuals for Weighted Fits for Pixels {pixel_A} (χ²/ν = {chi2_redA:.2f}) and {pixel_B} (χ²/ν = {chi2_redB:.2f})")
plt.legend()
plt.grid(True)
plt.tight_layout()
plt.show()Question 4: Based on what you have seen from both the single- and two-pixel fits, do you think a linear model is the right choice for analyzing how PCE changes with time? If yes, explain why. If no, what other types of models or approaches might better describe the trend?
Use this cell to answer Question 4
For potential future use: Here is a notebook that loops through all 8 pixels, calculating and plotting weighted linear fits and residuals for each one. This is useful for your team project when comparing degradation rates across all pixels.
3 Use of AI (required)
- How your team used AI tools: Describe the specific tasks where AI-assisted tools were involved. For example, did AI help with writing, debugging, optimizing, or refining your code? Which components of the analysis did your team use AI on?
- When your team used AI tools: Specify at what stage(s) of your programming process you used AI. Was it during initial code development, troubleshooting, etc.?
- Which AI tools your team used: Identify the AI tools or platforms your team consulted (e.g., ChatGPT, GitHub Copilot, etc.).