heapyx 0.2.0__tar.gz → 0.2.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.
Files changed (73) hide show
  1. {heapyx-0.2.0 → heapyx-0.2.1}/PKG-INFO +3 -2
  2. {heapyx-0.2.0 → heapyx-0.2.1}/README.md +0 -1
  3. heapyx-0.2.1/heapy/__info__.py +1 -0
  4. heapyx-0.2.1/heapy/__init__.py +1 -0
  5. heapyx-0.2.1/heapy/auto/baseline.py +404 -0
  6. heapyx-0.2.1/heapy/auto/polynomial.py +578 -0
  7. heapyx-0.2.1/heapy/auto/signal.py +1418 -0
  8. heapyx-0.2.1/heapy/auto/signal_utils.py +726 -0
  9. heapyx-0.2.1/heapy/data/filefinder.py +296 -0
  10. heapyx-0.2.1/heapy/data/retrieve.py +931 -0
  11. heapyx-0.2.1/heapy/geos/detector.py +132 -0
  12. heapyx-0.2.1/heapy/geos/geometry.py +557 -0
  13. {heapyx-0.2.0 → heapyx-0.2.1}/heapy/geos/localization.py +382 -147
  14. heapyx-0.2.1/heapy/geos/skymap.py +416 -0
  15. heapyx-0.2.1/heapy/pipe/batpipe.py +1174 -0
  16. heapyx-0.2.1/heapy/pipe/event.py +2365 -0
  17. heapyx-0.2.1/heapy/pipe/filter.py +173 -0
  18. heapyx-0.2.1/heapy/pipe/image.py +2035 -0
  19. heapyx-0.2.1/heapy/temp/lag.py +664 -0
  20. heapyx-0.2.1/heapy/temp/mvt.py +646 -0
  21. heapyx-0.2.1/heapy/temp/mvt_cl.py +970 -0
  22. heapyx-0.2.1/heapy/temp/mvt_gm.py +1104 -0
  23. heapyx-0.2.1/heapy/temp/temp_utils.py +347 -0
  24. heapyx-0.2.1/heapy/temp/txx.py +918 -0
  25. heapyx-0.2.1/heapy/util/coord.py +483 -0
  26. heapyx-0.2.1/heapy/util/data.py +785 -0
  27. heapyx-0.2.1/heapy/util/file.py +332 -0
  28. heapyx-0.2.1/heapy/util/significance.py +311 -0
  29. heapyx-0.2.1/heapy/util/time.py +326 -0
  30. heapyx-0.2.1/heapy/util/tools.py +383 -0
  31. {heapyx-0.2.0 → heapyx-0.2.1}/heapyx.egg-info/PKG-INFO +3 -2
  32. {heapyx-0.2.0 → heapyx-0.2.1}/heapyx.egg-info/SOURCES.txt +8 -3
  33. {heapyx-0.2.0 → heapyx-0.2.1}/heapyx.egg-info/requires.txt +2 -0
  34. heapyx-0.2.1/pyproject.toml +35 -0
  35. heapyx-0.2.1/setup.py +53 -0
  36. heapyx-0.2.0/heapy/__info__.py +0 -1
  37. heapyx-0.2.0/heapy/__init__.py +0 -1
  38. heapyx-0.2.0/heapy/auto/baseline.py +0 -306
  39. heapyx-0.2.0/heapy/auto/ggsignal.py +0 -264
  40. heapyx-0.2.0/heapy/auto/polybase.py +0 -686
  41. heapyx-0.2.0/heapy/auto/polynomial.py +0 -291
  42. heapyx-0.2.0/heapy/auto/ppsignal.py +0 -314
  43. heapyx-0.2.0/heapy/data/filefinder.py +0 -217
  44. heapyx-0.2.0/heapy/data/retrieve.py +0 -622
  45. heapyx-0.2.0/heapy/geos/detector.py +0 -68
  46. heapyx-0.2.0/heapy/geos/geometry.py +0 -347
  47. heapyx-0.2.0/heapy/geos/skymap.py +0 -190
  48. heapyx-0.2.0/heapy/pipe/batpipe.py +0 -828
  49. heapyx-0.2.0/heapy/pipe/event.py +0 -1934
  50. heapyx-0.2.0/heapy/pipe/filter.py +0 -77
  51. heapyx-0.2.0/heapy/pipe/image.py +0 -1709
  52. heapyx-0.2.0/heapy/temp/lag.py +0 -402
  53. heapyx-0.2.0/heapy/temp/txx.py +0 -909
  54. heapyx-0.2.0/heapy/util/coord.py +0 -444
  55. heapyx-0.2.0/heapy/util/data.py +0 -750
  56. heapyx-0.2.0/heapy/util/file.py +0 -308
  57. heapyx-0.2.0/heapy/util/significance.py +0 -240
  58. heapyx-0.2.0/heapy/util/time.py +0 -368
  59. heapyx-0.2.0/setup.py +0 -53
  60. {heapyx-0.2.0 → heapyx-0.2.1}/LICENSE +0 -0
  61. {heapyx-0.2.0 → heapyx-0.2.1}/heapy/auto/__init__.py +0 -0
  62. {heapyx-0.2.0 → heapyx-0.2.1}/heapy/data/__init__.py +0 -0
  63. {heapyx-0.2.0 → heapyx-0.2.1}/heapy/docs/McIlwainL_coeffs/McIlwainL_Coeffs.npy +0 -0
  64. {heapyx-0.2.0 → heapyx-0.2.1}/heapy/docs/psf_model/fxt_psf.cod +0 -0
  65. {heapyx-0.2.0 → heapyx-0.2.1}/heapy/docs/psf_model/fxt_psf.dat +0 -0
  66. {heapyx-0.2.0 → heapyx-0.2.1}/heapy/docs/psf_model/xrt_psf.cod +0 -0
  67. {heapyx-0.2.0 → heapyx-0.2.1}/heapy/geos/__init__.py +0 -0
  68. {heapyx-0.2.0 → heapyx-0.2.1}/heapy/pipe/__init__.py +0 -0
  69. {heapyx-0.2.0 → heapyx-0.2.1}/heapy/temp/__init__.py +0 -0
  70. {heapyx-0.2.0 → heapyx-0.2.1}/heapy/util/__init__.py +0 -0
  71. {heapyx-0.2.0 → heapyx-0.2.1}/heapyx.egg-info/dependency_links.txt +0 -0
  72. {heapyx-0.2.0 → heapyx-0.2.1}/heapyx.egg-info/top_level.txt +0 -0
  73. {heapyx-0.2.0 → heapyx-0.2.1}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: heapyx
3
- Version: 0.2.0
3
+ Version: 0.2.1
4
4
  Summary: High-energy (X-ray and gamma-ray) astronomical data analysis tools
5
5
  Home-page: https://github.com/jyangch/heapy
6
6
  Author: Jun Yang
@@ -22,7 +22,9 @@ Requires-Dist: astropy>=5.2.2
22
22
  Requires-Dist: matplotlib>=3.2.1
23
23
  Requires-Dist: tqdm>=4.64.1
24
24
  Requires-Dist: plotly>=5.22.0
25
+ Requires-Dist: kaleido>=0.2.1
25
26
  Requires-Dist: pybaselines>=1.1.0
27
+ Requires-Dist: pycwt>=0.3
26
28
  Dynamic: author
27
29
  Dynamic: author-email
28
30
  Dynamic: classifier
@@ -71,7 +73,6 @@ _Heapy_ is available via `pip`:
71
73
  ```bash
72
74
  $ pip3 install heapyx
73
75
  ```
74
- **NOTE**: The package name of _heapy_ in pypi is registered as `heapyx` rather than `heapy`, as the latter has already been taken.
75
76
 
76
77
 
77
78
  ## Documentation
@@ -33,7 +33,6 @@ _Heapy_ is available via `pip`:
33
33
  ```bash
34
34
  $ pip3 install heapyx
35
35
  ```
36
- **NOTE**: The package name of _heapy_ in pypi is registered as `heapyx` rather than `heapy`, as the latter has already been taken.
37
36
 
38
37
 
39
38
  ## Documentation
@@ -0,0 +1 @@
1
+ __version__ = '0.2.1'
@@ -0,0 +1 @@
1
+ from .__info__ import __version__
@@ -0,0 +1,404 @@
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
+ import warnings
10
+
11
+ from astropy.stats import mad_std, sigma_clip
12
+ import numpy as np
13
+ import pybaselines
14
+ from scipy.interpolate import CubicSpline
15
+ import scipy.sparse as sparse
16
+ from scipy.sparse.linalg import spsolve
17
+
18
+
19
+ class Baseline:
20
+ """Fit and evaluate a smooth baseline under a 1D signal.
21
+
22
+ Wraps multiple baseline algorithms behind a single ``fit``/``val``
23
+ interface. The SNIP family uses a Whittaker pre-smoothing step followed
24
+ by symmetric shrinking-window sweeps.
25
+
26
+ Attributes:
27
+ method: Selected baseline algorithm identifier.
28
+ x: Abscissae used for fitting (set by :meth:`fit`).
29
+ y: Ordinates used for fitting (set by :meth:`fit`).
30
+ mo: Baseline values sampled at :attr:`x` (set by :meth:`fit`).
31
+
32
+ Example:
33
+ >>> bl = Baseline.set_method('drpls')
34
+ >>> bl.fit(x, y)
35
+ >>> baseline = bl.val(x_new)
36
+ """
37
+
38
+ def __init__(self, method='drpls'):
39
+ """Store the baseline algorithm identifier.
40
+
41
+ Args:
42
+ method: Algorithm name; one of ``'drpls'``, ``'snip'``,
43
+ ``'isnip'``, ``'fabc'``, ``'goldindec'``, ``'mixture'``.
44
+ """
45
+
46
+ self.method = method
47
+
48
+ @classmethod
49
+ def set_method(cls, method='drpls'):
50
+ """Validate ``method`` and return a configured :class:`Baseline`.
51
+
52
+ Args:
53
+ method: Algorithm name; currently only ``'drpls'`` passes the
54
+ explicit check, other names from :meth:`fit` still work.
55
+
56
+ Returns:
57
+ A new :class:`Baseline` bound to ``method``.
58
+
59
+ Raises:
60
+ ValueError: If ``method`` is not ``'drpls'``.
61
+ """
62
+
63
+ if method == 'drpls':
64
+ pass
65
+ else:
66
+ raise ValueError('invalid method')
67
+
68
+ return cls(method=method)
69
+
70
+ def fit(self, x, y, w=None, lam=None, nk=None, dx=None):
71
+ """Estimate the baseline of ``(x, y)`` using the configured method.
72
+
73
+ Populates :attr:`x`, :attr:`y`, and :attr:`mo`. Defaults for
74
+ ``lam`` and ``nk`` are derived from ``len(x)``.
75
+
76
+ Args:
77
+ x: Monotonic 1D abscissae.
78
+ y: Ordinates matching ``x``.
79
+ w: Per-point weights; defaults to ones.
80
+ lam: Smoothing strength for Whittaker-based methods.
81
+ nk: Number of spline knots for the mixture model.
82
+ dx: Per-point width converting rate variance to count variance;
83
+ scalar or 1D matching ``x``. Defaults to ``x[1] - x[0]``.
84
+
85
+ Raises:
86
+ ValueError: If :attr:`method` is not a recognized algorithm.
87
+ """
88
+
89
+ self.x = np.array(x).astype(float)
90
+ self.y = np.array(y).astype(float)
91
+
92
+ if w is None:
93
+ w = np.ones(len(y))
94
+
95
+ if lam is None:
96
+ lam = 10 ** (4 * (np.log10(len(x)) - 1))
97
+
98
+ if nk is None:
99
+ nk = max(2 * len(x) - 200, 4)
100
+
101
+ if dx is None:
102
+ self.dx = self.x[1] - self.x[0]
103
+ else:
104
+ self.dx = np.array(dx)
105
+ if self.dx.ndim != 0 and self.dx.shape != self.x.shape:
106
+ raise TypeError('if dx is array, expected dx and x to have same length')
107
+
108
+ if self.method == 'snip':
109
+ mo = self.snip(y, x, w=w)
110
+
111
+ elif self.method == 'isnip':
112
+ mo = self.isnip(y, x, w=w)
113
+
114
+ elif self.method == 'drpls':
115
+ mo = pybaselines.whittaker.drpls(y, lam=lam, eta=0.5, weights=w)[0]
116
+
117
+ elif self.method == 'fabc':
118
+ mo = pybaselines.classification.fabc(y, lam=lam, weights=w)[0]
119
+
120
+ elif self.method == 'goldindec':
121
+ mo = pybaselines.polynomial.goldindec(y, x, poly_order=3, peak_ratio=0.1, weights=w)[0]
122
+
123
+ elif self.method == 'mixture':
124
+ mo = pybaselines.spline.mixture_model(
125
+ y, p=0.001, lam=lam, diff_order=2, num_knots=nk, weights=w
126
+ )[0]
127
+
128
+ else:
129
+ raise ValueError('invalid method')
130
+
131
+ self.mo = mo
132
+
133
+ def val(self, x):
134
+ """Evaluate the fitted baseline at ``x`` via cubic spline interpolation.
135
+
136
+ Args:
137
+ x: Query abscissae; values outside the fitting range are
138
+ extrapolated and trigger a ``UserWarning``.
139
+
140
+ Returns:
141
+ Interpolated baseline values at ``x``.
142
+ """
143
+
144
+ x = np.asarray(x)
145
+
146
+ if min(x) < min(self.x - self.dx / 1.8):
147
+ msg = f'Extrapolation may be imprecise: {min(x):f} < {min(self.x - self.dx / 1.8):f}'
148
+ warnings.warn(msg, UserWarning, stacklevel=2)
149
+
150
+ if max(x) > max(self.x + self.dx / 1.8):
151
+ msg = f'Extrapolation may be imprecise: {max(x):f} > {max(self.x + self.dx / 1.8):f}'
152
+ warnings.warn(msg, UserWarning, stacklevel=2)
153
+
154
+ interp = CubicSpline(self.x, self.mo, extrapolate=True)
155
+
156
+ return interp(x)
157
+
158
+ def integral(self, x):
159
+ """Evaluate the cumulative integral of the fitted baseline at ``x``.
160
+
161
+ Builds the cubic-spline antiderivative whose value at the
162
+ leftmost fitting abscissa ``self.x[0]`` is 0; integration is
163
+ analytical within the spline's piecewise representation. Useful
164
+ as a ``bkg_integral`` callable for time-rescaling Bayesian
165
+ blocks where only differences enter, so the choice of reference
166
+ point is irrelevant.
167
+
168
+ Args:
169
+ x: Query abscissae; values outside the fitting range are
170
+ extrapolated and trigger a ``UserWarning``.
171
+
172
+ Returns:
173
+ Antiderivative values at ``x``.
174
+ """
175
+
176
+ x = np.asarray(x)
177
+
178
+ if min(x) < min(self.x - self.dx / 1.8):
179
+ msg = f'Extrapolation may be imprecise: {min(x):f} < {min(self.x - self.dx / 1.8):f}'
180
+ warnings.warn(msg, UserWarning, stacklevel=2)
181
+
182
+ if max(x) > max(self.x + self.dx / 1.8):
183
+ msg = f'Extrapolation may be imprecise: {max(x):f} > {max(self.x + self.dx / 1.8):f}'
184
+ warnings.warn(msg, UserWarning, stacklevel=2)
185
+
186
+ antider = CubicSpline(self.x, self.mo, extrapolate=True).antiderivative()
187
+
188
+ return antider(x)
189
+
190
+ @staticmethod
191
+ def speyediff(N, d, format='csc'):
192
+ """Build the sparse ``d``-th order finite-difference matrix of size ``N``.
193
+
194
+ Used as the penalty operator in Whittaker smoothing.
195
+
196
+ Args:
197
+ N: Number of samples (rows of the identity before differencing).
198
+ d: Difference order; must be non-negative.
199
+ format: Sparse storage format passed to ``scipy.sparse.diags``.
200
+
201
+ Returns:
202
+ A ``(N - d) x N`` sparse difference matrix.
203
+ """
204
+
205
+ assert d >= 0, 'd must be non-negative'
206
+
207
+ shape = (N - d, N)
208
+ diagonals = np.zeros(2 * d + 1)
209
+ diagonals[d] = 1.0
210
+ for _i in range(d):
211
+ diff = diagonals[:-1] - diagonals[1:]
212
+ diagonals = diff
213
+ offsets = np.arange(d + 1)
214
+ spmat = sparse.diags(diagonals, offsets, shape, format=format)
215
+
216
+ return spmat
217
+
218
+ def whittaker_smooth(self, y, lmbd, d, w):
219
+ """Solve the weighted Whittaker smoothing normal equations.
220
+
221
+ Minimizes ``||W^{1/2} (y - z)||^2 + lmbd * ||D^d z||^2``.
222
+
223
+ Args:
224
+ y: Signal to smooth (1D).
225
+ lmbd: Penalty strength; larger values yield smoother output.
226
+ d: Difference order of the penalty.
227
+ w: Per-point weights matching ``y``.
228
+
229
+ Returns:
230
+ Tuple ``(coefmat, z)`` -- the coefficient matrix and the
231
+ smoothed signal.
232
+ """
233
+
234
+ y = np.asarray(y).ravel()
235
+ m = len(y)
236
+ # E = sparse.eye(m, format='csc')
237
+ D = self.speyediff(m, d, format='csc')
238
+ W = sparse.diags(w, 0, shape=(m, m))
239
+ # D is real, so .conj() is a no-op; plain transpose is enough
240
+ coefmat = W + lmbd * D.T.dot(D)
241
+ z = spsolve(coefmat, W @ y)
242
+
243
+ return coefmat, z
244
+
245
+ def get_smooth(self, y, w=None, d=None, lmbd=None):
246
+ """Iteratively sigma-clip large residuals while Whittaker-smoothing.
247
+
248
+ Runs three passes at ``sigma = 3, 2, 1``. Points flagged as
249
+ outliers have their weights zeroed, which effectively excludes
250
+ peaks from the smooth estimate.
251
+
252
+ Args:
253
+ y: Signal to smooth (1D).
254
+ w: Initial weights; defaults to ones.
255
+ d: Penalty difference order; defaults to ``3``.
256
+ lmbd: Penalty strength; defaults to a length-dependent heuristic.
257
+
258
+ Returns:
259
+ The smoothed signal after outlier rejection.
260
+ """
261
+
262
+ y = np.array(y)
263
+ m = len(y)
264
+ if w is None:
265
+ w = np.ones(m)
266
+ if d is None:
267
+ d = 3
268
+ if lmbd is None:
269
+ lmbd = 10 ** (4 * (np.log10(len(y)) - 1))
270
+ _, z = self.whittaker_smooth(y, lmbd, d, w)
271
+
272
+ cs = y - z
273
+ for sigma in [3, 2, 1]:
274
+ mask = sigma_clip(cs, sigma=sigma, maxiters=5, stdfunc=mad_std).mask
275
+ w[mask] = 0
276
+ _, z = self.whittaker_smooth(y, lmbd, d, w)
277
+ cs = y - z
278
+
279
+ return z
280
+
281
+ def _snip_core(self, y, x, w=None, d=None, lmbd=None, inte=None, pr=None, hwi=None, it=None):
282
+ """Run the SNIP iteration core shared by :meth:`snip` and :meth:`isnip`.
283
+
284
+ Pre-smooths ``y`` with Whittaker smoothing, downsamples into
285
+ ``inte`` bins, runs ``it`` symmetric SNIP sweeps with shrinking
286
+ windows, then fits a cubic polynomial through the envelope.
287
+
288
+ Args:
289
+ y: Signal (1D).
290
+ x: Abscissae matching ``y``; used only for median spacing.
291
+ w: Per-point weights; defaults to ones.
292
+ d: Difference order for the Whittaker pre-smooth.
293
+ lmbd: Penalty strength for the Whittaker pre-smooth.
294
+ inte: Number of SNIP sampling intervals.
295
+ pr: Peak ratio controlling the half window width.
296
+ hwi: Half window width; derived from ``inte`` and ``pr`` if omitted.
297
+ it: Number of SNIP iterations.
298
+
299
+ Returns:
300
+ Tuple ``(y, idx, poly_z)`` -- the input ``y``, the full integer
301
+ index array, and the cubic-fit baseline on the SNIP envelope.
302
+ """
303
+
304
+ y, x = np.asarray(y), np.asarray(x)
305
+ m = len(y)
306
+ if w is None:
307
+ w = np.ones(m)
308
+ z = self.get_smooth(y, w, d, lmbd)
309
+
310
+ # Robust to non-uniform sampling: use median spacing as representative dt
311
+ dt = float(np.median(np.diff(x))) if x.size > 1 else 1.0
312
+ if it is None:
313
+ it = 5
314
+ if inte is None:
315
+ inte = max(round(len(z) * dt / 5), 3)
316
+ if pr is None:
317
+ pr = 0.4
318
+ if hwi is None:
319
+ hwi = max(round(inte / 2 * pr), 1)
320
+
321
+ if it != 1:
322
+ d1 = np.log10(hwi)
323
+ d2 = 0
324
+ win = np.ceil(
325
+ np.concatenate((10 ** (d1 + np.arange(it - 1) * (d2 - d1) / (it - 1)), [d2]))
326
+ )
327
+ win = win.astype(int)
328
+ else:
329
+ win = np.array([hwi], dtype=int)
330
+
331
+ lims = np.linspace(0, z.size - 1, inte + 1)
332
+ lefts = np.ceil(lims[:-1]).astype(int)
333
+ rights = np.floor(lims[1:]).astype(int)
334
+ samp_x = np.round((lefts + rights) * 0.5)
335
+
336
+ bsl_z = np.zeros(inte)
337
+ for i in range(inte):
338
+ bsl_z[i] = z[lefts[i] : rights[i] + 1].mean()
339
+
340
+ # SNIP iteration: symmetric forward + reverse sweeps at shrinking windows
341
+ for i in range(it):
342
+ win0 = win[i]
343
+ for j in range(1, inte - 1):
344
+ v = min(j, win0, inte - j - 1)
345
+ a = bsl_z[j - v : j + v + 1].mean()
346
+ bsl_z[j] = min(a, bsl_z[j])
347
+ for j in range(1, inte - 1):
348
+ k = inte - j - 1
349
+ v = min(j, win0, inte - j - 1)
350
+ a = bsl_z[k - v : k + v + 1].mean()
351
+ bsl_z[k] = min(a, bsl_z[k])
352
+
353
+ samp_x = np.concatenate(([0], samp_x, [z.size - 1]))
354
+ bsl_z = np.concatenate((bsl_z[:1], bsl_z, bsl_z[-1:]))
355
+ idx = np.arange(z.size)
356
+
357
+ poly_fit = np.polyfit(samp_x, bsl_z, deg=3)
358
+ poly_z = np.polyval(poly_fit, idx)
359
+
360
+ return y, idx, poly_z
361
+
362
+ def snip(self, y, x, w=None, d=None, lmbd=None, inte=None, pr=None, hwi=None, it=None):
363
+ """Estimate the baseline via the SNIP algorithm.
364
+
365
+ Args:
366
+ y: Signal (1D).
367
+ x: Abscissae matching ``y``.
368
+ w, d, lmbd, inte, pr, hwi, it: See :meth:`_snip_core`.
369
+
370
+ Returns:
371
+ Baseline sampled on ``arange(len(y))``.
372
+ """
373
+
374
+ _, _, poly_z = self._snip_core(y, x, w, d, lmbd, inte, pr, hwi, it)
375
+
376
+ return poly_z
377
+
378
+ def isnip(self, y, x, w=None, d=None, lmbd=None, inte=None, pr=None, hwi=None, it=None):
379
+ """Estimate the baseline via iteratively refined SNIP.
380
+
381
+ Runs :meth:`_snip_core`, then sigma-clips residuals and re-fits a
382
+ cubic polynomial at ``sigma = 3, 2, 1`` to sharpen the envelope.
383
+
384
+ Args:
385
+ y: Signal (1D).
386
+ x: Abscissae matching ``y``.
387
+ w, d, lmbd, inte, pr, hwi, it: See :meth:`_snip_core`.
388
+
389
+ Returns:
390
+ Refined baseline sampled on ``arange(len(y))``.
391
+ """
392
+
393
+ y, idx, poly_z = self._snip_core(y, x, w, d, lmbd, inte, pr, hwi, it)
394
+
395
+ # Iterative refinement: sigma-clip residuals, re-fit cubic polynomial
396
+ poly_cs = y - poly_z
397
+ for sigma in [3, 2, 1]:
398
+ mask = sigma_clip(poly_cs, sigma=sigma, maxiters=5, stdfunc=mad_std).mask
399
+ keep = ~np.asarray(mask)
400
+ poly_fit = np.polyfit(idx[keep], y[keep], deg=3)
401
+ poly_z = np.polyval(poly_fit, idx)
402
+ poly_cs = y - poly_z
403
+
404
+ return poly_z