How to use the zfit.core.space.Space function in zfit

To help you get started, we’ve selected a few zfit examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github zfit / zfit / tests / test_integrate.py View on Github external
limits=Space(limits=limits3,
                                                         axes=(0, 1)),
                                            n_axes=2)

    integral = num_integral.numpy()
    integral2 = num_integral2.numpy()
    integral3 = num_integral3.numpy()

    assert integral.shape == (1,)
    assert integral2.shape == (1,)
    assert integral3.shape == (1,)
    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(limits=limits3, axes=(0, 1))).numpy() == pytest.approx(integral3, rel=0.03)
github zfit / zfit / tests / test_pdfs.py View on Github external
def normalization_testing(pdf, limits=None):
    limits = (low, high) if limits is None else limits
    space = Space(obs=obs1, limits=limits)
    with pdf.set_norm_range(space):
        samples = tf.cast(np.random.uniform(low=space.lower, high=space.upper, size=(40000, pdf.n_obs)),
                          dtype=tf.float64)
        samples = zfit.Data.from_tensor(obs=space, tensor=samples)
        probs = pdf.pdf(samples)
        result = probs.numpy()
        result = zfit.run(np.average(result) * space.rect_area())
        assert pytest.approx(result, rel=0.03) == 1
github zfit / zfit / tests / test_space_0.py View on Github external
upper11 = 3
upper12 = 7
limit11 = lower11, upper11
limit12 = lower12, upper12
limit11_true = copy.deepcopy(limit11)
limit12_true = copy.deepcopy(limit12)
limit11_area = 2
limit12_area = 3
limit11_axes = (1,)
limit12_axes = (1,)
limit11_obs = ("obs1",)
limit12_obs = ("obs1",)
limit11_axes_true = limit11_axes
limit12_axes_true = limit12_axes
space11 = Space(limits=limit11, axes=limit11_axes)
space12 = Space(limits=limit12, axes=limit12_axes)
space1 = space11 + space12
space11_obs = Space(obs=limit11_obs, limits=limit11)
space12_obs = Space(obs=limit12_obs, limits=limit12)
space1_obs = space11_obs + space12_obs
# arguments1 = (space1, lower1, upper1, limit1_true, limit1_axes, limit1_areas, 2)
arguments1 = []

lower2 = (1, 2, 3)
upper2 = (2, 4, 6)
sub_lower2 = (1, 3)
sub_upper2 = (2, 6)
limit2 = lower2, upper2
sub_limit2 = sub_lower2, sub_upper2
limit2_areas = (6, 18)
sub_limit2_areas = (3, 1.8)
limit2_axes = (1, 5, 6)
github zfit / zfit / zfit / models / polynomials.py View on Github external
# The laguerre shape makes the sum for us. setting the 0th coeff to 0, since no -1 term exists.
    coeffs_laguerre_nup = {f'c_{int(n.split("_", 1)[-1]) + 1}': c
                           for i, (n, c) in enumerate(params.items())}  # increase n -> n+1 of naming
    coeffs_laguerre_nup['c_0'] = tf.constant(0., dtype=model.dtype)
    coeffs_laguerre_nup = convert_coeffs_dict_to_list(coeffs_laguerre_nup)

    def indefinite_integral(limits):
        return -1 * laguerre_shape_alpha_minusone(x=limits, coeffs=coeffs_laguerre_nup)

    integral = indefinite_integral(upper) - indefinite_integral(lower)
    integral = tf.reshape(integral, shape=())
    integral *= 0.5 * model.space.area()  # rescale back to whole width
    return integral


laguerre_limits_integral = Space(axes=0, limits=(Space.ANY_LOWER, Space.ANY_UPPER))
Laguerre.register_analytic_integral(func=func_integral_laguerre, limits=laguerre_limits_integral)

hermite_polys = [lambda x: tf.ones_like(x), lambda x: 2 * x]


@z.function(wraps='zfit_tensor')
def hermite_recurrence(p1, p2, n, x):
    """Recurrence relation for Hermite polynomials (physics).

    :math:`H_{n+1}(x) = 2x H_{n}(x) - 2n H_{n-1}(x)`

    """
    return 2 * (tf.multiply(x, p1) - n * p2)


def hermite_shape(x, coeffs):
github zfit / zfit / zfit / models / polynomials.py View on Github external
Args:
            obs: The default space the PDF is defined in.
            coeffs (list[params]): A list of the coefficients for the polynomials of order 1+ in the sum.
            apply_scaling (bool): Rescale the data so that the actual limits represent (-1, 1).
            coeff0 (param): The scaling factor of the 0th order polynomial. If not given, it is set to 1.
            name (str): Name of the polynomial
        """
        super().__init__(obs=obs, name=name,
                         coeffs=coeffs, apply_scaling=apply_scaling, coeff0=coeff0)

    def _poly_func(self, x):
        coeffs = convert_coeffs_dict_to_list(self.params)
        return legendre_shape(x=x, coeffs=coeffs)


legendre_limits = Space(axes=0, limits=(Space.ANY_LOWER, Space.ANY_UPPER))
Legendre.register_analytic_integral(func=legendre_integral, limits=legendre_limits)

chebyshev_polys = [lambda x: tf.ones_like(x), lambda x: x]


@z.function(wraps='zfit_tensor')
def chebyshev_recurrence(p1, p2, _, x):
    """Recurrence relation for Chebyshev polynomials.

    T_{n+1}(x) = 2 x T_{n}(x) - T_{n-1}(x)

    """
    return 2 * tf.multiply(x, p1) - p2


def chebyshev_shape(x, coeffs):
github zfit / zfit / zfit / core / space.py View on Github external
#             for i in range(int(n_limits / len(limit))):
    #                 new_limits_comb[i].append(lim)
    #
    #     new_limits = tuple(tuple(limit) for limit in new_limits_comb)
    #     return new_limits

    # new_lower = check_extract_limits(all_lower)
    # new_upper = check_extract_limits(all_upper)
    # assert not (new_lower is None) ^ (new_upper is None), "Bug, please report issue. either both are defined or None."
    # if new_lower is None:
    #     limits = None
    # elif new_lower is False:
    #     return False
    # else:
    #     limits = (new_lower, new_upper)
    new_space = Space(obs=common_obs_ordered if using_obs else None, axes=None if using_obs else common_axes_ordered,
                      limits=limits)
    # if new_space.n_limits > 1:
    #     new_space = MultiSpace(Space, obs=all_obs)
    return new_space
github zfit / zfit / zfit / models / basefunctor.py View on Github external
"""
    spaces = convert_to_container(spaces)
    # combine spaces and limits
    try:
        models_space = combine_spaces(*spaces)
    except LimitsIncompatibleError:  # then only add obs
        extracted_obs = _extract_common_obs(obs=tuple(space.obs for space in spaces))
        models_space = Space(obs=extracted_obs)

    if obs is None:
        obs = models_space
    else:
        if isinstance(obs, Space):
            obs = obs
        else:
            obs = Space(obs=obs)
        # if not frozenset(obs.obs) == frozenset(models_space.obs):  # not needed, example projection
        #     raise SpaceIncompatibleError("The given obs do not coincide with the obs from the daughter models.")
        if not obs.obs == models_space.obs and not obs.limits_are_set:
            obs = models_space.with_obs(obs.obs)

    return obs
github zfit / zfit / zfit / models / basefunctor.py View on Github external
are pure strings), the inferred limits are used, sorted by obs. Otherwise, obs is directly used.

    Args:
        obs:
        spaces:

    Returns:

    """
    spaces = convert_to_container(spaces)
    # combine spaces and limits
    try:
        models_space = combine_spaces(*spaces)
    except LimitsIncompatibleError:  # then only add obs
        extracted_obs = _extract_common_obs(obs=tuple(space.obs for space in spaces))
        models_space = Space(obs=extracted_obs)

    if obs is None:
        obs = models_space
    else:
        if isinstance(obs, Space):
            obs = obs
        else:
            obs = Space(obs=obs)
        # if not frozenset(obs.obs) == frozenset(models_space.obs):  # not needed, example projection
        #     raise SpaceIncompatibleError("The given obs do not coincide with the obs from the daughter models.")
        if not obs.obs == models_space.obs and not obs.limits_are_set:
            obs = models_space.with_obs(obs.obs)

    return obs