def plot_slope(source, params, xaxis='qnuc', cycles=None, linear=True, display=True, depth=None, grid_version=0): """xaxis : ['accrate', 'qnuc'] """ xlabel = { 'accrate': '$\dot{M} / \dot{M}_\mathrm{Edd}$', 'qnuc': '$Q_\mathrm{nuc}$' }.get(xaxis, xaxis) kgrid = grid_analyser.Kgrid(source, grid_version=grid_version) subset = kgrid.get_params(params=params) slopes = qnuc_tools.get_slopes(param_table=subset, source=source, cycles=cycles, depth=depth) fig, ax = plt.subplots() ax.plot(subset[xaxis], slopes, ls='none', marker='o') x = np.array((0, 9)) ax.plot(x, [0, 0], color='black') set_axes(ax, xlabel=xlabel, ylabel='dT/dt (K s$^{-1}$)', title=params) if linear: linr = linregress(subset[xaxis], slopes) ax.plot(x, x * linr[0] + linr[1]) if display: plt.show(block=False) else: plt.close()
def __init__(self, source='grid4', source2='grid4', version=1, runs=(9, 10, 11), batches=(5, 5, 5), n_walkers=960, n_steps=1000): self.grid = grid_analyser.Kgrid(source2) self.bfit = burstfit.BurstFit(source, version, re_interp=False) self.runs = runs self.batches = batches self.best_params = mcmc_tools.get_max_lhood_params(source, version=version, n_walkers=n_walkers, n_steps=n_steps) red_idx = self.bfit.param_idxs['redshift'] fb_idx = self.bfit.param_idxs['f_b'] self.redshift = self.best_params[red_idx] self.f_b = self.best_params[fb_idx] self.n_epochs = len(runs) self.shifted_lc = {} self.interp_lc = {} self.t_shifts = None self.extract_lc() self.get_all_tshifts()
def extract_qnuc_table(source, grid_version=0, param_batch=None, param_table=None, cycles=None, depth=None): """Extracts optimal Qnuc across all parameters param_batch : int (optional) batch that represents all unique parameters (x, z, accrate, mass) param_table : pd.DataFrame (optional) alternative to param_batch. A table containing each unique set of paraemeters """ # TODO: make more automatic with grid_version (getting param_table) kgrid = grid_analyser.Kgrid(source, linregress_burst_rate=False, grid_version=grid_version) if param_table is None: if param_batch is None: raise ValueError( 'Must specify one of "param_batch" or "param_table"') else: param_table = kgrid.get_params(batch=param_batch) elif param_batch is not None: raise ValueError( 'Can only specify one of "param_batch" and "param_table"') qnuc_table = iterate_solve_qnuc(source, param_table=param_table, cycles=cycles, kgrid=kgrid, grid_version=grid_version, depth=depth) save_qnuc_table(qnuc_table, source, grid_version)
def solve_qnuc(source, params, cycles=None, kgrid=None, grid_version=0, depth=None): """Returns predicted Qnuc that gives stable base temperature """ # TODO: add other methods (e.g. bisection) param_list = ('x', 'z', 'accrate', 'mass') for p in param_list: if p not in params: raise ValueError(f'Missing "{p}" from "params"') if kgrid is None: kgrid = grid_analyser.Kgrid(source, linregress_burst_rate=False, grid_version=grid_version) subset = kgrid.get_params(params=params) slopes = get_slopes(param_table=subset, source=source, cycles=cycles, depth=depth) linr = linregress(subset['qnuc'], slopes) x0 = -linr[1] / linr[0] # x0 = -y0/m u_x0 = (linr[4] / linr[0]) * x0 return x0, u_x0
def generate_params(source, batches, run, mc_source, mc_version, free_params=('m_gr', 'd_b', 'xi_ratio')): """""" synth_grid = grid_analyser.Kgrid(source, use_sub_cols=True) mv = mcmc_versions.McmcVersion(mc_source, version=mc_version) n_epochs = len(batches) pkeys = mv.param_keys params = dict.fromkeys(pkeys) # ===== Pull model params from kepler grid ===== for key in mv.interp_keys: key = mv.param_aliases.get(key, key) if key in mv.epoch_unique: for i in range(n_epochs): grid_params = synth_grid.get_params(batches[i], run) e_key = f'{key}{i+1}' grid_key = {'mdot': 'accrate'}.get(key, key) params[e_key] = float(grid_params[grid_key]) else: grid_key = {'m_nw': 'mass'}.get(key, key) grid_params = synth_grid.get_params(batches[0], run) params[key] = float(grid_params[grid_key]) # ===== Randomly generate free params ===== for key in free_params: params[key] = mcmc_tools.get_random_params(key, n_models=1, mv=mv)[0] return params
def __init__(self, source, mcmc_source, mcmc_version, batches, runs=None, verbose=True, n_bursts=1, fit_tail_only=False, n_points=None): self.source = source self.n_epochs = len(batches) self.obs_source = obs_sources[source] self.grid = grid_analyser.Kgrid(self.source) self.bfit = burstfit.BurstFit(mcmc_source, version=mcmc_version, re_interp=False) self.obs = ctools.load_obs(self.obs_source) self.batches = batches self.params = load_param_sample(self.source, self.batches) self.verbose = verbose self.n_bursts = n_bursts # no. bursts to get from each model self.xlims = { 'gs1826': (-10, 170), '4u1820': (-2, 27), }.get(self.obs_source) self.epochs = { 'gs1826': (1998, 2000, 2007), '4u1820': (1997, 2009), }.get(self.obs_source) if runs is None: # assume all batches have corresponding runs sub_batch = self.grid.get_params(self.batches[0]) self.runs = np.array(sub_batch['run']) else: self.runs = runs self.n_runs = len(self.runs) self.n_bursts_batch = self.n_runs * self.n_bursts self.n_points = n_points if self.n_points is None: self.n_points = {'gs1826': 200, '4u1820': 500}.get(self.obs_source) self.peak_i = np.zeros(self.n_epochs, dtype=int) if fit_tail_only: self.get_peak_indexes() self.loaded_lc = {} self.shifted_lc = {} self.interp_lc = {} self.t_shifts = None self.load_model_lc() self.extract_lc() self.interp_obs_lc() self.get_all_tshifts()
def plot_batch(source, batch, error=False): kgrid = grid_analyser.Kgrid(source=source, linregress_burst_rate=False, load_lc=True) table = kgrid.get_params(batch) fig, ax = plt.subplots() for row in table.itertuples(): kgrid.add_lc_plot(ax, batch=batch, run=row.run, label=f'{row.run}', error=error) plt.tight_layout() plt.show(block=False)
def compare(batch, source, ref_source, bprops=('rate', 'fluence', 'peak')): """Compares models with differe bdats/adapnets""" kgrid = grid_analyser.Kgrid(source, linregress_burst_rate=False) kgrid_ref = grid_analyser.Kgrid(ref_source, linregress_burst_rate=False) sub_params = kgrid.get_params(batch).reset_index() sub_summ = kgrid.get_summ(batch).reset_index() params_ref, summ_ref = extract_ref_subset(param_table=sub_params, kgrid_ref=kgrid_ref) fig, ax = plt.subplots(len(bprops), 1, figsize=(10, 12)) for i, bprop in enumerate(bprops): u_bprop = f'u_{bprop}' ratio = sub_summ[bprop] / summ_ref[bprop] u_frac = sub_summ[u_bprop]/sub_summ[bprop] + summ_ref[u_bprop]/summ_ref[bprop] u_ratio = ratio * u_frac n = len(ratio) ax[i].errorbar(np.arange(n), ratio, yerr=u_ratio, ls='none', marker='o', capsize=3) ax[i].plot([0, n], [1, 1], color='black') ax[i].set_ylabel(bprop) plt.tight_layout() plt.show(block=False)
def plot_interp_residuals(synth_source, batches, mc_source, mc_version, fontsize=16): """Plot synthetic burst properties against interpolated predictions to test accuracy of interpolator """ n_sigma = 1.96 bfit = burstfit.BurstFit(source=mc_source, version=mc_version) bprops = bfit.mcmc_version.bprops kgrid = grid_analyser.Kgrid(source=synth_source) param_table = kgrid.get_combined_params(batches) interp_table = extract_interp_table(param_table, bfit=bfit) summ_table = kgrid.get_combined_summ(batches) fig, ax = plt.subplots(len(bprops), figsize=(6, 8)) for i, bprop in enumerate(bprops): u_bprop = f'u_{bprop}' yscale = plot_tools.unit_scale(bprop) yunits = plot_tools.unit_label(bprop) model = np.array(summ_table[bprop]) / yscale interp = np.array(interp_table[bprop]) / yscale u_model = np.array(summ_table[u_bprop]) / yscale u_interp = np.array(interp_table[u_bprop]) / yscale residuals = interp - model u_residuals = n_sigma * np.sqrt(u_model**2 + u_interp**2) ax[i].errorbar(model, residuals, yerr=u_residuals, marker='o', ls='none', capsize=3) x_max = np.max(model) x_min = np.min(model) ax[i].plot([0.9 * x_min, 1.1 * x_max], [0, 0], ls='--', color='black') ax[i].set_xlabel(f'{bprop} ({yunits})', fontsize=fontsize) ax[1].set_ylabel(f'Interpolated - model', fontsize=fontsize) plt.tight_layout() plt.show(block=False)
def plot_bprops(source, params, grid_version, bprop='dt'): """Plots burst property versus qnuc """ kgrid = grid_analyser.Kgrid(source, grid_version=grid_version) sub_p = kgrid.get_params(params=params) sub_s = kgrid.get_summ(params=params) fig, ax = plt.subplots() ax.errorbar(sub_p['qnuc'], sub_s[bprop], yerr=sub_s[f'u_{bprop}'], ls='None', marker='o', capsize=3) ax.set_xlabel('$Q_\mathrm{nuc}$') ax.set_ylabel(bprop) plt.show(block=False)
def __init__(self, source, mcmc_source, mcmc_version, batches, runs=None, verbose=True): self.source = source self.grid = grid_analyser.Kgrid(self.source) self.bfit = burstfit.BurstFit(mcmc_source, version=mcmc_version, re_interp=False) self.obs = ctools.load_obs('gs1826') self.batches = batches self.params = load_param_sample(self.source, self.batches) self.verbose = verbose if runs is None: sub_batch = self.grid.get_params(self.batches[0]) self.runs = np.array(sub_batch['run']) else: self.runs = runs self.n_epochs = len(batches) self.shifted_lc = {} self.interp_lc = {} self.t_shifts = None self.extract_lc() self.interp_obs_lc() self.get_all_tshifts()
def get_multigrids(sources, grid_version): kgrids = {} for source in sources: kgrids[source] = grid_analyser.Kgrid(source, grid_version=grid_version) return kgrids