LabPod 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- labpod/__init__.py +3 -0
- labpod/cli.py +22 -0
- labpod/protein.py +244 -0
- labpod/test_protein_quant.py +8 -0
- labpod-0.1.0.dist-info/METADATA +14 -0
- labpod-0.1.0.dist-info/RECORD +10 -0
- labpod-0.1.0.dist-info/WHEEL +5 -0
- labpod-0.1.0.dist-info/entry_points.txt +2 -0
- labpod-0.1.0.dist-info/licenses/LICENSE +21 -0
- labpod-0.1.0.dist-info/top_level.txt +1 -0
labpod/__init__.py
ADDED
labpod/cli.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import argparse
|
|
2
|
+
from .protein import protein_quantifier
|
|
3
|
+
|
|
4
|
+
def main():
|
|
5
|
+
p = argparse.ArgumentParser(description="LabPod protein quantifier (BSA curve from Excel).")
|
|
6
|
+
p.add_argument("excel_path", help="Path to Excel file (.xlsx)")
|
|
7
|
+
p.add_argument("n_samples", type=int, help="Number of protein samples (rows A..)")
|
|
8
|
+
p.add_argument("--sheet", default=0, help="Sheet name or index (default 0)")
|
|
9
|
+
p.add_argument("--dilution", type=float, default=1.0, help="Dilution factor (e.g. 10 for 1:10)")
|
|
10
|
+
p.add_argument("--no-plot", action="store_true", help="Disable plot display")
|
|
11
|
+
p.add_argument("--no-csv", action="store_true", help="Do not autosave CSV")
|
|
12
|
+
args = p.parse_args()
|
|
13
|
+
|
|
14
|
+
protein_quantifier(
|
|
15
|
+
args.excel_path,
|
|
16
|
+
args.n_samples,
|
|
17
|
+
sheet=args.sheet,
|
|
18
|
+
dilution_factor=args.dilution,
|
|
19
|
+
show_plot=not args.no_plot,
|
|
20
|
+
autosave_csv=not args.no_csv,
|
|
21
|
+
print_report=True,
|
|
22
|
+
)
|
labpod/protein.py
ADDED
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import Optional, Union, Tuple
|
|
6
|
+
|
|
7
|
+
import numpy as np
|
|
8
|
+
import pandas as pd
|
|
9
|
+
import matplotlib.pyplot as plt
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
DEFAULT_BSA_CONCS = np.array([2000, 1000, 500, 250, 125, 62.5, 31.25, 0], dtype=float)
|
|
13
|
+
ROW_LABELS = list("ABCDEFGH")
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass(frozen=True)
|
|
17
|
+
class ProteinQuantResult:
|
|
18
|
+
r2: float
|
|
19
|
+
slope: float
|
|
20
|
+
intercept: float
|
|
21
|
+
equation: str
|
|
22
|
+
standards: pd.DataFrame
|
|
23
|
+
samples: pd.DataFrame
|
|
24
|
+
fig: plt.Figure
|
|
25
|
+
csv_path: Optional[str]
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _find_plate_block(df: pd.DataFrame) -> Tuple[int, int]:
|
|
29
|
+
for label_col in range(min(10, df.shape[1])):
|
|
30
|
+
col = df.iloc[:, label_col].astype(str).str.strip().str.upper()
|
|
31
|
+
for r in range(0, df.shape[0] - 7):
|
|
32
|
+
if col.iloc[r : r + 8].tolist() == ROW_LABELS:
|
|
33
|
+
return r, label_col
|
|
34
|
+
raise ValueError("Could not find consecutive row labels A–H in the sheet.")
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _numeric_block(df: pd.DataFrame, start_row: int, label_col: int) -> pd.DataFrame:
|
|
38
|
+
block = df.iloc[start_row : start_row + 8, label_col + 1 :].copy()
|
|
39
|
+
block = block.apply(pd.to_numeric, errors="coerce")
|
|
40
|
+
while block.shape[1] > 0 and block.iloc[:, -1].isna().all():
|
|
41
|
+
block = block.iloc[:, :-1]
|
|
42
|
+
return block
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _linear_fit(x: np.ndarray, y: np.ndarray) -> Tuple[float, float, float]:
|
|
46
|
+
mask = np.isfinite(x) & np.isfinite(y)
|
|
47
|
+
x = x[mask]
|
|
48
|
+
y = y[mask]
|
|
49
|
+
if x.size < 2:
|
|
50
|
+
raise ValueError("Not enough valid points to fit a line (need >=2).")
|
|
51
|
+
|
|
52
|
+
slope, intercept = np.polyfit(x, y, 1)
|
|
53
|
+
y_pred = slope * x + intercept
|
|
54
|
+
ss_res = np.sum((y - y_pred) ** 2)
|
|
55
|
+
ss_tot = np.sum((y - np.mean(y)) ** 2)
|
|
56
|
+
r2 = 1.0 - (ss_res / ss_tot if ss_tot != 0 else np.nan)
|
|
57
|
+
return float(slope), float(intercept), float(r2)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def protein_quantifier(
|
|
61
|
+
excel_path: Union[str, Path],
|
|
62
|
+
n_protein_samples: int,
|
|
63
|
+
*,
|
|
64
|
+
sheet: Union[int, str] = 0,
|
|
65
|
+
bsa_concs_ug_ml: Optional[np.ndarray] = None,
|
|
66
|
+
dilution_factor: Union[float, np.ndarray] = 1.0,
|
|
67
|
+
clip_negative: bool = True,
|
|
68
|
+
autosave_csv: bool = True,
|
|
69
|
+
csv_out: Optional[Union[str, Path]] = None,
|
|
70
|
+
show_plot: bool = True,
|
|
71
|
+
print_report: bool = True,
|
|
72
|
+
) -> ProteinQuantResult:
|
|
73
|
+
"""
|
|
74
|
+
One-line user version:
|
|
75
|
+
protein_quantifier("file.xlsx", n_samples)
|
|
76
|
+
|
|
77
|
+
What it does automatically:
|
|
78
|
+
- fits BSA curve (blank-corrected using tube H)
|
|
79
|
+
- prints equation + R²
|
|
80
|
+
- prints a clean concentrations table (final_conc_ug_ml)
|
|
81
|
+
- saves CSV (default on)
|
|
82
|
+
- shows plot (default on)
|
|
83
|
+
|
|
84
|
+
Fixed layout:
|
|
85
|
+
- Column 0: A..H labels
|
|
86
|
+
- Next 3 columns: standards triplicates
|
|
87
|
+
- Next column: gap (ignored)
|
|
88
|
+
- Next 3 columns: protein replicates (cols 5–7)
|
|
89
|
+
- Sample i uses row (A,B,C,...) across those 3 protein replicate columns
|
|
90
|
+
"""
|
|
91
|
+
excel_path = Path(excel_path)
|
|
92
|
+
if not excel_path.exists():
|
|
93
|
+
raise FileNotFoundError(f"Excel file not found: {excel_path}")
|
|
94
|
+
|
|
95
|
+
if not (1 <= n_protein_samples <= 8):
|
|
96
|
+
raise ValueError("n_protein_samples must be between 1 and 8 (rows A..H).")
|
|
97
|
+
|
|
98
|
+
concs = DEFAULT_BSA_CONCS if bsa_concs_ug_ml is None else np.asarray(bsa_concs_ug_ml, dtype=float)
|
|
99
|
+
if concs.shape != (8,):
|
|
100
|
+
raise ValueError("bsa_concs_ug_ml must be length 8 for tubes A..H.")
|
|
101
|
+
|
|
102
|
+
df = pd.read_excel(excel_path, sheet_name=sheet, header=None, engine="openpyxl")
|
|
103
|
+
start_row, label_col = _find_plate_block(df)
|
|
104
|
+
block = _numeric_block(df, start_row, label_col)
|
|
105
|
+
|
|
106
|
+
if block.shape[1] < 7:
|
|
107
|
+
raise ValueError(
|
|
108
|
+
f"Expected at least 7 columns after the A–H label column "
|
|
109
|
+
f"(3 standards + gap + 3 protein replicate cols), but found {block.shape[1]}."
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
# ---- Standards ----
|
|
113
|
+
std_reps = block.iloc[:, 0:3].to_numpy(dtype=float) # (8,3)
|
|
114
|
+
std_mean = np.nanmean(std_reps, axis=1)
|
|
115
|
+
blank = float(std_mean[7]) # tube H
|
|
116
|
+
std_mean_bc = std_mean - blank
|
|
117
|
+
|
|
118
|
+
slope, intercept, r2 = _linear_fit(std_mean_bc, concs)
|
|
119
|
+
equation = f"y = {slope:.4g}x + {intercept:.4g}"
|
|
120
|
+
|
|
121
|
+
standards_df = pd.DataFrame({
|
|
122
|
+
"tube": ROW_LABELS,
|
|
123
|
+
"bsa_conc_ug_ml": concs,
|
|
124
|
+
"rep1": std_reps[:, 0],
|
|
125
|
+
"rep2": std_reps[:, 1],
|
|
126
|
+
"rep3": std_reps[:, 2],
|
|
127
|
+
"mean_abs": std_mean,
|
|
128
|
+
"blank_abs": blank,
|
|
129
|
+
"mean_abs_minus_blank": std_mean_bc,
|
|
130
|
+
})
|
|
131
|
+
|
|
132
|
+
# ---- Protein samples: fixed replicate columns ----
|
|
133
|
+
protein_rep_block = block.iloc[:, 4:7] # after label: [0..2]=std, [3]=gap, [4..6]=protein reps
|
|
134
|
+
samp_reps_all = protein_rep_block.to_numpy(dtype=float) # (8,3)
|
|
135
|
+
samp_reps = samp_reps_all[:n_protein_samples, :] # (n_samples,3)
|
|
136
|
+
|
|
137
|
+
samp_mean = np.nanmean(samp_reps, axis=1)
|
|
138
|
+
samp_mean_bc = samp_mean - blank
|
|
139
|
+
|
|
140
|
+
# Raw back-calc
|
|
141
|
+
calc_conc_raw = slope * samp_mean_bc + intercept
|
|
142
|
+
|
|
143
|
+
# QC flags
|
|
144
|
+
below_blank_flag = samp_mean_bc < 0
|
|
145
|
+
min_x = float(np.nanmin(std_mean_bc))
|
|
146
|
+
max_x = float(np.nanmax(std_mean_bc))
|
|
147
|
+
extrapolated_low_flag = samp_mean_bc < min_x
|
|
148
|
+
extrapolated_high_flag = samp_mean_bc > max_x
|
|
149
|
+
|
|
150
|
+
# Clip negatives (optional)
|
|
151
|
+
if clip_negative:
|
|
152
|
+
used_clipped_flag = calc_conc_raw < 0
|
|
153
|
+
calc_conc = np.maximum(calc_conc_raw, 0.0)
|
|
154
|
+
else:
|
|
155
|
+
used_clipped_flag = np.array([False] * n_protein_samples)
|
|
156
|
+
calc_conc = calc_conc_raw
|
|
157
|
+
|
|
158
|
+
# Dilution
|
|
159
|
+
if np.isscalar(dilution_factor):
|
|
160
|
+
dil = np.full(n_protein_samples, float(dilution_factor))
|
|
161
|
+
else:
|
|
162
|
+
dil = np.asarray(dilution_factor, dtype=float)
|
|
163
|
+
if dil.shape != (n_protein_samples,):
|
|
164
|
+
raise ValueError("If dilution_factor is an array, it must be length n_protein_samples.")
|
|
165
|
+
|
|
166
|
+
final_conc = calc_conc * dil
|
|
167
|
+
|
|
168
|
+
samples_df = pd.DataFrame({
|
|
169
|
+
"sample": [f"Sample_{i+1} (row {ROW_LABELS[i]})" for i in range(n_protein_samples)],
|
|
170
|
+
"rep1": samp_reps[:, 0],
|
|
171
|
+
"rep2": samp_reps[:, 1],
|
|
172
|
+
"rep3": samp_reps[:, 2],
|
|
173
|
+
"mean_abs": samp_mean,
|
|
174
|
+
"mean_abs_minus_blank": samp_mean_bc,
|
|
175
|
+
"calc_conc_ug_ml_raw": calc_conc_raw,
|
|
176
|
+
"calc_conc_ug_ml_used": calc_conc,
|
|
177
|
+
"dilution_factor": dil,
|
|
178
|
+
"final_conc_ug_ml": final_conc,
|
|
179
|
+
"below_blank_flag": below_blank_flag,
|
|
180
|
+
"used_clipped_flag": used_clipped_flag,
|
|
181
|
+
"extrapolated_low_flag": extrapolated_low_flag,
|
|
182
|
+
"extrapolated_high_flag": extrapolated_high_flag,
|
|
183
|
+
})
|
|
184
|
+
|
|
185
|
+
# ---- Plot ----
|
|
186
|
+
fig, ax = plt.subplots()
|
|
187
|
+
ax.scatter(std_mean_bc, concs, label="BSA standards")
|
|
188
|
+
x_line = np.linspace(np.nanmin(std_mean_bc), np.nanmax(std_mean_bc), 200)
|
|
189
|
+
ax.plot(x_line, slope * x_line + intercept, label="Linear fit")
|
|
190
|
+
|
|
191
|
+
ax.set_title("BSA standard curve (blank-corrected)")
|
|
192
|
+
ax.set_xlabel("Absorbance at 620 nm (mean - blank)")
|
|
193
|
+
ax.set_ylabel("BSA concentration (µg/mL)")
|
|
194
|
+
|
|
195
|
+
ax.text(
|
|
196
|
+
0.05, 0.95,
|
|
197
|
+
f"{equation}\nR² = {r2:.4f}",
|
|
198
|
+
transform=ax.transAxes,
|
|
199
|
+
va="top",
|
|
200
|
+
bbox=dict(boxstyle="round", facecolor="white", alpha=0.7),
|
|
201
|
+
)
|
|
202
|
+
ax.legend()
|
|
203
|
+
|
|
204
|
+
if show_plot:
|
|
205
|
+
plt.show()
|
|
206
|
+
|
|
207
|
+
# ---- Print report (one-line UX) ----
|
|
208
|
+
if print_report:
|
|
209
|
+
print("\nBSA standard curve")
|
|
210
|
+
print(f" Equation: {equation}")
|
|
211
|
+
print(f" R²: {r2:.4f}")
|
|
212
|
+
|
|
213
|
+
print("\nProtein sample concentrations (µg/mL)")
|
|
214
|
+
report_cols = [
|
|
215
|
+
"sample",
|
|
216
|
+
"final_conc_ug_ml",
|
|
217
|
+
"below_blank_flag",
|
|
218
|
+
"extrapolated_low_flag",
|
|
219
|
+
"extrapolated_high_flag",
|
|
220
|
+
]
|
|
221
|
+
# Keep terminal output tidy
|
|
222
|
+
print(samples_df[report_cols].to_string(index=False))
|
|
223
|
+
|
|
224
|
+
# ---- Autosave CSV ----
|
|
225
|
+
csv_path_str: Optional[str] = None
|
|
226
|
+
if autosave_csv:
|
|
227
|
+
if csv_out is None:
|
|
228
|
+
csv_out = excel_path.with_name(excel_path.stem + "_protein_results.csv")
|
|
229
|
+
csv_out = Path(csv_out)
|
|
230
|
+
samples_df.to_csv(csv_out, index=False)
|
|
231
|
+
csv_path_str = str(csv_out.resolve())
|
|
232
|
+
if print_report:
|
|
233
|
+
print(f"\nSaved results CSV: {csv_path_str}")
|
|
234
|
+
|
|
235
|
+
return ProteinQuantResult(
|
|
236
|
+
r2=r2,
|
|
237
|
+
slope=slope,
|
|
238
|
+
intercept=intercept,
|
|
239
|
+
equation=equation,
|
|
240
|
+
standards=standards_df,
|
|
241
|
+
samples=samples_df,
|
|
242
|
+
fig=fig,
|
|
243
|
+
csv_path=csv_path_str,
|
|
244
|
+
)
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: LabPod
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Laboratory data analysis tools (starting with protein quantification from BSA curves).
|
|
5
|
+
Author: Myles Hayhurst
|
|
6
|
+
License: MIT
|
|
7
|
+
Requires-Python: >=3.9
|
|
8
|
+
Description-Content-Type: text/markdown
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Requires-Dist: pandas>=2.0
|
|
11
|
+
Requires-Dist: numpy>=1.24
|
|
12
|
+
Requires-Dist: matplotlib>=3.7
|
|
13
|
+
Requires-Dist: openpyxl>=3.1
|
|
14
|
+
Dynamic: license-file
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
labpod/__init__.py,sha256=ZHvZRdhwqhVNA1hbk40Dd62AuSxpvs4yG1M-jMAc650,73
|
|
2
|
+
labpod/cli.py,sha256=otMJYaL0D0dqhTr9AFuPskF32b5q682SAdKA7tspSzM,936
|
|
3
|
+
labpod/protein.py,sha256=ZgxadyqXsSXOAHNU0-E-BCMMnNY6eaPOH52lqAn04fU,8243
|
|
4
|
+
labpod/test_protein_quant.py,sha256=cVnX-7RPXnSLeugzWpnpGQOn91e-QM95euORhWhBV2g,133
|
|
5
|
+
labpod-0.1.0.dist-info/licenses/LICENSE,sha256=zYUYb2MKWiXBnDDF1cCxTuBuB6LAHsR5SRaFRC_itB8,1079
|
|
6
|
+
labpod-0.1.0.dist-info/METADATA,sha256=Z2iyybC6T4etQG5X4Ve_eE3wE3zweOHzrw4hQ4aPGBQ,403
|
|
7
|
+
labpod-0.1.0.dist-info/WHEEL,sha256=wUyA8OaulRlbfwMtmQsvNngGrxQHAvkKcvRmdizlJi0,92
|
|
8
|
+
labpod-0.1.0.dist-info/entry_points.txt,sha256=VFqiNL-WulPSbwaIfNH4TXx8sz58EgHMnkuuAeGpN_Q,51
|
|
9
|
+
labpod-0.1.0.dist-info/top_level.txt,sha256=Ye43GaOBQMgloskDsJUpxw4JK6qdllg3YBg7fjb_wYo,7
|
|
10
|
+
labpod-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Myles Patrick Hayhurst
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
labpod
|