pyperspec 0.7.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,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.
@@ -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
+ [![codecov](https://codecov.io/gh/r-hyperspec/pyperspec/graph/badge.svg?token=P12AJV4JHC)](https://codecov.io/gh/r-hyperspec/pyperspec)
26
+ [![License](https://img.shields.io/github/license/r-hyperspec/pyperspec.svg)](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,109 @@
1
+ [![codecov](https://codecov.io/gh/r-hyperspec/pyperspec/graph/badge.svg?token=P12AJV4JHC)](https://codecov.io/gh/r-hyperspec/pyperspec)
2
+ [![License](https://img.shields.io/github/license/r-hyperspec/pyperspec.svg)](https://github.com/r-hyperspec/pyperspec/blob/main/LICENSE)
3
+
4
+ # Python Package pyperspec
5
+
6
+ This is a Python package designed to simplify the analysis and manipulation of hyperspectral datasets.
7
+ 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`.
8
+
9
+ This is heavily inspired by R package [hyperSpec](https://github.com/r-hyperspec/hyperSpec) and part of **`r-hyperspec`**.
10
+ 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.
11
+ The spectra can be data obtained during
12
+ [XRF](https://en.wikipedia.org/wiki/X-ray_fluorescence),
13
+ [UV/VIS](https://en.wikipedia.org/wiki/Ultraviolet%E2%80%93visible_spectroscopy),
14
+ [Fluorescence](https://en.wikipedia.org/wiki/Fluorescence_spectroscopy),
15
+ [AES](https://en.wikipedia.org/wiki/Auger_electron_spectroscopy),
16
+ [NIR](https://en.wikipedia.org/wiki/Near-infrared_spectroscopy),
17
+ [IR](https://en.wikipedia.org/wiki/Infrared_spectroscopy),
18
+ [Raman](https://en.wikipedia.org/wiki/Raman_spectroscopy),
19
+ [NMR](https://en.wikipedia.org/wiki/Nuclear_magnetic_resonance_spectroscopy),
20
+ [MS](https://en.wikipedia.org/wiki/Mass_spectrometry),
21
+ etc. spectroscopy measurements.
22
+
23
+ **NOTE:** The main focus is **not** on algroithms since there are already many other good packages implementing algorithms, e.g.
24
+ [numpy](https://numpy.org/),
25
+ [scipy](https://scipy.org/),
26
+ [pybaselines](https://github.com/derb12/pybaselines),
27
+ and more can be found in [FOSS For Spectroscopy](https://bryanhanson.github.io/FOSS4Spectroscopy/) list.
28
+
29
+ Rather, it provides convinient interface for those algorithms and other routine tasks.
30
+
31
+ For detailed information and documentation, please visit [Documentation](https://r-hyperspec.github.io/pyperspec/).
32
+
33
+ ## Documentation
34
+
35
+ Please, check [here](https://r-hyperspec.github.io/pyperspec/)
36
+
37
+ ## Installation
38
+
39
+ Requires Python 3.12 or newer. Install from PyPI:
40
+
41
+ ```bash
42
+ pip install pyperspec
43
+ ```
44
+
45
+ Or add it to a uv project:
46
+
47
+ ```bash
48
+ uv add pyperspec
49
+ ```
50
+
51
+ The Python import name is `pyspc`.
52
+
53
+ ## Quick Demo
54
+
55
+ ```python
56
+ import pyspc
57
+ import numpy as np
58
+ import pandas as pd
59
+
60
+ spc = np.random.rand(10, 20) # Here are your spectra in unfolded structure
61
+ wl = np.linspace(1000,2000,20) # Array of wavelength/wavenumbers
62
+ meta_data = pd.DataFrame({"group": ["A", "B"] * 5, "date": pd.date_range("2023-01-01", periods=10)}) # Additional meta-data
63
+
64
+ # Create the object
65
+ sf = pyspc.SpectraFrame(spc, wl=wl, data=meta_data)
66
+
67
+ # Easy meta-data manipulation
68
+ sf.A
69
+ sf["A"]
70
+ sf["group"] = ["Control", "Treatment"] * 5
71
+
72
+ # Easy data slicing/filtering, similar to hyperSpec
73
+ sf[:,:,500:1000] # Cut wavelength range to [500, 1000]
74
+ sf[:5,:,:5, True] # Use iloc style to get only first five spectra and first five wavenumbers
75
+ sf.query("group == 'Control'") # Get only 'Control' group
76
+
77
+ # Simple aggregation even with custom methods
78
+ sf[:,:,500:1000].mean(groupby=["group", "date"])
79
+ sf.query("group == 'Control'").apply(lambda x: np.sum(x**2), axis=0)
80
+
81
+ # Chaining methods
82
+ sf_processed = (
83
+ sf.query("group == 'Control'")
84
+ .mean(groupby="date")
85
+ .smooth("savgol", window_length=7, polyorder=2)
86
+ .sbaseline("rubberband")
87
+ .normalize("area")
88
+ )
89
+
90
+ # Select 3 random spectra and plot them colored by "date"
91
+ sf.sample(3).plot(colors="date")
92
+
93
+ # Export to wide pandas DataFrame
94
+ sf.to_pandas()
95
+ ```
96
+
97
+ ## Acknowlegments
98
+
99
+ * 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/)
100
+ * 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.
101
+ * The project was developed as part of secondment at [Chemometrix GmbH](https://chemometrix.gmbh/)
102
+ * Supervision was from [Chemometrix GmbH](https://chemometrix.gmbh/), [Leibniz-IPHT](https://www.leibniz-ipht.de/en/), and [BMD Software](https://www.bmd-software.com/)
103
+
104
+ <img src="https://biochemphysics.ru/static/img/logo_en.png" alt="Emanuel Institute of Biochemical Physics, RAS" style="height: 100px; margin: 10px"/>
105
+ <img src="https://bgsmath.cat/wp-content/uploads/2017/09/marie_curie1-300x160.jpg" alt="Horizon 2020" style="height: 100px; margin: 10px"/>
106
+ <img src="img/logo_imagein.png" alt="IMAGE-IN" style="height: 100px; margin: 10px"/>
107
+ <img src="https://chemometrix.gmbh/assets/images/chemometrix-logo.png" alt="Chemometrix GmbH" style="height: 80px; margin: 10px">
108
+ <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">
109
+ <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,104 @@
1
+ [project]
2
+ name = "pyperspec"
3
+ version = "0.7.1"
4
+ description = "Tools for Spectroscopy"
5
+ readme = "README.md"
6
+ requires-python = ">=3.12"
7
+ license = "MIT"
8
+ license-files = ["LICENSE"]
9
+ authors = [
10
+ { name = "Rustam Guliev", email = "glvrst@gmail.com" },
11
+ ]
12
+ keywords = ["spectroscopy", "Raman", "IR", "signal", "processing"]
13
+ dependencies = [
14
+ "pandas>=2.1.1,<3.0.0",
15
+ "matplotlib>=3.8.0",
16
+ "scipy>=1.11.2",
17
+ "pybaselines>=1.1.0",
18
+ ]
19
+
20
+ [project.urls]
21
+ Homepage = "https://github.com/r-hyperspec/pyperspec"
22
+ Documentation = "https://r-hyperspec.github.io/pyperspec/"
23
+ Repository = "https://github.com/r-hyperspec/pyperspec"
24
+ Issues = "https://github.com/r-hyperspec/pyperspec/issues"
25
+
26
+ [project.optional-dependencies]
27
+ einops = ["einops>=0.6.0"]
28
+ all = ["einops>=0.6.0"]
29
+
30
+ [dependency-groups]
31
+ dev = [
32
+ "black>=23.9.1,<24.0.0",
33
+ "ruff>=0.0.291",
34
+ "pytest>=7.4.2,<8.0.0",
35
+ "pre-commit>=3.4.0,<4.0.0",
36
+ "ipython>=8.15.0,<9.0.0",
37
+ "mkdocs>=1.6.0,<2.0.0",
38
+ "mkdocs-material>=9.5.28,<10.0.0",
39
+ "mkdocstrings[python]>=0.25.1,<0.26.0",
40
+ "pymdown-extensions>=10.9,<11.0",
41
+ "mkdocs-exclude>=1.0.2,<2.0.0",
42
+ "pytest-cov>=5.0.0,<6.0.0",
43
+ ]
44
+
45
+ [tool.pytest.ini_options]
46
+ norecursedirs = ["site"]
47
+
48
+ [tool.black]
49
+ target-version = ["py312"]
50
+
51
+ [tool.ruff]
52
+ line-length = 88
53
+ target-version = "py312"
54
+
55
+ [tool.ruff.lint]
56
+ # Enable the pycodestyle (`E`) and Pyflakes (`F`) rules by default.
57
+ # Unlike Flake8, Ruff doesn't enable pycodestyle warnings (`W`) or
58
+ # McCabe complexity (`C901`) by default.
59
+ select = ["E", "F"]
60
+ ignore = ["E731"]
61
+
62
+ # Allow autofix for all enabled rules (when `--fix`) is provided.
63
+ fixable = ["ALL"]
64
+ unfixable = []
65
+
66
+ # Exclude a variety of commonly ignored directories.
67
+ exclude = [
68
+ ".bzr",
69
+ ".direnv",
70
+ ".eggs",
71
+ ".git",
72
+ ".git-rewrite",
73
+ ".hg",
74
+ ".mypy_cache",
75
+ ".nox",
76
+ ".pants.d",
77
+ ".pytype",
78
+ ".ruff_cache",
79
+ ".svn",
80
+ ".tox",
81
+ ".venv",
82
+ "__pypackages__",
83
+ "_build",
84
+ "buck-out",
85
+ "build",
86
+ "dist",
87
+ "node_modules",
88
+ "venv",
89
+ ".vscode",
90
+ ]
91
+ per-file-ignores = {}
92
+
93
+ # Allow unused variables when underscore-prefixed.
94
+ dummy-variable-rgx = "^(_+|(_+[a-zA-Z0-9_]*[a-zA-Z0-9]+?))$"
95
+
96
+ [build-system]
97
+ requires = ["uv_build>=0.11.26,<0.12.0"]
98
+ build-backend = "uv_build"
99
+
100
+ [tool.uv.build-backend]
101
+ module-root = ""
102
+ module-name = "pyspc"
103
+ source-exclude = ["**/*.bkp"]
104
+ wheel-exclude = ["**/*.bkp"]
@@ -0,0 +1,5 @@
1
+ # ruff: noqa: F401, F403
2
+ from .spectra import SpectraFrame
3
+ from .concatenation import concat
4
+ from .peaks import *
5
+ from .spikes import find_spikes
@@ -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