plotastrodata 1.12.1__tar.gz → 1.12.2__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.
- {plotastrodata-1.12.1/plotastrodata.egg-info → plotastrodata-1.12.2}/PKG-INFO +11 -1
- {plotastrodata-1.12.1 → plotastrodata-1.12.2}/README.md +10 -0
- {plotastrodata-1.12.1 → plotastrodata-1.12.2}/plotastrodata/__init__.py +1 -1
- {plotastrodata-1.12.1 → plotastrodata-1.12.2}/plotastrodata/_type_utils.py +1 -1
- {plotastrodata-1.12.1 → plotastrodata-1.12.2}/plotastrodata/analysis_utils.py +39 -1
- {plotastrodata-1.12.1 → plotastrodata-1.12.2}/plotastrodata/noise_utils.py +146 -2
- {plotastrodata-1.12.1 → plotastrodata-1.12.2}/plotastrodata/other_utils.py +207 -0
- plotastrodata-1.12.2/plotastrodata/script_utils.py +282 -0
- {plotastrodata-1.12.1 → plotastrodata-1.12.2/plotastrodata.egg-info}/PKG-INFO +11 -1
- plotastrodata-1.12.1/plotastrodata/script_utils.py +0 -595
- {plotastrodata-1.12.1 → plotastrodata-1.12.2}/LICENSE +0 -0
- {plotastrodata-1.12.1 → plotastrodata-1.12.2}/MANIFEST.in +0 -0
- {plotastrodata-1.12.1 → plotastrodata-1.12.2}/plotastrodata/_validation_utils.py +0 -0
- {plotastrodata-1.12.1 → plotastrodata-1.12.2}/plotastrodata/const_utils.py +0 -0
- {plotastrodata-1.12.1 → plotastrodata-1.12.2}/plotastrodata/coord_utils.py +0 -0
- {plotastrodata-1.12.1 → plotastrodata-1.12.2}/plotastrodata/ext_utils.py +0 -0
- {plotastrodata-1.12.1 → plotastrodata-1.12.2}/plotastrodata/fft_utils.py +0 -0
- {plotastrodata-1.12.1 → plotastrodata-1.12.2}/plotastrodata/fits_utils.py +0 -0
- {plotastrodata-1.12.1 → plotastrodata-1.12.2}/plotastrodata/fitting_utils.py +0 -0
- {plotastrodata-1.12.1 → plotastrodata-1.12.2}/plotastrodata/los_utils.py +0 -0
- {plotastrodata-1.12.1 → plotastrodata-1.12.2}/plotastrodata/matrix_utils.py +0 -0
- {plotastrodata-1.12.1 → plotastrodata-1.12.2}/plotastrodata/plot_utils.py +0 -0
- {plotastrodata-1.12.1 → plotastrodata-1.12.2}/plotastrodata.egg-info/SOURCES.txt +0 -0
- {plotastrodata-1.12.1 → plotastrodata-1.12.2}/plotastrodata.egg-info/dependency_links.txt +0 -0
- {plotastrodata-1.12.1 → plotastrodata-1.12.2}/plotastrodata.egg-info/not-zip-safe +0 -0
- {plotastrodata-1.12.1 → plotastrodata-1.12.2}/plotastrodata.egg-info/requires.txt +0 -0
- {plotastrodata-1.12.1 → plotastrodata-1.12.2}/plotastrodata.egg-info/top_level.txt +0 -0
- {plotastrodata-1.12.1 → plotastrodata-1.12.2}/setup.cfg +0 -0
- {plotastrodata-1.12.1 → plotastrodata-1.12.2}/setup.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: plotastrodata
|
|
3
|
-
Version: 1.12.
|
|
3
|
+
Version: 1.12.2
|
|
4
4
|
Summary: plotastrodata is a tool for astronomers to create figures from FITS files and perform fundamental data analyses with ease.
|
|
5
5
|
Home-page: https://github.com/yusukeaso-astron/plotastrodata
|
|
6
6
|
Download-URL: https://github.com/yusukeaso-astron/plotastrodata
|
|
@@ -107,10 +107,20 @@ For a spectral cube, use `generate_cube_script("cube.fits", output="cube.py")`
|
|
|
107
107
|
from the same module. It generates an edge-channel noise visualization, a flux-integrated line
|
|
108
108
|
profile and 3D channel maps over estimated spatial and velocity ranges,
|
|
109
109
|
with intrinsic channel spacing. The flux profile assumes Jy/beam data with beam metadata.
|
|
110
|
+
Noise and range estimation in both generators assume PB-corrected intensities.
|
|
110
111
|
Both generators return an absolute pathlib.Path and write the script
|
|
111
112
|
without executing it.
|
|
112
113
|
See the [script-generation guide](docs/script_generation.rst).
|
|
113
114
|
|
|
115
|
+
Ranges can also be obtained from loaded data with
|
|
116
|
+
`rmax, vmin, vmax = d.estimate_ranges(pbcor=True)` for PB-corrected data.
|
|
117
|
+
For uniform-noise data, use `d.estimate_ranges()`. Noise is fitted when
|
|
118
|
+
`d.sigma=None`; a supplied positive scalar assumes a zero baseline unless
|
|
119
|
+
`pbcor=True`. For PB-corrected data, supplied sigma describes noise before
|
|
120
|
+
PB correction. The array-based function is `noise_utils.estimate_ranges`,
|
|
121
|
+
with the same `pbcor` option and optional `sigma`. Here, `rmax` is a symmetric
|
|
122
|
+
spatial half-width; 2D images return `None` for both velocity limits.
|
|
123
|
+
|
|
114
124
|
## Requirement
|
|
115
125
|
|
|
116
126
|
* Python >= 3.11
|
|
@@ -78,10 +78,20 @@ For a spectral cube, use `generate_cube_script("cube.fits", output="cube.py")`
|
|
|
78
78
|
from the same module. It generates an edge-channel noise visualization, a flux-integrated line
|
|
79
79
|
profile and 3D channel maps over estimated spatial and velocity ranges,
|
|
80
80
|
with intrinsic channel spacing. The flux profile assumes Jy/beam data with beam metadata.
|
|
81
|
+
Noise and range estimation in both generators assume PB-corrected intensities.
|
|
81
82
|
Both generators return an absolute pathlib.Path and write the script
|
|
82
83
|
without executing it.
|
|
83
84
|
See the [script-generation guide](docs/script_generation.rst).
|
|
84
85
|
|
|
86
|
+
Ranges can also be obtained from loaded data with
|
|
87
|
+
`rmax, vmin, vmax = d.estimate_ranges(pbcor=True)` for PB-corrected data.
|
|
88
|
+
For uniform-noise data, use `d.estimate_ranges()`. Noise is fitted when
|
|
89
|
+
`d.sigma=None`; a supplied positive scalar assumes a zero baseline unless
|
|
90
|
+
`pbcor=True`. For PB-corrected data, supplied sigma describes noise before
|
|
91
|
+
PB correction. The array-based function is `noise_utils.estimate_ranges`,
|
|
92
|
+
with the same `pbcor` option and optional `sigma`. Here, `rmax` is a symmetric
|
|
93
|
+
spatial half-width; 2D images return `None` for both velocity limits.
|
|
94
|
+
|
|
85
95
|
## Requirement
|
|
86
96
|
|
|
87
97
|
* Python >= 3.11
|
|
@@ -13,7 +13,7 @@ import numpy as np
|
|
|
13
13
|
from pydantic import WrapValidator
|
|
14
14
|
|
|
15
15
|
# Shared input types; validated settings are separate from uncoerced inputs.
|
|
16
|
-
RealScalar = float | np.floating | np.integer
|
|
16
|
+
RealScalar = int | float | np.floating | np.integer
|
|
17
17
|
RealSequence = list[RealScalar] | tuple[RealScalar, ...] | np.ndarray
|
|
18
18
|
PositionPair = tuple[RealScalar, RealScalar] | list[RealScalar] | np.ndarray
|
|
19
19
|
Position = str | PositionPair
|
|
@@ -35,7 +35,7 @@ from plotastrodata.fitting_utils import (
|
|
|
35
35
|
EmceeCorner, gaussfit1d, gaussfit2d, gaussian2d
|
|
36
36
|
)
|
|
37
37
|
from plotastrodata.matrix_utils import Mfac, Mrot, dot2d
|
|
38
|
-
from plotastrodata.noise_utils import estimate_rms
|
|
38
|
+
from plotastrodata.noise_utils import estimate_ranges, estimate_rms
|
|
39
39
|
from plotastrodata.other_utils import (
|
|
40
40
|
RGIxy, RGIxyv, nearest_index, to4dim, trim
|
|
41
41
|
)
|
|
@@ -586,6 +586,44 @@ class AstroData():
|
|
|
586
586
|
return {'popt': popt, 'plow': plow, 'pmid': pmid, 'phigh': phigh,
|
|
587
587
|
'model': modelopt, 'residual': residual}
|
|
588
588
|
|
|
589
|
+
def estimate_ranges(self, *, pbcor: bool = False
|
|
590
|
+
) -> tuple[float | np.longdouble,
|
|
591
|
+
float | np.longdouble | None,
|
|
592
|
+
float | np.longdouble | None]:
|
|
593
|
+
"""Estimate spatial and velocity limits for the current image or cube.
|
|
594
|
+
|
|
595
|
+
Read the data with AstroFrame first. Use the stored sigma when it
|
|
596
|
+
is a finite positive scalar, or fit noise when sigma=None. Without
|
|
597
|
+
PB preparation, data should have uniform noise; a supplied sigma
|
|
598
|
+
assumes a zero baseline. For PB-corrected data, a supplied sigma
|
|
599
|
+
describes noise before PB correction. Missing beam lengths use
|
|
600
|
+
pixel-based defaults. All inputs and stored attributes are unchanged.
|
|
601
|
+
|
|
602
|
+
Args:
|
|
603
|
+
pbcor (bool, optional): Python bool; fit hist-pbcor noise and
|
|
604
|
+
apply approximate PB weighting internally for PB-corrected
|
|
605
|
+
data. Defaults to False.
|
|
606
|
+
|
|
607
|
+
Returns:
|
|
608
|
+
tuple: (rmax, vmin, vmax). rmax is a symmetric spatial half-width
|
|
609
|
+
in the units of x/y. Velocity limits use the units of v and are
|
|
610
|
+
returned in ascending order. A 2D image returns None for both
|
|
611
|
+
velocity limits.
|
|
612
|
+
Computed scalars are Python floats, except np.longdouble
|
|
613
|
+
results retain extended precision.
|
|
614
|
+
|
|
615
|
+
Raises:
|
|
616
|
+
TypeError: pbcor is not a Python bool, or data is not a NumPy
|
|
617
|
+
array.
|
|
618
|
+
ValueError: Data, axes, noise, beam, or the centered finite
|
|
619
|
+
region are unsuitable. Errors from noise fitting also
|
|
620
|
+
propagate when sigma=None or pbcor=True.
|
|
621
|
+
"""
|
|
622
|
+
v = self.v if (isinstance(self.data, np.ndarray)
|
|
623
|
+
and self.data.ndim == 3) else None
|
|
624
|
+
return estimate_ranges(self.data, self.x, self.y, self.sigma,
|
|
625
|
+
v=v, beam=self.beam, pbcor=pbcor)
|
|
626
|
+
|
|
589
627
|
@_need_multipixels
|
|
590
628
|
def gaussfit2d(self, chan: int | np.integer | None = None,
|
|
591
629
|
*, progressbar: bool = False) -> _GaussFit2DResult:
|
|
@@ -6,13 +6,19 @@ import matplotlib.pyplot as plt
|
|
|
6
6
|
import numpy as np
|
|
7
7
|
from scipy.special import erf
|
|
8
8
|
|
|
9
|
-
from plotastrodata._type_utils import _normalize_float
|
|
9
|
+
from plotastrodata._type_utils import BeamInput, RealScalar, _normalize_float
|
|
10
10
|
from plotastrodata._validation_utils import (
|
|
11
11
|
_is_uniform_spacing,
|
|
12
|
+
_require_positive_real_scalar,
|
|
12
13
|
_require_integer
|
|
13
14
|
)
|
|
14
15
|
from plotastrodata.fitting_utils import EmceeCorner
|
|
15
|
-
from plotastrodata.other_utils import
|
|
16
|
+
from plotastrodata.other_utils import (
|
|
17
|
+
_estimate_ranges,
|
|
18
|
+
_get_minarea_margin,
|
|
19
|
+
_validate_range_inputs,
|
|
20
|
+
close_figure
|
|
21
|
+
)
|
|
16
22
|
|
|
17
23
|
|
|
18
24
|
def _uniform_bin_width(edges: np.ndarray) -> float | np.longdouble:
|
|
@@ -381,3 +387,141 @@ def estimate_rms(data: np.ndarray,
|
|
|
381
387
|
if np.abs(ave) > 0.2 * noise:
|
|
382
388
|
warnings.warn('|mean| > 0.2sigma.', UserWarning)
|
|
383
389
|
return _normalize_float(noise)
|
|
390
|
+
|
|
391
|
+
|
|
392
|
+
def _multiply_pb(data: np.ndarray, x: np.ndarray, y: np.ndarray,
|
|
393
|
+
R: RealScalar, r_out: RealScalar) -> np.ndarray:
|
|
394
|
+
"""Multiply an image or cube by an approximate Gaussian primary beam.
|
|
395
|
+
|
|
396
|
+
Args:
|
|
397
|
+
data: Numeric array with shape (ny, nx) or (nchan, ny, nx).
|
|
398
|
+
x: Finite real 1D x offsets from the assumed PB center, length nx.
|
|
399
|
+
y: Finite real 1D y offsets from the assumed PB center, length ny.
|
|
400
|
+
R: Positive dimensionless outer radius r_out / r_p from gauss_pbcor
|
|
401
|
+
(Noise.popt[2]), where r_p is the primary-beam HWHM.
|
|
402
|
+
r_out: Positive outer radius of the footprint used for the noise fit,
|
|
403
|
+
in the same spatial units as x and y. It is supplied explicitly,
|
|
404
|
+
not inferred from the array shape or the plotting crop.
|
|
405
|
+
|
|
406
|
+
Returns:
|
|
407
|
+
np.ndarray: New array of the same shape, multiplied by
|
|
408
|
+
B(x, y) = 2**(-R**2 * ((x/r_out)**2 + (y/r_out)**2)).
|
|
409
|
+
One spatial pattern is broadcast across all channels. Inputs are
|
|
410
|
+
not modified and nonfinite data pixels are not filled or removed.
|
|
411
|
+
NumPy determines the arithmetic dtype; integer data can become
|
|
412
|
+
floating point, and extended precision is retained without casting.
|
|
413
|
+
|
|
414
|
+
Raises:
|
|
415
|
+
TypeError: data is not a NumPy array.
|
|
416
|
+
ValueError: Shapes, coordinate values, or PB parameters are unsuitable.
|
|
417
|
+
|
|
418
|
+
Notes:
|
|
419
|
+
Applying this to PB-corrected data approximately restores the
|
|
420
|
+
pre-correction intensities. The assumed circular beam and center
|
|
421
|
+
are intended for range estimation, not calibrated PB reconstruction.
|
|
422
|
+
"""
|
|
423
|
+
if not isinstance(data, np.ndarray):
|
|
424
|
+
raise TypeError('data must be a NumPy array.')
|
|
425
|
+
if (data.ndim not in (2, 3) or 0 in data.shape
|
|
426
|
+
or not np.issubdtype(data.dtype, np.number)):
|
|
427
|
+
raise ValueError('data must be a nonempty numeric 2D or 3D array.')
|
|
428
|
+
x, y = np.asarray(x), np.asarray(y)
|
|
429
|
+
for coordinate, length, name in ((x, data.shape[-1], 'x'),
|
|
430
|
+
(y, data.shape[-2], 'y')):
|
|
431
|
+
if (coordinate.ndim != 1 or len(coordinate) != length
|
|
432
|
+
or coordinate.dtype.kind not in 'iuf'
|
|
433
|
+
or not np.all(np.isfinite(coordinate))):
|
|
434
|
+
raise ValueError(f'{name} must be a finite real 1D coordinate array'
|
|
435
|
+
+ ' matching the spatial data axis.')
|
|
436
|
+
_require_positive_real_scalar(R, 'R')
|
|
437
|
+
_require_positive_real_scalar(r_out, 'r_out')
|
|
438
|
+
radius_squared = (x[None, :] / r_out)**2 + (y[:, None] / r_out)**2
|
|
439
|
+
pattern = np.exp2(-R**2 * radius_squared)
|
|
440
|
+
return data * pattern
|
|
441
|
+
|
|
442
|
+
|
|
443
|
+
def estimate_ranges(data: np.ndarray, x: np.ndarray, y: np.ndarray,
|
|
444
|
+
sigma: RealScalar | None = None, *,
|
|
445
|
+
v: np.ndarray | None = None,
|
|
446
|
+
beam: BeamInput
|
|
447
|
+
| tuple[RealScalar | None, RealScalar | None]
|
|
448
|
+
| None = None,
|
|
449
|
+
pbcor: bool = False
|
|
450
|
+
) -> tuple[float | np.longdouble,
|
|
451
|
+
float | np.longdouble | None,
|
|
452
|
+
float | np.longdouble | None]:
|
|
453
|
+
"""Estimate spatial and velocity limits of an image or cube.
|
|
454
|
+
|
|
455
|
+
Fit noise to the full image or the first and last cube channels when
|
|
456
|
+
sigma=None or pbcor=True. Use hist for uniform-noise data and hist-pbcor
|
|
457
|
+
for PB-corrected data. Subtract the fitted mean when fitting is needed.
|
|
458
|
+
PB preparation uses an approximate beam centered at zero. All preparation
|
|
459
|
+
uses temporary arrays; input arrays and their dtypes are unchanged.
|
|
460
|
+
|
|
461
|
+
Args:
|
|
462
|
+
data (np.ndarray): Real image (ny, nx) or cube (nchan, ny, nx).
|
|
463
|
+
Each axis requires at least two samples. Without PB preparation,
|
|
464
|
+
noise should be approximately uniform.
|
|
465
|
+
x (np.ndarray): Finite, uniformly spaced 1D x offsets from the
|
|
466
|
+
intended center, matching the spatial data axis. May descend.
|
|
467
|
+
y (np.ndarray): Finite, uniformly spaced 1D y offsets from the
|
|
468
|
+
intended center, matching the spatial data axis. May descend.
|
|
469
|
+
sigma (int or float or np.integer or np.floating or None, optional):
|
|
470
|
+
Finite positive scalar noise level in the data units, or None to use
|
|
471
|
+
the fitted standard deviation. For PB-corrected data, this is
|
|
472
|
+
the noise before PB correction; a fit is still needed to obtain
|
|
473
|
+
the PB parameter and mean. With pbcor=False and a supplied sigma,
|
|
474
|
+
assume a zero baseline. Booleans are rejected. Defaults to None.
|
|
475
|
+
v (np.ndarray, optional): Finite, uniformly spaced channel
|
|
476
|
+
coordinates. Required for cubes and omitted for images.
|
|
477
|
+
At least two channels are needed; may descend. Defaults to None.
|
|
478
|
+
beam (list or tuple or np.ndarray, optional): [major, minor] FWHM
|
|
479
|
+
lengths or [major, minor, pa]. Lengths use the same units as
|
|
480
|
+
x and y; pa is unused. If beam or either FWHM length is None,
|
|
481
|
+
use pixel-based defaults. Defaults to None.
|
|
482
|
+
pbcor (bool, optional): Python bool; apply approximate PB weighting to
|
|
483
|
+
PB-corrected data before detecting emission. The assumed PB
|
|
484
|
+
center is x=y=0. Defaults to False.
|
|
485
|
+
|
|
486
|
+
Returns:
|
|
487
|
+
tuple: (rmax, vmin, vmax). rmax is a symmetric spatial half-width
|
|
488
|
+
in the units of x and y. Velocity limits use the units of v and are
|
|
489
|
+
returned in ascending order. An image returns None for both velocity
|
|
490
|
+
limits. Computed scalars are Python floats, except np.longdouble
|
|
491
|
+
results retain extended precision.
|
|
492
|
+
|
|
493
|
+
Raises:
|
|
494
|
+
TypeError: pbcor is not a Python bool, or data is not a NumPy array.
|
|
495
|
+
ValueError: Data, axes, noise, beam, or the centered finite region
|
|
496
|
+
are unsuitable. Errors from noise fitting also propagate.
|
|
497
|
+
"""
|
|
498
|
+
if not isinstance(pbcor, bool):
|
|
499
|
+
raise TypeError('pbcor must be a boolean.')
|
|
500
|
+
x, y, v = _validate_range_inputs(data, x, y, v)
|
|
501
|
+
if sigma is not None:
|
|
502
|
+
_require_positive_real_scalar(sigma, 'sigma')
|
|
503
|
+
dx, dy = abs(x[1] - x[0]), abs(y[1] - y[0])
|
|
504
|
+
min_area_pixels, spatial_margin = _get_minarea_margin(beam, dx, dy)
|
|
505
|
+
if not pbcor and sigma is not None:
|
|
506
|
+
return _estimate_ranges(data, x, y, sigma, v=v,
|
|
507
|
+
min_area_pixels=min_area_pixels,
|
|
508
|
+
spatial_margin=spatial_margin)
|
|
509
|
+
noise_data = data if data.ndim == 2 else data[[0, -1]]
|
|
510
|
+
noise = Noise(data=noise_data, sigma='hist-pbcor' if pbcor else 'hist')
|
|
511
|
+
noise.gen_histogram()
|
|
512
|
+
noise.fit_histogram()
|
|
513
|
+
if pbcor:
|
|
514
|
+
pixels = np.count_nonzero(np.isfinite(noise_data),
|
|
515
|
+
axis=None if data.ndim == 2 else (1, 2))
|
|
516
|
+
if data.ndim == 3:
|
|
517
|
+
pixels = np.mean(pixels)
|
|
518
|
+
r_out = np.sqrt(pixels * dx * dy / np.pi)
|
|
519
|
+
prepared = _multiply_pb(data, x, y, R=noise.popt[2], r_out=r_out)
|
|
520
|
+
prepared -= noise.mean
|
|
521
|
+
else:
|
|
522
|
+
prepared = data - noise.mean
|
|
523
|
+
if sigma is None:
|
|
524
|
+
sigma = noise.std
|
|
525
|
+
return _estimate_ranges(prepared, x, y, sigma, v=v,
|
|
526
|
+
min_area_pixels=min_area_pixels,
|
|
527
|
+
spatial_margin=spatial_margin)
|
|
@@ -5,8 +5,15 @@ from typing import Any
|
|
|
5
5
|
import matplotlib.pyplot as plt
|
|
6
6
|
import numpy as np
|
|
7
7
|
from matplotlib.figure import Figure
|
|
8
|
+
from scipy import ndimage
|
|
8
9
|
from scipy.interpolate import RegularGridInterpolator as RGI
|
|
9
10
|
|
|
11
|
+
from plotastrodata._type_utils import BeamInput, RealScalar, _normalize_float
|
|
12
|
+
from plotastrodata._validation_utils import (
|
|
13
|
+
_is_uniform_spacing,
|
|
14
|
+
_require_positive_real_scalar,
|
|
15
|
+
)
|
|
16
|
+
|
|
10
17
|
|
|
11
18
|
def isdeg(s: Any) -> bool:
|
|
12
19
|
"""Whether the given string means degree.
|
|
@@ -347,3 +354,203 @@ def close_figure(fig: Figure,
|
|
|
347
354
|
if show:
|
|
348
355
|
plt.show()
|
|
349
356
|
plt.close(fig)
|
|
357
|
+
|
|
358
|
+
|
|
359
|
+
def _validate_range_inputs(data: np.ndarray, x: np.ndarray, y: np.ndarray,
|
|
360
|
+
v: np.ndarray | None
|
|
361
|
+
) -> tuple[np.ndarray,
|
|
362
|
+
np.ndarray,
|
|
363
|
+
np.ndarray | None]:
|
|
364
|
+
"""Validate data and coordinates and return the coordinate arrays.
|
|
365
|
+
|
|
366
|
+
Preserve array dtypes and leave all inputs unchanged. Reject unsuitable
|
|
367
|
+
dimensions, coordinates, and image/cube velocity arguments.
|
|
368
|
+
"""
|
|
369
|
+
if not isinstance(data, np.ndarray):
|
|
370
|
+
raise TypeError('data must be a NumPy array.')
|
|
371
|
+
if (data.ndim not in (2, 3) or data.dtype.kind not in 'iuf'
|
|
372
|
+
or any(length < 2 for length in data.shape)):
|
|
373
|
+
raise ValueError('data must be a real 2D or 3D array with at least'
|
|
374
|
+
+ ' two samples on every axis.')
|
|
375
|
+
x, y = np.asarray(x), np.asarray(y)
|
|
376
|
+
axes = [(x, data.shape[-1], 'x'), (y, data.shape[-2], 'y')]
|
|
377
|
+
if data.ndim == 3:
|
|
378
|
+
if v is None:
|
|
379
|
+
raise ValueError('v is required for a cube.')
|
|
380
|
+
v = np.asarray(v)
|
|
381
|
+
axes.append((v, data.shape[0], 'v'))
|
|
382
|
+
elif v is not None:
|
|
383
|
+
raise ValueError('v must be omitted for a 2D image.')
|
|
384
|
+
for coordinate, length, name in axes:
|
|
385
|
+
if (coordinate.ndim != 1 or len(coordinate) != length
|
|
386
|
+
or coordinate.dtype.kind not in 'iuf'
|
|
387
|
+
or not np.all(np.isfinite(coordinate))):
|
|
388
|
+
raise ValueError(f'{name} must be a finite real 1D coordinate array'
|
|
389
|
+
+ ' matching its data axis.')
|
|
390
|
+
steps = np.diff(coordinate)
|
|
391
|
+
if steps[0] == 0 or not _is_uniform_spacing(steps, steps[0]):
|
|
392
|
+
raise ValueError(f'{name} must have nonzero uniform spacing.')
|
|
393
|
+
return x, y, v
|
|
394
|
+
|
|
395
|
+
|
|
396
|
+
def _get_minarea_margin(
|
|
397
|
+
beam: BeamInput | tuple[RealScalar | None, RealScalar | None] | None,
|
|
398
|
+
dx: RealScalar, dy: RealScalar) -> tuple[RealScalar, RealScalar]:
|
|
399
|
+
"""Return minimum spatial footprint in pixels and spatial margin.
|
|
400
|
+
|
|
401
|
+
Use a Gaussian beam area and the larger FWHM when beam lengths are
|
|
402
|
+
provided, otherwise one pixel. Either missing length selects pixel-based
|
|
403
|
+
defaults. Reject malformed shapes and invalid supplied lengths when both
|
|
404
|
+
lengths are present; PA is unused. Internal numeric precision is retained.
|
|
405
|
+
"""
|
|
406
|
+
min_area_pixels = 1
|
|
407
|
+
spatial_margin = max(dx, dy)
|
|
408
|
+
if beam is not None:
|
|
409
|
+
sizes = np.asarray(beam)
|
|
410
|
+
if sizes.ndim != 1 or sizes.size not in (2, 3):
|
|
411
|
+
raise ValueError('beam must contain [major, minor]'
|
|
412
|
+
+ ' or [major, minor, pa].')
|
|
413
|
+
if any(size is None for size in sizes[:2]):
|
|
414
|
+
return min_area_pixels, spatial_margin
|
|
415
|
+
for size in beam[:2]:
|
|
416
|
+
_require_positive_real_scalar(size, 'beam FWHM')
|
|
417
|
+
min_area_pixels = np.ceil(np.pi * sizes[0] * sizes[1]
|
|
418
|
+
/ (4 * np.log(2) * dx * dy))
|
|
419
|
+
spatial_margin = max(sizes[:2])
|
|
420
|
+
|
|
421
|
+
return min_area_pixels, spatial_margin
|
|
422
|
+
|
|
423
|
+
|
|
424
|
+
def _find_emission_bounds(data: np.ndarray, sigma: RealScalar,
|
|
425
|
+
min_area_pixels: RealScalar
|
|
426
|
+
) -> tuple[slice, ...] | None:
|
|
427
|
+
"""Return union bounding slices for qualified emission, or None.
|
|
428
|
+
|
|
429
|
+
Keep all face-connected 3-sigma components with a 5-sigma seed and the
|
|
430
|
+
minimum projected spatial footprint. Cubes also require two adjacent
|
|
431
|
+
channels. Input arrays are not modified.
|
|
432
|
+
"""
|
|
433
|
+
structure = ndimage.generate_binary_structure(data.ndim, 1)
|
|
434
|
+
mask = np.isfinite(data) & (data >= 3 * sigma)
|
|
435
|
+
labels, _ = ndimage.label(mask, structure=structure)
|
|
436
|
+
del mask
|
|
437
|
+
lower = list(data.shape)
|
|
438
|
+
upper = [0] * data.ndim
|
|
439
|
+
found = False
|
|
440
|
+
for component_id, region in enumerate(ndimage.find_objects(labels), start=1):
|
|
441
|
+
if region is None:
|
|
442
|
+
continue
|
|
443
|
+
component = labels[region] == component_id
|
|
444
|
+
if not np.any((data[region] >= 5 * sigma) & component):
|
|
445
|
+
continue
|
|
446
|
+
if data.ndim == 3:
|
|
447
|
+
if region[0].stop - region[0].start < 2:
|
|
448
|
+
continue
|
|
449
|
+
spatial = np.any(component, axis=0)
|
|
450
|
+
else:
|
|
451
|
+
spatial = component
|
|
452
|
+
if np.count_nonzero(spatial) < min_area_pixels:
|
|
453
|
+
continue
|
|
454
|
+
found = True
|
|
455
|
+
for axis, extent in enumerate(region):
|
|
456
|
+
lower[axis] = min(lower[axis], extent.start)
|
|
457
|
+
upper[axis] = max(upper[axis], extent.stop)
|
|
458
|
+
|
|
459
|
+
if not found:
|
|
460
|
+
return None
|
|
461
|
+
return tuple(slice(lo, hi) for lo, hi in zip(lower, upper))
|
|
462
|
+
|
|
463
|
+
|
|
464
|
+
def _estimate_ranges(data: np.ndarray, x: np.ndarray, y: np.ndarray,
|
|
465
|
+
sigma: RealScalar, *, v: np.ndarray | None = None,
|
|
466
|
+
min_area_pixels: RealScalar, spatial_margin: RealScalar,
|
|
467
|
+
) -> tuple[float | np.longdouble,
|
|
468
|
+
float | np.longdouble | None,
|
|
469
|
+
float | np.longdouble | None]:
|
|
470
|
+
"""Estimate spatial and velocity limits from positive emission.
|
|
471
|
+
|
|
472
|
+
Inputs and their array dtypes are unchanged. Thresholds assume a zero
|
|
473
|
+
noise baseline; subtract a fitted noise mean beforehand if appropriate.
|
|
474
|
+
The caller must validate data and coordinates with _validate_range_inputs
|
|
475
|
+
and calculate min_area_pixels and spatial_margin with _get_minarea_margin.
|
|
476
|
+
This function validates sigma, but does not fit noise or apply a PB.
|
|
477
|
+
|
|
478
|
+
Args:
|
|
479
|
+
data (np.ndarray): Real image (ny, nx) or cube (nchan, ny, nx)
|
|
480
|
+
with approximately uniform noise. Nonfinite values are excluded
|
|
481
|
+
from detection. Each axis requires at least two samples.
|
|
482
|
+
x (np.ndarray): Finite, uniformly spaced 1D x offsets from the
|
|
483
|
+
intended center, matching the spatial data axis. May descend.
|
|
484
|
+
y (np.ndarray): Finite, uniformly spaced 1D y offsets from the
|
|
485
|
+
intended center, matching the spatial data axis. May descend.
|
|
486
|
+
sigma (int or float or np.integer or np.floating): Finite positive
|
|
487
|
+
scalar noise level in the data units. Booleans are rejected.
|
|
488
|
+
v (np.ndarray, optional): Finite, uniformly spaced channel
|
|
489
|
+
coordinates. Required for cubes and omitted for images.
|
|
490
|
+
At least two channels are needed; may descend. Defaults to None.
|
|
491
|
+
min_area_pixels (int or float or np.integer or np.floating): Minimum
|
|
492
|
+
projected spatial footprint in pixels, calculated by the caller.
|
|
493
|
+
spatial_margin (int or float or np.integer or np.floating): Spatial
|
|
494
|
+
margin in the units of x and y, calculated by the caller.
|
|
495
|
+
|
|
496
|
+
Returns:
|
|
497
|
+
tuple: (rmax, vmin, vmax). Spatial limits use the units of x and y;
|
|
498
|
+
velocity limits use those of v and are returned in ascending order.
|
|
499
|
+
An image returns None for both velocity limits. Computed scalars
|
|
500
|
+
are Python floats, except np.longdouble results retain extended
|
|
501
|
+
precision.
|
|
502
|
+
|
|
503
|
+
Raises:
|
|
504
|
+
ValueError: sigma is unsuitable, or no sufficiently large centered
|
|
505
|
+
finite region remains.
|
|
506
|
+
"""
|
|
507
|
+
_require_positive_real_scalar(sigma, 'sigma')
|
|
508
|
+
dx, dy = abs(x[1] - x[0]), abs(y[1] - y[0])
|
|
509
|
+
|
|
510
|
+
full_radius = max((abs(x[0]) + abs(x[-1]) + dx) / 2,
|
|
511
|
+
(abs(y[0]) + abs(y[-1]) + dy) / 2)
|
|
512
|
+
available_radius = _get_valid_radius(data, x, y, full_radius)
|
|
513
|
+
bounds = _find_emission_bounds(data, sigma, min_area_pixels)
|
|
514
|
+
rmax = available_radius
|
|
515
|
+
if bounds is not None:
|
|
516
|
+
rx = (abs(x[bounds[-1].start]) + abs(x[bounds[-1].stop - 1])) / 2
|
|
517
|
+
ry = (abs(y[bounds[-2].start]) + abs(y[bounds[-2].stop - 1])) / 2
|
|
518
|
+
rmax = min(max(rx, ry) + spatial_margin, available_radius)
|
|
519
|
+
rmax = _normalize_float(rmax, force_float=True)
|
|
520
|
+
if v is None:
|
|
521
|
+
return rmax, None, None
|
|
522
|
+
first = max(bounds[0].start - 2, 0) if bounds is not None else 0
|
|
523
|
+
last = (min(bounds[0].stop + 1, len(v) - 1)
|
|
524
|
+
if bounds is not None else len(v) - 1)
|
|
525
|
+
return (rmax,
|
|
526
|
+
_normalize_float(min(v[first], v[last]), force_float=True),
|
|
527
|
+
_normalize_float(max(v[first], v[last]), force_float=True))
|
|
528
|
+
|
|
529
|
+
|
|
530
|
+
def _get_valid_radius(data: np.ndarray, x: np.ndarray, y: np.ndarray,
|
|
531
|
+
rmax: RealScalar
|
|
532
|
+
) -> float | np.longdouble:
|
|
533
|
+
"""Reduce a half-width to exclude nonfinite pixels, with a pixel margin.
|
|
534
|
+
|
|
535
|
+
data contains one 2D image or 3D cube with spatial coordinates.
|
|
536
|
+
rmax uses the same spatial units. For cubes, a spatial pixel is invalid
|
|
537
|
+
if any channel is nonfinite. Return the half-width as a Python float,
|
|
538
|
+
preserving np.longdouble results as an
|
|
539
|
+
extended-precision exception; emission-size selection is left to the caller.
|
|
540
|
+
Raise ValueError if no sufficiently large centered finite region remains.
|
|
541
|
+
"""
|
|
542
|
+
if data.ndim == 2:
|
|
543
|
+
valid = np.isfinite(data)
|
|
544
|
+
else:
|
|
545
|
+
valid = np.ones(data.shape[-2:], dtype=bool)
|
|
546
|
+
for channel in data:
|
|
547
|
+
valid &= np.isfinite(channel)
|
|
548
|
+
invalid_y, invalid_x = np.nonzero(~valid)
|
|
549
|
+
if invalid_x.size:
|
|
550
|
+
nearest_invalid = np.min(np.maximum(np.abs(x[invalid_x]),
|
|
551
|
+
np.abs(y[invalid_y])))
|
|
552
|
+
margin = max(abs(x[1] - x[0]), abs(y[1] - y[0]))
|
|
553
|
+
rmax = min(rmax, nearest_invalid - margin)
|
|
554
|
+
if not np.isfinite(rmax) or rmax <= margin:
|
|
555
|
+
raise ValueError('No centered finite spatial region large enough.')
|
|
556
|
+
return _normalize_float(rmax, force_float=True)
|