arcwind 1.0.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.
- arcwind/__init__.py +49 -0
- arcwind/_version.py +1 -0
- arcwind/analysis.py +533 -0
- arcwind/cli.py +144 -0
- arcwind/config.py +916 -0
- arcwind/constants.py +17 -0
- arcwind/continuum.py +164 -0
- arcwind/cube.py +514 -0
- arcwind/data/__init__.py +0 -0
- arcwind/data/template.toml +82 -0
- arcwind/derived.py +173 -0
- arcwind/diagnostics.py +228 -0
- arcwind/fitting.py +880 -0
- arcwind/geometry.py +173 -0
- arcwind/io.py +186 -0
- arcwind/laws.py +231 -0
- arcwind/masks.py +128 -0
- arcwind/mass.py +271 -0
- arcwind/mock.py +270 -0
- arcwind/model.py +442 -0
- arcwind/plotting/__init__.py +33 -0
- arcwind/plotting/_style.py +108 -0
- arcwind/plotting/fit.py +415 -0
- arcwind/plotting/maps.py +228 -0
- arcwind/plotting/other.py +138 -0
- arcwind/plotting/pv.py +188 -0
- arcwind/pv.py +81 -0
- arcwind/ringfit.py +433 -0
- arcwind/rotation.py +269 -0
- arcwind/trace.py +426 -0
- arcwind-1.0.0.dist-info/LICENSE +21 -0
- arcwind-1.0.0.dist-info/METADATA +241 -0
- arcwind-1.0.0.dist-info/RECORD +36 -0
- arcwind-1.0.0.dist-info/WHEEL +5 -0
- arcwind-1.0.0.dist-info/entry_points.txt +2 -0
- arcwind-1.0.0.dist-info/top_level.txt +1 -0
arcwind/__init__.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"""
|
|
2
|
+
arcwind -- geometry and kinematics of disk winds from transverse
|
|
3
|
+
position-velocity diagrams.
|
|
4
|
+
|
|
5
|
+
The method of Louvet et al. (2018, A&A 618, A120) for the edge-on HH 30
|
|
6
|
+
outflow, generalized to any inclination, to partially detected rings and to
|
|
7
|
+
flexible velocity laws: a conical wind is fitted to the traces of many cuts at
|
|
8
|
+
once.
|
|
9
|
+
|
|
10
|
+
Quick start
|
|
11
|
+
-----------
|
|
12
|
+
>>> from arcwind import WindAnalysis
|
|
13
|
+
>>> wa = WindAnalysis("mysource.toml") # doctest: +SKIP
|
|
14
|
+
>>> res = wa.fit() # doctest: +SKIP
|
|
15
|
+
>>> print(res.summary()) # doctest: +SKIP
|
|
16
|
+
|
|
17
|
+
Main classes
|
|
18
|
+
------------
|
|
19
|
+
:class:`WindConfig` all settings (TOML/YAML/JSON/Python)
|
|
20
|
+
:class:`WindAnalysis` the analysis, step by step or ``run()``
|
|
21
|
+
:class:`WindCube` the resampled cube and its PV diagrams
|
|
22
|
+
:class:`TraceExtractor` traces of the emission in the PV diagrams
|
|
23
|
+
:class:`ConicalWindModel` the model (geometry + velocity laws)
|
|
24
|
+
:class:`GlobalFitter` fit of the model to all cuts; returns :class:`FitResult`
|
|
25
|
+
:class:`RingFitter` independent per-cut ring fits (full rings)
|
|
26
|
+
:class:`MassAnalysis` mass and mass-loss rate
|
|
27
|
+
:func:`fit_disk_center` disk center from a continuum image
|
|
28
|
+
"""
|
|
29
|
+
from ._version import __version__
|
|
30
|
+
from .analysis import WindAnalysis
|
|
31
|
+
from .config import WindConfig
|
|
32
|
+
from .continuum import fit_disk_center
|
|
33
|
+
from .cube import WindCube
|
|
34
|
+
from .derived import WindProperties
|
|
35
|
+
from .fitting import FitResult, GlobalFitter, compare_fits
|
|
36
|
+
from .geometry import ViewGeometry
|
|
37
|
+
from .laws import VelocityLaw, available_laws, register_law
|
|
38
|
+
from .mass import MassAnalysis, MassResult
|
|
39
|
+
from .model import ConicalWindModel, ModelCurve
|
|
40
|
+
from .pv import PVDiagram
|
|
41
|
+
from .ringfit import RingFitter
|
|
42
|
+
from .rotation import RotationProfile, rotation_per_cut
|
|
43
|
+
from .trace import Trace, TraceExtractor
|
|
44
|
+
|
|
45
|
+
__all__ = ["__version__", "WindAnalysis", "WindConfig", "WindCube", "PVDiagram", "Trace",
|
|
46
|
+
"TraceExtractor", "ConicalWindModel", "ModelCurve", "ViewGeometry",
|
|
47
|
+
"GlobalFitter", "FitResult", "compare_fits", "RingFitter", "MassAnalysis",
|
|
48
|
+
"MassResult", "WindProperties", "VelocityLaw", "register_law", "available_laws",
|
|
49
|
+
"fit_disk_center", "RotationProfile", "rotation_per_cut"]
|
arcwind/_version.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "1.0.0"
|
arcwind/analysis.py
ADDED
|
@@ -0,0 +1,533 @@
|
|
|
1
|
+
"""
|
|
2
|
+
:class:`WindAnalysis` -- the high-level interface: one object that holds the
|
|
3
|
+
configuration, the cube, the traces and the fit results, with one method per
|
|
4
|
+
step of the analysis.
|
|
5
|
+
|
|
6
|
+
Typical session
|
|
7
|
+
---------------
|
|
8
|
+
>>> from arcwind import WindAnalysis
|
|
9
|
+
>>> wa = WindAnalysis("elias20.toml") # doctest: +SKIP
|
|
10
|
+
>>> wa.check_noise().summary() # 1. noise channels line-free? # doctest: +SKIP
|
|
11
|
+
>>> wa.check_disk_rotation().summary() # 2. disk rotation sense # doctest: +SKIP
|
|
12
|
+
>>> pl = wa.fit("power-law", n_boot=0) # 3. quick first fit # doctest: +SKIP
|
|
13
|
+
>>> bpl = wa.fit("broken-power-law", guide=pl, start_from=pl, iterations=2) # doctest: +SKIP
|
|
14
|
+
>>> wa.compare(pl, bpl) # 4. chi2 / BIC on the same traces # doctest: +SKIP
|
|
15
|
+
>>> m = wa.mass(bpl) # 5. mass and mass-loss rate # doctest: +SKIP
|
|
16
|
+
>>> print(wa.derived(bpl, m).summary()) # 6. Vp, r_L, travel time, ... # doctest: +SKIP
|
|
17
|
+
>>> wa.plot_cuts(bpl, others=[pl]) # figures # doctest: +SKIP
|
|
18
|
+
|
|
19
|
+
Or everything at once, as set in the configuration: ``wa.run()`` (also
|
|
20
|
+
``arcwind run elias20.toml`` on the command line).
|
|
21
|
+
"""
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
import os
|
|
25
|
+
|
|
26
|
+
from . import plotting
|
|
27
|
+
from .config import WindConfig
|
|
28
|
+
from .constants import FWHM2SIG
|
|
29
|
+
from .cube import WindCube
|
|
30
|
+
from .fitting import FitResult, GlobalFitter, compare_fits
|
|
31
|
+
from .mass import MassAnalysis
|
|
32
|
+
from .model import ConicalWindModel
|
|
33
|
+
from .ringfit import RingFitter
|
|
34
|
+
from .trace import TraceExtractor
|
|
35
|
+
|
|
36
|
+
__all__ = ["WindAnalysis"]
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class WindAnalysis:
|
|
40
|
+
"""A complete wind analysis.
|
|
41
|
+
|
|
42
|
+
Parameters
|
|
43
|
+
----------
|
|
44
|
+
config : WindConfig or str
|
|
45
|
+
Configuration object or file (TOML / YAML / JSON / Python).
|
|
46
|
+
cube : WindCube, optional
|
|
47
|
+
An already loaded cube (default: loaded on first use).
|
|
48
|
+
**options
|
|
49
|
+
Configuration options to change (bare or dotted names), e.g.
|
|
50
|
+
``WindAnalysis("elias20.toml", n_boot=0, **{"output.dir": "test"})``.
|
|
51
|
+
|
|
52
|
+
Attributes
|
|
53
|
+
----------
|
|
54
|
+
config : WindConfig
|
|
55
|
+
results : dict
|
|
56
|
+
Fit results by label, in the order they were made.
|
|
57
|
+
traces : dict
|
|
58
|
+
Traces of the last extraction, ``{y0: Trace}``.
|
|
59
|
+
"""
|
|
60
|
+
|
|
61
|
+
def __init__(self, config, cube=None, **options):
|
|
62
|
+
cfg = config if isinstance(config, WindConfig) else WindConfig.load(config)
|
|
63
|
+
if options:
|
|
64
|
+
cfg = cfg.copy().set(**options)
|
|
65
|
+
self.config = cfg
|
|
66
|
+
self._cubes = {}
|
|
67
|
+
if cube is not None:
|
|
68
|
+
self._cubes[getattr(cube, "lobe", "main")] = cube
|
|
69
|
+
self.results = {}
|
|
70
|
+
self.traces = {}
|
|
71
|
+
self.counter_traces = {}
|
|
72
|
+
|
|
73
|
+
# ---------------------------------------------------------------- data
|
|
74
|
+
@property
|
|
75
|
+
def default_lobe(self):
|
|
76
|
+
"""The lobe analyzed by default: 'main', 'counter' or 'both' (``source.lobes``)."""
|
|
77
|
+
return self.config.source.lobes
|
|
78
|
+
|
|
79
|
+
def cube_for(self, lobe="main"):
|
|
80
|
+
"""The :class:`WindCube` in the frame of ``lobe`` ('main' or 'counter'),
|
|
81
|
+
loaded on first access."""
|
|
82
|
+
if lobe not in self._cubes:
|
|
83
|
+
self._cubes[lobe] = WindCube(self.config, lobe=lobe)
|
|
84
|
+
return self._cubes[lobe]
|
|
85
|
+
|
|
86
|
+
@property
|
|
87
|
+
def cube(self):
|
|
88
|
+
"""The cube of the default lobe (the main lobe when both are analyzed)."""
|
|
89
|
+
return self.cube_for("counter" if self.default_lobe == "counter" else "main")
|
|
90
|
+
|
|
91
|
+
@property
|
|
92
|
+
def counter_cube(self):
|
|
93
|
+
"""The cube in the frame of the counter lobe."""
|
|
94
|
+
return self.cube_for("counter")
|
|
95
|
+
|
|
96
|
+
@property
|
|
97
|
+
def geometry(self):
|
|
98
|
+
return self.cube.geometry
|
|
99
|
+
|
|
100
|
+
def _lobe(self, lobe):
|
|
101
|
+
lobe = lobe or self.default_lobe
|
|
102
|
+
if lobe not in ("main", "counter", "both"):
|
|
103
|
+
raise ValueError("lobe must be 'main', 'counter' or 'both'")
|
|
104
|
+
return lobe
|
|
105
|
+
|
|
106
|
+
@staticmethod
|
|
107
|
+
def _in_frame(r, lobe):
|
|
108
|
+
"""A result (or None) in the frame of a single lobe."""
|
|
109
|
+
return r.view(lobe) if isinstance(r, FitResult) else r
|
|
110
|
+
|
|
111
|
+
@property
|
|
112
|
+
def sig_x(self):
|
|
113
|
+
"""Position uncertainty of trace points (arcsec)."""
|
|
114
|
+
return self.config.trace.sigx_beam * self.cube.beam_x * FWHM2SIG
|
|
115
|
+
|
|
116
|
+
def _log(self, msg):
|
|
117
|
+
if self.config.output.verbose:
|
|
118
|
+
print(f"[arcwind] {msg}")
|
|
119
|
+
|
|
120
|
+
def pv(self, y0, **kw):
|
|
121
|
+
"""Transverse PV diagram (:meth:`WindCube.pv`)."""
|
|
122
|
+
return self.cube.pv(y0, **kw)
|
|
123
|
+
|
|
124
|
+
def check_noise(self, plot=True):
|
|
125
|
+
"""Noise-channel check (:func:`arcwind.diagnostics.check_noise`); saves
|
|
126
|
+
``noise_check.txt`` and the figure."""
|
|
127
|
+
rep = self.cube.check_noise()
|
|
128
|
+
with open(self.config.outpath("noise_check", "txt"), "w") as fh:
|
|
129
|
+
fh.write(rep.summary() + "\n")
|
|
130
|
+
if plot:
|
|
131
|
+
rep.plot(save=self.config.outpath("noise_check"))
|
|
132
|
+
self._log(rep.summary().splitlines()[-1])
|
|
133
|
+
return rep
|
|
134
|
+
|
|
135
|
+
def check_disk_rotation(self, y_offsets=(0.0, -0.15, -0.3), plot=True):
|
|
136
|
+
"""Disk rotation-sense check (:func:`arcwind.diagnostics.check_disk_rotation`)."""
|
|
137
|
+
chk = self.cube.check_disk_rotation(y_offsets)
|
|
138
|
+
if plot:
|
|
139
|
+
chk.plot(save=self.config.outpath("disk_rotation_check"))
|
|
140
|
+
self._log(chk.summary())
|
|
141
|
+
return chk
|
|
142
|
+
|
|
143
|
+
# -------------------------------------------------------------- traces
|
|
144
|
+
def extract_traces(self, y_offsets=None, guide=None, lobe="main", **trace_options):
|
|
145
|
+
"""Extract the traces of the cuts of one lobe (:class:`TraceExtractor`).
|
|
146
|
+
|
|
147
|
+
Parameters
|
|
148
|
+
----------
|
|
149
|
+
y_offsets : array-like, optional
|
|
150
|
+
Default: ``cuts.y_offsets_arcsec``.
|
|
151
|
+
guide : FitResult, str or None
|
|
152
|
+
Guided extraction around a fit (or the label of a stored result); a fit
|
|
153
|
+
of the other lobe or of both lobes is mirrored into this lobe's frame.
|
|
154
|
+
lobe : {'main', 'counter'}
|
|
155
|
+
Which lobe (each in its own frame).
|
|
156
|
+
**trace_options
|
|
157
|
+
``[trace]`` options for this extraction.
|
|
158
|
+
|
|
159
|
+
Returns
|
|
160
|
+
-------
|
|
161
|
+
dict
|
|
162
|
+
``{y0: Trace}`` (also stored in ``self.traces`` or ``self.counter_traces``).
|
|
163
|
+
"""
|
|
164
|
+
g = self._in_frame(self._resolve(guide), lobe)
|
|
165
|
+
cube = self.cube_for(lobe)
|
|
166
|
+
if isinstance(g, ConicalWindModel): # a bare model: evaluate it here
|
|
167
|
+
model, geom = g, cube.geometry
|
|
168
|
+
g = lambda y0: model.curve(y0, geom) # noqa: E731
|
|
169
|
+
g.label = "a model"
|
|
170
|
+
tr = TraceExtractor(cube).extract_all(y_offsets, guide=g, **trace_options)
|
|
171
|
+
if lobe == "counter":
|
|
172
|
+
self.counter_traces = tr
|
|
173
|
+
else:
|
|
174
|
+
self.traces = tr
|
|
175
|
+
n = sum(t.n for t in tr.values())
|
|
176
|
+
self._log(f"traces ({lobe} lobe): {len(tr)} cuts, {n} points"
|
|
177
|
+
+ (f" (guided by {g.label})" if g is not None else ""))
|
|
178
|
+
return tr
|
|
179
|
+
|
|
180
|
+
def _resolve(self, r):
|
|
181
|
+
"""A result from a FitResult, a model, a stored label or 'last'."""
|
|
182
|
+
if r is None or isinstance(r, (FitResult, ConicalWindModel)):
|
|
183
|
+
return r
|
|
184
|
+
if r in ("last", "previous"):
|
|
185
|
+
if not self.results:
|
|
186
|
+
raise ValueError("no fit has been made yet")
|
|
187
|
+
return list(self.results.values())[-1]
|
|
188
|
+
if r not in self.results:
|
|
189
|
+
raise KeyError(f"no result labeled {r!r}; stored results: {list(self.results)} "
|
|
190
|
+
"(load saved ones with load_result)")
|
|
191
|
+
return self.results[r]
|
|
192
|
+
|
|
193
|
+
# ----------------------------------------------------------------- fit
|
|
194
|
+
def model(self, velocity_law=None, radial=None, rotation=None, fixed=None, bounds=None,
|
|
195
|
+
**values):
|
|
196
|
+
"""A :class:`ConicalWindModel` as set by ``[fit]``, with optional changes.
|
|
197
|
+
|
|
198
|
+
``fixed`` and ``bounds`` given here must name parameters of the model (an
|
|
199
|
+
error says which exist); those in the configuration are applied only where
|
|
200
|
+
they exist, since one configuration serves several models.
|
|
201
|
+
"""
|
|
202
|
+
cfg = self.config
|
|
203
|
+
if velocity_law or radial or rotation:
|
|
204
|
+
cfg = cfg.copy()
|
|
205
|
+
cfg.fit.velocity_law = velocity_law or cfg.fit.velocity_law
|
|
206
|
+
cfg.fit.radial = radial or cfg.fit.radial
|
|
207
|
+
cfg.fit.rotation = rotation or cfg.fit.rotation
|
|
208
|
+
m = ConicalWindModel.from_config(cfg)
|
|
209
|
+
m.fix(**(fixed or {}))
|
|
210
|
+
m.set_bounds(**(bounds or {}))
|
|
211
|
+
return m.set(**values)
|
|
212
|
+
|
|
213
|
+
def fit(self, velocity_law=None, radial=None, rotation=None, fixed=None, bounds=None,
|
|
214
|
+
guide=None, start_from=None, iterations=None, n_boot=None, y_offsets=None,
|
|
215
|
+
init=None, label=None, traces=None, save=True, lobe=None, **fit_options):
|
|
216
|
+
"""Global fit of a conical wind to all cuts.
|
|
217
|
+
|
|
218
|
+
Parameters
|
|
219
|
+
----------
|
|
220
|
+
velocity_law, radial, rotation : str, optional
|
|
221
|
+
Model choices (default: ``[fit]``); see :class:`ConicalWindModel`.
|
|
222
|
+
fixed : dict, optional
|
|
223
|
+
Extra fixed parameters ``{name: value}``.
|
|
224
|
+
bounds : dict, optional
|
|
225
|
+
Extra bounds ``{name: (lo, hi)}``.
|
|
226
|
+
guide : FitResult or str, optional
|
|
227
|
+
Extract the traces around this fit (``'last'``: the previous result).
|
|
228
|
+
start_from : FitResult or str, optional
|
|
229
|
+
Start from this (simpler) fit, e.g. a power law for a broken power law.
|
|
230
|
+
iterations : int, optional
|
|
231
|
+
With a guide: re-extract the traces around the new model and refit this
|
|
232
|
+
many times in total (default ``fit.iterations``).
|
|
233
|
+
n_boot : int, optional
|
|
234
|
+
Bootstrap resamplings (default ``fit.n_boot``; done on the last iteration).
|
|
235
|
+
y_offsets : array-like, optional
|
|
236
|
+
Cuts to use.
|
|
237
|
+
init : dict, optional
|
|
238
|
+
Starting values.
|
|
239
|
+
label : str, optional
|
|
240
|
+
Name of the result (default: the velocity law, plus the radial mode if not
|
|
241
|
+
'cone' and '-jz' for a power-law j; a number is appended if that name is
|
|
242
|
+
already used, so earlier fits are never overwritten).
|
|
243
|
+
traces : dict, optional
|
|
244
|
+
Use these traces instead of extracting them (for ``lobe='both'``: a pair
|
|
245
|
+
``(main_traces, counter_traces)``).
|
|
246
|
+
lobe : {'main', 'counter', 'both'}, optional
|
|
247
|
+
Which lobe to fit (default ``source.lobes``). ``'both'`` fits one
|
|
248
|
+
mirror-symmetric wind to the cuts of both lobes; the parameters refer to
|
|
249
|
+
the main lobe's frame (``res.view('counter')`` for the other).
|
|
250
|
+
save : bool
|
|
251
|
+
Write ``<label>.json`` and ``<label>.txt`` to the output folder.
|
|
252
|
+
**fit_options
|
|
253
|
+
Other ``[fit]`` options for this fit, e.g. ``loss='soft_l1'``.
|
|
254
|
+
|
|
255
|
+
Returns
|
|
256
|
+
-------
|
|
257
|
+
FitResult
|
|
258
|
+
|
|
259
|
+
Examples
|
|
260
|
+
--------
|
|
261
|
+
Start simple, then let the velocity law break:
|
|
262
|
+
|
|
263
|
+
>>> pl = wa.fit("power-law", n_boot=0) # doctest: +SKIP
|
|
264
|
+
>>> bpl = wa.fit("broken-power-law", guide=pl, start_from=pl) # doctest: +SKIP
|
|
265
|
+
|
|
266
|
+
Both lobes of a bipolar wind, jointly or one at a time:
|
|
267
|
+
|
|
268
|
+
>>> both = wa.fit(lobe="both") # doctest: +SKIP
|
|
269
|
+
>>> north, south = wa.fit(lobe="main"), wa.fit(lobe="counter") # doctest: +SKIP
|
|
270
|
+
|
|
271
|
+
Test a free radial velocity, or hold the axis tilt fixed:
|
|
272
|
+
|
|
273
|
+
>>> free_vr = wa.fit(radial="proportional", n_boot=0) # doctest: +SKIP
|
|
274
|
+
>>> no_tilt = wa.fit(fixed={"xslope": 0.0, "xoff_au": 0.0}) # doctest: +SKIP
|
|
275
|
+
"""
|
|
276
|
+
from copy import copy
|
|
277
|
+
fc = copy(self.config.fit)
|
|
278
|
+
for k, v in fit_options.items():
|
|
279
|
+
if not hasattr(fc, k):
|
|
280
|
+
raise ValueError(f"unknown fit option {k!r}")
|
|
281
|
+
setattr(fc, k, v)
|
|
282
|
+
model = self.model(velocity_law, radial, rotation, fixed, bounds)
|
|
283
|
+
lobe = self._lobe(lobe)
|
|
284
|
+
frame = "counter" if lobe == "counter" else "main"
|
|
285
|
+
guide = self._resolve(guide)
|
|
286
|
+
start_from = self._in_frame(self._resolve(start_from), frame)
|
|
287
|
+
n_boot = fc.n_boot if n_boot is None else n_boot
|
|
288
|
+
iterations = fc.iterations if iterations is None else iterations
|
|
289
|
+
if label is None:
|
|
290
|
+
base = (model.law.name + ("" if model.radial == "cone" else f"-{model.radial}")
|
|
291
|
+
+ ("" if model.rotation == "constant" else "-jz")
|
|
292
|
+
+ ("" if lobe == "main" else f"-{lobe}"))
|
|
293
|
+
label, k = base, 2
|
|
294
|
+
while label in self.results: # never overwrite an earlier fit
|
|
295
|
+
label, k = f"{base}-{k}", k + 1
|
|
296
|
+
|
|
297
|
+
def extract(g):
|
|
298
|
+
if lobe == "both":
|
|
299
|
+
return (self.extract_traces(y_offsets, guide=g, lobe="main"),
|
|
300
|
+
self.extract_traces(y_offsets, guide=g, lobe="counter"))
|
|
301
|
+
return self.extract_traces(y_offsets, guide=g, lobe=frame), None
|
|
302
|
+
|
|
303
|
+
if traces is None:
|
|
304
|
+
traces, ctraces = extract(guide)
|
|
305
|
+
elif lobe == "both":
|
|
306
|
+
traces, ctraces = traces
|
|
307
|
+
else:
|
|
308
|
+
ctraces = None
|
|
309
|
+
geom = self.cube_for(frame).geometry
|
|
310
|
+
if model.radial != "cone" and geom.edge_on:
|
|
311
|
+
self._log("edge-on view: Vz is unconstrained unless the flow is tied to the cone")
|
|
312
|
+
n_it = max(1, int(iterations)) if guide is not None else 1
|
|
313
|
+
res = None
|
|
314
|
+
for it in range(n_it):
|
|
315
|
+
last = it == n_it - 1
|
|
316
|
+
fitter = GlobalFitter.from_config(model, geom, traces, self.sig_x, fc,
|
|
317
|
+
verbose=self.config.output.verbose,
|
|
318
|
+
counter_traces=ctraces)
|
|
319
|
+
init_it = init if res is None else res.params
|
|
320
|
+
res = fitter.fit(init=init_it, start_from=start_from, n_boot=n_boot if last else 0)
|
|
321
|
+
res.frame = frame
|
|
322
|
+
if not last:
|
|
323
|
+
self._log(f"guided iteration {it + 1}/{n_it}: re-extracting traces")
|
|
324
|
+
traces, ctraces = extract(res)
|
|
325
|
+
res.label = label
|
|
326
|
+
self.results[label] = res
|
|
327
|
+
if frame == "counter":
|
|
328
|
+
self.counter_traces = traces
|
|
329
|
+
else:
|
|
330
|
+
self.traces = traces
|
|
331
|
+
if ctraces:
|
|
332
|
+
self.counter_traces = ctraces
|
|
333
|
+
if save:
|
|
334
|
+
res.save(self.config.outpath(label, "json"))
|
|
335
|
+
with open(self.config.outpath(label, "txt"), "w") as fh:
|
|
336
|
+
fh.write(res.summary() + "\n")
|
|
337
|
+
self._log(repr(res))
|
|
338
|
+
return res
|
|
339
|
+
|
|
340
|
+
def compare(self, *results, traces=None, other_traces=None, show=True):
|
|
341
|
+
"""Compare fits on the same traces (default: those of the last one).
|
|
342
|
+
|
|
343
|
+
Parameters
|
|
344
|
+
----------
|
|
345
|
+
*results : FitResult or str
|
|
346
|
+
Results or labels (default: all stored results).
|
|
347
|
+
traces, other_traces : dict, optional
|
|
348
|
+
Common traces of the main lobe (and of the counter lobe).
|
|
349
|
+
|
|
350
|
+
Returns
|
|
351
|
+
-------
|
|
352
|
+
list of dict
|
|
353
|
+
``label, k, n, chi2, bic, dbic`` sorted by BIC.
|
|
354
|
+
"""
|
|
355
|
+
rs = [self._resolve(r) for r in results] or list(self.results.values())
|
|
356
|
+
rows = compare_fits(rs, traces=traces, other_traces=other_traces)
|
|
357
|
+
if show:
|
|
358
|
+
print(f"{'model':28s} {'k':>3s} {'chi2':>10s} {'BIC':>10s} {'dBIC':>8s}")
|
|
359
|
+
for r in rows:
|
|
360
|
+
print(f"{r['label']:28s} {r['k']:3d} {r['chi2']:10.1f} {r['bic']:10.1f} "
|
|
361
|
+
f"{r['dbic']:8.1f}")
|
|
362
|
+
print("(trace points are ~2 per beam: chi2/BIC differences are overestimated "
|
|
363
|
+
"by about that factor)")
|
|
364
|
+
return rows
|
|
365
|
+
|
|
366
|
+
def load_result(self, path_or_label):
|
|
367
|
+
"""Load a saved :class:`FitResult` (path, or label in the output folder)."""
|
|
368
|
+
p = path_or_label if os.path.exists(str(path_or_label)) else \
|
|
369
|
+
self.config.outpath(path_or_label, "json")
|
|
370
|
+
r = FitResult.load(p)
|
|
371
|
+
self.results[r.label] = r
|
|
372
|
+
return r
|
|
373
|
+
|
|
374
|
+
# ------------------------------------------------------------ others
|
|
375
|
+
def _single(self, lobe):
|
|
376
|
+
"""A single lobe for per-lobe steps: 'both' -> 'main'."""
|
|
377
|
+
lobe = self._lobe(lobe)
|
|
378
|
+
return "main" if lobe == "both" else lobe
|
|
379
|
+
|
|
380
|
+
def _sfx(self, lobe):
|
|
381
|
+
return "" if lobe == "main" else f"_{lobe}"
|
|
382
|
+
|
|
383
|
+
def ring_fits(self, y_offsets=None, prior_from=None, fix_from=None, guide=None, lobe=None):
|
|
384
|
+
"""Independent per-cut ring fits (:class:`RingFitter`) of one lobe, for full
|
|
385
|
+
rings (``lobe`` default: the main lobe)."""
|
|
386
|
+
lobe = self._single(lobe)
|
|
387
|
+
v = lambda r: self._in_frame(self._resolve(r), lobe)
|
|
388
|
+
rs = RingFitter(self.cube_for(lobe)).fit_all(y_offsets, prior_from=v(prior_from),
|
|
389
|
+
fix_from=v(fix_from), guide=v(guide))
|
|
390
|
+
rs.save_csv(self.config.outpath("ring_fits" + self._sfx(lobe), "csv"))
|
|
391
|
+
return rs
|
|
392
|
+
|
|
393
|
+
def mass(self, result="last", plot=True, lobe=None, **mass_options):
|
|
394
|
+
"""Brightness, mass and mass-loss rate of one lobe (:class:`MassAnalysis`).
|
|
395
|
+
|
|
396
|
+
With two lobes, call it once per lobe (``lobe='main'``, ``lobe='counter'``)."""
|
|
397
|
+
lobe = self._single(lobe)
|
|
398
|
+
r = self._in_frame(self._resolve(result), lobe) if result is not None else None
|
|
399
|
+
cube = self.cube_for(lobe)
|
|
400
|
+
m = MassAnalysis(cube, velocity_model=r, **mass_options).run()
|
|
401
|
+
m.save(self.config.outpath("mass_slices" + self._sfx(lobe), "txt"))
|
|
402
|
+
if plot:
|
|
403
|
+
m.plot(cube=cube, save=self.config.outpath("mass_slices" + self._sfx(lobe)))
|
|
404
|
+
self._log(f"{lobe} lobe: " + m.summary().splitlines()[2])
|
|
405
|
+
return m
|
|
406
|
+
|
|
407
|
+
def derived(self, result="last", mass=None):
|
|
408
|
+
"""Derived quantities (:class:`~arcwind.derived.WindProperties`)."""
|
|
409
|
+
return self._resolve(result).derived(mass=mass)
|
|
410
|
+
|
|
411
|
+
# ------------------------------------------------------------ figures
|
|
412
|
+
# Every figure method takes ``lobe`` ('main' or 'counter'; default: the main
|
|
413
|
+
# lobe, or the counter lobe if that is the only one analyzed). A two-lobe fit
|
|
414
|
+
# is shown in the frame of the requested lobe.
|
|
415
|
+
def _save(self, fig, name, save):
|
|
416
|
+
"""``save``: True (to ``output.dir``), False, or a file path."""
|
|
417
|
+
if save:
|
|
418
|
+
path = save if isinstance(save, str) else self.config.outpath(name)
|
|
419
|
+
fig.savefig(path, dpi=self.config.output.dpi, bbox_inches="tight", pad_inches=0.05)
|
|
420
|
+
return fig
|
|
421
|
+
|
|
422
|
+
def _r(self, result, lobe):
|
|
423
|
+
return self._in_frame(self._resolve(result), lobe)
|
|
424
|
+
|
|
425
|
+
def plot_pv_grid(self, result=None, save=True, lobe=None, **kw):
|
|
426
|
+
lobe = self._single(lobe)
|
|
427
|
+
fig = plotting.plot_pv_grid(self.cube_for(lobe), result=self._r(result, lobe), **kw)
|
|
428
|
+
return self._save(fig, "pv_grid" + self._sfx(lobe), save)
|
|
429
|
+
|
|
430
|
+
def plot_gallery(self, result="last", save=True, lobe=None, **kw):
|
|
431
|
+
lobe = self._single(lobe)
|
|
432
|
+
fig = plotting.plot_gallery(self.cube_for(lobe), result=self._r(result, lobe), **kw)
|
|
433
|
+
return self._save(fig, "pv_gallery" + self._sfx(lobe), save)
|
|
434
|
+
|
|
435
|
+
def plot_slit_layout(self, save=True, lobe=None, **kw):
|
|
436
|
+
lobe = self._single(lobe)
|
|
437
|
+
return self._save(plotting.plot_slit_layout(self.cube_for(lobe), **kw),
|
|
438
|
+
"slit_layout" + self._sfx(lobe), save)
|
|
439
|
+
|
|
440
|
+
def plot_cuts(self, result="last", others=(), save=True, lobe=None, **kw):
|
|
441
|
+
lobe = self._single(lobe)
|
|
442
|
+
r = self._r(result, lobe)
|
|
443
|
+
fig = plotting.plot_cuts(self.cube_for(lobe), r, [self._r(o, lobe) for o in others],
|
|
444
|
+
**kw)
|
|
445
|
+
return self._save(fig, f"{r.label}_cuts" + self._sfx(lobe), save)
|
|
446
|
+
|
|
447
|
+
def plot_cut(self, y0, result="last", others=(), save=True, lobe=None, **kw):
|
|
448
|
+
lobe = self._single(lobe)
|
|
449
|
+
r = self._r(result, lobe)
|
|
450
|
+
fig = plotting.plot_cut(self.cube_for(lobe), r, y0, [self._r(o, lobe) for o in others],
|
|
451
|
+
**kw)
|
|
452
|
+
return self._save(fig, f"{r.label}_cut_y{y0:.2f}" + self._sfx(lobe), save)
|
|
453
|
+
|
|
454
|
+
def plot_profiles(self, result="last", others=(), save=True, **kw):
|
|
455
|
+
r = self._resolve(result)
|
|
456
|
+
fig = plotting.plot_profiles(r, [self._resolve(o) for o in others], **kw)
|
|
457
|
+
return self._save(fig, f"{r.label}_profiles", save)
|
|
458
|
+
|
|
459
|
+
def plot_angular_momentum(self, result="last", others=(), save=True, **kw):
|
|
460
|
+
"""j(z) and V_phi(z) with bootstrap bands (:func:`plotting.plot_angular_momentum`)."""
|
|
461
|
+
r = self._resolve(result)
|
|
462
|
+
fig = plotting.plot_angular_momentum(r, [self._resolve(o) for o in others], **kw)
|
|
463
|
+
return self._save(fig, f"{r.label}_angular_momentum", save)
|
|
464
|
+
|
|
465
|
+
def rotation_per_cut(self, result="last", nsigma=2.0, save=True, **kw):
|
|
466
|
+
"""j measured in each cut with the geometry and velocity law of ``result``
|
|
467
|
+
held fixed (:func:`arcwind.rotation.rotation_per_cut`); writes
|
|
468
|
+
``<label>_rotation_per_cut.txt``.
|
|
469
|
+
|
|
470
|
+
>>> rot = wa.rotation_per_cut(bpl) # doctest: +SKIP
|
|
471
|
+
>>> print(rot.summary()) # doctest: +SKIP
|
|
472
|
+
"""
|
|
473
|
+
from .rotation import rotation_per_cut
|
|
474
|
+
r = self._resolve(result)
|
|
475
|
+
prof = rotation_per_cut(r, nsigma=nsigma, **kw)
|
|
476
|
+
if save:
|
|
477
|
+
prof.save(self.config.outpath(f"{r.label}_rotation_per_cut", "txt"))
|
|
478
|
+
return prof
|
|
479
|
+
|
|
480
|
+
def plot_rotation(self, profile, result=None, save=True, **kw):
|
|
481
|
+
"""Figure of a :class:`~arcwind.rotation.RotationProfile`
|
|
482
|
+
(``<label>_rotation_per_cut``); ``result`` adds the global fit's j(z)."""
|
|
483
|
+
r = self._resolve(result) if result is not None else None
|
|
484
|
+
fig = plotting.plot_rotation(profile, r, **kw)
|
|
485
|
+
return self._save(fig, f"{profile.label}_rotation_per_cut", save)
|
|
486
|
+
|
|
487
|
+
def plot_bootstrap(self, result="last", save=True):
|
|
488
|
+
r = self._resolve(result)
|
|
489
|
+
return self._save(plotting.plot_bootstrap(r), f"{r.label}_bootstrap", save)
|
|
490
|
+
|
|
491
|
+
# --------------------------------------------------------------- run
|
|
492
|
+
def run(self, first_law="power-law", n_boot=None, figures=True):
|
|
493
|
+
"""The standard analysis, driven by the configuration.
|
|
494
|
+
|
|
495
|
+
1. noise and disk-rotation checks;
|
|
496
|
+
2. an unguided fit with ``first_law`` (no bootstrap);
|
|
497
|
+
3. the configured law (``fit.velocity_law``) guided by and started from it,
|
|
498
|
+
``fit.iterations`` times, with the bootstrap;
|
|
499
|
+
4. model comparison, mass, derived quantities, figures.
|
|
500
|
+
|
|
501
|
+
Returns
|
|
502
|
+
-------
|
|
503
|
+
dict
|
|
504
|
+
``first``, ``final``, ``comparison``, ``mass``, ``derived``.
|
|
505
|
+
"""
|
|
506
|
+
cfg = self.config
|
|
507
|
+
self.check_noise()
|
|
508
|
+
self.check_disk_rotation()
|
|
509
|
+
first = self.fit(first_law, n_boot=0, label=f"{first_law}-first")
|
|
510
|
+
final = self.fit(guide=first, start_from=first, n_boot=n_boot)
|
|
511
|
+
comp = self.compare(first, final)
|
|
512
|
+
m = self.mass(final)
|
|
513
|
+
if self.default_lobe == "both":
|
|
514
|
+
self.mass(final, lobe="counter")
|
|
515
|
+
props = self.derived(final, m)
|
|
516
|
+
with open(cfg.outpath("derived", "txt"), "w") as fh:
|
|
517
|
+
fh.write(props.summary() + "\n")
|
|
518
|
+
print(props.summary())
|
|
519
|
+
if figures:
|
|
520
|
+
lobes = ["main", "counter"] if self.default_lobe == "both" else [None]
|
|
521
|
+
for lb in lobes:
|
|
522
|
+
self.plot_cuts(final, others=[first], lobe=lb)
|
|
523
|
+
self.plot_gallery(final, lobe=lb)
|
|
524
|
+
self.plot_pv_grid(final, lobe=lb)
|
|
525
|
+
self.plot_profiles(final, others=[first])
|
|
526
|
+
if final.boot is not None and len(final.boot):
|
|
527
|
+
self.plot_bootstrap(final)
|
|
528
|
+
self._log(f"done: results in {cfg.output_dir}")
|
|
529
|
+
return dict(first=first, final=final, comparison=comp, mass=m, derived=props)
|
|
530
|
+
|
|
531
|
+
def __repr__(self):
|
|
532
|
+
return (f"WindAnalysis({self.config.source.name!r}, results={list(self.results)}, "
|
|
533
|
+
f"lobes={self.default_lobe!r}, cubes loaded={sorted(self._cubes)})")
|