pyperspec 0.7.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pyperspec-0.7.1.dist-info/METADATA +133 -0
- pyperspec-0.7.1.dist-info/RECORD +14 -0
- pyperspec-0.7.1.dist-info/WHEEL +4 -0
- pyperspec-0.7.1.dist-info/licenses/LICENSE +21 -0
- pyspc/__init__.py +5 -0
- pyspc/_plotting_breaks.py +305 -0
- pyspc/baselines.py +28 -0
- pyspc/concatenation.py +80 -0
- pyspc/peaks.py +284 -0
- pyspc/plotting.py +1014 -0
- pyspc/spectra.py +2376 -0
- pyspc/spikes.py +160 -0
- pyspc/testing.py +10 -0
- pyspc/utils.py +38 -0
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: pyperspec
|
|
3
|
+
Version: 0.7.1
|
|
4
|
+
Summary: Tools for Spectroscopy
|
|
5
|
+
Keywords: spectroscopy,Raman,IR,signal,processing
|
|
6
|
+
Author: Rustam Guliev
|
|
7
|
+
Author-email: Rustam Guliev <glvrst@gmail.com>
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Requires-Dist: pandas>=2.1.1,<3.0.0
|
|
11
|
+
Requires-Dist: matplotlib>=3.8.0
|
|
12
|
+
Requires-Dist: scipy>=1.11.2
|
|
13
|
+
Requires-Dist: pybaselines>=1.1.0
|
|
14
|
+
Requires-Dist: einops>=0.6.0 ; extra == 'all'
|
|
15
|
+
Requires-Dist: einops>=0.6.0 ; extra == 'einops'
|
|
16
|
+
Requires-Python: >=3.12
|
|
17
|
+
Project-URL: Homepage, https://github.com/r-hyperspec/pyperspec
|
|
18
|
+
Project-URL: Documentation, https://r-hyperspec.github.io/pyperspec/
|
|
19
|
+
Project-URL: Repository, https://github.com/r-hyperspec/pyperspec
|
|
20
|
+
Project-URL: Issues, https://github.com/r-hyperspec/pyperspec/issues
|
|
21
|
+
Provides-Extra: all
|
|
22
|
+
Provides-Extra: einops
|
|
23
|
+
Description-Content-Type: text/markdown
|
|
24
|
+
|
|
25
|
+
[](https://codecov.io/gh/r-hyperspec/pyperspec)
|
|
26
|
+
[](https://github.com/r-hyperspec/pyperspec/blob/main/LICENSE)
|
|
27
|
+
|
|
28
|
+
# Python Package pyperspec
|
|
29
|
+
|
|
30
|
+
This is a Python package designed to simplify the analysis and manipulation of hyperspectral datasets.
|
|
31
|
+
The package provides an object-oriented approach providing a user-friendly interface that feels familiar to Python users, i.e. close to libraries such as `numpy`, `pandas`, and `scikit-learn`.
|
|
32
|
+
|
|
33
|
+
This is heavily inspired by R package [hyperSpec](https://github.com/r-hyperspec/hyperSpec) and part of **`r-hyperspec`**.
|
|
34
|
+
The goal is to make the work with hyperspectral data sets, (i.e. spatially or time-resolved spectra, or spectra with any other kind of information associated with each of the spectra) more comfortable.
|
|
35
|
+
The spectra can be data obtained during
|
|
36
|
+
[XRF](https://en.wikipedia.org/wiki/X-ray_fluorescence),
|
|
37
|
+
[UV/VIS](https://en.wikipedia.org/wiki/Ultraviolet%E2%80%93visible_spectroscopy),
|
|
38
|
+
[Fluorescence](https://en.wikipedia.org/wiki/Fluorescence_spectroscopy),
|
|
39
|
+
[AES](https://en.wikipedia.org/wiki/Auger_electron_spectroscopy),
|
|
40
|
+
[NIR](https://en.wikipedia.org/wiki/Near-infrared_spectroscopy),
|
|
41
|
+
[IR](https://en.wikipedia.org/wiki/Infrared_spectroscopy),
|
|
42
|
+
[Raman](https://en.wikipedia.org/wiki/Raman_spectroscopy),
|
|
43
|
+
[NMR](https://en.wikipedia.org/wiki/Nuclear_magnetic_resonance_spectroscopy),
|
|
44
|
+
[MS](https://en.wikipedia.org/wiki/Mass_spectrometry),
|
|
45
|
+
etc. spectroscopy measurements.
|
|
46
|
+
|
|
47
|
+
**NOTE:** The main focus is **not** on algroithms since there are already many other good packages implementing algorithms, e.g.
|
|
48
|
+
[numpy](https://numpy.org/),
|
|
49
|
+
[scipy](https://scipy.org/),
|
|
50
|
+
[pybaselines](https://github.com/derb12/pybaselines),
|
|
51
|
+
and more can be found in [FOSS For Spectroscopy](https://bryanhanson.github.io/FOSS4Spectroscopy/) list.
|
|
52
|
+
|
|
53
|
+
Rather, it provides convinient interface for those algorithms and other routine tasks.
|
|
54
|
+
|
|
55
|
+
For detailed information and documentation, please visit [Documentation](https://r-hyperspec.github.io/pyperspec/).
|
|
56
|
+
|
|
57
|
+
## Documentation
|
|
58
|
+
|
|
59
|
+
Please, check [here](https://r-hyperspec.github.io/pyperspec/)
|
|
60
|
+
|
|
61
|
+
## Installation
|
|
62
|
+
|
|
63
|
+
Requires Python 3.12 or newer. Install from PyPI:
|
|
64
|
+
|
|
65
|
+
```bash
|
|
66
|
+
pip install pyperspec
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
Or add it to a uv project:
|
|
70
|
+
|
|
71
|
+
```bash
|
|
72
|
+
uv add pyperspec
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
The Python import name is `pyspc`.
|
|
76
|
+
|
|
77
|
+
## Quick Demo
|
|
78
|
+
|
|
79
|
+
```python
|
|
80
|
+
import pyspc
|
|
81
|
+
import numpy as np
|
|
82
|
+
import pandas as pd
|
|
83
|
+
|
|
84
|
+
spc = np.random.rand(10, 20) # Here are your spectra in unfolded structure
|
|
85
|
+
wl = np.linspace(1000,2000,20) # Array of wavelength/wavenumbers
|
|
86
|
+
meta_data = pd.DataFrame({"group": ["A", "B"] * 5, "date": pd.date_range("2023-01-01", periods=10)}) # Additional meta-data
|
|
87
|
+
|
|
88
|
+
# Create the object
|
|
89
|
+
sf = pyspc.SpectraFrame(spc, wl=wl, data=meta_data)
|
|
90
|
+
|
|
91
|
+
# Easy meta-data manipulation
|
|
92
|
+
sf.A
|
|
93
|
+
sf["A"]
|
|
94
|
+
sf["group"] = ["Control", "Treatment"] * 5
|
|
95
|
+
|
|
96
|
+
# Easy data slicing/filtering, similar to hyperSpec
|
|
97
|
+
sf[:,:,500:1000] # Cut wavelength range to [500, 1000]
|
|
98
|
+
sf[:5,:,:5, True] # Use iloc style to get only first five spectra and first five wavenumbers
|
|
99
|
+
sf.query("group == 'Control'") # Get only 'Control' group
|
|
100
|
+
|
|
101
|
+
# Simple aggregation even with custom methods
|
|
102
|
+
sf[:,:,500:1000].mean(groupby=["group", "date"])
|
|
103
|
+
sf.query("group == 'Control'").apply(lambda x: np.sum(x**2), axis=0)
|
|
104
|
+
|
|
105
|
+
# Chaining methods
|
|
106
|
+
sf_processed = (
|
|
107
|
+
sf.query("group == 'Control'")
|
|
108
|
+
.mean(groupby="date")
|
|
109
|
+
.smooth("savgol", window_length=7, polyorder=2)
|
|
110
|
+
.sbaseline("rubberband")
|
|
111
|
+
.normalize("area")
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
# Select 3 random spectra and plot them colored by "date"
|
|
115
|
+
sf.sample(3).plot(colors="date")
|
|
116
|
+
|
|
117
|
+
# Export to wide pandas DataFrame
|
|
118
|
+
sf.to_pandas()
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
## Acknowlegments
|
|
122
|
+
|
|
123
|
+
* This project was a continuation of [ibcp/pyspectra](https://github.com/ibcp/pyspectra). We acknowlege support and contribution of [Emanuel Institute of Biochemical Physics, RAS](https://biochemphysics.ru/)
|
|
124
|
+
* This project has received funding from the European Union’s [Horizon 2020](https://research-and-innovation.ec.europa.eu/funding/funding-opportunities/funding-programmes-and-open-calls/horizon-2020_en) research and innovation programme under the [Marie Sklodowska-Curie Actions](https://marie-sklodowska-curie-actions.ec.europa.eu/) *(Grant Agreement 861122)* as part of [IMAGE-IN](https://image-in-itn.eu/) project.
|
|
125
|
+
* The project was developed as part of secondment at [Chemometrix GmbH](https://chemometrix.gmbh/)
|
|
126
|
+
* Supervision was from [Chemometrix GmbH](https://chemometrix.gmbh/), [Leibniz-IPHT](https://www.leibniz-ipht.de/en/), and [BMD Software](https://www.bmd-software.com/)
|
|
127
|
+
|
|
128
|
+
<img src="https://biochemphysics.ru/static/img/logo_en.png" alt="Emanuel Institute of Biochemical Physics, RAS" style="height: 100px; margin: 10px"/>
|
|
129
|
+
<img src="https://bgsmath.cat/wp-content/uploads/2017/09/marie_curie1-300x160.jpg" alt="Horizon 2020" style="height: 100px; margin: 10px"/>
|
|
130
|
+
<img src="img/logo_imagein.png" alt="IMAGE-IN" style="height: 100px; margin: 10px"/>
|
|
131
|
+
<img src="https://chemometrix.gmbh/assets/images/chemometrix-logo.png" alt="Chemometrix GmbH" style="height: 80px; margin: 10px">
|
|
132
|
+
<img src="https://image-in-itn.eu/wp-content/uploads/2020/09/IPHTLogo_neu_rgb_01_de.png" alt="Leibniz-IPHT" style="height: 100px; margin: 10px">
|
|
133
|
+
<img src="https://image-in-itn.eu/wp-content/uploads/2020/09/bmd-1024x213.png" alt="BMD Software" style="height: 80px; width: 250px; margin: 10px">
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
pyspc/__init__.py,sha256=-FiND3h9w4-_wMA4MraTGMaRRAZ9DAWcDoRFzOTqXro,151
|
|
2
|
+
pyspc/_plotting_breaks.py,sha256=bKaiwLPXFlp7jr88Dft-9iX6YaCgQMNyW7hLW5laUFs,13312
|
|
3
|
+
pyspc/baselines.py,sha256=bENRECxI-kEfEM7fqBJ2CCYXD40dT4tKFQMaUFrU-84,684
|
|
4
|
+
pyspc/concatenation.py,sha256=hny8jay0ujbNRSvjy64BJTYvNTaoWOrff7xOpqK18lk,2843
|
|
5
|
+
pyspc/peaks.py,sha256=n7JRE3TP1EcqS2tsLplMA8qKSGSMLKI4aJBro4RKZbk,8976
|
|
6
|
+
pyspc/plotting.py,sha256=zz4gfUDKvrHY4UkLhWY3oazwWtfErU68xXqE12KfLLE,43335
|
|
7
|
+
pyspc/spectra.py,sha256=UVVBlel7v0AX5Val27t2-2TGAKDbMxjDCuf3k6QfHSo,87774
|
|
8
|
+
pyspc/spikes.py,sha256=hl0Eqgof4isnLq5glhPuPOYy1Mwk6uHMKGtM62BNwlM,5329
|
|
9
|
+
pyspc/testing.py,sha256=m0tSLaYMeJFNmmHt7eibWHsPDEmAKQjQ3QHaQk38qp4,298
|
|
10
|
+
pyspc/utils.py,sha256=EOWA63iCTPeIOlMvysqax1l3a9WpgSECwu_Ccer_VT8,1031
|
|
11
|
+
pyperspec-0.7.1.dist-info/licenses/LICENSE,sha256=hJxf38xyIlhrdQssaZtNWPXIO_LySESYXLU-p68b-LQ,1068
|
|
12
|
+
pyperspec-0.7.1.dist-info/WHEEL,sha256=uOqnPWqgFlbov4NeTCercq7cBQ2UN7xh5fiW55lOnAg,81
|
|
13
|
+
pyperspec-0.7.1.dist-info/METADATA,sha256=cQXCuTpKXP8HFY2DlC11vznsA5ZPYuf4u9CcnfsIyk0,6277
|
|
14
|
+
pyperspec-0.7.1.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2023 R hyperSpec
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
pyspc/__init__.py
ADDED
|
@@ -0,0 +1,305 @@
|
|
|
1
|
+
"""Post-process linear Matplotlib axes to omit x-coordinate intervals."""
|
|
2
|
+
|
|
3
|
+
from numbers import Real
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
from matplotlib.axes import Axes
|
|
7
|
+
from matplotlib.collections import PolyCollection
|
|
8
|
+
from matplotlib.path import Path
|
|
9
|
+
from matplotlib.scale import FuncScale
|
|
10
|
+
from matplotlib.ticker import FixedLocator, MaxNLocator, MultipleLocator, NullLocator
|
|
11
|
+
from matplotlib.transforms import IdentityTransform, Transform
|
|
12
|
+
from numpy.typing import ArrayLike
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _validate_spacing(value: float | None, name: str) -> float | None:
|
|
16
|
+
"""Accept a positive, finite data-coordinate spacing or None."""
|
|
17
|
+
if value is None:
|
|
18
|
+
return None
|
|
19
|
+
if isinstance(value, bool) or not isinstance(value, Real):
|
|
20
|
+
raise TypeError(f"{name} must be a positive finite number.")
|
|
21
|
+
try:
|
|
22
|
+
spacing = float(value)
|
|
23
|
+
except OverflowError as error:
|
|
24
|
+
raise ValueError(f"{name} must be a positive finite number.") from error
|
|
25
|
+
if not np.isfinite(spacing) or spacing <= 0:
|
|
26
|
+
raise ValueError(f"{name} must be a positive finite number.")
|
|
27
|
+
return spacing
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _set_xtick_spacing(ax: Axes, major: float | None, minor: float | None) -> None:
|
|
31
|
+
"""Configure requested intervals without changing an unbroken axis's scale."""
|
|
32
|
+
if major is not None:
|
|
33
|
+
ax.xaxis.set_major_locator(MultipleLocator(major))
|
|
34
|
+
if minor is not None:
|
|
35
|
+
ax.xaxis.set_minor_locator(MultipleLocator(minor))
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _validate_x_breaks(x_breaks: ArrayLike, *, ax: Axes | None = None) -> np.ndarray:
|
|
39
|
+
"""Normalize intervals and check an optional target without changing it."""
|
|
40
|
+
intervals = np.asarray(x_breaks)
|
|
41
|
+
if intervals.ndim == 1 and intervals.size == 0:
|
|
42
|
+
intervals = intervals.reshape(0, 2)
|
|
43
|
+
if intervals.ndim != 2 or intervals.shape[1] != 2:
|
|
44
|
+
raise ValueError("x_breaks must have shape (n_breaks, 2).")
|
|
45
|
+
if intervals.dtype.kind not in "iuf":
|
|
46
|
+
raise TypeError("x_breaks must contain real numeric values.")
|
|
47
|
+
if not np.isfinite(intervals).all():
|
|
48
|
+
raise ValueError("x_breaks must contain finite values.")
|
|
49
|
+
if np.any(intervals[:, 0] >= intervals[:, 1]):
|
|
50
|
+
raise ValueError("Each x_breaks interval must have lower < upper.")
|
|
51
|
+
intervals = intervals[np.argsort(intervals[:, 0])].astype(float)
|
|
52
|
+
if np.any(intervals[1:, 0] <= intervals[:-1, 1]):
|
|
53
|
+
raise ValueError("x_breaks intervals must not overlap or touch.")
|
|
54
|
+
if len(intervals) and ax is not None:
|
|
55
|
+
if not isinstance(ax, Axes):
|
|
56
|
+
raise TypeError("ax must be a matplotlib Axes.")
|
|
57
|
+
if ax.get_xscale() not in ("linear", _XBreakScale.name):
|
|
58
|
+
raise ValueError("break_xaxis requires a linear x axis.")
|
|
59
|
+
return intervals
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class _XBreakScale(FuncScale):
|
|
63
|
+
"""Identify our function scale when decorating shared axes or reapplying."""
|
|
64
|
+
|
|
65
|
+
name = "pyspc_xbreak"
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class _XBreakPathTransform(Transform):
|
|
69
|
+
"""Insert boundary vertices before the nonlinear x scale transforms paths."""
|
|
70
|
+
|
|
71
|
+
input_dims = output_dims = 2
|
|
72
|
+
is_separable = True
|
|
73
|
+
has_inverse = True
|
|
74
|
+
|
|
75
|
+
def __init__(self, boundaries: np.ndarray) -> None:
|
|
76
|
+
super().__init__()
|
|
77
|
+
self.boundaries = boundaries
|
|
78
|
+
|
|
79
|
+
def transform_non_affine(self, values: np.ndarray) -> np.ndarray:
|
|
80
|
+
return values
|
|
81
|
+
|
|
82
|
+
def inverted(self) -> IdentityTransform:
|
|
83
|
+
return IdentityTransform()
|
|
84
|
+
|
|
85
|
+
def transform_path_non_affine(self, path: Path) -> Path:
|
|
86
|
+
vertices, codes = [], []
|
|
87
|
+
previous = start = None
|
|
88
|
+
for segment, code in path.iter_segments(
|
|
89
|
+
curves=False, simplify=False, remove_nans=False
|
|
90
|
+
):
|
|
91
|
+
endpoint = start if code == Path.CLOSEPOLY else segment[-2:]
|
|
92
|
+
if code != Path.MOVETO and previous is not None:
|
|
93
|
+
if np.isfinite(previous).all() and np.isfinite(endpoint).all():
|
|
94
|
+
dx = endpoint[0] - previous[0]
|
|
95
|
+
if dx != 0:
|
|
96
|
+
fractions = (self.boundaries - previous[0]) / dx
|
|
97
|
+
for fraction in np.sort(
|
|
98
|
+
fractions[(fractions > 0) & (fractions < 1)]
|
|
99
|
+
):
|
|
100
|
+
vertices.append(previous + fraction * (endpoint - previous))
|
|
101
|
+
codes.append(Path.LINETO)
|
|
102
|
+
vertices.append(endpoint)
|
|
103
|
+
codes.append(code)
|
|
104
|
+
previous = np.asarray(endpoint)
|
|
105
|
+
if code == Path.MOVETO:
|
|
106
|
+
start = previous
|
|
107
|
+
return Path(vertices, codes) if vertices else path
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def break_xaxis(
|
|
111
|
+
ax: Axes,
|
|
112
|
+
x_breaks: ArrayLike,
|
|
113
|
+
*,
|
|
114
|
+
x_breaks_gap: float | None = None,
|
|
115
|
+
xtick_major: float | None = None,
|
|
116
|
+
xtick_minor: float | None = None,
|
|
117
|
+
) -> Axes:
|
|
118
|
+
"""Omit x-coordinate intervals while keeping the original Matplotlib axis.
|
|
119
|
+
|
|
120
|
+
Parameters
|
|
121
|
+
----------
|
|
122
|
+
ax : matplotlib.axes.Axes
|
|
123
|
+
A linear x axis with its data and limits already configured. An axis
|
|
124
|
+
previously processed by this function is also accepted.
|
|
125
|
+
x_breaks : array-like of shape (n_breaks, 2)
|
|
126
|
+
Intervals to omit, in original data coordinates, not ranges to retain.
|
|
127
|
+
Each pair must contain finite values with lower < upper, even for an
|
|
128
|
+
inverted axis. Intervals are sorted and must not overlap or touch.
|
|
129
|
+
Empty input leaves the scale unchanged, but requested tick spacings
|
|
130
|
+
are still applied. Intervals outside the current view are ignored;
|
|
131
|
+
partially visible intervals are clipped to the view. The entire view
|
|
132
|
+
cannot be omitted.
|
|
133
|
+
x_breaks_gap : positive float, optional
|
|
134
|
+
Width of every gap in the same units as the retained x coordinates.
|
|
135
|
+
Defaults to xtick_minor when provided, otherwise half the major-tick
|
|
136
|
+
interval, including when the major interval is chosen automatically.
|
|
137
|
+
xtick_major, xtick_minor : positive float, optional
|
|
138
|
+
Tick spacings in original x-data units, anchored at zero. Ticks inside
|
|
139
|
+
omitted intervals are excluded. Explicit major spacing is honored
|
|
140
|
+
without thinning labels, even if labels become crowded. If None, major
|
|
141
|
+
spacing is automatic and minor ticks are disabled for broken axes.
|
|
142
|
+
With no visible breaks, omitted options leave existing locators intact.
|
|
143
|
+
|
|
144
|
+
Returns
|
|
145
|
+
-------
|
|
146
|
+
matplotlib.axes.Axes
|
|
147
|
+
The supplied axis, with retained ranges on one linear scale, configured gaps,
|
|
148
|
+
break marks, and ticks in the original data coordinates. No new axes are
|
|
149
|
+
created. Original line data and legend handles are retained.
|
|
150
|
+
|
|
151
|
+
Notes
|
|
152
|
+
-----
|
|
153
|
+
Apply this as a final plotting step. It installs a custom x scale and fixed
|
|
154
|
+
tick locators, and replaces clipping paths on lines, filled polygons, and
|
|
155
|
+
horizontal spines. Line and polygon paths are subdivided
|
|
156
|
+
at break boundaries so sparse data interpolate correctly beside each gap.
|
|
157
|
+
Scatter, images, annotations, and custom artist clipping are not supported.
|
|
158
|
+
|
|
159
|
+
Normal axis operations have limitations after breaking: adding artists,
|
|
160
|
+
changing limits, autoscaling, or interactive pan/zoom can leave clipping and
|
|
161
|
+
ticks out of date. Reapply this function after such changes. Repeated calls
|
|
162
|
+
replace the marks and clipping rather than adding duplicate decorations.
|
|
163
|
+
Setting another x scale replaces the break transform and is not an undo
|
|
164
|
+
operation. An empty interval list does not undo existing breaks either.
|
|
165
|
+
|
|
166
|
+
X scales are shared by Matplotlib siblings. Apply this function to every
|
|
167
|
+
visible axis in a shared group to install each panel's clipping and marks.
|
|
168
|
+
Changing from a logarithmic or other nonlinear scale is rejected.
|
|
169
|
+
|
|
170
|
+
Examples
|
|
171
|
+
--------
|
|
172
|
+
>>> import matplotlib.pyplot as plt
|
|
173
|
+
>>> from pyspc.plotting import break_xaxis
|
|
174
|
+
>>> fig, ax = plt.subplots()
|
|
175
|
+
>>> _ = ax.plot([0, 10], [0, 10])
|
|
176
|
+
>>> _ = ax.set_xlim(0, 10)
|
|
177
|
+
>>> _ = break_xaxis(ax, [(4, 8)])
|
|
178
|
+
>>> plt.close(fig)
|
|
179
|
+
"""
|
|
180
|
+
# Validate before changing artists or shared axis state.
|
|
181
|
+
if not isinstance(ax, Axes):
|
|
182
|
+
raise TypeError("ax must be a matplotlib Axes.")
|
|
183
|
+
intervals = _validate_x_breaks(x_breaks, ax=ax)
|
|
184
|
+
x_breaks_gap = _validate_spacing(x_breaks_gap, "x_breaks_gap")
|
|
185
|
+
xtick_major = _validate_spacing(xtick_major, "xtick_major")
|
|
186
|
+
xtick_minor = _validate_spacing(xtick_minor, "xtick_minor")
|
|
187
|
+
if not len(intervals):
|
|
188
|
+
_set_xtick_spacing(ax, xtick_major, xtick_minor)
|
|
189
|
+
return ax
|
|
190
|
+
limits = ax.get_xlim()
|
|
191
|
+
lower, upper = sorted(limits)
|
|
192
|
+
if not np.isfinite(upper - lower):
|
|
193
|
+
raise ValueError("The visible x range is too large for x_breaks.")
|
|
194
|
+
intervals = intervals[(intervals[:, 1] > lower) & (intervals[:, 0] < upper)]
|
|
195
|
+
if not len(intervals):
|
|
196
|
+
_set_xtick_spacing(ax, xtick_major, xtick_minor)
|
|
197
|
+
return ax
|
|
198
|
+
intervals = np.clip(intervals, lower, upper)
|
|
199
|
+
widths = intervals[:, 1] - intervals[:, 0]
|
|
200
|
+
retained_width = (upper - lower) - widths.sum()
|
|
201
|
+
if retained_width <= 0:
|
|
202
|
+
raise ValueError("x_breaks cannot omit the entire visible x range.")
|
|
203
|
+
|
|
204
|
+
# Determine a global major interval and derive the default gap from ticks.
|
|
205
|
+
major = xtick_major
|
|
206
|
+
if major is None:
|
|
207
|
+
automatic = MaxNLocator(nbins=max(2, ax.xaxis.get_tick_space()), min_n_ticks=2)
|
|
208
|
+
major = float(np.min(np.diff(automatic.tick_values(0, retained_width))))
|
|
209
|
+
gap = x_breaks_gap
|
|
210
|
+
if gap is None:
|
|
211
|
+
gap = xtick_minor if xtick_minor is not None else major / 2
|
|
212
|
+
if gap <= 0:
|
|
213
|
+
raise ValueError("The retained x range is too small for x_breaks.")
|
|
214
|
+
reductions = widths - gap
|
|
215
|
+
starts = intervals[:, 0] - lower
|
|
216
|
+
compressed_starts = starts - (np.cumsum(reductions) - reductions)
|
|
217
|
+
|
|
218
|
+
def forward(values: ArrayLike) -> ArrayLike:
|
|
219
|
+
coordinates = np.asarray(values, dtype=float) - lower
|
|
220
|
+
result = coordinates.copy()
|
|
221
|
+
for start, width, reduction in zip(starts, widths, reductions):
|
|
222
|
+
result -= np.clip((coordinates - start) / width, 0, 1) * reduction
|
|
223
|
+
return result
|
|
224
|
+
|
|
225
|
+
def inverse(values: ArrayLike) -> ArrayLike:
|
|
226
|
+
coordinates = np.asarray(values, dtype=float)
|
|
227
|
+
result = coordinates + lower
|
|
228
|
+
for start, reduction in zip(compressed_starts, reductions):
|
|
229
|
+
result = result + np.clip((coordinates - start) / gap, 0, 1) * reduction
|
|
230
|
+
return result
|
|
231
|
+
|
|
232
|
+
# Keep the axis view and its autoscale setting while replacing its x scale.
|
|
233
|
+
autoscale = ax.get_autoscalex_on()
|
|
234
|
+
ax.set_xscale(_XBreakScale(ax.xaxis, functions=(forward, inverse)))
|
|
235
|
+
ax.set_xlim(limits, auto=autoscale)
|
|
236
|
+
edges = np.concatenate(([lower], intervals.ravel(), [upper])).reshape(-1, 2)
|
|
237
|
+
retained = edges[edges[:, 1] > edges[:, 0]]
|
|
238
|
+
|
|
239
|
+
# Generate regular data-coordinate ticks only in the retained ranges.
|
|
240
|
+
for interval, setter in (
|
|
241
|
+
(major, ax.xaxis.set_major_locator),
|
|
242
|
+
(xtick_minor, ax.xaxis.set_minor_locator),
|
|
243
|
+
):
|
|
244
|
+
if interval is None:
|
|
245
|
+
setter(NullLocator())
|
|
246
|
+
continue
|
|
247
|
+
ticks = []
|
|
248
|
+
locator = MultipleLocator(interval)
|
|
249
|
+
for left, right in retained:
|
|
250
|
+
candidates = locator.tick_values(left, right)
|
|
251
|
+
ticks.extend(candidates[(candidates >= left) & (candidates <= right)])
|
|
252
|
+
setter(FixedLocator(np.unique(ticks)))
|
|
253
|
+
|
|
254
|
+
# Only automatic major labels may be thinned near compressed gaps.
|
|
255
|
+
if xtick_major is None:
|
|
256
|
+
spacing = (forward(upper) - forward(lower)) / max(2, ax.xaxis.get_tick_space())
|
|
257
|
+
separated = []
|
|
258
|
+
for tick in ax.get_xticks():
|
|
259
|
+
if not separated or forward(tick) - forward(separated[-1]) >= spacing:
|
|
260
|
+
separated.append(tick)
|
|
261
|
+
ax.xaxis.set_major_locator(FixedLocator(separated))
|
|
262
|
+
|
|
263
|
+
# Clip visible segments, interpolating original line/band paths at boundaries.
|
|
264
|
+
clip_path = Path.make_compound_path_from_polys(
|
|
265
|
+
np.array(
|
|
266
|
+
[[[left, 0], [left, 1], [right, 1], [right, 0]] for left, right in retained]
|
|
267
|
+
)
|
|
268
|
+
)
|
|
269
|
+
clip_transform = ax.get_xaxis_transform()
|
|
270
|
+
for line in list(ax.lines):
|
|
271
|
+
if line.get_gid() == "pyspc-xbreak-marks":
|
|
272
|
+
line.remove()
|
|
273
|
+
artists = [
|
|
274
|
+
*ax.lines,
|
|
275
|
+
*(artist for artist in ax.collections if isinstance(artist, PolyCollection)),
|
|
276
|
+
]
|
|
277
|
+
for artist in artists:
|
|
278
|
+
if not hasattr(artist, "_pyspc_xbreak_base_transform"):
|
|
279
|
+
artist._pyspc_xbreak_base_transform = artist.get_transform()
|
|
280
|
+
artist.set_transform(
|
|
281
|
+
_XBreakPathTransform(intervals.ravel())
|
|
282
|
+
+ artist._pyspc_xbreak_base_transform
|
|
283
|
+
)
|
|
284
|
+
artist.set_clip_path(clip_path, clip_transform)
|
|
285
|
+
for name in ("bottom", "top"):
|
|
286
|
+
ax.spines[name].set_clip_path(clip_path, clip_transform)
|
|
287
|
+
|
|
288
|
+
# Marker sizes are in points so resizing a figure does not stretch the slashes.
|
|
289
|
+
for name, height in (("bottom", 0), ("top", 1)):
|
|
290
|
+
if ax.spines[name].get_visible():
|
|
291
|
+
marks = ax.plot(
|
|
292
|
+
intervals.ravel(),
|
|
293
|
+
np.full(intervals.size, height),
|
|
294
|
+
transform=clip_transform,
|
|
295
|
+
linestyle="none",
|
|
296
|
+
marker=[(-1, -0.5), (1, 0.5)],
|
|
297
|
+
markersize=6,
|
|
298
|
+
color=ax.spines[name].get_edgecolor(),
|
|
299
|
+
clip_on=False,
|
|
300
|
+
scalex=False,
|
|
301
|
+
scaley=False,
|
|
302
|
+
label="_nolegend_",
|
|
303
|
+
)[0]
|
|
304
|
+
marks.set_gid("pyspc-xbreak-marks")
|
|
305
|
+
return ax
|
pyspc/baselines.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
import scipy
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
def rubberband(x: np.array, y: np.array) -> np.ndarray:
|
|
6
|
+
"""Rubberband baseline correction
|
|
7
|
+
|
|
8
|
+
Based on code from Stack Exchange (Author: Roman Kiselev)
|
|
9
|
+
Source: https://dsp.stackexchange.com/a/30723/69444 (CC BY-SA 3.0)
|
|
10
|
+
|
|
11
|
+
Parameters
|
|
12
|
+
----------
|
|
13
|
+
x : np.array
|
|
14
|
+
1D array of wavelengths
|
|
15
|
+
y : np.array
|
|
16
|
+
1D array of signal values
|
|
17
|
+
|
|
18
|
+
Returns
|
|
19
|
+
-------
|
|
20
|
+
np.ndarray
|
|
21
|
+
1D array of rubberband baseline. Has the same size as x and y
|
|
22
|
+
"""
|
|
23
|
+
v = scipy.spatial.ConvexHull(np.array([x, y]).T).vertices
|
|
24
|
+
v = np.roll(v, -v.argmin())
|
|
25
|
+
v = v[: (v.argmax() + 1)]
|
|
26
|
+
bl = np.interp(x, x[v], y[v])
|
|
27
|
+
|
|
28
|
+
return bl
|
pyspc/concatenation.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
from typing import Iterable
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
import pandas as pd
|
|
5
|
+
|
|
6
|
+
from .spectra import SpectraFrame
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def concat(objs: Iterable[SpectraFrame], axis=None) -> SpectraFrame:
|
|
10
|
+
"""Concatenate multiple `SpectraFrame` objects along a specified axis.
|
|
11
|
+
|
|
12
|
+
Parameters
|
|
13
|
+
----------
|
|
14
|
+
objs : Iterable[SpectraFrame]
|
|
15
|
+
An iterable of `SpectraFrame` objects to concatenate.
|
|
16
|
+
axis : int, optional
|
|
17
|
+
The axis along which to concatenate the objects. If `None`, it will be inferred.
|
|
18
|
+
If all objects have the same `nspc` and different `wl`, it will default to `1`
|
|
19
|
+
(concatenate by columns). If all objects have the same wavelengths, it will
|
|
20
|
+
default to `0` (concatenate by rows).
|
|
21
|
+
|
|
22
|
+
Returns
|
|
23
|
+
-------
|
|
24
|
+
SpectraFrame
|
|
25
|
+
A new `SpectraFrame` object containing the concatenated spectral data.
|
|
26
|
+
|
|
27
|
+
Raises
|
|
28
|
+
------
|
|
29
|
+
ValueError
|
|
30
|
+
If the input `SpectraFrame` objects have incompatible shapes or wavelengths.
|
|
31
|
+
|
|
32
|
+
Notes
|
|
33
|
+
-----
|
|
34
|
+
- indices of the `data` DataFrame are reset after concatenation.
|
|
35
|
+
- No additional checks and sortings are performed. Pay attention to:
|
|
36
|
+
order of `wl` and overlapping ranges of `wl`
|
|
37
|
+
"""
|
|
38
|
+
# TODO: Allow concatenating np.ndarray and pd.DataFrame
|
|
39
|
+
is_same_wls = len(set(tuple(sf.wl.astype(np.float64)) for sf in objs)) == 1
|
|
40
|
+
is_same_nspc = len(set(sf.nspc for sf in objs)) == 1
|
|
41
|
+
|
|
42
|
+
if axis is None:
|
|
43
|
+
# If all objects have the same number of rows and different number of
|
|
44
|
+
# wavelengths then assume that we want to stack by columns
|
|
45
|
+
if (not is_same_wls) and is_same_nspc:
|
|
46
|
+
axis = 1
|
|
47
|
+
else:
|
|
48
|
+
axis = 0
|
|
49
|
+
|
|
50
|
+
if axis == 0:
|
|
51
|
+
if is_same_wls:
|
|
52
|
+
return SpectraFrame(
|
|
53
|
+
np.concatenate([sf.spc for sf in objs], axis=0),
|
|
54
|
+
wl=objs[0].wl,
|
|
55
|
+
data=pd.concat([sf.data for sf in objs], axis=0, ignore_index=True),
|
|
56
|
+
)
|
|
57
|
+
else:
|
|
58
|
+
raise ValueError("Spectral data has different wavelenghts")
|
|
59
|
+
elif axis == 1:
|
|
60
|
+
# Check overlapping data columns
|
|
61
|
+
data_columns = pd.Series(
|
|
62
|
+
[col for sf in objs for col in sf.data.columns]
|
|
63
|
+
).value_counts()
|
|
64
|
+
if any(data_columns > 1):
|
|
65
|
+
duplicates = data_columns[data_columns > 1].index.tolist()
|
|
66
|
+
raise ValueError(f"Overlapping data columns found: {duplicates}")
|
|
67
|
+
|
|
68
|
+
# TODO: Order of wl
|
|
69
|
+
# TODO: Check that wl ranges do not overlap
|
|
70
|
+
return SpectraFrame(
|
|
71
|
+
np.concatenate([sf.spc for sf in objs], axis=1),
|
|
72
|
+
wl=np.concatenate([sf.wl for sf in objs], axis=None),
|
|
73
|
+
data=pd.concat(
|
|
74
|
+
[sf.data.reset_index(drop=True) for sf in objs],
|
|
75
|
+
axis=1,
|
|
76
|
+
ignore_index=False,
|
|
77
|
+
),
|
|
78
|
+
)
|
|
79
|
+
else:
|
|
80
|
+
raise ValueError(f"Unexpected `axis` {axis}.")
|