Compare commits

...

40 Commits

Author SHA1 Message Date
b87ea5011c Improved deprecation warning for min/max_range 2025-12-06 08:52:44 -04:00
117e43a984 Standardize root outputs as numpy arrays. 2025-12-06 08:49:35 -04:00
b415df2983 feat: add complex root finding and dynamic CUDA shared memory optimization
Major update extending the library to solve for complex roots and optimizing GPU performance using Shared Memory.

Complex Number Support:
- Implemented `_solve_complex_cuda` and `_solve_complex_numpy` to find roots in the complex plane.
- Added specialized CUDA kernels (`_FITNESS_KERNEL_COMPLEX`, `_FITNESS_KERNEL_COMPLEX_DYNAMIC`) handling complex arithmetic (multiplication/addition) directly on the GPU.
- Updated `Function` class and `set_coeffs` to handle `np.complex128` data types.
- Updated `quadratic_solve` to return complex roots using `cmath`.

CUDA Performance & Optimization:
- Implemented Dynamic Shared Memory kernels (`extern __shared__`) to cache polynomial coefficients on the GPU block, significantly reducing global memory latency.
- Added intelligent fallback logic: The solver checks `MaxSharedMemoryPerBlock`. If the polynomial is too large for Shared Memory, it falls back to the standard Global Memory kernel to prevent crashes.
- Split complex coefficients into separate Real and Imaginary arrays for CUDA kernel efficiency.

Polynomial Logic:
- Added `_strip_leading_zeros` helper to ensure polynomial degree is correctly maintained after arithmetic operations (e.g., preventing `0x^2 + x` from being treated as degree 2).
- Updated `__init__` to allow direct coefficient injection.

GA Algorithm:
- Updated crossover logic to support 2D search space (Real + Imaginary) for complex solutions.
- Refined fitness function to explicitly handle `isinf`/`isnan` for numerical stability.
2025-12-05 13:47:29 -04:00
602269889b Got rid of min/max_range to exclusively use Cauchy's Bound. Updated quadratic solve to handle complex roots. 2025-11-24 15:05:13 -04:00
dca1d66346 Uploaded Technical Paper
Some checks failed
Publish Python Package to PyPI / deploy (push) Has been cancelled
2025-11-24 19:02:33 +00:00
1aa2e8875a Made the default values of min/max_range 0.0
All checks were successful
Run Python Tests / test (3.10) (pull_request) Successful in 14s
Run Python Tests / test (3.12) (pull_request) Successful in 26s
Run Python Tests / test (3.8) (pull_request) Successful in 14s
Publish Python Package to PyPI / deploy (push) Successful in 12s
2025-11-05 18:58:20 -04:00
94723dcb88 feat(Function): Add __eq__ method and improve quadratic_solve stability
All checks were successful
Run Python Tests / test (3.10) (pull_request) Successful in 13s
Run Python Tests / test (3.12) (pull_request) Successful in 12s
Run Python Tests / test (3.8) (pull_request) Successful in 14s
Publish Python Package to PyPI / deploy (push) Successful in 13s
Implements two features for the Function class:

1.  Adds the `__eq__` operator (`==`) to allow for logical comparison of two Function objects based on their coefficients.
2.  Replaces the standard quadratic formula with a numerically stable version in `quadratic_solve` to prevent "catastrophic cancellation" errors and improve accuracy.
2025-11-02 12:50:48 -04:00
f4c5d245e4 fix(ga): Derivative of a constant now returns 0 instead of a throwing an error
All checks were successful
Run Python Tests / test (3.12) (pull_request) Successful in 24s
Run Python Tests / test (3.10) (pull_request) Successful in 30s
Run Python Tests / test (3.8) (pull_request) Successful in 22s
Publish Python Package to PyPI / deploy (push) Successful in 20s
2025-10-31 11:17:29 -04:00
b7ea6c2e23 Added root_precision warning 2025-10-31 11:08:02 -04:00
9d967210fa feat(ga): Overhaul GA for multi-root robustness and CPU performance
All checks were successful
Run Python Tests / test (3.12) (pull_request) Successful in 34s
Run Python Tests / test (3.8) (pull_request) Successful in 35s
Run Python Tests / test (3.10) (pull_request) Successful in 3m8s
Publish Python Package to PyPI / deploy (push) Successful in 12s
### 🚀 Performance (CPU)
* Replaces `np.polyval` with a parallel Numba JIT function (`_calculate_ranks_numba`).
* Replaces $O(N \log N)$ `np.argsort` with $O(N)$ `np.argpartition` in the GA loop.
* Adds `numba` as a core dependency.

### 🧠 Robustness (Algorithm)
* Implements Blend Crossover (BLX-$\alpha$) for better, extrapolative exploration.
* Uses a hybrid selection model (top X% for crossover, 100% for mutation) to preserve root niches.
* Adds `selection_percentile` and `blend_alpha` to `GA_Options` for tuning.
2025-10-30 11:31:00 -04:00
1318006959 v0.5.1-dev (#20)
All checks were successful
Publish Python Package to PyPI / deploy (push) Successful in 56s
Reviewed-on: #20
Co-authored-by: Jonathan Rampersad <rampersad.jonathan@gmail.com>
Co-committed-by: Jonathan Rampersad <rampersad.jonathan@gmail.com>
2025-10-28 15:42:34 +00:00
2d8c8a09e3 Update README.md
Some checks failed
Publish Python Package to PyPI / deploy (push) Has been cancelled
2025-10-27 21:00:30 +00:00
4e46c11f83 feat(ga): Implement quality filtering and precision-based clustering (#19)
All checks were successful
Publish Python Package to PyPI / deploy (push) Successful in 12s
The previous GA logic was returning the "top N" solutions, which led to test failures when the algorithm correctly converged on only one of all possible roots (e.g., returning 1000 variations of -1.0).

This commit fixes the root-finding logic to correctly identify and return *all* unique, high-quality roots:

1.  **feat(api):** Adds `root_precision` to `GA_Options`. This new parameter (default: 5) allows the user to control the number of decimal places for clustering unique roots.

2.  **fix(ga):** Replaces the flawed "top N" logic in both `_solve_x_numpy` and `_solve_x_cuda`. The new process is:
    * Dynamically sets a `quality_threshold` based on the user's `root_precision` (e.g., `precision=5` requires a rank > `1e6`).
    * Filters the *entire* final population for all solutions that meet this quality threshold.
    * Rounds these high-quality solutions to `root_precision`.
    * Returns only the `np.unique()` results.

This ensures the solver returns all distinct roots that meet the accuracy requirements, rather than just the top N variations of a single root.

Reviewed-on: #19
Co-authored-by: Jonathan Rampersad <rampersad.jonathan@gmail.com>
Co-committed-by: Jonathan Rampersad <rampersad.jonathan@gmail.com>
2025-10-27 19:26:50 +00:00
962eab5af7 feat(ga): Implement Cauchy's bound for automatic root range detection
All checks were successful
Run Python Tests / test (3.12) (pull_request) Successful in 10s
Run Python Tests / test (3.10) (pull_request) Successful in 17s
Run Python Tests / test (3.8) (pull_request) Successful in 10s
Publish Python Package to PyPI / deploy (push) Successful in 12s
The previous benchmark results showed that the GA was failing to find accurate roots (high MAE) for many polynomials. This was because the fixed default search range ([-100, 100]) was often incorrect, and the GA was searching in the wrong place.

This commit introduces a significantly more robust solution:

1.  Adds a `_get_cauchy_bound` helper function to mathematically calculate a search radius that is guaranteed to contain all real roots.

2.  Updates `_solve_x_numpy` and `_solve_x_cuda` with new logic:
    * If the user provides a *custom* `min_range` or `max_range`, we treat them as an expert and use their specified range.
    * If the user is using the *default* range, we silently discard it and use the smarter, automatically-calculated Cauchy bound instead.

This provides the best of both worlds: a powerful, smart default for most users and an "expert override" for those who need to fine-tune the search area.
2025-10-27 14:33:12 -04:00
7c75000637 fix(ga): Suppress divide-by-zero warning in NumPy solver
All checks were successful
Publish Python Package to PyPI / deploy (push) Successful in 18s
Run Python Tests / test (3.12) (pull_request) Successful in 12s
Run Python Tests / test (3.10) (pull_request) Successful in 17s
Run Python Tests / test (3.8) (pull_request) Successful in 10s
The `_solve_x_numpy` method was correctly using `np.where(error == 0, ...)` to handle perfect roots. However, NumPy eagerly calculates `1.0 / error` for the entire array before applying the `where` condition, which was causing a `RuntimeWarning: divide by zero` when a perfect root was found.

This warning was harmless but created unnecessary console noise during testing and use.

This commit wraps the `ranks = ...` assignments in a `with np.errstate(divide='ignore'):` block to silence this specific, expected warning. The CUDA kernel is unaffected as its ternary operator already prevents this calculation.
2025-10-27 12:25:54 -04:00
c3b3513e79 feat(ga, api): Implement advanced GA strategy and refactor API for v0.4.0 (#16)
All checks were successful
Publish Python Package to PyPI / deploy (push) Successful in 18s
This commit introduces a major enhancement to the genetic algorithm's convergence logic and refactors key parts of the API for better clarity and usability.

- **feat(ga):** Re-implements the GA solver (CPU & CUDA) to use a more robust strategy based on Elitism, Crossover, and Mutation. This replaces the previous, less efficient model and is designed to significantly improve accuracy and convergence speed.

- **feat(api):** Updates `GA_Options` to expose the new GA strategy parameters:
    - Renames `mutation_percentage` to `mutation_strength` for clarity.
    - Adds `elite_ratio`, `crossover_ratio`, and `mutation_ratio`.
    - Includes a `__post_init__` validator to ensure ratios are valid.

- **refactor(api):** Moves `quadratic_solve` from a standalone function to a method of the `Function` class (`f1.quadratic_solve()`). This provides a cleaner, more object-oriented API.

- **docs:** Updates the README, `GA_Options` doc page, and `quadratic_solve` doc page to reflect all API changes, new parameters, and updated usage examples.

- **chore:** Bumps version to 0.4.0.

Reviewed-on: #16
Co-authored-by: Jonathan Rampersad <rampersad.jonathan@gmail.com>
Co-committed-by: Jonathan Rampersad <rampersad.jonathan@gmail.com>
2025-10-27 14:20:56 +00:00
0536003dce Update README.md
Some checks failed
Publish Python Package to PyPI / deploy (push) Has been cancelled
2025-06-30 15:39:47 +00:00
bb89149930 Update .all-contributorsrc
Some checks failed
Publish Python Package to PyPI / deploy (push) Has been cancelled
2025-06-30 15:38:24 +00:00
6596c2df99 typo fix
All checks were successful
Publish Python Package to PyPI / deploy (push) Successful in 14s
2025-06-19 18:00:29 +00:00
24337cea48 Updated Project urls
Some checks failed
Run Python Tests / test (3.12) (pull_request) Successful in 10s
Run Python Tests / test (3.10) (pull_request) Successful in 14s
Run Python Tests / test (3.8) (pull_request) Successful in 10s
Publish Python Package to PyPI / deploy (push) Failing after 14s
Signed-off-by: Jonathan Rampersad <jonathan@jono-rams.work>
2025-06-19 17:58:50 +00:00
ee18cc9e59 Added Branding (#14)
All checks were successful
Publish Python Package to PyPI / deploy (push) Successful in 19s
Reviewed-on: #14
2025-06-19 17:54:07 +00:00
ce464cffd4 FEAT: Added support for float coefficients (#13)
All checks were successful
Publish Python Package to PyPI / deploy (push) Successful in 13s
Reviewed-on: #13
Co-authored-by: Jonathan Rampersad <rampersad.jonathan@gmail.com>
Co-committed-by: Jonathan Rampersad <rampersad.jonathan@gmail.com>
2025-06-18 13:20:18 +00:00
c94d08498d Edited README to advise of function * function multiplication being available (#12)
All checks were successful
Publish Python Package to PyPI / deploy (push) Successful in 17s
Reviewed-on: #12
2025-06-18 12:55:37 +00:00
3aad9efb61 Merge pull request 'readme-patch' (#11) from readme-patch into main
All checks were successful
Publish Python Package to PyPI / deploy (push) Successful in 17s
Reviewed-on: #11
2025-06-17 18:37:50 +00:00
32d6cfeeea Update pyproject.toml
All checks were successful
Run Python Tests / test (3.12) (pull_request) Successful in 9s
Run Python Tests / test (3.10) (pull_request) Successful in 13s
Run Python Tests / test (3.8) (pull_request) Successful in 9s
2025-06-17 18:37:33 +00:00
8d6fe7aca0 Update README.md
Signed-off-by: Jonathan Rampersad <jonathan@jono-rams.work>
2025-06-17 18:37:17 +00:00
7927845f17 Merge pull request 'v0.2.0' (#10) from v0.2.0-dev into main
All checks were successful
Publish Python Package to PyPI / deploy (push) Successful in 13s
Reviewed-on: #10
2025-06-17 18:36:25 +00:00
ac591f49ec docs: Added documentation for nth_derivative function
All checks were successful
Run Python Tests / test (3.12) (pull_request) Successful in 10s
Run Python Tests / test (3.10) (pull_request) Successful in 13s
Run Python Tests / test (3.8) (pull_request) Successful in 10s
2025-06-17 14:35:03 -04:00
ec97aefee1 feat: Added nth derivative showcase in __main__ 2025-06-17 14:34:16 -04:00
d27497488f fix: differential in README.md renamed to derivative 2025-06-17 14:30:40 -04:00
41daf4f7e0 Remove CONTRIBUTORS.md 2025-06-17 14:30:11 -04:00
36f51ca67e fix: Typo in test
All checks were successful
Run Python Tests / test (3.12) (pull_request) Successful in 11s
Run Python Tests / test (3.10) (pull_request) Successful in 13s
Run Python Tests / test (3.8) (pull_request) Successful in 10s
2025-06-17 14:27:53 -04:00
25f20a4db2 v0.2.0
Some checks failed
Run Python Tests / test (3.12) (pull_request) Failing after 11s
Run Python Tests / test (3.10) (pull_request) Failing after 15s
Run Python Tests / test (3.8) (pull_request) Failing after 11s
2025-06-17 14:26:45 -04:00
ee414ea0dc feat: Added function * function multiplication 2025-06-17 14:26:26 -04:00
8656b558b4 feat: Added alternative degree property to return largest_exponent 2025-06-17 14:12:19 -04:00
30a5189928 fix: multiplying by 0 returns a function object representing 0 2025-06-17 14:08:36 -04:00
3d2c724ad4 feat: Add nth derivative function and fix: typo derivitive->derivative 2025-06-17 14:06:45 -04:00
a761efe28e fix: Renamed differential function to derivitive 2025-06-17 13:45:51 -04:00
GitHub Bridge Bot
1165c03955 Apply patch from GitHub PR #10 by jono-rams
Some checks failed
Run Python Tests / test (3.12) (pull_request) Successful in 9s
Run Python Tests / test (3.10) (pull_request) Successful in 14s
Run Python Tests / test (3.8) (pull_request) Successful in 9s
Publish Python Package to PyPI / deploy (push) Has been cancelled
2025-06-17 16:13:43 +00:00
GitHub Bridge Bot
0a36e955a1 Apply patch from GitHub PR #9 by allcontributors[bot]
Some checks failed
Run Python Tests / test (3.10) (pull_request) Successful in 10s
Run Python Tests / test (3.12) (pull_request) Successful in 12s
Run Python Tests / test (3.8) (pull_request) Successful in 9s
Publish Python Package to PyPI / deploy (push) Has been cancelled
2025-06-17 13:59:47 +00:00
7 changed files with 1332 additions and 199 deletions

View File

@@ -13,6 +13,18 @@
"linkToUsage": true,
"skipCi": true,
"contributors": [
]
{
"login": "jono-rams",
"name": "Jonathan Rampersad",
"avatar_url": "https://avatars.githubusercontent.com/u/29872001?v=4",
"profile": "https://jono-rams.work",
"contributions": [
"maintenance",
"code",
"doc",
"infra"
]
}
],
"commitType": "docs"
}

View File

@@ -1,10 +0,0 @@
## Contributors
<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->
<!-- prettier-ignore-start -->
<!-- markdownlint-disable -->
[![All Contributors](https://img.shields.io/github/all-contributors/jono-rams/PolySolve?color=ee8449&style=flat-square)](#contributors)
<!-- markdownlint-restore -->
<!-- prettier-ignore-end -->
<!-- ALL-CONTRIBUTORS-LIST:END -->

Binary file not shown.

View File

@@ -1,17 +1,20 @@
# polysolve
<p align="center">
<img src="https://i.ibb.co/N22Gx6xq/Poly-Solve-Logo.png" alt="polysolve Logo" width="256">
</p>
[![PyPI version](https://img.shields.io/pypi/v/polysolve.svg)](https://pypi.org/project/polysolve/)
[![PyPI pyversions](https://img.shields.io/pypi/pyversions/polysolve.svg)](https://pypi.org/project/polysolve/)
A Python library for representing, manipulating, and solving polynomial equations using a high-performance genetic algorithm, with optional CUDA/GPU acceleration.
A Python library for representing, manipulating, and solving polynomial equations. Features a high-performance, Numba-accelerated genetic algorithm for CPU, with an optional CUDA/GPU backend for massive-scale parallel solving.
---
## Key Features
* **Create and Manipulate Polynomials**: Easily define polynomials of any degree and perform arithmetic operations like addition, subtraction, and scaling.
* **Genetic Algorithm Solver**: Find approximate real roots for complex polynomials where analytical solutions are difficult or impossible.
* **Numerically Stable Solver**: Makes complex calculations **practical**. Leverage your GPU to power the robust genetic algorithm, solving high-degree polynomials accurately in a reasonable timeframe.
* **Numba Accelerated CPU Solver**: The default genetic algorithm is JIT-compiled with Numba for high-speed CPU performance, right out of the box.
* **CUDA Accelerated**: Leverage NVIDIA GPUs for a massive performance boost when finding roots in large solution spaces.
* **Create and Manipulate Polynomials**: Easily define polynomials of any degree using integer or float coefficients, and perform arithmetic operations like addition, subtraction, multiplication, and scaling.
* **Analytical Solvers**: Includes standard, exact solvers for simple cases (e.g., `quadratic_solve`).
* **Simple API**: Designed to be intuitive and easy to integrate into any project.
@@ -41,11 +44,12 @@ pip install polysolve[cuda12]
Here is a simple example of how to define a quadratic function, find its properties, and solve for its roots.
```python
from polysolve import Function, GA_Options, quadratic_solve
from polysolve import Function, GA_Options
# 1. Define the function f(x) = 2x^2 - 3x - 5
# Coefficients can be integers or floats.
f1 = Function(largest_exponent=2)
f1.set_constants([2, -3, -5])
f1.set_coeffs([2, -3, -5])
print(f"Function f1: {f1}")
# > Function f1: 2x^2 - 3x - 5
@@ -56,18 +60,23 @@ print(f"Value of f1 at x=5 is: {y_val}")
# > Value of f1 at x=5 is: 30.0
# 3. Get the derivative: 4x - 3
df1 = f1.differential()
df1 = f1.derivative()
print(f"Derivative of f1: {df1}")
# > Derivative of f1: 4x - 3
# 4. Find roots analytically using the quadratic formula
# 4. Get the 2nd derivative: 4
ddf1 = f1.nth_derivative(2)
print(f"2nd Derivative of f1: {ddf1}")
# > Derivative of f1: 4
# 5. Find roots analytically using the quadratic formula
# This is exact and fast for degree-2 polynomials.
roots_analytic = quadratic_solve(f1)
roots_analytic = f1.quadratic_solve()
print(f"Analytic roots: {sorted(roots_analytic)}")
# > Analytic roots: [-1.0, 2.5]
# 5. Find roots with the genetic algorithm (CPU)
# This can solve polynomials of any degree.
# 6. Find roots with the genetic algorithm (Numba CPU)
#    This is the default, JIT-compiled CPU solver.
ga_opts = GA_Options(num_of_generations=20)
roots_ga = f1.get_real_roots(ga_opts, use_cuda=False)
print(f"Approximate roots from GA: {roots_ga[:2]}")
@@ -81,6 +90,41 @@ print(f"Approximate roots from GA: {roots_ga[:2]}")
---
## Tuning the Genetic Algorithm
The `GA_Options` class gives you fine-grained control over the genetic algorithm's performance, letting you trade speed for accuracy.
The default options are balanced, but for very complex polynomials, you may want a more exhaustive search.
```python
from polysolve import GA_Options
# Create a config for a deep search, optimized for finding
# *all* real roots (even if they are far apart).
ga_robust_search = GA_Options(
num_of_generations=50, # Run for more generations
data_size=500000, # Use a larger population
# --- Key Tuning Parameters for Multi-Root Finding ---
# Widen the parent pool to 75% to keep more "niches"
# (solution-clouds around different roots) alive.
selection_percentile=0.75,
# Increase the crossover blend factor to 0.75.
# This allows new solutions to be created further
# away from their parents, increasing exploration.
blend_alpha=0.75
)
# Pass the custom options to the solver
roots = f1.get_real_roots(ga_accurate)
```
For a full breakdown of all parameters, including crossover_ratio, mutation_strength, and more, please see [the full GA_Options API Documentation](https://polysolve.jono-rams.work/docs/ga-options-api).
---
## Development & Testing Environment
This project is automatically tested against a specific set of dependencies to ensure stability. Our Continuous Integration (CI) pipeline runs on an environment using **CUDA 12.5** on **Ubuntu 24.04**.
@@ -90,7 +134,6 @@ While the code may work on other configurations, all contributions must pass the
## Contributing
[![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square)](http://makeapullrequest.com)
[![GitHub contributors](https://img.shields.io/github/contributors/jono-rams/PolySolve.svg?style=flat-square)](https://github.com/jono-rams/PolySolve/graphs/contributors)
[![GitHub issues](https://img.shields.io/github/issues/jono-rams/PolySolve.svg?style=flat-square)](https://github.com/jono-rams/PolySolve/issues)
[![GitHub pull requests](https://img.shields.io/github/issues-pr/jono-rams/PolySolve.svg?style=flat-square)](https://github.com/jono-rams/PolySolve/pulls)
@@ -103,6 +146,22 @@ Please read our `CONTRIBUTING.md` file for details on our code of conduct and th
<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->
<!-- prettier-ignore-start -->
<!-- markdownlint-disable -->
<table>
<tbody>
<tr>
<td align="center" valign="top" width="14.28%"><a href="https://jono-rams.work"><img src="https://avatars.githubusercontent.com/u/29872001?v=4?s=100" width="100px;" alt="Jonathan Rampersad"/><br /><sub><b>Jonathan Rampersad</b></sub></a><br /><a href="https://github.com/jono-rams/PolySolve/commits?author=jono-rams" title="Maintenance">🚧</a> <a href="https://github.com/jono-rams/PolySolve/commits?author=jono-rams" title="Code">💻</a> <a href="https://github.com/jono-rams/PolySolve/commits?author=jono-rams" title="Documentation">📖</a> <a href="#infra-jono-rams" title="Infrastructure (Hosting, Build-Tools, etc)">🚇</a></td>
</tr>
</tbody>
<tfoot>
<tr>
<td align="center" size="13px" colspan="7">
<img src="https://raw.githubusercontent.com/all-contributors/all-contributors-cli/1b8533af435da9854653492b1327a23a4dbd0a10/assets/logo-small.svg">
<a href="https://all-contributors.js.org/docs/en/bot/usage">Add your contributions</a>
</img>
</td>
</tr>
</tfoot>
</table>
<!-- markdownlint-restore -->
<!-- prettier-ignore-end -->

View File

@@ -5,7 +5,7 @@ build-backend = "setuptools.build_meta"
[project]
# --- Core Metadata ---
name = "polysolve"
version = "0.1.1"
version = "0.7.0"
authors = [
{ name="Jonathan Rampersad", email="jonathan@jono-rams.work" },
]
@@ -33,7 +33,8 @@ classifiers = [
# --- Dependencies ---
dependencies = [
"numpy>=1.21"
"numpy>=1.21",
"numba"
]
# --- Optional Dependencies (Extras) ---
@@ -42,6 +43,7 @@ cuda12 = ["cupy-cuda12x"]
dev = ["pytest"]
[project.urls]
Homepage = "https://github.com/jono-rams/PolySolve"
"Source Code" = "https://github.com/jono-rams/PolySolve"
Homepage = "https://polysolve.jono-rams.work"
Documentation = "https://polysolve.jono-rams.work/docs"
Repository = "https://github.com/jono-rams/PolySolve"
"Bug Tracker" = "https://github.com/jono-rams/PolySolve/issues"

File diff suppressed because it is too large Load Diff

View File

@@ -1,5 +1,6 @@
import pytest
import numpy as np
import numpy.testing as npt
# Try to import cupy to check for CUDA availability
try:
@@ -8,7 +9,7 @@ try:
except ImportError:
_CUPY_AVAILABLE = False
from polysolve import Function, GA_Options, quadratic_solve
from polysolve import Function, GA_Options
@pytest.fixture
def quadratic_func() -> Function:
@@ -24,6 +25,29 @@ def linear_func() -> Function:
f.set_coeffs([1, 10])
return f
@pytest.fixture
def m_func_1() -> Function:
f = Function(2)
f.set_coeffs([2, 3, 1])
return f
@pytest.fixture
def m_func_2() -> Function:
f = Function(1)
f.set_coeffs([5, -4])
return f
@pytest.fixture
def base_func():
f = Function(2)
f.set_coeffs([1, 2, 3])
return f
@pytest.fixture
def complex_func():
f = Function(2, [1, 2, 2])
return f
# --- Core Functionality Tests ---
def test_solve_y(quadratic_func):
@@ -32,16 +56,23 @@ def test_solve_y(quadratic_func):
assert quadratic_func.solve_y(0) == -5.0
assert quadratic_func.solve_y(-1) == 0.0
def test_differential(quadratic_func):
def test_derivative(quadratic_func):
"""Tests the calculation of the function's derivative."""
derivative = quadratic_func.differential()
derivative = quadratic_func.derivative()
assert derivative.largest_exponent == 1
# The derivative of 2x^2 - 3x - 5 is 4x - 3
assert np.array_equal(derivative.coefficients, [4, -3])
def test_nth_derivative(quadratic_func):
"""Tests the calculation of the function's 2nd derivative."""
derivative = quadratic_func.nth_derivative(2)
assert derivative.largest_exponent == 0
# The derivative of 2x^2 - 3x - 5 is 4x - 3
assert np.array_equal(derivative.coefficients, [4])
def test_quadratic_solve(quadratic_func):
"""Tests the analytical quadratic solver for exact roots."""
roots = quadratic_solve(quadratic_func)
roots = quadratic_func.quadratic_solve()
# Sorting ensures consistent order for comparison
assert sorted(roots) == [-1.0, 2.5]
@@ -61,13 +92,46 @@ def test_subtraction(quadratic_func, linear_func):
assert result.largest_exponent == 2
assert np.array_equal(result.coefficients, [2, -4, -15])
def test_multiplication(linear_func):
def test_scalar_multiplication(linear_func):
"""Tests the multiplication of a Function object by a scalar."""
# (x + 10) * 3 = 3x + 30
result = linear_func * 3
assert result.largest_exponent == 1
assert np.array_equal(result.coefficients, [3, 30])
def test_function_multiplication(m_func_1, m_func_2):
"""Tests the multiplication of two Function objects."""
# (2x^2 + 3x + 1) * (5x -4) = 10x^3 + 7x^2 - 7x -4
result = m_func_1 * m_func_2
assert result.largest_exponent == 3
assert np.array_equal(result.coefficients, [10, 7, -7, -4])
def test_equality(base_func):
"""Tests the __eq__ method for the Function class."""
# 1. Test for equality with a new, identical object
f_identical = Function(2)
f_identical.set_coeffs([1, 2, 3])
assert base_func == f_identical
# 2. Test for inequality (different coefficients)
f_different = Function(2)
f_different.set_coeffs([1, 9, 3])
assert base_func != f_different
# 3. Test for inequality (different degree)
f_diff_degree = Function(1)
f_diff_degree.set_coeffs([1, 2])
assert base_func != f_diff_degree
# 4. Test against a different type
assert base_func != "some_string"
assert base_func != 123
# 5. Test against an uninitialized Function
f_uninitialized = Function(2)
assert base_func != f_uninitialized
# --- Genetic Algorithm Root-Finding Tests ---
def test_get_real_roots_numpy(quadratic_func):
@@ -75,7 +139,7 @@ def test_get_real_roots_numpy(quadratic_func):
Tests that the NumPy-based genetic algorithm approximates the roots correctly.
"""
# Using more generations for higher accuracy in testing
ga_opts = GA_Options(num_of_generations=25, data_size=50000)
ga_opts = GA_Options(num_of_generations=50, data_size=200000, selection_percentile=0.66, root_precision=3)
roots = quadratic_func.get_real_roots(ga_opts, use_cuda=False)
@@ -83,11 +147,7 @@ def test_get_real_roots_numpy(quadratic_func):
# We don't know which order they'll be in, so we check for presence.
expected_roots = np.array([-1.0, 2.5])
# Check that at least one found root is close to -1.0
assert np.any(np.isclose(roots, expected_roots[0], atol=1e-2))
# Check that at least one found root is close to 2.5
assert np.any(np.isclose(roots, expected_roots[1], atol=1e-2))
npt.assert_allclose(np.sort(roots), np.sort(expected_roots), atol=1e-2)
@pytest.mark.skipif(not _CUPY_AVAILABLE, reason="CuPy is not installed, skipping CUDA test.")
@@ -98,13 +158,45 @@ def test_get_real_roots_cuda(quadratic_func):
It will be skipped automatically if CuPy is not available.
"""
ga_opts = GA_Options(num_of_generations=25, data_size=50000)
ga_opts = GA_Options(num_of_generations=50, data_size=200000, selection_percentile=0.66, root_precision=3)
roots = quadratic_func.get_real_roots(ga_opts, use_cuda=True)
expected_roots = np.array([-1.0, 2.5])
# Verify that the CUDA implementation also finds the correct roots within tolerance.
assert np.any(np.isclose(roots, expected_roots[0], atol=1e-2))
assert np.any(np.isclose(roots, expected_roots[1], atol=1e-2))
npt.assert_allclose(np.sort(roots), np.sort(expected_roots), atol=1e-2)
def test_get_roots_numpy(complex_func):
"""
Tests that the NumPy-based genetic algorithm approximates the roots correctly.
"""
# Using more generations for higher accuracy in testing
ga_opts = GA_Options(num_of_generations=50, data_size=200000, selection_percentile=0.66, root_precision=3)
roots = complex_func.get_roots(ga_opts, use_cuda=False)
# Check if the algorithm found values close to the two known roots.
# We don't know which order they'll be in, so we check for presence.
expected_roots = np.array([-1.0-1.j, -1.0+1.j])
npt.assert_allclose(np.sort(roots), np.sort(expected_roots), atol=1e-2)
@pytest.mark.skipif(not _CUPY_AVAILABLE, reason="CuPy is not installed, skipping CUDA test.")
def test_get_roots_cuda(complex_func):
"""
Tests that the CUDA-based genetic algorithm approximates the roots correctly.
This test implicitly verifies that the CUDA kernel is functioning.
It will be skipped automatically if CuPy is not available.
"""
ga_opts = GA_Options(num_of_generations=50, data_size=200000, selection_percentile=0.66, root_precision=3)
roots = complex_func.get_roots(ga_opts, use_cuda=True)
expected_roots = np.array([-1.0-1.j, -1+1.j])
# Verify that the CUDA implementation also finds the correct roots within tolerance.
npt.assert_allclose(np.sort(roots), np.sort(expected_roots), atol=1e-2)