lfit-python 0.1.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.
- lfit_python/__init__.py +27 -0
- lfit_python/chains.py +157 -0
- lfit_python/cli/__init__.py +1 -0
- lfit_python/cli/limbdark.py +64 -0
- lfit_python/cli/mcmcfit.py +168 -0
- lfit_python/cli/physparams.py +154 -0
- lfit_python/cli/reddening.py +50 -0
- lfit_python/cli/summary.py +78 -0
- lfit_python/cli/update_input.py +65 -0
- lfit_python/cli/watch.py +39 -0
- lfit_python/cli/wdparams.py +223 -0
- lfit_python/cv_model.py +864 -0
- lfit_python/data/Bergeron/README +7 -0
- lfit_python/data/Bergeron/Table_DA +257 -0
- lfit_python/data/Bergeron/Table_DA_sdss +307 -0
- lfit_python/data/Bergeron/Table_DB +312 -0
- lfit_python/data/Bergeron/color_correction_tables/color_corrections_HCAM-GTC-super_minus_ntt_ucam.csv +1067 -0
- lfit_python/data/Bergeron/color_correction_tables/color_corrections_HCAM-GTC-super_minus_tnt_uspec.csv +1067 -0
- lfit_python/data/Gianninas13/ld_coeffs_g.txt +654 -0
- lfit_python/data/Gianninas13/ld_coeffs_i.txt +654 -0
- lfit_python/data/Gianninas13/ld_coeffs_r.txt +654 -0
- lfit_python/data/Gianninas13/ld_coeffs_u.txt +654 -0
- lfit_python/data/Gianninas13/ld_coeffs_z.txt +654 -0
- lfit_python/data/Gianninas13/radial_bright_profiles.txt +6925 -0
- lfit_python/data/Hamada/mr_hamada.dat +1307 -0
- lfit_python/data/Panei/12C-MR-H-He/12C-MR-H-He.dat +387 -0
- lfit_python/data/Panei/12C-MR-H-He/12C-MR-H-He.saver +750 -0
- lfit_python/data/Panei/12C-MR-He/12C-MR-He.dat +431 -0
- lfit_python/data/Panei/HS/04He-H-S.dat +158 -0
- lfit_python/data/Panei/HS/12C-H-S.dat +158 -0
- lfit_python/data/Panei/HS/16O-H-S.dat +158 -0
- lfit_python/data/Panei/HS/28Si-H-S.dat +158 -0
- lfit_python/data/Panei/HS/56Fe-H-S.dat +158 -0
- lfit_python/data/Panei/othercores/04He-MR-H.dat +91 -0
- lfit_python/data/Panei/othercores/16O-MR-H-He.dat +602 -0
- lfit_python/data/Panei/othercores/28Si-MR-H-He.dat +386 -0
- lfit_python/data/Panei/othercores/56Fe-MR-H-He.dat +390 -0
- lfit_python/data/Panei/othercores/old/04He-MR-H.save +120 -0
- lfit_python/data/Panei/othercores/old/04He-MR.save +130 -0
- lfit_python/data/Panei/othercores/old/16O-MR-H-He.save +602 -0
- lfit_python/data/Panei/othercores/old/16O-MR-He.save +469 -0
- lfit_python/data/Panei/othercores/old/28Si-MR-H-He.save +386 -0
- lfit_python/data/Panei/othercores/old/28Si-MR-He.save +402 -0
- lfit_python/data/Panei/othercores/old/56Fe-MR-H-He.save +633 -0
- lfit_python/data/Panei/othercores/old/56Fe-MR-He.save +537 -0
- lfit_python/data/Wood95/co040.2.04dt1 +80 -0
- lfit_python/data/Wood95/co050.2.04dt1 +82 -0
- lfit_python/data/Wood95/co060.2.04dt1 +85 -0
- lfit_python/data/Wood95/co070.2.04dt1 +91 -0
- lfit_python/data/Wood95/co080.2.04dt1 +100 -0
- lfit_python/data/Wood95/co090.2.04dt1 +99 -0
- lfit_python/data/Wood95/co100.2.04dt1 +100 -0
- lfit_python/data/althaus/readme.tex +12 -0
- lfit_python/data/althaus/t106.one +1132 -0
- lfit_python/data/althaus/t108.one +679 -0
- lfit_python/data/althaus/t110.one +821 -0
- lfit_python/data/althaus/t112.one +239 -0
- lfit_python/data/althaus/t114.one +355 -0
- lfit_python/data/althaus/t116.one +353 -0
- lfit_python/data/althaus/t118.one +356 -0
- lfit_python/data/althaus/t120.one +882 -0
- lfit_python/data/althaus/t122.one +901 -0
- lfit_python/data/althaus/t124.one +913 -0
- lfit_python/data/althaus/t126.one +739 -0
- lfit_python/data/althaus/t128.one +665 -0
- lfit_python/data/althaus/t130.one +626 -0
- lfit_python/likelihood.py +26 -0
- lfit_python/limbdark.py +47 -0
- lfit_python/model.py +801 -0
- lfit_python/physical_params.py +279 -0
- lfit_python/plotting.py +364 -0
- lfit_python/priors.py +51 -0
- lfit_python/sampling.py +472 -0
- lfit_python/summary.py +327 -0
- lfit_python/watch_app.py +1001 -0
- lfit_python/wdparams.py +587 -0
- lfit_python-0.1.0.dist-info/METADATA +222 -0
- lfit_python-0.1.0.dist-info/RECORD +81 -0
- lfit_python-0.1.0.dist-info/WHEEL +5 -0
- lfit_python-0.1.0.dist-info/entry_points.txt +9 -0
- lfit_python-0.1.0.dist-info/top_level.txt +1 -0
lfit_python/sampling.py
ADDED
|
@@ -0,0 +1,472 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Helper functions for the MCMC nuts and bolts: starting walkers, running the
|
|
3
|
+
emcee sampler, and convergence diagnostics.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import emcee
|
|
7
|
+
import numpy as np
|
|
8
|
+
|
|
9
|
+
# lightweight progress bar
|
|
10
|
+
from tqdm import tqdm
|
|
11
|
+
|
|
12
|
+
from .likelihood import ln_prior, ln_prob
|
|
13
|
+
from .model import extract_par_and_key
|
|
14
|
+
|
|
15
|
+
TINY = -np.inf
|
|
16
|
+
|
|
17
|
+
# Relative scatter applied to each kind of parameter when starting walkers
|
|
18
|
+
# with ``per_parameter=True`` (the ``comp_scat`` option in the input file).
|
|
19
|
+
SCATTER_FACTORS = {
|
|
20
|
+
"ln_ampin_gp": 5.0,
|
|
21
|
+
"ln_ampout_gp": 5.0,
|
|
22
|
+
"tau_gp": 5.0,
|
|
23
|
+
"q": 1,
|
|
24
|
+
"rwd": 1,
|
|
25
|
+
"dphi": 0.2,
|
|
26
|
+
"dFlux": 1,
|
|
27
|
+
"sFlux": 1,
|
|
28
|
+
"wdFlux": 1,
|
|
29
|
+
"rsFlux": 1,
|
|
30
|
+
"rdisc": 1,
|
|
31
|
+
"ulimb": 1e-6,
|
|
32
|
+
"scale": 1,
|
|
33
|
+
"fis": 1,
|
|
34
|
+
"dexp": 1,
|
|
35
|
+
"phi0": 1,
|
|
36
|
+
"az": 1,
|
|
37
|
+
"exp1": 1,
|
|
38
|
+
"exp2": 1,
|
|
39
|
+
"yaw": 1,
|
|
40
|
+
"tilt": 1,
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
# Parameters that are naturally close to zero are scattered by a fixed amount,
|
|
44
|
+
# ``scatter * scale``, instead of a fraction of their value (which would give
|
|
45
|
+
# no scatter at all for a starting value of 0). E.g. a scatter of 0.1 spreads
|
|
46
|
+
# az and yaw by 10 degrees and phi0 by 0.001 in phase.
|
|
47
|
+
ABSOLUTE_SCATTER_SCALES = {
|
|
48
|
+
"az": 100.0,
|
|
49
|
+
"yaw": 100.0,
|
|
50
|
+
"phi0": 0.01,
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def fracWithin(pdf, val):
|
|
55
|
+
return pdf[pdf >= val].sum()
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def initialise_walkers(p, scatter, nwalkers, ln_prob, model):
|
|
59
|
+
"""Start ``nwalkers`` walkers in a ball around ``p``.
|
|
60
|
+
|
|
61
|
+
``scatter`` is the standard deviation of the ball for each parameter
|
|
62
|
+
(see ``walker_scatter``). Walkers where ``ln_prob(walker, model)`` is not
|
|
63
|
+
finite are moved near randomly chosen valid walkers until all are valid.
|
|
64
|
+
"""
|
|
65
|
+
print("\n\nInitialising walkers")
|
|
66
|
+
|
|
67
|
+
# Create starting ball of walkers with a certain amount of scatter
|
|
68
|
+
p0 = np.array(emcee.utils.sample_ball(p, scatter, size=nwalkers))
|
|
69
|
+
|
|
70
|
+
print("Checking initial walker ball for invalid locations...")
|
|
71
|
+
ln_probs = [ln_prob(p, model) for p in p0]
|
|
72
|
+
print("Done!")
|
|
73
|
+
isValid = np.isfinite(ln_probs)
|
|
74
|
+
whereInvalid = np.where(~isValid)[0] # Only take the 0th dimension
|
|
75
|
+
numInvalid = np.sum(~isValid)
|
|
76
|
+
|
|
77
|
+
print("My naiive walker ball has {} invalid walkers.".format(np.sum(~isValid)))
|
|
78
|
+
|
|
79
|
+
# All invalid params need to be resampled
|
|
80
|
+
while numInvalid > 0:
|
|
81
|
+
# Create a mask of invalid params
|
|
82
|
+
## TODO: Thread this?
|
|
83
|
+
print(
|
|
84
|
+
"Getting priors and probs for {} previously bad walkers...".format(
|
|
85
|
+
numInvalid
|
|
86
|
+
)
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
# ln_prob = lnlike + lnprob. Only check walkers that are invalid
|
|
90
|
+
# check walkers that were previously found to be bad, and update those.
|
|
91
|
+
for i, loc in enumerate(whereInvalid):
|
|
92
|
+
# print("getting ln_prob of value at location {}".format(loc))
|
|
93
|
+
isValid[loc] = np.isfinite(ln_prob(p0[loc], model))
|
|
94
|
+
print(" {}/{}".format(i + 1, numInvalid), end="\r")
|
|
95
|
+
print()
|
|
96
|
+
whereInvalid = np.where(~isValid)[0]
|
|
97
|
+
|
|
98
|
+
# Determine the number of good and bad walkers
|
|
99
|
+
numInvalid = np.sum(~isValid)
|
|
100
|
+
ngood = len(p0[isValid])
|
|
101
|
+
if numInvalid:
|
|
102
|
+
print(
|
|
103
|
+
"Now, I have {} bad walkers. Rescattering those...".format(numInvalid)
|
|
104
|
+
)
|
|
105
|
+
else:
|
|
106
|
+
print("No more invalid walkers!")
|
|
107
|
+
|
|
108
|
+
# Choose nbad random rows from ngood walker sample
|
|
109
|
+
replacement_rows = np.random.randint(ngood, size=numInvalid)
|
|
110
|
+
# Create replacement values from valid walkers
|
|
111
|
+
replacements = p0[isValid][replacement_rows]
|
|
112
|
+
# Add scatter to replacement values
|
|
113
|
+
replacements += (
|
|
114
|
+
0.5 * scatter * np.random.normal(size=replacements.shape)
|
|
115
|
+
)
|
|
116
|
+
# Replace invalid walkers with new values
|
|
117
|
+
p0[~isValid] = replacements
|
|
118
|
+
|
|
119
|
+
print()
|
|
120
|
+
|
|
121
|
+
return p0
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def walker_scatter(names, values, scatter, per_parameter=False):
|
|
125
|
+
"""Standard deviation of the starting ball for each parameter.
|
|
126
|
+
|
|
127
|
+
Most parameters are scattered by ``scatter * |value|``. Those in
|
|
128
|
+
``ABSOLUTE_SCATTER_SCALES`` are scattered by ``scatter * scale`` instead,
|
|
129
|
+
because they are naturally close to zero.
|
|
130
|
+
|
|
131
|
+
If ``per_parameter`` is True (the ``comp_scat`` input option), the scatter
|
|
132
|
+
is also multiplied by the factor for each kind of parameter in
|
|
133
|
+
``SCATTER_FACTORS``. GP parameters whose names start with "ln" are not.
|
|
134
|
+
|
|
135
|
+
Inputs:
|
|
136
|
+
-------
|
|
137
|
+
names: list of str
|
|
138
|
+
Parameter names, e.g. ``model.dynasty_par_names``.
|
|
139
|
+
values: array
|
|
140
|
+
Parameter values to scatter around.
|
|
141
|
+
scatter: float
|
|
142
|
+
Fractional scatter, e.g. ``first_scatter`` in the input file.
|
|
143
|
+
per_parameter: bool
|
|
144
|
+
Apply ``SCATTER_FACTORS``.
|
|
145
|
+
"""
|
|
146
|
+
sigma = []
|
|
147
|
+
for name, value in zip(names, values):
|
|
148
|
+
# Get the parameter of this parName, striping off the node encoding
|
|
149
|
+
key, _ = extract_par_and_key(name)
|
|
150
|
+
if key in ABSOLUTE_SCATTER_SCALES:
|
|
151
|
+
s = scatter * ABSOLUTE_SCATTER_SCALES[key]
|
|
152
|
+
else:
|
|
153
|
+
s = scatter * abs(value)
|
|
154
|
+
# Skip the GP params
|
|
155
|
+
if per_parameter and not key.startswith("ln"):
|
|
156
|
+
s *= SCATTER_FACTORS.get(key, 1.0)
|
|
157
|
+
sigma.append(s)
|
|
158
|
+
return np.array(sigma)
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def run_emcee(
|
|
162
|
+
model,
|
|
163
|
+
p_0,
|
|
164
|
+
nwalkers,
|
|
165
|
+
nburn,
|
|
166
|
+
nprod,
|
|
167
|
+
scatter_1,
|
|
168
|
+
scatter_2=None,
|
|
169
|
+
per_parameter_scatter=False,
|
|
170
|
+
double_burnin=False,
|
|
171
|
+
pool=None,
|
|
172
|
+
alt_moves=False,
|
|
173
|
+
extend=False,
|
|
174
|
+
chain_fname="chain_prod.h5",
|
|
175
|
+
log_prob_fn=ln_prob,
|
|
176
|
+
log_prior_fn=ln_prior,
|
|
177
|
+
):
|
|
178
|
+
"""Run burn-in and production phases of an emcee fit to ``model``.
|
|
179
|
+
|
|
180
|
+
The production chain is written to the HDF5 file ``chain_fname``.
|
|
181
|
+
|
|
182
|
+
Inputs:
|
|
183
|
+
-------
|
|
184
|
+
model: Node
|
|
185
|
+
The model; passed as the only extra argument to ``log_prob_fn``.
|
|
186
|
+
Its ``dynasty_par_names`` name the parameters in ``p_0``.
|
|
187
|
+
p_0: array
|
|
188
|
+
Starting parameter vector.
|
|
189
|
+
nwalkers, nburn, nprod: int
|
|
190
|
+
Number of walkers, burn-in steps and production steps.
|
|
191
|
+
scatter_1, scatter_2: float
|
|
192
|
+
Fractional scatter of the starting ball for the first and (if
|
|
193
|
+
``double_burnin``) second burn-in phases. See ``walker_scatter``.
|
|
194
|
+
per_parameter_scatter: bool
|
|
195
|
+
Scale the scatter of each kind of parameter by ``SCATTER_FACTORS``.
|
|
196
|
+
double_burnin: bool
|
|
197
|
+
Run a second burn-in, restarted around the best walker of the first.
|
|
198
|
+
pool: optional
|
|
199
|
+
A pool with a ``map`` method, passed to emcee.
|
|
200
|
+
alt_moves: bool
|
|
201
|
+
Use differential evolution moves instead of the default stretch move.
|
|
202
|
+
extend: bool
|
|
203
|
+
Skip burn-in and continue the chain already in ``chain_fname``.
|
|
204
|
+
|
|
205
|
+
Returns:
|
|
206
|
+
--------
|
|
207
|
+
emcee.EnsembleSampler
|
|
208
|
+
"""
|
|
209
|
+
npars = len(p_0)
|
|
210
|
+
if double_burnin and not extend and scatter_2 is None:
|
|
211
|
+
raise ValueError("double_burnin needs scatter_2")
|
|
212
|
+
|
|
213
|
+
backend = emcee.backends.HDFBackend(chain_fname)
|
|
214
|
+
if not extend:
|
|
215
|
+
# reset backend, overwriting existing chain if needs be
|
|
216
|
+
backend.reset(nwalkers, npars)
|
|
217
|
+
|
|
218
|
+
# Create the sampler
|
|
219
|
+
if alt_moves:
|
|
220
|
+
# use the differential evolution moves
|
|
221
|
+
moves = [
|
|
222
|
+
(emcee.moves.DEMove(), 0.7),
|
|
223
|
+
(emcee.moves.DESnookerMove(), 0.3),
|
|
224
|
+
]
|
|
225
|
+
else:
|
|
226
|
+
# used the default Goodman & Weare stretch move
|
|
227
|
+
moves = None
|
|
228
|
+
|
|
229
|
+
sampler = emcee.EnsembleSampler(
|
|
230
|
+
nwalkers,
|
|
231
|
+
npars,
|
|
232
|
+
log_prob_fn,
|
|
233
|
+
args=(model,),
|
|
234
|
+
pool=pool,
|
|
235
|
+
backend=backend,
|
|
236
|
+
moves=moves,
|
|
237
|
+
)
|
|
238
|
+
|
|
239
|
+
if not extend:
|
|
240
|
+
# use the initial guess as the starting point
|
|
241
|
+
p_0 = np.asarray(p_0, dtype=float)
|
|
242
|
+
names = model.dynasty_par_names
|
|
243
|
+
sigma = walker_scatter(names, p_0, scatter_1, per_parameter_scatter)
|
|
244
|
+
p_0 = initialise_walkers(p_0, sigma, nwalkers, log_prior_fn, model)
|
|
245
|
+
|
|
246
|
+
# Run the burnin phase
|
|
247
|
+
print("\n\nExecuting the burn-in phase...")
|
|
248
|
+
state = sampler.run_mcmc(p_0, nburn, store=False, progress=True)
|
|
249
|
+
|
|
250
|
+
# Do we want to do that again?
|
|
251
|
+
if double_burnin:
|
|
252
|
+
# If we wanted to run a second burn-in phase, then do. Scatter the
|
|
253
|
+
# position about the first burn
|
|
254
|
+
print("Executing the second burn-in phase")
|
|
255
|
+
p_0 = state.coords[np.argmax(state.log_prob)]
|
|
256
|
+
sigma = walker_scatter(names, p_0, scatter_2, per_parameter_scatter)
|
|
257
|
+
p_0 = initialise_walkers(p_0, sigma, nwalkers, log_prior_fn, model)
|
|
258
|
+
|
|
259
|
+
# Run that burn-in
|
|
260
|
+
state = sampler.run_mcmc(p_0, nburn, store=False, progress=True)
|
|
261
|
+
|
|
262
|
+
# Now, reset the sampler. We'll use the result of the burn-in phase to
|
|
263
|
+
# re-initialise it.
|
|
264
|
+
sampler.reset()
|
|
265
|
+
skip_initial_state_check = False
|
|
266
|
+
else:
|
|
267
|
+
# start from chain position
|
|
268
|
+
state = None
|
|
269
|
+
skip_initial_state_check = True
|
|
270
|
+
|
|
271
|
+
print("Starting the main MCMC chain. Probably going to take a while!")
|
|
272
|
+
sampler.run_mcmc(
|
|
273
|
+
state,
|
|
274
|
+
nprod,
|
|
275
|
+
store=True,
|
|
276
|
+
progress=True,
|
|
277
|
+
skip_initial_state_check=skip_initial_state_check,
|
|
278
|
+
)
|
|
279
|
+
return sampler
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
def run_burnin(sampler, startPos, nSteps, storechain=False, progress=True):
|
|
283
|
+
iStep = 0
|
|
284
|
+
if progress:
|
|
285
|
+
bar = tqdm(total=nSteps)
|
|
286
|
+
|
|
287
|
+
# emcee irritatingly changed the keyword. This is very ugly.
|
|
288
|
+
try:
|
|
289
|
+
for pos, prob, state in sampler.sample(
|
|
290
|
+
startPos, iterations=nSteps, store=storechain
|
|
291
|
+
):
|
|
292
|
+
iStep += 1
|
|
293
|
+
if progress:
|
|
294
|
+
bar.update()
|
|
295
|
+
except:
|
|
296
|
+
for pos, prob, state in sampler.sample(
|
|
297
|
+
startPos, iterations=nSteps, storechain=storechain
|
|
298
|
+
):
|
|
299
|
+
iStep += 1
|
|
300
|
+
if progress:
|
|
301
|
+
bar.update()
|
|
302
|
+
if progress:
|
|
303
|
+
bar.close()
|
|
304
|
+
return pos, prob, state
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
def run_mcmc_save(
|
|
308
|
+
sampler, startPos, nSteps, rState, file, col_names="", progress=True, **kwargs
|
|
309
|
+
):
|
|
310
|
+
"""runs an MCMC chain with emcee, and saves steps to a file"""
|
|
311
|
+
# open chain save file
|
|
312
|
+
if file:
|
|
313
|
+
with open(file, "w") as f:
|
|
314
|
+
f.write(col_names)
|
|
315
|
+
if col_names:
|
|
316
|
+
f.write("\n")
|
|
317
|
+
|
|
318
|
+
iStep = 0
|
|
319
|
+
if progress:
|
|
320
|
+
bar = tqdm(total=nSteps)
|
|
321
|
+
|
|
322
|
+
## TODO: Impliment this with kwrgs manipulation, currently it is dumb.
|
|
323
|
+
try:
|
|
324
|
+
for pos, prob, state in sampler.sample(
|
|
325
|
+
startPos,
|
|
326
|
+
iterations=nSteps,
|
|
327
|
+
rstate0=rState,
|
|
328
|
+
store=True,
|
|
329
|
+
skip_initial_state_check=True,
|
|
330
|
+
**kwargs
|
|
331
|
+
):
|
|
332
|
+
iStep += 1
|
|
333
|
+
if progress:
|
|
334
|
+
bar.update()
|
|
335
|
+
|
|
336
|
+
for k in range(pos.shape[0]):
|
|
337
|
+
# loop over all walkers and append to file
|
|
338
|
+
thisPos = pos[k]
|
|
339
|
+
thisProb = prob[k]
|
|
340
|
+
|
|
341
|
+
with open(file, "a") as f:
|
|
342
|
+
f.write(
|
|
343
|
+
"{0:4d} {1:s} {2:f}\n".format(
|
|
344
|
+
k, " ".join(map(str, thisPos)), thisProb
|
|
345
|
+
)
|
|
346
|
+
)
|
|
347
|
+
except TypeError:
|
|
348
|
+
for pos, prob, state in sampler.sample(
|
|
349
|
+
startPos, iterations=nSteps, rstate0=rState, storechain=False, **kwargs
|
|
350
|
+
):
|
|
351
|
+
iStep += 1
|
|
352
|
+
if progress:
|
|
353
|
+
bar.update()
|
|
354
|
+
|
|
355
|
+
for k in range(pos.shape[0]):
|
|
356
|
+
# loop over all walkers and append to file
|
|
357
|
+
thisPos = pos[k]
|
|
358
|
+
thisProb = prob[k]
|
|
359
|
+
|
|
360
|
+
with open(file, "a") as f:
|
|
361
|
+
f.write(
|
|
362
|
+
"{0:4d} {1:s} {2:f}\n".format(
|
|
363
|
+
k, " ".join(map(str, thisPos)), thisProb
|
|
364
|
+
)
|
|
365
|
+
)
|
|
366
|
+
|
|
367
|
+
if progress:
|
|
368
|
+
bar.close()
|
|
369
|
+
return sampler
|
|
370
|
+
|
|
371
|
+
|
|
372
|
+
def run_ptmcmc_save(
|
|
373
|
+
sampler, startPos, nSteps, file, progress=True, col_names="", **kwargs
|
|
374
|
+
):
|
|
375
|
+
"""runs PT MCMC and saves zero temperature chain to a file"""
|
|
376
|
+
if file:
|
|
377
|
+
with open(file, "w") as f:
|
|
378
|
+
f.write(col_names)
|
|
379
|
+
if col_names:
|
|
380
|
+
f.write("\n")
|
|
381
|
+
|
|
382
|
+
iStep = 0
|
|
383
|
+
if progress:
|
|
384
|
+
bar = tqdm(total=nSteps)
|
|
385
|
+
|
|
386
|
+
## TODO: Impliment this with kwrgs manipulation, currently it is dumb.
|
|
387
|
+
try:
|
|
388
|
+
for pos, prob, like in sampler.sample(
|
|
389
|
+
startPos, iterations=nSteps, store=False, **kwargs
|
|
390
|
+
):
|
|
391
|
+
iStep += 1
|
|
392
|
+
if progress:
|
|
393
|
+
bar.update()
|
|
394
|
+
# pos is shape (ntemps, nwalkers, npars)
|
|
395
|
+
# prob is shape (ntemps, nwalkers)
|
|
396
|
+
# loop over all walkers for first temp and append to file
|
|
397
|
+
zpos = pos[0, ...]
|
|
398
|
+
zprob = prob[0, ...]
|
|
399
|
+
|
|
400
|
+
for k in range(zpos.shape[0]):
|
|
401
|
+
thisPos = zpos[k]
|
|
402
|
+
thisProb = zprob[k]
|
|
403
|
+
|
|
404
|
+
with open(file, "a") as f:
|
|
405
|
+
f.write(
|
|
406
|
+
"{0:4d} {1:s} {2:f}\n".format(
|
|
407
|
+
k, " ".join(map(str, thisPos)), thisProb
|
|
408
|
+
)
|
|
409
|
+
)
|
|
410
|
+
|
|
411
|
+
except TypeError:
|
|
412
|
+
for pos, prob, like in sampler.sample(
|
|
413
|
+
startPos, iterations=nSteps, storechain=True, **kwargs
|
|
414
|
+
):
|
|
415
|
+
iStep += 1
|
|
416
|
+
if progress:
|
|
417
|
+
bar.update()
|
|
418
|
+
# pos is shape (ntemps, nwalkers, npars)
|
|
419
|
+
# prob is shape (ntemps, nwalkers)
|
|
420
|
+
# loop over all walkers for first temp and append to file
|
|
421
|
+
zpos = pos[0, ...]
|
|
422
|
+
zprob = prob[0, ...]
|
|
423
|
+
|
|
424
|
+
for k in range(zpos.shape[0]):
|
|
425
|
+
thisPos = zpos[k]
|
|
426
|
+
thisProb = zprob[k]
|
|
427
|
+
|
|
428
|
+
with open(file, "a") as f:
|
|
429
|
+
f.write(
|
|
430
|
+
"{0:4d} {1:s} {2:f}\n".format(
|
|
431
|
+
k, " ".join(map(str, thisPos)), thisProb
|
|
432
|
+
)
|
|
433
|
+
)
|
|
434
|
+
|
|
435
|
+
if progress:
|
|
436
|
+
bar.close()
|
|
437
|
+
return sampler
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+
def GR_diagnostic(sampler_chain):
|
|
441
|
+
"""Gelman & Rubin check for convergence."""
|
|
442
|
+
m, n, ndim = np.shape(sampler_chain)
|
|
443
|
+
R_hats = np.zeros((ndim))
|
|
444
|
+
samples = sampler_chain[:, :, :].reshape(-1, ndim)
|
|
445
|
+
for i in range(ndim): # iterate over parameters
|
|
446
|
+
# Define variables
|
|
447
|
+
chains = sampler_chain[:, :, i]
|
|
448
|
+
|
|
449
|
+
flat_chain = samples[:, i]
|
|
450
|
+
psi_dot_dot = np.mean(flat_chain)
|
|
451
|
+
psi_j_dot = np.mean(chains, axis=1)
|
|
452
|
+
psi_j_t = chains
|
|
453
|
+
|
|
454
|
+
# Calculate between-chain variance
|
|
455
|
+
between = sum((psi_j_dot - psi_dot_dot) ** 2) / (m - 1)
|
|
456
|
+
|
|
457
|
+
# Calculate within-chain variance
|
|
458
|
+
inner_sum = np.sum(
|
|
459
|
+
np.array([(psi_j_t[j, :] - psi_j_dot[j]) ** 2 for j in range(m)]), axis=1
|
|
460
|
+
)
|
|
461
|
+
|
|
462
|
+
outer_sum = np.sum(inner_sum)
|
|
463
|
+
W = outer_sum / (m * (n - 1))
|
|
464
|
+
|
|
465
|
+
# Calculate sigma
|
|
466
|
+
sigma2 = (n - 1) / n * W + between
|
|
467
|
+
|
|
468
|
+
# Calculate convergence criterion (potential scale reduction factor)
|
|
469
|
+
R_hats[i] = (m + 1) * sigma2 / (m * W) - (n - 1) / (m * n)
|
|
470
|
+
return R_hats
|
|
471
|
+
|
|
472
|
+
|