Skip to content
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

add numerical constants pi, e, Euler's gamma, and imaginary I #12

Merged
merged 4 commits into from
Oct 21, 2023
Merged
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
25 changes: 25 additions & 0 deletions sympy2jax/sympy_module.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,13 @@ def fn_(*args):
sympy.Determinant: jnp.linalg.det,
}

_constant_lookup = {
sympy.E: jnp.e,
sympy.pi: jnp.pi,
sympy.EulerGamma: jnp.euler_gamma,
sympy.I: 1j,
}

_reverse_lookup = {v: k for k, v in _lookup.items()}
assert len(_reverse_lookup) == len(_lookup)

Expand Down Expand Up @@ -198,6 +205,22 @@ def sympy(self, memodict: dict, func_lookup: dict) -> sympy.Expr:
)


class _Constant(_AbstractNode):
_value: jnp.ndarray
_expr: sympy.Expr

def __init__(self, expr: sympy.Expr, make_array: bool):
assert expr in _constant_lookup
self._value = _maybe_array(_constant_lookup[expr], make_array)
self._expr = expr

def __call__(self, memodict: dict):
return self._value

def sympy(self, memodict: dict, func_lookup: dict) -> sympy.Expr:
return self._expr


class _Func(_AbstractNode):
_func: Callable
_args: list
Expand Down Expand Up @@ -250,6 +273,8 @@ def _sympy_to_node(
out = _Float(expr, make_array)
elif isinstance(expr, sympy.Rational):
out = _Rational(expr, make_array)
elif expr in (sympy.E, sympy.pi, sympy.EulerGamma, sympy.I):
out = _Constant(expr, make_array)
else:
out = _Func(expr, memodict, func_lookup, make_array)
memodict[expr] = out
Expand Down
8 changes: 8 additions & 0 deletions tests/test_symbolic_module.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,14 @@ def test_rational():
assert mod.sympy() == y


def test_constants():
x = sympy.symbols("x")
y = x + sympy.pi + sympy.E + sympy.EulerGamma + sympy.I
mod = sympy2jax.SymbolicModule(y)
assert jnp.isclose(mod(x=1.0), 1 + jnp.pi + jnp.e + jnp.euler_gamma + 1j)
assert mod.sympy() == y


def test_extra_funcs():
class _MLP(eqx.Module):
mlp: eqx.nn.MLP
Expand Down
Loading