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,864 @@
1
+ """
2
+ Subclasses from the `model` module, that actually comprise the tree
3
+ structure of the model fed to emcee. The `trunk` is an LCModel or GPLCModel
4
+ node, with child Bands, that have XEclipse leaves to evaluate the CV lightcurve
5
+ fit to the data. Data is stored in the Lightcurve class.
6
+ """
7
+
8
+ import os
9
+
10
+ import configobj
11
+ import george
12
+ import lfit_rs as lfit
13
+ import numpy as np
14
+ import roche
15
+
16
+ from .model import Node, Param, extract_par_and_key
17
+
18
+ BIG = 9e99
19
+
20
+
21
+ class Lightcurve:
22
+ """This object keeps track of the observational data.
23
+ Can be generated from a file, with Lightcurve.from_calib(file)."""
24
+
25
+ def __init__(self, name, x, y, ye, w=None):
26
+ """Here, hold this."""
27
+ self.name = name
28
+
29
+ self.fname = None
30
+
31
+ if w is None:
32
+ w = np.mean(np.diff(x)) * np.ones_like(x) / 2.0
33
+
34
+ self.x = x
35
+ self.y = y
36
+ self.ye = ye
37
+ self.w = w
38
+
39
+ @property
40
+ def n_data(self):
41
+ return self.x.shape[0]
42
+
43
+ @classmethod
44
+ def from_calib(cls, fname, name=None):
45
+ """Read in a calib file, of the format;
46
+ phase flux error
47
+
48
+ and treat lines with # as commented out.
49
+ """
50
+ delimiters = " ,|"
51
+ for delimiter in delimiters:
52
+ try:
53
+ data = np.loadtxt(fname, delimiter=delimiter, comments="#")
54
+ break
55
+ except ValueError:
56
+ print(
57
+ "Couldn't split the calib file with '{}', trying next delimiter...".format(
58
+ delimiter
59
+ )
60
+ )
61
+ try:
62
+ phase, flux, error = data.T
63
+ except ValueError:
64
+ # we probably have a Tseries style file
65
+ phase, _, flux, error, bmask = data.T
66
+
67
+ # Filter out nans.
68
+ mask = np.where(np.isnan(flux) == 0)
69
+
70
+ phase = phase[mask]
71
+ flux = flux[mask]
72
+ error = error[mask]
73
+
74
+ width = np.mean(np.diff(phase)) * np.ones_like(phase)
75
+
76
+ # Set the name of this eclipse as the filename of the data file.
77
+ if name is None:
78
+ _, name = os.path.split(fname)
79
+
80
+ lc = cls(name, phase, flux, error, width)
81
+ lc.fname = fname
82
+ return lc
83
+
84
+ def trim(self, lo, hi):
85
+ """Trim the data, so that all points are in the x range lo > xi > hi"""
86
+ xt = self.x
87
+
88
+ mask = (xt > lo) & (xt < hi)
89
+
90
+ self.x = self.x[mask]
91
+ self.y = self.y[mask]
92
+ self.ye = self.ye[mask]
93
+ self.w = self.w[mask]
94
+
95
+
96
+ # Subclasses.
97
+ class SimpleEclipse(Node):
98
+ """Subclass of Node, specifically for storing a single eclipse.
99
+ Uses the simple BS model.
100
+ Lightcurve data is stored on this level.
101
+
102
+ Inputs:
103
+ -------
104
+ lightcurve; Lightcurve:
105
+ A Lightcurve object, containing data
106
+ label; str:
107
+ A label to apply to the node. Mostly used when searching trees.
108
+ parameter_objects; list(Param), or Param:
109
+ The parameter objects that correspond to this node. Single Param is
110
+ also accepted.
111
+ parent; Node, optional:
112
+ The parent of this node.
113
+ children; list(Node), or Node:
114
+ The children of this node. Single Node is also accepted
115
+ """
116
+
117
+ # Define this subclasses parameters
118
+ node_par_names = ("dFlux", "sFlux", "rdisc", "scale", "az", "fis", "dexp", "phi0")
119
+
120
+ def __init__(self, lightcurve, *args, **kwargs):
121
+ super().__init__(*args, **kwargs)
122
+
123
+ # If the lightcurve is a Lightcurve object, save it. Otherwise,
124
+ # read it in from the file.
125
+ if isinstance(lightcurve, Lightcurve):
126
+ self.lc = lightcurve
127
+ elif isinstance(lightcurve, str):
128
+ self.lc = Lightcurve.from_calib(lightcurve)
129
+ else:
130
+ msg = "Argument lightcurve is not a string or Lightcurve! "
131
+ msg += "Got {}".format(lightcurve)
132
+ raise TypeError(msg)
133
+
134
+ # Create the CV object
135
+ self.cv = lfit.CV(self.cv_parlist)
136
+
137
+ self.log(
138
+ "SimpleEclipse.__init__", "Successfully ran the SimpleEclipse initialiser."
139
+ )
140
+
141
+ def calcFlux(self):
142
+ """Fetch the CV parameter vector, and generate it's model lightcurve"""
143
+ # Get the model CV lightcurve across our data.
144
+ try:
145
+ flx = self.cv.calcFlux(self.cv_parlist, self.lc.x, self.lc.w)
146
+ except Exception as e:
147
+ # print(repr(e))
148
+ # msg = "Error: {}; parlist: {}".format(str(e), repr(self.cv_parlist))
149
+ # print(msg)
150
+ flx = np.nan
151
+ return flx
152
+
153
+ def calcComponents(self):
154
+ """Return a list of the component fluxes as well as the total
155
+ returns:
156
+ (tot_flx, wdFlux, sFlux, rsFlux, dFlux)
157
+ """
158
+ flx = self.cv.calcFlux(self.cv_parlist, self.lc.x, self.lc.w)
159
+ return flx, self.cv.ywd, self.cv.ys, self.cv.yrs, self.cv.yd
160
+
161
+ def chisq(self):
162
+ """Return the chisq of this eclipse, given current params."""
163
+ flx = self.calcFlux()
164
+
165
+ # If the model gets any nans, return inf
166
+ if np.any(np.isnan(flx)):
167
+ return BIG
168
+
169
+ # Calculate the chisq of this model.
170
+ chisq = ((self.lc.y - flx) / self.lc.ye) ** 2
171
+ chisq = np.sum(chisq)
172
+
173
+ return chisq
174
+
175
+ def ln_like(self):
176
+ """Calculate the chisq of this eclipse, against the data stored in its
177
+ lightcurve object."""
178
+
179
+ chisq = self.chisq()
180
+ return -0.5 * chisq
181
+
182
+ def check_validity(self) -> bool:
183
+ """
184
+ Check for validity of the parameters at this level.
185
+
186
+ Some parameter combinations are invalid (e.g: no eclipse for q and dphi). Here we
187
+ check for any of these invalid combinations
188
+ """
189
+ # Before we start, I'm going to collect the necessary parameters. By
190
+ # only calling this once, we save a little effort.
191
+ ancestor_param_dict = self.ancestor_param_dict
192
+
193
+ ##############################################
194
+ # ~~ Is the disc large enough to precess? ~~ #
195
+ ##############################################
196
+
197
+ # Defined the maximum size of the disc before it starts precessing, as
198
+ # a fraction of Roche Radius
199
+ rdisc_max_a = 0.46
200
+
201
+ # get the location of the L1 point from q
202
+ q = ancestor_param_dict["q"].currVal
203
+ try:
204
+ xl1 = roche.xl1(q)
205
+ except AssertionError:
206
+ return False
207
+
208
+ # Get the rdisc, scaled to the Roche Radius
209
+ rdisc = ancestor_param_dict["rdisc"].currVal
210
+ rdisc_a = rdisc * xl1
211
+ ##############################################
212
+ # ~~~~~ Does the stream miss the disc? ~~~~~ #
213
+ ##############################################
214
+ try:
215
+ # If the stream does not intersect the disc, this throws an error
216
+ r, _ = roche.bspot(q, rdisc_a)
217
+ except Exception:
218
+ return False
219
+
220
+ """
221
+ if rdisc_a > rdisc_max_a:
222
+ return False
223
+
224
+ ##############################################
225
+ # ~~~~~ Is the BS scale physically OK? ~~~~~ #
226
+ ##############################################
227
+ # We're gonna check to see if the BS scle is #
228
+ # in the range rwd/4 < (BS scale) < rwd*3. #
229
+ # If it isn't, then it's either too #
230
+ # concentrated to make sense, or so large #
231
+ # that our approximation of a smooth disc is #
232
+ # no longer a good idea. #
233
+ #
234
+ # We'll also check the BS scale is less than #
235
+ # 1/10th, since otherwise the bright spot #
236
+ # might extend more than one separation from #
237
+ # the spot position. #
238
+ ##############################################
239
+
240
+ # Get the WD radius.
241
+ rwd = ancestor_param_dict["rwd"].currVal
242
+
243
+ # Enforce the BS scale being within these limits
244
+ rmax = min(1 / 10, rwd * 4.0)
245
+ rmin = rwd / 4.0
246
+
247
+ scale = ancestor_param_dict["scale"].currVal
248
+ if scale > rmax or scale < rmin:
249
+ return False
250
+ """
251
+
252
+ # If we pass all that, then the parameters are valid.
253
+ return True
254
+
255
+ @property
256
+ def cv_parnames(self):
257
+ names = [
258
+ "wdFlux",
259
+ "dFlux",
260
+ "sFlux",
261
+ "rsFlux",
262
+ "q",
263
+ "dphi",
264
+ "rdisc",
265
+ "ulimb",
266
+ "rwd",
267
+ "scale",
268
+ "az",
269
+ "fis",
270
+ "dexp",
271
+ "phi0",
272
+ ]
273
+
274
+ return names
275
+
276
+ @property
277
+ def cv_parlist(self):
278
+ """Construct the parameter list needed by the CV"""
279
+
280
+ par_name_list = self.cv_parnames
281
+
282
+ param_dict = self.ancestor_param_dict
283
+ try:
284
+ parlist = [param_dict[key].currVal for key in par_name_list]
285
+ except KeyError as error:
286
+ print("Parameter dict:")
287
+ print("{")
288
+ for key, val in param_dict.items():
289
+ print(" {}: {}".format(key, val))
290
+ print("}")
291
+ raise error
292
+ return parlist
293
+
294
+
295
+ class ComplexEclipse(SimpleEclipse):
296
+ """Subclass of Node, specifically for storing a single eclipse.
297
+ Uses the complex BS model.
298
+ Lightcurve data is stored on this level.
299
+
300
+ Inputs:
301
+ -------
302
+ lightcurve; Lightcurve:
303
+ A Lightcurve object, containing data
304
+ label; str:
305
+ A label to apply to the node. Mostly used when searching trees.
306
+ parameter_objects; list(Param), or Param:
307
+ The parameter objects that correspond to this node. Single Param is
308
+ also accepted.
309
+ parent; Node, optional:
310
+ The parent of this node.
311
+ children; list(Node), or Node:
312
+ The children of this node. Single Node is also accepted
313
+ """
314
+
315
+ node_par_names = (
316
+ "dFlux",
317
+ "sFlux",
318
+ "rdisc",
319
+ "scale",
320
+ "az",
321
+ "fis",
322
+ "dexp",
323
+ "phi0",
324
+ "exp1",
325
+ "exp2",
326
+ "yaw",
327
+ "tilt",
328
+ )
329
+
330
+ @property
331
+ def cv_parnames(self):
332
+ names = [
333
+ "wdFlux",
334
+ "dFlux",
335
+ "sFlux",
336
+ "rsFlux",
337
+ "q",
338
+ "dphi",
339
+ "rdisc",
340
+ "ulimb",
341
+ "rwd",
342
+ "scale",
343
+ "az",
344
+ "fis",
345
+ "dexp",
346
+ "phi0",
347
+ "exp1",
348
+ "exp2",
349
+ "tilt",
350
+ "yaw",
351
+ ]
352
+
353
+ return names
354
+
355
+ def check_validity(self) -> bool:
356
+ """
357
+ Check for validity of the parameters at this level.
358
+
359
+ Some parameter combinations are invalid (e.g: no eclipse for q and dphi). Here we
360
+ check for any of these invalid combinations
361
+ """
362
+ # Before we start, I'm going to collect the necessary parameters. By
363
+ # only calling this once, we save a little effort.
364
+ ancestor_param_dict = self.ancestor_param_dict
365
+
366
+ ##############################################
367
+ # ~~~~ Is the bright spot max sensible? ~~~~ #
368
+ ##############################################
369
+ # The location of the bright spot max is #
370
+ # (in units of scale lengths) given by #
371
+ # pow(exp1/exp2, 1/exp2) #
372
+ exp1 = ancestor_param_dict["exp1"].currVal
373
+ exp2 = ancestor_param_dict["exp2"].currVal
374
+ bs_max = pow(exp1 / exp2, 1 / exp2)
375
+ if bs_max > 5:
376
+ return False
377
+
378
+ return super().check_validity()
379
+
380
+
381
+ class Band(Node):
382
+ """Subclass of Node, specific to observation bands. Contains the eclipse
383
+ objects taken in this band.
384
+
385
+ Inputs:
386
+ -------
387
+ label; str:
388
+ A label to apply to the node. Mostly used when searching trees.
389
+ parameter_objects; list(Param), or Param:
390
+ The parameter objects that correspond to this node. Single Param is
391
+ also accepted.
392
+ parent; Node, optional:
393
+ The parent of this node.
394
+ children; list(Node), or Node:
395
+ The children of this node. Single Node is also accepted
396
+ """
397
+
398
+ # What kind of parameters are we storing here?
399
+ node_par_names = ("wdFlux", "rsFlux", "ulimb")
400
+
401
+ @property
402
+ def eclipses(self):
403
+ return list(self.search_node_type("Eclipse"))
404
+
405
+
406
+ class LCModel(Node):
407
+ """Top layer Node class. Contains Bands, which contain Eclipses.
408
+ Inputs:
409
+ -------
410
+ label; str:
411
+ A label to apply to the node. Mostly used when searching trees.
412
+ parameter_objects; list(Param), or Param:
413
+ The parameter objects that correspond to this node. Single Param is
414
+ also accepted.
415
+ parent; Node, optional:
416
+ The parent of this node.
417
+ children; list(Node), or Node:
418
+ The children of this node. Single Node is also accepted
419
+ """
420
+
421
+ # Set the parameter names for this layer
422
+ node_par_names = ("q", "dphi", "rwd")
423
+
424
+ @property
425
+ def eclipses(self):
426
+ return list(self.search_node_type("Eclipse"))
427
+
428
+ def check_validity(self) -> bool:
429
+ """
430
+ Check for invalid parameter combinations.
431
+
432
+ This is the top level check (for q and dphi). If this is OK, we will also
433
+ check the validity of the children nodes, which will check for other invalid combinations.
434
+ """
435
+ dphi = getattr(self, "dphi").currVal
436
+ q = getattr(self, "q").currVal
437
+ if q <= 0.0 or dphi <= 0.0:
438
+ return False
439
+ # check for invalid q, dphi (phase width too large for q)
440
+ if roche.findi(q, dphi) < 0.0:
441
+ return False
442
+
443
+ # if the top level is OK, call Node's check validity, which will
444
+ # descend into the children and check their validity as well
445
+ return super().check_validity()
446
+
447
+ def ln_like(self):
448
+ """
449
+ Calculate the log likelihood of the model.
450
+
451
+ First we evaluate the validity of the model and return -inf if invalid.
452
+ If valid, we call the super class ln_like, which will descend into the children
453
+ and calculate the log likelihood of the model.
454
+ """
455
+ if not self.check_validity():
456
+ return -np.inf
457
+ return super().ln_like()
458
+
459
+
460
+ class GPLCModel(LCModel):
461
+ """This is a subclass of the LCModel class. It uses the Gaussian Process.
462
+
463
+ This version will, rather than evaluating via chisq, evaluate the
464
+ likelihood of the model by calculating the residuals between the model
465
+ and the data and computing the likelihood of those data given certain
466
+ Gaussian Process hyper-parameters.
467
+
468
+ These parameters require some explaination.
469
+ tau_gp:
470
+ the timescale of the covariance matrix
471
+ ln_ampin_gp:
472
+ The base amplitude of the covariance matrix
473
+ ln_ampout_gp:
474
+ The additional amplitude of the covariance matrix, when the WD
475
+ is visible
476
+ """
477
+
478
+ # Add the GP params
479
+ node_par_names = LCModel.node_par_names
480
+ node_par_names += ("ln_ampin_gp", "ln_ampout_gp", "tau_gp")
481
+
482
+
483
+ class SimpleGPEclipse(SimpleEclipse):
484
+ # Set the initial values of q, rwd, and dphi. These will be used to
485
+ # caclulate the location of the GP changepoints. Setting to initially
486
+ # unrealistically high values will ensure that the first time
487
+ # calcChangepoints is called, the changepoints are calculated.
488
+ _olddphi = 9e99
489
+ _oldq = 9e99
490
+ _oldrwd = 9e99
491
+
492
+ # _dist_cp is initially set to whatever, it will be overwritten anyway.
493
+ _dist_cp = 9e99
494
+
495
+ def calcChangepoints(self):
496
+ """Caclulate the WD ingress and egresses, i.e. where we want to switch
497
+ on or off the extra GP amplitude.
498
+
499
+ Requires an eclipse object, since this is specific to a given phase
500
+ range.
501
+ """
502
+
503
+ self.log("SimpleGPEclipse.calcChangepoints", "Calculating GP changepoints")
504
+
505
+ # Also get object for dphi, q and rwd as this is required to determine
506
+ # changepoints
507
+ pardict = self.ancestor_param_dict
508
+
509
+ dphi = pardict["dphi"]
510
+ q = pardict["q"]
511
+ rwd = pardict["rwd"]
512
+ phi0 = pardict["phi0"]
513
+
514
+ # Have they changed significantly?
515
+ # If not, dont bother recalculating dist_cp
516
+ dphi_change = np.fabs(self._olddphi - dphi.currVal) / dphi.currVal
517
+ q_change = np.fabs(self._oldq - q.currVal) / q.currVal
518
+ rwd_change = np.fabs(self._oldrwd - rwd.currVal) / rwd.currVal
519
+
520
+ # Check to see if our model parameters have changed enough to
521
+ # significantly change the location of the changepoints.
522
+ if (dphi_change > 1.2) or (q_change > 1.2) or (rwd_change > 1.2):
523
+ self.log(
524
+ "SimpleGPEclipse.calcChangepoints",
525
+ "The GP changepoint locations have chnged significantly enough to warrant a recalculation...",
526
+ )
527
+
528
+ # Calculate inclination
529
+ inc = roche.findi(q.currVal, dphi.currVal)
530
+
531
+ # Calculate wd contact phases 3 and 4
532
+ phi3, phi4 = roche.wdphases(q.currVal, inc, rwd.currVal, ntheta=10)
533
+
534
+ # Calculate length of wd egress
535
+ dpwd = phi4 - phi3
536
+
537
+ # Distance from changepoints to mideclipse
538
+ dist_cp = (dphi.currVal + dpwd) / 2.0
539
+
540
+ # save these values for speed
541
+ self._dist_cp = dist_cp
542
+ self._oldq = q.currVal
543
+ self._olddphi = dphi.currVal
544
+ self._oldrwd = rwd.currVal
545
+ else:
546
+ self.log("SimpleGPEclipse.calcChangepoints", "Using old values of dist_cp")
547
+ # Use the old values
548
+ dist_cp = self._dist_cp
549
+
550
+ # Find location of all changepoints
551
+ min_ecl = int(np.floor(self.lc.x.min()))
552
+ max_ecl = int(np.ceil(self.lc.x.max()))
553
+
554
+ eclipses = [
555
+ e
556
+ for e in range(min_ecl, max_ecl + 1)
557
+ if np.logical_and(e > self.lc.x.min(), e < 1 + self.lc.x.max())
558
+ ]
559
+
560
+ changepoints = []
561
+ for e in eclipses:
562
+ # When did the last eclipse end?
563
+ egress = (e - 1) + dist_cp + phi0.currVal
564
+ # When does this eclipse start?
565
+ ingress = e - dist_cp + phi0.currVal
566
+ changepoints.append([egress, ingress])
567
+
568
+ self.log(
569
+ "SimpleGPEclipse.calcChangepoints",
570
+ "Computed GP changepoints as:\n{}".format(changepoints),
571
+ )
572
+ return changepoints
573
+
574
+ def create_GP(self):
575
+ """Constructs a kernel, which is used to create Gaussian processes.
576
+
577
+ Creates kernels for both inside and out of eclipse,
578
+ works out the location of any changepoints present, constructs a single
579
+ (mixed) kernel and uses this kernel to create GPs
580
+
581
+ Requires an Eclipse object to create the GP for."""
582
+
583
+ self.log("SimpleGPEclipse.create_GP", "Creating a new GP")
584
+
585
+ # Get objects for ln_ampin_gp, ln_ampout_gp, tau_gp and find the exponential
586
+ # of their current values
587
+ pardict = self.ancestor_param_dict
588
+
589
+ ln_ampin = pardict["ln_ampin_gp"]
590
+ ln_ampout = pardict["ln_ampout_gp"]
591
+ tau = pardict["tau_gp"]
592
+
593
+ ampin_gp = np.exp(ln_ampin.currVal)
594
+ ampout_gp = np.exp(ln_ampout.currVal)
595
+ tau_gp = tau.currVal
596
+
597
+ # Calculate kernels for both out of and in eclipse WD eclipse
598
+ # Kernel inside of WD has smaller amplitude than that of outside
599
+ # eclipse.
600
+
601
+ # First, get the changepoints
602
+ changepoints = self.calcChangepoints()
603
+
604
+ # We need to make a fairly complex kernel.
605
+ # Global flicker
606
+ self.log("SimpleGPEclipse.create_GP", "Constructing a new kernel")
607
+ kernel = ampin_gp * george.kernels.Matern32Kernel(tau_gp**2)
608
+ # inter-eclipse flicker
609
+ for gap in changepoints:
610
+ kernel += ampout_gp * george.kernels.Matern32Kernel(tau_gp**2, block=gap)
611
+
612
+ # Use that kernel to make a GP object
613
+ georgeGP = george.GP(kernel, solver=george.HODLRSolver)
614
+
615
+ self.log("SimpleGPEclipse.create_GP", "Successfully created a new GP!")
616
+ return georgeGP
617
+
618
+ def ln_like(self):
619
+ """The GP sits at the top of the tree. It replaces the LCModel
620
+ class. When the evaluate function is called, this class should
621
+ hijack it, calculate the residuals of all the eclipses in the tree,
622
+ and find the likelihood of each of those residuals given the current GP
623
+ hyper-parameters.
624
+
625
+ Inputs:
626
+ -------
627
+ label; str:
628
+ A label to apply to the node. Mostly used when searching trees.
629
+ parameter_objects; list(Param), or Param:
630
+ The parameter objects that correspond to this node. Single Param is
631
+ also accepted.
632
+ parent; Node, optional:
633
+ The parent of this node.
634
+ children; list(Node), or Node:
635
+ The children of this node. Single Node is also accepted
636
+ """
637
+
638
+ self.log("SimpleGPEclipse.ln_like", "Computing ln_like for a GP")
639
+
640
+ # For each eclipse, I want to know the log likelihood of its residuals
641
+ gp_ln_like = 0.0
642
+
643
+ # Get the residuals of the model
644
+ residuals = self.lc.y - self.calcFlux()
645
+ # Did the model turn out ok?
646
+ if np.any(np.isinf(residuals)) or np.any(np.isnan(residuals)):
647
+ if self.DEBUG:
648
+ msg = "GP ln_like computed inf or nan residuals for the model. Returning -np.inf for the likelihood."
649
+ self.log("SimpleGPEclipse.ln_like", msg)
650
+ return -np.inf
651
+
652
+ # Create the GP of this eclipse
653
+ gp = self.create_GP()
654
+ # Compute the GP
655
+ gp.compute(self.lc.x, self.lc.ye)
656
+
657
+ # The 'quiet' argument tells the GP to return -inf when you get
658
+ # an invalid kernel, rather than throwing an exception.
659
+ gp_ln_like = gp.log_likelihood(residuals, quiet=True)
660
+
661
+ if self.DEBUG:
662
+ self.log(
663
+ "SimpleGPEclipse.ln_like",
664
+ "GP computed a ln_like of {}".format(gp_ln_like),
665
+ )
666
+
667
+ return gp_ln_like
668
+
669
+
670
+ class ComplexGPEclipse(SimpleGPEclipse):
671
+ # Exactly as the simple GP Eclipse, but this time with the extra 4 params.
672
+ node_par_names = ComplexEclipse.node_par_names
673
+
674
+ @property
675
+ def cv_parnames(self):
676
+ names = [
677
+ "wdFlux",
678
+ "dFlux",
679
+ "sFlux",
680
+ "rsFlux",
681
+ "q",
682
+ "dphi",
683
+ "rdisc",
684
+ "ulimb",
685
+ "rwd",
686
+ "scale",
687
+ "az",
688
+ "fis",
689
+ "dexp",
690
+ "phi0",
691
+ "exp1",
692
+ "exp2",
693
+ "tilt",
694
+ "yaw",
695
+ ]
696
+
697
+ return names
698
+
699
+
700
+ def construct_model(input_file, nodata=False, debug=False):
701
+ """Takes an input filename, and parses it into a model tree.
702
+
703
+ Inputs:
704
+ -------
705
+ input_file, str:
706
+ The input.dat file to be parsed
707
+ nodata, bool:
708
+ Use a blank dummy lightcurve instead of reading the data files.
709
+ debug, bool:
710
+ Enable the debugging flag for the Nodes. Debugging will be written to
711
+ the DEBUGGING directory.
712
+
713
+ Output:
714
+ -------
715
+ model root node
716
+ """
717
+
718
+ input_dict = configobj.ConfigObj(input_file)
719
+
720
+ # Do we use the complex model? Do we use the GP?
721
+ is_complex = bool(int(input_dict["complex"]))
722
+ use_gp = bool(int(input_dict["useGP"]))
723
+
724
+ # neclipses no longer strictly necessary, but can be used to limit the
725
+ # maximum number of fitted eclipses
726
+ try:
727
+ neclipses = int(input_dict["neclipses"])
728
+ except KeyError:
729
+ # Read in all the available eclipses
730
+ neclipses = 9999
731
+
732
+ # # # # # # # # # # # # # # # # #
733
+ # Get the initial model setup # #
734
+ # # # # # # # # # # # # # # # # #
735
+ # Start by creating the overall Node. Gather the parameters:
736
+ if use_gp:
737
+ core_par_names = GPLCModel.node_par_names
738
+ core_pars = [
739
+ Param.fromString(name, input_dict[name]) for name in core_par_names
740
+ ]
741
+
742
+ # and make the model object with no children
743
+ model = GPLCModel("core", core_pars)
744
+ else:
745
+ core_par_names = LCModel.node_par_names
746
+ core_pars = [
747
+ Param.fromString(name, input_dict[name]) for name in core_par_names
748
+ ]
749
+
750
+ # and make the model object with no children
751
+ model = LCModel("core", core_pars)
752
+
753
+ # # # # # # # # # # # # # # # # #
754
+ # # # Now do the band names # # #
755
+ # # # # # # # # # # # # # # # # #
756
+
757
+ # Collect the bands and their params. Add them total model.
758
+ band_par_names = Band.node_par_names
759
+ if not use_gp:
760
+ # Use the Eclipse class to find the parameters we're interested in
761
+ if is_complex:
762
+ ecl_pars = ComplexEclipse.node_par_names
763
+ else:
764
+ ecl_pars = SimpleEclipse.node_par_names
765
+
766
+ else:
767
+ # Use the Eclipse class to find the parameters we're interested in
768
+ if is_complex:
769
+ ecl_pars = ComplexGPEclipse.node_par_names
770
+
771
+ else:
772
+ ecl_pars = SimpleGPEclipse.node_par_names
773
+
774
+ # I care about the order in which eclipses and bands are defined.
775
+ # Collect that order here.
776
+ defined_bands = []
777
+ defined_eclipses = []
778
+ with open(input_file, "r") as input_file_obj:
779
+ for line in input_file_obj:
780
+ line = line.strip().split()
781
+
782
+ if len(line):
783
+ key = line[0]
784
+
785
+ # Check that the key starts with any of the band pars
786
+ if np.any([key.startswith(par) for par in band_par_names]):
787
+ # Strip off the variable part, and keep only the label
788
+ _, key = extract_par_and_key(key)
789
+ if key not in defined_bands:
790
+ defined_bands.append(key)
791
+
792
+ # Check that the key starts with any of the eclipse pars
793
+ if np.any([key.startswith(par) for par in ecl_pars]):
794
+ # Strip off the variable part, and keep only the label
795
+ _, key = extract_par_and_key(key)
796
+ if key not in defined_eclipses:
797
+ defined_eclipses.append(key)
798
+
799
+ # Collect the band params into their Band objects.
800
+ for label in defined_bands:
801
+ band_pars = []
802
+
803
+ # Build the Param objects for this band
804
+ for par in band_par_names:
805
+ # Construct the parameter key and retrieve the string
806
+ key = "{}_{}".format(par, label)
807
+ string = input_dict[key]
808
+
809
+ # Make the Param object, and save it
810
+ band_pars.append(Param.fromString(par, string))
811
+
812
+ # Define the band as a child of the model.
813
+ Band(label, band_pars, parent=model)
814
+
815
+ # # # # # # # # # # # # # # # # #
816
+ # # Finally, get the eclipses # #
817
+ # # # # # # # # # # # # # # # # #
818
+
819
+ lo = float(input_dict["phi_start"])
820
+ hi = float(input_dict["phi_end"])
821
+
822
+ for label in defined_eclipses[:neclipses]:
823
+ # Get the list of parameters, and their priors
824
+ params = []
825
+ for par in ecl_pars:
826
+ key = "{}_{}".format(par, label)
827
+ param = Param.fromString(par, input_dict[key])
828
+
829
+ params.append(param)
830
+
831
+ if nodata:
832
+ print("Using a roughly blank data dummy.")
833
+ x = np.linspace(-0.5, 0.5, 1000)
834
+ y = np.zeros_like(x)
835
+ yerr = np.ones_like(y)
836
+
837
+ lc = Lightcurve("Dummy_Data_{}".format(label), x, y, yerr)
838
+
839
+ else:
840
+ # Get the observational data
841
+ lc_fname = input_dict["file_{}".format(label)]
842
+ lc = Lightcurve.from_calib(lc_fname)
843
+ lc.trim(lo, hi)
844
+
845
+ # Get the band object that this eclipse belongs to
846
+ my_band_label = input_dict["band_{}".format(label)]
847
+ my_band = model.search_Node("Band", my_band_label)
848
+
849
+ if use_gp:
850
+ if is_complex:
851
+ ComplexGPEclipse(lc, label, params, parent=my_band)
852
+ else:
853
+ SimpleGPEclipse(lc, label, params, parent=my_band)
854
+ else:
855
+ if is_complex:
856
+ ComplexEclipse(lc, label, params, parent=my_band)
857
+ else:
858
+ SimpleEclipse(lc, label, params, parent=my_band)
859
+
860
+ # Make sure that all the model's Band have eclipses. Otherwise, prune them
861
+ model.children = [band for band in model.children if len(band.children)]
862
+
863
+ model.DEBUG = debug
864
+ return model