plotastrodata 1.12.2__tar.gz → 1.12.3__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (28) hide show
  1. {plotastrodata-1.12.2/plotastrodata.egg-info → plotastrodata-1.12.3}/PKG-INFO +5 -2
  2. {plotastrodata-1.12.2 → plotastrodata-1.12.3}/README.md +4 -1
  3. {plotastrodata-1.12.2 → plotastrodata-1.12.3}/plotastrodata/__init__.py +1 -1
  4. {plotastrodata-1.12.2 → plotastrodata-1.12.3}/plotastrodata/analysis_utils.py +119 -10
  5. {plotastrodata-1.12.2 → plotastrodata-1.12.3}/plotastrodata/script_utils.py +50 -7
  6. {plotastrodata-1.12.2 → plotastrodata-1.12.3/plotastrodata.egg-info}/PKG-INFO +5 -2
  7. {plotastrodata-1.12.2 → plotastrodata-1.12.3}/LICENSE +0 -0
  8. {plotastrodata-1.12.2 → plotastrodata-1.12.3}/MANIFEST.in +0 -0
  9. {plotastrodata-1.12.2 → plotastrodata-1.12.3}/plotastrodata/_type_utils.py +0 -0
  10. {plotastrodata-1.12.2 → plotastrodata-1.12.3}/plotastrodata/_validation_utils.py +0 -0
  11. {plotastrodata-1.12.2 → plotastrodata-1.12.3}/plotastrodata/const_utils.py +0 -0
  12. {plotastrodata-1.12.2 → plotastrodata-1.12.3}/plotastrodata/coord_utils.py +0 -0
  13. {plotastrodata-1.12.2 → plotastrodata-1.12.3}/plotastrodata/ext_utils.py +0 -0
  14. {plotastrodata-1.12.2 → plotastrodata-1.12.3}/plotastrodata/fft_utils.py +0 -0
  15. {plotastrodata-1.12.2 → plotastrodata-1.12.3}/plotastrodata/fits_utils.py +0 -0
  16. {plotastrodata-1.12.2 → plotastrodata-1.12.3}/plotastrodata/fitting_utils.py +0 -0
  17. {plotastrodata-1.12.2 → plotastrodata-1.12.3}/plotastrodata/los_utils.py +0 -0
  18. {plotastrodata-1.12.2 → plotastrodata-1.12.3}/plotastrodata/matrix_utils.py +0 -0
  19. {plotastrodata-1.12.2 → plotastrodata-1.12.3}/plotastrodata/noise_utils.py +0 -0
  20. {plotastrodata-1.12.2 → plotastrodata-1.12.3}/plotastrodata/other_utils.py +0 -0
  21. {plotastrodata-1.12.2 → plotastrodata-1.12.3}/plotastrodata/plot_utils.py +0 -0
  22. {plotastrodata-1.12.2 → plotastrodata-1.12.3}/plotastrodata.egg-info/SOURCES.txt +0 -0
  23. {plotastrodata-1.12.2 → plotastrodata-1.12.3}/plotastrodata.egg-info/dependency_links.txt +0 -0
  24. {plotastrodata-1.12.2 → plotastrodata-1.12.3}/plotastrodata.egg-info/not-zip-safe +0 -0
  25. {plotastrodata-1.12.2 → plotastrodata-1.12.3}/plotastrodata.egg-info/requires.txt +0 -0
  26. {plotastrodata-1.12.2 → plotastrodata-1.12.3}/plotastrodata.egg-info/top_level.txt +0 -0
  27. {plotastrodata-1.12.2 → plotastrodata-1.12.3}/setup.cfg +0 -0
  28. {plotastrodata-1.12.2 → plotastrodata-1.12.3}/setup.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: plotastrodata
3
- Version: 1.12.2
3
+ Version: 1.12.3
4
4
  Summary: plotastrodata is a tool for astronomers to create figures from FITS files and perform fundamental data analyses with ease.
5
5
  Home-page: https://github.com/yusukeaso-astron/plotastrodata
6
6
  Download-URL: https://github.com/yusukeaso-astron/plotastrodata
@@ -106,7 +106,10 @@ with three significant digits for editing.
106
106
  For a spectral cube, use `generate_cube_script("cube.fits", output="cube.py")`
107
107
  from the same module. It generates an edge-channel noise visualization, a flux-integrated line
108
108
  profile and 3D channel maps over estimated spatial and velocity ranges,
109
- with intrinsic channel spacing. The flux profile assumes Jy/beam data with beam metadata.
109
+ with intrinsic channel spacing. Two further single-panel figures show moments
110
+ 1 and 2 in linear colors with moment-0 contours and colorbar ticks to one
111
+ decimal place; moment 1 uses a blue-red colormap. The moments use the shared crop and are saved as
112
+ `<script stem>_mom1.png` and `<script stem>_mom2.png`. The flux profile assumes Jy/beam data with beam metadata.
110
113
  Noise and range estimation in both generators assume PB-corrected intensities.
111
114
  Both generators return an absolute pathlib.Path and write the script
112
115
  without executing it.
@@ -77,7 +77,10 @@ with three significant digits for editing.
77
77
  For a spectral cube, use `generate_cube_script("cube.fits", output="cube.py")`
78
78
  from the same module. It generates an edge-channel noise visualization, a flux-integrated line
79
79
  profile and 3D channel maps over estimated spatial and velocity ranges,
80
- with intrinsic channel spacing. The flux profile assumes Jy/beam data with beam metadata.
80
+ with intrinsic channel spacing. Two further single-panel figures show moments
81
+ 1 and 2 in linear colors with moment-0 contours and colorbar ticks to one
82
+ decimal place; moment 1 uses a blue-red colormap. The moments use the shared crop and are saved as
83
+ `<script stem>_mom1.png` and `<script stem>_mom2.png`. The flux profile assumes Jy/beam data with beam metadata.
81
84
  Noise and range estimation in both generators assume PB-corrected intensities.
82
85
  Both generators return an absolute pathlib.Path and write the script
83
86
  without executing it.
@@ -1,4 +1,4 @@
1
1
  import warnings
2
2
 
3
3
  warnings.simplefilter('ignore', FutureWarning)
4
- __version__ = '1.12.2'
4
+ __version__ = '1.12.3'
@@ -25,6 +25,7 @@ from plotastrodata._type_utils import (
25
25
  from plotastrodata._validation_utils import (
26
26
  _is_finite_real_scalar,
27
27
  _is_positive_real_scalar,
28
+ _is_uniform_spacing,
28
29
  _is_zero_dimensional_array,
29
30
  _require_integer,
30
31
  _require_positive_real_scalar,
@@ -707,24 +708,24 @@ class AstroData():
707
708
  if dataformask is None:
708
709
  dataformask = self.data
709
710
  if len(includepix) not in [0, 2] or len(excludepix) not in [0, 2]:
710
- raise ValueError(
711
- 'includepix and excludepix must be empty or [min, max].')
711
+ raise ValueError('includepix and excludepix must be empty'
712
+ + ' or [min, max].')
712
713
  if np.ndim(self.data) > np.ndim(dataformask):
713
714
  print('The mask is broadcasted.')
714
715
  try:
715
716
  mask = np.broadcast_to(dataformask, np.shape(self.data))
716
717
  except ValueError as exc:
717
- raise ValueError(
718
- 'dataformask must be broadcastable to the data shape; '
719
- f'got {np.shape(dataformask)} and {np.shape(self.data)}.'
720
- ) from exc
718
+ raise ValueError('dataformask must be broadcastable'
719
+ ' to the data shape;'
720
+ + f' got {np.shape(dataformask)}'
721
+ + f' and {np.shape(self.data)}.') from exc
721
722
  else:
722
723
  mask = dataformask
723
724
  if np.shape(self.data) != np.shape(mask):
724
- raise ValueError(
725
- 'dataformask must have the same shape as data after '
726
- f'broadcasting; got {np.shape(dataformask)} and '
727
- f'{np.shape(self.data)}.')
725
+ raise ValueError('dataformask must have the same shape as data'
726
+ + ' after broadcasting;'
727
+ + f' got {np.shape(dataformask)}'
728
+ + f' and {np.shape(self.data)}.')
728
729
 
729
730
  if ((len(includepix) == 2 or len(excludepix) == 2)
730
731
  and self.data.dtype.kind in 'biu'):
@@ -734,6 +735,114 @@ class AstroData():
734
735
  if len(excludepix) == 2:
735
736
  self.data[(excludepix[0] < mask) * (mask < excludepix[1])] = np.nan
736
737
 
738
+ def moment(self, vmask: np.ndarray | None = None,
739
+ threshold_cube: RealScalar = 3,
740
+ threshold_mom0: RealScalar = 3) -> None:
741
+ """Store integrated intensity, mean velocity, and velocity dispersion.
742
+
743
+ Uses the current data axis order (v, y, x), including after a
744
+ swapped read. Requires a nonempty real 3D cube, a finite 1D velocity
745
+ grid matching its first axis, finite positive scalar sigma, and
746
+ finite nonzero scalar dv. Multiple channels must be uniformly
747
+ spaced with spacing magnitude abs(dv) (relative tolerance 1e-5).
748
+ NaNs in the cube are ignored; infinities are rejected.
749
+
750
+ Args:
751
+ vmask (np.ndarray or None, optional): 1D Boolean array with one
752
+ entry per channel. True selects a channel. None selects all
753
+ channels; at least one must be selected.
754
+ threshold_cube (RealScalar, optional): Finite nonnegative noise
755
+ multiple used to select intensities for moments 1 and 2.
756
+ Values equal to the threshold survive. Defaults to 3.
757
+ threshold_mom0 (RealScalar, optional): Finite nonnegative
758
+ multiple of sigma_mom0 below which moments 1 and 2 are
759
+ masked. Values equal to the threshold survive. Defaults to 3.
760
+ Both thresholds accept Python/NumPy real scalars, excluding
761
+ booleans and arrays.
762
+
763
+ Returns:
764
+ None: Stores mom0, mom1, and mom2 as (y, x) NumPy arrays.
765
+ mom0 sums selected intensities times abs(dv), without cube
766
+ thresholding. mom1 is the intensity-weighted velocity; mom2 is
767
+ the weighted standard deviation, not FWHM. Both are NaN where
768
+ mom0 fails its threshold or no positive weight survives.
769
+ All-NaN spectra have mom0=0. sigma_mom0 is
770
+ sqrt(number of selected channels) * sigma * abs(dv), assuming
771
+ independent channel noise, even where data are NaN. It is a
772
+ Python float, except np.longdouble retains extended precision.
773
+ mom0 and sigma_mom0 use intensity times velocity units; mom1
774
+ and mom2 use the units of v. Input arrays are not modified.
775
+
776
+ Raises:
777
+ TypeError: data, v, or a supplied vmask is not a NumPy array.
778
+ ValueError: Shapes, numeric values, channel selection, noise,
779
+ spacing, or thresholds do not satisfy the requirements.
780
+ """
781
+ if not isinstance(self.data, np.ndarray):
782
+ raise TypeError('moment requires data to be a NumPy array.')
783
+ if (self.data.ndim != 3 or 0 in self.data.shape
784
+ or self.data.dtype.kind not in 'iuf'
785
+ or np.any(np.isinf(self.data))):
786
+ raise ValueError('moment requires a nonempty real 3D cube'
787
+ + ' without infinities.')
788
+ if not isinstance(self.v, np.ndarray):
789
+ raise TypeError('moment requires v to be a NumPy array.')
790
+ if (self.v.ndim != 1 or self.v.size != self.data.shape[0]
791
+ or self.v.dtype.kind not in 'iuf'
792
+ or not np.all(np.isfinite(self.v))):
793
+ raise ValueError('v must be a finite real 1D grid matching'
794
+ + ' the number of channels.')
795
+ if not _is_positive_real_scalar(self.sigma):
796
+ raise ValueError('moment requires finite positive scalar sigma.')
797
+ if not _is_finite_real_scalar(self.dv) or self.dv == 0:
798
+ raise ValueError('moment requires finite nonzero scalar dv.')
799
+ if self.v.size > 1:
800
+ steps = np.diff(self.v.astype(np.result_type(self.v.dtype, float)))
801
+ if (not (np.all(steps > 0) or np.all(steps < 0))
802
+ or not _is_uniform_spacing(steps, steps[0])
803
+ or not _is_uniform_spacing(np.abs(steps), abs(self.dv))):
804
+ raise ValueError('v must be monotonic and uniformly spaced'
805
+ + ' with spacing magnitude abs(dv).')
806
+ for name, value in (('threshold_cube', threshold_cube),
807
+ ('threshold_mom0', threshold_mom0)):
808
+ if not _is_finite_real_scalar(value) or value < 0:
809
+ raise ValueError(f'{name} must be a finite nonnegative'
810
+ + ' real scalar.')
811
+ if vmask is None:
812
+ vmask = np.ones(self.v.size, dtype=bool)
813
+ elif not isinstance(vmask, np.ndarray):
814
+ raise TypeError('vmask must be a NumPy Boolean array or None.')
815
+ if (vmask.dtype.kind != 'b' or vmask.shape != self.v.shape
816
+ or not np.any(vmask)):
817
+ raise ValueError('vmask must be a 1D Boolean array matching v'
818
+ + ' and selecting at least one channel.')
819
+
820
+ data = np.where(vmask[:, None, None], self.data, 0)
821
+ dv = abs(self.dv)
822
+ mom0 = np.nansum(data, axis=0) * dv
823
+ sigma_mom0 = np.sqrt(np.count_nonzero(vmask)) * self.sigma * dv
824
+ if (isinstance(self.sigma, np.longdouble)
825
+ or isinstance(dv, np.longdouble)):
826
+ sigma_mom0 = np.longdouble(sigma_mom0)
827
+ sigma_mom0 = _normalize_float(sigma_mom0)
828
+ w = np.where(data >= threshold_cube * self.sigma, data, 0)
829
+ total = np.sum(w, axis=0)
830
+ w = np.divide(w, total,
831
+ out=np.zeros_like(w, dtype=np.result_type(w, float)),
832
+ where=total > 0)
833
+ mask = (mom0 < threshold_mom0 * sigma_mom0) | (total <= 0)
834
+
835
+ def wmean(x: np.ndarray) -> np.ndarray:
836
+ return np.where(mask, np.nan, np.nansum(w * x, axis=0))
837
+
838
+ v = self.v[:, None, None]
839
+ mom1 = wmean(v)
840
+ mom2 = np.sqrt(wmean((v - mom1)**2))
841
+ self.mom0: np.ndarray = mom0
842
+ self.mom1: np.ndarray = mom1
843
+ self.mom2: np.ndarray = mom2
844
+ self.sigma_mom0: float | np.longdouble = sigma_mom0
845
+
737
846
  def _gfit_profile(self, prof: np.ndarray, gaussfit: bool
738
847
  ) -> dict[str, list[np.ndarray]]:
739
848
  if not gaussfit:
@@ -158,7 +158,7 @@ p.savefig({str(output.with_suffix('.png'))!r}, show=False)
158
158
  def generate_cube_script(fitsimage: str | Path,
159
159
  output: str | Path | None = None,
160
160
  *, overwrite: bool = False) -> Path:
161
- """Write noise, integrated line-profile, and 3D channel-map plotting code.
161
+ """Write noise, line-profile, channel-map, and moment-map plotting code.
162
162
 
163
163
  Use the existing AstroData, AstroFrame, Noise, plotprofile, and
164
164
  PlotAstroData APIs, following the line-profile and 3D channel-map
@@ -217,11 +217,26 @@ def generate_cube_script(fitsimage: str | Path,
217
217
  PB-corrected data about the FITS reference center. The generated
218
218
  noise visualization still uses the full spatial footprint.
219
219
 
220
- The script sets stretch='log' and show=False, with default fonts,
220
+ Channel maps use stretch='log' and show=False, with default fonts,
221
221
  beams, contours, and channel layout. Edit these choices directly.
222
222
  Channel-map pages are saved beside the script as <script stem>.png;
223
223
  multiple pages receive _0, _1, ... suffixes before .png, following
224
224
  PlotAstroData.savefig. Existing figures may be overwritten.
225
+
226
+ After channel maps, the cropped cube calls AstroData.moment
227
+ with 3-sigma cube and integrated-intensity thresholds. Two separate
228
+ figures show moments 1 and 2 with linear colors and moment-0 contours
229
+ at [3, 6, 12, 24, 48, 96] times sigma_mom0. Moment 1 uses a blue-red
230
+ colormap; both colorbars use cbformat='%.1f'. They are saved as
231
+ <script stem>_mom1.png and
232
+ <script stem>_mom2.png beside the script. Moment ranges follow the
233
+ crop frame; changing that frame changes the moment calculation.
234
+ After calculation, d_crop is reused as a 2D image: data and sigma
235
+ are replaced for each contour/color call through d_crop.todict().
236
+ The moment arrays remain NumPy arrays, and sigma_mom0 is a Python
237
+ float except that np.longdouble retains extended precision. The
238
+ final data is the mom2 array, sigma is None, and v is None. The
239
+ original cube d is unchanged.
225
240
  """
226
241
  if not isinstance(overwrite, bool):
227
242
  raise TypeError('overwrite must be a boolean.')
@@ -256,13 +271,13 @@ n.plot_histogram(savefig={str(output.with_name(output.stem + '_noise.png'))!r},
256
271
  d.sigma = n.std # A float number in the data unit is acceptable.
257
272
 
258
273
  # Line profile
259
- d_profile = AstroData(**d.todict())
260
- f_profile = AstroFrame(rmax={rmax!r}, # Estimated spatial half-width (arcsec); adjust as needed.
274
+ d_crop = AstroData(**d.todict())
275
+ f_crop = AstroFrame(rmax={rmax!r}, # Estimated spatial half-width (arcsec); adjust as needed.
261
276
  vmin={vmin!r}, vmax={vmax!r}, # Estimated velocity range (km/s); adjust as needed.
262
277
  )
263
- f_profile.read(d_profile)
264
- plotprofile(**d_profile.todict(), xlist=[0], ylist=[0],
265
- ellipse=[4 * f_profile.rmax, 4 * f_profile.rmax, 0], # Circle enclosing the cropped square.
278
+ f_crop.read(d_crop)
279
+ plotprofile(**d_crop.todict(), xlist=[0], ylist=[0],
280
+ ellipse=[4 * f_crop.rmax, 4 * f_crop.rmax, 0], # Circle enclosing the cropped square.
266
281
  flux=True,
267
282
  savefig={str(output.with_name(output.stem + '_profile.png'))!r},
268
283
  show=False,
@@ -277,6 +292,34 @@ p.add_color(**d.todict(), stretch='log')
277
292
  p.add_contour(**d.todict(), colors='r')
278
293
  p.set_axis()
279
294
  p.savefig({str(output.with_suffix('.png'))!r}, show=False)
295
+
296
+ # Moment maps over the crop frame's spatial and velocity ranges
297
+ d_crop.moment(threshold_cube=3, threshold_mom0=3) # Noise multiples; adjust as needed.
298
+ d_crop.v = None # The moment maps are 2D images.
299
+
300
+ # Moment 1 with moment-0 contours
301
+ p = PlotAstroData(rmax=f_crop.rmax, center=d_crop.center)
302
+ d_crop.data = d_crop.mom0
303
+ d_crop.sigma = d_crop.sigma_mom0 # sigma * abs(dv) * sqrt(number of channels).
304
+ p.add_contour(**d_crop.todict(), levels=[3, 6, 12, 24, 48, 96], colors='k')
305
+ d_crop.data = d_crop.mom1
306
+ d_crop.sigma = None
307
+ p.add_color(**d_crop.todict(), stretch='linear', cmap='RdBu_r', cbformat='%.1f',
308
+ cblabel=r'Moment 1 (km s$^{{-1}}$)')
309
+ p.set_axis_radec(nticksminor=5)
310
+ p.savefig({str(output.with_name(output.stem + '_mom1.png'))!r}, show=False)
311
+
312
+ # Moment 2 with moment-0 contours
313
+ p = PlotAstroData(rmax=f_crop.rmax, center=d_crop.center)
314
+ d_crop.data = d_crop.mom0
315
+ d_crop.sigma = d_crop.sigma_mom0 # sigma * abs(dv) * sqrt(number of channels).
316
+ p.add_contour(**d_crop.todict(), levels=[3, 6, 12, 24, 48, 96], colors='k')
317
+ d_crop.data = d_crop.mom2
318
+ d_crop.sigma = None
319
+ p.add_color(**d_crop.todict(), stretch='linear', cbformat='%.1f',
320
+ cblabel=r'Moment 2 (km s$^{{-1}}$)')
321
+ p.set_axis_radec(nticksminor=5)
322
+ p.savefig({str(output.with_name(output.stem + '_mom2.png'))!r}, show=False)
280
323
  """
281
324
  _write_script(source, output, overwrite=overwrite)
282
325
  return output
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: plotastrodata
3
- Version: 1.12.2
3
+ Version: 1.12.3
4
4
  Summary: plotastrodata is a tool for astronomers to create figures from FITS files and perform fundamental data analyses with ease.
5
5
  Home-page: https://github.com/yusukeaso-astron/plotastrodata
6
6
  Download-URL: https://github.com/yusukeaso-astron/plotastrodata
@@ -106,7 +106,10 @@ with three significant digits for editing.
106
106
  For a spectral cube, use `generate_cube_script("cube.fits", output="cube.py")`
107
107
  from the same module. It generates an edge-channel noise visualization, a flux-integrated line
108
108
  profile and 3D channel maps over estimated spatial and velocity ranges,
109
- with intrinsic channel spacing. The flux profile assumes Jy/beam data with beam metadata.
109
+ with intrinsic channel spacing. Two further single-panel figures show moments
110
+ 1 and 2 in linear colors with moment-0 contours and colorbar ticks to one
111
+ decimal place; moment 1 uses a blue-red colormap. The moments use the shared crop and are saved as
112
+ `<script stem>_mom1.png` and `<script stem>_mom2.png`. The flux profile assumes Jy/beam data with beam metadata.
110
113
  Noise and range estimation in both generators assume PB-corrected intensities.
111
114
  Both generators return an absolute pathlib.Path and write the script
112
115
  without executing it.
File without changes
File without changes
File without changes