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.
Files changed (81) hide show
  1. lfit_python/__init__.py +27 -0
  2. lfit_python/chains.py +157 -0
  3. lfit_python/cli/__init__.py +1 -0
  4. lfit_python/cli/limbdark.py +64 -0
  5. lfit_python/cli/mcmcfit.py +168 -0
  6. lfit_python/cli/physparams.py +154 -0
  7. lfit_python/cli/reddening.py +50 -0
  8. lfit_python/cli/summary.py +78 -0
  9. lfit_python/cli/update_input.py +65 -0
  10. lfit_python/cli/watch.py +39 -0
  11. lfit_python/cli/wdparams.py +223 -0
  12. lfit_python/cv_model.py +864 -0
  13. lfit_python/data/Bergeron/README +7 -0
  14. lfit_python/data/Bergeron/Table_DA +257 -0
  15. lfit_python/data/Bergeron/Table_DA_sdss +307 -0
  16. lfit_python/data/Bergeron/Table_DB +312 -0
  17. lfit_python/data/Bergeron/color_correction_tables/color_corrections_HCAM-GTC-super_minus_ntt_ucam.csv +1067 -0
  18. lfit_python/data/Bergeron/color_correction_tables/color_corrections_HCAM-GTC-super_minus_tnt_uspec.csv +1067 -0
  19. lfit_python/data/Gianninas13/ld_coeffs_g.txt +654 -0
  20. lfit_python/data/Gianninas13/ld_coeffs_i.txt +654 -0
  21. lfit_python/data/Gianninas13/ld_coeffs_r.txt +654 -0
  22. lfit_python/data/Gianninas13/ld_coeffs_u.txt +654 -0
  23. lfit_python/data/Gianninas13/ld_coeffs_z.txt +654 -0
  24. lfit_python/data/Gianninas13/radial_bright_profiles.txt +6925 -0
  25. lfit_python/data/Hamada/mr_hamada.dat +1307 -0
  26. lfit_python/data/Panei/12C-MR-H-He/12C-MR-H-He.dat +387 -0
  27. lfit_python/data/Panei/12C-MR-H-He/12C-MR-H-He.saver +750 -0
  28. lfit_python/data/Panei/12C-MR-He/12C-MR-He.dat +431 -0
  29. lfit_python/data/Panei/HS/04He-H-S.dat +158 -0
  30. lfit_python/data/Panei/HS/12C-H-S.dat +158 -0
  31. lfit_python/data/Panei/HS/16O-H-S.dat +158 -0
  32. lfit_python/data/Panei/HS/28Si-H-S.dat +158 -0
  33. lfit_python/data/Panei/HS/56Fe-H-S.dat +158 -0
  34. lfit_python/data/Panei/othercores/04He-MR-H.dat +91 -0
  35. lfit_python/data/Panei/othercores/16O-MR-H-He.dat +602 -0
  36. lfit_python/data/Panei/othercores/28Si-MR-H-He.dat +386 -0
  37. lfit_python/data/Panei/othercores/56Fe-MR-H-He.dat +390 -0
  38. lfit_python/data/Panei/othercores/old/04He-MR-H.save +120 -0
  39. lfit_python/data/Panei/othercores/old/04He-MR.save +130 -0
  40. lfit_python/data/Panei/othercores/old/16O-MR-H-He.save +602 -0
  41. lfit_python/data/Panei/othercores/old/16O-MR-He.save +469 -0
  42. lfit_python/data/Panei/othercores/old/28Si-MR-H-He.save +386 -0
  43. lfit_python/data/Panei/othercores/old/28Si-MR-He.save +402 -0
  44. lfit_python/data/Panei/othercores/old/56Fe-MR-H-He.save +633 -0
  45. lfit_python/data/Panei/othercores/old/56Fe-MR-He.save +537 -0
  46. lfit_python/data/Wood95/co040.2.04dt1 +80 -0
  47. lfit_python/data/Wood95/co050.2.04dt1 +82 -0
  48. lfit_python/data/Wood95/co060.2.04dt1 +85 -0
  49. lfit_python/data/Wood95/co070.2.04dt1 +91 -0
  50. lfit_python/data/Wood95/co080.2.04dt1 +100 -0
  51. lfit_python/data/Wood95/co090.2.04dt1 +99 -0
  52. lfit_python/data/Wood95/co100.2.04dt1 +100 -0
  53. lfit_python/data/althaus/readme.tex +12 -0
  54. lfit_python/data/althaus/t106.one +1132 -0
  55. lfit_python/data/althaus/t108.one +679 -0
  56. lfit_python/data/althaus/t110.one +821 -0
  57. lfit_python/data/althaus/t112.one +239 -0
  58. lfit_python/data/althaus/t114.one +355 -0
  59. lfit_python/data/althaus/t116.one +353 -0
  60. lfit_python/data/althaus/t118.one +356 -0
  61. lfit_python/data/althaus/t120.one +882 -0
  62. lfit_python/data/althaus/t122.one +901 -0
  63. lfit_python/data/althaus/t124.one +913 -0
  64. lfit_python/data/althaus/t126.one +739 -0
  65. lfit_python/data/althaus/t128.one +665 -0
  66. lfit_python/data/althaus/t130.one +626 -0
  67. lfit_python/likelihood.py +26 -0
  68. lfit_python/limbdark.py +47 -0
  69. lfit_python/model.py +801 -0
  70. lfit_python/physical_params.py +279 -0
  71. lfit_python/plotting.py +364 -0
  72. lfit_python/priors.py +51 -0
  73. lfit_python/sampling.py +472 -0
  74. lfit_python/summary.py +327 -0
  75. lfit_python/watch_app.py +1001 -0
  76. lfit_python/wdparams.py +587 -0
  77. lfit_python-0.1.0.dist-info/METADATA +222 -0
  78. lfit_python-0.1.0.dist-info/RECORD +81 -0
  79. lfit_python-0.1.0.dist-info/WHEEL +5 -0
  80. lfit_python-0.1.0.dist-info/entry_points.txt +9 -0
  81. lfit_python-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,1001 @@
1
+ """
2
+ Bokeh app for inspecting an lfit model and adjusting its starting parameters.
3
+
4
+ Run it with ``lfit-watch [mcmc_input.dat]``, which starts a bokeh server.
5
+ """
6
+
7
+ import sys
8
+ from os import getcwd
9
+
10
+ import configobj
11
+ import george as g
12
+ import numpy as np
13
+ from bokeh.layouts import Spacer, column, gridplot, row
14
+ from bokeh.models import Band, ColumnDataSource, Span, TabPanel, Tabs
15
+ from bokeh.models.widgets import Dropdown, Slider, markups
16
+ from bokeh.models.widgets.buttons import Button, Toggle
17
+ from bokeh.plotting import curdoc, figure
18
+ from pandas import DataFrame
19
+
20
+ import roche
21
+ from lfit_rs import CV
22
+
23
+ # bokeh runs this file as a script, so imports must be absolute
24
+ from lfit_python.cv_model import construct_model
25
+
26
+
27
+ def parseInput(file):
28
+ """Splits input file up making it easier to read"""
29
+ input_dict = configobj.ConfigObj(file)
30
+ return input_dict
31
+
32
+
33
+ class Watcher:
34
+ """This class will initialise a bokeh page, with some useful lfit MCMC chain supervision tools.
35
+ - Ability to plot a live chain file's evolution over time
36
+ - Interactive lightcurve model, with input sliders or the ability to grab the last step's mean
37
+ """
38
+
39
+ # Set the initial values of q, rwd, and dphi. These will be used to
40
+ # caclulate the location of the GP changepoints. Setting to initially
41
+ # unrealistically high values will ensure that the first time
42
+ # calcChangepoints is called, the changepoints are calculated.
43
+ _olddphi = 9e99
44
+ _oldq = 9e99
45
+ _oldrwd = 9e99
46
+
47
+ # _dist_cp is initially set to whatever, it will be overwritten anyway.
48
+ _dist_cp = 9e99
49
+
50
+ def __init__(self, mcmc_input, tail=5000, thin=0):
51
+ """
52
+ In the following order:
53
+ - Save the tail and thin parameters to the self.XX
54
+ - Read in the mcmc_input file to self.parDict
55
+ - Set up self.parNames to have all parameter names
56
+ - Set the other misc. trackers in handling files
57
+ - Initialise the data storage object
58
+ - Set up the first tab, with the live chain tracking page
59
+ - Now, regardless of if we're complex or not, generate all 18 of the parameter sliders
60
+ - If we're not complex BS model, the last 4 will just not do anything.
61
+ - Set up the second tab, with the parameter tweaking tool.
62
+ - Start watching for the creation of the chain file
63
+ """
64
+ # TODO:
65
+ # - Parameter reporting table
66
+ # - Physcial params corresponding to params?
67
+
68
+ #####################################################
69
+ ############### Information Gathering ###############
70
+ #####################################################
71
+
72
+ print("Gathering information about my initial conditions...")
73
+ # Save these, just in case I need to use them again later.
74
+ self.mcmc_fname = mcmc_input
75
+
76
+ print("Looking for the mcmc input '{}'".format(self.mcmc_fname))
77
+
78
+ # Parse the mcmc_input file
79
+ self.parse_mcmc_input()
80
+ self.init_data_storage()
81
+
82
+ # Create the model inspector tab
83
+ self.create_model_inspector_tab()
84
+ self.update_lc_model("value", "", "")
85
+
86
+ ######################################################
87
+ ############# Add the tabs to the figure #############
88
+ ######################################################
89
+
90
+ # Make a tabs object
91
+ self.tabs = Tabs(tabs=[self.inspector_tab]) # , tab2])
92
+ #  Add it
93
+ self.doc = curdoc()
94
+ self.doc.add_root(self.tabs)
95
+ print("Added the tabs to the document!")
96
+ self.doc.title = "MCMC Chain Supervisor"
97
+
98
+ # Is the file open? Check once a second until it is, then once we find it remove this callback.
99
+ self.update_lc_model("value", "", "")
100
+
101
+ print("Finished initialising the dashboard!")
102
+
103
+ def create_model_inspector_tab(self):
104
+ """Put together the model inspector tab.
105
+ This tab should have a plot with 18 sliders, one for each
106
+ parameter relevant to this eclipse.
107
+
108
+ When plotting a simple BS model, the complex sliders should
109
+ just not do anything.
110
+
111
+ The complex model should be toggleable.
112
+ The eclipse should be switchable via a dropdown box.
113
+ """
114
+ simple_parDesc = {
115
+ "wdFlux": "White Dwarf Flux",
116
+ "dFlux": "Disc Flux",
117
+ "sFlux": "BS Flux",
118
+ "rsFlux": "Donor Flux",
119
+ "q": "Mass Ratio",
120
+ "dphi": "WD Eclipse Width",
121
+ "rdisc": "Disc Radius",
122
+ "ulimb": "Limb Dark Coeff.",
123
+ "rwd": "White Dwarf Radius",
124
+ "scale": "BS Scale length",
125
+ "az": "BS Azimuth",
126
+ "fis": "BS Isotropic Fraction",
127
+ "dexp": "Disc Exponent",
128
+ "phi0": "Phase Offset",
129
+ }
130
+ complex_parDesc = {
131
+ "exp1": "BS Exponent 1",
132
+ "exp2": "BS Exponent 2",
133
+ "tilt": "BS Tilt",
134
+ "yaw": "BS Yaw",
135
+ }
136
+ GP_parDesc = {
137
+ "tau_gp": "GP Timescale",
138
+ "ln_ampin_gp": "GP intra-ecl amplitude",
139
+ "ln_ampout_gp": "GP inter-ecl amplitude",
140
+ }
141
+
142
+ print("Creating the model tweaker tab...")
143
+ # I need a myriad of parameter sliders. The ranges on these should be set by the priors.
144
+ self.par_sliders = []
145
+ for name, title in simple_parDesc.items():
146
+ title = simple_parDesc[name]
147
+ param = self.parDict[name]
148
+
149
+ if param[-1].lower() == "gauss":
150
+ new_param = [
151
+ param[0],
152
+ param[0] - 5 * param[2],
153
+ param[0] + 5 * param[2],
154
+ ]
155
+ param = new_param
156
+
157
+ print("Slider: {}".format(title))
158
+ print(" -> value, lower limit, upper limit: {}\n".format(param))
159
+
160
+ slider = Slider(
161
+ name=name,
162
+ title=title,
163
+ start=param[1],
164
+ end=param[2],
165
+ value=param[0],
166
+ step=(param[2] - param[1]) / 400,
167
+ width=200,
168
+ format="0.0000",
169
+ )
170
+
171
+ self.par_sliders.append(slider)
172
+
173
+ self.par_sliders_complex = []
174
+ for name, title in complex_parDesc.items():
175
+ title = complex_parDesc[name]
176
+ param = self.parDict[name]
177
+ print("Slider: {}".format(title))
178
+ print(" -> value, lower limit, upper limit: {}\n".format(param))
179
+
180
+ slider = Slider(
181
+ name=name,
182
+ title=title,
183
+ start=param[1],
184
+ end=param[2],
185
+ value=param[0],
186
+ step=(param[2] - param[1]) / 200,
187
+ width=200,
188
+ format="0.0000",
189
+ )
190
+
191
+ self.par_sliders_complex.append(slider)
192
+
193
+ self.par_sliders_GP = []
194
+ for name, title in GP_parDesc.items():
195
+ title = GP_parDesc[name]
196
+ param = self.parDict[name]
197
+ print("Slider: {}".format(title))
198
+ print(" -> value, lower limit, upper limit: {}\n".format(param))
199
+
200
+ slider = Slider(
201
+ name=name,
202
+ title=title,
203
+ start=param[1],
204
+ end=param[2],
205
+ value=param[0],
206
+ step=(param[2] - param[1]) / 200,
207
+ width=200,
208
+ format="0.0000",
209
+ )
210
+
211
+ self.par_sliders_GP.append(slider)
212
+
213
+ # Add the callbacks:
214
+ for slider in self.par_sliders:
215
+ slider.on_change("value_throttled", self.update_lc_model)
216
+ if self.complex:
217
+ for slider in self.par_sliders_complex:
218
+ slider.on_change("value_throttled", self.update_lc_model)
219
+ for slider in self.par_sliders_GP:
220
+ slider.on_change("value_throttled", self.update_lc_model)
221
+ print("Made the sliders...")
222
+
223
+ #  Data file picker
224
+ menu = self.menu
225
+ self.lc_change_fname_button = Dropdown(
226
+ label="Choose Data", button_type="success", menu=menu, width=500
227
+ )
228
+ self.lc_obs_fname = self.current_eclipse.lc.fname
229
+ self.lc_change_fname_button.on_click(self.update_lc_obs)
230
+ print("Made the data picker...")
231
+
232
+ # Button to switch from the complex to simple BS model, and vice versa
233
+ col = "success" if self.complex else "danger"
234
+ self.complex_button = Toggle(
235
+ label="Complex BS?", width=120, button_type=col, active=self.complex
236
+ )
237
+ self.complex_button.on_click(self.update_complex)
238
+ print("Made the complex button...")
239
+
240
+ # Button for the GP
241
+ col = "success" if self.GP else "danger"
242
+ self.GP_button = Toggle(
243
+ label="Use GP?", width=120, button_type=col, active=self.GP
244
+ )
245
+ self.GP_button.on_click(self.update_GP)
246
+ print("Made the GP button...")
247
+
248
+ print("Creating the LC plot...", end="")
249
+ # Initialise the figure
250
+ fname = self.current_eclipse.lc.name
251
+ band_name = self.current_eclipse.parent.label
252
+ title_text = "{} --- Band: {}".format(fname, band_name)
253
+ self.lc_plot = figure(
254
+ title=title_text,
255
+ height=500,
256
+ width=1200,
257
+ toolbar_location="above",
258
+ y_axis_location="left",
259
+ x_axis_location=None,
260
+ )
261
+
262
+ # Plot the lightcurve data
263
+ self.lc_plot.scatter(
264
+ x="phase", y="flux", source=self.lc_obs, size=5, color="black"
265
+ )
266
+
267
+ # also plot residuals
268
+ self.lc_res_plot = figure(
269
+ height=250,
270
+ width=1200,
271
+ toolbar_location=None,
272
+ y_axis_location="left",
273
+ x_range=self.lc_plot.x_range,
274
+ ) # , y_range=self.lc_plot.y_range)
275
+
276
+ # Plot the lightcurve data
277
+ self.lc_res_plot.scatter(
278
+ x="phase", y="res", source=self.lc_obs, size=5, color="red"
279
+ )
280
+ self.lc_res_plot.renderers += [
281
+ Span(location=0, dimension="width", line_color="green", line_width=1)
282
+ ]
283
+
284
+ #  Plot the GP over the residuals
285
+ band = Band(
286
+ base="phase",
287
+ lower="GP_lo",
288
+ upper="GP_up",
289
+ source=self.lc_obs,
290
+ level="underlay",
291
+ fill_alpha=0.3,
292
+ line_width=0,
293
+ line_color="black",
294
+ fill_color="black",
295
+ )
296
+ self.lc_res_plot.add_layout(band)
297
+
298
+ # Plot the model
299
+ self.lc_plot.line(x="phase", y="calc", source=self.lc_obs, line_color="red")
300
+ self.lc_plot.line(
301
+ x="phase", y="sec", source=self.lc_obs, alpha=0.5, line_color="brown"
302
+ )
303
+ self.lc_plot.line(
304
+ x="phase", y="wd", source=self.lc_obs, alpha=0.5, line_color="blue"
305
+ )
306
+ self.lc_plot.line(
307
+ x="phase", y="bspot", source=self.lc_obs, alpha=0.5, line_color="green"
308
+ )
309
+ self.lc_plot.line(
310
+ x="phase", y="disc", source=self.lc_obs, alpha=0.5, line_color="magenta"
311
+ )
312
+ print(" Done")
313
+
314
+ # I want a button that'll turn red when the parameters are invalid. When clicked, it will either return the
315
+ # model back to the initial values, or, if a chain has been read in, set the model to the last step read by the
316
+ # watcher.
317
+ self.lc_isvalid = Button(label="Initial Parameters", width=150)
318
+ self.lc_isvalid.on_click(self.reset_sliders)
319
+ print("Made the valid parameters button")
320
+
321
+ # Write the current slider values to mcmc_input.dat
322
+ self.write2input_button = Button(label="Write current values", width=150)
323
+ self.write2input_button.on_click(self.write2input)
324
+ print("Made the write2input button")
325
+
326
+ self.lnlike = None
327
+ self.like_label = markups.Div(width=1000)
328
+
329
+ self.console_logs = markups.Div(
330
+ text="Model errors will go here!",
331
+ width=1000,
332
+ height=30,
333
+ )
334
+
335
+ # Arrange the tab layout
336
+ inspector_layout = row(
337
+ [
338
+ column(
339
+ [
340
+ row(
341
+ [
342
+ self.lc_change_fname_button,
343
+ self.complex_button,
344
+ # self.GP_button,
345
+ self.lc_isvalid,
346
+ self.write2input_button,
347
+ ]
348
+ ),
349
+ self.lc_plot,
350
+ self.lc_res_plot,
351
+ ]
352
+ ),
353
+ column(
354
+ [
355
+ # self.like_label,
356
+ self.console_logs,
357
+ gridplot(
358
+ self.par_sliders, ncols=2, toolbar_options={"logo": None}
359
+ ),
360
+ Spacer(width=200, height=15, sizing_mode="scale_width"),
361
+ gridplot(
362
+ self.par_sliders_complex,
363
+ ncols=2,
364
+ toolbar_options={"logo": None},
365
+ ),
366
+ Spacer(width=200, height=15, sizing_mode="scale_width"),
367
+ # gridplot(
368
+ # self.par_sliders_GP, ncols=2,
369
+ # toolbar_options={'logo': None})
370
+ ]
371
+ ),
372
+ ]
373
+ )
374
+
375
+ self.inspector_tab = TabPanel(
376
+ child=inspector_layout, title="Lightcurve Inspector"
377
+ )
378
+ print("Constructed the Lightcurve Inspector tab!")
379
+
380
+ def init_data_storage(self):
381
+ print("Grabbing the observations...")
382
+ # Grab the data from the file, to start with just use the first in the list
383
+ self.lc_obs = {}
384
+ self.lc_obs["phase"] = self.current_eclipse.lc.x
385
+ self.lc_obs["flux"] = self.current_eclipse.lc.y
386
+ self.lc_obs["err"] = self.current_eclipse.lc.ye
387
+
388
+ self.lc_obs = DataFrame(self.lc_obs)
389
+ self.lc_obs.dropna(inplace=True, axis="index", how="any")
390
+
391
+ # Total model lightcurve
392
+ self.lc_obs["calc"] = np.zeros_like(self.lc_obs["phase"])
393
+ self.lc_obs["res"] = np.zeros_like(self.lc_obs["phase"])
394
+ #  Components
395
+ self.lc_obs["sec"] = np.zeros_like(self.lc_obs["phase"])
396
+ self.lc_obs["bspot"] = np.zeros_like(self.lc_obs["phase"])
397
+ self.lc_obs["wd"] = np.zeros_like(self.lc_obs["phase"])
398
+ self.lc_obs["disc"] = np.zeros_like(self.lc_obs["phase"])
399
+ #  GP
400
+ self.lc_obs["GP_up"] = np.zeros_like(self.lc_obs["phase"])
401
+ self.lc_obs["GP_lo"] = np.zeros_like(self.lc_obs["phase"])
402
+
403
+ print("Read in the observation, with the shape {}".format(self.lc_obs.shape))
404
+
405
+ # Whisker can only take the ColumnDataSource, not the pandas array
406
+ self.lc_obs = ColumnDataSource(self.lc_obs)
407
+
408
+ def make_header(self):
409
+ """Update the text at the top of the first tab to reflect mcmc_input, and the user defined stuff."""
410
+
411
+ header = "I'm working from the directory: <b>{}</b></br>".format(getcwd())
412
+ header += "This chain has <b>{:,d}</b> burn steps, and <b>{:,d}</b> product steps.</br>".format(
413
+ self.nBurn, self.nProd
414
+ )
415
+ header += " We're using <b>{:,d}</b> walkers,".format(self.nWalkers)
416
+
417
+ if bool(int(self.mcmc_input_dict["usePT"])):
418
+ header += (
419
+ " with parallel tempering sampling <b>{:,d}</b> temperatures,".format(
420
+ int(self.mcmc_input_dict["ntemps"])
421
+ )
422
+ )
423
+
424
+ header += " and running on <b>{:,d}</b> cores.</br>".format(
425
+ int(self.mcmc_input_dict["nthread"])
426
+ )
427
+
428
+ # self.reportChain_label.text = header
429
+
430
+ def write2input(self):
431
+ """Get the slider values, and modify mcmc_input.dat to match them."""
432
+ print("I should write the slider value back to the file!")
433
+
434
+ to_write = {}
435
+
436
+ band = self.current_eclipse.parent
437
+ core = band.parent
438
+
439
+ for par, param in self.current_eclipse.ancestor_param_dict.items():
440
+ if par in core.node_par_names:
441
+ parname_label = "{}".format(par)
442
+ if par in band.node_par_names:
443
+ parname_label = "{}_{}".format(par, band.label)
444
+ if par in self.current_eclipse.node_par_names:
445
+ parname_label = "{}_{}".format(par, self.current_eclipse.label)
446
+
447
+ # Collect the data
448
+ value = param.currVal
449
+ if param.prior.dist.name == "norm":
450
+ p1 = param.prior.kwds.get("loc", 0)
451
+ p2 = param.prior.kwds.get("scale", 1)
452
+ prior_type = "gauss"
453
+ elif param.prior.dist.name == "loguniform":
454
+ p1 = param.prior.a
455
+ p2 = param.prior.b
456
+ prior_type = "log_uniform"
457
+ elif param.prior.dist.name == "uniform":
458
+ p1 = param.prior.kwds.get("loc", 0)
459
+ p2 = param.prior.kwds.get("scale", 1) + p1
460
+ prior_type = "uniform"
461
+ else:
462
+ raise ValueError("Unknown prior type: {}".format(param.prior.dist.name))
463
+
464
+ isVar = param.isVar
465
+
466
+ newline = "{:>10s} = {:>16.8f} {:>12} {:>16.8f} {:>16.8f} {:>12}\n".format(
467
+ parname_label, value, prior_type, p1, p2, isVar
468
+ )
469
+
470
+ to_write[parname_label] = newline
471
+
472
+ with open(self.mcmc_fname, "r") as f:
473
+ mcmc_file = f.readlines()
474
+
475
+ for key, item in to_write.items():
476
+ print("\npar: {}".format(key))
477
+ print("new line:\n{}".format(item))
478
+
479
+ with open(self.mcmc_fname, "w") as f:
480
+ for line in mcmc_file:
481
+ if not line.startswith("#"):
482
+ splitted = line.strip().split(" ")
483
+
484
+ if len(splitted) > 0:
485
+ par = splitted[0]
486
+
487
+ # print("This line in the file starts with: '{}'".format(par))
488
+ if par in to_write.keys():
489
+ # print("Replacing the line with the line:")
490
+ # print(" --> {}".format(to_write[par]))
491
+ line = to_write[par]
492
+
493
+ if par.lower() == "usegp":
494
+ line = "useGP = {}\n".format(int(self.GP_button.active))
495
+ if par.lower() == "complex":
496
+ line = "complex = {}\n".format(int(self.complex))
497
+
498
+ # print("Writing the line:\n{}".format(line))
499
+ f.write(line)
500
+
501
+ def parse_mcmc_input(self):
502
+ """Parse the mcmc input dict, and store the following:
503
+ - self.complex: bool
504
+ Is the model using the simple or complex BS
505
+ - self.GP: bool
506
+ Is the model using the gaussian process?
507
+ - self.nWalkers: int
508
+ How many walkers are expected to be in the chain?
509
+ - self.necl: int
510
+ How many eclipses are we using?
511
+ - self.parDict: dict
512
+ Storage for the variables, including priors and initial guesses.
513
+ - self.nBurn: int
514
+ The number of burn-in steps.
515
+ - self.nProd: int
516
+ The number of product steps.
517
+ """
518
+ print("Parsing the mcmc_input file, '{}'...".format(self.mcmc_fname))
519
+ self.mcmc_input_dict = parseInput(self.mcmc_fname)
520
+
521
+ # Construct the model
522
+ self.model = construct_model(self.mcmc_fname)
523
+
524
+ # Gather the parameters we can use
525
+ self.complex = bool(int(self.mcmc_input_dict["complex"]))
526
+ self.nWalkers = int(self.mcmc_input_dict["nwalkers"])
527
+ self.GP = bool(int(self.mcmc_input_dict["useGP"]))
528
+ self.nBurn = int(self.mcmc_input_dict["nburn"])
529
+ self.nProd = int(self.mcmc_input_dict["nprod"])
530
+
531
+ try:
532
+ self.necl = int(self.mcmc_input_dict["neclipses"])
533
+ except:
534
+ self.necl = len(self.model.search_node_type("Eclipse"))
535
+
536
+ # Query thre model for the eclipses it has
537
+ self.eclipses = list(self.model.search_node_type("Eclipse"))
538
+ self.current_eclipse = self.eclipses[0]
539
+
540
+ # Get the parDict set up
541
+ self.update_par_dict()
542
+
543
+ if self.complex:
544
+ print("Using the simple BS model!")
545
+
546
+ if self.GP:
547
+ print("Using the GP!")
548
+
549
+ self.menu = [
550
+ (ecl.lc.fname, ecl.lc.fname)
551
+ for ecl in self.model.search_node_type("Eclipse")
552
+ ]
553
+ print("The menu looks like this:")
554
+ for m in self.menu:
555
+ print(m)
556
+
557
+ def update_par_dict(self):
558
+ """Take the current eclipse, and update the parDict with its limits
559
+ from the file."""
560
+ print("Updating the parameter dict")
561
+ raw_params = self.current_eclipse.ancestor_param_dict
562
+ print("My current eclipse is {}".format(self.current_eclipse.lc.fname))
563
+
564
+ #  Default values for the complex BS, as simple mcmc_input files may not have them:
565
+ self.parDict = {
566
+ "exp1": [1.00, 0.001, 5.0],
567
+ "exp2": [2.00, 0.001, 5.0],
568
+ "tilt": [45.00, 0.001, 180],
569
+ "yaw": [0.00, -90.0, 90.0],
570
+ "ln_ampin_gp": [-9.99, -25.0, -1.0],
571
+ "ln_ampout_gp": [-9.99, -25.0, -1.0],
572
+ "tau_gp": [0.03, 0.006, 0.1],
573
+ }
574
+
575
+ for key, param in raw_params.items():
576
+ currval = param.currVal
577
+ loc = param.prior.kwds.get("loc", 0)
578
+ scale = param.prior.kwds.get("scale", 1)
579
+ if param.prior.dist.name == "norm":
580
+ lolim = -3.0 * scale + loc
581
+ hilim = 3.0 * scale + loc
582
+ elif param.prior.dist.name == "loguniform":
583
+ # uniform or log uniform
584
+ lolim = param.prior.a
585
+ hilim = param.prior.b
586
+ elif param.prior.dist.name == "uniform":
587
+ lolim = loc
588
+ hilim = loc + scale
589
+ else:
590
+ raise ValueError("Unknown prior type: {}".format(param.prior.dist.name))
591
+
592
+ prior = param.prior.dist.name
593
+ self.parDict[key] = [currval, lolim, hilim, prior]
594
+ print("parDict[{}]: {}".format(key, currval))
595
+
596
+ def reset_sliders(self):
597
+ """Set the parameters to the initial guesses."""
598
+
599
+ print("resetting the sliders to new values.")
600
+ print("Removing the callbacks...")
601
+ all_sliders = self.par_sliders + self.par_sliders_complex + self.par_sliders_GP
602
+
603
+ # Disable the callbacks
604
+ for slider in all_sliders:
605
+ try:
606
+ slider.remove_on_change("value_throttled", self.update_lc_model)
607
+ except:
608
+ print(
609
+ "Slider {} already had its callback removed!".format(slider.title)
610
+ )
611
+ print("Removed all the callbacks.\nSetting the slider values...")
612
+
613
+ print("Here's a list of my slider names!")
614
+ for slider in all_sliders:
615
+ print(" - {}".format(slider.name))
616
+
617
+ for par_name, param in self.parDict.items():
618
+ print("Searching for slider for parameter {}".format(par_name))
619
+ for slider in all_sliders:
620
+ if slider.name == par_name:
621
+ print("Found that slider! Setting value to {}".format(param[0]))
622
+ slider.value = param[0]
623
+ slider.start = param[1]
624
+ slider.end = param[2]
625
+
626
+ # Re-enable the calbacks
627
+ for slider in all_sliders:
628
+ slider.on_change("value_throttled", self.update_lc_model)
629
+
630
+ self.update_lc_model("value_throttled", "", "")
631
+
632
+ print("Done resetting sliders")
633
+
634
+ def update_like_header(self, gp=False):
635
+ print(
636
+ "res: {} data, err: {} data".format(
637
+ len(self.lc_obs.data["res"]), len(self.lc_obs.data["err"])
638
+ )
639
+ )
640
+ chisq = self.lc_obs.data["res"] / self.lc_obs.data["err"]
641
+ chisq = np.sum(chisq**2)
642
+
643
+ print("Chisq = {}".format(chisq))
644
+ print("Updating header")
645
+
646
+ print("label text was before: {}".format(self.like_label.text))
647
+ print("label text is now: {}".format(self.like_label.text))
648
+
649
+ def update_GP(self, new):
650
+ """Update the colour of the GP button"""
651
+ self.GP = self.GP_button.active
652
+ self.GP_button.button_type = "success" if self.GP else "danger"
653
+ if self.GP:
654
+ self.recalc_GP_model("")
655
+
656
+ def update_complex(self, new):
657
+ """Handler for toggling the complex button. This should just enable/disable the complex sliders"""
658
+
659
+ print("Toggling the complex model...")
660
+ print("The complex variable was {}".format("on" if self.complex else "off"))
661
+ self.complex = self.complex_button.active
662
+ print("The complex variable is now {}".format("on" if self.complex else "off"))
663
+
664
+ if self.complex:
665
+ print("Changing to the complex BS model")
666
+ #  Complex sliders update the model
667
+ for slider in self.par_sliders_complex:
668
+ slider.on_change("value_throttled", self.update_lc_model)
669
+ print("Enabled the comlpex sliders")
670
+
671
+ # Initialise a new CV object with the new BS model
672
+ pars = [slider.value_throttled for slider in self.par_sliders]
673
+ pars.extend([slider.value_throttled for slider in self.par_sliders_complex])
674
+ self.cv = CV(pars)
675
+ print("Re-initialised the CV model")
676
+
677
+ self.complex_button.button_type = "success"
678
+
679
+ else:
680
+ print("Changing to the simple BS model")
681
+ #  Change the complex sliders to do nothing
682
+ for slider in self.par_sliders_complex:
683
+ slider.remove_on_change("value_throttled", self.update_lc_model)
684
+ print("Disabled the comlpex sliders")
685
+
686
+ # Initialise a new CV object with the new BS model
687
+ pars = [slider.value_throttled for slider in self.par_sliders]
688
+ print("Re-initialised the CV model")
689
+
690
+ self.complex_button.button_type = "danger"
691
+
692
+ self.update_lc_model("value", "", "")
693
+
694
+ def update_lc_model(self, attr, old, new, debug=False):
695
+ """Callback to recalculate and redraw the CV model"""
696
+
697
+ def print_bug(msg):
698
+ if debug:
699
+ print(msg)
700
+
701
+ print_bug("\n\nCALLED UPDATE_LC_MODEL")
702
+ print_bug(
703
+ "I want to update {} with the slider values.".format(
704
+ self.current_eclipse.name
705
+ )
706
+ )
707
+
708
+ # Get the band this eclipse belongs to
709
+ band = self.current_eclipse.parent
710
+
711
+ # Get a list of the current model parameter values
712
+ par_vals = self.model.dynasty_par_vals
713
+
714
+ # I need to check the complex and GP sliders, as well as the simple
715
+ # ones.
716
+ eclipse_par_sliders = self.par_sliders
717
+ if self.complex:
718
+ print_bug("Using the complex model, so handling those sliders too")
719
+ eclipse_par_sliders += self.par_sliders_complex
720
+
721
+ print_bug("Using the GP, so setting those sliders")
722
+ eclipse_par_sliders += self.par_sliders_GP
723
+
724
+ for i, par_name in enumerate(self.model.dynasty_par_names):
725
+ print_bug("Param {}: {}".format(i, par_name))
726
+ if par_name.endswith(self.current_eclipse.label):
727
+ for slider in eclipse_par_sliders:
728
+ if par_name.startswith(slider.name):
729
+ print_bug(
730
+ "Slider {} found, taking its value".format(slider.name)
731
+ )
732
+ par_vals[i] = slider.value
733
+
734
+ if par_name.endswith(band.label):
735
+ for slider in self.par_sliders:
736
+ if par_name.startswith(slider.name):
737
+ print_bug(
738
+ "Slider {} found, taking its value".format(slider.name)
739
+ )
740
+ par_vals[i] = slider.value
741
+
742
+ if par_name.endswith(self.model.label):
743
+ for slider in self.par_sliders:
744
+ if par_name.startswith(slider.name):
745
+ print_bug(
746
+ "Slider {} found, taking its value".format(slider.name)
747
+ )
748
+ par_vals[i] = slider.value
749
+
750
+ print_bug("I altered the the following parameter vector components:")
751
+ old_pars = self.model.dynasty_par_vals
752
+ for i, (old_par, new_par) in enumerate(zip(old_pars, par_vals)):
753
+ if old_par != new_par:
754
+ print_bug(
755
+ "parameter {} --- Old value: {:.3f} --- New value: {:.3f}".format(
756
+ i, old_par, new_par
757
+ )
758
+ )
759
+ self.model.dynasty_par_vals = par_vals
760
+
761
+ # Pull out a copy of the observations
762
+ new_obs = dict(self.lc_obs.data)
763
+
764
+ # Calculate
765
+ try:
766
+ components = self.current_eclipse.calcComponents()
767
+ self.lc_change_fname_button.button_type = "success"
768
+ self.lc_isvalid.button_type = "success"
769
+ self.console_logs.text = "Model errors will go here!"
770
+ except Exception as e:
771
+ print("Invalid model parameters!")
772
+ print(e)
773
+ self.console_logs.text = str(e)
774
+ self.lc_change_fname_button.button_type = "danger"
775
+ self.lc_isvalid.button_type = "danger"
776
+ self.model.dynasty_par_vals = old_pars
777
+ return
778
+
779
+ # Total model lightcurve
780
+ new_obs["calc"] = components[0]
781
+ new_obs["res"] = new_obs["flux"] - new_obs["calc"]
782
+
783
+ #  Components
784
+ new_obs["wd"] = components[1]
785
+ new_obs["sec"] = components[2]
786
+ new_obs["bspot"] = components[3]
787
+ new_obs["disc"] = components[4]
788
+
789
+ # Push back into lc_obs
790
+ self.lc_obs.data = dict(new_obs)
791
+
792
+ if self.GP:
793
+ self.recalc_GP_model("")
794
+
795
+ def update_lc_obs(self, event):
796
+ """callback to redraw the observations for the lightcurve"""
797
+ print("\n\nCALLED UPDATE_LC_OBS")
798
+ new = event.item
799
+
800
+ print("\nRedrawing the observations")
801
+ print("I want to take the menu item: {}".format(new))
802
+ for ecl in self.eclipses:
803
+ if ecl.lc.fname == new:
804
+ print("Found the eclipse!")
805
+ self.current_eclipse = ecl
806
+
807
+ new_obs = {}
808
+ phi = self.current_eclipse.lc.x
809
+ flx = self.current_eclipse.lc.y
810
+ err = self.current_eclipse.lc.ye
811
+
812
+ new_obs["phase"] = phi
813
+ new_obs["flux"] = flx
814
+ new_obs["err"] = err
815
+
816
+ # Total model lightcurve
817
+ new_obs["calc"] = np.zeros_like(new_obs["phase"])
818
+ new_obs["res"] = np.zeros_like(new_obs["phase"])
819
+ #  Components
820
+ new_obs["sec"] = np.zeros_like(new_obs["phase"])
821
+ new_obs["bspot"] = np.zeros_like(new_obs["phase"])
822
+ new_obs["wd"] = np.zeros_like(new_obs["phase"])
823
+ new_obs["disc"] = np.zeros_like(new_obs["phase"])
824
+ #  GP
825
+ new_obs["GP_up"] = np.zeros_like(new_obs["phase"])
826
+ new_obs["GP_lo"] = np.zeros_like(new_obs["phase"])
827
+
828
+ self.lc_obs.data = DataFrame(new_obs)
829
+
830
+ print("\nUpdate the parDict")
831
+ self.update_par_dict()
832
+
833
+ print("\nReset the sliders")
834
+ self.reset_sliders()
835
+
836
+ print("\nSet the plotting area title")
837
+ fname = self.current_eclipse.lc.name
838
+ band_name = self.current_eclipse.parent.label
839
+ title_text = "{} --- Band: {}".format(fname, band_name)
840
+ print("Trying to change the title of the plot")
841
+ print("Old title: {}".format(self.lc_plot.title.text))
842
+ self.lc_plot.title.text = title_text
843
+ print("The title should now be {}".format(title_text))
844
+
845
+ self.update_lc_model("value_throttled", "", "")
846
+
847
+ # self.update_like_header(gp=self.GP)
848
+
849
+ def calcChangepoints(self):
850
+ """Caclulate the WD ingress and egresses, i.e. where we want to switch
851
+ on or off the extra GP amplitude.
852
+
853
+ Requires an eclipse object, since this is specific to a given phase
854
+ range.
855
+ """
856
+
857
+ # Also get object for dphi, q and rwd as this is required to determine
858
+ # changepoints
859
+ pardict = {}
860
+ for slider in self.par_sliders:
861
+ pardict[slider.name] = slider.value_throttled
862
+
863
+ dphi = pardict["dphi"]
864
+ q = pardict["q"]
865
+ rwd = pardict["rwd"]
866
+ phi0 = pardict["phi0"]
867
+
868
+ # Have they changed significantly?
869
+ # If not, dont bother recalculating dist_cp
870
+ dphi_change = np.fabs(self._olddphi - dphi) / dphi
871
+ q_change = np.fabs(self._oldq - q) / q
872
+ rwd_change = np.fabs(self._oldrwd - rwd) / rwd
873
+
874
+ # Check to see if our model parameters have changed enough to
875
+ # significantly change the location of the changepoints.
876
+ if (dphi_change > 1.2) or (q_change > 1.2) or (rwd_change > 1.2):
877
+ # Calculate inclination
878
+ inc = roche.findi(q, dphi)
879
+
880
+ # Calculate wd contact phases 3 and 4
881
+ phi3, phi4 = roche.wdphases(q, inc, rwd, ntheta=10)
882
+
883
+ # Calculate length of wd egress
884
+ dpwd = phi4 - phi3
885
+
886
+ # Distance from changepoints to mideclipse
887
+ dist_cp = (dphi + dpwd) / 2.0
888
+
889
+ # save these values for speed
890
+ self._dist_cp = dist_cp
891
+ self._oldq = q
892
+ self._olddphi = dphi
893
+ self._oldrwd = rwd
894
+ else:
895
+ # Use the old values
896
+ dist_cp = self._dist_cp
897
+
898
+ # Find location of all changepoints
899
+ phase = self.lc_obs.data["phase"]
900
+ min_ecl = int(np.floor(phase.min()))
901
+ max_ecl = int(np.ceil(phase.max()))
902
+
903
+ eclipses = [
904
+ e
905
+ for e in range(min_ecl, max_ecl + 1)
906
+ if np.logical_and(e > phase.min(), e < 1 + phase.max())
907
+ ]
908
+
909
+ changepoints = []
910
+ for e in eclipses:
911
+ # When did the last eclipse end?
912
+ egress = (e - 1) + dist_cp + phi0
913
+ # When does this eclipse start?
914
+ ingress = e - dist_cp + phi0
915
+ changepoints.append([egress, ingress])
916
+
917
+ return changepoints
918
+
919
+ def create_GP(self):
920
+ """Constructs a kernel, which is used to create Gaussian processes.
921
+
922
+ Creates kernels for both inside and out of eclipse,
923
+ works out the location of any changepoints present, constructs a single
924
+ (mixed) kernel and uses this kernel to create GPs
925
+
926
+ Requires an Eclipse object to create the GP for."""
927
+
928
+ # Get objects for ln_ampin_gp, ln_ampout_gp, tau_gp and find the exponential
929
+ # of their current values
930
+ pardict = {}
931
+ for slider in self.par_sliders_GP:
932
+ pardict[slider.name] = slider.value_throttled
933
+
934
+ ln_ampin = pardict["ln_ampin_gp"]
935
+ ln_ampout = pardict["ln_ampout_gp"]
936
+ tau = pardict["tau_gp"]
937
+
938
+ ampin_gp = np.exp(ln_ampin)
939
+ ampout_gp = np.exp(ln_ampout)
940
+ tau_gp = tau
941
+
942
+ # Calculate kernels for both out of and in eclipse WD eclipse
943
+ # Kernel inside of WD has smaller amplitude than that of outside
944
+ # eclipse.
945
+
946
+ # First, get the changepoints
947
+ changepoints = self.calcChangepoints()
948
+
949
+ # We need to make a fairly complex kernel.
950
+ # Global flicker
951
+ kernel = ampin_gp * g.kernels.Matern32Kernel(tau_gp**2)
952
+ # inter-eclipse flicker
953
+ for gap in changepoints:
954
+ kernel += ampout_gp * g.kernels.Matern32Kernel(tau_gp**2, block=gap)
955
+
956
+ # Use that kernel to make a GP object
957
+ georgeGP = g.GP(kernel, solver=g.HODLRSolver)
958
+
959
+ return georgeGP
960
+
961
+ def recalc_GP_model(self, new):
962
+ """Update the GP model"""
963
+ lc_obs = dict(self.lc_obs.data)
964
+
965
+ phi = lc_obs["phase"]
966
+ err = lc_obs["err"]
967
+ res = lc_obs["res"]
968
+
969
+ # Create the GP
970
+ gp = self.create_GP()
971
+
972
+ # Compute the matrix
973
+ gp.compute(phi)
974
+
975
+ # Draw samples from the GP
976
+ samples = gp.sample_conditional(res, phi, size=100)
977
+
978
+ # Get the mean, mu, standard deviation, and
979
+ mu = np.mean(samples, axis=0)
980
+ std = np.std(samples, axis=0)
981
+
982
+ lc_obs["GP_up"] = mu + std
983
+ lc_obs["GP_lo"] = mu - std
984
+
985
+ self.lc_obs.data = lc_obs
986
+
987
+ def junk(self, attr, old, new):
988
+ """Sometimes, you just don't want to do anything"""
989
+ # print("Calling the junk pile")
990
+ pass
991
+
992
+
993
+ if __name__ == "__main__":
994
+ print("This app must be run within a bokeh server:")
995
+ print(" lfit-watch mcmc_input.dat")
996
+ print("Stopping!")
997
+ else:
998
+ # bokeh passes `--args` through in sys.argv
999
+ mc_fname = sys.argv[1] if len(sys.argv) > 1 else "mcmc_input.dat"
1000
+
1001
+ watcher = Watcher(mcmc_input=mc_fname)