75 lines
2.0 KiB
Python
75 lines
2.0 KiB
Python
#%%
|
|
from pathlib import Path
|
|
import numpy as np
|
|
import pandas as pd
|
|
import matplotlib.pyplot as plt
|
|
|
|
folder = Path(r"C:\Users\tschan_d\Documents\code\ACLC26_DataAnalysis\labcourse_TOC2026")
|
|
|
|
# Input your measured signal values here
|
|
measured_signal = [4, 5]
|
|
|
|
txt_files = sorted(folder.glob("*.txt"))
|
|
|
|
for file_path in txt_files:
|
|
# Read tab-separated file
|
|
df = pd.read_csv(file_path, sep="\t")
|
|
|
|
# First column = concentration, second column = signal
|
|
x = df.iloc[:, 0].to_numpy(dtype=float)
|
|
y = df.iloc[:, 1].to_numpy(dtype=float)
|
|
|
|
# Linear fit: y = slope * x + intercept
|
|
slope, intercept = np.polyfit(x, y, 1)
|
|
|
|
# Fitted y values
|
|
y_fit = slope * x + intercept
|
|
|
|
# R2 calculation
|
|
ss_res = np.sum((y - y_fit) ** 2)
|
|
ss_tot = np.sum((y - np.mean(y)) ** 2)
|
|
r2 = 1 - ss_res / ss_tot
|
|
|
|
# Convert measured signal y back to concentration x
|
|
measured_signal_array = np.array(measured_signal, dtype=float)
|
|
calculated_concentration = (measured_signal_array - intercept) / slope
|
|
|
|
print("\nFile:", file_path.name)
|
|
print(f"Fit equation: signal = {slope:.4f} * concentration + {intercept:.4f}")
|
|
print(f"R2 = {r2:.6f}")
|
|
|
|
for sig, conc in zip(measured_signal_array, calculated_concentration):
|
|
print(f"Measured signal {sig} -> concentration {conc:.4f}")
|
|
|
|
# Smooth line for plotting
|
|
x_line = np.linspace(x.min(), x.max(), 100)
|
|
y_line = slope * x_line + intercept
|
|
|
|
# Plot
|
|
plt.figure(figsize=(7, 5))
|
|
plt.scatter(x, y, label="Calibration data")
|
|
plt.plot(x_line, y_line, color="red", label="Linear fit")
|
|
|
|
equation_text = (
|
|
f"signal = {slope:.4f} x + {intercept:.4f}\n"
|
|
f"R2 = {r2:.4f}"
|
|
)
|
|
|
|
plt.text(
|
|
0.05,
|
|
0.95,
|
|
equation_text,
|
|
transform=plt.gca().transAxes,
|
|
verticalalignment="top",
|
|
bbox=dict(facecolor="white", alpha=0.8)
|
|
)
|
|
|
|
plt.xlabel(df.columns[0])
|
|
plt.ylabel(df.columns[1])
|
|
plt.title(file_path.stem)
|
|
plt.legend()
|
|
plt.grid(True)
|
|
plt.tight_layout()
|
|
plt.show()
|
|
# %%
|