Coverage for tests/spaces/test_hypercube_graph.py: 100%
32 statements
« prev ^ index » next coverage.py v7.11.3, created at 2025-11-16 21:43 +0000
« prev ^ index » next coverage.py v7.11.3, created at 2025-11-16 21:43 +0000
1import lab as B
2import numpy as np
3import pytest
4from plum import Tuple
6from geometric_kernels.kernels import MaternGeometricKernel
7from geometric_kernels.spaces import HypercubeGraph
8from geometric_kernels.utils.kernel_formulas import hypercube_graph_heat_kernel
10from ..helper import check_function_with_backend
13@pytest.fixture(params=[1, 2, 3, 5, 10])
14def inputs(request) -> Tuple[B.Numeric]:
15 """
16 Returns a tuple (space, eigenfunctions, X, X2) where:
17 - space is a HypercubeGraph object with dimension equal to request.param,
18 - eigenfunctions is the respective Eigenfunctions object with at most 5 levels,
19 - X is a random sample of random size from the space,
20 - X2 is another random sample of random size from the space,
21 - weights is an array of positive numbers of shape (eigenfunctions.num_levels, 1).
22 """
23 d = request.param
24 space = HypercubeGraph(d)
25 eigenfunctions = space.get_eigenfunctions(min(space.dim + 1, 5))
27 key = np.random.RandomState(0)
28 N, N2 = key.randint(low=1, high=min(2**d, 10) + 1, size=2)
29 key, X = space.random(key, N)
30 key, X2 = space.random(key, N2)
32 # These weights are used for testing the weighted outerproduct, they
33 # should be positive.
34 weights = np.random.rand(eigenfunctions.num_levels, 1) ** 2 + 1e-5
36 return space, eigenfunctions, X, X2, weights
39def test_numbers_of_eigenfunctions(inputs):
40 space, eigenfunctions, _, _, _ = inputs
41 num_levels = eigenfunctions.num_levels
43 # If the number of levels is maximal, check that the number of
44 # eigenfunctions is equal to the number of binary vectors of size `space.dim`.
45 if num_levels == space.dim + 1:
46 assert eigenfunctions.num_eigenfunctions == 2**space.dim
49@pytest.mark.parametrize("lengthscale", [1.0, 5.0, 10.0])
50@pytest.mark.parametrize("backend", ["numpy", "tensorflow", "torch", "jax"])
51def test_against_analytic_heat_kernel(inputs, lengthscale, backend):
52 space, _, X, X2, _ = inputs
53 lengthscale = np.array([lengthscale])
54 result = hypercube_graph_heat_kernel(lengthscale, X, X2)
56 kernel = MaternGeometricKernel(space)
58 # Check that MaternGeometricKernel on HypercubeGraph with nu=infinity
59 # coincides with the closed form expression for the heat kernel on the
60 # hypercube graph.
61 check_function_with_backend(
62 backend,
63 result,
64 kernel.K,
65 {"nu": np.array([np.inf]), "lengthscale": lengthscale},
66 X,
67 X2,
68 atol=1e-2,
69 )