plotastrodata 1.13.1__tar.gz → 1.13.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. {plotastrodata-1.13.1/plotastrodata.egg-info → plotastrodata-1.13.2}/PKG-INFO +1 -1
  2. {plotastrodata-1.13.1 → plotastrodata-1.13.2}/plotastrodata/__init__.py +1 -1
  3. {plotastrodata-1.13.1 → plotastrodata-1.13.2}/plotastrodata/analysis_utils.py +100 -47
  4. {plotastrodata-1.13.1 → plotastrodata-1.13.2}/plotastrodata/coord_utils.py +2 -2
  5. {plotastrodata-1.13.1 → plotastrodata-1.13.2}/plotastrodata/fft_utils.py +4 -4
  6. {plotastrodata-1.13.1 → plotastrodata-1.13.2}/plotastrodata/fits_utils.py +7 -7
  7. {plotastrodata-1.13.1 → plotastrodata-1.13.2}/plotastrodata/fitting_utils.py +134 -14
  8. {plotastrodata-1.13.1 → plotastrodata-1.13.2}/plotastrodata/noise_utils.py +11 -11
  9. {plotastrodata-1.13.1 → plotastrodata-1.13.2}/plotastrodata/other_utils.py +5 -5
  10. {plotastrodata-1.13.1 → plotastrodata-1.13.2}/plotastrodata/plot_utils.py +32 -32
  11. {plotastrodata-1.13.1 → plotastrodata-1.13.2}/plotastrodata/pngpdf_utils.py +2 -2
  12. {plotastrodata-1.13.1 → plotastrodata-1.13.2}/plotastrodata/script_utils.py +3 -3
  13. {plotastrodata-1.13.1 → plotastrodata-1.13.2/plotastrodata.egg-info}/PKG-INFO +1 -1
  14. {plotastrodata-1.13.1 → plotastrodata-1.13.2}/LICENSE +0 -0
  15. {plotastrodata-1.13.1 → plotastrodata-1.13.2}/MANIFEST.in +0 -0
  16. {plotastrodata-1.13.1 → plotastrodata-1.13.2}/README.md +0 -0
  17. {plotastrodata-1.13.1 → plotastrodata-1.13.2}/plotastrodata/_ptemcee_compat.py +0 -0
  18. {plotastrodata-1.13.1 → plotastrodata-1.13.2}/plotastrodata/_type_utils.py +0 -0
  19. {plotastrodata-1.13.1 → plotastrodata-1.13.2}/plotastrodata/_validation_utils.py +0 -0
  20. {plotastrodata-1.13.1 → plotastrodata-1.13.2}/plotastrodata/const_utils.py +0 -0
  21. {plotastrodata-1.13.1 → plotastrodata-1.13.2}/plotastrodata/ext_utils.py +0 -0
  22. {plotastrodata-1.13.1 → plotastrodata-1.13.2}/plotastrodata/los_utils.py +0 -0
  23. {plotastrodata-1.13.1 → plotastrodata-1.13.2}/plotastrodata/matrix_utils.py +0 -0
  24. {plotastrodata-1.13.1 → plotastrodata-1.13.2}/plotastrodata.egg-info/SOURCES.txt +0 -0
  25. {plotastrodata-1.13.1 → plotastrodata-1.13.2}/plotastrodata.egg-info/dependency_links.txt +0 -0
  26. {plotastrodata-1.13.1 → plotastrodata-1.13.2}/plotastrodata.egg-info/not-zip-safe +0 -0
  27. {plotastrodata-1.13.1 → plotastrodata-1.13.2}/plotastrodata.egg-info/requires.txt +0 -0
  28. {plotastrodata-1.13.1 → plotastrodata-1.13.2}/plotastrodata.egg-info/top_level.txt +0 -0
  29. {plotastrodata-1.13.1 → plotastrodata-1.13.2}/setup.cfg +0 -0
  30. {plotastrodata-1.13.1 → plotastrodata-1.13.2}/setup.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: plotastrodata
3
- Version: 1.13.1
3
+ Version: 1.13.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
@@ -1,4 +1,4 @@
1
1
  import warnings
2
2
 
3
3
  warnings.simplefilter('ignore', FutureWarning)
4
- __version__ = '1.13.1'
4
+ __version__ = '1.13.2'
@@ -4,7 +4,8 @@ import warnings
4
4
  from dataclasses import dataclass, field
5
5
  from functools import wraps
6
6
  from os import PathLike
7
- from typing import Any, Callable, Literal, ParamSpec, TypedDict, TypeVar
7
+ from typing import (Any, Callable, Literal,
8
+ ParamSpec, TypedDict, TypeVar)
8
9
 
9
10
  import numpy as np
10
11
  from astropy.io.fits import Header
@@ -33,7 +34,7 @@ from plotastrodata._validation_utils import (
33
34
  from plotastrodata.coord_utils import _getframe, coord2xy, rel2abs, xy2coord
34
35
  from plotastrodata.fits_utils import FitsData, Jy2K, data2fits
35
36
  from plotastrodata.fitting_utils import (
36
- EmceeCorner, gaussfit1d, gaussfit2d, gaussian2d
37
+ EmceeCorner, gaussfit1d, gaussfit2d, gaussian2d, gaussian_deconvolve
37
38
  )
38
39
  from plotastrodata.matrix_utils import Mfac, Mrot, dot2d
39
40
  from plotastrodata.noise_utils import estimate_ranges, estimate_rms
@@ -55,14 +56,14 @@ def _validate_moment_cube(data: np.ndarray, v: np.ndarray,
55
56
  or data.dtype.kind not in 'iuf'
56
57
  or np.any(np.isinf(data))):
57
58
  raise ValueError('moment requires a nonempty real 3D cube'
58
- + ' without infinities.')
59
+ ' without infinities.')
59
60
  if not isinstance(v, np.ndarray):
60
61
  raise TypeError('moment requires v to be a NumPy array.')
61
62
  if (v.ndim != 1 or v.size != data.shape[0]
62
63
  or v.dtype.kind not in 'iuf'
63
64
  or not np.all(np.isfinite(v))):
64
65
  raise ValueError('v must be a finite real 1D grid matching'
65
- + ' the number of channels.')
66
+ ' the number of channels.')
66
67
  if not _is_positive_real_scalar(sigma):
67
68
  raise ValueError('moment requires finite positive scalar sigma.')
68
69
  if not _is_finite_real_scalar(dv) or dv == 0:
@@ -73,7 +74,7 @@ def _validate_moment_cube(data: np.ndarray, v: np.ndarray,
73
74
  or not _is_uniform_spacing(steps, steps[0])
74
75
  or not _is_uniform_spacing(np.abs(steps), abs(dv))):
75
76
  raise ValueError('v must be monotonic and uniformly spaced'
76
- + ' with spacing magnitude abs(dv).')
77
+ ' with spacing magnitude abs(dv).')
77
78
 
78
79
 
79
80
  def _validate_moment_inputs(data: np.ndarray, v: np.ndarray,
@@ -92,7 +93,7 @@ def _validate_moment_inputs(data: np.ndarray, v: np.ndarray,
92
93
  ('threshold_mom0', threshold_mom0)):
93
94
  if not _is_finite_real_scalar(value) or value < 0:
94
95
  raise ValueError(f'{name} must be a finite nonnegative'
95
- + ' real scalar.')
96
+ ' real scalar.')
96
97
  if vmask is None:
97
98
  vmask = np.ones(v.size, dtype=bool)
98
99
  elif not isinstance(vmask, np.ndarray):
@@ -100,7 +101,7 @@ def _validate_moment_inputs(data: np.ndarray, v: np.ndarray,
100
101
  if (vmask.dtype.kind != 'b' or vmask.shape != v.shape
101
102
  or not np.any(vmask)):
102
103
  raise ValueError('vmask must be a 1D Boolean array matching v'
103
- + ' and selecting at least one channel.')
104
+ ' and selecting at least one channel.')
104
105
 
105
106
  return vmask
106
107
 
@@ -115,12 +116,12 @@ def _profile_ellipses(ellipse: Any, nprof: int) -> np.ndarray:
115
116
  ellipses = np.broadcast_to(ellipses, (nprof, 3))
116
117
  elif ellipses.shape != (nprof, 3):
117
118
  raise ValueError('ellipse must be one [major, minor, pa] triple'
118
- + ' or exactly one triple per position.')
119
+ ' or exactly one triple per position.')
119
120
  if (ellipses.dtype.kind not in 'iuf'
120
121
  or not np.all(np.isfinite(ellipses))
121
122
  or np.any(ellipses[:, :2] < 0)):
122
123
  raise ValueError('ellipse values must be finite real numbers'
123
- + ' with nonnegative major and minor sizes.')
124
+ ' with nonnegative major and minor sizes.')
124
125
  return ellipses
125
126
 
126
127
 
@@ -200,7 +201,7 @@ def _need_multipixels(method: Callable[_MethodArgs, _MethodResult]
200
201
  singlepixel = cls.dx is None or cls.dy is None
201
202
  if singlepixel:
202
203
  raise ValueError(f'{method.__name__}() requires at least'
203
- + ' two x and y pixels.')
204
+ ' two x and y pixels.')
204
205
  return method(*args, **kwargs)
205
206
  return wrapper
206
207
 
@@ -229,7 +230,15 @@ class _Fit2DResult(TypedDict):
229
230
  residual: np.ndarray
230
231
 
231
232
 
232
- class _GaussFit2DResult(TypedDict):
233
+ class _GaussianDeconvolutionResult(TypedDict):
234
+ deconvolved: tuple[float | np.longdouble,
235
+ float | np.longdouble,
236
+ float | np.longdouble] | None
237
+ deconvolution_status: Literal['success', 'unresolved',
238
+ 'missing_beam', 'unsupported_pv']
239
+
240
+
241
+ class _GaussFit2DResult(_GaussianDeconvolutionResult):
233
242
  popt: np.ndarray
234
243
  perr: np.ndarray
235
244
  model: np.ndarray
@@ -335,8 +344,8 @@ class AstroData():
335
344
  for i, data in enumerate(datasets):
336
345
  if data is not None and np.ndim(data) == 0:
337
346
  raise ValueError(f'Dataset {i} must be an array '
338
- + 'with spatial axes, not a scalar'
339
- + ' or zero-dimensional array.')
347
+ 'with spatial axes, not a scalar'
348
+ ' or zero-dimensional array.')
340
349
  self.n = n
341
350
  self.fitsimage_org = None
342
351
  self.sigma_org = None
@@ -350,7 +359,7 @@ class AstroData():
350
359
  return
351
360
  if grid is None:
352
361
  raise ValueError(f'Binning in the {t}-axis requires'
353
- + f' a {t} coordinate array.')
362
+ f' a {t} coordinate array.')
354
363
 
355
364
  dt = f'd{t}'
356
365
  sep = getattr(self, dt)
@@ -420,17 +429,17 @@ class AstroData():
420
429
  for axis, factor in zip(('v', 'y', 'x'), w):
421
430
  if factor > 1 and getattr(self, axis) is None:
422
431
  raise ValueError(f'Binning in the {axis}-axis requires'
423
- + ' a coordinate array.')
432
+ ' a coordinate array.')
424
433
  velocity_binning = (not self.pv and w[0] > 1) or (self.pv and w[1] > 1)
425
434
  if velocity_binning and isinstance(self.sigma, str):
426
435
  raise ValueError('Estimate sigma before velocity binning,'
427
- + ' or set sigma=None.')
436
+ ' or set sigma=None.')
428
437
  self.data = data4d
429
438
  if velocity_binning:
430
439
  width_v = w[1] if self.pv else w[0]
431
440
  if self.sigma is not None:
432
441
  print(f'sigma has been divided by sqrt({width_v:d})'
433
- + ' because of binning in the v-axis.')
442
+ ' because of binning in the v-axis.')
434
443
  self.sigma = _normalize_float(self.sigma / np.sqrt(width_v))
435
444
  if (not self.pv and w[1] > 1) or w[2] > 1:
436
445
  print('Binning in the x- or y-axis does not update sigma.')
@@ -494,7 +503,7 @@ class AstroData():
494
503
  bmaj, bmin, bpa = self.beam
495
504
  if not np.all(np.isfinite([bmaj, bmin, bpa])) or not 0 < bmin <= bmaj:
496
505
  raise ValueError('circularbeam requires finite beam values'
497
- + ' with major >= minor > 0.')
506
+ ' with major >= minor > 0.')
498
507
  if bmaj == bmin:
499
508
  return
500
509
  self.rotate(-bpa)
@@ -571,7 +580,7 @@ class AstroData():
571
580
  raise ValueError('Fitting requires finite, nonzero pixel sizes.')
572
581
  factor = np.pi * sizes[0] * sizes[1] / (4 * np.log(2) * area)
573
582
  print('In the fitting, sigma is multiplied by sqrt(pixel-per-beam)'
574
- + ' to account for beam noise correlation.')
583
+ ' to account for beam noise correlation.')
575
584
  return factor
576
585
 
577
586
  @_need_multipixels
@@ -624,7 +633,7 @@ class AstroData():
624
633
  result = model(p, x, y)
625
634
  if not isinstance(result, np.ndarray) or result.shape != d.shape:
626
635
  raise ValueError('model must return an ndarray matching'
627
- + ' the selected image shape.')
636
+ ' the selected image shape.')
628
637
  return result
629
638
 
630
639
  def logl(p: np.ndarray) -> float | np.floating:
@@ -688,6 +697,34 @@ class AstroData():
688
697
  return estimate_ranges(self.data, self.x, self.y, self.sigma,
689
698
  v=v, beam=self.beam, pbcor=pbcor)
690
699
 
700
+ def _validate_deconvolution_beam(self) -> None:
701
+ """Reject invalid spatial beam metadata before running the fit."""
702
+ if not self.pv:
703
+ if (not isinstance(self.beam, (list, tuple, np.ndarray))
704
+ or np.shape(self.beam) != (3,)):
705
+ raise ValueError('Deconvolution requires a three-entry beam.')
706
+ if all(v is not None for v in self.beam):
707
+ if (not all(_is_finite_real_scalar(v) for v in self.beam)
708
+ or any(v < 0 for v in self.beam[:2])):
709
+ raise ValueError('Deconvolution requires finite beam values'
710
+ ' and nonnegative widths.')
711
+
712
+ def _deconvolve_gaussian_fit(self, shape: np.ndarray
713
+ ) -> _GaussianDeconvolutionResult:
714
+ """Describe intrinsic shape availability without changing the fit."""
715
+ if self.pv:
716
+ return {'deconvolved': None,
717
+ 'deconvolution_status': 'unsupported_pv'}
718
+ if any(v is None for v in self.beam):
719
+ return {'deconvolved': None,
720
+ 'deconvolution_status': 'missing_beam'}
721
+ try:
722
+ intrinsic = gaussian_deconvolve(shape, self.beam)
723
+ except ValueError:
724
+ return {'deconvolved': None,
725
+ 'deconvolution_status': 'unresolved'}
726
+ return {'deconvolved': intrinsic, 'deconvolution_status': 'success'}
727
+
691
728
  @_need_multipixels
692
729
  def gaussfit2d(self, chan: int | np.integer | None = None,
693
730
  *, progressbar: bool = False) -> _GaussFit2DResult:
@@ -708,14 +745,30 @@ class AstroData():
708
745
  the best 2D Gaussian array (model), the residual from the
709
746
  model (residual), and the coordinates of the best-fit center
710
747
  (center). The fitted spatial offsets are divided by dist before
711
- conversion to sky coordinates.
748
+ conversion to sky coordinates. All these observed-fit outputs
749
+ retain their observed-fit meaning. Deconvolution is always
750
+ attempted for spatial images and cube channels using self.beam.
751
+ The deconvolved result is a (major FWHM, minor FWHM, PA) tuple
752
+ or None; deconvolution_status is success, unresolved (no Gaussian
753
+ solution), missing_beam (any beam entry is None), or unsupported_pv.
754
+ Successful zero-width limiting solutions are allowed. Scalars are
755
+ Python floats, preserving extended-precision NumPy floating
756
+ scalars. No intrinsic uncertainties or upper limits are computed;
757
+ perr remains the observed-fit uncertainty.
758
+
759
+ Notes:
760
+ The fit and self.beam must use the same length units and current
761
+ coordinate frame. PA is measured from +y toward +x. The processed
762
+ beam is used directly after swapxy; display flips need no angle
763
+ correction. Invalid complete beam metadata raises ValueError.
712
764
  """
765
+ self._validate_deconvolution_beam()
713
766
  z = self._fit_image(chan)
714
767
  if z.shape != (len(self.y), len(self.x)):
715
768
  raise ValueError('Selected image shape must match the x/y grids.')
716
769
  if self.sigma is not None and not _is_positive_real_scalar(self.sigma):
717
770
  raise ValueError('gaussfit2d requires finite, positive scalar'
718
- + ' sigma or None.')
771
+ ' sigma or None.')
719
772
  # Automatic estimation is handled by the underlying fitter; there is
720
773
  # no supplied sigma to scale in that case.
721
774
  sigma = None
@@ -733,9 +786,9 @@ class AstroData():
733
786
  coordorg=self.center)
734
787
  else:
735
788
  newcenter = None
736
- return {'popt': popt, 'perr': perr,
737
- 'model': model, 'residual': residual,
738
- 'center': newcenter}
789
+ return {'popt': popt, 'perr': perr, 'model': model,
790
+ 'residual': residual, 'center': newcenter,
791
+ **self._deconvolve_gaussian_fit(popt[3:6])}
739
792
 
740
793
  def histogram(self, **kwargs: Any) -> tuple[np.ndarray, np.ndarray]:
741
794
  """Output histogram of self.data using numpy.histogram. This
@@ -772,7 +825,7 @@ class AstroData():
772
825
  dataformask = self.data
773
826
  if len(includepix) not in [0, 2] or len(excludepix) not in [0, 2]:
774
827
  raise ValueError('includepix and excludepix must be empty'
775
- + ' or [min, max].')
828
+ ' or [min, max].')
776
829
  if np.ndim(self.data) > np.ndim(dataformask):
777
830
  print('The mask is broadcasted.')
778
831
  try:
@@ -780,15 +833,15 @@ class AstroData():
780
833
  except ValueError as exc:
781
834
  raise ValueError('dataformask must be broadcastable'
782
835
  ' to the data shape;'
783
- + f' got {np.shape(dataformask)}'
784
- + f' and {np.shape(self.data)}.') from exc
836
+ f' got {np.shape(dataformask)}'
837
+ f' and {np.shape(self.data)}.') from exc
785
838
  else:
786
839
  mask = dataformask
787
840
  if np.shape(self.data) != np.shape(mask):
788
841
  raise ValueError('dataformask must have the same shape as data'
789
- + ' after broadcasting;'
790
- + f' got {np.shape(dataformask)}'
791
- + f' and {np.shape(self.data)}.')
842
+ ' after broadcasting;'
843
+ f' got {np.shape(dataformask)}'
844
+ f' and {np.shape(self.data)}.')
792
845
 
793
846
  if ((len(includepix) == 2 or len(excludepix) == 2)
794
847
  and self.data.dtype.kind in 'biu'):
@@ -1042,16 +1095,16 @@ class AstroData():
1042
1095
  """Convert velocity reference and spacing, preserving scalar precision."""
1043
1096
  if self.v is None or self.dv is None:
1044
1097
  raise ValueError('Writing a velocity axis requires coordinates'
1045
- + ' and spacing.')
1098
+ ' and spacing.')
1046
1099
  cv, dv = self.v[ck], self.dv
1047
1100
  if (self.restfreq is not None
1048
1101
  and (not _is_finite_real_scalar(self.restfreq)
1049
1102
  or self.restfreq < 0)):
1050
1103
  raise ValueError('restfreq must be finite and positive,'
1051
- + ' or None/0.')
1104
+ ' or None/0.')
1052
1105
  if self.restfreq is None or self.restfreq == 0:
1053
1106
  warnings.warn('No valid restfreq.'
1054
- + ' The velocity axis is saved as is.',
1107
+ ' The velocity axis is saved as is.',
1055
1108
  UserWarning)
1056
1109
  else:
1057
1110
  cv = (1 - cv / cu.c_kms) * self.restfreq
@@ -1094,7 +1147,7 @@ class AstroData():
1094
1147
  """Add frequency or velocity cards to the cube/PV spectral axis."""
1095
1148
  if self.v is None:
1096
1149
  raise ValueError('A cube or PV image requires'
1097
- + ' velocity coordinates.')
1150
+ ' velocity coordinates.')
1098
1151
  ck = nearest_index(self.v)
1099
1152
  cv, dv = self._get_cvdv_in_freq(ck)
1100
1153
  axis = 2 if self.pv else 3
@@ -1127,7 +1180,7 @@ class AstroData():
1127
1180
  h['BPA'] = float(beam[2])
1128
1181
  elif self.pv and not all(k in h for k in ('BMAJ', 'BMIN', 'BPA')):
1129
1182
  warnings.warn('Original sky beam unavailable;'
1130
- + ' omitting FITS beam metadata.',
1183
+ ' omitting FITS beam metadata.',
1131
1184
  UserWarning)
1132
1185
  for key in ('BMAJ', 'BMIN', 'BPA'):
1133
1186
  h.pop(key, None)
@@ -1158,7 +1211,7 @@ class AstroData():
1158
1211
  if (not isinstance(self.data, np.ndarray)
1159
1212
  or self.data.ndim not in (2, 3)):
1160
1213
  raise ValueError('writetofits requires a single 2D image'
1161
- + ' or 3D cube.')
1214
+ ' or 3D cube.')
1162
1215
  _require_positive_real_scalar(self.dist, 'dist')
1163
1216
  h = self._build_fits_header()
1164
1217
  h.update(header or {})
@@ -1207,9 +1260,9 @@ def _validate_shared_grid(expected_grid: _Grid, actual_grid: _Grid,
1207
1260
  rtol=1e-7, atol=0))
1208
1261
  if not same:
1209
1262
  raise ValueError(f'Dataset {dataset} has a different'
1210
- + f' processed {name} grid; datasets'
1211
- + ' in one AstroData must share'
1212
- + ' coordinate grids.')
1263
+ f' processed {name} grid; datasets'
1264
+ ' in one AstroData must share'
1265
+ ' coordinate grids.')
1213
1266
 
1214
1267
 
1215
1268
  def _prepare_positions(poslist: Position | list[Position]
@@ -1235,7 +1288,7 @@ def _prepare_positions(poslist: Position | list[Position]
1235
1288
  for position in poslist:
1236
1289
  if not isinstance(position, str) and not is_pair(position):
1237
1290
  raise ValueError('Each numeric position must contain'
1238
- + ' two real scalars.')
1291
+ ' two real scalars.')
1239
1292
  return poslist
1240
1293
 
1241
1294
 
@@ -1365,9 +1418,9 @@ class AstroFrame():
1365
1418
  if self.center is None and any(isinstance(p, str) for p in poslist):
1366
1419
  clsname = type(self).__name__
1367
1420
  raise ValueError(f'{clsname}.pos2xy() requires "center"'
1368
- + ' when poslist contains sky-coordinate strings.'
1369
- + ' Set "center" explicitly or "fitsimage"'
1370
- + ' from which the center can be determined.')
1421
+ ' when poslist contains sky-coordinate strings.'
1422
+ ' Set "center" explicitly or "fitsimage"'
1423
+ ' from which the center can be determined.')
1371
1424
  x, y = [None] * len(poslist), [None] * len(poslist)
1372
1425
  for i, p in enumerate(poslist):
1373
1426
  if isinstance(p, str):
@@ -1499,8 +1552,8 @@ class AstroFrame():
1499
1552
  dx = d.dy if self.swapxy else d.dx
1500
1553
  if dx is None:
1501
1554
  raise ValueError('Brightness-temperature conversion requires'
1502
- + ' beam sizes or at least two spatial pixels'
1503
- + ' to determine pixel size.')
1555
+ ' beam sizes or at least two spatial pixels'
1556
+ ' to determine pixel size.')
1504
1557
  header.update(CDELT1=dx / self.dist / 3600, CUNIT1='deg')
1505
1558
  factor = Jy2K(header=header)
1506
1559
  d.data[i] = d.data[i] * factor
@@ -1609,4 +1662,4 @@ class AstroFrame():
1609
1662
  setattr(d, name, _scalar_if_single(getattr(d, name), d.n))
1610
1663
  if self.swapxy:
1611
1664
  print('x and y axes have been swapped; subsequent AstroData'
1612
- + ' operations use the current axis order.')
1665
+ ' operations use the current axis order.')
@@ -57,7 +57,7 @@ def _getframe(coord: str | list | tuple | np.ndarray, *, as_frame: bool = False
57
57
  for i, value in enumerate(values.flat):
58
58
  if not isinstance(value, str):
59
59
  raise ValueError('Coordinates must be strings'
60
- + ' in a rectangular collection.')
60
+ ' in a rectangular collection.')
61
61
  parts = value.split()
62
62
  hasframe = len(parts) == 3
63
63
  parsed.append(f'{parts[1]} {parts[2]}' if hasframe else value)
@@ -152,7 +152,7 @@ def xy2coord(xy: list | tuple | np.ndarray,
152
152
  offsets = np.asarray(xy)
153
153
  if offsets.ndim == 0 or offsets.shape[0] != 2:
154
154
  raise ValueError('xy must have shape (2, ...)'
155
- + ' with matching coordinate shapes.')
155
+ ' with matching coordinate shapes.')
156
156
  shape = offsets.shape[1:]
157
157
  if offsets.size == 0:
158
158
  return np.empty(shape, dtype=str)
@@ -120,17 +120,17 @@ def _ifft_xsize(nfreq: int, u: np.ndarray | None, dx: float,
120
120
  """Resolve inverse-transform length without resizing the spectrum."""
121
121
  if nfreq < 2:
122
122
  raise ValueError('Inverse centering requires at least'
123
- + ' two x-frequency samples.')
123
+ ' two x-frequency samples.')
124
124
  if u is not None and (np.ndim(u) != 1 or len(u) != nfreq):
125
125
  raise ValueError(f'u must be a 1D grid with {nfreq} points, matching '
126
- + 'the number of x-frequency samples in F.')
126
+ 'the number of x-frequency samples in F.')
127
127
  if nx is not None:
128
128
  if not rfft:
129
129
  raise ValueError('nx is only supported when rfft=True.')
130
130
  _require_integer(nx, 'nx', minimum=2)
131
131
  if int(nx) // 2 + 1 != nfreq:
132
132
  raise ValueError(f'nx={nx} must satisfy nx // 2 + 1 == {nfreq}, '
133
- + 'the number of x-frequency samples in F.')
133
+ 'the number of x-frequency samples in F.')
134
134
  return int(nx)
135
135
  if not rfft:
136
136
  return nfreq
@@ -480,7 +480,7 @@ def findindex(u: np.ndarray | None = None, v: np.ndarray | None = None,
480
480
  return None
481
481
  if grid is None or np.ndim(grid) != 1 or len(grid) < 2:
482
482
  raise ValueError(f'{name} observations require a 1D {name} grid '
483
- + 'with at least two points.')
483
+ 'with at least two points.')
484
484
  step = grid[1] - grid[0]
485
485
  if not np.isfinite(step) or step == 0:
486
486
  raise ValueError(f'{name} grid spacing must be finite and nonzero.')
@@ -79,12 +79,12 @@ def Jy2K(header: fits.Header | dict[str, Any] | None = None,
79
79
  bmaj, bmin, freq = _jy2k_metadata(header, bmaj, bmin, restfreq)
80
80
  if freq is None:
81
81
  raise ValueError('Brightness-temperature conversion requires restfreq'
82
- + ' or a RESTFREQ/RESTFRQ header value.')
82
+ ' or a RESTFREQ/RESTFRQ header value.')
83
83
  _require_positive_real_scalar(freq, 'restfreq')
84
84
  if not _is_positive_real_scalar(bmaj) or not _is_positive_real_scalar(bmin):
85
85
  raise ValueError('Brightness-temperature conversion requires finite,'
86
- + ' positive bmaj and bmin values'
87
- + ' or equivalent FITS header metadata.')
86
+ ' positive bmaj and bmin values'
87
+ ' or equivalent FITS header metadata.')
88
88
  omega = bmaj * bmin * units.arcsec**2 * np.pi / 4. / np.log(2.)
89
89
  equiv = units.brightness_temperature(freq * units.Hz, beam_area=omega)
90
90
  T = (1 * units.Jy / units.beam).to(units.K, equivalencies=equiv)
@@ -234,7 +234,7 @@ class FitsData:
234
234
  h, d = self.hdu.header, self.hdu.data
235
235
  if d is None:
236
236
  raise ValueError(f'Primary HDU in {self.fitsimage!s}'
237
- + ' contains no data.')
237
+ ' contains no data.')
238
238
  if drop:
239
239
  d = np.squeeze(d)
240
240
  if Tb:
@@ -281,7 +281,7 @@ class FitsData:
281
281
  rho_b = np.arctan2(np.abs(cd12), -np.sign(cd12) * cd22)
282
282
  if (drho := np.abs(np.degrees(rho_a - rho_b))) > 1.0:
283
283
  print('Angles from (CD21, CD11) and (CD12, CD22)'
284
- + f' are different by {drho:.2} degrees.')
284
+ f' are different by {drho:.2} degrees.')
285
285
  crota2 = (rho_a + rho_b) / 2.
286
286
  sin_rho = np.sin(crota2)
287
287
  cos_rho = np.cos(crota2)
@@ -368,7 +368,7 @@ class FitsData:
368
368
  if restfreq is None:
369
369
  freq = np.mean(v)
370
370
  print('restfreq is assumed to be'
371
- + ' the mean channel frequency.')
371
+ ' the mean channel frequency.')
372
372
  else:
373
373
  freq = restfreq
374
374
  if freq == 0:
@@ -383,7 +383,7 @@ class FitsData:
383
383
  v = v - vsys
384
384
  case _:
385
385
  print(f'Unknown CUNIT3 {cunitv} found.'
386
- + ' v is read as is.')
386
+ ' v is read as is.')
387
387
  dv = None if len(v) <= 1 else _normalize_float(v[1] - v[0])
388
388
  self.v, self.dv = v, dv
389
389
 
@@ -14,7 +14,7 @@ import matplotlib.pyplot as plt
14
14
  import numpy as np
15
15
  from matplotlib.figure import Figure
16
16
 
17
- from plotastrodata._type_utils import _normalize_float
17
+ from plotastrodata._type_utils import RealSequence, _normalize_float
18
18
  from plotastrodata._validation_utils import _require_integer
19
19
  from plotastrodata.matrix_utils import Mrot, dot2d
20
20
  from plotastrodata.other_utils import close_figure
@@ -178,10 +178,10 @@ class EmceeCorner():
178
178
  if (not np.all(np.isfinite(global_bounds))
179
179
  or np.any(global_bounds[:, 0] >= global_bounds[:, 1])):
180
180
  raise ValueError('Each parameter bound must be finite'
181
- + ' with lower < upper.')
181
+ ' with lower < upper.')
182
182
  if (len(percent) != 2 or not 0 <= percent[0] < percent[1] <= 100):
183
183
  raise ValueError('percent must contain two increasing values'
184
- + ' between 0 and 100.')
184
+ ' between 0 and 100.')
185
185
  global_progressbar = progressbar
186
186
  if logl is None and (model is not None
187
187
  and xdata is not None
@@ -190,7 +190,7 @@ class EmceeCorner():
190
190
  xdata=xdata, ydata=ydata, sigma=sigma)
191
191
  if logl is None:
192
192
  raise ValueError('Provide logl, or provide model, xdata,'
193
- + ' and ydata together.')
193
+ ' and ydata together.')
194
194
  self.bounds = global_bounds
195
195
  self.dim = len(self.bounds)
196
196
  self.logl = logl
@@ -225,9 +225,9 @@ class EmceeCorner():
225
225
  pickle.dumps(self.logl)
226
226
  except (pickle.PicklingError, AttributeError, TypeError) as exc:
227
227
  raise TypeError('logl and model must be pickleable'
228
- + ' when ncores > 1. Define them'
229
- + ' at module scope instead of inside'
230
- + ' another function.') from exc
228
+ ' when ncores > 1. Define them'
229
+ ' at module scope instead of inside'
230
+ ' another function.') from exc
231
231
 
232
232
  emcee = _import_fitting_package("emcee")
233
233
  sampler_cls = emcee.EnsembleSampler
@@ -646,6 +646,125 @@ class EmceeCorner():
646
646
  return {'evidence': self.evidence, 'error': _normalize_float(error)}
647
647
 
648
648
 
649
+ def _gaussian_shape(value: RealSequence, name: str) -> np.ndarray:
650
+ """Validate a single FWHM/angle triple without narrowing precision."""
651
+ if not isinstance(value, (list, tuple, np.ndarray)):
652
+ raise TypeError(f'{name} must be a list, tuple, or array of three reals.')
653
+ if np.shape(value) != (3,):
654
+ raise ValueError(f'{name} must have shape (3,).')
655
+ if any(isinstance(v, (bool, np.bool_))
656
+ or not isinstance(v, (int, float, np.integer, np.floating))
657
+ for v in value):
658
+ raise TypeError(f'{name} entries must be real scalars,'
659
+ ' excluding booleans.')
660
+ shape = np.asarray(value, dtype=np.result_type(*value, np.float64))
661
+ if not np.all(np.isfinite(shape)) or np.any(shape[:2] < 0):
662
+ raise ValueError(f'{name} requires finite values'
663
+ ' and nonnegative widths.')
664
+ return shape
665
+
666
+
667
+ def _combine_gaussians(first: RealSequence, second: RealSequence,
668
+ subtract: bool
669
+ ) -> tuple[float | np.longdouble,
670
+ float | np.longdouble,
671
+ float | np.longdouble]:
672
+ """Combine squared FWHM matrices through their trace and anisotropy."""
673
+ g1 = _gaussian_shape(first, 'observed' if subtract else 'gaussian1')
674
+ g2 = _gaussian_shape(second, 'kernel' if subtract else 'gaussian2')
675
+ dtype = np.result_type(g1.dtype, g2.dtype)
676
+ g1, g2 = g1.astype(dtype), g2.astype(dtype)
677
+ scale = max(*g1[:2], *g2[:2])
678
+ if scale == 0:
679
+ zero = _normalize_float(dtype.type(0), force_float=True)
680
+ return zero, zero, zero
681
+ # Scaling before squaring avoids overflow for large finite widths.
682
+ a, b = (g1[:2] / scale)**2
683
+ c, d = (g2[:2] / scale)**2
684
+ t, p = np.deg2rad(2 * (np.array([g1[2], g2[2]]) % 180))
685
+ sign = -1 if subtract else 1
686
+ trace = a + b + sign * (c + d)
687
+ real = (a - b) * np.cos(t) + sign * (c - d) * np.cos(p)
688
+ imag = (a - b) * np.sin(t) + sign * (c - d) * np.sin(p)
689
+ anisotropy = np.hypot(real, imag)
690
+ eigenvalues = np.array([(trace + anisotropy) / 2,
691
+ (trace - anisotropy) / 2])
692
+ tolerance = 32 * np.finfo(dtype).eps * (a + b + c + d)
693
+ if np.any(eigenvalues < -tolerance):
694
+ raise ValueError('The kernel cannot be deconvolved'
695
+ ' from the observed Gaussian.')
696
+ widths = np.sqrt(np.maximum(eigenvalues, 0)) * scale
697
+ angle = (dtype.type(0) if anisotropy <= tolerance else
698
+ (np.rad2deg(np.arctan2(imag, real)) / 2 + 90) % 180 - 90)
699
+ if not np.all(np.isfinite(widths)):
700
+ raise ValueError('The resulting Gaussian widths'
701
+ ' exceed the numeric range.')
702
+ values = (*widths, angle)
703
+ return tuple(_normalize_float(v, force_float=True) for v in values)
704
+
705
+
706
+ def gaussian_convolve(gaussian1: RealSequence, gaussian2: RealSequence
707
+ ) -> tuple[float | np.longdouble,
708
+ float | np.longdouble,
709
+ float | np.longdouble]:
710
+ """Return the shape of the convolution of two centered Gaussians.
711
+
712
+ Args:
713
+ gaussian1: (major FWHM, minor FWHM, PA in degrees), as a list,
714
+ tuple, or one-dimensional array. Widths must be finite and
715
+ nonnegative; zero widths represent limiting Gaussian shapes.
716
+ Reversed major/minor widths are accepted: PA always describes
717
+ the first width. Boolean and non-real entries are rejected.
718
+ gaussian2: Another shape in the same length units and coordinate
719
+ frame. PA is measured from +y toward +x. Inputs already in a
720
+ swapped frame require no additional angle transformation;
721
+ display flips have no effect.
722
+
723
+ Returns:
724
+ tuple: (major FWHM, minor FWHM, PA), with major >= minor and
725
+ PA in [-90, 90). Circular results use PA=0, including shapes whose
726
+ anisotropy is within numerical tolerance. Scalars are Python floats,
727
+ except that extended-precision NumPy floating scalars are preserved.
728
+ Input arrays are never modified. Only shape is calculated, not
729
+ amplitude, flux, or centroid.
730
+
731
+ Raises:
732
+ TypeError: Inputs or their entries have unsupported types.
733
+ ValueError: Shapes, values, or the resulting numeric range are invalid.
734
+ """
735
+ return _combine_gaussians(gaussian1, gaussian2, subtract=False)
736
+
737
+
738
+ def gaussian_deconvolve(observed: RealSequence, kernel: RealSequence
739
+ ) -> tuple[float | np.longdouble,
740
+ float | np.longdouble,
741
+ float | np.longdouble]:
742
+ """Return the Gaussian shape that convolved with kernel gives observed.
743
+
744
+ Args:
745
+ observed: Observed (major FWHM, minor FWHM, PA in degrees).
746
+ kernel: Gaussian shape to remove, in the same units and frame.
747
+ Both inputs follow gaussian_convolve's validation and angle
748
+ conventions, including support for reversed widths and zeros.
749
+
750
+ Returns:
751
+ tuple: Intrinsic (major FWHM, minor FWHM, PA), ordered and normalized
752
+ as in gaussian_convolve. Ordinary scalars are Python floats;
753
+ extended-precision NumPy floating scalars are preserved. Zero widths
754
+ are allowed. Circular and all-zero results use PA=0. Small negative
755
+ squared widths within 32 machine epsilons of the summed input
756
+ squared-width scale are clipped to zero. Inputs are never modified.
757
+
758
+ Raises:
759
+ TypeError: Inputs or entries have unsupported types.
760
+ ValueError: Inputs are invalid, or covariance subtraction has a
761
+ negative eigenvalue beyond rounding tolerance, so no Gaussian
762
+ solution exists. This is analytic shape deconvolution, not image
763
+ deconvolution or a statistical upper limit for unresolved sources.
764
+ """
765
+ return _combine_gaussians(observed, kernel, subtract=True)
766
+
767
+
649
768
  def gaussian1d(x: np.ndarray | float | np.floating,
650
769
  amplitude: float, xo: float, fwhm: float,
651
770
  ) -> float | np.longdouble | np.ndarray:
@@ -729,17 +848,18 @@ def gaussfit1d(xdata: np.ndarray, ydata: np.ndarray,
729
848
  """
730
849
  if not np.all(np.isfinite(xdata)) or not np.all(np.isfinite(ydata)):
731
850
  raise ValueError('gaussfit1d requires finite samples; crop or remove'
732
- + ' NaN and infinite values before fitting.')
851
+ ' NaN and infinite values before fitting.')
733
852
  if np.size(xdata) < 2 or np.size(ydata) < 2:
734
853
  raise ValueError('gaussfit1d requires at least two samples.')
735
854
  if np.min(ydata) == np.max(ydata):
736
855
  raise ValueError('gaussfit1d requires at least two samples'
737
- + ' with different values.')
856
+ ' with different values.')
738
857
  if np.min(xdata) == np.max(xdata):
739
- raise ValueError('gaussfit1d requires at least two different coordinates.')
858
+ raise ValueError('gaussfit1d requires at least'
859
+ ' two different coordinates.')
740
860
  if sigma is None:
741
861
  print('gaussfit1d: sigma is None;'
742
- + ' estimating noise from an initial fit.')
862
+ ' estimating noise from an initial fit.')
743
863
  xmin, xmax = np.min(xdata), np.max(xdata)
744
864
  ymin, ymax = np.min(ydata), np.max(ydata)
745
865
  xw = xmax - xmin
@@ -799,15 +919,15 @@ def gaussfit2d(xdata: np.ndarray, ydata: np.ndarray, zdata: np.ndarray,
799
919
  """
800
920
  if sigma is None:
801
921
  print('gaussfit2d: sigma is None;'
802
- + ' estimating noise from an initial fit.')
922
+ ' estimating noise from an initial fit.')
803
923
  xmin, xmax = np.min(xdata), np.max(xdata)
804
924
  ymin, ymax = np.min(ydata), np.max(ydata)
805
925
  if not np.all(np.isfinite(zdata)):
806
926
  raise ValueError('gaussfit2d requires finite pixels; crop or remove'
807
- + ' NaN and infinite values before fitting.')
927
+ ' NaN and infinite values before fitting.')
808
928
  if np.size(zdata) < 2 or np.min(zdata) == np.max(zdata):
809
929
  raise ValueError('gaussfit2d requires at least two pixels'
810
- + ' with different values.')
930
+ ' with different values.')
811
931
  zmin, zmax = np.min(zdata), np.max(zdata)
812
932
  xw = xmax - xmin
813
933
  yw = ymax - ymin
@@ -30,17 +30,17 @@ def _uniform_bin_width(edges: np.ndarray) -> float | np.longdouble:
30
30
  if (edges.ndim != 1 or len(edges) < 2
31
31
  or not np.all(np.isfinite(edges))):
32
32
  raise ValueError('Histogram edges must be a 1D array'
33
- + ' with at least two finite values.')
33
+ ' with at least two finite values.')
34
34
  widths = np.diff(edges)
35
35
  if not np.all(np.isfinite(widths)) or np.any(widths <= 0):
36
36
  raise ValueError('Histogram bin widths must be finite and positive;'
37
- + ' edges must be strictly increasing.')
37
+ ' edges must be strictly increasing.')
38
38
  width = np.mean(widths)
39
39
  if not _is_uniform_spacing(widths, width):
40
40
  raise ValueError('Only equal-width bins are supported;'
41
- + ' use an integer bin count, bins="auto",'
42
- + ' or equally spaced edges'
43
- + ' (for example np.linspace).')
41
+ ' use an integer bin count, bins="auto",'
42
+ ' or equally spaced edges'
43
+ ' (for example np.linspace).')
44
44
  return _normalize_float(width)
45
45
 
46
46
 
@@ -185,7 +185,7 @@ def select_noise(data: np.ndarray, sigma: str) -> np.ndarray:
185
185
  ntmp[ny // 5: ny * 4 // 5, nx // 5: nx * 4 // 5] = np.nan
186
186
  if np.all(np.isnan(ntmp)):
187
187
  print('\'out\' is ignored because'
188
- + ' the outer region is filled with nan.')
188
+ ' the outer region is filled with nan.')
189
189
  else:
190
190
  n = ntmp
191
191
  n = n[~np.isnan(n)]
@@ -223,13 +223,13 @@ class Noise:
223
223
  self.data = select_noise(data, sigma)
224
224
  if self.data.size < 2:
225
225
  raise ValueError('Noise estimation requires at least'
226
- + ' two selected finite pixels.')
226
+ ' two selected finite pixels.')
227
227
  self.sigma = sigma
228
228
  self.m0 = _normalize_float(np.mean(self.data))
229
229
  self.s0 = _normalize_float(np.std(self.data))
230
230
  if not np.isfinite(self.s0):
231
231
  raise ValueError('Noise estimation requires selected pixels'
232
- + ' with finite values.')
232
+ ' with finite values.')
233
233
 
234
234
  def gen_histogram(self, **kwargs: Any) -> None:
235
235
  """Generate a pair of histogram and bins using numpy.histogram.
@@ -252,12 +252,12 @@ class Noise:
252
252
  """
253
253
  if self.s0 == 0:
254
254
  raise ValueError('Histogram noise estimation requires'
255
- + ' selected pixels with nonzero variance.')
255
+ ' selected pixels with nonzero variance.')
256
256
  _kw = {'bins': 100, 'range': (-3.5, 3.5), 'density': True}
257
257
  _kw.update(kwargs)
258
258
  if _kw.get('weights') is not None:
259
259
  raise ValueError('Noise histograms currently support'
260
- + ' unweighted data only.')
260
+ ' unweighted data only.')
261
261
  n = (self.data - self.m0) / self.s0
262
262
  hist, edges = np.histogram(n, **_kw)
263
263
  width = _uniform_bin_width(edges)
@@ -432,7 +432,7 @@ def _multiply_pb(data: np.ndarray, x: np.ndarray, y: np.ndarray,
432
432
  or coordinate.dtype.kind not in 'iuf'
433
433
  or not np.all(np.isfinite(coordinate))):
434
434
  raise ValueError(f'{name} must be a finite real 1D coordinate array'
435
- + ' matching the spatial data axis.')
435
+ ' matching the spatial data axis.')
436
436
  _require_positive_real_scalar(R, 'R')
437
437
  _require_positive_real_scalar(r_out, 'r_out')
438
438
  radius_squared = (x[None, :] / r_out)**2 + (y[:, None] / r_out)**2
@@ -210,8 +210,8 @@ def reform_data(c: np.ndarray, v_in: np.ndarray | None,
210
210
  d = c
211
211
  else:
212
212
  warnings.warn('Velocity resolution mismatch (>1%).'
213
- + ' The cube needs to be regridded'
214
- + ' outside plotastrodata.',
213
+ ' The cube needs to be regridded'
214
+ ' outside plotastrodata.',
215
215
  UserWarning)
216
216
  n_valid = k1 - k0
217
217
  d = [None] * n_valid
@@ -371,7 +371,7 @@ def _validate_range_inputs(data: np.ndarray, x: np.ndarray, y: np.ndarray,
371
371
  if (data.ndim not in (2, 3) or data.dtype.kind not in 'iuf'
372
372
  or any(length < 2 for length in data.shape)):
373
373
  raise ValueError('data must be a real 2D or 3D array with at least'
374
- + ' two samples on every axis.')
374
+ ' two samples on every axis.')
375
375
  x, y = np.asarray(x), np.asarray(y)
376
376
  axes = [(x, data.shape[-1], 'x'), (y, data.shape[-2], 'y')]
377
377
  if data.ndim == 3:
@@ -386,7 +386,7 @@ def _validate_range_inputs(data: np.ndarray, x: np.ndarray, y: np.ndarray,
386
386
  or coordinate.dtype.kind not in 'iuf'
387
387
  or not np.all(np.isfinite(coordinate))):
388
388
  raise ValueError(f'{name} must be a finite real 1D coordinate array'
389
- + ' matching its data axis.')
389
+ ' matching its data axis.')
390
390
  steps = np.diff(coordinate)
391
391
  if steps[0] == 0 or not _is_uniform_spacing(steps, steps[0]):
392
392
  raise ValueError(f'{name} must have nonzero uniform spacing.')
@@ -409,7 +409,7 @@ def _get_minarea_margin(
409
409
  sizes = np.asarray(beam)
410
410
  if sizes.ndim != 1 or sizes.size not in (2, 3):
411
411
  raise ValueError('beam must contain [major, minor]'
412
- + ' or [major, minor, pa].')
412
+ ' or [major, minor, pa].')
413
413
  if any(size is None for size in sizes[:2]):
414
414
  return min_area_pixels, spatial_margin
415
415
  for size in beam[:2]:
@@ -96,7 +96,7 @@ def _image_edges(grid: np.ndarray, name: str
96
96
  if (not np.all(np.isfinite(grid)) or steps[0] == 0
97
97
  or not _is_uniform_spacing(steps, steps[0])):
98
98
  raise ValueError(f'RGB {name} coordinates must be finite'
99
- + ' and uniformly spaced.')
99
+ ' and uniformly spaced.')
100
100
  return grid[0] - steps[0] / 2, grid[-1] + steps[0] / 2
101
101
 
102
102
 
@@ -107,7 +107,7 @@ def _validate_colorbar(cbformat: str, cbticks: RealSequence | None,
107
107
  """Validate enabled colorbar options and prepare explicit tick positions."""
108
108
  if cblocation not in ('left', 'right', 'top', 'bottom'):
109
109
  raise ValueError('cblocation must be left, right,'
110
- + ' top, or bottom.')
110
+ ' top, or bottom.')
111
111
  try:
112
112
  formatter = (mpl.ticker.StrMethodFormatter(cbformat)
113
113
  if '{' in cbformat
@@ -124,7 +124,7 @@ def _validate_colorbar(cbformat: str, cbticks: RealSequence | None,
124
124
  and (cbticks is None or np.ndim(cbticklabels) != 1
125
125
  or len(cbticklabels) != len(cbticks))):
126
126
  raise ValueError('cbticklabels requires one label'
127
- + ' per explicit cbtick.')
127
+ ' per explicit cbtick.')
128
128
  return cbticks
129
129
 
130
130
 
@@ -165,7 +165,7 @@ def _log_limits(vmin: float, vmax: float) -> None:
165
165
  if not (_is_finite_real_scalar(vmin) and _is_finite_real_scalar(vmax)
166
166
  and 0 < vmin < vmax):
167
167
  raise ValueError('Logarithmic limits must be finite and satisfy'
168
- + ' 0 < vmin < vmax.')
168
+ ' 0 < vmin < vmax.')
169
169
 
170
170
 
171
171
  def logticks(ticks: RealSequence, lim: RealSequence
@@ -265,7 +265,7 @@ def get_figsize(xmin: float, xmax: float, ymin: float, ymax: float,
265
265
  if (not all(_is_finite_real_scalar(a) for a in (xmin, xmax, ymin, ymax))
266
266
  or xmin == xmax or ymin == ymax):
267
267
  raise ValueError('Automatic figure sizing requires finite limits'
268
- + ' and nonzero x and y spans.')
268
+ ' and nonzero x and y spans.')
269
269
 
270
270
  sqrt_a = (ymax - ymin) / (xmax - xmin)
271
271
  sqrt_a = np.sqrt(np.abs(sqrt_a))
@@ -433,7 +433,7 @@ class Stretcher():
433
433
  scale = sigma if scale is None else scale
434
434
  if st == 'asinh' and not _is_positive_real_scalar(scale):
435
435
  raise ValueError('asinh requires a finite positive'
436
- + ' stretchscale or sigma.')
436
+ ' stretchscale or sigma.')
437
437
  minimum = self._parameter('vmin', i)
438
438
  if minimum is None and st in ('log', 'power'):
439
439
  minimum = sigma
@@ -755,7 +755,7 @@ class PlotAxes2D():
755
755
  ) -> np.ndarray:
756
756
  if len(ticks) < 2:
757
757
  raise ValueError('Minor subdivisions require at least'
758
- + ' two major ticks.')
758
+ ' two major ticks.')
759
759
  dt = ticks[1] - ticks[0]
760
760
  t = np.r_[ticks[0] - dt, ticks, ticks[-1] + dt]
761
761
  num = ticksminor * (len(t) - 1) + 1
@@ -864,7 +864,7 @@ def _normalize_rgb_channel(data: np.ndarray, st: Stretcher,
864
864
  high = np.max(stretched[valid]) if hi is None else st.do(hi, i)
865
865
  if not np.isfinite(low) or not np.isfinite(high):
866
866
  raise ValueError('RGB stretch bounds must be finite'
867
- + ' after transformation.')
867
+ ' after transformation.')
868
868
  normalized[valid] = ((stretched[valid] - low) / (high - low)
869
869
  if high > low else 0)
870
870
  return normalized
@@ -974,7 +974,7 @@ def _plan_panels(v: np.ndarray, pv: bool, channelnumber: int | np.integer | None
974
974
  channelnumber = int(channelnumber)
975
975
  if not -nv <= channelnumber < nv:
976
976
  raise ValueError('channelnumber must be'
977
- + f'between {-nv} and {nv - 1}.')
977
+ f'between {-nv} and {nv - 1}.')
978
978
  channelnumber %= nv
979
979
  if pv or len(v) == 1 or animation:
980
980
  nrows = ncols = npages = nchan = 1
@@ -1135,7 +1135,7 @@ class PlotAstroData(AstroFrame):
1135
1135
  plan = _plan_panels(v, self.pv, channelnumber, nrows, ncols)
1136
1136
  if ax is not None and plan.nchan != 1:
1137
1137
  raise ValueError('External fig and ax support a single panel only;'
1138
- + ' select channelnumber for a cube.')
1138
+ ' select channelnumber for a cube.')
1139
1139
  if fontsize is None:
1140
1140
  fontsize = 18 if plan.nchan == 1 else 12
1141
1141
  set_rcparams(fontsize=fontsize, nancolor=nancolor, dpi=dpi)
@@ -1508,11 +1508,11 @@ class PlotAstroData(AstroFrame):
1508
1508
  """
1509
1509
  if self.pv:
1510
1510
  raise ValueError('add_scalebar() does not support position-velocity'
1511
- + ' (PV) diagrams; use it for spatial maps only.')
1511
+ ' (PV) diagrams; use it for spatial maps only.')
1512
1512
  _require_positive_real_scalar(length, 'length')
1513
1513
  if np.shape(barpos) != (2,) or not all(np.isfinite(v) for v in barpos):
1514
1514
  raise ValueError('barpos must contain two finite'
1515
- + ' relative coordinates.')
1515
+ ' relative coordinates.')
1516
1516
  bbox = {'alpha': 0} if bbox is None else bbox
1517
1517
  if fontsize is None:
1518
1518
  fontsize = 20 if len(self.ax) == 1 else 15
@@ -1540,7 +1540,7 @@ class PlotAstroData(AstroFrame):
1540
1540
 
1541
1541
  if mappable[ch] is None:
1542
1542
  raise ValueError('Cannot create a colorbar'
1543
- + ' without a plotted mappable.')
1543
+ ' without a plotted mappable.')
1544
1544
  fig = self.figs[ch // self.rowcol]
1545
1545
  if len(self.ax) == 1:
1546
1546
  ax = self.ax[ch]
@@ -1683,12 +1683,12 @@ class PlotAstroData(AstroFrame):
1683
1683
  or not np.all(np.isfinite(levels))
1684
1684
  or np.unique(levels).size != levels.size):
1685
1685
  raise ValueError('levels must be a nonempty 1D sequence'
1686
- + ' of finite distinct values.')
1686
+ ' of finite distinct values.')
1687
1687
  self._kw = {'colors': 'gray', 'linewidths': 1.0, 'zorder': 2}
1688
1688
  c, x, y, v, sigma, _, _kw, singlepix = self._map_init(kwargs)
1689
1689
  if singlepix:
1690
1690
  raise ValueError('add_contour() requires at least'
1691
- + ' two x and y pixels.')
1691
+ ' two x and y pixels.')
1692
1692
 
1693
1693
  _positive_noise(sigma, 'sigma')
1694
1694
  c = self.vskipfill(c, v)
@@ -1719,7 +1719,7 @@ class PlotAstroData(AstroFrame):
1719
1719
  amp = np.ones_like(ang)
1720
1720
  if amp.shape != ang.shape:
1721
1721
  raise ValueError('Amplitude and angle datasets must'
1722
- + ' have matching shapes.')
1722
+ ' have matching shapes.')
1723
1723
  valid = np.isfinite(amp) & np.isfinite(ang)
1724
1724
  if np.any(amp[valid] < 0):
1725
1725
  raise ValueError('Segment amplitudes must be nonnegative.')
@@ -1817,7 +1817,7 @@ class PlotAstroData(AstroFrame):
1817
1817
  raise ValueError('Provide both Stokes U and Q, or neither.')
1818
1818
  if not has_u and ang is None and angfits is None:
1819
1819
  raise ValueError('Provide an angle dataset or a complete'
1820
- + ' Stokes U/Q pair.')
1820
+ ' Stokes U/Q pair.')
1821
1821
  self._kw = {'angles': 'xy', 'scale_units': 'xy', 'color': 'gray',
1822
1822
  'pivot': 'mid', 'headwidth': 0, 'headlength': 0,
1823
1823
  'headaxislength': 0, 'width': 0.007, 'zorder': 3,
@@ -1889,7 +1889,7 @@ class PlotAstroData(AstroFrame):
1889
1889
  or len(source) != 3
1890
1890
  or any(c is None for c in source)):
1891
1891
  raise ValueError('add_rgb() requires exactly three red, green,'
1892
- + ' and blue datasets.')
1892
+ ' and blue datasets.')
1893
1893
  kwargs = kwargs.copy()
1894
1894
  if isinstance(source, tuple):
1895
1895
  key = 'data' if kwargs.get('data') is not None else 'fitsimage'
@@ -1901,7 +1901,7 @@ class PlotAstroData(AstroFrame):
1901
1901
  raise ValueError('add_rgb() requires at least two x and y pixels.')
1902
1902
  if len(c) != 3 or not (c[0].shape == c[1].shape == c[2].shape):
1903
1903
  raise ValueError('add_rgb() requires three datasets with'
1904
- + ' matching shapes.')
1904
+ ' matching shapes.')
1905
1905
  if isinstance(_kw['stretch'], str):
1906
1906
  _kw['stretch'] = [_kw['stretch']] * 3
1907
1907
  _kw['sigma'] = sigma
@@ -2037,15 +2037,15 @@ class PlotAstroData(AstroFrame):
2037
2037
  nticksminor = int(nticksminor)
2038
2038
  if self.pv:
2039
2039
  raise ValueError('set_axis_radec() does not support'
2040
- + ' position-velocity (PV) diagrams.')
2040
+ ' position-velocity (PV) diagrams.')
2041
2041
  if self.dist != 1:
2042
2042
  raise ValueError('set_axis_radec() requires dist=1;'
2043
- + ' distance-scaled axes are not supported.')
2043
+ ' distance-scaled axes are not supported.')
2044
2044
  if center is None:
2045
2045
  center = self.center
2046
2046
  if center is None:
2047
2047
  raise ValueError('set_axis_radec() requires a known center;'
2048
- + ' provide center or fitsimage.')
2048
+ ' provide center or fitsimage.')
2049
2049
  center, frame, _ = _getframe(center, as_frame=True)
2050
2050
  frame_name = frame.name.upper()
2051
2051
  xlabel = f'R.A. ({frame_name})' if xlabel is None else xlabel
@@ -2187,7 +2187,7 @@ def _prep_plotprofile(width: int | np.integer,
2187
2187
  or any(label is not None and not isinstance(label, str)
2188
2188
  for label in ylabel)):
2189
2189
  raise ValueError('ylabel must be a string, None,'
2190
- + ' or one string/None per profile.')
2190
+ ' or one string/None per profile.')
2191
2191
  _kw.setdefault('xlim', [v.min(), v.max()])
2192
2192
  pa2 = kwargs2instance(PlotAxes2D, _kw)
2193
2193
  return v, prof, gfitres, pa2, list(ylabel)
@@ -2211,11 +2211,11 @@ def _set_figax_plotprofile(fig: Figure | None, ax: Axes | None,
2211
2211
  nrows = (nprof + int(ncols) - 1) // int(ncols) if nrows == 0 else int(nrows)
2212
2212
  if nprof < 1 or nrows * ncols < nprof:
2213
2213
  raise ValueError('The subplot layout must have space'
2214
- + ' for every profile.')
2214
+ ' for every profile.')
2215
2215
  if ax is not None:
2216
2216
  if nprof != 1:
2217
2217
  raise ValueError('An external fig/ax pair supports'
2218
- + ' only one profile.')
2218
+ ' only one profile.')
2219
2219
  return fig, np.array([ax], dtype=object)
2220
2220
  fig = plt.figure(figsize=(6 * ncols, 3 * nrows))
2221
2221
  axes = np.empty(nprof, dtype=object)
@@ -2428,7 +2428,7 @@ def plotslice(length: RealScalar, dx: RealScalar | None = None,
2428
2428
  if txtfile is not None:
2429
2429
  np.savetxt(txtfile, np.c_[r, z],
2430
2430
  header=f'x ({xunit}), {yquantity} ({yunit}); '
2431
- + f'positive x is pa={pa:.2f} deg.')
2431
+ f'positive x is pa={pa:.2f} deg.')
2432
2432
  if 'xlabel' not in _kw:
2433
2433
  _kw['xlabel'] = f'Offset ({xunit})'
2434
2434
  if 'ylabel' not in _kw:
@@ -2464,7 +2464,7 @@ def _surface_levels(levels: RealSequence) -> np.ndarray:
2464
2464
  or not np.all(np.isfinite(values))
2465
2465
  or np.unique(values).size != values.size):
2466
2466
  raise ValueError('Isosurface levels must be a nonempty finite,'
2467
- + ' distinct real sequence.')
2467
+ ' distinct real sequence.')
2468
2468
  return values
2469
2469
 
2470
2470
 
@@ -2477,12 +2477,12 @@ def _surface_grid(grid: np.ndarray | None, size: int, name: str) -> None:
2477
2477
  """Require a matching 1D grid with uniform spacing relative to its first interval."""
2478
2478
  if grid is None or np.ndim(grid) != 1 or len(grid) != size or size < 2:
2479
2479
  raise ValueError('plot3d requires at least two matching'
2480
- + f' {name} coordinates.')
2480
+ f' {name} coordinates.')
2481
2481
  steps = np.diff(grid)
2482
2482
  if (not np.all(np.isfinite(grid)) or steps[0] == 0
2483
2483
  or not _is_uniform_spacing(steps, steps[0])):
2484
2484
  raise ValueError('plot3d requires a finite, uniformly spaced'
2485
- + f' {name} grid.')
2485
+ f' {name} grid.')
2486
2486
 
2487
2487
 
2488
2488
  def _surface_mesh(measure: ModuleType, volume: np.ndarray,
@@ -2609,7 +2609,7 @@ def _prepare_surface_cube(d: AstroData) -> _SurfaceCube:
2609
2609
  """Validate and orient a private volume without changing processed data."""
2610
2610
  if not isinstance(d.data, np.ndarray) or d.data.ndim != 3 or d.data.dtype.kind not in 'iuf':
2611
2611
  raise ValueError('plot3d() requires one real 3D spectral cube'
2612
- + ' with at least two samples per axis.')
2612
+ ' with at least two samples per axis.')
2613
2613
  for grid, size, name in zip((d.v, d.y, d.x), d.data.shape, ('v', 'y', 'x')):
2614
2614
  _surface_grid(grid, size, name)
2615
2615
  _positive_noise(d.sigma, 'sigma')
@@ -2764,7 +2764,7 @@ def plot3d(levels: RealSequence = (3, 6, 12),
2764
2764
  f = kwargs2instance(AstroFrame, kwargs)
2765
2765
  if f.dist != 1:
2766
2766
  raise ValueError('plot3d() requires dist=1;'
2767
- + ' distance-scaled plots are not supported.')
2767
+ ' distance-scaled plots are not supported.')
2768
2768
  if f.swapxy:
2769
2769
  raise ValueError('plot3d() does not support swapxy=True.')
2770
2770
  if f.pv:
@@ -2774,7 +2774,7 @@ def plot3d(levels: RealSequence = (3, 6, 12),
2774
2774
  from skimage import measure
2775
2775
  except ImportError as exc:
2776
2776
  raise ImportError('plot3d() requires plotly and'
2777
- + ' scikit-image.') from exc
2777
+ ' scikit-image.') from exc
2778
2778
  d = kwargs2instance(AstroData, kwargs)
2779
2779
  f.read(d, xskip, yskip)
2780
2780
  cube = _prepare_surface_cube(d)
@@ -75,7 +75,7 @@ def _grid_scales(values: Sequence[Sequence[RealScalar]], item_count: int,
75
75
  for r, row in enumerate(values):
76
76
  if isinstance(row, (str, bytes)) or isinstance(row, RealScalar):
77
77
  raise ValueError('scale_factors must be flat numbers'
78
- + ' or a nested grid')
78
+ ' or a nested grid')
79
79
  row = list(row)
80
80
  if len(row) > columns:
81
81
  raise ValueError('too many scale-factor columns')
@@ -127,7 +127,7 @@ def _layout(sizes: Sequence[tuple[RealScalar, RealScalar]], columns: int,
127
127
  if not all(_is_positive_real_scalar(v)
128
128
  for v in (w, h, dw, dh)):
129
129
  raise ValueError('input and scaled dimensions must be'
130
- + ' positive and finite')
130
+ ' positive and finite')
131
131
  cw, ch = max(1, round(dw)), max(1, round(dh))
132
132
  drawn.append((cw, ch))
133
133
  widths[i % columns] = max(widths[i % columns], cw)
@@ -25,7 +25,7 @@ def _validate_fits_image(fitsimage: str | Path, *, ndim: int = 2) -> None:
25
25
  or not str(h.get('CTYPE1', '')).upper().startswith('RA')
26
26
  or not str(h.get('CTYPE2', '')).upper().startswith('DEC')):
27
27
  raise ValueError(f'Expected a {ndim}D RA/Dec image'
28
- + ' in the primary FITS HDU.')
28
+ ' in the primary FITS HDU.')
29
29
  if ndim == 3 and (
30
30
  h.get('NAXIS3', 0) < 2
31
31
  or not str(h.get('CTYPE3', '')).upper().startswith(
@@ -33,8 +33,8 @@ def _validate_fits_image(fitsimage: str | Path, *, ndim: int = 2) -> None:
33
33
  or str(h.get('CUNIT3', '')).strip().upper() not in
34
34
  ('HZ', 'M/S', 'KM/S')):
35
35
  raise ValueError('Expected at least two frequency'
36
- + ' or velocity channels on the third FITS axis,'
37
- + ' in Hz, m/s, or km/s.')
36
+ ' or velocity channels on the third FITS axis,'
37
+ ' in Hz, m/s, or km/s.')
38
38
  scales = proj_plane_pixel_scales(WCS(h, naxis=2, fix=False).celestial)
39
39
  if not np.all(np.isfinite(scales)) or np.any(scales <= 0):
40
40
  raise ValueError('Expected finite positive spatial pixel scales.')
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: plotastrodata
3
- Version: 1.13.1
3
+ Version: 1.13.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
File without changes
File without changes
File without changes
File without changes