You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
lhs, rhs and system raise ValueError when a coordinate-dependent conditional contains trial arguments in an affine residual. These APIs should extract its bilinear and negated linear parts, and the corresponding bilinear conditional already passes compute_form_data.
For trial function u, test function v, coefficient f and spatial coordinate x, this fails:
We now extract each branch independently, preserving the condition and replacing branches that don't contribute to the selected arity with zero.
The regression test checks all three APIs on both sides of the condition, including zero branches and different branch arities, and the full UFL test suite passes.
@vera-rubin (Nathan) can you confirm that this is you and that you are fine with this contribution being added to UFL under our licensing terms? @pbrubeck what do think about the following patch that adds some additional tests?
This seems like the correct fix.
It works for the example and several other forms, including nested conditionals. It also works for blocked systems made with ufl.MixedFunctionSpace, where system(conditional(c, u - f, p) * v * dx) which raises an error on main.
These are not tested in this PR, so I've made a patch to test them (below). It also tests the two new error paths:
"Condition cannot depend on form arguments."
"Don't know what to do with conditionals with different Arguments."
system can't reach the second error, as lhs and rhs replace every Argument they don't extract by zero before the conditional is visited. The patch tests it through compute_form_arities on a form with three Arguments instead.
There is a slight issue with your proposed test: ufl.system calls ufl.lhs and ufl.rhs, so the loop over [(lhs(F), rhs(F)), (a, L)] checks the same thing twice. The patch compares a with the split written out by hand instead. L is still compared by value, as rhs negates outside the conditional.
The patch also fixes the docstring: only the condition is free of Arguments, not the branches.
Patch (applies on e604b0fb with git apply)
diff --git a/test/test_lhs_rhs.py b/test/test_lhs_rhs.py
index b09d6bc5..227b34ae 100755
--- a/test/test_lhs_rhs.py+++ b/test/test_lhs_rhs.py@@ -12,9 +12,12 @@ from ufl import (
Constant,
FunctionSpace,
Mesh,
+ MixedFunctionSpace,
SpatialCoordinate,
TestFunction,
+ TestFunctions,
TrialFunction,
+ TrialFunctions,
action,
conditional,
derivative,
@@ -22,11 +25,16 @@ from ufl import (
ds,
dx,
exp,
+ extract_blocks,+ grad,+ indices,+ inner,
interval,
- lhs,- rhs,
system,
+ triangle,
)
+from ufl.algorithms import compute_form_data+from ufl.algorithms.formtransformations import compute_form_arities
def test_lhs_rhs_simple():
@@ -70,13 +78,125 @@ def test_lhs_rhs_conditional(weights):
F = conditional(x[0] > 0, ut * u - ft * f, uf * u - ff * f) * v * dx
a, L = system(F)
- for actual_a, actual_L in [(lhs(F), rhs(F)), (a, L)]:- for coordinate, u_weight, f_weight in [(1, ut, ft), (-1, uf, ff)]:- mapping = {u: 2, v: 3, f: 5}- a_value = sum(i.integrand()((coordinate,), mapping) for i in actual_a.integrals())- L_value = sum(i.integrand()((coordinate,), mapping) for i in actual_L.integrals())- assert a_value == 6 * u_weight- assert L_value == 15 * f_weight+ assert a == conditional(x[0] > 0, ut * u, uf * u) * v * dx+ # rhs negates outside the conditional, so compare L by value+ mapping = {u: 2, v: 3, f: 5}+ for coordinate, f_weight in [(1, ft), (-1, ff)]:+ assert sum(i.integrand()((coordinate,), mapping) for i in L.integrals()) == 15 * f_weight+++def test_lhs_rhs_conditional_different_arguments_raises():+ domain = Mesh(LagrangeElement(interval, 1, (1,)))+ space = FunctionSpace(domain, LagrangeElement(interval, 1))+ v, u, w = TestFunction(space), TrialFunction(space), Argument(space, 2)+ x = SpatialCoordinate(domain)++ with pytest.raises(ValueError, match="conditionals with different Arguments"):+ compute_form_arities(conditional(x[0] > 0, u, w) * v * dx)+++def test_lhs_rhs_conditional_condition_with_argument_raises():+ domain = Mesh(LagrangeElement(interval, 1, (1,)))+ space = FunctionSpace(domain, LagrangeElement(interval, 1))+ u, v, f = TrialFunction(space), TestFunction(space), Coefficient(space)++ with pytest.raises(ValueError, match="Condition cannot depend on form arguments"):+ system(conditional(u > 0, f, 2 * f) * v * dx)+++@pytest.mark.parametrize("kind", ["vector", "free_index", "restricted"])+def test_lhs_rhs_conditional_splits(kind):+ domain = Mesh(LagrangeElement(interval, 1, (1,)))+ space = FunctionSpace(domain, LagrangeElement(interval, 1))+ u, v, f = TrialFunction(space), TestFunction(space), Coefficient(space)+ x = SpatialCoordinate(domain)+ c = x[0] > 0+ (i,) = indices(1)+ F = {+ # The zero branch must match the shape and free indices of the conditional+ "vector": inner(conditional(c, grad(u), grad(f)), grad(v)) * dx,+ "free_index": conditional(c, u.dx(i), f.dx(i)) * v.dx(i) * dx,+ "restricted": conditional(x[0]("+") > 0, u("+") - f("+"), 0) * v("+") * dS,+ }[kind]++ a, L = system(F)+ assert compute_form_arities(F) == {1, 2}+ assert compute_form_arities(a) == {2}+ assert compute_form_arities(L) == {1}+ compute_form_data(a)+ compute_form_data(L)+++@pytest.mark.parametrize("inner_branch", ["true", "false"])+def test_lhs_rhs_conditional_nested(inner_branch):+ domain = Mesh(LagrangeElement(interval, 1, (1,)))+ space = FunctionSpace(domain, LagrangeElement(interval, 1))+ u, v, f = TrialFunction(space), TestFunction(space), Coefficient(space)+ x = SpatialCoordinate(domain)+ c, d = x[0] > 0, x[0] > 0.5+ if inner_branch == "true":+ F = conditional(c, conditional(d, u - f, 3 * u), 2 * f) * v * dx+ expected_a = conditional(c, conditional(d, u, 3 * u), 0) * v * dx+ else:+ F = conditional(c, u - f, conditional(d, 2 * f, 4 * u)) * v * dx+ expected_a = conditional(c, u, conditional(d, 0, 4 * u)) * v * dx++ a, L = system(F)+ assert a == expected_a+ mapping = {u: 2, v: 3, f: 5}+ for coordinate in [(1,), (0.25,), (-1,)]:+ F_value, a_value, L_value = (+ sum(i.integrand()(coordinate, mapping) for i in form.integrals()) for form in (F, a, L)+ )+ assert a_value - L_value == F_value+++def test_lhs_rhs_conditional_derivative_term():+ domain = Mesh(LagrangeElement(interval, 1, (1,)))+ space = FunctionSpace(domain, LagrangeElement(interval, 2))+ u, v, f = TrialFunction(space), TestFunction(space), Coefficient(space)+ c = SpatialCoordinate(domain)[0] > 0++ # Both rank-one terms of a branch are kept, the rank-zero term goes to L+ a, L = system(conditional(c, u + 2 * grad(u)[0] - f, 3 * u - 2 * f) * v * dx)+ assert a == conditional(c, u + 2 * grad(u)[0], 3 * u) * v * dx+ mapping = {v: 3, f: 5}+ for coordinate, L_value in [(1, 15), (-1, 30)]:+ assert sum(i.integrand()((coordinate,), mapping) for i in L.integrals()) == L_value+++@pytest.mark.parametrize("branches", ["velocity_pressure_and_velocity", "velocity_and_pressure"])+def test_lhs_rhs_conditional_mixed_function_space(branches):+ domain = Mesh(LagrangeElement(triangle, 1, (2,)))+ V = FunctionSpace(domain, LagrangeElement(triangle, 2, (2,)))+ Q = FunctionSpace(domain, LagrangeElement(triangle, 1))+ W = MixedFunctionSpace(V, Q)+ u, p = TrialFunctions(W)+ v, _ = TestFunctions(W)+ f = Coefficient(Q)+ c = SpatialCoordinate(domain)[0] > 0+ if branches == "velocity_pressure_and_velocity":+ F = conditional(c, u[0] + p - f, 2 * u[0] - f) * v[0] * dx+ expected_uu = conditional(c, u[0], 2 * u[0]) * v[0] * dx+ expected_up = conditional(c, p, 0) * v[0] * dx+ else:+ F = conditional(c, u[0] - f, p) * v[0] * dx+ expected_uu = conditional(c, u[0], 0) * v[0] * dx+ expected_up = conditional(c, 0, p) * v[0] * dx++ # A branch without the trial function of a block is zero in that block+ a, L = system(F)+ (a_uu, a_up), (a_pu, a_pp) = extract_blocks(a)+ assert a_uu == expected_uu+ assert a_up == expected_up+ assert a_pu is None and a_pp is None++ mapping = {u: (2, 4), p: 7, v: (3, 1), f: 5}+ for coordinate in [(1, 0), (-1, 0)]:+ F_value, a_value, L_value = (+ sum(i.integrand()(coordinate, mapping) for i in form.integrals()) for form in (F, a, L)+ )+ assert a_value - L_value == F_value
def test_lhs_rhs_derivatives():
diff --git a/ufl/algorithms/formtransformations.py b/ufl/algorithms/formtransformations.py
index d354786f..9e149494 100644
--- a/ufl/algorithms/formtransformations.py+++ b/ufl/algorithms/formtransformations.py@@ -223,7 +223,7 @@ class PartExtracter(Transformer):
return (x, provides)
def conditional(self, x):
- """Extract parts from both branches of an argument-independent conditional."""+ """Extract parts from both branches of a conditional whose condition has no Arguments."""
condition, true_value, false_value = x.ufl_operands
if _expr_has_terminal_types(condition, Argument):
raise ValueError("Condition cannot depend on form arguments.")
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
lhs,rhsandsystemraiseValueErrorwhen a coordinate-dependent conditional contains trial arguments in an affine residual. These APIs should extract its bilinear and negated linear parts, and the corresponding bilinear conditional already passescompute_form_data.For trial function
u, test functionv, coefficientfand spatial coordinatex, this fails:We now extract each branch independently, preserving the condition and replacing branches that don't contribute to the selected arity with zero.
The regression test checks all three APIs on both sides of the condition, including zero branches and different branch arities, and the full UFL test suite passes.
— ChipLab