Skip to content

[FLPY-61] Fixed operator overloading when using unyt types as lvalues #1092

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: expressions
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions flow360/component/simulation/user_code.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,41 @@
_solver_variables: dict[str, str] = {}


def __soft_fail_add__(self, other):
if not isinstance(other, Expression) and not isinstance(other, Variable):
return np.ndarray.__add__(self, other)
else:
return NotImplemented


def __soft_fail_sub__(self, other):
if not isinstance(other, Expression) and not isinstance(other, Variable):
return np.ndarray.__sub__(self, other)
else:
return NotImplemented


def __soft_fail_mul__(self, other):
if not isinstance(other, Expression) and not isinstance(other, Variable):
return np.ndarray.__mul__(self, other)
else:
return NotImplemented


def __soft_fail_truediv__(self, other):
if not isinstance(other, Expression) and not isinstance(other, Variable):
return np.ndarray.__truediv__(self, other)
else:
return NotImplemented


unyt_array.__add__ = __soft_fail_add__
unyt_array.__sub__ = __soft_fail_sub__
unyt_array.__mul__ = __soft_fail_mul__
unyt_array.__truediv__ = __soft_fail_truediv__
# Possibly other operators too..?


def _is_number_string(s: str) -> bool:
try:
float(s)
Expand Down
15 changes: 14 additions & 1 deletion tests/simulation/test_expressions.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,8 @@
ValueOrExpression,
)

import unyt


@pytest.fixture(autouse=True)
def change_test_dir(request, monkeypatch):
Expand Down Expand Up @@ -709,9 +711,20 @@ def test_variable_space_init():
params, errors, _ = validate_model(
params_as_dict=data, validated_by=ValidationCalledBy.LOCAL, root_item_type="Geometry"
)
from flow360.component.simulation.user_code import _global_ctx, _user_variables

assert errors is None
evaluated = params.reference_geometry.area.evaluate()

assert evaluated == 1.0 * u.m**2


def test_unyt_operator_runtime_overloading():
x = UserVariable(name="x", value=10 * u.m + solution.coordinate * u.m)

with pytest.raises(ValueError):
x.value.evaluate()

y = UserVariable(name="y", value=solution.coordinate * u.m + 10 * u.m)

with pytest.raises(ValueError):
y.value.evaluate()
Loading