from sherpa.plot import DataPlot, ModelPlot dplot = DataPlot() dplot.prepare(f.data) mplot = ModelPlot() mplot.prepare(f.data, f.model) dplot.plot() mplot.overplot() savefig("data_model_c0_c2.png") dump("f.method.name") original_method = f.method from sherpa.optmethods import NelderMead f.method = NelderMead() resn = f.fit() print("Change in statistic: {}".format(resn.dstatval)) fit2 = Fit(d, mdl, method=NelderMead()) fit2.fit() mdl.c1.thaw() f.method = original_method res2 = f.fit() report("res2.format()") from sherpa.plot import DelchiPlot, FitPlot, SplitPlot fplot = FitPlot() rplot = DelchiPlot()
# Requires sherpa 4.9 import numpy as np from astropy import units as u from sherpa.models import ArithmeticModel, Parameter from sherpa.data import DataND, BaseData, Data from sherpa.stats import Likelihood from sherpa.optmethods import LevMar, NelderMead, MonCar, GridSearch __all__ = ['SherpaDataWrapper', 'SherpaModelWrapper', 'SherpaStatWrapper'] SHERPA_OPTMETHODS = { 'simplex': NelderMead(), 'moncar': MonCar(), 'gridsearch': GridSearch() } class SherpaDataWrapper(Data): def __init__(self, gp_data, name='GPData'): # sherpa does some magic here: it sets class attributes from constructor # arguments so `gp-data` will be available later on the instance. self._data_dummy = np.empty_like(gp_data.e_ref) BaseData.__init__(self) def to_fit(self, staterr): return self._data_dummy, None, None def eval_model_to_fit(self, model): return self._data_dummy
def run(fit, null_comp, alt_comp, conv_mdl=None, stat=None, method=None, niter=500, numcores=None): if stat is None: stat = CStat() if method is None: method = NelderMead() if not isinstance(stat, (Cash, CStat)): raise TypeError("Sherpa fit statistic must be Cash or CStat" + " for likelihood ratio test") niter = int(niter) alt = alt_comp null = null_comp oldaltvals = numpy.array(alt.thawedpars) oldnullvals = numpy.array(null.thawedpars) data = fit.data if conv_mdl is not None: # Copy the PSF null_conv_mdl = deepcopy(conv_mdl) alt = conv_mdl(alt_comp) if hasattr(conv_mdl, 'fold'): conv_mdl.fold(data) # Convolve the null model null = null_conv_mdl(null_comp) if hasattr(null_conv_mdl, 'fold'): null_conv_mdl.fold(data) nullfit = Fit(data, null, stat, method, Covariance()) # Fit with null model nullfit_results = nullfit.fit() debug(nullfit_results.format()) null_stat = nullfit_results.statval null_vals = nullfit_results.parvals # Calculate niter samples using null best-fit and covariance sampler = NormalParameterSampleFromScaleMatrix() samples = sampler.get_sample(nullfit, None, niter) # Fit with alt model, null component starts at null's best fit params. altfit = Fit(data, alt, stat, method, Covariance()) altfit_results = altfit.fit() debug(altfit_results.format()) alt_stat = altfit_results.statval alt_vals = altfit_results.parvals LR = -(alt_stat - null_stat) olddep = data.get_dep(filter=False) try: statistics = parallel_map( LikelihoodRatioTestWorker(nullfit, altfit, null_vals, alt_vals), samples, numcores) finally: data.set_dep(olddep) alt.thawedpars = list(oldaltvals) null.thawedpars = list(oldnullvals) debug("statistic null = " + repr(null_stat)) debug("statistic alt = " + repr(alt_stat)) debug("LR = " + repr(LR)) statistics = numpy.asarray(statistics) pppvalue = numpy.sum(statistics[:, 2] > LR) / (1.0 * niter) debug('ppp value = ' + str(pppvalue)) return LikelihoodRatioResults(statistics[:, 2], statistics[:, 0:2], samples, LR, pppvalue, null_stat, alt_stat)
def test_wstat_error(self): data = self.bkg data.notice(0.5, 7.0) fit = Fit(data, self.model, WStat(), NelderMead()) self.assertRaises(StatErr, fit.fit)
report("f") print("Starting statistic: {}".format(f.calc_stat())) fitres = f.fit() report("fitres.format()") print("Reduced chi square = {:.2f}".format(fitres.rstat)) mplot.prepare(d, mdl) dplot.plot() mplot.overplot() savefig("model_data_fit1.png") from sherpa.optmethods import NelderMead f.method = NelderMead() fitres2 = f.fit() report("mdl") dump("fitres2.dstatval") mdl.reset() report("mdl") plateau.c0 = np.max(d.y) mplot.prepare(d, mdl) dplot.plot() mplot.overplot() savefig("model_data_reset.png") fitres3 = f.fit()
def test_mycash_datahasbkg_modelhasnobkg(self): fit = Fit(self.data, self.model, MyCashNoBkg(), NelderMead()) results = fit.fit() self.compare_results(self._fit_mycash_results_bench, results)
def test_mycash_nobkgdata_modelhasbkg(self): data = self.bkg fit = Fit(data, self.model, MyCashWithBkg(), NelderMead()) results = fit.fit() self.compare_results(self._fit_mycashnobkg_results_bench, results, tol=1.0e-3)
def test_mycash_data_and_model_donothave_bkg(self): data = self.bkg fit = Fit(data, self.model, MyCashNoBkg(), NelderMead()) results = fit.fit() self.compare_results(self._fit_mycashnobkg_results_bench, results, tol=1.0e-3)
def test_mycash_data_and_model_have_bkg(self): fit = Fit(self.data, self.model, MyCashWithBkg(), NelderMead()) results = fit.fit() self.compare_results(self._fit_mycash_results_bench, results)
def test_cash_stat(self): fit = Fit(self.data, self.model, Cash(), NelderMead()) results = fit.fit() self.compare_results(self._fit_mycash_results_bench, results)
def test_chi2gehrels_stat(self): fit = Fit(self.data, self.model, Chi2Gehrels(), NelderMead()) results = fit.fit() self.compare_results(self._fit_chi2gehrels_results_bench, results)
def test_chi2modvar_stat(self): fit = Fit(self.data, self.model, Chi2ModVar(), NelderMead()) results = fit.fit() self.compare_results(self._fit_chi2modvar_results_bench, results)