lfit-python 0.1.0__tar.gz

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 (88) hide show
  1. lfit_python-0.1.0/PKG-INFO +222 -0
  2. lfit_python-0.1.0/README.md +190 -0
  3. lfit_python-0.1.0/pyproject.toml +55 -0
  4. lfit_python-0.1.0/setup.cfg +4 -0
  5. lfit_python-0.1.0/src/lfit_python/__init__.py +27 -0
  6. lfit_python-0.1.0/src/lfit_python/chains.py +157 -0
  7. lfit_python-0.1.0/src/lfit_python/cli/__init__.py +1 -0
  8. lfit_python-0.1.0/src/lfit_python/cli/limbdark.py +64 -0
  9. lfit_python-0.1.0/src/lfit_python/cli/mcmcfit.py +168 -0
  10. lfit_python-0.1.0/src/lfit_python/cli/physparams.py +154 -0
  11. lfit_python-0.1.0/src/lfit_python/cli/reddening.py +50 -0
  12. lfit_python-0.1.0/src/lfit_python/cli/summary.py +78 -0
  13. lfit_python-0.1.0/src/lfit_python/cli/update_input.py +65 -0
  14. lfit_python-0.1.0/src/lfit_python/cli/watch.py +39 -0
  15. lfit_python-0.1.0/src/lfit_python/cli/wdparams.py +223 -0
  16. lfit_python-0.1.0/src/lfit_python/cv_model.py +864 -0
  17. lfit_python-0.1.0/src/lfit_python/data/Bergeron/README +7 -0
  18. lfit_python-0.1.0/src/lfit_python/data/Bergeron/Table_DA +257 -0
  19. lfit_python-0.1.0/src/lfit_python/data/Bergeron/Table_DA_sdss +307 -0
  20. lfit_python-0.1.0/src/lfit_python/data/Bergeron/Table_DB +312 -0
  21. lfit_python-0.1.0/src/lfit_python/data/Bergeron/color_correction_tables/color_corrections_HCAM-GTC-super_minus_ntt_ucam.csv +1067 -0
  22. lfit_python-0.1.0/src/lfit_python/data/Bergeron/color_correction_tables/color_corrections_HCAM-GTC-super_minus_tnt_uspec.csv +1067 -0
  23. lfit_python-0.1.0/src/lfit_python/data/Gianninas13/ld_coeffs_g.txt +654 -0
  24. lfit_python-0.1.0/src/lfit_python/data/Gianninas13/ld_coeffs_i.txt +654 -0
  25. lfit_python-0.1.0/src/lfit_python/data/Gianninas13/ld_coeffs_r.txt +654 -0
  26. lfit_python-0.1.0/src/lfit_python/data/Gianninas13/ld_coeffs_u.txt +654 -0
  27. lfit_python-0.1.0/src/lfit_python/data/Gianninas13/ld_coeffs_z.txt +654 -0
  28. lfit_python-0.1.0/src/lfit_python/data/Gianninas13/radial_bright_profiles.txt +6925 -0
  29. lfit_python-0.1.0/src/lfit_python/data/Hamada/mr_hamada.dat +1307 -0
  30. lfit_python-0.1.0/src/lfit_python/data/Panei/12C-MR-H-He/12C-MR-H-He.dat +387 -0
  31. lfit_python-0.1.0/src/lfit_python/data/Panei/12C-MR-H-He/12C-MR-H-He.saver +750 -0
  32. lfit_python-0.1.0/src/lfit_python/data/Panei/12C-MR-He/12C-MR-He.dat +431 -0
  33. lfit_python-0.1.0/src/lfit_python/data/Panei/HS/04He-H-S.dat +158 -0
  34. lfit_python-0.1.0/src/lfit_python/data/Panei/HS/12C-H-S.dat +158 -0
  35. lfit_python-0.1.0/src/lfit_python/data/Panei/HS/16O-H-S.dat +158 -0
  36. lfit_python-0.1.0/src/lfit_python/data/Panei/HS/28Si-H-S.dat +158 -0
  37. lfit_python-0.1.0/src/lfit_python/data/Panei/HS/56Fe-H-S.dat +158 -0
  38. lfit_python-0.1.0/src/lfit_python/data/Panei/othercores/04He-MR-H.dat +91 -0
  39. lfit_python-0.1.0/src/lfit_python/data/Panei/othercores/16O-MR-H-He.dat +602 -0
  40. lfit_python-0.1.0/src/lfit_python/data/Panei/othercores/28Si-MR-H-He.dat +386 -0
  41. lfit_python-0.1.0/src/lfit_python/data/Panei/othercores/56Fe-MR-H-He.dat +390 -0
  42. lfit_python-0.1.0/src/lfit_python/data/Panei/othercores/old/04He-MR-H.save +120 -0
  43. lfit_python-0.1.0/src/lfit_python/data/Panei/othercores/old/04He-MR.save +130 -0
  44. lfit_python-0.1.0/src/lfit_python/data/Panei/othercores/old/16O-MR-H-He.save +602 -0
  45. lfit_python-0.1.0/src/lfit_python/data/Panei/othercores/old/16O-MR-He.save +469 -0
  46. lfit_python-0.1.0/src/lfit_python/data/Panei/othercores/old/28Si-MR-H-He.save +386 -0
  47. lfit_python-0.1.0/src/lfit_python/data/Panei/othercores/old/28Si-MR-He.save +402 -0
  48. lfit_python-0.1.0/src/lfit_python/data/Panei/othercores/old/56Fe-MR-H-He.save +633 -0
  49. lfit_python-0.1.0/src/lfit_python/data/Panei/othercores/old/56Fe-MR-He.save +537 -0
  50. lfit_python-0.1.0/src/lfit_python/data/Wood95/co040.2.04dt1 +80 -0
  51. lfit_python-0.1.0/src/lfit_python/data/Wood95/co050.2.04dt1 +82 -0
  52. lfit_python-0.1.0/src/lfit_python/data/Wood95/co060.2.04dt1 +85 -0
  53. lfit_python-0.1.0/src/lfit_python/data/Wood95/co070.2.04dt1 +91 -0
  54. lfit_python-0.1.0/src/lfit_python/data/Wood95/co080.2.04dt1 +100 -0
  55. lfit_python-0.1.0/src/lfit_python/data/Wood95/co090.2.04dt1 +99 -0
  56. lfit_python-0.1.0/src/lfit_python/data/Wood95/co100.2.04dt1 +100 -0
  57. lfit_python-0.1.0/src/lfit_python/data/althaus/readme.tex +12 -0
  58. lfit_python-0.1.0/src/lfit_python/data/althaus/t106.one +1132 -0
  59. lfit_python-0.1.0/src/lfit_python/data/althaus/t108.one +679 -0
  60. lfit_python-0.1.0/src/lfit_python/data/althaus/t110.one +821 -0
  61. lfit_python-0.1.0/src/lfit_python/data/althaus/t112.one +239 -0
  62. lfit_python-0.1.0/src/lfit_python/data/althaus/t114.one +355 -0
  63. lfit_python-0.1.0/src/lfit_python/data/althaus/t116.one +353 -0
  64. lfit_python-0.1.0/src/lfit_python/data/althaus/t118.one +356 -0
  65. lfit_python-0.1.0/src/lfit_python/data/althaus/t120.one +882 -0
  66. lfit_python-0.1.0/src/lfit_python/data/althaus/t122.one +901 -0
  67. lfit_python-0.1.0/src/lfit_python/data/althaus/t124.one +913 -0
  68. lfit_python-0.1.0/src/lfit_python/data/althaus/t126.one +739 -0
  69. lfit_python-0.1.0/src/lfit_python/data/althaus/t128.one +665 -0
  70. lfit_python-0.1.0/src/lfit_python/data/althaus/t130.one +626 -0
  71. lfit_python-0.1.0/src/lfit_python/likelihood.py +26 -0
  72. lfit_python-0.1.0/src/lfit_python/limbdark.py +47 -0
  73. lfit_python-0.1.0/src/lfit_python/model.py +801 -0
  74. lfit_python-0.1.0/src/lfit_python/physical_params.py +279 -0
  75. lfit_python-0.1.0/src/lfit_python/plotting.py +364 -0
  76. lfit_python-0.1.0/src/lfit_python/priors.py +51 -0
  77. lfit_python-0.1.0/src/lfit_python/sampling.py +472 -0
  78. lfit_python-0.1.0/src/lfit_python/summary.py +327 -0
  79. lfit_python-0.1.0/src/lfit_python/watch_app.py +1001 -0
  80. lfit_python-0.1.0/src/lfit_python/wdparams.py +587 -0
  81. lfit_python-0.1.0/src/lfit_python.egg-info/PKG-INFO +222 -0
  82. lfit_python-0.1.0/src/lfit_python.egg-info/SOURCES.txt +86 -0
  83. lfit_python-0.1.0/src/lfit_python.egg-info/dependency_links.txt +1 -0
  84. lfit_python-0.1.0/src/lfit_python.egg-info/entry_points.txt +9 -0
  85. lfit_python-0.1.0/src/lfit_python.egg-info/requires.txt +26 -0
  86. lfit_python-0.1.0/src/lfit_python.egg-info/top_level.txt +1 -0
  87. lfit_python-0.1.0/tests/test_likelihood.py +104 -0
  88. lfit_python-0.1.0/tests/test_package.py +182 -0
@@ -0,0 +1,222 @@
1
+ Metadata-Version: 2.4
2
+ Name: lfit_python
3
+ Version: 0.1.0
4
+ Summary: Hierarchical MCMC fitting of cataclysmic variable eclipse lightcurves with lfit_rs
5
+ Author: Stuart Littlefair
6
+ Project-URL: Homepage, https://github.com/StuartLittlefair/lfit_python
7
+ Requires-Python: >=3.9
8
+ Description-Content-Type: text/markdown
9
+ Requires-Dist: astropy
10
+ Requires-Dist: configobj
11
+ Requires-Dist: corner
12
+ Requires-Dist: emcee>=3
13
+ Requires-Dist: george
14
+ Requires-Dist: h5py
15
+ Requires-Dist: lfit_rs>=0.4.0
16
+ Requires-Dist: matplotlib>=3.6
17
+ Requires-Dist: networkx
18
+ Requires-Dist: numpy
19
+ Requires-Dist: pandas
20
+ Requires-Dist: roche
21
+ Requires-Dist: scipy
22
+ Requires-Dist: seaborn
23
+ Requires-Dist: tqdm
24
+ Provides-Extra: watch
25
+ Requires-Dist: bokeh>=3; extra == "watch"
26
+ Provides-Extra: reddening
27
+ Requires-Dist: astroquery; extra == "reddening"
28
+ Requires-Dist: dustmaps; extra == "reddening"
29
+ Requires-Dist: sigfig; extra == "reddening"
30
+ Provides-Extra: dev
31
+ Requires-Dist: pytest; extra == "dev"
32
+
33
+ # LFIT_PYTHON
34
+ `lfit_python` fits the eclipse lightcurves of cataclysmic variable (CV) stars, using the [`lfit_rs`](https://github.com/StuartLittlefair/rust_lfit) lightcurve model and MCMC sampling. Fitting one eclipse at a time can't easily cope with lightcurves with lots of flickering, and can't share parameters (e.g. the eclipse width) between eclipses. This software uses a tree structure to group eclipses into branches that can share some parameters but not others.
35
+
36
+ ## Setting up an MCMC run
37
+ The input file will define how a model is set up, and some of the details for the MCMC fit. It's almost certainly easier to understand the structure by looking at the [example](examples/mcmc_input.dat) file, and the comments in it should explain what the parameters mean. Something that may not be 100% clear, however, is how labels work - a parameter typically looks like this:
38
+ `variableName_nodeLabel`. The underscore separates the two, with the former telling the code which of the [model parameters](#model-parameters) is being set, and the latter telling it which node (i.e. band or eclipse) it belongs to. Similarly, `lfit-wdparams` needs an input configuration, and this [example](examples/wdinput.dat) is also given.
39
+
40
+
41
+ ## lfit_rs: functional knowledge you're gonna need
42
+
43
+ [`lfit_rs`](https://github.com/StuartLittlefair/rust_lfit) calculates the model lightcurve of a CV. It's installed automatically as a dependency of this package (`pip install lfit-rs` if you want it on its own).
44
+
45
+ `lfit_rs` operates not in time space, but rather in phase space. This necessitates a bit of pre-processing to get a lightcurve from the raw format, into flux as a function of eclipse phase. The eclipse minimum is assumed to occur at phase 0.0, though a variable in the model is a phase offset to tweak this... as a last resort! Good ephemeral data is much better than putting a plaster on the problem.
46
+
47
+ To reiterate - `lfit_rs` will output a lightcurve in `phase`, `flux`.
48
+
49
+ The module has, essentially, one main useful object with one main function. The `lfit_rs.CV` class handles the four components that are considered (namely, the disc, donor star, white dwarf, and bright spot), and puts them all together for you. These components _can_ be called individually, but this **usually** is more useful for diagnostics than for modelling. `lfit_rs.CV` has a `calcFlux()` method, which will make up your lightcurve. After a call to `calcFlux()`, the `ywd`, `yd`, `ys` and `yrs` attributes hold the white dwarf, disc, bright spot and donor fluxes.
50
+
51
+ ### Model parameters
52
+
53
+ `lfit_rs.CV` takes the CV parameters as a list, in a specific order. The last four are only supplied when using the (more computationally expensive) complex bright spot (BS) model, which is switched on with `complex = 1` in the input file. See [Savoury et al. (2011)](https://ui.adsabs.harvard.edu/abs/2011MNRAS.415.2025S/abstract) for a fuller description.
54
+
55
+ | # | Name | Description |
56
+ |---|------|-------------|
57
+ | 1 | `wdFlux` | white dwarf flux at maximum light |
58
+ | 2 | `dFlux` | disc flux at maximum light |
59
+ | 3 | `sFlux` | bright spot flux at maximum light |
60
+ | 4 | `rsFlux` | donor flux at maximum light |
61
+ | 5 | `q` | mass ratio |
62
+ | 6 | `dphi` | full width of white dwarf at mid ingress/egress |
63
+ | 7 | `rdisc` | radius of accretion disc (scaled by distance to inner lagrangian point XL1) |
64
+ | 8 | `ulimb` | linear limb darkening parameter for white dwarf |
65
+ | 9 | `rwd` | white dwarf radius (scaled to XL1) |
66
+ | 10 | `scale` | bright spot scale (scaled to XL1) |
67
+ | 11 | `az` | the azimuth of the bright spot strip, measured w.r.t. the tangent to the disc at the bright spot, so usually close to 0 (see note below) |
68
+ | 12 | `fis` | the fraction of the bright spot's flux which radiates isotropically |
69
+ | 13 | `dexp` | the exponent which governs how the brightness of the disc falls off with radius |
70
+ | 14 | `phi0` | a phase offset |
71
+ | 15 | `exp1` | [complex BS only] BS strip first exponent |
72
+ | 16 | `exp2` | [complex BS only] BS strip second exponent |
73
+ | 17 | `tilt` | [complex BS only] BS strip emission tilt, away from normal |
74
+ | 18 | `yaw` | [complex BS only] BS strip emission yaw, away from normal |
75
+
76
+ **Bright spot azimuth:** earlier versions of `lfit_rs` measured `az` from the line of centres between the stars, where typical values were around 100–150°. It is now measured from the tangent to the disc rim at the bright spot, so it should be roughly 0. The same `az` therefore gives a different bright spot orientation than before. To convert an old value, use
77
+
78
+ az_new = az_old - (θ_bs + 90°)
79
+
80
+ where `θ_bs = atan2(y_bs, x_bs)` is the position angle of the bright spot, measured from the line of centres. `θ_bs` depends on `q` and `rdisc`, so each eclipse (and each parameter set) must be converted separately, and priors on `az` need setting afresh. For example, with `roche`:
81
+
82
+ ```python
83
+ import numpy as np
84
+ import roche
85
+
86
+ r, _ = roche.bspot(q, rdisc * roche.xl1(q))
87
+ az_new = az_old - (np.degrees(np.arctan2(r.y, r.x)) + 90.0)
88
+ ```
89
+
90
+ The [example input file](examples/mcmc_input.dat) uses the new convention.
91
+
92
+ ```python
93
+ import lfit_rs
94
+ import numpy as np
95
+
96
+ pars = [wdFlux, dFlux, sFlux, rsFlux, q, dphi, rdisc, ulimb, rwd, scale, az, fis, dexp, phi0]
97
+
98
+ # initialise the CV
99
+ cv = lfit_rs.CV(pars)
100
+
101
+ phase = np.linspace(-0.3, 0.3, 300)
102
+ flux = cv.calcFlux(pars, phase)
103
+
104
+ # later, with new parameters
105
+ flux = cv.calcFlux(new_pars, phase)
106
+ ```
107
+
108
+ Note that the CV is created once, with the initial parameters, and new parameters are then passed to `calcFlux()`. This is because tweaking the parameters a bit is much less expensive than building the model from scratch - when running an MCMC as fast as possible, this saving adds up! Each eclipse node in `lfit_python` keeps its own `CV` object for this reason.
109
+
110
+ By default, `lfit_rs` uses an analytical approximation (Kopal 1959) for the donor's ellipsoidal variation, rather than a tiled donor star. This is fine when the donor contributes little light, as is usual for these CVs, but see the `lfit_rs` documentation (the `nlat_donor` option) if you care about the donor flux itself.
111
+
112
+ ### Limb Darkening
113
+
114
+ The model is usually only very dimly sensitive to the limb darkening coefficient (LDC), as this parameter only comes into play _during_ the WD ingress and egress. As such, it's recommended to first make a fit with a naiive LDC, then use the resulting WD model to calculate the value of the LDC that _should_ have been used, and conduct another fit with the new LDC.
115
+
116
+ ### Quickly diagnosing a fittable eclipse
117
+
118
+ Something that is important to understand is that the location of the BS ingress and egress, in conjuntion with the width of the eclipse and the size of the disc, constrains the mass ratio, q. It is crucial to be able to resolve these BS features in order to lift degeneracy between the other three.
119
+
120
+ ### Real world data considerations
121
+
122
+ One thing I'd be remiss not to mention is the bin width. When comparing models to data, we must account for the duration of a single exposure - if we don't, then periods where the flux is changing rapidly (i.e. the highly important ingresses and egresses), would be incorrect. `calcFlux()` can also take a `width` argument, which is the phase width of each data point; the model flux is then averaged over a bin of that width centred on each phase. Without it, `lfit_rs` evaluates the flux at each phase alone. `lfit_python` always passes widths, which it infers from the spacing of the data points. This will often not be an issue if your observations are successive, i.e. negligible dead time between frames, but if this is _not_ the case (as it often is), you must define the widths yourself!
123
+
124
+ These are, obviously, proxy parameters for the actual physical parameters of the system. The resulting chain from the MCMC simulation can be converted into physical parameters after the fact, using `lfit-wdparams` and `lfit-physparams`.
125
+
126
+ ## Markov Chain Monte-Carlo (MCMC), emcee, and the Affine-Invariant Ensemble Sampler (AIES)
127
+
128
+ [`emcee`](https://github.com/dfm/emcee) is the workhorse of this fitting process. MCMC essentially works by taking an initial position in parameter space, tweaking it a bit, and seeing if the fit to data improves. If it does, great, move there. If it doesn't, the 'walker' still has a finite chance to move to the new position anyway. This helps (in theory) to stop the walker from getting trapped in local minima; a core property of an MCMC is that it will explore 100% of the parameter space, given an infinite amount of time. Over time, the areas(or volumes) of parameter space that have a better fit to the data will accumulate more 'footprints' from the walkers, and the sampling frequencies will eventually converge towards the posterior distribution of the model.
129
+
130
+ It's hopefully obvious that we generally have less than infinite computer time. There are various algorithms that tweak the outline above, and the one currently used is the AIES. The `emcee` [paper](https://arxiv.org/abs/1202.3665) has a better explaination than I can give, so I recommend reading that rather than this, but here's a digested version. The chain uses many walkers rather than just one. When proposing new steps, a walker takes a random peer, and leapfrogs over its position by some fraction. This gives the proposed 'stretch move' new position of the walker. This is repeated (in parallel) for each walker's position, and then proceeds as normal - if it's a better fit, accept, if it isn't, roll some dice to see if it's accepted anyway. Note that this means that the walkers are **_not_** independant of each other, so don't use Gelman-Rubin convergence testing on these chains!
131
+
132
+ ## wdparams
133
+
134
+ `lfit-wdparams` is essentially a thin version of `lfit-mcmcfit`, only this time it takes the white dwarf fluxes found in a chain file as the 'observation', and fits white dwarf model atmosphere colours (the DA models found [here](http://www.astro.umontreal.ca/~bergeron/CoolingModels/)) to them. Using it is pretty much the same as using `lfit-mcmcfit`.
135
+
136
+ ## The model
137
+
138
+ This package uses a tree structure to group observational data. It's easier to explain with a diagram;
139
+
140
+ ```
141
+ Trunk
142
+ |
143
+ / \
144
+ Branch1 --- --- Branch2
145
+ | |
146
+ / \ / \
147
+ leaf1 leaf2 leaf3 leaf4
148
+ ```
149
+
150
+ Parameters are set from the top with an ordered list (as per `emcee` docs), and sorted down into the branches and leaves by the model structure. The eclipses are stored and modelled on the leaves, with the branches separating different observational filters and the `Trunk` storing the global parameters, `q`, `dphi`, and `rwd`. When we want to evaluate an eclipse fit, say that of `leaf1`, we call `leaf1.calcFlux`. This retrieves the parameters it inherits from its parent, `Branch1`, and grandparent, `Trunk`, passes them off to `lfit_rs.CV`, and returns the result.
151
+
152
+ The `lfit_python.likelihood` likelihood and prior functions take a parameter vector and an already constructed model. They update that model's variable parameters in place.
153
+
154
+ By segregating the eclipses like this, rather than fitting each individually, much better constraints on parameters can be achieved, even with less than stellar data. CV flickering can cause the BS ingress and egress to be ambiguous, as the amplitude of this stochastic process is often similar to the size of the BS features. It is unlikely that two eclipses will be unfortunate enough to be masked in this way _in the same place_, so by fitting them together, the MCMC should find it preferable to settle on the feature common to them both. Similarly, the white dwarf and donor fluxes (which should not change on human timescales) should be constant between eclipses - hence are shared at the branch level.
155
+
156
+ ### If you want to use this
157
+
158
+ The core functionality is agnostic to the model being fitted, and sub-classed to work with `lfit_rs` & `emcee`. This means that this structure should be _relatively_ easy to apply to other models in similar use-cases. The tree is constructed of `Node`s, that can have at most one parent, and any number of children. It can also be arbitrarily deep, for example the above illustration could have two levels of branches, one separating branches, and another layer separating observations that are distant in time, for a 4-layer model.
159
+
160
+ ## Fitting the Proxy Parameters
161
+
162
+ Actually using the software is fairly easy. In essence,
163
+
164
+ 1. Write a configuration file defining the initial conditions, and parameters of the MCMC. The [examples](examples/) folder contains configuration files that are documented reasonably well, just change the relevant parameters.
165
+ 2. Run the fit with the input file: `lfit-mcmcfit mcmc_input.dat`
166
+ 3. Wait. The chain is written to `chain_prod.h5`, and a summary (figures in `Initial_figs/` and `Final_figs/`, results in `modparams.csv`) is made at the end. Re-make the summary with `lfit-summary chain_prod.h5 mcmc_input.dat`.
167
+ 4. Fit the white dwarf fluxes with its relevant input file: `lfit-wdparams wdinput.dat`
168
+ 5. Use `lfit-limbdark LOGG E_LOGG TEFF E_TEFF` to calculate the limb darkening coefficient of this WD model
169
+ 6. Repeat steps 1-4 with the new value of limb darkening, until the value doesn't change. `lfit-update-input mcmc_input.dat chain_prod.h5` copies the chain medians into the input file as new starting values.
170
+ 7. Use `lfit-physparams chain_prod.h5 TWD E_TWD PERIOD E_PERIOD` to compute the physical system parameters, <a href="https://www.codecogs.com/eqnedit.php?latex=$q,&space;M_{wd},&space;R_{wd},&space;M_2,&space;R_2,&space;sep,&space;K_{wd},&space;K_2,&space;inclination,&space;log(g)$" target="_blank"><img src="https://latex.codecogs.com/gif.latex?$q,&space;M_{wd},&space;R_{wd},&space;M_2,&space;R_2,&space;sep,&space;K_{wd},&space;K_2,&space;inclination,&space;log(g)$" title="$q, M_{wd}, R_{wd}, M_2, R_2, sep, K_{wd}, K_2, inclination, log(g)$" /></a>
171
+ 8. Analyse results!
172
+
173
+ In reality, this is often iterative, and the result of one chain leads into the start position of another, until convergence is reached. Then, the resulting converged chain is fed into `lfit-wdparams` and `lfit-physparams` for conversion into physical parameters.
174
+
175
+ Other tools:
176
+
177
+ - `lfit-watch [mcmc_input.dat]` opens a bokeh app to inspect the model and adjust starting parameters (needs `pip install -e ".[watch]"`).
178
+ - `lfit-reddening TARGET` looks up the Gaia parallax and E(B-V) towards a target (needs `pip install -e ".[reddening]"`).
179
+
180
+ Every command takes `--help`.
181
+
182
+ ## Installation
183
+
184
+ ```bash
185
+ git clone https://github.com/StuartLittlefair/lfit_python.git
186
+ cd lfit_python
187
+ pip install -e . # or: pip install -e ".[watch,reddening,dev]"
188
+ ```
189
+
190
+ This installs the `lfit-*` commands and the `lfit_python` package, along with its dependencies, including [`lfit_rs`](https://pypi.org/project/lfit_rs/) and [`roche`](https://pypi.org/project/roche/). The white dwarf model tables (Bergeron, Wood, Panei, Hamada, Gianninas) are included in the package.
191
+
192
+ Run the tests with `pytest`.
193
+
194
+ ### Package layout
195
+
196
+ ```
197
+ src/lfit_python/
198
+ model.py generic Node/Param tree
199
+ cv_model.py CV eclipse nodes, Lightcurve, construct_model
200
+ likelihood.py ln_prior, ln_like, ln_prob for samplers
201
+ priors.py joint prior for pocoMC
202
+ sampling.py walker initialisation, run_emcee
203
+ chains.py reading/writing emcee, pocoMC and text chains
204
+ plotting.py lightcurve, model tree and corner plots
205
+ summary.py fit_summary
206
+ wdparams.py WD model atmosphere fit
207
+ physical_params.py WD mass-radius relations, system parameters
208
+ limbdark.py limb darkening coefficients
209
+ watch_app.py bokeh app behind lfit-watch
210
+ cli/ the lfit-* commands
211
+ data/ packaged model tables
212
+ examples/ example input files and lightcurves
213
+ tests/
214
+ ```
215
+
216
+ ## TODO
217
+ - AIES samplers are [likely not suitable for parameter spaces with N > ~5](https://statmodeling.stat.columbia.edu/2017/03/15/ensemble-methods-doomed-fail-high-dimensions/). Should we move to a different algorithm?
218
+ - Lipschitz optimisation may work well for this case (it is highly likely to find the global minimum, unless the likelihood is extremely concentrated) - though there are two problems. High dimensionality means many samples are necessary to characterise the gradient, and if the likelihood is very sharply peaked and otherwise smooth the global maximum can be easily missed.
219
+ - What about a burn-in with the MCMC, followed by optimisation by Lipschitz? This would localise it on the sharp peak and avoid that issue, potentially. Then, with a decent estimate of maximum gradient to work with, we can be confident that it will find the global maximum (or minimum, whatever.)
220
+
221
+
222
+ [![Codacy Badge](https://api.codacy.com/project/badge/Grade/e32287a32e864c278f1a06beeeb8e7fb)](https://www.codacy.com/manual/wildjames/lfit_python?utm_source=github.com&amp;utm_medium=referral&amp;utm_content=wildjames/lfit_python&amp;utm_campaign=Badge_Grade)
@@ -0,0 +1,190 @@
1
+ # LFIT_PYTHON
2
+ `lfit_python` fits the eclipse lightcurves of cataclysmic variable (CV) stars, using the [`lfit_rs`](https://github.com/StuartLittlefair/rust_lfit) lightcurve model and MCMC sampling. Fitting one eclipse at a time can't easily cope with lightcurves with lots of flickering, and can't share parameters (e.g. the eclipse width) between eclipses. This software uses a tree structure to group eclipses into branches that can share some parameters but not others.
3
+
4
+ ## Setting up an MCMC run
5
+ The input file will define how a model is set up, and some of the details for the MCMC fit. It's almost certainly easier to understand the structure by looking at the [example](examples/mcmc_input.dat) file, and the comments in it should explain what the parameters mean. Something that may not be 100% clear, however, is how labels work - a parameter typically looks like this:
6
+ `variableName_nodeLabel`. The underscore separates the two, with the former telling the code which of the [model parameters](#model-parameters) is being set, and the latter telling it which node (i.e. band or eclipse) it belongs to. Similarly, `lfit-wdparams` needs an input configuration, and this [example](examples/wdinput.dat) is also given.
7
+
8
+
9
+ ## lfit_rs: functional knowledge you're gonna need
10
+
11
+ [`lfit_rs`](https://github.com/StuartLittlefair/rust_lfit) calculates the model lightcurve of a CV. It's installed automatically as a dependency of this package (`pip install lfit-rs` if you want it on its own).
12
+
13
+ `lfit_rs` operates not in time space, but rather in phase space. This necessitates a bit of pre-processing to get a lightcurve from the raw format, into flux as a function of eclipse phase. The eclipse minimum is assumed to occur at phase 0.0, though a variable in the model is a phase offset to tweak this... as a last resort! Good ephemeral data is much better than putting a plaster on the problem.
14
+
15
+ To reiterate - `lfit_rs` will output a lightcurve in `phase`, `flux`.
16
+
17
+ The module has, essentially, one main useful object with one main function. The `lfit_rs.CV` class handles the four components that are considered (namely, the disc, donor star, white dwarf, and bright spot), and puts them all together for you. These components _can_ be called individually, but this **usually** is more useful for diagnostics than for modelling. `lfit_rs.CV` has a `calcFlux()` method, which will make up your lightcurve. After a call to `calcFlux()`, the `ywd`, `yd`, `ys` and `yrs` attributes hold the white dwarf, disc, bright spot and donor fluxes.
18
+
19
+ ### Model parameters
20
+
21
+ `lfit_rs.CV` takes the CV parameters as a list, in a specific order. The last four are only supplied when using the (more computationally expensive) complex bright spot (BS) model, which is switched on with `complex = 1` in the input file. See [Savoury et al. (2011)](https://ui.adsabs.harvard.edu/abs/2011MNRAS.415.2025S/abstract) for a fuller description.
22
+
23
+ | # | Name | Description |
24
+ |---|------|-------------|
25
+ | 1 | `wdFlux` | white dwarf flux at maximum light |
26
+ | 2 | `dFlux` | disc flux at maximum light |
27
+ | 3 | `sFlux` | bright spot flux at maximum light |
28
+ | 4 | `rsFlux` | donor flux at maximum light |
29
+ | 5 | `q` | mass ratio |
30
+ | 6 | `dphi` | full width of white dwarf at mid ingress/egress |
31
+ | 7 | `rdisc` | radius of accretion disc (scaled by distance to inner lagrangian point XL1) |
32
+ | 8 | `ulimb` | linear limb darkening parameter for white dwarf |
33
+ | 9 | `rwd` | white dwarf radius (scaled to XL1) |
34
+ | 10 | `scale` | bright spot scale (scaled to XL1) |
35
+ | 11 | `az` | the azimuth of the bright spot strip, measured w.r.t. the tangent to the disc at the bright spot, so usually close to 0 (see note below) |
36
+ | 12 | `fis` | the fraction of the bright spot's flux which radiates isotropically |
37
+ | 13 | `dexp` | the exponent which governs how the brightness of the disc falls off with radius |
38
+ | 14 | `phi0` | a phase offset |
39
+ | 15 | `exp1` | [complex BS only] BS strip first exponent |
40
+ | 16 | `exp2` | [complex BS only] BS strip second exponent |
41
+ | 17 | `tilt` | [complex BS only] BS strip emission tilt, away from normal |
42
+ | 18 | `yaw` | [complex BS only] BS strip emission yaw, away from normal |
43
+
44
+ **Bright spot azimuth:** earlier versions of `lfit_rs` measured `az` from the line of centres between the stars, where typical values were around 100–150°. It is now measured from the tangent to the disc rim at the bright spot, so it should be roughly 0. The same `az` therefore gives a different bright spot orientation than before. To convert an old value, use
45
+
46
+ az_new = az_old - (θ_bs + 90°)
47
+
48
+ where `θ_bs = atan2(y_bs, x_bs)` is the position angle of the bright spot, measured from the line of centres. `θ_bs` depends on `q` and `rdisc`, so each eclipse (and each parameter set) must be converted separately, and priors on `az` need setting afresh. For example, with `roche`:
49
+
50
+ ```python
51
+ import numpy as np
52
+ import roche
53
+
54
+ r, _ = roche.bspot(q, rdisc * roche.xl1(q))
55
+ az_new = az_old - (np.degrees(np.arctan2(r.y, r.x)) + 90.0)
56
+ ```
57
+
58
+ The [example input file](examples/mcmc_input.dat) uses the new convention.
59
+
60
+ ```python
61
+ import lfit_rs
62
+ import numpy as np
63
+
64
+ pars = [wdFlux, dFlux, sFlux, rsFlux, q, dphi, rdisc, ulimb, rwd, scale, az, fis, dexp, phi0]
65
+
66
+ # initialise the CV
67
+ cv = lfit_rs.CV(pars)
68
+
69
+ phase = np.linspace(-0.3, 0.3, 300)
70
+ flux = cv.calcFlux(pars, phase)
71
+
72
+ # later, with new parameters
73
+ flux = cv.calcFlux(new_pars, phase)
74
+ ```
75
+
76
+ Note that the CV is created once, with the initial parameters, and new parameters are then passed to `calcFlux()`. This is because tweaking the parameters a bit is much less expensive than building the model from scratch - when running an MCMC as fast as possible, this saving adds up! Each eclipse node in `lfit_python` keeps its own `CV` object for this reason.
77
+
78
+ By default, `lfit_rs` uses an analytical approximation (Kopal 1959) for the donor's ellipsoidal variation, rather than a tiled donor star. This is fine when the donor contributes little light, as is usual for these CVs, but see the `lfit_rs` documentation (the `nlat_donor` option) if you care about the donor flux itself.
79
+
80
+ ### Limb Darkening
81
+
82
+ The model is usually only very dimly sensitive to the limb darkening coefficient (LDC), as this parameter only comes into play _during_ the WD ingress and egress. As such, it's recommended to first make a fit with a naiive LDC, then use the resulting WD model to calculate the value of the LDC that _should_ have been used, and conduct another fit with the new LDC.
83
+
84
+ ### Quickly diagnosing a fittable eclipse
85
+
86
+ Something that is important to understand is that the location of the BS ingress and egress, in conjuntion with the width of the eclipse and the size of the disc, constrains the mass ratio, q. It is crucial to be able to resolve these BS features in order to lift degeneracy between the other three.
87
+
88
+ ### Real world data considerations
89
+
90
+ One thing I'd be remiss not to mention is the bin width. When comparing models to data, we must account for the duration of a single exposure - if we don't, then periods where the flux is changing rapidly (i.e. the highly important ingresses and egresses), would be incorrect. `calcFlux()` can also take a `width` argument, which is the phase width of each data point; the model flux is then averaged over a bin of that width centred on each phase. Without it, `lfit_rs` evaluates the flux at each phase alone. `lfit_python` always passes widths, which it infers from the spacing of the data points. This will often not be an issue if your observations are successive, i.e. negligible dead time between frames, but if this is _not_ the case (as it often is), you must define the widths yourself!
91
+
92
+ These are, obviously, proxy parameters for the actual physical parameters of the system. The resulting chain from the MCMC simulation can be converted into physical parameters after the fact, using `lfit-wdparams` and `lfit-physparams`.
93
+
94
+ ## Markov Chain Monte-Carlo (MCMC), emcee, and the Affine-Invariant Ensemble Sampler (AIES)
95
+
96
+ [`emcee`](https://github.com/dfm/emcee) is the workhorse of this fitting process. MCMC essentially works by taking an initial position in parameter space, tweaking it a bit, and seeing if the fit to data improves. If it does, great, move there. If it doesn't, the 'walker' still has a finite chance to move to the new position anyway. This helps (in theory) to stop the walker from getting trapped in local minima; a core property of an MCMC is that it will explore 100% of the parameter space, given an infinite amount of time. Over time, the areas(or volumes) of parameter space that have a better fit to the data will accumulate more 'footprints' from the walkers, and the sampling frequencies will eventually converge towards the posterior distribution of the model.
97
+
98
+ It's hopefully obvious that we generally have less than infinite computer time. There are various algorithms that tweak the outline above, and the one currently used is the AIES. The `emcee` [paper](https://arxiv.org/abs/1202.3665) has a better explaination than I can give, so I recommend reading that rather than this, but here's a digested version. The chain uses many walkers rather than just one. When proposing new steps, a walker takes a random peer, and leapfrogs over its position by some fraction. This gives the proposed 'stretch move' new position of the walker. This is repeated (in parallel) for each walker's position, and then proceeds as normal - if it's a better fit, accept, if it isn't, roll some dice to see if it's accepted anyway. Note that this means that the walkers are **_not_** independant of each other, so don't use Gelman-Rubin convergence testing on these chains!
99
+
100
+ ## wdparams
101
+
102
+ `lfit-wdparams` is essentially a thin version of `lfit-mcmcfit`, only this time it takes the white dwarf fluxes found in a chain file as the 'observation', and fits white dwarf model atmosphere colours (the DA models found [here](http://www.astro.umontreal.ca/~bergeron/CoolingModels/)) to them. Using it is pretty much the same as using `lfit-mcmcfit`.
103
+
104
+ ## The model
105
+
106
+ This package uses a tree structure to group observational data. It's easier to explain with a diagram;
107
+
108
+ ```
109
+ Trunk
110
+ |
111
+ / \
112
+ Branch1 --- --- Branch2
113
+ | |
114
+ / \ / \
115
+ leaf1 leaf2 leaf3 leaf4
116
+ ```
117
+
118
+ Parameters are set from the top with an ordered list (as per `emcee` docs), and sorted down into the branches and leaves by the model structure. The eclipses are stored and modelled on the leaves, with the branches separating different observational filters and the `Trunk` storing the global parameters, `q`, `dphi`, and `rwd`. When we want to evaluate an eclipse fit, say that of `leaf1`, we call `leaf1.calcFlux`. This retrieves the parameters it inherits from its parent, `Branch1`, and grandparent, `Trunk`, passes them off to `lfit_rs.CV`, and returns the result.
119
+
120
+ The `lfit_python.likelihood` likelihood and prior functions take a parameter vector and an already constructed model. They update that model's variable parameters in place.
121
+
122
+ By segregating the eclipses like this, rather than fitting each individually, much better constraints on parameters can be achieved, even with less than stellar data. CV flickering can cause the BS ingress and egress to be ambiguous, as the amplitude of this stochastic process is often similar to the size of the BS features. It is unlikely that two eclipses will be unfortunate enough to be masked in this way _in the same place_, so by fitting them together, the MCMC should find it preferable to settle on the feature common to them both. Similarly, the white dwarf and donor fluxes (which should not change on human timescales) should be constant between eclipses - hence are shared at the branch level.
123
+
124
+ ### If you want to use this
125
+
126
+ The core functionality is agnostic to the model being fitted, and sub-classed to work with `lfit_rs` & `emcee`. This means that this structure should be _relatively_ easy to apply to other models in similar use-cases. The tree is constructed of `Node`s, that can have at most one parent, and any number of children. It can also be arbitrarily deep, for example the above illustration could have two levels of branches, one separating branches, and another layer separating observations that are distant in time, for a 4-layer model.
127
+
128
+ ## Fitting the Proxy Parameters
129
+
130
+ Actually using the software is fairly easy. In essence,
131
+
132
+ 1. Write a configuration file defining the initial conditions, and parameters of the MCMC. The [examples](examples/) folder contains configuration files that are documented reasonably well, just change the relevant parameters.
133
+ 2. Run the fit with the input file: `lfit-mcmcfit mcmc_input.dat`
134
+ 3. Wait. The chain is written to `chain_prod.h5`, and a summary (figures in `Initial_figs/` and `Final_figs/`, results in `modparams.csv`) is made at the end. Re-make the summary with `lfit-summary chain_prod.h5 mcmc_input.dat`.
135
+ 4. Fit the white dwarf fluxes with its relevant input file: `lfit-wdparams wdinput.dat`
136
+ 5. Use `lfit-limbdark LOGG E_LOGG TEFF E_TEFF` to calculate the limb darkening coefficient of this WD model
137
+ 6. Repeat steps 1-4 with the new value of limb darkening, until the value doesn't change. `lfit-update-input mcmc_input.dat chain_prod.h5` copies the chain medians into the input file as new starting values.
138
+ 7. Use `lfit-physparams chain_prod.h5 TWD E_TWD PERIOD E_PERIOD` to compute the physical system parameters, <a href="https://www.codecogs.com/eqnedit.php?latex=$q,&space;M_{wd},&space;R_{wd},&space;M_2,&space;R_2,&space;sep,&space;K_{wd},&space;K_2,&space;inclination,&space;log(g)$" target="_blank"><img src="https://latex.codecogs.com/gif.latex?$q,&space;M_{wd},&space;R_{wd},&space;M_2,&space;R_2,&space;sep,&space;K_{wd},&space;K_2,&space;inclination,&space;log(g)$" title="$q, M_{wd}, R_{wd}, M_2, R_2, sep, K_{wd}, K_2, inclination, log(g)$" /></a>
139
+ 8. Analyse results!
140
+
141
+ In reality, this is often iterative, and the result of one chain leads into the start position of another, until convergence is reached. Then, the resulting converged chain is fed into `lfit-wdparams` and `lfit-physparams` for conversion into physical parameters.
142
+
143
+ Other tools:
144
+
145
+ - `lfit-watch [mcmc_input.dat]` opens a bokeh app to inspect the model and adjust starting parameters (needs `pip install -e ".[watch]"`).
146
+ - `lfit-reddening TARGET` looks up the Gaia parallax and E(B-V) towards a target (needs `pip install -e ".[reddening]"`).
147
+
148
+ Every command takes `--help`.
149
+
150
+ ## Installation
151
+
152
+ ```bash
153
+ git clone https://github.com/StuartLittlefair/lfit_python.git
154
+ cd lfit_python
155
+ pip install -e . # or: pip install -e ".[watch,reddening,dev]"
156
+ ```
157
+
158
+ This installs the `lfit-*` commands and the `lfit_python` package, along with its dependencies, including [`lfit_rs`](https://pypi.org/project/lfit_rs/) and [`roche`](https://pypi.org/project/roche/). The white dwarf model tables (Bergeron, Wood, Panei, Hamada, Gianninas) are included in the package.
159
+
160
+ Run the tests with `pytest`.
161
+
162
+ ### Package layout
163
+
164
+ ```
165
+ src/lfit_python/
166
+ model.py generic Node/Param tree
167
+ cv_model.py CV eclipse nodes, Lightcurve, construct_model
168
+ likelihood.py ln_prior, ln_like, ln_prob for samplers
169
+ priors.py joint prior for pocoMC
170
+ sampling.py walker initialisation, run_emcee
171
+ chains.py reading/writing emcee, pocoMC and text chains
172
+ plotting.py lightcurve, model tree and corner plots
173
+ summary.py fit_summary
174
+ wdparams.py WD model atmosphere fit
175
+ physical_params.py WD mass-radius relations, system parameters
176
+ limbdark.py limb darkening coefficients
177
+ watch_app.py bokeh app behind lfit-watch
178
+ cli/ the lfit-* commands
179
+ data/ packaged model tables
180
+ examples/ example input files and lightcurves
181
+ tests/
182
+ ```
183
+
184
+ ## TODO
185
+ - AIES samplers are [likely not suitable for parameter spaces with N > ~5](https://statmodeling.stat.columbia.edu/2017/03/15/ensemble-methods-doomed-fail-high-dimensions/). Should we move to a different algorithm?
186
+ - Lipschitz optimisation may work well for this case (it is highly likely to find the global minimum, unless the likelihood is extremely concentrated) - though there are two problems. High dimensionality means many samples are necessary to characterise the gradient, and if the likelihood is very sharply peaked and otherwise smooth the global maximum can be easily missed.
187
+ - What about a burn-in with the MCMC, followed by optimisation by Lipschitz? This would localise it on the sharp peak and avoid that issue, potentially. Then, with a decent estimate of maximum gradient to work with, we can be confident that it will find the global maximum (or minimum, whatever.)
188
+
189
+
190
+ [![Codacy Badge](https://api.codacy.com/project/badge/Grade/e32287a32e864c278f1a06beeeb8e7fb)](https://www.codacy.com/manual/wildjames/lfit_python?utm_source=github.com&amp;utm_medium=referral&amp;utm_content=wildjames/lfit_python&amp;utm_campaign=Badge_Grade)
@@ -0,0 +1,55 @@
1
+ [build-system]
2
+ requires = ["setuptools>=64"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "lfit_python"
7
+ version = "0.1.0"
8
+ description = "Hierarchical MCMC fitting of cataclysmic variable eclipse lightcurves with lfit_rs"
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ authors = [{ name = "Stuart Littlefair" }]
12
+ dependencies = [
13
+ "astropy",
14
+ "configobj",
15
+ "corner",
16
+ "emcee>=3",
17
+ "george",
18
+ "h5py",
19
+ "lfit_rs>=0.4.0",
20
+ "matplotlib>=3.6",
21
+ "networkx",
22
+ "numpy",
23
+ "pandas",
24
+ "roche",
25
+ "scipy",
26
+ "seaborn",
27
+ "tqdm",
28
+ ]
29
+
30
+ [project.optional-dependencies]
31
+ watch = ["bokeh>=3"]
32
+ reddening = ["astroquery", "dustmaps", "sigfig"]
33
+ dev = ["pytest"]
34
+
35
+ [project.scripts]
36
+ lfit-mcmcfit = "lfit_python.cli.mcmcfit:main"
37
+ lfit-summary = "lfit_python.cli.summary:main"
38
+ lfit-update-input = "lfit_python.cli.update_input:main"
39
+ lfit-wdparams = "lfit_python.cli.wdparams:main"
40
+ lfit-physparams = "lfit_python.cli.physparams:main"
41
+ lfit-limbdark = "lfit_python.cli.limbdark:main"
42
+ lfit-reddening = "lfit_python.cli.reddening:main"
43
+ lfit-watch = "lfit_python.cli.watch:main"
44
+
45
+ [project.urls]
46
+ Homepage = "https://github.com/StuartLittlefair/lfit_python"
47
+
48
+ [tool.setuptools.packages.find]
49
+ where = ["src"]
50
+
51
+ [tool.setuptools.package-data]
52
+ lfit_python = ["data/**/*"]
53
+
54
+ [tool.pytest.ini_options]
55
+ testpaths = ["tests"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,27 @@
1
+ """
2
+ lfit_python: hierarchical MCMC fitting of cataclysmic variable eclipse
3
+ lightcurves with lfit_rs.
4
+
5
+ Submodules are not imported here, so ``import lfit_python`` stays cheap:
6
+
7
+ - ``model``: generic ``Node``/``Param`` tree
8
+ - ``cv_model``: CV eclipse model nodes, ``Lightcurve`` and ``construct_model``
9
+ - ``likelihood``: ``ln_prior``, ``ln_like`` and ``ln_prob`` for samplers
10
+ - ``priors``: joint prior for pocoMC
11
+ - ``sampling``: walker initialisation and ``run_emcee``
12
+ - ``chains``: reading and writing chain files
13
+ - ``plotting``, ``summary``: figures and fit summaries
14
+ - ``wdparams``, ``physical_params``, ``limbdark``: white dwarf and system parameters
15
+ - ``cli``: the ``lfit-*`` command line tools
16
+ """
17
+
18
+ from importlib.metadata import PackageNotFoundError, version
19
+ from pathlib import Path
20
+
21
+ try:
22
+ __version__ = version("lfit_python")
23
+ except PackageNotFoundError: # pragma: no cover - running from a source tree
24
+ __version__ = "unknown"
25
+
26
+ #: Directory holding the packaged white dwarf model and limb darkening tables.
27
+ DATA_DIR = Path(__file__).parent / "data"