Beispiel #1
0
def test_analytic_integral():
    class DistFunc3(zbasepdf.BasePDF):
        def _unnormalized_pdf(self, x, norm_range=False):
            return func3_2deps(x)

    mu_true = 1.4
    sigma_true = 1.8
    limits = -4.3, 1.9
    mu = Parameter("mu_1414", mu_true, mu_true - 2., mu_true + 7.)
    sigma = Parameter("sigma_1414", sigma_true, sigma_true - 10., sigma_true + 5.)
    gauss_params1 = CustomGaussOLD(mu=mu, sigma=sigma, obs=obs1, name="gauss_params1")
    normal_params1 = Gauss(mu=mu, sigma=sigma, obs=obs1, name="gauss_params1")
    try:
        infinity = mt.inf
    except AttributeError:  # py34
        infinity = float('inf')
    gauss_integral_infs = gauss_params1.integrate(limits=(-infinity, infinity), norm_range=False)
    normal_integral_infs = normal_params1.integrate(limits=(-infinity, infinity), norm_range=False)

    DistFunc3.register_analytic_integral(func=func3_2deps_fully_integrated,
                                         limits=Space.from_axes(limits=limits3, axes=(0, 1)))

    dist_func3 = DistFunc3(obs=['obs1', 'obs2'])
    gauss_integral_infs = zfit.run(gauss_integral_infs)
    normal_integral_infs = zfit.run(normal_integral_infs)
    func3_integrated = zfit.run(
        ztf.convert_to_tensor(
            dist_func3.integrate(limits=Space.from_axes(limits=limits3, axes=(0, 1)), norm_range=False),
            dtype=tf.float64))
    assert func3_integrated == func3_2deps_fully_integrated(limits=Space.from_axes(limits=limits3, axes=(0, 1)))
    assert gauss_integral_infs == pytest.approx(np.sqrt(np.pi * 2.) * sigma_true, rel=0.0001)
    assert normal_integral_infs == pytest.approx(1, rel=0.0001)
Beispiel #2
0
def test_from_root(weights):
    from skhep_testdata import data_path

    path_root = data_path("uproot-Zmumu.root")

    branches = ['pt1', 'pt2', "phi2"]
    f = uproot.open(path_root)
    tree = f['events']

    true_data = tree.pandas.df()

    data = zfit.data.Data.from_root(path=path_root,
                                    treepath='events',
                                    branches=branches,
                                    weights=weights)
    x = data.value()
    x_np = zfit.run(x)
    if weights is not None:
        weights_np = zfit.run(data.weights)
    else:
        weights_np = weights
    np.testing.assert_allclose(x_np, true_data[branches].as_matrix())
    if weights is not None:
        true_weights = weights if not isinstance(
            weights, str) else true_data[weights].as_matrix()
        if isinstance(true_weights, tf.Tensor):
            true_weights = zfit.run(true_weights)
        np.testing.assert_allclose(weights_np, true_weights)
    else:
        assert weights_np is None
Beispiel #3
0
def test_convert_to_parameter():
    import zfit

    conv_param1 = zfit.param.convert_to_parameter(10.)
    assert pytest.approx(zfit.run(conv_param1.value())) == 10
    assert not conv_param1.floating

    conv_param2 = zfit.param.convert_to_parameter(12., prefer_constant=False)
    assert pytest.approx(zfit.run(conv_param2.value())) == 12.
    assert conv_param2.floating
    assert not conv_param2.has_limits

    conv_param3 = zfit.param.convert_to_parameter(12., lower=5., prefer_constant=False)
    assert pytest.approx(zfit.run(conv_param3.lower)) == 5.
    assert conv_param3.has_limits

    with pytest.raises(ValueError):
        _ = zfit.param.convert_to_parameter(5., lower=15., prefer_constant=False)

    with pytest.raises(ValueError):
        _ = zfit.param.convert_to_parameter(5., upper=1., prefer_constant=False)

    truename4 = 'myname1'
    stepsize4 = 1.5
    conv_param4 = zfit.param.convert_to_parameter(12., name=truename4,
                                                  upper=14., prefer_constant=False, step_size=stepsize4)
    assert conv_param4.floating
    assert conv_param4.name == truename4
    assert conv_param4.has_limits
    assert conv_param4.floating
    assert pytest.approx(zfit.run(conv_param4.step_size)) == stepsize4
Beispiel #4
0
def test_set_values():
    upper1 = 5.33
    lower1 = 0.
    param1 = zfit.Parameter('param1', 2., lower1, upper1)
    param1.set_value(lower1)
    assert pytest.approx(zfit.run(param1.value()), lower1)
    param1.set_value(upper1)
    assert pytest.approx(zfit.run(param1.value()), upper1)
    with pytest.raises(ValueError):
        param1.set_value(lower1 - 0.001)
    with pytest.raises(ValueError):
        param1.set_value(upper1 + 0.001)

    fitresult = create_fitresult((zfit.minimize.Minuit, {}, True))
    result = fitresult['result']
    param_a = fitresult['a_param']
    param_b = fitresult['b_param']
    param_c = fitresult['c_param']

    val_a = fitresult['a']
    val_b = fitresult['b']
    val_c = fitresult['c']
    with pytest.raises(ValueError):
        param_b.set_value(999)
    param_c.assign(9999)
    zfit.param.set_values([param_c, param_b], values=result)

    assert param_a.value() == val_a
    assert param_b.value() == val_b
    assert param_c.value() == val_c

    param_d = zfit.Parameter("param_d", 12)
    with pytest.raises(ValueError):
        zfit.param.set_values([param_d], result)
Beispiel #5
0
def test_mc_partial_integration():
    values = ztf.convert_to_tensor(func4_values)
    data1 = zfit.data.Data.from_tensor(obs='obs2',
                                       tensor=tf.expand_dims(values, axis=-1))
    limits1 = Space(limits=limits4_2dim, obs=['obs1', 'obs3'])
    limits1._set_obs_axes({'obs1': 0, 'obs3': 2})
    num_integral = zintegrate.mc_integrate(x=data1,
                                           func=func4_3deps,
                                           limits=limits1)

    vals_tensor = ztf.convert_to_tensor(func4_2values)

    vals_reshaped = tf.transpose(vals_tensor)
    data2 = zfit.data.Data.from_tensor(obs=['obs1', 'obs3'],
                                       tensor=vals_reshaped)

    limits2 = Space(limits=limits4_1dim, obs=['obs2'])
    limits2._set_obs_axes({'obs2': 1})
    num_integral2 = zintegrate.mc_integrate(x=data2,
                                            func=func4_3deps,
                                            limits=limits2,
                                            draws_per_dim=100)

    integral = zfit.run(num_integral)
    integral2 = zfit.run(num_integral2)
    # print("DEBUG", value:", zfit.run(vals_reshaped))
    assert len(integral) == len(func4_values)
    assert len(integral2) == len(func4_2values[0])
    assert func4_3deps_0and2_integrated(
        x=func4_values, limits=limits4_2dim) == pytest.approx(integral,
                                                              rel=0.03)

    assert func4_3deps_1_integrated(
        x=func4_2values, limits=limits4_1dim) == pytest.approx(integral2,
                                                               rel=0.03)
Beispiel #6
0
def test_mc_integration(chunksize):
    # simpel example
    zfit.run.chunking.active = True
    zfit.run._chunksize = chunksize
    num_integral = zintegrate.mc_integrate(func=func1_5deps,
                                           limits=Space.from_axes(
                                               limits=limits_simple_5deps,
                                               axes=tuple(range(5))),
                                           n_axes=5)
    num_integral2 = zintegrate.mc_integrate(func=func2_1deps,
                                            limits=Space.from_axes(
                                                limits=limits2,
                                                axes=tuple(range(1))),
                                            n_axes=1)
    num_integral3 = zintegrate.mc_integrate(func=func3_2deps,
                                            limits=Space.from_axes(
                                                limits=limits3,
                                                axes=tuple(range(2))),
                                            n_axes=2)

    integral = zfit.run(num_integral)
    integral2 = zfit.run(num_integral2)
    integral3 = zfit.run(num_integral3)

    assert not hasattr(integral, "__len__")
    assert not hasattr(integral2, "__len__")
    assert not hasattr(integral3, "__len__")
    assert func1_5deps_fully_integrated(limits_simple_5deps) == pytest.approx(
        integral, rel=0.1)
    assert func2_1deps_fully_integrated(limits2) == pytest.approx(integral2,
                                                                  rel=0.03)
    assert func3_2deps_fully_integrated(
        Space.from_axes(limits=limits3,
                        axes=(0, 1))) == pytest.approx(integral3, rel=0.03)
Beispiel #7
0
def test_gaussian_constraint_orderbug2(
):  # as raised in #162, failed before fixing
    param1 = zfit.Parameter("param1", 1500)
    param5 = zfit.Parameter("param2", 0.5)

    param2 = zfit.Parameter("param3", 1.0)
    param3 = zfit.Parameter("param4", 1.0)
    param4 = zfit.Parameter("param5", 1.0)

    constraint = {
        "params": [param1, param2, param3, param4, param5],
        "mu": [1500, 1.0, 1.0, 1.0, 0.5],
        "sigma": [0.05 * 1500, 0.001, 0.01, 0.1, 0.05 * 0.5]
    }

    constr1 = zfit.constraint.GaussianConstraint(**constraint)
    # param_vals = [1500, 1.0, 1.0, 1.0, 0.5]
    constraint['params'] = zfit.run(constraint['params'])

    true_val = true_gauss_constr_value(**constraint)

    value_tensor = constr1.value()
    constr_np = zfit.run(value_tensor)
    assert constr_np == pytest.approx(true_val)
    assert true_val < 1000
    assert true_val == pytest.approx(
        -8.592,
        abs=0.1)  # if failing, change value. Hardcoded for additional layer
Beispiel #8
0
def test_func_func():
    param1 = Parameter('param1', 1.)
    param2 = Parameter('param2', 2.)
    param3 = Parameter('param3', 3., floating=False)
    param4 = Parameter('param4', 4.)

    def func1_pure(self, x):
        x = ztf.unstack_x(x)
        return param1 * x

    def func2_pure(self, x):
        x = ztf.unstack_x(x)
        return param2 * x + param3

    func1 = SimpleFunc(func=func1_pure, obs=obs1, p1=param1)
    func2 = SimpleFunc(func=func2_pure, obs=obs1, p2=param2, p3=param3)

    added_func = func1 + func2
    prod_func = func1 * func2

    added_values = added_func.func(rnd_test_values)
    true_added_values = func1_pure(None, rnd_test_values) + func2_pure(None, rnd_test_values)
    prod_values = prod_func.func(rnd_test_values)
    true_prod_values = func1_pure(None, rnd_test_values) * func2_pure(None, rnd_test_values)

    added_values = zfit.run(added_values)
    true_added_values = zfit.run(true_added_values)
    prod_values = zfit.run(prod_values)
    true_prod_values = zfit.run(true_prod_values)
    np.testing.assert_allclose(true_added_values, added_values)
    np.testing.assert_allclose(true_prod_values, prod_values)
Beispiel #9
0
def test_extract_extended_pdfs():
    gauss1 = zfit.pdf.Gauss(obs=obs1, mu=1.3, sigma=5.4)
    gauss2 = zfit.pdf.Gauss(obs=obs1, mu=1.3, sigma=5.4)
    gauss3 = zfit.pdf.Gauss(obs=obs1, mu=1.3, sigma=5.4)
    gauss4 = zfit.pdf.Gauss(obs=obs1, mu=1.3, sigma=5.4)
    gauss5 = zfit.pdf.Gauss(obs=obs1, mu=1.3, sigma=5.4)
    gauss6 = zfit.pdf.Gauss(obs=obs1, mu=1.3, sigma=5.4)

    yield1 = zfit.Parameter('yield123' + str(np.random.random()), 200.)

    # sum1 = 0.3 * gauss1 + gauss2
    gauss3_ext = 45. * gauss3
    gauss4_ext = 100. * gauss4
    sum2_ext_daughters = gauss3_ext + gauss4_ext
    sum3 = 0.4 * gauss5 + gauss6
    sum3_ext = sum3.create_extended(yield1)

    sum_all = zfit.pdf.SumPDF(pdfs=[sum2_ext_daughters, sum3_ext])
    sum_all.set_norm_range((-5, 5))

    extracted_pdfs = extract_extended_pdfs(pdfs=sum_all)
    assert frozenset(extracted_pdfs) == {gauss3_ext, gauss4_ext, sum3_ext}

    limits = zfit.Space(obs=obs1, limits=(-4, 5))
    limits = limits.with_autofill_axes()
    extended_sample = extended_sampling(pdfs=sum_all, limits=limits)
    extended_sample_np = zfit.run(extended_sample)
    assert np.shape(extended_sample_np)[0] == pytest.approx(
        expected=(45 + 100 + 200), rel=0.1)
    samples_from_pdf = sum_all.sample(n='extended', limits=limits)
    samples_from_pdf_np = zfit.run(samples_from_pdf)
    assert np.shape(samples_from_pdf_np)[0] == pytest.approx(
        expected=(45 + 100 + 200), rel=0.1)
Beispiel #10
0
def create_fitresult(minimizer_class_and_kwargs):
    loss, (a_param, b_param, c_param) = create_loss()

    true_minimum = zfit.run(loss.value())

    parameter_tolerance = 0.25  # percent
    max_distance_to_min = 10.

    for param in [a_param, b_param, c_param]:
        zfit.run(param.initializer)  # reset the value

    minimizer_class, minimizer_kwargs, test_error = minimizer_class_and_kwargs
    minimizer = minimizer_class(**minimizer_kwargs)

    result = minimizer.minimize(loss=loss)
    cur_val = zfit.run(loss.value())
    aval, bval, cval = zfit.run([v for v in (a_param, b_param, c_param)])

    ret = {
        'result': result,
        'true_min': true_minimum,
        'cur_val': cur_val,
        'a': aval,
        'b': bval,
        'c': cval,
        'a_param': a_param,
        'b_param': b_param,
        'c_param': c_param
    }

    return ret
Beispiel #11
0
def test_pdf_simple_subclass():
    class SimpleGauss(zfit.pdf.ZPDF):
        _PARAMS = ['mu', 'sigma']

        def _unnormalized_pdf(self, x):
            mu = self.params['mu']
            sigma = self.params['sigma']
            x = ztf.unstack_x(x)
            return ztf.exp(-ztf.square((x - mu) / sigma))

    gauss1 = SimpleGauss(obs='obs1', mu=3, sigma=5)

    prob = gauss1.pdf(np.random.random(size=(10, 1)), norm_range=(-4, 5))
    zfit.run(prob)

    with pytest.raises(ValueError):
        gauss2 = SimpleGauss('obs1', 1., sigma=5.)
    with pytest.raises(SubclassingError):

        class SimpleGauss2(zfit.pdf.ZPDF):
            def _unnormalized_pdf(self, x):
                mu = self.params['mu']
                sigma = self.params['sigma']
                x = ztf.unstack_x(x)
                return ztf.exp(-ztf.square((x - mu) / sigma))
Beispiel #12
0
def test_func_simple_subclass():
    class SimpleGaussFunc(zfit.func.ZFunc):
        _PARAMS = ['mu', 'sigma']

        def _func(self, x):
            mu = self.params['mu']
            sigma = self.params['sigma']
            x = ztf.unstack_x(x)
            return ztf.exp(-ztf.square((x - mu) / sigma))

    gauss1 = SimpleGaussFunc(obs='obs1', mu=3, sigma=5)

    value = gauss1.func(np.random.random(size=(10, 1)))
    zfit.run(value)

    with pytest.raises(ValueError):
        gauss2 = SimpleGaussFunc('obs1', 1., sigma=5.)
    with pytest.raises(SubclassingError):

        class SimpleGauss2(zfit.func.ZFunc):
            def _func(self, x):
                mu = self.params['mu']
                sigma = self.params['sigma']
                x = ztf.unstack_x(x)
                return ztf.exp(-ztf.square((x - mu) / sigma))
Beispiel #13
0
def test_counts_multinomial():
    probs = [0.1, 0.3, 0.6]
    total_count = 1000.
    total_count_var = tf.Variable(total_count, trainable=False)
    zfit.run(total_count_var.initializer)
    counts = ztf.random.counts_multinomial(total_count=total_count_var, probs=probs)

    counts_np = [zfit.run(counts) for _ in range(20)]
    mean = np.mean(counts_np, axis=0)
    std = np.std(counts_np, axis=0)

    assert (3,) == counts_np[0].shape
    assert all(total_count == np.sum(counts_np, axis=1))
    probs_scaled = np.array(probs) * total_count
    assert probs_scaled == pytest.approx(mean, rel=0.05)
    assert [9, 14, 16] == pytest.approx(std, rel=0.5)  # flaky

    total_count2 = 5000
    total_count_var.load(total_count2, session=zfit.run.sess)
    counts_np2 = [zfit.run(counts) for _ in range(3)]
    mean2 = np.mean(counts_np2, axis=0)

    assert all(total_count2 == np.sum(counts_np2, axis=1))
    probs_scaled2 = np.array(probs) * total_count2
    assert pytest.approx(mean2, rel=0.15) == probs_scaled2

    total_count3 = 3000.
    counts3 = ztf.random.counts_multinomial(total_count=total_count3,
                                            logits=probs * 30)  # sigmoid: inverse of logits (softmax)

    counts_np3 = [zfit.run(counts3) for _ in range(5)]

    assert all(total_count3 == np.sum(counts_np3, axis=1))
Beispiel #14
0
def test_composed_param():
    param1 = Parameter('param1', 1.)
    param2 = Parameter('param2', 2.)
    param3 = Parameter('param3', 3., floating=False)
    param4 = Parameter(
        'param4',
        4.)  # needed to make sure it does not only take all params as deps
    a = ztf.log(3. * param1) * tf.square(param2) - param3
    param_a = ComposedParameter('param_as', tensor=a)
    assert isinstance(param_a.get_dependents(only_floating=True), OrderedSet)
    assert param_a.get_dependents(only_floating=True) == {param1, param2}
    assert param_a.get_dependents(only_floating=False) == {
        param1, param2, param3
    }
    a_unchanged = zfit.run(a)
    assert a_unchanged == zfit.run(param_a)
    assert zfit.run(param2.assign(3.5))
    a_changed = zfit.run(a)
    assert a_changed == zfit.run(param_a)
    assert a_changed != a_unchanged

    with pytest.raises(LogicalUndefinedOperationError):
        param_a.assign(value=5.)
    with pytest.raises(LogicalUndefinedOperationError):
        param_a.load(value=5., session=zfit.run.sess)
Beispiel #15
0
def test_extended_gauss():
    mu1 = Parameter("mu11", 1.0)
    mu2 = Parameter("mu21", 12.0)
    mu3 = Parameter("mu31", 3.0)
    sigma1 = Parameter("sigma11", 1.0)
    sigma2 = Parameter("sigma21", 12.0)
    sigma3 = Parameter("sigma31", 33.0)
    yield1 = Parameter("yield11", 150.0)
    yield2 = Parameter("yield21", 550.0)
    yield3 = Parameter("yield31", 2500.0)

    gauss1 = Gauss(mu=mu1, sigma=sigma1, obs=obs1, name="gauss11")
    gauss2 = Gauss(mu=mu2, sigma=sigma2, obs=obs1, name="gauss21")
    gauss3 = Gauss(mu=mu3, sigma=sigma3, obs=obs1, name="gauss31")
    gauss1 = gauss1.create_extended(yield1)
    gauss2 = gauss2.create_extended(yield2)
    gauss3 = gauss3.create_extended(yield3)

    gauss_dists = [gauss1, gauss2, gauss3]

    sum_gauss = SumPDF(pdfs=gauss_dists)
    integral_true = (sum_gauss.integrate((-1, 5), ) * sum_gauss.get_yield())

    assert zfit.run(integral_true) == pytest.approx(
        zfit.run(sum_gauss.ext_integrate((-1, 5), )))
    normalization_testing(pdf=sum_gauss, limits=obs1)
Beispiel #16
0
def test_convert_to_parameters_equivalence_to_single():
    import zfit

    conv_param1 = zfit.param.convert_to_parameters(10.0)[0]
    assert pytest.approx(zfit.run(conv_param1.value())) == 10
    assert not conv_param1.floating

    conv_param2 = zfit.param.convert_to_parameters(12.0,
                                                   prefer_constant=False)[0]
    assert pytest.approx(zfit.run(conv_param2.value())) == 12.0
    assert conv_param2.floating
    assert not conv_param2.has_limits

    conv_param3 = zfit.param.convert_to_parameters(12.0,
                                                   lower=5.0,
                                                   prefer_constant=False)[0]
    assert pytest.approx(zfit.run(conv_param3.lower)) == 5.0
    assert conv_param3.has_limits

    truename4 = "myname1"
    stepsize4 = 1.5
    conv_param4 = zfit.param.convert_to_parameters(12.0,
                                                   name=truename4,
                                                   upper=14.0,
                                                   prefer_constant=False,
                                                   step_size=stepsize4)[0]
    assert conv_param4.floating
    assert conv_param4.name == truename4
    assert conv_param4.has_limits
    assert conv_param4.floating
    assert pytest.approx(zfit.run(conv_param4.step_size)) == stepsize4
Beispiel #17
0
def test_convert_to_parameters_equivalence_to_single_multi():
    import zfit

    conv_param1 = zfit.param.convert_to_parameters([23, 10.0, 34, 23])[1]
    assert pytest.approx(zfit.run(conv_param1.value())) == 10
    assert not conv_param1.floating

    conv_param2 = zfit.param.convert_to_parameters([23, 10.0, 34, 12, 23],
                                                   prefer_constant=False)[-2]
    assert pytest.approx(zfit.run(conv_param2.value())) == 12.0
    assert conv_param2.floating
    assert not conv_param2.has_limits

    conv_param3 = zfit.param.convert_to_parameters([23, 10.0, 12, 34, 23],
                                                   lower=list(range(5)),
                                                   prefer_constant=False)[2]
    assert pytest.approx(zfit.run(conv_param3.lower)) == 2
    assert conv_param3.has_limits

    truename4 = ["oe", "myname1", "ue", "eu", "eue"]
    stepsize4 = [23, 1.5, 10.0, 34, 23]
    conv_param4 = zfit.param.convert_to_parameters(
        [23, 12, 121, 34, 23],
        name=truename4,
        upper=[213, 14.0, 1110.0, 314, 213],
        prefer_constant=False,
        step_size=stepsize4,
    )[1]
    assert conv_param4.floating
    assert conv_param4.name == "myname1"
    assert conv_param4.has_limits
    assert conv_param4.floating
    assert pytest.approx(zfit.run(conv_param4.step_size)) == 1.5
Beispiel #18
0
def test_cb_integral():
    obs = zfit.Space("x", limits=bounds)

    mu_ = zfit.Parameter("mu_cb5", mu)
    sigma_ = zfit.Parameter("sigma_cb5", sigma)
    alphal_ = zfit.Parameter("alphal_cb5", alphal)
    nl_ = zfit.Parameter("nl_cb5", nl)

    cbl = CrystalBall(obs=obs, mu=mu_, sigma=sigma_, alpha=alphal_, n=nl_)
    int_limits = (-1, 3)
    integral_numeric = cbl.numeric_integrate(limits=int_limits, norm=False)

    integral = cbl.analytic_integrate(limits=int_limits, norm=False)
    integral_numeric = zfit.run(integral_numeric)
    integral = zfit.run(integral)

    assert pytest.approx(integral_numeric, integral, 1e-5)

    rnd_limits = sorted(np.random.uniform(*bounds, 13))
    integrals = []
    for low, up in zip(rnd_limits[:-1], rnd_limits[1:]):
        integrals.append(cbl.integrate((low, up), norm=False))

    integral = np.sum(integrals)
    integral_full = zfit.run(cbl.integrate(bounds, norm=False))
    assert pytest.approx(integral_full, integral)
Beispiel #19
0
def test_integrate():
    class SimpleSampleSumPDF(zfit.pdf.SumPDF):
        @zfit.supports()
        def _integrate(self, limits, norm, options):
            raise SpecificFunctionNotImplemented  # fallback to the default sampling

        @zfit.supports()
        def _analytic_integrate(self, limits, norm):
            raise SpecificFunctionNotImplemented

        @zfit.supports()
        def _numeric_integrate(self, limits, norm=None, options=None):
            raise SpecificFunctionNotImplemented

    mu1, mu2 = 0, 1.7
    frac = 0.7

    lower = mu1 - 0.5
    upper = mu2 + 1
    obs = zfit.Space("obs1", (lower, upper))
    limits = zfit.Space("obs1", (mu1 - 0.3, mu2 + 0.1))
    gauss1 = zfit.pdf.Gauss(obs=obs, mu=mu1, sigma=0.93)
    gauss2 = zfit.pdf.Gauss(obs=obs, mu=mu2, sigma=1.2)

    sumpdf = zfit.pdf.SumPDF([gauss1, gauss2], frac)
    sumpdf_true = SimpleSampleSumPDF([gauss1, gauss2], frac)
    assert zfit.run(gauss1.integrate(
        limits,
        norm=limits,
    )) == pytest.approx(1, abs=0.01)
    integral = sumpdf.integrate(
        limits=limits,
        norm=False,
    ).numpy()
    integral_true = sumpdf_true.integrate(
        limits=limits,
        norm=False,
    ).numpy()
    integral_manual_true = gauss1.integrate(
        limits, ) * frac + gauss2.integrate(limits, ) * (1 - frac)

    assert integral_true == pytest.approx(integral_manual_true.numpy(),
                                          rel=0.03)
    assert integral_true == pytest.approx(integral, rel=0.03)
    assert integral_true < 0.85

    analytic_integral = sumpdf.analytic_integrate(limits=limits,
                                                  norm=False).numpy()

    assert integral_true == pytest.approx(analytic_integral, rel=0.03)

    rnd_limits = sorted(np.random.uniform(lower, upper, 10))
    integrals = []
    for low, up in zip(rnd_limits[:-1], rnd_limits[1:]):
        integrals.append(sumpdf.integrate((low, up), norm=False))

    integral = np.sum(integrals)
    integral_full = zfit.run(sumpdf.integrate((lower, upper), norm=False))
    assert pytest.approx(integral_full, integral)
Beispiel #20
0
def test_overloaded_operators():
    data1 = create_data1()
    a = data1 * 5.
    np.testing.assert_array_equal(5 * example_data1, zfit.run(a))
    np.testing.assert_array_equal(example_data1, zfit.run(data1))
    data_squared = data1 * data1
    np.testing.assert_allclose(example_data1 ** 2, zfit.run(data_squared), rtol=1e-8)
    np.testing.assert_allclose(np.log(example_data1), zfit.run(tf.math.log(data1)), rtol=1e-8)
Beispiel #21
0
def test_overloaded_operators():
    param_a = ComposedParameter('param_ao', 5 * 4)
    param_b = ComposedParameter('param_bo', 3)
    param_c = param_a * param_b
    assert not isinstance(param_c, zfit.Parameter)
    param_d = ComposedParameter("param_do", param_a + param_a * param_b ** 2)
    param_d_val = zfit.run(param_d)
    assert param_d_val == zfit.run(param_a + param_a * param_b ** 2)
Beispiel #22
0
def test_midpoints():
    edges = np.array([[-1.0, 0, 3, 10], [-5.0, 0, 1, 4]])
    bincounts = np.array([[0, 0, 1], [0, 5, 7], [0, 3, 0], [0, 0, 0]])

    edges = z.convert_to_tensor(edges)
    midpoints_true = np.array([[-0.5, 2.5], [1.5, 0.5], [1.5, 2.5], [6.5, 0.5]])
    bincounts_nonzero, midpoints_nonzero, bincounts_nonzero_index = midpoints_from_hist(
        bincounts=bincounts, edges=edges
    )
    np.testing.assert_allclose(np.array([1, 5, 7, 3]), zfit.run(bincounts_nonzero))
    np.testing.assert_allclose(midpoints_true, zfit.run(midpoints_nonzero))
Beispiel #23
0
def test_param_limits():
    lower, upper = -4., 3.
    param1 = Parameter('param1lim', 1., lower_limit=lower, upper_limit=upper)
    param2 = Parameter('param2lim', 2.)

    param1.load(upper + 0.5)
    assert upper == zfit.run(param1.value())
    param1.load(lower - 1.1)
    assert lower == zfit.run(param1.value())
    param2.lower_limit = lower
    param2.load(lower - 1.1)
    assert lower == zfit.run(param2.value())
Beispiel #24
0
def test_to_numpy():
    import zfit

    param = zfit.Parameter(f"param", 42)
    assert zfit.run(param) == 42

    p1 = zfit.param.ConstantParameter("aoeu1", 15)
    assert zfit.run(p1) == 15

    p2 = zfit.param.ComposedParameter("aoeu2", lambda params: 2 * params["p1"],
                                      {"p1": p1})
    assert zfit.run(p2) == 30
Beispiel #25
0
def test_polynomials(poly_cfg, coeffs):
    coeffs = copy.copy(coeffs)
    poly_pdf, n_sampling = poly_cfg
    polynomial = poly_pdf(obs=obs1, coeffs=coeffs)
    polynomial2 = poly_pdf(obs=obs1, coeffs=coeffs)

    polynomial_coeff0 = poly_pdf(obs=obs1, coeffs=coeffs, coeff0=1.)
    lower, upper = obs1.limit1d
    x = np.random.uniform(size=(1000, ), low=lower, high=upper)
    y_poly = polynomial.pdf(x)
    y_poly_u = polynomial.unnormalized_pdf(x)
    y_poly2 = polynomial2.pdf(x)
    y_poly2_u = polynomial2.unnormalized_pdf(x)
    y_poly_coeff0 = polynomial_coeff0.pdf(x)
    y_poly_coeff0_u = polynomial_coeff0.unnormalized_pdf(x)
    y_poly_np, y_poly2_np, y_poly_coeff0_np = zfit.run(
        [y_poly, y_poly2, y_poly_coeff0])
    y_polyu_np, y_poly2u_np, y_polyu_coeff0_np = zfit.run(
        [y_poly_u, y_poly2_u, y_poly_coeff0_u])
    np.testing.assert_allclose(y_polyu_np, y_poly2u_np)
    np.testing.assert_allclose(y_polyu_np, y_polyu_coeff0_np)
    np.testing.assert_allclose(y_poly_np, y_poly2_np)
    np.testing.assert_allclose(y_poly_np, y_poly_coeff0_np)

    # test 1 to 1 range
    integral = polynomial.analytic_integrate(limits=obs1, norm_range=False)
    numerical_integral = polynomial.numeric_integrate(limits=obs1,
                                                      norm_range=False)
    analytic_integral = zfit.run(integral)
    assert pytest.approx(analytic_integral,
                         rel=rel_integral) == zfit.run(numerical_integral)

    # test with different range scaling
    polynomial = poly_pdf(obs=obs1_random, coeffs=coeffs)

    # test with limits != space
    integral = polynomial.analytic_integrate(limits=obs1, norm_range=False)
    numerical_integral = polynomial.numeric_integrate(limits=obs1,
                                                      norm_range=False)
    analytic_integral = zfit.run(integral)
    assert pytest.approx(analytic_integral,
                         rel=rel_integral) == zfit.run(numerical_integral)

    # test with limits == space
    integral = polynomial.analytic_integrate(limits=obs1_random,
                                             norm_range=False)
    numerical_integral = polynomial.numeric_integrate(limits=obs1_random,
                                                      norm_range=False)
    analytic_integral = zfit.run(integral)
    assert pytest.approx(analytic_integral,
                         rel=rel_integral) == zfit.run(numerical_integral)

    lower, upper = obs1_random.limit1d
    test_integral = np.average(zfit.run(polynomial.unnormalized_pdf(tf.random.uniform((n_sampling,), lower, upper)))) \
                    * obs1_random.area()
    assert pytest.approx(analytic_integral,
                         rel=rel_integral * 3) == test_integral
Beispiel #26
0
def test_gauss1():
    probs1 = gauss1.pdf(x=test_values, norm_range=norm_range1)
    probs1_tfp = normal1.pdf(x=test_values, norm_range=norm_range1)
    probs1 = zfit.run(probs1)
    probs1_tfp = zfit.run(probs1_tfp)
    np.testing.assert_allclose(probs1, probs1_tfp, rtol=1e-2)

    probs1_unnorm = gauss1.pdf(x=test_values, norm_range=False)
    probs1_tfp_unnorm = normal1.pdf(x=test_values, norm_range=False)
    probs1_unnorm = zfit.run(probs1_unnorm)
    probs1_tfp_unnorm = zfit.run(probs1_tfp_unnorm)
    assert not np.allclose(probs1_tfp, probs1_tfp_unnorm, rtol=1e-2)
    assert not np.allclose(probs1, probs1_unnorm, rtol=1e-2)
Beispiel #27
0
def test_equality(space1, space2):
    """
    Args:
        space1:
        space2:
    """
    assert space1.axes == space2.axes
    assert space1.obs == space2.obs
    np.testing.assert_allclose(space1.rect_limits, space2.rect_limits)
    # TODO: reactivate below
    assert zfit.run(space1.rect_area()) == pytest.approx(
        zfit.run(space2.rect_area()), rel=1e-8
    )
Beispiel #28
0
def test_exp():
    lambda_true = 3.1
    lambda_ = zfit.Parameter('lambda1', lambda_true)
    exp1 = zfit.pdf.Exponential(lambda_=lambda_, obs='obs1')
    sample = exp1.sample(n=1000, limits=(-10, 10))
    sample_np = zfit.run(sample)
    assert not any(np.isnan(sample_np))
    probs1 = exp1.pdf(x=np.random.normal(size=842), norm_range=(-5, 5))
    probs2 = exp1.pdf(x=np.linspace(5300, 5700, num=1100),
                      norm_range=(5250, 5750))
    probs1_np, probs2_np = zfit.run([probs1, probs2])
    assert not any(np.isnan(probs1_np))
    assert not any(np.isnan(probs2_np))
    normalization_testing(exp1, 1)
Beispiel #29
0
def test_get_dependents():
    var1 = zfit.Parameter('var1', 1.)
    var2 = zfit.Parameter('var2', 2.)
    var3 = zfit.Parameter('var3', 3.)
    a = zfit.pdf.Gauss(var1, var2, obs='obs1').sample(n=500,
                                                      limits=(-5, 5)) * 5.
    b = ztf.constant(3.) + 4 * var1
    c = 5. * b * var3
    d = b * var2 + a
    e = d * 3.
    zfit.run(e)
    assert get_dependents(
        e, [a, b, c, d, var1, var2, var3]) == [a, b, d, var1, var2]
    assert get_dependents(e, [var1, var2, var3]) == [var1, var2]
    assert get_dependents(c, [a, b, d, var1, var2, var3]) == [b, var1, var3]
Beispiel #30
0
def test_prod_gauss_nd():
    # return
    test_values = np.random.random(size=(10, 3))
    lower = ((-5, -5, -5), )
    upper = ((4, 4, 4), )
    obs1 = ['a', 'b', 'c']
    norm_range_3d = Space(obs=obs1, limits=(lower, upper))
    test_values_data = Data.from_tensor(obs=obs1, tensor=test_values)
    probs = prod_gauss_3d.pdf(x=test_values_data, norm_range=norm_range_3d)
    true_probs = np.prod([
        gauss.pdf(test_values[:, i], norm_range=(-5, 4))
        for i, gauss in enumerate(gauss_dists)
    ])
    probs_np = zfit.run(probs)
    np.testing.assert_allclose(zfit.run(true_probs), probs_np, rtol=1e-2)