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,78 @@
1
+ """Summarise an lfit MCMC chain: before/after lightcurves, corner plots and
2
+ the likelihood evolution.
3
+
4
+ Usage: lfit-summary chain_prod.h5 mcmc_input.dat
5
+ """
6
+
7
+ import argparse
8
+
9
+ from ..summary import fit_summary
10
+
11
+
12
+ def main(argv=None):
13
+ # CLI Arguments
14
+ parser = argparse.ArgumentParser(
15
+ description="""Takes a chain file and the input file that created it, and
16
+ summarises the results.
17
+ Plots the before and after lightcurves, and the corner plot of each eclipse.
18
+ Plots the likelihood evolution."""
19
+ )
20
+
21
+ parser.add_argument(
22
+ "chain_fname",
23
+ help="The filename for the MCMC chain",
24
+ type=str,
25
+ )
26
+ parser.add_argument(
27
+ "input_fname",
28
+ help="The input command file for the MCMC chain",
29
+ type=str,
30
+ )
31
+ parser.add_argument(
32
+ "--nskip",
33
+ help="How many steps to cut off the front of the MCMC chain",
34
+ type=int,
35
+ default=0,
36
+ )
37
+ parser.add_argument(
38
+ "--thin",
39
+ help="I will only take every Nth step of the chain",
40
+ type=int,
41
+ default=1,
42
+ )
43
+ parser.add_argument(
44
+ "--quiet",
45
+ dest="quiet",
46
+ action="store_true",
47
+ help="If I'm being quiet, no figure will be shown, only saved to file.",
48
+ )
49
+ parser.add_argument(
50
+ "--no-corners",
51
+ dest="corners",
52
+ action="store_false",
53
+ help="Do not create the corner plots",
54
+ )
55
+
56
+ args = parser.parse_args(argv)
57
+
58
+ chain_fname = args.chain_fname
59
+ input_fname = args.input_fname
60
+
61
+ nskip = args.nskip
62
+ thin = args.thin
63
+
64
+ automated = bool(args.quiet)
65
+ corners = args.corners
66
+
67
+ fit_summary(
68
+ chain_fname,
69
+ input_fname,
70
+ nskip,
71
+ thin,
72
+ automated=automated,
73
+ corners=corners,
74
+ )
75
+
76
+
77
+ if __name__ == "__main__":
78
+ main()
@@ -0,0 +1,65 @@
1
+ """
2
+ Update an existing mcmcfit input file using the results of a
3
+ previous chain.
4
+
5
+ Usage: lfit-update-input mcmc_input.dat chain_prod.h5
6
+ """
7
+
8
+ import argparse
9
+
10
+ from ..chains import read_chain
11
+
12
+ def main(argv=None):
13
+ parser = argparse.ArgumentParser()
14
+
15
+ parser.add_argument(
16
+ "-t",
17
+ "--thin",
18
+ action="store",
19
+ type=int,
20
+ default=5,
21
+ help="thinning for chain (default=5)",
22
+ )
23
+ parser.add_argument(
24
+ "-d",
25
+ "--discard",
26
+ action="store",
27
+ type=int,
28
+ default=0,
29
+ help="thinning for chain (default=5)",
30
+ )
31
+ parser.add_argument("input_file", help="mcmc input file")
32
+ parser.add_argument("chain_file", help="chain output file")
33
+ args = parser.parse_args(argv)
34
+
35
+ print("Reading in the chain")
36
+ colkeys, df = read_chain(args.chain_file)
37
+ # get median from chain
38
+ results = df.quantile(0.5, numeric_only=True)
39
+
40
+ # strip "core" from core params
41
+ results.index = [entry.replace("_core", "") for entry in results.index]
42
+
43
+ # replace lines in MCMC input file
44
+ line_fmt = "{:>10} {:1} {:>16.8f} {:>12} {:>16} {:>16} {:>12}\n"
45
+ mcmc_input = open(args.input_file).readlines()
46
+ for i, line in enumerate(mcmc_input):
47
+ if line.startswith("#"):
48
+ continue
49
+ fields = line.strip().split() # split line on whitespace
50
+ if len(fields) == 0:
51
+ continue
52
+
53
+ parname = fields[0]
54
+ if parname in results.index:
55
+ # we have an updated value for this parameter!
56
+ fields[2] = results[parname]
57
+ mcmc_input[i] = line_fmt.format(*fields)
58
+
59
+ with open(args.input_file, "w") as f:
60
+ for line in mcmc_input:
61
+ f.write(line)
62
+
63
+
64
+ if __name__ == "__main__":
65
+ main()
@@ -0,0 +1,39 @@
1
+ """Start the bokeh app for inspecting a model and its starting parameters.
2
+
3
+ Needs the optional extras: pip install "lfit_python[watch]"
4
+
5
+ Usage: lfit-watch [mcmc_input.dat]
6
+ """
7
+
8
+ import argparse
9
+ import subprocess
10
+ import sys
11
+ from importlib.util import find_spec
12
+ from pathlib import Path
13
+
14
+ APP = Path(__file__).resolve().parents[1] / "watch_app.py"
15
+
16
+
17
+ def main(argv=None):
18
+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
19
+ parser.add_argument(
20
+ "input",
21
+ nargs="?",
22
+ default="mcmc_input.dat",
23
+ help="the mcmcfit input file (default: mcmc_input.dat)",
24
+ )
25
+ parser.add_argument("--port", type=int, help="port for the bokeh server")
26
+ args = parser.parse_args(argv)
27
+
28
+ if find_spec("bokeh") is None:
29
+ sys.exit('lfit-watch needs bokeh: pip install "lfit_python[watch]"')
30
+
31
+ cmd = [sys.executable, "-m", "bokeh", "serve", "--show", str(APP)]
32
+ if args.port is not None:
33
+ cmd += ["--port", str(args.port)]
34
+ cmd += ["--args", args.input]
35
+ sys.exit(subprocess.call(cmd))
36
+
37
+
38
+ if __name__ == "__main__":
39
+ main()
@@ -0,0 +1,223 @@
1
+ """Fit white dwarf model atmosphere fluxes to the WD fluxes from an lfit chain.
2
+
3
+ Usage: lfit-wdparams wdinput.dat
4
+ """
5
+
6
+ import argparse
7
+ import multiprocessing as mp
8
+
9
+ import configobj
10
+ import emcee
11
+ import h5py
12
+ import matplotlib.pyplot as plt
13
+ import numpy as np
14
+ from astropy.stats import sigma_clipped_stats
15
+
16
+ from ..chains import flatchain, read_chain
17
+ from ..model import Param
18
+ from ..plotting import thumbPlot
19
+ from ..wdparams import Flux, PhotometricSystem, WDModel, ln_prob, plotFluxes
20
+
21
+
22
+ def main(argv=None):
23
+ parser = argparse.ArgumentParser(description="Fit WD Fluxes")
24
+ parser.add_argument("file", action="store", help="input file")
25
+ args = parser.parse_args(argv)
26
+
27
+ LOGFILE = open("WDPARAMS.LOGS", "w")
28
+
29
+ # Use parseInput function to read data from input file
30
+ input_dict = configobj.ConfigObj(args.file)
31
+
32
+ # Read information about mcmc, priors, neclipses, sys err
33
+ nburn = int(input_dict["nburn"])
34
+ nprod = int(input_dict["nprod"])
35
+ nthread = int(input_dict["nthread"])
36
+ nwalkers = int(input_dict["nwalkers"])
37
+ scatter = float(input_dict["scatter"])
38
+ thin = int(input_dict.get("thin", 1))
39
+ skip = int(input_dict.get("skip", 0))
40
+ toFit = int(input_dict["fit"])
41
+
42
+ # Grab the variables
43
+ teff = Param.fromString("teff", input_dict["teff"])
44
+ logg = Param.fromString("logg", input_dict["logg"])
45
+ plax = Param.fromString("plax", input_dict["plax"])
46
+ ebv = Param.fromString("ebv", input_dict["ebv"])
47
+ syserr = float(input_dict["syserr"])
48
+ chain_file = input_dict.get("chain", None)
49
+
50
+ # Logging
51
+ LOGFILE.write("Fitting White Dwarf fluxes to model cooling tracks...\n")
52
+ LOGFILE.write("Running fit from the following input file:\n")
53
+ LOGFILE.write("#################################\n\n")
54
+ LOGFILE.write(open(args.file, "r").read())
55
+ LOGFILE.write("#################################\n\n")
56
+ LOGFILE.write("Setting up fluxes...\n\n")
57
+
58
+ # # # # # # # # # # # #
59
+ # Load in chain file #
60
+ # # # # # # # # # # # #
61
+ if chain_file is None:
62
+ colKeys = []
63
+ fluxes = []
64
+ else:
65
+ print("Reading in the chain file,", chain_file)
66
+ colKeys, chain = read_chain(chain_file)
67
+ print("Done!")
68
+
69
+ # Extract the fluxes from the chain file, and create a list of Fux objects from that
70
+ chain_bands = [
71
+ key.lower().replace("wdflux_", "")
72
+ for key in colKeys
73
+ if "wdflux" in key.lower()
74
+ ]
75
+ print("I found the following bands in the chain file:")
76
+ systems = input_dict["photometric_systems"]
77
+ for band in chain_bands:
78
+ print("\t{} ({})".format(band, systems.get(band, None)))
79
+ print("\n\n\n")
80
+
81
+ fluxes = []
82
+ for band in chain_bands:
83
+ # TODO: Add KG5 fluxes.
84
+ if band == "kg5":
85
+ LOGFILE.write("KG5 BANDS ARE CURRENTLY UNUSED. SKIPPING")
86
+ print("KG5 BANDS ARE CURRENTLY UNUSED. SKIPPING")
87
+ continue
88
+ else:
89
+ key = f"wdFlux_{band}"
90
+ if band not in systems:
91
+ msg = f"No photometric system for {band}, skipping"
92
+ LOGFILE.write(msg + "\n")
93
+ print(msg)
94
+ continue
95
+
96
+ system = PhotometricSystem(systems[band])
97
+ # skip and thin the chain if requested
98
+
99
+ mean, _, std = sigma_clipped_stats(chain[key][skip::thin])
100
+ flx = Flux(mean, std, system, band, syserr=syserr)
101
+ print(f"{band} = {flx}")
102
+ LOGFILE.write(f"{band} = {flx}")
103
+ fluxes.append(flx)
104
+
105
+ while True:
106
+ print("Would you like to add another flux?")
107
+ cont = input("y/n: ")
108
+ if cont.lower() == "y":
109
+ print("Enter a band:")
110
+ band = input("> ")
111
+ print("Enter a photometric system:")
112
+ system = input("> ")
113
+ print("Enter a Flux, in mJy")
114
+ flx = input("> ")
115
+ print("Enter an error on flux, mJy")
116
+ fle = input("> ")
117
+
118
+ flx = float(flx)
119
+ fle = float(fle)
120
+ system = PhotometricSystem(system)
121
+
122
+ flux = Flux(flx, fle, system, band, syserr=syserr)
123
+ fluxes.append(flux)
124
+ else:
125
+ print("Done!")
126
+ break
127
+
128
+ # Create the model object
129
+ myModel = WDModel(teff, logg, plax, ebv, fluxes)
130
+ npars = myModel.npars
131
+
132
+ if toFit:
133
+ guessP = np.array(myModel)
134
+ nameList = ["Teff", "log_g", "Parallax", "E(B-V)"]
135
+
136
+ # mp.set_start_method("spawn")
137
+ pool = mp.Pool(nthread)
138
+ p0 = np.array(emcee.utils.sample_ball(guessP, scatter * guessP, size=nwalkers))
139
+
140
+ backend = emcee.backends.HDFBackend("chain_wd.h5")
141
+
142
+ sampler = emcee.EnsembleSampler(
143
+ nwalkers,
144
+ npars,
145
+ ln_prob,
146
+ args=(myModel,),
147
+ pool=pool,
148
+ backend=backend,
149
+ )
150
+
151
+ # burnIn
152
+ print("\n\nExecuting the burn-in phase...")
153
+ state = sampler.run_mcmc(p0, nburn, store=False, progress=True)
154
+ skip_initial_state_check = False
155
+ sampler.reset()
156
+
157
+ # production
158
+ sampler.reset()
159
+ sampler.run_mcmc(
160
+ state,
161
+ nprod,
162
+ store=True,
163
+ progress=True,
164
+ skip_initial_state_check=skip_initial_state_check,
165
+ )
166
+ pos = sampler.get_last_sample()
167
+ col_names = "walker_no " + " ".join(nameList) + " ln_prob"
168
+ with h5py.File("chain_wd.h5", "r+") as f:
169
+ f["mcmc"].attrs["var_names"] = nameList
170
+
171
+ # Collect results from all walkers
172
+ colKeys, df = read_chain("chain_wd.h5")
173
+ fchain = flatchain(sampler.chain, npars, thin=thin)
174
+
175
+ # Plot the likelihoods
176
+ likes = sampler.get_log_prob(flat=False).T
177
+
178
+ # Plot the mean likelihood evolution
179
+ like_mu = np.mean(likes, axis=0)
180
+ like_std = np.std(likes, axis=0)
181
+ steps = np.arange(likes.shape[1])
182
+ std = np.std(likes)
183
+
184
+ # Make the likelihood plot
185
+ fig, ax = plt.subplots(figsize=(11, 8))
186
+ ax.fill_between(
187
+ steps, like_mu - like_std, like_mu + like_std, color="red", alpha=0.4
188
+ )
189
+ ax.plot(steps, like_mu, color="green")
190
+
191
+ ax.set_xlabel("Step")
192
+ ax.set_ylabel("ln_prob")
193
+
194
+ plt.tight_layout()
195
+ plt.savefig("wdparams_likelihoods.pdf")
196
+ plt.close("all")
197
+
198
+ bestPars = []
199
+ print(fchain.shape)
200
+ for i in range(npars):
201
+ par = fchain[:, i]
202
+ lolim, best, uplim = np.percentile(par, [16, 50, 84])
203
+ myModel[i] = best
204
+
205
+ print("%s = %f +%f -%f" % (nameList[i], best, uplim - best, best - lolim))
206
+ bestPars.append(best)
207
+ print("Creating corner plots...")
208
+ fig = thumbPlot(fchain, nameList)
209
+ fig.savefig("wdparams_cornerPlot.pdf")
210
+ plt.close("all")
211
+ else:
212
+ bestPars = [par for par in myModel]
213
+
214
+ print("Done!")
215
+ print("Chisq = {:.3f}".format(myModel.chisq()))
216
+ # Plot measured and model colors and fluxes
217
+ plotFluxes(myModel)
218
+ print("Model: {}".format(myModel))
219
+ LOGFILE.close()
220
+
221
+
222
+ if __name__ == "__main__":
223
+ main()