bbarolo 2.0.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- bbarolo/__init__.py +92 -0
- bbarolo/__main__.py +4 -0
- bbarolo/_features.py +42 -0
- bbarolo/_plotserver.py +135 -0
- bbarolo/_rng.py +100 -0
- bbarolo/_version.py +3 -0
- bbarolo/bayesian/__init__.py +113 -0
- bbarolo/bayesian/common.py +362 -0
- bbarolo/bayesian/density.py +151 -0
- bbarolo/bayesian/emission.py +275 -0
- bbarolo/bayesian/fitter.py +1136 -0
- bbarolo/bayesian/likelihood.py +753 -0
- bbarolo/bayesian/nautilus/LICENSE +21 -0
- bbarolo/bayesian/nautilus/__init__.py +28 -0
- bbarolo/bayesian/nautilus/bounds/__init__.py +10 -0
- bbarolo/bayesian/nautilus/bounds/basic.py +729 -0
- bbarolo/bayesian/nautilus/bounds/nautilus.py +405 -0
- bbarolo/bayesian/nautilus/bounds/neural.py +176 -0
- bbarolo/bayesian/nautilus/bounds/periodic.py +109 -0
- bbarolo/bayesian/nautilus/bounds/union.py +452 -0
- bbarolo/bayesian/nautilus/gmm.py +154 -0
- bbarolo/bayesian/nautilus/mlp.py +222 -0
- bbarolo/bayesian/nautilus/neural.py +197 -0
- bbarolo/bayesian/nautilus/pool.py +159 -0
- bbarolo/bayesian/nautilus/prior.py +182 -0
- bbarolo/bayesian/nautilus/sampler.py +1599 -0
- bbarolo/bayesian/noise.py +186 -0
- bbarolo/bayesian/optimize.py +503 -0
- bbarolo/bayesian/outputs.py +710 -0
- bbarolo/bayesian/rings.py +76 -0
- bbarolo/bayesian/sampling.py +355 -0
- bbarolo/bayesian/slit.py +1112 -0
- bbarolo/bayesian/slit_outputs.py +321 -0
- bbarolo/bayesian/slitdata.py +611 -0
- bbarolo/bayesian/slitmodel.py +215 -0
- bbarolo/bayesian/slittask.py +40 -0
- bbarolo/bayesian/task.py +53 -0
- bbarolo/bayesian/wind.py +1354 -0
- bbarolo/bayesian/wind_outputs.py +252 -0
- bbarolo/bayesian/wind_plots.py +469 -0
- bbarolo/bayesian/windtask.py +47 -0
- bbarolo/bbutils.py +765 -0
- bbarolo/cli.py +277 -0
- bbarolo/cube.py +909 -0
- bbarolo/ellprof.py +355 -0
- bbarolo/fitsutils.py +354 -0
- bbarolo/galfit.py +1732 -0
- bbarolo/galfit_out.py +488 -0
- bbarolo/galmod.py +1386 -0
- bbarolo/galmod3d.py +474 -0
- bbarolo/galwind.py +512 -0
- bbarolo/header.py +769 -0
- bbarolo/image.py +111 -0
- bbarolo/keywords.py +840 -0
- bbarolo/keywords_doc.py +2233 -0
- bbarolo/moments.py +466 -0
- bbarolo/paramguess.py +728 -0
- bbarolo/params.py +1946 -0
- bbarolo/plots/__init__.py +16 -0
- bbarolo/plots/fit3d.py +781 -0
- bbarolo/plots/inmemory.py +226 -0
- bbarolo/plots/scripts.py +354 -0
- bbarolo/plots/slitfit.py +156 -0
- bbarolo/plots/utils.py +70 -0
- bbarolo/plotscripts.py +349 -0
- bbarolo/profile.py +468 -0
- bbarolo/pvslice.py +347 -0
- bbarolo/rendering3d.py +97 -0
- bbarolo/ringmodel.py +461 -0
- bbarolo/rings.py +341 -0
- bbarolo/search.py +544 -0
- bbarolo/smooth.py +380 -0
- bbarolo/spacepar.py +240 -0
- bbarolo/stats.py +125 -0
- bbarolo/tasks.py +2013 -0
- bbarolo/utils.py +568 -0
- bbarolo/windmodel.py +889 -0
- bbarolo-2.0.1.dist-info/METADATA +187 -0
- bbarolo-2.0.1.dist-info/RECORD +84 -0
- bbarolo-2.0.1.dist-info/WHEEL +5 -0
- bbarolo-2.0.1.dist-info/entry_points.txt +2 -0
- bbarolo-2.0.1.dist-info/licenses/LICENSE.md +674 -0
- bbarolo-2.0.1.dist-info/licenses/bbarolo/bayesian/nautilus/LICENSE +21 -0
- bbarolo-2.0.1.dist-info/top_level.txt +1 -0
bbarolo/__init__.py
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
"""
|
|
2
|
+
bbarolo: 3D-Barolo (BBarolo) in pure Python.
|
|
3
|
+
|
|
4
|
+
A complete port of the C++ BBarolo code (3D tilted-ring fitting of emission-line
|
|
5
|
+
datacubes and related tools) to Python, accelerated with numpy/scipy/numba.
|
|
6
|
+
|
|
7
|
+
One class per task; each takes a datacube and any BBarolo parameter (the keywords of a
|
|
8
|
+
parameter file, case-insensitive) and runs the same code as the command line. run()
|
|
9
|
+
computes in memory and writes nothing; write() writes the files of the command line:
|
|
10
|
+
|
|
11
|
+
>>> from bbarolo import FitMod3D
|
|
12
|
+
>>> f = FitMod3D("ngc2403.fits", radii=np.arange(15, 1200, 30), xpos=77, ypos=77,
|
|
13
|
+
... vsys=132.8, vrot=120, vdisp=8, z0=10, inc=60, pa=123.7,
|
|
14
|
+
... free="VROT VDISP", mask="SEARCH", threads=4)
|
|
15
|
+
>>> res = f.run()
|
|
16
|
+
>>> res.rings, res.model
|
|
17
|
+
>>> res.write("output/") # or f.write()
|
|
18
|
+
|
|
19
|
+
Tasks: FitMod3D (3DFIT), <!-- windfit -->WindFit (WINDFIT), <!-- /windfit -->SlitFit (SLITFIT), GalMod (GALMOD), GalWind (GALWIND),
|
|
20
|
+
Search (SEARCH), FitMod2D (2DFIT), Ellprof (ELLPROF), Smooth (SMOOTH), SmoothSpec (SMOOTHSPEC),
|
|
21
|
+
Maps (TOTALMAP, VELOCITYMAP, ...), PVSlice (PVSLICE), SpacePar (SPACEPAR),
|
|
22
|
+
Rend3D (REND3D), ContSub (CONTSUB), Stats (STATS), MakeMask (MAKEMASK). The fits (FitMod3D, <!-- windfit -->WindFit, <!-- /windfit -->
|
|
23
|
+
SlitFit) take method= (METHOD): 'classic' (3DFIT only, its default), 'global' (the maximum of the likelihood,
|
|
24
|
+
the default of <!-- windfit -->WindFit and <!-- /windfit -->SlitFit) or 'bayesian' (nested sampling).
|
|
25
|
+
|
|
26
|
+
>>> bbarolo.run("ngc2403.par", threads=8) # a parameter file, as the command line (writes)
|
|
27
|
+
>>> bbarolo.help("free") # one parameter; help("3DFIT"): a task
|
|
28
|
+
|
|
29
|
+
Command line: ``BBarolo -p param.par`` (after pip install), ``python -m bbarolo -p
|
|
30
|
+
param.par``, or the launchers run_bbarolo.py and bin/BBarolo (no install needed).
|
|
31
|
+
|
|
32
|
+
Engines of the fits with METHOD GLOBAL and BAYESIAN, for custom likelihoods and more: Bayesian3DFIT,
|
|
33
|
+
<!-- windfit -->BayesianWind, <!-- /windfit -->BayesianSlitFit (run() follows METHOD; sample() and optimize()).
|
|
34
|
+
|
|
35
|
+
Other tools: GalMod3D (model cubes from 3D fields of the density and velocity of the gas, as
|
|
36
|
+
functions of (R, z), (R, phi, z) or (x, y, z); Python only), DiskModel (the model engine of
|
|
37
|
+
GALMOD, 3DFIT and Bayesian3DFIT: models of a set of Rings on the grid of a Cube, in memory), pv_path, pv_sample, pv_extract (PV
|
|
38
|
+
slices in memory), SimulatedGalaxyCube and emptyfits (utils), Param (all the parameters),
|
|
39
|
+
Cube, Rings. The modules with the computational engines (galmod, galfit, ringmodel,
|
|
40
|
+
search, ...) can also be used directly.
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
from ._version import __version__, __BBBversion__, __cpp_reference__
|
|
44
|
+
from . import _features
|
|
45
|
+
from .tasks import (FitMod3D, SlitFit, GalMod, GalWind, Search, FitMod2D, Ellprof, Smooth, SmoothSpec,
|
|
46
|
+
Maps, PVSlice, SpacePar, Rend3D, ContSub, Stats, MakeMask, run, Result, read_parfile)
|
|
47
|
+
from .keywords import help
|
|
48
|
+
from .params import Param
|
|
49
|
+
from .cube import Cube
|
|
50
|
+
from .rings import Rings
|
|
51
|
+
from .galmod import DiskModel
|
|
52
|
+
from .galmod3d import GalMod3D
|
|
53
|
+
from .pvslice import pv_path, pv_sample, pv_extract
|
|
54
|
+
from .utils import SimulatedGalaxyCube, emptyfits
|
|
55
|
+
from .bbutils import BBaroloError
|
|
56
|
+
|
|
57
|
+
__all__ = ['FitMod3D', 'WindFit', 'SlitFit', 'GalMod', 'GalWind', 'Search', 'FitMod2D', 'Ellprof', 'Smooth',
|
|
58
|
+
'SmoothSpec', 'Maps',
|
|
59
|
+
'PVSlice', 'SpacePar', 'Rend3D', 'ContSub', 'Stats', 'MakeMask', 'Bayesian3DFIT', 'BayesianWind',
|
|
60
|
+
'BayesianSlitFit', 'run',
|
|
61
|
+
'Result', 'read_parfile', 'Param', 'Cube', 'Rings', 'DiskModel', 'GalMod3D', 'pv_path', 'pv_sample',
|
|
62
|
+
'pv_extract', 'SimulatedGalaxyCube', 'emptyfits', 'BBaroloError', '__version__']
|
|
63
|
+
|
|
64
|
+
# WINDFIT is held back from the releases (bbarolo/_features.py): WindFit and BayesianWind only with BBAROLO_WINDFIT=1
|
|
65
|
+
__doc__ = _features.windfit_text(__doc__)
|
|
66
|
+
if _features.WINDFIT:
|
|
67
|
+
from .tasks import WindFit
|
|
68
|
+
else:
|
|
69
|
+
__all__ = [n for n in __all__ if n not in ("WindFit", "BayesianWind")]
|
|
70
|
+
|
|
71
|
+
version = __version__
|
|
72
|
+
BBBversion = __BBBversion__
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
# (help is not in __all__, so that 'from bbarolo import *' does not hide Python's help)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def __getattr__(name):
|
|
79
|
+
# the engines Bayesian3DFIT, BayesianWind and BayesianSlitFit are imported on demand (their samplers are optional
|
|
80
|
+
# dependencies)
|
|
81
|
+
if name == "Bayesian3DFIT":
|
|
82
|
+
from .bayesian import Bayesian3DFIT
|
|
83
|
+
return Bayesian3DFIT
|
|
84
|
+
if name in ("WindFit", "BayesianWind") and not _features.WINDFIT:
|
|
85
|
+
raise AttributeError(f"module 'bbarolo' has no attribute '{name}': {_features.not_available()}")
|
|
86
|
+
if name == "BayesianWind":
|
|
87
|
+
from .bayesian import BayesianWind
|
|
88
|
+
return BayesianWind
|
|
89
|
+
if name == "BayesianSlitFit":
|
|
90
|
+
from .bayesian import BayesianSlitFit
|
|
91
|
+
return BayesianSlitFit
|
|
92
|
+
raise AttributeError(f"module 'bbarolo' has no attribute '{name}'")
|
bbarolo/__main__.py
ADDED
bbarolo/_features.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Features held back from the releases.
|
|
3
|
+
|
|
4
|
+
WINDFIT (the fit of bi-conical winds: the keyword WINDFIT, bbarolo.WindFit, bbarolo.BayesianWind) is in the
|
|
5
|
+
package but off: its keywords are errors, its classes refuse to run, and the help, the docstrings and the
|
|
6
|
+
documentation leave it out. The environment variable BBAROLO_WINDFIT=1, set before bbarolo is imported, turns it
|
|
7
|
+
on: the tests set it (tests/conftest.py), and the documentation built with it shows the pages of WINDFIT
|
|
8
|
+
(BBAROLO_WINDFIT=1 sphinx-build ...).
|
|
9
|
+
|
|
10
|
+
The texts that mention WINDFIT (keywords_doc.py, docstrings, the pages in docs/) mark those parts as
|
|
11
|
+
<!-- windfit -->...<!-- /windfit --> (kept only with WINDFIT on), with an optional text for when it is off:
|
|
12
|
+
<!-- windfit -->on<!-- else -->off<!-- /windfit -->. windfit_text() resolves them; the documentation does the same
|
|
13
|
+
to its pages (docs/conf.py).
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
import os
|
|
17
|
+
import re
|
|
18
|
+
|
|
19
|
+
WINDFIT = os.environ.get("BBAROLO_WINDFIT", "").strip().lower() in ("1", "true", "yes", "on")
|
|
20
|
+
|
|
21
|
+
HIDDEN_TASKS = () if WINDFIT else ("WINDFIT",)
|
|
22
|
+
|
|
23
|
+
_SPAN = re.compile(r"<!--\s*windfit\s*-->(.*?)(?:<!--\s*else\s*-->(.*?))?<!--\s*/windfit\s*-->", re.S)
|
|
24
|
+
|
|
25
|
+
def not_available(what="WINDFIT"):
|
|
26
|
+
return f"{what} is not available in this version of BBarolo."
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def windfit_text(text, on=None):
|
|
30
|
+
"""text with its WINDFIT spans resolved (see the module): with WINDFIT on (on=None: as the environment says),
|
|
31
|
+
the marked text; with it off, the alternative or nothing."""
|
|
32
|
+
if not text:
|
|
33
|
+
return text
|
|
34
|
+
on = WINDFIT if on is None else on
|
|
35
|
+
return _SPAN.sub(lambda m: m.group(1) if on else (m.group(2) or ""), text)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def require_windfit(what="WINDFIT"):
|
|
39
|
+
"""Raise BBaroloError if WINDFIT is off."""
|
|
40
|
+
if not WINDFIT:
|
|
41
|
+
from .bbutils import BBaroloError
|
|
42
|
+
raise BBaroloError(not_available(what))
|
bbarolo/_plotserver.py
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Helper process that runs BBarolo's plotting scripts (started by plotscripts.PlotRunner).
|
|
3
|
+
|
|
4
|
+
It runs as a standalone script in a fresh interpreter (it does not import bbarolo).
|
|
5
|
+
It imports numpy, matplotlib (Agg backend), astropy and scipy once, warms up
|
|
6
|
+
matplotlib's font and mathtext caches, then reads a JSON request from stdin:
|
|
7
|
+
|
|
8
|
+
{"paths": [script, ...], "nproc": N}
|
|
9
|
+
|
|
10
|
+
Each script runs in a child process forked from this one, so the libraries are already
|
|
11
|
+
loaded. This is what makes it faster than starting a new interpreter for every script.
|
|
12
|
+
At most N children run at a time, longest scripts first. The scripts run as with
|
|
13
|
+
``python script.py``: as __main__, with their folder first in sys.path, in the current
|
|
14
|
+
working directory, with stdout/stderr discarded. The reply on stdout is a JSON list
|
|
15
|
+
with one exit code per script, in the order of the request.
|
|
16
|
+
|
|
17
|
+
The libraries are imported while the parent is still preparing the outputs, so the
|
|
18
|
+
cost of importing them is (partly) hidden.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
import os
|
|
22
|
+
import sys
|
|
23
|
+
import json
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _preload():
|
|
27
|
+
os.environ.setdefault("MPLBACKEND", "Agg")
|
|
28
|
+
try:
|
|
29
|
+
import numpy # noqa: F401
|
|
30
|
+
import matplotlib
|
|
31
|
+
matplotlib.use("Agg")
|
|
32
|
+
import matplotlib.pyplot as plt
|
|
33
|
+
import matplotlib.backends.backend_pdf # noqa: F401
|
|
34
|
+
import matplotlib.backends.backend_agg # noqa: F401
|
|
35
|
+
from matplotlib.colorbar import ColorbarBase # noqa: F401
|
|
36
|
+
import matplotlib.gridspec # noqa: F401
|
|
37
|
+
import astropy.io.fits # noqa: F401
|
|
38
|
+
import astropy.visualization # noqa: F401
|
|
39
|
+
import scipy.ndimage # noqa: F401
|
|
40
|
+
import scipy.interpolate # noqa: F401
|
|
41
|
+
except Exception: # the scripts import what they need
|
|
42
|
+
return
|
|
43
|
+
try:
|
|
44
|
+
# Warm-up: font lookups, glyph caches, mathtext parser and PDF writer, with the
|
|
45
|
+
# settings used by the scripts. rcParams are restored afterwards.
|
|
46
|
+
import io
|
|
47
|
+
with matplotlib.rc_context():
|
|
48
|
+
plt.rc('font', family='sans-serif', serif='Helvetica', size=13)
|
|
49
|
+
plt.rcParams.update({'text.usetex': False, 'mathtext.fontset': 'cm', 'mathtext.default': 'regular'})
|
|
50
|
+
fig = plt.figure(figsize=(2, 2))
|
|
51
|
+
ax = fig.add_subplot(111)
|
|
52
|
+
ax.plot([0, 1], [0, 1])
|
|
53
|
+
ax.contour([[0., 1.], [1., 2.]], [0.5, 1.5])
|
|
54
|
+
ax.set_xlabel(r'$\mathrm{\Delta V_{LOS}}$ (km/s) 0123456789.-')
|
|
55
|
+
ax.set_title(r'$\theta$ = 0$^\circ$ $\sigma_\mathrm{gas}$')
|
|
56
|
+
fig.savefig(io.BytesIO(), format='pdf', bbox_inches='tight')
|
|
57
|
+
plt.close(fig)
|
|
58
|
+
except Exception:
|
|
59
|
+
pass
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _run_child(path):
|
|
63
|
+
"""Body of a forked child: run the script as __main__, then exit (never returns)."""
|
|
64
|
+
code = 1
|
|
65
|
+
try:
|
|
66
|
+
devnull = os.open(os.devnull, os.O_WRONLY)
|
|
67
|
+
os.dup2(devnull, 1)
|
|
68
|
+
os.dup2(devnull, 2)
|
|
69
|
+
import runpy
|
|
70
|
+
sys.argv = [path]
|
|
71
|
+
sys.path.insert(0, os.path.dirname(os.path.abspath(path)))
|
|
72
|
+
runpy.run_path(path, run_name="__main__")
|
|
73
|
+
code = 0
|
|
74
|
+
except SystemExit as e:
|
|
75
|
+
code = e.code if isinstance(e.code, int) else (0 if e.code is None else 1)
|
|
76
|
+
except BaseException:
|
|
77
|
+
code = 1
|
|
78
|
+
finally:
|
|
79
|
+
try:
|
|
80
|
+
sys.stdout.flush()
|
|
81
|
+
sys.stderr.flush()
|
|
82
|
+
except Exception:
|
|
83
|
+
pass
|
|
84
|
+
os._exit(code)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
# scripts that usually take longest are started first
|
|
88
|
+
_ORDER = ("pvslices", "chanmaps", "kinmaps", "pvs", "parameters")
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _priority(path):
|
|
92
|
+
name = os.path.basename(path)
|
|
93
|
+
for i, key in enumerate(_ORDER):
|
|
94
|
+
if key in name:
|
|
95
|
+
return i
|
|
96
|
+
return len(_ORDER)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def run(paths, nproc):
|
|
100
|
+
codes = [1] * len(paths)
|
|
101
|
+
queue = sorted(range(len(paths)), key=lambda i: _priority(paths[i]))
|
|
102
|
+
running = {}
|
|
103
|
+
nproc = max(1, int(nproc))
|
|
104
|
+
while queue or running:
|
|
105
|
+
while queue and len(running) < nproc:
|
|
106
|
+
i = queue.pop(0)
|
|
107
|
+
sys.stdout.flush()
|
|
108
|
+
sys.stderr.flush()
|
|
109
|
+
pid = os.fork()
|
|
110
|
+
if pid == 0:
|
|
111
|
+
_run_child(paths[i])
|
|
112
|
+
running[pid] = i
|
|
113
|
+
pid, status = os.waitpid(-1, 0)
|
|
114
|
+
if pid in running:
|
|
115
|
+
i = running.pop(pid)
|
|
116
|
+
codes[i] = os.waitstatus_to_exitcode(status) if hasattr(os, "waitstatus_to_exitcode") else status
|
|
117
|
+
return codes
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def main():
|
|
121
|
+
_preload()
|
|
122
|
+
req = sys.stdin.read()
|
|
123
|
+
if not req.strip(): # nothing to do (e.g. the parent gave up)
|
|
124
|
+
return 0
|
|
125
|
+
req = json.loads(req)
|
|
126
|
+
paths = req.get("paths", [])
|
|
127
|
+
nproc = req.get("nproc") or os.cpu_count() or 1
|
|
128
|
+
codes = run(paths, min(nproc, max(len(paths), 1)))
|
|
129
|
+
sys.stdout.write(json.dumps(codes))
|
|
130
|
+
sys.stdout.flush()
|
|
131
|
+
return 0
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
if __name__ == "__main__":
|
|
135
|
+
sys.exit(main())
|
bbarolo/_rng.py
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Fast random numbers for the compiled kernels: xoroshiro128+ uniform generator
|
|
3
|
+
(seeded with splitmix64) and Marsaglia & Tsang's ziggurat for normal deviates.
|
|
4
|
+
|
|
5
|
+
They are ~5-10x faster than numba's np.random and, since the state is an explicit
|
|
6
|
+
array, each model evaluation has its own reproducible stream (seeded by ISEED),
|
|
7
|
+
independently of the thread that computes it.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import math
|
|
11
|
+
import numpy as np
|
|
12
|
+
import numba as nb
|
|
13
|
+
|
|
14
|
+
_U64 = np.uint64
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _zig_tables():
|
|
18
|
+
dn = 3.442619855899
|
|
19
|
+
tn = dn
|
|
20
|
+
vn = 9.91256303526217e-3
|
|
21
|
+
m1 = 2147483648.0
|
|
22
|
+
kn = np.zeros(128, np.int64)
|
|
23
|
+
wn = np.zeros(128, np.float64)
|
|
24
|
+
fn = np.zeros(128, np.float64)
|
|
25
|
+
q = vn / math.exp(-.5 * dn * dn)
|
|
26
|
+
kn[0] = int((dn / q) * m1)
|
|
27
|
+
kn[1] = 0
|
|
28
|
+
wn[0] = q / m1
|
|
29
|
+
wn[127] = dn / m1
|
|
30
|
+
fn[0] = 1.
|
|
31
|
+
fn[127] = math.exp(-.5 * dn * dn)
|
|
32
|
+
for i in range(126, 0, -1):
|
|
33
|
+
dn = math.sqrt(-2. * math.log(vn / dn + math.exp(-.5 * dn * dn)))
|
|
34
|
+
kn[i + 1] = int((dn / tn) * m1)
|
|
35
|
+
tn = dn
|
|
36
|
+
fn[i] = math.exp(-.5 * dn * dn)
|
|
37
|
+
wn[i] = dn / m1
|
|
38
|
+
return kn, wn, fn
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
KN, WN, FN = _zig_tables()
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@nb.njit(inline="always", cache=True)
|
|
45
|
+
def _rotl(x, k):
|
|
46
|
+
return (x << _U64(k)) | (x >> _U64(64 - k))
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@nb.njit(cache=True)
|
|
50
|
+
def rng_init(seed):
|
|
51
|
+
"""Return a xoroshiro128+ state (2 x uint64) initialised from an integer seed."""
|
|
52
|
+
s = np.empty(2, np.uint64)
|
|
53
|
+
z = _U64(seed) + _U64(0x9E3779B97F4A7C15)
|
|
54
|
+
for i in range(2):
|
|
55
|
+
z = z + _U64(0x9E3779B97F4A7C15)
|
|
56
|
+
x = z
|
|
57
|
+
x = (x ^ (x >> _U64(30))) * _U64(0xBF58476D1CE4E5B9)
|
|
58
|
+
x = (x ^ (x >> _U64(27))) * _U64(0x94D049BB133111EB)
|
|
59
|
+
x = x ^ (x >> _U64(31))
|
|
60
|
+
s[i] = x
|
|
61
|
+
if s[0] == 0 and s[1] == 0:
|
|
62
|
+
s[0] = _U64(1)
|
|
63
|
+
return s
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@nb.njit(inline="always", cache=True)
|
|
67
|
+
def rng_next(s):
|
|
68
|
+
s0 = s[0]
|
|
69
|
+
s1 = s[1]
|
|
70
|
+
result = s0 + s1
|
|
71
|
+
s1 ^= s0
|
|
72
|
+
s[0] = _rotl(s0, 24) ^ s1 ^ (s1 << _U64(16))
|
|
73
|
+
s[1] = _rotl(s1, 37)
|
|
74
|
+
return result
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
@nb.njit(inline="always", cache=True)
|
|
78
|
+
def rng_uniform(s):
|
|
79
|
+
"""Uniform deviate in [0,1)."""
|
|
80
|
+
return (rng_next(s) >> _U64(11)) * (1.0 / 9007199254740992.0)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
@nb.njit(inline="always", cache=True)
|
|
84
|
+
def rng_normal(s):
|
|
85
|
+
"""Standard normal deviate (Marsaglia & Tsang ziggurat, fully inlined)."""
|
|
86
|
+
while True:
|
|
87
|
+
hz = np.int64(rng_next(s) >> _U64(32)) - 2147483648
|
|
88
|
+
iz = hz & 127
|
|
89
|
+
if abs(hz) < KN[iz]:
|
|
90
|
+
return hz * WN[iz]
|
|
91
|
+
x = hz * WN[iz]
|
|
92
|
+
if iz == 0:
|
|
93
|
+
while True:
|
|
94
|
+
xx = -math.log(1.0 - rng_uniform(s)) * 0.2904764
|
|
95
|
+
yy = -math.log(1.0 - rng_uniform(s))
|
|
96
|
+
if yy + yy >= xx * xx:
|
|
97
|
+
break
|
|
98
|
+
return 3.442620 + xx if hz > 0 else -3.442620 - xx
|
|
99
|
+
if FN[iz] + rng_uniform(s) * (FN[iz - 1] - FN[iz]) < math.exp(-.5 * x * x):
|
|
100
|
+
return x
|
bbarolo/_version.py
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Bayesian BBarolo (BBB): fit a 3D tilted-ring model to a datacube by sampling the
|
|
3
|
+
posterior distribution of the ring parameters with nested sampling (nautilus, included in
|
|
4
|
+
nautilus/, or dynesty). Pure-Python port of bayesian.py of the original C++-based pyBBarolo (BBB 0.2).
|
|
5
|
+
|
|
6
|
+
The interface follows the other bbarolo tasks (it builds on bbarolo.FitMod3D): the
|
|
7
|
+
cube and any BBarolo parameter are given to the constructor, the rings with the usual
|
|
8
|
+
keywords (radii or nradii/radsep, xpos, ypos, vsys, vrot, vdisp, inc, pa, z0, vrad, dens,
|
|
9
|
+
...; single values or one value per ring; the values not given are estimated or set as in 3DFIT):
|
|
10
|
+
|
|
11
|
+
>>> from bbarolo import Bayesian3DFIT
|
|
12
|
+
>>> f = Bayesian3DFIT("ngc2403.fits", radii=np.arange(30,600,60), xpos=77, ypos=77,
|
|
13
|
+
... vsys=132.8, vrot=120, vdisp=10, inc=60, pa=123.7, z0=10,
|
|
14
|
+
... mask="SEARCH", outfolder="output/bbb")
|
|
15
|
+
>>> f.priors['vrot'] = dict(name='uniform', loc=0, scale=300) # optional
|
|
16
|
+
>>> f.run(freepar=['vrot','vdisp_single','inc_single'], method='dynesty', threads=4)
|
|
17
|
+
>>> f.print_stats(); f.write_bestmodel(); f.corner_plot()
|
|
18
|
+
|
|
19
|
+
Parameter files (``BBarolo -p``, ``bbarolo.run``): the task 3DFIT with METHOD GLOBAL or BAYESIAN, with the free
|
|
20
|
+
parameters in FREE (e.g. VROT VDISP PA_SINGLE INC_SINGLE RADMAX; by default VROT VDISP and the
|
|
21
|
+
geometry, Z0, RADMAX and FRACERR), the priors in PRIORS (e.g.
|
|
22
|
+
VROT=(uniform,loc=0,scale=250) INC=(norm,60,5)), and SAMPLER, SAMPLEROPTS, RUNOPTS and
|
|
23
|
+
THREADS; it samples, writes the outputs and the samples, prints the statistics (VERBOSE)
|
|
24
|
+
and makes the plots (PLOTS): see run_task and Bayesian3DFIT.write. These keywords are accepted by Bayesian3DFIT
|
|
25
|
+
too (defaults of run()), and Bayesian3DFIT.from_parfile reads a parameter file.
|
|
26
|
+
|
|
27
|
+
Free parameters are given as names: 'vrot' (one value per ring), 'vrot_single' (one value
|
|
28
|
+
for all rings), 'vrot_func' (parametric function of radius, see ``funcs``), plus
|
|
29
|
+
'sigma' (noise of the likelihood; default prior log-uniform between 0.5 and 1000 times the
|
|
30
|
+
measured noise), 'fracerr' (fractional model error: the variance of a voxel is
|
|
31
|
+
sigma^2 + (fracerr*model)^2) and 'radmax' (the outer edge of the disk; like_kwargs radmax='ring'
|
|
32
|
+
moves the last ring instead, as in the original module). Priors are frozen scipy.stats
|
|
33
|
+
distributions (``priors`` dictionary or ``prior_distr``). The default priors follow the initial
|
|
34
|
+
rings, given or estimated as in 3DFIT (e.g. INC +- 10 deg, PA +- 15 deg, VROT 0 to twice the
|
|
35
|
+
largest initial VROT; see Bayesian3DFIT._set_default_priors and the keyword PRIORS).
|
|
36
|
+
|
|
37
|
+
The options of the likelihood are given in run(like_kwargs=...) (LIKEOPTS in parameter files;
|
|
38
|
+
the options of the fit are in f.like_kwargs): likemask, dilation, noisecorr, densprof_smooth,
|
|
39
|
+
bbres (BBarolo's 3DFIT residuals), radmax and radmax_width (what RADMAX is), sigma and fracerr
|
|
40
|
+
(fixed values) and smooth (the smoothness priors of the profiles free in each ring).
|
|
41
|
+
|
|
42
|
+
Correlated noise: the log-likelihood is multiplied by 1/(number of voxels per independent
|
|
43
|
+
measurement). By default (noisecorr='measured') this is the correlation volume of the noise
|
|
44
|
+
(spatial x spectral), measured from the voxels without emission (see noise_correlation), and
|
|
45
|
+
conservative: at least one beam area spatially, and summed over the positive core of the
|
|
46
|
+
autocorrelation where it has negative lobes (the noise of synthesis images);
|
|
47
|
+
noisecorr='beam' uses the beam area in pixels instead, and noisecorr=<number> sets it.
|
|
48
|
+
|
|
49
|
+
Voxels of the likelihood (likemask): 'dilated' (default) compares the model with the data,
|
|
50
|
+
not masked, in the mask dilated by one beam and three channels (dilation); 'none' with the
|
|
51
|
+
data in all the voxels of the likelihood region (see _setup_likemask). The original module
|
|
52
|
+
compared it with the data times the mask (zero below the threshold of the mask), which
|
|
53
|
+
penalised the faint model emission outside the mask and biased the fits.
|
|
54
|
+
|
|
55
|
+
Density profile when DENS is not fitted: the densities whose beam-convolved model reproduces
|
|
56
|
+
the total intensity map (non-negative least squares with a smoothness term, densprof_smooth;
|
|
57
|
+
see _deconvolved_profile), with errors (deconvolved_profile_errors). The original module used
|
|
58
|
+
the average of the observed map in each ring (Ellprof), which is smoothed by the beam twice
|
|
59
|
+
(by the data and by the model); that profile is now only an output (<prefix>_densprof.txt).
|
|
60
|
+
|
|
61
|
+
Differences from the original module (other than running without the C++ library):
|
|
62
|
+
* the interface of the bbarolo tasks: Bayesian3DFIT(cube, **params), update(**params)
|
|
63
|
+
and run(freepar=..., ...) replace init(), set_options() and compute();
|
|
64
|
+
run_geometry() replaces compute_geometry(). The model engine always uses one thread
|
|
65
|
+
(and TWOSTAGE is off); run(threads=n) samples with n processes (default 1, or THREADS
|
|
66
|
+
if given);
|
|
67
|
+
* a model evaluation is ~3x faster (pure-Python GALMOD/convolution engine, compiled
|
|
68
|
+
residual kernel, empty channels skipped in the convolution);
|
|
69
|
+
* parallel sampling (``threads>1``) uses a fork-based process pool whose workers
|
|
70
|
+
inherit the fitter, so nothing big is pickled and it also works on macOS (where the
|
|
71
|
+
default 'spawn' start method broke the original global-function approach). Under MPI,
|
|
72
|
+
schwimmbad's MPIPool is used as before;
|
|
73
|
+
* the models are ANALYTIC by default (GALMODTYPE=MC for the Monte-Carlo models): the
|
|
74
|
+
likelihood has no Monte-Carlo noise, and is about twice faster;
|
|
75
|
+
* the likelihood uses the measured noise per voxel when 'sigma' is not fitted (instead
|
|
76
|
+
of sigma=1 in the units of the data), is multiplied by 1/(correlation volume of the
|
|
77
|
+
noise) (each independent noise measurement counts once; noisecorr='beam' uses the beam
|
|
78
|
+
area in pixels), and is computed in a fixed region (independent of the box of the
|
|
79
|
+
model); with 'sigma' free, the normalisation counts all the voxels; 'fracerr' adds
|
|
80
|
+
a model error proportional to the model; the data are not masked (likemask) and the
|
|
81
|
+
density profile is corrected for the beam. The credible intervals are thus uncertainties in
|
|
82
|
+
physical units. like_kwargs=dict(sigma=1, noisecorr=1) gives the noise conventions of the
|
|
83
|
+
original module (sigma = 1 in the units of the data, independent voxels);
|
|
84
|
+
* fixed: ``compute(verbose=...)`` raised a TypeError; ``useBBres=True`` returned an
|
|
85
|
+
undefined variable; ``write_bestmodel`` called a missing ``_normalize_model``;
|
|
86
|
+
``plot_profiles`` failed unless all nine parameters were free and did not handle
|
|
87
|
+
parametric ('_func') parameters; ``write_bestmodel`` failed with the density fitted;
|
|
88
|
+
``save_results``/``load_results`` now also work with nautilus;
|
|
89
|
+
* the posterior errors are written in <prefix>_rings_final1.txt (as the 3DFIT error columns) and
|
|
90
|
+
shown in the _parameters.pdf plot of write_bestmodel.
|
|
91
|
+
|
|
92
|
+
The package: fitter.py (Bayesian3DFIT: parameters, rings, priors, setup, run), likelihood.py (the
|
|
93
|
+
voxels, the region and the noise of the likelihood, the log-likelihoods), density.py (the deconvolved
|
|
94
|
+
density profile), sampling.py (nautilusbb, nautilus, dynesty and the process pool), outputs.py (files,
|
|
95
|
+
plots, statistics, save and load), noise.py (the correlation of the noise), rings.py, task.py
|
|
96
|
+
(3DFIT, METHOD GLOBAL or BAYESIAN), nautilus/ (the copy of nautilus 1.0.6 of SAMPLER NAUTILUSBB, MIT licence).
|
|
97
|
+
"""
|
|
98
|
+
|
|
99
|
+
########################################################################
|
|
100
|
+
# Copyright (C) 2024 Enrico Di Teodoro
|
|
101
|
+
# This program is free software: you can redistribute it and/or modify
|
|
102
|
+
# it under the terms of the GNU General Public License as published by
|
|
103
|
+
# the Free Software Foundation, either version 3 of the License, or
|
|
104
|
+
# (at your option) any later version.
|
|
105
|
+
########################################################################
|
|
106
|
+
|
|
107
|
+
from .fitter import Bayesian3DFIT
|
|
108
|
+
from .wind import BayesianWind
|
|
109
|
+
from .slit import BayesianSlitFit
|
|
110
|
+
from .noise import noise_correlation, dilate_mask
|
|
111
|
+
from .task import run_task, write_task
|
|
112
|
+
|
|
113
|
+
__all__ = ["Bayesian3DFIT", "BayesianWind", "BayesianSlitFit", "noise_correlation", "dilate_mask", "run_task", "write_task"]
|