lfit-python 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- lfit_python/__init__.py +27 -0
- lfit_python/chains.py +157 -0
- lfit_python/cli/__init__.py +1 -0
- lfit_python/cli/limbdark.py +64 -0
- lfit_python/cli/mcmcfit.py +168 -0
- lfit_python/cli/physparams.py +154 -0
- lfit_python/cli/reddening.py +50 -0
- lfit_python/cli/summary.py +78 -0
- lfit_python/cli/update_input.py +65 -0
- lfit_python/cli/watch.py +39 -0
- lfit_python/cli/wdparams.py +223 -0
- lfit_python/cv_model.py +864 -0
- lfit_python/data/Bergeron/README +7 -0
- lfit_python/data/Bergeron/Table_DA +257 -0
- lfit_python/data/Bergeron/Table_DA_sdss +307 -0
- lfit_python/data/Bergeron/Table_DB +312 -0
- lfit_python/data/Bergeron/color_correction_tables/color_corrections_HCAM-GTC-super_minus_ntt_ucam.csv +1067 -0
- lfit_python/data/Bergeron/color_correction_tables/color_corrections_HCAM-GTC-super_minus_tnt_uspec.csv +1067 -0
- lfit_python/data/Gianninas13/ld_coeffs_g.txt +654 -0
- lfit_python/data/Gianninas13/ld_coeffs_i.txt +654 -0
- lfit_python/data/Gianninas13/ld_coeffs_r.txt +654 -0
- lfit_python/data/Gianninas13/ld_coeffs_u.txt +654 -0
- lfit_python/data/Gianninas13/ld_coeffs_z.txt +654 -0
- lfit_python/data/Gianninas13/radial_bright_profiles.txt +6925 -0
- lfit_python/data/Hamada/mr_hamada.dat +1307 -0
- lfit_python/data/Panei/12C-MR-H-He/12C-MR-H-He.dat +387 -0
- lfit_python/data/Panei/12C-MR-H-He/12C-MR-H-He.saver +750 -0
- lfit_python/data/Panei/12C-MR-He/12C-MR-He.dat +431 -0
- lfit_python/data/Panei/HS/04He-H-S.dat +158 -0
- lfit_python/data/Panei/HS/12C-H-S.dat +158 -0
- lfit_python/data/Panei/HS/16O-H-S.dat +158 -0
- lfit_python/data/Panei/HS/28Si-H-S.dat +158 -0
- lfit_python/data/Panei/HS/56Fe-H-S.dat +158 -0
- lfit_python/data/Panei/othercores/04He-MR-H.dat +91 -0
- lfit_python/data/Panei/othercores/16O-MR-H-He.dat +602 -0
- lfit_python/data/Panei/othercores/28Si-MR-H-He.dat +386 -0
- lfit_python/data/Panei/othercores/56Fe-MR-H-He.dat +390 -0
- lfit_python/data/Panei/othercores/old/04He-MR-H.save +120 -0
- lfit_python/data/Panei/othercores/old/04He-MR.save +130 -0
- lfit_python/data/Panei/othercores/old/16O-MR-H-He.save +602 -0
- lfit_python/data/Panei/othercores/old/16O-MR-He.save +469 -0
- lfit_python/data/Panei/othercores/old/28Si-MR-H-He.save +386 -0
- lfit_python/data/Panei/othercores/old/28Si-MR-He.save +402 -0
- lfit_python/data/Panei/othercores/old/56Fe-MR-H-He.save +633 -0
- lfit_python/data/Panei/othercores/old/56Fe-MR-He.save +537 -0
- lfit_python/data/Wood95/co040.2.04dt1 +80 -0
- lfit_python/data/Wood95/co050.2.04dt1 +82 -0
- lfit_python/data/Wood95/co060.2.04dt1 +85 -0
- lfit_python/data/Wood95/co070.2.04dt1 +91 -0
- lfit_python/data/Wood95/co080.2.04dt1 +100 -0
- lfit_python/data/Wood95/co090.2.04dt1 +99 -0
- lfit_python/data/Wood95/co100.2.04dt1 +100 -0
- lfit_python/data/althaus/readme.tex +12 -0
- lfit_python/data/althaus/t106.one +1132 -0
- lfit_python/data/althaus/t108.one +679 -0
- lfit_python/data/althaus/t110.one +821 -0
- lfit_python/data/althaus/t112.one +239 -0
- lfit_python/data/althaus/t114.one +355 -0
- lfit_python/data/althaus/t116.one +353 -0
- lfit_python/data/althaus/t118.one +356 -0
- lfit_python/data/althaus/t120.one +882 -0
- lfit_python/data/althaus/t122.one +901 -0
- lfit_python/data/althaus/t124.one +913 -0
- lfit_python/data/althaus/t126.one +739 -0
- lfit_python/data/althaus/t128.one +665 -0
- lfit_python/data/althaus/t130.one +626 -0
- lfit_python/likelihood.py +26 -0
- lfit_python/limbdark.py +47 -0
- lfit_python/model.py +801 -0
- lfit_python/physical_params.py +279 -0
- lfit_python/plotting.py +364 -0
- lfit_python/priors.py +51 -0
- lfit_python/sampling.py +472 -0
- lfit_python/summary.py +327 -0
- lfit_python/watch_app.py +1001 -0
- lfit_python/wdparams.py +587 -0
- lfit_python-0.1.0.dist-info/METADATA +222 -0
- lfit_python-0.1.0.dist-info/RECORD +81 -0
- lfit_python-0.1.0.dist-info/WHEEL +5 -0
- lfit_python-0.1.0.dist-info/entry_points.txt +9 -0
- lfit_python-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Convert lfit model parameters (q, dphi, rwd) into physical system parameters,
|
|
3
|
+
using white dwarf mass-radius relations.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import os
|
|
7
|
+
|
|
8
|
+
import numpy as np
|
|
9
|
+
import roche
|
|
10
|
+
from astropy import constants as const
|
|
11
|
+
from astropy import units
|
|
12
|
+
from scipy import interpolate as interp
|
|
13
|
+
from scipy.optimize import brentq
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def read_wood_file(filename):
|
|
17
|
+
"""The Wood 1995 thick H layer models (CO)
|
|
18
|
+
returns temp and radius in K and solar units"""
|
|
19
|
+
x, y = np.loadtxt(filename, usecols=(5, 6)).T
|
|
20
|
+
temp = 10**y * units.K
|
|
21
|
+
radius = 10**x * units.R_sun / const.R_sun.to(units.cm).value
|
|
22
|
+
# must reverse so temp increases...
|
|
23
|
+
return temp[::-1], radius[::-1]
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def read_panei_file(filename):
|
|
27
|
+
x, y = np.loadtxt(filename, usecols=(1, 2)).T
|
|
28
|
+
temp = 10**y * units.K
|
|
29
|
+
radius = 10**x * units.R_sun / const.R_sun.to(units.cm).value
|
|
30
|
+
temp, mass, radius = np.loadtxt(filename).T
|
|
31
|
+
temp = 1000 * temp * units.K
|
|
32
|
+
mass = mass * units.M_sun
|
|
33
|
+
radius = radius * units.R_sun / 100
|
|
34
|
+
return temp, mass, radius
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def hamada_mr(baseDir):
|
|
38
|
+
"""Hamada-Salpeter 0 Kelvin Mass-radius relation"""
|
|
39
|
+
filename = os.path.join(baseDir, "Hamada/mr_hamada.dat")
|
|
40
|
+
mass, radius = np.loadtxt(filename, usecols=(0, 5)).T
|
|
41
|
+
# sort out units
|
|
42
|
+
mass, radius = mass * units.M_sun, radius * units.R_sun / 100.0
|
|
43
|
+
# return function which interpolates these points linearly
|
|
44
|
+
return interp.interp1d(mass, radius, kind="linear")
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def panei_mr(targetTemp, baseDir):
|
|
48
|
+
"""given a target temp, returns a function giving
|
|
49
|
+
radius as a function of mass.
|
|
50
|
+
function is derived from cubic interpolation of Panei models"""
|
|
51
|
+
assert np.all(
|
|
52
|
+
(targetTemp >= 5000.0 * units.K) & (targetTemp < 45000.0 * units.K)
|
|
53
|
+
), "Model invalid at temps less than 4000 or greater than 45,000 K"
|
|
54
|
+
|
|
55
|
+
# read panei model grid in
|
|
56
|
+
teffs, masses, radii = read_panei_file(
|
|
57
|
+
os.path.join(baseDir, "Panei/12C-MR-H-He/12C-MR-H-He.dat")
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
# this function interpolates to give radius as function of temp, mass
|
|
61
|
+
# (spline is fit to plain numbers: K, Msun and Rsun)
|
|
62
|
+
func = interp.SmoothBivariateSpline(
|
|
63
|
+
teffs.to_value(units.K),
|
|
64
|
+
masses.to_value(units.M_sun),
|
|
65
|
+
radii.to_value(units.R_sun),
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
# this function specifies the target temp to give just radius (Rsun)
|
|
69
|
+
# as fn of mass (Msun)
|
|
70
|
+
teff = targetTemp.to_value(units.K)
|
|
71
|
+
f2 = lambda x: func(teff, x, grid=False)
|
|
72
|
+
return f2
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def panei_he_mr(targetTemp, baseDir):
|
|
76
|
+
"""given a target temp, returns a function giving
|
|
77
|
+
radius as a function of mass.
|
|
78
|
+
function is derived from cubic interpolation of Panei models"""
|
|
79
|
+
assert np.all(
|
|
80
|
+
(targetTemp >= 4000.0 * units.K) & (targetTemp < 20000.0 * units.K)
|
|
81
|
+
), "Model invalid at temps less than 4000 or greater than 45,000 K"
|
|
82
|
+
|
|
83
|
+
# read panei model grid in
|
|
84
|
+
teffs, masses, radii = read_panei_file(
|
|
85
|
+
os.path.join(baseDir, "Panei/othercores/04He-MR-H.dat")
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
# this function interpolates to give radius as function of temp, mass
|
|
89
|
+
# (spline is fit to plain numbers: K, Msun and Rsun)
|
|
90
|
+
func = interp.SmoothBivariateSpline(
|
|
91
|
+
teffs.to_value(units.K),
|
|
92
|
+
masses.to_value(units.M_sun),
|
|
93
|
+
radii.to_value(units.R_sun),
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
# this function specifies the target temp to give just radius (Rsun)
|
|
97
|
+
# as fn of mass (Msun)
|
|
98
|
+
teff = targetTemp.to_value(units.K)
|
|
99
|
+
f2 = lambda x: func(teff, x, grid=False)
|
|
100
|
+
return f2
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def wood_mr(targetTemp, baseDir):
|
|
104
|
+
"""given a target temp, returns a function giving
|
|
105
|
+
radius as a function of mass.
|
|
106
|
+
|
|
107
|
+
function is derived from cubic interpolation of wood models"""
|
|
108
|
+
files = [
|
|
109
|
+
"Wood95/co040.2.04dt1",
|
|
110
|
+
"Wood95/co050.2.04dt1",
|
|
111
|
+
"Wood95/co060.2.04dt1",
|
|
112
|
+
"Wood95/co070.2.04dt1",
|
|
113
|
+
"Wood95/co080.2.04dt1",
|
|
114
|
+
"Wood95/co090.2.04dt1",
|
|
115
|
+
"Wood95/co100.2.04dt1",
|
|
116
|
+
]
|
|
117
|
+
m = np.array([0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]) * units.M_sun
|
|
118
|
+
r = []
|
|
119
|
+
for file in files:
|
|
120
|
+
temp, rad = read_wood_file(os.path.join(baseDir, file))
|
|
121
|
+
# linear interpolation to find radius at this mass, temp
|
|
122
|
+
r.append(
|
|
123
|
+
np.interp(
|
|
124
|
+
targetTemp.to_value(units.K),
|
|
125
|
+
temp.to_value(units.K),
|
|
126
|
+
rad.to_value(units.R_sun),
|
|
127
|
+
)
|
|
128
|
+
)
|
|
129
|
+
|
|
130
|
+
# fix units
|
|
131
|
+
r = np.array(r) * units.R_sun
|
|
132
|
+
|
|
133
|
+
# now return function which interpolates m,r arrays cubically
|
|
134
|
+
return interp.interp1d(m, r, kind="cubic")
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def geoFunc(mtest, scaled_mass, rw_a):
|
|
138
|
+
"""given a scaled mass thingy and rw/a, returns a radius in solar units"""
|
|
139
|
+
a3 = scaled_mass * mtest * units.M_sun
|
|
140
|
+
a = a3 ** (1.0 / 3.0)
|
|
141
|
+
rtest = rw_a * a
|
|
142
|
+
return rtest.to(units.R_sun).value
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def find_wdmass(wdtemp, scaled_mass, rw_a, baseDir, model="hamada"):
|
|
146
|
+
"""for a given white dwarf mass we have two estimates of the white dwarf radius:
|
|
147
|
+
one from WD theoretical models, and one from the scaled_mass (which gives a)
|
|
148
|
+
and rw_a - this is the geometric mass.
|
|
149
|
+
|
|
150
|
+
this routine finds the white dwarf mass where these estimates agree, if
|
|
151
|
+
one exists."""
|
|
152
|
+
assert model in ["hamada", "wood", "panei", "panei_he"], (
|
|
153
|
+
"Model %s not recognised" % model
|
|
154
|
+
)
|
|
155
|
+
limits = {
|
|
156
|
+
"hamada": [0.14, 1.44],
|
|
157
|
+
"wood": [0.4, 1.0],
|
|
158
|
+
"panei": [0.4, 1.2],
|
|
159
|
+
"panei_he": [0.24, 0.505],
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
mlo, mhi = limits[model]
|
|
163
|
+
|
|
164
|
+
if model == "hamada":
|
|
165
|
+
rwdFunc = hamada_mr(baseDir)
|
|
166
|
+
elif model == "wood":
|
|
167
|
+
rwdFunc = wood_mr(wdtemp, baseDir)
|
|
168
|
+
elif model == "panei_he":
|
|
169
|
+
rwdFunc = panei_he_mr(wdtemp, baseDir)
|
|
170
|
+
else:
|
|
171
|
+
rwdFunc = panei_mr(wdtemp, baseDir)
|
|
172
|
+
|
|
173
|
+
# scipys brentq finds the root of a function - in this case
|
|
174
|
+
# a function which returns the difference in predicted radius at
|
|
175
|
+
# a given mass.
|
|
176
|
+
# geoFunc gives the geometric soln for WD radius at a given mass
|
|
177
|
+
# this function = 0 when two estimates agree
|
|
178
|
+
funcToSolve = lambda x: geoFunc(x, scaled_mass, rw_a) - rwdFunc(x)
|
|
179
|
+
|
|
180
|
+
# first we'll check that it actually changes sign between the two
|
|
181
|
+
# limits of our model. Otherwise it has no root!
|
|
182
|
+
valAtLoLimit = funcToSolve(mlo)
|
|
183
|
+
valAtHiLimit = funcToSolve(mhi)
|
|
184
|
+
if np.sign(valAtLoLimit * valAtHiLimit) > 0:
|
|
185
|
+
# get here only when they are the same sign
|
|
186
|
+
raise Exception("No valid solution for this model")
|
|
187
|
+
|
|
188
|
+
# OK, there should be a solution: return it
|
|
189
|
+
return brentq(funcToSolve, mlo, mhi) * units.M_sun
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def logg(m, r):
|
|
193
|
+
MSUN = 1.9891e30
|
|
194
|
+
RSUN = 6.95508e8
|
|
195
|
+
G = 6.67384e-11 * 1000 # cgs units
|
|
196
|
+
|
|
197
|
+
try:
|
|
198
|
+
m = m.value * MSUN * 1000 # cgs units
|
|
199
|
+
r = r.value * RSUN * 100 # cgs units
|
|
200
|
+
except:
|
|
201
|
+
m = m * MSUN * 1000 # cgs units
|
|
202
|
+
r = r * RSUN * 100 # cgs units
|
|
203
|
+
return np.log10(G * m / (r * r))
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def solve(input_data, baseDir, helium=False):
|
|
207
|
+
q, dphi, rw, twd, p = input_data
|
|
208
|
+
|
|
209
|
+
# Kepler's law gives a quantity related to wd mass and separation, a
|
|
210
|
+
# scaled_mass = a**3/M_wd. I call this the scaled mass.
|
|
211
|
+
scaled_mass = const.G * (1 + q) * p**2 / 4.0 / np.pi**2
|
|
212
|
+
|
|
213
|
+
# convert white dwarf radius to units of separation, rw/a
|
|
214
|
+
xl1_a = roche.xl1(q)
|
|
215
|
+
rw_a = rw * xl1_a
|
|
216
|
+
|
|
217
|
+
solved = True
|
|
218
|
+
if helium:
|
|
219
|
+
try:
|
|
220
|
+
# try helium models
|
|
221
|
+
mw = find_wdmass(twd, scaled_mass, rw_a, baseDir, model="panei_he")
|
|
222
|
+
except FileNotFoundError:
|
|
223
|
+
raise
|
|
224
|
+
except Exception:
|
|
225
|
+
solved = False
|
|
226
|
+
else:
|
|
227
|
+
try:
|
|
228
|
+
# try wood models
|
|
229
|
+
mw = find_wdmass(twd, scaled_mass, rw_a, baseDir, model="wood")
|
|
230
|
+
except FileNotFoundError:
|
|
231
|
+
raise
|
|
232
|
+
except Exception:
|
|
233
|
+
# try panei models (usually for masses above 1 Msun)
|
|
234
|
+
try:
|
|
235
|
+
mw = find_wdmass(twd, scaled_mass, rw_a, baseDir, model="panei")
|
|
236
|
+
except FileNotFoundError:
|
|
237
|
+
raise
|
|
238
|
+
except Exception:
|
|
239
|
+
# try hamada models (for masses less than 0.4 or more than 1.2 Msun)
|
|
240
|
+
try:
|
|
241
|
+
mw = find_wdmass(twd, scaled_mass, rw_a, baseDir, model="hamada")
|
|
242
|
+
except FileNotFoundError:
|
|
243
|
+
raise
|
|
244
|
+
except Exception:
|
|
245
|
+
solved = False
|
|
246
|
+
|
|
247
|
+
# do nothing if none of the models yielded a solution
|
|
248
|
+
# otherwise,
|
|
249
|
+
if solved:
|
|
250
|
+
# donor star mass
|
|
251
|
+
mr = mw * q
|
|
252
|
+
|
|
253
|
+
# from this wd mass and scaled mass, find a
|
|
254
|
+
a3 = scaled_mass * mw
|
|
255
|
+
a = a3 ** (1.0 / 3.0)
|
|
256
|
+
a = a.to(units.R_sun)
|
|
257
|
+
|
|
258
|
+
# inc
|
|
259
|
+
inc = roche.findi(q, dphi)
|
|
260
|
+
sini = np.sin(np.radians(inc))
|
|
261
|
+
|
|
262
|
+
# radial velocities
|
|
263
|
+
kw = (2.0 * np.pi * sini * q * a / (1 + q) / p).to(units.km / units.s)
|
|
264
|
+
kr = kw / q
|
|
265
|
+
|
|
266
|
+
# secondary radius
|
|
267
|
+
# use from Warner 1995 (eggleton)
|
|
268
|
+
# radius of sphere with same volume as Roche Lobe...
|
|
269
|
+
r2 = 0.49 * a * q ** (2.0 / 3.0)
|
|
270
|
+
r2 /= 0.6 * q ** (2.0 / 3.0) + np.log(1.0 + q ** (1.0 / 3.0))
|
|
271
|
+
|
|
272
|
+
# logg from mass and radius of WD
|
|
273
|
+
logg_wd = logg(mw, rw_a * a)
|
|
274
|
+
|
|
275
|
+
# need to be a little careful here for different versions of astropy
|
|
276
|
+
data = (q, mw, rw_a * a, logg_wd, mr, r2, a, kw, kr, inc)
|
|
277
|
+
return data
|
|
278
|
+
else:
|
|
279
|
+
return None
|
lfit_python/plotting.py
ADDED
|
@@ -0,0 +1,364 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Plotting routines for lfit models and MCMC chains.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
from random import choice
|
|
7
|
+
|
|
8
|
+
import corner
|
|
9
|
+
import matplotlib.pyplot as plt
|
|
10
|
+
import networkx as nx
|
|
11
|
+
import numpy as np
|
|
12
|
+
import seaborn
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def nxdraw(model):
|
|
16
|
+
"""Draw a hierarchical node map of a model."""
|
|
17
|
+
|
|
18
|
+
# Build the network
|
|
19
|
+
G = model.create_tree()
|
|
20
|
+
pos = hierarchy_pos(G)
|
|
21
|
+
|
|
22
|
+
# Figure has two inches of width per node
|
|
23
|
+
figsize = (2 * float(G.number_of_nodes()), 8.0)
|
|
24
|
+
print("Figure will be {}".format(figsize))
|
|
25
|
+
|
|
26
|
+
_, ax = plt.subplots(figsize=figsize)
|
|
27
|
+
nx.draw(G, ax=ax, pos=pos, with_labels=True, node_color="grey", font_weight="heavy")
|
|
28
|
+
|
|
29
|
+
plt.show()
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def hierarchy_pos(G, root=None, width=1.0, vert_gap=0.2, vert_loc=0, xcenter=0.5):
|
|
33
|
+
"""
|
|
34
|
+
From Joel's answer at https://stackoverflow.com/a/29597209/2966723.
|
|
35
|
+
Licensed under Creative Commons Attribution-Share Alike
|
|
36
|
+
|
|
37
|
+
If the graph is a tree this will return the positions to plot this in a
|
|
38
|
+
hierarchical layout.
|
|
39
|
+
|
|
40
|
+
G: the graph (must be a tree)
|
|
41
|
+
|
|
42
|
+
root: the root node of current branch
|
|
43
|
+
- if the tree is directed and this is not given,
|
|
44
|
+
the root will be found and used
|
|
45
|
+
- if the tree is directed and this is given, then
|
|
46
|
+
the positions will be just for the descendants of this node.
|
|
47
|
+
- if the tree is undirected and not given,
|
|
48
|
+
then a random choice will be used.
|
|
49
|
+
|
|
50
|
+
width: horizontal space allocated for this branch - avoids overlap with
|
|
51
|
+
other branches
|
|
52
|
+
|
|
53
|
+
vert_gap: gap between levels of hierarchy
|
|
54
|
+
|
|
55
|
+
vert_loc: vertical location of root
|
|
56
|
+
|
|
57
|
+
xcenter: horizontal location of root
|
|
58
|
+
"""
|
|
59
|
+
if not nx.is_tree(G):
|
|
60
|
+
fail_msg = "cannot use hierarchy_pos on a graph that is not a tree"
|
|
61
|
+
raise TypeError(fail_msg)
|
|
62
|
+
|
|
63
|
+
if root is None:
|
|
64
|
+
if isinstance(G, nx.DiGraph):
|
|
65
|
+
# Allows back compatibility with nx version 1.11
|
|
66
|
+
root = next(iter(nx.topological_sort(G)))
|
|
67
|
+
else:
|
|
68
|
+
root = choice(list(G.nodes))
|
|
69
|
+
|
|
70
|
+
return _hierarchy_pos(G, root, width, vert_gap, vert_loc, xcenter)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _hierarchy_pos(
|
|
74
|
+
G, root, width=1.0, vert_gap=0.2, vert_loc=0, xcenter=0.5, pos=None, parent=None
|
|
75
|
+
):
|
|
76
|
+
"""
|
|
77
|
+
see hierarchy_pos docstring for most arguments
|
|
78
|
+
|
|
79
|
+
pos: a dict saying where all nodes go if they have been assigned
|
|
80
|
+
parent: parent of this branch. - only affects it if non-directed
|
|
81
|
+
|
|
82
|
+
"""
|
|
83
|
+
|
|
84
|
+
if pos is None:
|
|
85
|
+
pos = {root: (xcenter, vert_loc)}
|
|
86
|
+
else:
|
|
87
|
+
pos[root] = (xcenter, vert_loc)
|
|
88
|
+
|
|
89
|
+
children = list(G.neighbors(root))
|
|
90
|
+
|
|
91
|
+
if not isinstance(G, nx.DiGraph) and parent is not None:
|
|
92
|
+
children.remove(parent)
|
|
93
|
+
|
|
94
|
+
if len(children) != 0:
|
|
95
|
+
dx = width / len(children)
|
|
96
|
+
nextx = xcenter - width / 2 - dx / 2
|
|
97
|
+
for child in children:
|
|
98
|
+
nextx += dx
|
|
99
|
+
pos = _hierarchy_pos(
|
|
100
|
+
G,
|
|
101
|
+
child,
|
|
102
|
+
width=dx,
|
|
103
|
+
vert_gap=vert_gap,
|
|
104
|
+
vert_loc=vert_loc - vert_gap,
|
|
105
|
+
xcenter=nextx,
|
|
106
|
+
pos=pos,
|
|
107
|
+
parent=root,
|
|
108
|
+
)
|
|
109
|
+
|
|
110
|
+
return pos
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def plot_eclipse(
|
|
114
|
+
ecl_node, save=False, figsize=(11.0, 8.0), fname=None, save_dir=".", ext=".pdf"
|
|
115
|
+
):
|
|
116
|
+
"""Create a plot of the eclipse's data.
|
|
117
|
+
|
|
118
|
+
If save is True, a copy of the figure is saved.
|
|
119
|
+
|
|
120
|
+
If fname is defined, save the figure with that filename. Otherwise,
|
|
121
|
+
infer one from the data filename
|
|
122
|
+
"""
|
|
123
|
+
# Generate the lightcurve of the total, and the components.
|
|
124
|
+
flx = ecl_node.cv.calcFlux(ecl_node.cv_parlist, ecl_node.lc.x, ecl_node.lc.w)
|
|
125
|
+
wd_flx = ecl_node.cv.ywd
|
|
126
|
+
sec_flx = ecl_node.cv.yrs
|
|
127
|
+
BS_flx = ecl_node.cv.ys
|
|
128
|
+
disc_flx = ecl_node.cv.yd
|
|
129
|
+
|
|
130
|
+
# print("This model has a chisq of {:.3f}".format(ecl_node.chisq()))
|
|
131
|
+
|
|
132
|
+
# Start the plotting area
|
|
133
|
+
try:
|
|
134
|
+
plt.style.use("MNRAS_Style")
|
|
135
|
+
except OSError:
|
|
136
|
+
# The MNRAS style sheet is a personal matplotlib style; carry on
|
|
137
|
+
# with the defaults if it isn't installed.
|
|
138
|
+
pass
|
|
139
|
+
fig, axs = plt.subplots(2, sharex=True, figsize=figsize, height_ratios=(2, 1))
|
|
140
|
+
|
|
141
|
+
# Plot the data first. Also do errors
|
|
142
|
+
axs[0].errorbar(
|
|
143
|
+
ecl_node.lc.x,
|
|
144
|
+
ecl_node.lc.y,
|
|
145
|
+
yerr=ecl_node.lc.ye,
|
|
146
|
+
linestyle="none",
|
|
147
|
+
ecolor="grey",
|
|
148
|
+
zorder=1,
|
|
149
|
+
)
|
|
150
|
+
axs[0].step(ecl_node.lc.x, ecl_node.lc.y, where="mid", color="black")
|
|
151
|
+
|
|
152
|
+
# Plot the model over the data
|
|
153
|
+
axs[0].plot(ecl_node.lc.x, wd_flx, color="lightblue", label="WD")
|
|
154
|
+
axs[0].plot(ecl_node.lc.x, sec_flx, color="magenta", label="Sec")
|
|
155
|
+
axs[0].plot(ecl_node.lc.x, BS_flx, color="darkblue", label="BS")
|
|
156
|
+
axs[0].plot(ecl_node.lc.x, disc_flx, color="brown", label="Disc")
|
|
157
|
+
axs[0].plot(ecl_node.lc.x, flx, color="red")
|
|
158
|
+
axs[0].legend(fontsize="x-large")
|
|
159
|
+
|
|
160
|
+
# Plot the errorbars
|
|
161
|
+
axs[1].errorbar(
|
|
162
|
+
ecl_node.lc.x,
|
|
163
|
+
ecl_node.lc.y - flx,
|
|
164
|
+
yerr=ecl_node.lc.ye,
|
|
165
|
+
linestyle="none",
|
|
166
|
+
ecolor="grey",
|
|
167
|
+
zorder=1,
|
|
168
|
+
)
|
|
169
|
+
axs[1].step(ecl_node.lc.x, ecl_node.lc.y - flx, where="mid", color="black")
|
|
170
|
+
|
|
171
|
+
# 0 residuals line, to guide the eye
|
|
172
|
+
axs[1].axhline(0.0, linestyle="--", color="black", alpha=0.7, zorder=0)
|
|
173
|
+
|
|
174
|
+
# Labelling. Top one gets title, bottom one gets x label
|
|
175
|
+
title_text = "{} --- chisq: {:.1f} --- ln_like: {:.1f}".format(
|
|
176
|
+
ecl_node.lc.name, ecl_node.chisq(), ecl_node.ln_like()
|
|
177
|
+
)
|
|
178
|
+
# axs[0].set_title(title_text)
|
|
179
|
+
axs[0].set_ylabel("Flux (mJy)", fontsize="x-large")
|
|
180
|
+
axs[1].set_xlabel("Orbital Phase", fontsize="x-large")
|
|
181
|
+
axs[1].set_ylabel("Residual Flux (mJy)", fontsize="x-large")
|
|
182
|
+
|
|
183
|
+
# increase the size of the tick labels
|
|
184
|
+
for ax in axs:
|
|
185
|
+
ax.tick_params(axis="both", which="major", labelsize="x-large")
|
|
186
|
+
ax.tick_params(axis="both", which="minor", labelsize="large")
|
|
187
|
+
|
|
188
|
+
# Arrange the figure on the page, and show it
|
|
189
|
+
plt.tight_layout()
|
|
190
|
+
fig.subplots_adjust(wspace=0, hspace=0)
|
|
191
|
+
|
|
192
|
+
if save:
|
|
193
|
+
# Check that save_dir exists
|
|
194
|
+
if not os.path.isdir(save_dir):
|
|
195
|
+
os.mkdir(save_dir)
|
|
196
|
+
|
|
197
|
+
# If we didnt get told to use a certain fname, use this node's name
|
|
198
|
+
if fname is None:
|
|
199
|
+
fname = ecl_node.lc.name.replace(".calib", "")
|
|
200
|
+
fname = fname.replace(".txt", "")
|
|
201
|
+
fname += ext
|
|
202
|
+
|
|
203
|
+
# Make the filename
|
|
204
|
+
fname = "/".join([save_dir, fname])
|
|
205
|
+
|
|
206
|
+
# If the user specified a path like './figs/', then the above could
|
|
207
|
+
# return './figs//Eclipse_N.pdf'; I want to be robust against that.
|
|
208
|
+
while "//" in fname:
|
|
209
|
+
fname = fname.replace("//", "/")
|
|
210
|
+
|
|
211
|
+
plt.savefig(fname)
|
|
212
|
+
|
|
213
|
+
return fig, axs
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def plot_GP_eclipse(
|
|
217
|
+
ecl_node, save=False, figsize=(11.0, 8.0), fname=None, save_dir=".", ext=".pdf"
|
|
218
|
+
):
|
|
219
|
+
"""Plot my data. Returns fig, ax
|
|
220
|
+
|
|
221
|
+
If save is True, save the figures.
|
|
222
|
+
Figsize is passed to matplotlib.
|
|
223
|
+
"""
|
|
224
|
+
|
|
225
|
+
# Get the figure and axes from the eclipse
|
|
226
|
+
fig, ax = plot_eclipse(ecl_node, False, figsize, fname, save_dir, ext)
|
|
227
|
+
|
|
228
|
+
# Get the residuals of the model
|
|
229
|
+
residuals = ecl_node.lc.y - ecl_node.calcFlux()
|
|
230
|
+
|
|
231
|
+
# Create the GP of this eclipse
|
|
232
|
+
gp = ecl_node.create_GP()
|
|
233
|
+
# Compute the GP
|
|
234
|
+
gp.compute(ecl_node.lc.x, ecl_node.lc.ye)
|
|
235
|
+
|
|
236
|
+
# Draw samples from the GP
|
|
237
|
+
samples = gp.sample_conditional(residuals, ecl_node.lc.x, size=300)
|
|
238
|
+
|
|
239
|
+
# Get the mean, mu, standard deviation, and
|
|
240
|
+
mu = np.mean(samples, axis=0)
|
|
241
|
+
std = np.std(samples, axis=0)
|
|
242
|
+
|
|
243
|
+
ax[1].fill_between(
|
|
244
|
+
ecl_node.lc.x,
|
|
245
|
+
mu + (1.0 * std),
|
|
246
|
+
mu - (1.0 * std),
|
|
247
|
+
color="r",
|
|
248
|
+
alpha=0.4,
|
|
249
|
+
zorder=20,
|
|
250
|
+
)
|
|
251
|
+
|
|
252
|
+
if save:
|
|
253
|
+
# Check that save_dir exists
|
|
254
|
+
if not os.path.isdir(save_dir):
|
|
255
|
+
os.mkdir(save_dir)
|
|
256
|
+
|
|
257
|
+
# If we didnt get told to use a certain fname, use this node's name
|
|
258
|
+
if fname is None:
|
|
259
|
+
fname = ecl_node.lc.name.replace(".calib", "")
|
|
260
|
+
fname = fname.replace(".txt", "")
|
|
261
|
+
fname += ext
|
|
262
|
+
|
|
263
|
+
# Make the filename
|
|
264
|
+
fname = "/".join([save_dir, fname])
|
|
265
|
+
|
|
266
|
+
# If the user specified a path like './figs/', then the above could
|
|
267
|
+
# return './figs//Eclipse_N.pdf'; I want to be robust against that.
|
|
268
|
+
while "//" in fname:
|
|
269
|
+
fname = fname.replace("//", "/")
|
|
270
|
+
|
|
271
|
+
plt.savefig(fname)
|
|
272
|
+
|
|
273
|
+
return fig, ax
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def plot_model(model, show, *args, **kwargs):
|
|
277
|
+
"""Calls the relevant plotter for each eclipse contained in the model.
|
|
278
|
+
Passes *args and **kwargs to it.
|
|
279
|
+
|
|
280
|
+
Inputs:
|
|
281
|
+
-------
|
|
282
|
+
model, Node:
|
|
283
|
+
The model to be plotted. This will be queried for child Eclipse nodes,
|
|
284
|
+
which will then be passed to the plot_eclipse and plot_GP_eclipse funcs
|
|
285
|
+
show, Bool:
|
|
286
|
+
If show is True, call plt.show(). Otherwise, just save the figures
|
|
287
|
+
args, kwargs:
|
|
288
|
+
Passed to the plot_eclipse and plot_GP_eclipse functions.
|
|
289
|
+
|
|
290
|
+
Returns:
|
|
291
|
+
--------
|
|
292
|
+
None.
|
|
293
|
+
"""
|
|
294
|
+
|
|
295
|
+
eclipses = model.search_node_type("Eclipse")
|
|
296
|
+
for eclipse in eclipses:
|
|
297
|
+
if str(eclipse.__class__.__name__) in ["SimpleEclipse", "ComplexEclipse"]:
|
|
298
|
+
fig, ax = plot_eclipse(eclipse, *args, **kwargs)
|
|
299
|
+
elif str(eclipse.__class__.__name__) in ["SimpleGPEclipse", "ComplexGPEclipse"]:
|
|
300
|
+
fig, ax = plot_GP_eclipse(eclipse, *args, **kwargs)
|
|
301
|
+
|
|
302
|
+
if show:
|
|
303
|
+
plt.show()
|
|
304
|
+
|
|
305
|
+
plt.close()
|
|
306
|
+
del fig
|
|
307
|
+
del ax
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def thumbPlot(chain, labels, **kwargs):
|
|
311
|
+
seaborn.set(style="ticks")
|
|
312
|
+
seaborn.set_style({"xtick.direction": "in", "ytick.direction": "in"})
|
|
313
|
+
fig = corner.corner(
|
|
314
|
+
chain,
|
|
315
|
+
labels=labels,
|
|
316
|
+
bins=30,
|
|
317
|
+
quantiles=[0.16, 0.5, 0.84],
|
|
318
|
+
show_titles=True,
|
|
319
|
+
title_fmt=".1e",
|
|
320
|
+
label_kwargs=dict(fontsize=18),
|
|
321
|
+
**kwargs
|
|
322
|
+
)
|
|
323
|
+
return fig
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
def plotchains(chain, npar, alpha=0.2):
|
|
327
|
+
nwalkers, nsteps, npars = chain.shape
|
|
328
|
+
fig = plt.figure()
|
|
329
|
+
for i in range(nwalkers):
|
|
330
|
+
plt.plot(chain[i, :, npar], alpha=alpha, color="k")
|
|
331
|
+
return fig
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
def rebin(xbins, x, y, e=None, weighted=True, errors_from_rms=False):
|
|
335
|
+
digitized = np.digitize(x, xbins)
|
|
336
|
+
xbin = []
|
|
337
|
+
ybin = []
|
|
338
|
+
ebin = []
|
|
339
|
+
for i in range(0, len(xbins)):
|
|
340
|
+
bin_y_vals = y[digitized == i]
|
|
341
|
+
bin_x_vals = x[digitized == i]
|
|
342
|
+
if e is not None:
|
|
343
|
+
bin_e_vals = e[digitized == i]
|
|
344
|
+
if weighted:
|
|
345
|
+
if e is None:
|
|
346
|
+
raise Exception("Cannot compute weighted mean without errors")
|
|
347
|
+
weights = 1.0 / bin_e_vals**2
|
|
348
|
+
xbin.append(np.sum(weights * bin_x_vals) / np.sum(weights))
|
|
349
|
+
ybin.append(np.sum(weights * bin_y_vals) / np.sum(weights))
|
|
350
|
+
if errors_from_rms:
|
|
351
|
+
ebin.append(np.std(bin_y_vals))
|
|
352
|
+
else:
|
|
353
|
+
ebin.append(np.sqrt(1.0 / np.sum(weights)))
|
|
354
|
+
else:
|
|
355
|
+
xbin.append(bin_x_vals.mean())
|
|
356
|
+
ybin.append(bin_y_vals.mean())
|
|
357
|
+
if errors_from_rms:
|
|
358
|
+
ebin.append(np.std(bin_y_vals))
|
|
359
|
+
else:
|
|
360
|
+
ebin.append(np.sqrt(np.sum(bin_e_vals**2)) / len(bin_e_vals))
|
|
361
|
+
xbin = np.array(xbin)
|
|
362
|
+
ybin = np.array(ybin)
|
|
363
|
+
ebin = np.array(ebin)
|
|
364
|
+
return (xbin, ybin, ebin)
|
lfit_python/priors.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
"""Custom prior for the pocoMC library"""
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
|
|
5
|
+
from .model import Node
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class CustomPrior:
|
|
9
|
+
def __init__(self, model: Node):
|
|
10
|
+
self.model = model
|
|
11
|
+
self.dim = len(model.priors)
|
|
12
|
+
|
|
13
|
+
def _propose_sample(self):
|
|
14
|
+
"""Propose a single sample from the prior distribution of the individual parameters"""
|
|
15
|
+
|
|
16
|
+
sample = np.array([dist.rvs() for dist in self.model.priors])
|
|
17
|
+
return sample
|
|
18
|
+
|
|
19
|
+
def rvs(self, size=1):
|
|
20
|
+
"""Draw samples from the prior distribution of the individual parameters.
|
|
21
|
+
|
|
22
|
+
This must respect not only the individual parameter priors, but also any constraints between
|
|
23
|
+
parameters. For example, we cannot have brightspots that miss the disc, or a phase width
|
|
24
|
+
that is too large for the mass ratio.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
# draw samples with replacement until valid
|
|
28
|
+
samples = []
|
|
29
|
+
for i in range(size):
|
|
30
|
+
ok = False
|
|
31
|
+
sample = self._propose_sample()
|
|
32
|
+
while not ok:
|
|
33
|
+
self.model.dynasty_par_vals = sample
|
|
34
|
+
ok = self.model.check_validity()
|
|
35
|
+
sample = self._propose_sample()
|
|
36
|
+
samples.append(sample)
|
|
37
|
+
return np.array(samples)
|
|
38
|
+
|
|
39
|
+
def logpdf(self, x):
|
|
40
|
+
x = np.atleast_2d(x)
|
|
41
|
+
logp = np.zeros(len(x))
|
|
42
|
+
for i, dist in enumerate(self.model.priors):
|
|
43
|
+
logp += dist.logpdf(x[:, i])
|
|
44
|
+
return logp
|
|
45
|
+
|
|
46
|
+
@property
|
|
47
|
+
def bounds(self):
|
|
48
|
+
bounds = []
|
|
49
|
+
for prior in self.model.priors:
|
|
50
|
+
bounds.append(prior.support())
|
|
51
|
+
return np.array(bounds)
|