plotastrodata 1.12.1__py3-none-any.whl → 1.12.3__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.
plotastrodata/__init__.py CHANGED
@@ -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)
@@ -5,296 +5,8 @@ import numpy as np
5
5
  from astropy.io import fits
6
6
  from astropy.wcs import WCS
7
7
  from astropy.wcs.utils import proj_plane_pixel_scales
8
- from scipy import ndimage
9
8
 
10
- from plotastrodata._type_utils import RealScalar, RealSequence, _normalize_float
11
- from plotastrodata._validation_utils import (
12
- _is_uniform_spacing,
13
- _require_positive_real_scalar,
14
- )
15
9
  from plotastrodata.analysis_utils import AstroData, AstroFrame
16
- from plotastrodata.noise_utils import Noise
17
-
18
-
19
- def _multiply_pb(data: np.ndarray, x: np.ndarray, y: np.ndarray,
20
- R: float | np.integer | np.floating,
21
- r_out: float | np.integer | np.floating) -> np.ndarray:
22
- """Multiply an image or cube by an approximate Gaussian primary beam.
23
-
24
- Args:
25
- data: Numeric array with shape (ny, nx) or (nchan, ny, nx).
26
- x: Finite real 1D x offsets from the assumed PB center, length nx.
27
- y: Finite real 1D y offsets from the assumed PB center, length ny.
28
- R: Positive dimensionless outer radius r_out / r_p from gauss_pbcor
29
- (Noise.popt[2]), where r_p is the primary-beam HWHM.
30
- r_out: Positive outer radius of the footprint used for the noise fit,
31
- in the same spatial units as x and y. It is supplied explicitly,
32
- not inferred from the array shape or the plotting crop.
33
-
34
- Returns:
35
- np.ndarray: New array of the same shape, multiplied by
36
- B(x, y) = 2**(-R**2 * ((x/r_out)**2 + (y/r_out)**2)).
37
- One spatial pattern is broadcast across all channels. Inputs are
38
- not modified and nonfinite data pixels are not filled or removed.
39
- NumPy determines the arithmetic dtype; integer data can become
40
- floating point, and extended precision is retained without casting.
41
-
42
- Raises:
43
- TypeError: data is not a NumPy array.
44
- ValueError: Shapes, coordinate values, or PB parameters are unsuitable.
45
-
46
- Notes:
47
- Applying this to PB-corrected data approximately restores the
48
- pre-correction intensities. The assumed circular beam and center
49
- are intended for range estimation, not calibrated PB reconstruction.
50
- """
51
- if not isinstance(data, np.ndarray):
52
- raise TypeError('data must be a NumPy array.')
53
- if (data.ndim not in (2, 3) or 0 in data.shape
54
- or not np.issubdtype(data.dtype, np.number)):
55
- raise ValueError('data must be a nonempty numeric 2D or 3D array.')
56
- x, y = np.asarray(x), np.asarray(y)
57
- for coordinate, length, name in ((x, data.shape[-1], 'x'),
58
- (y, data.shape[-2], 'y')):
59
- if (coordinate.ndim != 1 or len(coordinate) != length
60
- or coordinate.dtype.kind not in 'iuf'
61
- or not np.all(np.isfinite(coordinate))):
62
- raise ValueError(f'{name} must be a finite real 1D coordinate array'
63
- + ' matching the spatial data axis.')
64
- _require_positive_real_scalar(R, 'R')
65
- _require_positive_real_scalar(r_out, 'r_out')
66
- radius_squared = (x[None, :] / r_out)**2 + (y[:, None] / r_out)**2
67
- pattern = np.exp2(-R**2 * radius_squared)
68
- return data * pattern
69
-
70
-
71
- def _validate_range_inputs(data: np.ndarray, x: np.ndarray, y: np.ndarray,
72
- sigma: RealScalar, v: np.ndarray | None
73
- ) -> tuple[np.ndarray,
74
- np.ndarray,
75
- np.ndarray | None]:
76
- """Validate range-estimator inputs and return the coordinate arrays.
77
-
78
- Preserve array dtypes and leave all inputs unchanged. Reject unsuitable
79
- dimensions, noise values, coordinates, and image/cube velocity arguments.
80
- """
81
- if not isinstance(data, np.ndarray):
82
- raise TypeError('data must be a NumPy array.')
83
- if (data.ndim not in (2, 3) or data.dtype.kind not in 'iuf'
84
- or any(length < 2 for length in data.shape)):
85
- raise ValueError('data must be a real 2D or 3D array with at least'
86
- + ' two samples on every axis.')
87
- _require_positive_real_scalar(sigma, 'sigma')
88
- x, y = np.asarray(x), np.asarray(y)
89
- axes = [(x, data.shape[-1], 'x'), (y, data.shape[-2], 'y')]
90
- if data.ndim == 3:
91
- if v is None:
92
- raise ValueError('v is required for a cube.')
93
- v = np.asarray(v)
94
- axes.append((v, data.shape[0], 'v'))
95
- elif v is not None:
96
- raise ValueError('v must be omitted for a 2D image.')
97
- for coordinate, length, name in axes:
98
- if (coordinate.ndim != 1 or len(coordinate) != length
99
- or coordinate.dtype.kind not in 'iuf'
100
- or not np.all(np.isfinite(coordinate))):
101
- raise ValueError(f'{name} must be a finite real 1D coordinate array'
102
- + ' matching its data axis.')
103
- steps = np.diff(coordinate)
104
- if steps[0] == 0 or not _is_uniform_spacing(steps, steps[0]):
105
- raise ValueError(f'{name} must have nonzero uniform spacing.')
106
- return x, y, v
107
-
108
-
109
- def _range_beam_settings(beam: RealSequence | None, dx: RealScalar, dy: RealScalar
110
- ) -> tuple[RealScalar, RealScalar]:
111
- """Return minimum spatial footprint in pixels and spatial padding.
112
-
113
- Use a Gaussian beam area and the larger FWHM when beam lengths are
114
- provided, otherwise one pixel. Internal numeric precision is retained.
115
- """
116
- minimum_pixels = 1
117
- padding = max(dx, dy)
118
- if beam is not None:
119
- sizes = np.asarray(beam)
120
- if sizes.ndim != 1 or sizes.size not in (2, 3):
121
- raise ValueError('beam must contain [major, minor]'
122
- + ' or [major, minor, pa].')
123
- for size in sizes[:2]:
124
- _require_positive_real_scalar(size, 'beam FWHM')
125
- minimum_pixels = np.ceil(np.pi * sizes[0] * sizes[1]
126
- / (4 * np.log(2) * dx * dy))
127
- padding = max(sizes[:2])
128
-
129
- return minimum_pixels, padding
130
-
131
-
132
- def _find_emission_bounds(data: np.ndarray, sigma: RealScalar,
133
- minimum_pixels: RealScalar
134
- ) -> tuple[slice, ...] | None:
135
- """Return union bounding slices for qualified emission, or None.
136
-
137
- Keep all face-connected 3-sigma components with a 5-sigma seed and the
138
- minimum projected spatial footprint. Cubes also require two adjacent
139
- channels. Input arrays are not modified.
140
- """
141
- structure = ndimage.generate_binary_structure(data.ndim, 1)
142
- mask = np.isfinite(data) & (data >= 3 * sigma)
143
- labels, _ = ndimage.label(mask, structure=structure)
144
- del mask
145
- lower = list(data.shape)
146
- upper = [0] * data.ndim
147
- found = False
148
- for component_id, region in enumerate(ndimage.find_objects(labels), start=1):
149
- if region is None:
150
- continue
151
- component = labels[region] == component_id
152
- if not np.any((data[region] >= 5 * sigma) & component):
153
- continue
154
- if data.ndim == 3:
155
- if region[0].stop - region[0].start < 2:
156
- continue
157
- spatial = np.any(component, axis=0)
158
- else:
159
- spatial = component
160
- if np.count_nonzero(spatial) < minimum_pixels:
161
- continue
162
- found = True
163
- for axis, extent in enumerate(region):
164
- lower[axis] = min(lower[axis], extent.start)
165
- upper[axis] = max(upper[axis], extent.stop)
166
-
167
- if not found:
168
- return None
169
- return tuple(slice(lo, hi) for lo, hi in zip(lower, upper))
170
-
171
-
172
- def _estimate_ranges(data: np.ndarray, x: np.ndarray, y: np.ndarray,
173
- sigma: RealScalar, *, v: np.ndarray | None = None,
174
- beam: RealSequence | None = None
175
- ) -> tuple[float | np.longdouble,
176
- float | np.longdouble | None,
177
- float | np.longdouble | None]:
178
- """Estimate spatial and velocity limits from positive emission.
179
-
180
- Args:
181
- data: Real numeric image (ny, nx) or cube (nchan, ny, nx), with
182
- approximately uniform noise, for example after _multiply_pb.
183
- Nonfinite values are excluded from detection.
184
- x: Finite, uniformly spaced 1D x offsets from the intended center.
185
- y: Finite, uniformly spaced 1D y offsets from the intended center.
186
- Both spatial axes require at least two samples and may descend.
187
- sigma: Finite positive scalar noise level in the data units.
188
- v: Finite, uniformly spaced channel coordinates, required for a
189
- cube and omitted for an image. At least two channels are needed.
190
- beam: Optional [major, minor] FWHM lengths, or [major, minor, pa].
191
- Lengths use the same units as x and y; pa is unused. Without a
192
- beam, the minimum footprint is one pixel and padding is one
193
- spatial pixel rather than one beam FWHM.
194
-
195
- Returns:
196
- tuple: (rmax, vmin, vmax). Computed scalars are Python floats,
197
- except np.longdouble results retain extended precision. An image
198
- returns None for both velocity limits. A cube returns numerical
199
- velocity limits in ascending order even for a descending v axis.
200
- Inputs and their array dtypes are unchanged.
201
-
202
- Raises:
203
- TypeError: data is not a NumPy array.
204
- ValueError: Data, axes, noise, beam, or the centered finite region
205
- are unsuitable.
206
-
207
- Notes:
208
- Face-connected components at or above 3*sigma survive only when they
209
- contain a 5*sigma seed and cover at least one Gaussian beam area
210
- in projected spatial pixels. Cube components must also span two
211
- adjacent channels. All qualifying components are retained.
212
-
213
- For each spatial axis, average the absolute values of the two
214
- emission endpoints; take the larger x/y average and add the major
215
- beam FWHM. Thus asymmetric emission uses mean absolute extent,
216
- not maximum distance, and its farthest edge may lie outside the
217
- symmetric field. Clip rmax to the centered finite footprint.
218
- Velocity limits include two extra channels on each side, clipped
219
- to the available channels, without skipping or binning.
220
-
221
- With no qualifying component, use the centered finite footprint
222
- and full velocity range. Spatial pixels with any nonfinite cube
223
- channel restrict that footprint, with a pixel margin as in the
224
- script generators. Thresholds assume a zero noise baseline; subtract
225
- a fitted noise mean from data before calling if appropriate.
226
- This helper does not fit noise or apply a PB.
227
- """
228
- x, y, v = _validate_range_inputs(data, x, y, sigma, v)
229
- dx, dy = abs(x[1] - x[0]), abs(y[1] - y[0])
230
- minimum_pixels, padding = _range_beam_settings(beam, dx, dy)
231
-
232
- footprint = AstroData(data=data, x=x, y=y, sigma=None)
233
- footprint.dx, footprint.dy = dx, dy
234
- full_radius = max((abs(x[0]) + abs(x[-1]) + dx) / 2,
235
- (abs(y[0]) + abs(y[-1]) + dy) / 2)
236
- available_radius = _get_valid_radius(footprint, full_radius)
237
- bounds = _find_emission_bounds(data, sigma, minimum_pixels)
238
- rmax = available_radius
239
- if bounds is not None:
240
- rx = (abs(x[bounds[-1].start]) + abs(x[bounds[-1].stop - 1])) / 2
241
- ry = (abs(y[bounds[-2].start]) + abs(y[bounds[-2].stop - 1])) / 2
242
- rmax = min(max(rx, ry) + padding, available_radius)
243
- rmax = _normalize_float(rmax, force_float=True)
244
- if v is None:
245
- return rmax, None, None
246
- first = max(bounds[0].start - 2, 0) if bounds is not None else 0
247
- last = (min(bounds[0].stop + 1, len(v) - 1)
248
- if bounds is not None else len(v) - 1)
249
- return (rmax,
250
- _normalize_float(min(v[first], v[last]), force_float=True),
251
- _normalize_float(max(v[first], v[last]), force_float=True))
252
-
253
-
254
- def _estimate_pb_ranges(image: AstroData
255
- ) -> tuple[float | np.longdouble,
256
- float | np.longdouble | None,
257
- float | np.longdouble | None]:
258
- """Fit PB-corrected noise and estimate emission ranges for loaded data.
259
-
260
- image must contain one real 2D image or 3D cube already read by
261
- AstroFrame, with spatial coordinates, pixel sizes, and cube velocities.
262
- Fit hist-pbcor to the full image or the first and last cube channels.
263
- Infer r_out from the equivalent circular area of the finite noise
264
- footprint, averaging the two sampled channel areas for a cube.
265
-
266
- Multiply a temporary array by the approximate PB from the fitted R,
267
- subtract the fitted noise mean, and pass it to _estimate_ranges with
268
- the fitted noise standard deviation and available beam metadata.
269
- Missing beam lengths select the estimator's pixel-based defaults.
270
- The AstroData object, its arrays, and the input FITS file are unchanged.
271
-
272
- Return (rmax, vmin, vmax), with None velocity limits for an image.
273
- Scalar results are Python floats, except np.longdouble results retain
274
- extended precision. The selection rules and fallback are those of
275
- _estimate_ranges. Errors from noise fitting, PB weighting, and range
276
- estimation propagate from the underlying helpers.
277
- """
278
- if not isinstance(image.data, np.ndarray) or image.data.ndim not in (2, 3):
279
- raise ValueError('Expected a loaded 2D image or 3D cube.')
280
- if image.data.ndim == 2:
281
- noise_data = image.data
282
- pixels = np.count_nonzero(np.isfinite(noise_data))
283
- else:
284
- noise_data = image.data[[0, -1]]
285
- pixels = np.mean(np.count_nonzero(np.isfinite(noise_data), axis=(1, 2)))
286
- noise = Noise(data=noise_data, sigma='hist-pbcor')
287
- noise.gen_histogram()
288
- noise.fit_histogram()
289
- r_out = np.sqrt(pixels * abs(image.dx * image.dy) / np.pi)
290
- del noise_data
291
- weighted = _multiply_pb(image.data, image.x, image.y,
292
- R=noise.popt[2], r_out=r_out)
293
- weighted -= noise.mean
294
- beam = image.beam if None not in image.beam[:2] else None
295
- return _estimate_ranges(weighted, image.x, image.y, noise.std,
296
- v=image.v if image.data.ndim == 3 else None,
297
- beam=beam)
298
10
 
299
11
 
300
12
  def _validate_fits_image(fitsimage: str | Path, *, ndim: int = 2) -> None:
@@ -328,35 +40,6 @@ def _validate_fits_image(fitsimage: str | Path, *, ndim: int = 2) -> None:
328
40
  raise ValueError('Expected finite positive spatial pixel scales.')
329
41
 
330
42
 
331
- def _get_valid_radius(image: AstroData, rmax: RealScalar
332
- ) -> float | np.longdouble:
333
- """Reduce a half-width to exclude nonfinite pixels, with a pixel margin.
334
-
335
- image must contain one 2D image or 3D cube already read by AstroFrame,
336
- with spatial coordinates and pixel spacings. rmax uses those same
337
- spatial units. For cubes, a
338
- spatial pixel is invalid if any channel is nonfinite. Return the
339
- half-width as a Python float, preserving np.longdouble results as an
340
- extended-precision exception; emission-size selection is left to the caller.
341
- Raise ValueError if no sufficiently large centered finite region remains.
342
- """
343
- if image.data.ndim == 2:
344
- valid = np.isfinite(image.data)
345
- else:
346
- valid = np.ones(image.data.shape[-2:], dtype=bool)
347
- for channel in image.data:
348
- valid &= np.isfinite(channel)
349
- invalid_y, invalid_x = np.nonzero(~valid)
350
- if invalid_x.size:
351
- nearest_invalid = np.min(np.maximum(np.abs(image.x[invalid_x]),
352
- np.abs(image.y[invalid_y])))
353
- margin = max(abs(image.dx), abs(image.dy))
354
- rmax = min(rmax, nearest_invalid - margin)
355
- if not np.isfinite(rmax) or rmax <= margin:
356
- raise ValueError('No centered finite spatial region large enough.')
357
- return _normalize_float(rmax, force_float=True)
358
-
359
-
360
43
  def _write_script(source: str, output: Path, *, overwrite: bool = False
361
44
  ) -> None:
362
45
  """Check Python syntax and write source, creating parent directories.
@@ -377,15 +60,17 @@ def generate_image_script(fitsimage: str | Path,
377
60
  *, overwrite: bool = False) -> Path:
378
61
  """Write an editable noise, Gaussian-fit, and 2D image plotting script.
379
62
 
380
- Generation reads the primary FITS image, fits its noise histogram, and
381
- estimates an emission-based fitting region. It does not execute the
382
- generated script or modify the input FITS file.
63
+ Generation reads the primary FITS image and calls
64
+ AstroData.estimate_ranges(pbcor=True) to fit noise and estimate the
65
+ spatial half-width. It does not execute the generated script or modify
66
+ the input FITS file.
383
67
  The generated script uses the existing AstroData, AstroFrame, Noise,
384
68
  and PlotAstroData APIs directly, following example.py.
385
69
 
386
70
  Args:
387
71
  fitsimage (str | Path): A primary-HDU RA/Dec image with at least
388
72
  two pixels on each spatial axis. Any higher axes must be singleton.
73
+ Noise and range estimation assume PB-corrected intensities.
389
74
  output (str | Path | None): Script path with a .py suffix. Defaults
390
75
  to <input stem>_image.py in the current working directory.
391
76
  Relative paths are resolved at generation time.
@@ -429,7 +114,7 @@ def generate_image_script(fitsimage: str | Path,
429
114
  _validate_fits_image(fitsimage)
430
115
  image = AstroData(fitsimage=str(fitsimage), sigma=None)
431
116
  AstroFrame().read(image)
432
- rmax, _, _ = _estimate_pb_ranges(image)
117
+ rmax, _, _ = image.estimate_ranges(pbcor=True)
433
118
  rmax = float(f'{rmax:.3g}')
434
119
  source = f'''
435
120
  from plotastrodata.analysis_utils import AstroData, AstroFrame
@@ -473,19 +158,21 @@ p.savefig({str(output.with_suffix('.png'))!r}, show=False)
473
158
  def generate_cube_script(fitsimage: str | Path,
474
159
  output: str | Path | None = None,
475
160
  *, overwrite: bool = False) -> Path:
476
- """Write noise, integrated line-profile, and 3D channel-map plotting code.
161
+ """Write noise, line-profile, channel-map, and moment-map plotting code.
477
162
 
478
163
  Use the existing AstroData, AstroFrame, Noise, plotprofile, and
479
164
  PlotAstroData APIs, following the line-profile and 3D channel-map
480
165
  sections of example.py. Generation reads the FITS header and cube
481
- pixels, fits edge-channel noise, and estimates emission ranges. It does
166
+ pixels and calls AstroData.estimate_ranges(pbcor=True) to fit
167
+ edge-channel noise and estimate emission ranges. It does
482
168
  not execute the generated script or modify the input FITS file.
483
169
 
484
170
  Args:
485
171
  fitsimage (str | Path): Primary-HDU RA/Dec spectral cube with at least
486
172
  two pixels on each spatial axis and two frequency or velocity
487
173
  channels on axis 3, in Hz, m/s, or km/s. Higher axes must be
488
- singleton. Running the generated flux profile assumes Jy/beam
174
+ singleton. Noise and range estimation assume PB-corrected
175
+ intensities. Running the generated flux profile assumes Jy/beam
489
176
  intensities and requires a complete beam and spatial pixel sizes.
490
177
  output (str | Path | None): Script path with a .py suffix. Defaults
491
178
  to <input stem>_cube.py in the current working directory.
@@ -530,11 +217,26 @@ def generate_cube_script(fitsimage: str | Path,
530
217
  PB-corrected data about the FITS reference center. The generated
531
218
  noise visualization still uses the full spatial footprint.
532
219
 
533
- The script sets stretch='log' and show=False, with default fonts,
220
+ Channel maps use stretch='log' and show=False, with default fonts,
534
221
  beams, contours, and channel layout. Edit these choices directly.
535
222
  Channel-map pages are saved beside the script as <script stem>.png;
536
223
  multiple pages receive _0, _1, ... suffixes before .png, following
537
224
  PlotAstroData.savefig. Existing figures may be overwritten.
225
+
226
+ After channel maps, the cropped cube calls AstroData.moment
227
+ with 3-sigma cube and integrated-intensity thresholds. Two separate
228
+ figures show moments 1 and 2 with linear colors and moment-0 contours
229
+ at [3, 6, 12, 24, 48, 96] times sigma_mom0. Moment 1 uses a blue-red
230
+ colormap; both colorbars use cbformat='%.1f'. They are saved as
231
+ <script stem>_mom1.png and
232
+ <script stem>_mom2.png beside the script. Moment ranges follow the
233
+ crop frame; changing that frame changes the moment calculation.
234
+ After calculation, d_crop is reused as a 2D image: data and sigma
235
+ are replaced for each contour/color call through d_crop.todict().
236
+ The moment arrays remain NumPy arrays, and sigma_mom0 is a Python
237
+ float except that np.longdouble retains extended precision. The
238
+ final data is the mom2 array, sigma is None, and v is None. The
239
+ original cube d is unchanged.
538
240
  """
539
241
  if not isinstance(overwrite, bool):
540
242
  raise TypeError('overwrite must be a boolean.')
@@ -545,7 +247,7 @@ def generate_cube_script(fitsimage: str | Path,
545
247
  _validate_fits_image(fitsimage, ndim=3)
546
248
  cube = AstroData(fitsimage=str(fitsimage), sigma=None)
547
249
  AstroFrame().read(cube)
548
- rmax, vmin, vmax = _estimate_pb_ranges(cube)
250
+ rmax, vmin, vmax = cube.estimate_ranges(pbcor=True)
549
251
  rmax = float(f'{rmax:.3g}')
550
252
  vmin, vmax = float(f'{vmin:.3g}'), float(f'{vmax:.3g}')
551
253
  source = f"""
@@ -569,13 +271,13 @@ n.plot_histogram(savefig={str(output.with_name(output.stem + '_noise.png'))!r},
569
271
  d.sigma = n.std # A float number in the data unit is acceptable.
570
272
 
571
273
  # Line profile
572
- d_profile = AstroData(**d.todict())
573
- f_profile = AstroFrame(rmax={rmax!r}, # Estimated spatial half-width (arcsec); adjust as needed.
274
+ d_crop = AstroData(**d.todict())
275
+ f_crop = AstroFrame(rmax={rmax!r}, # Estimated spatial half-width (arcsec); adjust as needed.
574
276
  vmin={vmin!r}, vmax={vmax!r}, # Estimated velocity range (km/s); adjust as needed.
575
277
  )
576
- f_profile.read(d_profile)
577
- plotprofile(**d_profile.todict(), xlist=[0], ylist=[0],
578
- ellipse=[4 * f_profile.rmax, 4 * f_profile.rmax, 0], # Circle enclosing the cropped square.
278
+ f_crop.read(d_crop)
279
+ plotprofile(**d_crop.todict(), xlist=[0], ylist=[0],
280
+ ellipse=[4 * f_crop.rmax, 4 * f_crop.rmax, 0], # Circle enclosing the cropped square.
579
281
  flux=True,
580
282
  savefig={str(output.with_name(output.stem + '_profile.png'))!r},
581
283
  show=False,
@@ -590,6 +292,34 @@ p.add_color(**d.todict(), stretch='log')
590
292
  p.add_contour(**d.todict(), colors='r')
591
293
  p.set_axis()
592
294
  p.savefig({str(output.with_suffix('.png'))!r}, show=False)
295
+
296
+ # Moment maps over the crop frame's spatial and velocity ranges
297
+ d_crop.moment(threshold_cube=3, threshold_mom0=3) # Noise multiples; adjust as needed.
298
+ d_crop.v = None # The moment maps are 2D images.
299
+
300
+ # Moment 1 with moment-0 contours
301
+ p = PlotAstroData(rmax=f_crop.rmax, center=d_crop.center)
302
+ d_crop.data = d_crop.mom0
303
+ d_crop.sigma = d_crop.sigma_mom0 # sigma * abs(dv) * sqrt(number of channels).
304
+ p.add_contour(**d_crop.todict(), levels=[3, 6, 12, 24, 48, 96], colors='k')
305
+ d_crop.data = d_crop.mom1
306
+ d_crop.sigma = None
307
+ p.add_color(**d_crop.todict(), stretch='linear', cmap='RdBu_r', cbformat='%.1f',
308
+ cblabel=r'Moment 1 (km s$^{{-1}}$)')
309
+ p.set_axis_radec(nticksminor=5)
310
+ p.savefig({str(output.with_name(output.stem + '_mom1.png'))!r}, show=False)
311
+
312
+ # Moment 2 with moment-0 contours
313
+ p = PlotAstroData(rmax=f_crop.rmax, center=d_crop.center)
314
+ d_crop.data = d_crop.mom0
315
+ d_crop.sigma = d_crop.sigma_mom0 # sigma * abs(dv) * sqrt(number of channels).
316
+ p.add_contour(**d_crop.todict(), levels=[3, 6, 12, 24, 48, 96], colors='k')
317
+ d_crop.data = d_crop.mom2
318
+ d_crop.sigma = None
319
+ p.add_color(**d_crop.todict(), stretch='linear', cbformat='%.1f',
320
+ cblabel=r'Moment 2 (km s$^{{-1}}$)')
321
+ p.set_axis_radec(nticksminor=5)
322
+ p.savefig({str(output.with_name(output.stem + '_mom2.png'))!r}, show=False)
593
323
  """
594
324
  _write_script(source, output, overwrite=overwrite)
595
325
  return output
@@ -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
@@ -1,7 +1,7 @@
1
- plotastrodata/__init__.py,sha256=_tYrE-ZW2jWY3-eX-LlXDzrpDijfWleiZx8y7wV2YEQ,87
2
- plotastrodata/_type_utils.py,sha256=0026EApTPLxkZ9NcB5QSQ-bWq2RFcq5T00wiA9iAF_8,4193
1
+ plotastrodata/__init__.py,sha256=KI3EqomaP9HpGt-2or-qOx-t3pwtl2Bch51ZOYPYxtY,87
2
+ plotastrodata/_type_utils.py,sha256=e-k_r6DA_K790Ttpz3-ZMFJgFD8pOFc2e3kUm8X4Apo,4199
3
3
  plotastrodata/_validation_utils.py,sha256=FOIOgzrP1vwuDfjqCMvYcp4yMdRjQUMtZWE-BnUXBgA,2924
4
- plotastrodata/analysis_utils.py,sha256=dkuRu93huyah4Ck1Im8kWj7sU9twfdLILi9jUaZRIsg,64333
4
+ plotastrodata/analysis_utils.py,sha256=394E5AOYQKNK5Yus7kamcZ01rhQIgcY7WCriDLXQWSk,72344
5
5
  plotastrodata/const_utils.py,sha256=8TCxHkV6P62XDGLK-t50O7P8ME10cjCS9S2DmPgi4hI,4789
6
6
  plotastrodata/coord_utils.py,sha256=0jOhLIBlUZKpHbF7o6Tvroq-ezoTLADHeR1j4v1xvGQ,9854
7
7
  plotastrodata/ext_utils.py,sha256=mi84yKu-T0lXkIk-9Fme0h5CwBu-_n3cCubLIia7tbo,5715
@@ -10,12 +10,12 @@ plotastrodata/fits_utils.py,sha256=-q0CRxUBCbTvCQoQNe9m1k2NIOcjx924FMDy3ayDnNg,2
10
10
  plotastrodata/fitting_utils.py,sha256=oP-fAXIeQR3hjal0tvftTKwWxn7MJHqS4Fl7BehnJEk,38950
11
11
  plotastrodata/los_utils.py,sha256=Q239z__C-kvzb0NR6NyGB-21quBl6KLhE2GdRMhMwn4,8112
12
12
  plotastrodata/matrix_utils.py,sha256=H6Ad9Sn8itsi0FU2D70Sb_SSJ4xmprYGueYYrIqotOY,2462
13
- plotastrodata/noise_utils.py,sha256=SPpHzPop0tzUExtP4SnQHzBCbJ6TG779R8ZmqrI5ib8,16439
14
- plotastrodata/other_utils.py,sha256=ouiizsR9-ygeaGMs7U5dy2UUEE5SRzrNKu65-EpqjRA,12124
13
+ plotastrodata/noise_utils.py,sha256=LfpAEcKiX8afOwSaXvECboiTt2LUhecLfLCeAq4L_eo,23808
14
+ plotastrodata/other_utils.py,sha256=Kjh_PYfsm09-GZ2ezq7TpMxkvgSTzRf1nvtE9lby8vE,21788
15
15
  plotastrodata/plot_utils.py,sha256=Qmb03AqL7xPa9C1vVRlOSXeVzMlxTuOxmWxAAlQjPkE,128445
16
- plotastrodata/script_utils.py,sha256=4Oa0LvhTjRF98evtbBrj1rb-eyHtQ5NJYTFSx3oXfQ4,28500
17
- plotastrodata-1.12.1.dist-info/licenses/LICENSE,sha256=OXLcl0T2SZ8Pmy2_dmlvKuetivmyPd5m1q-Gyd-zaYY,35149
18
- plotastrodata-1.12.1.dist-info/METADATA,sha256=8b9qS8Qv88vKemG2ibbAEBoFiUEY1L65R8IkLNd3ki8,5214
19
- plotastrodata-1.12.1.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
20
- plotastrodata-1.12.1.dist-info/top_level.txt,sha256=mv2FRRtreGAUE_UF_Z_TYj_NZLECJqkQx7ErkA_Rttg,14
21
- plotastrodata-1.12.1.dist-info/RECORD,,
16
+ plotastrodata/script_utils.py,sha256=F5d20-DcmwGCUdQWZXE-DYuOryJEbhUGZBBWwo2BnL4,15649
17
+ plotastrodata-1.12.3.dist-info/licenses/LICENSE,sha256=OXLcl0T2SZ8Pmy2_dmlvKuetivmyPd5m1q-Gyd-zaYY,35149
18
+ plotastrodata-1.12.3.dist-info/METADATA,sha256=RdwLRfQwfJoYDVFIXIXYMxw8pu02jcVdPiUppHhSC5c,6136
19
+ plotastrodata-1.12.3.dist-info/WHEEL,sha256=YLJXdYXQ2FQ0Uqn2J-6iEIC-3iOey8lH3xCtvFLkd8Q,91
20
+ plotastrodata-1.12.3.dist-info/top_level.txt,sha256=mv2FRRtreGAUE_UF_Z_TYj_NZLECJqkQx7ErkA_Rttg,14
21
+ plotastrodata-1.12.3.dist-info/RECORD,,
@@ -1,5 +1,5 @@
1
1
  Wheel-Version: 1.0
2
- Generator: setuptools (84.0.0)
2
+ Generator: setuptools (81.0.0)
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
5
5