biolaser-twin 0.2.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.
- biolaser_twin/__init__.py +3 -0
- biolaser_twin/calibration.py +29 -0
- biolaser_twin/constants.py +25 -0
- biolaser_twin/extractor/__init__.py +15 -0
- biolaser_twin/extractor/frame_features.py +243 -0
- biolaser_twin/identifiability/__init__.py +47 -0
- biolaser_twin/identifiability/doe.py +111 -0
- biolaser_twin/identifiability/fisher.py +139 -0
- biolaser_twin/identifiability/observability.py +227 -0
- biolaser_twin/identifiability/profile_likelihood.py +311 -0
- biolaser_twin/kinetics_nominal/__init__.py +25 -0
- biolaser_twin/kinetics_nominal/priors.py +59 -0
- biolaser_twin/kinetics_nominal/reduced_moments.py +92 -0
- biolaser_twin/kinetics_nominal/symbolic_check.py +33 -0
- biolaser_twin/metrics.py +44 -0
- biolaser_twin/observations.py +275 -0
- biolaser_twin/simulator/__init__.py +60 -0
- biolaser_twin/simulator/aggregate_optics.py +204 -0
- biolaser_twin/simulator/fp_cavity.py +398 -0
- biolaser_twin/simulator/kinetics/__init__.py +39 -0
- biolaser_twin/simulator/kinetics/analytic.py +62 -0
- biolaser_twin/simulator/kinetics/mechanisms.py +146 -0
- biolaser_twin/simulator/kinetics/moments.py +116 -0
- biolaser_twin/simulator/kinetics/population_balance.py +311 -0
- biolaser_twin/simulator/kinetics/symbolic_audit.py +304 -0
- biolaser_twin/simulator/longitudinal.py +98 -0
- biolaser_twin/simulator/photophysics.py +159 -0
- biolaser_twin/simulator/proxy_map.py +32 -0
- biolaser_twin/simulator/sggw_dbr_mirror_spectra.json +2102 -0
- biolaser_twin/simulator/sggw_exp_lasing_spectrum_96.json +83 -0
- biolaser_twin/solvers/__init__.py +59 -0
- biolaser_twin/solvers/baselines.py +437 -0
- biolaser_twin/solvers/classical_nls.py +123 -0
- biolaser_twin/solvers/kinetic_classical.py +276 -0
- biolaser_twin/solvers/kinetic_modern.py +266 -0
- biolaser_twin/solvers/kinetic_pielm.py +532 -0
- biolaser_twin/solvers/kinetic_sbi.py +174 -0
- biolaser_twin/solvers/kinetic_ude.py +185 -0
- biolaser_twin/solvers/photonic_pielm.py +248 -0
- biolaser_twin-0.2.0.dist-info/METADATA +116 -0
- biolaser_twin-0.2.0.dist-info/RECORD +44 -0
- biolaser_twin-0.2.0.dist-info/WHEEL +5 -0
- biolaser_twin-0.2.0.dist-info/licenses/LICENSE +21 -0
- biolaser_twin-0.2.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"""Shared split-conformal calibration for fair UQ across all inverse solvers."""
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
from scipy.stats import norm
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class SplitConformalCalibrator:
|
|
8
|
+
"""Per-latent multiplicative split-conformal calibrator fitted on Level 1 val."""
|
|
9
|
+
|
|
10
|
+
def __init__(self, alpha: float = 0.10) -> None:
|
|
11
|
+
if not (0.0 < alpha < 1.0):
|
|
12
|
+
raise ValueError("alpha must be in (0, 1)")
|
|
13
|
+
self.alpha = alpha
|
|
14
|
+
self.scales: np.ndarray | None = None
|
|
15
|
+
|
|
16
|
+
def fit(self, y_true: np.ndarray, y_mean: np.ndarray, y_std: np.ndarray) -> "SplitConformalCalibrator":
|
|
17
|
+
"""Compute finite-sample conformal order-statistic scaling factors per latent."""
|
|
18
|
+
scores = np.abs(y_true - y_mean) / np.maximum(y_std, 1e-8)
|
|
19
|
+
n = scores.shape[0]
|
|
20
|
+
q_level = min(1.0, ((1.0 - self.alpha) * (n + 1)) / max(n, 1))
|
|
21
|
+
self.scales = np.quantile(scores, q_level, axis=0, method="higher")
|
|
22
|
+
return self
|
|
23
|
+
|
|
24
|
+
def calibrate_std(self, y_std: np.ndarray) -> np.ndarray:
|
|
25
|
+
"""Scale predictive stds so z_{1-alpha/2} * std_cal matches conformal half-width."""
|
|
26
|
+
if self.scales is None:
|
|
27
|
+
raise RuntimeError("SplitConformalCalibrator must be fitted before calibrate_std().")
|
|
28
|
+
z_alpha = float(norm.ppf(1.0 - 0.5 * self.alpha))
|
|
29
|
+
return np.maximum(y_std, 1e-8) * (self.scales / z_alpha)
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"""Separate nominal constants registry for solvers/identifiability vs. truth generator."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
import numpy as np
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
LATENT_NAMES: tuple[str, ...] = ("nL_um", "z1_visc", "z2_bound", "z4_scat")
|
|
8
|
+
LATENT_PRIOR_SCALES: np.ndarray = np.array([35.0, 0.30, 0.30, 4.0], dtype=float)
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@dataclass(frozen=True)
|
|
12
|
+
class NominalOpticalConstants:
|
|
13
|
+
"""Nominal optical and dye constants exposed to inverse solvers and FIM/DoE.
|
|
14
|
+
|
|
15
|
+
Strictly separated from truth-generator parameter draws to prevent inverse crime.
|
|
16
|
+
gain_scale_kappa is calibrated strictly on Level 0 / dev data only.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
n_water_nominal: float = 1.333
|
|
20
|
+
mirror_reflectivity_nominal: float = 0.99
|
|
21
|
+
tht_molar_absorptivity_412: float = 36000.0 # M^-1 cm^-1
|
|
22
|
+
spec_resolution_nm_nominal: float = 0.10
|
|
23
|
+
nominal_tht_conc_mm: float = 10.0
|
|
24
|
+
gain_scale_kappa: float = 1.0
|
|
25
|
+
scat_scale_nominal: float = 0.02
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"""Frame-level observable feature extraction shared across synthetic and real data."""
|
|
2
|
+
|
|
3
|
+
from .frame_features import (
|
|
4
|
+
ExtractedFeatures,
|
|
5
|
+
SweepFeatures,
|
|
6
|
+
extract_spectral_features,
|
|
7
|
+
extract_sweep_features,
|
|
8
|
+
)
|
|
9
|
+
|
|
10
|
+
__all__ = [
|
|
11
|
+
"ExtractedFeatures",
|
|
12
|
+
"SweepFeatures",
|
|
13
|
+
"extract_spectral_features",
|
|
14
|
+
"extract_sweep_features",
|
|
15
|
+
]
|
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
"""Physical feature extraction from 1D spectra and 2D spatial-spectral frames."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
import numpy as np
|
|
5
|
+
from scipy.signal import find_peaks
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
@dataclass(frozen=True)
|
|
9
|
+
class ExtractedFeatures:
|
|
10
|
+
"""Observable physical summary vector extracted from a frame or spectrum."""
|
|
11
|
+
|
|
12
|
+
center_of_mass_nm: float
|
|
13
|
+
spectral_variance_nm2: float
|
|
14
|
+
peak_wavelength_nm: float
|
|
15
|
+
peak_intensity: float
|
|
16
|
+
estimated_fsr_nm: float | None
|
|
17
|
+
apparent_fwhm_nm: float | None
|
|
18
|
+
spectrometer_limited_q_flag: bool
|
|
19
|
+
fit_failed: bool
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass(frozen=True)
|
|
23
|
+
class SweepFeatures:
|
|
24
|
+
"""Observable summary vector extracted from a full pump-energy sweep."""
|
|
25
|
+
|
|
26
|
+
lasing_detected: bool
|
|
27
|
+
threshold_energy_uj: float | None
|
|
28
|
+
slope_efficiency: float
|
|
29
|
+
mean_fsr_nm: float | None
|
|
30
|
+
apparent_fwhm_nm: float | None
|
|
31
|
+
center_of_mass_nm: float
|
|
32
|
+
off_peak_baseline: float
|
|
33
|
+
spatial_width_px: float
|
|
34
|
+
spectrometer_limited_q_flag: bool
|
|
35
|
+
saturated: bool
|
|
36
|
+
fit_failed: bool
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _estimate_noise_std(spectra_1d: np.ndarray, dark_frames: np.ndarray | None) -> tuple[float, float]:
|
|
40
|
+
"""Estimate background offset and noise std from dark frames (matching central-quarter ROI) or MAD."""
|
|
41
|
+
if dark_frames is not None and dark_frames.size > 0:
|
|
42
|
+
if dark_frames.ndim == 3:
|
|
43
|
+
n_y = dark_frames.shape[1]
|
|
44
|
+
y_lo, y_hi = max(0, (3 * n_y) // 8), min(n_y, max(1, (5 * n_y) // 8))
|
|
45
|
+
dark_1d = np.mean(dark_frames[:, y_lo:y_hi, :], axis=1)
|
|
46
|
+
else:
|
|
47
|
+
dark_1d = np.mean(dark_frames, axis=1)
|
|
48
|
+
return float(np.mean(dark_1d)), max(1e-6, float(np.std(dark_1d)))
|
|
49
|
+
|
|
50
|
+
# Fallback: MAD of second-difference high-pass residual on lowest-energy spectrum
|
|
51
|
+
spec = spectra_1d[0]
|
|
52
|
+
diff2 = np.diff(spec, n=2)
|
|
53
|
+
mad = float(np.median(np.abs(diff2 - np.median(diff2))))
|
|
54
|
+
sigma = max(1e-6, mad / (0.6745 * np.sqrt(6.0)))
|
|
55
|
+
return float(np.percentile(spec, 5)), sigma
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _interpolated_fwhm_nm(wavelengths_nm: np.ndarray, spectrum: np.ndarray, bg: float) -> float | None:
|
|
59
|
+
"""Estimate subpixel-interpolated FWHM around the highest peak; return None if truncated."""
|
|
60
|
+
if len(spectrum) < 5:
|
|
61
|
+
return None
|
|
62
|
+
peak_idx = int(np.argmax(spectrum))
|
|
63
|
+
peak_val = float(spectrum[peak_idx])
|
|
64
|
+
if peak_val <= bg:
|
|
65
|
+
return None
|
|
66
|
+
half_val = bg + 0.5 * (peak_val - bg)
|
|
67
|
+
|
|
68
|
+
left_idx = peak_idx
|
|
69
|
+
while left_idx > 0 and spectrum[left_idx] > half_val:
|
|
70
|
+
left_idx -= 1
|
|
71
|
+
right_idx = peak_idx
|
|
72
|
+
while right_idx < len(spectrum) - 1 and spectrum[right_idx] > half_val:
|
|
73
|
+
right_idx += 1
|
|
74
|
+
|
|
75
|
+
if left_idx == 0 and spectrum[0] > half_val:
|
|
76
|
+
return None
|
|
77
|
+
if right_idx == len(spectrum) - 1 and spectrum[-1] > half_val:
|
|
78
|
+
return None
|
|
79
|
+
if left_idx == peak_idx or right_idx == peak_idx:
|
|
80
|
+
return None
|
|
81
|
+
|
|
82
|
+
# Linear subpixel interpolation on both sides
|
|
83
|
+
dl = (half_val - spectrum[left_idx]) / max(spectrum[left_idx + 1] - spectrum[left_idx], 1e-12)
|
|
84
|
+
wl_left = wavelengths_nm[left_idx] + dl * (wavelengths_nm[left_idx + 1] - wavelengths_nm[left_idx])
|
|
85
|
+
|
|
86
|
+
dr = (spectrum[right_idx - 1] - half_val) / max(spectrum[right_idx - 1] - spectrum[right_idx], 1e-12)
|
|
87
|
+
wl_right = wavelengths_nm[right_idx - 1] + dr * (wavelengths_nm[right_idx] - wavelengths_nm[right_idx - 1])
|
|
88
|
+
return float(max(0.0, wl_right - wl_left))
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _fit_hinge_threshold(energies: np.ndarray, integrated_sig: np.ndarray) -> tuple[float | None, float, bool]:
|
|
92
|
+
"""Fit piecewise-linear hinge model y = a + s0*E + s_excess*max(0, E - E_th)."""
|
|
93
|
+
if len(energies) < 3:
|
|
94
|
+
slope = float(np.polyfit(energies, integrated_sig, 1)[0]) if len(energies) >= 2 else 0.0
|
|
95
|
+
return None, slope, False
|
|
96
|
+
|
|
97
|
+
best_sse = np.inf
|
|
98
|
+
best_e_th = None
|
|
99
|
+
best_excess_slope = 0.0
|
|
100
|
+
|
|
101
|
+
# Linear no-threshold null model
|
|
102
|
+
p_lin = np.polyfit(energies, integrated_sig, 1)
|
|
103
|
+
sse_null = float(np.sum((integrated_sig - np.polyval(p_lin, energies)) ** 2))
|
|
104
|
+
|
|
105
|
+
candidates = np.linspace(float(energies[0]), float(energies[-2]), 25)
|
|
106
|
+
for e_cand in candidates:
|
|
107
|
+
hinge = np.maximum(0.0, energies - e_cand)
|
|
108
|
+
design = np.column_stack([np.ones_like(energies), energies, hinge])
|
|
109
|
+
coef, _, _, _ = np.linalg.lstsq(design, integrated_sig, rcond=None)
|
|
110
|
+
if coef[2] <= 0.0:
|
|
111
|
+
continue
|
|
112
|
+
resid = integrated_sig - design @ coef
|
|
113
|
+
sse = float(np.sum(resid**2))
|
|
114
|
+
if sse < best_sse:
|
|
115
|
+
best_sse = sse
|
|
116
|
+
best_e_th = float(e_cand)
|
|
117
|
+
best_excess_slope = float(coef[2])
|
|
118
|
+
|
|
119
|
+
# Require genuine kink improvement over linear fluorescence
|
|
120
|
+
lasing_detected = bool(best_e_th is not None and best_sse < 0.70 * sse_null and best_excess_slope > 0.0)
|
|
121
|
+
if not lasing_detected:
|
|
122
|
+
return None, float(p_lin[0]), False
|
|
123
|
+
return best_e_th, best_excess_slope, True
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def extract_spectral_features(
|
|
127
|
+
wavelengths_nm: np.ndarray,
|
|
128
|
+
spectrum: np.ndarray,
|
|
129
|
+
spec_psf_fwhm_nm: float = 0.10,
|
|
130
|
+
noise_std: float | None = None,
|
|
131
|
+
nominal_cavity_um: float = 30.0,
|
|
132
|
+
) -> ExtractedFeatures:
|
|
133
|
+
"""Extract moments, wavenumber-based FSR, interpolated FWHM, and resolution flag."""
|
|
134
|
+
bg = float(np.percentile(spectrum, 5))
|
|
135
|
+
weights = np.clip(spectrum - bg, a_min=0.0, a_max=None)
|
|
136
|
+
total = float(np.sum(weights))
|
|
137
|
+
if total <= 0.0:
|
|
138
|
+
com = float(np.mean(wavelengths_nm))
|
|
139
|
+
var = 0.0
|
|
140
|
+
else:
|
|
141
|
+
com = float(np.sum(wavelengths_nm * weights) / total)
|
|
142
|
+
var = float(np.sum(((wavelengths_nm - com) ** 2) * weights) / total)
|
|
143
|
+
|
|
144
|
+
peak_idx = int(np.argmax(spectrum))
|
|
145
|
+
peak_wl = float(wavelengths_nm[peak_idx])
|
|
146
|
+
peak_val = float(spectrum[peak_idx])
|
|
147
|
+
|
|
148
|
+
if noise_std is None:
|
|
149
|
+
diff2 = np.diff(spectrum, n=2)
|
|
150
|
+
noise_std = max(1e-6, float(np.median(np.abs(diff2))) / (0.6745 * np.sqrt(6.0)))
|
|
151
|
+
|
|
152
|
+
d_wl = float(abs(wavelengths_nm[1] - wavelengths_nm[0]))
|
|
153
|
+
fsr_nom = (485.0**2) / (2.0 * 1.34 * max(nominal_cavity_um, 1.0) * 1000.0)
|
|
154
|
+
min_dist_px = max(2, int(0.55 * fsr_nom / d_wl))
|
|
155
|
+
prominence = max(6.0 * noise_std, 0.08 * max(peak_val - bg, 0.0))
|
|
156
|
+
|
|
157
|
+
peaks, _ = find_peaks(spectrum - bg, prominence=prominence, distance=min_dist_px)
|
|
158
|
+
if len(peaks) >= 2:
|
|
159
|
+
# Median of consecutive inverse-wavelength spacings (referenced to 485 nm)
|
|
160
|
+
inv_lam = 1.0 / wavelengths_nm[peaks]
|
|
161
|
+
diffs = np.diff(inv_lam)
|
|
162
|
+
step_inv = float(np.median(np.abs(diffs)))
|
|
163
|
+
fsr_nm = float((485.0**2) * step_inv) if step_inv > 0 else None
|
|
164
|
+
fit_failed = fsr_nm is None
|
|
165
|
+
else:
|
|
166
|
+
fsr_nm = None
|
|
167
|
+
fit_failed = True
|
|
168
|
+
|
|
169
|
+
fwhm = _interpolated_fwhm_nm(wavelengths_nm, spectrum, bg)
|
|
170
|
+
spec_limited = bool(fwhm is not None and fwhm <= 1.25 * spec_psf_fwhm_nm)
|
|
171
|
+
|
|
172
|
+
return ExtractedFeatures(
|
|
173
|
+
center_of_mass_nm=com,
|
|
174
|
+
spectral_variance_nm2=var,
|
|
175
|
+
peak_wavelength_nm=peak_wl,
|
|
176
|
+
peak_intensity=peak_val,
|
|
177
|
+
estimated_fsr_nm=fsr_nm,
|
|
178
|
+
apparent_fwhm_nm=fwhm,
|
|
179
|
+
spectrometer_limited_q_flag=spec_limited,
|
|
180
|
+
fit_failed=fit_failed,
|
|
181
|
+
)
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def extract_sweep_features(
|
|
185
|
+
frames: np.ndarray,
|
|
186
|
+
wavelengths_nm: np.ndarray,
|
|
187
|
+
pump_energies_uj: np.ndarray,
|
|
188
|
+
spec_psf_fwhm_nm: float = 0.10,
|
|
189
|
+
dark_frames: np.ndarray | None = None,
|
|
190
|
+
nominal_cavity_um: float = 30.0,
|
|
191
|
+
adc_max_counts: int = 65535,
|
|
192
|
+
) -> SweepFeatures:
|
|
193
|
+
"""Extract order-invariant threshold, slope, modal FSR, and flags from a 2D sweep."""
|
|
194
|
+
if frames.ndim != 3 or frames.shape[0] == 0:
|
|
195
|
+
raise ValueError("frames must have shape (n_sweeps, n_spatial_px, n_spectral_px)")
|
|
196
|
+
|
|
197
|
+
# Sort sweep by ascending pump energy for strict order invariance
|
|
198
|
+
order = np.argsort(pump_energies_uj)
|
|
199
|
+
energies = np.asarray(pump_energies_uj, dtype=float)[order]
|
|
200
|
+
frames_sorted = frames[order]
|
|
201
|
+
|
|
202
|
+
# Use central 25% of spatial rows to avoid slit-tilt broadening
|
|
203
|
+
n_y = frames_sorted.shape[1]
|
|
204
|
+
y_lo, y_hi = max(0, (3 * n_y) // 8), min(n_y, max(1, (5 * n_y) // 8))
|
|
205
|
+
spectra_1d = np.mean(frames_sorted[:, y_lo:y_hi, :], axis=1)
|
|
206
|
+
|
|
207
|
+
bg_offset, noise_std = _estimate_noise_std(spectra_1d, dark_frames)
|
|
208
|
+
integrated_sig = np.sum(np.clip(spectra_1d - bg_offset, a_min=0.0, a_max=None), axis=1)
|
|
209
|
+
|
|
210
|
+
e_th, slope, lasing_detected = _fit_hinge_threshold(energies, integrated_sig)
|
|
211
|
+
top_feats = extract_spectral_features(
|
|
212
|
+
wavelengths_nm,
|
|
213
|
+
spectra_1d[-1],
|
|
214
|
+
spec_psf_fwhm_nm=spec_psf_fwhm_nm,
|
|
215
|
+
noise_std=noise_std,
|
|
216
|
+
nominal_cavity_um=nominal_cavity_um,
|
|
217
|
+
)
|
|
218
|
+
|
|
219
|
+
spatial_profile = np.mean(frames_sorted[-1], axis=1)
|
|
220
|
+
y_idx = np.arange(len(spatial_profile), dtype=float)
|
|
221
|
+
sp_w = np.clip(spatial_profile - np.min(spatial_profile), a_min=0.0, a_max=None)
|
|
222
|
+
sp_sum = float(np.sum(sp_w))
|
|
223
|
+
if sp_sum > 0.0:
|
|
224
|
+
y_mean = float(np.sum(y_idx * sp_w) / sp_sum)
|
|
225
|
+
spatial_width = float(np.sqrt(np.sum(((y_idx - y_mean) ** 2) * sp_w) / sp_sum))
|
|
226
|
+
else:
|
|
227
|
+
spatial_width = 0.0
|
|
228
|
+
|
|
229
|
+
saturated = bool(np.max(frames_sorted) >= adc_max_counts)
|
|
230
|
+
|
|
231
|
+
return SweepFeatures(
|
|
232
|
+
lasing_detected=lasing_detected,
|
|
233
|
+
threshold_energy_uj=e_th,
|
|
234
|
+
slope_efficiency=slope,
|
|
235
|
+
mean_fsr_nm=top_feats.estimated_fsr_nm,
|
|
236
|
+
apparent_fwhm_nm=top_feats.apparent_fwhm_nm,
|
|
237
|
+
center_of_mass_nm=top_feats.center_of_mass_nm,
|
|
238
|
+
off_peak_baseline=float(np.percentile(spectra_1d[-1], 5) - bg_offset),
|
|
239
|
+
spatial_width_px=spatial_width,
|
|
240
|
+
spectrometer_limited_q_flag=top_feats.spectrometer_limited_q_flag,
|
|
241
|
+
saturated=saturated,
|
|
242
|
+
fit_failed=top_feats.fit_failed,
|
|
243
|
+
)
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""Fisher Information Matrix (FIM), structural rank check, CRB, and Bayesian DoE."""
|
|
2
|
+
|
|
3
|
+
from .doe import DesignScore, evaluate_design, select_optimal_designs
|
|
4
|
+
from .fisher import (
|
|
5
|
+
DesignConfig,
|
|
6
|
+
active_observable_mask,
|
|
7
|
+
check_structural_n_l_rank,
|
|
8
|
+
compute_fim,
|
|
9
|
+
cramer_rao_sd,
|
|
10
|
+
numerical_jacobian,
|
|
11
|
+
reduced_forward_observables,
|
|
12
|
+
)
|
|
13
|
+
from .observability import (
|
|
14
|
+
KineticObservableConfig,
|
|
15
|
+
compute_kinetic_timeseries_fim,
|
|
16
|
+
integrate_nominal_5moment_ode,
|
|
17
|
+
kinetic_crb_widths,
|
|
18
|
+
nominal_kinetic_forward_observables,
|
|
19
|
+
)
|
|
20
|
+
from .profile_likelihood import (
|
|
21
|
+
IndistinguishablePair,
|
|
22
|
+
ProfileLikelihoodResult,
|
|
23
|
+
find_indistinguishable_pair,
|
|
24
|
+
profile_likelihood_log10_kp,
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
__all__ = [
|
|
28
|
+
"DesignConfig",
|
|
29
|
+
"DesignScore",
|
|
30
|
+
"IndistinguishablePair",
|
|
31
|
+
"KineticObservableConfig",
|
|
32
|
+
"ProfileLikelihoodResult",
|
|
33
|
+
"active_observable_mask",
|
|
34
|
+
"check_structural_n_l_rank",
|
|
35
|
+
"compute_fim",
|
|
36
|
+
"compute_kinetic_timeseries_fim",
|
|
37
|
+
"cramer_rao_sd",
|
|
38
|
+
"evaluate_design",
|
|
39
|
+
"find_indistinguishable_pair",
|
|
40
|
+
"integrate_nominal_5moment_ode",
|
|
41
|
+
"kinetic_crb_widths",
|
|
42
|
+
"nominal_kinetic_forward_observables",
|
|
43
|
+
"numerical_jacobian",
|
|
44
|
+
"profile_likelihood_log10_kp",
|
|
45
|
+
"reduced_forward_observables",
|
|
46
|
+
"select_optimal_designs",
|
|
47
|
+
]
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
"""Bayesian prior-averaged, unit-normalized, budget-matched A/D-optimal DoE."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
import numpy as np
|
|
5
|
+
from biolaser_twin.constants import LATENT_PRIOR_SCALES, NominalOpticalConstants
|
|
6
|
+
from .fisher import (
|
|
7
|
+
DesignConfig,
|
|
8
|
+
active_observable_mask,
|
|
9
|
+
compute_fim,
|
|
10
|
+
cramer_rao_sd,
|
|
11
|
+
numerical_jacobian,
|
|
12
|
+
)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass(frozen=True)
|
|
16
|
+
class DesignScore:
|
|
17
|
+
"""Identifiability score for a candidate experimental design."""
|
|
18
|
+
|
|
19
|
+
design: DesignConfig
|
|
20
|
+
a_opt_norm_trace: float # unit-normalized trace(S^{-1} F^{-1} S^{-1}) (lower is better)
|
|
21
|
+
d_opt_logdet: float # log det of scaled FIM (higher is better)
|
|
22
|
+
mean_crb_sd: np.ndarray
|
|
23
|
+
identifiable_mask: np.ndarray
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def evaluate_design(
|
|
27
|
+
design: DesignConfig,
|
|
28
|
+
reference_latents_grid: np.ndarray,
|
|
29
|
+
noise_cov: np.ndarray,
|
|
30
|
+
constants: NominalOpticalConstants | None = None,
|
|
31
|
+
rel_sd_threshold: float = 0.25,
|
|
32
|
+
measurement_budget_shots: int = 2,
|
|
33
|
+
) -> DesignScore:
|
|
34
|
+
"""Score a candidate design averaged over reference latents at matched shot budget.
|
|
35
|
+
|
|
36
|
+
Dual excitation (2 wavelengths) uses half as many repeats per excitation as single
|
|
37
|
+
excitation under a fixed total shot budget.
|
|
38
|
+
"""
|
|
39
|
+
mask = active_observable_mask(design)
|
|
40
|
+
n_exc = max(1, len(design.excitations_nm))
|
|
41
|
+
if measurement_budget_shots <= 0:
|
|
42
|
+
return DesignScore(
|
|
43
|
+
design=design,
|
|
44
|
+
a_opt_norm_trace=np.inf,
|
|
45
|
+
d_opt_logdet=-np.inf,
|
|
46
|
+
mean_crb_sd=np.full(len(LATENT_PRIOR_SCALES), np.inf),
|
|
47
|
+
identifiable_mask=np.zeros(len(LATENT_PRIOR_SCALES), dtype=bool),
|
|
48
|
+
)
|
|
49
|
+
repeats = float(measurement_budget_shots) / float(n_exc)
|
|
50
|
+
|
|
51
|
+
sub_cov = noise_cov[np.ix_(mask, mask)] / repeats
|
|
52
|
+
sub_cov_inv = np.linalg.pinv(sub_cov)
|
|
53
|
+
|
|
54
|
+
scale = LATENT_PRIOR_SCALES
|
|
55
|
+
scale_mat = np.diag(scale)
|
|
56
|
+
|
|
57
|
+
a_traces = []
|
|
58
|
+
d_logdets = []
|
|
59
|
+
crbs = []
|
|
60
|
+
for ref in reference_latents_grid:
|
|
61
|
+
jac_full = numerical_jacobian(ref, design, constants)
|
|
62
|
+
jac = jac_full[mask, :]
|
|
63
|
+
fim = compute_fim(jac, sub_cov_inv)
|
|
64
|
+
# Unit-normalized FIM: S^T F S
|
|
65
|
+
fim_norm = scale_mat @ fim @ scale_mat
|
|
66
|
+
crb_norm = cramer_rao_sd(fim_norm)
|
|
67
|
+
crb = crb_norm * scale
|
|
68
|
+
crbs.append(crb)
|
|
69
|
+
|
|
70
|
+
eigvals = np.linalg.eigvalsh(0.5 * (fim_norm + fim_norm.T))
|
|
71
|
+
pos = eigvals[eigvals > 1e-10]
|
|
72
|
+
if len(pos) == len(scale):
|
|
73
|
+
a_traces.append(float(np.sum(1.0 / pos)))
|
|
74
|
+
d_logdets.append(float(np.sum(np.log(pos))))
|
|
75
|
+
else:
|
|
76
|
+
a_traces.append(np.inf)
|
|
77
|
+
d_logdets.append(-np.inf)
|
|
78
|
+
|
|
79
|
+
mean_crb = np.mean(np.stack(crbs, axis=0), axis=0)
|
|
80
|
+
ident_mask = (mean_crb / scale) < rel_sd_threshold
|
|
81
|
+
return DesignScore(
|
|
82
|
+
design=design,
|
|
83
|
+
a_opt_norm_trace=float(np.mean(a_traces)),
|
|
84
|
+
d_opt_logdet=float(np.mean(d_logdets)),
|
|
85
|
+
mean_crb_sd=mean_crb,
|
|
86
|
+
identifiable_mask=ident_mask,
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def select_optimal_designs(
|
|
91
|
+
candidates: list[DesignConfig],
|
|
92
|
+
reference_latents_grid: np.ndarray,
|
|
93
|
+
noise_cov: np.ndarray,
|
|
94
|
+
criterion: str = "d_opt",
|
|
95
|
+
constants: NominalOpticalConstants | None = None,
|
|
96
|
+
measurement_budget_shots: int = 2,
|
|
97
|
+
) -> list[DesignScore]:
|
|
98
|
+
"""Rank candidate experimental designs by budget-matched Bayesian A- or D-optimality."""
|
|
99
|
+
scores = [
|
|
100
|
+
evaluate_design(
|
|
101
|
+
d,
|
|
102
|
+
reference_latents_grid,
|
|
103
|
+
noise_cov=noise_cov,
|
|
104
|
+
constants=constants,
|
|
105
|
+
measurement_budget_shots=measurement_budget_shots,
|
|
106
|
+
)
|
|
107
|
+
for d in candidates
|
|
108
|
+
]
|
|
109
|
+
if criterion == "a_opt":
|
|
110
|
+
return sorted(scores, key=lambda s: s.a_opt_norm_trace)
|
|
111
|
+
return sorted(scores, key=lambda s: s.d_opt_logdet, reverse=True)
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
"""Reduced-order nominal forward model, structural rank check, and eigen-based FIM/CRB."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
import numpy as np
|
|
5
|
+
from biolaser_twin.constants import NominalOpticalConstants
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
@dataclass(frozen=True)
|
|
9
|
+
class DesignConfig:
|
|
10
|
+
"""Candidate experimental design configuration (controllable hardware settings)."""
|
|
11
|
+
|
|
12
|
+
nominal_cavity_um: float = 30.0
|
|
13
|
+
spec_psf_fwhm_nm: float = 0.10
|
|
14
|
+
excitations_nm: tuple[float, ...] = (405.0, 440.0)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def reduced_forward_observables(
|
|
18
|
+
latents: np.ndarray,
|
|
19
|
+
design: DesignConfig,
|
|
20
|
+
constants: NominalOpticalConstants | None = None,
|
|
21
|
+
) -> np.ndarray:
|
|
22
|
+
"""Reduced-order nominal map from [nL_um, z1_visc, z2_bound, z4_scat] to 6D schema.
|
|
23
|
+
|
|
24
|
+
Schema: [fsr_nm, e_th_405_uj, e_th_440_uj, com_405_nm, com_440_nm, scat_norm].
|
|
25
|
+
Uses only NominalOpticalConstants (isolated from truth simulator).
|
|
26
|
+
"""
|
|
27
|
+
c = constants or NominalOpticalConstants()
|
|
28
|
+
nl_um, z1_visc, z2_bound, z4_scat = [float(v) for v in latents]
|
|
29
|
+
|
|
30
|
+
# FSR = lambda^2 / (2 * nL)
|
|
31
|
+
fsr_nm = (485.0**2) / (2.0 * max(nl_um, 1.0) * 1000.0)
|
|
32
|
+
|
|
33
|
+
# Nominal cavity loss depends on L_est = nL / n_water_nominal (so dE_th/dnL != 0)
|
|
34
|
+
l_est_cm = max((nl_um / c.n_water_nominal) * 1e-4, 1e-5)
|
|
35
|
+
mirror_loss = -np.log(c.mirror_reflectivity_nominal**2) / (2.0 * l_est_cm)
|
|
36
|
+
total_loss = mirror_loss + max(z4_scat, 0.01)
|
|
37
|
+
|
|
38
|
+
def _e_th_and_com(exc_nm: float) -> tuple[float, float]:
|
|
39
|
+
w_free = float(np.exp(-0.5 * ((exc_nm - 408.0) / 18.0) ** 2))
|
|
40
|
+
w_bound = float(np.exp(-0.5 * ((exc_nm - 442.0) / 16.0) ** 2))
|
|
41
|
+
visc_proxy = 0.12 * (1.0 + 4.0 * max(0.0, z1_visc))
|
|
42
|
+
gain_proxy = (
|
|
43
|
+
c.gain_scale_kappa
|
|
44
|
+
* c.nominal_tht_conc_mm
|
|
45
|
+
* ((1.0 - z2_bound) * w_free * visc_proxy + z2_bound * w_bound)
|
|
46
|
+
)
|
|
47
|
+
e_th = total_loss / max(0.04 * gain_proxy, 1e-4)
|
|
48
|
+
# Excitation-dependent COM shift
|
|
49
|
+
bound_weight = (z2_bound * w_bound) / max((1.0 - z2_bound) * w_free * visc_proxy + z2_bound * w_bound, 1e-6)
|
|
50
|
+
com = 478.0 + 8.0 * bound_weight
|
|
51
|
+
return e_th, com
|
|
52
|
+
|
|
53
|
+
exc_blue = next((e for e in design.excitations_nm if e < 430.0), 405.0)
|
|
54
|
+
exc_long = next((e for e in design.excitations_nm if e >= 430.0), 440.0)
|
|
55
|
+
e_405, com_405 = _e_th_and_com(exc_blue)
|
|
56
|
+
e_440, com_440 = _e_th_and_com(exc_long)
|
|
57
|
+
scat_norm = c.scat_scale_nominal * max(z4_scat, 0.0)
|
|
58
|
+
return np.array([fsr_nm, e_405, e_440, com_405, com_440, scat_norm], dtype=float)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def active_observable_mask(design: DesignConfig) -> np.ndarray:
|
|
62
|
+
"""Return boolean mask of schema indices active under the given DesignConfig."""
|
|
63
|
+
has_blue = any(e < 430.0 for e in design.excitations_nm)
|
|
64
|
+
has_long = any(e >= 430.0 for e in design.excitations_nm)
|
|
65
|
+
return np.array([True, has_blue, has_long, has_blue, has_long, True], dtype=bool)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def numerical_jacobian(
|
|
69
|
+
latents: np.ndarray,
|
|
70
|
+
design: DesignConfig,
|
|
71
|
+
constants: NominalOpticalConstants | None = None,
|
|
72
|
+
eps: float = 1e-4,
|
|
73
|
+
) -> np.ndarray:
|
|
74
|
+
"""Compute central finite-difference Jacobian J = d(observables)/d(latents)."""
|
|
75
|
+
x0 = np.asarray(latents, dtype=float)
|
|
76
|
+
y0 = reduced_forward_observables(x0, design, constants)
|
|
77
|
+
jac = np.zeros((len(y0), len(x0)), dtype=float)
|
|
78
|
+
for j in range(len(x0)):
|
|
79
|
+
step = eps * max(1.0, abs(x0[j]))
|
|
80
|
+
dx = np.zeros_like(x0)
|
|
81
|
+
dx[j] = step
|
|
82
|
+
yp = reduced_forward_observables(x0 + dx, design, constants)
|
|
83
|
+
ym = reduced_forward_observables(x0 - dx, design, constants)
|
|
84
|
+
jac[:, j] = (yp - ym) / (2.0 * step)
|
|
85
|
+
return jac
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def check_structural_n_l_rank(
|
|
89
|
+
n_val: float = 1.345,
|
|
90
|
+
l_um: float = 30.0,
|
|
91
|
+
z1: float = 0.3,
|
|
92
|
+
z2: float = 0.7,
|
|
93
|
+
z4: float = 0.5,
|
|
94
|
+
design: DesignConfig | None = None,
|
|
95
|
+
constants: NominalOpticalConstants | None = None,
|
|
96
|
+
) -> tuple[int, int]:
|
|
97
|
+
"""Verify S1 structural unidentifiability: [n, L, z1, z2, z4] Jacobian is rank-deficient (<5)."""
|
|
98
|
+
d = design or DesignConfig()
|
|
99
|
+
# Parameterize via (n, L) -> nL = n * L and evaluate observables dependent on nL
|
|
100
|
+
x5 = np.array([n_val, l_um, z1, z2, z4], dtype=float)
|
|
101
|
+
eps = 1e-4
|
|
102
|
+
|
|
103
|
+
def _obs_nl(p: np.ndarray) -> np.ndarray:
|
|
104
|
+
nl_um = p[0] * p[1]
|
|
105
|
+
fsr = (485.0**2) / (2.0 * nl_um * 1000.0)
|
|
106
|
+
base = reduced_forward_observables(np.array([nl_um, p[2], p[3], p[4]]), d, constants)
|
|
107
|
+
base[0] = fsr
|
|
108
|
+
return base
|
|
109
|
+
|
|
110
|
+
jac5 = np.zeros((6, 5), dtype=float)
|
|
111
|
+
for j in range(5):
|
|
112
|
+
step = eps * max(1.0, abs(x5[j]))
|
|
113
|
+
dx = np.zeros(5)
|
|
114
|
+
dx[j] = step
|
|
115
|
+
jac5[:, j] = (_obs_nl(x5 + dx) - _obs_nl(x5 - dx)) / (2.0 * step)
|
|
116
|
+
rank = int(np.linalg.matrix_rank(jac5, tol=1e-8))
|
|
117
|
+
return rank, 5
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def compute_fim(jacobian: np.ndarray, noise_cov_inv: np.ndarray) -> np.ndarray:
|
|
121
|
+
"""Compute Fisher Information Matrix F = J^T Sigma^{-1} J."""
|
|
122
|
+
return jacobian.T @ noise_cov_inv @ jacobian
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def cramer_rao_sd(fim: np.ndarray, eig_tol: float = 1e-10) -> np.ndarray:
|
|
126
|
+
"""Eigen-based CRB SD: returns np.inf on null/unidentifiable eigendirections."""
|
|
127
|
+
eigvals, eigvecs = np.linalg.eigh(0.5 * (fim + fim.T))
|
|
128
|
+
max_eig = float(np.max(eigvals)) if len(eigvals) > 0 else 0.0
|
|
129
|
+
cutoff = max(eig_tol, 1e-12 * max_eig)
|
|
130
|
+
|
|
131
|
+
variances = np.zeros(fim.shape[0], dtype=float)
|
|
132
|
+
for k, lam in enumerate(eigvals):
|
|
133
|
+
v = eigvecs[:, k]
|
|
134
|
+
if lam <= cutoff:
|
|
135
|
+
# Any coordinate with projection onto null eigenvector is unidentifiable
|
|
136
|
+
variances = np.where(np.abs(v) > 1e-8, np.inf, variances)
|
|
137
|
+
else:
|
|
138
|
+
variances += (v**2) / lam
|
|
139
|
+
return np.sqrt(variances)
|