-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshared_utils.py
More file actions
1852 lines (1542 loc) · 60.7 KB
/
Copy pathshared_utils.py
File metadata and controls
1852 lines (1542 loc) · 60.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
shared_utils.py
===============
Single shared module for the NIH Catalyze Smart Catheter project.
Covers three analysis pipelines:
- Ammonia/CO₂ extraction: Master sheet loaders, ratio computation
- Spline interpolation: NaOH @ pH=11 (PCHIP) and citric acid @ pH=4 (linear)
- Biomarker analysis: statistics, by-pig plots, summary table
Pipeline order (CSV/PNG artifacts default to ``catalyze/output/``):
ammonia_analysis.ipynb → output/ammonia_*.csv, …
spline_interpolation.ipynb → output/naoh_*.csv, output/citric_*.csv, …
biomarker_analysis.ipynb → output/biomarker_summary.csv + PNGs
Dependencies: pandas, numpy, scipy, matplotlib, openpyxl
"""
import re
import warnings
from pathlib import Path
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
from scipy.interpolate import PchipInterpolator, interp1d
from scipy.stats import mannwhitneyu, ttest_ind
# Avoid globally suppressing warnings in a shared library.
# If a specific warning stream becomes noisy, handle it at the call site.
# ============================================================================
# CONSTANTS
# ============================================================================
HEALTHY_PIGS = ["PIG-04", "PIG-06", "PIG-07", "PIG-08"]
NONHEALTHY_PIGS = ["PIG-01", "PIG-02", "PIG-03", "PIG-05", "PIG-09", "PIG-10"]
ALL_PIGS_ORDER = [f"PIG-{i:02d}" for i in range(1, 11)]
# Master-sheet column names (p1 … p10) grouped for time-series plots
GROUPS_PIG_COLS = {
"Healthy Controls": ["p4", "p6", "p7", "p8"],
"Non-Healthy Controls": ["p1", "p2", "p3", "p5", "p9", "p10"],
}
HEALTHY_COLOR = "#90EE90" # light green
NONHEALTHY_COLOR = "#FFB6C1" # light pink
MEAN_LINE_HEALTHY = "#228B22" # dark green dashed mean line
MEAN_LINE_NONHEALTHY = "#C71585" # dark pink dashed mean line
# Repository root (folder containing this file) and default artifact directory
CATALYZE_DIR = Path(__file__).resolve().parent
DEFAULT_OUTPUT_DIR = CATALYZE_DIR / "output"
def ensure_parent_dir(file_path):
"""
Create the parent directory for a file path if it is missing.
Parameters
----------
file_path : str or pathlib.Path
Path whose parent directory should exist before writing a file.
"""
Path(file_path).parent.mkdir(parents=True, exist_ok=True)
# ============================================================================
# STATISTICS
# ============================================================================
def calculate_statistics(healthy_data, nonhealthy_data):
"""
Compare two groups with t-test, Mann-Whitney U, and Cohen's d.
Parameters
----------
healthy_data : array-like
Observations for the healthy group.
nonhealthy_data : array-like
Observations for the non-healthy group.
Returns
-------
dict
Keys: healthy_mean, healthy_std, nonhealthy_mean, nonhealthy_std,
p_value_ttest, p_value_mannwhitney, cohens_d, diff_percent,
significance_status, effect_size.
"""
healthy_mean = np.mean(healthy_data)
healthy_std = np.std(healthy_data, ddof=1)
nonhealthy_mean = np.mean(nonhealthy_data)
nonhealthy_std = np.std(nonhealthy_data, ddof=1)
t_stat, p_val_ttest = ttest_ind(healthy_data, nonhealthy_data)
u_stat, p_val_mw = mannwhitneyu(healthy_data, nonhealthy_data, alternative="two-sided")
pooled_std = np.sqrt((healthy_std**2 + nonhealthy_std**2) / 2)
cohens_d = (healthy_mean - nonhealthy_mean) / pooled_std
diff_pct = 100 * (healthy_mean - nonhealthy_mean) / nonhealthy_mean
if p_val_ttest < 0.001:
sig_status = "Highly Significant"
elif p_val_ttest < 0.01:
sig_status = "Very Significant"
elif p_val_ttest < 0.05:
sig_status = "Significant"
else:
sig_status = "Not Significant"
d_abs = abs(cohens_d)
if d_abs < 0.2:
effect_size = "None"
elif d_abs < 0.5:
effect_size = "Small"
elif d_abs < 0.8:
effect_size = "Medium"
else:
effect_size = "Large"
return {
"healthy_mean": healthy_mean,
"healthy_std": healthy_std,
"nonhealthy_mean": nonhealthy_mean,
"nonhealthy_std": nonhealthy_std,
"p_value_ttest": p_val_ttest,
"p_value_mannwhitney": p_val_mw,
"cohens_d": cohens_d,
"diff_percent": diff_pct,
"significance_status": sig_status,
"effect_size": effect_size,
}
# ============================================================================
# PLOTTING — by-pig boxplots
# ============================================================================
def pig_facecolor(pig_id):
"""Return box face color for a pig (green = healthy, pink = non-healthy)."""
return HEALTHY_COLOR if pig_id in HEALTHY_PIGS else NONHEALTHY_COLOR
def format_mean_for_legend(x):
"""Format a pooled mean for legend text, adapting to its magnitude."""
if not np.isfinite(x):
return "n/a"
axv = abs(x)
if axv >= 1000 or (axv > 0 and axv < 1e-3):
return f"{x:.3e}"
if axv >= 100:
return f"{x:.1f}"
if axv >= 1:
return f"{x:.2f}"
return f"{x:.3g}"
def plot_biomarkers_by_pig_figure(panels, suptitle, subtitle, output_path, y_axis_scales=None):
"""
One row of subplots: per-pig boxplot (PIG-01 … PIG-10), green vs pink by group.
Parameters
----------
panels : list of tuple
Each entry: (panel_letter, distribution_title, y_axis_label, pig_to_values)
where pig_to_values maps 'PIG-XX' to a 1-D array of measurements.
suptitle : str
Figure title.
subtitle : str
Subtitle line (e.g. legend description).
output_path : str or pathlib.Path
Output PNG path (300 dpi).
y_axis_scales : list of str, optional
Same length as panels; each entry 'linear' or 'log'.
"""
n = len(panels)
if n == 0:
return
scales = (["linear"] * n) if y_axis_scales is None else list(y_axis_scales)
if len(scales) != n:
raise ValueError(f"y_axis_scales length ({len(scales)}) must match panels ({n}).")
fig, axes = plt.subplots(1, n, figsize=(6.2 * n, 6.0))
if n == 1:
axes = [axes]
for ax, (letter, dist_title, ylabel, pig_value_dict), yscale in zip(axes, panels, scales):
data = []
facecolors = []
for pig in ALL_PIGS_ORDER:
vals = np.asarray(pig_value_dict.get(pig, []), dtype=float)
vals = vals[np.isfinite(vals)]
if yscale == "log":
vals = vals[vals > 0]
data.append(vals.tolist() if vals.size else [])
facecolors.append(pig_facecolor(pig))
bp = ax.boxplot(
data,
labels=ALL_PIGS_ORDER,
patch_artist=True,
widths=0.55,
showfliers=True,
medianprops=dict(color="black", linewidth=2),
boxprops=dict(linewidth=1.5),
)
for patch, fc in zip(bp["boxes"], facecolors):
patch.set_facecolor(fc)
if yscale == "log":
ax.set_yscale("log")
h_parts = [np.asarray(data[i]) for i, pig in enumerate(ALL_PIGS_ORDER)
if pig in HEALTHY_PIGS and len(data[i]) > 0]
nh_parts = [np.asarray(data[i]) for i, pig in enumerate(ALL_PIGS_ORDER)
if pig in NONHEALTHY_PIGS and len(data[i]) > 0]
h_pooled = np.concatenate(h_parts) if h_parts else np.array([])
nh_pooled = np.concatenate(nh_parts) if nh_parts else np.array([])
hm = float(np.mean(h_pooled)) if h_pooled.size else float("nan")
nhm = float(np.mean(nh_pooled)) if nh_pooled.size else float("nan")
if h_pooled.size:
ax.axhline(hm, color=MEAN_LINE_HEALTHY, linestyle="--", linewidth=2.2, zorder=1)
if nh_pooled.size:
ax.axhline(nhm, color=MEAN_LINE_NONHEALTHY, linestyle="--", linewidth=2.2, zorder=1)
leg_lines = [
Line2D([0], [0], color=MEAN_LINE_HEALTHY, linestyle="--", linewidth=2.2),
Line2D([0], [0], color=MEAN_LINE_NONHEALTHY, linestyle="--", linewidth=2.2),
]
ax.legend(
leg_lines,
[f"Healthy mean\n{format_mean_for_legend(hm)}",
f"Non-Healthy mean\n{format_mean_for_legend(nhm)}"],
loc="upper left", fontsize=9, framealpha=0.95,
)
ax.set_title(f"{letter}. {dist_title}", fontsize=12, fontweight="bold", pad=8)
ax.set_xlabel("Pig ID", fontsize=11, fontweight="bold")
ax.set_ylabel(ylabel, fontsize=11, fontweight="bold")
ax.tick_params(axis="x", rotation=45)
ax.grid(True, alpha=0.3, axis="y", which="both" if yscale == "log" else "major")
fig.suptitle(suptitle, fontsize=14, fontweight="bold", y=1.02)
fig.text(0.5, 0.965, subtitle, ha="center", fontsize=11, style="italic")
plt.tight_layout(rect=[0, 0, 1, 0.88])
out = Path(output_path)
out.parent.mkdir(parents=True, exist_ok=True)
plt.savefig(out, dpi=300, bbox_inches="tight")
plt.close()
print(f"✓ Saved: {out}")
def plot_timeseries_by_group(df, ylabel, title, log_y=False, groups=None):
"""
Plot time-series concentration data side-by-side for each pig group.
Parameters
----------
df : pandas.DataFrame
Wide format with a 'Cumulative time (min)' column and pig columns (p1, …).
ylabel : str
Y-axis label.
title : str
Figure super-title.
log_y : bool
Use log scale on the y-axis.
groups : dict, optional
Maps group label → list of pig column names. Defaults to GROUPS_PIG_COLS.
"""
if groups is None:
groups = GROUPS_PIG_COLS
fig, axes = plt.subplots(1, len(groups), figsize=(7 * len(groups), 6))
if len(groups) == 1:
axes = [axes]
for ax, (group_label, pig_cols) in zip(axes, groups.items()):
for pig_col in pig_cols:
if pig_col not in df.columns:
continue
mask = df[pig_col].notna()
ax.plot(
df.loc[mask, "Cumulative time (min)"],
df.loc[mask, pig_col],
marker="o", markersize=4, linewidth=1.5, label=pig_col,
)
if log_y:
ax.set_yscale("log")
ax.set_title(group_label)
ax.set_xlabel("Cumulative time (min)")
ax.set_ylabel(ylabel)
ax.legend(title="Pig", bbox_to_anchor=(1.01, 1), loc="upper left")
ax.grid(True, alpha=0.3)
all_ylims = [ax.get_ylim() for ax in axes]
for ax in axes:
ax.set_ylim(min(lim[0] for lim in all_ylims), max(lim[1] for lim in all_ylims))
plt.suptitle(title)
plt.tight_layout()
plt.show()
def plot_combined_timeseries(ammonia_df, co2_df, ratio_df):
"""
Three-panel figure: ammonia, CO₂, and ratio vs cumulative time (all pigs).
Parameters
----------
ammonia_df : pandas.DataFrame
co2_df : pandas.DataFrame
ratio_df : pandas.DataFrame
All three must have a 'Cumulative time (min)' column and pig columns.
"""
fig, (ax_amm, ax_co2, ax_ratio) = plt.subplots(1, 3, figsize=(21, 6))
pig_cols = [c for c in ammonia_df.columns if c.startswith("p")]
for pig_col in pig_cols:
for ax, df, log_y in [
(ax_amm, ammonia_df, False),
(ax_co2, co2_df, False),
(ax_ratio, ratio_df, True),
]:
if pig_col not in df.columns:
continue
mask = df[pig_col].notna()
ax.plot(
df.loc[mask, "Cumulative time (min)"],
df.loc[mask, pig_col],
marker="o", markersize=4, linewidth=1.5, label=pig_col,
)
panel_cfg = [
(ax_amm, "Ammonia concentration (mM)", "Ammonia", False),
(ax_co2, "Carbon dioxide concentration (mM)", "Carbon Dioxide", False),
(ax_ratio, "Ammonia / CO\u2082 ratio (log scale)", "Ammonia / CO\u2082", True),
]
for ax, ylabel, panel_title, log_y in panel_cfg:
ax.set_title(panel_title)
ax.set_xlabel("Cumulative time (min)")
ax.set_ylabel(ylabel)
if log_y:
ax.set_yscale("log")
ax.legend(title="Pig", bbox_to_anchor=(1.01, 1), loc="upper left")
ax.grid(True, alpha=0.3)
plt.suptitle("Ammonia, CO\u2082, and Ammonia/CO\u2082 ratio vs cumulative time (Control Pigs)")
plt.tight_layout()
plt.show()
# ============================================================================
# DATA HELPERS
# ============================================================================
def pooled_from_pig_series_dict(pig_value_dict, pig_ids):
"""
Concatenate all finite observations for pigs listed in pig_ids.
Parameters
----------
pig_value_dict : dict
Maps 'PIG-XX' to a 1-D array-like of values.
pig_ids : iterable of str
Pig identifiers to include.
Returns
-------
numpy.ndarray
Pooled finite values, shape (0,) if none available.
"""
parts = []
for p in pig_ids:
v = np.asarray(pig_value_dict.get(p, []), dtype=float)
v = v[np.isfinite(v)]
if v.size:
parts.append(v)
return np.concatenate(parts) if parts else np.array([])
def master_wide_df_to_pig_dict(df):
"""
Convert a wide Master-sheet DataFrame (columns p1 … p10) to a pig dict.
Parameters
----------
df : pandas.DataFrame
Must include p1 … p10 columns (or a subset).
Returns
-------
dict
'PIG-XX' → 1-D numpy.ndarray of finite values.
"""
out = {}
for pig in ALL_PIGS_ORDER:
col = f"p{int(pig.split('-')[1])}"
if col not in df.columns:
out[pig] = np.array([])
continue
v = df[col].dropna().to_numpy(dtype=float)
out[pig] = v[np.isfinite(v)]
return out
def pig_ids_to_master_sheet_columns(pig_ids):
"""
Map 'PIG-04' style identifiers to Master-sheet column names ('p4').
Parameters
----------
pig_ids : list of str
Returns
-------
list of str
"""
return [f"p{int(p.split('-')[1])}" for p in pig_ids]
def pooled_biomarker_values_for_pigs(df, pig_ids):
"""
Pool all non-null, finite values for the given pigs from a wide DataFrame.
Parameters
----------
df : pandas.DataFrame
Wide table with one column per pig (p1, …).
pig_ids : list of str
'PIG-' identifiers.
Returns
-------
numpy.ndarray
1-D pooled array (may be empty).
"""
cols = pig_ids_to_master_sheet_columns(pig_ids)
parts = []
for col in cols:
if col not in df.columns:
continue
series = df[col].dropna().to_numpy(dtype=float)
series = series[np.isfinite(series)]
if series.size:
parts.append(series)
return np.concatenate(parts) if parts else np.array([])
def pig_dict_from_spline_long_csv(csv_path, value_column_prefix):
"""
Build a per-pig value dict from a long-format spline results CSV.
Parameters
----------
csv_path : str or pathlib.Path
CSV with 'Pig' column and a value column.
value_column_prefix : str
The first column whose stripped name starts with this prefix is used
(e.g. 'NaOH @ pH=11', 'Citric @ pH=4').
Returns
-------
dict
'PIG-01' … 'PIG-10' → 1-D float arrays (empty if data missing).
"""
out = {p: np.array([], dtype=float) for p in ALL_PIGS_ORDER}
path = Path(csv_path)
if not path.is_file():
return out
df = pd.read_csv(path)
if "Pig" not in df.columns:
return out
val_col = next(
(c for c in df.columns if str(c).strip().startswith(value_column_prefix)),
None,
)
if val_col is None:
return out
for pig, grp in df.groupby("Pig"):
pig = str(pig).strip()
if pig not in out:
continue
v = grp[val_col].dropna().to_numpy(dtype=float)
out[pig] = v[np.isfinite(v)]
return out
def scale_pig_series_dict(pig_dict, factor):
"""
Multiply each pig's observation vector by a scalar (e.g. mol/L → mM).
Parameters
----------
pig_dict : dict
Maps pig ID to 1-D array-like.
factor : float
Returns
-------
dict
New dict with scaled numpy.ndarray values.
"""
return {pig: np.asarray(vals, dtype=float) * factor for pig, vals in pig_dict.items()}
# ============================================================================
# EXCEL LOADERS — phosphate, creatinine, urine pH
# ============================================================================
def read_phosphate_creatinine_by_pig(input_file):
"""
Load per-pig phosphate and creatinine series from the titration workbook.
Parameters
----------
input_file : str or pathlib.Path
Excel workbook with a 'PHOSPHATE and CREATININE' sheet.
Returns
-------
tuple of dict
(phosphate_data, creatinine_data), each mapping 'PIG-XX' to values.
"""
df = pd.read_excel(input_file, sheet_name="PHOSPHATE and CREATININE", nrows=13)
phosphate_cols = [3, 6, 9, 12, 15, 18, 21, 24, 28, 31]
pig_names = [f"PIG-{i:02d}" for i in range(1, 11)]
phosphate_data = {}
for pig, col_idx in zip(pig_names, phosphate_cols):
raw = df.iloc[:, col_idx].dropna().to_numpy(dtype=float)
phosphate_data[pig] = raw[np.isfinite(raw)]
creatinine_cols = [38, 41, 44, 47, 50, 53, 56, 59, 62, 65]
creatinine_pig_order = [
"PIG-03", "PIG-01", "PIG-02", "PIG-04", "PIG-05",
"PIG-06", "PIG-07", "PIG-08", "PIG-09", "PIG-10",
]
creatinine_data = {}
for pig, col_idx in zip(creatinine_pig_order, creatinine_cols):
raw = df.iloc[:, col_idx].dropna().to_numpy(dtype=float)
creatinine_data[pig] = raw[np.isfinite(raw)]
return phosphate_data, creatinine_data
def load_urine_ph_by_pig(input_file):
"""
Load direct urine pH per pig from the 'pHi, OSM, Vol rate' sheet.
Parameters
----------
input_file : str or pathlib.Path
Returns
-------
dict
'PIG-XX' → 1-D array of pH values.
"""
df = pd.read_excel(input_file, sheet_name="pHi, OSM, Vol rate", nrows=18)
out = {}
for pig in ALL_PIGS_ORDER:
if pig in df.columns:
v = df[pig].dropna().to_numpy(dtype=float)
out[pig] = v[np.isfinite(v)]
else:
out[pig] = np.array([])
return out
# ============================================================================
# AMMONIA / CO₂ — Master sheet extraction
# ============================================================================
_SAMPLE_LABEL_RE = re.compile(r"^UB?\d{2,}$", re.IGNORECASE)
def _is_sample_label(value):
"""Return True only if value matches expected sample ID pattern (U01, UB03, …)."""
return bool(_SAMPLE_LABEL_RE.match(str(value).strip()))
def _label_sort_key(label):
"""Sort UB labels before U labels, both in ascending numeric order."""
m = re.match(r"^(UB?)(\d+)$", label, re.IGNORECASE)
if m:
return (0 if m.group(1).upper() == "UB" else 1, int(m.group(2)))
return (2, label)
def _cumulative_time(label, max_ub):
"""
Convert a sample label to cumulative time in minutes.
The last UB label maps to time 0; earlier UBs step back by -20 each.
U labels step forward by 20 (U01 = 20 min, U02 = 40 min, …).
"""
m = re.match(r"^(UB?)(\d+)$", label, re.IGNORECASE)
num = int(m.group(2))
if m.group(1).upper() == "UB":
return (num - max_ub) * 20
return num * 20
def _load_sheet(filepath, sheet_name, label_col):
"""
Load an Excel sheet, auto-detecting the header row by locating label_col.
Parameters
----------
filepath : str or pathlib.Path
sheet_name : str
label_col : str
Column name used to identify the header row.
Returns
-------
pandas.DataFrame
Data below the header row, with proper column names.
"""
df_raw = pd.read_excel(filepath, sheet_name=sheet_name, header=None)
header_row = 0
label_lower = label_col.strip().lower()
for i in range(min(10, len(df_raw))):
if (df_raw.iloc[i].astype(str).str.strip().str.lower() == label_lower).any():
header_row = i
break
df_raw.columns = df_raw.iloc[header_row]
return df_raw.iloc[header_row + 1:].reset_index(drop=True)
def _find_column(df, patterns, match_type="exact"):
"""
Find a DataFrame column by name matching.
Parameters
----------
df : pandas.DataFrame
patterns : list of str
For 'exact': normalized column name must equal one of the patterns.
For 'contains': column name must contain all substrings.
match_type : {'exact', 'contains'}
Returns
-------
Column label or None.
"""
for col in df.columns:
c_lower = re.sub(r"\s+", " ", str(col).strip()).lower()
if match_type == "exact":
normalized = [re.sub(r"\s+", " ", p).lower() for p in patterns]
if c_lower in normalized:
return col
else:
if all(s.lower() in c_lower for s in patterns):
return col
return None
def _extract_pig_series(df, pig_col_name, label_col, conc_col):
"""
Extract label and concentration from a loaded sheet for one pig.
Parameters
----------
df : pandas.DataFrame
Output of _load_sheet.
pig_col_name : str
Column name to assign to concentration values (e.g. 'p4').
label_col : str
Name of the sample label column.
conc_col : str
Name of the concentration column (exact match tried first, then contains).
Returns
-------
pandas.DataFrame or None
Two columns ['Label', pig_col_name], filtered to valid sample IDs.
"""
lc = _find_column(df, [label_col], match_type="exact")
cc = _find_column(df, [conc_col], match_type="exact")
if cc is None:
keywords = [w for w in re.split(r"[\s()]+", conc_col) if len(w) > 1]
cc = _find_column(df, keywords, match_type="contains")
if lc is None or cc is None:
return None
result = df[[lc, cc]].copy()
result.columns = ["Label", pig_col_name]
result["Label"] = result["Label"].astype(str).str.strip()
return result[result["Label"].apply(_is_sample_label)].copy()
def _get_pig_number(filename):
"""Extract pig number from a Master sheet filename (PFI01 → 1, PFI10 → 10)."""
m = re.search(r"PFI(\d+)", filename, re.IGNORECASE)
return int(m.group(1)) if m else None
def _load_analyte_from_master_sheets(filepaths, sheet_name, label_col, conc_col, verbose=True):
"""
Load one analyte from all Master sheet workbooks.
Returns
-------
tuple
(data_dict, pig_cols, all_labels) where data_dict maps (label, pig_col) → value.
"""
data = {}
pig_cols = []
for filepath in filepaths:
pig_num = _get_pig_number(filepath.name)
if verbose:
print(f" {filepath.name} ...", end=" ", flush=True)
if pig_num is None:
if verbose:
print("skipped (no pig number)")
continue
pig_col = f"p{pig_num}"
df_raw = _load_sheet(filepath, sheet_name, label_col)
df_pig = _extract_pig_series(df_raw, pig_col, label_col, conc_col)
if df_pig is None:
if verbose:
print("skipped (missing columns)")
continue
pig_cols.append(pig_col)
for _, row in df_pig.iterrows():
key = (row["Label"], pig_col)
if key not in data:
data[key] = row[pig_col]
if verbose:
print("OK")
all_labels = sorted({k[0] for k in data.keys()}, key=_label_sort_key)
return data, pig_cols, all_labels
def _build_analyte_df(data, pig_cols, all_labels):
"""
Build a wide time-series DataFrame from an extracted analyte data dict.
Parameters
----------
data : dict
Maps (label, pig_col) → concentration value.
pig_cols : list of str
all_labels : list of str
Returns
-------
pandas.DataFrame
Columns: Label, Cumulative time (min), p1, p2, …
"""
df = pd.DataFrame({"Label": all_labels})
for pig_col in pig_cols:
df[pig_col] = df["Label"].map(lambda L, pc=pig_col: data.get((L, pc), np.nan))
ub_nums = [
int(re.match(r"^UB(\d+)$", L, re.IGNORECASE).group(1))
for L in df["Label"] if re.match(r"^UB\d+$", L, re.IGNORECASE)
]
max_ub = max(ub_nums) if ub_nums else 0
df.insert(
1, "Cumulative time (min)",
df["Label"].apply(lambda L: _cumulative_time(L, max_ub)),
)
return df
def load_ammonia_co2_dataframes(master_dir="Master sheets", verbose=True):
"""
Load all Master sheet Excel files and return ammonia, CO₂, and ratio DataFrames.
Parameters
----------
master_dir : str or pathlib.Path
Folder containing PFI##-Control-Master sheet_*.xlsx workbooks.
verbose : bool
Print per-file progress.
Returns
-------
tuple of pandas.DataFrame
(ammonia_df, co2_df, ratio_df) in wide format:
columns = [Label, Cumulative time (min), p1, p2, …, p10].
"""
master_path = Path(master_dir)
if not master_path.exists():
raise FileNotFoundError(f"Master sheets folder not found: {master_path}")
filepaths = [
f for f in sorted(master_path.glob("*.xlsx")) + sorted(master_path.glob("*.xls"))
if not f.name.startswith("~")
]
if verbose:
print("Loading Ammonia sheets …")
amm_data, amm_cols, amm_labels = _load_analyte_from_master_sheets(
filepaths, "Ammonia", "Label", "Ammonia concentration (mM)", verbose=verbose,
)
ammonia_df = _build_analyte_df(amm_data, amm_cols, amm_labels)
if verbose:
print("\nLoading Carbon dioxide sheets …")
co2_data, co2_cols, co2_labels = _load_analyte_from_master_sheets(
filepaths, "Carbon dioxide", "Sample", "Concentration (mM)", verbose=verbose,
)
co2_df = _build_analyte_df(co2_data, co2_cols, co2_labels)
ratio_df = ammonia_df[["Label", "Cumulative time (min)"]].copy()
pig_cols = [c for c in ammonia_df.columns if c.startswith("p")]
for pig_col in pig_cols:
if pig_col in co2_df.columns:
ratio_df[pig_col] = ammonia_df[pig_col].values / co2_df[pig_col].values
if verbose:
print(f"\nAmmonia shape: {ammonia_df.shape}, CO₂ shape: {co2_df.shape}, "
f"Ratio shape: {ratio_df.shape}")
return ammonia_df, co2_df, ratio_df
# ============================================================================
# SPLINE INTERPOLATION
# ============================================================================
def extract_titration_data(filepath, sheet_name, verbose=True):
"""
Extract NaOH titration data from an Excel ACIDITY sheet (columns A–K).
Column B = NaOH concentration; columns C–K = pH per time point.
Parameters
----------
filepath : str or pathlib.Path
sheet_name : str
Sheet name (typically 'ACIDITY').
verbose : bool
Returns
-------
dict
'PIG-XX' → {'time_points', 'naoh_conc', 'ph_matrix'}.
"""
if verbose:
print("=" * 80)
print("EXTRACTING DATA FROM EXCEL (ACIDITY)")
print("=" * 80)
df = pd.read_excel(filepath, sheet_name=sheet_name)
df_cols = df.iloc[:, :11]
pig_starts = [
(str(val), idx)
for idx, val in enumerate(df_cols.iloc[:, 0])
if pd.notna(val) and "PIG-" in str(val)
]
if verbose:
print(f"\nFound {len(pig_starts)} pigs")
all_pig_data = {}
for pig_name, start_row in pig_starts:
time_points = [
float(val)
for val in df_cols.iloc[start_row, 2:11]
if pd.notna(val) and str(val) != "min" and _can_float(val)
]
naoh_conc = []
ph_matrix = []
row_idx = start_row + 2
while row_idx < len(df_cols):
naoh_val = df_cols.iloc[row_idx, 1]
if pd.isna(naoh_val):
break
try:
naoh_conc.append(float(naoh_val))
ph_row = [
float(df_cols.iloc[row_idx, c]) if pd.notna(df_cols.iloc[row_idx, c]) else np.nan
for c in range(2, 11)
]
ph_matrix.append(ph_row)
row_idx += 1
except (ValueError, TypeError):
break
all_pig_data[pig_name] = {
"time_points": np.array(time_points),
"naoh_conc": np.array(naoh_conc),
"ph_matrix": np.array(ph_matrix),
}
if verbose and naoh_conc:
print(f" {pig_name}: {len(time_points)} times, {len(naoh_conc)} conc × pH")
if verbose:
print(f"✓ Data extraction complete for {len(all_pig_data)} pigs\n")
return all_pig_data
def extract_alkalinity_data(filepath, sheet_name, verbose=True):
"""
Extract citric acid titration data from an Excel ALKALINITY sheet (columns A–K).
Same layout as ACIDITY: column B = citric concentration, columns C–K = pH per time.
Parameters
----------
filepath : str or pathlib.Path
sheet_name : str
Sheet name (typically 'ALKALINITY').
verbose : bool
Returns
-------
dict
'PIG-XX' → {'time_points', 'citric_conc', 'ph_matrix'}.
"""
if verbose:
print("=" * 80)
print("EXTRACTING CITRIC ACID DATA FROM ALKALINITY SHEET")
print("=" * 80)
df = pd.read_excel(filepath, sheet_name=sheet_name)
df_cols = df.iloc[:, :11]
pig_starts = [
(str(val), idx)
for idx, val in enumerate(df_cols.iloc[:, 0])
if pd.notna(val) and "PIG-" in str(val)
]
if verbose:
print(f"\nFound {len(pig_starts)} pigs in ALKALINITY sheet")
all_pig_data = {}
for pig_name, start_row in pig_starts:
time_points = [
float(val)
for val in df_cols.iloc[start_row, 2:11]
if pd.notna(val) and str(val) != "min" and _can_float(val)
]
citric_conc = []
ph_matrix = []
row_idx = start_row + 2
while row_idx < len(df_cols):
citric_val = df_cols.iloc[row_idx, 1]
if pd.isna(citric_val):
break
try:
citric_conc.append(float(citric_val))
ph_row = [
float(df_cols.iloc[row_idx, c]) if pd.notna(df_cols.iloc[row_idx, c]) else np.nan
for c in range(2, 11)
]
ph_matrix.append(ph_row)
row_idx += 1
except (ValueError, TypeError):
break
all_pig_data[pig_name] = {
"time_points": np.array(time_points),
"citric_conc": np.array(citric_conc),
"ph_matrix": np.array(ph_matrix),
}
if verbose:
print(f"✓ Citric data extraction complete for {len(all_pig_data)} pigs\n")
return all_pig_data
def _can_float(val):
"""Return True if val can be converted to float."""
try:
float(val)
return True
except (ValueError, TypeError):
return False
def interpolate_naoh_at_pH(naoh_conc, ph_values, target_pH):
"""
Use PCHIP monotonic cubic spline to find NaOH concentration at target pH.
Parameters
----------
naoh_conc : array-like
ph_values : array-like
target_pH : float
Returns
-------
tuple
(naoh_at_target: float, success: bool). Returns (nan, False) on failure.
"""
valid = ~np.isnan(ph_values)
naoh = naoh_conc[valid]
ph = ph_values[valid]