aspcap 0.2.0__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.
aspcap/spectrum.py ADDED
@@ -0,0 +1,551 @@
1
+ """Lightweight multi-order spectra, adapted from Doppler's Spec1D design.
2
+
3
+ Arrays follow Doppler's convention: one-dimensional for a single order and
4
+ ``(maximum_pixels, orders)`` otherwise. ``mask=True`` always means unusable.
5
+ The implementation is independent of Doppler's fitting, LSF and model loaders.
6
+ See LICENSE-DOPPLER for the original source notice.
7
+ """
8
+
9
+ from copy import deepcopy
10
+ import numpy as np
11
+
12
+
13
+ def _orders(value, name):
14
+ if isinstance(value, (list, tuple)) and value and np.ndim(value[0]) > 0:
15
+ arrays = [np.asarray(v) for v in value]
16
+ else:
17
+ array = np.asarray(value)
18
+ if array.ndim == 1:
19
+ arrays = [array]
20
+ elif array.ndim == 2 and array.shape[1] > 0:
21
+ arrays = [array[:, i] for i in range(array.shape[1])]
22
+ else:
23
+ raise ValueError(f"{name} must be one-dimensional or (pixels, orders)")
24
+ if any(a.ndim != 1 for a in arrays):
25
+ raise ValueError(f"{name} must contain one-dimensional orders")
26
+ return arrays
27
+
28
+
29
+ def _pack(arrays, shape, fill, dtype):
30
+ out = np.full(shape, fill, dtype=dtype)
31
+ for i, array in enumerate(arrays):
32
+ if out.ndim == 1:
33
+ out[: len(array)] = array
34
+ else:
35
+ out[: len(array), i] = array
36
+ return out
37
+
38
+
39
+ class Spec1D:
40
+ """Store one or more spectral orders without fitting-model dependencies.
41
+
42
+ Parameters
43
+ ----------
44
+ flux : array-like or sequence of arrays
45
+ One order, a ``(pixels, orders)`` array, or unequal-length order arrays.
46
+ err, wave, mask, bitmask : array-like, optional
47
+ Matching uncertainties, wavelengths, bad-pixel flags and integer flags.
48
+ Errors are one-sigma standard deviations. True mask values are bad.
49
+ Nonfinite flux, invalid wavelengths, invalid supplied errors and padded
50
+ samples are automatically masked. No uncertainty is invented if absent.
51
+ numpix : sequence of int, optional
52
+ Valid extent of each order in rectangular input. If omitted, trailing
53
+ invalid wavelengths are treated as padding; interior defects stay masked.
54
+ wavevac : bool, optional
55
+ Whether wavelengths are in vacuum. This is metadata; assigning it does
56
+ not convert the coordinates. Units/frame conversion is explicitly external.
57
+ wave_unit, flux_unit : object, optional
58
+ Unit metadata; numerical arrays are not converted automatically.
59
+ head, instrument, filename, metadata, lsf : optional
60
+ Observation metadata. LSF information is optional opaque metadata; this
61
+ class does not construct, convolve or interpret an LSF model.
62
+
63
+ Notes
64
+ -----
65
+ Order selection and ``copy`` return independent arrays. Public arrays are
66
+ mutable; call ``clear_continuum`` after editing data with a cached continuum.
67
+ This intentionally implements the data interface, not every Doppler method.
68
+ """
69
+
70
+ def __init__(
71
+ self,
72
+ flux,
73
+ err=None,
74
+ wave=None,
75
+ mask=None,
76
+ bitmask=None,
77
+ *,
78
+ numpix=None,
79
+ wavevac=True,
80
+ wave_unit="Angstrom",
81
+ flux_unit=None,
82
+ head=None,
83
+ instrument=None,
84
+ filename=None,
85
+ metadata=None,
86
+ lsf=None,
87
+ ):
88
+ fs = _orders(flux, "flux")
89
+ lengths = np.array([len(a) for a in fs], dtype=int)
90
+ shape = (int(max(lengths)),) if len(fs) == 1 else (int(max(lengths)), len(fs))
91
+
92
+ def matching(value, name, fill, dtype):
93
+ if value is None:
94
+ return None
95
+ arrays = _orders(value, name)
96
+ if len(arrays) != len(fs) or any(
97
+ len(a) != n for a, n in zip(arrays, lengths)
98
+ ):
99
+ raise ValueError(f"{name} must match the flux order lengths")
100
+ return _pack(arrays, shape, fill, dtype)
101
+
102
+ self.flux = _pack(fs, shape, np.nan, float)
103
+ self.err = matching(err, "err", np.inf, float)
104
+ self.wave = matching(wave, "wave", 0.0, float)
105
+ self.mask = matching(mask, "mask", True, bool)
106
+ if self.mask is None:
107
+ self.mask = _pack([np.zeros(n, bool) for n in lengths], shape, True, bool)
108
+ if bitmask is not None and any(
109
+ a.dtype.kind not in "iu" for a in _orders(bitmask, "bitmask")
110
+ ):
111
+ raise ValueError("bitmask must contain integers")
112
+ bitdtype = (
113
+ np.result_type(*[a.dtype for a in _orders(bitmask, "bitmask")])
114
+ if bitmask is not None
115
+ else np.dtype(np.int64)
116
+ )
117
+ if bitdtype.kind not in "iu":
118
+ raise ValueError(
119
+ "Mixed bitmask types cannot be represented without precision loss"
120
+ )
121
+ self.bitmask = matching(bitmask, "bitmask", 0, bitdtype)
122
+ if numpix is None:
123
+ self.numpix = lengths.copy()
124
+ if self.wave is not None:
125
+ for i in range(len(fs)):
126
+ w = self._column(self.wave, i)
127
+ good = np.flatnonzero(np.isfinite(w) & (w > 0))
128
+ self.numpix[i] = good[-1] + 1 if len(good) else 0
129
+ else:
130
+ counts = np.atleast_1d(np.asarray(numpix))
131
+ if (
132
+ counts.shape != lengths.shape
133
+ or not np.all(np.isfinite(counts))
134
+ or np.any(counts != np.floor(counts))
135
+ ):
136
+ raise ValueError("numpix must contain one integer per order")
137
+ if np.any(counts < 0) or np.any(counts > lengths):
138
+ raise ValueError("numpix lies outside the supplied order lengths")
139
+ self.numpix = counts.astype(int)
140
+ self.mask |= ~np.isfinite(self.flux)
141
+ if self.wave is not None:
142
+ self.mask |= ~np.isfinite(self.wave) | (self.wave <= 0)
143
+ if self.err is not None:
144
+ self.mask |= ~np.isfinite(self.err) | (self.err <= 0)
145
+ for i, count in enumerate(self.numpix):
146
+ self._column(self.mask, i)[count:] = True
147
+ self.wavevac = bool(wavevac)
148
+ self.wave_unit, self.flux_unit = wave_unit, flux_unit
149
+ self.head, self.instrument, self.filename = deepcopy(head), instrument, filename
150
+ self.metadata, self.lsf = deepcopy(metadata or {}), deepcopy(lsf)
151
+ self.normalized = False
152
+ self._cont = None
153
+ self._continuum_func = None
154
+ self.continuum_history = []
155
+ self._native_wave = None
156
+ self._native_indices = None
157
+
158
+ @staticmethod
159
+ def _column(array, order):
160
+ return array if array.ndim == 1 else array[:, order]
161
+
162
+ @property
163
+ def shape(self):
164
+ return self.flux.shape
165
+
166
+ @property
167
+ def ndim(self):
168
+ return self.flux.ndim
169
+
170
+ @property
171
+ def npix(self):
172
+ return self.shape[0]
173
+
174
+ @property
175
+ def norder(self):
176
+ return 1 if self.ndim == 1 else self.shape[1]
177
+
178
+ @property
179
+ def size(self):
180
+ """Number of samples within order extents, including masked samples."""
181
+ return int(sum(self.numpix))
182
+
183
+ @property
184
+ def valid(self):
185
+ """Current usable pixels, including edits to data and order extents."""
186
+ good = ~self.mask & np.isfinite(self.flux)
187
+ if self.wave is not None:
188
+ good &= np.isfinite(self.wave) & (self.wave > 0)
189
+ if self.err is not None:
190
+ good &= np.isfinite(self.err) & (self.err > 0)
191
+ for i, count in enumerate(self.numpix):
192
+ self._column(good, i)[count:] = False
193
+ return good
194
+
195
+ @property
196
+ def snr(self):
197
+ if self.err is None:
198
+ return None
199
+ good = self.valid
200
+ return (
201
+ float(np.median(self.flux[good] / self.err[good]))
202
+ if np.any(good)
203
+ else np.nan
204
+ )
205
+
206
+ def __len__(self):
207
+ return self.norder
208
+
209
+ def __iter__(self):
210
+ return (self[i] for i in range(self.norder))
211
+
212
+ def __array__(self, dtype=None, copy=None):
213
+ """Expose flux to NumPy, following its optional copy contract."""
214
+ if copy is False and dtype is not None and np.dtype(dtype) != self.flux.dtype:
215
+ raise ValueError("Cannot change dtype without copying")
216
+ array = np.asarray(self.flux, dtype=dtype)
217
+ return array.copy() if copy else array
218
+
219
+ def __repr__(self):
220
+ return f"Spec1D(norder={self.norder}, numpix={self.numpix.tolist()}, normalized={self.normalized})"
221
+
222
+ def copy(self):
223
+ """Deep-copy data, masks, continuum state and metadata."""
224
+ return deepcopy(self)
225
+
226
+ def __getitem__(self, index):
227
+ """Copy an order, order slice, or ``spectrum[pixel_slice, order]``.
228
+
229
+ A slice of a single-order spectrum selects pixels. All results are
230
+ independent copies, unlike a NumPy view. Native pixel mappings survive.
231
+ """
232
+ pixels = slice(None)
233
+ if isinstance(index, tuple):
234
+ pixels, index = index
235
+ if not isinstance(pixels, slice) or not isinstance(
236
+ index, (int, np.integer)
237
+ ):
238
+ raise IndexError("Use a pixel slice and an integer order")
239
+ elif isinstance(index, slice) and self.norder == 1:
240
+ pixels, index = index, 0
241
+ selected = np.arange(self.norder)[index]
242
+ selected = np.atleast_1d(selected)
243
+ if not len(selected):
244
+ raise IndexError("No orders selected")
245
+ arrays = {}
246
+ for name in ("flux", "wave", "err", "mask", "bitmask"):
247
+ value = getattr(self, name)
248
+ arrays[name] = (
249
+ None
250
+ if value is None
251
+ else [
252
+ self._column(value, i)[: self.numpix[i]][pixels].copy()
253
+ for i in selected
254
+ ]
255
+ )
256
+ out = Spec1D(
257
+ **arrays,
258
+ wavevac=self.wavevac,
259
+ wave_unit=self.wave_unit,
260
+ flux_unit=self.flux_unit,
261
+ head=self.head,
262
+ instrument=self.instrument,
263
+ filename=self.filename,
264
+ metadata=self.metadata,
265
+ lsf=self.lsf,
266
+ )
267
+ for name in ("_flux", "_err"):
268
+ value = getattr(self, name, None)
269
+ if value is not None:
270
+ setattr(
271
+ out,
272
+ name,
273
+ _pack(
274
+ [
275
+ self._column(value, i)[: self.numpix[i]][pixels]
276
+ for i in selected
277
+ ],
278
+ out.shape,
279
+ np.nan,
280
+ float,
281
+ ),
282
+ )
283
+ out.normalized = self.normalized
284
+ if hasattr(self, "_flux_unit"):
285
+ out._flux_unit = deepcopy(self._flux_unit)
286
+ out._continuum_func = self._continuum_func
287
+ out.continuum_history = deepcopy(self.continuum_history)
288
+ if self._cont is not None:
289
+ out.cont = _pack(
290
+ [
291
+ self._column(self._cont, i)[: self.numpix[i]][pixels]
292
+ for i in selected
293
+ ],
294
+ out.shape,
295
+ np.nan,
296
+ float,
297
+ )
298
+ if self._native_indices is not None:
299
+ out._native_wave = self._native_wave.copy()
300
+ out._native_indices = [
301
+ self._native_indices[i][pixels].copy() for i in selected
302
+ ]
303
+ return out
304
+
305
+ @property
306
+ def continuum_func(self):
307
+ """Optional callable ``function(spec, **options)``; changing it clears the cache."""
308
+ return self._continuum_func
309
+
310
+ @continuum_func.setter
311
+ def continuum_func(self, value):
312
+ if value is not None and not callable(value):
313
+ raise TypeError("continuum_func must be callable or None")
314
+ self._continuum_func = value
315
+ self.clear_continuum()
316
+
317
+ def clear_continuum(self):
318
+ """Invalidate a cached estimate after changes to raw data or settings."""
319
+ self._cont = None
320
+
321
+ @property
322
+ def cont(self):
323
+ """Cached external continuum, computed lazily when first requested."""
324
+ if self._cont is None:
325
+ from .continuum import fit
326
+
327
+ value = self.continuum_func(self) if self.continuum_func else fit(self)
328
+ self.cont = value.continuum if hasattr(value, "continuum") else value
329
+ return self._cont
330
+
331
+ @cont.setter
332
+ def cont(self, value):
333
+ if value is None:
334
+ self._cont = None
335
+ return
336
+ array = np.asarray(value, dtype=float)
337
+ if array.shape != self.shape:
338
+ raise ValueError("Continuum must match the flux shape")
339
+ self._cont = array.copy()
340
+
341
+ def normalize(self, *, method=None, inplace=True, **options):
342
+ """Apply external normalization; forward options to the estimator.
343
+
344
+ Like Doppler, the default updates this object. ``inplace=False`` returns
345
+ a copy. Prefer ``continuum.fit(spec).apply(spec)`` to retain diagnostics.
346
+ Repeating normalization without options is a no-op; changing methods on
347
+ an already normalized spectrum requires the original measurements.
348
+ """
349
+ from .continuum import fit, from_array
350
+
351
+ if self.normalized:
352
+ if method is not None or options:
353
+ raise ValueError(
354
+ "Already normalized; fit a new continuum to the original spectrum"
355
+ )
356
+ return self if inplace else self.copy()
357
+ if method is not None:
358
+ result = fit(self, method=method, **options)
359
+ elif self.continuum_func:
360
+ value = self.continuum_func(self, **options)
361
+ result = value if hasattr(value, "apply") else from_array(self, value)
362
+ elif options or self._cont is None:
363
+ result = fit(self, **options)
364
+ else:
365
+ result = from_array(self, self._cont)
366
+ return result.apply(self, inplace=inplace)
367
+
368
+ @classmethod
369
+ def from_spectrum(cls, spectrum):
370
+ """Copy a Doppler-compatible object without importing Doppler.
371
+
372
+ Required attribute is flux; wave/err/mask/numpix and metadata are
373
+ optional (wavelength-coordinate methods require wave). Wavelengths and fluxes must already be numerical arrays in the
374
+ desired units/frame. No model initialization or downloads occur.
375
+ """
376
+ if isinstance(spectrum, cls):
377
+ return spectrum.copy()
378
+ kw = {
379
+ name: getattr(spectrum, name, None)
380
+ for name in (
381
+ "err",
382
+ "wave",
383
+ "mask",
384
+ "bitmask",
385
+ "numpix",
386
+ "head",
387
+ "instrument",
388
+ "filename",
389
+ "lsf",
390
+ )
391
+ }
392
+ out = cls(
393
+ spectrum.flux,
394
+ **kw,
395
+ wavevac=getattr(spectrum, "wavevac", True),
396
+ wave_unit=getattr(spectrum, "wave_unit", "Angstrom"),
397
+ flux_unit=getattr(spectrum, "flux_unit", None),
398
+ metadata=getattr(spectrum, "metadata", None),
399
+ )
400
+ out.normalized = bool(getattr(spectrum, "normalized", False))
401
+ cached = getattr(spectrum, "_cont", None)
402
+ if cached is not None:
403
+ out.cont = cached
404
+ for name in ("_flux", "_err", "_flux_unit", "continuum_history"):
405
+ if hasattr(spectrum, name):
406
+ setattr(out, name, deepcopy(getattr(spectrum, name)))
407
+ callback = getattr(spectrum, "continuum_func", None)
408
+ if callable(callback):
409
+ # Preserve the cache as well as the callable; the public setter
410
+ # intentionally invalidates a cache when a user changes methods.
411
+ out._continuum_func = callback
412
+ return out
413
+
414
+ @classmethod
415
+ def from_native(
416
+ cls, wave, flux, *, regions, err=None, mask=None, bitmask=None, **metadata
417
+ ):
418
+ """Split a native 1-D grid into orders, preserving original pixel indices.
419
+
420
+ ``regions`` is a sequence of inclusive wavelength bounds, one per chip.
421
+ Regions may not overlap. Gaps are retained in the saved native mapping
422
+ and restored as masked samples by ``to_native``; no resampling occurs.
423
+ """
424
+ original = cls(flux, wave=wave, err=err, mask=mask, bitmask=bitmask, **metadata)
425
+ if original.norder != 1 or original.wave is None:
426
+ raise ValueError("from_native requires one-dimensional wave and flux")
427
+ indices, used = [], set()
428
+ for lo, hi in regions:
429
+ if not np.isfinite([lo, hi]).all() or lo > hi:
430
+ raise ValueError("Invalid region bounds")
431
+ selected = np.flatnonzero((original.wave >= lo) & (original.wave <= hi))
432
+ if not len(selected) or used.intersection(selected.tolist()):
433
+ raise ValueError("Regions must be nonempty and non-overlapping")
434
+ used.update(selected.tolist())
435
+ indices.append(selected)
436
+ if not indices:
437
+ raise ValueError("Provide at least one region")
438
+ kw = {
439
+ name: (
440
+ None
441
+ if getattr(original, name) is None
442
+ else [getattr(original, name)[ind] for ind in indices]
443
+ )
444
+ for name in ("flux", "wave", "err", "mask", "bitmask")
445
+ }
446
+ out = cls(**kw, **metadata)
447
+ out._native_wave = original.wave.copy()
448
+ out._native_indices = [ind.copy() for ind in indices]
449
+ return out
450
+
451
+ def to_native(self):
452
+ """Restore saved native positions, marking uncovered samples as bad.
453
+
454
+ Returns a new single-order spectrum. Without a mapping, use ``flatten``
455
+ for concatenation instead. Gaps get NaN flux, infinite supplied errors,
456
+ and mask=True. Masks/bitmasks are preserved without inventing flag bits.
457
+ """
458
+ if self._native_indices is None:
459
+ raise ValueError("No native pixel mapping; construct with from_native")
460
+ n = len(self._native_wave)
461
+ flux, mask = np.full(n, np.nan), np.ones(n, bool)
462
+ err = None if self.err is None else np.full(n, np.inf)
463
+ bitmask = None if self.bitmask is None else np.zeros(n, self.bitmask.dtype)
464
+ cont = None if self._cont is None else np.full(n, np.nan)
465
+ for i, ind in enumerate(self._native_indices):
466
+ count = self.numpix[i]
467
+ flux[ind] = self._column(self.flux, i)[:count]
468
+ mask[ind] = self._column(self.mask, i)[:count]
469
+ if err is not None:
470
+ err[ind] = self._column(self.err, i)[:count]
471
+ if bitmask is not None:
472
+ bitmask[ind] = self._column(self.bitmask, i)[:count]
473
+ if cont is not None:
474
+ cont[ind] = self._column(self._cont, i)[:count]
475
+ out = Spec1D(
476
+ flux,
477
+ wave=self._native_wave,
478
+ err=err,
479
+ mask=mask,
480
+ bitmask=bitmask,
481
+ wavevac=self.wavevac,
482
+ wave_unit=self.wave_unit,
483
+ flux_unit=self.flux_unit,
484
+ metadata=self.metadata,
485
+ head=self.head,
486
+ instrument=self.instrument,
487
+ filename=self.filename,
488
+ lsf=self.lsf,
489
+ )
490
+ out.normalized = self.normalized
491
+ if hasattr(self, "_flux_unit"):
492
+ out._flux_unit = deepcopy(self._flux_unit)
493
+ out.cont = cont
494
+ for name in ("_flux", "_err"):
495
+ value = getattr(self, name, None)
496
+ if value is not None:
497
+ saved = np.full(n, np.nan)
498
+ for i, ind in enumerate(self._native_indices):
499
+ saved[ind] = self._column(value, i)[: self.numpix[i]]
500
+ setattr(out, name, saved)
501
+ out.continuum_history = deepcopy(self.continuum_history)
502
+ return out
503
+
504
+ def flatten(self):
505
+ """Concatenate order samples; this does not insert detector gaps."""
506
+ kw = {
507
+ name: (
508
+ None
509
+ if getattr(self, name) is None
510
+ else np.concatenate(
511
+ [
512
+ self._column(getattr(self, name), i)[:n]
513
+ for i, n in enumerate(self.numpix)
514
+ ]
515
+ )
516
+ )
517
+ for name in ("flux", "wave", "err", "mask", "bitmask")
518
+ }
519
+ out = Spec1D(
520
+ **kw,
521
+ wavevac=self.wavevac,
522
+ wave_unit=self.wave_unit,
523
+ flux_unit=self.flux_unit,
524
+ metadata=self.metadata,
525
+ head=self.head,
526
+ instrument=self.instrument,
527
+ filename=self.filename,
528
+ lsf=self.lsf,
529
+ )
530
+ out.normalized = self.normalized
531
+ if hasattr(self, "_flux_unit"):
532
+ out._flux_unit = deepcopy(self._flux_unit)
533
+ for name in ("_flux", "_err"):
534
+ value = getattr(self, name, None)
535
+ if value is not None:
536
+ setattr(
537
+ out,
538
+ name,
539
+ np.concatenate(
540
+ [self._column(value, i)[:n] for i, n in enumerate(self.numpix)]
541
+ ),
542
+ )
543
+ if self._cont is not None:
544
+ out.cont = np.concatenate(
545
+ [self._column(self._cont, i)[:n] for i, n in enumerate(self.numpix)]
546
+ )
547
+ out.continuum_history = deepcopy(self.continuum_history)
548
+ if self._native_indices is not None:
549
+ out._native_wave = self._native_wave.copy()
550
+ out._native_indices = [np.concatenate(self._native_indices)]
551
+ return out