Note
Click here to download the full example code
MCMC search v.s. grid searchΒΆ
An example to compare MCMCSearch and GridSearch on the same data.
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 | import pyfstat
import os
import numpy as np
import matplotlib.pyplot as plt
# flip this switch for a more expensive 4D (F0,F1,Alpha,Delta) run
# instead of just (F0,F1)
# (still only a few minutes on current laptops)
sky = False
outdir = os.path.join(
"PyFstat_example_data", "PyFstat_example_simple_mcmc_vs_grid_comparison"
)
if sky:
outdir += "AlphaDelta"
# parameters for the data set to generate
tstart = 1000000000
duration = 30 * 86400
Tsft = 1800
detectors = "H1,L1"
sqrtSX = 1e-22
# parameters for injected signals
inj = {
"tref": tstart,
"F0": 30.0,
"F1": -1e-10,
"F2": 0,
"Alpha": 0.5,
"Delta": 1,
"h0": 0.05 * sqrtSX,
"cosi": 1.0,
}
# latex-formatted plotting labels
labels = {
"F0": "$f$ [Hz]",
"F1": "$\\dot{f}$ [Hz/s]",
"2F": "$2\\mathcal{F}$",
"Alpha": "$\\alpha$",
"Delta": "$\\delta$",
}
labels["max2F"] = "$\\max\\,$" + labels["2F"]
def plot_grid_vs_samples(grid_res, mcmc_res, xkey, ykey):
""" local plotting function to avoid code duplication in the 4D case """
plt.plot(grid_res[xkey], grid_res[ykey], ".", label="grid")
plt.plot(mcmc_res[xkey], mcmc_res[ykey], ".", label="mcmc")
plt.plot(inj[xkey], inj[ykey], "*k", label="injection")
grid_maxidx = np.argmax(grid_res["twoF"])
mcmc_maxidx = np.argmax(mcmc_res["twoF"])
plt.plot(
grid_res[xkey][grid_maxidx],
grid_res[ykey][grid_maxidx],
"+g",
label=labels["max2F"] + "(grid)",
)
plt.plot(
mcmc_res[xkey][mcmc_maxidx],
mcmc_res[ykey][mcmc_maxidx],
"xm",
label=labels["max2F"] + "(mcmc)",
)
plt.xlabel(labels[xkey])
plt.ylabel(labels[ykey])
plt.legend()
plotfilename_base = os.path.join(outdir, "grid_vs_mcmc_{:s}{:s}".format(xkey, ykey))
plt.savefig(plotfilename_base + ".png")
if xkey == "F0" and ykey == "F1":
plt.xlim(zoom[xkey])
plt.ylim(zoom[ykey])
plt.savefig(plotfilename_base + "_zoom.png")
plt.close()
def plot_2F_scatter(res, label, xkey, ykey):
""" local plotting function to avoid code duplication in the 4D case """
markersize = 3 if label == "grid" else 1
sc = plt.scatter(res[xkey], res[ykey], c=res["twoF"], s=markersize)
cb = plt.colorbar(sc)
plt.xlabel(labels[xkey])
plt.ylabel(labels[ykey])
cb.set_label(labels["2F"])
plt.title(label)
plt.plot(inj[xkey], inj[ykey], "*k", label="injection")
maxidx = np.argmax(res["twoF"])
plt.plot(
res[xkey][maxidx],
res[ykey][maxidx],
"+r",
label=labels["max2F"],
)
plt.legend()
plotfilename_base = os.path.join(
outdir, "{:s}_{:s}{:s}_2F".format(label, xkey, ykey)
)
plt.xlim([min(res[xkey]), max(res[xkey])])
plt.ylim([min(res[ykey]), max(res[ykey])])
plt.savefig(plotfilename_base + ".png")
plt.close()
if __name__ == "__main__":
print("Generating SFTs with injected signal...")
writer = pyfstat.Writer(
label="simulated_signal",
outdir=outdir,
tstart=tstart,
duration=duration,
detectors=detectors,
sqrtSX=sqrtSX,
Tsft=Tsft,
**inj,
Band=1, # default band estimation would be too narrow for a wide grid/prior
)
writer.make_data()
print("")
# set up square search grid with fixed (F0,F1) mismatch
# and (optionally) some ad-hoc sky coverage
m = 0.001
dF0 = np.sqrt(12 * m) / (np.pi * duration)
dF1 = np.sqrt(180 * m) / (np.pi * duration ** 2)
DeltaF0 = 500 * dF0
DeltaF1 = 200 * dF1
if sky:
# cover less range to keep runtime down
DeltaF0 /= 10
DeltaF1 /= 10
F0s = [inj["F0"] - DeltaF0 / 2.0, inj["F0"] + DeltaF0 / 2.0, dF0]
F1s = [inj["F1"] - DeltaF1 / 2.0, inj["F1"] + DeltaF1 / 2.0, dF1]
F2s = [inj["F2"]]
search_keys = ["F0", "F1"] # only the ones that aren't 0-width
if sky:
dSky = 0.01 # rather coarse to keep runtime down
DeltaSky = 10 * dSky
Alphas = [inj["Alpha"] - DeltaSky / 2.0, inj["Alpha"] + DeltaSky / 2.0, dSky]
Deltas = [inj["Delta"] - DeltaSky / 2.0, inj["Delta"] + DeltaSky / 2.0, dSky]
search_keys += ["Alpha", "Delta"]
else:
Alphas = [inj["Alpha"]]
Deltas = [inj["Delta"]]
search_keys_label = "".join(search_keys)
print("Performing GridSearch...")
gridsearch = pyfstat.GridSearch(
label="grid_search_" + search_keys_label,
outdir=outdir,
sftfilepattern=os.path.join(outdir, "*simulated_signal*sft"),
F0s=F0s,
F1s=F1s,
F2s=F2s,
Alphas=Alphas,
Deltas=Deltas,
tref=inj["tref"],
)
gridsearch.run()
gridsearch.print_max_twoF()
# do some plots of the GridSearch results
if not sky: # this plotter can't currently deal with too large result arrays
print("Plotting 1D 2F distributions...")
for key in search_keys:
gridsearch.plot_1D(xkey=key, xlabel=labels[key], ylabel=labels["2F"])
print("Making GridSearch {:s} corner plot...".format("-".join(search_keys)))
vals = [np.unique(gridsearch.data[key]) - inj[key] for key in search_keys]
twoF = gridsearch.data["twoF"].reshape([len(kval) for kval in vals])
corner_labels = [
"$f - f_0$ [Hz]",
"$\\dot{f} - \\dot{f}_0$ [Hz/s]",
]
if sky:
corner_labels.append("$\\alpha - \\alpha_0$")
corner_labels.append("$\\delta - \\delta_0$")
corner_labels.append(labels["2F"])
gridcorner_fig, gridcorner_axes = pyfstat.gridcorner(
twoF, vals, projection="log_mean", labels=corner_labels, whspace=0.1, factor=1.8
)
gridcorner_fig.savefig(os.path.join(outdir, gridsearch.label + "_corner.png"))
plt.close(gridcorner_fig)
print("")
print("Performing MCMCSearch...")
# set up priors in F0 and F1 (over)covering the grid ranges
if sky: # MCMC will still be fast in 4D with wider range than grid
DeltaF0 *= 50
DeltaF1 *= 50
theta_prior = {
"F0": {
"type": "unif",
"lower": inj["F0"] - DeltaF0 / 2.0,
"upper": inj["F0"] + DeltaF0 / 2.0,
},
"F1": {
"type": "unif",
"lower": inj["F1"] - DeltaF1 / 2.0,
"upper": inj["F1"] + DeltaF1 / 2.0,
},
"F2": inj["F2"],
}
if sky:
# also implicitly covering twice the grid range here
theta_prior["Alpha"] = {
"type": "unif",
"lower": inj["Alpha"] - DeltaSky,
"upper": inj["Alpha"] + DeltaSky,
}
theta_prior["Delta"] = {
"type": "unif",
"lower": inj["Delta"] - DeltaSky,
"upper": inj["Delta"] + DeltaSky,
}
else:
theta_prior["Alpha"] = inj["Alpha"]
theta_prior["Delta"] = inj["Delta"]
# ptemcee sampler settings - in a real application we might want higher values
ntemps = 2
log10beta_min = -1
nwalkers = 100
nsteps = [200, 200] # [burnin,production]
mcmcsearch = pyfstat.MCMCSearch(
label="mcmc_search_" + search_keys_label,
outdir=outdir,
sftfilepattern=os.path.join(outdir, "*simulated_signal*sft"),
theta_prior=theta_prior,
tref=inj["tref"],
nsteps=nsteps,
nwalkers=nwalkers,
ntemps=ntemps,
log10beta_min=log10beta_min,
)
# walker plot is generated during main run of the search class
mcmcsearch.run(
walker_plot_args={"plot_det_stat": True, "injection_parameters": inj}
)
mcmcsearch.print_summary()
# call some built-in plotting methods
# these can all highlight the injection parameters, too
print("Making MCMCSearch {:s} corner plot...".format("-".join(search_keys)))
mcmcsearch.plot_corner(truths=inj)
print("Making MCMCSearch prior-posterior comparison plot...")
mcmcsearch.plot_prior_posterior(injection_parameters=inj)
print("")
# NOTE: everything below here is just custom commandline output and plotting
# for this particular example, which uses the PyFstat outputs,
# but isn't very instructive if you just want to learn the main usage of the package.
# some informative command-line output comparing search results and injection
# get max of GridSearch, contains twoF and all Doppler parameters in the dict
max_dict_grid = gridsearch.get_max_twoF()
# same for MCMCSearch, here twoF is separate, and non-sampled parameters are not included either
max_dict_mcmc, max_2F_mcmc = mcmcsearch.get_max_twoF()
print(
"max2F={:.4f} from GridSearch, offsets from injection: {:s}.".format(
max_dict_grid["twoF"],
", ".join(
[
"{:.4e} in {:s}".format(max_dict_grid[key] - inj[key], key)
for key in search_keys
]
),
)
)
print(
"max2F={:.4f} from MCMCSearch, offsets from injection: {:s}.".format(
max_2F_mcmc,
", ".join(
[
"{:.4e} in {:s}".format(max_dict_mcmc[key] - inj[key], key)
for key in search_keys
]
),
)
)
# get additional point and interval estimators
stats_dict_mcmc = mcmcsearch.get_summary_stats()
print(
"mean from MCMCSearch: offset from injection by {:s},"
" or in fractions of 2sigma intervals: {:s}.".format(
", ".join(
[
"{:.4e} in {:s}".format(
stats_dict_mcmc[key]["mean"] - inj[key], key
)
for key in search_keys
]
),
", ".join(
[
"{:.2f}% in {:s}".format(
100
* np.abs(stats_dict_mcmc[key]["mean"] - inj[key])
/ (2 * stats_dict_mcmc[key]["std"]),
key,
)
for key in search_keys
]
),
)
)
print(
"median from MCMCSearch: offset from injection by {:s},"
" or in fractions of 90% confidence intervals: {:s}.".format(
", ".join(
[
"{:.4e} in {:s}".format(
stats_dict_mcmc[key]["median"] - inj[key], key
)
for key in search_keys
]
),
", ".join(
[
"{:.2f}% in {:s}".format(
100
* np.abs(stats_dict_mcmc[key]["median"] - inj[key])
/ (
stats_dict_mcmc[key]["upper90"]
- stats_dict_mcmc[key]["lower90"]
),
key,
)
for key in search_keys
]
),
)
)
print()
# do additional custom plotting
print("Loading grid and MCMC search results for custom comparison plots...")
gridfile = os.path.join(outdir, gridsearch.label + "_NA_GridSearch.txt")
if not os.path.isfile(gridfile):
raise RuntimeError(
"Failed to load GridSearch results from file '{:s}',"
" something must have gone wrong!".format(gridfile)
)
grid_res = pyfstat.helper_functions.read_txt_file_with_header(gridfile)
mcmc_file = os.path.join(outdir, mcmcsearch.label + "_samples.dat")
if not os.path.isfile(mcmc_file):
raise RuntimeError(
"Failed to load MCMCSearch results from file '{:s}',"
" something must have gone wrong!".format(mcmc_file)
)
mcmc_res = pyfstat.helper_functions.read_txt_file_with_header(mcmc_file)
zoom = {
"F0": [inj["F0"] - 10 * dF0, inj["F0"] + 10 * dF0],
"F1": [inj["F1"] - 5 * dF1, inj["F1"] + 5 * dF1],
}
# we'll use the two local plotting functions defined above
# to avoid code duplication in the sky case
print("Creating MCMC-grid comparison plots...")
plot_grid_vs_samples(grid_res, mcmc_res, "F0", "F1")
plot_2F_scatter(grid_res, "grid", "F0", "F1")
plot_2F_scatter(mcmc_res, "mcmc", "F0", "F1")
if sky:
plot_grid_vs_samples(grid_res, mcmc_res, "Alpha", "Delta")
plot_2F_scatter(grid_res, "grid", "Alpha", "Delta")
plot_2F_scatter(mcmc_res, "mcmc", "Alpha", "Delta")
|
Total running time of the script: ( 0 minutes 0.000 seconds)