diff --git a/examples/example_10_problems.py b/examples/example_10_problems.py new file mode 100644 index 0000000..db2e4af --- /dev/null +++ b/examples/example_10_problems.py @@ -0,0 +1,363 @@ +#!/usr/bin/env python3 +""" +10 real-world problems currently solved by numerical methods (Runge-Kutta, +finite differences, etc.), solved here via Remizov's Chernoff formula. + +Each problem is formulated as a PDE evolution: + du/dt = a(x)·u_xx + b(x)·u_x + c(x)·u + +Chernoff solution is compared with scipy.integrate.solve_ivp using +the Method of Lines (MOL) — the standard numerical approach. + +Verification: relative L² error on interior grid points. +""" + +import time + +import numpy as np +from scipy.integrate import solve_ivp + +from remizov_net.core import ChernoffStep, ODECoefficients + +# --------------------------------------------------------------------------- +# Helpers +# --------------------------------------------------------------------------- + +N = 201 # grid points +X_MIN, X_MAX = -5.0, 5.0 + + +def make_grid(): + x = np.linspace(X_MIN, X_MAX, N) + dx = x[1] - x[0] + return x, dx + + +def chernoff_evolve(coeffs, x, g, total_time, n_steps=80): + """Solve via Chernoff approximation (Remizov's formula).""" + step = ChernoffStep(coeffs, x) + tau = total_time / n_steps + y = g.copy() + for _ in range(n_steps): + y = step.apply(y, tau, use_fft=True) + return y + + +def scipy_mol_evolve(a_arr, b_arr, c_arr, dx, g, total_time): + """Solve via Method of Lines + scipy RK45 (standard approach). + + Discretizes: du/dt = a(x)·u_xx + b(x)·u_x + c(x)·u + using second-order finite differences, then integrates with solve_ivp. + """ + n = len(g) + + def rhs(t, u): # noqa: ARG001 + dudt = np.zeros(n) + # Interior: central differences + for i in range(1, n - 1): + u_xx = (u[i + 1] - 2 * u[i] + u[i - 1]) / dx**2 + u_x = (u[i + 1] - u[i - 1]) / (2 * dx) + dudt[i] = a_arr[i] * u_xx + b_arr[i] * u_x + c_arr[i] * u[i] + # Boundary: zero (Dirichlet) + dudt[0] = 0.0 + dudt[-1] = 0.0 + return dudt + + sol = solve_ivp(rhs, [0, total_time], g, method="RK45", + rtol=1e-8, atol=1e-10, max_step=total_time / 20) + return sol.y[:, -1] + + +def compare(name, desc, coeffs, g, total_time, x, dx): + """Run both methods, compare, print result.""" + a_arr = coeffs.eval_a(x) + b_arr = coeffs.eval_b(x) + c_arr = coeffs.eval_c(x) + + t0 = time.perf_counter() + y_chernoff = chernoff_evolve(coeffs, x, g, total_time) + t_chernoff = time.perf_counter() - t0 + + t0 = time.perf_counter() + y_scipy = scipy_mol_evolve(a_arr, b_arr, c_arr, dx, g, total_time) + t_scipy = time.perf_counter() - t0 + + # Error on interior (skip 15% boundary on each side) + margin = N // 7 + s = slice(margin, N - margin) + denom = np.sqrt(np.mean(y_scipy[s] ** 2)) + if denom < 1e-12: + denom = 1.0 + rel_err = np.sqrt(np.mean((y_chernoff[s] - y_scipy[s]) ** 2)) / denom + + return { + "name": name, + "desc": desc, + "rel_err": rel_err, + "t_chernoff": t_chernoff, + "t_scipy": t_scipy, + "y_chernoff_mid": y_chernoff[N // 2], + "y_scipy_mid": y_scipy[N // 2], + } + + +# --------------------------------------------------------------------------- +# 10 problems +# --------------------------------------------------------------------------- + +def problem_1(x, dx): + """Pure heat equation — thermal diffusion in a metal rod.""" + coeffs = ODECoefficients(a=1.0, b=0.0, c=0.0) + g = np.exp(-x**2) + return compare( + "Heat equation", + "du/dt = u_xx (thermal diffusion)", + coeffs, g, total_time=0.5, x=x, dx=dx, + ) + + +def problem_2(x, dx): + """Variable thermal conductivity — real materials (ceramic, composites).""" + coeffs = ODECoefficients( + a=lambda x: 1.0 + 0.5 * np.sin(x), + b=0.0, + c=0.0, + ) + g = np.exp(-x**2) + return compare( + "Variable conductivity", + "du/dt = (1+0.5sin(x))·u_xx (composite material)", + coeffs, g, total_time=0.3, x=x, dx=dx, + ) + + +def problem_3(x, dx): + """Advection-diffusion — pollution transport in a river. + + Diffusion (spreading) + advection (flow carries downstream). + Standard in environmental modeling. Currently solved by FEM/FDM. + """ + coeffs = ODECoefficients(a=0.5, b=1.0, c=0.0) + g = np.exp(-2 * x**2) + return compare( + "Advection-diffusion", + "du/dt = 0.5·u_xx + 1.0·u_x (river pollution)", + coeffs, g, total_time=0.3, x=x, dx=dx, + ) + + +def problem_4(x, dx): + """Fokker-Planck / Ornstein-Uhlenbeck — financial modeling. + + Describes probability distribution of a mean-reverting process. + Used in option pricing and interest rate models. + Currently solved by Crank-Nicolson or Monte Carlo. + """ + theta = 1.0 # mean-reversion speed + sigma = 1.0 # volatility + coeffs = ODECoefficients( + a=0.5 * sigma**2, + b=lambda x: -theta * x, # drift toward zero + c=theta, # normalization correction + ) + g = np.exp(-x**2) # initial distribution + return compare( + "Ornstein-Uhlenbeck", + "du/dt = 0.5·u_xx - x·u_x + u (finance, mean-reversion)", + coeffs, g, total_time=0.3, x=x, dx=dx, + ) + + +def problem_5(x, dx): + """Damped diffusion — vibration damping in engineering. + + Heat-like spread + exponential decay. Models energy dissipation + in materials. Currently solved by FEM packages (COMSOL, ANSYS). + """ + coeffs = ODECoefficients(a=1.0, b=0.0, c=-0.5) + g = np.exp(-x**2) + return compare( + "Damped diffusion", + "du/dt = u_xx - 0.5·u (energy dissipation)", + coeffs, g, total_time=0.5, x=x, dx=dx, + ) + + +def problem_6(x, dx): + """Quantum potential well — Schrodinger-like evolution. + + Harmonic potential V(x) = -x². Describes bound states + in quantum mechanics. Currently solved by split-step methods. + (Real-valued version — imaginary time propagation.) + """ + coeffs = ODECoefficients( + a=0.5, + b=0.0, + c=lambda x: -0.5 * x**2, # harmonic potential + ) + g = np.exp(-x**2) + return compare( + "Quantum potential well", + "du/dt = 0.5·u_xx - 0.5x²·u (harmonic oscillator)", + coeffs, g, total_time=0.2, x=x, dx=dx, + ) + + +def problem_7(x, dx): + """Periodic potential (Mathieu-like) — crystal lattice / parametric resonance. + + Periodic c(x) creates band structure. Describes electrons in + crystals, ion traps, parametric oscillators. + Currently solved by Floquet/Hill methods or specialized codes. + """ + coeffs = ODECoefficients( + a=1.0, + b=0.0, + c=lambda x: -1.0 + 0.5 * np.cos(2 * x), # periodic potential + ) + g = np.exp(-x**2) + return compare( + "Periodic potential (Mathieu)", + "du/dt = u_xx + (-1+0.5cos(2x))·u (crystal lattice)", + coeffs, g, total_time=0.3, x=x, dx=dx, + ) + + +def problem_8(x, dx): + """Exponentially varying medium — sound in atmosphere. + + Air density decreases exponentially with altitude. + a(x) = e^(-0.3x) models variable propagation speed. + Currently solved by WKB approximation or ray tracing. + """ + coeffs = ODECoefficients( + a=lambda x: np.exp(-0.3 * x), + b=0.0, + c=0.0, + ) + g = np.exp(-2 * x**2) + return compare( + "Exponential medium", + "du/dt = e^(-0.3x)·u_xx (atmospheric acoustics)", + coeffs, g, total_time=0.2, x=x, dx=dx, + ) + + +def problem_9(x, dx): + """Drift-diffusion with position-dependent mobility — semiconductor physics. + + Models charge carrier transport in semiconductors. + a=const (diffusion), b(x) = electric field (position-dependent). + Currently solved by Scharfetter-Gummel or TCAD simulators. + """ + coeffs = ODECoefficients( + a=0.5, + b=lambda x: -0.5 * np.tanh(x), # built-in electric field + c=0.0, + ) + g = np.exp(-x**2) + return compare( + "Semiconductor drift-diffusion", + "du/dt = 0.5·u_xx - 0.5tanh(x)·u_x (carrier transport)", + coeffs, g, total_time=0.3, x=x, dx=dx, + ) + + +def problem_10(x, dx): + """Reaction-diffusion with localized source — chemical reactor. + + Diffusion + spatially varying reaction rate. + Models catalyst pellets where reaction rate depends on position. + Currently solved by COMSOL or custom FEM codes. + """ + coeffs = ODECoefficients( + a=1.0, + b=0.0, + c=lambda x: -0.3 * np.exp(-x**2), # localized reaction sink + ) + g = np.exp(-0.5 * x**2) + 0.5 * np.exp(-2 * (x - 1) ** 2) + return compare( + "Reaction-diffusion", + "du/dt = u_xx - 0.3·e^(-x²)·u (chemical reactor)", + coeffs, g, total_time=0.3, x=x, dx=dx, + ) + + +# --------------------------------------------------------------------------- +# Main +# --------------------------------------------------------------------------- + +def main(): + x, dx = make_grid() + + problems = [ + problem_1, problem_2, problem_3, problem_4, problem_5, + problem_6, problem_7, problem_8, problem_9, problem_10, + ] + + print("=" * 78) + print(" 10 Real-World Problems: Chernoff (Remizov) vs scipy MOL (Runge-Kutta)") + print("=" * 78) + + results = [] + for i, prob_fn in enumerate(problems, 1): + r = prob_fn(x, dx) + results.append(r) + status = "OK" if r["rel_err"] < 0.05 else "WARN" if r["rel_err"] < 0.15 else "FAIL" + print(f"\n [{i:>2}] {r['name']}") + print(f" {r['desc']}") + print(f" u(0): Chernoff={r['y_chernoff_mid']:.6f} " + f"scipy={r['y_scipy_mid']:.6f}") + print(f" Rel L² error: {r['rel_err']:.2e} [{status}]") + print(f" Time: Chernoff={r['t_chernoff']:.3f}s " + f"scipy={r['t_scipy']:.3f}s") + + # --- Summary table --- + print(f"\n{'=' * 78}") + print(" SUMMARY") + print(f"{'=' * 78}") + print(f"\n {'#':>3} {'Problem':<30} {'Rel Error':>10} {'Status':>8} " + f"{'Chernoff':>9} {'scipy':>9}") + print(f" {'-' * 73}") + + passed = 0 + for i, r in enumerate(results, 1): + status = "OK" if r["rel_err"] < 0.05 else "~" if r["rel_err"] < 0.15 else "FAIL" + if r["rel_err"] < 0.15: + passed += 1 + print(f" {i:>3} {r['name']:<30} {r['rel_err']:>10.2e} {status:>8} " + f"{r['t_chernoff']:>8.3f}s {r['t_scipy']:>8.3f}s") + + print(f"\n Passed: {passed}/{len(results)}") + + total_ch = sum(r["t_chernoff"] for r in results) + total_sc = sum(r["t_scipy"] for r in results) + print(f" Total time: Chernoff={total_ch:.2f}s scipy={total_sc:.2f}s") + + # --- What's different --- + print(f""" + {'=' * 78} + WHAT THIS DEMONSTRATES + {'=' * 78} + + Standard approach (scipy column): + - Discretize derivatives with finite differences + - Feed the resulting ODE system to Runge-Kutta (RK45) + - Adaptive step control, error estimation + + Remizov/Chernoff approach (Chernoff column): + - No finite differences — uses Gaussian convolution instead + - No ODE solver — just iterate S₃·S₂ n times + - Analytically motivated: converges to exact semigroup + + Key differences: + 1. Chernoff doesn't need spatial derivative discretization + 2. Chernoff is trivially parallelizable (FFT-based) + 3. Chernoff works with VARIABLE coefficients a(x), b(x), c(x) + without any special treatment — same algorithm for all 10 problems + 4. Chernoff steps are differentiable → can plug into PyTorch +""") + + +if __name__ == "__main__": + main() diff --git a/src/remizov_net/core.py b/src/remizov_net/core.py index 1e5ec3b..33b974c 100644 --- a/src/remizov_net/core.py +++ b/src/remizov_net/core.py @@ -109,9 +109,12 @@ class ChernoffStep: def apply_s2_fft(self, f: NDArray[np.float64], tau: float) -> NDArray[np.float64]: """Apply S₂(τ) using FFT for O(N log N) performance. - Approximation: treat a(x) and b(x) as locally constant, - use the average value for a global convolution kernel, - then apply pointwise drift correction. + Splits S₂ into three sub-steps: + 1. Advection: shift f by b(x)·τ via interpolation (handles variable b) + 2. Diffusion: Gaussian convolution via FFT (uses mean a) + 3. Completion factor: exp(b(x)²τ/(4a(x))) from completing the square + + This is exact for constant coefficients and O(N log N) for variable. """ a_mean = np.mean(self.a_vals) sigma2 = 4.0 * tau * a_mean @@ -119,21 +122,19 @@ class ChernoffStep: if sigma2 <= 1e-15: return f.copy() - # Gaussian kernel in Fourier space + # Step 1: Advection — shift f(x) → f(x + b(x)·τ) + # Each point shifts by its local drift amount + x_shifted = self.x + self.b_vals * tau + f_shifted = np.interp(x_shifted, self.x, f, left=0.0, right=0.0) + + # Step 2: Diffusion — Gaussian convolution via FFT k = np.fft.fftfreq(self.n_points, d=self.dx) gauss_ft = np.exp(-sigma2 * (np.pi * k) ** 2) - - # Convolve - f_ft = np.fft.fft(f) + f_ft = np.fft.fft(f_shifted) result = np.real(np.fft.ifft(f_ft * gauss_ft)) - # Pointwise drift correction - # This corrects for the b(x) term that FFT can't handle globally - drift_correction = np.exp( - -self.b_vals**2 * tau / (4.0 * self.a_vals) - + self.b_vals**2 * tau / (4.0 * a_mean) - ) - result *= drift_correction + # Step 3: Completion-of-square factor: exp(b(x)²τ/(4a(x))) + result *= np.exp(self.b_vals**2 * tau / (4.0 * self.a_vals)) return result