Metadata-Version: 2.4
Name: symjit
Version: 2.29.1
Summary: A lightweight just-in-time (JIT) compiler that translates SymPy and Symbolica expressions into machine code
License-Expression: MIT
Project-URL: Homepage, https://github.com/siravan/symjit
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy
Requires-Dist: sympy
Dynamic: license-file

# Introduction
[Release Notes](CHANGELOG.md)

**SymJit** is a lightweight just-in-time (JIT) compiler that directly translates *SymPy* expressions into machine code without using a separate library such as LLVM. Its main utility is to generate fast numerical functions to feed into various numerical solvers provided by the NumPy/SciPy ecosystem, including numerical integration routines, ordinary differential equation (ODE) solvers, and image filtering functions. It is also able to generate `LowLevelCallable` functions for better coupling to certain fast Scipy numerical functions.

SymJit has two different code-generating backends. The default is a Rust library with minimum external dependencies. The Rust backend generates **AMD64** (also known as x86-64), **ARM64** (also known as aarch64), and 64-bit **RISC-V** (riscv64) machine code on Linux, Windows, and Darwin (MacOS) platforms. The Python backend is written in plain Python, relies solely on the Python standard library and NumPy, is considered obsolete, and is moved to a separate package [pysymjit](https://github.com/siravan/pysymjit).

The following table shows the supported CPU profiles and operating systems. Tier-1 are heavily tested and receive the latest features. Tier-2 are also distributed as binary and pass the test suite; however, they may not have the full features and optimizations. Tier-3 may work but are not routinely tested. 

| **Tiers**  | **Supported OS/CPU**     | **Comments**       |
|--------|------------------------------|--------------------|
| Tier 1 | Linux x86-64-v3              | 256-bit AVX2 SIMD  |
| Tier 1 | Linux x86-64-v4              | 512-bit AVX512 SIMD|
| Tier 1 | MacOS aarch64 (Apple silicon)|                    |
| Tier 1 | Windows x86-64-v3            | 256-bit AVX2 SIMD  |
| Tier 1 | Windows x86-64-v4            | 512-bit AVX512 SIMD|
| Tier 2 | Linux aarch64                | Raspberry Pi 4/5   |
| Tier 2 | Linux riscv64                | GC profile         |
| Tier 2 | Linux x86-64-v2              | SSE (no AVX)       |
| Tier 2 | Windows x86-64-v2            | SSE (no AVX)       |
| Tier 3 | Windows aarch64              |                    |
| Tier 3 | MacOS x64                    |                    |


Symjit is the central package of a [family of JIT compilers](./docs/COMPANIONS.md). SymJit is the JIT backend for the [Symbolica](./docs/SYMBOLICA.md) computer algebra system. 

A low-level interface is exposed through [Composer](./docs/COMPOSER.md) to give the user fine-control over the generated code.

SymJit is primarily a JIT compiler; however, additional binary utilities are available from [symjit-utils](https://github.com/siravan/symjit-utils). These 
utilities include:

* `sjb2wasm`: translates a Symjit intermediate representation (IR) file (`.sjb` file) to WebAssembly.
* `sjb2obj`: compiles an `.sjb` file and saves the compiled kernel as an object file (`.o`), which can be linked into C/C++ programs.
* `sjb2ptx`: translates an `.sjb` file into CUDA PTX format.
* `sjbinfo`: prints the details of an `.sjb` file, useful for debugging and optimization. 
* `rust2sjb`: compiles a limited subset of Rust into `.sjb`. 

# Installing symjit

Installing SymJit from the `conda-forge` channel can be achieved by adding `conda-forge` to your channels with:

```
conda config --add channels conda-forge
conda config --set channel_priority strict
```

Once the `conda-forge` channel has been enabled, SymJit can be installed with `conda`:

```
conda install symjit
```

After installation, you can update to the latest version by:

```
conda update -c conda-forge symjit
```

Another way to install SymJit is to use `mamba`:

```
mamba install symjit
```

Alternatively, you may use `pixi` to install Symjit:

```
pixi add symjit
```

It is possible to list all of the versions of SymJit available on your platform with `conda`:

```
conda search symjit --channel conda-forge
```

or with `mamba`:

```
mamba search symjit --channel conda-forge
```

Alternatively, `mamba repoquery` may provide more information:

```
# Search all versions available on your platform:
mamba repoquery search symjit --channel conda-forge

# List packages depending on `symjit`:
mamba repoquery whoneeds symjit --channel conda-forge

# List dependencies of `symjit`:
mamba repoquery depends symjit --channel conda-forge
```

You can also install symjit from pypi using pip:

```
python -m pip install symjit
```

However, the pip install may not include the correct binary Rust backend for different platforms and the conda-forge install is preferable.

To build Symjit from the source, see [Compilation](./docs/COMPILATION.md).

# Tutorial

## `compile_func`: a fast substitute for `lambdify`

SymJit is invoked by calling different `compile_*` functions (or load a previously compiled function using `load_func`, see below). The most basic is `compile_func`, which behaves similarly to SymPy `lambdify` function. While `lambdify` translates SymPy expressions into regular Python functions, which in turn call numpy functions, `compile_func` returns a callable object `Func`, which is a thin wrapper over the jit code generated by the backends.

A simple example is

```python
import numpy as np
from symjit import compile_func
from sympy import symbols

x, y = symbols('x y')
f = compile_func([x, y], [x+y, x*y])
assert(np.all(f(3, 5) == [8., 15.]))
```

`compile_*` functions support these [operators and functions](./docs/FUNCTIONS.md).

`compile_func` takes two mandatory arguments as `compile_func(states, eqs)`. The first one, `states`, is a list or tuple of SymPy symbols. The second argument, `eqs`, is a list, a tuple, or a single expression. We can think of `states` and `eqs` as corresponding to function signature and body.

If `states` has only one element, it can be passed directly. Similar to SymPy `lambdify`, the output follows the form of the second argument to `compile_func`. Therefore, if `f = compile_func([x, y], [x+y, x*y])`, then `f(2, 3)` returns a list. On the other hand, if `f = compile_func([x, y], (x+y, x*y))`, the output will be `(5, 6)`. The third form is a single scalar, such as if `f = compile_func([x, y], sin(x+y))`.

In addition, `compile_func` accepts a named argument `params`, which is a list of symbolic parameters. The output of `compile_func`, say `f`, is a callable object of type `Func`. The signature of `f` is `f(x_1,...,x_n,p_1,...,p_m)`, where `x`s are the state variables and `p`s are the parameters. Therefore, `n = len(states)` and `m = len(params)`. For example,

```python
x, y, a = symbols('x y a')
f = compile_func([x, y], [(x+y)**a], params=[a])
assert(np.all(f(3., 5., 2.) == [64.]))  # 2. is the value of parameter a
```

By default, `compile_func` uses the Rust backend. However, we can force the use of the Python backend by passing `backend='python'` to `compile_func`. Moreover, if the binary library containing the Rust backend is unavailable or incompatible, symjit automatically switches to the Python backend. Note that the Python backend will be removed in version 3 of Symjit.

`compile_func` helps generate functions to pass to numerical integration (quadrature) routines. The following example is adapted from scipy documentation:

```python
import numpy as np
from scipy.integrate import nquad
from sympy import symbols, exp
from symjit import compile_func

N = 5
t, x = symbols("t x")
f = compile_func([t, x], exp(-t*x)/t**N)

sol = nquad(f, [[1, np.inf], [0, np.inf]])

np.testing.assert_approx_equal(sol[0], 1/N)
```

The output of the returned callable is a numpy array with `dtype='double'`. Note that you can call `f` by passing a list of numbers (say, `f(1.0, 2.0)`) or a list of numpy arrays (for example, `f(np.asarray([1., 2.]), np.asarray([3., 4.]))`. However, broadcasting is not supported. All the parameters should be passed as scalars even if the state variables are arrays. For example,

```python
import numpy as np
import matplotlib.pyplot as plt
from sympy import symbols
from symjit import compile_func

x, sigma = symbols('x sigma')
f = compile_func([x], [exp(-(x-100)**2/(2*sigma**2))], params=[sigma])

t = np.arange(0, 200)
y = f(t, 25.)[0]

plt.plot(t, y)
```

The following example uses the vectorization feature to calculate the [Mandelbrot set](https://en.wikipedia.org/wiki/Mandelbrot_set).

```python
# examples/mandelbrot.py
import numpy as np
import matplotlib.pyplot as plt
from sympy import symbols
from symjit import compile_func

x, y, a, b = symbols("x y a b")

A, B = np.meshgrid(np.arange(-2, 1, 0.002), np.arange(-1.5, 1.5, 0.002))
X = np.zeros_like(A)
Y = np.zeros_like(A)

f = compile_func([a, b, x, y], [x**2 - y**2 + a, 2*x*y + b])

for i in range(20):
    X, Y = f(A, B, X, Y)

Z = np.hypot(X, Y)

plt.imshow(Z < 2)
```

The output is:

![Mandelbrot](./figures/mandelbrot.png)

## Complex Numbers

Symjit supports complex numbers by passing `dtype = "complex128"` to `compile` functions:

```python
import numpy as np
from symjit import compile_func
from sympy import symbols

x, y = symbols('x y')
f = compile_func([x, y], [x+y, x*y], dtype = "complex128")
assert(np.all(f(1 + 2j, 3 - 1j) == [4+1j, 5+5j]))

f = compile_func([x, y], sin(x) + y*sinh(x*y), dtype="complex128")  # fast function
assert(f(2, 1j) == 0)
```

## Optimization

The Rust backend supports different optimization methods, which can be controlled using `compile_func` arguments. See [Optimization](./docs/OPTIMIZATION.md) for details.

## `compile_ode`: to solve ODEs

`compile_ode` returns a callable object (`OdeFunc`) suitable for passing to `scipy.integrate.solve_ivp` (the main Numpy/Scipy ODE solver). It takes three mandatory arguments as `compile_ode(iv, states, odes)`. The first one (`iv`) is a single symbol that specifies the independent variable. The second argument, `states`, is a list of symbols defining the ODE state. The right-hand side of ODE equations is passed as the third argument, `odes.` It is a list of expressions that define the ODE by providing the derivative of each state variable with respect to the independent variable. In addition, similar to `compile_func`, `compile_ode` can accept an optional `params`. For example,

```python
# examples/trig.py
import scipy.integrate
import matplotlib.pyplot as plt
import numpy as np
from sympy import symbols
from symjit import compile_ode

t, x, y = symbols('t x y')
f = compile_ode(t, (x, y), (y, -x))
t_eval=np.arange(0, 10, 0.01)
sol = scipy.integrate.solve_ivp(f, (0, 10), (0.0, 1.0), t_eval=t_eval)

plt.plot(t_eval, sol.y.T)
```

Here, the ODE definition is `x' = y` and `y' = -x`, which means `y" = y`. The solution is `a*sin(t) + b*cos(t)`, where `a` and `b` are determined by the initial values. Given the initial values of 0 and 1 passed as the third argument of `solve_ivp`, the solutions are `sin(t)` and `cos(t)`. We can confirm this by running the code. The output is

![sin/cos functions](./figures/trig.png)

Note that `OdeFunc` conforms to the function form `scipy.integrate.solve_ivp` expects, i.e., it should be called as `f(t, y, *args)`.

The following example is more complicated and showcases the [Lorenz system](https://en.wikipedia.org/wiki/Lorenz_system), an important milestone in the historical development of chaos theory.

```python
import numpy as np
from scipy.integrate import solve_ivp
import matplotlib.pyplot as plt
from sympy import symbols

from symjit import compile_ode

t, x, y, z = symbols("t x y z")
sigma, rho, beta = symbols("sigma rho beta")

ode = (
    sigma * (y - x),
    x * (rho - z) - y,
    x * y - beta * z
    )

f = compile_ode(t, (x, y, z), ode, params=(sigma, rho, beta))

u0 = (1.0, 1.0, 1.0)
p = (10.0, 28.0, 8 / 3)
t_eval = np.arange(0, 100, 0.01)

sol = solve_ivp(f, (0, 100.0), u0, t_eval=t_eval, args=p)

plt.plot(sol.y[0, :], sol.y[2, :])
```

The result is the famous *strange attractor*:

![the strange attractor](./figures/lorenz.png)


## `compile_jac`: calculating Jacobian

The ODE examples discussed in the previous section are non-stiff and easy to solve using explicit methods. However, not all differential equations are so accommodating! Many important equations are stiff and usually require implicit methods. Many implicit ODE solvers use the system's [Jacobian matrix](https://en.wikipedia.org/wiki/Jacobian_matrix_and_determinant) to improve performance.

There are different techniques for calculating the Jacobian. In the last few years, automatic differentiation (AD) methods have gained popularity, working at the abstract syntax tree or lower level. However, if we define our model symbolically using a Computer Algebra System (CAS) such as SymPy, we can calculate the Jacobian by differentiating the source symbolic expressions.

`compile_jac` is the symjit function to calculate the Jacobian of an ODE system. It has the same call signature as `compile_ode,` i.e., it is called `compile_jac(iv, states, odes)` with an optional argument `params.` The return value (of type `JacFunc`) is a callable similar to `OdeFunc`, which returns an n-by-n matrix J, where n is the number of states. The element at the ith row and jth column of J is the derivative of `odes[i]` w.r.t `state[j]` (this is the definition of Jacobian).

For example, we can consider the [Van der Pol oscillator](https://en.wikipedia.org/wiki/Van_der_Pol_oscillator). This system has a control parameter (mu). For small values of mu, the ODE system is not stiff and can easily be solved using explicit methods.

```python
import matplotlib.pyplot as plt
import numpy as np
from scipy.integrate import solve_ivp
from sympy import symbols
from math import sqrt
from symjit import compile_ode, compile_jac

t, x, y, mu = symbols('t x y mu')
ode = [y, mu * ((1 - x*x) * y - x)]

f = compile_ode(t, [x, y], ode, params=[mu])
u0 = [0.0, sqrt(3.0)]
t_eval = np.arange(0, 10.0, 0.01)

sol1 = solve_ivp(f, (0, 10.0), u0, method='RK45', t_eval=t_eval, args=[5.0])

plt.plot(t_eval, sol1.y[0,:])
```

The output is

![non-stiff Van der Pol](./figures/van_der_pol_non_stiff.png)

On the other hand, as mu is increased (for example, to 1e6), the system becomes very stiff. An explicit ODE solver, such as RK45 (Runge-Kutta 4/5), cannot solve this problem. Instead, we need an implicit method, such as the backward differentiation formula (BDF). BDF needs a Jacobian. If one is not provided, it numerically calculates one using the finite-difference method. However, this technique is both inaccurate and computationally intensive. It would be much better to give the solver a closed-form Jacobian. As mentioned above, `calculate_jac` exactly does this.

```python
jac = compile_jac(t, [x, y], ode, params=[mu])
sol2 = solve_ivp(f, (0, 10.0), u0, method='BDF', t_eval=t_eval, args=[1e6], jac=jac)

plot.plot(t_eval, sol2.y[0,:])
```

The output of the stiff system is

![non-stiff Van der Pol](./figures/van_der_pol_stiff.png)

# Advanced Features

## Explicit Looping

SymJit supports construction of explicit loops using `Sum` and `Product` operators. The syntax follows sympy's syntax. For example, we can define the factorial function as

```python
x, y = symbols('x y')
fact = compile_func([x], Product(y, (y, 1, x)))
assert(fact(5) == 120)
```

The looping operators can be nested:

```python
import math 
x, y, k = symbols('x y k')
my_exp = compile_func([x], Sum(x**k / Product(y, (y, 1, k)), (k, 0, 20)))
assert(my_exp(2.0) == math.exp(2.0))
```

Note that for `Sum` and `Product`, the range follows the mathematical convention of including the last expression, i.e., `(x, 1, 3)` means `x` assumes values of `1, 2, 3`.

## Calling External Functions

SymJit also allows calling other simple SymJit or Python functions. Currently, only functions that accept one or two double arguments and return a double result are supported; therefore, only SymJit functions defined as *fast* as allowed, see [Optimization](./docs/OPTIMIZATION.md). To pass a function, we need to define a placeholder symbol using SymPy's `Function` constructor. Then, we pass a dictionary of `Function`s and their definitions as an argument `defuns` to `compile_*` functions. For example, we can rewrite `my_exp` function above as

```python
import math 
from sympy import Function 
from symjit import compile_func

x, y, k = symbols('x y k')
fact = compile_func([x], Product(y, (y, 1, x)))
F = Function('F')
my_exp = compile_func([x], Sum(x**k / F(k), (k, 0, 20)), defuns={F: fact})
assert(my_exp(2.0) == math.exp(2.0))
```

It is also possible to pass Python functions:

```python
def print_res(x, y):
    print(x, ': ', y)
    return x

P = Function('P')
f = compile_func([x], Sum(P(y, sin(y)), (y, 1, x)), defuns={P: print_res})

f(5)    # returns
# 1.0 :  0.8414709848078965
# 2.0 :  0.9092974268256817
# 3.0 :  0.1411200080598672
# 4.0 :  -0.7568024953079282
# 5.0 :  -0.9589242746631385
# 15.0
```

Warning! When `use_threads` option is set to `True` (which is the default), SymJit uses multi-threading for array inputs. Calling a Python function 
in this situation can cause all sort of problems because of the Global Interpreter Lock (GIL). Python 3.14 has removed GIL; therefore, multi-threading
is possible, but still needs extreme caution due to various race conditions. Used correctly, SymJit multi-threading can be useful as a thread-dispatcher; however, preventing race condition is the responsibility of the user.

# Code Generation

All `compile_*` functions accept an optional parameter `ty`, which defines the type of the code to generate. Currently, the possible values are:

* `amd`: generates 64-bit AMD64/x86-64 code. If the processor supports AVX and FMA3, then this is equivalent to passing `amd-avx`; otherwise, it is equal to `amd-sse`.
* `amd-avx`: generates 64-bit AMD64/x86-64 AVX code.
* `amd-sse`: generates 64-bit AMD64/x86-64 SSE code. It requires a minimum SSE2.1 specification, which should be easily fulfilled by all except the most ancient processors (will be deprecated in version 3.0).
* `arm` generates 64-bit ARM64/aarch64 code. This option is mainly tested on Apple Silicon.
* `riscv` generates 64-bit RISC-V code. This option is tested on a computer running XuanTie C910 RISC-V with an RV64GC architecture.
* `bytecode`: this option uses a generic and simple bytecode evaluator as a fallback option in case of unsupported instruction sets. The utility is to test correctness, not speed.
* `native` (**default**): selects the correct instruction set based on the current processor.
* `debug`: deprecated.

Note that `ty='wasm'` is no longer supported in version 2. Also, as discussed above, `compile_*` functions accept a `backend` argument with possible values of `rust` and `python`.

# Saving Models

It is possible to save a compiled function using its `save(file_name)` method. To load such a model, use `load_func(file_name)`:

```python
from sympy import *
from symjit import compile_func, load_func

x, y = symbols('x y')
ext_fun = lambda x, y: x + y**2
e = Function('e')
f = compile_func([x, y], [3 * e(x, y)], defuns={e: ext_fun})
f.save('test.sjb')
g = load_func('test.sjb', defuns={e: ext_fun})
assert(f(2, 3) == g(2, 3))
```

Note that the list of external functions, if not empty, needs to be passed to `load_func`.

## Code Inspection

You can inspect the generate intermediate form (IR) and machine code. Refer to [Inspection](./docs/INSPECTION.md) for details.
