mathhook_core/calculus/pde/educational/
message_registry.rs

1//! PDE-specific educational messages
2//!
3//! This module provides educational messages for partial differential equation concepts,
4//! following the pattern established in the ODE module.
5
6use once_cell::sync::Lazy;
7use std::collections::HashMap;
8
9/// PDE-specific message keys
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
11pub enum PdeMessageKey {
12    // General PDE concepts
13    WhatIsPde,
14    PdeVsOde,
15    PdeClassification,
16
17    // PDE types
18    EllipticEquation,
19    ParabolicEquation,
20    HyperbolicEquation,
21
22    // Standard PDEs
23    HeatEquation,
24    WaveEquation,
25    LaplaceEquation,
26    PoissonEquation,
27
28    // Solution methods
29    SeparationOfVariables,
30    MethodOfCharacteristics,
31    FourierSeries,
32    GreensFunctions,
33
34    // Boundary conditions
35    DirichletCondition,
36    NeumannCondition,
37    RobinCondition,
38    PeriodicCondition,
39
40    // Initial conditions
41    InitialValueProblem,
42    InitialBoundaryValueProblem,
43
44    // Numerical methods
45    FiniteDifference,
46    FiniteElement,
47    SpectralMethods,
48}
49
50/// Global PDE message registry
51pub static PDE_MESSAGE_REGISTRY: Lazy<HashMap<PdeMessageKey, &'static str>> = Lazy::new(|| {
52    let mut messages = HashMap::new();
53
54    // General PDE concepts
55    messages.insert(
56        PdeMessageKey::WhatIsPde,
57        "A **Partial Differential Equation (PDE)** is an equation that relates a function of several variables to its partial derivatives. \
58        PDEs describe phenomena involving multiple independent variables, such as heat distribution over time and space, \
59        wave propagation, or electromagnetic fields. The solution to a PDE is a function (or family of functions) \
60        that satisfies the equation and given boundary/initial conditions."
61    );
62
63    messages.insert(
64        PdeMessageKey::PdeVsOde,
65        "**PDEs vs ODEs**: While Ordinary Differential Equations (ODEs) involve functions of a single variable and their derivatives, \
66        PDEs involve functions of multiple variables and their partial derivatives. For example, y'(t) = f(t,y) is an ODE \
67        (one variable t), while ∂u/∂t = α∂²u/∂x² is a PDE (two variables t and x). PDEs are generally more complex to solve \
68        and often require specialized techniques based on their type and boundary conditions."
69    );
70
71    messages.insert(
72        PdeMessageKey::PdeClassification,
73        "**PDE Classification**: Second-order linear PDEs are classified based on the discriminant B² - 4AC: \
74        **Elliptic** (B² - 4AC < 0): Steady-state problems like Laplace's equation. \
75        **Parabolic** (B² - 4AC = 0): Diffusion processes like the heat equation. \
76        **Hyperbolic** (B² - 4AC > 0): Wave propagation like the wave equation. \
77        This classification determines solution behavior and appropriate numerical methods."
78    );
79
80    // PDE types
81    messages.insert(
82        PdeMessageKey::EllipticEquation,
83        "**Elliptic PDEs** describe steady-state phenomena where time is not a factor. The Laplace equation ∇²u = 0 \
84        is the prototype, modeling equilibrium states in physics. Solutions are smooth and determined entirely by \
85        boundary conditions. Examples include electrostatic potential, steady heat distribution, and incompressible \
86        fluid flow. Numerical methods like finite elements work well for elliptic problems."
87    );
88
89    messages.insert(
90        PdeMessageKey::ParabolicEquation,
91        "**Parabolic PDEs** model diffusion and dissipative processes that evolve toward equilibrium. The heat equation \
92        ∂u/∂t = α∇²u is the classic example, describing how temperature spreads through a material. Solutions smooth out \
93        discontinuities over time and exhibit infinite speed of propagation (disturbances affect the entire domain instantly, \
94        though with exponentially decreasing magnitude). Require initial conditions and boundary conditions."
95    );
96
97    messages.insert(
98        PdeMessageKey::HyperbolicEquation,
99        "**Hyperbolic PDEs** describe wave propagation and vibrations with finite speed. The wave equation ∂²u/∂t² = c²∇²u \
100        is the prototype, modeling sound waves, electromagnetic waves, and vibrating strings. Solutions preserve discontinuities \
101        along characteristics (paths of information propagation). D'Alembert's solution shows waves traveling at speed c. \
102        Require initial position and velocity, plus boundary conditions."
103    );
104
105    // Standard PDEs
106    messages.insert(
107        PdeMessageKey::HeatEquation,
108        "The **Heat Equation** ∂u/∂t = α∇²u models heat diffusion in materials. Here u(x,t) is temperature, \
109        α is thermal diffusivity. Heat flows from hot to cold regions, smoothing out temperature differences. \
110        Solutions can be found using separation of variables: u(x,t) = X(x)T(t), leading to Fourier series. \
111        The fundamental solution (Green's function) is a Gaussian that spreads over time, showing how point \
112        sources of heat diffuse."
113    );
114
115    messages.insert(
116        PdeMessageKey::WaveEquation,
117        "The **Wave Equation** ∂²u/∂t² = c²∇²u describes wave propagation at speed c. Solutions include \
118        traveling waves u = f(x - ct) + g(x + ct) (d'Alembert's formula in 1D). Energy is conserved and \
119        waves maintain their shape while traveling. Separation of variables gives standing wave solutions \
120        u(x,t) = sin(nπx/L)cos(nπct/L), representing harmonics of a vibrating string. The wave equation \
121        appears in acoustics, electromagnetics, and quantum mechanics."
122    );
123
124    messages.insert(
125        PdeMessageKey::LaplaceEquation,
126        "**Laplace's Equation** ∇²u = 0 describes equilibrium states in physics. Solutions (harmonic functions) \
127        have remarkable properties: they satisfy the maximum principle (extrema occur on boundaries), \
128        mean value property (value at a point equals average over any surrounding sphere), and are \
129        infinitely differentiable. Applications include electrostatics (potential), steady heat flow, \
130        incompressible fluid flow, and minimal surfaces. Solved using separation of variables, conformal \
131        mapping, or Green's functions."
132    );
133
134    messages.insert(
135        PdeMessageKey::PoissonEquation,
136        "**Poisson's Equation** ∇²u = f is the inhomogeneous version of Laplace's equation, where f \
137        represents sources or sinks. In electrostatics, f is charge density and u is potential. \
138        Solutions combine the particular solution (accounting for sources) with homogeneous solutions \
139        (satisfying boundary conditions). Green's functions provide explicit integral representations. \
140        The equation appears in gravity (f is mass density), electromagnetism, and fluid mechanics."
141    );
142
143    // Solution methods
144    messages.insert(
145        PdeMessageKey::SeparationOfVariables,
146        "**Separation of Variables** assumes the solution can be written as a product of single-variable functions: \
147        u(x,t) = X(x)T(t). Substituting into the PDE and dividing yields separate ODEs for each function. \
148        This works when the PDE and boundary conditions are separable. The method produces eigenvalue problems \
149        whose solutions form a complete basis (often trigonometric or special functions). The general solution \
150        is a superposition (Fourier series) of these eigenfunctions."
151    );
152
153    messages.insert(
154        PdeMessageKey::MethodOfCharacteristics,
155        "The **Method of Characteristics** solves first-order PDEs by finding curves (characteristics) along which \
156        the PDE becomes an ODE. For the equation a∂u/∂x + b∂u/∂y = c, characteristics satisfy dx/a = dy/b = du/c. \
157        The solution is constant along characteristics for homogeneous equations. This method extends to systems \
158        and higher-order hyperbolic equations, revealing how information propagates through the domain. \
159        Wave fronts and shock waves follow characteristics."
160    );
161
162    messages.insert(
163        PdeMessageKey::FourierSeries,
164        "**Fourier Series** represent periodic functions as infinite sums of sines and cosines. In PDE solutions, \
165        they arise naturally from separation of variables with periodic boundary conditions. For a function on [0,L], \
166        f(x) = a₀/2 + Σ(aₙcos(nπx/L) + bₙsin(nπx/L)). Coefficients are found by orthogonality: \
167        aₙ = (2/L)∫f(x)cos(nπx/L)dx. Fourier series converge to the function (in L² sense) and provide \
168        spectral decomposition, showing which frequencies are present."
169    );
170
171    messages.insert(
172        PdeMessageKey::GreensFunctions,
173        "**Green's Functions** G(x,x';t,t') represent the response at (x,t) to a unit impulse at (x',t'). \
174        They convert PDEs into integral equations: u(x,t) = ∫G(x,x';t,0)f(x')dx' for initial value f. \
175        Green's functions satisfy the PDE with a delta function source and appropriate boundary conditions. \
176        They embody the superposition principle: the solution for any source is the integral of point source \
177        solutions. Finding Green's functions is often difficult but provides complete solution formulas."
178    );
179
180    // Boundary conditions
181    messages.insert(
182        PdeMessageKey::DirichletCondition,
183        "**Dirichlet Boundary Conditions** specify the value of the solution on the boundary: u|∂Ω = g. \
184        Physically, this fixes temperature (heat equation), displacement (wave equation), or potential \
185        (Laplace equation) at boundaries. For uniqueness, Dirichlet conditions completely determine \
186        elliptic and parabolic solutions. In separation of variables, they determine the eigenvalues \
187        and eigenfunctions. Example: u(0,t) = 0, u(L,t) = 0 for a string fixed at both ends."
188    );
189
190    messages.insert(
191        PdeMessageKey::NeumannCondition,
192        "**Neumann Boundary Conditions** specify the normal derivative on the boundary: ∂u/∂n|∂Ω = h. \
193        This prescribes flux: heat flow (heat equation), velocity (wave equation), or electric field \
194        (Laplace equation). Pure Neumann problems for Laplace's equation are only solvable if ∫h = 0 \
195        (conservation). Solutions are unique up to a constant. Example: ∂u/∂x(0,t) = 0 represents \
196        an insulated boundary (no heat flow)."
197    );
198
199    messages.insert(
200        PdeMessageKey::RobinCondition,
201        "**Robin Boundary Conditions** (mixed/third type) combine Dirichlet and Neumann: αu + β∂u/∂n = γ. \
202        They model realistic boundaries like convective heat transfer: -k∂u/∂n = h(u - u∞), where heat \
203        flux is proportional to temperature difference. Robin conditions often arise from coupling PDEs \
204        across interfaces. They ensure unique solutions for elliptic problems when α and β have appropriate \
205        signs. Eigenvalue problems with Robin conditions have discrete spectra."
206    );
207
208    messages.insert(
209        PdeMessageKey::PeriodicCondition,
210        "**Periodic Boundary Conditions** require u(x + L) = u(x) and ∂u/∂x(x + L) = ∂u/∂x(x), \
211        making the solution periodic with period L. They model systems on circles, tori, or with \
212        translational symmetry. Eigenfunctions are complex exponentials e^(2πinx/L) or sines/cosines. \
213        Periodic conditions lead naturally to Fourier series representations. Applications include \
214        crystal lattices, circular membranes, and periodic wave guides."
215    );
216
217    // Initial conditions
218    messages.insert(
219        PdeMessageKey::InitialValueProblem,
220        "An **Initial Value Problem (IVP)** specifies the solution and possibly its time derivatives at t = 0. \
221        For parabolic equations (heat), only u(x,0) = f(x) is needed. For hyperbolic equations (wave), \
222        both position u(x,0) = f(x) and velocity ∂u/∂t(x,0) = g(x) are required. The initial data \
223        determines the future evolution uniquely (for well-posed problems). Smoothness of initial data \
224        affects solution regularity: discontinuous data may remain discontinuous (hyperbolic) or smooth \
225        out (parabolic)."
226    );
227
228    messages.insert(
229        PdeMessageKey::InitialBoundaryValueProblem,
230        "An **Initial-Boundary Value Problem (IBVP)** combines initial conditions with boundary conditions, \
231        typical for evolution equations on bounded domains. The heat equation on [0,L] × [0,∞) needs: \
232        initial temperature u(x,0) = f(x), and boundary conditions like u(0,t) = u(L,t) = 0. \
233        Well-posedness requires compatibility: initial and boundary data must agree at corners (x,t) = (0,0), (L,0). \
234        Solutions are often found by separation of variables, yielding Fourier series representations."
235    );
236
237    // Numerical methods
238    messages.insert(
239        PdeMessageKey::FiniteDifference,
240        "**Finite Difference Methods** approximate derivatives using nearby function values: \
241        ∂u/∂x ≈ (u(x+h) - u(x-h))/(2h). PDEs become systems of algebraic equations on a grid. \
242        Explicit methods (forward Euler) are simple but may require small time steps for stability. \
243        Implicit methods (backward Euler, Crank-Nicolson) are stable but require solving linear systems. \
244        Accuracy depends on grid spacing (typically O(h²)). Boundary conditions are incorporated through \
245        ghost points or modified stencils."
246    );
247
248    messages.insert(
249        PdeMessageKey::FiniteElement,
250        "**Finite Element Methods (FEM)** approximate solutions as linear combinations of basis functions \
251        (often piecewise polynomials on triangular/tetrahedral meshes). The PDE is reformulated weakly: \
252        multiply by test functions and integrate by parts. This naturally handles complex geometries and \
253        boundary conditions. Galerkin method uses same basis for trial and test functions. FEM provides \
254        rigorous error estimates and adaptive refinement. It's the standard for elliptic problems in \
255        engineering (structural mechanics, electromagnetics)."
256    );
257
258    messages.insert(
259        PdeMessageKey::SpectralMethods,
260        "**Spectral Methods** represent solutions using global basis functions (Fourier series, Chebyshev \
261        polynomials). They achieve exponential convergence for smooth solutions (spectral accuracy). \
262        Derivatives are computed in spectral space (multiplication by ik for Fourier). Nonlinear terms \
263        use transforms: FFT to physical space, multiply, FFT back. Spectral methods excel for periodic \
264        domains and smooth solutions but struggle with discontinuities (Gibbs phenomenon). They're used \
265        in turbulence simulation and numerical weather prediction."
266    );
267
268    messages
269});
270
271/// Get a PDE educational message by key
272pub fn get_pde_message(key: PdeMessageKey) -> Option<&'static str> {
273    PDE_MESSAGE_REGISTRY.get(&key).copied()
274}
275
276#[cfg(test)]
277mod tests {
278    use super::*;
279
280    #[test]
281    fn test_pde_message_registry() {
282        let test_keys = vec![
283            PdeMessageKey::WhatIsPde,
284            PdeMessageKey::HeatEquation,
285            PdeMessageKey::WaveEquation,
286            PdeMessageKey::LaplaceEquation,
287            PdeMessageKey::SeparationOfVariables,
288            PdeMessageKey::DirichletCondition,
289            PdeMessageKey::FiniteDifference,
290        ];
291
292        for key in test_keys {
293            let message = get_pde_message(key);
294            assert!(message.is_some(), "Missing message for key {:?}", key);
295            assert!(
296                !message.unwrap().is_empty(),
297                "Empty message for key {:?}",
298                key
299            );
300        }
301    }
302
303    #[test]
304    fn test_message_content_quality() {
305        let message = get_pde_message(PdeMessageKey::HeatEquation).unwrap();
306        assert!(message.len() > 100, "Message too short");
307        assert!(message.contains("Heat Equation"), "Missing key term");
308        assert!(message.contains("∂u/∂t"), "Missing equation");
309    }
310
311    #[test]
312    fn test_all_messages_present() {
313        assert_eq!(PDE_MESSAGE_REGISTRY.len(), 23, "Expected 23 PDE messages");
314    }
315}