Skip to content

Commit

Permalink
Fix sympify usage (#976)
Browse files Browse the repository at this point in the history
  • Loading branch information
alesanter authored Mar 7, 2025
1 parent c9e71ec commit 03ead43
Show file tree
Hide file tree
Showing 21 changed files with 66 additions and 94 deletions.
4 changes: 2 additions & 2 deletions examples/electricity/charged_particle_in_electric_field.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
#!/usr/bin/env python3

from sympy import solve, symbols, sympify
from sympy import solve, symbols
from symplyphysics import print_expression, Vector, Quantity, units, convert_to
from symplyphysics.laws.electricity.vector import electric_field_is_force_over_test_charge as electric_field_law
from symplyphysics.laws.dynamics import acceleration_is_force_over_mass
Expand Down Expand Up @@ -30,7 +30,7 @@

electric_field_vector = Vector([0, -1 * electric_field_magnitude, 0])
electrostatic_force_vector = electric_field_law.electrostatic_force_law(electric_field_vector)
electrostatic_force_y_expr = sympify(electrostatic_force_vector.components[1])
electrostatic_force_y_expr = electrostatic_force_vector.components[1]
electrostatic_force_y = electrostatic_force_y_expr.subs(electric_field_law.test_charge, drop_charge)

drop_acceleration_y = solve(acceleration_is_force_over_mass.law,
Expand Down
4 changes: 2 additions & 2 deletions symplyphysics/core/convert.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from typing import Any, SupportsFloat
from sympy import Expr, S, sympify
from sympy import Expr, S
from sympy.physics.units import Quantity as SymQuantity

from .dimensions import assert_equivalent_dimension, dimension_to_si_unit
Expand All @@ -16,7 +16,7 @@ def convert_to(value: Expr, target_unit: Expr) -> Expr:
target_unit = Quantity(target_unit)

assert_equivalent_dimension(value, value.dimension.name, "convert_to", target_unit.dimension)
return sympify(value.scale_factor) * (1 / sympify(target_unit.scale_factor))
return value.scale_factor / target_unit.scale_factor


def convert_to_float(value: Expr) -> float:
Expand Down
6 changes: 3 additions & 3 deletions symplyphysics/core/dimensions/collect_expression.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import Iterable, Callable, Any
from typing import Iterable, Callable, Any, SupportsFloat
from sympy import Expr, S, Mul, Add, Pow, Abs, Min, Max, Derivative, Function as SymFunction, sympify
from sympy.functions.elementary.miscellaneous import MinMaxBase
from sympy.physics.units import Dimension, Quantity as SymQuantity
Expand Down Expand Up @@ -190,7 +190,7 @@ def _collect_derivative(expr: Derivative) -> tuple[Expr, Dimension]:
}


def collect_expression_and_dimension(expr: Any) -> tuple[Expr, Dimension]:
def collect_expression_and_dimension(expr: SupportsFloat) -> tuple[Expr, Dimension]:
"""
Returns the simplified representation and the dimension of the given expression. Unlike
`collect_quantity_factor_and_dimension` it supports derivatives, symbols, and functions with
Expand All @@ -201,7 +201,7 @@ def collect_expression_and_dimension(expr: Any) -> tuple[Expr, Dimension]:
UnitsError: if the dimensions of sub-expressions don't match.
"""

expr = sympify(expr)
expr = sympify(expr) # no `strict` because we want to allow sympy functions here too

# early return that works for `sympy.Quantity`, `SymbolNew`, `SymbolIndexedNew`, and `FunctionNew`
if hasattr(expr, "dimension"):
Expand Down
2 changes: 1 addition & 1 deletion symplyphysics/core/dimensions/collect_quantity.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ def collect_quantity_factor_and_dimension(expr: SupportsFloat) -> tuple[Expr, Di
sympy.SympifyError: If ``expr`` cannot be converted to a value used by `sympy`.
"""

expr = sympify(expr)
expr = sympify(expr) # no `strict` because we want to allow sympy functions here too

for type_, collector in _cases.items():
if isinstance(expr, type_):
Expand Down
2 changes: 1 addition & 1 deletion symplyphysics/core/experimental/vectors/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -259,7 +259,7 @@ def __init__(self, vector: VectorExpr, scale: Any, **kwargs: Any) -> None:
evaluate = kwargs.get("evaluate", global_parameters.evaluate)

if evaluate:
scale = sympify(scale)
scale = sympify(scale, strict=True)
if not isinstance(scale, Expr):
raise TypeError(f"Scale {scale} must be an Expr, got {type(scale).__name__}.")

Expand Down
6 changes: 3 additions & 3 deletions symplyphysics/core/fields/scalar_field.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
def _subs_with_point(expr: Any, coordinate_system: CoordinateSystem, point_: Point) -> Expr:
base_scalars = coordinate_system.coord_system.base_scalars()
# convert Any to Expr
expression = sympify(expr)
expression = sympify(expr, strict=True)
for i, scalar in enumerate(base_scalars):
expression = expression.subs(scalar, point_.coordinate(i))
return expression
Expand All @@ -42,7 +42,7 @@ def __init__(
coordinate_system: CoordinateSystem = CoordinateSystem(CoordinateSystem.System.CARTESIAN)
) -> None:
if not callable(point_function):
point_function = sympify(point_function)
point_function = sympify(point_function, strict=True)

self._point_function = point_function
self._coordinate_system = coordinate_system
Expand Down Expand Up @@ -109,7 +109,7 @@ def apply_to_basis(self) -> Expr:

# Converts ScalarField to SymPy expression
def to_expression(self) -> Expr:
return sympify(self.apply_to_basis())
return self.apply_to_basis()

# Convert field coordinate system to new basis and construct new field.
# Scalar field invariant (coordinate system independence) should hold.
Expand Down
4 changes: 2 additions & 2 deletions symplyphysics/core/fields/vector_field.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ def _subs_with_point(
base_scalars = coordinate_system.coord_system.base_scalars()
result: list[Expr] = []
for e in expr:
expression = sympify(e)
expression = sympify(e, strict=True)
for i, scalar in enumerate(base_scalars):
expression = expression.subs(scalar, point_.coordinate(i))
result.append(expression)
Expand All @@ -46,7 +46,7 @@ def __init__(
coordinate_system: CoordinateSystem = CoordinateSystem(CoordinateSystem.System.CARTESIAN)
) -> None:
if not callable(point_function):
point_function = list(map(sympify, point_function))
point_function = [sympify(c, strict=True) for c in point_function]

self._point_function = point_function
self._coordinate_system = coordinate_system
Expand Down
4 changes: 2 additions & 2 deletions symplyphysics/core/points/point.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ class Point:
_coordinates: list[Expr] = []

def __init__(self, *coordinates: Any) -> None:
self._coordinates = list(map(sympify, coordinates))
self._coordinates = [sympify(c, strict=True) for c in coordinates]

@property
def coordinates(self) -> Iterable[Expr]:
Expand All @@ -26,4 +26,4 @@ def set_coordinate(self, index: int, value: Any) -> None:
value = S.Zero
if len(self._coordinates) <= index:
self._coordinates.extend([S.Zero] * (index + 1 - len(self._coordinates)))
self._coordinates[index] = sympify(value)
self._coordinates[index] = sympify(value, strict=True)
2 changes: 1 addition & 1 deletion symplyphysics/core/symbols/quantities.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ def subs_list(
input_: Sequence[SupportsFloat],
subs_: dict[Expr, SymQuantity],
) -> Sequence[Quantity]:
return [Quantity(sympify(c).subs(subs_)) for c in input_]
return [Quantity(sympify(c, strict=True).subs(subs_)) for c in input_]


def scale_factor(quantity_: SupportsFloat) -> float:
Expand Down
5 changes: 3 additions & 2 deletions symplyphysics/core/vectors/arithmetics.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ def add_two_cartesian_vectors(vector_left: Vector, vector_right: Vector) -> Vect

(list_left_extended, list_right_extended) = _extend_two_vectors(vector_left, vector_right)
result = [
sympify(left_component + right_component)
sympify(left_component + right_component, strict=True)
for (left_component, right_component) in zip(list_left_extended, list_right_extended)
]

Expand Down Expand Up @@ -114,7 +114,8 @@ def _multiply_lists_and_sum(
list_left: Sequence[Any],
list_right: Sequence[Any],
) -> Expr:
return sympify(reduce(add, map(lambda lr: lr[0] * lr[1], zip(list_left, list_right)), 0))
return sympify(reduce(add, map(lambda lr: lr[0] * lr[1], zip(list_left, list_right)), 0),
strict=True)


# Dot product of two vectors
Expand Down
4 changes: 2 additions & 2 deletions symplyphysics/core/vectors/vectors.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ def __init__(
coordinate_system: CoordinateSystem = CoordinateSystem(CoordinateSystem.System.CARTESIAN)
) -> None:
self._coordinate_system = coordinate_system
self._components = list(map(sympify, components))
self._components = [sympify(c, strict=True) for c in components]

@property
def coordinate_system(self) -> CoordinateSystem:
Expand Down Expand Up @@ -102,7 +102,7 @@ def simplify(self, **kwargs: Any) -> Vector:
return Vector(components, self.coordinate_system)

def subs(self, *args: Any) -> Vector:
components = [sympify(component).subs(*args) for component in self.components]
components = [sympify(component, strict=True).subs(*args) for component in self.components]
return Vector(components, self.coordinate_system)


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
#. `Britannica <https://www.britannica.com/science/Newtons-laws-of-motion/Newtons-second-law-F-ma>`__.
"""

from sympy import (Eq, solve, sympify)
from sympy import (Eq, solve)
from symplyphysics import (Vector, Quantity, validate_input, validate_output, symbols)
from symplyphysics.core.expr_comparisons import expr_equals
from symplyphysics.laws.dynamics.vector import acceleration_from_force as acceleration_law_vector
Expand Down Expand Up @@ -43,8 +43,8 @@
_force_vector = Vector([force])
_acceleration_vector = acceleration_law_vector.acceleration_law(_force_vector)
assert len(_acceleration_vector.components) == 1
_acceleration_with_mass = sympify(_acceleration_vector.components[0]).subs(
acceleration_law_vector.mass, mass)
_acceleration_with_mass = _acceleration_vector.components[0].subs(acceleration_law_vector.mass,
mass)
assert expr_equals(_acceleration_with_mass, law.rhs)


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
#. `Wikipedia, last formula in paragraph <https://en.wikipedia.org/wiki/Hooke%27s_law#Linear_springs>`__.
"""

from sympy import Eq, sympify
from sympy import Eq
from symplyphysics import (
symbols,
Quantity,
Expand Down Expand Up @@ -66,7 +66,7 @@
_deformation_vector = Vector([deformation])
_spring_reaction_vector_derived = hookes_vector_law.force_law(_deformation_vector)
assert len(_spring_reaction_vector_derived.components) == 1
_spring_reaction_derived = sympify(_spring_reaction_vector_derived.components[0]).subs(
_spring_reaction_derived = _spring_reaction_vector_derived.components[0].subs(
hookes_vector_law.stiffness, stiffness)
assert expr_equals(_spring_reaction_derived, law.rhs)

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from sympy import Derivative, sympify
from sympy import Derivative
from symplyphysics import (
units,
Quantity,
Expand Down Expand Up @@ -45,6 +45,6 @@ def calculate_force(
scale_vector(-1, momentum_before_.to_base_vector())))
result_force_vector = force_law(momentum_function)
result_force_components = [
sympify(component).doit() for component in result_force_vector.components
component.doit() for component in result_force_vector.components
]
return QuantityVector(result_force_components, momentum_before_.coordinate_system)
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from sympy import Derivative, sympify
from sympy import Derivative
from symplyphysics import (
units,
Quantity,
Expand Down Expand Up @@ -48,5 +48,5 @@ def calculate_torque(
add_cartesian_vectors(angular_momentum_after_.to_base_vector(),
scale_vector(-1, angular_momentum_before_.to_base_vector())))
result_torque_vector = torque_law(angular_momentum_function)
result_components = [sympify(component).doit() for component in result_torque_vector.components]
result_components = [component.doit() for component in result_torque_vector.components]
return QuantityVector(result_components, angular_momentum_before_.coordinate_system)
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from sympy import diff, sympify
from sympy import diff
from symplyphysics import (QuantityVector, add_cartesian_vectors, scale_vector, units,
Quantity, validate_input, validate_output, symbols)
from symplyphysics.core.fields.operators import curl_operator
Expand Down Expand Up @@ -78,8 +78,7 @@ def calculate_conductivity_current_density_at_point(magnetic_intensity_: VectorF

electric_induction_vector = electric_induction_.apply(cartesian_point_)
for i, c in enumerate(electric_induction_vector.components):
expr = sympify(c)
expr = expr.subs(time, time_)
expr = c.subs(time, time_)
assert_equivalent_dimension(expr, f"electric_induction_vector[{i}]",
"calculate_conductivity_current_density_at_point", units.charge / units.area)

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from sympy import Expr, symbols as sym_symbols, sympify
from sympy import Expr, symbols as sym_symbols
from symplyphysics import (
units,
Quantity,
Expand Down Expand Up @@ -112,7 +112,7 @@ def rest_mass_law(

for _force_derived_component, _force_component in zip(_force_derived.components, _force.components):
assert expr_equals(
sympify(_force_derived_component),
_force_derived_component,
_force_component,
)

Expand All @@ -122,7 +122,7 @@ def rest_mass_law(
for _acceleration_derived_component, _acceleration_component in zip(
_acceleration_derived.components, _acceleration.components):
assert expr_equals(
sympify(_acceleration_derived_component),
_acceleration_derived_component,
_acceleration_component,
)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,16 +22,7 @@
#. `Wikipedia <https://en.wikipedia.org/wiki/Maxwell%E2%80%93Boltzmann_distribution#Distribution_for_the_speed>`__.
"""

from sympy import (
Eq,
Rational,
sqrt,
pi,
exp,
symbols as sym_symbols,
solve,
sympify,
)
from sympy import (Eq, Rational, sqrt, pi, exp, symbols as sym_symbols, solve)
from symplyphysics import (
units,
Quantity,
Expand Down Expand Up @@ -104,9 +95,8 @@
# The speed distribution depends solely on the radial component of the velocity vector.
# Therefore we integrate over polar and azimuthal angles to get rid of them.
# We work in the three-dimensional velocity space `d^3(v)` so radius is speed (magnitude of velocity vector)
_spherical_volume_velocity_element = (sympify(
volume_element_magnitude(_spherical_coordinate_system)).subs(_radius, particle_speed).integrate(
(_polar_angle, 0, pi), (_azimuthal_angle, 0, 2 * pi)))
_spherical_volume_velocity_element = (volume_element_magnitude(_spherical_coordinate_system).subs(
_radius, particle_speed).integrate((_polar_angle, 0, pi), (_azimuthal_angle, 0, 2 * pi)))

# `v_x`, `v_y` and `v_z` are independent random variables, therefore we can get the distribution of
# the velocity vector `v` by multiplying the distributions of its coordinates.
Expand Down
12 changes: 6 additions & 6 deletions test/core/dimensions/collect_dimension_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,14 +49,14 @@ def test_pow() -> None:
assert dimsys_SI.equivalent_dims(dim, units.current**n)

expr = symbols.current**(2 * n)
_ = collect_expression_and_dimension(expr)[1]
collect_expression_and_dimension(expr)[1]

expr = (symbols.acceleration * symbols.mass)**(2 * symbols.time * symbols.temporal_frequency)
_ = collect_expression_and_dimension(expr)[1]
collect_expression_and_dimension(expr)[1]

bad_expr = symbols.mass**symbols.amount_of_substance
with raises(ValueError):
_ = collect_expression_and_dimension(bad_expr)
collect_expression_and_dimension(bad_expr)


def test_add() -> None:
Expand All @@ -70,7 +70,7 @@ def test_add() -> None:

expr = first_mass + second_mass + symbols.time
with raises(ValueError):
_ = collect_expression_and_dimension(expr)[1]
collect_expression_and_dimension(expr)[1]


def test_abs() -> None:
Expand All @@ -85,7 +85,7 @@ def test_abs() -> None:
# the error propagates from the argument
expr = abs(symbols.time + symbols.length)
with raises(ValueError):
_ = collect_expression_and_dimension(expr)[1]
collect_expression_and_dimension(expr)[1]


def test_min() -> None:
Expand All @@ -99,7 +99,7 @@ def test_min() -> None:

expr = Min(first_mass, second_mass, symbols.time)
with raises(ValueError):
_ = collect_expression_and_dimension(expr)[1]
collect_expression_and_dimension(expr)[1]


def test_derivative() -> None:
Expand Down
Loading

0 comments on commit 03ead43

Please sign in to comment.