eemkit 0.2.0__tar.gz → 0.3.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.
- {eemkit-0.2.0 → eemkit-0.3.0}/CHANGELOG.md +28 -1
- {eemkit-0.2.0 → eemkit-0.3.0}/CITATION.cff +5 -2
- {eemkit-0.2.0 → eemkit-0.3.0}/PKG-INFO +3 -2
- {eemkit-0.2.0 → eemkit-0.3.0}/README.md +2 -1
- {eemkit-0.2.0 → eemkit-0.3.0}/docs/index.md +2 -1
- {eemkit-0.2.0 → eemkit-0.3.0}/docs/indices.md +8 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/docs/parafac.md +30 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/src/eemkit/__init__.py +1 -1
- {eemkit-0.2.0 → eemkit-0.3.0}/src/eemkit/indices.py +41 -9
- {eemkit-0.2.0 → eemkit-0.3.0}/src/eemkit/parafac/__init__.py +2 -0
- eemkit-0.3.0/src/eemkit/parafac/channels.py +159 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/src/eemkit/report.py +12 -0
- eemkit-0.3.0/tests/test_channels.py +171 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/tests/test_indices.py +43 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/tests/test_outliers_report.py +11 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/.gitignore +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/LICENSE +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/docs/absorbance.md +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/docs/api.md +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/docs/app-guide.md +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/docs/campaigns.md +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/docs/cli.md +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/docs/corrections.md +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/docs/data_model.md +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/docs/gui.md +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/docs/img/app/1_project.png +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/docs/img/app/2_corrections.png +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/docs/img/app/3_indices.png +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/docs/img/app/4a_parafac_ranks.png +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/docs/img/app/4b_parafac_outliers.png +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/docs/img/app/4c_parafac_final.png +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/docs/img/app/4d_parafac_by_model.png +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/docs/img/app/5a_rivers_time.png +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/docs/img/app/5b_rivers_composition.png +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/docs/img/app/5c_rivers_tests.png +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/docs/img/app/6_export.png +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/docs/instruments.md +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/docs/plotting.md +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/docs/quickstart.md +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/pyproject.toml +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/src/eemkit/__main__.py +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/src/eemkit/absorbance.py +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/src/eemkit/campaigns.py +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/src/eemkit/cli.py +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/src/eemkit/core/__init__.py +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/src/eemkit/core/dataset.py +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/src/eemkit/core/grid.py +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/src/eemkit/core/history.py +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/src/eemkit/corrections/__init__.py +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/src/eemkit/corrections/_common.py +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/src/eemkit/corrections/blank.py +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/src/eemkit/corrections/crop.py +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/src/eemkit/corrections/dilution.py +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/src/eemkit/corrections/inner_filter.py +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/src/eemkit/corrections/instrument.py +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/src/eemkit/corrections/raman.py +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/src/eemkit/corrections/scatter.py +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/src/eemkit/corrections/spectral.py +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/src/eemkit/corrections/zap.py +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/src/eemkit/errors.py +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/src/eemkit/gui/__init__.py +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/src/eemkit/gui/__main__.py +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/src/eemkit/gui/campaigns_tab.py +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/src/eemkit/gui/common.py +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/src/eemkit/gui/corrections_tab.py +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/src/eemkit/gui/export_tab.py +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/src/eemkit/gui/indices_tab.py +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/src/eemkit/gui/main_window.py +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/src/eemkit/gui/parafac_tab.py +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/src/eemkit/gui/project_tab.py +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/src/eemkit/gui/state.py +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/src/eemkit/gui/theme.py +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/src/eemkit/io/__init__.py +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/src/eemkit/io/_cary_csv.py +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/src/eemkit/io/cary60.py +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/src/eemkit/io/cary_eclipse.py +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/src/eemkit/io/discover.py +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/src/eemkit/io/instruments.py +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/src/eemkit/io/loader.py +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/src/eemkit/io/pairing.py +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/src/eemkit/parafac/_cp.py +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/src/eemkit/parafac/compare.py +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/src/eemkit/parafac/diagnostics.py +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/src/eemkit/parafac/export.py +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/src/eemkit/parafac/model.py +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/src/eemkit/parafac/outliers.py +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/src/eemkit/parafac/validation.py +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/src/eemkit/pipeline.py +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/src/eemkit/plot.py +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/tests/conftest.py +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/tests/data/eemR/README.md +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/tests/data/eemR/aqualog/sample4.dat +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/tests/data/eemR/eemR_DESCRIPTION.txt +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/tests/data/eemR/fluoromax4/f1.dat +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/tests/data/eemR/fluoromax4/f2.dat +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/tests/data/eemR/fluoromax4/f3.dat +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/tests/data/eemR/hitachi-f7000-fl/hitachi1.TXT +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/tests/data/eemR/hitachi-f7000-fl/hitachi2.TXT +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/tests/data/eemR/shimadzu/shimadzu.TXT +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/tests/test_absorbance.py +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/tests/test_campaigns.py +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/tests/test_cary60.py +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/tests/test_cary_eclipse.py +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/tests/test_cli.py +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/tests/test_corrections.py +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/tests/test_dataset.py +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/tests/test_dilution_zap.py +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/tests/test_grid.py +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/tests/test_gui.py +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/tests/test_instruments.py +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/tests/test_pairing.py +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/tests/test_parafac.py +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/tests/test_parafac_compare.py +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/tests/test_pipeline.py +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/tests/test_plot.py +0 -0
- {eemkit-0.2.0 → eemkit-0.3.0}/tests/test_real_data.py +0 -0
|
@@ -3,6 +3,34 @@
|
|
|
3
3
|
All notable changes are listed here. Versions follow
|
|
4
4
|
[semantic versioning](https://semver.org/).
|
|
5
5
|
|
|
6
|
+
## 0.3.0 (2026-11-23)
|
|
7
|
+
|
|
8
|
+
A new function to check what a filter-based optical channel sees, and a fix
|
|
9
|
+
to the indices table. The values of everything that could be computed in 0.2.0
|
|
10
|
+
are unchanged.
|
|
11
|
+
|
|
12
|
+
* New: `parafac.component_signals(model, channels)`: the signal each PARAFAC
|
|
13
|
+
component gives in an LED and filter channel, for every sample (score x
|
|
14
|
+
excitation loading weighted by the LED x emission loading integrated over the
|
|
15
|
+
filter), with the share of each component and the channel's sensitivity.
|
|
16
|
+
Meant to check whether a channel (e.g. a tryptophan-like one) follows the
|
|
17
|
+
component it is meant to follow.
|
|
18
|
+
* **Fixed: one index that cannot be computed no longer stops the whole
|
|
19
|
+
index table.** In 0.2.0, `compute_indices` (and so the application, the
|
|
20
|
+
command line and `pipeline.compute_indices`) raised as soon as one index or
|
|
21
|
+
peak needed a wavelength outside the measured range: for example, on data
|
|
22
|
+
whose emission starts at 300.3 nm (the drEEM tutorial data), HIX needs
|
|
23
|
+
300 nm and no index at all was returned. Now that index is left empty
|
|
24
|
+
(NaN) with an `EEMKitWarning` giving the reason, every other index and peak
|
|
25
|
+
is computed, and the reasons are kept in
|
|
26
|
+
`df.attrs["settings"]["not_computed"]` (also in the JSON file of
|
|
27
|
+
`export_indices`). Each peak is computed on its own, so one peak outside
|
|
28
|
+
the data does not empty the others. `on_error="raise"` keeps the old,
|
|
29
|
+
strict behaviour. Values of the indices that can be computed do not
|
|
30
|
+
change.
|
|
31
|
+
* HTML report: index columns that are empty for every sample are listed with
|
|
32
|
+
their reason, instead of being left out of the summary without a word.
|
|
33
|
+
|
|
6
34
|
## 0.2.0 (2026-11-06)
|
|
7
35
|
|
|
8
36
|
Other fluorometers, diluted samples, zap, PARAFAC model comparison and
|
|
@@ -25,7 +53,6 @@ consistency is now computed as in drEEM (first item).
|
|
|
25
53
|
wide laptop screen.
|
|
26
54
|
* Benchmark of the PARAFAC fit against drEEM 2.26.03 (N-way and parafac3w
|
|
27
55
|
engines) on the Ombrone data: same model, Tucker congruence ≥ 0.9999.
|
|
28
|
-
|
|
29
56
|
* Command line: `eemkit check project.toml` reports missing files and
|
|
30
57
|
settings; `eemkit run project.toml` runs the whole chain and exports the
|
|
31
58
|
results, as the application does (also `python -m eemkit`).
|
|
@@ -6,13 +6,16 @@ authors:
|
|
|
6
6
|
- family-names: Cirrone
|
|
7
7
|
given-names: Riccardo Gaetano
|
|
8
8
|
affiliation: University of Siena
|
|
9
|
-
version: 0.
|
|
10
|
-
date-released: "2026-11-
|
|
9
|
+
version: 0.3.0
|
|
10
|
+
date-released: "2026-11-23"
|
|
11
11
|
doi: 10.5281/zenodo.23982732
|
|
12
12
|
identifiers:
|
|
13
13
|
- type: doi
|
|
14
14
|
value: 10.5281/zenodo.23982732
|
|
15
15
|
description: "All versions (concept DOI); resolves to the latest release"
|
|
16
|
+
- type: doi
|
|
17
|
+
value: 10.5281/zenodo.24015024
|
|
18
|
+
description: "Version 0.2.0"
|
|
16
19
|
- type: doi
|
|
17
20
|
value: 10.5281/zenodo.23982733
|
|
18
21
|
description: "Version 0.1.0"
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: eemkit
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.3.0
|
|
4
4
|
Summary: Excitation-emission matrix (EEM) processing and PARAFAC modelling of dissolved organic matter fluorescence
|
|
5
5
|
Project-URL: Homepage, https://github.com/LowCostSensor/eemkit
|
|
6
6
|
Project-URL: Documentation, https://lowcostsensor.github.io/eemkit/
|
|
@@ -211,7 +211,8 @@ If you use eemkit, please cite it, together with the methods it implements
|
|
|
211
211
|
> [doi:10.5281/zenodo.23982732](https://doi.org/10.5281/zenodo.23982732)
|
|
212
212
|
|
|
213
213
|
This DOI always points to the latest version; each release also has its own
|
|
214
|
-
DOI, listed on the Zenodo page (0.
|
|
214
|
+
DOI, listed on the Zenodo page (0.2.0:
|
|
215
|
+
[10.5281/zenodo.24015024](https://doi.org/10.5281/zenodo.24015024); 0.1.0:
|
|
215
216
|
[10.5281/zenodo.23982733](https://doi.org/10.5281/zenodo.23982733)). The
|
|
216
217
|
details are in
|
|
217
218
|
[CITATION.cff](https://github.com/LowCostSensor/eemkit/blob/main/CITATION.cff).
|
|
@@ -167,7 +167,8 @@ If you use eemkit, please cite it, together with the methods it implements
|
|
|
167
167
|
> [doi:10.5281/zenodo.23982732](https://doi.org/10.5281/zenodo.23982732)
|
|
168
168
|
|
|
169
169
|
This DOI always points to the latest version; each release also has its own
|
|
170
|
-
DOI, listed on the Zenodo page (0.
|
|
170
|
+
DOI, listed on the Zenodo page (0.2.0:
|
|
171
|
+
[10.5281/zenodo.24015024](https://doi.org/10.5281/zenodo.24015024); 0.1.0:
|
|
171
172
|
[10.5281/zenodo.23982733](https://doi.org/10.5281/zenodo.23982733)). The
|
|
172
173
|
details are in
|
|
173
174
|
[CITATION.cff](https://github.com/LowCostSensor/eemkit/blob/main/CITATION.cff).
|
|
@@ -88,7 +88,8 @@ Cite eemkit as *Cirrone, R. G. eemkit: EEM processing and PARAFAC modelling
|
|
|
88
88
|
of dissolved organic matter fluorescence. Zenodo.
|
|
89
89
|
[doi:10.5281/zenodo.23982732](https://doi.org/10.5281/zenodo.23982732)*,
|
|
90
90
|
together with the methods you used. This DOI always points to the latest
|
|
91
|
-
version; each release has its own DOI on the Zenodo page (0.
|
|
91
|
+
version; each release has its own DOI on the Zenodo page (0.2.0:
|
|
92
|
+
[10.5281/zenodo.24015024](https://doi.org/10.5281/zenodo.24015024); 0.1.0:
|
|
92
93
|
[10.5281/zenodo.23982733](https://doi.org/10.5281/zenodo.23982733)). Full
|
|
93
94
|
metadata:
|
|
94
95
|
[CITATION.cff](https://github.com/LowCostSensor/eemkit/blob/main/CITATION.cff). eemkit is free software under the GNU General Public License v3.0 or
|
|
@@ -24,6 +24,14 @@ emission pair used by eemR, or `peak_definitions=` for other peaks.
|
|
|
24
24
|
* A value that would need a missing point (removed scatter) is NaN and raises
|
|
25
25
|
a warning, so compute indices **before** scatter removal: peak B at ex 275 /
|
|
26
26
|
em 310 lies inside the first-order Raman band.
|
|
27
|
+
* An index or peak the data cannot give at all (a wavelength outside the
|
|
28
|
+
measured range, e.g. HIX needs emission from 300 nm and the data start at
|
|
29
|
+
300.3 nm; or an excitation that was not measured with `ex_method="exact"`)
|
|
30
|
+
is left **empty** with a warning that gives the reason; the other indices
|
|
31
|
+
are still computed. The reasons are stored in
|
|
32
|
+
`df.attrs["settings"]["not_computed"]`, written to the JSON file of
|
|
33
|
+
`export_indices`, and listed in the HTML report. Pass `on_error="raise"` to
|
|
34
|
+
stop at the first index that cannot be computed instead.
|
|
27
35
|
* Ratios depend on the instrument's spectral response (Cory et al. 2010).
|
|
28
36
|
Without [spectral correction](corrections.md#spectral-correction), compare
|
|
29
37
|
them only with values from the same instrument.
|
|
@@ -149,6 +149,36 @@ the same way; a warning says when their processing history differs.
|
|
|
149
149
|
sample used to build the model: the model does not describe them well, and
|
|
150
150
|
they may contain a component the model does not have.
|
|
151
151
|
|
|
152
|
+
## Signal of each component in an LED and filter channel
|
|
153
|
+
|
|
154
|
+
```python
|
|
155
|
+
ch = {"T": {"ex": 280.0, "em": (330.0, 370.0)}, # LED line, flat filter band (nm)
|
|
156
|
+
"H": {"ex": 330.0, "em": ([420, 440, 480], [0.0, 0.8, 0.0])}} # filter table
|
|
157
|
+
sig = eemkit.parafac.component_signals(model, ch)
|
|
158
|
+
sig["signal"] # sample x channel x component
|
|
159
|
+
sig["share"] # each component's share of the channel signal
|
|
160
|
+
sig["sensitivity"] # channel x component: signal per unit score
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
A sensor with an LED and an emission filter records one number per sample.
|
|
164
|
+
The fitted model says how much of it each component accounts for: the
|
|
165
|
+
component's score times its excitation loading at the LED wavelength times its
|
|
166
|
+
emission loading integrated over the filter. With `ex` a single wavelength the
|
|
167
|
+
LED is a line; a band `(low, high)` or a table `(wavelengths, weights)` is
|
|
168
|
+
averaged with its weights, so a wide LED is not counted as a single line.
|
|
169
|
+
The filter is a band `(low, high)` with flat transmission or a table
|
|
170
|
+
`(wavelengths, transmission)`; band edges need not fall on the model's grid
|
|
171
|
+
(the loadings are interpolated linearly). Loadings have unit norm and the
|
|
172
|
+
scores carry the scale, so the signal is in the units of the data times nm
|
|
173
|
+
(`reduce="integral"`, the default) or in data units (`reduce="mean"`, the
|
|
174
|
+
integral divided by the filter's area). Wavelengths outside the model's range
|
|
175
|
+
raise an error. `sensitivity` does not depend on the samples: it shows which
|
|
176
|
+
components a channel can see at all, e.g. whether a tryptophan-like channel
|
|
177
|
+
sits on the protein component or on a humic tail.
|
|
178
|
+
|
|
179
|
+
The numbers describe the model, not the sensor: lamp output, detector
|
|
180
|
+
response and filter blocking beyond the table are not included.
|
|
181
|
+
|
|
152
182
|
## References
|
|
153
183
|
|
|
154
184
|
Andersson, C.A., Bro, R. (2000) *Chemometrics and Intelligent Laboratory Systems* 52, 1–4 ·
|
|
@@ -22,9 +22,12 @@ Excitation wavelengths that are not on the measured grid (e.g. 254, 275 or
|
|
|
22
22
|
Emission values off the grid are linearly interpolated; emission areas are
|
|
23
23
|
trapezoidal integrals of the piecewise-linear spectrum between the exact
|
|
24
24
|
limits. A value that needs a NaN point (e.g. removed scatter) is NaN and
|
|
25
|
-
triggers a warning.
|
|
26
|
-
|
|
27
|
-
|
|
25
|
+
triggers a warning. In :func:`compute_indices`, an index the dataset cannot
|
|
26
|
+
give at all (a wavelength outside the measured range) is left empty with a
|
|
27
|
+
warning and its reason recorded, and the other indices are still computed.
|
|
28
|
+
Ratios are unit-free; peaks are in the units of ``intensity``. Indices
|
|
29
|
+
depend on instrument spectral response (Cory et al. 2010), so the
|
|
30
|
+
spectral-correction status travels with every result.
|
|
28
31
|
"""
|
|
29
32
|
|
|
30
33
|
from __future__ import annotations
|
|
@@ -42,6 +45,8 @@ from eemkit.core.history import get_history
|
|
|
42
45
|
from eemkit.errors import EEMKitWarning, IndexComputationError
|
|
43
46
|
|
|
44
47
|
EX_METHODS = ("linear", "nearest", "exact")
|
|
48
|
+
#: what :func:`compute_indices` does with an index it cannot compute
|
|
49
|
+
ON_ERROR = ("nan", "raise")
|
|
45
50
|
|
|
46
51
|
#: Coble (1996) peaks: name -> (ex nm, (em_min, em_max) nm)
|
|
47
52
|
COBLE_1996: dict[str, tuple[float, tuple[float, float]]] = {
|
|
@@ -203,23 +208,49 @@ def compute_indices(
|
|
|
203
208
|
hix: Mapping | None = None,
|
|
204
209
|
bix: Mapping | None = None,
|
|
205
210
|
peak_definitions: Mapping[str, tuple[float, tuple[float, float]]] | None = None,
|
|
211
|
+
on_error: str = "nan",
|
|
206
212
|
) -> pd.DataFrame:
|
|
207
213
|
"""All indices in one table (one row per sample) with the settings in ``df.attrs``.
|
|
208
214
|
|
|
209
215
|
``fi``, ``hix``, ``bix`` are keyword overrides for the respective
|
|
210
216
|
functions; ``peak_definitions`` defaults to :data:`COBLE_1996`.
|
|
211
217
|
``ex_method`` applies to every index and peak.
|
|
218
|
+
|
|
219
|
+
An index or peak that cannot be computed on this dataset (a wavelength
|
|
220
|
+
outside the measured range, or an excitation that was not measured when
|
|
221
|
+
``ex_method="exact"``) does not stop the table: with ``on_error="nan"``
|
|
222
|
+
(default) its column is left empty (NaN), an :class:`EEMKitWarning` says
|
|
223
|
+
why, and the reason is stored in ``df.attrs["settings"]["not_computed"]``
|
|
224
|
+
(and so in the JSON sidecar of :func:`export_indices`). With
|
|
225
|
+
``on_error="raise"`` the :class:`IndexComputationError` is raised instead.
|
|
212
226
|
"""
|
|
227
|
+
if on_error not in ON_ERROR:
|
|
228
|
+
raise ValueError(f"on_error must be one of {ON_ERROR}")
|
|
213
229
|
fi, hix, bix = dict(fi or {}), dict(hix or {}), dict(bix or {})
|
|
214
230
|
peak_definitions = dict(peak_definitions or COBLE_1996)
|
|
231
|
+
samples = pd.Index(ds["sample"].values, name="sample")
|
|
232
|
+
not_computed: dict[str, str] = {}
|
|
233
|
+
|
|
234
|
+
def attempt(name: str, compute) -> pd.Series:
|
|
235
|
+
try:
|
|
236
|
+
return compute().to_series()
|
|
237
|
+
except IndexComputationError as exc:
|
|
238
|
+
if on_error == "raise":
|
|
239
|
+
raise
|
|
240
|
+
not_computed[name] = str(exc)
|
|
241
|
+
warnings.warn(f"{name} not computed: {exc}", EEMKitWarning, stacklevel=3)
|
|
242
|
+
return pd.Series(np.nan, index=samples, name=name)
|
|
243
|
+
|
|
215
244
|
cols = {
|
|
216
|
-
"FI": fluorescence_index(ds, ex_method=ex_method, **fi),
|
|
217
|
-
"HIX": humification_index(ds, ex_method=ex_method, **hix),
|
|
218
|
-
"BIX": biological_index(ds, ex_method=ex_method, **bix),
|
|
245
|
+
"FI": attempt("FI", lambda: fluorescence_index(ds, ex_method=ex_method, **fi)),
|
|
246
|
+
"HIX": attempt("HIX", lambda: humification_index(ds, ex_method=ex_method, **hix)),
|
|
247
|
+
"BIX": attempt("BIX", lambda: biological_index(ds, ex_method=ex_method, **bix)),
|
|
219
248
|
}
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
249
|
+
for k, definition in peak_definitions.items():
|
|
250
|
+
cols[f"peak_{k}"] = attempt(
|
|
251
|
+
f"peak_{k}",
|
|
252
|
+
lambda k=k, d=definition: peaks(ds, {k: d}, ex_method=ex_method)[k])
|
|
253
|
+
df = pd.DataFrame(cols)
|
|
223
254
|
df.index.name = "sample"
|
|
224
255
|
df.attrs["settings"] = {
|
|
225
256
|
"ex_method": ex_method,
|
|
@@ -232,6 +263,7 @@ def compute_indices(
|
|
|
232
263
|
"definitions": {k: [v[0], list(v[1])] for k, v in peak_definitions.items()},
|
|
233
264
|
"units": ds["intensity"].attrs.get("units", "")},
|
|
234
265
|
"spectral_correction": ds.attrs.get("spectral_correction", "none"),
|
|
266
|
+
"not_computed": not_computed,
|
|
235
267
|
"processing_history": get_history(ds),
|
|
236
268
|
}
|
|
237
269
|
return df
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
"""Non-negative PARAFAC with the diagnostics of Murphy et al. (2013)."""
|
|
2
2
|
|
|
3
3
|
from eemkit.parafac._cp import nn_parafac
|
|
4
|
+
from eemkit.parafac.channels import component_signals
|
|
4
5
|
from eemkit.parafac.compare import compare_models, compare_ranks, component_correlations
|
|
5
6
|
from eemkit.parafac.diagnostics import (
|
|
6
7
|
core_consistency,
|
|
@@ -26,6 +27,7 @@ __all__ = [
|
|
|
26
27
|
"compare_models",
|
|
27
28
|
"compare_ranks",
|
|
28
29
|
"component_correlations",
|
|
30
|
+
"component_signals",
|
|
29
31
|
"core_consistency",
|
|
30
32
|
"eemqual",
|
|
31
33
|
"fit_parafac",
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
"""Signal of each PARAFAC component in a filter-based optical channel.
|
|
2
|
+
|
|
3
|
+
A sensor with an LED and an emission filter does not record an EEM: it records
|
|
4
|
+
one number per sample, the fluorescence excited by the LED and passed by the
|
|
5
|
+
filter. A fitted PARAFAC model says how much of that number each component
|
|
6
|
+
accounts for. The modelled EEM of a sample is
|
|
7
|
+
|
|
8
|
+
X(ex, em) = sum_f score_f * exload_f(ex) * emload_f(em)
|
|
9
|
+
|
|
10
|
+
so the part of a channel's signal that comes from component f is
|
|
11
|
+
|
|
12
|
+
score_f * (LED-weighted excitation loading) * (filter-weighted emission integral).
|
|
13
|
+
|
|
14
|
+
Loadings of an eemkit model have unit norm and the scores carry the scale, so
|
|
15
|
+
the result is in the units of the data multiplied by nm (the emission
|
|
16
|
+
integral); ``reduce="mean"`` divides by the filter's integrated transmission
|
|
17
|
+
instead and returns data units.
|
|
18
|
+
|
|
19
|
+
No threshold or decision is made here: the numbers say whether a channel (e.g.
|
|
20
|
+
a tryptophan-like "T" channel) follows the component it is meant to follow or
|
|
21
|
+
a humic one.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
from __future__ import annotations
|
|
25
|
+
|
|
26
|
+
from collections.abc import Mapping
|
|
27
|
+
|
|
28
|
+
import numpy as np
|
|
29
|
+
import xarray as xr
|
|
30
|
+
|
|
31
|
+
from eemkit.core.dataset import SAMPLE_DIM
|
|
32
|
+
from eemkit.errors import SettingsError
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _profile(spec, name: str, kind: str):
|
|
36
|
+
"""(wavelengths, weights) of an LED or a filter given as a number, a band or a table."""
|
|
37
|
+
if np.ndim(spec) == 0: # a single wavelength
|
|
38
|
+
return np.array([float(spec)]), np.array([1.0])
|
|
39
|
+
if len(spec) != 2:
|
|
40
|
+
raise SettingsError(f"channel {name!r}, {kind}: give a wavelength, a band (low, high) "
|
|
41
|
+
"or a table (wavelengths, weights)")
|
|
42
|
+
a, b = spec
|
|
43
|
+
if np.ndim(a) == 0 and np.ndim(b) == 0: # a band (low, high)
|
|
44
|
+
lo, hi = float(a), float(b)
|
|
45
|
+
if not lo < hi:
|
|
46
|
+
raise SettingsError(f"channel {name!r}, {kind}: band {lo}-{hi} nm is empty")
|
|
47
|
+
return np.array([lo, hi]), np.array([1.0, 1.0])
|
|
48
|
+
wl, w = np.asarray(a, float), np.asarray(b, float)
|
|
49
|
+
if wl.ndim != 1 or wl.shape != w.shape or wl.size < 2 or np.any(np.diff(wl) <= 0):
|
|
50
|
+
raise SettingsError(f"channel {name!r}, {kind}: a table needs increasing wavelengths "
|
|
51
|
+
"and one weight each")
|
|
52
|
+
if np.any(w < 0) or not np.any(w > 0):
|
|
53
|
+
raise SettingsError(f"channel {name!r}, {kind}: weights must be >= 0 and not all zero")
|
|
54
|
+
return wl, w
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _check_range(wl: np.ndarray, grid: np.ndarray, name: str, kind: str, mode: str) -> None:
|
|
58
|
+
if wl.min() < grid.min() or wl.max() > grid.max():
|
|
59
|
+
raise SettingsError(
|
|
60
|
+
f"channel {name!r}, {kind}: {wl.min():g}-{wl.max():g} nm is outside the "
|
|
61
|
+
f"{mode} range of the model ({grid.min():g}-{grid.max():g} nm)")
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _trapz(y: np.ndarray, x: np.ndarray) -> float:
|
|
65
|
+
"""Trapezoid rule (numpy.trapezoid needs numpy 2; eemkit supports 1.24)."""
|
|
66
|
+
return float(np.sum((y[1:] + y[:-1]) * np.diff(x)) / 2)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _weighted_ex(loadings: np.ndarray, grid: np.ndarray, wl, w) -> np.ndarray:
|
|
70
|
+
"""Excitation loadings averaged with the LED's spectrum (weights sum to 1)."""
|
|
71
|
+
if wl.size == 1:
|
|
72
|
+
return np.array([np.interp(wl[0], grid, loadings[:, f])
|
|
73
|
+
for f in range(loadings.shape[1])])
|
|
74
|
+
fine = np.union1d(grid[(grid >= wl.min()) & (grid <= wl.max())], wl)
|
|
75
|
+
wf = np.interp(fine, wl, w)
|
|
76
|
+
return np.array([_trapz(wf * np.interp(fine, grid, loadings[:, f]), fine)
|
|
77
|
+
for f in range(loadings.shape[1])]) / _trapz(wf, fine)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _filter_em(loadings: np.ndarray, grid: np.ndarray, wl, w):
|
|
81
|
+
"""Emission integral of each loading over the filter, and the integral of the filter."""
|
|
82
|
+
fine = np.union1d(grid[(grid >= wl.min()) & (grid <= wl.max())], wl)
|
|
83
|
+
wf = np.interp(fine, wl, w) # a band (low, high) is flat: weights 1, 1
|
|
84
|
+
ints = np.array([_trapz(wf * np.interp(fine, grid, loadings[:, f]), fine)
|
|
85
|
+
for f in range(loadings.shape[1])])
|
|
86
|
+
return ints, _trapz(wf, fine)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def component_signals(model: xr.Dataset, channels: Mapping[str, Mapping],
|
|
90
|
+
reduce: str = "integral") -> xr.Dataset:
|
|
91
|
+
"""Signal each component gives in each LED + filter channel, for every sample.
|
|
92
|
+
|
|
93
|
+
``channels`` maps a channel name to ``{"ex": ..., "em": ...}``:
|
|
94
|
+
|
|
95
|
+
* ``ex``, the LED: one wavelength (nm), a band ``(low, high)`` (flat
|
|
96
|
+
spectrum), or a table ``(wavelengths, weights)`` of its emission
|
|
97
|
+
spectrum. A band or table is averaged with the weights (scaled to sum
|
|
98
|
+
to one), so a wide LED is not counted as a single line.
|
|
99
|
+
* ``em``, the filter: a band ``(low, high)`` in nm (flat transmission), or a
|
|
100
|
+
table ``(wavelengths, transmission)``.
|
|
101
|
+
|
|
102
|
+
The emission loadings are integrated over the filter with the trapezoid
|
|
103
|
+
rule on the union of the model's grid and the band edges (the edges are
|
|
104
|
+
interpolated, so a band need not fall on grid points). With
|
|
105
|
+
``reduce="integral"`` (default) the result is in data units x nm; with
|
|
106
|
+
``reduce="mean"`` the integral is divided by the filter's integrated
|
|
107
|
+
transmission (data units).
|
|
108
|
+
|
|
109
|
+
Returns a dataset with ``signal`` (sample, channel, component), ``total``
|
|
110
|
+
(sample, channel; the sum over components), ``share`` (sample, channel,
|
|
111
|
+
component; signal over total, NaN where the total is zero) and
|
|
112
|
+
``sensitivity`` (channel, component; signal per unit of score, which tells
|
|
113
|
+
which components a channel can see at all, independent of the samples).
|
|
114
|
+
Ranges outside the excitation or emission range of the model raise an
|
|
115
|
+
error; the model is not extrapolated.
|
|
116
|
+
"""
|
|
117
|
+
if reduce not in ("integral", "mean"):
|
|
118
|
+
raise SettingsError("reduce must be 'integral' or 'mean'")
|
|
119
|
+
if not channels:
|
|
120
|
+
raise SettingsError("give at least one channel")
|
|
121
|
+
ex, em = model["ex"].values.astype(float), model["em"].values.astype(float)
|
|
122
|
+
B, C = model["ex_loadings"].values, model["em_loadings"].values
|
|
123
|
+
scores = model["scores"].values
|
|
124
|
+
names, sens = list(channels), []
|
|
125
|
+
for name in names:
|
|
126
|
+
spec = channels[name]
|
|
127
|
+
if "ex" not in spec or "em" not in spec:
|
|
128
|
+
raise SettingsError(f"channel {name!r} needs 'ex' (LED) and 'em' (filter)")
|
|
129
|
+
wl_ex, w_ex = _profile(spec["ex"], name, "LED")
|
|
130
|
+
wl_em, w_em = _profile(spec["em"], name, "filter")
|
|
131
|
+
if wl_em.size == 1:
|
|
132
|
+
raise SettingsError(f"channel {name!r}, filter: give a band (low, high) or a "
|
|
133
|
+
"table, not a single wavelength")
|
|
134
|
+
_check_range(wl_ex, ex, name, "LED", "excitation")
|
|
135
|
+
_check_range(wl_em, em, name, "filter", "emission")
|
|
136
|
+
ex_eff = _weighted_ex(B, ex, wl_ex, w_ex)
|
|
137
|
+
em_int, area = _filter_em(C, em, wl_em, w_em)
|
|
138
|
+
if reduce == "mean":
|
|
139
|
+
em_int = em_int / area
|
|
140
|
+
sens.append(ex_eff * em_int)
|
|
141
|
+
sens = np.array(sens) # (channel, component)
|
|
142
|
+
signal = scores[:, None, :] * sens[None, :, :] # (sample, channel, component)
|
|
143
|
+
total = signal.sum(axis=2)
|
|
144
|
+
with np.errstate(invalid="ignore", divide="ignore"):
|
|
145
|
+
share = np.where(total[:, :, None] != 0, signal / total[:, :, None], np.nan)
|
|
146
|
+
units = model["scores"].attrs.get("units", "")
|
|
147
|
+
unit = (f"{units} nm" if units else "nm") if reduce == "integral" else units
|
|
148
|
+
dims = (SAMPLE_DIM, "channel", "component")
|
|
149
|
+
coords = {SAMPLE_DIM: model[SAMPLE_DIM].values, "channel": names,
|
|
150
|
+
"component": model["component"].values}
|
|
151
|
+
out = xr.Dataset(
|
|
152
|
+
{"signal": (dims, signal, {"units": unit, "long_name": "signal of each component"}),
|
|
153
|
+
"total": ((SAMPLE_DIM, "channel"), total, {"units": unit}),
|
|
154
|
+
"share": (dims, share, {"long_name": "share of the channel signal"}),
|
|
155
|
+
"sensitivity": (("channel", "component"), sens,
|
|
156
|
+
{"units": unit, "long_name": "signal per unit score"})},
|
|
157
|
+
coords=coords)
|
|
158
|
+
out.attrs = {"reduce": reduce, "source": "eemkit.parafac.component_signals"}
|
|
159
|
+
return out
|
|
@@ -195,6 +195,18 @@ def write_report(
|
|
|
195
195
|
desc = num.describe().T[["count", "mean", "std", "min", "max"]]
|
|
196
196
|
body = ("<p>Summary over all samples; the full table is in <code>indices.csv</code>."
|
|
197
197
|
"</p>" + _table(desc))
|
|
198
|
+
# an index the data cannot give is an empty column: say so instead of
|
|
199
|
+
# leaving it out of the summary silently
|
|
200
|
+
reasons = indices.attrs.get("settings", {}).get("not_computed", {})
|
|
201
|
+
empty = [c for c in indices.columns
|
|
202
|
+
if (c in ("FI", "HIX", "BIX") or str(c).startswith("peak_"))
|
|
203
|
+
and indices[c].isna().all()]
|
|
204
|
+
if empty:
|
|
205
|
+
items = "".join(f"<li><code>{html.escape(str(c))}</code>"
|
|
206
|
+
+ (f": {html.escape(reasons[c])}" if c in reasons else "")
|
|
207
|
+
+ "</li>" for c in empty)
|
|
208
|
+
body += ('<p class="warn">Not computed for these data (empty columns):</p>'
|
|
209
|
+
f"<ul>{items}</ul>")
|
|
198
210
|
if "cdom_notes" in indices:
|
|
199
211
|
n_notes = int((indices["cdom_notes"].fillna("").astype(str) != "").sum())
|
|
200
212
|
if n_notes:
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
import pytest
|
|
3
|
+
import xarray as xr
|
|
4
|
+
|
|
5
|
+
from eemkit import SettingsError
|
|
6
|
+
from eemkit import parafac as P
|
|
7
|
+
from eemkit.parafac.channels import _trapz
|
|
8
|
+
|
|
9
|
+
EX = np.arange(240.0, 451.0, 10.0)
|
|
10
|
+
EM = np.arange(250.0, 601.0, 5.0)
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def gauss(x, c, w):
|
|
14
|
+
return np.exp(-0.5 * ((x - c) / w) ** 2)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def unit(v):
|
|
18
|
+
return v / np.linalg.norm(v, axis=0)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def make_model(n=6, seed=0, em_loadings=None):
|
|
22
|
+
"""A model with known loadings: humic-like C1, humic-like C2, tryptophan-like C3."""
|
|
23
|
+
rng = np.random.default_rng(seed)
|
|
24
|
+
B = unit(np.column_stack([gauss(EX, 250, 30), gauss(EX, 330, 25), gauss(EX, 280, 12)]))
|
|
25
|
+
C = unit(np.column_stack([gauss(EM, 450, 50), gauss(EM, 410, 40), gauss(EM, 345, 20)])
|
|
26
|
+
if em_loadings is None else em_loadings)
|
|
27
|
+
A = rng.lognormal(0, 0.5, (n, 3))
|
|
28
|
+
return xr.Dataset(
|
|
29
|
+
{"scores": (("sample", "component"), A, {"units": "R.U."}),
|
|
30
|
+
"ex_loadings": (("ex", "component"), B),
|
|
31
|
+
"em_loadings": (("em", "component"), C)},
|
|
32
|
+
coords={"sample": [f"s{i}" for i in range(n)], "ex": EX, "em": EM,
|
|
33
|
+
"component": [1, 2, 3]})
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def test_total_is_the_integral_of_the_modelled_eem():
|
|
37
|
+
m = make_model()
|
|
38
|
+
eem = P.model_eem(m)
|
|
39
|
+
ch = {"T": {"ex": 280.0, "em": (330.0, 370.0)}}
|
|
40
|
+
out = P.component_signals(m, ch)
|
|
41
|
+
band = (EM >= 330) & (EM <= 370)
|
|
42
|
+
expect = [_trapz(eem.sel(sample=s, ex=280.0).values[band], EM[band])
|
|
43
|
+
for s in m["sample"].values]
|
|
44
|
+
np.testing.assert_allclose(out["total"].sel(channel="T"), expect, rtol=1e-12)
|
|
45
|
+
np.testing.assert_allclose(out["signal"].sum("component"), out["total"])
|
|
46
|
+
assert out["signal"].attrs["units"] == "R.U. nm"
|
|
47
|
+
assert out["signal"].dims == ("sample", "channel", "component")
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def test_signal_is_score_times_loadings():
|
|
51
|
+
m = make_model()
|
|
52
|
+
out = P.component_signals(m, {"T": {"ex": 280.0, "em": (330.0, 370.0)}})
|
|
53
|
+
band = (EM >= 330) & (EM <= 370)
|
|
54
|
+
f = 2 # C3 (index 2)
|
|
55
|
+
em_int = _trapz(m["em_loadings"].values[band, f], EM[band])
|
|
56
|
+
ex_val = float(m["ex_loadings"].sel(ex=280.0).values[f])
|
|
57
|
+
np.testing.assert_allclose(out["signal"].values[:, 0, f],
|
|
58
|
+
m["scores"].values[:, f] * ex_val * em_int, rtol=1e-12)
|
|
59
|
+
np.testing.assert_allclose(out["sensitivity"].values[0, f], ex_val * em_int, rtol=1e-12)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def test_a_channel_on_the_protein_peak_follows_the_protein_component():
|
|
63
|
+
m = make_model()
|
|
64
|
+
out = P.component_signals(m, {"T": {"ex": 280.0, "em": (335.0, 355.0)},
|
|
65
|
+
"H": {"ex": 330.0, "em": (430.0, 470.0)}})
|
|
66
|
+
share = out["share"]
|
|
67
|
+
assert float(share.sel(channel="T", component=3).min()) > 0.5
|
|
68
|
+
assert float(share.sel(channel="H", component=3).max()) < 0.1
|
|
69
|
+
np.testing.assert_allclose(share.sum("component"), 1.0)
|
|
70
|
+
sens = out["sensitivity"]
|
|
71
|
+
assert int(sens.sel(channel="T").argmax("component")) == 2
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def test_band_edges_between_grid_points_are_interpolated():
|
|
75
|
+
# linear emission loadings: the trapezoid rule is exact, also between grid points
|
|
76
|
+
C = np.column_stack([EM / 600, 2 - EM / 600, np.full_like(EM, 0.5)])
|
|
77
|
+
m = make_model(em_loadings=C)
|
|
78
|
+
Cn = m["em_loadings"].values
|
|
79
|
+
lo, hi = 332.5, 371.5
|
|
80
|
+
out = P.component_signals(m, {"x": {"ex": 280.0, "em": (lo, hi)}})
|
|
81
|
+
for f in range(3):
|
|
82
|
+
slope = (Cn[1, f] - Cn[0, f]) / 5
|
|
83
|
+
icpt = Cn[0, f] - slope * EM[0]
|
|
84
|
+
exact = icpt * (hi - lo) + slope * (hi ** 2 - lo ** 2) / 2
|
|
85
|
+
got = out["sensitivity"].values[0, f] / float(m["ex_loadings"].sel(ex=280.0)[f])
|
|
86
|
+
assert got == pytest.approx(exact, rel=1e-10)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def test_mean_is_the_integral_over_the_filter_area():
|
|
90
|
+
m = make_model()
|
|
91
|
+
ch = {"T": {"ex": 280.0, "em": (330.0, 370.0)}}
|
|
92
|
+
i = P.component_signals(m, ch)
|
|
93
|
+
mean = P.component_signals(m, ch, reduce="mean")
|
|
94
|
+
np.testing.assert_allclose(mean["signal"], i["signal"] / 40.0, rtol=1e-12)
|
|
95
|
+
assert mean["signal"].attrs["units"] == "R.U."
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def test_filter_table_and_flat_band_agree_when_transmission_is_one():
|
|
99
|
+
m = make_model()
|
|
100
|
+
band = P.component_signals(m, {"T": {"ex": 280.0, "em": (330.0, 370.0)}})
|
|
101
|
+
table = P.component_signals(m, {"T": {"ex": 280.0,
|
|
102
|
+
"em": ([330.0, 370.0], [1.0, 1.0])}})
|
|
103
|
+
np.testing.assert_allclose(table["signal"], band["signal"])
|
|
104
|
+
half = P.component_signals(m, {"T": {"ex": 280.0, "em": ([330.0, 370.0], [0.5, 0.5])}})
|
|
105
|
+
np.testing.assert_allclose(half["signal"], 0.5 * band["signal"])
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def test_led_table_is_a_weighted_average_of_the_loadings():
|
|
109
|
+
m = make_model()
|
|
110
|
+
two = P.component_signals(m, {"x": {"ex": ([270.0, 290.0], [1.0, 1.0]),
|
|
111
|
+
"em": (330.0, 370.0)}})
|
|
112
|
+
line = {w: P.component_signals(m, {"x": {"ex": w, "em": (330.0, 370.0)}})
|
|
113
|
+
for w in (270.0, 280.0, 290.0)}
|
|
114
|
+
# flat LED over 270-290 nm, trapezoid on the 10 nm grid: (a + 2 b + c) / 4
|
|
115
|
+
expect = (line[270.0]["sensitivity"] + 2 * line[280.0]["sensitivity"]
|
|
116
|
+
+ line[290.0]["sensitivity"]) / 4
|
|
117
|
+
np.testing.assert_allclose(two["sensitivity"], expect, rtol=1e-12)
|
|
118
|
+
# a very narrow LED is the single line (the loadings are linear between grid points,
|
|
119
|
+
# so a window of 0.02 nm around a grid point differs from the line by ~0.01 nm of slope)
|
|
120
|
+
narrow = P.component_signals(m, {"x": {"ex": ([279.99, 280.01], [1, 1]),
|
|
121
|
+
"em": (330.0, 370.0)}})
|
|
122
|
+
np.testing.assert_allclose(narrow["sensitivity"], line[280.0]["sensitivity"], rtol=1e-3)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def test_share_is_nan_where_the_total_is_zero():
|
|
126
|
+
m = make_model()
|
|
127
|
+
m["scores"].values[0] = 0.0
|
|
128
|
+
out = P.component_signals(m, {"T": {"ex": 280.0, "em": (330.0, 370.0)}})
|
|
129
|
+
assert np.isnan(out["share"].values[0]).all()
|
|
130
|
+
assert np.isfinite(out["share"].values[1:]).all()
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
@pytest.mark.parametrize("channels, match", [
|
|
134
|
+
({"x": {"ex": 200.0, "em": (330.0, 370.0)}}, "outside the excitation range"),
|
|
135
|
+
({"x": {"ex": 280.0, "em": (330.0, 700.0)}}, "outside the emission range"),
|
|
136
|
+
({"x": {"ex": 280.0, "em": 350.0}}, "not a single wavelength"),
|
|
137
|
+
({"x": {"ex": 280.0, "em": (370.0, 330.0)}}, "is empty"),
|
|
138
|
+
({"x": {"ex": 280.0}}, "needs 'ex'"),
|
|
139
|
+
({"x": {"ex": 280.0, "em": ([330.0, 370.0], [0.0, 0.0])}}, "weights"),
|
|
140
|
+
({"x": {"ex": 280.0, "em": ([370.0, 330.0], [1.0, 1.0])}}, "increasing"),
|
|
141
|
+
({}, "at least one channel"),
|
|
142
|
+
])
|
|
143
|
+
def test_bad_channels_are_rejected(channels, match):
|
|
144
|
+
with pytest.raises(SettingsError, match=match):
|
|
145
|
+
P.component_signals(make_model(), channels)
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def test_bad_reduce_is_rejected():
|
|
149
|
+
with pytest.raises(SettingsError, match="reduce"):
|
|
150
|
+
P.component_signals(make_model(), {"x": {"ex": 280.0, "em": (330.0, 370.0)}},
|
|
151
|
+
reduce="sum")
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def test_works_on_a_fitted_model():
|
|
155
|
+
m0 = make_model(n=30)
|
|
156
|
+
X = P.model_eem(m0).values
|
|
157
|
+
ds = xr.Dataset({"intensity": (("sample", "ex", "em"), X, {"units": "R.U."})},
|
|
158
|
+
coords={"sample": m0["sample"].values, "ex": EX, "em": EM})
|
|
159
|
+
ds.attrs["spectral_correction"] = "none"
|
|
160
|
+
fit = P.fit_parafac(ds, 3, n_init=3, max_iter=2000)
|
|
161
|
+
ch = {"T": {"ex": 280.0, "em": (330.0, 370.0)}}
|
|
162
|
+
out = P.component_signals(fit, ch)
|
|
163
|
+
# whatever the component order, the sum is the modelled signal of the sample
|
|
164
|
+
band = (EM >= 330) & (EM <= 370)
|
|
165
|
+
ref = [_trapz(P.model_eem(fit).sel(sample=s, ex=280.0).values[band], EM[band])
|
|
166
|
+
for s in fit["sample"].values]
|
|
167
|
+
np.testing.assert_allclose(out["total"].sel(channel="T"), ref, rtol=1e-10)
|
|
168
|
+
# and the model describes the data: same signal as the data themselves
|
|
169
|
+
data = [_trapz(ds["intensity"].sel(sample=s, ex=280.0).values[band], EM[band])
|
|
170
|
+
for s in fit["sample"].values]
|
|
171
|
+
np.testing.assert_allclose(out["total"].sel(channel="T"), data, rtol=0.05)
|
|
@@ -95,6 +95,49 @@ def test_compute_and_export(tmp_path):
|
|
|
95
95
|
assert back.loc["s1", "river"] == "B"
|
|
96
96
|
meta = json.loads(side.read_text())
|
|
97
97
|
assert meta["ex_method"] == "linear" and meta["HIX"]["reference"] == "Ohno 2002"
|
|
98
|
+
assert meta["not_computed"] == {}
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def test_index_the_data_cannot_give_leaves_the_rest_of_the_table():
|
|
102
|
+
# emission starts at 300.3 nm (as drEEM's tutorial data): HIX needs 300 nm
|
|
103
|
+
em = EM[EM >= 300.0] + 0.3
|
|
104
|
+
ds = make_ds(lambda ex, em: 1000.0 / em + ex / 1000).interp(em=em)
|
|
105
|
+
with pytest.warns(EEMKitWarning, match="HIX not computed"):
|
|
106
|
+
df = I.compute_indices(ds, ex_method="linear")
|
|
107
|
+
assert list(df.columns) == ["FI", "HIX", "BIX", "peak_B", "peak_T", "peak_A",
|
|
108
|
+
"peak_M", "peak_C"]
|
|
109
|
+
assert df["HIX"].isna().all()
|
|
110
|
+
assert df.drop(columns="HIX").notna().all().all()
|
|
111
|
+
assert "outside" in df.attrs["settings"]["not_computed"]["HIX"]
|
|
112
|
+
assert set(df.attrs["settings"]["not_computed"]) == {"HIX"}
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def test_unmeasured_excitations_with_exact_method_leave_the_rest():
|
|
116
|
+
# 254, 275 and 312 nm are not on the 10 nm grid; 260, 310, 350 and 370 are
|
|
117
|
+
ds = make_ds(lambda ex, em: 1000.0 / em + ex / 1000)
|
|
118
|
+
with pytest.warns(EEMKitWarning, match="not computed"):
|
|
119
|
+
df = I.compute_indices(ds, ex_method="exact")
|
|
120
|
+
empty = {c for c in df if df[c].isna().all()}
|
|
121
|
+
assert empty == {"HIX", "peak_B", "peak_T", "peak_M"}
|
|
122
|
+
assert set(df.attrs["settings"]["not_computed"]) == empty
|
|
123
|
+
assert df[["FI", "BIX", "peak_A", "peak_C"]].notna().all().all()
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def test_one_failing_peak_does_not_drop_the_others():
|
|
127
|
+
ds = make_ds(lambda ex, em: em + 0 * ex)
|
|
128
|
+
defs = {"T": I.COBLE_1996["T"], "X": (500.0, (400.0, 450.0))} # ex 500 not measured
|
|
129
|
+
with pytest.warns(EEMKitWarning, match="peak_X not computed"):
|
|
130
|
+
df = I.compute_indices(ds, ex_method="linear", peak_definitions=defs)
|
|
131
|
+
assert df["peak_X"].isna().all() and df["peak_T"].notna().all()
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def test_on_error_raise_keeps_the_strict_behaviour():
|
|
135
|
+
em = EM[EM >= 300.0] + 0.3
|
|
136
|
+
ds = make_ds(lambda ex, em: em + 0 * ex).interp(em=em)
|
|
137
|
+
with pytest.raises(IndexComputationError, match="outside"):
|
|
138
|
+
I.compute_indices(ds, ex_method="linear", on_error="raise")
|
|
139
|
+
with pytest.raises(ValueError, match="on_error"):
|
|
140
|
+
I.compute_indices(ds, ex_method="linear", on_error="skip")
|
|
98
141
|
|
|
99
142
|
|
|
100
143
|
def test_per_scan_coordinates_do_not_break_peaks():
|
|
@@ -86,3 +86,14 @@ def test_report_with_only_settings(tmp_path):
|
|
|
86
86
|
path = write_report(tmp_path / "report.html", pipeline.default_settings())
|
|
87
87
|
text = path.read_text(encoding="utf-8")
|
|
88
88
|
assert 'id="reproduce"' in text and 'id="model"' not in text
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def test_report_names_indices_that_were_not_computed(tmp_path):
|
|
92
|
+
indices = pd.DataFrame({"FI": [1.4, 1.5], "HIX": [np.nan, np.nan]}, index=["s0", "s1"])
|
|
93
|
+
indices.attrs["settings"] = {"not_computed": {"HIX": "emission 300.0 nm is outside "
|
|
94
|
+
"300.3-618.5 nm"}}
|
|
95
|
+
path = write_report(tmp_path / "report.html", pipeline.default_settings(), indices=indices)
|
|
96
|
+
text = path.read_text(encoding="utf-8")
|
|
97
|
+
assert "Not computed for these data" in text
|
|
98
|
+
assert "<code>HIX</code>: emission 300.0 nm is outside 300.3-618.5 nm" in text
|
|
99
|
+
assert "<code>FI</code>" not in text
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|