eemkit 0.3.0__tar.gz → 0.4.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.
Files changed (116) hide show
  1. {eemkit-0.3.0 → eemkit-0.4.0}/CHANGELOG.md +19 -0
  2. {eemkit-0.3.0 → eemkit-0.4.0}/CITATION.cff +1 -1
  3. {eemkit-0.3.0 → eemkit-0.4.0}/PKG-INFO +4 -1
  4. {eemkit-0.3.0 → eemkit-0.4.0}/README.md +3 -0
  5. {eemkit-0.3.0 → eemkit-0.4.0}/docs/app-guide.md +11 -1
  6. {eemkit-0.3.0 → eemkit-0.4.0}/docs/parafac.md +10 -0
  7. {eemkit-0.3.0 → eemkit-0.4.0}/docs/plotting.md +1 -0
  8. {eemkit-0.3.0 → eemkit-0.4.0}/src/eemkit/__init__.py +1 -1
  9. {eemkit-0.3.0 → eemkit-0.4.0}/src/eemkit/gui/parafac_tab.py +166 -0
  10. {eemkit-0.3.0 → eemkit-0.4.0}/src/eemkit/gui/state.py +11 -0
  11. {eemkit-0.3.0 → eemkit-0.4.0}/src/eemkit/parafac/channels.py +8 -3
  12. {eemkit-0.3.0 → eemkit-0.4.0}/src/eemkit/pipeline.py +64 -1
  13. {eemkit-0.3.0 → eemkit-0.4.0}/src/eemkit/plot.py +79 -0
  14. {eemkit-0.3.0 → eemkit-0.4.0}/src/eemkit/report.py +25 -1
  15. {eemkit-0.3.0 → eemkit-0.4.0}/tests/test_channels.py +110 -1
  16. {eemkit-0.3.0 → eemkit-0.4.0}/tests/test_gui.py +18 -1
  17. {eemkit-0.3.0 → eemkit-0.4.0}/.gitignore +0 -0
  18. {eemkit-0.3.0 → eemkit-0.4.0}/LICENSE +0 -0
  19. {eemkit-0.3.0 → eemkit-0.4.0}/docs/absorbance.md +0 -0
  20. {eemkit-0.3.0 → eemkit-0.4.0}/docs/api.md +0 -0
  21. {eemkit-0.3.0 → eemkit-0.4.0}/docs/campaigns.md +0 -0
  22. {eemkit-0.3.0 → eemkit-0.4.0}/docs/cli.md +0 -0
  23. {eemkit-0.3.0 → eemkit-0.4.0}/docs/corrections.md +0 -0
  24. {eemkit-0.3.0 → eemkit-0.4.0}/docs/data_model.md +0 -0
  25. {eemkit-0.3.0 → eemkit-0.4.0}/docs/gui.md +0 -0
  26. {eemkit-0.3.0 → eemkit-0.4.0}/docs/img/app/1_project.png +0 -0
  27. {eemkit-0.3.0 → eemkit-0.4.0}/docs/img/app/2_corrections.png +0 -0
  28. {eemkit-0.3.0 → eemkit-0.4.0}/docs/img/app/3_indices.png +0 -0
  29. {eemkit-0.3.0 → eemkit-0.4.0}/docs/img/app/4a_parafac_ranks.png +0 -0
  30. {eemkit-0.3.0 → eemkit-0.4.0}/docs/img/app/4b_parafac_outliers.png +0 -0
  31. {eemkit-0.3.0 → eemkit-0.4.0}/docs/img/app/4c_parafac_final.png +0 -0
  32. {eemkit-0.3.0 → eemkit-0.4.0}/docs/img/app/4d_parafac_by_model.png +0 -0
  33. {eemkit-0.3.0 → eemkit-0.4.0}/docs/img/app/5a_rivers_time.png +0 -0
  34. {eemkit-0.3.0 → eemkit-0.4.0}/docs/img/app/5b_rivers_composition.png +0 -0
  35. {eemkit-0.3.0 → eemkit-0.4.0}/docs/img/app/5c_rivers_tests.png +0 -0
  36. {eemkit-0.3.0 → eemkit-0.4.0}/docs/img/app/6_export.png +0 -0
  37. {eemkit-0.3.0 → eemkit-0.4.0}/docs/index.md +0 -0
  38. {eemkit-0.3.0 → eemkit-0.4.0}/docs/indices.md +0 -0
  39. {eemkit-0.3.0 → eemkit-0.4.0}/docs/instruments.md +0 -0
  40. {eemkit-0.3.0 → eemkit-0.4.0}/docs/quickstart.md +0 -0
  41. {eemkit-0.3.0 → eemkit-0.4.0}/pyproject.toml +0 -0
  42. {eemkit-0.3.0 → eemkit-0.4.0}/src/eemkit/__main__.py +0 -0
  43. {eemkit-0.3.0 → eemkit-0.4.0}/src/eemkit/absorbance.py +0 -0
  44. {eemkit-0.3.0 → eemkit-0.4.0}/src/eemkit/campaigns.py +0 -0
  45. {eemkit-0.3.0 → eemkit-0.4.0}/src/eemkit/cli.py +0 -0
  46. {eemkit-0.3.0 → eemkit-0.4.0}/src/eemkit/core/__init__.py +0 -0
  47. {eemkit-0.3.0 → eemkit-0.4.0}/src/eemkit/core/dataset.py +0 -0
  48. {eemkit-0.3.0 → eemkit-0.4.0}/src/eemkit/core/grid.py +0 -0
  49. {eemkit-0.3.0 → eemkit-0.4.0}/src/eemkit/core/history.py +0 -0
  50. {eemkit-0.3.0 → eemkit-0.4.0}/src/eemkit/corrections/__init__.py +0 -0
  51. {eemkit-0.3.0 → eemkit-0.4.0}/src/eemkit/corrections/_common.py +0 -0
  52. {eemkit-0.3.0 → eemkit-0.4.0}/src/eemkit/corrections/blank.py +0 -0
  53. {eemkit-0.3.0 → eemkit-0.4.0}/src/eemkit/corrections/crop.py +0 -0
  54. {eemkit-0.3.0 → eemkit-0.4.0}/src/eemkit/corrections/dilution.py +0 -0
  55. {eemkit-0.3.0 → eemkit-0.4.0}/src/eemkit/corrections/inner_filter.py +0 -0
  56. {eemkit-0.3.0 → eemkit-0.4.0}/src/eemkit/corrections/instrument.py +0 -0
  57. {eemkit-0.3.0 → eemkit-0.4.0}/src/eemkit/corrections/raman.py +0 -0
  58. {eemkit-0.3.0 → eemkit-0.4.0}/src/eemkit/corrections/scatter.py +0 -0
  59. {eemkit-0.3.0 → eemkit-0.4.0}/src/eemkit/corrections/spectral.py +0 -0
  60. {eemkit-0.3.0 → eemkit-0.4.0}/src/eemkit/corrections/zap.py +0 -0
  61. {eemkit-0.3.0 → eemkit-0.4.0}/src/eemkit/errors.py +0 -0
  62. {eemkit-0.3.0 → eemkit-0.4.0}/src/eemkit/gui/__init__.py +0 -0
  63. {eemkit-0.3.0 → eemkit-0.4.0}/src/eemkit/gui/__main__.py +0 -0
  64. {eemkit-0.3.0 → eemkit-0.4.0}/src/eemkit/gui/campaigns_tab.py +0 -0
  65. {eemkit-0.3.0 → eemkit-0.4.0}/src/eemkit/gui/common.py +0 -0
  66. {eemkit-0.3.0 → eemkit-0.4.0}/src/eemkit/gui/corrections_tab.py +0 -0
  67. {eemkit-0.3.0 → eemkit-0.4.0}/src/eemkit/gui/export_tab.py +0 -0
  68. {eemkit-0.3.0 → eemkit-0.4.0}/src/eemkit/gui/indices_tab.py +0 -0
  69. {eemkit-0.3.0 → eemkit-0.4.0}/src/eemkit/gui/main_window.py +0 -0
  70. {eemkit-0.3.0 → eemkit-0.4.0}/src/eemkit/gui/project_tab.py +0 -0
  71. {eemkit-0.3.0 → eemkit-0.4.0}/src/eemkit/gui/theme.py +0 -0
  72. {eemkit-0.3.0 → eemkit-0.4.0}/src/eemkit/indices.py +0 -0
  73. {eemkit-0.3.0 → eemkit-0.4.0}/src/eemkit/io/__init__.py +0 -0
  74. {eemkit-0.3.0 → eemkit-0.4.0}/src/eemkit/io/_cary_csv.py +0 -0
  75. {eemkit-0.3.0 → eemkit-0.4.0}/src/eemkit/io/cary60.py +0 -0
  76. {eemkit-0.3.0 → eemkit-0.4.0}/src/eemkit/io/cary_eclipse.py +0 -0
  77. {eemkit-0.3.0 → eemkit-0.4.0}/src/eemkit/io/discover.py +0 -0
  78. {eemkit-0.3.0 → eemkit-0.4.0}/src/eemkit/io/instruments.py +0 -0
  79. {eemkit-0.3.0 → eemkit-0.4.0}/src/eemkit/io/loader.py +0 -0
  80. {eemkit-0.3.0 → eemkit-0.4.0}/src/eemkit/io/pairing.py +0 -0
  81. {eemkit-0.3.0 → eemkit-0.4.0}/src/eemkit/parafac/__init__.py +0 -0
  82. {eemkit-0.3.0 → eemkit-0.4.0}/src/eemkit/parafac/_cp.py +0 -0
  83. {eemkit-0.3.0 → eemkit-0.4.0}/src/eemkit/parafac/compare.py +0 -0
  84. {eemkit-0.3.0 → eemkit-0.4.0}/src/eemkit/parafac/diagnostics.py +0 -0
  85. {eemkit-0.3.0 → eemkit-0.4.0}/src/eemkit/parafac/export.py +0 -0
  86. {eemkit-0.3.0 → eemkit-0.4.0}/src/eemkit/parafac/model.py +0 -0
  87. {eemkit-0.3.0 → eemkit-0.4.0}/src/eemkit/parafac/outliers.py +0 -0
  88. {eemkit-0.3.0 → eemkit-0.4.0}/src/eemkit/parafac/validation.py +0 -0
  89. {eemkit-0.3.0 → eemkit-0.4.0}/tests/conftest.py +0 -0
  90. {eemkit-0.3.0 → eemkit-0.4.0}/tests/data/eemR/README.md +0 -0
  91. {eemkit-0.3.0 → eemkit-0.4.0}/tests/data/eemR/aqualog/sample4.dat +0 -0
  92. {eemkit-0.3.0 → eemkit-0.4.0}/tests/data/eemR/eemR_DESCRIPTION.txt +0 -0
  93. {eemkit-0.3.0 → eemkit-0.4.0}/tests/data/eemR/fluoromax4/f1.dat +0 -0
  94. {eemkit-0.3.0 → eemkit-0.4.0}/tests/data/eemR/fluoromax4/f2.dat +0 -0
  95. {eemkit-0.3.0 → eemkit-0.4.0}/tests/data/eemR/fluoromax4/f3.dat +0 -0
  96. {eemkit-0.3.0 → eemkit-0.4.0}/tests/data/eemR/hitachi-f7000-fl/hitachi1.TXT +0 -0
  97. {eemkit-0.3.0 → eemkit-0.4.0}/tests/data/eemR/hitachi-f7000-fl/hitachi2.TXT +0 -0
  98. {eemkit-0.3.0 → eemkit-0.4.0}/tests/data/eemR/shimadzu/shimadzu.TXT +0 -0
  99. {eemkit-0.3.0 → eemkit-0.4.0}/tests/test_absorbance.py +0 -0
  100. {eemkit-0.3.0 → eemkit-0.4.0}/tests/test_campaigns.py +0 -0
  101. {eemkit-0.3.0 → eemkit-0.4.0}/tests/test_cary60.py +0 -0
  102. {eemkit-0.3.0 → eemkit-0.4.0}/tests/test_cary_eclipse.py +0 -0
  103. {eemkit-0.3.0 → eemkit-0.4.0}/tests/test_cli.py +0 -0
  104. {eemkit-0.3.0 → eemkit-0.4.0}/tests/test_corrections.py +0 -0
  105. {eemkit-0.3.0 → eemkit-0.4.0}/tests/test_dataset.py +0 -0
  106. {eemkit-0.3.0 → eemkit-0.4.0}/tests/test_dilution_zap.py +0 -0
  107. {eemkit-0.3.0 → eemkit-0.4.0}/tests/test_grid.py +0 -0
  108. {eemkit-0.3.0 → eemkit-0.4.0}/tests/test_indices.py +0 -0
  109. {eemkit-0.3.0 → eemkit-0.4.0}/tests/test_instruments.py +0 -0
  110. {eemkit-0.3.0 → eemkit-0.4.0}/tests/test_outliers_report.py +0 -0
  111. {eemkit-0.3.0 → eemkit-0.4.0}/tests/test_pairing.py +0 -0
  112. {eemkit-0.3.0 → eemkit-0.4.0}/tests/test_parafac.py +0 -0
  113. {eemkit-0.3.0 → eemkit-0.4.0}/tests/test_parafac_compare.py +0 -0
  114. {eemkit-0.3.0 → eemkit-0.4.0}/tests/test_pipeline.py +0 -0
  115. {eemkit-0.3.0 → eemkit-0.4.0}/tests/test_plot.py +0 -0
  116. {eemkit-0.3.0 → eemkit-0.4.0}/tests/test_real_data.py +0 -0
@@ -3,6 +3,25 @@
3
3
  All notable changes are listed here. Versions follow
4
4
  [semantic versioning](https://semver.org/).
5
5
 
6
+ ## 0.4.0 (2026-11-23)
7
+
8
+ Sensor channels (LED and filter) in the application, the figures and the
9
+ report. Nothing that existed before changes.
10
+
11
+ * **Sensor channels in the application, the figures and the report.** The
12
+ PARAFAC page has a new view, `Sensor channels`: type the LED wavelength and
13
+ the filter band of each channel and see, for the final or any exploratory
14
+ model, which components it follows (the channels on the mean modelled EEM,
15
+ the share of each component per channel with its range between samples).
16
+ The channels are saved in the project (`[channels.NAME]`), and with them
17
+ the export writes `parafac_*comp_channels.csv`,
18
+ `parafac_*comp_channel_sensitivity.csv` and `figures/channel_signals`; the
19
+ HTML report gets a `Sensor channels` section. New figure
20
+ `plot.channel_signals`; `pipeline.channel_signals`, `channel_specs` and
21
+ `channel_tables` do the same from scripts and the command line
22
+ (`eemkit run`). `component_signals` now also returns where each channel
23
+ sits (`ex_min`, `ex_max`, `em_min`, `em_max`).
24
+
6
25
  ## 0.3.0 (2026-11-23)
7
26
 
8
27
  A new function to check what a filter-based optical channel sees, and a fix
@@ -6,7 +6,7 @@ authors:
6
6
  - family-names: Cirrone
7
7
  given-names: Riccardo Gaetano
8
8
  affiliation: University of Siena
9
- version: 0.3.0
9
+ version: 0.4.0
10
10
  date-released: "2026-11-23"
11
11
  doi: 10.5281/zenodo.23982732
12
12
  identifiers:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: eemkit
3
- Version: 0.3.0
3
+ Version: 0.4.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/
@@ -86,6 +86,9 @@ step recorded so that an analysis can be repeated exactly.
86
86
  & Vidal 2011); models and ranks can be compared component by component.
87
87
  * **Outliers**: leverage, residuals by sample and by wavelength, and residual
88
88
  EEMs of the worst-fitted samples.
89
+ * **Sensor channels**: which components an LED and filter channel follows
90
+ (signal and share of each component per sample), in the application, the
91
+ figures, the report and from Python (`parafac.component_signals`).
89
92
  * **New samples** can be scored on a fitted model with its spectra fixed;
90
93
  samples the model describes worse than any of its own are flagged.
91
94
  * **Rivers, sites and dates**: any index, CDOM metric or PARAFAC component
@@ -42,6 +42,9 @@ step recorded so that an analysis can be repeated exactly.
42
42
  & Vidal 2011); models and ranks can be compared component by component.
43
43
  * **Outliers**: leverage, residuals by sample and by wavelength, and residual
44
44
  EEMs of the worst-fitted samples.
45
+ * **Sensor channels**: which components an LED and filter channel follows
46
+ (signal and share of each component per sample), in the application, the
47
+ figures, the report and from Python (`parafac.component_signals`).
45
48
  * **New samples** can be scored on a fitted model with its spectra fixed;
46
49
  samples the model describes worse than any of its own are flagged.
47
50
  * **Rivers, sites and dates**: any index, CDOM metric or PARAFAC component
@@ -259,6 +259,15 @@ In the `Final model` box set the number of components, initialisations (20), tol
259
259
 
260
260
  *The final Ombrone model (20 initialisations, all at the same minimum). The line at the top gives explained variance, core consistency, initialisations at the minimum and the split-half verdict.*
261
261
 
262
+ ### “Sensor channels” view
263
+
264
+ For a sensor with an LED and an emission filter: which components does each channel follow? One row per channel in the table: its name, the **LED wavelength** and the **filter band** (from, to), all in nm. `Add channel` inserts a row with starting values to edit (LED 280 nm, filter 330–370 nm); `Remove selected` deletes the selected rows. The `Model` menu chooses the final model or any exploratory model, so channels can be tried before the final fit.
265
+
266
+ * **Left figure:** the mean modelled EEM with each channel drawn on it: the LED excitation is the height of the bar, the filter band its length. A channel on the edge of a humic peak instead of the protein peak is visible at once.
267
+ * **Right figure and table:** the share of each component in the signal of each channel, mean over samples; the table also gives the range between samples (min–max). A channel meant to follow the protein-like component should have most of its signal there in every sample.
268
+ * The signal of a component in a channel is its score × its excitation loading at the LED wavelength × its emission loading integrated over the filter band. The numbers describe the model, not the sensor: lamp output, detector response and filter blocking outside the band are not included.
269
+ * A channel outside the wavelength range of the model is refused with a message. The channels are saved in the project (`[channels.NAME]`, with `ex` and `em = [from, to]`) and written on export. LED spectra and filter transmission curves (not just a line and a flat band) are available from Python: see [PARAFAC](parafac.md).
270
+
262
271
  ## 5 · Rivers and dates
263
272
 
264
273
  Compares campaigns, sites and rivers for any variable of the indices table or of the final model: indices, CDOM metrics, the Fmax of each component and its share of the total (`C1_pct`, …). The methods are described in [Rivers, sites and dates](campaigns.md).
@@ -312,9 +321,10 @@ Compares campaigns, sites and rivers for any variable of the indices table or of
312
321
  | `parafac_exploration.csv` | The “Number of components” table. |
313
322
  | `parafac_3comp_fmax.csv` | Fmax of every component per sample, in Raman units. |
314
323
  | `parafac_3comp_ex_loadings.csv` `parafac_3comp_em_loadings.csv` | Excitation and emission loadings. |
324
+ | `parafac_3comp_channels.csv` `parafac_3comp_channel_sensitivity.csv` | With sensor channels defined: signal and share of each component in each channel per sample, and the signal per unit score of each channel (see “Sensor channels”). |
315
325
  | `parafac_3comp_openfluor.txt` | File for OpenFluor. Check it against the current upload template before submitting it. |
316
326
  | `parafac_3comp_model.nc` | The complete model. |
317
- | `figures/` | Number-of-components diagnostics, components and leverage, as PDF and PNG, in the colours chosen in `View` → `EEM colours`. |
327
+ | `figures/` | Number-of-components diagnostics, components and leverage (and the sensor channels, when defined), as PDF and PNG, in the colours chosen in `View` → `EEM colours`. |
318
328
  | `report.html` | One page with the whole analysis: samples, every processing step, indices, the exploratory models, the final model with its validation, outlier diagnostics (residual EEMs of the worst-fitted samples, residuals by wavelength) and the settings. The figures are inside the page, so it can be e-mailed or archived as it is. |
319
329
 
320
330
  The `3` in the names is the number of components of the final model.
@@ -179,6 +179,16 @@ sits on the protein component or on a humic tail.
179
179
  The numbers describe the model, not the sensor: lamp output, detector
180
180
  response and filter blocking beyond the table are not included.
181
181
 
182
+ `eemkit.plot.channel_signals(sig, model)` draws the channels on the mean
183
+ modelled EEM next to the share of each component in each channel. In the
184
+ application, the `Sensor channels` view of the PARAFAC page does the same for
185
+ the final or an exploratory model, with channels typed as a table (LED
186
+ wavelength, filter from and to); they are saved in the project as
187
+ `[channels.NAME]` with `ex = 280.0` and `em = [330.0, 370.0]`, and written on
188
+ export (`parafac_*comp_channels.csv`, `figures/channel_signals`) and in the
189
+ HTML report. LED spectra and filter transmission tables are available from
190
+ Python only.
191
+
182
192
  ## References
183
193
 
184
194
  Andersson, C.A., Bro, R. (2000) *Chemometrics and Intelligent Laboratory Systems* 52, 1–4 ·
@@ -12,6 +12,7 @@ Each function returns a matplotlib figure; `plot.save(fig, "fig1")` writes
12
12
  | `spectral_factors(ds)` | the excitation and emission correction factors applied |
13
13
  | `rank_diagnostics(table, chosen=3)` | explained variance, core consistency and split-half congruence vs rank, one panel each |
14
14
  | `leverage(model, by="river")` | leverage vs residuals, the most extreme samples labelled |
15
+ | `channel_signals(sig, model)` | LED and filter channels on the mean modelled EEM, and the share of each component in each channel |
15
16
  | `scores_over(df, cols, x="campaign", by="river")` | mean ± SD per group over time, samples as faint points |
16
17
 
17
18
  Widths default to two journal columns (180 mm); `plot.SINGLE_COLUMN` is 85 mm.
@@ -1,6 +1,6 @@
1
1
  """eemkit: EEM processing and PARAFAC modelling of dissolved organic matter fluorescence."""
2
2
 
3
- __version__ = "0.3.0"
3
+ __version__ = "0.4.0"
4
4
 
5
5
  from eemkit import corrections, indices, parafac, pipeline
6
6
  from eemkit.core.dataset import stack
@@ -9,6 +9,7 @@ from PySide6.QtWidgets import (
9
9
  QComboBox,
10
10
  QFormLayout,
11
11
  QGroupBox,
12
+ QHeaderView,
12
13
  QLabel,
13
14
  QLineEdit,
14
15
  QListWidget,
@@ -18,12 +19,15 @@ from PySide6.QtWidgets import (
18
19
  QSpinBox,
19
20
  QSplitter,
20
21
  QTableView,
22
+ QTableWidget,
23
+ QTableWidgetItem,
21
24
  QTabWidget,
22
25
  QVBoxLayout,
23
26
  QWidget,
24
27
  )
25
28
 
26
29
  from eemkit import pipeline, plot
30
+ from eemkit.errors import SettingsError
27
31
  from eemkit.gui.common import DataFrameModel, PlotPanel, TaskBar, note, pair, primary, spin
28
32
  from eemkit.gui.state import Project
29
33
 
@@ -172,11 +176,50 @@ class ParafacTab(QWidget):
172
176
  v.addWidget(self.final_text)
173
177
  v.addWidget(self.final_plot, 1)
174
178
 
179
+ # sensor channels: which components an LED and filter channel follows
180
+ self._editing_channels = False
181
+ self.ch_table = QTableWidget(0, 4)
182
+ self.ch_table.setHorizontalHeaderLabels(
183
+ ["Channel", "LED (nm)", "Filter from (nm)", "Filter to (nm)"])
184
+ self.ch_table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
185
+ self.ch_table.setMaximumHeight(150)
186
+ self.ch_table.itemChanged.connect(self._channels_edited)
187
+ b_add = QPushButton("Add channel")
188
+ b_add.clicked.connect(self.add_channel)
189
+ b_remove = QPushButton("Remove selected")
190
+ b_remove.clicked.connect(self.remove_channels)
191
+ self.ch_model = QComboBox()
192
+ self.ch_model.currentIndexChanged.connect(self.draw_channels)
193
+ self.ch_status = QLabel("")
194
+ self.ch_status.setWordWrap(True)
195
+ self.ch_plot = PlotPanel()
196
+ self.ch_shares_model = DataFrameModel()
197
+ ch_shares = QTableView()
198
+ ch_shares.setModel(self.ch_shares_model)
199
+ ch_shares.setMaximumHeight(130)
200
+ page_ch = QWidget()
201
+ v = QVBoxLayout(page_ch)
202
+ v.addWidget(note(
203
+ "A sensor with an LED and an emission filter records one number per sample. The "
204
+ "signal of a component in a channel is its score × its excitation loading at the "
205
+ "LED wavelength × its emission loading integrated over the filter band. These "
206
+ "numbers describe the model, not the sensor: lamp output, detector response and "
207
+ "filter blocking outside the band are not included."))
208
+ v.addWidget(pair(QLabel("Model"), self.ch_model))
209
+ v.addWidget(self.ch_table)
210
+ v.addWidget(pair(b_add, b_remove))
211
+ v.addWidget(self.ch_status)
212
+ v.addWidget(self.ch_plot, 1)
213
+ v.addWidget(QLabel("Share of each component in the channel signal, % (mean over "
214
+ "samples, with the range between samples)"))
215
+ v.addWidget(ch_shares)
216
+
175
217
  self.results = QTabWidget()
176
218
  self.results.addTab(page_summary, "Number of components")
177
219
  self.results.addTab(page_load, "Components by model")
178
220
  self.results.addTab(page_out, "Outliers")
179
221
  self.results.addTab(page_final, "Final model")
222
+ self.results.addTab(page_ch, "Sensor channels")
180
223
 
181
224
  split = QSplitter()
182
225
  split.addWidget(scroll)
@@ -216,6 +259,126 @@ class ParafacTab(QWidget):
216
259
  self.f_init.setValue(int(fin["n_init"]))
217
260
  self.f_tol.setText(f"{float(fin['tol']):g}")
218
261
  self.f_iter.setValue(int(fin["max_iter"]))
262
+ if not self._editing_channels:
263
+ self._fill_channels(self.project.settings.get("channels") or {})
264
+
265
+ # sensor channels ---------------------------------------------------- #
266
+
267
+ def _fill_channels(self, channels: dict) -> None:
268
+ self.ch_table.blockSignals(True)
269
+ self.ch_table.setRowCount(0)
270
+ for name, c in channels.items():
271
+ self._append_row([str(name), f"{float(c['ex']):g}", f"{float(c['em'][0]):g}",
272
+ f"{float(c['em'][1]):g}"])
273
+ self.ch_table.blockSignals(False)
274
+
275
+ def _append_row(self, cells: list[str]) -> None:
276
+ r = self.ch_table.rowCount()
277
+ self.ch_table.insertRow(r)
278
+ for c, text in enumerate(cells):
279
+ self.ch_table.setItem(r, c, QTableWidgetItem(text))
280
+
281
+ def add_channel(self) -> None:
282
+ """A new row with starting values to edit (a protein-like LED and filter)."""
283
+ taken = {self.ch_table.item(r, 0).text() for r in range(self.ch_table.rowCount())
284
+ if self.ch_table.item(r, 0)}
285
+ k = 1
286
+ while f"Ch{k}" in taken:
287
+ k += 1
288
+ self.ch_table.blockSignals(True)
289
+ self._append_row([f"Ch{k}", "280", "330", "370"])
290
+ self.ch_table.blockSignals(False)
291
+ self._channels_edited()
292
+
293
+ def remove_channels(self) -> None:
294
+ rows = sorted({i.row() for i in self.ch_table.selectedIndexes()}, reverse=True)
295
+ self.ch_table.blockSignals(True)
296
+ for r in rows:
297
+ self.ch_table.removeRow(r)
298
+ self.ch_table.blockSignals(False)
299
+ self._channels_edited()
300
+
301
+ def _read_channels(self) -> dict:
302
+ """The table as the ``channels`` settings; raises ValueError for a bad row."""
303
+ out: dict = {}
304
+ for r in range(self.ch_table.rowCount()):
305
+ cells = [(self.ch_table.item(r, c).text() if self.ch_table.item(r, c) else "").strip()
306
+ for c in range(4)]
307
+ if not any(cells):
308
+ continue
309
+ try:
310
+ ex, lo, hi = (float(x.replace(",", ".")) for x in cells[1:])
311
+ except ValueError:
312
+ raise ValueError(f"Row {r + 1}: the LED and the filter limits must be numbers "
313
+ "(nm).") from None
314
+ if cells[0] in out:
315
+ raise ValueError(f"The channel name {cells[0]!r} is used twice.")
316
+ out[cells[0]] = {"ex": ex, "em": [lo, hi]}
317
+ return out
318
+
319
+ def _channels_edited(self, *_args) -> None:
320
+ try:
321
+ channels = self._read_channels()
322
+ pipeline.channel_specs({"channels": channels})
323
+ except (ValueError, SettingsError) as exc:
324
+ self.ch_status.setText(str(exc))
325
+ return
326
+ self.ch_status.setText("")
327
+ self._editing_channels = True
328
+ try:
329
+ self.project.set_channels(channels)
330
+ finally:
331
+ self._editing_channels = False
332
+ self.draw_channels()
333
+
334
+ def _refresh_channel_models(self) -> None:
335
+ """The models channels can be computed on: the final one and the exploratory ones."""
336
+ keep = self.ch_model.currentData()
337
+ items: list[tuple[str, object]] = []
338
+ if self.project.model is not None:
339
+ items.append((f"Final model ({self.project.model.sizes['component']} components)",
340
+ "final"))
341
+ if self.project.exploration is not None:
342
+ items += [(f"Exploratory, {r} components", r) for r in self.project.exploration.models]
343
+ self.ch_model.blockSignals(True)
344
+ self.ch_model.clear()
345
+ for text, key in items:
346
+ self.ch_model.addItem(text, key)
347
+ k = self.ch_model.findData(keep)
348
+ self.ch_model.setCurrentIndex(k if k >= 0 else 0)
349
+ self.ch_model.blockSignals(False)
350
+ self.draw_channels()
351
+
352
+ def draw_channels(self) -> None:
353
+ key = self.ch_model.currentData()
354
+ channels = self.project.settings.get("channels") or {}
355
+ if key is None:
356
+ self.ch_plot.clear("Fit the final model or run the exploratory models first.")
357
+ self.ch_shares_model.set_frame(pd.DataFrame())
358
+ return
359
+ if not channels:
360
+ self.ch_plot.clear("Add a channel: the LED wavelength and the filter band.")
361
+ self.ch_shares_model.set_frame(pd.DataFrame())
362
+ return
363
+ model = self.project.model if key == "final" else self.project.exploration.models[key]
364
+ try:
365
+ sig = pipeline.channel_signals(model, self.project.settings)
366
+ except SettingsError as exc:
367
+ self.ch_status.setText(str(exc))
368
+ self.ch_plot.clear("The channels do not fit the wavelength range of the model.")
369
+ self.ch_shares_model.set_frame(pd.DataFrame())
370
+ return
371
+ self.ch_status.setText("")
372
+ self.ch_plot.show_figure(plot.channel_signals(sig, model, width=9.0,
373
+ cmap=self.project.eem_colours))
374
+ share = 100 * sig["share"]
375
+ lo, mean, hi = (share.min("sample"), share.mean("sample"), share.max("sample"))
376
+ table = pd.DataFrame(
377
+ {f"C{c}": [f"{mean.values[i, j]:.0f} ({lo.values[i, j]:.0f}–{hi.values[i, j]:.0f})"
378
+ for i in range(sig.sizes["channel"])]
379
+ for j, c in enumerate(sig["component"].values)},
380
+ index=pd.Index([str(c) for c in sig["channel"].values], name="channel"))
381
+ self.ch_shares_model.set_frame(table)
219
382
 
220
383
  def _exploration_settings(self) -> dict | None:
221
384
  try:
@@ -344,6 +507,9 @@ class ParafacTab(QWidget):
344
507
  self.draw_loadings()
345
508
  if self.project.model is not None:
346
509
  self.show_final()
510
+ if what in ("exploration", "final", "corrected", "settings", "display") \
511
+ and not (what == "settings" and self._editing_channels):
512
+ self._refresh_channel_models()
347
513
 
348
514
  def show_exploration(self) -> None:
349
515
  ex = self.project.exploration
@@ -112,6 +112,17 @@ class Project(QObject):
112
112
  if invalidates:
113
113
  self.invalidate(invalidates)
114
114
 
115
+ def set_channels(self, channels: dict) -> None:
116
+ """Replace the filter-based channels (``set_settings`` would only add to them).
117
+
118
+ Channels do not change any computed result, so nothing is invalidated.
119
+ """
120
+ if channels == (self.settings.get("channels") or {}):
121
+ return
122
+ self.settings["channels"] = channels
123
+ self.dirty = True
124
+ self.changed.emit("settings")
125
+
115
126
  @property
116
127
  def eem_colours(self) -> str:
117
128
  """Name of the EEM colour map (a key of :data:`eemkit.plot.COLORMAPS`)."""
@@ -121,7 +121,7 @@ def component_signals(model: xr.Dataset, channels: Mapping[str, Mapping],
121
121
  ex, em = model["ex"].values.astype(float), model["em"].values.astype(float)
122
122
  B, C = model["ex_loadings"].values, model["em_loadings"].values
123
123
  scores = model["scores"].values
124
- names, sens = list(channels), []
124
+ names, sens, extent = list(channels), [], []
125
125
  for name in names:
126
126
  spec = channels[name]
127
127
  if "ex" not in spec or "em" not in spec:
@@ -138,7 +138,8 @@ def component_signals(model: xr.Dataset, channels: Mapping[str, Mapping],
138
138
  if reduce == "mean":
139
139
  em_int = em_int / area
140
140
  sens.append(ex_eff * em_int)
141
- sens = np.array(sens) # (channel, component)
141
+ extent.append((wl_ex.min(), wl_ex.max(), wl_em.min(), wl_em.max()))
142
+ sens = np.array(sens) # (channel, component)
142
143
  signal = scores[:, None, :] * sens[None, :, :] # (sample, channel, component)
143
144
  total = signal.sum(axis=2)
144
145
  with np.errstate(invalid="ignore", divide="ignore"):
@@ -146,8 +147,12 @@ def component_signals(model: xr.Dataset, channels: Mapping[str, Mapping],
146
147
  units = model["scores"].attrs.get("units", "")
147
148
  unit = (f"{units} nm" if units else "nm") if reduce == "integral" else units
148
149
  dims = (SAMPLE_DIM, "channel", "component")
150
+ ext = np.array(extent, float)
149
151
  coords = {SAMPLE_DIM: model[SAMPLE_DIM].values, "channel": names,
150
- "component": model["component"].values}
152
+ "component": model["component"].values,
153
+ # where each channel sits (nm): LED range and filter range, for the figures
154
+ "ex_min": ("channel", ext[:, 0]), "ex_max": ("channel", ext[:, 1]),
155
+ "em_min": ("channel", ext[:, 2]), "em_max": ("channel", ext[:, 3])}
151
156
  out = xr.Dataset(
152
157
  {"signal": (dims, signal, {"units": unit, "long_name": "signal of each component"}),
153
158
  "total": ((SAMPLE_DIM, "channel"), total, {"units": unit}),
@@ -3,7 +3,7 @@
3
3
  The settings are a nested dictionary, stored as TOML, with the sections
4
4
  ``project``, ``spectral``, ``inner_filter``, ``raman``, ``scatter``, ``crop``,
5
5
  ``indices``, ``absorbance``, ``campaigns``, ``parafac`` (with ``split_half``
6
- and ``final``), ``missing`` and ``display``. The same file drives scripts and
6
+ and ``final``), ``channels``, ``missing`` and ``display``. The same file drives scripts and
7
7
  the desktop application, so every analysis can be rerun from the command line.
8
8
 
9
9
  Steps, in the enforced order of the corrections:
@@ -101,6 +101,10 @@ DEFAULTS: dict = {
101
101
  "split_half": {"n_init": 5, "stratify": [], "random_state": 0, "threshold": 0.95},
102
102
  "final": {"rank": None, "tol": 1e-8, "max_iter": 20000, "n_init": 20},
103
103
  },
104
+ # Filter-based optical channels to check against the PARAFAC components, one table per
105
+ # channel: [channels.T] ex = LED wavelength (nm), em = [filter low, filter high] (nm).
106
+ # Names: letters, digits, "_" and "-" only. Empty = no channels.
107
+ "channels": {},
104
108
  "missing": {"policy": "error"},
105
109
  # EEM colour map of the figures: "eclipse" (Cary Eclipse rainbow) or "blues"
106
110
  "display": {"eem_colours": "eclipse"},
@@ -430,6 +434,52 @@ def fit_final(ds: xr.Dataset, settings: dict, *, progress: Progress | None = Non
430
434
  # Campaigns, sites and rivers
431
435
  # --------------------------------------------------------------------------- #
432
436
 
437
+ _CHANNEL_NAME = re.compile(r"^[A-Za-z0-9_-]+$")
438
+
439
+
440
+ def channel_specs(settings: dict) -> dict:
441
+ """The ``channels`` section as the argument of :func:`eemkit.parafac.component_signals`.
442
+
443
+ Each channel is ``{"ex": LED wavelength, "em": [filter low, filter high]}`` (nm);
444
+ names may hold letters, digits, ``_`` and ``-`` only (they are TOML keys and
445
+ column labels). Raises :class:`SettingsError` for anything else.
446
+ """
447
+ out = {}
448
+ for name, c in (settings.get("channels") or {}).items():
449
+ if not _CHANNEL_NAME.match(str(name)):
450
+ raise SettingsError(f"channels.{name}: use letters, digits, '_' or '-' in the name")
451
+ try:
452
+ ex = float(c["ex"])
453
+ lo, hi = (float(v) for v in c["em"])
454
+ except (KeyError, TypeError, ValueError) as exc:
455
+ raise SettingsError(f"channels.{name} needs ex = LED wavelength (nm) and "
456
+ "em = [filter low, filter high] (nm)") from exc
457
+ if not lo < hi:
458
+ raise SettingsError(f"channels.{name}: the filter band {lo:g}-{hi:g} nm is empty")
459
+ out[str(name)] = {"ex": ex, "em": (lo, hi)}
460
+ return out
461
+
462
+
463
+ def channel_signals(model: xr.Dataset, settings: dict, reduce: str = "integral"
464
+ ) -> xr.Dataset | None:
465
+ """Signal of each component in each channel of ``settings['channels']`` (None if none).
466
+
467
+ See :func:`eemkit.parafac.component_signals`.
468
+ """
469
+ specs = channel_specs(settings)
470
+ return P.component_signals(model, specs, reduce=reduce) if specs else None
471
+
472
+
473
+ def channel_tables(signals: xr.Dataset) -> tuple[pd.DataFrame, pd.DataFrame]:
474
+ """``signals`` as two tables: per sample, channel and component (signal, share),
475
+ and the sensitivity of each channel to each component (rows = channels)."""
476
+ long = signals[["signal", "share"]].to_dataframe().reset_index()
477
+ long["component"] = "C" + long["component"].astype(str)
478
+ sens = signals["sensitivity"].to_pandas()
479
+ sens.columns = [f"C{c}" for c in sens.columns]
480
+ return long[["sample", "channel", "component", "signal", "share"]], sens
481
+
482
+
433
483
  def sample_table(indices: pd.DataFrame | None, model: xr.Dataset | None = None) -> pd.DataFrame:
434
484
  """Indices and CDOM metrics, plus Fmax and the share of each component if a model is given.
435
485
 
@@ -617,6 +667,14 @@ def export_results(
617
667
  if split is not None:
618
668
  record["parafac"]["split_half_min_tcc"] = split.attrs["min_tcc"]
619
669
  record["parafac"]["split_half_validated"] = bool(split.attrs["validated"])
670
+ sig = channel_signals(model, settings)
671
+ if sig is not None:
672
+ long, sens = channel_tables(sig)
673
+ written.append(out / f"parafac_{r}comp_channels.csv")
674
+ long.to_csv(written[-1], index=False, float_format="%.6g")
675
+ written.append(out / f"parafac_{r}comp_channel_sensitivity.csv")
676
+ sens.rename_axis("channel").to_csv(written[-1], float_format="%.6g")
677
+ record["channels"] = channel_specs(settings)
620
678
  if figures:
621
679
  written += export_figures(out / "figures", settings, exploration, model, split)
622
680
  if report:
@@ -651,4 +709,9 @@ def export_figures(out: Path, settings: dict, exploration: Exploration | None,
651
709
  ("leverage", plot.leverage(model))):
652
710
  written += plot.save(fig, out / name)
653
711
  plt.close(fig)
712
+ sig = channel_signals(model, settings)
713
+ if sig is not None:
714
+ fig = plot.channel_signals(sig, model, cmap=cmap)
715
+ written += plot.save(fig, out / "channel_signals")
716
+ plt.close(fig)
654
717
  return written
@@ -15,6 +15,7 @@ scatter) are shown in light grey.
15
15
 
16
16
  from __future__ import annotations
17
17
 
18
+ import warnings
18
19
  from collections.abc import Mapping, Sequence
19
20
  from contextlib import contextmanager
20
21
  from pathlib import Path
@@ -254,6 +255,84 @@ def components(model: xr.Dataset, split_half: xr.Dataset | None = None, *,
254
255
  return fig
255
256
 
256
257
 
258
+ _HATCHES = ("", "////", "....", "xxxx", "\\\\\\\\", "++++", "----", "oooo")
259
+
260
+
261
+ def channel_signals(signals: xr.Dataset, model: xr.Dataset | None = None, *,
262
+ names: Sequence[str] | None = None, width: float = DOUBLE_COLUMN,
263
+ cmap="blues"):
264
+ """What each LED and filter channel sees: where it sits, and which components it follows.
265
+
266
+ ``signals`` is the output of :func:`eemkit.parafac.component_signals`. Right
267
+ panel: one bar per channel, split by the share of each component in its
268
+ signal (mean over the samples; a component is also told apart by its hatch,
269
+ not by colour alone). With ``model`` a left panel shows the mean modelled
270
+ EEM with each channel on it: the LED excitation (vertical position) and
271
+ the filter band (horizontal extent), so a channel that sits on the edge of
272
+ a humic peak instead of the protein peak is visible at a glance.
273
+ """
274
+ from eemkit.parafac.model import model_eem
275
+
276
+ chan = [str(c) for c in signals["channel"].values]
277
+ comp = [int(c) for c in signals["component"].values]
278
+ names = list(names) if names is not None else [f"C{c}" for c in comp]
279
+ if len(comp) > len(CATEGORICAL):
280
+ raise ValueError(f"at most {len(CATEGORICAL)} components can be drawn")
281
+ with warnings.catch_warnings():
282
+ warnings.simplefilter("ignore", RuntimeWarning) # all-NaN shares: drawn as 0
283
+ mean = np.nan_to_num(np.nanmean(signals["share"].values, axis=0)) # (channel, comp)
284
+ ncols = 2 if model is not None else 1
285
+ with style():
286
+ fig, axes = plt.subplots(
287
+ 1, ncols, figsize=(width if model is not None else width * 0.6,
288
+ width * (0.42 if model is not None else 0.3)),
289
+ squeeze=False, layout="constrained",
290
+ width_ratios=[1, 1.15] if model is not None else None)
291
+ if model is not None:
292
+ ax = axes[0, 0]
293
+ mean_eem = model_eem(model).mean("sample")
294
+ mean_eem.attrs["units"] = model["scores"].attrs.get("units", "")
295
+ eem(ax, mean_eem, colorbar=True, label="Mean modelled intensity", cmap=cmap)
296
+ ax.set_title("Where the channels sit", loc="left")
297
+ for k, name in enumerate(chan):
298
+ x0, x1 = float(signals["em_min"][k]), float(signals["em_max"][k])
299
+ y0, y1 = float(signals["ex_min"][k]), float(signals["ex_max"][k])
300
+ if y1 - y0 < 1e-9: # LED line: a bar over the filter band
301
+ xs, ys = [x0, x1], [y0, y0]
302
+ ax.plot(xs, ys, color="white", lw=4.2, solid_capstyle="butt", zorder=3)
303
+ ax.plot(xs, ys, color=INK, lw=2.2, solid_capstyle="butt", zorder=4)
304
+ else: # LED band: a box
305
+ ax.add_patch(mpl.patches.Rectangle((x0, y0), x1 - x0, y1 - y0, fill=False,
306
+ ec="white", lw=3.2, zorder=3))
307
+ ax.add_patch(mpl.patches.Rectangle((x0, y0), x1 - x0, y1 - y0, fill=False,
308
+ ec=INK, lw=1.6, zorder=4))
309
+ ax.annotate(name, (x1, (y0 + y1) / 2), xytext=(4, 0), textcoords="offset points",
310
+ va="center", fontsize=7, color=INK, zorder=5,
311
+ bbox={"fc": "white", "ec": "none", "alpha": 0.8, "pad": 1.0})
312
+ ax = axes[0, ncols - 1]
313
+ y = np.arange(len(chan))[::-1]
314
+ left = np.zeros(len(chan))
315
+ for f in range(len(comp)):
316
+ pct = 100 * mean[:, f]
317
+ ax.barh(y, pct, left=left, height=0.62, color=_colour(f), hatch=_HATCHES[f],
318
+ ec="white", lw=0.8, label=names[f])
319
+ for yi, l0, w in zip(y, left, pct, strict=True):
320
+ if w >= 9:
321
+ ax.text(l0 + w / 2, yi, f"{w:.0f} %", ha="center", va="center", fontsize=6.5,
322
+ color=INK, bbox={"fc": "white", "ec": "none", "alpha": 0.85,
323
+ "pad": 1.0})
324
+ left = left + pct
325
+ ax.set_yticks(y, chan)
326
+ ax.set_xlim(0, 100)
327
+ ax.set_ylim(-0.6, len(chan) - 0.4)
328
+ ax.set_xlabel("Share of the channel signal (%), mean over samples")
329
+ ax.set_title("Which components it follows", loc="left")
330
+ ax.xaxis.grid(True)
331
+ ax.set_axisbelow(True)
332
+ fig.legend(*ax.get_legend_handles_labels(), loc="outside lower center", ncols=len(comp))
333
+ return fig
334
+
335
+
257
336
  def rank_diagnostics(table: pd.DataFrame, *, threshold: float = 0.95,
258
337
  chosen: int | None = None, width: float = DOUBLE_COLUMN):
259
338
  """Explained variance, core consistency and split-half congruence against rank.
@@ -162,7 +162,7 @@ def write_report(
162
162
  from eemkit import parafac as P
163
163
  from eemkit import plot
164
164
  from eemkit.core.history import get_history
165
- from eemkit.pipeline import dumps_settings, versions
165
+ from eemkit.pipeline import channel_signals, channel_specs, dumps_settings, versions
166
166
 
167
167
  del matplotlib # imported only to fail early when it is missing
168
168
  path = Path(path)
@@ -277,6 +277,30 @@ def write_report(
277
277
  + _table(fmax.describe().T[["mean", "std", "min", "max"]]))
278
278
  section("model", "Final PARAFAC model", body)
279
279
 
280
+ # --- filter-based channels ---------------------------------------------
281
+ sig = channel_signals(model, settings)
282
+ if sig is not None:
283
+ specs = channel_specs(settings)
284
+ rows = pd.DataFrame([
285
+ {"channel": k, "LED (nm)": v["ex"],
286
+ "filter (nm)": f"{v['em'][0]:g}-{v['em'][1]:g}"} for k, v in specs.items()])
287
+ share = (100 * sig["share"].mean("sample")).to_pandas()
288
+ share.columns = [f"C{c} share (%)" for c in share.columns]
289
+ body = ("<p>What each LED and filter channel would see in these samples: the signal "
290
+ "of a component in a channel is its score &times; its excitation loading at "
291
+ "the LED wavelength &times; its emission loading integrated over the "
292
+ "filter. The numbers describe the model, not the sensor: lamp output, "
293
+ "detector response and filter blocking outside the band are not "
294
+ "included.</p>" + _table(rows, index=False))
295
+ body += _figure(plot.channel_signals(sig, model, cmap=cmap),
296
+ "Channels on the mean modelled EEM (left) and the share of each "
297
+ "component in the signal of each channel, mean over samples (right).")
298
+ body += ("<h3>Share of each component, mean over samples</h3>"
299
+ + _table(share.rename_axis("channel"), digits=1)
300
+ + "<p>The signal of every sample is in "
301
+ "<code>parafac_*comp_channels.csv</code>.</p>")
302
+ section("channels", "Sensor channels", body)
303
+
280
304
  # --- outliers ---------------------------------------------------------
281
305
  diag = P.sample_diagnostics(model)
282
306
  diag = diag.drop(columns=[c for c in diag.columns if c == "stratum" or (
@@ -1,10 +1,16 @@
1
+ import matplotlib
2
+
3
+ matplotlib.use("Agg")
4
+ import matplotlib.pyplot as plt
1
5
  import numpy as np
2
6
  import pytest
3
7
  import xarray as xr
8
+ from test_parafac import synthetic
4
9
 
5
- from eemkit import SettingsError
10
+ from eemkit import SettingsError, pipeline, plot
6
11
  from eemkit import parafac as P
7
12
  from eemkit.parafac.channels import _trapz
13
+ from eemkit.report import write_report
8
14
 
9
15
  EX = np.arange(240.0, 451.0, 10.0)
10
16
  EM = np.arange(250.0, 601.0, 5.0)
@@ -169,3 +175,106 @@ def test_works_on_a_fitted_model():
169
175
  data = [_trapz(ds["intensity"].sel(sample=s, ex=280.0).values[band], EM[band])
170
176
  for s in fit["sample"].values]
171
177
  np.testing.assert_allclose(out["total"].sel(channel="T"), data, rtol=0.05)
178
+
179
+
180
+ # --------------------------------------------------------------------------- #
181
+ # Settings, tables, figure, export and report
182
+ # --------------------------------------------------------------------------- #
183
+
184
+ def _settings():
185
+ s = pipeline.default_settings()
186
+ s["channels"] = {"T": {"ex": 280.0, "em": [330.0, 370.0]},
187
+ "H": {"ex": 330.0, "em": [420.0, 470.0]}}
188
+ return s
189
+
190
+
191
+ @pytest.fixture(scope="module")
192
+ def fitted():
193
+ ds, *_ = synthetic(n=24)
194
+ return ds, P.fit_parafac(ds, 3, n_init=2, max_iter=1500)
195
+
196
+
197
+ @pytest.fixture(autouse=True)
198
+ def _close():
199
+ yield
200
+ plt.close("all")
201
+
202
+
203
+ def test_channels_round_trip_through_the_settings_file(tmp_path):
204
+ s = _settings()
205
+ path = pipeline.save_settings(s, tmp_path / "s.toml")
206
+ assert "[channels.T]" in path.read_text(encoding="utf-8")
207
+ assert pipeline.load_settings(path) == s
208
+ assert pipeline.default_settings()["channels"] == {}
209
+ assert pipeline.channel_signals(make_model(), pipeline.default_settings()) is None
210
+
211
+
212
+ @pytest.mark.parametrize("channels, match", [
213
+ ({"a b": {"ex": 280, "em": [330, 370]}}, "letters, digits"),
214
+ ({"T": {"ex": 280}}, "needs ex"),
215
+ ({"T": {"ex": "x", "em": [330, 370]}}, "needs ex"),
216
+ ({"T": {"ex": 280, "em": [370, 330]}}, "is empty"),
217
+ ])
218
+ def test_channel_settings_are_checked(channels, match):
219
+ with pytest.raises(SettingsError, match=match):
220
+ pipeline.channel_specs({"channels": channels})
221
+
222
+
223
+ def test_channel_signals_from_settings_and_tables():
224
+ m = make_model()
225
+ sig = pipeline.channel_signals(m, _settings())
226
+ assert list(sig["channel"].values) == ["T", "H"]
227
+ direct = P.component_signals(m, {"T": {"ex": 280.0, "em": (330.0, 370.0)},
228
+ "H": {"ex": 330.0, "em": (420.0, 470.0)}})
229
+ np.testing.assert_allclose(sig["signal"], direct["signal"])
230
+ long, sens = pipeline.channel_tables(sig)
231
+ assert list(long.columns) == ["sample", "channel", "component", "signal", "share"]
232
+ assert len(long) == 6 * 2 * 3 and set(long["component"]) == {"C1", "C2", "C3"}
233
+ assert list(sens.columns) == ["C1", "C2", "C3"] and list(sens.index) == ["T", "H"]
234
+
235
+
236
+ def test_channel_positions_are_kept_for_the_figures():
237
+ sig = P.component_signals(make_model(), {"T": {"ex": 280.0, "em": (330.0, 370.0)},
238
+ "W": {"ex": (260.0, 300.0), "em": (380.0, 440.0)}})
239
+ assert list(sig["ex_min"]) == [280.0, 260.0] and list(sig["ex_max"]) == [280.0, 300.0]
240
+ assert list(sig["em_min"]) == [330.0, 380.0] and list(sig["em_max"]) == [370.0, 440.0]
241
+
242
+
243
+ def test_channel_figure_with_and_without_the_model():
244
+ m = make_model()
245
+ sig = pipeline.channel_signals(m, _settings())
246
+ fig = plot.channel_signals(sig, m)
247
+ bars = [a for a in fig.axes if a.get_xlabel().startswith("Share")]
248
+ assert len(bars) == 1 and len(bars[0].patches) == 2 * 3 # channels x components
249
+ assert [t.get_text() for t in fig.legends[0].get_texts()] == ["C1", "C2", "C3"]
250
+ # the first-listed channel (T) has the highest position, i.e. is drawn at the top
251
+ assert [t.get_text() for t in bars[0].get_yticklabels()] == ["T", "H"]
252
+ assert list(bars[0].get_yticks()) == [1.0, 0.0]
253
+ assert fig.axes[0].get_title(loc="left") == "Where the channels sit"
254
+ alone = plot.channel_signals(sig, names=["a", "b", "c"])
255
+ assert len(alone.axes) == 1 and alone.legends[0].get_texts()[0].get_text() == "a"
256
+
257
+
258
+ def test_export_writes_the_channel_files(fitted, tmp_path):
259
+ ds, model = fitted
260
+ s = _settings()
261
+ paths = pipeline.export_results(tmp_path, s, model=model)
262
+ names = {p.name for p in paths}
263
+ assert {"parafac_3comp_channels.csv", "parafac_3comp_channel_sensitivity.csv",
264
+ "channel_signals.pdf", "channel_signals.png"} <= names
265
+ import pandas as pd
266
+ long = pd.read_csv(tmp_path / "parafac_3comp_channels.csv")
267
+ assert len(long) == 24 * 2 * 3
268
+ assert '"channels"' in (tmp_path / "processing_record.json").read_text(encoding="utf-8")
269
+ # no channels: no channel files
270
+ none = pipeline.export_results(tmp_path / "none", pipeline.default_settings(), model=model)
271
+ assert not [p for p in none if "channel" in p.name]
272
+
273
+
274
+ def test_report_has_a_channel_section_only_when_channels_are_set(fitted, tmp_path):
275
+ ds, model = fitted
276
+ text = write_report(tmp_path / "a.html", _settings(), model=model).read_text("utf-8")
277
+ assert 'id="channels"' in text and "Sensor channels" in text and "280" in text
278
+ text = write_report(tmp_path / "b.html", pipeline.default_settings(),
279
+ model=model).read_text("utf-8")
280
+ assert 'id="channels"' not in text
@@ -110,13 +110,30 @@ def test_full_workflow(qtbot, window, dialogs, tmp_path):
110
110
  _idle(qtbot, w)
111
111
  assert p.model.sizes["component"] == 2 and "Split-half" in t.final_text.text()
112
112
 
113
+ # sensor channels: an LED and filter channel on the final and the exploratory models
114
+ assert t.ch_model.count() == 3 # final model + two exploratory ranks
115
+ t.add_channel()
116
+ assert p.settings["channels"] == {"Ch1": {"ex": 280.0, "em": [330.0, 370.0]}}
117
+ assert t.ch_plot.figure is not None and t.ch_shares_model.rowCount() == 1
118
+ t.ch_table.item(0, 1).setText("999") # an LED outside the model: refused, said so
119
+ assert "outside" in t.ch_status.text() and t.ch_shares_model.rowCount() == 0
120
+ t.ch_table.item(0, 1).setText("280")
121
+ assert t.ch_status.text() == "" and t.ch_shares_model.rowCount() == 1
122
+ t.ch_table.item(0, 0).setText("T")
123
+ assert list(p.settings["channels"]) == ["T"]
124
+ t.ch_table.item(0, 2).setText("abc") # not a number: kept out of the settings
125
+ assert "numbers" in t.ch_status.text() and p.settings["channels"]["T"]["em"] == [330.0, 370.0]
126
+ t.ch_table.item(0, 2).setText("330")
127
+ assert t.ch_status.text() == ""
128
+
113
129
  # 5 export
114
130
  w.export_tab.meta["creator"].setText("Test Person")
115
131
  w.export_tab.export()
116
132
  _idle(qtbot, w)
117
133
  out = tmp_path / "results"
118
134
  for name in ("settings.toml", "processing_record.json", "indices.csv",
119
- "parafac_2comp_openfluor.txt", "figures/components.pdf"):
135
+ "parafac_2comp_openfluor.txt", "figures/components.pdf",
136
+ "parafac_2comp_channels.csv", "figures/channel_signals.pdf"):
120
137
  assert (out / name).is_file(), name
121
138
  assert "creator\tTest Person" in (out / "parafac_2comp_openfluor.txt").read_text("utf-8")
122
139
  assert not [d for d in dialogs if d[0] in ("warning", "exec")]
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