Skip to content

Partial expression evaluation, example of a builtin function #1115

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

Merged
merged 19 commits into from
Jun 5, 2025
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
7 changes: 7 additions & 0 deletions flow360/component/simulation/blueprint/core/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ def __init__(
self._values = initial_values or {}
self._data_models = {}
self._resolver = resolver
self._aliases: dict[str, str] = {}

def get(self, name: str, resolve: bool = True) -> Any:
"""
Expand Down Expand Up @@ -77,6 +78,12 @@ def get_data_model(self, name: str) -> Optional[pd.BaseModel]:
return None
return self._data_models[name]

def set_alias(self, name, alias) -> None:
self._aliases[name] = alias

def get_alias(self, name) -> Optional[str]:
return self._aliases.get(name)

def set(self, name: str, value: Any, data_model: pd.BaseModel = None) -> None:
"""
Assign a value to a name in the context.
Expand Down
1 change: 1 addition & 0 deletions flow360/component/simulation/blueprint/core/expressions.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import abc
from typing import Annotated, Any, Literal, Union

import numpy as np
import pydantic as pd

from ..utils.operators import BINARY_OPERATORS, UNARY_OPERATORS
Expand Down
4 changes: 2 additions & 2 deletions flow360/component/simulation/unit_system.py
Original file line number Diff line number Diff line change
Expand Up @@ -424,7 +424,7 @@ def __get_pydantic_core_schema__(con_cls, *args, **kwargs) -> pd.CoreSchema:
# pylint: disable=invalid-name
# pylint: disable=too-many-arguments
@classmethod
def Constrained(cls, gt=None, ge=None, lt=None, le=None, allow_inf_nan=False):
def Constrained(cls, gt=None, ge=None, lt=None, le=None, allow_inf_nan=True):
"""
Utility method to generate a dimensioned type with constraints based on the pydantic confloat
"""
Expand Down Expand Up @@ -524,7 +524,7 @@ def validate(vec_cls, value, *args, **kwargs):
value, vec_cls.type.dim, vec_cls.type.expect_delta_unit
)

if kwargs.get("allow_inf_nan", False) is False:
if kwargs.get("allow_inf_nan", True) is False:
value = _nan_inf_vector_validator(value)

value = _has_dimensions_validator(
Expand Down
62 changes: 25 additions & 37 deletions flow360/component/simulation/user_code/core/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,6 @@
)

_user_variables: set[str] = set()
_solver_variable_name_map: dict[str, str] = {}


def __soft_fail_add__(self, other):
if not isinstance(other, Expression) and not isinstance(other, Variable):
Expand Down Expand Up @@ -109,10 +107,10 @@ class SerializedValueOrExpression(Flow360BaseModel):
"""Serialized frontend-compatible format of an arbitrary value/expression field"""

type_name: Union[Literal["number"], Literal["expression"]] = pd.Field(None)
value: Optional[Union[Number, Iterable[Number]]] = pd.Field(None)
value: Optional[Union[Number, list[Number]]] = pd.Field(None)
units: Optional[str] = pd.Field(None)
expression: Optional[str] = pd.Field(None)
evaluated_value: Optional[Union[Number, Iterable[Number]]] = pd.Field(None)
evaluated_value: Optional[Union[Number, list[Number]]] = pd.Field(None)
evaluated_units: Optional[str] = pd.Field(None)


Expand Down Expand Up @@ -292,9 +290,8 @@ class SolverVariable(Variable):
def update_context(cls, value):
"""Auto updating context when new variable is declared"""
default_context.set(value.name, value.value, SolverVariable)
_solver_variable_name_map[value.name] = (
value.solver_name if value.solver_name is not None else value.name
)
if value.solver_name:
default_context.set_alias(value.name, value.solver_name)
return value


Expand Down Expand Up @@ -374,8 +371,10 @@ def to_solver_code(self, params):
"""Convert to solver readable code."""

def translate_symbol(name):
if name in _solver_variable_name_map:
return _solver_variable_name_map[name]
alias = default_context.get_alias(name)

if alias:
return alias

match = re.fullmatch("u\\.(.+)", name)

Expand Down Expand Up @@ -514,37 +513,26 @@ def _internal_validator(value: Expression):
expr_type = Annotated[Expression, pd.AfterValidator(_internal_validator)]

def _deserialize(value) -> Self:
def _validation_attempt_(input_value):
deserialized = None
try:
deserialized = SerializedValueOrExpression.model_validate(input_value)
except: # pylint:disable=bare-except
pass
return deserialized

###
deserialized = None
if isinstance(value, dict) and "type_name" not in value:
# Deserializing legacy simulation.json where there is only "units" + "value"
deserialized = _validation_attempt_({**value, "type_name": "number"})
else:
deserialized = _validation_attempt_(value)
if deserialized is None:
# All validation attempt failed
deserialized = value
else:
if deserialized.type_name == "number":
if deserialized.units is not None:
# Note: Flow360 unyt_array could not be constructed here.
return unyt_array(deserialized.value, deserialized.units)
return deserialized.value
if deserialized.type_name == "expression":
return expr_type(expression=deserialized.expression)
is_serialized = False

return deserialized
try:
value = SerializedValueOrExpression.model_validate(value)
is_serialized = True
except Exception as err:
pass

if is_serialized:
if value.type_name == "number":
if value.units is not None:
return unyt_array(value.value, value.units)
else:
return value.value
elif value.type_name == "expression":
return expr_type(expression=value.expression)
else:
return value

def _serializer(value, info) -> dict:
print(">>> Inside serializer: value = ", value)
if isinstance(value, Expression):
serialized = SerializedValueOrExpression(type_name="expression")

Expand Down
35 changes: 31 additions & 4 deletions flow360/component/simulation/user_code/functions/math.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from enum import Enum
import numpy as np
from unyt import unyt_array

from flow360.component.simulation.user_code.core.types import Expression, Variable

Expand All @@ -13,6 +14,19 @@ def _convert_argument(value):
return value


def _extract_units(value):
units = 1 # Neutral element of multiplication

if isinstance(value, Expression):
result = value.evaluate(raise_error=False)
if isinstance(result, unyt_array):
units = result.units
elif isinstance(value, unyt_array):
units = value.units

return units


def cross(left, right):
"""Customized Cross function to work with the `Expression` and Variables"""

Expand All @@ -32,6 +46,19 @@ def cross(left, right):
is_expression_type = True

if is_expression_type:
return Expression.model_validate(result)
else:
return result
result = Expression.model_validate(result)

unit = 1

left_units = _extract_units(left)
right_units = _extract_units(right)

if left_units != 1:
unit = left_units
if right_units != 1:
unit = unit * right_units if unit != 1 else right_units

if unit != 1:
result *= unit

return result
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
},
"reference_geometry": {
"moment_center": {
"type_name": "number",
"value": [
0,
0,
Expand Down
36 changes: 33 additions & 3 deletions tests/simulation/test_expressions.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
from flow360.component.simulation.models.material import Water, aluminum
from flow360.component.simulation.outputs.outputs import SurfaceOutput
from flow360.component.simulation.primitives import GenericVolume, Surface
from flow360.component.simulation.services import ValidationCalledBy, validate_model
from flow360.component.simulation.unit_system import (
AbsoluteTemperatureType,
AngleType,
Expand Down Expand Up @@ -601,9 +602,8 @@ class TestModel(Flow360BaseModel):

def test_variable_space_init():
# Simulating loading a SimulationParams object from file - ensure that the variable space is loaded correctly
with open("data/variables.json", "r+") as fh:
with open("data/simulation.json", "r+") as fh:
data = json.load(fh)
from flow360.component.simulation.services import ValidationCalledBy, validate_model

params, errors, _ = validate_model(
params_as_dict=data, validated_by=ValidationCalledBy.LOCAL, root_item_type="Geometry"
Expand All @@ -617,7 +617,7 @@ def test_variable_space_init():

def test_cross_product():
class TestModel(Flow360BaseModel):
field: ValueOrExpression[VelocityType] = pd.Field()
field: ValueOrExpression[VelocityType.Vector] = pd.Field()

x = UserVariable(name="x", value=[1, 2, 3])

Expand All @@ -632,3 +632,33 @@ class TestModel(Flow360BaseModel):

result = model.field.evaluate()
assert (result == [-4, 8, -4] * u.m / u.s).all()


def test_vector_solver_variable_cross_product_translation():
with open("data/simulation.json", "r+") as fh:
data = json.load(fh)

params, errors, _ = validate_model(
params_as_dict=data, validated_by=ValidationCalledBy.LOCAL, root_item_type="Geometry"
)

class TestModel(Flow360BaseModel):
field: ValueOrExpression[LengthType.Vector] = pd.Field()

# From string
expr_1 = TestModel(field="math.cross([1, 2, 3], solution.coordinate)").field
assert str(expr_1) == "math.cross([1, 2, 3], solution.coordinate)"

# During solver translation both options are inlined the same way through partial evaluation
solver_1 = expr_1.to_solver_code(params)
print(solver_1)

# From python code
expr_2 = TestModel(field=math.cross([1, 2, 3], solution.coordinate)).field
assert str(expr_2) == "([2 * ((solution.coordinate)[2]) - (3 * ((solution.coordinate)[1])),3 * ((solution.coordinate)[0]) - (1 * ((solution.coordinate)[2])),1 * ((solution.coordinate)[1]) - (2 * ((solution.coordinate)[0]))]) * u.m"

# During solver translation both options are inlined the same way through partial evaluation
solver_2 = expr_2.to_solver_code(params)
print(solver_2) # <- TODO: This currently will break, because the overloaded unyt operators in types.py don't
# handle List[Expression]... We should do some sort of implicit conversion perhaps?

Loading