1---2name: differentiation-schemes3description: >4 Select and apply numerical differentiation schemes for PDE and ODE5 discretization — generate finite-difference stencils at arbitrary order and6 accuracy, choose between central, upwind, compact (Pade), and spectral7 methods, handle boundary stencils, and estimate truncation error scaling.8 Use when discretizing spatial derivatives, picking a scheme for advection-9 or diffusion-dominated problems, building custom stencils for nonstandard10 operators, or comparing dispersion and dissipation properties of candidate11 schemes, even if the user just says "how do I approximate this derivative"12 or "my solution is too diffusive."13allowed-tools: Read, Bash, Write, Grep, Glob14metadata:15 source: https://skillmd.com/skills/heshamfs/differentiation-schemes16 author: HeshamFS17 version: "1.2.2"18 security_tier: high19 security_reviewed: true20 tested_with:21 - claude-code22 last_evaluated: "2026-06-24"23 eval_cases: 424 last_reviewed: "2026-06-23"25 standards:26 - "Fornberg (1988), Generation of finite difference formulas on arbitrarily spaced grids"27 - "Taylor-series truncation-error analysis / order-of-accuracy theory"28 - "Lele (1992), Compact finite difference schemes with spectral-like resolution"29 - "Richardson extrapolation and grid-convergence (observed-order) verification"30 - "Jiang & Shu (1996), ENO/WENO essentially non-oscillatory schemes"31---3233# Differentiation Schemes3435## Goal3637Provide a reliable workflow to select a differentiation scheme, generate stencils, and assess accuracy for simulation discretization.3839## Requirements4041- Python 3.10+42- NumPy (for stencil computations)43- No heavy dependencies4445## Inputs to Gather4647| Input | Description | Example |48|-------|-------------|---------|49| Derivative order | First, second, etc. | `1` or `2` |50| Target accuracy | Order of truncation error | `2` or `4` |51| Grid type | Uniform, nonuniform | `uniform` |52| Boundary type | Periodic, Dirichlet, Neumann | `periodic` |53| Smoothness | Smooth or discontinuous | `smooth` |5455## Decision Guidance5657### Scheme Selection Flowchart5859```60Is the field smooth?61├── YES → Is domain periodic?62│ ├── YES → Use central differences or spectral63│ └── NO → Use central interior + one-sided at boundaries64└── NO → Are there shocks/discontinuities?65 ├── YES → Use upwind, TVD, or WENO66 └── NO → Use central with limiters67```6869### Quick Reference7071| Situation | Recommended Scheme |72|-----------|-------------------|73| Smooth, periodic | Central, spectral |74| Smooth, bounded | Central + one-sided BCs |75| Advection-dominated | Upwind |76| Shocks/fronts | TVD, WENO |77| High accuracy needed | Compact (Padé), spectral |7879## Script Outputs (JSON Fields)8081| Script | Key Outputs |82|--------|-------------|83| `scripts/stencil_generator.py` | `offsets`, `coefficients`, `order`, `accuracy`, `scheme` |84| `scripts/scheme_selector.py` | `recommended`, `alternatives`, `notes` |85| `scripts/truncation_error.py` | `error_scale`, `order`, `reduction_if_halved` |8687## Workflow88891. **Identify requirements** - derivative order, accuracy, smoothness902. **Select scheme** - Run `scripts/scheme_selector.py`913. **Generate stencils** - Run `scripts/stencil_generator.py`924. **Estimate error** - Run `scripts/truncation_error.py`935. **Validate** - Test with manufactured solutions or grid refinement9495## Conversational Workflow Example9697**User**: I need to discretize a second derivative for a diffusion equation on a uniform grid. I want 4th-order accuracy.9899**Agent workflow**:1001. Select appropriate scheme (boundary type was not stated; if the domain is101 bounded rather than periodic, add `--boundary` to surface one-sided/ghost-cell102 guidance, or ask the user):103 ```bash104 python3 scripts/scheme_selector.py --smooth --order 2 --accuracy 4 --json105 ```1062. Generate the stencil:107 ```bash108 python3 scripts/stencil_generator.py --order 2 --accuracy 4 --scheme central --json109 ```1103. Result: 5-point stencil with coefficients `[-1/12, 4/3, -5/2, 4/3, -1/12]` / dx².111112## Pre-Discretization Checklist113114- [ ] Confirm derivative order and target accuracy115- [ ] Choose scheme appropriate to smoothness and boundaries116- [ ] Generate and inspect stencils at boundaries117- [ ] Estimate truncation error vs physics scales118- [ ] Verify with grid refinement study119120## CLI Examples121122```bash123# Select scheme for smooth periodic problem124python3 scripts/scheme_selector.py --smooth --periodic --order 1 --accuracy 4 --json125126# Generate central difference stencil for first derivative127python3 scripts/stencil_generator.py --order 1 --accuracy 2 --scheme central --json128129# Generate 4th-order second derivative stencil130python3 scripts/stencil_generator.py --order 2 --accuracy 4 --scheme central --json131132# Estimate truncation error133python3 scripts/truncation_error.py --dx 0.01 --accuracy 2 --scale 1.0 --json134```135136## Error Handling137138| Error | Cause | Resolution |139|-------|-------|------------|140| `order must be positive` | Invalid derivative order | Use 1, 2, 3, ... (max 6) |141| `order must be <= 6` | Derivative order too large | Use 1–6 |142| `accuracy must be even for central` | Odd accuracy requested for central scheme | Use 2, 4, 6, ... |143| `scheme must be central, forward, or backward` | Invalid `--scheme` value | Use `central`, `forward`, or `backward` |144145## Interpretation Guidance146147### Stencil Properties148149| Property | Meaning |150|----------|---------|151| Symmetric offsets | Central scheme (no directional bias) |152| Asymmetric offsets | One-sided or upwind scheme |153| More points | Higher accuracy but wider stencil |154155### Truncation Error Scaling156157| Accuracy Order | Error Scales As | Refinement Factor |158|----------------|-----------------|-------------------|159| 2nd order | O(dx²) | 2× refinement → 4× error reduction |160| 4th order | O(dx⁴) | 2× refinement → 16× error reduction |161| 6th order | O(dx⁶) | 2× refinement → 64× error reduction |162163### Common Stencils164165| Derivative | Accuracy | Points | Coefficients (× 1/dx or 1/dx²) |166|------------|----------|--------|-------------------------------|167| 1st | 2 | 3 | [-1/2, 0, 1/2] |168| 1st | 4 | 5 | [1/12, -2/3, 0, 2/3, -1/12] |169| 2nd | 2 | 3 | [1, -2, 1] |170| 2nd | 4 | 5 | [-1/12, 4/3, -5/2, 4/3, -1/12] |171172## Verification checklist173174Before trusting a generated stencil or accepting a scheme recommendation, record concrete evidence for each item below:175176- [ ] Ran `stencil_generator.py --json` and confirmed `results.accuracy` matches the requested order AND that `len(results.offsets)` equals the expected stencil width (e.g. 5 points for a 4th-order central second derivative); for a `central` scheme also verified the offsets are symmetric about 0.177- [ ] Sanity-checked the returned `coefficients` against `references/stencil_catalog.md`: confirmed they sum to ~0 (consistency: the operator annihilates a constant) and reproduce a known catalog stencil for at least one standard case (e.g. 2nd-order d²/dx² gives `[1, -2, 1]/dx²`).178- [ ] For a `central` scheme, confirmed `--accuracy` is even (odd values exit 2 with `accuracy must be even for central`); recorded the actual exit code rather than assuming the requested order was achieved.179- [ ] Recorded the `error_scale`, `order`, and `reduction_if_halved` from `truncation_error.py` and confirmed `reduction_if_halved == 2**accuracy`, then compared `error_scale` against the smallest physical feature size (dx/L_feature from `references/error_guidance.md`) to confirm the grid actually resolves the physics.180- [ ] Ran an independent grid-refinement / manufactured-solution study on >=3 grids (the scripts do NOT do this) and confirmed the observed order `p_obs = log(e_h/e_{h/2})/log(2)` is within ~10% of the formal `accuracy` before quoting that order.181- [ ] For a bounded (non-periodic) domain, confirmed boundary stencils were generated/selected explicitly (`--scheme forward|backward` or `--boundary` guidance) per `references/boundary_handling.md`, since the interior stencil alone does not define the scheme order at the boundary.182- [ ] For non-smooth fields (shocks/fronts), confirmed `scheme_selector.py` did NOT recommend high-order central FD and that a limiter/WENO/upwind path was chosen instead.183184## Common pitfalls & rationalizations185186| Tempting shortcut | Why it's wrong / what to do |187|-------------------|------------------------------|188| "The stencil generator returned coefficients, so the scheme is the order I asked for." | The `accuracy` field just echoes your request; it is not measured. Verify the achieved order with a grid-refinement study and confirm the coefficients match a catalog stencil and sum to ~0. |189| "I asked for 4th order on a central scheme with `--accuracy 3`, it'll just round up." | It will not — central schemes reject odd accuracy with `accuracy must be even for central` (exit 2). Pass an even accuracy; an odd request is an error, not a silent upgrade. |190| "Higher accuracy order always means lower error here." | `truncation_error.py` reports asymptotic *scaling* (`scale * dx**accuracy`); for a coarse grid or under-resolved feature the higher-order term need not dominate, and roundoff (`O(ε/dx^p)`) can win on very fine grids. Compare `error_scale` to the feature size, do not assume monotone improvement. |191| "Two grids agree closely, so it's converged." | Two grids cannot estimate observed order or confirm the asymptotic range. Use >=3 grids and compute `p_obs` before claiming the formal order (see `references/error_guidance.md`). |192| "The interior stencil is 4th order, so my whole solve is 4th order." | The generator emits interior stencils only; boundary closures often limit the global order. Generate one-sided/ghost-cell stencils explicitly and verify the boundary does not drop the observed order (`references/boundary_handling.md`). |193| "The field has a shock but a wide central stencil is more accurate, so use it." | High-order central FD oscillates (Gibbs) at discontinuities. `scheme_selector.py` recommends FV with limiter/WENO or upwind for `--discontinuous`; follow it rather than maximizing formal order. |194| "Custom `--offsets` let me build any stencil I want." | Offsets must be distinct, length-capped (51), and number more than the derivative order, or the script exits 2. A valid run still does not guarantee the intended accuracy — verify the coefficients and observed order. |195196## Security197198### Input Validation199- `--order` (derivative order) is validated as a positive integer with an upper bound (`order <= 6`)200- `--accuracy` is validated as a positive integer (`<= 8`), and additionally must be even for central schemes201- `--scheme` is validated against a fixed allowlist (`central`, `forward`, `backward`)202- `--offsets` (custom stencil) is length-capped (max 51), parsed as distinct integers, and must exceed the derivative order203- `--dx` and `--scale` are validated as finite, non-negative numbers (`--dx` strictly positive)204- No user-supplied strings are interpolated into code paths or shell commands205206### File Access207- Scripts read no external files; all inputs are provided via CLI arguments208- Scripts write only to stdout (JSON output); no files are created unless the agent explicitly uses the Write tool209210### Tool Restrictions211- **Read**: Used to inspect script source, references, and user configuration files212- **Bash**: Used to execute the three Python scripts (`stencil_generator.py`, `scheme_selector.py`, `truncation_error.py`) with explicit argument lists213- **Write**: Used to save generated stencil coefficients or scheme recommendations; writes are scoped to the user's working directory214- **Grep/Glob**: Used to locate relevant files and search references215216### Safety Measures217- No `eval()`, `exec()`, or dynamic code generation218- All subprocess calls use explicit argument lists (no `shell=True`)219- Stencil computation uses only small, bounded arrays (derivative order capped at 6, accuracy at 8, and custom offset lists capped at 51 points)220- All output is deterministic JSON with no shell-interpretable content221222## Limitations223224- **Boundary handling**: Stencil generator provides interior stencils; boundaries need special treatment225- **Nonuniform grids**: Standard stencils assume uniform spacing226- **Spectral**: Not covered by stencil generator227228## References229230- `references/stencil_catalog.md` - Common stencils231- `references/boundary_handling.md` - One-sided schemes232- `references/scheme_selection.md` - FD/FV/spectral comparison233- `references/error_guidance.md` - Truncation error scaling234235## Version History236237- **v1.2.2** (2026-06-24): Added a Verification checklist (evidence-based, tied to script JSON outputs and the references) and a Common pitfalls & rationalizations table.238- **v1.2.0** (2026-06-23): Enforced even-accuracy and order upper-bound validation, corrected Security/error-handling/output docs to match scripts, fixed CLI/eval examples, hardened input validation239- **v1.1.0** (2024-12-24): Enhanced documentation, decision guidance, examples240- **v1.0.0**: Initial release with 3 differentiation scripts