heapyx 0.2.0__tar.gz → 0.2.3__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 (75) hide show
  1. heapyx-0.2.3/PKG-INFO +159 -0
  2. heapyx-0.2.3/README.md +116 -0
  3. heapyx-0.2.3/heapy/__info__.py +1 -0
  4. heapyx-0.2.3/heapy/__init__.py +1 -0
  5. heapyx-0.2.3/heapy/auto/baseline.py +388 -0
  6. heapyx-0.2.3/heapy/auto/polynomial.py +566 -0
  7. heapyx-0.2.3/heapy/auto/signal.py +1586 -0
  8. heapyx-0.2.3/heapy/auto/signal_utils.py +722 -0
  9. heapyx-0.2.3/heapy/data/filefinder.py +545 -0
  10. heapyx-0.2.3/heapy/data/retrieve.py +939 -0
  11. heapyx-0.2.3/heapy/geos/detector.py +132 -0
  12. heapyx-0.2.3/heapy/geos/geometry.py +557 -0
  13. {heapyx-0.2.0 → heapyx-0.2.3}/heapy/geos/localization.py +382 -147
  14. heapyx-0.2.3/heapy/geos/skymap.py +416 -0
  15. heapyx-0.2.3/heapy/pipe/batpipe.py +1173 -0
  16. heapyx-0.2.3/heapy/pipe/event.py +2373 -0
  17. heapyx-0.2.3/heapy/pipe/filter.py +173 -0
  18. heapyx-0.2.3/heapy/pipe/image.py +2034 -0
  19. heapyx-0.2.3/heapy/temp/cwt.py +418 -0
  20. heapyx-0.2.3/heapy/temp/lag.py +738 -0
  21. heapyx-0.2.3/heapy/temp/mvt.py +431 -0
  22. heapyx-0.2.3/heapy/temp/temp_utils.py +1879 -0
  23. heapyx-0.2.3/heapy/temp/txx.py +686 -0
  24. heapyx-0.2.3/heapy/util/coord.py +483 -0
  25. heapyx-0.2.3/heapy/util/data.py +791 -0
  26. heapyx-0.2.3/heapy/util/file.py +332 -0
  27. heapyx-0.2.3/heapy/util/significance.py +311 -0
  28. heapyx-0.2.3/heapy/util/time.py +326 -0
  29. heapyx-0.2.3/heapy/util/tools.py +383 -0
  30. heapyx-0.2.3/heapyx.egg-info/PKG-INFO +159 -0
  31. {heapyx-0.2.0 → heapyx-0.2.3}/heapyx.egg-info/SOURCES.txt +7 -3
  32. {heapyx-0.2.0 → heapyx-0.2.3}/heapyx.egg-info/requires.txt +5 -0
  33. heapyx-0.2.3/pyproject.toml +39 -0
  34. heapyx-0.2.3/setup.py +56 -0
  35. heapyx-0.2.0/PKG-INFO +0 -84
  36. heapyx-0.2.0/README.md +0 -46
  37. heapyx-0.2.0/heapy/__info__.py +0 -1
  38. heapyx-0.2.0/heapy/__init__.py +0 -1
  39. heapyx-0.2.0/heapy/auto/baseline.py +0 -306
  40. heapyx-0.2.0/heapy/auto/ggsignal.py +0 -264
  41. heapyx-0.2.0/heapy/auto/polybase.py +0 -686
  42. heapyx-0.2.0/heapy/auto/polynomial.py +0 -291
  43. heapyx-0.2.0/heapy/auto/ppsignal.py +0 -314
  44. heapyx-0.2.0/heapy/data/filefinder.py +0 -217
  45. heapyx-0.2.0/heapy/data/retrieve.py +0 -622
  46. heapyx-0.2.0/heapy/geos/detector.py +0 -68
  47. heapyx-0.2.0/heapy/geos/geometry.py +0 -347
  48. heapyx-0.2.0/heapy/geos/skymap.py +0 -190
  49. heapyx-0.2.0/heapy/pipe/batpipe.py +0 -828
  50. heapyx-0.2.0/heapy/pipe/event.py +0 -1934
  51. heapyx-0.2.0/heapy/pipe/filter.py +0 -77
  52. heapyx-0.2.0/heapy/pipe/image.py +0 -1709
  53. heapyx-0.2.0/heapy/temp/lag.py +0 -402
  54. heapyx-0.2.0/heapy/temp/txx.py +0 -909
  55. heapyx-0.2.0/heapy/util/coord.py +0 -444
  56. heapyx-0.2.0/heapy/util/data.py +0 -750
  57. heapyx-0.2.0/heapy/util/file.py +0 -308
  58. heapyx-0.2.0/heapy/util/significance.py +0 -240
  59. heapyx-0.2.0/heapy/util/time.py +0 -368
  60. heapyx-0.2.0/heapyx.egg-info/PKG-INFO +0 -84
  61. heapyx-0.2.0/setup.py +0 -53
  62. {heapyx-0.2.0 → heapyx-0.2.3}/LICENSE +0 -0
  63. {heapyx-0.2.0 → heapyx-0.2.3}/heapy/auto/__init__.py +0 -0
  64. {heapyx-0.2.0 → heapyx-0.2.3}/heapy/data/__init__.py +0 -0
  65. {heapyx-0.2.0 → heapyx-0.2.3}/heapy/docs/McIlwainL_coeffs/McIlwainL_Coeffs.npy +0 -0
  66. {heapyx-0.2.0 → heapyx-0.2.3}/heapy/docs/psf_model/fxt_psf.cod +0 -0
  67. {heapyx-0.2.0 → heapyx-0.2.3}/heapy/docs/psf_model/fxt_psf.dat +0 -0
  68. {heapyx-0.2.0 → heapyx-0.2.3}/heapy/docs/psf_model/xrt_psf.cod +0 -0
  69. {heapyx-0.2.0 → heapyx-0.2.3}/heapy/geos/__init__.py +0 -0
  70. {heapyx-0.2.0 → heapyx-0.2.3}/heapy/pipe/__init__.py +0 -0
  71. {heapyx-0.2.0 → heapyx-0.2.3}/heapy/temp/__init__.py +0 -0
  72. {heapyx-0.2.0 → heapyx-0.2.3}/heapy/util/__init__.py +0 -0
  73. {heapyx-0.2.0 → heapyx-0.2.3}/heapyx.egg-info/dependency_links.txt +0 -0
  74. {heapyx-0.2.0 → heapyx-0.2.3}/heapyx.egg-info/top_level.txt +0 -0
  75. {heapyx-0.2.0 → heapyx-0.2.3}/setup.cfg +0 -0
heapyx-0.2.3/PKG-INFO ADDED
@@ -0,0 +1,159 @@
1
+ Metadata-Version: 2.4
2
+ Name: heapyx
3
+ Version: 0.2.3
4
+ Summary: High-energy (X-ray and gamma-ray) astronomical data analysis tools
5
+ Home-page: https://github.com/jyangch/heapy
6
+ Author: Jun Yang
7
+ Author-email: jyang@smail.nju.edu.cn
8
+ License: GPLv3
9
+ Project-URL: Source Code, https://github.com/jyangch/heapy
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: License :: OSI Approved :: GNU General Public License v3 (GPLv3)
12
+ Classifier: Operating System :: POSIX :: Linux
13
+ Classifier: Operating System :: MacOS
14
+ Classifier: Topic :: Scientific/Engineering :: Astronomy
15
+ Requires-Python: >=3.10
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Requires-Dist: numpy>=1.20.4
19
+ Requires-Dist: pandas>=1.4.2
20
+ Requires-Dist: scipy>=1.8.0
21
+ Requires-Dist: astropy>=5.2.2
22
+ Requires-Dist: matplotlib>=3.2.1
23
+ Requires-Dist: tqdm>=4.64.1
24
+ Requires-Dist: plotly>=5.22.0
25
+ Requires-Dist: kaleido>=0.2.1
26
+ Requires-Dist: pybaselines>=1.1.0
27
+ Requires-Dist: pycwt>=0.3.0a22
28
+ Requires-Dist: scikit-learn>=1.0
29
+ Requires-Dist: healpy>=1.16
30
+ Requires-Dist: cartopy>=0.21
31
+ Dynamic: author
32
+ Dynamic: author-email
33
+ Dynamic: classifier
34
+ Dynamic: description
35
+ Dynamic: description-content-type
36
+ Dynamic: home-page
37
+ Dynamic: license
38
+ Dynamic: license-file
39
+ Dynamic: project-url
40
+ Dynamic: requires-dist
41
+ Dynamic: requires-python
42
+ Dynamic: summary
43
+
44
+ <h1 align="center">HEAPY</h1>
45
+
46
+ <p align="center">
47
+ <strong>A Python toolkit for data reduction, temporal analysis, and spectral extraction of X-ray and gamma-ray transients.</strong>
48
+ </p>
49
+
50
+ <p align="center">
51
+ <a href="https://pypi.org/project/heapyx/"><img alt="PyPI" src="https://img.shields.io/pypi/v/heapyx?color=4F46E5&labelColor=1f2937&logo=pypi&logoColor=white"></a>
52
+ <a href="https://github.com/jyangch/heapy/tree/main/examples"><img alt="Examples" src="https://img.shields.io/badge/docs-examples-06B6D4?labelColor=1f2937"></a>
53
+ <a href="https://www.gnu.org/licenses/gpl-3.0"><img alt="License GPL-3.0" src="https://img.shields.io/badge/license-GPL--3.0-9CA3AF?labelColor=1f2937"></a>
54
+ </p>
55
+
56
+ ---
57
+
58
+ `Heapy` is a Python toolkit for data reduction, temporal analysis, and
59
+ spectral extraction of X-ray and gamma-ray transients. It pulls event and response data from mission
60
+ archives, reduces time-tagged-event (TTE) and image data into light curves
61
+ and OGIP spectra, separates burst signals from fitted backgrounds, and
62
+ measures durations, spectral lags, and source localizations — across
63
+ [`Fermi`](https://gammaray.nsstc.nasa.gov/gbm/)/GBM, GECAM, GRID,
64
+ [`Einstein Probe`](https://ep.bao.ac.cn/) (WXT/FXT), and
65
+ [`Swift`](https://swift.gsfc.nasa.gov/) (XRT/BAT). It bridges to
66
+ [`HEASoft`](https://heasarc.gsfc.nasa.gov/docs/software/heasoft/) and
67
+ [`gbm_drm_gen`](https://github.com/grburgess/gbm_drm_gen) for mission-specific
68
+ reduction and response generation.
69
+
70
+
71
+ ## Features
72
+
73
+ - **Data retrieval.** Pull event, position, and response files straight
74
+ from mission archives by burst ID, UTC window, or observation ID
75
+ (`gbmRetrieve`, `gecamRetrieve`, `gridRetrieve`, `epRetrieve`,
76
+ `swiftRetrieve`).
77
+ - **Multi-mission event reduction.** One `Event` interface across
78
+ Fermi/GBM TTE, GECAM, GRID, Einstein Probe (WXT/FXT), and Swift
79
+ (XRT/BAT).
80
+ - **Light curves.** Extract and rebin light curves with automatic
81
+ background fitting.
82
+ - **Signal detection.** Bayesian-block signal/background separation with
83
+ three noise regimes — Poisson + polynomial background (`pgSignal`),
84
+ Poisson + supplied background (`ppSignal`), and Gaussian (`ggSignal`).
85
+ - **OGIP spectra.** Generate source and background `PHA`/`PHA2` spectra,
86
+ and — for Fermi/GBM — response matrices via `gbm_drm_gen`.
87
+ - **Timing analysis.** Duration measurements (`T90`/`Txx`) and
88
+ spectral-lag estimation.
89
+ - **Localization & geometry.** Detector geometry, sky maps, and source
90
+ localization.
91
+
92
+
93
+ ## Installation
94
+
95
+ `Heapy` requires Python 3.10 or later and is available on PyPI:
96
+
97
+ ```bash
98
+ pip install heapyx
99
+ ```
100
+
101
+ ### Optional: `HEASoft`
102
+
103
+ For some missions (e.g., `Swift`), `heapy` invokes `HEASoft` tools such as
104
+ `xselect` and `ximage`. Ensure
105
+ [`HEASoft`](https://heasarc.gsfc.nasa.gov/docs/software/heasoft/#install) is
106
+ installed, along with the
107
+ [`Calibration Database`](https://heasarc.gsfc.nasa.gov/docs/heasarc/caldb/install.html)
108
+ (CALDB) for the mission you are processing.
109
+
110
+ ### Optional: Fermi GBM response generator
111
+
112
+ To build response matrices for Fermi/GBM, `heapy` calls
113
+ [`gbm_drm_gen`](https://github.com/grburgess/gbm_drm_gen). The forked
114
+ packages below are fine-tuned for newer `numpy`/`astropy` and use TTE
115
+ instead of CSPEC data:
116
+
117
+ ```bash
118
+ git clone https://github.com/jyangch/responsum.git
119
+ pip3 install ./responsum
120
+
121
+ git clone https://github.com/jyangch/gbmgeometry.git
122
+ pip3 install ./gbmgeometry
123
+
124
+ git clone https://github.com/jyangch/gbm_drm_gen.git
125
+ pip3 install ./gbm_drm_gen
126
+ ```
127
+
128
+
129
+ ## Documentation
130
+
131
+ Browse the [examples](https://github.com/jyangch/heapy/tree/main/examples)
132
+ for typical workflows end to end.
133
+
134
+
135
+ ## Citation
136
+
137
+ If you use `HEAPY` in your research, please include a software citation in
138
+ your reference list and state the version used in your methods section.
139
+ Citation metadata are available in [CITATION.cff](CITATION.cff).
140
+
141
+ Until a DOI-backed release is available, the repository can be cited as:
142
+
143
+ > Yang, J. HEAPY: A Python toolkit for data reduction, temporal analysis, and
144
+ > spectral extraction of X-ray and gamma-ray transients [Computer software].
145
+ > https://github.com/jyangch/heapy
146
+
147
+ ```bibtex
148
+ @software{heapy,
149
+ author = {Yang, Jun},
150
+ title = {{HEAPY}: A Python toolkit for data reduction, temporal analysis, and
151
+ spectral extraction of X-ray and gamma-ray transients},
152
+ url = {https://github.com/jyangch/heapy}
153
+ }
154
+ ```
155
+
156
+ ## License
157
+
158
+ `Heapy` is distributed under the
159
+ [GPL-3.0](https://www.gnu.org/licenses/gpl-3.0-standalone.html) license.
heapyx-0.2.3/README.md ADDED
@@ -0,0 +1,116 @@
1
+ <h1 align="center">HEAPY</h1>
2
+
3
+ <p align="center">
4
+ <strong>A Python toolkit for data reduction, temporal analysis, and spectral extraction of X-ray and gamma-ray transients.</strong>
5
+ </p>
6
+
7
+ <p align="center">
8
+ <a href="https://pypi.org/project/heapyx/"><img alt="PyPI" src="https://img.shields.io/pypi/v/heapyx?color=4F46E5&labelColor=1f2937&logo=pypi&logoColor=white"></a>
9
+ <a href="https://github.com/jyangch/heapy/tree/main/examples"><img alt="Examples" src="https://img.shields.io/badge/docs-examples-06B6D4?labelColor=1f2937"></a>
10
+ <a href="https://www.gnu.org/licenses/gpl-3.0"><img alt="License GPL-3.0" src="https://img.shields.io/badge/license-GPL--3.0-9CA3AF?labelColor=1f2937"></a>
11
+ </p>
12
+
13
+ ---
14
+
15
+ `Heapy` is a Python toolkit for data reduction, temporal analysis, and
16
+ spectral extraction of X-ray and gamma-ray transients. It pulls event and response data from mission
17
+ archives, reduces time-tagged-event (TTE) and image data into light curves
18
+ and OGIP spectra, separates burst signals from fitted backgrounds, and
19
+ measures durations, spectral lags, and source localizations — across
20
+ [`Fermi`](https://gammaray.nsstc.nasa.gov/gbm/)/GBM, GECAM, GRID,
21
+ [`Einstein Probe`](https://ep.bao.ac.cn/) (WXT/FXT), and
22
+ [`Swift`](https://swift.gsfc.nasa.gov/) (XRT/BAT). It bridges to
23
+ [`HEASoft`](https://heasarc.gsfc.nasa.gov/docs/software/heasoft/) and
24
+ [`gbm_drm_gen`](https://github.com/grburgess/gbm_drm_gen) for mission-specific
25
+ reduction and response generation.
26
+
27
+
28
+ ## Features
29
+
30
+ - **Data retrieval.** Pull event, position, and response files straight
31
+ from mission archives by burst ID, UTC window, or observation ID
32
+ (`gbmRetrieve`, `gecamRetrieve`, `gridRetrieve`, `epRetrieve`,
33
+ `swiftRetrieve`).
34
+ - **Multi-mission event reduction.** One `Event` interface across
35
+ Fermi/GBM TTE, GECAM, GRID, Einstein Probe (WXT/FXT), and Swift
36
+ (XRT/BAT).
37
+ - **Light curves.** Extract and rebin light curves with automatic
38
+ background fitting.
39
+ - **Signal detection.** Bayesian-block signal/background separation with
40
+ three noise regimes — Poisson + polynomial background (`pgSignal`),
41
+ Poisson + supplied background (`ppSignal`), and Gaussian (`ggSignal`).
42
+ - **OGIP spectra.** Generate source and background `PHA`/`PHA2` spectra,
43
+ and — for Fermi/GBM — response matrices via `gbm_drm_gen`.
44
+ - **Timing analysis.** Duration measurements (`T90`/`Txx`) and
45
+ spectral-lag estimation.
46
+ - **Localization & geometry.** Detector geometry, sky maps, and source
47
+ localization.
48
+
49
+
50
+ ## Installation
51
+
52
+ `Heapy` requires Python 3.10 or later and is available on PyPI:
53
+
54
+ ```bash
55
+ pip install heapyx
56
+ ```
57
+
58
+ ### Optional: `HEASoft`
59
+
60
+ For some missions (e.g., `Swift`), `heapy` invokes `HEASoft` tools such as
61
+ `xselect` and `ximage`. Ensure
62
+ [`HEASoft`](https://heasarc.gsfc.nasa.gov/docs/software/heasoft/#install) is
63
+ installed, along with the
64
+ [`Calibration Database`](https://heasarc.gsfc.nasa.gov/docs/heasarc/caldb/install.html)
65
+ (CALDB) for the mission you are processing.
66
+
67
+ ### Optional: Fermi GBM response generator
68
+
69
+ To build response matrices for Fermi/GBM, `heapy` calls
70
+ [`gbm_drm_gen`](https://github.com/grburgess/gbm_drm_gen). The forked
71
+ packages below are fine-tuned for newer `numpy`/`astropy` and use TTE
72
+ instead of CSPEC data:
73
+
74
+ ```bash
75
+ git clone https://github.com/jyangch/responsum.git
76
+ pip3 install ./responsum
77
+
78
+ git clone https://github.com/jyangch/gbmgeometry.git
79
+ pip3 install ./gbmgeometry
80
+
81
+ git clone https://github.com/jyangch/gbm_drm_gen.git
82
+ pip3 install ./gbm_drm_gen
83
+ ```
84
+
85
+
86
+ ## Documentation
87
+
88
+ Browse the [examples](https://github.com/jyangch/heapy/tree/main/examples)
89
+ for typical workflows end to end.
90
+
91
+
92
+ ## Citation
93
+
94
+ If you use `HEAPY` in your research, please include a software citation in
95
+ your reference list and state the version used in your methods section.
96
+ Citation metadata are available in [CITATION.cff](CITATION.cff).
97
+
98
+ Until a DOI-backed release is available, the repository can be cited as:
99
+
100
+ > Yang, J. HEAPY: A Python toolkit for data reduction, temporal analysis, and
101
+ > spectral extraction of X-ray and gamma-ray transients [Computer software].
102
+ > https://github.com/jyangch/heapy
103
+
104
+ ```bibtex
105
+ @software{heapy,
106
+ author = {Yang, Jun},
107
+ title = {{HEAPY}: A Python toolkit for data reduction, temporal analysis, and
108
+ spectral extraction of X-ray and gamma-ray transients},
109
+ url = {https://github.com/jyangch/heapy}
110
+ }
111
+ ```
112
+
113
+ ## License
114
+
115
+ `Heapy` is distributed under the
116
+ [GPL-3.0](https://www.gnu.org/licenses/gpl-3.0-standalone.html) license.
@@ -0,0 +1 @@
1
+ __version__ = '0.2.3'
@@ -0,0 +1 @@
1
+ from .__info__ import __version__
@@ -0,0 +1,388 @@
1
+ """Baseline estimators for 1D signals.
2
+
3
+ Exposes a unified :class:`Baseline` facade over several algorithms
4
+ (``drpls``, ``snip``, ``isnip``, ``fabc``, ``goldindec``, ``mixture``).
5
+ The fitted baseline is stored on the instance and can be evaluated at
6
+ arbitrary abscissae via cubic spline interpolation.
7
+ """
8
+
9
+ from astropy.stats import mad_std, sigma_clip
10
+ import numpy as np
11
+ import pybaselines
12
+ from scipy.interpolate import CubicSpline
13
+ import scipy.sparse as sparse
14
+ from scipy.sparse.linalg import spsolve
15
+
16
+
17
+ class Baseline:
18
+ """Fit and evaluate a smooth baseline under a 1D signal.
19
+
20
+ Wraps multiple baseline algorithms behind a single ``fit``/``val``
21
+ interface. The SNIP family uses a Whittaker pre-smoothing step followed
22
+ by symmetric shrinking-window sweeps.
23
+
24
+ Attributes:
25
+ method: Selected baseline algorithm identifier.
26
+ x: Abscissae used for fitting (set by :meth:`fit`).
27
+ y: Ordinates used for fitting (set by :meth:`fit`).
28
+ mo: Baseline values sampled at :attr:`x` (set by :meth:`fit`).
29
+
30
+ Example:
31
+ >>> bl = Baseline.set_method('drpls')
32
+ >>> bl.fit(x, y)
33
+ >>> baseline = bl.val(x_new)
34
+ """
35
+
36
+ def __init__(self, method='drpls'):
37
+ """Store the baseline algorithm identifier.
38
+
39
+ Args:
40
+ method: Algorithm name; one of ``'drpls'``, ``'snip'``,
41
+ ``'isnip'``, ``'fabc'``, ``'goldindec'``, ``'mixture'``.
42
+ """
43
+
44
+ self.method = method
45
+
46
+ @classmethod
47
+ def set_method(cls, method='drpls'):
48
+ """Validate ``method`` and return a configured :class:`Baseline`.
49
+
50
+ Args:
51
+ method: Algorithm name; currently only ``'drpls'`` passes the
52
+ explicit check, other names from :meth:`fit` still work.
53
+
54
+ Returns:
55
+ A new :class:`Baseline` bound to ``method``.
56
+
57
+ Raises:
58
+ ValueError: If ``method`` is not ``'drpls'``.
59
+ """
60
+
61
+ if method == 'drpls':
62
+ pass
63
+ else:
64
+ raise ValueError('invalid method')
65
+
66
+ return cls(method=method)
67
+
68
+ def fit(self, x, y, w=None, lam=None, nk=None, dx=None):
69
+ """Estimate the baseline of ``(x, y)`` using the configured method.
70
+
71
+ Populates :attr:`x`, :attr:`y`, and :attr:`mo`. Defaults for
72
+ ``lam`` and ``nk`` are derived from ``len(x)``.
73
+
74
+ Args:
75
+ x: Monotonic 1D abscissae.
76
+ y: Ordinates matching ``x``.
77
+ w: Per-point weights; defaults to ones.
78
+ lam: Smoothing strength for Whittaker-based methods.
79
+ nk: Number of spline knots for the mixture model.
80
+ dx: Per-point width converting rate variance to count variance;
81
+ scalar or 1D matching ``x``. Defaults to ``x[1] - x[0]``.
82
+
83
+ Raises:
84
+ ValueError: If :attr:`method` is not a recognized algorithm.
85
+ """
86
+
87
+ self.x = np.array(x).astype(float)
88
+ self.y = np.array(y).astype(float)
89
+
90
+ if w is None:
91
+ w = np.ones(len(y))
92
+
93
+ if lam is None:
94
+ lam = 10 ** (4 * (np.log10(len(x)) - 1))
95
+
96
+ if nk is None:
97
+ nk = max(2 * len(x) - 200, 4)
98
+
99
+ if dx is None:
100
+ self.dx = self.x[1] - self.x[0]
101
+ else:
102
+ self.dx = np.array(dx)
103
+ if self.dx.ndim != 0 and self.dx.shape != self.x.shape:
104
+ raise TypeError('if dx is array, expected dx and x to have same length')
105
+
106
+ if self.method == 'snip':
107
+ mo = self.snip(y, x, w=w)
108
+
109
+ elif self.method == 'isnip':
110
+ mo = self.isnip(y, x, w=w)
111
+
112
+ elif self.method == 'drpls':
113
+ mo = pybaselines.whittaker.drpls(y, lam=lam, eta=0.5, weights=w)[0]
114
+
115
+ elif self.method == 'fabc':
116
+ mo = pybaselines.classification.fabc(y, lam=lam, weights=w)[0]
117
+
118
+ elif self.method == 'goldindec':
119
+ mo = pybaselines.polynomial.goldindec(y, x, poly_order=3, peak_ratio=0.1, weights=w)[0]
120
+
121
+ elif self.method == 'mixture':
122
+ mo = pybaselines.spline.mixture_model(
123
+ y, p=0.001, lam=lam, diff_order=2, num_knots=nk, weights=w
124
+ )[0]
125
+
126
+ else:
127
+ raise ValueError('invalid method')
128
+
129
+ self.mo = mo
130
+
131
+ def val(self, x):
132
+ """Evaluate the fitted baseline at ``x`` via cubic spline interpolation.
133
+
134
+ Args:
135
+ x: Query abscissae; values more than one fitted-bin spacing
136
+ outside the fitting range are extrapolated and trigger a
137
+ ``UserWarning``.
138
+
139
+ Returns:
140
+ Interpolated baseline values at ``x``.
141
+ """
142
+
143
+ x = np.asarray(x)
144
+
145
+ interp = CubicSpline(self.x, self.mo, extrapolate=True)
146
+
147
+ return interp(x)
148
+
149
+ def integral(self, x):
150
+ """Evaluate the cumulative integral of the fitted baseline at ``x``.
151
+
152
+ Builds the cubic-spline antiderivative whose value at the
153
+ leftmost fitting abscissa ``self.x[0]`` is 0; integration is
154
+ analytical within the spline's piecewise representation. Useful
155
+ as a ``bkg_integral`` callable for time-rescaling Bayesian
156
+ blocks where only differences enter, so the choice of reference
157
+ point is irrelevant.
158
+
159
+ Args:
160
+ x: Query abscissae; values more than one fitted-bin spacing
161
+ outside the fitting range are extrapolated and trigger a
162
+ ``UserWarning``.
163
+
164
+ Returns:
165
+ Antiderivative values at ``x``.
166
+ """
167
+
168
+ x = np.asarray(x)
169
+
170
+ antider = CubicSpline(self.x, self.mo, extrapolate=True).antiderivative()
171
+
172
+ return antider(x)
173
+
174
+ @staticmethod
175
+ def speyediff(N, d, format='csc'):
176
+ """Build the sparse ``d``-th order finite-difference matrix of size ``N``.
177
+
178
+ Used as the penalty operator in Whittaker smoothing.
179
+
180
+ Args:
181
+ N: Number of samples (rows of the identity before differencing).
182
+ d: Difference order; must be non-negative.
183
+ format: Sparse storage format passed to ``scipy.sparse.diags``.
184
+
185
+ Returns:
186
+ A ``(N - d) x N`` sparse difference matrix.
187
+ """
188
+
189
+ assert d >= 0, 'd must be non-negative'
190
+
191
+ shape = (N - d, N)
192
+ diagonals = np.zeros(2 * d + 1)
193
+ diagonals[d] = 1.0
194
+ for _i in range(d):
195
+ diff = diagonals[:-1] - diagonals[1:]
196
+ diagonals = diff
197
+ offsets = np.arange(d + 1)
198
+ spmat = sparse.diags(diagonals, offsets, shape, format=format)
199
+
200
+ return spmat
201
+
202
+ def whittaker_smooth(self, y, lmbd, d, w):
203
+ """Solve the weighted Whittaker smoothing normal equations.
204
+
205
+ Minimizes ``||W^{1/2} (y - z)||^2 + lmbd * ||D^d z||^2``.
206
+
207
+ Args:
208
+ y: Signal to smooth (1D).
209
+ lmbd: Penalty strength; larger values yield smoother output.
210
+ d: Difference order of the penalty.
211
+ w: Per-point weights matching ``y``.
212
+
213
+ Returns:
214
+ Tuple ``(coefmat, z)`` -- the coefficient matrix and the
215
+ smoothed signal.
216
+ """
217
+
218
+ y = np.asarray(y).ravel()
219
+ m = len(y)
220
+ # E = sparse.eye(m, format='csc')
221
+ D = self.speyediff(m, d, format='csc')
222
+ W = sparse.diags(w, 0, shape=(m, m))
223
+ # D is real, so .conj() is a no-op; plain transpose is enough
224
+ coefmat = W + lmbd * D.T.dot(D)
225
+ z = spsolve(coefmat, W @ y)
226
+
227
+ return coefmat, z
228
+
229
+ def get_smooth(self, y, w=None, d=None, lmbd=None):
230
+ """Iteratively sigma-clip large residuals while Whittaker-smoothing.
231
+
232
+ Runs three passes at ``sigma = 3, 2, 1``. Points flagged as
233
+ outliers have their weights zeroed, which effectively excludes
234
+ peaks from the smooth estimate.
235
+
236
+ Args:
237
+ y: Signal to smooth (1D).
238
+ w: Initial weights; defaults to ones.
239
+ d: Penalty difference order; defaults to ``3``.
240
+ lmbd: Penalty strength; defaults to a length-dependent heuristic.
241
+
242
+ Returns:
243
+ The smoothed signal after outlier rejection.
244
+ """
245
+
246
+ y = np.array(y)
247
+ m = len(y)
248
+ if w is None:
249
+ w = np.ones(m)
250
+ if d is None:
251
+ d = 3
252
+ if lmbd is None:
253
+ lmbd = 10 ** (4 * (np.log10(len(y)) - 1))
254
+ _, z = self.whittaker_smooth(y, lmbd, d, w)
255
+
256
+ cs = y - z
257
+ for sigma in [3, 2, 1]:
258
+ mask = sigma_clip(cs, sigma=sigma, maxiters=5, stdfunc=mad_std).mask
259
+ w[mask] = 0
260
+ _, z = self.whittaker_smooth(y, lmbd, d, w)
261
+ cs = y - z
262
+
263
+ return z
264
+
265
+ def _snip_core(self, y, x, w=None, d=None, lmbd=None, inte=None, pr=None, hwi=None, it=None):
266
+ """Run the SNIP iteration core shared by :meth:`snip` and :meth:`isnip`.
267
+
268
+ Pre-smooths ``y`` with Whittaker smoothing, downsamples into
269
+ ``inte`` bins, runs ``it`` symmetric SNIP sweeps with shrinking
270
+ windows, then fits a cubic polynomial through the envelope.
271
+
272
+ Args:
273
+ y: Signal (1D).
274
+ x: Abscissae matching ``y``; used only for median spacing.
275
+ w: Per-point weights; defaults to ones.
276
+ d: Difference order for the Whittaker pre-smooth.
277
+ lmbd: Penalty strength for the Whittaker pre-smooth.
278
+ inte: Number of SNIP sampling intervals.
279
+ pr: Peak ratio controlling the half window width.
280
+ hwi: Half window width; derived from ``inte`` and ``pr`` if omitted.
281
+ it: Number of SNIP iterations.
282
+
283
+ Returns:
284
+ Tuple ``(y, idx, poly_z)`` -- the input ``y``, the full integer
285
+ index array, and the cubic-fit baseline on the SNIP envelope.
286
+ """
287
+
288
+ y, x = np.asarray(y), np.asarray(x)
289
+ m = len(y)
290
+ if w is None:
291
+ w = np.ones(m)
292
+ z = self.get_smooth(y, w, d, lmbd)
293
+
294
+ # Robust to non-uniform sampling: use median spacing as representative dt
295
+ dt = float(np.median(np.diff(x))) if x.size > 1 else 1.0
296
+ if it is None:
297
+ it = 5
298
+ if inte is None:
299
+ inte = max(round(len(z) * dt / 5), 3)
300
+ if pr is None:
301
+ pr = 0.4
302
+ if hwi is None:
303
+ hwi = max(round(inte / 2 * pr), 1)
304
+
305
+ if it != 1:
306
+ d1 = np.log10(hwi)
307
+ d2 = 0
308
+ win = np.ceil(
309
+ np.concatenate((10 ** (d1 + np.arange(it - 1) * (d2 - d1) / (it - 1)), [d2]))
310
+ )
311
+ win = win.astype(int)
312
+ else:
313
+ win = np.array([hwi], dtype=int)
314
+
315
+ lims = np.linspace(0, z.size - 1, inte + 1)
316
+ lefts = np.ceil(lims[:-1]).astype(int)
317
+ rights = np.floor(lims[1:]).astype(int)
318
+ samp_x = np.round((lefts + rights) * 0.5)
319
+
320
+ bsl_z = np.zeros(inte)
321
+ for i in range(inte):
322
+ bsl_z[i] = z[lefts[i] : rights[i] + 1].mean()
323
+
324
+ # SNIP iteration: symmetric forward + reverse sweeps at shrinking windows
325
+ for i in range(it):
326
+ win0 = win[i]
327
+ for j in range(1, inte - 1):
328
+ v = min(j, win0, inte - j - 1)
329
+ a = bsl_z[j - v : j + v + 1].mean()
330
+ bsl_z[j] = min(a, bsl_z[j])
331
+ for j in range(1, inte - 1):
332
+ k = inte - j - 1
333
+ v = min(j, win0, inte - j - 1)
334
+ a = bsl_z[k - v : k + v + 1].mean()
335
+ bsl_z[k] = min(a, bsl_z[k])
336
+
337
+ samp_x = np.concatenate(([0], samp_x, [z.size - 1]))
338
+ bsl_z = np.concatenate((bsl_z[:1], bsl_z, bsl_z[-1:]))
339
+ idx = np.arange(z.size)
340
+
341
+ poly_fit = np.polyfit(samp_x, bsl_z, deg=3)
342
+ poly_z = np.polyval(poly_fit, idx)
343
+
344
+ return y, idx, poly_z
345
+
346
+ def snip(self, y, x, w=None, d=None, lmbd=None, inte=None, pr=None, hwi=None, it=None):
347
+ """Estimate the baseline via the SNIP algorithm.
348
+
349
+ Args:
350
+ y: Signal (1D).
351
+ x: Abscissae matching ``y``.
352
+ w, d, lmbd, inte, pr, hwi, it: See :meth:`_snip_core`.
353
+
354
+ Returns:
355
+ Baseline sampled on ``arange(len(y))``.
356
+ """
357
+
358
+ _, _, poly_z = self._snip_core(y, x, w, d, lmbd, inte, pr, hwi, it)
359
+
360
+ return poly_z
361
+
362
+ def isnip(self, y, x, w=None, d=None, lmbd=None, inte=None, pr=None, hwi=None, it=None):
363
+ """Estimate the baseline via iteratively refined SNIP.
364
+
365
+ Runs :meth:`_snip_core`, then sigma-clips residuals and re-fits a
366
+ cubic polynomial at ``sigma = 3, 2, 1`` to sharpen the envelope.
367
+
368
+ Args:
369
+ y: Signal (1D).
370
+ x: Abscissae matching ``y``.
371
+ w, d, lmbd, inte, pr, hwi, it: See :meth:`_snip_core`.
372
+
373
+ Returns:
374
+ Refined baseline sampled on ``arange(len(y))``.
375
+ """
376
+
377
+ y, idx, poly_z = self._snip_core(y, x, w, d, lmbd, inte, pr, hwi, it)
378
+
379
+ # Iterative refinement: sigma-clip residuals, re-fit cubic polynomial
380
+ poly_cs = y - poly_z
381
+ for sigma in [3, 2, 1]:
382
+ mask = sigma_clip(poly_cs, sigma=sigma, maxiters=5, stdfunc=mad_std).mask
383
+ keep = ~np.asarray(mask)
384
+ poly_fit = np.polyfit(idx[keep], y[keep], deg=3)
385
+ poly_z = np.polyval(poly_fit, idx)
386
+ poly_cs = y - poly_z
387
+
388
+ return poly_z