plotastrodata 1.11.2__tar.gz → 1.12.0__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.11.2/plotastrodata.egg-info → plotastrodata-1.12.0}/PKG-INFO +36 -6
  2. {plotastrodata-1.11.2 → plotastrodata-1.12.0}/README.md +35 -5
  3. {plotastrodata-1.11.2 → plotastrodata-1.12.0}/plotastrodata/__init__.py +1 -1
  4. {plotastrodata-1.11.2 → plotastrodata-1.12.0}/plotastrodata/analysis_utils.py +41 -31
  5. {plotastrodata-1.11.2 → plotastrodata-1.12.0}/plotastrodata/const_utils.py +1 -3
  6. {plotastrodata-1.11.2 → plotastrodata-1.12.0}/plotastrodata/coord_utils.py +1 -1
  7. {plotastrodata-1.11.2 → plotastrodata-1.12.0}/plotastrodata/ext_utils.py +2 -1
  8. {plotastrodata-1.11.2 → plotastrodata-1.12.0}/plotastrodata/fits_utils.py +8 -5
  9. {plotastrodata-1.11.2 → plotastrodata-1.12.0}/plotastrodata/fitting_utils.py +76 -38
  10. {plotastrodata-1.11.2 → plotastrodata-1.12.0}/plotastrodata/matrix_utils.py +2 -2
  11. {plotastrodata-1.11.2 → plotastrodata-1.12.0}/plotastrodata/noise_utils.py +9 -6
  12. {plotastrodata-1.11.2 → plotastrodata-1.12.0}/plotastrodata/other_utils.py +4 -3
  13. {plotastrodata-1.11.2 → plotastrodata-1.12.0}/plotastrodata/plot_utils.py +30 -22
  14. plotastrodata-1.12.0/plotastrodata/script_utils.py +302 -0
  15. {plotastrodata-1.11.2 → plotastrodata-1.12.0/plotastrodata.egg-info}/PKG-INFO +36 -6
  16. {plotastrodata-1.11.2 → plotastrodata-1.12.0}/plotastrodata.egg-info/SOURCES.txt +1 -0
  17. {plotastrodata-1.11.2 → plotastrodata-1.12.0}/LICENSE +0 -0
  18. {plotastrodata-1.11.2 → plotastrodata-1.12.0}/MANIFEST.in +0 -0
  19. {plotastrodata-1.11.2 → plotastrodata-1.12.0}/plotastrodata/_type_utils.py +2 -2
  20. {plotastrodata-1.11.2 → plotastrodata-1.12.0}/plotastrodata/_validation_utils.py +0 -0
  21. {plotastrodata-1.11.2 → plotastrodata-1.12.0}/plotastrodata/fft_utils.py +4 -4
  22. {plotastrodata-1.11.2 → plotastrodata-1.12.0}/plotastrodata/los_utils.py +1 -1
  23. {plotastrodata-1.11.2 → plotastrodata-1.12.0}/plotastrodata.egg-info/dependency_links.txt +0 -0
  24. {plotastrodata-1.11.2 → plotastrodata-1.12.0}/plotastrodata.egg-info/not-zip-safe +0 -0
  25. {plotastrodata-1.11.2 → plotastrodata-1.12.0}/plotastrodata.egg-info/requires.txt +0 -0
  26. {plotastrodata-1.11.2 → plotastrodata-1.12.0}/plotastrodata.egg-info/top_level.txt +0 -0
  27. {plotastrodata-1.11.2 → plotastrodata-1.12.0}/setup.cfg +0 -0
  28. {plotastrodata-1.11.2 → plotastrodata-1.12.0}/setup.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: plotastrodata
3
- Version: 1.11.2
3
+ Version: 1.12.0
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,31 @@ 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 use a centered
105
+ field whose width is one quarter of the estimated valid image width.
106
+ The estimated rmax is written inline for editing.
107
+ For a spectral cube, use `generate_cube_script("cube.fits", output="cube.py")`
108
+ from the same module. It generates an edge-channel noise visualization, a flux-integrated line
109
+ profile over the spatial quarter-size, and 3D channel maps at the intrinsic
110
+ channel spacing. The flux profile assumes Jy/beam data with beam metadata.
111
+ Both generators return an absolute pathlib.Path and write the script
112
+ without executing it.
113
+ See the [script-generation guide](docs/script_generation.rst).
114
+
85
115
  ## Requirement
86
116
 
87
117
  * Python >= 3.11
@@ -16,6 +16,8 @@ The PDF manual is available [here](https://github.com/yusukeaso-astron/plotastro
16
16
 
17
17
  ## Installation
18
18
 
19
+ ### Released version
20
+
19
21
  Install from conda-forge:
20
22
 
21
23
  ```bash
@@ -28,19 +30,22 @@ or from PyPI:
28
30
  pip install plotastrodata
29
31
  ```
30
32
 
31
- To install the latest source from GitHub:
33
+ ### Development version from GitHub
34
+
35
+ Clone the repository to install the latest development version, which may
36
+ include changes not yet available in the published releases:
32
37
 
33
38
  ```bash
34
39
  git clone https://github.com/yusukeaso-astron/plotastrodata
35
- cd plotastrodata
36
- python -m pip install .
40
+ (cd plotastrodata)
41
+ (python -m pip install .)
37
42
  ```
38
43
 
39
- To update a source installation, run the following commands in the cloned repository:
44
+ To update the development version, run the following commands in the cloned repository:
40
45
 
41
46
  ```bash
42
47
  git pull
43
- python -m pip install --upgrade .
48
+ (python -m pip install --upgrade .)
44
49
  ```
45
50
 
46
51
  ## Demo and Usage
@@ -53,6 +58,31 @@ python example.py
53
58
 
54
59
  More examples and the complete API reference are available in the [online documentation](https://plotastrodata.readthedocs.io/en/latest/).
55
60
 
61
+ ## Generate plotting scripts
62
+
63
+ ```python
64
+ from plotastrodata.script_utils import generate_image_script
65
+
66
+ script = generate_image_script(
67
+ "image.fits", output="image.py",
68
+ )
69
+ ```
70
+
71
+ Review the inline values, then run `python image.py`. The script uses existing
72
+ library APIs to visualize a hist-pbcor noise fit, fit a 2D Gaussian and report
73
+ its sky center and east/north uncertainties, and plot a logarithmic image
74
+ with contours, a beam, and RA/Dec axes. It saves separate noise and image PNGs.
75
+ Noise estimation uses the full image. Fitting and plotting use a centered
76
+ field whose width is one quarter of the estimated valid image width.
77
+ The estimated rmax is written inline for editing.
78
+ For a spectral cube, use `generate_cube_script("cube.fits", output="cube.py")`
79
+ from the same module. It generates an edge-channel noise visualization, a flux-integrated line
80
+ profile over the spatial quarter-size, and 3D channel maps at the intrinsic
81
+ channel spacing. The flux profile assumes Jy/beam data with beam metadata.
82
+ Both generators return an absolute pathlib.Path and write the script
83
+ without executing it.
84
+ See the [script-generation guide](docs/script_generation.rst).
85
+
56
86
  ## Requirement
57
87
 
58
88
  * Python >= 3.11
@@ -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.0'
@@ -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,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)
@@ -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
 
@@ -159,7 +162,7 @@ def select_noise(data: np.ndarray, sigma: str) -> np.ndarray:
159
162
  Returns:
160
163
  np.ndarray: 1D array that includes only the selected pixels.
161
164
  """
162
- n = np.array(data).copy()
165
+ n = np.array(data, copy=True)
163
166
  if 'edge' in sigma:
164
167
  if np.ndim(n) <= 2:
165
168
  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,302 @@
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
+
9
+ from plotastrodata.analysis_utils import AstroData, AstroFrame
10
+
11
+
12
+ def _get_image_radius(fitsimage: str | Path, *, ndim: int = 2) -> float:
13
+ """Validate a primary-HDU RA/Dec image or cube and return its half-width.
14
+
15
+ Read only the header. The result is half the larger image dimension
16
+ in arcsec, using projected WCS pixel scales, as a Python float.
17
+ Internal callers use ndim=2 for an image or ndim=3 for a spectral
18
+ cube. Higher axes must be singleton. Raise ValueError for unsuitable axes or spatial pixel scales.
19
+ """
20
+ with fits.open(fitsimage, memmap=True) as hdus:
21
+ h = hdus[0].header
22
+ n = int(h.get('NAXIS', 0))
23
+ if (n < ndim or h.get('NAXIS1', 0) < 2 or h.get('NAXIS2', 0) < 2
24
+ or any(h[f'NAXIS{i}'] != 1 for i in range(ndim + 1, n + 1))
25
+ or not str(h.get('CTYPE1', '')).upper().startswith('RA')
26
+ or not str(h.get('CTYPE2', '')).upper().startswith('DEC')):
27
+ raise ValueError(f'Expected a {ndim}D RA/Dec image'
28
+ + ' in the primary FITS HDU.')
29
+ if ndim == 3 and (
30
+ h.get('NAXIS3', 0) < 2
31
+ or not str(h.get('CTYPE3', '')).upper().startswith(
32
+ ('FREQ', 'VRAD', 'VELO', 'VOPT', 'FELO'))
33
+ or str(h.get('CUNIT3', '')).strip().upper() not in
34
+ ('HZ', 'M/S', 'KM/S')):
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.')
38
+ scales = proj_plane_pixel_scales(WCS(h, naxis=2, fix=False).celestial)
39
+ rmax = max(h['NAXIS1'] * scales[0], h['NAXIS2'] * scales[1]) * 3600 / 2
40
+ if not np.isfinite(rmax) or rmax <= 0:
41
+ raise ValueError('Expected finite positive spatial pixel scales.')
42
+ return float(rmax)
43
+
44
+
45
+ def _get_valid_radius(image: AstroData, rmax: float) -> float:
46
+ """Reduce a half-width to exclude nonfinite pixels, with a pixel margin.
47
+
48
+ image must contain one 2D image or 3D cube already read by AstroFrame,
49
+ with spatial coordinates and pixel spacings. rmax uses those same
50
+ spatial units. For cubes, a
51
+ spatial pixel is invalid if any channel is nonfinite. Return the
52
+ half-width as a Python float; quarter-size scaling is left to the caller.
53
+ Raise ValueError if no sufficiently large centered finite region remains.
54
+ """
55
+ if image.data.ndim == 2:
56
+ valid = np.isfinite(image.data)
57
+ else:
58
+ valid = np.ones(image.data.shape[-2:], dtype=bool)
59
+ for channel in image.data:
60
+ valid &= np.isfinite(channel)
61
+ invalid_y, invalid_x = np.nonzero(~valid)
62
+ if invalid_x.size:
63
+ nearest_invalid = np.min(np.maximum(np.abs(image.x[invalid_x]),
64
+ np.abs(image.y[invalid_y])))
65
+ margin = max(abs(image.dx), abs(image.dy))
66
+ rmax = min(rmax, nearest_invalid - margin)
67
+ if not np.isfinite(rmax) or rmax <= margin:
68
+ raise ValueError('No centered finite spatial region large enough.')
69
+ return float(rmax)
70
+
71
+
72
+ def _write_script(source: str, output: Path, *, overwrite: bool = False
73
+ ) -> None:
74
+ """Check Python syntax and write source, creating parent directories.
75
+
76
+ Compilation does not execute the source. Existing scripts raise
77
+ FileExistsError unless overwrite is True. SyntaxError is raised before
78
+ directories or files are created when source is invalid. Other I/O
79
+ errors propagate. output is a Path; return None.
80
+ """
81
+ compile(source, str(output), 'exec')
82
+ output.parent.mkdir(parents=True, exist_ok=True)
83
+ with output.open('w' if overwrite else 'x') as stream:
84
+ stream.write(source)
85
+
86
+
87
+ def generate_image_script(fitsimage: str | Path,
88
+ output: str | Path | None = None,
89
+ *, overwrite: bool = False) -> Path:
90
+ """Write an editable noise, Gaussian-fit, and 2D image plotting script.
91
+
92
+ Generation reads the primary FITS image to estimate a finite fitting
93
+ region, but does not execute the script or modify the input file.
94
+ The generated script uses the existing AstroData, AstroFrame, Noise,
95
+ and PlotAstroData APIs directly, following example.py.
96
+
97
+ Args:
98
+ fitsimage (str | Path): A primary-HDU RA/Dec image with at least
99
+ two pixels on each spatial axis. Any higher axes must be singleton.
100
+ output (str | Path | None): Script path with a .py suffix. Defaults
101
+ to <input stem>_image.py in the current working directory.
102
+ Relative paths are resolved at generation time.
103
+ overwrite (bool): Allow replacing an existing script. Defaults to
104
+ False. This option does not control figure overwriting.
105
+
106
+ Returns:
107
+ Path: Absolute path of the written script.
108
+
109
+ Raises:
110
+ TypeError: overwrite is not a Python bool.
111
+ ValueError: The output path, image axes, spatial pixel scales, or
112
+ centered finite fitting region are unsuitable.
113
+ FileExistsError: The script exists and overwrite is False.
114
+ OSError: The input cannot be read or the script cannot be written.
115
+
116
+ Notes:
117
+ The initial half-width is half the larger image dimension in arcsec,
118
+ using projected WCS pixel scales. If nonfinite pixels are present,
119
+ it is reduced to a square around the FITS reference position that
120
+ excludes them, with one spatial pixel of margin. That half-width
121
+ is divided by four and rounded to eight significant digits for the
122
+ inline Python float used by the fitting frame and plotting frame.
123
+ Thus the full field width is one quarter of the initial valid width.
124
+ This is a footprint estimate, not a measurement of source emission.
125
+
126
+ The generated script reads the full image with sigma=None, fits
127
+ a hist-pbcor noise model, and saves <script stem>_noise.png. It then
128
+ reads a separate cropped image with the fitted noise level and calls
129
+ gaussfit2d(progressbar=True). It prints the sky center and east/north
130
+ position uncertainties in arcsec, then centers the 2D image on the
131
+ fitted sky position and saves <script stem>.png.
132
+ Both PNGs are beside the script and follow the existing plotting
133
+ methods' overwrite behavior. Noise statistics print with .3e format.
134
+ Plotting uses stretch='log', show=False, and the default fonts,
135
+ beam, and contour levels. Edit these choices directly in the script.
136
+ """
137
+ if not isinstance(overwrite, bool):
138
+ raise TypeError('overwrite must be a boolean.')
139
+ fitsimage = Path(fitsimage).resolve()
140
+ output = Path(output or f'{fitsimage.stem}_image.py').resolve()
141
+ if output.suffix != '.py':
142
+ raise ValueError('output must have a .py suffix.')
143
+ rmax = _get_image_radius(fitsimage)
144
+ image = AstroData(fitsimage=str(fitsimage), sigma=None)
145
+ AstroFrame().read(image)
146
+ rmax = _get_valid_radius(image, rmax)
147
+ rmax = float(f'{rmax / 4:.8g}')
148
+ source = f'''
149
+ from plotastrodata.analysis_utils import AstroData, AstroFrame
150
+ from plotastrodata.noise_utils import Noise
151
+ from plotastrodata.plot_utils import PlotAstroData
152
+
153
+
154
+ # Read the image
155
+ d = AstroData(fitsimage={str(fitsimage)!r}, sigma=None) # Estimate noise below.
156
+ f = AstroFrame()
157
+ f.read(d)
158
+
159
+ # Noise visualization
160
+ n = Noise(data=d.data, sigma='hist-pbcor')
161
+ n.gen_histogram()
162
+ n.fit_histogram()
163
+ print(f'Noise (mean, std): {{n.mean:.3e}}, {{n.std:.3e}}')
164
+ n.plot_histogram(savefig={str(output.with_name(output.stem + '_noise.png'))!r}, show=False)
165
+
166
+ d.sigma = n.std # A float number in the data unit is acceptable.
167
+
168
+ # 2D Gaussian fitting
169
+ d_fit = AstroData(fitsimage={str(fitsimage)!r}, sigma=d.sigma)
170
+ f_fit = AstroFrame(rmax={rmax!r}) # One quarter of the valid half-width in arcsec; adjust the fit region here.
171
+ f_fit.read(d_fit)
172
+ fit = d_fit.gaussfit2d(progressbar=True)
173
+ print('Gaussian center:', fit['center'])
174
+ print('Center uncertainties (east, north; arcsec):', fit['perr'][1:3])
175
+
176
+ # 2D image
177
+ p = PlotAstroData(rmax={rmax!r}, center=fit['center']) # One quarter of the valid half-width in arcsec; adjust as needed.
178
+ p.add_color(**d.todict(), stretch='log', cblabel=d.bunit)
179
+ p.add_contour(**d.todict(), colors='r')
180
+ p.set_axis_radec(nticksminor=5)
181
+ p.savefig({str(output.with_suffix('.png'))!r}, show=False)
182
+ '''
183
+ _write_script(source, output, overwrite=overwrite)
184
+ return output
185
+
186
+
187
+ def generate_cube_script(fitsimage: str | Path,
188
+ output: str | Path | None = None,
189
+ *, overwrite: bool = False) -> Path:
190
+ """Write noise, integrated line-profile, and 3D channel-map plotting code.
191
+
192
+ Use the existing AstroData, AstroFrame, Noise, plotprofile, and
193
+ PlotAstroData APIs, following the line-profile and 3D channel-map
194
+ sections of example.py. Generation reads
195
+ the FITS header and cube pixels, but does not execute the script.
196
+
197
+ Args:
198
+ fitsimage (str | Path): Primary-HDU RA/Dec spectral cube with at least
199
+ two pixels on each spatial axis and two frequency or velocity
200
+ channels on axis 3, in Hz, m/s, or km/s. Higher axes must be
201
+ singleton. Running the generated flux profile assumes Jy/beam
202
+ intensities and requires a complete beam and spatial pixel sizes.
203
+ output (str | Path | None): Script path with a .py suffix. Defaults
204
+ to <input stem>_cube.py in the current working directory.
205
+ Relative input and output paths are resolved at generation time.
206
+ overwrite (bool): Permit replacing an existing script. Defaults to
207
+ False. This does not control figure overwriting.
208
+
209
+ Returns:
210
+ Path: Absolute path of the written script.
211
+
212
+ Raises:
213
+ TypeError: overwrite is not a Python bool.
214
+ ValueError: The output suffix, cube axes, spatial pixel scales, or
215
+ centered finite spatial region are unsuitable.
216
+ FileExistsError: The script exists and overwrite is False.
217
+ OSError: The input cannot be read or the script cannot be written.
218
+
219
+ Notes:
220
+ The script reads the full cube with sigma=None. Noise uses
221
+ edge,hist-pbcor (first and last spectral channels); the fitted
222
+ standard deviation is reused for colors and contours. Statistics
223
+ print with .3e format and the histogram is saved as
224
+ <script stem>_noise.png beside the script.
225
+
226
+ A separate AstroData instance reuses the loaded cube and is read
227
+ through AstroFrame to crop it to the spatial quarter-size.
228
+ plotprofile integrates flux over that crop with a circle whose
229
+ diameter is four times rmax, enclosing the entire square. Flux
230
+ integration assumes Jy/beam intensities and requires beam metadata
231
+ and spatial pixel sizes. The single-panel profile is saved as
232
+ <script stem>_profile.png at intrinsic channel spacing.
233
+
234
+ Channel maps use the full spectral range at intrinsic channel
235
+ spacing, without skipping or binning. Spatial rmax starts from
236
+ half the larger image dimension in arcsec. A spatial pixel is
237
+ invalid if any channel there is nonfinite. If invalid pixels exist,
238
+ the centered square is reduced to exclude them with one spatial
239
+ pixel of margin. This valid half-width is divided by four and
240
+ rounded to eight significant digits as an inline Python float
241
+ for the profile crop and channel maps. The full field width is one
242
+ quarter of the estimated valid width. This estimates the footprint,
243
+ not the source emission. Both regions use the FITS reference center;
244
+ noise uses the full cube.
245
+
246
+ The script sets stretch='log' and show=False, with default fonts,
247
+ beams, contours, and channel layout. Edit these choices directly.
248
+ Channel-map pages are saved beside the script as <script stem>.png;
249
+ multiple pages receive _0, _1, ... suffixes before .png, following
250
+ PlotAstroData.savefig. Existing figures may be overwritten.
251
+ """
252
+ if not isinstance(overwrite, bool):
253
+ raise TypeError('overwrite must be a boolean.')
254
+ fitsimage = Path(fitsimage).resolve()
255
+ output = Path(output or f'{fitsimage.stem}_cube.py').resolve()
256
+ if output.suffix != '.py':
257
+ raise ValueError('output must have a .py suffix.')
258
+ rmax = _get_image_radius(fitsimage, ndim=3)
259
+ cube = AstroData(fitsimage=str(fitsimage), sigma=None)
260
+ AstroFrame().read(cube)
261
+ rmax = _get_valid_radius(cube, rmax)
262
+ rmax = float(f'{rmax / 4:.8g}')
263
+ source = f"""
264
+ from plotastrodata.analysis_utils import AstroData, AstroFrame
265
+ from plotastrodata.noise_utils import Noise
266
+ from plotastrodata.plot_utils import PlotAstroData, plotprofile
267
+
268
+
269
+ # Read the cube
270
+ d = AstroData(fitsimage={str(fitsimage)!r}, sigma=None) # Estimate noise below.
271
+ f = AstroFrame()
272
+ f.read(d)
273
+
274
+ # Noise visualization
275
+ n = Noise(data=d.data, sigma='edge,hist-pbcor') # First and last channels; adjust if they contain emission.
276
+ n.gen_histogram()
277
+ n.fit_histogram()
278
+ print(f'Noise (mean, std): {{n.mean:.3e}}, {{n.std:.3e}}')
279
+ n.plot_histogram(savefig={str(output.with_name(output.stem + '_noise.png'))!r}, show=False)
280
+
281
+ d.sigma = n.std # A float number in the data unit is acceptable.
282
+
283
+ # Line profile
284
+ d_profile = AstroData(**d.todict())
285
+ f_profile = AstroFrame(rmax={rmax!r}) # One quarter of the valid half-width in arcsec; adjust as needed.
286
+ f_profile.read(d_profile)
287
+ plotprofile(**d_profile.todict(), xlist=[0], ylist=[0],
288
+ ellipse=[4 * f_profile.rmax, 4 * f_profile.rmax, 0], # Circle enclosing the cropped square.
289
+ flux=True,
290
+ savefig={str(output.with_name(output.stem + '_profile.png'))!r},
291
+ show=False,
292
+ )
293
+
294
+ # 3D channel maps
295
+ p = PlotAstroData(v=d.v, rmax={rmax!r}, center=d.center) # One quarter of the valid half-width in arcsec; adjust as needed.
296
+ p.add_color(**d.todict(), stretch='log', cblabel=d.bunit)
297
+ p.add_contour(**d.todict(), colors='r')
298
+ p.set_axis()
299
+ p.savefig({str(output.with_suffix('.png'))!r}, show=False)
300
+ """
301
+ _write_script(source, output, overwrite=overwrite)
302
+ 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.0
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,31 @@ 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 use a centered
105
+ field whose width is one quarter of the estimated valid image width.
106
+ The estimated rmax is written inline for editing.
107
+ For a spectral cube, use `generate_cube_script("cube.fits", output="cube.py")`
108
+ from the same module. It generates an edge-channel noise visualization, a flux-integrated line
109
+ profile over the spatial quarter-size, and 3D channel maps at the intrinsic
110
+ channel spacing. The flux profile assumes Jy/beam data with beam metadata.
111
+ Both generators return an absolute pathlib.Path and write the script
112
+ without executing it.
113
+ See the [script-generation guide](docs/script_generation.rst).
114
+
85
115
  ## Requirement
86
116
 
87
117
  * Python >= 3.11
@@ -18,6 +18,7 @@ plotastrodata/matrix_utils.py
18
18
  plotastrodata/noise_utils.py
19
19
  plotastrodata/other_utils.py
20
20
  plotastrodata/plot_utils.py
21
+ plotastrodata/script_utils.py
21
22
  plotastrodata.egg-info/PKG-INFO
22
23
  plotastrodata.egg-info/SOURCES.txt
23
24
  plotastrodata.egg-info/dependency_links.txt
File without changes
@@ -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,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,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,
File without changes
File without changes