|
| 1 | +import numpy as np |
| 2 | +import dpctl |
| 3 | + |
| 4 | +from kde_setuptools import cython_kde_eval as kde_eval |
| 5 | + |
| 6 | +import pytest |
| 7 | + |
| 8 | +def ref_kde(x, data, h): |
| 9 | + """ |
| 10 | + Reference NumPy implementation for KDE evaluation |
| 11 | + """ |
| 12 | + assert x.ndim == 2 and data.ndim == 2 |
| 13 | + assert x.shape[1] == data.shape[1] |
| 14 | + dim = x.shape[1] |
| 15 | + n_data = data.shape[0] |
| 16 | + return np.exp( |
| 17 | + np.square(x[:, np.newaxis, :]-data).sum(axis=-1)/(-2*h*h) |
| 18 | + ).sum(axis=1)/(np.sqrt(2*np.pi)*h)**dim / n_data |
| 19 | + |
| 20 | + |
| 21 | +def test_1d(): |
| 22 | + try: |
| 23 | + q = dpctl.SyclQueue() |
| 24 | + except dpctl.SyclQueueCreationError: |
| 25 | + pytest.skip("Execution queue could not be created, skipping...") |
| 26 | + |
| 27 | + x = np.linspace(0.1, 0.9, num=15).reshape((-1, 1)) |
| 28 | + data = np.random.rand(128,1) |
| 29 | + |
| 30 | + f_cy = kde_eval(q, x, data, 0.1) |
| 31 | + f_ref = ref_kde(x, data, 0.1) |
| 32 | + |
| 33 | + assert np.allclose(f_cy, f_ref) |
| 34 | + |
| 35 | + |
| 36 | +def test_2d(): |
| 37 | + try: |
| 38 | + q = dpctl.SyclQueue() |
| 39 | + except dpctl.SyclQueueCreationError: |
| 40 | + pytest.skip("Execution queue could not be created, skipping...") |
| 41 | + |
| 42 | + x = np.dstack( |
| 43 | + np.meshgrid( |
| 44 | + np.linspace(0.1, 0.9, num=7), |
| 45 | + np.linspace(0.1, 0.9, num=7) |
| 46 | + ) |
| 47 | + ).reshape(-1, 2) |
| 48 | + |
| 49 | + data = np.random.rand(128*128, 2) |
| 50 | + |
| 51 | + f_cy = kde_eval(q, x, data, 0.05) |
| 52 | + f_ref = ref_kde(x, data, 0.05) |
| 53 | + |
| 54 | + assert np.allclose(f_cy, f_ref) |
| 55 | + |
| 56 | + |
| 57 | +def test_3d(): |
| 58 | + try: |
| 59 | + q = dpctl.SyclQueue() |
| 60 | + except dpctl.SyclQueueCreationError: |
| 61 | + pytest.skip("Execution queue could not be created, skipping...") |
| 62 | + |
| 63 | + x = np.dstack( |
| 64 | + np.meshgrid( |
| 65 | + np.linspace(0.1, 0.9, num=7), |
| 66 | + np.linspace(0.1, 0.9, num=7), |
| 67 | + np.linspace(0.1, 0.9, num=7) |
| 68 | + ) |
| 69 | + ).reshape(-1, 3) |
| 70 | + |
| 71 | + data = np.random.rand(16000,3) |
| 72 | + |
| 73 | + f_cy = kde_eval(q, x, data, 0.01) |
| 74 | + f_ref = ref_kde(x, data, 0.01) |
| 75 | + |
| 76 | + assert np.allclose(f_cy, f_ref) |
0 commit comments