biolaser-twin 0.2.0__tar.gz
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-0.2.0/LICENSE +21 -0
- biolaser_twin-0.2.0/PKG-INFO +116 -0
- biolaser_twin-0.2.0/README.md +85 -0
- biolaser_twin-0.2.0/biolaser_twin/__init__.py +3 -0
- biolaser_twin-0.2.0/biolaser_twin/calibration.py +29 -0
- biolaser_twin-0.2.0/biolaser_twin/constants.py +25 -0
- biolaser_twin-0.2.0/biolaser_twin/extractor/__init__.py +15 -0
- biolaser_twin-0.2.0/biolaser_twin/extractor/frame_features.py +243 -0
- biolaser_twin-0.2.0/biolaser_twin/identifiability/__init__.py +47 -0
- biolaser_twin-0.2.0/biolaser_twin/identifiability/doe.py +111 -0
- biolaser_twin-0.2.0/biolaser_twin/identifiability/fisher.py +139 -0
- biolaser_twin-0.2.0/biolaser_twin/identifiability/observability.py +227 -0
- biolaser_twin-0.2.0/biolaser_twin/identifiability/profile_likelihood.py +311 -0
- biolaser_twin-0.2.0/biolaser_twin/kinetics_nominal/__init__.py +25 -0
- biolaser_twin-0.2.0/biolaser_twin/kinetics_nominal/priors.py +59 -0
- biolaser_twin-0.2.0/biolaser_twin/kinetics_nominal/reduced_moments.py +92 -0
- biolaser_twin-0.2.0/biolaser_twin/kinetics_nominal/symbolic_check.py +33 -0
- biolaser_twin-0.2.0/biolaser_twin/metrics.py +44 -0
- biolaser_twin-0.2.0/biolaser_twin/observations.py +275 -0
- biolaser_twin-0.2.0/biolaser_twin/simulator/__init__.py +60 -0
- biolaser_twin-0.2.0/biolaser_twin/simulator/aggregate_optics.py +204 -0
- biolaser_twin-0.2.0/biolaser_twin/simulator/fp_cavity.py +398 -0
- biolaser_twin-0.2.0/biolaser_twin/simulator/kinetics/__init__.py +39 -0
- biolaser_twin-0.2.0/biolaser_twin/simulator/kinetics/analytic.py +62 -0
- biolaser_twin-0.2.0/biolaser_twin/simulator/kinetics/mechanisms.py +146 -0
- biolaser_twin-0.2.0/biolaser_twin/simulator/kinetics/moments.py +116 -0
- biolaser_twin-0.2.0/biolaser_twin/simulator/kinetics/population_balance.py +311 -0
- biolaser_twin-0.2.0/biolaser_twin/simulator/kinetics/symbolic_audit.py +304 -0
- biolaser_twin-0.2.0/biolaser_twin/simulator/longitudinal.py +98 -0
- biolaser_twin-0.2.0/biolaser_twin/simulator/photophysics.py +159 -0
- biolaser_twin-0.2.0/biolaser_twin/simulator/proxy_map.py +32 -0
- biolaser_twin-0.2.0/biolaser_twin/simulator/sggw_dbr_mirror_spectra.json +2102 -0
- biolaser_twin-0.2.0/biolaser_twin/simulator/sggw_exp_lasing_spectrum_96.json +83 -0
- biolaser_twin-0.2.0/biolaser_twin/solvers/__init__.py +59 -0
- biolaser_twin-0.2.0/biolaser_twin/solvers/baselines.py +437 -0
- biolaser_twin-0.2.0/biolaser_twin/solvers/classical_nls.py +123 -0
- biolaser_twin-0.2.0/biolaser_twin/solvers/kinetic_classical.py +276 -0
- biolaser_twin-0.2.0/biolaser_twin/solvers/kinetic_modern.py +266 -0
- biolaser_twin-0.2.0/biolaser_twin/solvers/kinetic_pielm.py +532 -0
- biolaser_twin-0.2.0/biolaser_twin/solvers/kinetic_sbi.py +174 -0
- biolaser_twin-0.2.0/biolaser_twin/solvers/kinetic_ude.py +185 -0
- biolaser_twin-0.2.0/biolaser_twin/solvers/photonic_pielm.py +248 -0
- biolaser_twin-0.2.0/biolaser_twin.egg-info/PKG-INFO +116 -0
- biolaser_twin-0.2.0/biolaser_twin.egg-info/SOURCES.txt +59 -0
- biolaser_twin-0.2.0/biolaser_twin.egg-info/dependency_links.txt +1 -0
- biolaser_twin-0.2.0/biolaser_twin.egg-info/requires.txt +9 -0
- biolaser_twin-0.2.0/biolaser_twin.egg-info/top_level.txt +1 -0
- biolaser_twin-0.2.0/pyproject.toml +64 -0
- biolaser_twin-0.2.0/setup.cfg +4 -0
- biolaser_twin-0.2.0/tests/test_aggregate_optics.py +150 -0
- biolaser_twin-0.2.0/tests/test_identifiability_kinetics.py +115 -0
- biolaser_twin-0.2.0/tests/test_kinetics_nominal.py +86 -0
- biolaser_twin-0.2.0/tests/test_kinetics_pbe.py +273 -0
- biolaser_twin-0.2.0/tests/test_longitudinal_history.py +87 -0
- biolaser_twin-0.2.0/tests/test_m_a2_simulator_extractor.py +105 -0
- biolaser_twin-0.2.0/tests/test_m_a3_identifiability_solvers.py +214 -0
- biolaser_twin-0.2.0/tests/test_s2_bridge.py +83 -0
- biolaser_twin-0.2.0/tests/test_scaffold.py +41 -0
- biolaser_twin-0.2.0/tests/test_sggw_dbr_and_smc.py +94 -0
- biolaser_twin-0.2.0/tests/test_solvers_p06b.py +162 -0
- biolaser_twin-0.2.0/tests/test_verification.py +85 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Karol Struniawski
|
|
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,116 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: biolaser-twin
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Physics-based biophotonic cavity simulator, feature extractor, Fisher/DoE identifiability, and PIELM/NLS inversion suite.
|
|
5
|
+
Author-email: Karol Struniawski <karol_struniawski@sggw.edu.pl>
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/KStruniawski/BioLaserTwin
|
|
8
|
+
Project-URL: Repository, https://github.com/KStruniawski/BioLaserTwin
|
|
9
|
+
Project-URL: Issues, https://github.com/KStruniawski/BioLaserTwin/issues
|
|
10
|
+
Keywords: biophotonics,fabry-perot,microcavity-laser,population-balance,identifiability,inverse-problems
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Intended Audience :: Science/Research
|
|
13
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
14
|
+
Classifier: Operating System :: OS Independent
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
18
|
+
Classifier: Topic :: Scientific/Engineering :: Physics
|
|
19
|
+
Requires-Python: >=3.10
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
License-File: LICENSE
|
|
22
|
+
Requires-Dist: numpy<2.4.0,>=1.26.0
|
|
23
|
+
Requires-Dist: scipy>=1.11.0
|
|
24
|
+
Requires-Dist: torch>=2.1.0
|
|
25
|
+
Requires-Dist: sympy>=1.12
|
|
26
|
+
Provides-Extra: dev
|
|
27
|
+
Requires-Dist: pytest>=8.0.0; extra == "dev"
|
|
28
|
+
Requires-Dist: ruff>=0.4; extra == "dev"
|
|
29
|
+
Requires-Dist: matplotlib>=3.8.0; extra == "dev"
|
|
30
|
+
Dynamic: license-file
|
|
31
|
+
|
|
32
|
+
# BioLaserTwin (`v0.2.0`)
|
|
33
|
+
|
|
34
|
+
[](https://doi.org/10.5281/zenodo.24421423)
|
|
35
|
+
|
|
36
|
+
**BioLaserTwin** is an open-source Python software package for physics-based simulation of biophotonic Fabry–Pérot (FP) microcavity lasers coupled to amyloid-like protein aggregation kinetics, 2D spatial–spectral feature extraction, Fisher/profile-likelihood identifiability analysis, and multi-paradigm inverse parameter estimation.
|
|
37
|
+
|
|
38
|
+
- **Author (Software):** Karol Struniawski, PhD (Warsaw University of Life Sciences — WULS, `karol_struniawski@sggw.edu.pl`)
|
|
39
|
+
- **Experimental Reference Data (`simulator/sggw_*.json`):** Measured and provided by the study co-authors (K. Struniawski, A. Konopka, P. Hańczyc, K. Rusakov), redistributed under the MIT License ([`LICENSE`](LICENSE)).
|
|
40
|
+
- **Funding:** National Science Centre (NCN), Poland (SONATINA grant No. `UMO-2026/60/C/ST7/00025`)
|
|
41
|
+
- **License:** MIT ([`LICENSE`](LICENSE))
|
|
42
|
+
|
|
43
|
+
---
|
|
44
|
+
|
|
45
|
+
## Architecture
|
|
46
|
+
|
|
47
|
+
The package is organized into five decoupled subpackages under `biolaser_twin/`:
|
|
48
|
+
|
|
49
|
+
1. **`biolaser_twin.simulator`** — Independent forward physics engine (isolated from solvers and reduced nominal models):
|
|
50
|
+
- `kinetics/`: Kumar–Ramkrishna discrete-plus-geometric-pivot Population Balance Equation (PBE) solver (`96` discrete + `224` log pivots) with stiff `Radau` integration, analytical Jacobian, and SymPy symbolic audit across 7 mechanisms (`M0`–`M5`, `M_w`).
|
|
51
|
+
- `aggregate_optics.py`: Rayleigh–Gans–Debye (RGD) thin-rod scattering crossover ($\ell^2 \to \ell$), Thioflavin-T (ThT) binding, and crowding microviscosity.
|
|
52
|
+
- `fp_cavity.py` & `photophysics.py`: Dispersive Fabry–Pérot Airy cavity, pump-threshold lasing dynamics, and digitized University of Warsaw (UW) dielectric Bragg reflector (DBR) spectra (`simulator/sggw_dbr_mirror_spectra.json`, `simulator/sggw_exp_lasing_spectrum_96.json`).
|
|
53
|
+
- `longitudinal.py`: Multi-shot thermal and photobleaching sample history.
|
|
54
|
+
2. **`biolaser_twin.kinetics_nominal`** — Reduced 4-moment ODE models, priors, and SymPy symbolic checks (intentionally isolated from `simulator/`).
|
|
55
|
+
3. **`biolaser_twin.extractor`** — 2D spatial–spectral frame feature extractor (`frame_features.py`): peak detection, threshold estimation, center-of-mass wavelength, and Free Spectral Range (FSR) referenced to `485 nm`.
|
|
56
|
+
4. **`biolaser_twin.identifiability`** — Fisher Information Matrix (FIM), optimal Design of Experiments (DoE), and quasi-likelihood profile-likelihood observability diagnostics.
|
|
57
|
+
5. **`biolaser_twin.solvers`** — Inverse solvers spanning Physics-Informed Extreme Learning Machines (`kinetic_pielm.py`, `photonic_pielm.py`), classical NLS / tempered SMC (`kinetic_classical.py`), Neural/KAN UDEs (`kinetic_ude.py`), Simulation-Based Inference (`kinetic_sbi.py`), and modern SciML architectures (`kinetic_modern.py`).
|
|
58
|
+
|
|
59
|
+
---
|
|
60
|
+
|
|
61
|
+
## Installation
|
|
62
|
+
|
|
63
|
+
Python `>=3.10` (tested on `3.11.0`) is required. Note that `numpy<2.4.0` is pinned for compatibility with legacy `np.trapz` calls in benchmark scripts (core `biolaser_twin` modules support both `np.trapezoid` and `np.trapz`).
|
|
64
|
+
|
|
65
|
+
```bash
|
|
66
|
+
python3 -m venv .venv
|
|
67
|
+
source .venv/bin/activate
|
|
68
|
+
pip install -e ".[dev]"
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
---
|
|
72
|
+
|
|
73
|
+
## Verification & Testing
|
|
74
|
+
|
|
75
|
+
Run the full unit and symbolic verification test suite (`59` tests; ~28 min, `1708.39 s` in reference log):
|
|
76
|
+
|
|
77
|
+
```bash
|
|
78
|
+
pytest
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
For a fast smoke check (~1 s; `0.73 s` in reference log) of analytical cavity limits, `DesignConfig` masks, and API regression tests:
|
|
82
|
+
|
|
83
|
+
```bash
|
|
84
|
+
pytest tests/test_verification.py
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
For the standalone numerical/analytical verification suite (~5 min, checking mass conservation across all 7 PBE mechanisms, $2\times$ mesh-doubling, Cohen/Oosawa limits, RGD slopes, and `history=None` equivalence):
|
|
88
|
+
|
|
89
|
+
```bash
|
|
90
|
+
python3 examples/verify_s1.py
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
Representative output (floating-point values and runtimes are machine-dependent):
|
|
94
|
+
`Max mass conservation rel err : ~2e-15`, `Max mesh-2x mass rel err : 2.997e-10`, `Mesh-2x M2 rel err : 0.0086, 0.0085`, `Cohen : 5.909e-04`, `Oosawa : 1.527e-03`, `RGD slopes : 1.999, 1.236`, `history=None bitwise : True`.
|
|
95
|
+
|
|
96
|
+
---
|
|
97
|
+
|
|
98
|
+
## Illustrative Examples
|
|
99
|
+
|
|
100
|
+
1. **`spectra-96` mode-spacing consistency check (`examples/illustrative_spectra96.py`):** Simulates a $d = 33.22\,\mu\text{m}$ Fabry–Pérot microcavity with digitized UW DBR mirror spectra and compares extracted FSR (`2.6430 nm`) against the `spectra-96` reference spectrum (`2.6115 nm` in the `485 nm` convention, `+1.21%`; full-window `465–535 nm` peak `478.8 nm`, CoM `482.0 nm`):
|
|
101
|
+
|
|
102
|
+
```bash
|
|
103
|
+
python3 examples/illustrative_spectra96.py
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
2. **Three-stage API demonstration (`examples/forward_to_inverse.py`):** Demonstrates forward cavity rendering + feature extraction (`FSR = 2.8313 nm`), optical-latent FIM/CRB rank (`4/4`), and `AmyloFitGlobalNLSSolver.fit_predict_multi` on noisy multi-concentration nominal kinetics (`2%` seeded noise; representative output: `fit ≈ [-8.496, -3.5, -6.046, -1.757]`, `L2 ≈ 1.05`, runtime `< 10 s`):
|
|
107
|
+
|
|
108
|
+
```bash
|
|
109
|
+
python3 examples/forward_to_inverse.py
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
---
|
|
113
|
+
|
|
114
|
+
## Citation
|
|
115
|
+
|
|
116
|
+
If you use **BioLaserTwin** in academic work, please cite it using [`CITATION.cff`](CITATION.cff).
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
# BioLaserTwin (`v0.2.0`)
|
|
2
|
+
|
|
3
|
+
[](https://doi.org/10.5281/zenodo.24421423)
|
|
4
|
+
|
|
5
|
+
**BioLaserTwin** is an open-source Python software package for physics-based simulation of biophotonic Fabry–Pérot (FP) microcavity lasers coupled to amyloid-like protein aggregation kinetics, 2D spatial–spectral feature extraction, Fisher/profile-likelihood identifiability analysis, and multi-paradigm inverse parameter estimation.
|
|
6
|
+
|
|
7
|
+
- **Author (Software):** Karol Struniawski, PhD (Warsaw University of Life Sciences — WULS, `karol_struniawski@sggw.edu.pl`)
|
|
8
|
+
- **Experimental Reference Data (`simulator/sggw_*.json`):** Measured and provided by the study co-authors (K. Struniawski, A. Konopka, P. Hańczyc, K. Rusakov), redistributed under the MIT License ([`LICENSE`](LICENSE)).
|
|
9
|
+
- **Funding:** National Science Centre (NCN), Poland (SONATINA grant No. `UMO-2026/60/C/ST7/00025`)
|
|
10
|
+
- **License:** MIT ([`LICENSE`](LICENSE))
|
|
11
|
+
|
|
12
|
+
---
|
|
13
|
+
|
|
14
|
+
## Architecture
|
|
15
|
+
|
|
16
|
+
The package is organized into five decoupled subpackages under `biolaser_twin/`:
|
|
17
|
+
|
|
18
|
+
1. **`biolaser_twin.simulator`** — Independent forward physics engine (isolated from solvers and reduced nominal models):
|
|
19
|
+
- `kinetics/`: Kumar–Ramkrishna discrete-plus-geometric-pivot Population Balance Equation (PBE) solver (`96` discrete + `224` log pivots) with stiff `Radau` integration, analytical Jacobian, and SymPy symbolic audit across 7 mechanisms (`M0`–`M5`, `M_w`).
|
|
20
|
+
- `aggregate_optics.py`: Rayleigh–Gans–Debye (RGD) thin-rod scattering crossover ($\ell^2 \to \ell$), Thioflavin-T (ThT) binding, and crowding microviscosity.
|
|
21
|
+
- `fp_cavity.py` & `photophysics.py`: Dispersive Fabry–Pérot Airy cavity, pump-threshold lasing dynamics, and digitized University of Warsaw (UW) dielectric Bragg reflector (DBR) spectra (`simulator/sggw_dbr_mirror_spectra.json`, `simulator/sggw_exp_lasing_spectrum_96.json`).
|
|
22
|
+
- `longitudinal.py`: Multi-shot thermal and photobleaching sample history.
|
|
23
|
+
2. **`biolaser_twin.kinetics_nominal`** — Reduced 4-moment ODE models, priors, and SymPy symbolic checks (intentionally isolated from `simulator/`).
|
|
24
|
+
3. **`biolaser_twin.extractor`** — 2D spatial–spectral frame feature extractor (`frame_features.py`): peak detection, threshold estimation, center-of-mass wavelength, and Free Spectral Range (FSR) referenced to `485 nm`.
|
|
25
|
+
4. **`biolaser_twin.identifiability`** — Fisher Information Matrix (FIM), optimal Design of Experiments (DoE), and quasi-likelihood profile-likelihood observability diagnostics.
|
|
26
|
+
5. **`biolaser_twin.solvers`** — Inverse solvers spanning Physics-Informed Extreme Learning Machines (`kinetic_pielm.py`, `photonic_pielm.py`), classical NLS / tempered SMC (`kinetic_classical.py`), Neural/KAN UDEs (`kinetic_ude.py`), Simulation-Based Inference (`kinetic_sbi.py`), and modern SciML architectures (`kinetic_modern.py`).
|
|
27
|
+
|
|
28
|
+
---
|
|
29
|
+
|
|
30
|
+
## Installation
|
|
31
|
+
|
|
32
|
+
Python `>=3.10` (tested on `3.11.0`) is required. Note that `numpy<2.4.0` is pinned for compatibility with legacy `np.trapz` calls in benchmark scripts (core `biolaser_twin` modules support both `np.trapezoid` and `np.trapz`).
|
|
33
|
+
|
|
34
|
+
```bash
|
|
35
|
+
python3 -m venv .venv
|
|
36
|
+
source .venv/bin/activate
|
|
37
|
+
pip install -e ".[dev]"
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
---
|
|
41
|
+
|
|
42
|
+
## Verification & Testing
|
|
43
|
+
|
|
44
|
+
Run the full unit and symbolic verification test suite (`59` tests; ~28 min, `1708.39 s` in reference log):
|
|
45
|
+
|
|
46
|
+
```bash
|
|
47
|
+
pytest
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
For a fast smoke check (~1 s; `0.73 s` in reference log) of analytical cavity limits, `DesignConfig` masks, and API regression tests:
|
|
51
|
+
|
|
52
|
+
```bash
|
|
53
|
+
pytest tests/test_verification.py
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
For the standalone numerical/analytical verification suite (~5 min, checking mass conservation across all 7 PBE mechanisms, $2\times$ mesh-doubling, Cohen/Oosawa limits, RGD slopes, and `history=None` equivalence):
|
|
57
|
+
|
|
58
|
+
```bash
|
|
59
|
+
python3 examples/verify_s1.py
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
Representative output (floating-point values and runtimes are machine-dependent):
|
|
63
|
+
`Max mass conservation rel err : ~2e-15`, `Max mesh-2x mass rel err : 2.997e-10`, `Mesh-2x M2 rel err : 0.0086, 0.0085`, `Cohen : 5.909e-04`, `Oosawa : 1.527e-03`, `RGD slopes : 1.999, 1.236`, `history=None bitwise : True`.
|
|
64
|
+
|
|
65
|
+
---
|
|
66
|
+
|
|
67
|
+
## Illustrative Examples
|
|
68
|
+
|
|
69
|
+
1. **`spectra-96` mode-spacing consistency check (`examples/illustrative_spectra96.py`):** Simulates a $d = 33.22\,\mu\text{m}$ Fabry–Pérot microcavity with digitized UW DBR mirror spectra and compares extracted FSR (`2.6430 nm`) against the `spectra-96` reference spectrum (`2.6115 nm` in the `485 nm` convention, `+1.21%`; full-window `465–535 nm` peak `478.8 nm`, CoM `482.0 nm`):
|
|
70
|
+
|
|
71
|
+
```bash
|
|
72
|
+
python3 examples/illustrative_spectra96.py
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
2. **Three-stage API demonstration (`examples/forward_to_inverse.py`):** Demonstrates forward cavity rendering + feature extraction (`FSR = 2.8313 nm`), optical-latent FIM/CRB rank (`4/4`), and `AmyloFitGlobalNLSSolver.fit_predict_multi` on noisy multi-concentration nominal kinetics (`2%` seeded noise; representative output: `fit ≈ [-8.496, -3.5, -6.046, -1.757]`, `L2 ≈ 1.05`, runtime `< 10 s`):
|
|
76
|
+
|
|
77
|
+
```bash
|
|
78
|
+
python3 examples/forward_to_inverse.py
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
---
|
|
82
|
+
|
|
83
|
+
## Citation
|
|
84
|
+
|
|
85
|
+
If you use **BioLaserTwin** in academic work, please cite it using [`CITATION.cff`](CITATION.cff).
|
|
@@ -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
|
+
]
|