def get_gaussian_fit(z, t0, x0, x1, c, lc, seed, temp_dir, interped, type="iminuit"): model = sncosmo.Model(source='salt2-extended') p = {'z': z, 't0': t0, 'x0': x0, 'x1': x1, 'c': c} model.set(**p) correct_model = sncosmo.Model(source='salt2-extended') correct_model.set(**p) if type == "iminuit": res, fitted_model = sncosmo.fit_lc(lc, model, ['t0', 'x0', 'x1', 'c'], guess_amplitude=False, guess_t0=False) chain = np.random.multivariate_normal(res.parameters[1:], res.covariance, size=int(1e5)) fig = sncosmo.plot_lc(lc, model=[fitted_model, correct_model], errors=res.errors) fig.savefig(temp_dir + os.sep + "lc_%d.png" % seed, bbox_inches="tight", dpi=300) elif type == "mcmc": res, fitted_model = sncosmo.mcmc_lc(lc, model, ['t0', 'x0', 'x1', 'c'], nburn=500, nwalkers=20, nsamples=1500, guess_amplitude=False, guess_t0=False) chain = np.random.multivariate_normal(res.parameters[1:], res.covariance, size=int(1e5)) elif type == "nestle": bounds = {"t0": [980, 1020], "x0": [0.1e-6, 9e-3], "x1": [-10, 10], "c": [-1, 1]} res, fitted_model = sncosmo.nest_lc(lc, model, ['t0', 'x0', 'x1', 'c'], bounds, guess_amplitude=False, guess_t0=False) chain = np.random.multivariate_normal(res.parameters[1:], res.covariance, size=int(1e5)) else: raise ValueError("Type %s not recognised" % type) map = {"x0": "$x_0$", "x1": "$x_1$", "c": "$c$", "t0": "$t_0$"} parameters = [map[a] for a in res.vparam_names] chain, parameters = add_mu_to_chain(interped, chain, parameters) return chain, parameters, res.parameters[1:], res.covariance
def test_nest_lc(self): """Ensure that nested sampling runs.""" np.random.seed(0) # seed the RNG for reproducible results. self.model.set(**self.params) res, fitmodel = sncosmo.nest_lc( self.data, self.model, ['z', 't0', 'amplitude'], bounds={'z': (0., 1.0)}, guess_amplitude_bound=True, nobj=50) assert_allclose(fitmodel.parameters, self.model.parameters, rtol=0.05)
def test_nest_lc(self): """Ensure that nested sampling runs. Pass in parameter names in order different from that stored in model; tests parameter re-ordering. """ np.random.seed(0) # seed the RNG for reproducible results. self.model.set(**self.params) res, fitmodel = sncosmo.nest_lc( self.data, self.model, ['amplitude', 'z', 't0'], bounds={'z': (0., 1.0)}, guess_amplitude_bound=True, nobj=50) assert_allclose(fitmodel.parameters, self.model.parameters, rtol=0.05)
def test_nest_lc(self): """Ensure that nested sampling runs. Pass in parameter names in order different from that stored in model; tests parameter re-ordering. """ rstate = RandomState(0) self.model.set(**self.params) res, fitmodel = sncosmo.nest_lc( self.data, self.model, ['amplitude', 'z', 't0'], bounds={'z': (0., 1.0)}, guess_amplitude_bound=True, npoints=50, rstate=rstate) assert_allclose(fitmodel.parameters, self.model.parameters, rtol=0.05)
def nest_fit(data, model, vparam_names, **kwargs): """Fit light curves using nested sampling Args: data (Table): Table of photometric data model (Model): The model to fit vparam_names (iterable): Model parameters to vary Any other parameters for ``sncosmo.nest_lc`` Returns: - A dictionary like object with fit results - A fitted ``Model`` instance """ data, model, vparam_names, kwargs = \ _copy_data(data, model, vparam_names, kwargs) return sncosmo.nest_lc(data, model, vparam_names, **kwargs)
def task(filename, i, j, nrv, nebv, kind='mcmc'): lc = sncosmo.read_lc(filename, format='csp') model = sncosmo.Model(bump.BumpSource(), effect_names=['host', 'mw'], effect_frames=['rest', 'obs'], effects=[sncosmo.OD94Dust(), sncosmo.F99Dust()]) rv_prior = burns.get_hostrv_prior(lc.meta['name'], 'gmm', sncosmo.OD94Dust) host_ebv, err = burns.get_hostebv(lc.meta['name']) ebv_prior = TruncNorm(-np.inf, np.inf, host_ebv, err) rv_prior, low, high = burns.get_hostrv_prior(lc.meta['name'], 'gmm', sncosmo.OD94Dust, retlims=True) host_ebv, err = burns.get_hostebv(lc.meta['name']) rv = np.linspace(low if low >= 0 else 0, high, nrv)[i] ebvlo = host_ebv - err ebvhi = host_ebv + err ebv = np.linspace(ebvlo if ebvlo >= 0 else 0, ebvhi, nebv)[j] model.set(z=lc.meta['zcmb']) model.set(mwebv=burns.get_mwebv(lc.meta['name'])[0]) model.set(hostebv=ebv) model.set(hostr_v=rv) model.set(t0=burns.get_t0(lc.meta['name'])) vparams = filter(lambda x: 'bump' in x, model._param_names) vparams += ['t0', 's'] bounds = {b.name + "_bump_amp": (-1, 2) for b in model.source.bumps} #bounds['hostr_v'] = (rv_prior.mean - 0.5, rv_prior.mean + 0.5) #bounds['hostebv'] = (0, 0.2) bounds['s'] = (0, 3.) res, model = sncosmo.fit_lc(lc, model, ['amplitude'] + vparams, bounds=bounds) bounds['t0'] = (model.get('t0') - 2, model.get('t0') + 2) vparams.append('amplitude') bounds['amplitude'] = (0.5 * model.get('amplitude'), 2 * model.get('amplitude')) qualifier = '_ebv_%.2f_rv_%.2f' % (ebv, rv) if kind != 'fit': if kind == 'mcmc': result = sncosmo.mcmc_lc(lc, model, vparams, bounds=bounds, nwalkers=500, nburn=1000, nsamples=20) elif kind == 'nest': result = sncosmo.nest_lc(lc, model, vparams, bounds=bounds, method='multi', npoints=800) samples = result[0].samples.reshape(500, 20, -1) vparams = result[0].vparam_names plot_arg = np.rollaxis(samples, 2) plotting.plot_chains(plot_arg, param_names=vparams, filename='fits/%s_samples%s.pdf' % (lc.meta['name'], qualifier)) dicts = [ dict(zip(vparams, samp)) for samp in samples.reshape(500 * 20, -1) ] thinned = samples.reshape(500, 20, -1)[:, [0, -1]].reshape(1000, -1) pickle.dump( samples, open('fits/%s_samples%s.pkl' % (lc.meta['name'], qualifier), 'wb')) models = [copy(result[1]) for i in range(len(thinned))] for d, m in zip(dicts, models): m.set(**d) fig = sncosmo.plot_lc(data=lc, model=models, ci=(50 - 68 / 2., 50., 50 + 68 / 2.), model_label=lc.meta['name']) fig.savefig('fits/%s%s.pdf' % (lc.meta['name'], qualifier)) else: fitres, model = sncosmo.fit_lc(lc, model, vparams, bounds=bounds) fig = sncosmo.plot_lc(data=lc, model=model) fig.savefig('fits/%s_fit%s.pdf' % (lc.meta['name'], qualifier))
def runNest(self): nestOut = sncosmo.nest_lc(self.data, self.model, vparam_names=self.vparams, bounds=self.bounds, guess_amplitude_bound=True, minsnr=3.0, verbose=True) return nestOut
def task(filename, i, j, nrv, nebv, kind='mcmc'): lc = sncosmo.read_lc(filename, format='csp') model = sncosmo.Model(bump.BumpSource(), effect_names=['host','mw'], effect_frames=['rest','obs'], effects=[sncosmo.OD94Dust(), sncosmo.F99Dust()]) rv_prior = burns.get_hostrv_prior(lc.meta['name'], 'gmm', sncosmo.OD94Dust) host_ebv, err = burns.get_hostebv(lc.meta['name']) ebv_prior = TruncNorm(-np.inf, np.inf, host_ebv, err) rv_prior, low, high = burns.get_hostrv_prior(lc.meta['name'], 'gmm', sncosmo.OD94Dust, retlims=True) host_ebv, err = burns.get_hostebv(lc.meta['name']) rv = np.linspace(low if low >= 0 else 0, high, nrv)[i] ebvlo = host_ebv - err ebvhi = host_ebv + err ebv = np.linspace(ebvlo if ebvlo >= 0 else 0, ebvhi, nebv)[j] model.set(z=lc.meta['zcmb']) model.set(mwebv=burns.get_mwebv(lc.meta['name'])[0]) model.set(hostebv=ebv) model.set(hostr_v=rv) model.set(t0=burns.get_t0(lc.meta['name'])) vparams = filter(lambda x: 'bump' in x, model._param_names) vparams += ['t0', 's'] bounds = {b.name + "_bump_amp":(-1,2) for b in model.source.bumps} #bounds['hostr_v'] = (rv_prior.mean - 0.5, rv_prior.mean + 0.5) #bounds['hostebv'] = (0, 0.2) bounds['s'] = (0, 3.) res, model = sncosmo.fit_lc(lc,model,['amplitude']+vparams, bounds=bounds) bounds['t0'] = (model.get('t0')-2, model.get('t0')+2) vparams.append('amplitude') bounds['amplitude'] = (0.5 * model.get('amplitude'), 2 * model.get('amplitude')) qualifier = '_ebv_%.2f_rv_%.2f' % (ebv, rv) if kind != 'fit': if kind == 'mcmc': result = sncosmo.mcmc_lc(lc, model, vparams, bounds=bounds, nwalkers=500, nburn=1000, nsamples=20) elif kind == 'nest': result = sncosmo.nest_lc(lc, model, vparams, bounds=bounds, method='multi', npoints=800) samples = result[0].samples.reshape(500, 20, -1) vparams = result[0].vparam_names plot_arg = np.rollaxis(samples, 2) plotting.plot_chains(plot_arg, param_names=vparams, filename='fits/%s_samples%s.pdf' % (lc.meta['name'], qualifier)) dicts = [dict(zip(vparams, samp)) for samp in samples.reshape(500 * 20, -1)] thinned = samples.reshape(500, 20, -1)[:, [0, -1]].reshape(1000, -1) pickle.dump(samples, open('fits/%s_samples%s.pkl' % (lc.meta['name'], qualifier), 'wb')) models = [copy(result[1]) for i in range(len(thinned))] for d, m in zip(dicts, models): m.set(**d) fig = sncosmo.plot_lc(data=lc, model=models, ci=(50-68/2., 50., 50+68/2.), model_label=lc.meta['name']) fig.savefig('fits/%s%s.pdf' % (lc.meta['name'], qualifier)) else: fitres, model = sncosmo.fit_lc(lc, model, vparams, bounds=bounds) fig = sncosmo.plot_lc(data=lc, model=model) fig.savefig('fits/%s_fit%s.pdf' % (lc.meta['name'], qualifier))