Metadata-Version: 2.2
Name: coremlmath
Version: 0.2.0
Summary: A multithreaded C++ backend for high-performance Machine Learning Math
Keywords: machine-learning,math,c++,pybind11,multithreading,android,linux,windows
Author-Email: Kartavya Shukla <kartavyashuklahardoi@gmail.com>
License: MIT License
         
         Copyright (c) 2026 Kartavya Shukla
         
         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.
         
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: Microsoft :: Windows
Classifier: Operating System :: POSIX :: Linux
Classifier: Operating System :: POSIX
Classifier: Programming Language :: C++
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Scientific/Engineering :: Mathematics
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Project-URL: Homepage, https://github.com/Novfensec/coremlmath
Project-URL: Repository, https://github.com/Novfensec/coremlmath.git
Project-URL: Bug Tracker, https://github.com/Novfensec/coremlmath/issues
Requires-Python: >=3.11
Requires-Dist: numpy
Description-Content-Type: text/markdown

# CoreMLMath

[![PyPI version](https://img.shields.io/pypi/v/coremlmath.svg)](https://pypi.org/project/coremlmath/)
[![Python versions](https://img.shields.io/pypi/pyversions/coremlmath.svg)](https://pypi.org/project/coremlmath/)
[![License](https://img.shields.io/github/license/novfensec/coremlmath.svg)](https://github.com/novfensec/coremlmath/blob/master/LICENSE)

A multithreaded C++ backend for Machine Learning Math. 

> [!NOTE]
> This library uses OpenMP to bypass the Python GIL and multithread calculations across all available CPU cores. Thanks to [pybind11](https://github.com/pybind/pybind11) and OpenMP for existing in this world.

## Financial Support
[![GitHub Sponsors](https://img.shields.io/github/sponsors/Novfensec?style=for-the-badge&label=Sponsor%20Novfensec&logo=github&color=000000)](https://github.com/sponsors/Novfensec)

[![Donate via](https://img.shields.io/badge/Donate%20via-Wise-9FE870?style=for-the-badge&logo=wise&labelColor=163300)](https://wise.com/pay/business/kartavyashukla)

[![Donate via PayPal](https://img.shields.io/badge/Donate%20via-PayPal-00457C?style=for-the-badge&logo=paypal&logoColor=white)](https://www.paypal.me/KARTAVYASHUKLA)


## Installation

The easiest way to install CoreMLMath is via pip.

> [!TIP]
> The package is installed as `coremlmath` but imported as `cmlmath`.

```sh
pip install coremlmath
```

## Build Instructions

- Clone the repo locally:

    ```sh
    git clone https://github.com/novfensec/coremlmath -b master --single-branch --depth 1
    cd coremlmath
    ```

- Linux:
    ```sh
    sudo apt update
    sudo apt install -y build-essential cmake
    ```

- Windows (Powershell):

    Install the necessary C++ build tools and CMake using Windows Package Manager (`winget`):
    > This has to be done only once.

    ```powershell
    winget install -e --id Microsoft.VisualStudio.BuildTools --override "--passive --wait --add Microsoft.VisualStudio.Workload.VCTools --includeRecommended" --source winget
    winget install -e --id Kitware.CMake --source winget
    ```

- Install pybind11:
    ```sh
    pip install "pybind11[global]" uv
    ```

- Build and install using standard pip:
    ```sh
    pip install .

    ```

    Or using `uv` for isolated, fast builds:

    ```sh
    uv pip install .
    ```

- Build an installable wheel:
    ```sh
    uv build --wheel
    ```

- Build Linux wheels locally using cibuildwheel:
    ```sh
    pip install cibuildwheel
    cibuildwheel --platform linux
    ```

- Build Android wheels locally using cibuildwheel (requires Android SDK):
    ```sh
    pip install cibuildwheel
    cibuildwheel --platform android
    ```


- Build Windows wheels locally using cibuildwheel (requires MSVC):
    ```sh
    pip install cibuildwheel
    cibuildwheel --platform windows
    ```

The repository also includes GitHub Actions workflows under `.github/workflows/` (targeting Python 3.11 through 3.14):
- `wheels-linux.yml`: Compiles `manylinux_2_28` wheels for `x86_64` and `aarch64` (via QEMU) on Ubuntu runners.
- `wheels-android.yml`: Compiles PEP 738 Android wheels for `arm64_v8a` and `x86_64` on Ubuntu runners.
- `publish.yml`: Triggered upon GitHub Release creation (or manual dispatch); builds `sdist`, Linux (`x86_64`, `aarch64`), Android (`arm64_v8a`, `x86_64`), and Windows (`x86_64`) wheels, then automatically publishes them to PyPI using PyPA Trusted Publishing (OIDC).

## Usage

The package expects 2D and 1D NumPy arrays of integers for maximum memory efficiency.

```python
import numpy as np
import cmlmath
import time

print("Generating massive dataset (1,000,000 rows, 500 features)...")
X_raw = np.random.randint(0, 2, size=(1000000, 500), dtype=np.int32)
y_raw = np.random.randint(0, 16, size=(1000000,), dtype=np.int32)

# Enforce C-contiguous (Row-Major) layout in memory. 
# (np.random generates C-contiguous arrays by default, but this guarantees 
# safety in case of Pandas DataFrame or transposed array).
X = np.ascontiguousarray(X_raw, dtype=np.int32)
y = np.ascontiguousarray(y_raw, dtype=np.int32)

print(f"Starting multithreaded C++ calculation using {cmlmath.get_cpu_cores()} cores...")
start = time.time()

info_gains = cmlmath.information_gain(X, y)
gini_gains = cmlmath.gini_gain(X, y)

calc_time = time.time() - start

print(f"Calculated 500 Information and Gini Gains in {calc_time:.4f} seconds.")
print(f"Best feature index to split on (Information Gain): {np.argmax(info_gains)}")
print(f"Best feature index to split on (Gini Gain): {np.argmax(gini_gains)}")
```

### Decision Tree Classifier

`coremlmath` includes a full, scikit-learn compatible `DecisionTreeClassifier` powered directly by the multithreaded OpenMP C++ backend:

<details>
<summary>Showcase</summary>

![entropytree](./examples/decision_tree_entropy.png)
![ginitree](./examples/decision_tree_gini.png)

</details>

```python
from cmlmath import DecisionTreeClassifier

# Initialize classifier (supports criterion="entropy" or "gini")
clf = DecisionTreeClassifier(
    criterion="entropy",
    max_depth=5,
    min_samples_split=2,
    min_samples_leaf=1,
)

# Fit on training data (supports NumPy arrays and Pandas DataFrames)
clf.fit(X_train, y_train)

# Inference and accuracy evaluation
y_pred = clf.predict(X_test)
accuracy = clf.score(X_test, y_test)
probas = clf.predict_proba(X_test)

# Inspect tree structure & feature contributions
clf.print_tree()
print("Feature importances:", clf.feature_importances_)

# Plot tree using matplotlib (or save directly to image)
clf.plot_tree(save_path="decision_tree.png")

# Or using the functional plot_tree API
from cmlmath import plot_tree
import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(16, 9))
plot_tree(clf, ax=ax, filled=True, rounded=True)
plt.show()
```
