spectrochempy-iris 0.1.1__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.
@@ -0,0 +1,8 @@
1
+ Metadata-Version: 2.4
2
+ Name: spectrochempy-iris
3
+ Version: 0.1.1
4
+ Summary: IRIS analysis extension for SpectroChemPy
5
+ Requires-Python: >=3.11
6
+ Requires-Dist: spectrochempy<0.10,>=0.9.0.dev0
7
+ Requires-Dist: scipy
8
+ Requires-Dist: osqp
@@ -0,0 +1,37 @@
1
+ # spectrochempy-iris
2
+
3
+ IRIS analysis plugin for SpectroChemPy.
4
+
5
+ Provides IRIS analysis objects, batch workflows, kernel comparison helpers,
6
+ visualisation helpers, and dataset-bound accessors.
7
+
8
+ ## Installation
9
+
10
+ ```bash
11
+ pip install spectrochempy[iris]
12
+ ```
13
+
14
+ ## Usage
15
+
16
+ ```python
17
+ import spectrochempy as scp
18
+
19
+ # Package-level plugin APIs are available under scp.iris after installation.
20
+ results = scp.iris.batch_iris([dataset], kernel_type="langmuir", q=[-6, 1, 6])
21
+ report = scp.iris.iris_report(results[0]["iris"])
22
+
23
+ # Operations on an existing dataset are exposed through dataset accessors.
24
+ kernel = dataset.iris.kernel_matrix(kernel_type="langmuir", q=[-6, 1, 6])
25
+ ```
26
+
27
+ The legacy flat accessor `dataset.iris_kernel_matrix(...)` is kept for
28
+ compatibility.
29
+
30
+ ## Development
31
+
32
+ ```bash
33
+ pip install -e .
34
+ pip install -e plugins/spectrochempy-iris
35
+ cd plugins/spectrochempy-iris
36
+ python -m pytest tests/
37
+ ```
@@ -0,0 +1,26 @@
1
+ [build-system]
2
+ requires = ["setuptools>=64"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "spectrochempy-iris"
7
+ version = "0.1.1"
8
+ description = "IRIS analysis extension for SpectroChemPy"
9
+ requires-python = ">=3.11"
10
+ dependencies = [
11
+ "spectrochempy>=0.9.0.dev0,<0.10",
12
+ "scipy",
13
+ "osqp",
14
+ ]
15
+
16
+ [project.entry-points."spectrochempy.plugins"]
17
+ iris = "spectrochempy_iris:IrisPlugin"
18
+
19
+ [tool.setuptools.packages.find]
20
+ where = ["src"]
21
+
22
+ [tool.pytest.ini_options]
23
+ testpaths = ["tests"]
24
+ markers = [
25
+ "network: tests requiring network access",
26
+ ]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,451 @@
1
+ # ruff: noqa: PLC0415 — defer imports in plugin methods to avoid startup cost
2
+ """
3
+ spectrochempy-iris — IRIS analysis for SpectroChemPy.
4
+
5
+ Provides Integral Inversion for Spectroscopic data (IRIS) analysis,
6
+ including the :class:`IrisKernel` and :class:`IRIS` classes,
7
+ plus additional kernels, batch analysis, model comparison, and
8
+ extended visualisation.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from typing import TYPE_CHECKING
14
+
15
+ from spectrochempy.api.plugins import CORE_PLUGIN_API_VERSION
16
+ from spectrochempy.api.plugins import PluginCapability
17
+ from spectrochempy.api.plugins import SpectroChemPyPlugin
18
+
19
+ # ------------------------------------------------------------------
20
+ # Lazy module-level access for public API (IRIS, IrisKernel, plotting)
21
+ # ------------------------------------------------------------------
22
+
23
+
24
+ def __getattr__(name: str):
25
+ if name in ("IRIS", "IrisKernel"):
26
+ from ._core import IRIS as _IRIS # noqa: PLC0415
27
+ from ._core import IrisKernel as _IrisKernel # noqa: PLC0415
28
+
29
+ return _IRIS if name == "IRIS" else _IrisKernel
30
+
31
+ # Functions defined in _plotting.py
32
+ if name in {"plot_iris_distribution", "plot_iris_lcurve", "plot_iris_merit"}:
33
+ from ._plotting import plot_iris_distribution as _f1 # noqa: PLC0415
34
+ from ._plotting import plot_iris_lcurve as _f2 # noqa: PLC0415
35
+ from ._plotting import plot_iris_merit as _f3 # noqa: PLC0415
36
+
37
+ _mapping = {
38
+ "plot_iris_distribution": _f1,
39
+ "plot_iris_lcurve": _f2,
40
+ "plot_iris_merit": _f3,
41
+ }
42
+ return _mapping[name]
43
+
44
+ msg = f"module {__name__!r} has no attribute {name!r}"
45
+ raise AttributeError(msg)
46
+
47
+
48
+ def __dir__() -> list[str]:
49
+ return [
50
+ "IRIS",
51
+ "IrisKernel",
52
+ "IrisPlugin",
53
+ "batch_iris_analysis",
54
+ "compare_kernel_models",
55
+ "iris_analysis_report",
56
+ "plot_distribution_grid",
57
+ "plot_iris_distribution",
58
+ "plot_iris_lcurve",
59
+ "plot_iris_merit",
60
+ "plot_kernel_comparison",
61
+ ]
62
+
63
+
64
+ if TYPE_CHECKING:
65
+ from spectrochempy import NDDataset
66
+
67
+
68
+ # ------------------------------------------------------------------
69
+ # Plugin class
70
+ # ------------------------------------------------------------------
71
+
72
+
73
+ class IrisPlugin(SpectroChemPyPlugin):
74
+ """
75
+ Extended IRIS analysis plugin for SpectroChemPy.
76
+
77
+ Adds custom kernels, batch processing, model comparison, and
78
+ extended visualisation on top of the core IRIS class.
79
+ """
80
+
81
+ name = "iris"
82
+ version = "0.1.0"
83
+ description = "Extended IRIS analysis: custom kernels, batch analysis, model comparison, enhanced plots"
84
+ spectrochempy_min_version = "0.9.0.dev0"
85
+ PLUGIN_API_VERSION = CORE_PLUGIN_API_VERSION
86
+ capabilities = [
87
+ PluginCapability.ANALYSIS,
88
+ PluginCapability.VISUALIZER,
89
+ PluginCapability.ACCESSOR,
90
+ ]
91
+ root_exports = {
92
+ "IRIS": {
93
+ "target": "IRIS",
94
+ "deprecated": True,
95
+ "replacement": "scp.iris.IRIS",
96
+ },
97
+ "IrisKernel": {
98
+ "target": "IrisKernel",
99
+ "deprecated": True,
100
+ "replacement": "scp.iris.IrisKernel",
101
+ },
102
+ "batch_iris": {
103
+ "target": "batch_iris",
104
+ "deprecated": True,
105
+ "replacement": "scp.iris.batch_iris",
106
+ },
107
+ "compare_kernels": {
108
+ "target": "compare_kernels",
109
+ "deprecated": True,
110
+ "replacement": "scp.iris.compare_kernels",
111
+ },
112
+ "iris_report": {
113
+ "target": "iris_report",
114
+ "deprecated": True,
115
+ "replacement": "scp.iris.iris_report",
116
+ },
117
+ }
118
+
119
+ def register_analyses(self) -> list[dict]:
120
+ """Declare analysis workflows extending core IRIS."""
121
+ return [
122
+ {
123
+ "name": "batch_iris",
124
+ "func": batch_iris_analysis,
125
+ "description": "Run IRIS analysis on multiple datasets or conditions",
126
+ },
127
+ {
128
+ "name": "compare_kernels",
129
+ "func": compare_kernel_models,
130
+ "description": "Compare multiple IRIS kernel models on the same data",
131
+ },
132
+ {
133
+ "name": "iris_report",
134
+ "func": iris_analysis_report,
135
+ "description": "Generate a summary report of an IRIS analysis",
136
+ },
137
+ ]
138
+
139
+ def register_visualizers(self) -> list[dict]:
140
+ """Declare extended IRIS visualisation functions."""
141
+ return [
142
+ {
143
+ "name": "plot_iris_comparison",
144
+ "func": plot_kernel_comparison,
145
+ "description": "Side-by-side comparison of multiple kernel fits",
146
+ },
147
+ {
148
+ "name": "plot_iris_distribution_grid",
149
+ "func": plot_distribution_grid,
150
+ "description": "Grid of distribution functions across lambdas and conditions",
151
+ },
152
+ ]
153
+
154
+ def register_accessors(self) -> list[dict]:
155
+ """Declare dataset accessor methods for IRIS."""
156
+ return [
157
+ {
158
+ "namespace": "iris",
159
+ "name": "kernel_matrix",
160
+ "legacy_names": ["iris_kernel_matrix"],
161
+ "func": _ndd_build_kernel,
162
+ "description": "Build an IrisKernel from the dataset",
163
+ },
164
+ ]
165
+
166
+
167
+ # ------------------------------------------------------------------
168
+ # Helper / kernel functions (deferred imports internally)
169
+ # ------------------------------------------------------------------
170
+
171
+
172
+ def _kernel_freundlich(p, q):
173
+ """Freundlich isotherm kernel: K = p^b (with b = exp(q))."""
174
+ import numpy as np # noqa: PLC0415
175
+
176
+ b = np.exp(q)
177
+ return p[:, np.newaxis] ** b[np.newaxis, :]
178
+
179
+
180
+ def _kernel_temkin(p, q):
181
+ """Temkin isotherm kernel: K = -exp(q) * ln(p)."""
182
+ import numpy as np # noqa: PLC0415
183
+
184
+ a = -np.exp(q)
185
+ kernel_data = a[np.newaxis, :] * np.log(p[:, np.newaxis])
186
+ return np.maximum(kernel_data, 0.0)
187
+
188
+
189
+ def _kernel_linear(p, q):
190
+ """Linear interaction kernel: K = p * q."""
191
+ import numpy as np # noqa: PLC0415
192
+
193
+ return p[:, np.newaxis] * q[np.newaxis, :]
194
+
195
+
196
+ def _ndd_build_kernel(
197
+ self: NDDataset,
198
+ kernel_type: str = "langmuir",
199
+ q: list | None = None,
200
+ ) -> object:
201
+ from ._core import IrisKernel as _IrisKernel # noqa: PLC0415
202
+
203
+ extra_kernels = {
204
+ "freundlich": _kernel_freundlich,
205
+ "temkin": _kernel_temkin,
206
+ "linear": _kernel_linear,
207
+ }
208
+ selected_kernel = extra_kernels.get(kernel_type, kernel_type)
209
+ return _IrisKernel(self, selected_kernel, q=q)
210
+
211
+
212
+ def batch_iris_analysis(
213
+ datasets: list[NDDataset] | dict[str, NDDataset],
214
+ kernel_type: str = "langmuir",
215
+ q: list | None = None,
216
+ reg_par: list | None = None,
217
+ ) -> list[dict]:
218
+ """
219
+ Run IRIS analysis on multiple datasets or conditions.
220
+
221
+ Parameters
222
+ ----------
223
+ datasets : list[NDDataset] or dict[str, NDDataset]
224
+ Datasets to analyse. If a dict, keys are used as condition labels.
225
+ kernel_type : str, optional
226
+ Kernel type name or callable. Default is ``"langmuir"``.
227
+ q : list, optional
228
+ Internal variable parameter vector or ``[start, stop, num]``.
229
+ reg_par : list, optional
230
+ Regularisation parameters (``[min, max]`` or ``[start, stop, num]``).
231
+
232
+ Returns
233
+ -------
234
+ list[dict]
235
+ Each dict contains ``label``, ``iris``, ``f``, ``RSS``, ``SM``.
236
+ """
237
+ from ._core import IRIS as _IRIS # noqa: PLC0415
238
+ from ._core import IrisKernel as _IrisKernel # noqa: PLC0415
239
+
240
+ extra_kernels = {
241
+ "freundlich": _kernel_freundlich,
242
+ "temkin": _kernel_temkin,
243
+ "linear": _kernel_linear,
244
+ }
245
+
246
+ if isinstance(datasets, dict):
247
+ items = list(datasets.items())
248
+ else:
249
+ items = [(f"dataset_{i}", ds) for i, ds in enumerate(datasets)]
250
+
251
+ results = []
252
+ for label, ds in items:
253
+ kernel_fn = extra_kernels.get(kernel_type, kernel_type)
254
+ kernel = _IrisKernel(ds, kernel_fn, q=q)
255
+ iris = _IRIS(reg_par=reg_par)
256
+ iris.fit(ds, kernel)
257
+
258
+ results.append(
259
+ {
260
+ "label": label,
261
+ "iris": iris,
262
+ "f": iris.f,
263
+ "RSS": iris.RSS,
264
+ "SM": iris.SM,
265
+ }
266
+ )
267
+
268
+ return results
269
+
270
+
271
+ def compare_kernel_models(
272
+ dataset: NDDataset,
273
+ kernels: list[str] | None = None,
274
+ q: list | None = None,
275
+ reg_par: list | None = None,
276
+ ) -> list[dict]:
277
+ """
278
+ Compare multiple IRIS kernel models on the same dataset.
279
+
280
+ Parameters
281
+ ----------
282
+ dataset : NDDataset
283
+ Dataset to fit.
284
+ kernels : list[str], optional
285
+ Kernel names to compare. Defaults to ``["langmuir", "ca", "freundlich"]``.
286
+ q : list, optional
287
+ Internal variable parameter vector or ``[start, stop, num]``.
288
+ reg_par : list, optional
289
+ Regularisation parameters (``[min, max]`` or ``[start, stop, num]``).
290
+
291
+ Returns
292
+ -------
293
+ list[dict]
294
+ Each dict contains ``kernel``, ``iris``, ``RSS``, ``SM``, ``n_components``.
295
+ """
296
+ from ._core import IRIS as _IRIS # noqa: PLC0415
297
+ from ._core import IrisKernel as _IrisKernel # noqa: PLC0415
298
+
299
+ extra_kernels = {
300
+ "freundlich": _kernel_freundlich,
301
+ "temkin": _kernel_temkin,
302
+ "linear": _kernel_linear,
303
+ }
304
+
305
+ if kernels is None:
306
+ kernels = ["langmuir", "ca", "freundlich"]
307
+
308
+ results = []
309
+ for name in kernels:
310
+ kernel_fn = extra_kernels.get(name, name)
311
+ kernel = _IrisKernel(dataset, kernel_fn, q=q)
312
+ iris = _IRIS(reg_par=reg_par)
313
+ iris.fit(dataset, kernel)
314
+
315
+ results.append(
316
+ {
317
+ "kernel": name,
318
+ "iris": iris,
319
+ "RSS": iris.RSS,
320
+ "SM": iris.SM,
321
+ "n_components": iris.f.shape[0],
322
+ }
323
+ )
324
+
325
+ return results
326
+
327
+
328
+ def iris_analysis_report(iris_object: object) -> dict:
329
+ """
330
+ Generate a summary report of an IRIS analysis.
331
+
332
+ Parameters
333
+ ----------
334
+ iris_object : IRIS
335
+ A fitted IRIS object.
336
+
337
+ Returns
338
+ -------
339
+ dict
340
+ Report containing ``kernel_type``, ``n_lambdas``, ``lambda_values``,
341
+ ``RSS_range``, ``SM_range``, ``q_range``, ``n_channels``.
342
+ """
343
+ import numpy as np # noqa: PLC0415
344
+
345
+ return {
346
+ "kernel_type": str(type(iris_object.K).__name__),
347
+ "n_lambdas": len(iris_object.lambdas),
348
+ "lambda_values": iris_object.lambdas.data,
349
+ "RSS_range": (float(np.min(iris_object.RSS)), float(np.max(iris_object.RSS))),
350
+ "SM_range": (float(np.min(iris_object.SM)), float(np.max(iris_object.SM))),
351
+ "q_range": (float(iris_object.q.data[0]), float(iris_object.q.data[-1])),
352
+ "n_channels": iris_object.f.shape[-1],
353
+ }
354
+
355
+
356
+ def plot_kernel_comparison(
357
+ comparison_results: list[dict],
358
+ **kwargs,
359
+ ) -> tuple:
360
+ """
361
+ Plot a side-by-side comparison of multiple kernel fits.
362
+
363
+ Parameters
364
+ ----------
365
+ comparison_results : list[dict]
366
+ Output from :func:`compare_kernel_models`.
367
+ **kwargs
368
+ Additional keyword arguments (reserved for future use).
369
+
370
+ Returns
371
+ -------
372
+ tuple of (matplotlib.figure.Figure, numpy.ndarray of Axes)
373
+ The figure and axes array.
374
+ """
375
+ import matplotlib.pyplot as plt # noqa: PLC0415
376
+ import numpy as np # noqa: PLC0415
377
+
378
+ n = len(comparison_results)
379
+ fig, axes = plt.subplots(1, n, figsize=(5 * n, 4), squeeze=False)
380
+ axes = axes[0]
381
+
382
+ for i, result in enumerate(comparison_results):
383
+ f = result["iris"].f
384
+ if f is not None and f.data.ndim >= 2:
385
+ dist = f[0].squeeze().data
386
+ if dist.ndim == 1:
387
+ axes[i].plot(f[0].y.data, dist)
388
+ elif dist.ndim >= 2:
389
+ axes[i].plot(f[0].y.data, dist[:, 0])
390
+ axes[i].set_title(f"Kernel: {result['kernel']}")
391
+ axes[i].set_xlabel("q")
392
+ axes[i].set_ylabel("f(q)")
393
+ rss = float(np.mean(result["RSS"]))
394
+ axes[i].text(
395
+ 0.05,
396
+ 0.95,
397
+ f"RSS={rss:.2e}",
398
+ transform=axes[i].transAxes,
399
+ va="top",
400
+ fontsize=8,
401
+ )
402
+
403
+ fig.tight_layout()
404
+ return fig, axes
405
+
406
+
407
+ def plot_distribution_grid(
408
+ batch_results: list[dict],
409
+ **kwargs,
410
+ ) -> tuple:
411
+ """
412
+ Plot a grid of distribution functions across conditions and lambdas.
413
+
414
+ Parameters
415
+ ----------
416
+ batch_results : list[dict]
417
+ Output from :func:`batch_iris_analysis`.
418
+ **kwargs
419
+ Additional keyword arguments (reserved for future use).
420
+
421
+ Returns
422
+ -------
423
+ tuple of (matplotlib.figure.Figure, numpy.ndarray of Axes)
424
+ The figure and axes array.
425
+ """
426
+ import matplotlib.pyplot as plt # noqa: PLC0415
427
+
428
+ n_conditions = len(batch_results)
429
+ fig, axes = plt.subplots(
430
+ n_conditions, 1, figsize=(8, 3 * n_conditions), squeeze=False
431
+ )
432
+
433
+ for i, result in enumerate(batch_results):
434
+ ax = axes[i, 0]
435
+ f = result["iris"].f
436
+ lambdas = result["iris"].lambdas.data
437
+ for j in range(min(len(lambdas), 5)):
438
+ dist = f[j].squeeze().data
439
+ if dist.ndim >= 1:
440
+ ax.plot(
441
+ result["iris"].q.data,
442
+ dist[:, 0] if dist.ndim > 1 else dist,
443
+ label=rf"$\lambda$={lambdas[j]:.2e}",
444
+ )
445
+ ax.set_title(f"Condition: {result['label']}")
446
+ ax.set_xlabel("q")
447
+ ax.set_ylabel("f(q)")
448
+ ax.legend(fontsize=7)
449
+
450
+ fig.tight_layout()
451
+ return fig, axes