From 1c4d4e900920d2a74079c796f677d650e208981b Mon Sep 17 00:00:00 2001 From: dance858 Date: Fri, 13 Nov 2026 08:37:59 -0800 Subject: [PATCH] Copy Parameter values on assignment Parameter.value = arr kept a view of arr for 1-D, vector and F-ordered float64 input. Editing arr in place then changed p.value without bumping the parameter version, so the engine kept the old values until some other Parameter was assigned. Part of #37 (item 4). Co-Authored-By: Claude Opus 5.5 --- sparsediffpy/_expression.py | 2 +- tests/test_api.py | 12 ++++++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/sparsediffpy/_expression.py b/sparsediffpy/_expression.py index 535b318..522cbfa 100644 --- a/sparsediffpy/_expression.py +++ b/sparsediffpy/_expression.py @@ -165,7 +165,7 @@ def value(self): @value.setter def value(self, val): - flat = _flatten_shaped(val, self.shape) + flat = _flatten_shaped(val, self.shape).copy() # don't alias the caller's array if self._symmetric: _check_symmetric(flat, self.shape) self._flat = flat diff --git a/tests/test_api.py b/tests/test_api.py index 99263a9..e370eff 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -270,6 +270,18 @@ def test_parameter_update_without_recompile(scope): np.testing.assert_allclose(fn.jacobian().toarray(), J) +def test_parameter_value_is_copied(scope): + """Editing the assigned array in place must not change the parameter.""" + x = scope.Variable(2, 1) + x.value = [1.0, 2.0] + arr = np.ones(2) + p = scope.Parameter(2, 1, value=arr) + fn = sp.compile(sp.sum(p * x)) + arr[:] = 10.0 + np.testing.assert_array_equal(p.value, [[1.0], [1.0]]) + assert fn.forward().item() == 3.0 + + def test_unset_parameter_raises(scope): x, p = scope.Variable(2, 1), scope.Parameter(2, 1) fn = sp.compile(p * x)