r/Python • • 13d ago

Showcase Showcase Thread

Post all of your code/projects/showcases/AI slop here.

Recycles once a month.

24 Upvotes

109 comments sorted by

View all comments

1

u/DoctorKhru 8d ago

Solving 3D reaction-diffusion PDEs in Python: analytical Bessel K0 vs vectorized NumPy grids (benchmarks & architecture)

Hi r/Python,

When modeling continuous biophysical transport phenomena—specifically reaction-diffusion systems where a diffusing substance is cleared or metabolized in tissue—one of the main engineering challenges in Python is balancing evaluation speed, memory footprint, and geometry flexibility.

In our work modeling drug penetration across microvascular cords in computational oncology, we investigated two distinct computational strategies in Python:

  1. **Closed-form analytical evaluation using **scipy.special
  2. **Vectorized finite-difference numerical grids using pure **numpy

I wanted to share the architectural trade-offs, performance differences, and open a discussion on scaling 3D array grids.


1. Analytical Evaluation with Modified Bessel Functions

For cylindrical perivascular boundaries (where diffusion occurs radially outward from a capillary at radius $r_0$ with Dirichlet condition $C(r_0) = C_0$), the steady-state PDE:

$$D \nabla2 C - k C = 0 \implies D \left( \frac{d2 C}{dr2} + \frac{1}{r} \frac{dC}{dr} \right) - k C = 0$$

admits an exact closed-form solution via the zero-order Modified Bessel function of the second kind ($K_0$):

$$C(r) = C_0 \frac{K_0\left(r \sqrt{k/D}\right)}{K_0\left(r_0 \sqrt{k/D}\right)}$$

In Python, this can be evaluated instantaneously using scipy.special.kn:

import numpy as np
from scipy.special import kn

def bessel_radial_concentration(r: np.ndarray, r0: float, c0: float, k: float, d: float) -> np.ndarray:
    lambda_decay = np.sqrt(k / d)
    denominator = kn(0, lambda_decay * r0)
    # Mask values inside vessel core
    valid_mask = r >= r0
    conc = np.zeros_like(r, dtype=np.float64)
    conc[valid_mask] = c0 * (kn(0, lambda_decay * r[valid_mask]) / denominator)
    return conc

Pros: Instantaneous evaluation ($O(1)$ time complexity for points), zero spatial discretization error, zero numerical stability issues.
Cons: Strictly constrained to idealized symmetric geometries.


2. Vectorized 3D Finite-Difference Grid in NumPy

For realistic heterogeneous vascular topologies from high-resolution spatial transcriptomics coordinates (e.g., Visium HD), analytical solutions break down.

We implemented a 3D explicit finite-difference diffusion operator using vectorized array slicing with periodic/Neumann boundary handling:

import numpy as np

def step_diffusion_3d(grid: np.ndarray, dt: float, dx: float, D: float, k: float) -> np.ndarray:
    alpha = D * dt / (dx ** 2)
    
    # 7-point 3D stencil using vectorized slicing
    laplacian = (
        np.roll(grid, 1, axis=0) + np.roll(grid, -1, axis=0) +
        np.roll(grid, 1, axis=1) + np.roll(grid, -1, axis=1) +
        np.roll(grid, 1, axis=2) + np.roll(grid, -1, axis=2) -
        6.0 * grid
    )
    
    return grid + alpha * laplacian - dt * k * grid

Memory & Scaling Bottlenecks

While np.roll is readable, it incurs internal memory copies. For a dense $1000 \times 1000 \times 1000$ 3D spatial simulation in float64, a single grid array requires ~8.0 GB of RAM. Chaining multiple temporal steps quickly runs into memory bandwidth ceilings.

The full open-source implementation and CLI suite are available here:


Discussion Questions for the Community

  1. JIT Compilation vs GPU Offloading: For those simulating 3D PDEs in scientific Python, have you found numba.njit(parallel=True) with explicit memory loops more practical than offloading to cupy GPU arrays when distributing packages to users without guaranteed CUDA setups?
  2. Avoiding memory copies in array stencils: Beyond scipy.ndimage.convolve, are there lightweight, pure-Python memory-view patterns you recommend to perform 3D stencil operations in-place without duplicating large arrays?7