API Reference

This section provides comprehensive documentation for all functions, classes, and methods in the HPFRACC library.

Note

RL / Caputo / Grünwald–Letnikov layout

Core Module

Fractional Order Definitions

High-Performance Fractional Calculus Library (hpfracc)

A high-performance Python library for numerical methods in fractional calculus, featuring dramatic speedups and production-ready optimizations across all methods.

This library provides optimized implementations of: - Core fractional derivatives: Caputo, Riemann-Liouville, Grünwald-Letnikov - Advanced methods: Weyl, Marchaud, Hadamard, Reiz-Feller derivatives - Fractional operator extensions (Laplacian, FrFT, Z/Mellin): see hpfracc.algorithms.fractional_operator_methods (not hpfracc.special, which is Γ / binomial / Mittag–Leffler) - GPU acceleration via JAX, PyTorch, and CuPy - Parallel computing via NUMBA

hpfracc.OptimizedRiemannLiouville

alias of RiemannLiouville

hpfracc.OptimizedCaputo

alias of Caputo

hpfracc.OptimizedGrunwaldLetnikov

alias of GrunwaldLetnikov

hpfracc.optimized_riemann_liouville(f, t, alpha, h=None)[source]
class hpfracc.FractionalOrder(alpha, validate=True, method=None)[source]

Bases: object

Represents a fractional order with validation and properties.

The fractional order α can be any real number, but typically we consider 0 < α < 2 for most applications.

Parameters:
__init__(alpha, validate=True, method=None)[source]

Initialize fractional order.

Parameters:
_validate()[source]

Validate the fractional order.

property value: float

Get the fractional order value.

property is_integer: bool

Check if the order is an integer.

property is_fractional: bool

Check if the order is fractional (not integer).

property integer_part: int

Get the integer part of the fractional order.

property fractional_part: float

Get the fractional part of the fractional order.

class hpfracc.WeylDerivative(alpha, parallel_config=None, optimized=True, **kwargs)[source]

Bases: object

Weyl fractional derivative via FFT Convolution with parallelization.

The Weyl derivative is defined as: D^α f(x) = (1/Γ(n-α)) (d/dx)^n ∫_x^∞ (τ-x)^(n-α-1) f(τ) dτ

This implementation uses FFT convolution for efficiency and parallel processing.

Parameters:
__init__(alpha, parallel_config=None, optimized=True, **kwargs)[source]

Initialize Weyl derivative calculator.

Parameters:
compute(f, x, h=None, use_parallel=True)[source]

Compute Weyl derivative using optimized FFT convolution.

Parameters:
Return type:

float | ndarray

_compute_serial(f, x, h)[source]

Serial computation using optimized FFT convolution.

Parameters:
Return type:

ndarray

_compute_parallel(f, x, h)[source]

Parallel computation using chunked processing.

Parameters:
Return type:

ndarray

_process_chunk(chunk_data)[source]

Process a chunk of data for parallel computation.

Parameters:

chunk_data (Tuple[ndarray, ndarray, float])

Return type:

ndarray

class hpfracc.MarchaudDerivative(alpha, parallel_config=None, **kwargs)[source]

Bases: object

Marchaud fractional derivative with Difference Quotient convolution and memory optimization.

The Marchaud derivative is defined as: D^α f(x) = α/Γ(1-α) ∫_0^∞ [f(x) - f(x-τ)] / τ^(α+1) dτ

This implementation uses difference quotient convolution with memory optimization.

Parameters:
__init__(alpha, parallel_config=None, **kwargs)[source]

Initialize Marchaud derivative calculator.

Parameters:
compute(f, x, h=None, use_parallel=True, memory_optimized=True)[source]

Compute Marchaud derivative with memory optimization.

Parameters:
Return type:

float | ndarray

_compute_memory_optimized(f, x, h, use_parallel)[source]

Memory-optimized computation using streaming approach.

Parameters:
Return type:

ndarray

_process_marchaud_chunk(chunk_data)[source]

Process a chunk for Marchaud derivative.

Parameters:

chunk_data (Tuple[ndarray, ndarray, float, int, int])

Return type:

ndarray

_compute_marchaud_segment(f, x, h, start_idx, end_idx)[source]

Compute Marchaud derivative for a segment.

Parameters:
Return type:

ndarray

_compute_standard(f, x, h, use_parallel)[source]

Standard computation without memory optimization.

Parameters:
Return type:

ndarray

class hpfracc.FractionalLaplacian(alpha, *, dimension=1, boundary_conditions=None)[source]

Bases: object

Fractional Laplacian operator implementation.

The fractional Laplacian is defined as: \((-\Delta)^{\alpha/2} f(x) = \mathcal{F}^{-1}\left(|\xi|^{\alpha}\, \mathcal{F}[f](\xi)\right)\)

This is a fundamental operator in fractional PDEs, diffusion processes, and many physical applications.

Parameters:
__init__(alpha, *, dimension=1, boundary_conditions=None)[source]

Initialize fractional Laplacian calculator.

Parameters:
  • order – Fractional order (0 < α < 2)

  • dimension (int) – Spatial dimension

  • boundary_conditions (str | None) – Boundary condition type

  • alpha (float | FractionalOrder)

compute(f, x, h=None, method='spectral')[source]

Compute fractional Laplacian.

Parameters:
  • f (Callable | ndarray) – Function or array of function values

  • x (float | ndarray) – Domain points

  • h (float | None) – Step size (if not provided, inferred from x)

  • method (str) – Computation method (“spectral”, “finite_difference”, “integral”)

Returns:

Fractional Laplacian values

Return type:

float | ndarray

_spectral_method(f, x, h)[source]

Spectral method using FFT.

Parameters:
Return type:

ndarray

_finite_difference_method(f, x, h)[source]

Finite difference approximation.

Parameters:
Return type:

ndarray

compute_numerical(f, x, h=None)[source]

Numerical convenience API used by tests.

Uses finite-difference approximation under the hood.

Parameters:
Return type:

ndarray

_integral_method(f, x, h)[source]

Integral representation method.

Parameters:
Return type:

ndarray

_grunwald_coefficients(N)[source]

Compute Grünwald-Letnikov coefficients.

Parameters:

N (int)

Return type:

ndarray

class hpfracc.FractionalFourierTransform(alpha, *, method='spectral')[source]

Bases: object

Fractional Fourier Transform (FrFT) implementation.

The fractional Fourier transform is a generalization of the Fourier transform that depends on a parameter α. For α = π/2, it reduces to the standard Fourier transform.

FrFT[f](u) = ∫_{-∞}^∞ K_α(x, u) f(x) dx

where K_α is the fractional Fourier kernel.

Parameters:
__init__(alpha, *, method='spectral')[source]

Initialize fractional Fourier transform calculator.

Parameters:
transform(f, x, h=None, method='auto')[source]

Compute fractional Fourier transform.

Parameters:
  • f (Callable | ndarray) – Function or array of function values

  • x (float | ndarray) – Domain points

  • h (float | None) – Step size

  • method (str) – Computation method (“auto”, “discrete”, “spectral”, “fast”)

Returns:

Tuple of (u_domain, transformed_values)

Return type:

Tuple[ndarray, ndarray]

compute(f, x, h=None, method='auto')[source]

Compatibility wrapper returning only transformed values.

Some call sites expect a compute(…) API that returns the transformed values array directly. This method delegates to transform(…) and returns only the values component.

Parameters:
Return type:

ndarray

_discrete_method(f, x, h)[source]

Discrete fractional Fourier transform using optimized FFT-based approach.

Parameters:
Return type:

Tuple[ndarray, ndarray]

_fft_based_method(f, x, u, h)[source]

Fast FFT-based fractional Fourier transform.

Parameters:
Return type:

Tuple[ndarray, ndarray]

_chirp_based_method(f, x, u, h)[source]

Chirp-based algorithm for fractional Fourier transform.

Parameters:
Return type:

Tuple[ndarray, ndarray]

_spectral_method(f, x, h)[source]

Spectral method using decomposition.

Parameters:
Return type:

Tuple[ndarray, ndarray]

compute_numerical(f, x, h=None)[source]

Numerical convenience API returning only values.

Maps to the discrete method for accuracy.

Parameters:
Return type:

ndarray

_compute_transform_matrix(x, u, h)[source]

Compute the discrete fractional Fourier transform matrix.

Parameters:
Return type:

ndarray

_hermite_decomposition(f, x, h)[source]

Decompose function into Hermite-Gaussian basis.

Parameters:
Return type:

ndarray

_hermite_function(n, x)[source]

Compute Hermite-Gaussian function of order n.

Parameters:
Return type:

ndarray

_fractional_hermite(n, u, alpha)[source]

Compute fractional Fourier transform of Hermite function.

Parameters:
Return type:

ndarray

_fast_approximation(f, x, h)[source]

Fast approximation using interpolation between standard FFT and identity.

Parameters:
Return type:

Tuple[ndarray, ndarray]

class hpfracc.RiemannLiouvilleIntegral(order)[source]

Bases: FractionalIntegral

Riemann-Liouville fractional integral.

The Riemann-Liouville fractional integral of order α is defined as:

I^α f(t) = (1/Γ(α)) ∫₀ᵗ (t-τ)^(α-1) f(τ) dτ

where Γ(α) is the gamma function.

Parameters:

order (float | FractionalOrder)

__init__(order)[source]

Initialize fractional integral.

Parameters:
  • order (float | FractionalOrder) – Fractional order (0 < α < 1 for most methods)

  • method – Integration method (“RL”, “Caputo”, “Weyl”, “Hadamard”)

compute(f, x, h=None)[source]

Compute Riemann-Liouville fractional integral (alias for __call__).

Parameters:
  • f (Callable) – Function to integrate

  • x (float | ndarray | torch.Tensor) – Point(s) at which to evaluate the integral

  • h (float)

Returns:

Fractional integral value(s)

Return type:

float | ndarray | torch.Tensor

_coerce_function(f, x_arg)[source]

If f is an array, create an interpolating callable over x grid.

Parameters:
Return type:

Callable

_compute_scalar(f, x)[source]

Compute fractional integral at a scalar point.

Parameters:
Return type:

float

_compute_array_numpy(f, x)[source]

Compute fractional integral for numpy array.

Parameters:
Return type:

ndarray

_compute_array_torch(f, x)[source]

Compute fractional integral for torch tensor.

Parameters:
Return type:

torch.Tensor

class hpfracc.CaputoIntegral(order)[source]

Bases: FractionalIntegral

Caputo fractional integral.

The Caputo fractional integral is related to the Riemann-Liouville integral and is often more suitable for initial value problems.

Supports all fractional orders α ≥ 0: - For 0 < α < 1: Equals Riemann-Liouville integral - For α ≥ 1: Uses decomposition I^α = I^n * I^β where α = n + β

Examples

>>> from hpfracc.core.integrals import CaputoIntegral
>>> def f(x): return x**2
>>> # For 0 < α < 1
>>> integral_05 = CaputoIntegral(0.5)
>>> result = integral_05(f, 1.0)
>>> # For α ≥ 1
>>> integral_15 = CaputoIntegral(1.5)
>>> result = integral_15(f, 1.0)
Parameters:

order (float | FractionalOrder)

__init__(order)[source]

Initialize fractional integral.

Parameters:
  • order (float | FractionalOrder) – Fractional order (0 < α < 1 for most methods)

  • method – Integration method (“RL”, “Caputo”, “Weyl”, “Hadamard”)

_coerce_function(f, x_arg)[source]

If f is an array, create an interpolating callable over x grid.

Parameters:
Return type:

Callable

compute(f, x, h=None)[source]

Alias for __call__; accepts an optional step size h for compatibility.

Parameters:
Return type:

float | ndarray | torch.Tensor

class hpfracc.CaputoFabrizioDerivative(order, **kwargs)[source]

Bases: BaseFractionalDerivative

Caputo-Fabrizio fractional derivative implementation.

Uses the novel implementation from algorithms.

Parameters:

order (float | FractionalOrder)

__init__(order, **kwargs)[source]

Initialize fractional derivative.

Parameters:
  • order (float | FractionalOrder) – Fractional order

  • definition – Mathematical definition

  • use_jax – Whether to use JAX optimizations

  • use_numba – Whether to use NUMBA optimizations

compute(f, x, **kwargs)[source]

Compute the Caputo-Fabrizio fractional derivative.

Parameters:
Return type:

float | ndarray

compute_numerical(f_values, x_values, **kwargs)[source]

Compute the derivative numerically from function values.

Parameters:
Return type:

ndarray

class hpfracc.AtanganaBaleanuDerivative(order, **kwargs)[source]

Bases: BaseFractionalDerivative

Atangana-Baleanu fractional derivative implementation.

Uses the novel implementation from algorithms.

Parameters:

order (float | FractionalOrder)

__init__(order, **kwargs)[source]

Initialize fractional derivative.

Parameters:
  • order (float | FractionalOrder) – Fractional order

  • definition – Mathematical definition

  • use_jax – Whether to use JAX optimizations

  • use_numba – Whether to use NUMBA optimizations

compute(f, x, **kwargs)[source]

Compute the Atangana-Baleanu fractional derivative.

Parameters:
Return type:

float | ndarray

compute_numerical(f_values, x_values, **kwargs)[source]

Compute the derivative numerically from function values.

Parameters:
Return type:

ndarray

hpfracc.RiemannLiouville

alias of RiemannLiouvilleDerivative

class hpfracc.RiemannLiouvilleDerivative(order, **kwargs)[source]

Bases: BaseFractionalDerivative

Riemann-Liouville fractional derivative — adapter over the canonical engine hpfracc.algorithms.derivatives.RiemannLiouville.

Parameters:

order (float | FractionalOrder)

__init__(order, **kwargs)[source]

Initialize fractional derivative.

Parameters:
  • order (float | FractionalOrder) – Fractional order

  • definition – Mathematical definition

  • use_jax – Whether to use JAX optimizations

  • use_numba – Whether to use NUMBA optimizations

compute(f, x, h=None, **kwargs)[source]

Compute the Riemann-Liouville fractional derivative.

Parameters:
Return type:

float | ndarray

compute_numerical(f_values, x_values, **kwargs)[source]

Compute the derivative numerically from function values.

Parameters:
Return type:

ndarray

hpfracc.Caputo

alias of CaputoDerivative

class hpfracc.CaputoDerivative(order, **kwargs)[source]

Bases: BaseFractionalDerivative

Caputo fractional derivative — adapter over the canonical engine hpfracc.algorithms.derivatives.Caputo (single implementation path).

Parameters:

order (float | FractionalOrder)

__init__(order, **kwargs)[source]

Initialize fractional derivative.

Parameters:
  • order (float | FractionalOrder) – Fractional order

  • definition – Mathematical definition

  • use_jax – Whether to use JAX optimizations

  • use_numba – Whether to use NUMBA optimizations

compute(f, x, h=None, **kwargs)[source]

Compute the Caputo fractional derivative.

Parameters:
Return type:

float | ndarray

compute_numerical(f_values, x_values, **kwargs)[source]

Compute the derivative numerically from function values.

Parameters:
Return type:

ndarray

hpfracc.GrunwaldLetnikov

alias of GrunwaldLetnikovDerivative

class hpfracc.GrunwaldLetnikovDerivative(order, **kwargs)[source]

Bases: BaseFractionalDerivative

Grünwald–Letnikov fractional derivative — adapter over the canonical engine hpfracc.algorithms.derivatives.GrunwaldLetnikov.

Parameters:

order (float | FractionalOrder)

__init__(order, **kwargs)[source]

Initialize fractional derivative.

Parameters:
  • order (float | FractionalOrder) – Fractional order

  • definition – Mathematical definition

  • use_jax – Whether to use JAX optimizations

  • use_numba – Whether to use NUMBA optimizations

compute(f, x, h=None, **kwargs)[source]

Compute the Grunwald-Letnikov fractional derivative.

Parameters:
Return type:

float | ndarray

compute_numerical(f_values, x_values, **kwargs)[source]

Compute the derivative numerically from function values.

Parameters:
Return type:

ndarray

class hpfracc.HadamardDerivative(alpha=None, order=None, **kwargs)[source]

Bases: object

Hadamard fractional derivative.

The Hadamard derivative is defined as: D^α f(x) = (1/Γ(n-α)) (x d/dx)^n ∫_1^x (log(x/t))^(n-α-1) f(t) dt/t

This implementation uses logarithmic transformation and efficient quadrature.

Parameters:
__init__(alpha=None, order=None, **kwargs)[source]

Initialize Hadamard derivative calculator.

Accepts both alpha and order for backward compatibility.

Parameters:
compute(f, x, h=None)[source]

Compute Hadamard derivative using logarithmic transformation.

Parameters:
Return type:

float | ndarray

_compute_hadamard(f, x, h)[source]

Compute Hadamard derivative using logarithmic transformation.

Parameters:
Return type:

ndarray

class hpfracc.ReizFellerDerivative(alpha, parallel_config=None, **kwargs)[source]

Bases: object

Reiz-Feller fractional derivative via spectral method.

The Reiz-Feller derivative is defined as: \(D^{\alpha} f(x) = \frac{1}{2\pi} \int_{-\infty}^{\infty} |\xi|^{\alpha} \, \mathcal{F}[f](\xi) \, e^{i\xi x} \, d\xi\)

This implementation uses FFT for spectral computation.

Parameters:
__init__(alpha, parallel_config=None, **kwargs)[source]

Initialize Reiz-Feller derivative calculator.

Parameters:
compute(f, x, h=None, use_parallel=True)[source]

Compute Reiz-Feller derivative using spectral method.

Parameters:
Return type:

float | ndarray

_compute_spectral(f, x, h, use_parallel)[source]

Compute using spectral method with FFT.

Parameters:
Return type:

ndarray

class hpfracc.FractionalZTransform(alpha, *, method='spectral')[source]

Bases: object

Fractional Z-Transform implementation.

The fractional Z-transform is a generalization of the Z-transform that depends on a fractional parameter α. It’s useful for discrete-time systems and digital signal processing.

Z^α[f](z) = Σ_{n=0}^∞ f[n] z^(-αn)

Parameters:
__init__(alpha, *, method='spectral')[source]

Initialize fractional Z-transform calculator.

Parameters:
transform(f, z, method='direct')[source]

Compute fractional Z-transform.

Parameters:
  • f (ndarray) – Discrete signal array

  • z (complex | ndarray) – Complex variable(s) for evaluation

  • method (str) – Computation method (“direct”, “fft”)

Returns:

Transform values

Return type:

complex | ndarray

_direct_method(f, z)[source]

Direct computation of fractional Z-transform.

Parameters:
Return type:

complex | ndarray

_fft_method(f, z)[source]

FFT-based computation for unit circle evaluation.

Parameters:
Return type:

complex | ndarray

inverse_transform(F, z, N, method='contour')[source]

Compute inverse fractional Z-transform.

Parameters:
  • F (complex | ndarray) – Transform values

  • z (complex | ndarray) – Complex variable(s)

  • N (int) – Length of output signal

  • method (str) – Inversion method (“contour”, “residue”)

Returns:

Original signal

Return type:

ndarray

_contour_integration(F, z, N)[source]

Contour integration method for inverse transform.

Parameters:
Return type:

ndarray

_residue_method(F, z, N)[source]

Residue method for inverse transform.

Parameters:
Return type:

ndarray

class hpfracc.FractionalMellinTransform(alpha)[source]

Bases: object

Fractional Mellin Transform implementation.

The fractional Mellin transform is defined as: M_α[f](s) = ∫₀^∞ f(x) x^(s-1+α) dx

This transform is useful for: - Scale-invariant signal processing - Fractional differential equations - Image processing and pattern recognition - Quantum mechanics applications

Parameters:

alpha (float | FractionalOrder)

__init__(alpha)[source]

Initialize fractional Mellin transform calculator.

Parameters:

alpha (float | FractionalOrder)

transform(f, x, s, method='numerical')[source]

Compute fractional Mellin transform.

Parameters:
  • f (Callable | ndarray) – Function or array of function values

  • x (float | ndarray) – Domain points (must be positive)

  • s (complex | ndarray) – Complex variable(s) for transform

  • method (str) – Computation method (“numerical”, “analytical”, “fft”)

Returns:

Transform values

Return type:

complex | ndarray

_numerical_method(f, x, s)[source]

Numerical integration method.

Parameters:
Return type:

complex | ndarray

_analytical_method(f, x, s)[source]

Analytical method for special functions.

Parameters:
Return type:

complex | ndarray

_fft_method(f, x, s)[source]

FFT-based method for efficient computation.

Parameters:
Return type:

complex | ndarray

inverse_transform(F, s, x, method='numerical')[source]

Compute inverse fractional Mellin transform.

Parameters:
Returns:

Original function values

Return type:

ndarray

_inverse_numerical(F, s, x)[source]

Numerical inverse transform.

Parameters:
Return type:

ndarray

_inverse_fft(F, s, x)[source]

FFT-based inverse transform.

Parameters:
Return type:

ndarray

Core Algorithms

Unified fractional derivative engines (canonical implementation path).

RiemannLiouville, Caputo, and GrunwaldLetnikov here are the single dispatching implementations used across the library. Higher-level wrappers in hpfracc.core.fractional_implementations delegate to these classes; names such as OptimizedCaputo in hpfracc.algorithms.optimized_methods are backward-compatible aliases of the same types. ParallelOptimized* in that module are the same engine classes with a parallel-oriented name; compute_numerical is provided on UnifiedFractionalOperator so call sites match adapter-style APIs without duplicating kernels.

hpfracc.algorithms.derivatives._handle_backend_failure(method, backend, error)[source]

Apply fail-fast policy or explicit warning for backend failures.

Parameters:
Return type:

None

class hpfracc.algorithms.derivatives.UnifiedFractionalOperator(order, backend='auto')[source]

Bases: FractionalOperator

Base class for unified operators with backend dispatch.

Parameters:
__init__(order, backend='auto')[source]
Parameters:
compute_numerical(f_values, x_values, **kwargs)[source]

Array-in / array-out entry point; same backend path as compute().

Matches the BaseFractionalDerivative.compute_numerical surface so parallel and engine aliases can be used interchangeably in tests and factory wiring without a second implementation.

Parameters:
Return type:

ndarray

_dispatch(f_arr, h)[source]

Dispatches computation to the appropriate backend implementation.

class hpfracc.algorithms.derivatives.RiemannLiouville(order, backend='auto')[source]

Bases: UnifiedFractionalOperator

Riemann-Liouville fractional derivative. D^α f(t) = (d/dt)^n I^(n-α) f(t)

Parameters:
__init__(order, backend='auto')[source]
Parameters:
compute(f, t, h=None)[source]
Parameters:
Return type:

ndarray

class hpfracc.algorithms.derivatives.Caputo(order, backend='auto')[source]

Bases: UnifiedFractionalOperator

Caputo fractional derivative. D^α f(t) = I^(n-α) f^(n)(t)

Parameters:
compute(f, t, h=None)[source]
Parameters:
Return type:

ndarray

class hpfracc.algorithms.derivatives.GrunwaldLetnikov(order, backend='auto')[source]

Bases: UnifiedFractionalOperator

Grünwald-Letnikov fractional derivative.

Parameters:
compute(f, t, h=None)[source]
Parameters:
Return type:

ndarray

Backward-compatibility shim for legacy Optimized* names (RL / Caputo / GL engines).

The only RL / Caputo / Grünwald–Letnikov implementations are RiemannLiouville, Caputo, and GrunwaldLetnikov. Optimized* and ParallelOptimized* here are thin aliases of those classes.

Deprecated GPU-prefixed wrappers and GPUConfig also live here. Import them from this module only.

Prefer: from hpfracc.algorithms.derivatives import Caputo.

Numerical integrity: symbols that are not implemented do not silently succeed. They raise NotImplementedError with guidance. Reserved APIs may be implemented later.

hpfracc.algorithms.optimized_methods.optimized_riemann_liouville(f, t, alpha, h=None)[source]
hpfracc.algorithms.optimized_methods.optimized_caputo(f, t, alpha, h=None)[source]
hpfracc.algorithms.optimized_methods.optimized_grunwald_letnikov(f, t, alpha, h=None)[source]
class hpfracc.algorithms.optimized_methods.OptimizedFractionalMethods[source]

Bases: object

Reserved unified facade; not implemented — use per-method classes in derivatives.

compute(*args, **kwargs)[source]
Parameters:
Return type:

Any

class hpfracc.algorithms.optimized_methods.ParallelConfig(n_jobs=1, enabled=False, *, num_workers=None, chunk_size=None, **kwargs)[source]

Bases: object

Configuration for optional parallel paths in advanced_methods (e.g. Weyl).

Accepts n_jobs / enabled and common aliases num_workers, chunk_size.

Parameters:
  • n_jobs (int)

  • enabled (bool)

  • num_workers (int | None)

  • chunk_size (int | None)

  • kwargs (Any)

__init__(n_jobs=1, enabled=False, *, num_workers=None, chunk_size=None, **kwargs)[source]
Parameters:
  • n_jobs (int)

  • enabled (bool)

  • num_workers (int | None)

  • chunk_size (int | None)

  • kwargs (Any)

get_optimal_workers()[source]

Return a sensible worker count (minimal implementation for callers/tests).

Return type:

int

class hpfracc.algorithms.optimized_methods.AdvancedFFTMethods(method='spectral', *args, **kwargs)[source]

Bases: object

Reserved for future FFT-focused helpers; not implemented.

Parameters:
__init__(method='spectral', *args, **kwargs)[source]
Parameters:
class hpfracc.algorithms.optimized_methods.L1L2Schemes(scheme='l1', *args, **kwargs)[source]

Bases: object

Reserved for L1/L2 temporal discretization helpers; not implemented.

Parameters:
__init__(scheme='l1', *args, **kwargs)[source]
Parameters:
class hpfracc.algorithms.optimized_methods.ParallelLoadBalancer[source]

Bases: object

Reserved for future parallel chunking; no balancing logic yet.

balance_load(data, num_workers=1)[source]
Parameters:
  • data (Any)

  • num_workers (int)

Return type:

Any

get_chunk_sizes(total, num_workers)[source]
Parameters:
  • total (int)

  • num_workers (int)

Return type:

list

class hpfracc.algorithms.optimized_methods.ParallelOptimizedRiemannLiouville(order, backend='auto')[source]

Bases: RiemannLiouville

Alias for RiemannLiouville.

Parameters:
class hpfracc.algorithms.optimized_methods.ParallelOptimizedCaputo(order, backend='auto')[source]

Bases: Caputo

Alias for Caputo.

Parameters:
class hpfracc.algorithms.optimized_methods.ParallelOptimizedGrunwaldLetnikov(order, backend='auto')[source]

Bases: GrunwaldLetnikov

Alias for GrunwaldLetnikov.

Parameters:
class hpfracc.algorithms.optimized_methods.NumbaOptimizer(*args, **kwargs)[source]

Bases: object

Parameters:
__init__(*args, **kwargs)[source]
Parameters:
class hpfracc.algorithms.optimized_methods.NumbaFractionalKernels(*args, **kwargs)[source]

Bases: object

Parameters:
__init__(*args, **kwargs)[source]
Parameters:
class hpfracc.algorithms.optimized_methods.NumbaParallelManager(*args, **kwargs)[source]

Bases: object

Parameters:
__init__(*args, **kwargs)[source]
Parameters:
hpfracc.algorithms.optimized_methods.benchmark_parallel_vs_serial(*args, **kwargs)[source]
Parameters:
Return type:

Any

hpfracc.algorithms.optimized_methods.optimize_parallel_parameters(*args, **kwargs)[source]
Parameters:
Return type:

Any

hpfracc.algorithms.optimized_methods.memory_efficient_caputo(*args, **kwargs)[source]
Parameters:
Return type:

Any

hpfracc.algorithms.optimized_methods.block_processing_kernel(*args, **kwargs)[source]
Parameters:
Return type:

Any

class hpfracc.algorithms.optimized_methods.GPUConfig(backend='auto', memory_limit=0.8, batch_size=None, multi_gpu=False, monitor_performance=True, fallback_to_cpu=True, device_id=None, use_intelligent_selection=True)[source]

Bases: object

[DEPRECATED] Legacy GPU dispatch config; use backend= on unified engines.

Parameters:
  • backend (str)

  • memory_limit (float)

  • batch_size (int | None)

  • multi_gpu (bool)

  • monitor_performance (bool)

  • fallback_to_cpu (bool)

  • device_id (int | None)

  • use_intelligent_selection (bool)

__init__(backend='auto', memory_limit=0.8, batch_size=None, multi_gpu=False, monitor_performance=True, fallback_to_cpu=True, device_id=None, use_intelligent_selection=True)[source]
Parameters:
  • backend (str)

  • memory_limit (float)

  • batch_size (int | None)

  • multi_gpu (bool)

  • monitor_performance (bool)

  • fallback_to_cpu (bool)

  • device_id (int | None)

  • use_intelligent_selection (bool)

select_backend_for_data(*args, **kwargs)[source]
Parameters:
Return type:

str

class hpfracc.algorithms.optimized_methods._LegacyGPUShim[source]

Bases: object

Map legacy GPUConfig backend strings to unified backend.

class hpfracc.algorithms.optimized_methods.GPUOptimizedRiemannLiouville(alpha, gpu_config=None, *, config=None, batch_size=None)[source]

Bases: RiemannLiouville, _LegacyGPUShim

[DEPRECATED] Use RiemannLiouville(..., backend='jax'|'cuda'|'numpy').

Parameters:
__init__(alpha, gpu_config=None, *, config=None, batch_size=None)[source]
Parameters:
enable_monitoring()[source]
Return type:

None

class hpfracc.algorithms.optimized_methods.GPUOptimizedCaputo(alpha, gpu_config=None, *, config=None, memory_efficient=None)[source]

Bases: Caputo, _LegacyGPUShim

[DEPRECATED] Use Caputo(..., backend='jax'|'cuda'|'numpy').

Parameters:
__init__(alpha, gpu_config=None, *, config=None, memory_efficient=None)[source]
Parameters:
compute(f, t, h=None, method='l1')[source]
Parameters:
Return type:

Any

class hpfracc.algorithms.optimized_methods.GPUOptimizedGrunwaldLetnikov(alpha, gpu_config=None, *, config=None, use_shared_memory=None)[source]

Bases: GrunwaldLetnikov, _LegacyGPUShim

[DEPRECATED] Use GrunwaldLetnikov(..., backend='jax'|'cuda'|'numpy').

Parameters:
__init__(alpha, gpu_config=None, *, config=None, use_shared_memory=None)[source]
Parameters:
class hpfracc.algorithms.optimized_methods.MultiGPUManager(*args, **kwargs)[source]

Bases: object

[DEPRECATED] Stub; not used by unified engines.

Parameters:
__init__(*args, **kwargs)[source]
Parameters:
Return type:

None

class hpfracc.algorithms.optimized_methods.GPUOptimizedMethods(*args, **kwargs)[source]

Bases: object

Legacy placeholder; never implemented. Use engines from derivatives.

Parameters:
__init__(*args, **kwargs)[source]
Parameters:
Return type:

None

hpfracc.algorithms.optimized_methods.gpu_optimized_riemann_liouville(f, alpha, t, h=None, *args, **kwargs)[source]
Parameters:
Return type:

Any

hpfracc.algorithms.optimized_methods.gpu_optimized_caputo(f, alpha, t, h=None, *args, **kwargs)[source]
Parameters:
Return type:

Any

hpfracc.algorithms.optimized_methods.gpu_optimized_grunwald_letnikov(f, alpha, t, h=None, *args, **kwargs)[source]
Parameters:
Return type:

Any

hpfracc.algorithms.optimized_methods.benchmark_gpu_vs_cpu(*args, **kwargs)[source]
Parameters:
Return type:

dict

Fractional Integral Methods

Legacy / alternate API: FFT- and method-switching integral classes used by existing tests and examples. For the canonical integral hierarchy tied to FractionalOrder and core (quad-based __call__ / compute), use hpfracc.core.integrals (RiemannLiouvilleIntegral, CaputoIntegral, …). The direct RL path in this module calls that canonical implementation for α 1e-4; for smaller α a legacy discrete sum avoids quad blow-up on short grids. WeylIntegral here follows the same rule: core quad Weyl for normal α, legacy discrete window for α < 1e-4.

``method`` and ``fft_threshold`` (RL / Caputo): With method="auto", arrays shorter than fft_threshold (default 1000 on RiemannLiouvilleIntegral) use the direct path; longer grids use FFT. For α 1e-4, direct mode calls hpfracc.core.integrals (quad on each prefix of t). If FFT accumulation looks unstable for your grid length or α, pass method="direct" or use core.integrals directly.

``method=”adaptive”``: FFT and direct paths are different discretizations; cross-check uses a scale-aware relative L2 residual. UserWarning signals moderate disagreement (direct is returned); RuntimeWarning is reserved for non-finite FFT output or severe disagreement—see module constants _ADAPTIVE_AGREE_RTOL and _ADAPTIVE_SEVERE_RTOL.

This module provides high-performance implementations of fractional integrals including Riemann-Liouville and Caputo integrals with optimized algorithms.

hpfracc.algorithms.integral_methods._adaptive_fft_direct_relative_l2(a, b)[source]

||a-b||_2 / max(||b||_2, eps) for scale-aware comparison.

Parameters:
Return type:

float

class hpfracc.algorithms.integral_methods.RiemannLiouvilleIntegral(alpha, method='auto', optimize_memory=True, use_jax=False)[source]

Bases: object

Riemann-Liouville fractional integral of order α.

The Riemann-Liouville fractional integral of order α > 0 is defined as:

I^α f(t) = (1/Γ(α)) ∫₀ᵗ (t-τ)^(α-1) f(τ) dτ

where Γ(α) is the gamma function.

Features: - Optimized FFT-based computation for large arrays - Direct method for small arrays with high accuracy - Memory-efficient algorithms - Support for both callable and array inputs - Error estimation and convergence analysis

Thresholds: method="auto" chooses FFT when len(t) >= fft_threshold (default 1000); otherwise the direct path is used. For α 1e-4, direct computation is delegated to hpfracc.core.integrals.RiemannLiouvilleIntegral.

Parameters:
__init__(alpha, method='auto', optimize_memory=True, use_jax=False)[source]

Initialize Riemann-Liouville integral calculator.

Parameters:
  • alpha (float | FractionalOrder) – Fractional order (must be > 0)

  • method (str) – Computation method (“auto”, “fft”, “direct”, “adaptive”)

  • optimize_memory (bool) – Use memory optimization techniques

  • use_jax (bool) – Use JAX acceleration if available

compute(f, t, h=None, method=None)[source]

Compute the Riemann-Liouville fractional integral.

Parameters:
  • f (Callable | ndarray) – Function to integrate (callable) or function values (array)

  • t (ndarray) – Time points where integral is evaluated

  • h (float | None) – Step size (if None, computed from t)

  • method (str | None) – Override the default method

Returns:

Array of integral values at each time point

Return type:

ndarray

_select_optimal_method(n_points)[source]

Select optimal computation method based on array size.

Parameters:

n_points (int)

Return type:

str

_compute_fft(f, t, h)[source]

RL fractional integral via linear convolution on the uniform grid.

Matches the legacy discrete sum in _compute_direct_discrete_legacy() (kernel weight ((i-j)h)^{\alpha-1} / \Gamma(\alpha), then \times h). Uses scipy.signal.fftconvolve so the operation is causal (first n samples of the full convolution), not periodic length-n FFT convolution (which was incorrect and disagreed strongly with quadrature).

Parameters:
Return type:

ndarray

_compute_direct_discrete_legacy(f, t, h)[source]

Original O(N²) uniform-grid RL sum (used only for tiny α where quad is ill-conditioned).

Parameters:
Return type:

ndarray

_compute_direct(f, t, h)[source]

RL integral on the sample grid via the canonical quad-based implementation in hpfracc.core.integrals (same definition as the rest of the library), except for extremely small α where the kernel is near-singular on a short grid.

Parameters:
Return type:

ndarray

_compute_adaptive(f, t, h)[source]

Compare FFT to the direct reference on short grids (len(t) < fft_threshold).

FFT and quad/discrete direct are not required to match to tight allclose tolerances; a scale-aware L2 relative residual is used. RuntimeWarning is used only for non-finite FFT output or severe disagreement; moderate mismatch emits UserWarning and still returns the direct result.

Parameters:
Return type:

ndarray

class hpfracc.algorithms.integral_methods.CaputoIntegral(alpha, method='auto', optimize_memory=True, use_jax=False)[source]

Bases: object

Caputo fractional integral of order α.

For α > 0, the Caputo fractional integral equals the Riemann-Liouville integral:

I^α f(t) = (1/Γ(α)) ∫₀ᵗ (t-τ)^(α-1) f(τ) dτ

This class provides a consistent interface while reusing the RL implementation. method and fft_threshold behaviour match RiemannLiouvilleIntegral.

Parameters:
__init__(alpha, method='auto', optimize_memory=True, use_jax=False)[source]

Initialize Caputo integral calculator.

Parameters:
  • alpha (float | FractionalOrder) – Fractional order (must be > 0)

  • method (str) – Computation method (“auto”, “fft”, “direct”, “adaptive”)

  • optimize_memory (bool) – Use memory optimization techniques

  • use_jax (bool) – Use JAX acceleration if available

compute(f, t, h=None, method=None)[source]

Compute the Caputo fractional integral.

Parameters:
  • f (Callable | ndarray) – Function to integrate (callable) or function values (array)

  • t (ndarray) – Time points where integral is evaluated

  • h (float | None) – Step size (if None, computed from t)

  • method (str | None) – Override the default method

Returns:

Array of integral values at each time point

Return type:

ndarray

class hpfracc.algorithms.integral_methods.WeylIntegral(alpha, method='auto')[source]

Bases: object

Weyl fractional integral of order α (grid API).

For α 1e-4, delegates to the canonical quad-based hpfracc.core.integrals.WeylIntegral. For smaller α (near-identity kernel), keeps a legacy discrete RL-style sum on the sample grid for stability.

Parameters:
__init__(alpha, method='auto')[source]
Parameters:
_compute_weyl_discrete_legacy(f, t, h)[source]

Original windowed RL-style sum on t (used only for tiny α).

Parameters:
Return type:

ndarray

compute(f, t, h=None)[source]
Parameters:
Return type:

ndarray

hpfracc.algorithms.integral_methods.riemann_liouville_integral(f, t, alpha, h=None, method='auto')[source]

Compute Riemann-Liouville fractional integral.

Parameters:
Returns:

Integral values

Return type:

ndarray

hpfracc.algorithms.integral_methods.caputo_integral(f, t, alpha, h=None, method='auto')[source]

Compute Caputo fractional integral.

Parameters:
Returns:

Integral values

Return type:

ndarray

hpfracc.algorithms.integral_methods.optimized_riemann_liouville_integral(f, t, alpha, h=None)[source]

Optimized Riemann-Liouville integral with automatic method selection.

Parameters:
Returns:

Integral values

Return type:

ndarray

hpfracc.algorithms.integral_methods.optimized_caputo_integral(f, t, alpha, h=None)[source]

Optimized Caputo integral with automatic method selection.

Parameters:
Returns:

Integral values

Return type:

ndarray

Advanced Fractional Calculus Methods

This module implements advanced fractional calculus methods with optimizations: - Weyl derivative via FFT Convolution with parallelization - Marchaud derivative with Difference Quotient convolution and memory optimization - Hadamard derivative - Reiz/Reiz-Feller derivative via spectral method - Adomian Decomposition method

All methods include parallel processing and memory optimizations.

Naming: parallel-enhanced variants of Weyl / Marchaud / … are exposed as Parallel* classes. The legacy names OptimizedWeylDerivative, etc., remain as aliases of those classes (they are unrelated to OptimizedCaputo in hpfracc.algorithms.optimized_methods, which aliases the unified RL/Caputo/GL engines).

class hpfracc.algorithms.advanced_methods.WeylDerivative(alpha, parallel_config=None, optimized=True, **kwargs)[source]

Bases: object

Weyl fractional derivative via FFT Convolution with parallelization.

The Weyl derivative is defined as: D^α f(x) = (1/Γ(n-α)) (d/dx)^n ∫_x^∞ (τ-x)^(n-α-1) f(τ) dτ

This implementation uses FFT convolution for efficiency and parallel processing.

Parameters:
__init__(alpha, parallel_config=None, optimized=True, **kwargs)[source]

Initialize Weyl derivative calculator.

Parameters:
compute(f, x, h=None, use_parallel=True)[source]

Compute Weyl derivative using optimized FFT convolution.

Parameters:
Return type:

float | ndarray

_compute_serial(f, x, h)[source]

Serial computation using optimized FFT convolution.

Parameters:
Return type:

ndarray

_compute_parallel(f, x, h)[source]

Parallel computation using chunked processing.

Parameters:
Return type:

ndarray

_process_chunk(chunk_data)[source]

Process a chunk of data for parallel computation.

Parameters:

chunk_data (Tuple[ndarray, ndarray, float])

Return type:

ndarray

class hpfracc.algorithms.advanced_methods.MarchaudDerivative(alpha, parallel_config=None, **kwargs)[source]

Bases: object

Marchaud fractional derivative with Difference Quotient convolution and memory optimization.

The Marchaud derivative is defined as: D^α f(x) = α/Γ(1-α) ∫_0^∞ [f(x) - f(x-τ)] / τ^(α+1) dτ

This implementation uses difference quotient convolution with memory optimization.

Parameters:
__init__(alpha, parallel_config=None, **kwargs)[source]

Initialize Marchaud derivative calculator.

Parameters:
compute(f, x, h=None, use_parallel=True, memory_optimized=True)[source]

Compute Marchaud derivative with memory optimization.

Parameters:
Return type:

float | ndarray

_compute_memory_optimized(f, x, h, use_parallel)[source]

Memory-optimized computation using streaming approach.

Parameters:
Return type:

ndarray

_process_marchaud_chunk(chunk_data)[source]

Process a chunk for Marchaud derivative.

Parameters:

chunk_data (Tuple[ndarray, ndarray, float, int, int])

Return type:

ndarray

_compute_marchaud_segment(f, x, h, start_idx, end_idx)[source]

Compute Marchaud derivative for a segment.

Parameters:
Return type:

ndarray

_compute_standard(f, x, h, use_parallel)[source]

Standard computation without memory optimization.

Parameters:
Return type:

ndarray

class hpfracc.algorithms.advanced_methods.HadamardDerivative(alpha=None, order=None, **kwargs)[source]

Bases: object

Hadamard fractional derivative.

The Hadamard derivative is defined as: D^α f(x) = (1/Γ(n-α)) (x d/dx)^n ∫_1^x (log(x/t))^(n-α-1) f(t) dt/t

This implementation uses logarithmic transformation and efficient quadrature.

Parameters:
__init__(alpha=None, order=None, **kwargs)[source]

Initialize Hadamard derivative calculator.

Accepts both alpha and order for backward compatibility.

Parameters:
compute(f, x, h=None)[source]

Compute Hadamard derivative using logarithmic transformation.

Parameters:
Return type:

float | ndarray

_compute_hadamard(f, x, h)[source]

Compute Hadamard derivative using logarithmic transformation.

Parameters:
Return type:

ndarray

class hpfracc.algorithms.advanced_methods.ReizFellerDerivative(alpha, parallel_config=None, **kwargs)[source]

Bases: object

Reiz-Feller fractional derivative via spectral method.

The Reiz-Feller derivative is defined as: \(D^{\alpha} f(x) = \frac{1}{2\pi} \int_{-\infty}^{\infty} |\xi|^{\alpha} \, \mathcal{F}[f](\xi) \, e^{i\xi x} \, d\xi\)

This implementation uses FFT for spectral computation.

Parameters:
__init__(alpha, parallel_config=None, **kwargs)[source]

Initialize Reiz-Feller derivative calculator.

Parameters:
compute(f, x, h=None, use_parallel=True)[source]

Compute Reiz-Feller derivative using spectral method.

Parameters:
Return type:

float | ndarray

_compute_spectral(f, x, h, use_parallel)[source]

Compute using spectral method with FFT.

Parameters:
Return type:

ndarray

class hpfracc.algorithms.advanced_methods.AdomianDecomposition(alpha, parallel_config=None, **kwargs)[source]

Bases: object

Adomian Decomposition Method for solving fractional differential equations.

This method decomposes the solution into a series and computes each term using the Adomian polynomials.

Parameters:
__init__(alpha, parallel_config=None, **kwargs)[source]

Initialize Adomian Decomposition solver.

Parameters:
solve(equation, initial_conditions, t_span, n_steps=1000, n_terms=10, use_parallel=True)[source]

Solve fractional differential equation using Adomian decomposition.

Parameters:
  • equation (Callable) – Function representing the FDE

  • initial_conditions (Dict) – Dictionary of initial conditions

  • t_span (Tuple[float, float]) – Time span (t0, tf)

  • n_steps (int) – Number of time steps

  • n_terms (int) – Number of terms in the decomposition

  • use_parallel (bool) – Whether to use parallel processing

Returns:

Tuple of (time_points, solution)

Return type:

Tuple[ndarray, ndarray]

_compute_terms_serial(equation, t, h, n_terms)[source]

Compute decomposition terms serially.

Parameters:
Return type:

List[ndarray]

_compute_terms_parallel(equation, t, h, n_terms)[source]

Compute decomposition terms in parallel.

Parameters:
Return type:

List[ndarray]

_compute_adomian_polynomial(equation, previous_terms, n, t)[source]

Compute the nth Adomian polynomial.

Parameters:
Return type:

ndarray

_compute_integral_term(adomian, t, h)[source]

Compute integral term using fractional integration.

Parameters:
Return type:

ndarray

_compute_single_term(equation, t, h, n)[source]

Compute a single decomposition term.

Parameters:
Return type:

ndarray

hpfracc.algorithms.advanced_methods.weyl_derivative(f, x, alpha, h=None, **kwargs)[source]

Convenience function for Weyl derivative.

Parameters:
Return type:

float | ndarray

hpfracc.algorithms.advanced_methods.marchaud_derivative(f, x, alpha, h=None, **kwargs)[source]

Convenience function for Marchaud derivative.

Parameters:
Return type:

float | ndarray

hpfracc.algorithms.advanced_methods.hadamard_derivative(f, x, alpha, h=None, **kwargs)[source]

Convenience function for Hadamard derivative.

Parameters:
Return type:

float | ndarray

hpfracc.algorithms.advanced_methods.reiz_feller_derivative(f, x, alpha, h=None, **kwargs)[source]

Convenience function for Reiz-Feller derivative.

Parameters:
Return type:

float | ndarray

class hpfracc.algorithms.advanced_methods.ParallelWeylDerivative(order, **kwargs)[source]

Bases: WeylDerivative

Weyl derivative with optimized=True defaults (parallel / FFT path).

Parameters:

order (float | FractionalOrder)

__init__(order, **kwargs)[source]

Initialize Weyl derivative calculator.

Parameters:

order (float | FractionalOrder)

class hpfracc.algorithms.advanced_methods.ParallelMarchaudDerivative(order, **kwargs)[source]

Bases: MarchaudDerivative

Marchaud derivative exposed under the parallel-enhanced naming scheme.

Parameters:

order (float | FractionalOrder)

__init__(order, **kwargs)[source]

Initialize Marchaud derivative calculator.

Parameters:

order (float | FractionalOrder)

class hpfracc.algorithms.advanced_methods.ParallelHadamardDerivative(order, **kwargs)[source]

Bases: HadamardDerivative

Hadamard derivative under the parallel-enhanced naming scheme.

Parameters:

order (float | FractionalOrder)

__init__(order, **kwargs)[source]

Initialize Hadamard derivative calculator.

Accepts both alpha and order for backward compatibility.

Parameters:

order (float | FractionalOrder)

class hpfracc.algorithms.advanced_methods.ParallelReizFellerDerivative(order, **kwargs)[source]

Bases: ReizFellerDerivative

Reiz–Feller derivative under the parallel-enhanced naming scheme.

Parameters:

order (float | FractionalOrder)

__init__(order, **kwargs)[source]

Initialize Reiz-Feller derivative calculator.

Parameters:

order (float | FractionalOrder)

class hpfracc.algorithms.advanced_methods.ParallelAdomianDecomposition(order, **kwargs)[source]

Bases: AdomianDecomposition

Adomian decomposition under the parallel-enhanced naming scheme.

Parameters:

order (float | FractionalOrder)

__init__(order, **kwargs)[source]

Initialize Adomian Decomposition solver.

Parameters:

order (float | FractionalOrder)

hpfracc.algorithms.advanced_methods.OptimizedWeylDerivative

alias of ParallelWeylDerivative

hpfracc.algorithms.advanced_methods.OptimizedMarchaudDerivative

alias of ParallelMarchaudDerivative

hpfracc.algorithms.advanced_methods.OptimizedHadamardDerivative

alias of ParallelHadamardDerivative

hpfracc.algorithms.advanced_methods.OptimizedReizFellerDerivative

alias of ParallelReizFellerDerivative

hpfracc.algorithms.advanced_methods.OptimizedAdomianDecomposition

alias of ParallelAdomianDecomposition

hpfracc.algorithms.advanced_methods.parallel_weyl_derivative(f, x, alpha, h=None, **kwargs)[source]
Parameters:
Return type:

float | ndarray

hpfracc.algorithms.advanced_methods.parallel_marchaud_derivative(f, x, alpha, h=None, **kwargs)[source]
Parameters:
Return type:

float | ndarray

hpfracc.algorithms.advanced_methods.parallel_hadamard_derivative(f, x, alpha, h=None, **kwargs)[source]
Parameters:
Return type:

float | ndarray

hpfracc.algorithms.advanced_methods.parallel_reiz_feller_derivative(f, x, alpha, h=None, **kwargs)[source]
Parameters:
Return type:

float | ndarray

hpfracc.algorithms.advanced_methods.optimized_weyl_derivative(f, x, alpha, h=None, **kwargs)[source]
Parameters:
Return type:

float | ndarray

hpfracc.algorithms.advanced_methods.optimized_marchaud_derivative(f, x, alpha, h=None, **kwargs)[source]
Parameters:
Return type:

float | ndarray

hpfracc.algorithms.advanced_methods.optimized_hadamard_derivative(f, x, alpha, h=None, **kwargs)[source]
Parameters:
Return type:

float | ndarray

hpfracc.algorithms.advanced_methods.optimized_reiz_feller_derivative(f, x, alpha, h=None, **kwargs)[source]
Parameters:
Return type:

float | ndarray

Fractional operator extensions (Laplacian, FrFT, Z/Mellin transforms).

This is the algorithms-layer complement to hpfracc.special (Γ, β, binomial, Mittag–Leffler). It implements operators used in PDEs and signal processing:

  • Fractional Laplacian

  • Fractional Fourier / Z / Mellin transforms

Canonical import: from hpfracc.algorithms.fractional_operator_methods import .... The legacy path hpfracc.algorithms.special_methods remains a thin re-export shim.

hpfracc.algorithms.fractional_operator_methods._numpy_trapezoid(y, x)[source]

Trapezoidal rule; prefers numpy.trapezoid (NumPy 2+) over deprecated trapz.

hpfracc.algorithms.fractional_operator_methods._factorial(n)

Simple factorial function for NUMBA compatibility.

Parameters:

n (int)

Return type:

int

class hpfracc.algorithms.fractional_operator_methods.FractionalLaplacian(alpha, *, dimension=1, boundary_conditions=None)[source]

Bases: object

Fractional Laplacian operator implementation.

The fractional Laplacian is defined as: \((-\Delta)^{\alpha/2} f(x) = \mathcal{F}^{-1}\left(|\xi|^{\alpha}\, \mathcal{F}[f](\xi)\right)\)

This is a fundamental operator in fractional PDEs, diffusion processes, and many physical applications.

Parameters:
__init__(alpha, *, dimension=1, boundary_conditions=None)[source]

Initialize fractional Laplacian calculator.

Parameters:
  • order – Fractional order (0 < α < 2)

  • dimension (int) – Spatial dimension

  • boundary_conditions (str | None) – Boundary condition type

  • alpha (float | FractionalOrder)

compute(f, x, h=None, method='spectral')[source]

Compute fractional Laplacian.

Parameters:
  • f (Callable | ndarray) – Function or array of function values

  • x (float | ndarray) – Domain points

  • h (float | None) – Step size (if not provided, inferred from x)

  • method (str) – Computation method (“spectral”, “finite_difference”, “integral”)

Returns:

Fractional Laplacian values

Return type:

float | ndarray

_spectral_method(f, x, h)[source]

Spectral method using FFT.

Parameters:
Return type:

ndarray

_finite_difference_method(f, x, h)[source]

Finite difference approximation.

Parameters:
Return type:

ndarray

compute_numerical(f, x, h=None)[source]

Numerical convenience API used by tests.

Uses finite-difference approximation under the hood.

Parameters:
Return type:

ndarray

_integral_method(f, x, h)[source]

Integral representation method.

Parameters:
Return type:

ndarray

_grunwald_coefficients(N)[source]

Compute Grünwald-Letnikov coefficients.

Parameters:

N (int)

Return type:

ndarray

class hpfracc.algorithms.fractional_operator_methods.FractionalFourierTransform(alpha, *, method='spectral')[source]

Bases: object

Fractional Fourier Transform (FrFT) implementation.

The fractional Fourier transform is a generalization of the Fourier transform that depends on a parameter α. For α = π/2, it reduces to the standard Fourier transform.

FrFT[f](u) = ∫_{-∞}^∞ K_α(x, u) f(x) dx

where K_α is the fractional Fourier kernel.

Parameters:
__init__(alpha, *, method='spectral')[source]

Initialize fractional Fourier transform calculator.

Parameters:
transform(f, x, h=None, method='auto')[source]

Compute fractional Fourier transform.

Parameters:
  • f (Callable | ndarray) – Function or array of function values

  • x (float | ndarray) – Domain points

  • h (float | None) – Step size

  • method (str) – Computation method (“auto”, “discrete”, “spectral”, “fast”)

Returns:

Tuple of (u_domain, transformed_values)

Return type:

Tuple[ndarray, ndarray]

compute(f, x, h=None, method='auto')[source]

Compatibility wrapper returning only transformed values.

Some call sites expect a compute(…) API that returns the transformed values array directly. This method delegates to transform(…) and returns only the values component.

Parameters:
Return type:

ndarray

_discrete_method(f, x, h)[source]

Discrete fractional Fourier transform using optimized FFT-based approach.

Parameters:
Return type:

Tuple[ndarray, ndarray]

_fft_based_method(f, x, u, h)[source]

Fast FFT-based fractional Fourier transform.

Parameters:
Return type:

Tuple[ndarray, ndarray]

_chirp_based_method(f, x, u, h)[source]

Chirp-based algorithm for fractional Fourier transform.

Parameters:
Return type:

Tuple[ndarray, ndarray]

_spectral_method(f, x, h)[source]

Spectral method using decomposition.

Parameters:
Return type:

Tuple[ndarray, ndarray]

compute_numerical(f, x, h=None)[source]

Numerical convenience API returning only values.

Maps to the discrete method for accuracy.

Parameters:
Return type:

ndarray

_compute_transform_matrix(x, u, h)[source]

Compute the discrete fractional Fourier transform matrix.

Parameters:
Return type:

ndarray

_hermite_decomposition(f, x, h)[source]

Decompose function into Hermite-Gaussian basis.

Parameters:
Return type:

ndarray

_hermite_function(n, x)[source]

Compute Hermite-Gaussian function of order n.

Parameters:
Return type:

ndarray

_fractional_hermite(n, u, alpha)[source]

Compute fractional Fourier transform of Hermite function.

Parameters:
Return type:

ndarray

_fast_approximation(f, x, h)[source]

Fast approximation using interpolation between standard FFT and identity.

Parameters:
Return type:

Tuple[ndarray, ndarray]

class hpfracc.algorithms.fractional_operator_methods.FractionalZTransform(alpha, *, method='spectral')[source]

Bases: object

Fractional Z-Transform implementation.

The fractional Z-transform is a generalization of the Z-transform that depends on a fractional parameter α. It’s useful for discrete-time systems and digital signal processing.

Z^α[f](z) = Σ_{n=0}^∞ f[n] z^(-αn)

Parameters:
__init__(alpha, *, method='spectral')[source]

Initialize fractional Z-transform calculator.

Parameters:
transform(f, z, method='direct')[source]

Compute fractional Z-transform.

Parameters:
  • f (ndarray) – Discrete signal array

  • z (complex | ndarray) – Complex variable(s) for evaluation

  • method (str) – Computation method (“direct”, “fft”)

Returns:

Transform values

Return type:

complex | ndarray

_direct_method(f, z)[source]

Direct computation of fractional Z-transform.

Parameters:
Return type:

complex | ndarray

_fft_method(f, z)[source]

FFT-based computation for unit circle evaluation.

Parameters:
Return type:

complex | ndarray

inverse_transform(F, z, N, method='contour')[source]

Compute inverse fractional Z-transform.

Parameters:
  • F (complex | ndarray) – Transform values

  • z (complex | ndarray) – Complex variable(s)

  • N (int) – Length of output signal

  • method (str) – Inversion method (“contour”, “residue”)

Returns:

Original signal

Return type:

ndarray

_contour_integration(F, z, N)[source]

Contour integration method for inverse transform.

Parameters:
Return type:

ndarray

_residue_method(F, z, N)[source]

Residue method for inverse transform.

Parameters:
Return type:

ndarray

class hpfracc.algorithms.fractional_operator_methods.FractionalMellinTransform(alpha)[source]

Bases: object

Fractional Mellin Transform implementation.

The fractional Mellin transform is defined as: M_α[f](s) = ∫₀^∞ f(x) x^(s-1+α) dx

This transform is useful for: - Scale-invariant signal processing - Fractional differential equations - Image processing and pattern recognition - Quantum mechanics applications

Parameters:

alpha (float | FractionalOrder)

__init__(alpha)[source]

Initialize fractional Mellin transform calculator.

Parameters:

alpha (float | FractionalOrder)

transform(f, x, s, method='numerical')[source]

Compute fractional Mellin transform.

Parameters:
  • f (Callable | ndarray) – Function or array of function values

  • x (float | ndarray) – Domain points (must be positive)

  • s (complex | ndarray) – Complex variable(s) for transform

  • method (str) – Computation method (“numerical”, “analytical”, “fft”)

Returns:

Transform values

Return type:

complex | ndarray

_numerical_method(f, x, s)[source]

Numerical integration method.

Parameters:
Return type:

complex | ndarray

_analytical_method(f, x, s)[source]

Analytical method for special functions.

Parameters:
Return type:

complex | ndarray

_fft_method(f, x, s)[source]

FFT-based method for efficient computation.

Parameters:
Return type:

complex | ndarray

inverse_transform(F, s, x, method='numerical')[source]

Compute inverse fractional Mellin transform.

Parameters:
Returns:

Original function values

Return type:

ndarray

_inverse_numerical(F, s, x)[source]

Numerical inverse transform.

Parameters:
Return type:

ndarray

_inverse_fft(F, s, x)[source]

FFT-based inverse transform.

Parameters:
Return type:

ndarray

hpfracc.algorithms.fractional_operator_methods.fractional_laplacian(f, x, alpha, h=None, method='spectral')[source]

Convenience function for fractional Laplacian.

Parameters:
Return type:

float | ndarray

hpfracc.algorithms.fractional_operator_methods.fractional_fourier_transform(f, x, alpha, h=None, method='auto')[source]

Convenience function for fractional Fourier transform.

Parameters:
Return type:

Tuple[ndarray, ndarray]

hpfracc.algorithms.fractional_operator_methods.fractional_z_transform(f, z, alpha, method='direct')[source]

Convenience function for fractional Z-transform.

Parameters:
Return type:

complex | ndarray

hpfracc.algorithms.fractional_operator_methods.fractional_mellin_transform(f, x, s, alpha, method='numerical')[source]

Convenience function for fractional Mellin transform.

Parameters:
Return type:

complex | ndarray

class hpfracc.algorithms.fractional_operator_methods.SpecialMethodsConfig(optimized=True, parallel=False)[source]

Bases: object

Configuration for special methods optimization.

Parameters:
__init__(optimized=True, parallel=False)[source]

Initialize special methods configuration.

Parameters:
  • optimized (bool) – Enable optimized implementations

  • parallel (bool) – Enable parallel processing (if available)

class hpfracc.algorithms.fractional_operator_methods.SpecialOptimizedWeylDerivative(alpha, config=None)[source]

Bases: object

Weyl derivative optimized using Fractional Fourier Transform.

This implementation replaces the standard FFT convolution approach with Fractional Fourier Transform for better performance, especially for large arrays and specific alpha values.

Parameters:
__init__(alpha, config=None)[source]

Initialize special optimized Weyl derivative calculator.

Parameters:
_determine_optimal_method()[source]

Determine the optimal computation method based on alpha value.

compute(f, x, h=None, method=None)[source]

Compute Weyl derivative using optimized method.

Parameters:
Return type:

float | ndarray

_compute_frft(f, x, h)[source]

Compute using Fractional Fourier Transform.

Parameters:
Return type:

ndarray

_compute_standard_fft(f, x, h)[source]

Compute using standard FFT approach.

Parameters:
Return type:

ndarray

_compute_hybrid(f, x, h)[source]

Compute using hybrid approach combining FRFT and standard FFT.

Parameters:
Return type:

ndarray

_compute_weyl_kernel(u, h)[source]

Compute Weyl derivative kernel.

Parameters:
Return type:

ndarray

class hpfracc.algorithms.fractional_operator_methods.SpecialOptimizedMarchaudDerivative(alpha, config=None)[source]

Bases: object

Marchaud derivative optimized using Fractional Z-Transform.

This implementation replaces the difference quotient convolution with Fractional Z-Transform for better performance on discrete signals.

Parameters:
__init__(alpha, config=None)[source]

Initialize special optimized Marchaud derivative calculator.

Parameters:
compute(f, x, h=None, method='z_transform')[source]

Compute Marchaud derivative using optimized method.

Parameters:
Return type:

float | ndarray

_compute_z_transform(f, x, h)[source]

Compute using Fractional Z-Transform.

Parameters:
Return type:

ndarray

_compute_standard(f, x, h)[source]

Compute using standard difference quotient approach.

Parameters:
Return type:

ndarray

class hpfracc.algorithms.fractional_operator_methods.SpecialOptimizedReizFellerDerivative(alpha, config=None)[source]

Bases: object

Reiz-Feller derivative optimized using Fractional Laplacian.

This implementation uses the Fractional Laplacian for efficient computation of the Reiz-Feller derivative, especially for spectral methods and large-scale problems.

Parameters:
__init__(alpha, config=None)[source]

Initialize special optimized Reiz-Feller derivative calculator.

Parameters:
compute(f, x, h=None, method='laplacian')[source]

Compute Reiz-Feller derivative using optimized method.

Parameters:
Return type:

float | ndarray

_compute_laplacian(f, x, h)[source]

Compute using Fractional Laplacian.

Parameters:
Return type:

ndarray

_compute_spectral(f, x, h)[source]

Compute using spectral method.

Parameters:
Return type:

ndarray

class hpfracc.algorithms.fractional_operator_methods.UnifiedSpecialMethods(config=None)[source]

Bases: object

Unified interface for all special methods with automatic method selection.

This class provides a unified API that automatically selects the best special method based on the problem characteristics.

Parameters:

config (SpecialMethodsConfig | None)

__init__(config=None)[source]

Initialize unified special methods interface.

Parameters:

config (SpecialMethodsConfig | None)

compute_derivative(f, x, alpha, h, method=None, problem_type='general')[source]

Compute fractional derivative using optimal special method.

Parameters:
  • f (Callable | ndarray) – Function or function values

  • x (ndarray) – Domain points

  • alpha (float | FractionalOrder) – Fractional order

  • h (float) – Step size

  • method (str | None) – Specific method to use (if None, auto-select)

  • problem_type (str) – Type of problem (“periodic”, “discrete”, “spectral”, “general”)

Returns:

Derivative values

Return type:

ndarray

_auto_select_method(problem_type, size, alpha)[source]

Automatically select the best method based on problem characteristics.

Parameters:
Return type:

str

hpfracc.algorithms.fractional_operator_methods.special_optimized_weyl_derivative(f, x, alpha, h=None, method=None)[source]

Convenience function for special optimized Weyl derivative.

Parameters:
Return type:

float | ndarray

hpfracc.algorithms.fractional_operator_methods.special_optimized_marchaud_derivative(f, x, alpha, h=None, method='z_transform')[source]

Convenience function for special optimized Marchaud derivative.

Parameters:
Return type:

float | ndarray

hpfracc.algorithms.fractional_operator_methods.special_optimized_reiz_feller_derivative(f, x, alpha, h=None, method='laplacian')[source]

Convenience function for special optimized Reiz-Feller derivative.

Parameters:
Return type:

float | ndarray

hpfracc.algorithms.fractional_operator_methods.unified_special_derivative(f, x, alpha, h, method=None, problem_type='general')[source]

Convenience function for unified special derivative computation.

Parameters:
Return type:

ndarray

Fractional Implementations

Fractional derivative and integral implementations.

This module provides concrete implementations of fractional derivatives and integrals that can be registered with the factory.

Performance Note (v2.1.0): - All implementations automatically benefit from intelligent backend selection - Backend selection happens in the underlying optimized algorithms - Small data (< 1K elements): Uses NumPy/Numba for minimal overhead - Large data (> 100K elements): Uses GPU when available for acceleration - Zero code changes required - optimization is automatic

Engine path (RL / Caputo / Grünwald–Letnikov):

  • Canonical numerical engines live in hpfracc.algorithms.derivatives.

  • Classes in this module (for example CaputoDerivative) are thin BaseFractionalDerivative adapters that delegate to those engines via _engine; there is no second implementation.

class hpfracc.core.fractional_implementations._AlphaCompatibilityWrapper(fractional_order)[source]

Bases: object

Wrapper that makes alpha behave like both a float and FractionalOrder.

Parameters:

fractional_order (FractionalOrder)

__init__(fractional_order)[source]
Parameters:

fractional_order (FractionalOrder)

class hpfracc.core.fractional_implementations.RiemannLiouvilleDerivative(order, **kwargs)[source]

Bases: BaseFractionalDerivative

Riemann-Liouville fractional derivative — adapter over the canonical engine hpfracc.algorithms.derivatives.RiemannLiouville.

Parameters:

order (float | FractionalOrder)

__init__(order, **kwargs)[source]

Initialize fractional derivative.

Parameters:
  • order (float | FractionalOrder) – Fractional order

  • definition – Mathematical definition

  • use_jax – Whether to use JAX optimizations

  • use_numba – Whether to use NUMBA optimizations

compute(f, x, h=None, **kwargs)[source]

Compute the Riemann-Liouville fractional derivative.

Parameters:
Return type:

float | ndarray

compute_numerical(f_values, x_values, **kwargs)[source]

Compute the derivative numerically from function values.

Parameters:
Return type:

ndarray

class hpfracc.core.fractional_implementations.CaputoDerivative(order, **kwargs)[source]

Bases: BaseFractionalDerivative

Caputo fractional derivative — adapter over the canonical engine hpfracc.algorithms.derivatives.Caputo (single implementation path).

Parameters:

order (float | FractionalOrder)

__init__(order, **kwargs)[source]

Initialize fractional derivative.

Parameters:
  • order (float | FractionalOrder) – Fractional order

  • definition – Mathematical definition

  • use_jax – Whether to use JAX optimizations

  • use_numba – Whether to use NUMBA optimizations

compute(f, x, h=None, **kwargs)[source]

Compute the Caputo fractional derivative.

Parameters:
Return type:

float | ndarray

compute_numerical(f_values, x_values, **kwargs)[source]

Compute the derivative numerically from function values.

Parameters:
Return type:

ndarray

class hpfracc.core.fractional_implementations.GrunwaldLetnikovDerivative(order, **kwargs)[source]

Bases: BaseFractionalDerivative

Grünwald–Letnikov fractional derivative — adapter over the canonical engine hpfracc.algorithms.derivatives.GrunwaldLetnikov.

Parameters:

order (float | FractionalOrder)

__init__(order, **kwargs)[source]

Initialize fractional derivative.

Parameters:
  • order (float | FractionalOrder) – Fractional order

  • definition – Mathematical definition

  • use_jax – Whether to use JAX optimizations

  • use_numba – Whether to use NUMBA optimizations

compute(f, x, h=None, **kwargs)[source]

Compute the Grunwald-Letnikov fractional derivative.

Parameters:
Return type:

float | ndarray

compute_numerical(f_values, x_values, **kwargs)[source]

Compute the derivative numerically from function values.

Parameters:
Return type:

ndarray

class hpfracc.core.fractional_implementations.CaputoFabrizioDerivative(order, **kwargs)[source]

Bases: BaseFractionalDerivative

Caputo-Fabrizio fractional derivative implementation.

Uses the novel implementation from algorithms.

Parameters:

order (float | FractionalOrder)

__init__(order, **kwargs)[source]

Initialize fractional derivative.

Parameters:
  • order (float | FractionalOrder) – Fractional order

  • definition – Mathematical definition

  • use_jax – Whether to use JAX optimizations

  • use_numba – Whether to use NUMBA optimizations

compute(f, x, **kwargs)[source]

Compute the Caputo-Fabrizio fractional derivative.

Parameters:
Return type:

float | ndarray

compute_numerical(f_values, x_values, **kwargs)[source]

Compute the derivative numerically from function values.

Parameters:
Return type:

ndarray

class hpfracc.core.fractional_implementations.AtanganaBaleanuDerivative(order, **kwargs)[source]

Bases: BaseFractionalDerivative

Atangana-Baleanu fractional derivative implementation.

Uses the novel implementation from algorithms.

Parameters:

order (float | FractionalOrder)

__init__(order, **kwargs)[source]

Initialize fractional derivative.

Parameters:
  • order (float | FractionalOrder) – Fractional order

  • definition – Mathematical definition

  • use_jax – Whether to use JAX optimizations

  • use_numba – Whether to use NUMBA optimizations

compute(f, x, **kwargs)[source]

Compute the Atangana-Baleanu fractional derivative.

Parameters:
Return type:

float | ndarray

compute_numerical(f_values, x_values, **kwargs)[source]

Compute the derivative numerically from function values.

Parameters:
Return type:

ndarray

class hpfracc.core.fractional_implementations.FractionalLaplacian(order, **kwargs)[source]

Bases: BaseFractionalDerivative

Fractional Laplacian operator implementation.

Uses the special implementation from algorithms.

Parameters:

order (float | FractionalOrder)

__init__(order, **kwargs)[source]

Initialize fractional derivative.

Parameters:
  • order (float | FractionalOrder) – Fractional order

  • definition – Mathematical definition

  • use_jax – Whether to use JAX optimizations

  • use_numba – Whether to use NUMBA optimizations

compute(f, x, **kwargs)[source]

Compute the fractional Laplacian.

Parameters:
Return type:

float | ndarray

compute_numerical(f_values, x_values, **kwargs)[source]

Compute the fractional Laplacian numerically from function values.

Parameters:
Return type:

ndarray

class hpfracc.core.fractional_implementations.FractionalFourierTransform(order, **kwargs)[source]

Bases: BaseFractionalDerivative

Fractional Fourier Transform implementation.

Uses the special implementation from algorithms.

Parameters:

order (float | FractionalOrder)

__init__(order, **kwargs)[source]

Initialize fractional derivative.

Parameters:
  • order (float | FractionalOrder) – Fractional order

  • definition – Mathematical definition

  • use_jax – Whether to use JAX optimizations

  • use_numba – Whether to use NUMBA optimizations

compute(f, x, **kwargs)[source]

Compute the fractional Fourier transform.

Parameters:
Return type:

float | ndarray

compute_numerical(f_values, x_values, **kwargs)[source]

Compute the fractional Fourier transform numerically from function values.

Parameters:
Return type:

ndarray

class hpfracc.core.fractional_implementations.MillerRossDerivative(order, **kwargs)[source]

Bases: BaseFractionalDerivative

Miller-Ross fractional derivative implementation.

This is a generalization of the Riemann-Liouville derivative.

Parameters:

order (float | FractionalOrder)

__init__(order, **kwargs)[source]

Initialize fractional derivative.

Parameters:
  • order (float | FractionalOrder) – Fractional order

  • definition – Mathematical definition

  • use_jax – Whether to use JAX optimizations

  • use_numba – Whether to use NUMBA optimizations

compute(f, x, **kwargs)[source]

Compute the Miller-Ross fractional derivative.

Parameters:
Return type:

float | ndarray

compute_numerical(f_values, x_values, **kwargs)[source]

Compute the Miller-Ross fractional derivative numerically.

Parameters:
Return type:

ndarray

class hpfracc.core.fractional_implementations.WeylDerivative(order, **kwargs)[source]

Bases: BaseFractionalDerivative

Weyl fractional derivative implementation.

Uses the advanced implementation from algorithms with FFT convolution and parallel processing optimizations.

Parameters:

order (float | FractionalOrder)

__init__(order, **kwargs)[source]

Initialize fractional derivative.

Parameters:
  • order (float | FractionalOrder) – Fractional order

  • definition – Mathematical definition

  • use_jax – Whether to use JAX optimizations

  • use_numba – Whether to use NUMBA optimizations

compute(f, x, **kwargs)[source]

Compute the Weyl fractional derivative using advanced methods.

Parameters:
Return type:

float | ndarray

compute_numerical(f_values, x_values, **kwargs)[source]

Compute the Weyl fractional derivative numerically using advanced methods.

Parameters:
Return type:

ndarray

class hpfracc.core.fractional_implementations.MarchaudDerivative(order, **kwargs)[source]

Bases: BaseFractionalDerivative

Marchaud fractional derivative implementation.

Uses the advanced implementation from algorithms with difference quotient convolution and memory optimization.

Parameters:

order (float | FractionalOrder)

__init__(order, **kwargs)[source]

Initialize fractional derivative.

Parameters:
  • order (float | FractionalOrder) – Fractional order

  • definition – Mathematical definition

  • use_jax – Whether to use JAX optimizations

  • use_numba – Whether to use NUMBA optimizations

compute(f, x, **kwargs)[source]

Compute the Marchaud fractional derivative using advanced methods.

Parameters:
Return type:

float | ndarray

compute_numerical(f_values, x_values, **kwargs)[source]

Compute the Marchaud fractional derivative numerically using advanced methods.

Parameters:
Return type:

ndarray

class hpfracc.core.fractional_implementations.HadamardDerivative(order, **kwargs)[source]

Bases: BaseFractionalDerivative

Hadamard fractional derivative implementation.

Uses the advanced implementation from algorithms with logarithmic kernels.

Parameters:

order (float | FractionalOrder)

__init__(order, **kwargs)[source]

Initialize fractional derivative.

Parameters:
  • order (float | FractionalOrder) – Fractional order

  • definition – Mathematical definition

  • use_jax – Whether to use JAX optimizations

  • use_numba – Whether to use NUMBA optimizations

compute(f, x, **kwargs)[source]

Compute the Hadamard fractional derivative using advanced methods.

Parameters:
Return type:

float | ndarray

compute_numerical(f_values, x_values, **kwargs)[source]

Compute the Hadamard fractional derivative numerically using advanced methods.

Parameters:
Return type:

ndarray

class hpfracc.core.fractional_implementations.ReizFellerDerivative(order, **kwargs)[source]

Bases: BaseFractionalDerivative

Reiz-Feller fractional derivative implementation.

Uses the advanced implementation from algorithms with spectral methods.

Parameters:

order (float | FractionalOrder)

__init__(order, **kwargs)[source]

Initialize fractional derivative.

Parameters:
  • order (float | FractionalOrder) – Fractional order

  • definition – Mathematical definition

  • use_jax – Whether to use JAX optimizations

  • use_numba – Whether to use NUMBA optimizations

compute(f, x, **kwargs)[source]

Compute the Reiz-Feller fractional derivative using advanced methods.

Parameters:
Return type:

float | ndarray

compute_numerical(f_values, x_values, **kwargs)[source]

Compute the Reiz-Feller fractional derivative numerically using advanced methods.

Parameters:
Return type:

ndarray

class hpfracc.core.fractional_implementations.RieszFisherOperator(alpha, **kwargs)[source]

Bases: BaseFractionalDerivative

Riesz-Fisher fractional operator implementation.

The Riesz-Fisher operator is a combination of left and right fractional derivatives/integrals that is particularly useful in signal processing and image analysis. It’s defined as:

R^α f(x) = (1/2) * [D^α_+ f(x) + D^α_- f(x)]

where D^α_+ is the left-sided and D^α_- is the right-sided operator.

For α > 0: acts as a derivative For α < 0: acts as an integral For α = 0: acts as identity

Parameters:

alpha (float | FractionalOrder)

__init__(alpha, **kwargs)[source]

Initialize fractional derivative.

Parameters:
  • order – Fractional order

  • definition – Mathematical definition

  • use_jax – Whether to use JAX optimizations

  • use_numba – Whether to use NUMBA optimizations

  • alpha (float | FractionalOrder)

compute(f, x, **kwargs)[source]

Compute the Riesz-Fisher fractional operator.

Parameters:
Return type:

float | ndarray

compute_numerical(f_values, x_values, **kwargs)[source]

Compute the Riesz-Fisher fractional operator numerically.

Parameters:
Return type:

ndarray

class hpfracc.core.fractional_implementations.AdomianDecompositionMethod(max_terms=10, tolerance=1e-06)[source]

Bases: object

Adomian Decomposition Method for solving fractional differential equations.

This is an analytical method that decomposes the solution into a series of components that can be computed iteratively.

Parameters:
__init__(max_terms=10, tolerance=1e-06)[source]

Initialize the Adomian Decomposition Method.

Parameters:
  • max_terms (int) – Maximum number of terms to compute

  • tolerance (float) – Convergence tolerance

solve(equation, initial_condition, domain, **kwargs)[source]

Solve a fractional differential equation using Adomian decomposition.

Parameters:
  • equation (Callable) – The fractional differential equation

  • initial_condition (Callable) – Initial condition function

  • domain (Tuple[float, float] | ndarray) – Solution domain or array of points

  • **kwargs – Additional parameters

Returns:

Solution dictionary with components and convergence info

Return type:

Dict[str, Any]

compute_adomian_polynomials(nonlinear_term, u_series, order)[source]

Compute Adomian polynomials for nonlinear terms.

Parameters:
  • nonlinear_term (Callable) – The nonlinear term in the equation

  • u_series (List[Callable]) – Series of solution components

  • order (int) – Order of the polynomial to compute

Returns:

List of Adomian polynomial functions

Return type:

List[Callable]

decompose_function(func, x_vals)[source]

Decompose a function using Adomian decomposition.

Parameters:
  • func (Callable) – Function to decompose

  • x_vals (ndarray) – Array of x values

Returns:

Decomposed function values

Return type:

ndarray

solve_equation(func, x_vals)[source]

Solve an equation using Adomian decomposition.

Parameters:
  • func (Callable) – Equation function

  • x_vals (ndarray) – Array of x values

Returns:

Solution values

Return type:

ndarray

hpfracc.core.fractional_implementations.create_fractional_integral(method, alpha, **kwargs)[source]

Create a fractional integral implementation.

Parameters:
  • method (str) – Integration method (“RL” for Riemann-Liouville)

  • alpha (float | FractionalOrder) – Fractional order

  • **kwargs – Additional parameters

Returns:

Fractional integral implementation

hpfracc.core.fractional_implementations.create_riesz_fisher_operator(alpha, **kwargs)[source]

Create a Riesz-Fisher fractional operator.

Parameters:
  • alpha (float | FractionalOrder) – Fractional order - α > 0: acts as a derivative - α < 0: acts as an integral - α = 0: acts as identity

  • **kwargs – Additional parameters

Returns:

RieszFisherOperator instance

hpfracc.core.fractional_implementations.register_fractional_implementations()[source]

Register all fractional derivative implementations with the factory.

This function should be called during package initialization.

Core Derivatives

Base classes for fractional derivatives.

This module provides abstract base classes and common interfaces for implementing different fractional derivative definitions.

class hpfracc.core.derivatives.BaseFractionalDerivative(order, definition=None, use_jax=False, use_numba=True)[source]

Bases: ABC

Abstract base class for fractional derivatives.

This class defines the common interface that all fractional derivative implementations must follow.

Parameters:
__init__(order, definition=None, use_jax=False, use_numba=True)[source]

Initialize fractional derivative.

Parameters:
  • order (float | FractionalOrder) – Fractional order

  • definition (FractionalDefinition | None) – Mathematical definition

  • use_jax (bool) – Whether to use JAX optimizations

  • use_numba (bool) – Whether to use NUMBA optimizations

_validate_parameters()[source]

Validate input parameters.

abstractmethod compute(f, x, **kwargs)[source]

Compute the fractional derivative of function f at point(s) x.

Parameters:
  • f (Callable) – Function to differentiate

  • x (float | ndarray | jax.numpy.ndarray) – Point(s) at which to compute the derivative

  • **kwargs – Additional parameters

Returns:

Fractional derivative value(s)

Return type:

float | ndarray | jax.numpy.ndarray

abstractmethod compute_numerical(f_values, x_values, **kwargs)[source]

Compute the fractional derivative numerically from function values.

Parameters:
  • f_values (ndarray | jax.numpy.ndarray) – Function values at x_values

  • x_values (ndarray | jax.numpy.ndarray) – Points where function is evaluated

  • **kwargs – Additional parameters

Returns:

Fractional derivative values

Return type:

ndarray | jax.numpy.ndarray

get_definition_info()[source]

Get information about the mathematical definition.

Return type:

Dict[str, Any]

class hpfracc.core.derivatives.FractionalDerivativeOperator(alpha, definition_type=DefinitionType.CAPUTO, use_jax=False, use_numba=True)[source]

Bases: object

High-level operator for fractional derivatives.

This class provides a unified interface for different fractional derivative definitions and implementations.

Parameters:
__init__(alpha, definition_type=DefinitionType.CAPUTO, use_jax=False, use_numba=True)[source]

Initialize fractional derivative operator.

Parameters:
  • alpha (float | FractionalOrder) – Fractional order

  • definition_type (str | DefinitionType) – Type of fractional definition

  • use_jax (bool) – Whether to use JAX optimizations

  • use_numba (bool) – Whether to use NUMBA optimizations

compute_numerical(f_values, x_values, **kwargs)[source]

Compute the fractional derivative numerically.

Parameters:
  • f_values (ndarray | jax.numpy.ndarray) – Function values at x_values

  • x_values (ndarray | jax.numpy.ndarray) – Points where function is evaluated

  • **kwargs – Additional parameters

Returns:

Fractional derivative values

Return type:

ndarray | jax.numpy.ndarray

set_implementation(implementation)[source]

Set the implementation for this operator.

Parameters:

implementation (BaseFractionalDerivative)

get_info()[source]

Get comprehensive information about this operator.

Return type:

Dict[str, Any]

class hpfracc.core.derivatives.FractionalDerivativeFactory[source]

Bases: object

Factory class for creating fractional derivative implementations.

This class provides a convenient way to create different types of fractional derivative implementations.

__init__()[source]

Initialize the factory.

register_implementation(definition_type, implementation_class)[source]

Register an implementation for a specific definition type.

Parameters:
  • definition_type (DefinitionType) – Type of fractional definition

  • implementation_class (type) – Implementation class

create(definition_type, alpha, use_jax=False, use_numba=True, **kwargs)[source]

Create a fractional derivative implementation.

Parameters:
  • definition_type (str | DefinitionType) – Type of fractional definition

  • alpha (float | FractionalOrder) – Fractional order

  • use_jax (bool) – Whether to use JAX optimizations

  • use_numba (bool) – Whether to use NUMBA optimizations

  • **kwargs – Additional parameters for the implementation

Returns:

Fractional derivative implementation

Return type:

BaseFractionalDerivative

get_available_implementations()[source]

Get list of available implementation types.

Return type:

List[str]

class hpfracc.core.derivatives.FractionalDerivativeChain(derivatives)[source]

Bases: object

Chain of fractional derivatives for composition.

This class allows composing multiple fractional derivatives to create higher-order or mixed-order derivatives.

Parameters:

derivatives (List[BaseFractionalDerivative])

__init__(derivatives)[source]

Initialize derivative chain.

Parameters:

derivatives (List[BaseFractionalDerivative]) – List of fractional derivatives to chain

_validate_chain()[source]

Validate the derivative chain.

compute(f, x, **kwargs)[source]

Compute the chained fractional derivative.

Parameters:
  • f (Callable) – Function to differentiate

  • x (float | ndarray | jax.numpy.ndarray) – Point(s) at which to compute the derivative

  • **kwargs – Additional parameters

Returns:

Chained fractional derivative value(s)

Return type:

float | ndarray | jax.numpy.ndarray

get_total_order()[source]

Get the total fractional order of the chain.

Return type:

float

get_chain_info()[source]

Get information about each derivative in the chain.

Return type:

List[Dict[str, Any]]

class hpfracc.core.derivatives.FractionalDerivativeProperties[source]

Bases: object

Properties and utilities for fractional derivatives.

static check_linearity(derivative, f, g, x, a=1.0, b=1.0, tolerance=1e-10)[source]

Check if a fractional derivative satisfies linearity.

Parameters:
Returns:

True if linearity is satisfied

Return type:

bool

static check_semigroup_property(derivative_class, alpha, beta, f, x, tolerance=1e-10)[source]

Check if a fractional derivative satisfies the semigroup property.

Parameters:
  • derivative_class (type) – Class of fractional derivative

  • alpha (float) – Fractional orders

  • beta (float) – Fractional orders

  • f (Callable) – Function to test

  • x (float | ndarray) – Point(s) to test at

  • tolerance (float) – Numerical tolerance

Returns:

True if semigroup property is satisfied

Return type:

bool

static get_analytical_solutions()[source]

Get analytical solutions for common functions.

Returns:

Dictionary of analytical solutions

Return type:

Dict[str, Callable]

hpfracc.core.derivatives.create_fractional_derivative(definition_type, alpha, use_jax=False, use_numba=True, **kwargs)[source]

Create a fractional derivative implementation.

Parameters:
  • definition_type (str | DefinitionType) – Type of fractional definition

  • alpha (float | FractionalOrder) – Fractional order

  • use_jax (bool) – Whether to use JAX optimizations

  • use_numba (bool) – Whether to use NUMBA optimizations

  • **kwargs – Additional parameters

Returns:

Fractional derivative implementation

Return type:

BaseFractionalDerivative

hpfracc.core.derivatives.create_derivative_operator(definition_type, alpha, use_jax=False, use_numba=True)[source]

Create a fractional derivative operator.

Parameters:
  • definition_type (str | DefinitionType) – Type of fractional definition

  • alpha (float | FractionalOrder) – Fractional order

  • use_jax (bool) – Whether to use JAX optimizations

  • use_numba (bool) – Whether to use NUMBA optimizations

Returns:

Fractional derivative operator

Return type:

FractionalDerivativeOperator

hpfracc.core.derivatives.caputo(f, alpha, **kwargs)[source]

Convenience function for Caputo derivative (canonical Caputo engine).

hpfracc.core.derivatives.riemann_liouville(f, alpha, **kwargs)[source]

Convenience function for Riemann-Liouville derivative (canonical engine).

hpfracc.core.derivatives.grunwald_letnikov(f, alpha, **kwargs)[source]

Convenience function for Grünwald-Letnikov derivative (canonical engine).

Core Integrals

Fractional Integrals Module

Canonical integral path for the library: subclasses of FractionalIntegral here are what hpfracc re-exports and what core workflows should use. For an FFT-focused API with a different surface (method="fft", alpha= kwargs), see hpfracc.algorithms.integral_methods — that module is legacy/alternate, not a second copy of these quadrature-based classes. The hpfracc.core package loads this submodule lazily (see core/__init__.py); prefer import hpfracc.core.integrals when you only need integrals.

This module provides comprehensive implementations of fractional integrals including: - Riemann-Liouville fractional integrals - Caputo fractional integrals - Weyl fractional integrals - Hadamard fractional integrals - Numerical methods for fractional integration - Special cases and analytical solutions

hpfracc.core.integrals._handle_integration_failure(method, x, error)[source]

Handle numerical integration failures without fabricating valid-looking values.

Returning NaN makes downstream quality checks catch failures instead of silently treating failures as valid zeros.

Parameters:
Return type:

float

class hpfracc.core.integrals.FractionalIntegral(order, method='RL')[source]

Bases: object

Base class for fractional integral implementations.

This class provides the foundation for different types of fractional integrals and their numerical implementations.

Parameters:
__init__(order, method='RL')[source]

Initialize fractional integral.

Parameters:
  • order (float | FractionalOrder) – Fractional order (0 < α < 1 for most methods)

  • method (str) – Integration method (“RL”, “Caputo”, “Weyl”, “Hadamard”)

_validate_parameters()[source]

Validate fractional order and method parameters.

compute(f, x, h=None)[source]

Alias for __call__; accepts an optional step size h for compatibility.

Parameters:
Return type:

float | ndarray | torch.Tensor

class hpfracc.core.integrals.RiemannLiouvilleIntegral(order)[source]

Bases: FractionalIntegral

Riemann-Liouville fractional integral.

The Riemann-Liouville fractional integral of order α is defined as:

I^α f(t) = (1/Γ(α)) ∫₀ᵗ (t-τ)^(α-1) f(τ) dτ

where Γ(α) is the gamma function.

Parameters:

order (float | FractionalOrder)

__init__(order)[source]

Initialize fractional integral.

Parameters:
  • order (float | FractionalOrder) – Fractional order (0 < α < 1 for most methods)

  • method – Integration method (“RL”, “Caputo”, “Weyl”, “Hadamard”)

compute(f, x, h=None)[source]

Compute Riemann-Liouville fractional integral (alias for __call__).

Parameters:
  • f (Callable) – Function to integrate

  • x (float | ndarray | torch.Tensor) – Point(s) at which to evaluate the integral

  • h (float)

Returns:

Fractional integral value(s)

Return type:

float | ndarray | torch.Tensor

_coerce_function(f, x_arg)[source]

If f is an array, create an interpolating callable over x grid.

Parameters:
Return type:

Callable

_compute_scalar(f, x)[source]

Compute fractional integral at a scalar point.

Parameters:
Return type:

float

_compute_array_numpy(f, x)[source]

Compute fractional integral for numpy array.

Parameters:
Return type:

ndarray

_compute_array_torch(f, x)[source]

Compute fractional integral for torch tensor.

Parameters:
Return type:

torch.Tensor

class hpfracc.core.integrals.CaputoIntegral(order)[source]

Bases: FractionalIntegral

Caputo fractional integral.

The Caputo fractional integral is related to the Riemann-Liouville integral and is often more suitable for initial value problems.

Supports all fractional orders α ≥ 0: - For 0 < α < 1: Equals Riemann-Liouville integral - For α ≥ 1: Uses decomposition I^α = I^n * I^β where α = n + β

Examples

>>> from hpfracc.core.integrals import CaputoIntegral
>>> def f(x): return x**2
>>> # For 0 < α < 1
>>> integral_05 = CaputoIntegral(0.5)
>>> result = integral_05(f, 1.0)
>>> # For α ≥ 1
>>> integral_15 = CaputoIntegral(1.5)
>>> result = integral_15(f, 1.0)
Parameters:

order (float | FractionalOrder)

__init__(order)[source]

Initialize fractional integral.

Parameters:
  • order (float | FractionalOrder) – Fractional order (0 < α < 1 for most methods)

  • method – Integration method (“RL”, “Caputo”, “Weyl”, “Hadamard”)

_coerce_function(f, x_arg)[source]

If f is an array, create an interpolating callable over x grid.

Parameters:
Return type:

Callable

compute(f, x, h=None)[source]

Alias for __call__; accepts an optional step size h for compatibility.

Parameters:
Return type:

float | ndarray | torch.Tensor

class hpfracc.core.integrals.WeylIntegral(order)[source]

Bases: FractionalIntegral

Weyl fractional integral.

The Weyl fractional integral is suitable for functions defined on the entire real line and is particularly useful for periodic functions.

Parameters:

order (float | FractionalOrder)

__init__(order)[source]

Initialize fractional integral.

Parameters:
  • order (float | FractionalOrder) – Fractional order (0 < α < 1 for most methods)

  • method – Integration method (“RL”, “Caputo”, “Weyl”, “Hadamard”)

_compute_scalar(f, x)[source]

Compute Weyl fractional integral at a scalar point.

Parameters:
Return type:

float

_coerce_function(f, x_arg)[source]

If f is an array, create an interpolating callable over x grid.

Parameters:
Return type:

Callable

_compute_array_numpy(f, x)[source]

Compute Weyl fractional integral for numpy array.

Parameters:
Return type:

ndarray

compute(f, x, h=None)[source]

Compute Weyl integral; h parameter is accepted for compatibility but not used.

Parameters:
Return type:

float | ndarray | torch.Tensor

_compute_array_torch(f, x)[source]

Compute Weyl fractional integral for torch tensor.

Parameters:
Return type:

torch.Tensor

class hpfracc.core.integrals.HadamardIntegral(order)[source]

Bases: FractionalIntegral

Hadamard fractional integral.

The Hadamard fractional integral uses logarithmic kernels and is defined as: I^α_H f(t) = (1/Γ(α)) ∫₁ᵗ (ln(t/τ))^(α-1) f(τ) dτ/τ

Parameters:

order (float | FractionalOrder)

__init__(order)[source]

Initialize fractional integral.

Parameters:
  • order (float | FractionalOrder) – Fractional order (0 < α < 1 for most methods)

  • method – Integration method (“RL”, “Caputo”, “Weyl”, “Hadamard”)

_compute_scalar(f, x)[source]

Compute Hadamard fractional integral at a scalar point.

Parameters:
Return type:

float

_compute_array_numpy(f, x)[source]

Compute Hadamard fractional integral for numpy array.

Parameters:
Return type:

ndarray

_compute_array_torch(f, x)[source]

Compute Hadamard fractional integral for torch tensor.

Parameters:
Return type:

torch.Tensor

hpfracc.core.integrals.create_fractional_integral(order, method='RL')[source]

Factory function to create fractional integral objects.

Parameters:
  • order (float | FractionalOrder) – Fractional order

  • method (str) – Integration method (“RL”, “Caputo”, “Weyl”, “Hadamard”)

Returns:

Appropriate fractional integral object

Return type:

FractionalIntegral

hpfracc.core.integrals.analytical_fractional_integral(f_type, alpha, x)[source]

Compute analytical fractional integrals for common functions.

Parameters:
  • f_type (str) – Type of function (“power”, “exponential”, “trigonometric”)

  • alpha (float) – Fractional order

  • x (float | ndarray) – Point(s) at which to evaluate

Returns:

Analytical fractional integral value(s)

Return type:

float | ndarray

hpfracc.core.integrals.trapezoidal_fractional_integral(f, x, alpha, method='RL')[source]

Compute fractional integral using trapezoidal rule.

Parameters:
  • f (Callable) – Function to integrate

  • x (ndarray) – Points at which to evaluate

  • alpha (float) – Fractional order

  • method (str) – Integration method

Returns:

Fractional integral values

Return type:

ndarray

hpfracc.core.integrals.simpson_fractional_integral(f, x, alpha, method='RL')[source]

Compute fractional integral using Simpson’s rule.

Parameters:
  • f (Callable) – Function to integrate

  • x (ndarray) – Points at which to evaluate

  • alpha (float) – Fractional order

  • method (str) – Integration method

Returns:

Fractional integral values

Return type:

ndarray

hpfracc.core.integrals.fractional_integral_properties(alpha)[source]

Return mathematical properties of fractional integrals.

Parameters:

alpha (float) – Fractional order

Returns:

Dictionary containing properties

Return type:

dict

hpfracc.core.integrals.validate_fractional_integral(f, integral_result, x, alpha, method='RL')[source]

Validate fractional integral computation.

Parameters:
  • f (Callable) – Original function

  • integral_result (ndarray) – Computed fractional integral

  • x (ndarray) – Points at which integral was computed

  • alpha (float) – Fractional order

  • method (str) – Integration method

Returns:

Validation results

Return type:

dict

class hpfracc.core.integrals.MillerRossIntegral(order)[source]

Bases: FractionalIntegral

Miller-Ross fractional integral.

The Miller-Ross fractional integral is defined as: I^α_MR f(t) = (1/Γ(α)) ∫₀ᵗ (t-τ)^(α-1) f(τ) dτ

This is similar to Riemann-Liouville but with different normalization.

Parameters:

order (float | FractionalOrder)

__init__(order)[source]

Initialize fractional integral.

Parameters:
  • order (float | FractionalOrder) – Fractional order (0 < α < 1 for most methods)

  • method – Integration method (“RL”, “Caputo”, “Weyl”, “Hadamard”)

_coerce_function(f, x_arg)[source]

If f is an array, create an interpolating callable over x grid.

Parameters:
Return type:

Callable

_compute_scalar(f, x)[source]

Compute Miller-Ross fractional integral at a scalar point.

Parameters:
Return type:

float

_compute_array_numpy(f, x)[source]

Compute Miller-Ross fractional integral for numpy array.

Parameters:
Return type:

ndarray

_compute_array_torch(f, x)[source]

Compute Miller-Ross fractional integral for torch tensor.

Parameters:
Return type:

torch.Tensor

class hpfracc.core.integrals.MarchaudIntegral(order)[source]

Bases: FractionalIntegral

Marchaud fractional integral.

The Marchaud fractional integral is defined as: I^α_M f(t) = (1/Γ(α)) ∫₀ᵗ (t-τ)^(α-1) f(τ) dτ

This is a generalization that can handle more general kernels.

Parameters:

order (float | FractionalOrder)

__init__(order)[source]

Initialize fractional integral.

Parameters:
  • order (float | FractionalOrder) – Fractional order (0 < α < 1 for most methods)

  • method – Integration method (“RL”, “Caputo”, “Weyl”, “Hadamard”)

_compute_scalar(f, x)[source]

Compute Marchaud fractional integral at a scalar point.

Parameters:
Return type:

float

_compute_array_numpy(f, x)[source]

Compute Marchaud fractional integral for numpy array.

Parameters:
Return type:

ndarray

_compute_array_torch(f, x)[source]

Compute Marchaud fractional integral for torch tensor.

Parameters:
Return type:

torch.Tensor

class hpfracc.core.integrals.FractionalIntegralFactory[source]

Bases: object

Factory class for creating fractional integral implementations.

This class provides a convenient way to create different types of fractional integral implementations.

__init__()[source]

Initialize the factory.

register_implementation(method, implementation_class)[source]

Register an implementation for a specific method.

Parameters:
  • method (str) – Integration method (e.g., “RL”, “Caputo”, “Weyl”, “Hadamard”)

  • implementation_class (type) – Implementation class

create(method, alpha, **kwargs)[source]

Create a fractional integral implementation.

Parameters:
  • method (str) – Integration method

  • alpha (float | FractionalOrder) – Fractional order

  • **kwargs – Additional parameters for the implementation

Returns:

Fractional integral implementation

Return type:

FractionalIntegral

get_available_methods()[source]

Get list of available integration methods.

Return type:

List[str]

hpfracc.core.integrals.create_fractional_integral_factory(method, order, **kwargs)[source]

Create a fractional integral implementation using the factory.

Parameters:
  • method (str) – Integration method (“RL”, “Caputo”, “Weyl”, “Hadamard”)

  • alpha – Fractional order

  • **kwargs – Additional parameters

  • order (float | FractionalOrder)

Returns:

Fractional integral implementation

Return type:

FractionalIntegral

Machine Learning Module

Fractional Autograd Framework

Spectral fractional calculus utilities for ML integration.

This module provides a small, self-contained implementation that satisfies the expectations encoded in the extensive test-suite that accompanies the library. It focuses on three primary responsibilities:

  • Safe FFT utilities with backend selection and graceful fallbacks.

  • Spectral fractional derivative helpers that operate on PyTorch tensors while remaining differentiable with respect to both the input and the fractional order parameter alpha.

  • Thin neural-network wrappers (layers, learnable alpha parameters, and simple network scaffolding) that integrate the derivative into PyTorch models.

The goal is functional correctness and API compatibility rather than raw numerical performance; consequently many routines favour clarity and predictability over micro-optimisation. Every public utility is intentionally simple and well-behaved so that the surrounding tests can exercise a broad range of scenarios (different dtypes, devices, edge-cases, etc.).

Relation to ``FractionalNeuralNetwork``: that class (in hpfracc.ml.core) is a separate multi-backend MLP whose optional fractional preprocessing uses discrete Grünwald–Letnikov / L1-Caputo along a chosen axis (see hpfracc.ml.fractional_derivative_native). This module does not subclass or call FractionalNeuralNetwork; SpectralFractionalNetwork here stacks linear layers with spectral (FFT) fractional derivatives instead.

hpfracc.ml.spectral_autograd.set_fft_backend(backend)[source]

Select the preferred FFT backend.

Parameters:

backend (str) – One of the identifiers listed in _ALLOWED_BACKENDS. The value is stored verbatim (after lower-casing) for retrieval via get_fft_backend(), while internal helpers map it to the effective behaviour (Torch FFT, NumPy FFT, robust fallback, etc.).

Return type:

str

hpfracc.ml.spectral_autograd.get_fft_backend()[source]

Return the currently configured FFT backend identifier.

Return type:

str

hpfracc.ml.spectral_autograd.safe_fft(x, dim=-1, norm='ortho', backend=None)[source]

FFT helper that honours the configured backend and preserves dtype.

Parameters:
  • x (torch.Tensor)

  • dim (int)

  • norm (str)

  • backend (str | None)

Return type:

torch.Tensor

hpfracc.ml.spectral_autograd.safe_ifft(x, dim=-1, norm='ortho', backend=None)[source]
Parameters:
  • x (torch.Tensor)

  • dim (int)

  • norm (str)

  • backend (str | None)

Return type:

torch.Tensor

hpfracc.ml.spectral_autograd.robust_fft(x, dim=-1, norm='ortho')[source]

FFT with an automatic fallback to NumPy when PyTorch fails.

Parameters:
  • x (torch.Tensor)

  • dim (int)

  • norm (str)

Return type:

torch.Tensor

hpfracc.ml.spectral_autograd.robust_ifft(x, dim=-1, norm='ortho')[source]
Parameters:
  • x (torch.Tensor)

  • dim (int)

  • norm (str)

Return type:

torch.Tensor

hpfracc.ml.spectral_autograd.spectral_fractional_derivative(x, alpha, kernel_type='riesz', dim=-1, backend=None, **kwargs)[source]

Dispatcher for spectral fractional derivative. Selects backend based on input tensor type.

Parameters:
Return type:

torch.Tensor | jax.Array

hpfracc.ml.spectral_autograd.fractional_derivative(x, alpha, kernel_type='riesz', dim=-1, norm='ortho', backend=None, epsilon=1e-06)[source]

Public alias used throughout the tests.

Parameters:
Return type:

torch.Tensor

class hpfracc.ml.spectral_autograd.SpectralFractionalDerivative(alpha=0.5, dim=-1, backend=None, kernel_type='riesz', norm='ortho', epsilon=1e-06)[source]

Bases: object

Callable wrapper that mimics the autograd Function.apply interface.

Parameters:
  • alpha (_Alpha)

  • dim (_DimType)

  • backend (_Backend)

  • kernel_type (str)

  • norm (str)

  • epsilon (float)

__init__(alpha=0.5, dim=-1, backend=None, kernel_type='riesz', norm='ortho', epsilon=1e-06)[source]

Initialize the spectral fractional derivative operator.

Parameters:
  • alpha (int | float | torch.Tensor) – Fractional order (default: 0.5)

  • dim (int | Sequence[int] | None) – Dimension along which to compute derivative (default: -1)

  • backend (str | None) – FFT backend to use (default: None, uses global setting)

  • kernel_type (str) – Type of fractional kernel (default: “riesz”)

  • norm (str) – FFT normalization mode (default: “ortho”)

  • epsilon (float) – Small value for numerical stability (default: 1e-6)

static apply(x, alpha, kernel_type='riesz', dim=-1, norm='ortho', backend=None, epsilon=1e-06)[source]

Static method for backward compatibility.

Parameters:
Return type:

torch.Tensor

class hpfracc.ml.spectral_autograd.SpectralFractionalFunction(alpha=0.5, dim=-1, backend=None, kernel_type='riesz', norm='ortho', epsilon=1e-06)[source]

Bases: object

Legacy-style interface exposing explicit forward/backward hooks.

Parameters:
  • alpha (_Alpha)

  • dim (_DimType)

  • backend (_Backend)

  • kernel_type (str)

  • norm (str)

  • epsilon (float)

__init__(alpha=0.5, dim=-1, backend=None, kernel_type='riesz', norm='ortho', epsilon=1e-06)[source]

Initialize the spectral fractional function.

Parameters:
  • alpha (int | float | torch.Tensor) – Fractional order (default: 0.5)

  • dim (int | Sequence[int] | None) – Dimension along which to compute derivative (default: -1)

  • backend (str | None) – FFT backend to use (default: None, uses global setting)

  • kernel_type (str) – Type of fractional kernel (default: “riesz”)

  • norm (str) – FFT normalization mode (default: “ortho”)

  • epsilon (float) – Small value for numerical stability (default: 1e-6)

static forward(x, alpha, **kwargs)[source]

Static forward method for backward compatibility.

Parameters:
  • x (torch.Tensor)

  • alpha (int | float | torch.Tensor)

Return type:

torch.Tensor

static backward(grad_output, alpha, **kwargs)[source]

Static backward method for backward compatibility.

Parameters:
  • grad_output (torch.Tensor)

  • alpha (int | float | torch.Tensor)

Return type:

torch.Tensor

class hpfracc.ml.spectral_autograd.SpectralFractionalLayer(*args, **kwargs)[source]

Bases: Module

Apply a spectral fractional derivative inside a PyTorch layer.

Parameters:
  • input_size (Optional[int])

  • output_size (Optional[int])

  • alpha (_Alpha)

  • kernel_type (str)

  • dim (_DimType)

  • norm (str)

  • backend (_Backend)

  • epsilon (float)

  • learnable_alpha (bool)

__init__(input_size=None, output_size=None, alpha=0.5, kernel_type='riesz', dim=-1, norm='ortho', backend=None, epsilon=1e-06, learnable_alpha=False, **kwargs)[source]
Parameters:
Return type:

None

property alpha: float
property learnable: bool
get_alpha()[source]
Return type:

float | torch.Tensor

forward(x)[source]
Parameters:

x (torch.Tensor)

Return type:

torch.Tensor

class hpfracc.ml.spectral_autograd.SpectralFractionalNetwork(*args, **kwargs)[source]

Bases: Module

Simple network that incorporates spectral fractional layers.

Modes - unified (default): unified adaptive framework (input_dim, hidden_dims, output_dim). - model: model-specific/coverage style (input_size, hidden_sizes, output_size).

Backends - torch (default), jax, numba. If unavailable, CPU-safe fallbacks are used.

Parameters:
  • input_size (Optional[int])

  • hidden_sizes (Optional[Sequence[int]])

  • output_size (Optional[int])

  • alpha (_Alpha)

  • input_dim (Optional[int])

  • hidden_dims (Optional[Sequence[int]])

  • output_dim (Optional[int])

  • kernel_type (str)

  • activation (Union[str, nn.Module, None])

  • learnable_alpha (bool)

  • backend (_Backend)

  • norm (str)

  • epsilon (float)

  • mode (str)

__init__(input_size=None, hidden_sizes=None, output_size=None, alpha=0.5, *, input_dim=None, hidden_dims=None, output_dim=None, kernel_type='riesz', activation='relu', learnable_alpha=False, backend=None, norm='ortho', epsilon=1e-06, mode='unified', **kwargs)[source]
Parameters:
  • input_size (int | None)

  • hidden_sizes (Sequence[int] | None)

  • output_size (int | None)

  • alpha (int | float | torch.Tensor)

  • input_dim (int | None)

  • hidden_dims (Sequence[int] | None)

  • output_dim (int | None)

  • kernel_type (str)

  • activation (str | torch.nn.Module | None)

  • learnable_alpha (bool)

  • backend (str | None)

  • norm (str)

  • epsilon (float)

  • mode (str)

Return type:

None

forward(x)[source]
Parameters:

x (torch.Tensor)

Return type:

torch.Tensor

class hpfracc.ml.spectral_autograd.BoundedAlphaParameter(*args, **kwargs)[source]

Bases: Module

Learnable scalar constrained to the open interval (alpha_min, alpha_max).

Parameters:
__init__(alpha=0.5, min_alpha=0.0, max_alpha=2.0, alpha_init=None, alpha_min=None, alpha_max=None, learnable_alpha=True)[source]
Parameters:
Return type:

None

property alpha: float

Get current alpha value.

forward(x=None)[source]

Forward pass - returns alpha value, optionally applies to input tensor.

Parameters:

x (torch.Tensor | None)

Return type:

torch.Tensor

extra_repr()[source]
Return type:

str

hpfracc.ml.spectral_autograd.create_fractional_layer(input_size=None, *, alpha=0.5, kernel_type='riesz', dim=-1, norm='ortho', backend=None, epsilon=1e-06, learnable_alpha=False, activation=None)[source]
Parameters:
Return type:

SpectralFractionalLayer

hpfracc.ml.spectral_autograd.benchmark_backends(x=None, alpha=None, *, iterations=10, kernel_type='riesz', dim=-1, norm='ortho', epsilon=1e-06, test_size=100, num_iterations=None, backends=None)[source]

Crude benchmarking helper used in documentation and diagnostics.

Parameters:
  • x (Optional[Tensor])

  • alpha (Optional[_Alpha])

  • iterations (int)

  • kernel_type (str)

  • dim (_DimType)

  • norm (str)

  • epsilon (float)

  • test_size (int)

  • num_iterations (Optional[int])

  • backends (Optional[List[str]])

Return type:

dict

hpfracc.ml.spectral_autograd.original_set_fft_backend(backend)[source]
Parameters:

backend (str)

Return type:

str

hpfracc.ml.spectral_autograd.original_get_fft_backend()[source]
Return type:

str

hpfracc.ml.spectral_autograd.original_safe_fft(x, dim=-1, norm='ortho', backend=None)[source]
Parameters:
  • x (torch.Tensor)

  • dim (int)

  • norm (str)

  • backend (str | None)

Return type:

torch.Tensor

hpfracc.ml.spectral_autograd.original_safe_ifft(x, dim=-1, norm='ortho', backend=None)[source]
Parameters:
  • x (torch.Tensor)

  • dim (int)

  • norm (str)

  • backend (str | None)

Return type:

torch.Tensor

hpfracc.ml.spectral_autograd.original_get_fractional_kernel(alpha, n, kernel_type='riesz', epsilon=1e-06, dtype=None, device=None)[source]
Parameters:
  • alpha (int | float | torch.Tensor)

  • n (int)

  • kernel_type (str)

  • epsilon (float)

  • dtype (torch.dtype | None)

  • device (torch.device | None)

Return type:

torch.Tensor

hpfracc.ml.spectral_autograd.original_spectral_fractional_derivative(x, alpha, kernel_type='riesz', dim=-1, norm='ortho', backend=None, epsilon=1e-06)[source]
Parameters:
Return type:

torch.Tensor

hpfracc.ml.spectral_autograd.OriginalSpectral

alias of SpectralFractionalDerivative

hpfracc.ml.spectral_autograd.OriginalSpectralFractionalLayer

alias of SpectralFractionalLayer

hpfracc.ml.spectral_autograd.OriginalSpectralFractionalNetwork

alias of SpectralFractionalNetwork

hpfracc.ml.spectral_autograd.original_create_fractional_layer(input_size=None, *, alpha=0.5, kernel_type='riesz', dim=-1, norm='ortho', backend=None, epsilon=1e-06, learnable_alpha=False, activation=None)
Parameters:
Return type:

SpectralFractionalLayer

Stochastic Memory Sampling for Fractional Derivatives

This module implements unbiased estimators for fractional derivatives using stochastic sampling of the memory history instead of full computation.

class hpfracc.ml.stochastic_memory_sampling.StochasticMemorySampler(alpha, method='importance', **kwargs)[source]

Bases: object

Base class for stochastic memory sampling strategies.

Parameters:
__init__(alpha, method='importance', **kwargs)[source]
Parameters:
sample_indices(n, k)[source]

Sample k indices from history of length n.

Parameters:
Return type:

torch.Tensor

compute_weights(indices, n)[source]

Compute importance weights for sampled indices.

Parameters:
  • indices (torch.Tensor)

  • n (int)

Return type:

torch.Tensor

estimate_derivative(x, indices, weights)[source]

Estimate fractional derivative using sampled indices and weights.

Parameters:
  • x (torch.Tensor)

  • indices (torch.Tensor)

  • weights (torch.Tensor)

Return type:

torch.Tensor

class hpfracc.ml.stochastic_memory_sampling.ImportanceSampler(alpha, tau=0.1, **kwargs)[source]

Bases: StochasticMemorySampler

Importance sampling for fractional derivative memory.

Uses power-law distribution p(j) ∝ (n-j)^(-(1+α-τ)) where τ controls the tempering of the heavy tail.

Parameters:
__init__(alpha, tau=0.1, **kwargs)[source]
Parameters:
sample_indices(n, k)[source]

Sample indices using importance sampling distribution.

Parameters:
Return type:

torch.Tensor

compute_weights(indices, n)[source]

Compute importance weights w(j)/p(j).

Parameters:
  • indices (torch.Tensor)

  • n (int)

Return type:

torch.Tensor

estimate_derivative(x, indices, weights)[source]

Estimate fractional derivative using importance sampling.

Parameters:
  • x (torch.Tensor)

  • indices (torch.Tensor)

  • weights (torch.Tensor)

Return type:

torch.Tensor

class hpfracc.ml.stochastic_memory_sampling.StratifiedSampler(alpha, recent_window=32, tail_ratio=0.3, **kwargs)[source]

Bases: StochasticMemorySampler

Stratified sampling with recent window and tail sampling.

Samples densely from recent history and sparsely from tail.

Parameters:
__init__(alpha, recent_window=32, tail_ratio=0.3, **kwargs)[source]
Parameters:
sample_indices(n, k)[source]

Sample indices using stratified sampling.

Parameters:
Return type:

torch.Tensor

compute_weights(indices, n)[source]

Compute weights for stratified sampling.

Parameters:
  • indices (torch.Tensor)

  • n (int)

Return type:

torch.Tensor

estimate_derivative(x, indices, weights)[source]

Estimate fractional derivative using stratified sampling.

Parameters:
  • x (torch.Tensor)

  • indices (torch.Tensor)

  • weights (torch.Tensor)

Return type:

torch.Tensor

class hpfracc.ml.stochastic_memory_sampling.ControlVariateSampler(alpha, baseline_window=16, **kwargs)[source]

Bases: StochasticMemorySampler

Control variate sampling with deterministic baseline.

Uses a cheap deterministic approximation (e.g., short memory) as baseline and samples only the residual tail.

Parameters:
__init__(alpha, baseline_window=16, **kwargs)[source]
Parameters:
compute_baseline(x)[source]

Compute deterministic baseline using recent window.

Parameters:

x (torch.Tensor)

Return type:

torch.Tensor

sample_indices(n, k)[source]

Sample indices from tail only (excluding baseline window).

Parameters:
Return type:

torch.Tensor

compute_weights(indices, n)[source]

Compute weights for control variate sampling.

Parameters:
  • indices (torch.Tensor)

  • n (int)

Return type:

torch.Tensor

estimate_derivative(x, indices, weights)[source]

Estimate derivative using control variate method.

Parameters:
  • x (torch.Tensor)

  • indices (torch.Tensor)

  • weights (torch.Tensor)

Return type:

torch.Tensor

hpfracc.ml.stochastic_memory_sampling.stochastic_fractional_derivative(x, alpha, k=64, method='importance', **sampler_kwargs)[source]

Public interface for stochastic fractional derivative. Fully differentiable via PyTorch Autograd.

Parameters:
Return type:

torch.Tensor

class hpfracc.ml.stochastic_memory_sampling.StochasticFractionalLayer(*args, **kwargs)[source]

Bases: Module

PyTorch module for stochastic fractional derivatives.

Parameters:
__init__(alpha, k=64, method='importance', **kwargs)[source]
Parameters:
forward(x)[source]

Forward pass.

Parameters:

x (torch.Tensor)

Return type:

torch.Tensor

extra_repr()[source]
Return type:

str

hpfracc.ml.stochastic_memory_sampling.create_stochastic_fractional_layer(alpha, k=64, method='importance', **kwargs)[source]

Convenience function for creating stochastic fractional layer.

Parameters:
Return type:

StochasticFractionalLayer

Probabilistic Fractional Orders Implementation

This module implements probabilistic fractional orders where the fractional order itself becomes a random variable, enabling uncertainty quantification and robust optimization.

hpfracc.ml.probabilistic_fractional_orders.model(x, y)[source]

NumPyro model for Bayesian fractional order.

hpfracc.ml.probabilistic_fractional_orders.guide(x, y)[source]

NumPyro guide for Bayesian fractional order.

class hpfracc.ml.probabilistic_fractional_orders.ProbabilisticFractionalOrder(*args, **kwargs)[source]

Bases: Module

Represents a fractional order alpha as a random variable.

Parameters:
  • backend (str)

  • distribution (torch.distributions.Distribution)

  • learnable (bool)

__init__(model=None, guide=None, backend='numpyro', distribution=None, learnable=False)[source]
Parameters:
  • backend (str)

  • distribution (torch.distributions.Distribution)

  • learnable (bool)

init(rng_key, *args, **kwargs)[source]

Initialize the SVI state.

sample(k=1)[source]
Parameters:

k (int)

log_prob(value)[source]
Parameters:

value (torch.Tensor)

Return type:

torch.Tensor

class hpfracc.ml.probabilistic_fractional_orders.ProbabilisticFractionalLayer(*args, **kwargs)[source]

Bases: Module

PyTorch module for probabilistic fractional derivatives.

__init__(**kwargs)[source]
forward(x)[source]

Forward pass.

Parameters:

x (torch.Tensor)

Return type:

torch.Tensor

sample_alpha(n_samples=1)[source]

Sample fractional orders from the distribution.

Parameters:

n_samples (int)

Return type:

torch.Tensor

get_alpha_statistics()[source]

Get statistics of the fractional order distribution.

Return type:

Dict[str, torch.Tensor]

to(device)[source]

Move layer parameters to specified device (PyTorch compatibility)

extra_repr()[source]
Return type:

str

hpfracc.ml.probabilistic_fractional_orders.create_probabilistic_fractional_layer(**kwargs)[source]

Create a probabilistic fractional layer.

Return type:

ProbabilisticFractionalLayer

hpfracc.ml.probabilistic_fractional_orders.create_normal_alpha_layer(mean, std, learnable=True, **kwargs)[source]

Create probabilistic fractional layer with normal distribution (torch-backed).

Parameters:
Return type:

ProbabilisticFractionalLayer

hpfracc.ml.probabilistic_fractional_orders.create_uniform_alpha_layer(low, high, learnable=False, **kwargs)[source]

Create probabilistic fractional layer with uniform distribution (torch-backed).

Parameters:
Return type:

ProbabilisticFractionalLayer

hpfracc.ml.probabilistic_fractional_orders.create_beta_alpha_layer(a, b, learnable=False, **kwargs)[source]

Create probabilistic fractional layer with beta distribution (torch-backed).

Parameters:
Return type:

ProbabilisticFractionalLayer

Variance-aware training hooks for stochastic and probabilistic fractional calculus.

This module provides training utilities that monitor and control variance in stochastic fractional derivatives and probabilistic fractional orders.

class hpfracc.ml.variance_aware_training.VarianceMetrics(mean, std, variance, coefficient_of_variation, sample_count, timestamp)[source]

Bases: object

Container for variance-related metrics.

Parameters:
mean: float
std: float
variance: float
coefficient_of_variation: float
sample_count: int
timestamp: float
__init__(mean, std, variance, coefficient_of_variation, sample_count, timestamp)
Parameters:
Return type:

None

class hpfracc.ml.variance_aware_training.VarianceMonitor(window_size=100, log_level='INFO')[source]

Bases: object

Monitor variance in stochastic fractional derivatives.

Parameters:
  • window_size (int)

  • log_level (str)

__init__(window_size=100, log_level='INFO')[source]
Parameters:
  • window_size (int)

  • log_level (str)

metrics_history: Dict[str, deque]
property current_metrics

Backward compatibility property for current metrics.

update(name, values, timestamp=None)[source]

Update variance metrics for a given component.

Parameters:
  • name (str)

  • values (torch.Tensor)

  • timestamp (float | None)

get_metrics(name=None)[source]

Get current metrics for a component.

Parameters:

name (str | None)

Return type:

VarianceMetrics | None

get_history(name)[source]

Get historical metrics for a component.

Parameters:

name (str)

Return type:

List[VarianceMetrics]

should_adapt()[source]

Determine if adaptation is needed based on variance levels.

Return type:

bool

get_summary()[source]

Get summary of all monitored components.

Return type:

Dict[str, Dict[str, float]]

class hpfracc.ml.variance_aware_training.StochasticSeedManager(base_seed=42)[source]

Bases: object

Manage random seeds for stochastic fractional derivatives.

Parameters:

base_seed (int)

__init__(base_seed=42)[source]
Parameters:

base_seed (int)

set_seed(seed)[source]

Set the current seed.

Parameters:

seed (int)

get_next_seed()[source]

Get the next seed in sequence.

Return type:

int

reset_to_base()[source]

Reset to base seed.

set_deterministic_mode(deterministic=True)[source]

Enable/disable deterministic mode.

Parameters:

deterministic (bool)

class hpfracc.ml.variance_aware_training.VarianceAwareCallback(monitor, seed_manager, log_interval=10, variance_check_interval=5)[source]

Bases: object

Callback for variance-aware training.

Parameters:
__init__(monitor, seed_manager, log_interval=10, variance_check_interval=5)[source]
Parameters:
on_epoch_begin(epoch, **kwargs)[source]

Called at the beginning of each epoch.

Parameters:

epoch (int)

on_batch_begin(batch_idx, **kwargs)[source]

Called at the beginning of each batch.

Parameters:

batch_idx (int)

on_batch_end(batch_idx, **kwargs)[source]

Called at the end of each batch.

Parameters:

batch_idx (int)

on_epoch_end(epoch, **kwargs)[source]

Called at the end of each epoch.

Parameters:

epoch (int)

_check_variance()[source]

Check variance metrics and log warnings.

_log_variance_summary()[source]

Log variance summary.

class hpfracc.ml.variance_aware_training.AdaptiveSamplingManager(initial_k=32, min_k=8, max_k=256, variance_threshold=0.1)[source]

Bases: object

Adaptively adjust sampling parameters based on variance.

Parameters:
__init__(initial_k=32, min_k=8, max_k=256, variance_threshold=0.1)[source]
Parameters:
update_k(variance, current_k)[source]

Update K based on variance.

Parameters:
Return type:

int

get_current_k()[source]

Get current K value.

Return type:

int

class hpfracc.ml.variance_aware_training.VarianceAwareTrainer(model, optimizer, loss_fn, variance_monitor=None, seed_manager=None, adaptive_sampling=None, callbacks=None)[source]

Bases: object

Enhanced trainer with variance awareness for stochastic fractional calculus.

Parameters:
__init__(model, optimizer, loss_fn, variance_monitor=None, seed_manager=None, adaptive_sampling=None, callbacks=None)[source]
Parameters:
_register_hooks()[source]

Register forward hooks to monitor variance.

train_epoch(dataloader, epoch=0)[source]

Train for one epoch with variance monitoring.

Parameters:

epoch (int)

Return type:

Dict[str, float]

train(dataloader, num_epochs)[source]

Train for multiple epochs.

Parameters:

num_epochs (int)

Return type:

Dict[str, List]

get_variance_summary()[source]

Get current variance summary.

Return type:

Dict[str, Dict[str, float]]

set_sampling_budget(k)[source]

Set sampling budget for stochastic components.

Parameters:

k (int)

enable_deterministic_mode(deterministic=True)[source]

Enable/disable deterministic mode.

Parameters:

deterministic (bool)

hpfracc.ml.variance_aware_training.create_variance_aware_trainer(model, optimizer=None, loss_fn=None, learning_rate=0.001, base_seed=42, variance_threshold=0.1, log_interval=10)[source]

Factory function to create a variance-aware trainer.

Parameters:
  • model (torch.nn.Module)

  • optimizer (torch.optim.Optimizer)

  • loss_fn (torch.nn.Module)

  • learning_rate (float)

  • base_seed (int)

  • variance_threshold (float)

  • log_interval (int)

Return type:

VarianceAwareTrainer

hpfracc.ml.variance_aware_training.test_variance_aware_training()[source]

Test variance-aware training with a simple model.

GPU Optimization

GPU optimization utilities for fractional calculus computations.

This module provides GPU acceleration features including Automatic Mixed Precision (AMP), chunked FFT operations, and performance profiling for fractional calculus operations.

class hpfracc.ml.gpu_optimization.PerformanceMetrics(operation, device, dtype, input_shape, execution_time, memory_used, memory_peak, throughput, timestamp)[source]

Bases: object

Container for performance metrics.

Parameters:
operation: str
device: str
dtype: str
input_shape: Tuple[int, ...]
execution_time: float
memory_used: float
memory_peak: float
throughput: float
timestamp: float
__init__(operation, device, dtype, input_shape, execution_time, memory_used, memory_peak, throughput, timestamp)
Parameters:
Return type:

None

class hpfracc.ml.gpu_optimization.GPUProfiler(device='cuda')[source]

Bases: object

Simple profiler for GPU operations.

Parameters:

device (str)

__init__(device='cuda')[source]
Parameters:

device (str)

metrics_history: List[PerformanceMetrics]
current_metrics: Dict[str, PerformanceMetrics]
start_timer(operation)[source]

Start timing an operation.

Parameters:

operation (str)

end_timer(input_tensor, output_tensor=None)[source]

End timing and record metrics.

Parameters:
  • input_tensor (torch.Tensor)

  • output_tensor (torch.Tensor | None)

get_summary()[source]

Get performance summary.

Return type:

Dict[str, Dict[str, float]]

clear_history()[source]

Clear metrics history.

class hpfracc.ml.gpu_optimization.ChunkedFFT(chunk_size=1024, overlap=0.1, window_type='hann')[source]

Bases: object

Chunked FFT operations for large sequences.

Parameters:
__init__(chunk_size=1024, overlap=0.1, window_type='hann')[source]
Parameters:
fft_chunked(x, dim=-1)[source]

Perform chunked FFT on large sequences.

Parameters:
  • x (torch.Tensor)

  • dim (int)

Return type:

torch.Tensor

ifft_chunked(x, dim=-1)[source]

Perform chunked IFFT on large sequences.

Parameters:
  • x (torch.Tensor)

  • dim (int)

Return type:

torch.Tensor

forward(x, dim=-1)[source]

Alias for fft_chunked.

Parameters:
  • x (torch.Tensor)

  • dim (int)

Return type:

torch.Tensor

inverse(x, dim=-1)[source]

Alias for ifft_chunked.

Parameters:
  • x (torch.Tensor)

  • dim (int)

Return type:

torch.Tensor

_process_chunks(x, dim, fft_func)[source]

Process tensor in chunks with overlap.

Parameters:
  • x (torch.Tensor)

  • dim (int)

Return type:

torch.Tensor

class hpfracc.ml.gpu_optimization.AMPFractionalEngine(base_engine, use_amp=True, dtype=torch.float16)[source]

Bases: object

Automatic Mixed Precision wrapper for fractional engines.

Parameters:
  • use_amp (bool)

  • dtype (torch.dtype)

__init__(base_engine, use_amp=True, dtype=torch.float16)[source]
Parameters:
  • use_amp (bool)

  • dtype (torch.dtype)

forward(x, alpha, **kwargs)[source]

Forward pass with AMP support.

Parameters:
  • x (torch.Tensor)

  • alpha (float)

Return type:

torch.Tensor

backward(grad_output, **kwargs)[source]

Backward pass with AMP support.

Parameters:

grad_output (torch.Tensor)

Return type:

torch.Tensor

update_scaler()[source]

Update the GradScaler after an optimization step.

get_scaler_state()[source]

Get the current state of the GradScaler.

Return type:

Dict[str, Any]

class hpfracc.ml.gpu_optimization.GPUOptimizedSpectralEngine(engine_type='fft', use_amp=True, chunk_size=1024, dtype=torch.float16)[source]

Bases: object

GPU-optimized spectral engine with AMP and chunked FFT.

Parameters:
  • engine_type (str)

  • use_amp (bool)

  • chunk_size (int)

  • dtype (torch.dtype)

__init__(engine_type='fft', use_amp=True, chunk_size=1024, dtype=torch.float16)[source]
Parameters:
  • engine_type (str)

  • use_amp (bool)

  • chunk_size (int)

  • dtype (torch.dtype)

forward(x, alpha)[source]

GPU-optimized forward pass.

Parameters:
  • x (torch.Tensor)

  • alpha (float)

Return type:

torch.Tensor

_compute_spectral_transform(x, alpha)[source]

Compute spectral transform with GPU optimizations.

Parameters:
  • x (torch.Tensor)

  • alpha (float)

Return type:

torch.Tensor

spectral_derivative(x, alpha)[source]

Compute spectral fractional derivative.

Parameters:
  • x (torch.Tensor)

  • alpha (float)

Return type:

torch.Tensor

spectral_integral(x, alpha)[source]

Compute spectral fractional integral.

Parameters:
  • x (torch.Tensor)

  • alpha (float)

Return type:

torch.Tensor

spectral_transform(x, alpha)[source]

Compute spectral transform (returns complex result).

Parameters:
  • x (torch.Tensor)

  • alpha (float)

Return type:

torch.Tensor

_fallback_compute(x, alpha)[source]

Fallback computation without GPU optimizations.

Parameters:
  • x (torch.Tensor)

  • alpha (float)

Return type:

torch.Tensor

get_performance_summary()[source]

Get performance summary.

Return type:

Dict[str, Dict[str, float]]

class hpfracc.ml.gpu_optimization.GPUOptimizedStochasticSampler(base_sampler, use_amp=True, batch_size=1024)[source]

Bases: object

GPU-optimized stochastic memory sampler.

Parameters:
__init__(base_sampler, use_amp=True, batch_size=1024)[source]
Parameters:
sample_indices(n, k)[source]

GPU-optimized index sampling.

Parameters:
Return type:

torch.Tensor

_gpu_sample_indices(n, k)[source]

GPU-optimized index sampling implementation.

Parameters:
Return type:

torch.Tensor

sample(mu, sigma, num_samples)[source]

GPU-optimized distribution sampling.

Parameters:
  • mu (torch.Tensor)

  • sigma (torch.Tensor)

  • num_samples (int)

Return type:

torch.Tensor

get_performance_summary()[source]

Get performance summary.

Return type:

Dict[str, Dict[str, float]]

hpfracc.ml.gpu_optimization.gpu_optimization_context(use_amp=True, dtype=torch.float16)[source]

Context manager for GPU optimization.

Parameters:
  • use_amp (bool)

  • dtype (torch.dtype)

hpfracc.ml.gpu_optimization.benchmark_gpu_optimization()[source]

Benchmark GPU optimization performance.

hpfracc.ml.gpu_optimization.create_gpu_optimized_components(use_amp=True, chunk_size=1024, dtype=torch.float16, enable_profiling=False)[source]

Factory function to create GPU-optimized components.

Parameters:
  • use_amp (bool)

  • chunk_size (int)

  • dtype (torch.dtype)

  • enable_profiling (bool)

hpfracc.ml.gpu_optimization.test_gpu_optimization(test_size=1024, num_iterations=10, use_amp=True)[source]

Test GPU optimization functionality.

Returns:

Dictionary containing test results with test_passed, test_results, and performance_metrics.

Parameters:
  • test_size (int)

  • num_iterations (int)

  • use_amp (bool)

Backend Management

Backend Management System for Multi-Framework Support

This module provides unified interfaces for PyTorch, JAX, and NUMBA backends, enabling seamless switching between frameworks and automatic backend selection based on data type, hardware availability, and performance requirements.

class hpfracc.ml.backends.BackendType(value)[source]

Bases: Enum

Available computation backends

TORCH = 'torch'
JAX = 'jax'
NUMBA = 'numba'
AUTO = 'auto'
class hpfracc.ml.backends.BackendManager(preferred_backend=BackendType.AUTO, force_cpu=False, enable_jit=True, enable_gpu=True)[source]

Bases: object

Manages backend selection and provides unified interfaces

This class handles automatic backend selection based on: - Data type and size - Hardware availability (CPU/GPU) - Performance requirements - User preferences

Parameters:
__init__(preferred_backend=BackendType.AUTO, force_cpu=False, enable_jit=True, enable_gpu=True)[source]
Parameters:
_detect_available_backends()[source]

Detect which backends are available on the system

Return type:

List[BackendType]

_select_optimal_backend()[source]

Select the optimal backend based on preferences and availability

Return type:

BackendType

_initialize_backend_configs()[source]

Initialize backend-specific configurations

Return type:

Dict[BackendType, Dict[str, Any]]

get_backend_config(backend=None)[source]

Get configuration for a specific backend

Parameters:

backend (BackendType | None)

Return type:

Dict[str, Any]

switch_backend(backend)[source]

Switch to a different backend

Parameters:

backend (BackendType)

Return type:

bool

get_tensor_lib()[source]

Get the active tensor library

Return type:

Any

create_tensor(data, **kwargs)[source]

Create a tensor in the active backend

Parameters:

data (Any)

Return type:

Any

to_device(tensor, device=None)[source]

Move tensor to specified device

Parameters:
  • tensor (Any)

  • device (str | None)

Return type:

Any

compile_function(func)[source]

Compile a function using the active backend’s compilation system

Parameters:

func (Callable)

Return type:

Callable

hpfracc.ml.backends.get_backend_manager()[source]

Get the global backend manager instance

Return type:

BackendManager

hpfracc.ml.backends.set_backend_manager(manager)[source]

Set the global backend manager instance

Parameters:

manager (BackendManager)

Return type:

None

hpfracc.ml.backends.get_active_backend()[source]

Get the currently active backend

Return type:

BackendType

hpfracc.ml.backends.switch_backend(backend)[source]

Switch to a different backend

Parameters:

backend (BackendType)

Return type:

bool

Tensor Operations

hpfracc.ml.tensor_ops.get_tensor_ops(backend=None)[source]

Factory function to get the appropriate TensorOps implementation.

Parameters:

backend (BackendType | None)

Return type:

TensorOps

class hpfracc.ml.tensor_ops.TensorOps[source]

Bases: ABC

Abstract base class for tensor operations across different backends.

abstractmethod create_tensor(data, **kwargs)[source]
Parameters:

data (Any)

Return type:

Any

abstractmethod shape(tensor)[source]
Parameters:

tensor (Any)

Return type:

Any

abstractmethod from_numpy(array)[source]
Parameters:

array (Any)

Return type:

Any

abstractmethod to_numpy(tensor)[source]
Parameters:

tensor (Any)

Return type:

Any

abstractmethod no_grad()[source]
Return type:

ContextManager

abstractmethod zeros(shape, **kwargs)[source]
Parameters:

shape (Tuple[int, ...])

Return type:

Any

abstractmethod ones(shape, **kwargs)[source]
Parameters:

shape (Tuple[int, ...])

Return type:

Any

abstractmethod eye(n, **kwargs)[source]
Parameters:

n (int)

Return type:

Any

abstractmethod arange(start, end, step=1, **kwargs)[source]
Parameters:
Return type:

Any

abstractmethod linspace(start, end, num, **kwargs)[source]
Parameters:
Return type:

Any

abstractmethod zeros_like(tensor, **kwargs)[source]
Parameters:

tensor (Any)

Return type:

Any

abstractmethod ones_like(tensor, **kwargs)[source]
Parameters:

tensor (Any)

Return type:

Any

abstractmethod sqrt(tensor)[source]
Parameters:

tensor (Any)

Return type:

Any

abstractmethod stack(tensors, dim=0)[source]
Parameters:
Return type:

Any

abstractmethod cat(tensors, dim=0)[source]
Parameters:
Return type:

Any

abstractmethod reshape(tensor, shape)[source]
Parameters:
Return type:

Any

abstractmethod repeat(tensor, repeats, dim=0)[source]
Parameters:
Return type:

Any

abstractmethod tile(tensor, reps)[source]
Parameters:
Return type:

Any

abstractmethod clip(tensor, min_val, max_val)[source]
Parameters:
Return type:

Any

abstractmethod unsqueeze(tensor, dim)[source]
Parameters:
Return type:

Any

abstractmethod expand(tensor, *sizes)[source]
Parameters:
Return type:

Any

abstractmethod gather(tensor, dim, index)[source]
Parameters:
Return type:

Any

abstractmethod squeeze(tensor, dim=None)[source]
Parameters:
  • tensor (Any)

  • dim (int | None)

Return type:

Any

abstractmethod transpose(tensor, *args, **kwargs)[source]
Parameters:

tensor (Any)

Return type:

Any

abstractmethod matmul(a, b)[source]
Parameters:
Return type:

Any

abstractmethod inverse(tensor)[source]
Parameters:

tensor (Any)

Return type:

Any

abstractmethod mean(tensor, dim=None, keepdims=False, axis=None)[source]
Parameters:
  • tensor (Any)

  • dim (int | None)

  • keepdims (bool)

  • axis (int | None)

Return type:

Any

abstractmethod sum(tensor, dim=None, keepdims=False, axis=None)[source]
Parameters:
  • tensor (Any)

  • dim (int | None)

  • keepdims (bool)

  • axis (int | None)

Return type:

Any

abstractmethod max(tensor, dim=None, keepdims=False, axis=None)[source]
Parameters:
  • tensor (Any)

  • dim (int | None)

  • keepdims (bool)

  • axis (int | None)

Return type:

Any

abstractmethod min(tensor, dim=None, keepdims=False, axis=None)[source]
Parameters:
  • tensor (Any)

  • dim (int | None)

  • keepdims (bool)

  • axis (int | None)

Return type:

Any

abstractmethod minimum(a, b)[source]
Parameters:
Return type:

Any

abstractmethod maximum(a, b)[source]
Parameters:
Return type:

Any

abstractmethod where(condition, x, y)[source]
Parameters:
Return type:

Any

abstractmethod norm(tensor, dim=None, axis=None, keepdims=False, ord=2)[source]
Parameters:
Return type:

Any

tensor(data, **kwargs)[source]

Alias for create_tensor

Parameters:

data (Any)

Return type:

Any

abstractmethod add(a, b)[source]
Parameters:
Return type:

Any

abstractmethod subtract(a, b)[source]
Parameters:
Return type:

Any

abstractmethod multiply(a, b)[source]
Parameters:
Return type:

Any

abstractmethod divide(a, b)[source]
Parameters:
Return type:

Any

abstractmethod power(a, b)[source]
Parameters:
Return type:

Any

abstractmethod sin(tensor)[source]
Parameters:

tensor (Any)

Return type:

Any

abstractmethod cos(tensor)[source]
Parameters:

tensor (Any)

Return type:

Any

abstractmethod exp(tensor)[source]
Parameters:

tensor (Any)

Return type:

Any

abstractmethod log(tensor)[source]
Parameters:

tensor (Any)

Return type:

Any

abstractmethod abs(tensor)[source]
Parameters:

tensor (Any)

Return type:

Any

abstractmethod sign(tensor)[source]
Parameters:

tensor (Any)

Return type:

Any

abstractmethod relu(tensor)[source]
Parameters:

tensor (Any)

Return type:

Any

abstractmethod sigmoid(tensor)[source]
Parameters:

tensor (Any)

Return type:

Any

abstractmethod tanh(tensor)[source]
Parameters:

tensor (Any)

Return type:

Any

abstractmethod softmax(tensor, dim=-1)[source]
Parameters:
Return type:

Any

abstractmethod dropout(tensor, p=0.5, training=True, **kwargs)[source]
Parameters:
Return type:

Any

abstractmethod batch_norm(tensor, mean=None, var=None, weight=None, bias=None, training=False, momentum=0.1, eps=1e-05)[source]
Parameters:
Return type:

Any

abstractmethod layer_norm(tensor, normalized_shape=None, weight=None, bias=None, eps=1e-05)[source]
Parameters:
Return type:

Any

abstractmethod convolve(input, weight, bias=None, stride=1, padding=0, dilation=1, groups=1)[source]
Parameters:
Return type:

Any

abstractmethod max_pool(input, kernel_size, stride=None, padding=0)[source]
Parameters:
  • input (Any)

  • kernel_size (int)

  • stride (int | None)

  • padding (int)

Return type:

Any

abstractmethod avg_pool(input, kernel_size, stride=None, padding=0)[source]
Parameters:
  • input (Any)

  • kernel_size (int)

  • stride (int | None)

  • padding (int)

Return type:

Any

abstractmethod backward(tensor, grad_tensor=None)[source]
Parameters:
  • tensor (Any)

  • grad_tensor (Any | None)

Return type:

Any

abstractmethod grad(tensor)[source]
Parameters:

tensor (Any)

Return type:

Any

abstractmethod random_normal(shape, mean=0.0, std=1.0, **kwargs)[source]
Parameters:
Return type:

Any

abstractmethod random_uniform(shape, min_val=0.0, max_val=1.0, **kwargs)[source]
Parameters:
Return type:

Any

abstractmethod mse_loss(input, target, reduction='mean')[source]
Parameters:
Return type:

Any

abstractmethod cross_entropy_loss(input, target, reduction='mean', **kwargs)[source]
Parameters:
Return type:

Any

abstractmethod to_device(tensor, device)[source]
Parameters:
Return type:

Any

abstractmethod device(tensor)[source]
Parameters:

tensor (Any)

Return type:

str

abstractmethod equal(a, b)[source]
Parameters:
Return type:

Any

abstractmethod greater(a, b)[source]
Parameters:
Return type:

Any

abstractmethod less(a, b)[source]
Parameters:
Return type:

Any

abstractmethod logical_and(a, b)[source]
Parameters:
Return type:

Any

abstractmethod logical_or(a, b)[source]
Parameters:
Return type:

Any

abstractmethod logical_not(a)[source]
Parameters:

a (Any)

Return type:

Any

abstractmethod fft(tensor, n=None, dim=-1, norm=None)[source]
Parameters:
Return type:

Any

abstractmethod ifft(tensor, n=None, dim=-1, norm=None)[source]
Parameters:
Return type:

Any

concatenate(tensors, dim=0)[source]
Parameters:
Return type:

Any

abstractmethod index(tensor, index)[source]
Parameters:
Return type:

Any

abstractmethod slice(tensor, start, end, dim=0)[source]
Parameters:
Return type:

Any

abstractmethod sgd_step(tensor, lr)[source]
Parameters:
Return type:

Any

abstractmethod adam_step(tensor, lr)[source]
Parameters:
Return type:

Any

switch_backend(backend)[source]
Parameters:

backend (Any)

Return type:

bool

abstractmethod get_backend_info()[source]
Return type:

Dict[str, Any]

enable_profiling(enable)[source]
Parameters:

enable (bool)

get_profile_results()[source]
Return type:

Dict[str, Any]

clear_cache()[source]
get_memory_usage()[source]
Return type:

Dict[str, Any]

hpfracc.ml.tensor_ops.create_tensor(data, *args, **kwargs)[source]

Wrapper to create tensor using active backend

Parameters:

data (Any)

Return type:

Any

hpfracc.ml.tensor_ops.switch_backend(backend)[source]

Wrapper to switch backend

Parameters:

backend (BackendType)

Return type:

bool

Core ML Components

Core Machine Learning Components for Fractional Calculus

This module provides the foundational ML classes that integrate fractional calculus with neural networks, attention mechanisms, loss functions, and AutoML capabilities.

class hpfracc.ml.core.MLConfig(device='cpu', dtype='float32', fractional_order=0.5, use_gpu=False, batch_size=32, learning_rate=0.001, max_epochs=100, validation_split=0.2, early_stopping_patience=10, model_save_path='models/', log_interval=10, backend=BackendType.AUTO)[source]

Bases: object

Configuration for ML components

Parameters:
device: str = 'cpu'
dtype: str = 'float32'
fractional_order: float = 0.5
use_gpu: bool = False
batch_size: int = 32
learning_rate: float = 0.001
max_epochs: int = 100
validation_split: float = 0.2
early_stopping_patience: int = 10
model_save_path: str = 'models/'
log_interval: int = 10
backend: BackendType = 'auto'
__init__(device='cpu', dtype='float32', fractional_order=0.5, use_gpu=False, batch_size=32, learning_rate=0.001, max_epochs=100, validation_split=0.2, early_stopping_patience=10, model_save_path='models/', log_interval=10, backend=BackendType.AUTO)
Parameters:
Return type:

None

class hpfracc.ml.core.FractionalNeuralNetwork(input_size, hidden_sizes, output_size, fractional_order=0.5, activation='relu', dropout=0.1, config=None, backend=None, differentiable_fractional=True, fractional_axis=-1, fractional_step=None, fractional_t_grid=None)[source]

Bases: object

Neural network with fractional calculus integration.

Tensor layout. The first linear layer expects the same shape you pass to forward (typically (batch, input_size)). The fractional pre-processing step applies a discrete fractional operator along fractional_axis (default -1, the feature / time-sample axis). Use fractional_axis=0 only if your rows are samples along an index (unusual for (batch, features)).

Grid. Native GL / Caputo L1 use a uniform step h. Provide fractional_step (scalar h), or fractional_t_grid (length matching the sampled axis; must be strictly increasing and evenly spaced), or omit both for the default grid t = linspace(0, 1, n) with h = 1/(n-1). Non-uniform grids are rejected in the native path; use differentiable_fractional=False for the legacy NumPy operator (still uniform t implied the same way).

Supports PyTorch, JAX, and NUMBA backends.

Parameters:
__init__(input_size, hidden_sizes, output_size, fractional_order=0.5, activation='relu', dropout=0.1, config=None, backend=None, differentiable_fractional=True, fractional_axis=-1, fractional_step=None, fractional_t_grid=None)[source]
Parameters:
train(mode=True)[source]

Set training mode

Parameters:

mode (bool)

eval()[source]

Set evaluation mode

parameters()[source]

Return list of learnable parameters for compatibility with optimizers/tests

Return type:

List[Any]

_build_network()[source]

Build the network architecture using the current backend

_initialize_weights()[source]

Initialize network weights using Xavier initialization

fractional_forward(x, method='RL', *, axis=None, fractional_step=None, fractional_t_grid=None)[source]

Apply a discrete fractional operator along axis (default: fractional_axis).

Optional per-call overrides: axis, fractional_step, fractional_t_grid (same semantics as constructor; per-call grid overrides instance grid).

Parameters:
Return type:

Any

forward(x, use_fractional=True, method='RL', params=None, fractional_axis=None, fractional_step=None, fractional_t_grid=None)[source]

Forward pass through the network

Parameters:
  • x (Any) – Input tensor

  • use_fractional (bool) – Whether to apply fractional derivatives

  • method (str) – Fractional derivative method if use_fractional is True

  • params (Dict[str, List[Any]] | None) – Optional dictionary of parameters {‘weights’: […], ‘biases’: […]} for functional execution (JAX support).

  • fractional_axis (int | None) – Optional override for the sampled axis (see class docstring).

  • fractional_step (float | None) – Optional uniform step h for the fractional grid.

  • fractional_t_grid (ndarray | Sequence[float] | None) – Optional uniform 1D grid (length = size along sampled axis).

Returns:

Network output

Return type:

Any

_apply_activation(x)[source]

Apply activation function based on backend

Parameters:

x (Any)

Return type:

Any

save_model(path)[source]

Save model to file

Parameters:

path (str)

classmethod load_model(path, config_path=None)[source]

Load model from file

Parameters:
  • path (str)

  • config_path (str | None)

class hpfracc.ml.core.FractionalAttention(d_model, n_heads=8, fractional_order=0.5, dropout=0.1, backend=None, differentiable_fractional=True, fractional_step=None, fractional_t_grid=None)[source]

Bases: object

Multi-head attention with an optional discrete fractional map on the attended context.

After standard attention, the context tensor has shape (batch, n_heads, seq_len, d_k). The fractional step runs along the sequence dimension (axis 2), using the same native Grünwald–Letnikov / L1-Caputo machinery as FractionalNeuralNetwork when differentiable_fractional is True. Optional fractional_step and fractional_t_grid define a uniform grid along that axis (see fractional_feature_map_native).

The spectral FFT stack in hpfracc.ml.spectral_autograd is separate; this class does not use it.

Supports PyTorch, JAX, and NUMBA backends.

Parameters:
__init__(d_model, n_heads=8, fractional_order=0.5, dropout=0.1, backend=None, differentiable_fractional=True, fractional_step=None, fractional_t_grid=None)[source]
Parameters:
train(mode=True)[source]
Parameters:

mode (bool)

eval()[source]
_initialize_weights()[source]

Initialize attention weights

fractional_attention(q, k, v, method='RL')[source]

Compute attention with fractional derivatives

Parameters:
  • q (Any) – Query, key, value tensors of shape (batch_size, n_heads, seq_len, d_k)

  • k (Any) – Query, key, value tensors of shape (batch_size, n_heads, seq_len, d_k)

  • v (Any) – Query, key, value tensors of shape (batch_size, n_heads, seq_len, d_k)

  • method (str) – Fractional derivative method

Returns:

Attention output with fractional calculus applied

Return type:

Any

forward(x, method='RL')[source]

Forward pass through fractional attention

Parameters:
  • x (Any) – Input tensor of shape (batch_size, seq_len, d_model)

  • method (str) – Fractional derivative method

Returns:

Output tensor with attention and fractional calculus applied

Return type:

Any

class hpfracc.ml.core.FractionalLossFunction(fractional_order=0.5, backend=None)[source]

Bases: object

Base class for loss functions with fractional calculus integration

This class provides a framework for creating loss functions that incorporate fractional derivatives to capture complex relationships. Supports multiple backends: PyTorch, JAX, and NUMBA.

Parameters:
__init__(fractional_order=0.5, backend=None)[source]
Parameters:
abstractmethod compute_loss(predictions, targets)[source]

Compute the base loss

Parameters:
  • predictions (Any)

  • targets (Any)

Return type:

Any

fractional_loss(predictions, targets)[source]

Compute loss with fractional derivative applied to predictions

Parameters:
  • predictions (Any) – Model predictions

  • targets (Any) – Ground truth targets

Returns:

Fractional loss value

Return type:

Any

forward(predictions, targets, use_fractional=True)[source]

Forward pass for loss computation

Parameters:
  • predictions (Any) – Model predictions

  • targets (Any) – Ground truth targets

  • use_fractional (bool) – Whether to apply fractional derivatives

Returns:

Loss value

Return type:

Any

class hpfracc.ml.core.FractionalMSELoss(fractional_order=0.5, backend=None)[source]

Bases: FractionalLossFunction

Mean Squared Error loss with fractional calculus integration

Parameters:
compute_loss(predictions, targets)[source]

Compute the base loss

Parameters:
  • predictions (Any)

  • targets (Any)

Return type:

Any

class hpfracc.ml.core.FractionalCrossEntropyLoss(fractional_order=0.5, backend=None)[source]

Bases: FractionalLossFunction

Cross Entropy loss with fractional calculus integration

Parameters:
compute_loss(predictions, targets)[source]

Compute the base loss

Parameters:
  • predictions (Any)

  • targets (Any)

Return type:

Any

class hpfracc.ml.core.FractionalAutoML(config=None)[source]

Bases: object

Automated Machine Learning for fractional calculus parameters

This class provides automated optimization of fractional orders and other hyperparameters for optimal performance on specific tasks.

Parameters:

config (MLConfig | None)

__init__(config=None)[source]
Parameters:

config (MLConfig | None)

optimize_fractional_order(model_class, train_data, val_data, param_ranges, n_trials=50, metric='accuracy')[source]

Optimize fractional order and other hyperparameters

Parameters:
  • model_class (type) – Class of model to optimize

  • train_data (Tuple[Any, Any]) – Training data (X, y)

  • val_data (Tuple[Any, Any]) – Validation data (X, y)

  • param_ranges (Dict[str, List[float]]) – Dictionary of parameter ranges to search

  • n_trials (int) – Number of optimization trials

  • metric (str) – Metric to optimize

Returns:

Dictionary with best parameters and optimization results

Return type:

Dict[str, Any]

get_best_model(model_class, **kwargs)[source]

Get model instance with best parameters

Parameters:

model_class (type)

Return type:

Any

Neural Network Layers

Comprehensive Optimal Neural Network Layers with Fractional Calculus

This module provides the optimal hybrid implementation of all neural network layers with fractional calculus integration, combining the best performance, features, and stability from all implementations.

Performance: 7.56x faster than original implementation Stability: 100% success rate across all test cases Features: Complete layer type coverage with optimal architecture

Author: Davian R. Chin, Department of Biomedical Engineering, University of Reading Comprehensive Optimal Implementation: September 2025

class hpfracc.ml.layers.LayerConfig(fractional_order=None, method='RL', use_fractional=True, activation='relu', dropout=0.1, backend=BackendType.AUTO, device=None, dtype=torch.float32, enable_caching=True, enable_benchmarking=False, performance_mode='balanced')[source]

Bases: object

Optimal configuration for all fractional layers

Parameters:
fractional_order: FractionalOrder = None
method: str = 'RL'
use_fractional: bool = True
activation: str = 'relu'
dropout: float = 0.1
backend: BackendType = 'auto'
device: torch.device | None = None
enable_caching: bool = True
enable_benchmarking: bool = False
performance_mode: str = 'balanced'
__init__(fractional_order=None, method='RL', use_fractional=True, activation='relu', dropout=0.1, backend=BackendType.AUTO, device=None, dtype=torch.float32, enable_caching=True, enable_benchmarking=False, performance_mode='balanced')
Parameters:
Return type:

None

class hpfracc.ml.layers.BackendManager[source]

Bases: object

Intelligent backend management with workload-aware selection and performance learning

__init__()[source]
_detect_available_backends()[source]

Detect available backends and their capabilities

Return type:

Dict[str, bool]

select_optimal_backend(config, input_shape)[source]

Select optimal backend based on workload characteristics and learning

Parameters:
Return type:

str

class hpfracc.ml.layers.FractionalOps(config)[source]

Bases: object

Optimal fractional operations with performance optimization

Parameters:

config (LayerConfig)

__init__(config)[source]
Parameters:

config (LayerConfig)

apply_fractional_derivative(x, alpha, method='RL', backend='pytorch')[source]

Apply fractional derivative with optimal backend selection

Parameters:
  • x (torch.Tensor)

  • alpha (float)

  • method (str)

  • backend (str)

Return type:

torch.Tensor

class hpfracc.ml.layers.FractionalLayerBase(*args, **kwargs)[source]

Bases: Module, ABC

Optimal base class for all fractional layers

Parameters:
__init__(config, *, backend=None)[source]
Parameters:
_setup_layer()[source]

Setup layer-specific components

apply_fractional_derivative(x)[source]

Apply fractional derivative with optimal backend selection

Parameters:

x (torch.Tensor)

Return type:

torch.Tensor

apply_activation(x)[source]

Apply activation function

Parameters:

x (torch.Tensor)

Return type:

torch.Tensor

apply_dropout(x)[source]

Apply dropout if training

Parameters:

x (torch.Tensor)

Return type:

torch.Tensor

abstractmethod forward(x)[source]

Forward pass - must be implemented by subclasses

Parameters:

x (torch.Tensor)

Return type:

torch.Tensor

class hpfracc.ml.layers.FractionalConv1D(*args, **kwargs)[source]

Bases: FractionalLayerBase

Optimal 1D Convolutional layer with fractional calculus integration

Parameters:
__init__(in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True, config=None, backend=None)[source]
Parameters:
_initialize_weights()[source]

Initialize weights using optimal methods

forward(x)[source]

Forward pass with optimal fractional derivative integration

Parameters:

x (torch.Tensor)

Return type:

torch.Tensor

class hpfracc.ml.layers.FractionalConv2D(*args, **kwargs)[source]

Bases: FractionalLayerBase

Optimal 2D Convolutional layer with fractional calculus integration

Parameters:
__init__(in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True, config=None, backend=None)[source]
Parameters:
_initialize_weights()[source]

Initialize weights using optimal methods

forward(x)[source]

Forward pass with optimal fractional derivative integration

Parameters:

x (torch.Tensor)

Return type:

torch.Tensor

class hpfracc.ml.layers.FractionalLinear(*args, **kwargs)[source]

Bases: FractionalLayerBase

Optimal Linear layer with fractional calculus integration

Parameters:
__init__(in_features, out_features, bias=True, config=None, backend=None)[source]
Parameters:
_initialize_weights()[source]

Initialize weights using optimal methods

forward(x)[source]

Forward pass with optimal fractional derivative integration

Parameters:

x (torch.Tensor)

Return type:

torch.Tensor

class hpfracc.ml.layers.FractionalLSTM(*args, **kwargs)[source]

Bases: FractionalLayerBase

Minimal LSTM layer wrapper satisfying tests.

Parameters:
__init__(input_size, hidden_size, num_layers=1, bidirectional=False, dropout=0.0, bias=True, config=None, backend=None, fractional_order=0.5)[source]
Parameters:
forward(x, return_state=False)[source]

Forward pass - must be implemented by subclasses

Parameters:

return_state (bool)

forward_with_state(x)[source]

Return (output, (h, c)) for callers that need states.

class hpfracc.ml.layers.FractionalTransformer(*args, **kwargs)[source]

Bases: FractionalLayerBase

Minimal Transformer wrapper satisfying tests.

Parameters:
__init__(d_model, nhead=None, num_encoder_layers=1, num_decoder_layers=1, dim_feedforward=None, dropout=0.1, activation='relu', n_heads=None, d_ff=None, config=None, backend=None)[source]
Parameters:
forward(src, tgt=None)[source]

Forward pass - must be implemented by subclasses

class hpfracc.ml.layers.FractionalPooling(*args, **kwargs)[source]

Bases: FractionalLayerBase

Minimal pooling wrapper satisfying tests.

Parameters:
__init__(kernel_size, stride=1, padding=0, pool_type='max', dim=1, config=None, backend=None, fractional_order=0.5)[source]
Parameters:
forward(x)[source]

Forward pass - must be implemented by subclasses

class hpfracc.ml.layers.FractionalBatchNorm1d(*args, **kwargs)[source]

Bases: FractionalLayerBase

Minimal BatchNorm1d wrapper satisfying tests.

Parameters:
__init__(num_features, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True, config=None, backend=None)[source]
Parameters:
forward(x)[source]

Forward pass - must be implemented by subclasses

class hpfracc.ml.layers.FractionalDropout(*args, **kwargs)[source]

Bases: FractionalLayerBase

Minimal Dropout wrapper satisfying tests.

Parameters:
__init__(p=0.5, inplace=False, config=None, backend=None)[source]
Parameters:
forward(x, training=None)[source]

Forward pass - must be implemented by subclasses

class hpfracc.ml.layers.FractionalLayerNorm(*args, **kwargs)[source]

Bases: FractionalLayerBase

Minimal LayerNorm wrapper satisfying tests.

Parameters:
__init__(normalized_shape, eps=1e-05, elementwise_affine=True, config=None, backend=None)[source]
Parameters:
forward(x)[source]

Forward pass - must be implemented by subclasses

class hpfracc.ml.layers.FractionalMaxUnpool1d(*args, **kwargs)[source]

Bases: FractionalLayerBase

Parameters:
__init__(kernel_size, stride=1, padding=0, output_size=None, config=None, backend=None)[source]
Parameters:
forward(x, indices)[source]

Forward pass - must be implemented by subclasses

Parameters:
  • x (torch.Tensor)

  • indices (torch.Tensor)

Return type:

torch.Tensor

class hpfracc.ml.layers.FractionalMaxUnpool2d(*args, **kwargs)[source]

Bases: FractionalLayerBase

Parameters:
__init__(kernel_size, stride=1, padding=0, output_size=None, config=None, backend=None)[source]
Parameters:
forward(x, indices)[source]

Forward pass - must be implemented by subclasses

Parameters:
  • x (torch.Tensor)

  • indices (torch.Tensor)

Return type:

torch.Tensor

class hpfracc.ml.layers.FractionalMaxUnpool3d(*args, **kwargs)[source]

Bases: FractionalLayerBase

Parameters:
__init__(kernel_size, stride=1, padding=0, output_size=None, config=None, backend=None)[source]
Parameters:
forward(x, indices)[source]

Forward pass - must be implemented by subclasses

Parameters:
  • x (torch.Tensor)

  • indices (torch.Tensor)

Return type:

torch.Tensor

class hpfracc.ml.layers.FractionalSelfAttention(*args, **kwargs)[source]

Bases: Module

Parameters:
  • embed_dim (int)

  • num_heads (int)

  • dropout (float)

  • bias (bool)

  • add_bias_kv (bool)

  • add_zero_attn (bool)

  • kdim (int | None)

  • vdim (int | None)

  • batch_first (bool)

  • device (torch.device | None)

  • dtype (torch.dtype | None)

__init__(embed_dim, num_heads, dropout=0.0, bias=True, add_bias_kv=False, add_zero_attn=False, kdim=None, vdim=None, batch_first=True, device=None, dtype=None)[source]
Parameters:
  • embed_dim (int)

  • num_heads (int)

  • dropout (float)

  • bias (bool)

  • add_bias_kv (bool)

  • add_zero_attn (bool)

  • kdim (int | None)

  • vdim (int | None)

  • batch_first (bool)

  • device (torch.device | None)

  • dtype (torch.dtype | None)

forward(query, key, value)[source]
Parameters:
  • query (torch.Tensor) – (batch, seq_len, embed_dim)

  • key (torch.Tensor) – (batch, seq_len, embed_dim)

  • value (torch.Tensor) – (batch, seq_len, embed_dim)

Return type:

Tensor

Graph Neural Networks

class hpfracc.ml.gnn_layers.FractionalGraphConv(in_channels, out_channels, fractional_order=0.5, method='RL', use_fractional=True, activation='relu', dropout=0.1, bias=True, backend=None)[source]

Bases: TorchFractionalGNNMixin, JaxFractionalGNNMixin, NumbaFractionalGNNMixin, BaseFractionalGNNLayer

Fractional Graph Convolutional Layer. Combines backend-specific implementations via mixins.

Parameters:
_initialize_layer()[source]

Initialize the graph convolution layer

forward(x, edge_index, edge_weight=None, **kwargs)[source]

Forward pass through the layer

Parameters:
  • x (Any)

  • edge_index (Any)

  • edge_weight (Any | None)

Return type:

Any

train(mode=True)[source]
Parameters:

mode (bool)

eval()[source]
parameters()[source]
named_parameters()[source]
state_dict()[source]
load_state_dict(state_dict)[source]
class hpfracc.ml.gnn_layers.FractionalGraphAttention(in_channels, out_channels, heads=8, fractional_order=0.5, method='RL', use_fractional=True, activation='relu', dropout=0.1, bias=True, backend=None, **kwargs)[source]

Bases: TorchFractionalGNNMixin, JaxFractionalGNNMixin, NumbaFractionalGNNMixin, BaseFractionalGNNLayer

Fractional Graph Attention Layer.

Parameters:
__init__(in_channels, out_channels, heads=8, fractional_order=0.5, method='RL', use_fractional=True, activation='relu', dropout=0.1, bias=True, backend=None, **kwargs)[source]
Parameters:
forward(x, edge_index, edge_weight=None, **kwargs)[source]

Forward pass through the layer

Parameters:
  • x (Any)

  • edge_index (Any)

  • edge_weight (Any | None)

Return type:

Any

class hpfracc.ml.gnn_layers.FractionalGraphPooling(in_channels=64, pooling_ratio=0.5, out_channels=None, fractional_order=0.5, method='RL', use_fractional=True, backend=None, **kwargs)[source]

Bases: TorchFractionalGNNMixin, JaxFractionalGNNMixin, NumbaFractionalGNNMixin, BaseFractionalGNNLayer

Fractional Graph Pooling Layer. Reduces graph size while preserving fractional properties.

Parameters:
__init__(in_channels=64, pooling_ratio=0.5, out_channels=None, fractional_order=0.5, method='RL', use_fractional=True, backend=None, **kwargs)[source]
Parameters:
forward(x, edge_index, batch=None, **kwargs)[source]

Identity pooling on features; always returns (x, edge_index, batch).

Graph coarsening (changing node count / edges) is not implemented yet. Returning a triple keeps FractionalGraphUNet and call sites consistent.

Parameters:
  • x (Any)

  • edge_index (Any)

  • batch (Any | None)

Return type:

Tuple[Any, Any, Any]

class hpfracc.ml.gnn_layers.BaseFractionalGNNLayer(in_channels, out_channels, fractional_order=0.5, method='RL', use_fractional=True, activation='relu', dropout=0.1, bias=True, backend=None)[source]

Bases: ABC

Base class for fractional GNN layers

Parameters:
__init__(in_channels, out_channels, fractional_order=0.5, method='RL', use_fractional=True, activation='relu', dropout=0.1, bias=True, backend=None)[source]
Parameters:
abstractmethod forward(x, edge_index, edge_weight=None, **kwargs)[source]

Forward pass through the layer

Parameters:
  • x (Any)

  • edge_index (Any)

  • edge_weight (Any | None)

Return type:

Any

apply_fractional_derivative(x)[source]

Apply fractional derivative to input features.

Parameters:

x (Any)

Return type:

Any

Complete Fractional Graph Neural Network Architectures

This module provides complete GNN architectures with fractional calculus integration, including various model types and configurations for different graph learning tasks.

class hpfracc.ml.gnn_models.BaseFractionalGNN(input_dim, hidden_dim, output_dim, num_layers=3, fractional_order=0.5, method='RL', use_fractional=True, activation='relu', dropout=0.1, backend=None)[source]

Bases: ABC

Base class for fractional Graph Neural Networks

This abstract class defines the interface for all fractional GNN models, ensuring consistency across different architectures and backends.

Parameters:
__init__(input_dim, hidden_dim, output_dim, num_layers=3, fractional_order=0.5, method='RL', use_fractional=True, activation='relu', dropout=0.1, backend=None)[source]
Parameters:
abstractmethod _build_network()[source]

Build the specific network architecture

abstractmethod forward(x, edge_index, batch=None, **kwargs)[source]

Forward pass through the network

Parameters:
  • x (Any)

  • edge_index (Any)

  • batch (Any | None)

Return type:

Any

get_backend_info()[source]

Get information about the current backend

Return type:

Dict[str, Any]

parameters()[source]

Collect learnable parameters from sub-layers for testing/optimizers

Return type:

List[Any]

class hpfracc.ml.gnn_models.FractionalGCN(input_dim, hidden_dim, output_dim, num_layers=3, fractional_order=0.5, method='RL', use_fractional=True, activation='relu', dropout=0.1, backend=None)[source]

Bases: BaseFractionalGNN

Fractional Graph Convolutional Network

A GNN architecture that uses fractional graph convolution layers for node classification, graph classification, and other tasks.

Parameters:
_build_network()[source]

Build the GCN architecture

forward(x, edge_index, batch=None, **kwargs)[source]

Forward pass through the fractional GCN

Parameters:
  • x (Any) – Node feature matrix [num_nodes, input_dim]

  • edge_index (Any) – Graph connectivity [2, num_edges]

  • batch (Any | None) – Batch assignment vector [num_nodes]

Returns:

Node embeddings [num_nodes, output_dim]

Return type:

Any

class hpfracc.ml.gnn_models.FractionalGAT(input_dim, hidden_dim, output_dim, num_layers=3, num_heads=8, fractional_order=0.5, method='RL', use_fractional=True, activation='relu', dropout=0.1, backend=None)[source]

Bases: BaseFractionalGNN

Fractional Graph Attention Network

A GNN architecture that uses fractional graph attention layers for enhanced graph representation learning.

Parameters:
__init__(input_dim, hidden_dim, output_dim, num_layers=3, num_heads=8, fractional_order=0.5, method='RL', use_fractional=True, activation='relu', dropout=0.1, backend=None)[source]
Parameters:
_build_network()[source]

Build the GAT architecture

forward(x, edge_index, batch=None, **kwargs)[source]

Forward pass through the fractional GAT

Parameters:
  • x (Any) – Node feature matrix [num_nodes, input_dim]

  • edge_index (Any) – Graph connectivity [2, num_edges]

  • batch (Any | None) – Batch assignment vector [num_nodes]

Returns:

Node embeddings [num_nodes, output_dim]

Return type:

Any

class hpfracc.ml.gnn_models.FractionalGraphSAGE(input_dim, hidden_dim, output_dim, num_layers=3, num_samples=25, fractional_order=0.5, method='RL', use_fractional=True, activation='relu', dropout=0.1, backend=None)[source]

Bases: BaseFractionalGNN

Fractional GraphSAGE Network

A GNN architecture that uses fractional graph convolution layers with neighbor sampling for scalable graph learning.

Parameters:
__init__(input_dim, hidden_dim, output_dim, num_layers=3, num_samples=25, fractional_order=0.5, method='RL', use_fractional=True, activation='relu', dropout=0.1, backend=None)[source]
Parameters:
_build_network()[source]

Build the GraphSAGE architecture

forward(x, edge_index, batch=None, **kwargs)[source]

Forward pass through the fractional GraphSAGE

Parameters:
  • x (Any) – Node feature matrix [num_nodes, input_dim]

  • edge_index (Any) – Graph connectivity [2, num_edges]

  • batch (Any | None) – Batch assignment vector [num_nodes]

Returns:

Node embeddings [num_nodes, output_dim]

Return type:

Any

class hpfracc.ml.gnn_models.FractionalGraphUNet(input_dim, hidden_dim, output_dim, num_layers=4, pooling_ratio=0.5, fractional_order=0.5, method='RL', use_fractional=True, activation='relu', dropout=0.1, backend=None)[source]

Bases: BaseFractionalGNN

Fractional Graph U-Net

A hierarchical GNN architecture that uses fractional calculus for multi-scale graph representation learning.

Parameters:
__init__(input_dim, hidden_dim, output_dim, num_layers=4, pooling_ratio=0.5, fractional_order=0.5, method='RL', use_fractional=True, activation='relu', dropout=0.1, backend=None)[source]
Parameters:
_build_network()[source]

Build the Graph U-Net architecture

forward(x, edge_index, batch=None, **kwargs)[source]

Forward pass through the fractional Graph U-Net

Parameters:
  • x (Any) – Node feature matrix [num_nodes, input_dim]

  • edge_index (Any) – Graph connectivity [2, num_edges]

  • batch (Any | None) – Batch assignment vector [num_nodes]

Returns:

Node embeddings [num_nodes, output_dim]

Return type:

Any

class hpfracc.ml.gnn_models.FractionalGNNFactory[source]

Bases: object

Factory class for creating fractional GNN models

This class provides a convenient interface for creating different types of fractional GNN architectures with consistent configurations.

static create_model(model_type, input_dim, hidden_dim, output_dim, **kwargs)[source]

Create a fractional GNN model of the specified type

Parameters:
  • model_type (str) – Type of GNN model (‘gcn’, ‘gat’, ‘sage’, ‘unet’)

  • input_dim (int) – Input feature dimension

  • hidden_dim (int) – Hidden layer dimension

  • output_dim (int) – Output dimension

  • **kwargs – Additional arguments for the model

Returns:

Configured fractional GNN model

Return type:

BaseFractionalGNN

static get_available_models()[source]

Get list of available model types

Return type:

List[str]

static get_model_info(model_type)[source]

Get information about a specific model type

Parameters:

model_type (str)

Return type:

Dict[str, Any]

Loss Functions

Loss Functions with Fractional Calculus Integration

This module provides loss functions that incorporate fractional derivatives, enabling enhanced training dynamics and potentially better convergence. Supports multiple backends: PyTorch, JAX, and NUMBA.

class hpfracc.ml.losses.FractionalLossFunction(fractional_order=0.5, method='RL', backend=None)[source]

Bases: ABC

Base class for loss functions with fractional calculus integration

This class provides a framework for loss functions that can apply fractional derivatives to predictions before computing the loss. Supports multiple backends: PyTorch, JAX, and NUMBA.

Parameters:
__init__(fractional_order=0.5, method='RL', backend=None)[source]
Parameters:
fractional_forward(x)[source]

Apply fractional derivative to input tensor

Parameters:

x (Any) – Input tensor

Returns:

Tensor with fractional derivative applied

Return type:

Any

abstractmethod compute_loss(predictions, targets)[source]

Compute the base loss function

Parameters:
  • predictions (Any) – Model predictions

  • targets (Any) – Ground truth targets

Returns:

Loss value

Return type:

Any

forward(predictions, targets, use_fractional=True)[source]

Forward pass for loss computation

Parameters:
  • predictions (Any) – Model predictions

  • targets (Any) – Ground truth targets

  • use_fractional (bool) – Whether to apply fractional derivatives

Returns:

Loss value

Return type:

Any

class hpfracc.ml.losses.FractionalMSELoss(fractional_order=0.5, method='RL', reduction='mean', backend=None)[source]

Bases: FractionalLossFunction

Mean Squared Error loss with fractional calculus integration

Parameters:
__init__(fractional_order=0.5, method='RL', reduction='mean', backend=None)[source]
Parameters:
compute_loss(predictions, targets)[source]

Compute the base loss function

Parameters:
  • predictions (Any) – Model predictions

  • targets (Any) – Ground truth targets

Returns:

Loss value

Return type:

Any

class hpfracc.ml.losses.FractionalCrossEntropyLoss(fractional_order=0.5, method='RL', reduction='mean', backend=None)[source]

Bases: FractionalLossFunction

Cross Entropy loss with fractional calculus integration

Parameters:
__init__(fractional_order=0.5, method='RL', reduction='mean', backend=None)[source]
Parameters:
compute_loss(predictions, targets)[source]

Compute the base loss function

Parameters:
  • predictions (Any) – Model predictions

  • targets (Any) – Ground truth targets

Returns:

Loss value

Return type:

Any

class hpfracc.ml.losses.FractionalHuberLoss(fractional_order=0.5, method='RL', delta=1.0, reduction='mean', backend=None)[source]

Bases: FractionalLossFunction

Huber loss with fractional calculus integration

Parameters:
__init__(fractional_order=0.5, method='RL', delta=1.0, reduction='mean', backend=None)[source]
Parameters:
compute_loss(predictions, targets)[source]

Compute the base loss function

Parameters:
  • predictions (Any) – Model predictions

  • targets (Any) – Ground truth targets

Returns:

Loss value

Return type:

Any

class hpfracc.ml.losses.FractionalSmoothL1Loss(fractional_order=0.5, method='RL', beta=1.0, reduction='mean', backend=None)[source]

Bases: FractionalLossFunction

Smooth L1 loss with fractional calculus integration

Parameters:
__init__(fractional_order=0.5, method='RL', beta=1.0, reduction='mean', backend=None)[source]
Parameters:
compute_loss(predictions, targets)[source]

Compute the base loss function

Parameters:
  • predictions (Any) – Model predictions

  • targets (Any) – Ground truth targets

Returns:

Loss value

Return type:

Any

class hpfracc.ml.losses.FractionalKLDivLoss(fractional_order=0.5, method='RL', reduction='mean', backend=None)[source]

Bases: FractionalLossFunction

KL Divergence loss with fractional calculus integration

Parameters:
__init__(fractional_order=0.5, method='RL', reduction='mean', backend=None)[source]
Parameters:
compute_loss(predictions, targets)[source]

Compute the base loss function

Parameters:
  • predictions (Any) – Model predictions

  • targets (Any) – Ground truth targets

Returns:

Loss value

Return type:

Any

class hpfracc.ml.losses.FractionalBCELoss(fractional_order=0.5, method='RL', reduction='mean', backend=None)[source]

Bases: FractionalLossFunction

Binary Cross Entropy loss with fractional calculus integration

Parameters:
__init__(fractional_order=0.5, method='RL', reduction='mean', backend=None)[source]
Parameters:
compute_loss(predictions, targets)[source]

Compute the base loss function

Parameters:
  • predictions (Any) – Model predictions

  • targets (Any) – Ground truth targets

Returns:

Loss value

Return type:

Any

class hpfracc.ml.losses.FractionalNLLLoss(fractional_order=0.5, method='RL', reduction='mean', backend=None)[source]

Bases: FractionalLossFunction

Negative Log Likelihood loss with fractional calculus integration

Parameters:
__init__(fractional_order=0.5, method='RL', reduction='mean', backend=None)[source]
Parameters:
compute_loss(predictions, targets)[source]

Compute the base loss function

Parameters:
  • predictions (Any) – Model predictions

  • targets (Any) – Ground truth targets

Returns:

Loss value

Return type:

Any

class hpfracc.ml.losses.FractionalPoissonNLLLoss(fractional_order=0.5, method='RL', log_input=True, full=False, reduction='mean', backend=None)[source]

Bases: FractionalLossFunction

Poisson Negative Log Likelihood loss with fractional calculus integration

Parameters:
__init__(fractional_order=0.5, method='RL', log_input=True, full=False, reduction='mean', backend=None)[source]
Parameters:
compute_loss(predictions, targets)[source]

Compute the base loss function

Parameters:
  • predictions (Any) – Model predictions

  • targets (Any) – Ground truth targets

Returns:

Loss value

Return type:

Any

class hpfracc.ml.losses.FractionalCosineEmbeddingLoss(fractional_order=0.5, method='RL', margin=0.0, reduction='mean', backend=None)[source]

Bases: FractionalLossFunction

Cosine Embedding loss with fractional calculus integration

Parameters:
__init__(fractional_order=0.5, method='RL', margin=0.0, reduction='mean', backend=None)[source]
Parameters:
compute_loss(predictions, targets)[source]

Compute the base loss function

Parameters:
  • predictions (Any) – Model predictions

  • targets (Any) – Ground truth targets

Returns:

Loss value

Return type:

Any

class hpfracc.ml.losses.FractionalMarginRankingLoss(fractional_order=0.5, method='RL', margin=0.0, reduction='mean', backend=None)[source]

Bases: FractionalLossFunction

Margin Ranking loss with fractional calculus integration

Parameters:
__init__(fractional_order=0.5, method='RL', margin=0.0, reduction='mean', backend=None)[source]
Parameters:
compute_loss(predictions, targets)[source]

Compute the base loss function

Parameters:
  • predictions (Any) – Model predictions

  • targets (Any) – Ground truth targets

Returns:

Loss value

Return type:

Any

class hpfracc.ml.losses.FractionalMultiMarginLoss(fractional_order=0.5, method='RL', p=1, margin=1.0, reduction='mean', backend=None)[source]

Bases: FractionalLossFunction

Multi Margin loss with fractional calculus integration

Parameters:
__init__(fractional_order=0.5, method='RL', p=1, margin=1.0, reduction='mean', backend=None)[source]
Parameters:
compute_loss(predictions, targets)[source]

Compute the base loss function

Parameters:
  • predictions (Any) – Model predictions

  • targets (Any) – Ground truth targets

Returns:

Loss value

Return type:

Any

class hpfracc.ml.losses.FractionalTripletMarginLoss(fractional_order=0.5, method='RL', margin=1.0, p=2.0, reduction='mean', backend=None)[source]

Bases: FractionalLossFunction

Triplet Margin loss with fractional calculus integration

Parameters:
__init__(fractional_order=0.5, method='RL', margin=1.0, p=2.0, reduction='mean', backend=None)[source]
Parameters:
compute_loss(predictions, targets)[source]

Compute the base loss function

Parameters:
  • predictions (Any) – Model predictions

  • targets (Any) – Ground truth targets

Returns:

Loss value

Return type:

Any

class hpfracc.ml.losses.FractionalCTCLoss(fractional_order=0.5, method='RL', blank=0, reduction='mean', backend=None)[source]

Bases: FractionalLossFunction

Connectionist Temporal Classification loss with fractional calculus integration

Parameters:
__init__(fractional_order=0.5, method='RL', blank=0, reduction='mean', backend=None)[source]
Parameters:
compute_loss(predictions, targets)[source]

Compute the base loss function

Parameters:
  • predictions (Any) – Model predictions

  • targets (Any) – Ground truth targets

Returns:

Loss value

Return type:

Any

class hpfracc.ml.losses.FractionalCustomLoss(loss_fn, fractional_order=0.5, method='RL', backend=None)[source]

Bases: FractionalLossFunction

Custom loss function with fractional calculus integration

Parameters:
__init__(loss_fn, fractional_order=0.5, method='RL', backend=None)[source]
Parameters:
compute_loss(predictions, targets)[source]

Compute the base loss function

Parameters:
  • predictions (Any) – Model predictions

  • targets (Any) – Ground truth targets

Returns:

Loss value

Return type:

Any

class hpfracc.ml.losses.FractionalCombinedLoss(loss_functions, weights=None, fractional_order=0.5, method='RL', backend=None)[source]

Bases: FractionalLossFunction

Combined loss function with fractional calculus integration

Parameters:
__init__(loss_functions, weights=None, fractional_order=0.5, method='RL', backend=None)[source]
Parameters:
compute_loss(predictions, targets)[source]

Compute the base loss function

Parameters:
  • predictions (Any) – Model predictions

  • targets (Any) – Ground truth targets

Returns:

Loss value

Return type:

Any

class hpfracc.ml.losses.FractionalSDEMSELoss(num_samples=10, reduction='mean', fractional_order=0.5, method='RL', backend=None)[source]

Bases: FractionalLossFunction

MSE loss for fractional SDE trajectory matching.

Computes L2 distance between predicted and target trajectories, accounting for stochastic variability through multiple samples.

Parameters:
__init__(num_samples=10, reduction='mean', fractional_order=0.5, method='RL', backend=None)[source]

Initialize SDE MSE loss.

Parameters:
  • num_samples (int) – Number of stochastic samples to average over

  • reduction (str) – Reduction type (“mean”, “sum”, “none”)

  • fractional_order (float) – Fractional order for loss computation

  • method (str) – Fractional derivative method

  • backend (BackendType | None) – Computation backend

compute_loss(predictions, targets)[source]

Compute MSE loss for SDE trajectories.

Parameters:
  • predictions (Any) – Predicted trajectories (may be stochastic samples)

  • targets (Any) – Target trajectories

Returns:

MSE loss

Return type:

Any

class hpfracc.ml.losses.FractionalKLDivergenceLoss(eps=1e-08, fractional_order=0.5, method='RL', backend=None)[source]

Bases: FractionalLossFunction

KL divergence loss for matching SDE distributions.

Measures divergence between predicted and target distributions in stochastic dynamics.

Parameters:
__init__(eps=1e-08, fractional_order=0.5, method='RL', backend=None)[source]

Initialize KL divergence loss.

Parameters:
  • eps (float) – Small constant for numerical stability

  • fractional_order (float) – Fractional order for loss computation

  • method (str) – Fractional derivative method

  • backend (BackendType | None) – Computation backend

compute_loss(predictions, targets)[source]

Compute KL divergence loss.

Parameters:
  • predictions (Any) – Predicted probabilities or samples

  • targets (Any) – Target probabilities or samples

Returns:

KL divergence loss

Return type:

Any

class hpfracc.ml.losses.FractionalPathwiseLoss(uncertainty_weight=1.0, fractional_order=0.5, method='RL', backend=None)[source]

Bases: FractionalLossFunction

Pathwise loss with uncertainty weighting.

Weighted loss that accounts for prediction uncertainty in stochastic trajectories.

Parameters:
__init__(uncertainty_weight=1.0, fractional_order=0.5, method='RL', backend=None)[source]

Initialize pathwise loss.

Parameters:
  • uncertainty_weight (float) – Weight for uncertainty term

  • fractional_order (float) – Fractional order for loss computation

  • method (str) – Fractional derivative method

  • backend (BackendType | None) – Computation backend

compute_loss(predictions, targets)[source]

Compute pathwise loss with uncertainty weighting.

Parameters:
  • predictions (Any) – Predicted trajectories with uncertainty

  • targets (Any) – Target trajectories

Returns:

Weighted pathwise loss

Return type:

Any

class hpfracc.ml.losses.FractionalMomentMatchingLoss(moments=None, weights=None, fractional_order=0.5, method='RL', backend=None)[source]

Bases: FractionalLossFunction

Moment matching loss for SDE distributions.

Matches statistical moments (mean, variance, etc.) between predicted and target distributions.

Parameters:
__init__(moments=None, weights=None, fractional_order=0.5, method='RL', backend=None)[source]

Initialize moment matching loss.

Parameters:
  • moments (list) – List of moments to match (default: [1, 2] for mean, variance)

  • weights (list) – Weights for each moment

  • fractional_order (float) – Fractional order for loss computation

  • method (str) – Fractional derivative method

  • backend (BackendType | None) – Computation backend

compute_loss(predictions, targets)[source]

Compute moment matching loss.

Parameters:
  • predictions (Any) – Predicted samples or distribution parameters

  • targets (Any) – Target samples or distribution parameters

Returns:

Moment matching loss

Return type:

Any

_compute_moment(x, order)[source]

Compute statistical moment of given order.

Parameters:
Return type:

Any

Optimizers

Optimized Fractional Calculus Optimizers

This module provides highly optimized fractional calculus optimizers that:

  • Inherit from torch.optim.Optimizer for standard PyTorch compatibility.

  • Implement “Fractional Gradient Descent” logic where gradients are pre-processed with fractional calculus operators before the standard update step.

Author: Davian R. Chin

class hpfracc.ml.optimized_optimizers.FractionalOptimizer(*args, **kwargs)[source]

Bases: Optimizer

Base class for fractional optimizers. intercepts gradients and applies fractional derivatives before the update step.

__init__(params, defaults)[source]
_apply_fractional_gradients(group)[source]

Applies fractional derivative to gradients in place or returns modified list. Currently we modify the grad attribute in-place temporarily or return tensor.

class hpfracc.ml.optimized_optimizers.OptimizedFractionalSGD(*args, **kwargs)[source]

Bases: FractionalOptimizer

Optimized SGD with fractional calculus integration.

__init__(params, lr=0.001, momentum=0, dampening=0, weight_decay=0, nesterov=False, fractional_order=0.5, method='RL', use_fractional=True)[source]
step(closure=None)
class hpfracc.ml.optimized_optimizers.OptimizedFractionalAdam(*args, **kwargs)[source]

Bases: FractionalOptimizer

Optimized Adam with fractional calculus integration.

__init__(params, lr=0.001, betas=(0.9, 0.999), eps=1e-08, weight_decay=0, amsgrad=False, fractional_order=0.5, method='RL', use_fractional=True)[source]
step(closure=None)
class hpfracc.ml.optimized_optimizers.OptimizedFractionalRMSprop(*args, **kwargs)[source]

Bases: FractionalOptimizer

Optimized RMSprop with fractional calculus integration.

__init__(params, lr=0.01, alpha=0.99, eps=1e-08, weight_decay=0, momentum=0, centered=False, fractional_order=0.5, method='RL', use_fractional=True)[source]
step(closure=None)
hpfracc.ml.optimized_optimizers.OptimizedBaseOptimizer

alias of FractionalOptimizer

hpfracc.ml.optimized_optimizers.create_optimized_sgd(lr=0.001, momentum=0.0, **kwargs)[source]
hpfracc.ml.optimized_optimizers.create_optimized_adam(lr=0.001, betas=(0.9, 0.999), **kwargs)[source]

Detailed API Documentation

Core Definitions

FractionalOrder

class hpfracc.FractionalOrder(alpha, validate=True, method=None)[source]

Bases: object

Represents a fractional order with validation and properties.

The fractional order α can be any real number, but typically we consider 0 < α < 2 for most applications.

Parameters:
__init__(alpha, validate=True, method=None)[source]

Initialize fractional order.

Parameters:
_validate()[source]

Validate the fractional order.

property value: float

Get the fractional order value.

property is_integer: bool

Check if the order is an integer.

property is_fractional: bool

Check if the order is fractional (not integer).

property integer_part: int

Get the integer part of the fractional order.

property fractional_part: float

Get the fractional part of the fractional order.

__repr__()[source]

Return repr(self).

Return type:

str

__str__()[source]

Return str(self).

Return type:

str

Core Fractional Calculus Methods

Canonical engines (algorithms.derivatives)

These are the single dispatching implementations used library-wide.

class hpfracc.algorithms.derivatives.RiemannLiouville(order, backend='auto')[source]

Bases: UnifiedFractionalOperator

Riemann-Liouville fractional derivative. D^α f(t) = (d/dt)^n I^(n-α) f(t)

Parameters:
__init__(order, backend='auto')[source]
Parameters:
compute(f, t, h=None)[source]
Parameters:
Return type:

ndarray

class hpfracc.algorithms.derivatives.Caputo(order, backend='auto')[source]

Bases: UnifiedFractionalOperator

Caputo fractional derivative. D^α f(t) = I^(n-α) f^(n)(t)

Parameters:
compute(f, t, h=None)[source]
Parameters:
Return type:

ndarray

class hpfracc.algorithms.derivatives.GrunwaldLetnikov(order, backend='auto')[source]

Bases: UnifiedFractionalOperator

Grünwald-Letnikov fractional derivative.

Parameters:
compute(f, t, h=None)[source]
Parameters:
Return type:

ndarray

OptimizedRiemannLiouville

hpfracc.OptimizedRiemannLiouville

alias of RiemannLiouville

OptimizedCaputo

hpfracc.OptimizedCaputo

alias of Caputo

OptimizedGrunwaldLetnikov

hpfracc.OptimizedGrunwaldLetnikov

alias of GrunwaldLetnikov

RiemannLiouvilleDerivative

class hpfracc.core.fractional_implementations.RiemannLiouvilleDerivative(order, **kwargs)[source]

Bases: BaseFractionalDerivative

Riemann-Liouville fractional derivative — adapter over the canonical engine hpfracc.algorithms.derivatives.RiemannLiouville.

Parameters:

order (float | FractionalOrder)

__init__(order, **kwargs)[source]

Initialize fractional derivative.

Parameters:
  • order (float | FractionalOrder) – Fractional order

  • definition – Mathematical definition

  • use_jax – Whether to use JAX optimizations

  • use_numba – Whether to use NUMBA optimizations

compute(f, x, h=None, **kwargs)[source]

Compute the Riemann-Liouville fractional derivative.

Parameters:
Return type:

float | ndarray

compute_numerical(f_values, x_values, **kwargs)[source]

Compute the derivative numerically from function values.

Parameters:
Return type:

ndarray

CaputoDerivative

class hpfracc.core.fractional_implementations.CaputoDerivative(order, **kwargs)[source]

Bases: BaseFractionalDerivative

Caputo fractional derivative — adapter over the canonical engine hpfracc.algorithms.derivatives.Caputo (single implementation path).

Parameters:

order (float | FractionalOrder)

__init__(order, **kwargs)[source]

Initialize fractional derivative.

Parameters:
  • order (float | FractionalOrder) – Fractional order

  • definition – Mathematical definition

  • use_jax – Whether to use JAX optimizations

  • use_numba – Whether to use NUMBA optimizations

compute(f, x, h=None, **kwargs)[source]

Compute the Caputo fractional derivative.

Parameters:
Return type:

float | ndarray

compute_numerical(f_values, x_values, **kwargs)[source]

Compute the derivative numerically from function values.

Parameters:
Return type:

ndarray

GrunwaldLetnikovDerivative

class hpfracc.core.fractional_implementations.GrunwaldLetnikovDerivative(order, **kwargs)[source]

Bases: BaseFractionalDerivative

Grünwald–Letnikov fractional derivative — adapter over the canonical engine hpfracc.algorithms.derivatives.GrunwaldLetnikov.

Parameters:

order (float | FractionalOrder)

__init__(order, **kwargs)[source]

Initialize fractional derivative.

Parameters:
  • order (float | FractionalOrder) – Fractional order

  • definition – Mathematical definition

  • use_jax – Whether to use JAX optimizations

  • use_numba – Whether to use NUMBA optimizations

compute(f, x, h=None, **kwargs)[source]

Compute the Grunwald-Letnikov fractional derivative.

Parameters:
Return type:

float | ndarray

compute_numerical(f_values, x_values, **kwargs)[source]

Compute the derivative numerically from function values.

Parameters:
Return type:

ndarray

Public package adapters (hpfracc.*)

hpfracc.RiemannLiouville, hpfracc.Caputo, and hpfracc.GrunwaldLetnikov are the same *Derivative classes as above (re-exported at package scope).

hpfracc.RiemannLiouville

alias of RiemannLiouvilleDerivative

hpfracc.Caputo

alias of CaputoDerivative

hpfracc.GrunwaldLetnikov

alias of GrunwaldLetnikovDerivative

Backend Management

BackendType

class hpfracc.ml.backends.BackendType(value)[source]

Bases: Enum

Available computation backends

TORCH = 'torch'
JAX = 'jax'
NUMBA = 'numba'
AUTO = 'auto'

BackendManager

class hpfracc.ml.backends.BackendManager(preferred_backend=BackendType.AUTO, force_cpu=False, enable_jit=True, enable_gpu=True)[source]

Bases: object

Manages backend selection and provides unified interfaces

This class handles automatic backend selection based on: - Data type and size - Hardware availability (CPU/GPU) - Performance requirements - User preferences

Parameters:
__init__(preferred_backend=BackendType.AUTO, force_cpu=False, enable_jit=True, enable_gpu=True)[source]
Parameters:
_detect_available_backends()[source]

Detect which backends are available on the system

Return type:

List[BackendType]

_select_optimal_backend()[source]

Select the optimal backend based on preferences and availability

Return type:

BackendType

_initialize_backend_configs()[source]

Initialize backend-specific configurations

Return type:

Dict[BackendType, Dict[str, Any]]

get_backend_config(backend=None)[source]

Get configuration for a specific backend

Parameters:

backend (BackendType | None)

Return type:

Dict[str, Any]

switch_backend(backend)[source]

Switch to a different backend

Parameters:

backend (BackendType)

Return type:

bool

get_tensor_lib()[source]

Get the active tensor library

Return type:

Any

create_tensor(data, **kwargs)[source]

Create a tensor in the active backend

Parameters:

data (Any)

Return type:

Any

to_device(tensor, device=None)[source]

Move tensor to specified device

Parameters:
  • tensor (Any)

  • device (str | None)

Return type:

Any

compile_function(func)[source]

Compile a function using the active backend’s compilation system

Parameters:

func (Callable)

Return type:

Callable

Tensor Operations

TensorOps

class hpfracc.ml.tensor_ops.TensorOps[source]

Bases: ABC

Abstract base class for tensor operations across different backends.

abstractmethod create_tensor(data, **kwargs)[source]
Parameters:

data (Any)

Return type:

Any

abstractmethod shape(tensor)[source]
Parameters:

tensor (Any)

Return type:

Any

abstractmethod from_numpy(array)[source]
Parameters:

array (Any)

Return type:

Any

abstractmethod to_numpy(tensor)[source]
Parameters:

tensor (Any)

Return type:

Any

abstractmethod no_grad()[source]
Return type:

ContextManager

abstractmethod zeros(shape, **kwargs)[source]
Parameters:

shape (Tuple[int, ...])

Return type:

Any

abstractmethod ones(shape, **kwargs)[source]
Parameters:

shape (Tuple[int, ...])

Return type:

Any

abstractmethod eye(n, **kwargs)[source]
Parameters:

n (int)

Return type:

Any

abstractmethod arange(start, end, step=1, **kwargs)[source]
Parameters:
Return type:

Any

abstractmethod linspace(start, end, num, **kwargs)[source]
Parameters:
Return type:

Any

abstractmethod zeros_like(tensor, **kwargs)[source]
Parameters:

tensor (Any)

Return type:

Any

abstractmethod ones_like(tensor, **kwargs)[source]
Parameters:

tensor (Any)

Return type:

Any

abstractmethod sqrt(tensor)[source]
Parameters:

tensor (Any)

Return type:

Any

abstractmethod stack(tensors, dim=0)[source]
Parameters:
Return type:

Any

abstractmethod cat(tensors, dim=0)[source]
Parameters:
Return type:

Any

abstractmethod reshape(tensor, shape)[source]
Parameters:
Return type:

Any

abstractmethod repeat(tensor, repeats, dim=0)[source]
Parameters:
Return type:

Any

abstractmethod tile(tensor, reps)[source]
Parameters:
Return type:

Any

abstractmethod clip(tensor, min_val, max_val)[source]
Parameters:
Return type:

Any

abstractmethod unsqueeze(tensor, dim)[source]
Parameters:
Return type:

Any

abstractmethod expand(tensor, *sizes)[source]
Parameters:
Return type:

Any

abstractmethod gather(tensor, dim, index)[source]
Parameters:
Return type:

Any

abstractmethod squeeze(tensor, dim=None)[source]
Parameters:
  • tensor (Any)

  • dim (int | None)

Return type:

Any

abstractmethod transpose(tensor, *args, **kwargs)[source]
Parameters:

tensor (Any)

Return type:

Any

abstractmethod matmul(a, b)[source]
Parameters:
Return type:

Any

abstractmethod inverse(tensor)[source]
Parameters:

tensor (Any)

Return type:

Any

abstractmethod mean(tensor, dim=None, keepdims=False, axis=None)[source]
Parameters:
  • tensor (Any)

  • dim (int | None)

  • keepdims (bool)

  • axis (int | None)

Return type:

Any

abstractmethod sum(tensor, dim=None, keepdims=False, axis=None)[source]
Parameters:
  • tensor (Any)

  • dim (int | None)

  • keepdims (bool)

  • axis (int | None)

Return type:

Any

abstractmethod max(tensor, dim=None, keepdims=False, axis=None)[source]
Parameters:
  • tensor (Any)

  • dim (int | None)

  • keepdims (bool)

  • axis (int | None)

Return type:

Any

abstractmethod min(tensor, dim=None, keepdims=False, axis=None)[source]
Parameters:
  • tensor (Any)

  • dim (int | None)

  • keepdims (bool)

  • axis (int | None)

Return type:

Any

abstractmethod minimum(a, b)[source]
Parameters:
Return type:

Any

abstractmethod maximum(a, b)[source]
Parameters:
Return type:

Any

abstractmethod where(condition, x, y)[source]
Parameters:
Return type:

Any

abstractmethod norm(tensor, dim=None, axis=None, keepdims=False, ord=2)[source]
Parameters:
Return type:

Any

tensor(data, **kwargs)[source]

Alias for create_tensor

Parameters:

data (Any)

Return type:

Any

abstractmethod add(a, b)[source]
Parameters:
Return type:

Any

abstractmethod subtract(a, b)[source]
Parameters:
Return type:

Any

abstractmethod multiply(a, b)[source]
Parameters:
Return type:

Any

abstractmethod divide(a, b)[source]
Parameters:
Return type:

Any

abstractmethod power(a, b)[source]
Parameters:
Return type:

Any

abstractmethod sin(tensor)[source]
Parameters:

tensor (Any)

Return type:

Any

abstractmethod cos(tensor)[source]
Parameters:

tensor (Any)

Return type:

Any

abstractmethod exp(tensor)[source]
Parameters:

tensor (Any)

Return type:

Any

abstractmethod log(tensor)[source]
Parameters:

tensor (Any)

Return type:

Any

abstractmethod abs(tensor)[source]
Parameters:

tensor (Any)

Return type:

Any

abstractmethod sign(tensor)[source]
Parameters:

tensor (Any)

Return type:

Any

abstractmethod relu(tensor)[source]
Parameters:

tensor (Any)

Return type:

Any

abstractmethod sigmoid(tensor)[source]
Parameters:

tensor (Any)

Return type:

Any

abstractmethod tanh(tensor)[source]
Parameters:

tensor (Any)

Return type:

Any

abstractmethod softmax(tensor, dim=-1)[source]
Parameters:
Return type:

Any

abstractmethod dropout(tensor, p=0.5, training=True, **kwargs)[source]
Parameters:
Return type:

Any

abstractmethod batch_norm(tensor, mean=None, var=None, weight=None, bias=None, training=False, momentum=0.1, eps=1e-05)[source]
Parameters:
Return type:

Any

abstractmethod layer_norm(tensor, normalized_shape=None, weight=None, bias=None, eps=1e-05)[source]
Parameters:
Return type:

Any

abstractmethod convolve(input, weight, bias=None, stride=1, padding=0, dilation=1, groups=1)[source]
Parameters:
Return type:

Any

abstractmethod max_pool(input, kernel_size, stride=None, padding=0)[source]
Parameters:
  • input (Any)

  • kernel_size (int)

  • stride (int | None)

  • padding (int)

Return type:

Any

abstractmethod avg_pool(input, kernel_size, stride=None, padding=0)[source]
Parameters:
  • input (Any)

  • kernel_size (int)

  • stride (int | None)

  • padding (int)

Return type:

Any

abstractmethod backward(tensor, grad_tensor=None)[source]
Parameters:
  • tensor (Any)

  • grad_tensor (Any | None)

Return type:

Any

abstractmethod grad(tensor)[source]
Parameters:

tensor (Any)

Return type:

Any

abstractmethod random_normal(shape, mean=0.0, std=1.0, **kwargs)[source]
Parameters:
Return type:

Any

abstractmethod random_uniform(shape, min_val=0.0, max_val=1.0, **kwargs)[source]
Parameters:
Return type:

Any

abstractmethod mse_loss(input, target, reduction='mean')[source]
Parameters:
Return type:

Any

abstractmethod cross_entropy_loss(input, target, reduction='mean', **kwargs)[source]
Parameters:
Return type:

Any

abstractmethod to_device(tensor, device)[source]
Parameters:
Return type:

Any

abstractmethod device(tensor)[source]
Parameters:

tensor (Any)

Return type:

str

abstractmethod equal(a, b)[source]
Parameters:
Return type:

Any

abstractmethod greater(a, b)[source]
Parameters:
Return type:

Any

abstractmethod less(a, b)[source]
Parameters:
Return type:

Any

abstractmethod logical_and(a, b)[source]
Parameters:
Return type:

Any

abstractmethod logical_or(a, b)[source]
Parameters:
Return type:

Any

abstractmethod logical_not(a)[source]
Parameters:

a (Any)

Return type:

Any

abstractmethod fft(tensor, n=None, dim=-1, norm=None)[source]
Parameters:
Return type:

Any

abstractmethod ifft(tensor, n=None, dim=-1, norm=None)[source]
Parameters:
Return type:

Any

concatenate(tensors, dim=0)[source]
Parameters:
Return type:

Any

abstractmethod index(tensor, index)[source]
Parameters:
Return type:

Any

abstractmethod slice(tensor, start, end, dim=0)[source]
Parameters:
Return type:

Any

abstractmethod sgd_step(tensor, lr)[source]
Parameters:
Return type:

Any

abstractmethod adam_step(tensor, lr)[source]
Parameters:
Return type:

Any

switch_backend(backend)[source]
Parameters:

backend (Any)

Return type:

bool

abstractmethod get_backend_info()[source]
Return type:

Dict[str, Any]

enable_profiling(enable)[source]
Parameters:

enable (bool)

get_profile_results()[source]
Return type:

Dict[str, Any]

clear_cache()[source]
get_memory_usage()[source]
Return type:

Dict[str, Any]

Neural Networks

FractionalNeuralNetwork

class hpfracc.ml.core.FractionalNeuralNetwork(input_size, hidden_sizes, output_size, fractional_order=0.5, activation='relu', dropout=0.1, config=None, backend=None, differentiable_fractional=True, fractional_axis=-1, fractional_step=None, fractional_t_grid=None)[source]

Bases: object

Neural network with fractional calculus integration.

Tensor layout. The first linear layer expects the same shape you pass to forward (typically (batch, input_size)). The fractional pre-processing step applies a discrete fractional operator along fractional_axis (default -1, the feature / time-sample axis). Use fractional_axis=0 only if your rows are samples along an index (unusual for (batch, features)).

Grid. Native GL / Caputo L1 use a uniform step h. Provide fractional_step (scalar h), or fractional_t_grid (length matching the sampled axis; must be strictly increasing and evenly spaced), or omit both for the default grid t = linspace(0, 1, n) with h = 1/(n-1). Non-uniform grids are rejected in the native path; use differentiable_fractional=False for the legacy NumPy operator (still uniform t implied the same way).

Supports PyTorch, JAX, and NUMBA backends.

Parameters:
__init__(input_size, hidden_sizes, output_size, fractional_order=0.5, activation='relu', dropout=0.1, config=None, backend=None, differentiable_fractional=True, fractional_axis=-1, fractional_step=None, fractional_t_grid=None)[source]
Parameters:
train(mode=True)[source]

Set training mode

Parameters:

mode (bool)

eval()[source]

Set evaluation mode

parameters()[source]

Return list of learnable parameters for compatibility with optimizers/tests

Return type:

List[Any]

_build_network()[source]

Build the network architecture using the current backend

_initialize_weights()[source]

Initialize network weights using Xavier initialization

fractional_forward(x, method='RL', *, axis=None, fractional_step=None, fractional_t_grid=None)[source]

Apply a discrete fractional operator along axis (default: fractional_axis).

Optional per-call overrides: axis, fractional_step, fractional_t_grid (same semantics as constructor; per-call grid overrides instance grid).

Parameters:
Return type:

Any

forward(x, use_fractional=True, method='RL', params=None, fractional_axis=None, fractional_step=None, fractional_t_grid=None)[source]

Forward pass through the network

Parameters:
  • x (Any) – Input tensor

  • use_fractional (bool) – Whether to apply fractional derivatives

  • method (str) – Fractional derivative method if use_fractional is True

  • params (Dict[str, List[Any]] | None) – Optional dictionary of parameters {‘weights’: […], ‘biases’: […]} for functional execution (JAX support).

  • fractional_axis (int | None) – Optional override for the sampled axis (see class docstring).

  • fractional_step (float | None) – Optional uniform step h for the fractional grid.

  • fractional_t_grid (ndarray | Sequence[float] | None) – Optional uniform 1D grid (length = size along sampled axis).

Returns:

Network output

Return type:

Any

_apply_activation(x)[source]

Apply activation function based on backend

Parameters:

x (Any)

Return type:

Any

save_model(path)[source]

Save model to file

Parameters:

path (str)

classmethod load_model(path, config_path=None)[source]

Load model from file

Parameters:
  • path (str)

  • config_path (str | None)

Graph Neural Networks

FractionalGCN

class hpfracc.ml.gnn_models.FractionalGCN(input_dim, hidden_dim, output_dim, num_layers=3, fractional_order=0.5, method='RL', use_fractional=True, activation='relu', dropout=0.1, backend=None)[source]

Bases: BaseFractionalGNN

Fractional Graph Convolutional Network

A GNN architecture that uses fractional graph convolution layers for node classification, graph classification, and other tasks.

Parameters:
_build_network()[source]

Build the GCN architecture

forward(x, edge_index, batch=None, **kwargs)[source]

Forward pass through the fractional GCN

Parameters:
  • x (Any) – Node feature matrix [num_nodes, input_dim]

  • edge_index (Any) – Graph connectivity [2, num_edges]

  • batch (Any | None) – Batch assignment vector [num_nodes]

Returns:

Node embeddings [num_nodes, output_dim]

Return type:

Any

FractionalGAT

class hpfracc.ml.gnn_models.FractionalGAT(input_dim, hidden_dim, output_dim, num_layers=3, num_heads=8, fractional_order=0.5, method='RL', use_fractional=True, activation='relu', dropout=0.1, backend=None)[source]

Bases: BaseFractionalGNN

Fractional Graph Attention Network

A GNN architecture that uses fractional graph attention layers for enhanced graph representation learning.

Parameters:
__init__(input_dim, hidden_dim, output_dim, num_layers=3, num_heads=8, fractional_order=0.5, method='RL', use_fractional=True, activation='relu', dropout=0.1, backend=None)[source]
Parameters:
_build_network()[source]

Build the GAT architecture

forward(x, edge_index, batch=None, **kwargs)[source]

Forward pass through the fractional GAT

Parameters:
  • x (Any) – Node feature matrix [num_nodes, input_dim]

  • edge_index (Any) – Graph connectivity [2, num_edges]

  • batch (Any | None) – Batch assignment vector [num_nodes]

Returns:

Node embeddings [num_nodes, output_dim]

Return type:

Any

FractionalGraphSAGE

class hpfracc.ml.gnn_models.FractionalGraphSAGE(input_dim, hidden_dim, output_dim, num_layers=3, num_samples=25, fractional_order=0.5, method='RL', use_fractional=True, activation='relu', dropout=0.1, backend=None)[source]

Bases: BaseFractionalGNN

Fractional GraphSAGE Network

A GNN architecture that uses fractional graph convolution layers with neighbor sampling for scalable graph learning.

Parameters:
__init__(input_dim, hidden_dim, output_dim, num_layers=3, num_samples=25, fractional_order=0.5, method='RL', use_fractional=True, activation='relu', dropout=0.1, backend=None)[source]
Parameters:
_build_network()[source]

Build the GraphSAGE architecture

forward(x, edge_index, batch=None, **kwargs)[source]

Forward pass through the fractional GraphSAGE

Parameters:
  • x (Any) – Node feature matrix [num_nodes, input_dim]

  • edge_index (Any) – Graph connectivity [2, num_edges]

  • batch (Any | None) – Batch assignment vector [num_nodes]

Returns:

Node embeddings [num_nodes, output_dim]

Return type:

Any

FractionalGraphUNet

class hpfracc.ml.gnn_models.FractionalGraphUNet(input_dim, hidden_dim, output_dim, num_layers=4, pooling_ratio=0.5, fractional_order=0.5, method='RL', use_fractional=True, activation='relu', dropout=0.1, backend=None)[source]

Bases: BaseFractionalGNN

Fractional Graph U-Net

A hierarchical GNN architecture that uses fractional calculus for multi-scale graph representation learning.

Parameters:
__init__(input_dim, hidden_dim, output_dim, num_layers=4, pooling_ratio=0.5, fractional_order=0.5, method='RL', use_fractional=True, activation='relu', dropout=0.1, backend=None)[source]
Parameters:
_build_network()[source]

Build the Graph U-Net architecture

forward(x, edge_index, batch=None, **kwargs)[source]

Forward pass through the fractional Graph U-Net

Parameters:
  • x (Any) – Node feature matrix [num_nodes, input_dim]

  • edge_index (Any) – Graph connectivity [2, num_edges]

  • batch (Any | None) – Batch assignment vector [num_nodes]

Returns:

Node embeddings [num_nodes, output_dim]

Return type:

Any

GNN Factory

class hpfracc.ml.gnn_models.FractionalGNNFactory[source]

Bases: object

Factory class for creating fractional GNN models

This class provides a convenient interface for creating different types of fractional GNN architectures with consistent configurations.

static create_model(model_type, input_dim, hidden_dim, output_dim, **kwargs)[source]

Create a fractional GNN model of the specified type

Parameters:
  • model_type (str) – Type of GNN model (‘gcn’, ‘gat’, ‘sage’, ‘unet’)

  • input_dim (int) – Input feature dimension

  • hidden_dim (int) – Hidden layer dimension

  • output_dim (int) – Output dimension

  • **kwargs – Additional arguments for the model

Returns:

Configured fractional GNN model

Return type:

BaseFractionalGNN

static get_available_models()[source]

Get list of available model types

Return type:

List[str]

static get_model_info(model_type)[source]

Get information about a specific model type

Parameters:

model_type (str)

Return type:

Dict[str, Any]

GNN Layers

FractionalGraphConv

class hpfracc.ml.gnn_layers.FractionalGraphConv(in_channels, out_channels, fractional_order=0.5, method='RL', use_fractional=True, activation='relu', dropout=0.1, bias=True, backend=None)[source]

Bases: TorchFractionalGNNMixin, JaxFractionalGNNMixin, NumbaFractionalGNNMixin, BaseFractionalGNNLayer

Fractional Graph Convolutional Layer. Combines backend-specific implementations via mixins.

Parameters:
_initialize_layer()[source]

Initialize the graph convolution layer

forward(x, edge_index, edge_weight=None, **kwargs)[source]

Forward pass through the layer

Parameters:
  • x (Any)

  • edge_index (Any)

  • edge_weight (Any | None)

Return type:

Any

train(mode=True)[source]
Parameters:

mode (bool)

eval()[source]
parameters()[source]
named_parameters()[source]
state_dict()[source]
load_state_dict(state_dict)[source]

FractionalGraphAttention

class hpfracc.ml.gnn_layers.FractionalGraphAttention(in_channels, out_channels, heads=8, fractional_order=0.5, method='RL', use_fractional=True, activation='relu', dropout=0.1, bias=True, backend=None, **kwargs)[source]

Bases: TorchFractionalGNNMixin, JaxFractionalGNNMixin, NumbaFractionalGNNMixin, BaseFractionalGNNLayer

Fractional Graph Attention Layer.

Parameters:
__init__(in_channels, out_channels, heads=8, fractional_order=0.5, method='RL', use_fractional=True, activation='relu', dropout=0.1, bias=True, backend=None, **kwargs)[source]
Parameters:
forward(x, edge_index, edge_weight=None, **kwargs)[source]

Forward pass through the layer

Parameters:
  • x (Any)

  • edge_index (Any)

  • edge_weight (Any | None)

Return type:

Any

FractionalGraphPooling

class hpfracc.ml.gnn_layers.FractionalGraphPooling(in_channels=64, pooling_ratio=0.5, out_channels=None, fractional_order=0.5, method='RL', use_fractional=True, backend=None, **kwargs)[source]

Bases: TorchFractionalGNNMixin, JaxFractionalGNNMixin, NumbaFractionalGNNMixin, BaseFractionalGNNLayer

Fractional Graph Pooling Layer. Reduces graph size while preserving fractional properties.

Parameters:
__init__(in_channels=64, pooling_ratio=0.5, out_channels=None, fractional_order=0.5, method='RL', use_fractional=True, backend=None, **kwargs)[source]
Parameters:
forward(x, edge_index, batch=None, **kwargs)[source]

Identity pooling on features; always returns (x, edge_index, batch).

Graph coarsening (changing node count / edges) is not implemented yet. Returning a triple keeps FractionalGraphUNet and call sites consistent.

Parameters:
  • x (Any)

  • edge_index (Any)

  • batch (Any | None)

Return type:

Tuple[Any, Any, Any]

BaseFractionalGNNLayer

class hpfracc.ml.gnn_layers.BaseFractionalGNNLayer(in_channels, out_channels, fractional_order=0.5, method='RL', use_fractional=True, activation='relu', dropout=0.1, bias=True, backend=None)[source]

Bases: ABC

Base class for fractional GNN layers

Parameters:
__init__(in_channels, out_channels, fractional_order=0.5, method='RL', use_fractional=True, activation='relu', dropout=0.1, bias=True, backend=None)[source]
Parameters:
abstractmethod forward(x, edge_index, edge_weight=None, **kwargs)[source]

Forward pass through the layer

Parameters:
  • x (Any)

  • edge_index (Any)

  • edge_weight (Any | None)

Return type:

Any

apply_fractional_derivative(x)[source]

Apply fractional derivative to input features.

Parameters:

x (Any)

Return type:

Any

Attention Mechanisms

FractionalAttention

class hpfracc.ml.core.FractionalAttention(d_model, n_heads=8, fractional_order=0.5, dropout=0.1, backend=None, differentiable_fractional=True, fractional_step=None, fractional_t_grid=None)[source]

Bases: object

Multi-head attention with an optional discrete fractional map on the attended context.

After standard attention, the context tensor has shape (batch, n_heads, seq_len, d_k). The fractional step runs along the sequence dimension (axis 2), using the same native Grünwald–Letnikov / L1-Caputo machinery as FractionalNeuralNetwork when differentiable_fractional is True. Optional fractional_step and fractional_t_grid define a uniform grid along that axis (see fractional_feature_map_native).

The spectral FFT stack in hpfracc.ml.spectral_autograd is separate; this class does not use it.

Supports PyTorch, JAX, and NUMBA backends.

Parameters:
__init__(d_model, n_heads=8, fractional_order=0.5, dropout=0.1, backend=None, differentiable_fractional=True, fractional_step=None, fractional_t_grid=None)[source]
Parameters:
train(mode=True)[source]
Parameters:

mode (bool)

eval()[source]
_initialize_weights()[source]

Initialize attention weights

fractional_attention(q, k, v, method='RL')[source]

Compute attention with fractional derivatives

Parameters:
  • q (Any) – Query, key, value tensors of shape (batch_size, n_heads, seq_len, d_k)

  • k (Any) – Query, key, value tensors of shape (batch_size, n_heads, seq_len, d_k)

  • v (Any) – Query, key, value tensors of shape (batch_size, n_heads, seq_len, d_k)

  • method (str) – Fractional derivative method

Returns:

Attention output with fractional calculus applied

Return type:

Any

forward(x, method='RL')[source]

Forward pass through fractional attention

Parameters:
  • x (Any) – Input tensor of shape (batch_size, seq_len, d_model)

  • method (str) – Fractional derivative method

Returns:

Output tensor with attention and fractional calculus applied

Return type:

Any

Fractional Autograd Framework (spectral)

Spectral fractional operators live in hpfracc.ml.spectral_autograd. They use FFT-based kernels and are not the same class as FractionalNeuralNetwork (which applies a discrete Grünwald–Letnikov / L1-Caputo map along a chosen axis; see hpfracc.ml.core.FractionalNeuralNetwork and hpfracc.ml.fractional_derivative_native).

SpectralFractionalDerivative

class hpfracc.ml.spectral_autograd.SpectralFractionalDerivative(alpha=0.5, dim=-1, backend=None, kernel_type='riesz', norm='ortho', epsilon=1e-06)[source]

Bases: object

Callable wrapper that mimics the autograd Function.apply interface.

Parameters:
  • alpha (_Alpha)

  • dim (_DimType)

  • backend (_Backend)

  • kernel_type (str)

  • norm (str)

  • epsilon (float)

__init__(alpha=0.5, dim=-1, backend=None, kernel_type='riesz', norm='ortho', epsilon=1e-06)[source]

Initialize the spectral fractional derivative operator.

Parameters:
  • alpha (int | float | torch.Tensor) – Fractional order (default: 0.5)

  • dim (int | Sequence[int] | None) – Dimension along which to compute derivative (default: -1)

  • backend (str | None) – FFT backend to use (default: None, uses global setting)

  • kernel_type (str) – Type of fractional kernel (default: “riesz”)

  • norm (str) – FFT normalization mode (default: “ortho”)

  • epsilon (float) – Small value for numerical stability (default: 1e-6)

static apply(x, alpha, kernel_type='riesz', dim=-1, norm='ortho', backend=None, epsilon=1e-06)[source]

Static method for backward compatibility.

Parameters:
Return type:

torch.Tensor

SpectralFractionalLayer

class hpfracc.ml.spectral_autograd.SpectralFractionalLayer(*args, **kwargs)[source]

Bases: Module

Apply a spectral fractional derivative inside a PyTorch layer.

Parameters:
  • input_size (Optional[int])

  • output_size (Optional[int])

  • alpha (_Alpha)

  • kernel_type (str)

  • dim (_DimType)

  • norm (str)

  • backend (_Backend)

  • epsilon (float)

  • learnable_alpha (bool)

__init__(input_size=None, output_size=None, alpha=0.5, kernel_type='riesz', dim=-1, norm='ortho', backend=None, epsilon=1e-06, learnable_alpha=False, **kwargs)[source]
Parameters:
Return type:

None

property alpha: float
property learnable: bool
get_alpha()[source]
Return type:

float | torch.Tensor

forward(x)[source]
Parameters:

x (torch.Tensor)

Return type:

torch.Tensor

SpectralFractionalNetwork

class hpfracc.ml.spectral_autograd.SpectralFractionalNetwork(*args, **kwargs)[source]

Bases: Module

Simple network that incorporates spectral fractional layers.

Modes - unified (default): unified adaptive framework (input_dim, hidden_dims, output_dim). - model: model-specific/coverage style (input_size, hidden_sizes, output_size).

Backends - torch (default), jax, numba. If unavailable, CPU-safe fallbacks are used.

Parameters:
  • input_size (Optional[int])

  • hidden_sizes (Optional[Sequence[int]])

  • output_size (Optional[int])

  • alpha (_Alpha)

  • input_dim (Optional[int])

  • hidden_dims (Optional[Sequence[int]])

  • output_dim (Optional[int])

  • kernel_type (str)

  • activation (Union[str, nn.Module, None])

  • learnable_alpha (bool)

  • backend (_Backend)

  • norm (str)

  • epsilon (float)

  • mode (str)

__init__(input_size=None, hidden_sizes=None, output_size=None, alpha=0.5, *, input_dim=None, hidden_dims=None, output_dim=None, kernel_type='riesz', activation='relu', learnable_alpha=False, backend=None, norm='ortho', epsilon=1e-06, mode='unified', **kwargs)[source]
Parameters:
  • input_size (int | None)

  • hidden_sizes (Sequence[int] | None)

  • output_size (int | None)

  • alpha (int | float | torch.Tensor)

  • input_dim (int | None)

  • hidden_dims (Sequence[int] | None)

  • output_dim (int | None)

  • kernel_type (str)

  • activation (str | torch.nn.Module | None)

  • learnable_alpha (bool)

  • backend (str | None)

  • norm (str)

  • epsilon (float)

  • mode (str)

Return type:

None

forward(x)[source]
Parameters:

x (torch.Tensor)

Return type:

torch.Tensor

StochasticMemorySampler

class hpfracc.ml.stochastic_memory_sampling.StochasticMemorySampler(alpha, method='importance', **kwargs)[source]

Bases: object

Base class for stochastic memory sampling strategies.

Parameters:
__init__(alpha, method='importance', **kwargs)[source]
Parameters:
sample_indices(n, k)[source]

Sample k indices from history of length n.

Parameters:
Return type:

torch.Tensor

compute_weights(indices, n)[source]

Compute importance weights for sampled indices.

Parameters:
  • indices (torch.Tensor)

  • n (int)

Return type:

torch.Tensor

estimate_derivative(x, indices, weights)[source]

Estimate fractional derivative using sampled indices and weights.

Parameters:
  • x (torch.Tensor)

  • indices (torch.Tensor)

  • weights (torch.Tensor)

Return type:

torch.Tensor

ProbabilisticFractionalLayer

class hpfracc.ml.probabilistic_fractional_orders.ProbabilisticFractionalLayer(*args, **kwargs)[source]

Bases: Module

PyTorch module for probabilistic fractional derivatives.

__init__(**kwargs)[source]
forward(x)[source]

Forward pass.

Parameters:

x (torch.Tensor)

Return type:

torch.Tensor

sample_alpha(n_samples=1)[source]

Sample fractional orders from the distribution.

Parameters:

n_samples (int)

Return type:

torch.Tensor

get_alpha_statistics()[source]

Get statistics of the fractional order distribution.

Return type:

Dict[str, torch.Tensor]

to(device)[source]

Move layer parameters to specified device (PyTorch compatibility)

extra_repr()[source]
Return type:

str

VarianceAwareTrainer

class hpfracc.ml.variance_aware_training.VarianceAwareTrainer(model, optimizer, loss_fn, variance_monitor=None, seed_manager=None, adaptive_sampling=None, callbacks=None)[source]

Bases: object

Enhanced trainer with variance awareness for stochastic fractional calculus.

Parameters:
__init__(model, optimizer, loss_fn, variance_monitor=None, seed_manager=None, adaptive_sampling=None, callbacks=None)[source]
Parameters:
_register_hooks()[source]

Register forward hooks to monitor variance.

train_epoch(dataloader, epoch=0)[source]

Train for one epoch with variance monitoring.

Parameters:

epoch (int)

Return type:

Dict[str, float]

train(dataloader, num_epochs)[source]

Train for multiple epochs.

Parameters:

num_epochs (int)

Return type:

Dict[str, List]

get_variance_summary()[source]

Get current variance summary.

Return type:

Dict[str, Dict[str, float]]

set_sampling_budget(k)[source]

Set sampling budget for stochastic components.

Parameters:

k (int)

enable_deterministic_mode(deterministic=True)[source]

Enable/disable deterministic mode.

Parameters:

deterministic (bool)

GPU Optimization

GPUProfiler

class hpfracc.ml.gpu_optimization.GPUProfiler(device='cuda')[source]

Bases: object

Simple profiler for GPU operations.

Parameters:

device (str)

__init__(device='cuda')[source]
Parameters:

device (str)

metrics_history: List[PerformanceMetrics]
current_metrics: Dict[str, PerformanceMetrics]
start_timer(operation)[source]

Start timing an operation.

Parameters:

operation (str)

end_timer(input_tensor, output_tensor=None)[source]

End timing and record metrics.

Parameters:
  • input_tensor (torch.Tensor)

  • output_tensor (torch.Tensor | None)

get_summary()[source]

Get performance summary.

Return type:

Dict[str, Dict[str, float]]

clear_history()[source]

Clear metrics history.

ChunkedFFT

class hpfracc.ml.gpu_optimization.ChunkedFFT(chunk_size=1024, overlap=0.1, window_type='hann')[source]

Bases: object

Chunked FFT operations for large sequences.

Parameters:
__init__(chunk_size=1024, overlap=0.1, window_type='hann')[source]
Parameters:
fft_chunked(x, dim=-1)[source]

Perform chunked FFT on large sequences.

Parameters:
  • x (torch.Tensor)

  • dim (int)

Return type:

torch.Tensor

ifft_chunked(x, dim=-1)[source]

Perform chunked IFFT on large sequences.

Parameters:
  • x (torch.Tensor)

  • dim (int)

Return type:

torch.Tensor

forward(x, dim=-1)[source]

Alias for fft_chunked.

Parameters:
  • x (torch.Tensor)

  • dim (int)

Return type:

torch.Tensor

inverse(x, dim=-1)[source]

Alias for ifft_chunked.

Parameters:
  • x (torch.Tensor)

  • dim (int)

Return type:

torch.Tensor

_process_chunks(x, dim, fft_func)[source]

Process tensor in chunks with overlap.

Parameters:
  • x (torch.Tensor)

  • dim (int)

Return type:

torch.Tensor

AMPFractionalEngine

class hpfracc.ml.gpu_optimization.AMPFractionalEngine(base_engine, use_amp=True, dtype=torch.float16)[source]

Bases: object

Automatic Mixed Precision wrapper for fractional engines.

Parameters:
  • use_amp (bool)

  • dtype (torch.dtype)

__init__(base_engine, use_amp=True, dtype=torch.float16)[source]
Parameters:
  • use_amp (bool)

  • dtype (torch.dtype)

forward(x, alpha, **kwargs)[source]

Forward pass with AMP support.

Parameters:
  • x (torch.Tensor)

  • alpha (float)

Return type:

torch.Tensor

backward(grad_output, **kwargs)[source]

Backward pass with AMP support.

Parameters:

grad_output (torch.Tensor)

Return type:

torch.Tensor

update_scaler()[source]

Update the GradScaler after an optimization step.

get_scaler_state()[source]

Get the current state of the GradScaler.

Return type:

Dict[str, Any]

Utility entry points (no duplicate autodoc stubs)

Fractional-derivative factories live under hpfracc.core.derivatives and the algorithm engines (hpfracc.algorithms.derivatives), both covered by .. automodule:: sections earlier in this page. Backend helpers (hpfracc.ml.backends) and tensor factories (hpfracc.ml.tensor_ops) are likewise indexed once via their automodule blocks to avoid duplicate Sphinx inventory entries.

Model Utilities

Note

Model creation utilities are available through the main ML module. See hpfracc.ml for factory functions and model constructors.

Configuration

Default Parameters

hpfracc.core.definitions.DEFAULT_FRACTIONAL_ORDER = 0.5
hpfracc.ml.backends.DEFAULT_BACKEND = BackendType.JAX
hpfracc.ml.tensor_ops.DEFAULT_DTYPE = 'float32'

Supported Backends

hpfracc.ml.backends.SUPPORTED_BACKENDS = [BackendType.TORCH, BackendType.JAX, BackendType.NUMBA]

Supported GNN Types

hpfracc.ml.gnn_models.SUPPORTED_GNN_TYPES = ['gcn', 'gat', 'sage', 'unet']

Supported Derivative Methods

hpfracc.core.derivatives.SUPPORTED_METHODS = ['RL', 'Caputo', 'GL']

Type Information

The library uses Python type hints throughout. Key types include:

  • FractionalOrder: Core class for representing fractional orders

  • BackendType: Enum for backend selection (TORCH, JAX, NUMBA, AUTO)

  • TensorType: Union of numpy arrays, PyTorch tensors, and JAX arrays

See the source code for detailed type annotations.

Usage Examples

Basic Fractional Calculus

from hpfracc.core.definitions import FractionalOrder
from hpfracc.core.derivatives import create_fractional_derivative
import numpy as np

# Create fractional derivative
alpha = FractionalOrder(0.5)
deriv = create_fractional_derivative(alpha, method="RL")

# Test function
def f(x):
    return np.exp(-x)

# Compute derivative
x = np.linspace(0, 1, 100)
result = deriv(f, x)

Neural Network Usage

from hpfracc.ml import FractionalNeuralNetwork
from hpfracc.ml.backends import BackendType
import numpy as np

# Create model (input_size = feature dimension per row)
model = FractionalNeuralNetwork(
    input_size=10,
    hidden_sizes=[32, 16],
    output_size=1,
    fractional_order=0.5,
    backend=BackendType.JAX,
    fractional_axis=-1,
)

# Forward pass: (batch, input_size); fractional step along last axis by default
X = np.random.randn(100, 10).astype(np.float32)
output = model(X, use_fractional=True, method="RL")

GNN Usage

from hpfracc.ml import FractionalGNNFactory
from hpfracc.core.definitions import FractionalOrder
from hpfracc.ml.backends import BackendType
import numpy as np

# Create GNN
gnn = FractionalGNNFactory.create_model(
    model_type='gcn',
    input_dim=16,
    hidden_dim=32,
    output_dim=4,
    fractional_order=FractionalOrder(0.5),
    backend=BackendType.TORCH
)

# Graph data
node_features = np.random.randn(50, 16)
edge_index = np.random.randint(0, 50, (2, 100))

# Forward pass
output = gnn.forward(node_features, edge_index)

Backend Management

from hpfracc.ml.backends import BackendManager, BackendType

# Check available backends
available = BackendManager.get_available_backends()
print(f"Available: {available}")

# Set backend
BackendManager.set_backend(BackendType.JAX)

# Get current backend
current = BackendManager.get_current_backend()
print(f"Current: {current}")

Spectral fractional (FFT) usage

import torch
from hpfracc.ml.spectral_autograd import spectral_fractional_derivative
from hpfracc.ml.stochastic_memory_sampling import StochasticMemorySampler
from hpfracc.ml.probabilistic_fractional_orders import ProbabilisticFractionalLayer

# Spectral fractional derivative along last dimension (PyTorch)
x = torch.randn(32, 128, requires_grad=True)
y = spectral_fractional_derivative(x, alpha=0.5, dim=-1, kernel_type="riesz")

# Stochastic memory sampler
sampler = StochasticMemorySampler(k=32, method="importance")

# Probabilistic fractional layer
prob_layer = ProbabilisticFractionalLayer(mean=0.5, std=0.1, learnable=True)

loss = y.sum()
loss.backward()
print(f"Gradients computed: {x.grad is not None}")

GPU Optimization

import torch
from hpfracc.ml.gpu_optimization import GPUProfiler, ChunkedFFT, gpu_optimization_context

# GPU profiling
profiler = GPUProfiler()
with profiler:
    # Your GPU operations here
    x = torch.randn(1000, 1000, device='cuda')
    result = torch.fft.fft(x)

# Chunked FFT for large sequences
chunked_fft = ChunkedFFT(chunk_size=1024)
x = torch.randn(10000, device='cuda')
result = chunked_fft.forward(x)

# GPU optimization context
with gpu_optimization_context(use_amp=True, chunk_size=512):
    # Your fractional calculus operations here
    pass

Performance Considerations

Backend Selection

  • PyTorch: Best for GPU acceleration and complex neural networks

  • JAX: Best for functional programming and TPU acceleration

  • NUMBA: Best for CPU optimization and lightweight deployment

Memory Management

  • Use batch processing for large datasets

  • Clear intermediate tensors when possible

  • Monitor memory usage with large models

Computation Optimization

  • Choose appropriate fractional derivative method for your use case

  • Use JIT compilation when available

  • Profile performance with different backends

Troubleshooting

Common Issues

Backend not available

# Check available backends
from hpfracc.ml.backends import BackendManager
available = BackendManager.get_available_backends()
print(f"Available: {available}")

Invalid fractional order

# Valid orders: -1 < order < 2
from hpfracc.core.definitions import FractionalOrder
try:
    order = FractionalOrder(0.5)  # Valid
except ValueError as e:
    print(f"Error: {e}")

Tensor shape mismatch

# Ensure input dimensions match model expectations
model = FractionalNeuralNetwork(input_size=10, hidden_sizes=[8], output_size=1)
X = np.random.randn(100, 10)  # Correct shape (batch, input_size)
# X = np.random.randn(100, 5)  # Wrong shape - will fail

Debugging Tips

  1. Enable debug logging

  2. Check tensor shapes and types

  3. Verify backend compatibility

  4. Test with small datasets first

For more detailed examples, see Tutorials & Examples.