torchsympy 0.3.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ibrahim H.I. Abushawish
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,163 @@
1
+ Metadata-Version: 2.4
2
+ Name: torchsympy
3
+ Version: 0.3.0
4
+ Summary: TorchSymPy: SymPy-to-Torch transcompilation and GPU-accelerated numerical integration
5
+ Author-email: "Ibrahim H.I. Abushawish" <ibrahim.hamed2701@gmail.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/ibeuler/TorchSymPy
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: Operating System :: OS Independent
10
+ Classifier: Topic :: Scientific/Engineering :: Physics
11
+ Classifier: Topic :: Scientific/Engineering :: Mathematics
12
+ Requires-Python: >=3.8
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Requires-Dist: torch>=2.5.1
16
+ Requires-Dist: sympy>=1.13.1
17
+ Requires-Dist: torchquad>=0.5.0
18
+ Requires-Dist: numpy>=2.4.2
19
+ Requires-Dist: scipy>=1.17.0
20
+ Requires-Dist: loguru>=0.7.3
21
+ Provides-Extra: dev
22
+ Requires-Dist: pytest>=8; extra == "dev"
23
+ Requires-Dist: build>=1; extra == "dev"
24
+ Requires-Dist: twine>=5; extra == "dev"
25
+ Provides-Extra: examples
26
+ Requires-Dist: matplotlib>=3.8; extra == "examples"
27
+ Dynamic: license-file
28
+
29
+ <div align="center">
30
+ <h1>TorchSymPy</h1>
31
+ <p><strong>SymPy-to-Torch Transcompilation for Massively Batched, GPU-Accelerated Numerical Integration</strong></p>
32
+
33
+ [![PyPI - Version](https://img.shields.io/pypi/v/torchsympy)](https://pypi.org/project/torchsympy/)
34
+ [![PyPI - Python Version](https://img.shields.io/pypi/pyversions/torchsympy)](https://pypi.org/project/torchsympy/)
35
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
36
+ </div>
37
+
38
+ ---
39
+
40
+ **TorchSymPy** bridges the gap between SymPy's symbolic manipulation and PyTorch's highly optimized batched tensor operations. You can transcompile symbolic integrals directly into callable PyTorch engines capable of extremely fast, batched evaluation on GPUs and CPUs.
41
+
42
+ *Note: this module was first developed for [libphysics](https://github.com/ferhatpy/libphysics) — then split out into a standalone library to tackle generalized parallel computational bottlenecks.*
43
+
44
+ ---
45
+
46
+ ## Why TorchSymPy?
47
+
48
+ When working with analytical integrals in computational physics or machine learning, researchers often hit a bottleneck:
49
+ 1. **SymPy** is great for exact manipulation but painfully slow (or fails) for heavy numeric evaluation.
50
+ 2. **SciPy** (e.g. `scipy.integrate.nquad`) is highly accurate but inherently sequential and single-threaded.
51
+ 3. **PyTorch** thrives on massively parallel grid evaluations, but writing integrators by hand is tedious.
52
+
53
+ **TorchSymPy** gives you the best of all worlds. You write math in `SymPy`, and TorchSymPy transpiles it into highly optimized `TorchExpr` kernels that run up to **2,700x faster** than `SciPy` by leveraging `torchquad` and massively batched GPU architectures.
54
+
55
+ ## Installation
56
+
57
+ To install the latest stable version from PyPI:
58
+ ```bash
59
+ pip install torchsympy
60
+ ```
61
+
62
+ To install from source (development):
63
+ ```bash
64
+ git clone https://github.com/ibeuler/TorchSymPy.git
65
+ cd TorchSymPy
66
+ pip install -e .
67
+ ```
68
+
69
+ > **Note on PyTorch:** For GPU acceleration, ensure you have a CUDA-compatible `torch` wheel installed (e.g., `torch==2.5.1+cu121`).
70
+
71
+ ## Quickstart
72
+
73
+ The easiest path from a symbolic integral to a batched GPU evaluation:
74
+
75
+ ```python
76
+ import torch
77
+ import torchsympy
78
+ import sympy as sp
79
+
80
+ # 1. Define your integrand symbolically
81
+ x = sp.Symbol("x", real=True)
82
+ p = sp.Symbol("p", real=True)
83
+ expr = sp.Integral(sp.exp(-p * x**2), (x, -sp.oo, sp.oo))
84
+
85
+ # 2. Compile to a TorchSymPy engine
86
+ lt = torchsympy.TorchSymPy()
87
+ texpr = lt.torchify(expr)
88
+
89
+ # 3. Evaluate massively batched parameter grids on accelerators
90
+ p_grid = torch.linspace(0.5, 100.0, 10000, dtype=torch.float64, device="cuda").unsqueeze(-1)
91
+ re, im = texpr.torch_integrate_batched(
92
+ params_values=p_grid,
93
+ method="gauss-legendre",
94
+ N=501, # Quadrature nodes
95
+ device="cuda", # Target accelerator
96
+ dtype=torch.float64,
97
+ chunk_size_params=4096 # Safely chunk massive batches to avoid OOM
98
+ )
99
+
100
+ print(f"Real part shape: {re.shape}") # Output: torch.Size([10000])
101
+ ```
102
+
103
+ ## Core Concepts: Integration Methods
104
+
105
+ Once you compile an expression, `TorchSymPy` provides three execution paths depending on your memory and scaling constraints:
106
+
107
+ ### 1. Batched Path: `torch_integrate_batched()` (Recommended)
108
+ This is the primary workhorse for large parameter sweeps. It automatically handles shape broadcasting, batches execution in chunks to prevent Out-Of-Memory (OOM) errors, and manages device placement. It is the safest and most structured way to evaluate dense multidimensional grids.
109
+
110
+ ### 2. Vectorized Path: `torchquad_integrate_vectorized()`
111
+ This is the raw, broadcasting-first path. It passes unstructured parameter tensors directly into the integrand. You are completely responsible for ensuring that the parameter grids broadcast correctly against the spatial integration domain. While riskier for OOM errors, it can yield slightly higher throughput on specific architectures by eliminating chunking overhead.
112
+
113
+ ### 3. Loop-Driven Path: `torchquad_integrate()`
114
+ This is a simpler, unbatched evaluation method. Instead of projecting the entire parameter space onto the GPU at once, it accepts a simple 1D array of parameter combinations and internally loops through them. Use this when memory is severely constrained, or when you only need to evaluate a handful of distinct parameter points rather than a massive grid sweep.
115
+
116
+ ## Benchmarks: Speed Gains & Accuracy vs. SciPy & SymPy
117
+
118
+ TorchSymPy evaluates parameterized integrals across vast grids immensely faster than traditional methods. In our benchmark suite evaluating a parameterized Damped Cosine $\int_{0}^{\infty} e^{-x} \cos(k x) dx$, we observe huge multi-order speedups on GPUs.
119
+
120
+ The following table demonstrates the inherent trade-off between quadrature resolution ($N$) and accuracy/speed:
121
+
122
+ | Execution | Time per Point | Speedup vs SciPy | Accuracy (vs Analytical) |
123
+ | :--- | :---: | :---: | :---: |
124
+ | **SciPy (nquad)** | 1.664 ms | 1.0x | $\sim 2.90 \times 10^{-9}$ |
125
+ | **TorchSymPy (Vectorized, N=121)** | 0.00048 ms | **3,467x** | $\sim 2.07 \times 10^{-1}$ (Low N) |
126
+ | **TorchSymPy (Batched, N=121)** | 0.00073 ms | **2,279x** | $\sim 2.07 \times 10^{-1}$ (Low N) |
127
+ | **TorchSymPy (Vectorized, N=2001)** | 0.00854 ms | **194x** | $\sim 5.72 \times 10^{-5}$ (Medium N) |
128
+ | **TorchSymPy (Batched, N=2001)** | 0.05164 ms | **32x** | $\sim 5.72 \times 10^{-5}$ (Medium N) |
129
+ | **TorchSymPy (Vectorized, N=5001)** | 0.02589 ms | **64x** | $\sim 2.90 \times 10^{-9}$ (High N) |
130
+ | **TorchSymPy (Batched, N=5001)** | 0.55701 ms | **3.0x** | $\sim 2.90 \times 10^{-9}$ (High N) |
131
+
132
+ *(Benchmarks run on an NVIDIA RTX GPU across a 10,000 parameter grid. `TorchSymPy` converges to parity with SciPy while remaining orders of magnitude faster at standard resolutions).*
133
+
134
+ ### The "Hard Integrals" Problem (Experimental Analytical Check)
135
+
136
+ While `TorchSymPy` achieves numeric parity with `SciPy` for well-behaved integrals (like $\int x^{-x} dx$), evaluating conditionally convergent oscillatory integrals over infinite domains numerically pushes *all* quadrature engines to their breaking points.
137
+
138
+ Consider the famously difficult oscillatory integral:
139
+ $$ \int_0^\infty \frac{\sin(x)}{\sqrt{x^2 + 1}} dx $$
140
+
141
+ The true, analytical exact value (calculated symbolically via SymPy hypergeometric functions) is `0.873084`. However, if we force pure numerical evaluation without symbolic reduction:
142
+
143
+ | Method | Output Value | Absolute Error | Notes |
144
+ | :--- | :---: | :---: | :--- |
145
+ | **SymPy (True Analytical)** | `0.873084` | **0.0** | Solved symbolically via Hypergeometric functions |
146
+ | **SymPy (Pure `evalf()`)** | `-4.000000` | `4.873` | Completely fails convergence natively |
147
+ | **SciPy (`nquad`)** | `1.550175` | `0.677` | Fails with `IntegrationWarning` (Divergent) |
148
+ | **TorchSymPy (`GaussLegendre`)** | `-1.343219` | `2.216` | Breaks due to mapped infinite oscillations |
149
+
150
+ **Takeaway:** `TorchSymPy` provides incredible performance scaling and accurate results matching `SciPy` on standard mapping domains. However, for pathological integrands (like conditionally convergent oscillations at infinity), you should rely on `SymPy`'s exact symbolic analytical integrations *before* attempting numerical grid sweeps.
151
+
152
+ ## Running the Test Suite
153
+
154
+ ```bash
155
+ pytest tests/ -v
156
+ ```
157
+
158
+ ## Examples & Tutorials
159
+
160
+ Check the [`examples/`](examples/) directory for specific physics applications and basic integration usage, including generating Wigner functions.
161
+
162
+ ## License
163
+ Distributed under the MIT License. See `LICENSE` for more information.
@@ -0,0 +1,135 @@
1
+ <div align="center">
2
+ <h1>TorchSymPy</h1>
3
+ <p><strong>SymPy-to-Torch Transcompilation for Massively Batched, GPU-Accelerated Numerical Integration</strong></p>
4
+
5
+ [![PyPI - Version](https://img.shields.io/pypi/v/torchsympy)](https://pypi.org/project/torchsympy/)
6
+ [![PyPI - Python Version](https://img.shields.io/pypi/pyversions/torchsympy)](https://pypi.org/project/torchsympy/)
7
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
8
+ </div>
9
+
10
+ ---
11
+
12
+ **TorchSymPy** bridges the gap between SymPy's symbolic manipulation and PyTorch's highly optimized batched tensor operations. You can transcompile symbolic integrals directly into callable PyTorch engines capable of extremely fast, batched evaluation on GPUs and CPUs.
13
+
14
+ *Note: this module was first developed for [libphysics](https://github.com/ferhatpy/libphysics) — then split out into a standalone library to tackle generalized parallel computational bottlenecks.*
15
+
16
+ ---
17
+
18
+ ## Why TorchSymPy?
19
+
20
+ When working with analytical integrals in computational physics or machine learning, researchers often hit a bottleneck:
21
+ 1. **SymPy** is great for exact manipulation but painfully slow (or fails) for heavy numeric evaluation.
22
+ 2. **SciPy** (e.g. `scipy.integrate.nquad`) is highly accurate but inherently sequential and single-threaded.
23
+ 3. **PyTorch** thrives on massively parallel grid evaluations, but writing integrators by hand is tedious.
24
+
25
+ **TorchSymPy** gives you the best of all worlds. You write math in `SymPy`, and TorchSymPy transpiles it into highly optimized `TorchExpr` kernels that run up to **2,700x faster** than `SciPy` by leveraging `torchquad` and massively batched GPU architectures.
26
+
27
+ ## Installation
28
+
29
+ To install the latest stable version from PyPI:
30
+ ```bash
31
+ pip install torchsympy
32
+ ```
33
+
34
+ To install from source (development):
35
+ ```bash
36
+ git clone https://github.com/ibeuler/TorchSymPy.git
37
+ cd TorchSymPy
38
+ pip install -e .
39
+ ```
40
+
41
+ > **Note on PyTorch:** For GPU acceleration, ensure you have a CUDA-compatible `torch` wheel installed (e.g., `torch==2.5.1+cu121`).
42
+
43
+ ## Quickstart
44
+
45
+ The easiest path from a symbolic integral to a batched GPU evaluation:
46
+
47
+ ```python
48
+ import torch
49
+ import torchsympy
50
+ import sympy as sp
51
+
52
+ # 1. Define your integrand symbolically
53
+ x = sp.Symbol("x", real=True)
54
+ p = sp.Symbol("p", real=True)
55
+ expr = sp.Integral(sp.exp(-p * x**2), (x, -sp.oo, sp.oo))
56
+
57
+ # 2. Compile to a TorchSymPy engine
58
+ lt = torchsympy.TorchSymPy()
59
+ texpr = lt.torchify(expr)
60
+
61
+ # 3. Evaluate massively batched parameter grids on accelerators
62
+ p_grid = torch.linspace(0.5, 100.0, 10000, dtype=torch.float64, device="cuda").unsqueeze(-1)
63
+ re, im = texpr.torch_integrate_batched(
64
+ params_values=p_grid,
65
+ method="gauss-legendre",
66
+ N=501, # Quadrature nodes
67
+ device="cuda", # Target accelerator
68
+ dtype=torch.float64,
69
+ chunk_size_params=4096 # Safely chunk massive batches to avoid OOM
70
+ )
71
+
72
+ print(f"Real part shape: {re.shape}") # Output: torch.Size([10000])
73
+ ```
74
+
75
+ ## Core Concepts: Integration Methods
76
+
77
+ Once you compile an expression, `TorchSymPy` provides three execution paths depending on your memory and scaling constraints:
78
+
79
+ ### 1. Batched Path: `torch_integrate_batched()` (Recommended)
80
+ This is the primary workhorse for large parameter sweeps. It automatically handles shape broadcasting, batches execution in chunks to prevent Out-Of-Memory (OOM) errors, and manages device placement. It is the safest and most structured way to evaluate dense multidimensional grids.
81
+
82
+ ### 2. Vectorized Path: `torchquad_integrate_vectorized()`
83
+ This is the raw, broadcasting-first path. It passes unstructured parameter tensors directly into the integrand. You are completely responsible for ensuring that the parameter grids broadcast correctly against the spatial integration domain. While riskier for OOM errors, it can yield slightly higher throughput on specific architectures by eliminating chunking overhead.
84
+
85
+ ### 3. Loop-Driven Path: `torchquad_integrate()`
86
+ This is a simpler, unbatched evaluation method. Instead of projecting the entire parameter space onto the GPU at once, it accepts a simple 1D array of parameter combinations and internally loops through them. Use this when memory is severely constrained, or when you only need to evaluate a handful of distinct parameter points rather than a massive grid sweep.
87
+
88
+ ## Benchmarks: Speed Gains & Accuracy vs. SciPy & SymPy
89
+
90
+ TorchSymPy evaluates parameterized integrals across vast grids immensely faster than traditional methods. In our benchmark suite evaluating a parameterized Damped Cosine $\int_{0}^{\infty} e^{-x} \cos(k x) dx$, we observe huge multi-order speedups on GPUs.
91
+
92
+ The following table demonstrates the inherent trade-off between quadrature resolution ($N$) and accuracy/speed:
93
+
94
+ | Execution | Time per Point | Speedup vs SciPy | Accuracy (vs Analytical) |
95
+ | :--- | :---: | :---: | :---: |
96
+ | **SciPy (nquad)** | 1.664 ms | 1.0x | $\sim 2.90 \times 10^{-9}$ |
97
+ | **TorchSymPy (Vectorized, N=121)** | 0.00048 ms | **3,467x** | $\sim 2.07 \times 10^{-1}$ (Low N) |
98
+ | **TorchSymPy (Batched, N=121)** | 0.00073 ms | **2,279x** | $\sim 2.07 \times 10^{-1}$ (Low N) |
99
+ | **TorchSymPy (Vectorized, N=2001)** | 0.00854 ms | **194x** | $\sim 5.72 \times 10^{-5}$ (Medium N) |
100
+ | **TorchSymPy (Batched, N=2001)** | 0.05164 ms | **32x** | $\sim 5.72 \times 10^{-5}$ (Medium N) |
101
+ | **TorchSymPy (Vectorized, N=5001)** | 0.02589 ms | **64x** | $\sim 2.90 \times 10^{-9}$ (High N) |
102
+ | **TorchSymPy (Batched, N=5001)** | 0.55701 ms | **3.0x** | $\sim 2.90 \times 10^{-9}$ (High N) |
103
+
104
+ *(Benchmarks run on an NVIDIA RTX GPU across a 10,000 parameter grid. `TorchSymPy` converges to parity with SciPy while remaining orders of magnitude faster at standard resolutions).*
105
+
106
+ ### The "Hard Integrals" Problem (Experimental Analytical Check)
107
+
108
+ While `TorchSymPy` achieves numeric parity with `SciPy` for well-behaved integrals (like $\int x^{-x} dx$), evaluating conditionally convergent oscillatory integrals over infinite domains numerically pushes *all* quadrature engines to their breaking points.
109
+
110
+ Consider the famously difficult oscillatory integral:
111
+ $$ \int_0^\infty \frac{\sin(x)}{\sqrt{x^2 + 1}} dx $$
112
+
113
+ The true, analytical exact value (calculated symbolically via SymPy hypergeometric functions) is `0.873084`. However, if we force pure numerical evaluation without symbolic reduction:
114
+
115
+ | Method | Output Value | Absolute Error | Notes |
116
+ | :--- | :---: | :---: | :--- |
117
+ | **SymPy (True Analytical)** | `0.873084` | **0.0** | Solved symbolically via Hypergeometric functions |
118
+ | **SymPy (Pure `evalf()`)** | `-4.000000` | `4.873` | Completely fails convergence natively |
119
+ | **SciPy (`nquad`)** | `1.550175` | `0.677` | Fails with `IntegrationWarning` (Divergent) |
120
+ | **TorchSymPy (`GaussLegendre`)** | `-1.343219` | `2.216` | Breaks due to mapped infinite oscillations |
121
+
122
+ **Takeaway:** `TorchSymPy` provides incredible performance scaling and accurate results matching `SciPy` on standard mapping domains. However, for pathological integrands (like conditionally convergent oscillations at infinity), you should rely on `SymPy`'s exact symbolic analytical integrations *before* attempting numerical grid sweeps.
123
+
124
+ ## Running the Test Suite
125
+
126
+ ```bash
127
+ pytest tests/ -v
128
+ ```
129
+
130
+ ## Examples & Tutorials
131
+
132
+ Check the [`examples/`](examples/) directory for specific physics applications and basic integration usage, including generating Wigner functions.
133
+
134
+ ## License
135
+ Distributed under the MIT License. See `LICENSE` for more information.
@@ -0,0 +1,49 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [tool.setuptools]
6
+ package-dir = {"" = "src"}
7
+
8
+ [tool.setuptools.packages.find]
9
+ where = ["src"]
10
+
11
+ [project]
12
+ name = "torchsympy"
13
+ version = "0.3.0"
14
+ authors = [
15
+ { name="Ibrahim H.I. Abushawish", email="ibrahim.hamed2701@gmail.com" },
16
+ ]
17
+ description = "TorchSymPy: SymPy-to-Torch transcompilation and GPU-accelerated numerical integration"
18
+ readme = "README.md"
19
+ requires-python = ">=3.8"
20
+ license = "MIT"
21
+ license-files = ["LICENSE"]
22
+ dependencies = [
23
+ "torch>=2.5.1",
24
+ "sympy>=1.13.1",
25
+ "torchquad>=0.5.0",
26
+ "numpy>=2.4.2",
27
+ "scipy>=1.17.0",
28
+ "loguru>=0.7.3",
29
+ ]
30
+
31
+ classifiers = [
32
+ "Programming Language :: Python :: 3",
33
+ "Operating System :: OS Independent",
34
+ "Topic :: Scientific/Engineering :: Physics",
35
+ "Topic :: Scientific/Engineering :: Mathematics",
36
+ ]
37
+
38
+ [project.optional-dependencies]
39
+ dev = [
40
+ "pytest>=8",
41
+ "build>=1",
42
+ "twine>=5",
43
+ ]
44
+ examples = [
45
+ "matplotlib>=3.8",
46
+ ]
47
+
48
+ [project.urls]
49
+ "Homepage" = "https://github.com/ibeuler/TorchSymPy"
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,32 @@
1
+ """torchsympy package.
2
+
3
+ This package is intended to be used as a standalone library:
4
+
5
+ import torchsympy
6
+ lt = torchsympy.TorchSymPy()
7
+
8
+ The implementation lives in :mod:`torchsympy.main` and is re-exported here for
9
+ convenient imports.
10
+ """
11
+
12
+ from .main import (
13
+ TorchSymPy,
14
+ TorchExpr,
15
+ )
16
+
17
+ try:
18
+ from importlib.metadata import version as _pkg_version
19
+
20
+ # Distribution name may differ from import package name.
21
+ try:
22
+ __version__ = _pkg_version("torchsympy")
23
+ except Exception:
24
+ __version__ = _pkg_version("torchsympy")
25
+ except Exception:
26
+ __version__ = "0.3.0"
27
+
28
+ __all__ = [
29
+ "TorchSymPy",
30
+ "TorchExpr",
31
+ "__version__",
32
+ ]