def test_goodness_of_fit():

    # Let's generate some data with y = Powerlaw(x)

    gen_function = Powerlaw()

    # Generate a dataset using the power law, and a
    # constant 30% error

    x = np.logspace(0, 2, 50)

    xyl_generator = XYLike.from_function(
        "sim_data", function=gen_function, x=x, yerr=0.3 * gen_function(x)
    )

    y = xyl_generator.y
    y_err = xyl_generator.yerr

    fit_function = Powerlaw()

    xyl = XYLike("data", x, y, y_err)

    parameters, like_values = xyl.fit(fit_function)

    gof, all_results, all_like_values = xyl.goodness_of_fit()

    # Compute the number of degrees of freedom
    n_dof = len(xyl.x) - len(fit_function.free_parameters)

    # Get the observed value for chi2
    obs_chi2 = 2 * like_values["-log(likelihood)"]["data"]

    theoretical_gof = scipy.stats.chi2(n_dof).sf(obs_chi2)

    assert np.isclose(theoretical_gof, gof["total"], rtol=0.1)
예제 #2
0
def test_all():
    response = OGIPResponse(
        get_path_of_data_file("datasets/ogip_powerlaw.rsp"))

    np.random.seed(1234)

    # rescale the functions for the response
    source_function = Blackbody(K=1e-7, kT=500.0)
    background_function = Powerlaw(K=1, index=-1.5, piv=1.0e3)
    spectrum_generator = DispersionSpectrumLike.from_function(
        "fake",
        source_function=source_function,
        background_function=background_function,
        response=response)

    source_function.K.prior = Log_normal(mu=np.log(1e-7), sigma=1)
    source_function.kT.prior = Log_normal(mu=np.log(300), sigma=2)

    ps = PointSource("demo", 0, 0, spectral_shape=source_function)

    model = Model(ps)

    ba = BayesianAnalysis(model, DataList(spectrum_generator))

    ba.set_sampler()

    ba.sample(quiet=True)

    ppc = compute_ppc(ba,
                      ba.results,
                      n_sims=500,
                      file_name="my_ppc.h5",
                      overwrite=True,
                      return_ppc=True)

    ppc.fake.plot(bkg_subtract=True)

    ppc.fake.plot(bkg_subtract=False)