plotastrodata 1.11.2__py3-none-any.whl → 1.12.1__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.11.2'
4
+ __version__ = '1.12.1'
@@ -7,10 +7,10 @@ explicitly requests scalar output.
7
7
  """
8
8
 
9
9
  from dataclasses import field
10
- import numpy as np
11
10
  from typing import Annotated, Any, Callable, Literal, overload
12
- from pydantic import WrapValidator
13
11
 
12
+ import numpy as np
13
+ from pydantic import WrapValidator
14
14
 
15
15
  # Shared input types; validated settings are separate from uncoerced inputs.
16
16
  RealScalar = float | np.floating | np.integer
@@ -1,35 +1,44 @@
1
- import numpy as np
2
- import warnings
1
+ import numbers
3
2
  import re
3
+ import warnings
4
4
  from dataclasses import dataclass, field
5
- from os import PathLike
6
5
  from functools import wraps
7
- import numbers
6
+ from os import PathLike
7
+ from typing import Any, Callable, Literal, ParamSpec, TypedDict, TypeVar
8
+
9
+ import numpy as np
8
10
  from astropy.io.fits import Header
9
- from scipy.interpolate import RegularGridInterpolator as RGI
10
- from scipy.signal import convolve
11
11
  from pydantic import ConfigDict
12
12
  from pydantic.dataclasses import dataclass as pydantic_dataclass
13
- from typing import (Any, Callable, Literal,
14
- TypeVar, ParamSpec, TypedDict)
13
+ from scipy.interpolate import RegularGridInterpolator as RGI
14
+ from scipy.signal import convolve
15
15
 
16
16
  from plotastrodata import const_utils as cu
17
- from plotastrodata._validation_utils import (_require_integer,
18
- _is_finite_real_scalar,
19
- _is_positive_real_scalar,
20
- _require_positive_real_scalar,
21
- _is_zero_dimensional_array)
22
- from plotastrodata._type_utils import (_normalize_float, _internal_field,
23
- RealScalar, Position,
24
- ValidatedFloat, BeamInput)
25
- from plotastrodata.coord_utils import coord2xy, rel2abs, xy2coord, _getframe
26
- from plotastrodata.fits_utils import data2fits, FitsData, Jy2K
27
- from plotastrodata.fitting_utils import (EmceeCorner, gaussfit1d,
28
- gaussfit2d, gaussian2d)
29
- from plotastrodata.matrix_utils import dot2d, Mfac, Mrot
17
+ from plotastrodata._type_utils import (
18
+ BeamInput,
19
+ Position,
20
+ RealScalar,
21
+ ValidatedFloat,
22
+ _internal_field,
23
+ _normalize_float,
24
+ )
25
+ from plotastrodata._validation_utils import (
26
+ _is_finite_real_scalar,
27
+ _is_positive_real_scalar,
28
+ _is_zero_dimensional_array,
29
+ _require_integer,
30
+ _require_positive_real_scalar,
31
+ )
32
+ from plotastrodata.coord_utils import _getframe, coord2xy, rel2abs, xy2coord
33
+ from plotastrodata.fits_utils import FitsData, Jy2K, data2fits
34
+ from plotastrodata.fitting_utils import (
35
+ EmceeCorner, gaussfit1d, gaussfit2d, gaussian2d
36
+ )
37
+ from plotastrodata.matrix_utils import Mfac, Mrot, dot2d
30
38
  from plotastrodata.noise_utils import estimate_rms
31
- from plotastrodata.other_utils import (nearest_index, RGIxy, RGIxyv,
32
- to4dim, trim)
39
+ from plotastrodata.other_utils import (
40
+ RGIxy, RGIxyv, nearest_index, to4dim, trim
41
+ )
33
42
 
34
43
 
35
44
  def _profile_ellipses(ellipse: Any, nprof: int) -> np.ndarray:
@@ -497,10 +506,8 @@ class AstroData():
497
506
  if not np.isfinite(area) or area <= 0:
498
507
  raise ValueError('Fitting requires finite, nonzero pixel sizes.')
499
508
  factor = np.pi * sizes[0] * sizes[1] / (4 * np.log(2) * area)
500
- warnings.warn('In the fitting, sigma is multiplied by'
501
- + ' sqrt(pixel-per-beam) to account for'
502
- + ' beam noise correlation.',
503
- UserWarning)
509
+ print('In the fitting, sigma is multiplied by sqrt(pixel-per-beam)'
510
+ + ' to account for beam noise correlation.')
504
511
  return factor
505
512
 
506
513
  @_need_multipixels
@@ -580,8 +587,8 @@ class AstroData():
580
587
  'model': modelopt, 'residual': residual}
581
588
 
582
589
  @_need_multipixels
583
- def gaussfit2d(self, chan: int | np.integer | None = None
584
- ) -> _GaussFit2DResult:
590
+ def gaussfit2d(self, chan: int | np.integer | None = None,
591
+ *, progressbar: bool = False) -> _GaussFit2DResult:
585
592
  """Fit a 2D Gaussian function to self.data using
586
593
  fitting_utils.gaussfit2d(). With sigma=None, noise is estimated
587
594
  from an initial fit. Supplied sigma must be a finite positive real
@@ -592,6 +599,7 @@ class AstroData():
592
599
  chan (int): The channel number where the 2D Gaussian is
593
600
  fitted. Required for cubes; must be None for images.
594
601
  NumPy integer indices are also accepted.
602
+ progressbar (bool): Display the MCMC progress bar. Defaults to False.
595
603
 
596
604
  Returns:
597
605
  dict: The best parameter set (popt), the error set (perr),
@@ -613,7 +621,8 @@ class AstroData():
613
621
  sigma = self.sigma * np.sqrt(self._fit_pixelperbeam())
614
622
  sigma = _normalize_float(sigma)
615
623
  res = gaussfit2d(xdata=self.x, ydata=self.y, zdata=z,
616
- sigma=sigma, show=False, nwalkersperdim=4)
624
+ sigma=sigma, show=False, progressbar=progressbar,
625
+ nwalkersperdim=4)
617
626
  popt, perr = res['popt'], res['perr']
618
627
  model = gaussian2d(np.meshgrid(self.x, self.y), *popt)
619
628
  residual = z - model
@@ -868,7 +877,8 @@ class AstroData():
868
877
  raise ValueError('restfreq must be finite and positive,'
869
878
  + ' or None/0.')
870
879
  if self.restfreq is None or self.restfreq == 0:
871
- warnings.warn('No valid restfreq. The velocity axis is saved as is.',
880
+ warnings.warn('No valid restfreq.'
881
+ + ' The velocity axis is saved as is.',
872
882
  UserWarning)
873
883
  else:
874
884
  cv = (1 - cv / cu.c_kms) * self.restfreq
@@ -1,10 +1,8 @@
1
1
  import numpy as np
2
+ from astropy import constants, units
2
3
 
3
4
  from plotastrodata._type_utils import _normalize_float
4
5
 
5
- from astropy import constants
6
- from astropy import units
7
-
8
6
  # astropy.units in the SI unit system
9
7
  Angstrom = units.Angstrom.to('m')
10
8
  angstrom = units.angstrom.to('m')
@@ -1,6 +1,6 @@
1
1
  import numpy as np
2
2
  from astropy import units
3
- from astropy.coordinates import BaseCoordinateFrame, FK4, FK5, SkyCoord
3
+ from astropy.coordinates import FK4, FK5, BaseCoordinateFrame, SkyCoord
4
4
 
5
5
 
6
6
  def _updateframe(frame: str) -> str | FK4 | FK5:
@@ -1,8 +1,9 @@
1
- import numpy as np
2
1
  import shlex
3
2
  import subprocess
4
3
  from typing import Any
5
4
 
5
+ import numpy as np
6
+
6
7
  from plotastrodata import const_utils as cu
7
8
  from plotastrodata._type_utils import _normalize_float
8
9
  from plotastrodata._validation_utils import _require_integer
@@ -1,11 +1,11 @@
1
+ from os import PathLike
2
+ from typing import Callable
3
+
1
4
  import matplotlib.pyplot as plt
2
5
  import numpy as np
3
- from typing import Callable
4
- from os import PathLike
5
6
 
6
- from plotastrodata._validation_utils import _require_integer
7
7
  from plotastrodata._type_utils import _normalize_float
8
-
8
+ from plotastrodata._validation_utils import _require_integer
9
9
  from plotastrodata.fits_utils import fits2data
10
10
  from plotastrodata.other_utils import close_figure
11
11
 
@@ -1,18 +1,21 @@
1
- import numpy as np
2
1
  import numbers
3
2
  from os import PathLike
3
+ from typing import Any, Callable
4
+
5
+ import numpy as np
4
6
  from astropy import units, wcs
5
7
  from astropy.io import fits
6
- from typing import Any, Callable
7
8
 
8
9
  from plotastrodata import const_utils as cu
9
- from plotastrodata._validation_utils import (_is_positive_real_scalar,
10
- _require_positive_real_scalar)
11
10
  from plotastrodata._type_utils import _normalize_float
11
+ from plotastrodata._validation_utils import (
12
+ _is_positive_real_scalar,
13
+ _require_positive_real_scalar,
14
+ )
12
15
  from plotastrodata.coord_utils import coord2xy, xy2coord
13
16
  from plotastrodata.matrix_utils import dot2d
14
17
  from plotastrodata.noise_utils import estimate_rms
15
- from plotastrodata.other_utils import isdeg, RGIxy, trim
18
+ from plotastrodata.other_utils import RGIxy, isdeg, trim
16
19
 
17
20
 
18
21
  def _jy2k_metadata(header: fits.Header | dict[str, Any] | None,
@@ -1,23 +1,23 @@
1
+ import pickle
2
+ import warnings
3
+ from functools import partial
4
+ from multiprocessing import Pool
5
+ from typing import Any, Callable
6
+
1
7
  import corner
2
8
  import emcee
3
9
  import matplotlib.pyplot as plt
4
10
  import numpy as np
5
- import pickle
6
11
  import ptemcee
7
- import warnings
8
12
  from dynesty import DynamicNestedSampler as DNS
9
- from functools import partial
10
- from multiprocessing import Pool
11
- from tqdm import tqdm
12
- from typing import Any, Callable
13
13
  from matplotlib.figure import Figure
14
+ from tqdm import tqdm
14
15
 
15
- from plotastrodata._validation_utils import _require_integer
16
16
  from plotastrodata._type_utils import _normalize_float
17
+ from plotastrodata._validation_utils import _require_integer
17
18
  from plotastrodata.matrix_utils import Mrot, dot2d
18
19
  from plotastrodata.other_utils import close_figure
19
20
 
20
-
21
21
  global_bounds = None
22
22
  bar = None
23
23
  global_progressbar = True
@@ -342,31 +342,35 @@ class EmceeCorner():
342
342
  nwalkers = nwalkersperdim * self.dim # must be even and >= 2 * dim
343
343
  if ntemps > 1:
344
344
  pt = True
345
- if global_progressbar:
346
- total = ntry * ntemps * nwalkers * (nsteps + 1) // ncores
347
- bar = tqdm(total=total)
348
- bar.set_description('Within the ranges')
349
- samples = None
350
- sampler = None
351
- for i in range(1, ntry + 1):
352
- if pos0 is None:
353
- pos0 = self._get_pos0(ntemps=ntemps, nwalkers=nwalkers, pt=pt)
354
- sampler = self._run_sampler(pos0=pos0, pt=pt, ncores=ncores,
355
- ntemps=ntemps, nsteps=nsteps,
356
- nwalkers=nwalkers)
357
- samples = self._get_samples(sampler=sampler,
358
- nburnin=nburnin, pt=pt)
359
- i = _check_GR(samples=samples, nwalkers=nwalkers,
360
- ndata=self.ndata, dim=self.dim,
361
- i=i, ntry=ntry, grcheck=grcheck)
362
- if savechain is not None:
363
- np.save(savechain.removesuffix('.npy') + '.npy', samples)
364
- self.lnp, self.popt = self._get_lnp_popt(sampler=sampler, pt=pt,
365
- nburnin=nburnin)
366
- self.plow, self.pmid, self.phigh = self._get_percentiles(samples)
367
- self.samples = samples
368
- if global_progressbar:
369
- print()
345
+ active_bar = None
346
+ try:
347
+ if global_progressbar:
348
+ total = ntry * ntemps * nwalkers * (nsteps + 1) // ncores
349
+ active_bar = bar = tqdm(total=total)
350
+ active_bar.set_description('Within the ranges')
351
+ samples = None
352
+ sampler = None
353
+ for i in range(1, ntry + 1):
354
+ if pos0 is None:
355
+ pos0 = self._get_pos0(ntemps=ntemps, nwalkers=nwalkers, pt=pt)
356
+ sampler = self._run_sampler(pos0=pos0, pt=pt, ncores=ncores,
357
+ ntemps=ntemps, nsteps=nsteps,
358
+ nwalkers=nwalkers)
359
+ samples = self._get_samples(sampler=sampler,
360
+ nburnin=nburnin, pt=pt)
361
+ i = _check_GR(samples=samples, nwalkers=nwalkers,
362
+ ndata=self.ndata, dim=self.dim,
363
+ i=i, ntry=ntry, grcheck=grcheck)
364
+ if savechain is not None:
365
+ np.save(savechain.removesuffix('.npy') + '.npy', samples)
366
+ self.lnp, self.popt = self._get_lnp_popt(sampler=sampler, pt=pt,
367
+ nburnin=nburnin)
368
+ self.plow, self.pmid, self.phigh = self._get_percentiles(samples)
369
+ self.samples = samples
370
+ finally:
371
+ if active_bar is not None:
372
+ active_bar.close()
373
+ bar = None
370
374
 
371
375
  def plotcorner(self, labels: list[str] | None = None,
372
376
  cornerrange: list[float | tuple[float, float] | list[float]]
@@ -707,9 +711,15 @@ def gaussian2d(xy: np.ndarray | list[float | np.ndarray]
707
711
 
708
712
  def gaussfit1d(xdata: np.ndarray, ydata: np.ndarray,
709
713
  sigma: float | np.floating | np.ndarray | None = None,
710
- show: bool = False, **kwargs: Any) -> dict:
714
+ show: bool = False, progressbar: bool = False,
715
+ **kwargs: Any) -> dict:
711
716
  """Gaussian fitting to a pair of 1D arrays.
712
717
 
718
+ NaN and infinite values in xdata or ydata are rejected. Both arrays
719
+ must contain at least two values and have nonzero ranges. Two fitting
720
+ passes are always performed: broad initial bounds, then bounds refined
721
+ around the first result. Noise is estimated only when sigma is None.
722
+
713
723
  Args:
714
724
  xdata (np.ndarray): ydata is compared with Gauss(xdata).
715
725
  ydata (np.ndarray): ydata is compared with Gauss(xdata).
@@ -718,12 +728,23 @@ def gaussfit1d(xdata: np.ndarray, ydata: np.ndarray,
718
728
  residuals of an initial fit.
719
729
  show (bool, optional): True means to show the best-fit
720
730
  parameters and uncertainties. Defaults to False.
731
+ progressbar (bool): Display the MCMC progress bar. Defaults to False.
721
732
 
722
733
  Returns:
723
734
  dict: popt and perr are arrays. Scalar sigma, including a supplied
724
735
  integer, is a Python float, except that extended precision is preserved.
725
736
  Array-valued sigma retains its dtype.
726
737
  """
738
+ if not np.all(np.isfinite(xdata)) or not np.all(np.isfinite(ydata)):
739
+ raise ValueError('gaussfit1d requires finite samples; crop or remove'
740
+ + ' NaN and infinite values before fitting.')
741
+ if np.size(xdata) < 2 or np.size(ydata) < 2:
742
+ raise ValueError('gaussfit1d requires at least two samples.')
743
+ if np.min(ydata) == np.max(ydata):
744
+ raise ValueError('gaussfit1d requires at least two samples'
745
+ + ' with different values.')
746
+ if np.min(xdata) == np.max(xdata):
747
+ raise ValueError('gaussfit1d requires at least two different coordinates.')
727
748
  if sigma is None:
728
749
  print('gaussfit1d: sigma is None;'
729
750
  + ' estimating noise from an initial fit.')
@@ -735,10 +756,15 @@ def gaussfit1d(xdata: np.ndarray, ydata: np.ndarray,
735
756
  bounds = [[ymin - yw * 10, ymax + yw * 10], [xmin, xmax], [dx, xw]]
736
757
  sigtmp = (max(np.abs(ymin), np.abs(ymax)) * 0.01
737
758
  if sigma is None else sigma)
738
- for i in range(2 if sigma is None else 1):
759
+ for i in range(2):
739
760
  fitter = EmceeCorner(bounds=bounds, model=gaussian1d,
740
- sigma=sigtmp, xdata=xdata, ydata=ydata)
761
+ sigma=sigtmp, xdata=xdata, ydata=ydata,
762
+ progressbar=progressbar)
741
763
  fitter.fit(**kwargs)
764
+ a, center, width = fitter.popt
765
+ bounds = [sorted([a / 2, a * 2]),
766
+ [center - width, center + width],
767
+ [width / 2, width * 2]]
742
768
  if i == 0 and sigma is None:
743
769
  sigtmp = np.std(ydata - gaussian1d(xdata, *fitter.popt))
744
770
  popt = fitter.popt
@@ -756,9 +782,13 @@ def gaussfit1d(xdata: np.ndarray, ydata: np.ndarray,
756
782
 
757
783
  def gaussfit2d(xdata: np.ndarray, ydata: np.ndarray, zdata: np.ndarray,
758
784
  sigma: float | np.floating | np.ndarray | None = None,
759
- show: bool = False, **kwargs: Any) -> dict:
785
+ show: bool = False, progressbar: bool = False,
786
+ **kwargs: Any) -> dict:
760
787
  """Fit a two-dimensional Gaussian to zdata on the xdata/ydata grid.
761
788
 
789
+ Nonfinite image pixels are rejected. At least two pixels with
790
+ different values are required.
791
+
762
792
  Args:
763
793
  xdata (np.ndarray): zdata is compared with Gauss(xdata, ydata).
764
794
  ydata (np.ndarray): zdata is compared with Gauss(xdata, ydata).
@@ -768,6 +798,7 @@ def gaussfit2d(xdata: np.ndarray, ydata: np.ndarray, zdata: np.ndarray,
768
798
  residuals of an initial fit.
769
799
  show (bool, optional): True means to show the best-fit
770
800
  parameters and uncertainties. Defaults to False.
801
+ progressbar (bool): Display the MCMC progress bar. Defaults to False.
771
802
 
772
803
  Returns:
773
804
  dict: popt and perr are arrays. Scalar sigma, including a supplied
@@ -779,6 +810,12 @@ def gaussfit2d(xdata: np.ndarray, ydata: np.ndarray, zdata: np.ndarray,
779
810
  + ' estimating noise from an initial fit.')
780
811
  xmin, xmax = np.min(xdata), np.max(xdata)
781
812
  ymin, ymax = np.min(ydata), np.max(ydata)
813
+ if not np.all(np.isfinite(zdata)):
814
+ raise ValueError('gaussfit2d requires finite pixels; crop or remove'
815
+ + ' NaN and infinite values before fitting.')
816
+ if np.size(zdata) < 2 or np.min(zdata) == np.max(zdata):
817
+ raise ValueError('gaussfit2d requires at least two pixels'
818
+ + ' with different values.')
782
819
  zmin, zmax = np.min(zdata), np.max(zdata)
783
820
  xw = xmax - xmin
784
821
  yw = ymax - ymin
@@ -803,7 +840,8 @@ def gaussfit2d(xdata: np.ndarray, ydata: np.ndarray, zdata: np.ndarray,
803
840
  [dx, xw], [dx, xw], [-90, 90]]
804
841
  for i in range(2):
805
842
  fitter = EmceeCorner(bounds=bounds, model=model,
806
- sigma=sigtmp, xdata=xy, ydata=zdata)
843
+ sigma=sigtmp, xdata=xy, ydata=zdata,
844
+ progressbar=progressbar)
807
845
  fitter.fit(**kwargs)
808
846
  a, cx, cy, wmaj, wmin, pa = fitter.popt
809
847
  wmax = max(wmaj, wmin)
@@ -1,7 +1,7 @@
1
1
  import numpy as np
2
2
 
3
- from plotastrodata.matrix_utils import Mrot3d
4
3
  from plotastrodata._type_utils import _normalize_float
4
+ from plotastrodata.matrix_utils import Mrot3d
5
5
 
6
6
 
7
7
  def obs2sys(xobs: float | np.floating | list[float] | np.ndarray,
@@ -41,8 +41,8 @@ def dot2d(M: np.ndarray | list[list[float]] = [[1, 0], [0, 1]],
41
41
  Returns:
42
42
  np.ndarray: The 2D vector after the matrix multiplied.
43
43
  """
44
- x = M[0][0] * np.array(a[0]) + M[0][1] * np.array(a[1])
45
- y = M[1][0] * np.array(a[0]) + M[1][1] * np.array(a[1])
44
+ x = M[0][0] * np.asarray(a[0]) + M[0][1] * np.asarray(a[1])
45
+ y = M[1][0] * np.asarray(a[0]) + M[1][1] * np.asarray(a[1])
46
46
  return np.array([x, y])
47
47
 
48
48
 
@@ -1,13 +1,16 @@
1
- import matplotlib.pyplot as plt
2
1
  import numbers
3
- import numpy as np
4
2
  import warnings
5
- from scipy.special import erf
6
3
  from typing import Any, Callable
7
4
 
8
- from plotastrodata._validation_utils import (_require_integer,
9
- _is_uniform_spacing)
5
+ import matplotlib.pyplot as plt
6
+ import numpy as np
7
+ from scipy.special import erf
8
+
10
9
  from plotastrodata._type_utils import _normalize_float
10
+ from plotastrodata._validation_utils import (
11
+ _is_uniform_spacing,
12
+ _require_integer
13
+ )
11
14
  from plotastrodata.fitting_utils import EmceeCorner
12
15
  from plotastrodata.other_utils import close_figure
13
16
 
@@ -123,7 +126,9 @@ def gauss_pbcor(x: float | np.floating | np.ndarray,
123
126
  The variable of the probability density.
124
127
  s (float): Standard deviation of the Gaussian noise.
125
128
  m (float): Mean of the Gaussian noise.
126
- R (float): The maximum radius scaled by the FWHM of the primary beam.
129
+ R (float): Dimensionless outer radius r_out / r_p, where r_p is
130
+ the primary-beam half-width at half maximum (HWHM). The
131
+ primary-beam response at radius r is 2**(-(r / r_p)**2).
127
132
 
128
133
  Returns:
129
134
  float or np.longdouble or np.ndarray: Probability density.
@@ -159,7 +164,7 @@ def select_noise(data: np.ndarray, sigma: str) -> np.ndarray:
159
164
  Returns:
160
165
  np.ndarray: 1D array that includes only the selected pixels.
161
166
  """
162
- n = np.array(data).copy()
167
+ n = np.array(data, copy=True)
163
168
  if 'edge' in sigma:
164
169
  if np.ndim(n) <= 2:
165
170
  print('\'edge\' is ignored because ndim <= 2.')
@@ -1,10 +1,11 @@
1
+ import warnings
1
2
  from os import PathLike
3
+ from typing import Any
4
+
2
5
  import matplotlib.pyplot as plt
3
6
  import numpy as np
4
- import warnings
5
- from scipy.interpolate import RegularGridInterpolator as RGI
6
7
  from matplotlib.figure import Figure
7
- from typing import Any
8
+ from scipy.interpolate import RegularGridInterpolator as RGI
8
9
 
9
10
 
10
11
  def isdeg(s: Any) -> bool:
@@ -1,39 +1,47 @@
1
+ from dataclasses import dataclass, field, fields
1
2
  from os import PathLike
2
3
  from pathlib import Path
3
- from dataclasses import dataclass, fields, field
4
+ from types import ModuleType
5
+ from typing import TYPE_CHECKING, Any, Callable, Literal, TypedDict, TypeVar
6
+
4
7
  import matplotlib as mpl
5
8
  import matplotlib.pyplot as plt
6
9
  import numpy as np
7
10
  from matplotlib.axes import Axes
8
- from matplotlib.figure import Figure
9
11
  from matplotlib.collections import QuadMesh
12
+ from matplotlib.figure import Figure
10
13
  from matplotlib.patches import Ellipse, Rectangle
11
14
  from pydantic import ConfigDict, Field, field_validator
12
15
  from pydantic.dataclasses import dataclass as pydantic_dataclass
13
- from typing import (Any, Callable, Literal,
14
- TypeVar, TypedDict, TYPE_CHECKING)
15
- from types import ModuleType
16
16
 
17
17
  if TYPE_CHECKING:
18
18
  from plotly.graph_objs import Layout
19
19
 
20
- from plotastrodata._validation_utils import (_require_integer,
21
- _is_finite_real_scalar,
22
- _is_positive_real_scalar,
23
- _require_positive_real_scalar,
24
- _is_zero_dimensional_array,
25
- _is_uniform_spacing)
26
- from plotastrodata._type_utils import (_normalize_float, _internal_field,
27
- RealScalar, RealSequence,
28
- PositionPair, Positions,
29
- ValidatedFloat, ValidatedBeams)
20
+ from plotastrodata._type_utils import (
21
+ PositionPair,
22
+ Positions,
23
+ RealScalar,
24
+ RealSequence,
25
+ ValidatedBeams,
26
+ ValidatedFloat,
27
+ _internal_field,
28
+ _normalize_float,
29
+ )
30
+ from plotastrodata._validation_utils import (
31
+ _is_finite_real_scalar,
32
+ _is_positive_real_scalar,
33
+ _is_uniform_spacing,
34
+ _is_zero_dimensional_array,
35
+ _require_integer,
36
+ _require_positive_real_scalar,
37
+ )
30
38
  from plotastrodata.analysis_utils import AstroData, AstroFrame
31
- from plotastrodata.coord_utils import (coord2xy, xy2coord,
32
- get_hmdm, get_min, get_sec, _getframe)
39
+ from plotastrodata.coord_utils import (
40
+ _getframe, coord2xy, get_hmdm, get_min, get_sec, xy2coord
41
+ )
33
42
  from plotastrodata.fitting_utils import gaussian1d
34
43
  from plotastrodata.noise_utils import estimate_rms
35
- from plotastrodata.other_utils import close_figure, reform_grid, reform_data
36
-
44
+ from plotastrodata.other_utils import close_figure, reform_data, reform_grid
37
45
 
38
46
  plt.ioff() # force to turn off interactive mode
39
47
 
@@ -889,8 +897,8 @@ def _radec_ticks(center: str, frame_name: str, dec_center: RealScalar,
889
897
  getter = get_min if no_sec else get_sec
890
898
  tickvalues = [getter(t, mode) for t in tickvalues] # str
891
899
  tickvalues = np.array(tickvalues, dtype=float)
892
- # 7-digit precision for practical use.
893
- tickvalues = np.round(tickvalues, 7)
900
+ # 8-digit precision for practical use.
901
+ tickvalues = np.round(tickvalues, 8)
894
902
  return tickvalues
895
903
 
896
904
  units = {'ra': {'h': r'$^\mathrm{h}$',
@@ -1560,7 +1568,7 @@ class PlotAstroData(AstroFrame):
1560
1568
  else mpl.ticker.FormatStrFormatter(cbformat))
1561
1569
  cbticklabels = [formatter(t) for t in st.undo(cbticks)]
1562
1570
  else:
1563
- cbticklabels = np.array(cbticklabels)[cond]
1571
+ cbticklabels = np.asarray(cbticklabels)[cond]
1564
1572
  cb.set_ticklabels(cbticklabels)
1565
1573
 
1566
1574
  def add_color(self,
@@ -0,0 +1,595 @@
1
+ """Generate short, editable plotting scripts using existing plotastrodata APIs."""
2
+ from pathlib import Path
3
+
4
+ import numpy as np
5
+ from astropy.io import fits
6
+ from astropy.wcs import WCS
7
+ from astropy.wcs.utils import proj_plane_pixel_scales
8
+ from scipy import ndimage
9
+
10
+ from plotastrodata._type_utils import RealScalar, RealSequence, _normalize_float
11
+ from plotastrodata._validation_utils import (
12
+ _is_uniform_spacing,
13
+ _require_positive_real_scalar,
14
+ )
15
+ from plotastrodata.analysis_utils import AstroData, AstroFrame
16
+ from plotastrodata.noise_utils import Noise
17
+
18
+
19
+ def _multiply_pb(data: np.ndarray, x: np.ndarray, y: np.ndarray,
20
+ R: float | np.integer | np.floating,
21
+ r_out: float | np.integer | np.floating) -> np.ndarray:
22
+ """Multiply an image or cube by an approximate Gaussian primary beam.
23
+
24
+ Args:
25
+ data: Numeric array with shape (ny, nx) or (nchan, ny, nx).
26
+ x: Finite real 1D x offsets from the assumed PB center, length nx.
27
+ y: Finite real 1D y offsets from the assumed PB center, length ny.
28
+ R: Positive dimensionless outer radius r_out / r_p from gauss_pbcor
29
+ (Noise.popt[2]), where r_p is the primary-beam HWHM.
30
+ r_out: Positive outer radius of the footprint used for the noise fit,
31
+ in the same spatial units as x and y. It is supplied explicitly,
32
+ not inferred from the array shape or the plotting crop.
33
+
34
+ Returns:
35
+ np.ndarray: New array of the same shape, multiplied by
36
+ B(x, y) = 2**(-R**2 * ((x/r_out)**2 + (y/r_out)**2)).
37
+ One spatial pattern is broadcast across all channels. Inputs are
38
+ not modified and nonfinite data pixels are not filled or removed.
39
+ NumPy determines the arithmetic dtype; integer data can become
40
+ floating point, and extended precision is retained without casting.
41
+
42
+ Raises:
43
+ TypeError: data is not a NumPy array.
44
+ ValueError: Shapes, coordinate values, or PB parameters are unsuitable.
45
+
46
+ Notes:
47
+ Applying this to PB-corrected data approximately restores the
48
+ pre-correction intensities. The assumed circular beam and center
49
+ are intended for range estimation, not calibrated PB reconstruction.
50
+ """
51
+ if not isinstance(data, np.ndarray):
52
+ raise TypeError('data must be a NumPy array.')
53
+ if (data.ndim not in (2, 3) or 0 in data.shape
54
+ or not np.issubdtype(data.dtype, np.number)):
55
+ raise ValueError('data must be a nonempty numeric 2D or 3D array.')
56
+ x, y = np.asarray(x), np.asarray(y)
57
+ for coordinate, length, name in ((x, data.shape[-1], 'x'),
58
+ (y, data.shape[-2], 'y')):
59
+ if (coordinate.ndim != 1 or len(coordinate) != length
60
+ or coordinate.dtype.kind not in 'iuf'
61
+ or not np.all(np.isfinite(coordinate))):
62
+ raise ValueError(f'{name} must be a finite real 1D coordinate array'
63
+ + ' matching the spatial data axis.')
64
+ _require_positive_real_scalar(R, 'R')
65
+ _require_positive_real_scalar(r_out, 'r_out')
66
+ radius_squared = (x[None, :] / r_out)**2 + (y[:, None] / r_out)**2
67
+ pattern = np.exp2(-R**2 * radius_squared)
68
+ return data * pattern
69
+
70
+
71
+ def _validate_range_inputs(data: np.ndarray, x: np.ndarray, y: np.ndarray,
72
+ sigma: RealScalar, v: np.ndarray | None
73
+ ) -> tuple[np.ndarray,
74
+ np.ndarray,
75
+ np.ndarray | None]:
76
+ """Validate range-estimator inputs and return the coordinate arrays.
77
+
78
+ Preserve array dtypes and leave all inputs unchanged. Reject unsuitable
79
+ dimensions, noise values, coordinates, and image/cube velocity arguments.
80
+ """
81
+ if not isinstance(data, np.ndarray):
82
+ raise TypeError('data must be a NumPy array.')
83
+ if (data.ndim not in (2, 3) or data.dtype.kind not in 'iuf'
84
+ or any(length < 2 for length in data.shape)):
85
+ raise ValueError('data must be a real 2D or 3D array with at least'
86
+ + ' two samples on every axis.')
87
+ _require_positive_real_scalar(sigma, 'sigma')
88
+ x, y = np.asarray(x), np.asarray(y)
89
+ axes = [(x, data.shape[-1], 'x'), (y, data.shape[-2], 'y')]
90
+ if data.ndim == 3:
91
+ if v is None:
92
+ raise ValueError('v is required for a cube.')
93
+ v = np.asarray(v)
94
+ axes.append((v, data.shape[0], 'v'))
95
+ elif v is not None:
96
+ raise ValueError('v must be omitted for a 2D image.')
97
+ for coordinate, length, name in axes:
98
+ if (coordinate.ndim != 1 or len(coordinate) != length
99
+ or coordinate.dtype.kind not in 'iuf'
100
+ or not np.all(np.isfinite(coordinate))):
101
+ raise ValueError(f'{name} must be a finite real 1D coordinate array'
102
+ + ' matching its data axis.')
103
+ steps = np.diff(coordinate)
104
+ if steps[0] == 0 or not _is_uniform_spacing(steps, steps[0]):
105
+ raise ValueError(f'{name} must have nonzero uniform spacing.')
106
+ return x, y, v
107
+
108
+
109
+ def _range_beam_settings(beam: RealSequence | None, dx: RealScalar, dy: RealScalar
110
+ ) -> tuple[RealScalar, RealScalar]:
111
+ """Return minimum spatial footprint in pixels and spatial padding.
112
+
113
+ Use a Gaussian beam area and the larger FWHM when beam lengths are
114
+ provided, otherwise one pixel. Internal numeric precision is retained.
115
+ """
116
+ minimum_pixels = 1
117
+ padding = max(dx, dy)
118
+ if beam is not None:
119
+ sizes = np.asarray(beam)
120
+ if sizes.ndim != 1 or sizes.size not in (2, 3):
121
+ raise ValueError('beam must contain [major, minor]'
122
+ + ' or [major, minor, pa].')
123
+ for size in sizes[:2]:
124
+ _require_positive_real_scalar(size, 'beam FWHM')
125
+ minimum_pixels = np.ceil(np.pi * sizes[0] * sizes[1]
126
+ / (4 * np.log(2) * dx * dy))
127
+ padding = max(sizes[:2])
128
+
129
+ return minimum_pixels, padding
130
+
131
+
132
+ def _find_emission_bounds(data: np.ndarray, sigma: RealScalar,
133
+ minimum_pixels: RealScalar
134
+ ) -> tuple[slice, ...] | None:
135
+ """Return union bounding slices for qualified emission, or None.
136
+
137
+ Keep all face-connected 3-sigma components with a 5-sigma seed and the
138
+ minimum projected spatial footprint. Cubes also require two adjacent
139
+ channels. Input arrays are not modified.
140
+ """
141
+ structure = ndimage.generate_binary_structure(data.ndim, 1)
142
+ mask = np.isfinite(data) & (data >= 3 * sigma)
143
+ labels, _ = ndimage.label(mask, structure=structure)
144
+ del mask
145
+ lower = list(data.shape)
146
+ upper = [0] * data.ndim
147
+ found = False
148
+ for component_id, region in enumerate(ndimage.find_objects(labels), start=1):
149
+ if region is None:
150
+ continue
151
+ component = labels[region] == component_id
152
+ if not np.any((data[region] >= 5 * sigma) & component):
153
+ continue
154
+ if data.ndim == 3:
155
+ if region[0].stop - region[0].start < 2:
156
+ continue
157
+ spatial = np.any(component, axis=0)
158
+ else:
159
+ spatial = component
160
+ if np.count_nonzero(spatial) < minimum_pixels:
161
+ continue
162
+ found = True
163
+ for axis, extent in enumerate(region):
164
+ lower[axis] = min(lower[axis], extent.start)
165
+ upper[axis] = max(upper[axis], extent.stop)
166
+
167
+ if not found:
168
+ return None
169
+ return tuple(slice(lo, hi) for lo, hi in zip(lower, upper))
170
+
171
+
172
+ def _estimate_ranges(data: np.ndarray, x: np.ndarray, y: np.ndarray,
173
+ sigma: RealScalar, *, v: np.ndarray | None = None,
174
+ beam: RealSequence | None = None
175
+ ) -> tuple[float | np.longdouble,
176
+ float | np.longdouble | None,
177
+ float | np.longdouble | None]:
178
+ """Estimate spatial and velocity limits from positive emission.
179
+
180
+ Args:
181
+ data: Real numeric image (ny, nx) or cube (nchan, ny, nx), with
182
+ approximately uniform noise, for example after _multiply_pb.
183
+ Nonfinite values are excluded from detection.
184
+ x: Finite, uniformly spaced 1D x offsets from the intended center.
185
+ y: Finite, uniformly spaced 1D y offsets from the intended center.
186
+ Both spatial axes require at least two samples and may descend.
187
+ sigma: Finite positive scalar noise level in the data units.
188
+ v: Finite, uniformly spaced channel coordinates, required for a
189
+ cube and omitted for an image. At least two channels are needed.
190
+ beam: Optional [major, minor] FWHM lengths, or [major, minor, pa].
191
+ Lengths use the same units as x and y; pa is unused. Without a
192
+ beam, the minimum footprint is one pixel and padding is one
193
+ spatial pixel rather than one beam FWHM.
194
+
195
+ Returns:
196
+ tuple: (rmax, vmin, vmax). Computed scalars are Python floats,
197
+ except np.longdouble results retain extended precision. An image
198
+ returns None for both velocity limits. A cube returns numerical
199
+ velocity limits in ascending order even for a descending v axis.
200
+ Inputs and their array dtypes are unchanged.
201
+
202
+ Raises:
203
+ TypeError: data is not a NumPy array.
204
+ ValueError: Data, axes, noise, beam, or the centered finite region
205
+ are unsuitable.
206
+
207
+ Notes:
208
+ Face-connected components at or above 3*sigma survive only when they
209
+ contain a 5*sigma seed and cover at least one Gaussian beam area
210
+ in projected spatial pixels. Cube components must also span two
211
+ adjacent channels. All qualifying components are retained.
212
+
213
+ For each spatial axis, average the absolute values of the two
214
+ emission endpoints; take the larger x/y average and add the major
215
+ beam FWHM. Thus asymmetric emission uses mean absolute extent,
216
+ not maximum distance, and its farthest edge may lie outside the
217
+ symmetric field. Clip rmax to the centered finite footprint.
218
+ Velocity limits include two extra channels on each side, clipped
219
+ to the available channels, without skipping or binning.
220
+
221
+ With no qualifying component, use the centered finite footprint
222
+ and full velocity range. Spatial pixels with any nonfinite cube
223
+ channel restrict that footprint, with a pixel margin as in the
224
+ script generators. Thresholds assume a zero noise baseline; subtract
225
+ a fitted noise mean from data before calling if appropriate.
226
+ This helper does not fit noise or apply a PB.
227
+ """
228
+ x, y, v = _validate_range_inputs(data, x, y, sigma, v)
229
+ dx, dy = abs(x[1] - x[0]), abs(y[1] - y[0])
230
+ minimum_pixels, padding = _range_beam_settings(beam, dx, dy)
231
+
232
+ footprint = AstroData(data=data, x=x, y=y, sigma=None)
233
+ footprint.dx, footprint.dy = dx, dy
234
+ full_radius = max((abs(x[0]) + abs(x[-1]) + dx) / 2,
235
+ (abs(y[0]) + abs(y[-1]) + dy) / 2)
236
+ available_radius = _get_valid_radius(footprint, full_radius)
237
+ bounds = _find_emission_bounds(data, sigma, minimum_pixels)
238
+ rmax = available_radius
239
+ if bounds is not None:
240
+ rx = (abs(x[bounds[-1].start]) + abs(x[bounds[-1].stop - 1])) / 2
241
+ ry = (abs(y[bounds[-2].start]) + abs(y[bounds[-2].stop - 1])) / 2
242
+ rmax = min(max(rx, ry) + padding, available_radius)
243
+ rmax = _normalize_float(rmax, force_float=True)
244
+ if v is None:
245
+ return rmax, None, None
246
+ first = max(bounds[0].start - 2, 0) if bounds is not None else 0
247
+ last = (min(bounds[0].stop + 1, len(v) - 1)
248
+ if bounds is not None else len(v) - 1)
249
+ return (rmax,
250
+ _normalize_float(min(v[first], v[last]), force_float=True),
251
+ _normalize_float(max(v[first], v[last]), force_float=True))
252
+
253
+
254
+ def _estimate_pb_ranges(image: AstroData
255
+ ) -> tuple[float | np.longdouble,
256
+ float | np.longdouble | None,
257
+ float | np.longdouble | None]:
258
+ """Fit PB-corrected noise and estimate emission ranges for loaded data.
259
+
260
+ image must contain one real 2D image or 3D cube already read by
261
+ AstroFrame, with spatial coordinates, pixel sizes, and cube velocities.
262
+ Fit hist-pbcor to the full image or the first and last cube channels.
263
+ Infer r_out from the equivalent circular area of the finite noise
264
+ footprint, averaging the two sampled channel areas for a cube.
265
+
266
+ Multiply a temporary array by the approximate PB from the fitted R,
267
+ subtract the fitted noise mean, and pass it to _estimate_ranges with
268
+ the fitted noise standard deviation and available beam metadata.
269
+ Missing beam lengths select the estimator's pixel-based defaults.
270
+ The AstroData object, its arrays, and the input FITS file are unchanged.
271
+
272
+ Return (rmax, vmin, vmax), with None velocity limits for an image.
273
+ Scalar results are Python floats, except np.longdouble results retain
274
+ extended precision. The selection rules and fallback are those of
275
+ _estimate_ranges. Errors from noise fitting, PB weighting, and range
276
+ estimation propagate from the underlying helpers.
277
+ """
278
+ if not isinstance(image.data, np.ndarray) or image.data.ndim not in (2, 3):
279
+ raise ValueError('Expected a loaded 2D image or 3D cube.')
280
+ if image.data.ndim == 2:
281
+ noise_data = image.data
282
+ pixels = np.count_nonzero(np.isfinite(noise_data))
283
+ else:
284
+ noise_data = image.data[[0, -1]]
285
+ pixels = np.mean(np.count_nonzero(np.isfinite(noise_data), axis=(1, 2)))
286
+ noise = Noise(data=noise_data, sigma='hist-pbcor')
287
+ noise.gen_histogram()
288
+ noise.fit_histogram()
289
+ r_out = np.sqrt(pixels * abs(image.dx * image.dy) / np.pi)
290
+ del noise_data
291
+ weighted = _multiply_pb(image.data, image.x, image.y,
292
+ R=noise.popt[2], r_out=r_out)
293
+ weighted -= noise.mean
294
+ beam = image.beam if None not in image.beam[:2] else None
295
+ return _estimate_ranges(weighted, image.x, image.y, noise.std,
296
+ v=image.v if image.data.ndim == 3 else None,
297
+ beam=beam)
298
+
299
+
300
+ def _validate_fits_image(fitsimage: str | Path, *, ndim: int = 2) -> None:
301
+ """Validate the header of a primary-HDU RA/Dec image or spectral cube.
302
+
303
+ Internal callers use ndim=2 for an image or ndim=3 for a cube.
304
+ Higher axes must be singleton. Read only the header and return None.
305
+ Raise ValueError for unsuitable axes or nonpositive/nonfinite spatial
306
+ pixel scales. No data pixels are loaded or modified.
307
+ """
308
+ with fits.open(fitsimage, memmap=True) as hdus:
309
+ h = hdus[0].header
310
+ n = int(h.get('NAXIS', 0))
311
+ if (n < ndim or h.get('NAXIS1', 0) < 2 or h.get('NAXIS2', 0) < 2
312
+ or any(h[f'NAXIS{i}'] != 1 for i in range(ndim + 1, n + 1))
313
+ or not str(h.get('CTYPE1', '')).upper().startswith('RA')
314
+ or not str(h.get('CTYPE2', '')).upper().startswith('DEC')):
315
+ raise ValueError(f'Expected a {ndim}D RA/Dec image'
316
+ + ' in the primary FITS HDU.')
317
+ if ndim == 3 and (
318
+ h.get('NAXIS3', 0) < 2
319
+ or not str(h.get('CTYPE3', '')).upper().startswith(
320
+ ('FREQ', 'VRAD', 'VELO', 'VOPT', 'FELO'))
321
+ or str(h.get('CUNIT3', '')).strip().upper() not in
322
+ ('HZ', 'M/S', 'KM/S')):
323
+ raise ValueError('Expected at least two frequency'
324
+ + ' or velocity channels on the third FITS axis,'
325
+ + ' in Hz, m/s, or km/s.')
326
+ scales = proj_plane_pixel_scales(WCS(h, naxis=2, fix=False).celestial)
327
+ if not np.all(np.isfinite(scales)) or np.any(scales <= 0):
328
+ raise ValueError('Expected finite positive spatial pixel scales.')
329
+
330
+
331
+ def _get_valid_radius(image: AstroData, rmax: RealScalar
332
+ ) -> float | np.longdouble:
333
+ """Reduce a half-width to exclude nonfinite pixels, with a pixel margin.
334
+
335
+ image must contain one 2D image or 3D cube already read by AstroFrame,
336
+ with spatial coordinates and pixel spacings. rmax uses those same
337
+ spatial units. For cubes, a
338
+ spatial pixel is invalid if any channel is nonfinite. Return the
339
+ half-width as a Python float, preserving np.longdouble results as an
340
+ extended-precision exception; emission-size selection is left to the caller.
341
+ Raise ValueError if no sufficiently large centered finite region remains.
342
+ """
343
+ if image.data.ndim == 2:
344
+ valid = np.isfinite(image.data)
345
+ else:
346
+ valid = np.ones(image.data.shape[-2:], dtype=bool)
347
+ for channel in image.data:
348
+ valid &= np.isfinite(channel)
349
+ invalid_y, invalid_x = np.nonzero(~valid)
350
+ if invalid_x.size:
351
+ nearest_invalid = np.min(np.maximum(np.abs(image.x[invalid_x]),
352
+ np.abs(image.y[invalid_y])))
353
+ margin = max(abs(image.dx), abs(image.dy))
354
+ rmax = min(rmax, nearest_invalid - margin)
355
+ if not np.isfinite(rmax) or rmax <= margin:
356
+ raise ValueError('No centered finite spatial region large enough.')
357
+ return _normalize_float(rmax, force_float=True)
358
+
359
+
360
+ def _write_script(source: str, output: Path, *, overwrite: bool = False
361
+ ) -> None:
362
+ """Check Python syntax and write source, creating parent directories.
363
+
364
+ Compilation does not execute the source. Existing scripts raise
365
+ FileExistsError unless overwrite is True. SyntaxError is raised before
366
+ directories or files are created when source is invalid. Other I/O
367
+ errors propagate. output is a Path; return None.
368
+ """
369
+ compile(source, str(output), 'exec')
370
+ output.parent.mkdir(parents=True, exist_ok=True)
371
+ with output.open('w' if overwrite else 'x') as stream:
372
+ stream.write(source)
373
+
374
+
375
+ def generate_image_script(fitsimage: str | Path,
376
+ output: str | Path | None = None,
377
+ *, overwrite: bool = False) -> Path:
378
+ """Write an editable noise, Gaussian-fit, and 2D image plotting script.
379
+
380
+ Generation reads the primary FITS image, fits its noise histogram, and
381
+ estimates an emission-based fitting region. It does not execute the
382
+ generated script or modify the input FITS file.
383
+ The generated script uses the existing AstroData, AstroFrame, Noise,
384
+ and PlotAstroData APIs directly, following example.py.
385
+
386
+ Args:
387
+ fitsimage (str | Path): A primary-HDU RA/Dec image with at least
388
+ two pixels on each spatial axis. Any higher axes must be singleton.
389
+ output (str | Path | None): Script path with a .py suffix. Defaults
390
+ to <input stem>_image.py in the current working directory.
391
+ Relative paths are resolved at generation time.
392
+ overwrite (bool): Allow replacing an existing script. Defaults to
393
+ False. This option does not control figure overwriting.
394
+
395
+ Returns:
396
+ Path: Absolute path of the written script.
397
+
398
+ Raises:
399
+ TypeError: overwrite is not a Python bool.
400
+ ValueError: The output path, image axes, spatial pixel scales, or
401
+ centered finite fitting region are unsuitable.
402
+ FileExistsError: The script exists and overwrite is False.
403
+ OSError: The input cannot be read or the script cannot be written.
404
+
405
+ Notes:
406
+ Generation estimates rmax and writes it directly into the fitting
407
+ and plotting frames, rounded to three significant digits as a
408
+ Python float literal with an inline comment. Edit it in the script
409
+ to change either field; no runtime range-selection helper is added.
410
+
411
+ The generated script reads the full image with sigma=None, fits
412
+ a hist-pbcor noise model, and saves <script stem>_noise.png. It then
413
+ reads a separate cropped image with the fitted noise level and calls
414
+ gaussfit2d(progressbar=True). It prints the sky center and east/north
415
+ position uncertainties in arcsec, then centers the 2D image on the
416
+ fitted sky position and saves <script stem>.png.
417
+ Both PNGs are beside the script and follow the existing plotting
418
+ methods' overwrite behavior. Noise statistics print with .3e format.
419
+ Changing the generated noise fit does not recompute the inline range.
420
+ Plotting uses stretch='log', show=False, and the default fonts,
421
+ beam, and contour levels. Edit these choices directly in the script.
422
+ """
423
+ if not isinstance(overwrite, bool):
424
+ raise TypeError('overwrite must be a boolean.')
425
+ fitsimage = Path(fitsimage).resolve()
426
+ output = Path(output or f'{fitsimage.stem}_image.py').resolve()
427
+ if output.suffix != '.py':
428
+ raise ValueError('output must have a .py suffix.')
429
+ _validate_fits_image(fitsimage)
430
+ image = AstroData(fitsimage=str(fitsimage), sigma=None)
431
+ AstroFrame().read(image)
432
+ rmax, _, _ = _estimate_pb_ranges(image)
433
+ rmax = float(f'{rmax:.3g}')
434
+ source = f'''
435
+ from plotastrodata.analysis_utils import AstroData, AstroFrame
436
+ from plotastrodata.noise_utils import Noise
437
+ from plotastrodata.plot_utils import PlotAstroData
438
+
439
+
440
+ # Read the image
441
+ d = AstroData(fitsimage={str(fitsimage)!r}, sigma=None) # Estimate noise below.
442
+ f = AstroFrame()
443
+ f.read(d)
444
+
445
+ # Noise visualization
446
+ n = Noise(data=d.data, sigma='hist-pbcor')
447
+ n.gen_histogram()
448
+ n.fit_histogram()
449
+ print(f'Noise (mean, std): {{n.mean:.3e}}, {{n.std:.3e}}')
450
+ n.plot_histogram(savefig={str(output.with_name(output.stem + '_noise.png'))!r}, show=False)
451
+
452
+ d.sigma = n.std # A float number in the data unit is acceptable.
453
+
454
+ # 2D Gaussian fitting
455
+ d_fit = AstroData(fitsimage={str(fitsimage)!r}, sigma=d.sigma)
456
+ f_fit = AstroFrame(rmax={rmax!r}) # Estimated from PB-weighted emission (arcsec); adjust the fit region here.
457
+ f_fit.read(d_fit)
458
+ fit = d_fit.gaussfit2d(progressbar=True)
459
+ print('Gaussian center:', fit['center'])
460
+ print('Center uncertainties (east, north; arcsec):', fit['perr'][1:3])
461
+
462
+ # 2D image
463
+ p = PlotAstroData(rmax={rmax!r}, center=fit['center']) # Estimated from PB-weighted emission (arcsec); adjust as needed.
464
+ p.add_color(**d.todict(), stretch='log')
465
+ p.add_contour(**d.todict(), colors='r')
466
+ p.set_axis_radec(nticksminor=5)
467
+ p.savefig({str(output.with_suffix('.png'))!r}, show=False)
468
+ '''
469
+ _write_script(source, output, overwrite=overwrite)
470
+ return output
471
+
472
+
473
+ def generate_cube_script(fitsimage: str | Path,
474
+ output: str | Path | None = None,
475
+ *, overwrite: bool = False) -> Path:
476
+ """Write noise, integrated line-profile, and 3D channel-map plotting code.
477
+
478
+ Use the existing AstroData, AstroFrame, Noise, plotprofile, and
479
+ PlotAstroData APIs, following the line-profile and 3D channel-map
480
+ sections of example.py. Generation reads the FITS header and cube
481
+ pixels, fits edge-channel noise, and estimates emission ranges. It does
482
+ not execute the generated script or modify the input FITS file.
483
+
484
+ Args:
485
+ fitsimage (str | Path): Primary-HDU RA/Dec spectral cube with at least
486
+ two pixels on each spatial axis and two frequency or velocity
487
+ channels on axis 3, in Hz, m/s, or km/s. Higher axes must be
488
+ singleton. Running the generated flux profile assumes Jy/beam
489
+ intensities and requires a complete beam and spatial pixel sizes.
490
+ output (str | Path | None): Script path with a .py suffix. Defaults
491
+ to <input stem>_cube.py in the current working directory.
492
+ Relative input and output paths are resolved at generation time.
493
+ overwrite (bool): Permit replacing an existing script. Defaults to
494
+ False. This does not control figure overwriting.
495
+
496
+ Returns:
497
+ Path: Absolute path of the written script.
498
+
499
+ Raises:
500
+ TypeError: overwrite is not a Python bool.
501
+ ValueError: The output suffix, cube axes, spatial pixel scales, or
502
+ centered finite spatial region are unsuitable.
503
+ FileExistsError: The script exists and overwrite is False.
504
+ OSError: The input cannot be read or the script cannot be written.
505
+
506
+ Notes:
507
+ The script reads the full cube with sigma=None. Noise uses
508
+ edge,hist-pbcor (first and last spectral channels); the fitted
509
+ standard deviation is reused for colors and contours. Statistics
510
+ print with .3e format and the histogram is saved as
511
+ <script stem>_noise.png beside the script.
512
+
513
+ A separate AstroData instance reuses the loaded cube and is read
514
+ through AstroFrame to crop it to the estimated spatial and velocity
515
+ ranges, written directly in the script with inline comments.
516
+ plotprofile integrates flux over that crop with a circle whose
517
+ diameter is four times rmax, enclosing the entire square. Flux
518
+ integration assumes Jy/beam intensities and requires beam metadata
519
+ and spatial pixel sizes. The single-panel profile is saved as
520
+ <script stem>_profile.png at intrinsic channel spacing.
521
+
522
+ Generation estimates rmax, vmin, and vmax and writes them into
523
+ both frames as Python float literals rounded to three significant
524
+ digits, with inline comments. Edit them in the generated script
525
+ to change the profile or channel-map region. Changing its noise
526
+ fit does not recompute these values.
527
+
528
+ Both profile and channel maps use the selected ranges at intrinsic
529
+ channel spacing, without skipping or binning. They plot original
530
+ PB-corrected data about the FITS reference center. The generated
531
+ noise visualization still uses the full spatial footprint.
532
+
533
+ The script sets stretch='log' and show=False, with default fonts,
534
+ beams, contours, and channel layout. Edit these choices directly.
535
+ Channel-map pages are saved beside the script as <script stem>.png;
536
+ multiple pages receive _0, _1, ... suffixes before .png, following
537
+ PlotAstroData.savefig. Existing figures may be overwritten.
538
+ """
539
+ if not isinstance(overwrite, bool):
540
+ raise TypeError('overwrite must be a boolean.')
541
+ fitsimage = Path(fitsimage).resolve()
542
+ output = Path(output or f'{fitsimage.stem}_cube.py').resolve()
543
+ if output.suffix != '.py':
544
+ raise ValueError('output must have a .py suffix.')
545
+ _validate_fits_image(fitsimage, ndim=3)
546
+ cube = AstroData(fitsimage=str(fitsimage), sigma=None)
547
+ AstroFrame().read(cube)
548
+ rmax, vmin, vmax = _estimate_pb_ranges(cube)
549
+ rmax = float(f'{rmax:.3g}')
550
+ vmin, vmax = float(f'{vmin:.3g}'), float(f'{vmax:.3g}')
551
+ source = f"""
552
+ from plotastrodata.analysis_utils import AstroData, AstroFrame
553
+ from plotastrodata.noise_utils import Noise
554
+ from plotastrodata.plot_utils import PlotAstroData, plotprofile
555
+
556
+
557
+ # Read the cube
558
+ d = AstroData(fitsimage={str(fitsimage)!r}, sigma=None) # Estimate noise below.
559
+ f = AstroFrame()
560
+ f.read(d)
561
+
562
+ # Noise visualization
563
+ n = Noise(data=d.data, sigma='edge,hist-pbcor') # First and last channels; adjust if they contain emission.
564
+ n.gen_histogram()
565
+ n.fit_histogram()
566
+ print(f'Noise (mean, std): {{n.mean:.3e}}, {{n.std:.3e}}')
567
+ n.plot_histogram(savefig={str(output.with_name(output.stem + '_noise.png'))!r}, show=False)
568
+
569
+ d.sigma = n.std # A float number in the data unit is acceptable.
570
+
571
+ # Line profile
572
+ d_profile = AstroData(**d.todict())
573
+ f_profile = AstroFrame(rmax={rmax!r}, # Estimated spatial half-width (arcsec); adjust as needed.
574
+ vmin={vmin!r}, vmax={vmax!r}, # Estimated velocity range (km/s); adjust as needed.
575
+ )
576
+ f_profile.read(d_profile)
577
+ plotprofile(**d_profile.todict(), xlist=[0], ylist=[0],
578
+ ellipse=[4 * f_profile.rmax, 4 * f_profile.rmax, 0], # Circle enclosing the cropped square.
579
+ flux=True,
580
+ savefig={str(output.with_name(output.stem + '_profile.png'))!r},
581
+ show=False,
582
+ )
583
+
584
+ # 3D channel maps
585
+ p = PlotAstroData(v=d.v, center=d.center,
586
+ rmax={rmax!r}, # Estimated spatial half-width (arcsec); adjust as needed.
587
+ vmin={vmin!r}, vmax={vmax!r}, # Estimated velocity range (km/s); adjust as needed.
588
+ )
589
+ p.add_color(**d.todict(), stretch='log')
590
+ p.add_contour(**d.todict(), colors='r')
591
+ p.set_axis()
592
+ p.savefig({str(output.with_suffix('.png'))!r}, show=False)
593
+ """
594
+ _write_script(source, output, overwrite=overwrite)
595
+ return output
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: plotastrodata
3
- Version: 1.11.2
3
+ Version: 1.12.1
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
@@ -45,6 +45,8 @@ The PDF manual is available [here](https://github.com/yusukeaso-astron/plotastro
45
45
 
46
46
  ## Installation
47
47
 
48
+ ### Released version
49
+
48
50
  Install from conda-forge:
49
51
 
50
52
  ```bash
@@ -57,19 +59,22 @@ or from PyPI:
57
59
  pip install plotastrodata
58
60
  ```
59
61
 
60
- To install the latest source from GitHub:
62
+ ### Development version from GitHub
63
+
64
+ Clone the repository to install the latest development version, which may
65
+ include changes not yet available in the published releases:
61
66
 
62
67
  ```bash
63
68
  git clone https://github.com/yusukeaso-astron/plotastrodata
64
- cd plotastrodata
65
- python -m pip install .
69
+ (cd plotastrodata)
70
+ (python -m pip install .)
66
71
  ```
67
72
 
68
- To update a source installation, run the following commands in the cloned repository:
73
+ To update the development version, run the following commands in the cloned repository:
69
74
 
70
75
  ```bash
71
76
  git pull
72
- python -m pip install --upgrade .
77
+ (python -m pip install --upgrade .)
73
78
  ```
74
79
 
75
80
  ## Demo and Usage
@@ -82,6 +87,30 @@ python example.py
82
87
 
83
88
  More examples and the complete API reference are available in the [online documentation](https://plotastrodata.readthedocs.io/en/latest/).
84
89
 
90
+ ## Generate plotting scripts
91
+
92
+ ```python
93
+ from plotastrodata.script_utils import generate_image_script
94
+
95
+ script = generate_image_script(
96
+ "image.fits", output="image.py",
97
+ )
98
+ ```
99
+
100
+ Review the inline values, then run `python image.py`. The script uses existing
101
+ library APIs to visualize a hist-pbcor noise fit, fit a 2D Gaussian and report
102
+ its sky center and east/north uncertainties, and plot a logarithmic image
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 ranges are estimated automatically and written inline
105
+ with three significant digits for editing.
106
+ For a spectral cube, use `generate_cube_script("cube.fits", output="cube.py")`
107
+ from the same module. It generates an edge-channel noise visualization, a flux-integrated line
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
+ Both generators return an absolute pathlib.Path and write the script
111
+ without executing it.
112
+ See the [script-generation guide](docs/script_generation.rst).
113
+
85
114
  ## Requirement
86
115
 
87
116
  * Python >= 3.11
@@ -0,0 +1,21 @@
1
+ plotastrodata/__init__.py,sha256=_tYrE-ZW2jWY3-eX-LlXDzrpDijfWleiZx8y7wV2YEQ,87
2
+ plotastrodata/_type_utils.py,sha256=0026EApTPLxkZ9NcB5QSQ-bWq2RFcq5T00wiA9iAF_8,4193
3
+ plotastrodata/_validation_utils.py,sha256=FOIOgzrP1vwuDfjqCMvYcp4yMdRjQUMtZWE-BnUXBgA,2924
4
+ plotastrodata/analysis_utils.py,sha256=dkuRu93huyah4Ck1Im8kWj7sU9twfdLILi9jUaZRIsg,64333
5
+ plotastrodata/const_utils.py,sha256=8TCxHkV6P62XDGLK-t50O7P8ME10cjCS9S2DmPgi4hI,4789
6
+ plotastrodata/coord_utils.py,sha256=0jOhLIBlUZKpHbF7o6Tvroq-ezoTLADHeR1j4v1xvGQ,9854
7
+ plotastrodata/ext_utils.py,sha256=mi84yKu-T0lXkIk-9Fme0h5CwBu-_n3cCubLIia7tbo,5715
8
+ plotastrodata/fft_utils.py,sha256=5Ark824VKVRdVlftf5i5Sg1KBpXFiC_vQQxksLLOEHs,23177
9
+ plotastrodata/fits_utils.py,sha256=-q0CRxUBCbTvCQoQNe9m1k2NIOcjx924FMDy3ayDnNg,23264
10
+ plotastrodata/fitting_utils.py,sha256=oP-fAXIeQR3hjal0tvftTKwWxn7MJHqS4Fl7BehnJEk,38950
11
+ plotastrodata/los_utils.py,sha256=Q239z__C-kvzb0NR6NyGB-21quBl6KLhE2GdRMhMwn4,8112
12
+ plotastrodata/matrix_utils.py,sha256=H6Ad9Sn8itsi0FU2D70Sb_SSJ4xmprYGueYYrIqotOY,2462
13
+ plotastrodata/noise_utils.py,sha256=SPpHzPop0tzUExtP4SnQHzBCbJ6TG779R8ZmqrI5ib8,16439
14
+ plotastrodata/other_utils.py,sha256=ouiizsR9-ygeaGMs7U5dy2UUEE5SRzrNKu65-EpqjRA,12124
15
+ plotastrodata/plot_utils.py,sha256=Qmb03AqL7xPa9C1vVRlOSXeVzMlxTuOxmWxAAlQjPkE,128445
16
+ plotastrodata/script_utils.py,sha256=4Oa0LvhTjRF98evtbBrj1rb-eyHtQ5NJYTFSx3oXfQ4,28500
17
+ plotastrodata-1.12.1.dist-info/licenses/LICENSE,sha256=OXLcl0T2SZ8Pmy2_dmlvKuetivmyPd5m1q-Gyd-zaYY,35149
18
+ plotastrodata-1.12.1.dist-info/METADATA,sha256=8b9qS8Qv88vKemG2ibbAEBoFiUEY1L65R8IkLNd3ki8,5214
19
+ plotastrodata-1.12.1.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
20
+ plotastrodata-1.12.1.dist-info/top_level.txt,sha256=mv2FRRtreGAUE_UF_Z_TYj_NZLECJqkQx7ErkA_Rttg,14
21
+ plotastrodata-1.12.1.dist-info/RECORD,,
@@ -1,20 +0,0 @@
1
- plotastrodata/__init__.py,sha256=xEIkQG82q-U5HhA5XUbjCu-LfnR00eCJVOJ6809sywc,87
2
- plotastrodata/_type_utils.py,sha256=OBFWmDnrIMWKvnpbAjrNqFFqE8RChl0nNUweXB-w1ek,4193
3
- plotastrodata/_validation_utils.py,sha256=FOIOgzrP1vwuDfjqCMvYcp4yMdRjQUMtZWE-BnUXBgA,2924
4
- plotastrodata/analysis_utils.py,sha256=pkueWH08ZKSZuD1-8agjb1XihHUQJXCbY7y8VFOrbts,64516
5
- plotastrodata/const_utils.py,sha256=1rg59_VZrraVCqz974ac8i-utGuzSEY-1KNMDDUUUtI,4809
6
- plotastrodata/coord_utils.py,sha256=QN2LQJSZfjTwbO1d7pEf14n6KPkK7OXiqw0UgPmsMCM,9854
7
- plotastrodata/ext_utils.py,sha256=jiHy50cwEO045k3IM9nPdVm44g28y-t_AbXm8AIPWYM,5714
8
- plotastrodata/fft_utils.py,sha256=nLZR6mjmxh1uAdWiuyuVi6KmQSaPwuV02BqqiK68phw,23177
9
- plotastrodata/fits_utils.py,sha256=pqJLxocR3wVSZcOEqdmjXzImUxf6R2wZ3j-LV99Q2gE,23297
10
- plotastrodata/fitting_utils.py,sha256=2swKVkakri7uVqtrlc95RfhYO9cNWHV5M3qr7U-gqXI,36842
11
- plotastrodata/los_utils.py,sha256=CEjOu1Yc-1rdiNfzOuq1a0wa2MusHDCEMD_EYzOmpXk,8112
12
- plotastrodata/matrix_utils.py,sha256=W03es1Gw4LeIqlCMnzvAxsAa99zAShlGxzbbMe6_P3E,2454
13
- plotastrodata/noise_utils.py,sha256=jIIEIJDU4hT2N7mGvgRDx7y-C4c_SstOW7ldF--Y1M4,16338
14
- plotastrodata/other_utils.py,sha256=M4l0YXI_OVCuBa9owGEtbEw1hudsD7-2_8NHEWrebG4,12123
15
- plotastrodata/plot_utils.py,sha256=21b3oosgT12ATaDTfcB933skxDestA2q2d5KvSr7QWs,128778
16
- plotastrodata-1.11.2.dist-info/licenses/LICENSE,sha256=OXLcl0T2SZ8Pmy2_dmlvKuetivmyPd5m1q-Gyd-zaYY,35149
17
- plotastrodata-1.11.2.dist-info/METADATA,sha256=KKvnSTk1TXsWv5l1b75pwkc-1LPCgLVqYuFCQMdMwQU,3917
18
- plotastrodata-1.11.2.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
19
- plotastrodata-1.11.2.dist-info/top_level.txt,sha256=mv2FRRtreGAUE_UF_Z_TYj_NZLECJqkQx7ErkA_Rttg,14
20
- plotastrodata-1.11.2.dist-info/RECORD,,