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,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"
lfit_python/chains.py ADDED
@@ -0,0 +1,157 @@
1
+ """
2
+ Reading and writing MCMC chain files (emcee HDF5, pocoMC HDF5 and legacy
3
+ whitespace-delimited text chains).
4
+ """
5
+
6
+ import emcee
7
+ import h5py
8
+ import numpy as np
9
+ import pandas as pd
10
+
11
+ try:
12
+ import dask.dataframe as dd
13
+
14
+ use_dask = True
15
+ except ImportError:
16
+ use_dask = False
17
+
18
+
19
+ def read_chain(chain_fname):
20
+ """
21
+ Reads an old style text chain, and emcee HDF5 chain or a new style pocoMC HDF5 chain
22
+
23
+ Returns pandas DataFrame and list of variable names
24
+ """
25
+ try:
26
+ df = pd.read_csv(chain_fname, sep=r"\s+")
27
+ colKeys = list(df.columns.values)[1:-1]
28
+ except UnicodeDecodeError:
29
+ with h5py.File(chain_fname, "r") as f:
30
+ pocoMC = "weights" in f
31
+
32
+ if pocoMC:
33
+ # pocoMC chain
34
+ colKeys, df = read_pocoMC_chain(chain_fname)
35
+ else:
36
+ # emcee chain
37
+ colKeys, df = read_emcee_chain(chain_fname)
38
+
39
+ return colKeys, df
40
+
41
+
42
+ def read_pocoMC_chain(chain_fname):
43
+ with h5py.File(chain_fname, "r") as f:
44
+ colKeys = [n.decode() for n in f["var_names"]]
45
+ samples = np.array(f["samples"])
46
+ weights = np.array(f["weights"])
47
+ ln_prob = np.array(f["logp"])
48
+
49
+ # weight samples
50
+ idx_resampled = np.random.choice(
51
+ np.arange(len(weights)), size=len(samples), replace=True, p=weights
52
+ )
53
+ samples = samples[idx_resampled]
54
+ ln_prob = ln_prob[idx_resampled]
55
+ df = pd.DataFrame(samples, columns=colKeys)
56
+ df["ln_prob"] = ln_prob
57
+ return colKeys, df
58
+
59
+
60
+ def write_pocoMC_chain(chain_fname, model, sampler):
61
+ samples, weights, logl, logp = sampler.posterior()
62
+ # list of strings for parameter names
63
+ names = model.dynasty_par_names
64
+ with h5py.File(chain_fname, "w") as f:
65
+ f.create_dataset("samples", data=samples)
66
+ f.create_dataset("weights", data=weights)
67
+ f.create_dataset("logp", data=logp)
68
+ f.create_dataset("logl", data=logl)
69
+ f.create_dataset("var_names", data=np.array(names, dtype="S"))
70
+
71
+
72
+ def read_emcee_chain(chain_fname):
73
+ reader = emcee.backends.HDFBackend(chain_fname, read_only=True)
74
+ samples = reader.get_chain(discard=0, flat=True, thin=1)
75
+ nwalkers, npars = reader.shape
76
+ nsamples = samples.size // npars // nwalkers
77
+ with h5py.File(chain_fname, "r") as f:
78
+ colKeys = list(f["mcmc"].attrs["var_names"])
79
+ df = pd.DataFrame(samples, columns=colKeys)
80
+ df["ln_prob"] = reader.get_log_prob(discard=0, flat=True, thin=1)
81
+ nsamples = samples.size // npars // nwalkers
82
+ df["walker_no"] = np.array(list(range(nwalkers)) * nsamples)
83
+ return colKeys, df
84
+
85
+
86
+ def flatchain(chain, npars=None, nskip=0, thin=1):
87
+ """flattens a chain (i.e collects results from all walkers),
88
+ with options to skip the first nskip parameters, and thin the chain
89
+ by only retrieving a point every thin steps - thinning can be useful when
90
+ the steps of the chain are highly correlated"""
91
+ if npars is None:
92
+ npars = chain.shape[2]
93
+ return chain[:, nskip::thin, :].reshape((-1, npars))
94
+
95
+
96
+ def readchain(file, **kwargs):
97
+ """Reads in the chain file in a single thread.
98
+ Returns the chain in the shape (nwalkers, nprod, npars)
99
+ """
100
+ data = pd.read_csv(file, sep=r"\s+", comment="#", **kwargs)
101
+ data = np.array(data)
102
+
103
+ # Figure out what shape the result should have.
104
+ nwalkers = int(np.amax(data[:, 0]) + 1)
105
+ nprod = int(data.shape[0] / nwalkers)
106
+ npars = int(data.shape[1] - 1)
107
+
108
+ # empty array to fill. Make it nans to be safe?
109
+ chain = np.zeros((nwalkers, nprod, npars))
110
+ chain[:, :, :] = np.nan
111
+
112
+ for i in range(nwalkers):
113
+ index = np.where(data[:, 0] == float(i))
114
+ chain[i] = data[index, 1:]
115
+
116
+ return chain
117
+
118
+
119
+ def readchain_dask(file, **kwargs):
120
+ """Reads in the chain file using threading.
121
+ Returns the chain in the shape (nwalkers, nprod, npars)."""
122
+
123
+ if not use_dask:
124
+ return readchain(file, **kwargs)
125
+
126
+ data = dd.io.read_csv(
127
+ file,
128
+ engine="c",
129
+ header=0,
130
+ compression=None,
131
+ na_filter=False,
132
+ sep=r"\s+",
133
+ **kwargs
134
+ )
135
+ data = data.compute()
136
+ data = np.array(data)
137
+
138
+ # Figure out what shape the result should have.
139
+ nwalkers = int(np.amax(data[:, 0]) + 1)
140
+ nprod = int(data.shape[0] / nwalkers)
141
+ npars = int(data.shape[1] - 1)
142
+
143
+ # empty array to fill. Make it nans to be safe?
144
+ chain = np.zeros((nwalkers, nprod, npars))
145
+ chain[:, :, :] = np.nan
146
+
147
+ for i in range(nwalkers):
148
+ index = np.where(data[:, 0] == float(i))
149
+ chain[i] = data[index, 1:]
150
+
151
+ return chain
152
+
153
+
154
+ def readflatchain(file):
155
+ data = pd.read_csv(file, header=None, compression=None, sep=r"\s+")
156
+ data = np.array(data)
157
+ return data
@@ -0,0 +1 @@
1
+ """Command line entry points. Each module has a ``main(argv=None)``."""
@@ -0,0 +1,64 @@
1
+ """Interactively compute WD limb darkening coefficients (Gianninas et al. 2013).
2
+
3
+ Usage: lfit-limbdark [LOGG E_LOGG TEFF E_TEFF]
4
+ """
5
+
6
+ import argparse
7
+
8
+ import numpy as np
9
+
10
+ from ..limbdark import ld
11
+
12
+
13
+ def main(argv=None):
14
+ parser = argparse.ArgumentParser(
15
+ description="WD limb darkening coefficients in ugriz (Gianninas et al. 2013). "
16
+ "Prompts for any values not given."
17
+ )
18
+ parser.add_argument("logg", type=float, nargs="?", help="log g")
19
+ parser.add_argument("e_logg", type=float, nargs="?", help="error on log g")
20
+ parser.add_argument("teff", type=float, nargs="?", help="effective temperature (K)")
21
+ parser.add_argument("e_teff", type=float, nargs="?", help="error on temperature")
22
+ args = parser.parse_args(argv)
23
+
24
+ if args.logg is None or args.e_logg is None:
25
+ args.logg, args.e_logg = map(float, input("> Give log g and error: ").split())
26
+ if args.teff is None or args.e_teff is None:
27
+ args.teff, args.e_teff = map(
28
+ float, input("> Give eff. temp. and error: ").split()
29
+ )
30
+ logg, gerr, teff, terr = args.logg, args.e_logg, args.teff, args.e_teff
31
+
32
+ gvals = np.random.normal(loc=logg, scale=gerr, size=100)
33
+ tvals = np.random.normal(loc=teff, scale=terr, size=100)
34
+
35
+ # ldvals = []
36
+ # for g,t in zip(gvals,tvals):
37
+ # ldvals.extend( ld('i',g,t) )
38
+ print("-------------------")
39
+ for band in ["u", "g", "r", "i", "z"]:
40
+ ldvals = [ld(band, g, t) for g, t in zip(gvals, tvals)]
41
+ print(
42
+ "%s band LD coeff = %f +/- %f" % (band, np.median(ldvals), np.std(ldvals))
43
+ )
44
+
45
+ ldvals = [ld(band, g, t, law="quad") for g, t in zip(gvals, tvals)]
46
+ # unpack list of tuples into two lists
47
+ a, b = list(
48
+ zip(*ldvals)
49
+ ) # use splat operator to expand list into positional arguments
50
+ print("%s band quad coeff a = %f +/- %f" % (band, np.median(a), np.std(a)))
51
+ print("%s band quad coeff b = %f +/- %f" % (band, np.median(b), np.std(b)))
52
+
53
+ ldvals = [ld(band, g, t, law="sqr") for g, t in zip(gvals, tvals)]
54
+ # unpack list of tuples into two lists
55
+ a, b = list(
56
+ zip(*ldvals)
57
+ ) # use splat operator to expand list into positional arguments
58
+ print("%s band sqr coeff d = %f +/- %f" % (band, np.median(a), np.std(a)))
59
+ print("%s band sqr coeff f = %f +/- %f" % (band, np.median(b), np.std(b)))
60
+ print("-------------------")
61
+
62
+
63
+ if __name__ == "__main__":
64
+ main()
@@ -0,0 +1,168 @@
1
+ """
2
+ Run the MCMC fit. Requires the input file, and the data files defined in it:
3
+
4
+ lfit-mcmcfit mcmc_input.dat
5
+ """
6
+
7
+ import argparse
8
+ import multiprocessing as mp
9
+ import os
10
+ import sys
11
+ from pprint import pprint
12
+ from shutil import rmtree
13
+
14
+ import configobj
15
+ import h5py
16
+ import numpy as np
17
+
18
+ from ..cv_model import construct_model
19
+ from ..likelihood import ln_like, ln_prior, ln_prob
20
+ from ..plotting import nxdraw, plot_model
21
+ from ..sampling import run_emcee
22
+ from ..summary import fit_summary
23
+
24
+ CHAIN_FNAME = "chain_prod.h5"
25
+
26
+
27
+ def main(argv=None):
28
+ # Set up the parser.
29
+ parser = argparse.ArgumentParser(
30
+ description="""Execute an MCMC fit to a dataset."""
31
+ )
32
+
33
+ parser.add_argument(
34
+ "input",
35
+ help="The filename for the MCMC parameters' input file.",
36
+ type=str,
37
+ )
38
+
39
+ parser.add_argument(
40
+ "--debug", help="Enable the debugging flag in the model", action="store_true"
41
+ )
42
+
43
+ parser.add_argument(
44
+ "--quiet", help="Do not plot the initial conditions", action="store_true"
45
+ )
46
+
47
+ parser.add_argument(
48
+ "-e", "--extend", help="extend a previous chain", action="store_true"
49
+ )
50
+
51
+ parser.add_argument(
52
+ "-a",
53
+ "--alt_moves",
54
+ help="use alternative (differential evolution) moves",
55
+ action="store_true",
56
+ )
57
+
58
+ args = parser.parse_args(argv)
59
+ input_fname = args.input
60
+
61
+ if args.debug:
62
+ if os.path.isdir("DEBUGGING"):
63
+ rmtree("DEBUGGING")
64
+
65
+ # Build the model from the input file
66
+ model = construct_model(input_fname, debug=args.debug)
67
+
68
+ print("\nStructure:")
69
+ pprint(model.structure)
70
+
71
+ input_dict = configobj.ConfigObj(input_fname)
72
+
73
+ # Read in information about mcmc
74
+ nburn = int(input_dict["nburn"])
75
+ nprod = int(input_dict["nprod"])
76
+ nthreads = int(input_dict["nthread"])
77
+ nwalkers = int(input_dict["nwalkers"])
78
+ scatter_1 = float(input_dict["first_scatter"])
79
+ scatter_2 = float(input_dict["second_scatter"])
80
+ to_fit = int(input_dict["fit"])
81
+ double_burnin = bool(int(input_dict["double_burnin"]))
82
+ comp_scat = bool(int(input_dict["comp_scat"]))
83
+
84
+ # Work out how many degrees of freedom we have in the model
85
+ # How many data points do we have?
86
+ dof = np.sum([ecl.lc.n_data for ecl in model.search_node_type("Eclipse")])
87
+ # Subtract a DoF for each variable
88
+ dof -= len(model.dynasty_par_names)
89
+ # Subtract one DoF for the fit
90
+ dof -= 1
91
+ dof = int(dof)
92
+
93
+ print(
94
+ "\n\nInitial guess has a chisq of {:.3f} ({:d} D.o.F.).".format(
95
+ model.chisq(), dof
96
+ )
97
+ )
98
+ print("\nFrom the wrapper functions with the above parameters, we get;")
99
+ pars = model.dynasty_par_vals
100
+ print("a ln_prior of {:.3f}".format(ln_prior(pars, model)))
101
+ print("a ln_like of {:.3f}".format(ln_like(pars, model)))
102
+ print("a ln_prob of {:.3f}".format(ln_prob(pars, model)))
103
+ print()
104
+ if np.isinf(ln_prior(pars, model)):
105
+ print("ERROR: Starting position violates priors!")
106
+ print("Offending parameters are:")
107
+
108
+ parameters, names = model.__get_descendant_params__()
109
+ for par, name in zip(parameters, names):
110
+ print("{:>15s}_{:<5s}: Valid?: {}".format(par.name, name, par.isValid))
111
+
112
+ if not par.isValid:
113
+ print(" -> {}_{}".format(par.name, name))
114
+
115
+ print("If all params are valid; they may lead to invalid combinations.")
116
+ print("Check the ln_prior methods of SimpleEclipse and ComplexEclipse")
117
+ sys.exit(1)
118
+
119
+ # If we're not running the fit, plot our stuff.
120
+ if not args.quiet:
121
+ nxdraw(model)
122
+ plot_model(model, True, save=True, figsize=(11, 8), save_dir="Initial_figs/")
123
+ if not to_fit:
124
+ return
125
+
126
+ # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
127
+ # MCMC Chain sampler, handled by emcee. #
128
+ # The below plugs the above into emcee's relevant functions #
129
+ # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
130
+
131
+ # How many parameters do I have to deal with?
132
+ npars = len(model.dynasty_par_vals)
133
+
134
+ print("\n\nThe MCMC has {:d} variables and {:d} walkers".format(npars, nwalkers))
135
+ print("(It should have at least 2*npars, {:d} walkers)".format(2 * npars))
136
+ if nwalkers < 2 * npars:
137
+ sys.exit(1)
138
+
139
+ # p_0 is the initial position vector of the MCMC walker
140
+ p_0 = model.dynasty_par_vals
141
+
142
+ # Run MCMC
143
+ with mp.get_context("spawn").Pool(nthreads) as pool:
144
+ run_emcee(
145
+ model,
146
+ p_0,
147
+ nwalkers,
148
+ nburn,
149
+ nprod,
150
+ scatter_1,
151
+ scatter_2,
152
+ # If comp_scat is asked for, each parameter is scattered by a
153
+ # different amount.
154
+ per_parameter_scatter=comp_scat,
155
+ double_burnin=double_burnin,
156
+ pool=pool,
157
+ alt_moves=args.alt_moves,
158
+ extend=args.extend,
159
+ chain_fname=CHAIN_FNAME,
160
+ )
161
+ # add parnames to chain file
162
+ with h5py.File(CHAIN_FNAME, "r+") as f:
163
+ f["mcmc"].attrs["var_names"] = model.dynasty_par_names
164
+ fit_summary(CHAIN_FNAME, input_fname, automated=True)
165
+
166
+
167
+ if __name__ == "__main__":
168
+ main()
@@ -0,0 +1,154 @@
1
+ """Compute physical system parameters from an lfit MCMC chain.
2
+
3
+ Usage: lfit-physparams chain_prod.h5 TWD E_TWD PERIOD E_PERIOD
4
+ """
5
+
6
+ import argparse
7
+ import os
8
+ from functools import partial
9
+ from multiprocessing import Pool
10
+
11
+ import emcee
12
+ import h5py
13
+ import matplotlib.pyplot as plt
14
+ import numpy as np
15
+ import seaborn as sns
16
+ from astropy import units
17
+ from astropy.table import Table
18
+ from tqdm import tqdm
19
+
20
+ from .. import DATA_DIR
21
+ from ..chains import flatchain, readchain_dask
22
+ from ..physical_params import solve
23
+ from ..plotting import thumbPlot
24
+
25
+
26
+ def main(argv=None):
27
+ sns.set()
28
+ parser = argparse.ArgumentParser(
29
+ description="Calculate physical parameters from MCMC chain of LFIT parameters"
30
+ )
31
+ parser.add_argument("file", action="store", help="chain_prod file from mcmcfit run")
32
+ parser.add_argument(
33
+ "twd", action="store", type=float, help="white dwarf temperature (K)"
34
+ )
35
+ parser.add_argument("e_twd", action="store", type=float, help="error on wd temp")
36
+ parser.add_argument("p", action="store", type=float, help="orbital period (days)")
37
+ parser.add_argument("e_p", action="store", type=float, help="error on period")
38
+ parser.add_argument(
39
+ "--thin", "-t", type=int, help="amount to thin MCMC chain by", default=1
40
+ )
41
+ parser.add_argument(
42
+ "--helium",
43
+ "-e",
44
+ action="store_true",
45
+ help="use helium core models for WDs",
46
+ )
47
+ parser.add_argument(
48
+ "--skip",
49
+ "-s",
50
+ type=int,
51
+ help="number of steps to skip in MCMC chain",
52
+ default=1,
53
+ )
54
+ parser.add_argument(
55
+ "--nthreads", "-n", type=int, help="number of threads to run", default=6
56
+ )
57
+ parser.add_argument(
58
+ "--dir",
59
+ "-d",
60
+ help="directory with WD models (default: the packaged copies)",
61
+ default=None,
62
+ )
63
+ args = parser.parse_args(argv)
64
+ fname = args.file
65
+ thin = args.thin
66
+ nthreads = args.nthreads
67
+ skip = args.skip
68
+ baseDir = args.dir
69
+
70
+ if baseDir is None:
71
+ print("Using the packaged WD model files")
72
+ baseDir = DATA_DIR
73
+ print("baseDir (must contain WD model directories): {}".format(baseDir))
74
+
75
+ print("Reading chain file...")
76
+ try:
77
+ chain = readchain_dask(fname)
78
+ nwalkers, nsteps, npars = chain.shape
79
+ fchain = flatchain(chain, npars, nskip=skip, thin=thin)
80
+ # grab param names from the file
81
+ with open(fname, "r") as chain_file:
82
+ nameList = chain_file.readline().strip().split(" ")[1:]
83
+ except:
84
+ reader = emcee.backends.HDFBackend(fname, read_only=True)
85
+ fchain = reader.get_chain(discard=skip, thin=thin, flat=True)
86
+ nwalkers, npars = reader.shape
87
+ with h5py.File(fname, "r") as chain_file:
88
+ nameList = list(chain_file["mcmc"].attrs["var_names"])
89
+ print("Done!")
90
+
91
+ # we need q, dphi, rw from the chain
92
+ qVals = fchain[:, nameList.index("q_core")]
93
+ dphiVals = fchain[:, nameList.index("dphi_core")]
94
+ rwVals = fchain[:, nameList.index("rwd_core")]
95
+ chainLength = len(qVals)
96
+ print("The chain contains {} samples".format(chainLength))
97
+
98
+ print("Means; ")
99
+ print(" q: {:.3f}".format(np.mean(qVals)))
100
+ print(" dphi: {:.3f}".format(np.mean(dphiVals)))
101
+ print(" rwd: {:.3f}".format(np.mean(rwVals)))
102
+
103
+ # white dwarf temp
104
+ twdVals = (
105
+ np.random.normal(loc=args.twd, scale=args.e_twd, size=chainLength) * units.K
106
+ )
107
+
108
+ # period
109
+ pVals = np.random.normal(loc=args.p, scale=args.e_p, size=chainLength) * units.d
110
+
111
+ # loop over the MCMC chain, calculating system parameters as we go
112
+
113
+ # table for results
114
+ results = Table(
115
+ names=("q", "Mw", "Rw", "logg", "Mr", "Rr", "a", "Kw", "Kr", "incl")
116
+ )
117
+ # need to be a little careful about astropy versions here, since only
118
+ # versions >=1.0 allow quantities in tables
119
+ # function below extracts value from quantity and floats alike
120
+ getval = lambda el: getattr(el, "value", el)
121
+
122
+ print("Getting solutions for each step of the MCMC chain...")
123
+ psolve = partial(solve, baseDir=baseDir, helium=args.helium)
124
+ data = zip(qVals, dphiVals, rwVals, twdVals, pVals)
125
+ with Pool(processes=args.nthreads) as pool:
126
+ solvedParams = []
127
+ for result in tqdm(pool.imap(psolve, data), total=len(qVals)):
128
+ solvedParams.append(result)
129
+
130
+ print("Writing out results...")
131
+ # loop over these results and put all the solutions in our results table
132
+ for thisResult in tqdm(solvedParams):
133
+ if thisResult is not None:
134
+ results.add_row(thisResult)
135
+
136
+ print(
137
+ "Found solutions for %d percent of samples in MCMC chain"
138
+ % (100 * float(len(results)) / float(chainLength))
139
+ )
140
+ results.write("physicalparams.log", format="ascii", overwrite=True)
141
+
142
+ data = results.to_pandas()
143
+
144
+ with open("physicalparams_summary.log", "w") as f:
145
+ for p, m, s in zip(data.columns, data.mean(), data.std()):
146
+ f.write("{:>5s}: {:.5f} +/- {:.5f}\n".format(p, m, s))
147
+ print("{:>5s}: {:.5f} +/- {:.5f}".format(p, m, s))
148
+
149
+ fig = thumbPlot(data, data.columns)
150
+ plt.savefig("physicalParams_corners.png")
151
+
152
+
153
+ if __name__ == "__main__":
154
+ main()
@@ -0,0 +1,50 @@
1
+ """Look up the Gaia parallax and E(B-V) towards a target.
2
+
3
+ Needs the optional extras: pip install "lfit_python[reddening]"
4
+
5
+ Usage: lfit-reddening "V* OY Car"
6
+ """
7
+
8
+ import argparse
9
+
10
+ from astropy import coordinates as coord
11
+ from astropy import units as u
12
+ from astroquery.gaia import Gaia
13
+ from dustmaps.bayestar import BayestarQuery
14
+ from dustmaps.sfd import SFDQuery
15
+ from sigfig import round
16
+
17
+
18
+ def main(argv=None):
19
+ parser = argparse.ArgumentParser(
20
+ description="Find the Gaia parallax and Bayestar/SFD reddening for a target."
21
+ )
22
+ parser.add_argument("target", help="object name or coordinates")
23
+ args = parser.parse_args(argv)
24
+
25
+ Gaia.MAIN_GAIA_TABLE = "gaiadr3.gaia_source"
26
+
27
+ try:
28
+ coo = coord.SkyCoord.from_name(args.target)
29
+ except Exception:
30
+ coo = coord.SkyCoord.from_name(args.target, parse=True)
31
+
32
+ r = Gaia.query_object_async(coordinate=coo, width=10 * u.arcsec, height=10 * u.arcsec)
33
+ d = coord.Distance(parallax=float(r["parallax"]) * u.mas)
34
+ coo = coord.SkyCoord(coo.ra, coo.dec, distance=d)
35
+
36
+ bayestar = BayestarQuery()
37
+ sfd = SFDQuery()
38
+
39
+ ebv_bayestar = bayestar(coo, mode="percentile", pct=[16.0, 50.0, 84.0])
40
+ ebv_sfd = sfd(coo)
41
+
42
+ pstring = round(float(r["parallax"]), float(r["parallax_error"]))
43
+ print(f"Gaia Parallax = {pstring}")
44
+
45
+ print(f"Bayestar 16th-84th percentiles = {ebv_bayestar}")
46
+ print(f"Max E(B-V) from SFD = {ebv_sfd}")
47
+
48
+
49
+ if __name__ == "__main__":
50
+ main()