plotastrodata 1.12.1__tar.gz → 1.12.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 (29) hide show
  1. {plotastrodata-1.12.1/plotastrodata.egg-info → plotastrodata-1.12.3}/PKG-INFO +15 -2
  2. {plotastrodata-1.12.1 → plotastrodata-1.12.3}/README.md +14 -1
  3. {plotastrodata-1.12.1 → plotastrodata-1.12.3}/plotastrodata/__init__.py +1 -1
  4. {plotastrodata-1.12.1 → plotastrodata-1.12.3}/plotastrodata/_type_utils.py +1 -1
  5. {plotastrodata-1.12.1 → plotastrodata-1.12.3}/plotastrodata/analysis_utils.py +158 -11
  6. {plotastrodata-1.12.1 → plotastrodata-1.12.3}/plotastrodata/noise_utils.py +146 -2
  7. {plotastrodata-1.12.1 → plotastrodata-1.12.3}/plotastrodata/other_utils.py +207 -0
  8. plotastrodata-1.12.3/plotastrodata/script_utils.py +325 -0
  9. {plotastrodata-1.12.1 → plotastrodata-1.12.3/plotastrodata.egg-info}/PKG-INFO +15 -2
  10. plotastrodata-1.12.1/plotastrodata/script_utils.py +0 -595
  11. {plotastrodata-1.12.1 → plotastrodata-1.12.3}/LICENSE +0 -0
  12. {plotastrodata-1.12.1 → plotastrodata-1.12.3}/MANIFEST.in +0 -0
  13. {plotastrodata-1.12.1 → plotastrodata-1.12.3}/plotastrodata/_validation_utils.py +0 -0
  14. {plotastrodata-1.12.1 → plotastrodata-1.12.3}/plotastrodata/const_utils.py +0 -0
  15. {plotastrodata-1.12.1 → plotastrodata-1.12.3}/plotastrodata/coord_utils.py +0 -0
  16. {plotastrodata-1.12.1 → plotastrodata-1.12.3}/plotastrodata/ext_utils.py +0 -0
  17. {plotastrodata-1.12.1 → plotastrodata-1.12.3}/plotastrodata/fft_utils.py +0 -0
  18. {plotastrodata-1.12.1 → plotastrodata-1.12.3}/plotastrodata/fits_utils.py +0 -0
  19. {plotastrodata-1.12.1 → plotastrodata-1.12.3}/plotastrodata/fitting_utils.py +0 -0
  20. {plotastrodata-1.12.1 → plotastrodata-1.12.3}/plotastrodata/los_utils.py +0 -0
  21. {plotastrodata-1.12.1 → plotastrodata-1.12.3}/plotastrodata/matrix_utils.py +0 -0
  22. {plotastrodata-1.12.1 → plotastrodata-1.12.3}/plotastrodata/plot_utils.py +0 -0
  23. {plotastrodata-1.12.1 → plotastrodata-1.12.3}/plotastrodata.egg-info/SOURCES.txt +0 -0
  24. {plotastrodata-1.12.1 → plotastrodata-1.12.3}/plotastrodata.egg-info/dependency_links.txt +0 -0
  25. {plotastrodata-1.12.1 → plotastrodata-1.12.3}/plotastrodata.egg-info/not-zip-safe +0 -0
  26. {plotastrodata-1.12.1 → plotastrodata-1.12.3}/plotastrodata.egg-info/requires.txt +0 -0
  27. {plotastrodata-1.12.1 → plotastrodata-1.12.3}/plotastrodata.egg-info/top_level.txt +0 -0
  28. {plotastrodata-1.12.1 → plotastrodata-1.12.3}/setup.cfg +0 -0
  29. {plotastrodata-1.12.1 → plotastrodata-1.12.3}/setup.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: plotastrodata
3
- Version: 1.12.1
3
+ Version: 1.12.3
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
@@ -106,11 +106,24 @@ with three significant digits for editing.
106
106
  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
- with intrinsic channel spacing. The flux profile assumes Jy/beam data with beam metadata.
109
+ with intrinsic channel spacing. Two further single-panel figures show moments
110
+ 1 and 2 in linear colors with moment-0 contours and colorbar ticks to one
111
+ decimal place; moment 1 uses a blue-red colormap. The moments use the shared crop and are saved as
112
+ `<script stem>_mom1.png` and `<script stem>_mom2.png`. The flux profile assumes Jy/beam data with beam metadata.
113
+ Noise and range estimation in both generators assume PB-corrected intensities.
110
114
  Both generators return an absolute pathlib.Path and write the script
111
115
  without executing it.
112
116
  See the [script-generation guide](docs/script_generation.rst).
113
117
 
118
+ Ranges can also be obtained from loaded data with
119
+ `rmax, vmin, vmax = d.estimate_ranges(pbcor=True)` for PB-corrected data.
120
+ For uniform-noise data, use `d.estimate_ranges()`. Noise is fitted when
121
+ `d.sigma=None`; a supplied positive scalar assumes a zero baseline unless
122
+ `pbcor=True`. For PB-corrected data, supplied sigma describes noise before
123
+ PB correction. The array-based function is `noise_utils.estimate_ranges`,
124
+ with the same `pbcor` option and optional `sigma`. Here, `rmax` is a symmetric
125
+ spatial half-width; 2D images return `None` for both velocity limits.
126
+
114
127
  ## Requirement
115
128
 
116
129
  * Python >= 3.11
@@ -77,11 +77,24 @@ with three significant digits for editing.
77
77
  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
- with intrinsic channel spacing. The flux profile assumes Jy/beam data with beam metadata.
80
+ with intrinsic channel spacing. Two further single-panel figures show moments
81
+ 1 and 2 in linear colors with moment-0 contours and colorbar ticks to one
82
+ decimal place; moment 1 uses a blue-red colormap. The moments use the shared crop and are saved as
83
+ `<script stem>_mom1.png` and `<script stem>_mom2.png`. The flux profile assumes Jy/beam data with beam metadata.
84
+ Noise and range estimation in both generators assume PB-corrected intensities.
81
85
  Both generators return an absolute pathlib.Path and write the script
82
86
  without executing it.
83
87
  See the [script-generation guide](docs/script_generation.rst).
84
88
 
89
+ Ranges can also be obtained from loaded data with
90
+ `rmax, vmin, vmax = d.estimate_ranges(pbcor=True)` for PB-corrected data.
91
+ For uniform-noise data, use `d.estimate_ranges()`. Noise is fitted when
92
+ `d.sigma=None`; a supplied positive scalar assumes a zero baseline unless
93
+ `pbcor=True`. For PB-corrected data, supplied sigma describes noise before
94
+ PB correction. The array-based function is `noise_utils.estimate_ranges`,
95
+ with the same `pbcor` option and optional `sigma`. Here, `rmax` is a symmetric
96
+ spatial half-width; 2D images return `None` for both velocity limits.
97
+
85
98
  ## Requirement
86
99
 
87
100
  * Python >= 3.11
@@ -1,4 +1,4 @@
1
1
  import warnings
2
2
 
3
3
  warnings.simplefilter('ignore', FutureWarning)
4
- __version__ = '1.12.1'
4
+ __version__ = '1.12.3'
@@ -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
@@ -25,6 +25,7 @@ from plotastrodata._type_utils import (
25
25
  from plotastrodata._validation_utils import (
26
26
  _is_finite_real_scalar,
27
27
  _is_positive_real_scalar,
28
+ _is_uniform_spacing,
28
29
  _is_zero_dimensional_array,
29
30
  _require_integer,
30
31
  _require_positive_real_scalar,
@@ -35,7 +36,7 @@ from plotastrodata.fitting_utils import (
35
36
  EmceeCorner, gaussfit1d, gaussfit2d, gaussian2d
36
37
  )
37
38
  from plotastrodata.matrix_utils import Mfac, Mrot, dot2d
38
- from plotastrodata.noise_utils import estimate_rms
39
+ from plotastrodata.noise_utils import estimate_ranges, estimate_rms
39
40
  from plotastrodata.other_utils import (
40
41
  RGIxy, RGIxyv, nearest_index, to4dim, trim
41
42
  )
@@ -586,6 +587,44 @@ class AstroData():
586
587
  return {'popt': popt, 'plow': plow, 'pmid': pmid, 'phigh': phigh,
587
588
  'model': modelopt, 'residual': residual}
588
589
 
590
+ def estimate_ranges(self, *, pbcor: bool = False
591
+ ) -> tuple[float | np.longdouble,
592
+ float | np.longdouble | None,
593
+ float | np.longdouble | None]:
594
+ """Estimate spatial and velocity limits for the current image or cube.
595
+
596
+ Read the data with AstroFrame first. Use the stored sigma when it
597
+ is a finite positive scalar, or fit noise when sigma=None. Without
598
+ PB preparation, data should have uniform noise; a supplied sigma
599
+ assumes a zero baseline. For PB-corrected data, a supplied sigma
600
+ describes noise before PB correction. Missing beam lengths use
601
+ pixel-based defaults. All inputs and stored attributes are unchanged.
602
+
603
+ Args:
604
+ pbcor (bool, optional): Python bool; fit hist-pbcor noise and
605
+ apply approximate PB weighting internally for PB-corrected
606
+ data. Defaults to False.
607
+
608
+ Returns:
609
+ tuple: (rmax, vmin, vmax). rmax is a symmetric spatial half-width
610
+ in the units of x/y. Velocity limits use the units of v and are
611
+ returned in ascending order. A 2D image returns None for both
612
+ velocity limits.
613
+ Computed scalars are Python floats, except np.longdouble
614
+ results retain extended precision.
615
+
616
+ Raises:
617
+ TypeError: pbcor is not a Python bool, or data is not a NumPy
618
+ array.
619
+ ValueError: Data, axes, noise, beam, or the centered finite
620
+ region are unsuitable. Errors from noise fitting also
621
+ propagate when sigma=None or pbcor=True.
622
+ """
623
+ v = self.v if (isinstance(self.data, np.ndarray)
624
+ and self.data.ndim == 3) else None
625
+ return estimate_ranges(self.data, self.x, self.y, self.sigma,
626
+ v=v, beam=self.beam, pbcor=pbcor)
627
+
589
628
  @_need_multipixels
590
629
  def gaussfit2d(self, chan: int | np.integer | None = None,
591
630
  *, progressbar: bool = False) -> _GaussFit2DResult:
@@ -669,24 +708,24 @@ class AstroData():
669
708
  if dataformask is None:
670
709
  dataformask = self.data
671
710
  if len(includepix) not in [0, 2] or len(excludepix) not in [0, 2]:
672
- raise ValueError(
673
- 'includepix and excludepix must be empty or [min, max].')
711
+ raise ValueError('includepix and excludepix must be empty'
712
+ + ' or [min, max].')
674
713
  if np.ndim(self.data) > np.ndim(dataformask):
675
714
  print('The mask is broadcasted.')
676
715
  try:
677
716
  mask = np.broadcast_to(dataformask, np.shape(self.data))
678
717
  except ValueError as exc:
679
- raise ValueError(
680
- 'dataformask must be broadcastable to the data shape; '
681
- f'got {np.shape(dataformask)} and {np.shape(self.data)}.'
682
- ) from exc
718
+ raise ValueError('dataformask must be broadcastable'
719
+ ' to the data shape;'
720
+ + f' got {np.shape(dataformask)}'
721
+ + f' and {np.shape(self.data)}.') from exc
683
722
  else:
684
723
  mask = dataformask
685
724
  if np.shape(self.data) != np.shape(mask):
686
- raise ValueError(
687
- 'dataformask must have the same shape as data after '
688
- f'broadcasting; got {np.shape(dataformask)} and '
689
- f'{np.shape(self.data)}.')
725
+ raise ValueError('dataformask must have the same shape as data'
726
+ + ' after broadcasting;'
727
+ + f' got {np.shape(dataformask)}'
728
+ + f' and {np.shape(self.data)}.')
690
729
 
691
730
  if ((len(includepix) == 2 or len(excludepix) == 2)
692
731
  and self.data.dtype.kind in 'biu'):
@@ -696,6 +735,114 @@ class AstroData():
696
735
  if len(excludepix) == 2:
697
736
  self.data[(excludepix[0] < mask) * (mask < excludepix[1])] = np.nan
698
737
 
738
+ def moment(self, vmask: np.ndarray | None = None,
739
+ threshold_cube: RealScalar = 3,
740
+ threshold_mom0: RealScalar = 3) -> None:
741
+ """Store integrated intensity, mean velocity, and velocity dispersion.
742
+
743
+ Uses the current data axis order (v, y, x), including after a
744
+ swapped read. Requires a nonempty real 3D cube, a finite 1D velocity
745
+ grid matching its first axis, finite positive scalar sigma, and
746
+ finite nonzero scalar dv. Multiple channels must be uniformly
747
+ spaced with spacing magnitude abs(dv) (relative tolerance 1e-5).
748
+ NaNs in the cube are ignored; infinities are rejected.
749
+
750
+ Args:
751
+ vmask (np.ndarray or None, optional): 1D Boolean array with one
752
+ entry per channel. True selects a channel. None selects all
753
+ channels; at least one must be selected.
754
+ threshold_cube (RealScalar, optional): Finite nonnegative noise
755
+ multiple used to select intensities for moments 1 and 2.
756
+ Values equal to the threshold survive. Defaults to 3.
757
+ threshold_mom0 (RealScalar, optional): Finite nonnegative
758
+ multiple of sigma_mom0 below which moments 1 and 2 are
759
+ masked. Values equal to the threshold survive. Defaults to 3.
760
+ Both thresholds accept Python/NumPy real scalars, excluding
761
+ booleans and arrays.
762
+
763
+ Returns:
764
+ None: Stores mom0, mom1, and mom2 as (y, x) NumPy arrays.
765
+ mom0 sums selected intensities times abs(dv), without cube
766
+ thresholding. mom1 is the intensity-weighted velocity; mom2 is
767
+ the weighted standard deviation, not FWHM. Both are NaN where
768
+ mom0 fails its threshold or no positive weight survives.
769
+ All-NaN spectra have mom0=0. sigma_mom0 is
770
+ sqrt(number of selected channels) * sigma * abs(dv), assuming
771
+ independent channel noise, even where data are NaN. It is a
772
+ Python float, except np.longdouble retains extended precision.
773
+ mom0 and sigma_mom0 use intensity times velocity units; mom1
774
+ and mom2 use the units of v. Input arrays are not modified.
775
+
776
+ Raises:
777
+ TypeError: data, v, or a supplied vmask is not a NumPy array.
778
+ ValueError: Shapes, numeric values, channel selection, noise,
779
+ spacing, or thresholds do not satisfy the requirements.
780
+ """
781
+ if not isinstance(self.data, np.ndarray):
782
+ raise TypeError('moment requires data to be a NumPy array.')
783
+ if (self.data.ndim != 3 or 0 in self.data.shape
784
+ or self.data.dtype.kind not in 'iuf'
785
+ or np.any(np.isinf(self.data))):
786
+ raise ValueError('moment requires a nonempty real 3D cube'
787
+ + ' without infinities.')
788
+ if not isinstance(self.v, np.ndarray):
789
+ raise TypeError('moment requires v to be a NumPy array.')
790
+ if (self.v.ndim != 1 or self.v.size != self.data.shape[0]
791
+ or self.v.dtype.kind not in 'iuf'
792
+ or not np.all(np.isfinite(self.v))):
793
+ raise ValueError('v must be a finite real 1D grid matching'
794
+ + ' the number of channels.')
795
+ if not _is_positive_real_scalar(self.sigma):
796
+ raise ValueError('moment requires finite positive scalar sigma.')
797
+ if not _is_finite_real_scalar(self.dv) or self.dv == 0:
798
+ raise ValueError('moment requires finite nonzero scalar dv.')
799
+ if self.v.size > 1:
800
+ steps = np.diff(self.v.astype(np.result_type(self.v.dtype, float)))
801
+ if (not (np.all(steps > 0) or np.all(steps < 0))
802
+ or not _is_uniform_spacing(steps, steps[0])
803
+ or not _is_uniform_spacing(np.abs(steps), abs(self.dv))):
804
+ raise ValueError('v must be monotonic and uniformly spaced'
805
+ + ' with spacing magnitude abs(dv).')
806
+ for name, value in (('threshold_cube', threshold_cube),
807
+ ('threshold_mom0', threshold_mom0)):
808
+ if not _is_finite_real_scalar(value) or value < 0:
809
+ raise ValueError(f'{name} must be a finite nonnegative'
810
+ + ' real scalar.')
811
+ if vmask is None:
812
+ vmask = np.ones(self.v.size, dtype=bool)
813
+ elif not isinstance(vmask, np.ndarray):
814
+ raise TypeError('vmask must be a NumPy Boolean array or None.')
815
+ if (vmask.dtype.kind != 'b' or vmask.shape != self.v.shape
816
+ or not np.any(vmask)):
817
+ raise ValueError('vmask must be a 1D Boolean array matching v'
818
+ + ' and selecting at least one channel.')
819
+
820
+ data = np.where(vmask[:, None, None], self.data, 0)
821
+ dv = abs(self.dv)
822
+ mom0 = np.nansum(data, axis=0) * dv
823
+ sigma_mom0 = np.sqrt(np.count_nonzero(vmask)) * self.sigma * dv
824
+ if (isinstance(self.sigma, np.longdouble)
825
+ or isinstance(dv, np.longdouble)):
826
+ sigma_mom0 = np.longdouble(sigma_mom0)
827
+ sigma_mom0 = _normalize_float(sigma_mom0)
828
+ w = np.where(data >= threshold_cube * self.sigma, data, 0)
829
+ total = np.sum(w, axis=0)
830
+ w = np.divide(w, total,
831
+ out=np.zeros_like(w, dtype=np.result_type(w, float)),
832
+ where=total > 0)
833
+ mask = (mom0 < threshold_mom0 * sigma_mom0) | (total <= 0)
834
+
835
+ def wmean(x: np.ndarray) -> np.ndarray:
836
+ return np.where(mask, np.nan, np.nansum(w * x, axis=0))
837
+
838
+ v = self.v[:, None, None]
839
+ mom1 = wmean(v)
840
+ mom2 = np.sqrt(wmean((v - mom1)**2))
841
+ self.mom0: np.ndarray = mom0
842
+ self.mom1: np.ndarray = mom1
843
+ self.mom2: np.ndarray = mom2
844
+ self.sigma_mom0: float | np.longdouble = sigma_mom0
845
+
699
846
  def _gfit_profile(self, prof: np.ndarray, gaussfit: bool
700
847
  ) -> dict[str, list[np.ndarray]]:
701
848
  if not gaussfit:
@@ -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 close_figure
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)