All-Pixel Weighted Fits — Colab Notebook

Last Updated: March 31, 2026 Download notebook (.ipynb)

This notebook extends the single-pixel and two-pixel weighted linear regression analysis from the Data Collection 4 notebook by looping through all 8 pixels automatically.

For each pixel, the code:

  1. Performs a weighted linear fit of PCE vs. time
  2. Generates a plot of the data with the fit line and error bars
  3. Generates a residuals plot
  4. Produces a summary table of fit parameters (\(m\), \(b\), \(\chi^2/\nu\)) for all pixels

This is useful for your team project when you want to compare degradation rates across all pixels at once, rather than running the fit code manually for each one.

1 Setup

Update the file list below to point to your uncertainty CSV files from each week. These are the same files you used in the Data Collection 4 notebook.

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import os

# Update these file names to match your data
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
]
df_all = pd.concat([pd.read_csv(f) for f in files], ignore_index=True)

# Set to True to save plots as PNG files, False to display inline
save_plots = False
outdir = "weighted_fit_all_pixels"
if save_plots:
    os.makedirs(outdir, exist_ok=True)

2 Weighted Linear Fit Function

This is the same weighted_linear_fit function from Data Collection 4. Each data point is weighted by \(1/\sigma^2\), so points with smaller uncertainties have more influence on the fit.

def weighted_linear_fit(x, y, yerr):
    """Weighted linear least-squares fit (y = m*x + b, weights = 1/sigma^2)."""
    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)         # [m, b]
    cov  = np.linalg.inv(XTWX)                 # unscaled covariance

    y_fit = X @ beta
    resid = y - y_fit
    chi2 = np.sum((resid / yerr)**2)
    dof = max(len(y) - 2, 1)
    chi2_red = chi2 / dof

    cov_scaled = cov * chi2_red                 # scale by reduced chi^2
    se = np.sqrt(np.diag(cov_scaled))           # [sigma_m, sigma_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, x, y, yerr

3 Fit All Pixels

The loop below fits each pixel independently and generates two plots per pixel:

  • Fit plot: Data with error bars and the weighted linear fit line
  • Residuals plot: Deviations from the fit, with error bars for comparison

At the end, a summary table collects the fit parameters for easy comparison across pixels.

summary_rows = []

for pixel in range(1, 9):
    dfp = df_all[df_all["Pixel Number"] == pixel].copy()
    if dfp.empty:
        continue

    # Build arrays: x = days, y = PCE (%), yerr = absolute % uncertainty
    x = (dfp["Time (hr)"].astype(float) / 24.0).to_numpy()
    y = dfp["PCE"].astype(float).to_numpy()
    yerr = dfp["PCE_uncertainty (%)"].astype(float).to_numpy()

    order = np.argsort(x)
    x, y, yerr = x[order], y[order], yerr[order]

    if x.size < 2:
        print(f"Pixel {pixel}: insufficient points, skipping.")
        continue

    # Weighted fit
    m, b, se_m, se_b, chi2, chi2_red, y_fit, resid, x_w, y_w, yerr_w = (
        weighted_linear_fit(x, y, yerr)
    )

    summary_rows.append({
        "Pixel": pixel,
        "N points": int(x_w.size),
        "Slope (/day)": m,
        "Slope SE (/day)": se_m,
        "Intercept (%)": b,
        "Intercept SE (%)": se_b,
        "chi2": chi2,
        "chi2/nu": chi2_red,
    })

    # --- Fit plot ---
    xs = np.linspace(np.nanmin(x_w), np.nanmax(x_w), 200)
    ys = m * xs + b

    plt.figure(figsize=(7.5, 5.5))
    plt.errorbar(x_w, y_w, yerr=yerr_w, 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}: Weighted Linear Fit (\u03c7\u00b2/\u03bd = {chi2_red:.2f})")
    plt.grid(True); plt.legend(); plt.tight_layout()
    if save_plots:
        plt.savefig(os.path.join(outdir, f"pixel_{pixel:02d}_fit.png"), dpi=150)
        plt.close()
    else:
        plt.show()

    # --- Residuals plot ---
    plt.figure(figsize=(7.5, 3.8))
    plt.errorbar(x_w, resid, yerr=yerr_w, 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}: Residuals")
    plt.grid(True); plt.legend(); plt.tight_layout()
    if save_plots:
        plt.savefig(os.path.join(outdir, f"pixel_{pixel:02d}_residuals.png"), dpi=150)
        plt.close()
    else:
        plt.show()

4 Summary Table

The table below shows the fit parameters for all pixels. Compare the slopes to see which pixels are degrading faster, and check the \(\chi^2/\nu\) values to assess whether a linear model is appropriate for each pixel.

summary_df = pd.DataFrame(summary_rows).sort_values("Pixel").reset_index(drop=True)
display(summary_df)