plotastrodata 1.12.0__py3-none-any.whl → 1.12.2__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.0'
4
+ __version__ = '1.12.2'
@@ -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 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:
@@ -126,7 +132,9 @@ def gauss_pbcor(x: float | np.floating | np.ndarray,
126
132
  The variable of the probability density.
127
133
  s (float): Standard deviation of the Gaussian noise.
128
134
  m (float): Mean of the Gaussian noise.
129
- R (float): The maximum radius scaled by the FWHM of the primary beam.
135
+ R (float): Dimensionless outer radius r_out / r_p, where r_p is
136
+ the primary-beam half-width at half maximum (HWHM). The
137
+ primary-beam response at radius r is 2**(-(r / r_p)**2).
130
138
 
131
139
  Returns:
132
140
  float or np.longdouble or np.ndarray: Probability density.
@@ -379,3 +387,141 @@ def estimate_rms(data: np.ndarray,
379
387
  if np.abs(ave) > 0.2 * noise:
380
388
  warnings.warn('|mean| > 0.2sigma.', UserWarning)
381
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)
@@ -9,13 +9,13 @@ from astropy.wcs.utils import proj_plane_pixel_scales
9
9
  from plotastrodata.analysis_utils import AstroData, AstroFrame
10
10
 
11
11
 
12
- def _get_image_radius(fitsimage: str | Path, *, ndim: int = 2) -> float:
13
- """Validate a primary-HDU RA/Dec image or cube and return its half-width.
12
+ def _validate_fits_image(fitsimage: str | Path, *, ndim: int = 2) -> None:
13
+ """Validate the header of a primary-HDU RA/Dec image or spectral cube.
14
14
 
15
- Read only the header. The result is half the larger image dimension
16
- in arcsec, using projected WCS pixel scales, as a Python float.
17
- Internal callers use ndim=2 for an image or ndim=3 for a spectral
18
- cube. Higher axes must be singleton. Raise ValueError for unsuitable axes or spatial pixel scales.
15
+ Internal callers use ndim=2 for an image or ndim=3 for a cube.
16
+ Higher axes must be singleton. Read only the header and return None.
17
+ Raise ValueError for unsuitable axes or nonpositive/nonfinite spatial
18
+ pixel scales. No data pixels are loaded or modified.
19
19
  """
20
20
  with fits.open(fitsimage, memmap=True) as hdus:
21
21
  h = hdus[0].header
@@ -36,37 +36,8 @@ def _get_image_radius(fitsimage: str | Path, *, ndim: int = 2) -> float:
36
36
  + ' or velocity channels on the third FITS axis,'
37
37
  + ' in Hz, m/s, or km/s.')
38
38
  scales = proj_plane_pixel_scales(WCS(h, naxis=2, fix=False).celestial)
39
- rmax = max(h['NAXIS1'] * scales[0], h['NAXIS2'] * scales[1]) * 3600 / 2
40
- if not np.isfinite(rmax) or rmax <= 0:
39
+ if not np.all(np.isfinite(scales)) or np.any(scales <= 0):
41
40
  raise ValueError('Expected finite positive spatial pixel scales.')
42
- return float(rmax)
43
-
44
-
45
- def _get_valid_radius(image: AstroData, rmax: float) -> float:
46
- """Reduce a half-width to exclude nonfinite pixels, with a pixel margin.
47
-
48
- image must contain one 2D image or 3D cube already read by AstroFrame,
49
- with spatial coordinates and pixel spacings. rmax uses those same
50
- spatial units. For cubes, a
51
- spatial pixel is invalid if any channel is nonfinite. Return the
52
- half-width as a Python float; quarter-size scaling is left to the caller.
53
- Raise ValueError if no sufficiently large centered finite region remains.
54
- """
55
- if image.data.ndim == 2:
56
- valid = np.isfinite(image.data)
57
- else:
58
- valid = np.ones(image.data.shape[-2:], dtype=bool)
59
- for channel in image.data:
60
- valid &= np.isfinite(channel)
61
- invalid_y, invalid_x = np.nonzero(~valid)
62
- if invalid_x.size:
63
- nearest_invalid = np.min(np.maximum(np.abs(image.x[invalid_x]),
64
- np.abs(image.y[invalid_y])))
65
- margin = max(abs(image.dx), abs(image.dy))
66
- rmax = min(rmax, nearest_invalid - margin)
67
- if not np.isfinite(rmax) or rmax <= margin:
68
- raise ValueError('No centered finite spatial region large enough.')
69
- return float(rmax)
70
41
 
71
42
 
72
43
  def _write_script(source: str, output: Path, *, overwrite: bool = False
@@ -89,14 +60,17 @@ def generate_image_script(fitsimage: str | Path,
89
60
  *, overwrite: bool = False) -> Path:
90
61
  """Write an editable noise, Gaussian-fit, and 2D image plotting script.
91
62
 
92
- Generation reads the primary FITS image to estimate a finite fitting
93
- region, but does not execute the script or modify the input 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.
94
67
  The generated script uses the existing AstroData, AstroFrame, Noise,
95
68
  and PlotAstroData APIs directly, following example.py.
96
69
 
97
70
  Args:
98
71
  fitsimage (str | Path): A primary-HDU RA/Dec image with at least
99
72
  two pixels on each spatial axis. Any higher axes must be singleton.
73
+ Noise and range estimation assume PB-corrected intensities.
100
74
  output (str | Path | None): Script path with a .py suffix. Defaults
101
75
  to <input stem>_image.py in the current working directory.
102
76
  Relative paths are resolved at generation time.
@@ -114,14 +88,10 @@ def generate_image_script(fitsimage: str | Path,
114
88
  OSError: The input cannot be read or the script cannot be written.
115
89
 
116
90
  Notes:
117
- The initial half-width is half the larger image dimension in arcsec,
118
- using projected WCS pixel scales. If nonfinite pixels are present,
119
- it is reduced to a square around the FITS reference position that
120
- excludes them, with one spatial pixel of margin. That half-width
121
- is divided by four and rounded to eight significant digits for the
122
- inline Python float used by the fitting frame and plotting frame.
123
- Thus the full field width is one quarter of the initial valid width.
124
- This is a footprint estimate, not a measurement of source emission.
91
+ Generation estimates rmax and writes it directly into the fitting
92
+ and plotting frames, rounded to three significant digits as a
93
+ Python float literal with an inline comment. Edit it in the script
94
+ to change either field; no runtime range-selection helper is added.
125
95
 
126
96
  The generated script reads the full image with sigma=None, fits
127
97
  a hist-pbcor noise model, and saves <script stem>_noise.png. It then
@@ -131,6 +101,7 @@ def generate_image_script(fitsimage: str | Path,
131
101
  fitted sky position and saves <script stem>.png.
132
102
  Both PNGs are beside the script and follow the existing plotting
133
103
  methods' overwrite behavior. Noise statistics print with .3e format.
104
+ Changing the generated noise fit does not recompute the inline range.
134
105
  Plotting uses stretch='log', show=False, and the default fonts,
135
106
  beam, and contour levels. Edit these choices directly in the script.
136
107
  """
@@ -140,11 +111,11 @@ def generate_image_script(fitsimage: str | Path,
140
111
  output = Path(output or f'{fitsimage.stem}_image.py').resolve()
141
112
  if output.suffix != '.py':
142
113
  raise ValueError('output must have a .py suffix.')
143
- rmax = _get_image_radius(fitsimage)
114
+ _validate_fits_image(fitsimage)
144
115
  image = AstroData(fitsimage=str(fitsimage), sigma=None)
145
116
  AstroFrame().read(image)
146
- rmax = _get_valid_radius(image, rmax)
147
- rmax = float(f'{rmax / 4:.8g}')
117
+ rmax, _, _ = image.estimate_ranges(pbcor=True)
118
+ rmax = float(f'{rmax:.3g}')
148
119
  source = f'''
149
120
  from plotastrodata.analysis_utils import AstroData, AstroFrame
150
121
  from plotastrodata.noise_utils import Noise
@@ -167,15 +138,15 @@ d.sigma = n.std # A float number in the data unit is acceptable.
167
138
 
168
139
  # 2D Gaussian fitting
169
140
  d_fit = AstroData(fitsimage={str(fitsimage)!r}, sigma=d.sigma)
170
- f_fit = AstroFrame(rmax={rmax!r}) # One quarter of the valid half-width in arcsec; adjust the fit region here.
141
+ f_fit = AstroFrame(rmax={rmax!r}) # Estimated from PB-weighted emission (arcsec); adjust the fit region here.
171
142
  f_fit.read(d_fit)
172
143
  fit = d_fit.gaussfit2d(progressbar=True)
173
144
  print('Gaussian center:', fit['center'])
174
145
  print('Center uncertainties (east, north; arcsec):', fit['perr'][1:3])
175
146
 
176
147
  # 2D image
177
- p = PlotAstroData(rmax={rmax!r}, center=fit['center']) # One quarter of the valid half-width in arcsec; adjust as needed.
178
- p.add_color(**d.todict(), stretch='log', cblabel=d.bunit)
148
+ p = PlotAstroData(rmax={rmax!r}, center=fit['center']) # Estimated from PB-weighted emission (arcsec); adjust as needed.
149
+ p.add_color(**d.todict(), stretch='log')
179
150
  p.add_contour(**d.todict(), colors='r')
180
151
  p.set_axis_radec(nticksminor=5)
181
152
  p.savefig({str(output.with_suffix('.png'))!r}, show=False)
@@ -191,14 +162,17 @@ def generate_cube_script(fitsimage: str | Path,
191
162
 
192
163
  Use the existing AstroData, AstroFrame, Noise, plotprofile, and
193
164
  PlotAstroData APIs, following the line-profile and 3D channel-map
194
- sections of example.py. Generation reads
195
- the FITS header and cube pixels, but does not execute the script.
165
+ sections of example.py. Generation reads the FITS header and cube
166
+ pixels and calls AstroData.estimate_ranges(pbcor=True) to fit
167
+ edge-channel noise and estimate emission ranges. It does
168
+ not execute the generated script or modify the input FITS file.
196
169
 
197
170
  Args:
198
171
  fitsimage (str | Path): Primary-HDU RA/Dec spectral cube with at least
199
172
  two pixels on each spatial axis and two frequency or velocity
200
173
  channels on axis 3, in Hz, m/s, or km/s. Higher axes must be
201
- 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
202
176
  intensities and requires a complete beam and spatial pixel sizes.
203
177
  output (str | Path | None): Script path with a .py suffix. Defaults
204
178
  to <input stem>_cube.py in the current working directory.
@@ -224,24 +198,24 @@ def generate_cube_script(fitsimage: str | Path,
224
198
  <script stem>_noise.png beside the script.
225
199
 
226
200
  A separate AstroData instance reuses the loaded cube and is read
227
- through AstroFrame to crop it to the spatial quarter-size.
201
+ through AstroFrame to crop it to the estimated spatial and velocity
202
+ ranges, written directly in the script with inline comments.
228
203
  plotprofile integrates flux over that crop with a circle whose
229
204
  diameter is four times rmax, enclosing the entire square. Flux
230
205
  integration assumes Jy/beam intensities and requires beam metadata
231
206
  and spatial pixel sizes. The single-panel profile is saved as
232
207
  <script stem>_profile.png at intrinsic channel spacing.
233
208
 
234
- Channel maps use the full spectral range at intrinsic channel
235
- spacing, without skipping or binning. Spatial rmax starts from
236
- half the larger image dimension in arcsec. A spatial pixel is
237
- invalid if any channel there is nonfinite. If invalid pixels exist,
238
- the centered square is reduced to exclude them with one spatial
239
- pixel of margin. This valid half-width is divided by four and
240
- rounded to eight significant digits as an inline Python float
241
- for the profile crop and channel maps. The full field width is one
242
- quarter of the estimated valid width. This estimates the footprint,
243
- not the source emission. Both regions use the FITS reference center;
244
- noise uses the full cube.
209
+ Generation estimates rmax, vmin, and vmax and writes them into
210
+ both frames as Python float literals rounded to three significant
211
+ digits, with inline comments. Edit them in the generated script
212
+ to change the profile or channel-map region. Changing its noise
213
+ fit does not recompute these values.
214
+
215
+ Both profile and channel maps use the selected ranges at intrinsic
216
+ channel spacing, without skipping or binning. They plot original
217
+ PB-corrected data about the FITS reference center. The generated
218
+ noise visualization still uses the full spatial footprint.
245
219
 
246
220
  The script sets stretch='log' and show=False, with default fonts,
247
221
  beams, contours, and channel layout. Edit these choices directly.
@@ -255,11 +229,12 @@ def generate_cube_script(fitsimage: str | Path,
255
229
  output = Path(output or f'{fitsimage.stem}_cube.py').resolve()
256
230
  if output.suffix != '.py':
257
231
  raise ValueError('output must have a .py suffix.')
258
- rmax = _get_image_radius(fitsimage, ndim=3)
232
+ _validate_fits_image(fitsimage, ndim=3)
259
233
  cube = AstroData(fitsimage=str(fitsimage), sigma=None)
260
234
  AstroFrame().read(cube)
261
- rmax = _get_valid_radius(cube, rmax)
262
- rmax = float(f'{rmax / 4:.8g}')
235
+ rmax, vmin, vmax = cube.estimate_ranges(pbcor=True)
236
+ rmax = float(f'{rmax:.3g}')
237
+ vmin, vmax = float(f'{vmin:.3g}'), float(f'{vmax:.3g}')
263
238
  source = f"""
264
239
  from plotastrodata.analysis_utils import AstroData, AstroFrame
265
240
  from plotastrodata.noise_utils import Noise
@@ -282,7 +257,9 @@ d.sigma = n.std # A float number in the data unit is acceptable.
282
257
 
283
258
  # Line profile
284
259
  d_profile = AstroData(**d.todict())
285
- f_profile = AstroFrame(rmax={rmax!r}) # One quarter of the valid half-width in arcsec; adjust as needed.
260
+ f_profile = AstroFrame(rmax={rmax!r}, # Estimated spatial half-width (arcsec); adjust as needed.
261
+ vmin={vmin!r}, vmax={vmax!r}, # Estimated velocity range (km/s); adjust as needed.
262
+ )
286
263
  f_profile.read(d_profile)
287
264
  plotprofile(**d_profile.todict(), xlist=[0], ylist=[0],
288
265
  ellipse=[4 * f_profile.rmax, 4 * f_profile.rmax, 0], # Circle enclosing the cropped square.
@@ -292,8 +269,11 @@ plotprofile(**d_profile.todict(), xlist=[0], ylist=[0],
292
269
  )
293
270
 
294
271
  # 3D channel maps
295
- p = PlotAstroData(v=d.v, rmax={rmax!r}, center=d.center) # One quarter of the valid half-width in arcsec; adjust as needed.
296
- p.add_color(**d.todict(), stretch='log', cblabel=d.bunit)
272
+ p = PlotAstroData(v=d.v, center=d.center,
273
+ rmax={rmax!r}, # Estimated spatial half-width (arcsec); adjust as needed.
274
+ vmin={vmin!r}, vmax={vmax!r}, # Estimated velocity range (km/s); adjust as needed.
275
+ )
276
+ p.add_color(**d.todict(), stretch='log')
297
277
  p.add_contour(**d.todict(), colors='r')
298
278
  p.set_axis()
299
279
  p.savefig({str(output.with_suffix('.png'))!r}, show=False)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: plotastrodata
3
- Version: 1.12.0
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
@@ -101,17 +101,26 @@ Review the inline values, then run `python image.py`. The script uses existing
101
101
  library APIs to visualize a hist-pbcor noise fit, fit a 2D Gaussian and report
102
102
  its sky center and east/north uncertainties, and plot a logarithmic image
103
103
  with contours, a beam, and RA/Dec axes. It saves separate noise and image PNGs.
104
- Noise estimation uses the full image. Fitting and plotting use a centered
105
- field whose width is one quarter of the estimated valid image width.
106
- The estimated rmax is written inline for editing.
104
+ Noise estimation uses the full image. Fitting and plotting ranges are estimated automatically and written inline
105
+ with three significant digits for editing.
107
106
  For a spectral cube, use `generate_cube_script("cube.fits", output="cube.py")`
108
107
  from the same module. It generates an edge-channel noise visualization, a flux-integrated line
109
- profile over the spatial quarter-size, and 3D channel maps at the intrinsic
110
- channel spacing. The flux profile assumes Jy/beam data with beam metadata.
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.
110
+ Noise and range estimation in both generators assume PB-corrected intensities.
111
111
  Both generators return an absolute pathlib.Path and write the script
112
112
  without executing it.
113
113
  See the [script-generation guide](docs/script_generation.rst).
114
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
+
115
124
  ## Requirement
116
125
 
117
126
  * Python >= 3.11
@@ -1,7 +1,7 @@
1
- plotastrodata/__init__.py,sha256=PhXrmmIl9fwMyvQqqlaFE59q-Kq2QShRqLot7tJ1UNI,87
2
- plotastrodata/_type_utils.py,sha256=0026EApTPLxkZ9NcB5QSQ-bWq2RFcq5T00wiA9iAF_8,4193
1
+ plotastrodata/__init__.py,sha256=aIs2sfHdFR0u_mYmEt0mQH-Z8VeOjbdDIQlvlPb4u9s,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=Io_v4PBcO9N8XFx7-haPeRstSJ1kN2gym-paCjT46uo,66288
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=9r70QD1HX0GdZtel3Ug7BfHqWXzvLPCDl332aG6U5ng,16308
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=4-r87HfpKGT1HpvVrwonyP2zYKAYpdVslQxdKuJHzkY,14395
17
- plotastrodata-1.12.0.dist-info/licenses/LICENSE,sha256=OXLcl0T2SZ8Pmy2_dmlvKuetivmyPd5m1q-Gyd-zaYY,35149
18
- plotastrodata-1.12.0.dist-info/METADATA,sha256=FkpgjmHYOLi0_Z7QJl78v7YduCD3xqYd2EhFMFeXWIQ,5240
19
- plotastrodata-1.12.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
20
- plotastrodata-1.12.0.dist-info/top_level.txt,sha256=mv2FRRtreGAUE_UF_Z_TYj_NZLECJqkQx7ErkA_Rttg,14
21
- plotastrodata-1.12.0.dist-info/RECORD,,
16
+ plotastrodata/script_utils.py,sha256=SsdGUcSyUnHv4WbZJ0JKGyK5TJ5lxX8ym93wCQOgNy4,13407
17
+ plotastrodata-1.12.2.dist-info/licenses/LICENSE,sha256=OXLcl0T2SZ8Pmy2_dmlvKuetivmyPd5m1q-Gyd-zaYY,35149
18
+ plotastrodata-1.12.2.dist-info/METADATA,sha256=ill1Njb4pf7Ty3e2s8Pw8CS6w8gQ7g_1NO-A6KQzfwA,5862
19
+ plotastrodata-1.12.2.dist-info/WHEEL,sha256=YLJXdYXQ2FQ0Uqn2J-6iEIC-3iOey8lH3xCtvFLkd8Q,91
20
+ plotastrodata-1.12.2.dist-info/top_level.txt,sha256=mv2FRRtreGAUE_UF_Z_TYj_NZLECJqkQx7ErkA_Rttg,14
21
+ plotastrodata-1.12.2.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