PDE Module API Reference

Complete API reference for the PDE matrix generation module.

Main Classes

PDEMatrixGenerator

class matrix_toolkit.pde.PDEMatrixGenerator(equation_type: str, config: PDEConfig)[source]

Bases: object

Main interface for generating PDE matrices

Examples

>>> from matrix_toolkit.pde import PDEMatrixGenerator, PDEConfig
>>>
>>> # 2D Poisson equation
>>> config = PDEConfig(
...     dimension=2,
...     mesh_size=64,
...     backend='scipy',
...     format='csr'
... )
>>>
>>> gen = PDEMatrixGenerator('poisson', config)
>>> A = gen.generate()
>>> print(A.shape)  # (4096, 4096)

Supported Equation Types:

  • Classical: poisson, heat, wave, helmholtz, biharmonic

  • Fluid: stokes, navier_stokes, burgers, advection_diffusion

  • Solid: elasticity

  • EM: maxwell

  • Reaction: reaction_diffusion, fisher_kpp, gray_scott

  • Quantum: schrodinger, klein_gordon

__init__(equation_type: str, config: PDEConfig)[source]

Initialize PDE matrix generator

Parameters:
  • equation_type – Type of equation (‘poisson’, ‘heat’, ‘wave’, etc.)

  • config – PDE configuration

generate(n_matrices: int = 1, randomize: bool = None) Any | List[Any][source]

Generate PDE matrix/matrices

Parameters:
  • n_matrices – Number of matrices to generate

  • randomize – Whether to randomize parameters (overrides config)

Returns:

Single matrix if n_matrices=1, otherwise list of matrices

generate_batch(n_matrices: int, vary_params: List[str] = None, **param_ranges) List[Any][source]

Generate batch of matrices with varying parameters

Parameters:
  • n_matrices – Number of matrices to generate

  • vary_params – Which parameters to vary

  • **param_ranges – Parameter ranges for randomization

Returns:

List of matrices

Examples

>>> gen.generate_batch(
...     n_matrices=10,
...     vary_params=['diffusion_coeff'],
...     diffusion_coeff=(0.1, 10.0)
... )

PDEConfig

class matrix_toolkit.pde.PDEConfig(dimension: int = 2, domain: Tuple[float, ...]=(0.0, 1.0), mesh_size: int | ~typing.Tuple[int, ...]=32, mesh_type: str = 'uniform', discretization: DiscretizationType = DiscretizationType.FINITE_DIFFERENCE, stencil_order: StencilType = StencilType.SECOND_ORDER, boundary_condition: BoundaryCondition | List[BoundaryCondition] = BoundaryCondition.DIRICHLET, coefficients: Dict[str, ~typing.Any]=<factory>, random_params: bool = False, random_seed: int | None = None, param_ranges: Dict[str, ~typing.Tuple[float, float]]=<factory>, backend: str = 'scipy', format: str = 'csr', dtype: str = 'float64', include_rhs: bool = False, include_exact_solution: bool = False, normalize: bool = False)[source]

Bases: object

Configuration for PDE matrix generation

dimension: int = 2
domain: Tuple[float, ...] = (0.0, 1.0)
mesh_size: int | Tuple[int, ...] = 32
mesh_type: str = 'uniform'
discretization: DiscretizationType = 'fd'
stencil_order: StencilType = 2
boundary_condition: BoundaryCondition | List[BoundaryCondition] = 'dirichlet'
coefficients: Dict[str, Any]
random_params: bool = False
random_seed: int | None = None
param_ranges: Dict[str, Tuple[float, float]]
backend: str = 'scipy'
format: str = 'csr'
dtype: str = 'float64'
include_rhs: bool = False
include_exact_solution: bool = False
normalize: bool = False
__post_init__()[source]

Validate and process configuration

get_mesh_spacing() Tuple[float, ...][source]

Calculate mesh spacing for each dimension

total_dofs() int[source]

Calculate total degrees of freedom

__init__(dimension: int = 2, domain: Tuple[float, ...]=(0.0, 1.0), mesh_size: int | ~typing.Tuple[int, ...]=32, mesh_type: str = 'uniform', discretization: DiscretizationType = DiscretizationType.FINITE_DIFFERENCE, stencil_order: StencilType = StencilType.SECOND_ORDER, boundary_condition: BoundaryCondition | List[BoundaryCondition] = BoundaryCondition.DIRICHLET, coefficients: Dict[str, ~typing.Any]=<factory>, random_params: bool = False, random_seed: int | None = None, param_ranges: Dict[str, ~typing.Tuple[float, float]]=<factory>, backend: str = 'scipy', format: str = 'csr', dtype: str = 'float64', include_rhs: bool = False, include_exact_solution: bool = False, normalize: bool = False) None

Equation Classes

Classical PDEs

class matrix_toolkit.pde.PoissonEquation(config: PDEConfig)[source]

Bases: BasePDEEquation

The Poisson equation:

\[-\Delta u = f\]

In 1D:

\[-\]

rac{d^2 u}{dx^2} = f

In 2D:

\[-\left(\]

rac{partial^2 u}{partial x^2} + rac{partial^2 u}{partial y^2} ight) = f

In 3D:

\[-\left(\]

rac{partial^2 u}{partial x^2} + rac{partial^2 u}{partial y^2} + rac{partial^2 u}{partial z^2} ight) = f

Examples:
>>> config = PDEConfig(dimension=2, mesh_size=64)
>>> eq = PoissonEquation(config)
>>> A = eq.generate_matrix()
get_operator_name() str[source]

Get the name of the differential operator

get_default_coefficients() Dict[str, Any][source]

Get default PDE coefficients

randomize_coefficients(seed=None) Dict[str, Any][source]

Randomize diffusion coefficient

generate_matrix() spmatrix[source]

Generate Poisson matrix for configured dimension

generate_rhs(source_function=None) ndarray[source]

Generate right-hand side for Poisson equation

Parameters:

source_function – f(x) or f(x,y) or f(x,y,z)

Returns:

RHS vector

class matrix_toolkit.pde.HeatEquation(config: PDEConfig)[source]

Bases: BasePDEEquation

The heat/diffusion equation:

\[\]

rac{partial u}{partial t} = lpha abla^2 u

Time discretization using the theta-method:

  • :math:` heta = 0`: Forward Euler (explicit)

  • :math:` heta = 0.5`: Crank-Nicolson

  • :math:` heta = 1`: Backward Euler (implicit)

Examples:
>>> config = PDEConfig(
...     dimension=2,
...     mesh_size=32,
...     coefficients={'dt': 0.01, 'theta': 0.5}
... )
>>> eq = HeatEquation(config)
>>> M = eq.generate_matrix()  # System matrix
get_operator_name() str[source]

Get the name of the differential operator

get_default_coefficients() Dict[str, Any][source]

Get default PDE coefficients

generate_matrix() spmatrix[source]

Generate system matrix for heat equation

Returns matrix M such that: M u^{n+1} = RHS(u^n)

generate_rhs_matrix() spmatrix[source]

Generate RHS matrix for explicit part

class matrix_toolkit.pde.WaveEquation(config: PDEConfig)[source]

Bases: BasePDEEquation

The wave equation:

\[\]

rac{partial^2 u}{partial t^2} = c^2 abla^2 u

Discretized in time using finite differences:

\[\]

rac{u^{n+1} - 2u^n + u^{n-1}}{Delta t^2} = c^2 abla^2 u^n

Examples:
>>> config = PDEConfig(
...     dimension=2,
...     mesh_size=64,
...     coefficients={'wave_speed': 1.0, 'dt': 0.01}
... )
>>> eq = WaveEquation(config)
>>> M = eq.generate_matrix()
get_operator_name() str[source]

Get the name of the differential operator

get_default_coefficients() Dict[str, Any][source]

Get default PDE coefficients

generate_matrix() spmatrix[source]

Generate system matrix for wave equation

Returns matrix M for: M u^{n+1} = RHS(u^n, u^{n-1})

class matrix_toolkit.pde.ConvectionDiffusionEquation(config: PDEConfig)[source]

Bases: BasePDEEquation

The convection-diffusion equation:

\[-\]

arepsilon abla^2 u + mathbf{v} cdot abla u = f

Examples:
>>> config = PDEConfig(
...     dimension=2,
...     mesh_size=64,
...     coefficients={'velocity': (1.0, 0.5), 'diffusion': 0.01}
... )
>>> eq = ConvectionDiffusionEquation(config)
>>> A = eq.generate_matrix()
get_operator_name() str[source]

Get the name of the differential operator

get_default_coefficients() Dict[str, Any][source]

Get default PDE coefficients

randomize_coefficients(seed=None) Dict[str, Any][source]

Randomize coefficients with dimension-aware defaults

generate_matrix() spmatrix[source]

Generate convection-diffusion matrix

class matrix_toolkit.pde.HelmholtzEquation(config: PDEConfig)[source]

Bases: BasePDEEquation

The Helmholtz equation:

\[-\Delta u - k^2 u = f\]

This equation arises in wave propagation, acoustics, and electromagnetics.

Examples

>>> config = PDEConfig(
...     dimension=2,
...     mesh_size=64,
...     coefficients={'wavenumber': 10.0}
... )
>>> eq = HelmholtzEquation(config)
>>> A = eq.generate_matrix()
get_operator_name() str[source]

Get the name of the differential operator

get_default_coefficients() Dict[str, Any][source]

Get default PDE coefficients

generate_matrix() spmatrix[source]

Generate Helmholtz matrix

Fluid Mechanics

Solid Mechanics

Electromagnetics

Reaction-Diffusion

Quantum Mechanics

Matrix Generators

1D Generators

matrix_toolkit.pde.dim1d.generate_1d_laplacian(n: int, h: float = None, boundary: BoundaryCondition = BoundaryCondition.DIRICHLET, stencil_order: StencilType = StencilType.SECOND_ORDER) spmatrix[source]

Generate 1D Laplacian matrix: -d²u/dx²

Parameters:
  • n – Number of interior grid points

  • h – Grid spacing (default: 1/(n+1))

  • boundary – Boundary condition type

  • stencil_order – Finite difference accuracy order

Returns:

Sparse matrix in CSR format

Examples

>>> A = generate_1d_laplacian(100)
>>> A.shape
(100, 100)
matrix_toolkit.pde.dim1d.generate_1d_convection_diffusion(n: int, velocity: float = 1.0, diffusion: float = 1.0, h: float = None, boundary: BoundaryCondition = BoundaryCondition.DIRICHLET) spmatrix[source]

Generate 1D convection-diffusion matrix: -ε d²u/dx² + v du/dx

Parameters:
  • n – Number of grid points

  • velocity – Convection velocity (v)

  • diffusion – Diffusion coefficient (ε)

  • h – Grid spacing

  • boundary – Boundary condition

Returns:

Sparse CSR matrix

matrix_toolkit.pde.dim1d.generate_1d_heat(n: int, dt: float, diffusion: float = 1.0, h: float = None, theta: float = 0.5) spmatrix[source]

Generate 1D heat equation matrix: du/dt = ε d²u/dx²

Uses theta-method: implicit (θ=1), explicit (θ=0), Crank-Nicolson (θ=0.5)

Parameters:
  • n – Number of grid points

  • dt – Time step

  • diffusion – Thermal diffusivity

  • h – Spatial grid spacing

  • theta – Implicitness parameter

Returns:

M u^{n+1} = … u^n

Return type:

System matrix M for

matrix_toolkit.pde.dim1d.generate_1d_wave(n: int, dt: float, wave_speed: float = 1.0, h: float = None) spmatrix[source]

Generate 1D wave equation matrix: d²u/dt² = c² d²u/dx²

Parameters:
  • n – Number of grid points

  • dt – Time step

  • wave_speed – Wave speed c

  • h – Grid spacing

Returns:

System matrix M

matrix_toolkit.pde.dim1d.generate_1d_helmholtz(n: int, wavenumber: float, h: float = None) spmatrix[source]

Generate 1D Helmholtz matrix: -d²u/dx² - k²u

Parameters:
  • n – Number of grid points

  • wavenumber – Wave number k

  • h – Grid spacing

Returns:

Sparse CSR matrix

matrix_toolkit.pde.dim1d.generate_1d_biharmonic(n: int, h: float = None) spmatrix[source]

Generate 1D biharmonic matrix: d⁴u/dx⁴

Parameters:
  • n – Number of grid points

  • h – Grid spacing

Returns:

Sparse CSR matrix

2D Generators

matrix_toolkit.pde.dim2d.generate_2d_laplacian(nx: int, ny: int, hx: float = None, hy: float = None, boundary: BoundaryCondition = BoundaryCondition.DIRICHLET) spmatrix[source]

Generate 2D Laplacian matrix: -(∂²u/∂x² + ∂²u/∂y²)

Uses standard 5-point stencil:
1/(h²) * [-1 ]

[-1 4 -1] [ -1 ]

Parameters:
  • nx – Number of grid points in x-direction

  • ny – Number of grid points in y-direction

  • hx – Grid spacing in x (default: 1/(nx+1))

  • hy – Grid spacing in y (default: 1/(ny+1))

  • boundary – Boundary condition

Returns:

Sparse CSR matrix of size (nx*ny, nx*ny)

Examples

>>> A = generate_2d_laplacian(32, 32)
>>> A.shape
(1024, 1024)
matrix_toolkit.pde.dim2d.generate_2d_convection_diffusion(nx: int, ny: int, velocity: Tuple[float, float] = (1.0, 1.0), diffusion: float = 1.0, hx: float = None, hy: float = None, boundary: BoundaryCondition = BoundaryCondition.DIRICHLET) spmatrix[source]

Generate 2D convection-diffusion matrix: -ε(∂²u/∂x² + ∂²u/∂y²) + vx ∂u/∂x + vy ∂u/∂y

Parameters:
  • nx – Grid points in each direction

  • ny – Grid points in each direction

  • velocity – Convection velocity (vx, vy)

  • diffusion – Diffusion coefficient ε

  • hx – Grid spacings

  • hy – Grid spacings

  • boundary – Boundary condition

Returns:

Sparse CSR matrix

matrix_toolkit.pde.dim2d.generate_2d_heat(nx: int, ny: int, dt: float, diffusion: float = 1.0, hx: float = None, hy: float = None, theta: float = 0.5) spmatrix[source]

Generate 2D heat equation matrix: ∂u/∂t = ε(∂²u/∂x² + ∂²u/∂y²)

Parameters:
  • nx – Grid points

  • ny – Grid points

  • dt – Time step

  • diffusion – Thermal diffusivity

  • hx – Grid spacings

  • hy – Grid spacings

  • theta – Implicitness parameter

Returns:

System matrix M

matrix_toolkit.pde.dim2d.generate_2d_wave(nx: int, ny: int, dt: float, wave_speed: float = 1.0, hx: float = None, hy: float = None) spmatrix[source]

Generate 2D wave equation matrix: ∂²u/∂t² = c²(∂²u/∂x² + ∂²u/∂y²)

Parameters:
  • nx – Grid points

  • ny – Grid points

  • dt – Time step

  • wave_speed – Wave speed c

  • hx – Grid spacings

  • hy – Grid spacings

Returns:

System matrix M

matrix_toolkit.pde.dim2d.generate_2d_helmholtz(nx: int, ny: int, wavenumber: float, hx: float = None, hy: float = None) spmatrix[source]

Generate 2D Helmholtz matrix: -Δu - k²u

Parameters:
  • nx – Grid points

  • ny – Grid points

  • wavenumber – Wave number k

  • hx – Grid spacings

  • hy – Grid spacings

Returns:

Sparse CSR matrix

matrix_toolkit.pde.dim2d.generate_2d_biharmonic(nx: int, ny: int, hx: float = None, hy: float = None) spmatrix[source]

Generate 2D biharmonic matrix: Δ²u = ΔΔu

Parameters:
  • nx – Grid points

  • ny – Grid points

  • hx – Grid spacings

  • hy – Grid spacings

Returns:

Sparse CSR matrix

3D Generators

matrix_toolkit.pde.dim3d.generate_3d_laplacian(nx: int, ny: int, nz: int, hx: float = None, hy: float = None, hz: float = None, boundary: BoundaryCondition = BoundaryCondition.DIRICHLET) spmatrix[source]

Generate 3D Laplacian matrix: -(∂²u/∂x² + ∂²u/∂y² + ∂²u/∂z²)

Uses standard 7-point stencil.

Parameters:
  • nx – Grid points in each direction

  • ny – Grid points in each direction

  • nz – Grid points in each direction

  • hx – Grid spacings

  • hy – Grid spacings

  • hz – Grid spacings

  • boundary – Boundary condition

Returns:

Sparse CSR matrix of size (nx*ny*nz, nx*ny*nz)

Examples

>>> A = generate_3d_laplacian(16, 16, 16)
>>> A.shape
(4096, 4096)
>>> A.nnz  # 7-point stencil
28672
matrix_toolkit.pde.dim3d.generate_3d_convection_diffusion(nx: int, ny: int, nz: int, velocity: Tuple[float, float, float] = (1.0, 1.0, 1.0), diffusion: float = 1.0, hx: float = None, hy: float = None, hz: float = None) spmatrix[source]

Generate 3D convection-diffusion matrix

-ε∇²u + v·∇u

Parameters:
  • nx – Grid points

  • ny – Grid points

  • nz – Grid points

  • velocity – Convection velocity (vx, vy, vz)

  • diffusion – Diffusion coefficient

  • hx – Grid spacings

  • hy – Grid spacings

  • hz – Grid spacings

Returns:

Sparse CSR matrix

matrix_toolkit.pde.dim3d.generate_3d_heat(nx: int, ny: int, nz: int, dt: float, diffusion: float = 1.0, hx: float = None, hy: float = None, hz: float = None, theta: float = 0.5) spmatrix[source]

Generate 3D heat equation matrix: ∂u/∂t = ε∇²u

Parameters:
  • nx – Grid points

  • ny – Grid points

  • nz – Grid points

  • dt – Time step

  • diffusion – Thermal diffusivity

  • hx – Grid spacings

  • hy – Grid spacings

  • hz – Grid spacings

  • theta – Implicitness parameter

Returns:

System matrix M

matrix_toolkit.pde.dim3d.generate_3d_wave(nx: int, ny: int, nz: int, dt: float, wave_speed: float = 1.0, hx: float = None, hy: float = None, hz: float = None) spmatrix[source]

Generate 3D wave equation matrix: ∂²u/∂t² = c²∇²u

Parameters:
  • nx – Grid points

  • ny – Grid points

  • nz – Grid points

  • dt – Time step

  • wave_speed – Wave speed c

  • hx – Grid spacings

  • hy – Grid spacings

  • hz – Grid spacings

Returns:

System matrix M

matrix_toolkit.pde.dim3d.generate_3d_helmholtz(nx: int, ny: int, nz: int, wavenumber: float, hx: float = None, hy: float = None, hz: float = None) spmatrix[source]

Generate 3D Helmholtz matrix: -∇²u - k²u

Parameters:
  • nx – Grid points

  • ny – Grid points

  • nz – Grid points

  • wavenumber – Wave number k

  • hx – Grid spacings

  • hy – Grid spacings

  • hz – Grid spacings

Returns:

Sparse CSR matrix

matrix_toolkit.pde.dim3d.generate_3d_biharmonic(nx: int, ny: int, nz: int, hx: float = None, hy: float = None, hz: float = None) spmatrix[source]

Generate 3D biharmonic matrix: ∇⁴u = ∇²∇²u

Parameters:
  • nx – Grid points

  • ny – Grid points

  • nz – Grid points

  • hx – Grid spacings

  • hy – Grid spacings

  • hz – Grid spacings

Returns:

Sparse CSR matrix

Random Parameter Generation

RandomParameterGenerator

class matrix_toolkit.pde.random_params.RandomParameterGenerator[source]

Bases: object

Generate random parameters for PDE problems

Examples

>>> gen = RandomParameterGenerator()
>>> gen.add_parameter('diffusion', 'uniform', low=0.1, high=10.0)
>>> gen.add_parameter('velocity', 'normal', mean=1.0, std=0.5)
>>> params = gen.sample(n=100)
__init__()[source]
add_parameter(name: str, distribution: str = 'uniform', **dist_params)[source]

Add a parameter to sample

Parameters:
  • name – Parameter name

  • distribution – Distribution type

  • **dist_params – Distribution parameters

sample(n: int = 1, seed: int | None = None) List[Dict[str, float]][source]

Sample n parameter sets

Parameters:
  • n – Number of samples

  • seed – Random seed

Returns:

List of parameter dictionaries

LatinHypercubeSampler

class matrix_toolkit.pde.random_params.LatinHypercubeSampler[source]

Bases: object

Latin Hypercube Sampling for better space coverage

Examples

>>> sampler = LatinHypercubeSampler()
>>> sampler.add_parameter('diffusion', low=0.1, high=10.0)
>>> sampler.add_parameter('velocity', low=-1.0, high=1.0)
>>> samples = sampler.sample(n=50)
__init__()[source]
add_parameter(name: str, low: float, high: float)[source]

Add parameter with range

sample(n: int, seed: int | None = None) List[Dict[str, float]][source]

Generate Latin Hypercube samples

Parameters:
  • n – Number of samples

  • seed – Random seed

Returns:

List of parameter dictionaries

ParameterDistribution

class matrix_toolkit.pde.random_params.ParameterDistribution(name: str, distribution: str = 'uniform', params: Dict = None)[source]

Bases: object

Parameter distribution specification

name: str
distribution: str = 'uniform'
params: Dict = None
sample(seed: int | None = None) float[source]

Sample from distribution

__init__(name: str, distribution: str = 'uniform', params: Dict = None) None

Enumerations

BoundaryCondition

class matrix_toolkit.pde.config.BoundaryCondition(value)[source]

Boundary condition types

Available boundary conditions:

  • DIRICHLET: u = 0 on boundary

  • NEUMANN: ∂u/∂n = 0 on boundary

  • PERIODIC: Periodic boundaries

  • ROBIN: αu + β∂u/∂n = 0

  • MIXED: Different conditions on different boundaries

DIRICHLET = 'dirichlet'
NEUMANN = 'neumann'
PERIODIC = 'periodic'
ROBIN = 'robin'
MIXED = 'mixed'

DiscretizationType

class matrix_toolkit.pde.config.DiscretizationType(value)[source]

Discretization method types

  • FINITE_DIFFERENCE: Finite difference method

  • FINITE_ELEMENT: Finite element method (basic)

  • FINITE_VOLUME: Finite volume method

FINITE_DIFFERENCE = 'fd'
FINITE_ELEMENT = 'fe'
FINITE_VOLUME = 'fv'

StencilType

class matrix_toolkit.pde.config.StencilType(value)[source]

Finite difference stencil types

  • SECOND_ORDER: O(h²) accurate

  • FOURTH_ORDER: O(h⁴) accurate

  • SIXTH_ORDER: O(h⁶) accurate

SECOND_ORDER = 2
FOURTH_ORDER = 4
SIXTH_ORDER = 6

Quick Reference Table

PDE Equation Summary

Equation

String ID

Dimensions

Key Coefficients

Poisson

'poisson'

1D, 2D, 3D

diffusion

Heat

'heat'

1D, 2D, 3D

diffusion, dt, theta

Wave

'wave'

1D, 2D, 3D

wave_speed, dt

Helmholtz

'helmholtz'

1D, 2D, 3D

wavenumber

Stokes

'stokes'

2D, 3D

viscosity

Navier-Stokes

'navier_stokes'

2D, 3D

viscosity, dt, velocity_x0

Burgers

'burgers'

1D

viscosity, dt, u0

Elasticity

'elasticity'

2D, 3D

youngs_modulus, poisson_ratio

Maxwell

'maxwell'

3D

frequency, permittivity

Schrödinger

'schrodinger'

1D, 2D, 3D

hbar, mass, potential

Klein-Gordon

'klein_gordon'

1D, 2D, 3D

mass, wave_speed

Usage Examples

Basic Usage

from matrix_toolkit.pde import PDEMatrixGenerator, PDEConfig

# Simple Poisson
config = PDEConfig(dimension=2, mesh_size=64)
gen = PDEMatrixGenerator('poisson', config)
A = gen.generate()

With Parameters

# Navier-Stokes with parameters
config = PDEConfig(
    dimension=2,
    mesh_size=64,
    coefficients={
        'viscosity': 0.01,
        'dt': 0.01,
        'velocity_x0': 1.0,
        'velocity_y0': 0.0
    }
)
gen = PDEMatrixGenerator('navier_stokes', config)
A = gen.generate()

Batch Generation

# Generate 100 matrices with random parameters
config = PDEConfig(
    dimension=2,
    mesh_size=32,
    random_params=True,
    param_ranges={'viscosity': (0.001, 0.1)}
)

gen = PDEMatrixGenerator('stokes', config)
matrices = gen.generate(n_matrices=100)

See Also

  • PDE Matrix Generation - User guide

  • ../examples/pde_examples - Examples

  • ../tutorials/pde_tutorial - Tutorial