├── .github
└── FUNDING.yml
├── .gitignore
├── .pre-commit-config.yaml
├── LICENSE
├── MANIFEST.in
├── README.md
├── setup.py
├── sympytorch
├── __init__.py
├── hide_floats_m.py
├── py.typed
└── sympy_module.py
└── tests
├── test_hide_floats.py
└── test_sympymodule.py
/.github/FUNDING.yml:
--------------------------------------------------------------------------------
1 | github: [patrick-kidger]
2 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | **/__pycache__
2 | *.egg-info
3 | build/
4 | dist/
5 |
6 |
--------------------------------------------------------------------------------
/.pre-commit-config.yaml:
--------------------------------------------------------------------------------
1 | repos:
2 | - repo: https://github.com/ambv/black
3 | rev: 22.3.0
4 | hooks:
5 | - id: black
6 | - repo: https://github.com/charliermarsh/ruff-pre-commit
7 | rev: 'v0.0.255'
8 | hooks:
9 | - id: ruff
10 | args: ["--fix"]
11 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/MANIFEST.in:
--------------------------------------------------------------------------------
1 | include LICENSE
2 | prune tests
3 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
sympytorch
2 |
3 | Turn SymPy expressions into PyTorch Modules.
4 |
5 | SymPy floats (optionally) become trainable parameters. SymPy symbols are inputs to the Module.
6 |
7 | Optimise your symbolic expressions via gradient descent!
8 |
9 | ## Installation
10 |
11 | ```bash
12 | pip install sympytorch
13 | ```
14 | Requires Python 3.7+ and PyTorch 1.6.0+ and SymPy 1.7.1+.
15 |
16 | ## Example
17 |
18 | ```python
19 | import sympy, torch, sympytorch
20 |
21 | x = sympy.symbols('x_name')
22 | cosx = 1.0 * sympy.cos(x)
23 | sinx = 2.0 * sympy.sin(x)
24 | mod = sympytorch.SymPyModule(expressions=[cosx, sinx])
25 |
26 | x_ = torch.rand(3)
27 | out = mod(x_name=x_) # out has shape (3, 2)
28 |
29 | assert torch.equal(out[:, 0], x_.cos())
30 | assert torch.equal(out[:, 1], 2 * x_.sin())
31 | assert out.requires_grad # from the two Parameters initialised as 1.0 and 2.0
32 | assert {x.item() for x in mod.parameters()} == {1.0, 2.0}
33 | ```
34 |
35 | ## API
36 |
37 | ```python
38 | sympytorch.SymPyModule(*, expressions, extra_funcs=None)
39 | ```
40 | Where:
41 | - `expressions` is a list of SymPy expressions.
42 | - `extra_funcs` is a dictionary mapping from custom `sympy.Function`s to their PyTorch implementation. Defaults to no extra functions.
43 |
44 | Instances of `SymPyModule` can be called, passing the values of the symbols as in the above example.
45 |
46 | `SymPyModule` has a method `.sympy()`, which returns the corresponding list of SymPy expressions. (Which may not be the same as the expressions it was initialised with, if the values of its Parameters have been changed, i.e. have been learnt.)
47 |
48 | Wrapping floats in `sympy.UnevaluatedExpr` will cause them not to be trained, by registering them as buffers rather than parameters.
49 |
50 | ```python
51 | sympytorch.hide_floats(expression)
52 | ```
53 | As a convenience, `hide_floats` will take an expression and return a new expression with every float wrapped in a `sympy.UnevaluatedExpr`, so that it is interpreted as a buffer rather than a parameter.
54 |
55 | ## Extensions
56 |
57 | Not every PyTorch or SymPy operation is supported -- just the ones that I found I've needed! There's a dictionary [here](./sympytorch/sympy_module.py#L12) that lists the supported operations. Feel free to submit PRs for any extra operations you think should be in by default. You can also use the `extra_funcs` argument to specify extra functions, including custom functions.
58 |
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | import pathlib
2 | import re
3 |
4 | import setuptools
5 |
6 |
7 | _here = pathlib.Path(__file__).resolve().parent
8 |
9 |
10 | name = "sympytorch"
11 |
12 | # for simplicity we actually store the version in the __version__ attribute in the
13 | # source
14 | with open(_here / name / "__init__.py") as f:
15 | meta_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", f.read(), re.M)
16 | if meta_match:
17 | version = meta_match.group(1)
18 | else:
19 | raise RuntimeError("Unable to find __version__ string.")
20 |
21 | author = "Patrick Kidger"
22 |
23 | author_email = "contact@kidger.site"
24 |
25 | description = "Turning SymPy expressions into PyTorch modules."
26 |
27 | with open(_here / "README.md", "r") as f:
28 | readme = f.read()
29 |
30 | url = "https://github.com/patrick-kidger/sympytorch"
31 |
32 | license = "Apache-2.0"
33 |
34 | classifiers = [
35 | "Development Status :: 3 - Alpha",
36 | "Intended Audience :: Developers",
37 | "Intended Audience :: Financial and Insurance Industry",
38 | "Intended Audience :: Information Technology",
39 | "Intended Audience :: Science/Research",
40 | "License :: OSI Approved :: Apache Software License",
41 | "Natural Language :: English",
42 | "Programming Language :: Python :: 3",
43 | "Topic :: Scientific/Engineering :: Artificial Intelligence",
44 | "Topic :: Scientific/Engineering :: Information Analysis",
45 | "Topic :: Scientific/Engineering :: Mathematics",
46 | ]
47 |
48 | python_requires = "~=3.7"
49 |
50 | install_requires = ["torch>=1.6.0", "sympy>=1.7.1"]
51 |
52 | setuptools.setup(
53 | name=name,
54 | version=version,
55 | author=author,
56 | author_email=author_email,
57 | maintainer=author,
58 | maintainer_email=author_email,
59 | description=description,
60 | long_description=readme,
61 | long_description_content_type="text/markdown",
62 | url=url,
63 | license=license,
64 | classifiers=classifiers,
65 | zip_safe=False,
66 | python_requires=python_requires,
67 | install_requires=install_requires,
68 | packages=[name],
69 | package_data={name: ["py.typed"]},
70 | )
71 |
--------------------------------------------------------------------------------
/sympytorch/__init__.py:
--------------------------------------------------------------------------------
1 | from .hide_floats_m import hide_floats as hide_floats
2 | from .sympy_module import SymPyModule as SymPyModule
3 |
4 |
5 | __version__ = "0.1.4"
6 |
--------------------------------------------------------------------------------
/sympytorch/hide_floats_m.py:
--------------------------------------------------------------------------------
1 | from typing import Dict, TypeVar
2 |
3 | import sympy
4 |
5 |
6 | ExprType = TypeVar("ExprType", bound=sympy.Expr)
7 |
8 |
9 | def hide_floats(expression: ExprType) -> ExprType:
10 | _memodict: Dict[ExprType, ExprType] = {}
11 | return _hide_floats(expression, _memodict)
12 |
13 |
14 | def _hide_floats(expression: ExprType, _memodict: Dict[ExprType, ExprType]) -> ExprType:
15 | try:
16 | return _memodict[expression]
17 | except KeyError:
18 | pass
19 |
20 | if issubclass(expression.func, (sympy.Min, sympy.Max)):
21 | evaluate = False
22 | else:
23 | evaluate = True
24 |
25 | new_expression: ExprType
26 | if issubclass(expression.func, sympy.Float):
27 | new_expression = sympy.UnevaluatedExpr(expression) # type: ignore
28 | elif issubclass(expression.func, sympy.Integer):
29 | new_expression = expression
30 | elif issubclass(expression.func, sympy.Symbol):
31 | new_expression = expression
32 | else:
33 | new_expression = expression.func(
34 | *[_hide_floats(arg, _memodict) for arg in expression.args],
35 | evaluate=evaluate
36 | ) # type: ignore
37 | _memodict[expression] = new_expression
38 | return new_expression
39 |
--------------------------------------------------------------------------------
/sympytorch/py.typed:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/patrick-kidger/sympytorch/0670a3bbdfc0b77fa1ecc1367f51887eb6c6e3e9/sympytorch/py.typed
--------------------------------------------------------------------------------
/sympytorch/sympy_module.py:
--------------------------------------------------------------------------------
1 | from __future__ import annotations
2 |
3 | import collections as co
4 | import functools as ft
5 | from typing import (
6 | Any,
7 | Callable,
8 | Dict,
9 | Generic,
10 | List,
11 | Sequence,
12 | Tuple,
13 | Type,
14 | TYPE_CHECKING,
15 | TypeVar,
16 | Union,
17 | )
18 |
19 | import sympy
20 | import torch
21 |
22 |
23 | ExprType = TypeVar("ExprType", bound=sympy.Expr)
24 | T = TypeVar("T")
25 |
26 | if TYPE_CHECKING:
27 | # Because there are methods of our class objects below called `sympy` that
28 | # implicitly override the `sympy` name in the global namespace while defining other
29 | # methods, our type checker needs to know that we're referring to the sympy module
30 | # in our type annotations.
31 | import sympy as sympy_
32 |
33 |
34 | def _reduce(fn: Callable[..., T]) -> Callable[..., T]:
35 | def fn_(*args: Any) -> T:
36 | return ft.reduce(fn, args)
37 |
38 | return fn_
39 |
40 |
41 | def _I(*args: Any) -> torch.Tensor:
42 | return torch.tensor(1j)
43 |
44 |
45 | _global_func_lookup: Dict[
46 | Union[Type[sympy.Basic], Callable[..., Any]], Callable[..., torch.Tensor]
47 | ] = {
48 | sympy.Mul: _reduce(torch.mul),
49 | sympy.Add: _reduce(torch.add),
50 | sympy.div: torch.div,
51 | sympy.Abs: torch.abs,
52 | sympy.sign: torch.sign,
53 | # Note: May raise error for ints.
54 | sympy.ceiling: torch.ceil,
55 | sympy.floor: torch.floor,
56 | sympy.log: torch.log,
57 | sympy.exp: torch.exp,
58 | sympy.sqrt: torch.sqrt,
59 | sympy.cos: torch.cos,
60 | sympy.acos: torch.acos,
61 | sympy.sin: torch.sin,
62 | sympy.asin: torch.asin,
63 | sympy.tan: torch.tan,
64 | sympy.atan: torch.atan,
65 | sympy.atan2: torch.atan2,
66 | # Note: May give NaN for complex results.
67 | sympy.cosh: torch.cosh,
68 | sympy.acosh: torch.acosh,
69 | sympy.sinh: torch.sinh,
70 | sympy.asinh: torch.asinh,
71 | sympy.tanh: torch.tanh,
72 | sympy.atanh: torch.atanh,
73 | sympy.Pow: torch.pow,
74 | sympy.re: torch.real,
75 | sympy.im: torch.imag,
76 | sympy.arg: torch.angle,
77 | # Note: May raise error for ints and complexes
78 | sympy.erf: torch.erf,
79 | sympy.loggamma: torch.lgamma,
80 | sympy.Eq: torch.eq,
81 | sympy.Ne: torch.ne,
82 | sympy.StrictGreaterThan: torch.gt,
83 | sympy.StrictLessThan: torch.lt,
84 | sympy.LessThan: torch.le,
85 | sympy.GreaterThan: torch.ge,
86 | sympy.And: torch.logical_and,
87 | sympy.Or: torch.logical_or,
88 | sympy.Not: torch.logical_not,
89 | sympy.Max: torch.max,
90 | sympy.Min: torch.min,
91 | # Matrices
92 | sympy.MatAdd: torch.add,
93 | sympy.HadamardProduct: torch.mul,
94 | sympy.Trace: torch.trace,
95 | # Note: May raise error for integer matrices.
96 | sympy.Determinant: torch.det,
97 | sympy.core.numbers.ImaginaryUnit: _I,
98 | sympy.conjugate: torch.conj,
99 | }
100 |
101 | number_symbols = [cls for cls in sympy.NumberSymbol.__subclasses__()]
102 |
103 |
104 | def number_symbol_to_torch(symbol: sympy.NumberSymbol, *args: Any) -> torch.Tensor:
105 | return torch.tensor(float(symbol))
106 |
107 |
108 | _global_func_lookup.update(
109 | {s: ft.partial(number_symbol_to_torch, s()) for s in number_symbols}
110 | )
111 |
112 |
113 | class _Node(torch.nn.Module, Generic[ExprType]):
114 | def __init__(
115 | self,
116 | *,
117 | expr: ExprType,
118 | _memodict: Dict[sympy.Basic, torch.nn.Module],
119 | _func_lookup,
120 | **kwargs,
121 | ) -> None:
122 | super().__init__(**kwargs)
123 |
124 | self._sympy_func: Type[ExprType] = expr.func
125 |
126 | self._torch_func: Callable[..., torch.Tensor]
127 | self._args: Union[
128 | torch.nn.ModuleList,
129 | Tuple[Callable[[Dict[str, torch.Tensor]], torch.Tensor], ...],
130 | ]
131 | self._value: Any
132 |
133 | if issubclass(expr.func, sympy.Float):
134 | self._value = torch.nn.Parameter(torch.tensor(float(expr)))
135 | self._torch_func = lambda: self._value
136 | self._args = ()
137 | elif issubclass(expr.func, sympy.Integer):
138 | self._value = torch.tensor(int(expr))
139 | self._torch_func = lambda: self._value
140 | self._args = ()
141 | elif issubclass(expr.func, sympy.Rational):
142 | self._numerator: torch.Tensor
143 | self._denominator: torch.Tensor
144 | assert isinstance(expr, sympy.Rational)
145 | self.register_buffer(
146 | "_numerator", torch.tensor(expr.p, dtype=torch.get_default_dtype())
147 | )
148 | self.register_buffer(
149 | "_denominator", torch.tensor(expr.q, dtype=torch.get_default_dtype())
150 | )
151 | self._torch_func = lambda: self._numerator / self._denominator
152 | self._args = ()
153 | elif issubclass(expr.func, sympy.UnevaluatedExpr):
154 | if len(expr.args) != 1 or not issubclass(expr.args[0].func, sympy.Float):
155 | raise ValueError("UnevaluatedExpr should only be used to wrap floats.")
156 | assert isinstance(expr.args[0], sympy.Float)
157 | self.register_buffer("_value", torch.tensor(float(expr.args[0])))
158 | self._torch_func = lambda: self._value
159 | self._args = ()
160 | elif issubclass(expr.func, sympy.Symbol):
161 | assert isinstance(expr, sympy.Symbol)
162 | self._name = expr.name
163 | self._torch_func = lambda value: value
164 | self._args = ((lambda memodict: memodict[expr.name]),)
165 | else:
166 | self._torch_func = _func_lookup[expr.func]
167 | args: List[torch.nn.Module] = []
168 | for arg in expr.args:
169 | try:
170 | arg_ = _memodict[arg]
171 | except KeyError:
172 | arg_ = type(self)(
173 | expr=arg, # type: ignore
174 | _memodict=_memodict,
175 | _func_lookup=_func_lookup,
176 | **kwargs,
177 | )
178 | _memodict[arg] = arg_
179 | args.append(arg_)
180 | self._args = torch.nn.ModuleList(args)
181 |
182 | def sympy(self, _memodict: Dict[_Node, sympy_.Expr]) -> ExprType:
183 | if issubclass(self._sympy_func, sympy.Float):
184 | assert isinstance(self._value, torch.nn.Parameter)
185 | return self._sympy_func(self._value.item())
186 | elif issubclass(self._sympy_func, sympy.UnevaluatedExpr):
187 | assert isinstance(self._value, torch.Tensor)
188 | return self._sympy_func(self._value.item())
189 | elif issubclass(
190 | self._sympy_func,
191 | (type(sympy.S.NegativeOne), type(sympy.S.One), type(sympy.S.Zero)),
192 | ):
193 | return self._sympy_func()
194 | elif issubclass(self._sympy_func, sympy.Integer):
195 | return self._sympy_func(self._value)
196 | elif issubclass(self._sympy_func, sympy.Rational):
197 | if issubclass(self._sympy_func, type(sympy.S.Half)):
198 | return sympy.S.Half
199 | else:
200 | return self._sympy_func(
201 | self._numerator.item(), self._denominator.item()
202 | )
203 | elif issubclass(self._sympy_func, sympy.Symbol):
204 | return self._sympy_func(self._name)
205 | elif issubclass(self._sympy_func, sympy.core.numbers.ImaginaryUnit):
206 | return sympy.I
207 | elif issubclass(self._sympy_func, sympy.core.numbers.NumberSymbol):
208 | return self._sympy_func()
209 | else:
210 | if issubclass(self._sympy_func, (sympy.Min, sympy.Max)):
211 | evaluate = False
212 | else:
213 | evaluate = True
214 | args = []
215 | for arg in self._args:
216 | assert isinstance(arg, _Node)
217 | try:
218 | arg_ = _memodict[arg]
219 | except KeyError:
220 | arg_ = arg.sympy(_memodict)
221 | _memodict[arg] = arg_
222 | args.append(arg_)
223 | return self._sympy_func(*args, evaluate=evaluate) # type: ignore
224 |
225 | def forward(self, memodict) -> torch.Tensor:
226 | args = []
227 | for arg in self._args:
228 | try:
229 | arg_ = memodict[arg]
230 | except KeyError:
231 | arg_ = arg(memodict)
232 | memodict[arg] = arg_
233 | args.append(arg_)
234 | return self._torch_func(*args)
235 |
236 |
237 | class SymPyModule(torch.nn.Module):
238 | def __init__(self, *, expressions, extra_funcs=None, **kwargs):
239 | super().__init__(**kwargs)
240 |
241 | expressions = tuple(expressions)
242 |
243 | if extra_funcs is None:
244 | extra_funcs = {}
245 | _func_lookup = co.ChainMap(_global_func_lookup, extra_funcs)
246 |
247 | _memodict = {}
248 | self._nodes: Sequence[_Node] = torch.nn.ModuleList( # type: ignore
249 | [
250 | _Node(expr=expr, _memodict=_memodict, _func_lookup=_func_lookup)
251 | for expr in expressions
252 | ]
253 | )
254 | self._expressions_string = str(expressions)
255 |
256 | def __repr__(self):
257 | return f"{type(self).__name__}(expressions={self._expressions_string})"
258 |
259 | def sympy(self) -> List[sympy.Expr]:
260 | _memodict: Dict[_Node, sympy.Expr] = {}
261 | return [node.sympy(_memodict) for node in self._nodes]
262 |
263 | def forward(self, **symbols: Any) -> torch.Tensor:
264 | out = [node(symbols) for node in self._nodes]
265 | out = torch.broadcast_tensors(*out)
266 | return torch.stack(out, dim=-1)
267 |
--------------------------------------------------------------------------------
/tests/test_hide_floats.py:
--------------------------------------------------------------------------------
1 | import sympy
2 |
3 | import sympytorch
4 |
5 |
6 | def test_hide_floats():
7 | x = sympy.Symbol("x")
8 | y = sympy.Symbol("y")
9 | e = sympy.UnevaluatedExpr
10 |
11 | z = 3.0 * x + (4.0 * y + 1.0) ** 2 - 1
12 | z_ = sympytorch.hide_floats(z)
13 | assert z_ == x * e(3.0) - 1 + e(16.0) * (y + e(0.25)) ** 2
14 |
--------------------------------------------------------------------------------
/tests/test_sympymodule.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | import sympy
3 | import torch
4 |
5 | import sympytorch
6 |
7 |
8 | def test_example():
9 | x = sympy.symbols("x_name")
10 | cosx = 1.0 * sympy.cos(x)
11 | sinx = 2.0 * sympy.sin(x)
12 |
13 | mod = sympytorch.SymPyModule(expressions=[cosx, sinx])
14 |
15 | x_ = torch.rand(3)
16 | out = mod(x_name=x_) # out has shape (3, 2)
17 |
18 | assert torch.equal(out[:, 0], x_.cos())
19 | assert torch.equal(out[:, 1], 2 * x_.sin())
20 | assert out.requires_grad # from the two Parameters initialised as 1.0 and 2.0
21 | assert {x.item() for x in mod.parameters()} == {1.0, 2.0}
22 |
23 |
24 | def test_grad():
25 | x = sympy.symbols("x_name")
26 | y = 1.0 * x
27 | mod = sympytorch.SymPyModule(expressions=[y])
28 | out = mod(x_name=torch.ones(()))
29 | out.backward()
30 | with torch.no_grad():
31 | for param in mod.parameters():
32 | param += param.grad
33 | (expr,) = mod.sympy()
34 | assert expr == 2.0 * x
35 |
36 |
37 | def test_reduce():
38 | x, y = sympy.symbols("x y")
39 | z = 2 * x * y
40 | mod = sympytorch.SymPyModule(expressions=[z])
41 | mod(x=torch.rand(2), y=torch.rand(2))
42 |
43 | z = 2 + x + y
44 | mod = sympytorch.SymPyModule(expressions=[z])
45 | mod(x=torch.rand(2), y=torch.rand(2))
46 |
47 |
48 | def test_special_subclasses():
49 | x, y = sympy.symbols("x y")
50 | z = x - 1
51 | w = y * 0
52 | u = sympy.Integer(1)
53 |
54 | mod = sympytorch.SymPyModule(expressions=[z, w, u])
55 | assert mod.sympy() == [x - 1, sympy.Integer(0), sympy.Integer(1)]
56 |
57 |
58 | def test_constants():
59 | x = sympy.symbols("x")
60 | y = 2.0 * x + sympy.UnevaluatedExpr(1.0)
61 | mod = sympytorch.SymPyModule(expressions=[y])
62 | assert mod.sympy() == [y]
63 | assert set(p.item() for p in mod.parameters()) == {2.0}
64 | assert set(b.item() for b in mod.buffers()) == {1.0}
65 |
66 |
67 | def test_custom_function():
68 | x, y = sympy.symbols("x y")
69 | f = sympy.Function("f")
70 | z = x + f(y)
71 | extra_funcs = {f: lambda y_: y_**2}
72 | mod = sympytorch.SymPyModule(expressions=[z], extra_funcs=extra_funcs)
73 | assert mod.sympy() == [z]
74 | assert mod(x=1, y=2) == 1 + 2**2
75 |
76 |
77 | def test_rationals():
78 | xvals = np.random.randn(100)
79 | x = sympy.symbols("x")
80 | y = x * sympy.Rational(2, 7)
81 | mod = sympytorch.SymPyModule(expressions=[y])
82 | mod.to(torch.float64)
83 | assert mod.sympy() == [y], "mod: {}, y:{}".format(mod.sympy(), y)
84 | assert len([p.item() for p in mod.parameters()]) == 0
85 | y_tilde = mod(x=torch.tensor(xvals, dtype=torch.float64))[:, 0]
86 | error = y_tilde.detach().numpy() - xvals * 2 / 7
87 | assert (error**2).mean() < 1e-10, "error:{}".format((error**2).mean())
88 |
89 |
90 | def test_half1():
91 | xvals = np.random.randn(100)
92 | x = sympy.symbols("x")
93 | y = abs(x) ** sympy.S.Half
94 | mod = sympytorch.SymPyModule(expressions=[y])
95 | mod.to(torch.float64)
96 | assert mod.sympy() == [y], "mod: {}, y:{}".format(mod.sympy(), y)
97 | y_tilde = mod(x=torch.tensor(xvals, dtype=torch.float64))[:, 0]
98 | error = y_tilde.detach().numpy() - np.abs(xvals) ** 0.5
99 | assert (error**2).mean() < 1e-10, "error:{}".format((error**2).mean())
100 |
101 |
102 | def test_half2():
103 | xvals = np.random.randn(100)
104 | y = sympy.parse_expr("sqrt(Abs(x))")
105 | mod = sympytorch.SymPyModule(expressions=[y])
106 | mod.to(torch.float64)
107 | assert mod.sympy() == [y], "mod: {}, y:{}".format(mod.sympy(), y)
108 | assert len([p.item() for p in mod.parameters()]) == 0
109 | y_tilde = mod(x=torch.tensor(xvals, dtype=torch.float64))[:, 0]
110 | error = y_tilde.detach().numpy() - np.abs(xvals) ** 0.5
111 | assert (error**2).mean() < 1e-10, "error:{}".format((error**2).mean())
112 |
113 |
114 | def test_constants2():
115 | constants = [
116 | sympy.pi,
117 | sympy.E,
118 | sympy.GoldenRatio,
119 | sympy.TribonacciConstant,
120 | sympy.EulerGamma,
121 | sympy.Catalan,
122 | ]
123 | mod = sympytorch.SymPyModule(expressions=constants)
124 | mod.to(torch.float64)
125 | assert mod.sympy() == constants, "mod: {}, y:{}".format(mod.sympy(), constants)
126 | assert len([p.item() for p in mod.parameters()]) == 0
127 | torch.testing.assert_allclose(mod(), torch.tensor([float(c) for c in constants]))
128 |
129 |
130 | def test_complex():
131 | # Simple complex number handing test
132 | x = sympy.symbols("x")
133 |
134 | complex_func_torch = sympytorch.SymPyModule(
135 | expressions=[
136 | x * sympy.I,
137 | sympy.conjugate(x),
138 | sympy.sqrt(sympy.conjugate(x * sympy.I) * x * sympy.I),
139 | ]
140 | )
141 |
142 | out = complex_func_torch(x=torch.tensor(2.0, dtype=torch.double)).detach().numpy()
143 | assert out[0].item() == 2.0j, "Expected 2j, eval:{}".format(out[0].item())
144 | assert out[1].item() == 2.0, "Expected 2, eval:{}".format(out[1].item())
145 | assert out[2].item() == 2.0, "Expected 2, eval:{}".format(out[2].item())
146 |
147 | # Complex number handling test with complex parameters
148 | out = (
149 | complex_func_torch(x=torch.tensor(2.0j, dtype=torch.complex128))
150 | .detach()
151 | .numpy()
152 | )
153 | assert out[0].item() == -2.0, "Expected -2, eval:{}".format(out[0].item())
154 | assert out[1].item() == -2.0j, "Expected -2j, eval:{}".format(out[1].item())
155 | assert out[2].item() == 2.0, "Expected 2, eval:{}".format(out[2].item())
156 |
157 | # Comparison with numpy using spherical harmonics
158 | theta, phi = sympy.symbols("theta phi")
159 | max_l = 2
160 | m_list = range(-max_l, max_l + 1)
161 |
162 | # spherical harmonics from l=-2 to l=2
163 | func_list = [
164 | sympy.simplify(
165 | sympy.functions.special.spherical_harmonics.Znm(
166 | max_l, m, theta, phi
167 | ).expand(func=True)
168 | ).evalf()
169 | for m in m_list
170 | ]
171 |
172 | # Numpy and Torch based functions
173 | func_list_np = [sympy.lambdify([theta, phi], func, "numpy") for func in func_list]
174 | func_list_torch = sympytorch.SymPyModule(expressions=func_list)
175 |
176 | np_eval = np.array(
177 | list(map(lambda i: func_list_np[i](np.pi / 3, np.pi / 3), np.arange(5)))
178 | )
179 | torch_eval = func_list_torch(
180 | theta=torch.tensor(np.pi / 3, dtype=torch.double),
181 | phi=torch.tensor(np.pi / 3, dtype=torch.double),
182 | )
183 |
184 | # Correctness within single precision
185 | error = np.sum(np.abs(torch_eval.detach().numpy() - np_eval))
186 | assert error < 1e-7, "np v torch complex error:{}".format(error)
187 |
188 |
189 | def test_integers():
190 | m = sympytorch.SymPyModule(expressions=[sympy.core.numbers.Zero()])
191 | assert m() == torch.tensor([0.0])
192 |
193 | m = sympytorch.SymPyModule(expressions=[sympy.core.numbers.One()])
194 | assert m() == torch.tensor([1.0])
195 |
196 | m = sympytorch.SymPyModule(expressions=[sympy.core.numbers.NegativeOne()])
197 | assert m() == torch.tensor([-1.0])
198 |
199 | for i in range(-10, 10):
200 | m = sympytorch.SymPyModule(expressions=[sympy.core.numbers.Integer(i)])
201 | assert m() == torch.tensor([float(i)])
202 |
--------------------------------------------------------------------------------