plotastrodata 1.11.2__py3-none-any.whl → 1.12.0__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 +1 -1
- plotastrodata/_type_utils.py +2 -2
- plotastrodata/analysis_utils.py +41 -31
- plotastrodata/const_utils.py +1 -3
- plotastrodata/coord_utils.py +1 -1
- plotastrodata/ext_utils.py +2 -1
- plotastrodata/fft_utils.py +4 -4
- plotastrodata/fits_utils.py +8 -5
- plotastrodata/fitting_utils.py +76 -38
- plotastrodata/los_utils.py +1 -1
- plotastrodata/matrix_utils.py +2 -2
- plotastrodata/noise_utils.py +9 -6
- plotastrodata/other_utils.py +4 -3
- plotastrodata/plot_utils.py +30 -22
- plotastrodata/script_utils.py +302 -0
- {plotastrodata-1.11.2.dist-info → plotastrodata-1.12.0.dist-info}/METADATA +36 -6
- plotastrodata-1.12.0.dist-info/RECORD +21 -0
- plotastrodata-1.11.2.dist-info/RECORD +0 -20
- {plotastrodata-1.11.2.dist-info → plotastrodata-1.12.0.dist-info}/WHEEL +0 -0
- {plotastrodata-1.11.2.dist-info → plotastrodata-1.12.0.dist-info}/licenses/LICENSE +0 -0
- {plotastrodata-1.11.2.dist-info → plotastrodata-1.12.0.dist-info}/top_level.txt +0 -0
plotastrodata/__init__.py
CHANGED
plotastrodata/_type_utils.py
CHANGED
|
@@ -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
|
plotastrodata/analysis_utils.py
CHANGED
|
@@ -1,35 +1,44 @@
|
|
|
1
|
-
import
|
|
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
|
|
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
|
|
14
|
-
|
|
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.
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
from plotastrodata.
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
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 (
|
|
32
|
-
|
|
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
|
-
|
|
501
|
-
|
|
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,
|
|
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.
|
|
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
|
plotastrodata/const_utils.py
CHANGED
|
@@ -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')
|
plotastrodata/coord_utils.py
CHANGED
plotastrodata/ext_utils.py
CHANGED
|
@@ -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
|
plotastrodata/fft_utils.py
CHANGED
|
@@ -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
|
|
plotastrodata/fits_utils.py
CHANGED
|
@@ -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
|
|
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,
|
plotastrodata/fitting_utils.py
CHANGED
|
@@ -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
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
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,
|
|
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
|
|
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,
|
|
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)
|
plotastrodata/los_utils.py
CHANGED
plotastrodata/matrix_utils.py
CHANGED
|
@@ -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.
|
|
45
|
-
y = M[1][0] * np.
|
|
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
|
|
plotastrodata/noise_utils.py
CHANGED
|
@@ -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
|
-
|
|
9
|
-
|
|
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
|
|
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.')
|
plotastrodata/other_utils.py
CHANGED
|
@@ -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
|
|
8
|
+
from scipy.interpolate import RegularGridInterpolator as RGI
|
|
8
9
|
|
|
9
10
|
|
|
10
11
|
def isdeg(s: Any) -> bool:
|
plotastrodata/plot_utils.py
CHANGED
|
@@ -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
|
|
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.
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
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 (
|
|
32
|
-
|
|
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,
|
|
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
|
-
#
|
|
893
|
-
tickvalues = np.round(tickvalues,
|
|
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.
|
|
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.
|
|
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
|
-
|
|
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
|
|
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
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
plotastrodata/__init__.py,sha256=PhXrmmIl9fwMyvQqqlaFE59q-Kq2QShRqLot7tJ1UNI,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=9r70QD1HX0GdZtel3Ug7BfHqWXzvLPCDl332aG6U5ng,16308
|
|
14
|
+
plotastrodata/other_utils.py,sha256=ouiizsR9-ygeaGMs7U5dy2UUEE5SRzrNKu65-EpqjRA,12124
|
|
15
|
+
plotastrodata/plot_utils.py,sha256=Qmb03AqL7xPa9C1vVRlOSXeVzMlxTuOxmWxAAlQjPkE,128445
|
|
16
|
+
plotastrodata/script_utils.py,sha256=4-r87HfpKGT1HpvVrwonyP2zYKAYpdVslQxdKuJHzkY,14395
|
|
17
|
+
plotastrodata-1.12.0.dist-info/licenses/LICENSE,sha256=OXLcl0T2SZ8Pmy2_dmlvKuetivmyPd5m1q-Gyd-zaYY,35149
|
|
18
|
+
plotastrodata-1.12.0.dist-info/METADATA,sha256=FkpgjmHYOLi0_Z7QJl78v7YduCD3xqYd2EhFMFeXWIQ,5240
|
|
19
|
+
plotastrodata-1.12.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
|
|
20
|
+
plotastrodata-1.12.0.dist-info/top_level.txt,sha256=mv2FRRtreGAUE_UF_Z_TYj_NZLECJqkQx7ErkA_Rttg,14
|
|
21
|
+
plotastrodata-1.12.0.dist-info/RECORD,,
|
|
@@ -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,,
|
|
File without changes
|
|
File without changes
|
|
File without changes
|