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/summary.py
ADDED
|
@@ -0,0 +1,327 @@
|
|
|
1
|
+
"""Summarise the result of an lfit MCMC run."""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import warnings
|
|
5
|
+
|
|
6
|
+
import configobj
|
|
7
|
+
import matplotlib.pyplot as plt
|
|
8
|
+
import numpy as np
|
|
9
|
+
import pandas as pd
|
|
10
|
+
|
|
11
|
+
from .chains import read_chain
|
|
12
|
+
from .cv_model import construct_model
|
|
13
|
+
from .likelihood import ln_like, ln_prior, ln_prob
|
|
14
|
+
from .plotting import plot_model, thumbPlot
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _skip_and_thin_walkers(df, colKeys, nskip, thin, automated):
|
|
18
|
+
"""Plot the likelihood evolution of an emcee chain, then drop the first
|
|
19
|
+
``nskip`` steps and keep every ``thin``-th step. If not ``automated``,
|
|
20
|
+
asks the user to confirm ``nskip`` and ``thin``."""
|
|
21
|
+
nwalkers = df["walker_no"].max() + 1
|
|
22
|
+
df["step"] = df.index // nwalkers
|
|
23
|
+
nsteps = df["step"].max() + 1
|
|
24
|
+
|
|
25
|
+
print(
|
|
26
|
+
"The chain file actually contains {} walkers, over {} steps.".format(
|
|
27
|
+
nwalkers, nsteps
|
|
28
|
+
)
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
# Plot an image of the walker likelihoods over time.
|
|
32
|
+
|
|
33
|
+
print("Reading in the chain file for likelihoods...")
|
|
34
|
+
walker_likes = df["ln_prob"]
|
|
35
|
+
|
|
36
|
+
# Get a numpy array of likelihoods, shaped (nwalkers, nprod).
|
|
37
|
+
walker_likes = np.asarray(
|
|
38
|
+
[walker_likes.loc[df["walker_no"] == i] for i in range(nwalkers)]
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
# Plot the mean likelihood evolution
|
|
42
|
+
std = np.std(walker_likes, axis=0)
|
|
43
|
+
likes = np.mean(walker_likes, axis=0)
|
|
44
|
+
|
|
45
|
+
steps = np.asarray(df["step"].loc[df["walker_no"] == 1])
|
|
46
|
+
|
|
47
|
+
likes = likes[nskip::thin]
|
|
48
|
+
std = std[nskip::thin]
|
|
49
|
+
steps = steps[nskip::thin]
|
|
50
|
+
|
|
51
|
+
# Make the likelihood plot
|
|
52
|
+
fig, ax = plt.subplots(figsize=(11, 8))
|
|
53
|
+
ax.fill_between(steps, likes - std, likes + std, color="red", alpha=0.4)
|
|
54
|
+
ax.plot(steps, likes, color="green")
|
|
55
|
+
|
|
56
|
+
ax.set_xlabel("Step")
|
|
57
|
+
ax.set_ylabel("ln_prob")
|
|
58
|
+
|
|
59
|
+
plt.tight_layout()
|
|
60
|
+
|
|
61
|
+
oname = "Final_figs/ln_prob.pdf"
|
|
62
|
+
|
|
63
|
+
plt.savefig(oname)
|
|
64
|
+
print("Saved to {}".format(oname))
|
|
65
|
+
if automated:
|
|
66
|
+
plt.close()
|
|
67
|
+
else:
|
|
68
|
+
plt.show(block=False)
|
|
69
|
+
|
|
70
|
+
# Check that the user is sure about not thinning or skipping, in light of the chain size.
|
|
71
|
+
if not automated:
|
|
72
|
+
if nskip == 0:
|
|
73
|
+
nskip = input(
|
|
74
|
+
"You opted not to skip any data, are you still sure? (default 0)\n-> nskip: "
|
|
75
|
+
)
|
|
76
|
+
try:
|
|
77
|
+
nskip = int(nskip)
|
|
78
|
+
except ValueError:
|
|
79
|
+
nskip = 0
|
|
80
|
+
data = df.loc[df["step"] >= nskip]
|
|
81
|
+
print("First step is {}".format(steps.min()))
|
|
82
|
+
ax.set_xlim(left=nskip + steps.min(), right=steps.max())
|
|
83
|
+
fig.canvas.draw_idle()
|
|
84
|
+
|
|
85
|
+
if not automated:
|
|
86
|
+
if thin == 1:
|
|
87
|
+
print("Thinning omits every Nth step of the chain.")
|
|
88
|
+
thin = input(
|
|
89
|
+
"You opted not to thin the data, are you sure? (defaults to no thinning)\n-> thin: "
|
|
90
|
+
)
|
|
91
|
+
try:
|
|
92
|
+
thin = int(thin)
|
|
93
|
+
except ValueError:
|
|
94
|
+
thin = 1
|
|
95
|
+
if thin > 1:
|
|
96
|
+
data = data.loc[data.step % thin == 0]
|
|
97
|
+
|
|
98
|
+
nwalkers = len(np.unique(data["walker_no"]))
|
|
99
|
+
nsteps = len(np.unique(data["step"]))
|
|
100
|
+
npars = len(colKeys)
|
|
101
|
+
print(
|
|
102
|
+
"After thinning and skipping: {} walkers, {} steps, {} params".format(
|
|
103
|
+
nwalkers, nsteps, npars
|
|
104
|
+
)
|
|
105
|
+
)
|
|
106
|
+
plt.close()
|
|
107
|
+
return data
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def fit_summary(
|
|
111
|
+
chain_fname,
|
|
112
|
+
input_fname,
|
|
113
|
+
nskip=0,
|
|
114
|
+
thin=1,
|
|
115
|
+
automated=False,
|
|
116
|
+
corners=True,
|
|
117
|
+
):
|
|
118
|
+
"""Takes the chain file made by mcmcfit.py and summarises the initial
|
|
119
|
+
and final conditions. Uses the input filename normally supplied to
|
|
120
|
+
mcmcfit.py to accurately reconstruct the model.
|
|
121
|
+
|
|
122
|
+
Inputs:
|
|
123
|
+
-------
|
|
124
|
+
chain_fname: str
|
|
125
|
+
The chain file to be read in: an emcee or pocoMC HDF5 chain, or an
|
|
126
|
+
old-style chain_prod.txt that tracks which walker is doing what.
|
|
127
|
+
input_fname: str
|
|
128
|
+
The input file normally supplied to mcmcfit.py.
|
|
129
|
+
nskip: int
|
|
130
|
+
This many steps will be stripped from the front of the chain
|
|
131
|
+
thin: int
|
|
132
|
+
Only every 'thin'-th step will be used.
|
|
133
|
+
automated: bool
|
|
134
|
+
If this is True, no figures will actually show, and will only be
|
|
135
|
+
saved to file.
|
|
136
|
+
corners: bool
|
|
137
|
+
If this is True, create and save corner plots of each eclipse's params
|
|
138
|
+
"""
|
|
139
|
+
|
|
140
|
+
# Retrieve some info from the input dict.
|
|
141
|
+
input_dict = configobj.ConfigObj(input_fname)
|
|
142
|
+
|
|
143
|
+
nsteps = int(input_dict["nprod"])
|
|
144
|
+
nwalkers = int(input_dict["nwalkers"])
|
|
145
|
+
|
|
146
|
+
# Read in the data
|
|
147
|
+
print("Reading in the data...")
|
|
148
|
+
colKeys, df = read_chain(chain_fname)
|
|
149
|
+
|
|
150
|
+
print("Done!\nData shape: {}".format(df.shape))
|
|
151
|
+
print(
|
|
152
|
+
"Expected a shape (nwalkers, nprod, npars+2): ({}, {}, {})".format(
|
|
153
|
+
nwalkers, nsteps, len(colKeys) + 2
|
|
154
|
+
)
|
|
155
|
+
)
|
|
156
|
+
|
|
157
|
+
# Create the Final_figs and Initial_figs directories.
|
|
158
|
+
if not os.path.isdir("Final_figs"):
|
|
159
|
+
os.mkdir("Final_figs")
|
|
160
|
+
if not os.path.isdir("Initial_figs"):
|
|
161
|
+
os.mkdir("Initial_figs")
|
|
162
|
+
|
|
163
|
+
if "walker_no" in df.columns:
|
|
164
|
+
data = _skip_and_thin_walkers(df, colKeys, nskip, thin, automated)
|
|
165
|
+
else:
|
|
166
|
+
# e.g. pocoMC: the chain is already independent posterior samples,
|
|
167
|
+
# with no walkers or steps to skip or thin.
|
|
168
|
+
print("Chain has no walkers or steps; using all samples.")
|
|
169
|
+
data = df
|
|
170
|
+
|
|
171
|
+
# Analyse the chain. Take the mean as the result, and 2 sigma as the error
|
|
172
|
+
result = pd.DataFrame()
|
|
173
|
+
result["median"] = data.quantile(0.50)
|
|
174
|
+
result["84th percentile"] = data.quantile(0.84)
|
|
175
|
+
result["16th percentile"] = data.quantile(0.16)
|
|
176
|
+
|
|
177
|
+
# report. While we're doing that, make a dict of the values we want to assign
|
|
178
|
+
# to the new version of the model.
|
|
179
|
+
print("Result of the chain:")
|
|
180
|
+
with pd.option_context("display.max_rows", None, "display.max_columns", None):
|
|
181
|
+
print(result)
|
|
182
|
+
modparams = result.loc[colKeys, :]
|
|
183
|
+
modparams.to_csv("modparams.csv", header=True)
|
|
184
|
+
|
|
185
|
+
# # # # # # # # # # # # # # # # # # # # # # # #
|
|
186
|
+
# Use the input file to reconstruct the model #
|
|
187
|
+
# # # # # # # # # # # # # # # # # # # # # # # #
|
|
188
|
+
|
|
189
|
+
model = construct_model(input_fname)
|
|
190
|
+
parDict = {k: v for k, v in result["median"].to_dict().items() if k in colKeys}
|
|
191
|
+
|
|
192
|
+
# We want to know where we started, so we can evaluate improvements.
|
|
193
|
+
# Wok out how many degrees of freedom we have in the model
|
|
194
|
+
eclipses = model.search_node_type("Eclipse")
|
|
195
|
+
# How many data points do we have?
|
|
196
|
+
dof = np.sum([ecl.lc.x.size for ecl in eclipses])
|
|
197
|
+
# Subtract a DoF for each variable
|
|
198
|
+
dof -= len(model.dynasty_par_vals)
|
|
199
|
+
# Subtract one DoF for the fit
|
|
200
|
+
dof -= 1
|
|
201
|
+
|
|
202
|
+
model_preport = "The following is the result of the MCMC fit running in:\n"
|
|
203
|
+
model_preport += " Machine name: {}\n Directory: {}\n".format(
|
|
204
|
+
os.uname().nodename, os.getcwd()
|
|
205
|
+
)
|
|
206
|
+
model_preport += "\n\nInitial guess has a chisq of {:.3f} ({:d} D.o.F.).\n".format(
|
|
207
|
+
model.chisq(), dof
|
|
208
|
+
)
|
|
209
|
+
model_preport += "\nEvaluating the model, we get;\n"
|
|
210
|
+
model_preport += "a ln_prior of {:.3f}\n".format(
|
|
211
|
+
ln_prior(model.dynasty_par_vals, model)
|
|
212
|
+
)
|
|
213
|
+
model_preport += "a ln_like of {:.3f}\n".format(
|
|
214
|
+
ln_like(model.dynasty_par_vals, model)
|
|
215
|
+
)
|
|
216
|
+
model_preport += "a ln_prob of {:.3f}\n".format(
|
|
217
|
+
ln_prob(model.dynasty_par_vals, model)
|
|
218
|
+
)
|
|
219
|
+
print(model_preport)
|
|
220
|
+
|
|
221
|
+
if not automated:
|
|
222
|
+
print("Initial conditions being plotted now...")
|
|
223
|
+
|
|
224
|
+
plot_model(
|
|
225
|
+
model, not automated, save=True, figsize=(11, 8), save_dir="Initial_figs/"
|
|
226
|
+
)
|
|
227
|
+
|
|
228
|
+
# # # # # # # # # # # # # # # # #
|
|
229
|
+
# The model is now fully built. #
|
|
230
|
+
# # # # # # # # # # # # # # # # #
|
|
231
|
+
|
|
232
|
+
model.dynasty_par_dict = parDict
|
|
233
|
+
|
|
234
|
+
model_report = ""
|
|
235
|
+
model_report += "\n\nMCMC result has a chisq of {:.3f} ({:d} D.o.F.).\n".format(
|
|
236
|
+
model.chisq(), dof
|
|
237
|
+
)
|
|
238
|
+
model_report += "\nEvaluating the model, we get;\n"
|
|
239
|
+
model_report += "a ln_prior of {:.3f}\n".format(
|
|
240
|
+
ln_prior(model.dynasty_par_vals, model)
|
|
241
|
+
)
|
|
242
|
+
model_report += "a ln_like of {:.3f}\n".format(
|
|
243
|
+
ln_like(model.dynasty_par_vals, model)
|
|
244
|
+
)
|
|
245
|
+
model_report += "a ln_prob of {:.3f}\n".format(
|
|
246
|
+
ln_prob(model.dynasty_par_vals, model)
|
|
247
|
+
)
|
|
248
|
+
model_report += "\n\nThe final fits of this chain are attached below.\n\n"
|
|
249
|
+
|
|
250
|
+
if not automated:
|
|
251
|
+
print("Final conditions being plotted now...")
|
|
252
|
+
input("> ")
|
|
253
|
+
|
|
254
|
+
plot_model(model, not automated, save=True, figsize=(11, 8), save_dir="Final_figs/")
|
|
255
|
+
|
|
256
|
+
if corners:
|
|
257
|
+
# Corner plots. Collect the eclipses.
|
|
258
|
+
eclipses = model.search_node_type("Eclipse")
|
|
259
|
+
for eclipse in eclipses:
|
|
260
|
+
# Get the par names from the eclipse.
|
|
261
|
+
print("Doing the corner plot for eclipse {}".format(eclipse))
|
|
262
|
+
|
|
263
|
+
# Sometimes, the walkers can fall into a phi0 == 0.0. When this happens,
|
|
264
|
+
# the thumbplot gets confused and dies, since there's no range.
|
|
265
|
+
# This parameter it typically only important if something goes badly
|
|
266
|
+
# wrong anyway, so if it gets stuck here, just filter it out.
|
|
267
|
+
|
|
268
|
+
# Eclipse-level variables
|
|
269
|
+
par_labels = [
|
|
270
|
+
"{}_{}".format(par, eclipse.label) for par in eclipse.node_par_names
|
|
271
|
+
]
|
|
272
|
+
|
|
273
|
+
# Get the par names from the band
|
|
274
|
+
band = eclipse.parent
|
|
275
|
+
par_labels += [
|
|
276
|
+
"{}_{}".format(par, band.label) for par in band.node_par_names
|
|
277
|
+
]
|
|
278
|
+
|
|
279
|
+
# get the par names from the core part of the model
|
|
280
|
+
my_model = band.parent
|
|
281
|
+
par_labels += [
|
|
282
|
+
"{}_{}".format(par, my_model.label) for par in my_model.node_par_names
|
|
283
|
+
]
|
|
284
|
+
|
|
285
|
+
# Only plot parameters that are in the chain file.
|
|
286
|
+
par_labels = list(set(par_labels).intersection(colKeys))
|
|
287
|
+
print("\nMy corner plot labels are:")
|
|
288
|
+
print(par_labels)
|
|
289
|
+
|
|
290
|
+
# Get the indexes in the chain file, and gather those columns
|
|
291
|
+
chain_slice = np.asarray(data[par_labels])
|
|
292
|
+
print("chain_slice has the shape:", chain_slice.shape)
|
|
293
|
+
|
|
294
|
+
# If I've nothing to plot, continue to the next thing.
|
|
295
|
+
if par_labels == []:
|
|
296
|
+
continue
|
|
297
|
+
|
|
298
|
+
# skip immobile pars (with warning)
|
|
299
|
+
dev = np.std(chain_slice, axis=0)
|
|
300
|
+
if any(dev == 0):
|
|
301
|
+
stationary_mask = np.where(dev == 0)[0]
|
|
302
|
+
bad_params = ", ".join([par_labels[i] for i in stationary_mask])
|
|
303
|
+
warnings.warn(f"chains for {bad_params} are stationary")
|
|
304
|
+
dev[stationary_mask] = np.nan
|
|
305
|
+
chain_slice = chain_slice[:, ~np.isnan(dev)]
|
|
306
|
+
par_labels = [p for p, d in zip(par_labels, dev) if not np.isnan(d)]
|
|
307
|
+
|
|
308
|
+
print(
|
|
309
|
+
"\nAfter checking for immobile variables, my corner plot labels are:~"
|
|
310
|
+
)
|
|
311
|
+
print(par_labels)
|
|
312
|
+
print("chain_slice has the shape:", chain_slice.shape)
|
|
313
|
+
print("Par_labels has the shape: ", len(par_labels))
|
|
314
|
+
|
|
315
|
+
fig = thumbPlot(chain_slice, par_labels)
|
|
316
|
+
fname = os.path.split(eclipse.lc.fname)[1]
|
|
317
|
+
fname = os.path.splitext(fname)[0]
|
|
318
|
+
oname = "Final_figs/" + fname + "_corners.pdf"
|
|
319
|
+
print("Saving to {}...".format(oname))
|
|
320
|
+
plt.savefig(oname)
|
|
321
|
+
plt.close("all")
|
|
322
|
+
|
|
323
|
+
del chain_slice
|
|
324
|
+
try:
|
|
325
|
+
del fig
|
|
326
|
+
except NameError:
|
|
327
|
+
pass
|