Metadata-Version: 2.4
Name: sandalwood
Version: 0.1.4
Summary: A library for working with Multivariate Taylor Functions.
Author-email: Shashikant Manikonda <manikonda@outlook.com>
License: MIT License
        
        Copyright (c) 2024-2026 Shashikant Manikonda
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
        
Project-URL: Homepage, https://github.com/shashi-manikonda/sandalwood
Project-URL: Documentation, https://sandalwood.readthedocs.io/en/latest/
Project-URL: Bug Tracker, https://github.com/shashi-manikonda/sandalwood/issues
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Scientific/Engineering :: Mathematics
Classifier: Topic :: Software Development :: Libraries
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy
Requires-Dist: pandas
Requires-Dist: tabulate
Provides-Extra: accel
Requires-Dist: numba>=0.57; extra == "accel"
Provides-Extra: torch
Requires-Dist: torch; extra == "torch"
Provides-Extra: demos
Requires-Dist: jupyter; extra == "demos"
Requires-Dist: matplotlib; extra == "demos"
Requires-Dist: tqdm; extra == "demos"
Requires-Dist: ipykernel; extra == "demos"
Requires-Dist: jupytext; extra == "demos"
Requires-Dist: psutil; extra == "demos"
Provides-Extra: test
Requires-Dist: pytest; extra == "test"
Requires-Dist: pytest-cov; extra == "test"
Requires-Dist: matplotlib; extra == "test"
Requires-Dist: nbconvert; extra == "test"
Requires-Dist: ipykernel; extra == "test"
Requires-Dist: jupytext; extra == "test"
Requires-Dist: pandas; extra == "test"
Requires-Dist: torch; extra == "test"
Requires-Dist: ipython; extra == "test"
Requires-Dist: sympy; extra == "test"
Requires-Dist: jupyter; extra == "test"
Requires-Dist: psutil; extra == "test"
Provides-Extra: docs
Requires-Dist: sphinx; extra == "docs"
Requires-Dist: sphinx-rtd-theme; extra == "docs"
Requires-Dist: myst_parser; extra == "docs"
Requires-Dist: sympy; extra == "docs"
Requires-Dist: matplotlib; extra == "docs"
Requires-Dist: pandas; extra == "docs"
Requires-Dist: torch; extra == "docs"
Requires-Dist: ipython; extra == "docs"
Requires-Dist: nbconvert; extra == "docs"
Provides-Extra: dev
Requires-Dist: pytest; extra == "dev"
Requires-Dist: pytest-cov; extra == "dev"
Requires-Dist: matplotlib; extra == "dev"
Requires-Dist: nbconvert; extra == "dev"
Requires-Dist: ipykernel; extra == "dev"
Requires-Dist: torch; extra == "dev"
Requires-Dist: sphinx; extra == "dev"
Requires-Dist: sphinx-rtd-theme; extra == "dev"
Requires-Dist: myst_parser; extra == "dev"
Requires-Dist: sympy; extra == "dev"
Requires-Dist: pre-commit; extra == "dev"
Requires-Dist: ruff; extra == "dev"
Requires-Dist: jupytext; extra == "dev"
Requires-Dist: pandas; extra == "dev"
Requires-Dist: ipython; extra == "dev"
Requires-Dist: mypy; extra == "dev"
Requires-Dist: build; extra == "dev"
Requires-Dist: twine; extra == "dev"
Requires-Dist: jupyter; extra == "dev"
Dynamic: license-file

# sandalwood: Multivariate Taylor Function Library

[![Documentation Status](https://readthedocs.org/projects/sandalwood/badge/?version=latest)](https://sandalwood.readthedocs.io/en/latest/?badge=latest)
[![Run Tests](https://github.com/shashi-manikonda/sandalwood/actions/workflows/test.yml/badge.svg)](https://github.com/shashi-manikonda/sandalwood/actions/workflows/test.yml)
[![PyPI version](https://img.shields.io/pypi/v/sandalwood.svg)](https://pypi.org/project/sandalwood/)
[![Python versions](https://img.shields.io/pypi/pyversions/sandalwood.svg)](https://pypi.org/project/sandalwood/)
[![Downloads](https://img.shields.io/pypi/dm/sandalwood.svg)](https://pypi.org/project/sandalwood/)


A Python library for creating, manipulating, and composing Multivariate Taylor Functions (MTF/mtf), featuring a high-performance hybrid architecture (Python + Numba + COSY Infinity).

![Platform](https://img.shields.io/badge/platform-linux%20%7C%20windows%20%7C%20macos-blue)
![Fortran Compiler](https://img.shields.io/badge/compiler-gfortran%20%7C%20ifx-green)
![Numba Accelerated](https://img.shields.io/badge/accel-numba-orange)

## 🚀 Key Features

*   **Hybrid Backend**: Seamlessly switch between a pure Python/Numba backend for portability and a compiled Fortran (COSY Infinity) backend for maximum performance, utilizing a direct Fortran `POLVAL` memory bridge for high-performance real-valued map compositions.
*   **Arbitrary Order & Dimension**: Calculate derivatives and compositions up to very high orders (e.g., order 20+).
*   **Memory Efficiency**: Robust object pooling (`CosyIndexPool`) and stack-based scoping (`CosyScope`) for ultra-low latency variable allocation.
*   **Parallel Acceleration**: OpenMP-parallelized evaluation and Numba-JIT optimized algebraic kernels.
*   **Seamless Integration**: Full support for NumPy, JSON serialization, and symbolic LaTeX rendering.
*   **Production-Ready Quality**: Tightened type checking (strict `mypy` compliance) and standardized `logging` integration for clean, verbose-controlled embedded usage.

## Installation

The recommended way to install `sandalwood` is from PyPI:

```bash
uv pip install sandalwood
```

### Installation from Source

Alternatively, you can install `sandalwood` directly from the source repository using uv (recommended) or pip.

For standard usage:
```bash
uv pip install .
```

For running demos (includes Jupyter and plotting tools):
```bash
uv pip install .[demos]
```

For developers (includes testing, linting, and documentation tools):
```bash
uv pip install .[dev]
```

## Quick Start

Here's a simple example to get you started with `sandalwood`:

```python
import numpy as np
from sandalwood import mtf
from IPython.display import display

# 1. Initialize global settings (optional but recommended for non-default values)
# If skipped, defaults to max_order=4, max_dimension=3.
mtf.initialize_mtf(max_order=5, max_dimension=2)

# 2. Define symbolic variables
# var(1) corresponds to x, var(2) to y
x = mtf.var(1)
y = mtf.var(2)

# 3. Create a Taylor series expression
# This creates a Taylor series for sin(x) + y^2
f = mtf.sin(x) + y**2

# 4. Evaluate the result at a point
# Let's evaluate f at (x=0.5, y=2.0)
eval_point = np.array([0.5, 2.0])
result = f.eval(eval_point)

print(f"\nf(x, y) = sin(x) + y^2")
print(f"Result of f(0.5, 2.0): {result[0]}")

# For comparison, the exact value is sin(0.5) + 2.0^2
exact_value = np.sin(0.5) + 4.0
print(f"Exact value: {exact_value}")

# You can also view the Taylor series coefficients
print("\nTaylor Series Representation:")
print(f)

print("Symbolic representation of the function:")
display(f.symprint())  # This will print the series in a human-readable format
```
output:
```
Initializing MTF globals with: _MAX_ORDER=5, _MAX_DIMENSION=2
Loading/Precomputing Taylor coefficients up to order 5
Global precomputed coefficients loading/generation complete.
Size of precomputed_coefficients dictionary in memory: 464 bytes, 0.45 KB, 0.00 MB
MTF globals initialized: _MAX_ORDER=5, _MAX_DIMENSION=2, _INITIALIZED=True
Max coefficient count (order=5, nvars=2): 21
Precomputed coefficients loaded and ready for use.

f(x, y) = sin(x) + y^2
Result of f(0.5, 2.0): 4.479427083333333
Exact value: 4.479425538604203

Taylor Series Representation:
          Coefficient  Order Exponents
0  1.000000000000e+00      1    (1, 0)
1  1.000000000000e+00      2    (0, 2)
2 -1.666666666667e-01      3    (3, 0)
3  8.333333333333e-03      5    (5, 0)

Symbolic representation of the function:
```
$\displaystyle 0.00833333 x^{5} - 0.166667 x^{3} + 1.0 x + 1.0 y^{2}$


## JSON Serialization

`sandalwood` supports serializing MTF objects to JSON format, preserving all coefficients and properties (including complex values).

```python
# Serialize to JSON string
json_str = f.to_json()

# Deserialize back to object
f_loaded = mtf.from_json(json_str)
```

## Platform Support

`sandalwood` supports Linux, Windows, and macOS.

### COSY Backend (Side-Load)

Due to licensing restrictions, the proprietary COSY Infinity Fortran source files are not distributed with the Sandalwood library. Sandalwood will default to its high-performance **Python/Numba** JIT backend.

Licensed users can easily enable and compile the COSY Infinity backend on **Windows** or **Linux** post-installation via a single command:

```bash
sandalwood-setup-cosy --src "/path/to/COSY10p2/src" -v
```

This utility automatically detects your Fortran compiler (`ifx` or `gfortran`), resolves linker search paths, patches static memory limits, and compiles the shared bridge directly into your active Sandalwood installation.

For detailed system requirements, compiler options, and step-by-step instructions, see the comprehensive [COSY Installation Guide](docs/INSTALL_COSY.md).

## 🏗️ Architecture

`sandalwood` employs a **Layered Hybrid Strategy** to overcome the "Python tax":

1.  **Symbolic Layer (Python)**: Provides the intuitive `mtf` API and high-level logic.
2.  **Accelerator Layer (Numba)**: JIT-compiles dense algebraic kernels (multiplication, evaluation) into machine code, achieving 5-10x speedups over pure Python.
3.  **HPC Layer (COSY Infinity)**: Bridges to a compiled Fortran core for massive batch operations and map compositions using a **Direct Memory Bridge**.
4.  **Memory Management**: Implements an **Object Pool Pattern** (`CosyIndexPool`) and **Stack-based Scoping** (`CosyScope`) to bridge Python's GC with Fortran's static memory.

## ⚙️ Performance Tuning

Sandalwood allows for fine-grained performance tuning through environment variables:

*   **`SANDALWOOD_COSY_POOL_SIZE`**: (Default: `1024`) Controls the size of the internal COSY index pool. Larger pools reduce allocation latency in massive batch operations but increase static memory overhead.
*   **`SANDALWOOD_NUMBA_PARALLEL`**: (Default: `1`) Set to `1` to enable Numba's multi-threaded execution for algebraic kernels.
*   **`SANDALWOOD_COSY_LMEM`**: Override the default COSY stack size for extremely large calculations.

For advanced architectural details on memory management and high-performance kernels, see the [Documentation](https://sandalwood.readthedocs.io/en/latest/).

## Running Tests

The project uses `pytest` for testing. First, install the test dependencies:

```bash
uv pip install -e .[test]
```

To install all development tools (recommended for contributors):
```bash
uv pip install -e .[dev]
```

Then, run the test suite from the root of the repository:

```bash
pytest
```

### Running Demo Tests

Demo tests are excluded by default to keep the core test suite fast. To run them, use the `-m demo` marker:

*   **Quick Mode (Verification)**: Automatically reduces simulation complexity for fast feedback (~10s).
    ```bash
    pytest -v -m demo tests/test_demos_quick.py
    ```
*   **Full Mode (Simulation)**: Runs demos with their original, high-fidelity parameters.
    ```bash
    SANDALWOOD_TEST_FULL_DEMOS=1 pytest -v -m demo tests/test_demos_quick.py
    ```

## Code Quality & Pre-commit Hooks

This project uses `pre-commit` to automate code quality checks (formatting, linting, and type checking) before each commit.

### Installation & Setup

1. Install development tools:
   ```bash
   uv pip install -e .[dev]
   ```
2. Activate your virtual environment and register the hooks with Git:
   ```bash
   pre-commit install
   ```

### Manual Run

You can run the quality checks manually on all files:
* **Windows (PowerShell)**:
  ```powershell
  # Ensure the environment is active so local hooks find pytest
  & "path/to/.venv/Scripts/Activate.ps1"
  pre-commit run --all-files
  ```
* **WSL / Linux**:
  ```bash
  source .venv/bin/activate
  pre-commit run --all-files
  ```

### Release and Publishing

This project uses Trusted Publishing to automatically build and upload releases to PyPI when a GitHub release is created.

To publish a new version:
1. Update the version number in `pyproject.toml`.
2. Commit and push the version change to `main`.
3. Create and publish a new Release on GitHub. The `Upload Python Package` workflow will trigger automatically to build platform wheels via `cibuildwheel` and upload them directly to PyPI.

## License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

