|
| 1 | +# encoding: utf-8 |
| 2 | +""" |
| 3 | +Interoperability tests exercising the larray usage patterns that downstream |
| 4 | +projects (notably PyNN) rely on. |
| 5 | +
|
| 6 | +The goal is to lock in the public-API contract that other EBRAINS components |
| 7 | +depend on, so that an internal refactor cannot silently break those callers. |
| 8 | +
|
| 9 | +Copyright CNRS, 2012-2026 |
| 10 | +""" |
| 11 | + |
| 12 | +import numpy as np |
| 13 | +from numpy.testing import assert_array_almost_equal |
| 14 | + |
| 15 | +from lazyarray import larray |
| 16 | + |
| 17 | + |
| 18 | +def test_callable_base_value_partial_evaluation(): |
| 19 | + """ |
| 20 | + PyNN uses larray to represent synaptic weights as f(i, j), and evaluates |
| 21 | + only the slice of (i, j) pairs that the local MPI rank is responsible for. |
| 22 | + Verify that only the requested indices are computed. |
| 23 | + """ |
| 24 | + calls = [] |
| 25 | + |
| 26 | + def weight(i, j): |
| 27 | + calls.append((int(i), int(j)) if np.isscalar(i) else None) |
| 28 | + return 0.1 * np.asarray(i) + 0.01 * np.asarray(j) |
| 29 | + |
| 30 | + A = larray(weight, shape=(100, 100)) |
| 31 | + |
| 32 | + sub = A[10:13, 20:22] |
| 33 | + |
| 34 | + assert sub.shape == (3, 2) |
| 35 | + expected = 0.1 * np.arange(10, 13)[:, None] + 0.01 * np.arange(20, 22)[None, :] |
| 36 | + assert_array_almost_equal(sub, expected) |
| 37 | + |
| 38 | + |
| 39 | +def test_arithmetic_then_partial_evaluation(): |
| 40 | + """ |
| 41 | + PyNN scales weights by a unit conversion factor and adds delays. |
| 42 | + The arithmetic must be queued lazily and only applied to the elements |
| 43 | + that are actually evaluated. |
| 44 | + """ |
| 45 | + A = larray(lambda i, j: i + j, shape=(10, 10)) |
| 46 | + scaled = A * 1000.0 + 0.5 |
| 47 | + |
| 48 | + result = scaled[3:5, 0:4] |
| 49 | + expected = 1000.0 * (np.arange(3, 5)[:, None] + np.arange(0, 4)[None, :]) + 0.5 |
| 50 | + |
| 51 | + assert result.shape == (2, 4) |
| 52 | + assert_array_almost_equal(result, expected) |
| 53 | + |
| 54 | + |
| 55 | +def test_scalar_homogeneous_evaluation(): |
| 56 | + """ |
| 57 | + PyNN frequently constructs larrays from a single scalar (uniform |
| 58 | + weight or delay across a whole projection) and expects evaluate(simplify=True) |
| 59 | + to return that scalar unchanged. |
| 60 | + """ |
| 61 | + A = larray(0.5, shape=(50, 50)) |
| 62 | + assert A.evaluate(simplify=True) == 0.5 |
| 63 | + |
| 64 | + |
| 65 | +def test_boolean_mask_evaluation(): |
| 66 | + """ |
| 67 | + Evaluation through a boolean mask is the typical MPI-distribution pattern: |
| 68 | + each rank holds a mask over the global index set. |
| 69 | + """ |
| 70 | + A = larray(lambda i: i ** 2, shape=(20,)) |
| 71 | + mask = np.zeros(20, dtype=bool) |
| 72 | + mask[[2, 5, 7]] = True |
| 73 | + |
| 74 | + result = A[mask] |
| 75 | + |
| 76 | + assert_array_almost_equal(result, np.array([4, 25, 49])) |
0 commit comments