科研 Skill
PDE数值微分格式选择
differentiation-schemes
Selects and applies numerical differentiation schemes for PDE/ODE discretization: finite-difference stencils. Use when choosing a spatial discretization scheme.
SKILL.md
Differentiation Schemes
Goal
Provide a reliable workflow to select a differentiation scheme, generate stencils, and assess accuracy for simulation discretization.
Requirements
- Python 3.10+
- NumPy (for stencil computations)
- No heavy dependencies
Inputs to Gather
| Input | Description | Example |
|---|---|---|
| Derivative order | First, second, etc. | 1 or 2 |
| Target accuracy | Order of truncation error | 2 or 4 |
| Grid type | Uniform, nonuniform | uniform |
| Boundary type | Periodic, Dirichlet, Neumann | periodic |
| Smoothness | Smooth or discontinuous | smooth |
Decision Guidance
Scheme Selection Flowchart
Is the field smooth?
├── YES → Is domain periodic?
│ ├── YES → Use central differences or spectral
│ └── NO → Use central interior + one-sided at boundaries
└── NO → Are there shocks/discontinuities?
├── YES → Use upwind, TVD, or WENO
└── NO → Use central with limiters
Quick Reference
| Situation | Recommended Scheme |
|---|---|
| Smooth, periodic | Central, spectral |
| Smooth, bounded | Central + one-sided BCs |
| Advection-dominated | Upwind |
| Shocks/fronts | TVD, WENO |
| High accuracy needed | Compact (Padé), spectral |
Script Outputs (JSON Fields)
| Script | Key Outputs |
|---|---|
scripts/stencil_generator.py | offsets, coefficients, order, accuracy, scheme |
scripts/scheme_selector.py | recommended, alternatives, notes |
scripts/truncation_error.py | error_scale, order, reduction_if_halved |
Workflow
- Identify requirements - derivative order, accuracy, smoothness
- Select scheme - Run
scripts/scheme_selector.py - Generate stencils - Run
scripts/stencil_generator.py - Estimate error - Run
scripts/truncation_error.py - Validate - Test with manufactured solutions or grid refinement
Conversational Workflow Example
User: I need to discretize a second derivative for a diffusion equation on a uniform grid. I want 4th-order accuracy.
Agent workflow:
- Select appropriate scheme (boundary type was not stated; if the domain is
bounded rather than periodic, add
--boundaryto surface one-sided/ghost-cell guidance, or ask the user):python3 scripts/scheme_selector.py --smooth --order 2 --accuracy 4 --json - Generate the stencil:
python3 scripts/stencil_generator.py --order 2 --accuracy 4 --scheme central --json - Result: 5-point stencil with coefficients
[-1/12, 4/3, -5/2, 4/3, -1/12]/ dx².
Pre-Discretization Checklist
- Confirm derivative order and target accuracy
- Choose scheme appropriate to smoothness and boundaries
- Generate and inspect stencils at boundaries
- Estimate truncation error vs physics scales
- Verify with grid refinement study
CLI Examples
# Select scheme for smooth periodic problem
python3 scripts/scheme_selector.py --smooth --periodic --order 1 --accuracy 4 --json
# Generate central difference stencil for first derivative
python3 scripts/stencil_generator.py --order 1 --accuracy 2 --scheme central --json
# Generate 4th-order second derivative stencil
python3 scripts/stencil_generator.py --order 2 --accuracy 4 --scheme central --json
# Estimate truncation error
python3 scripts/truncation_error.py --dx 0.01 --accuracy 2 --scale 1.0 --json
Error Handling
| Error | Cause | Resolution |
|---|---|---|
order must be positive | Invalid derivative order | Use 1, 2, 3, ... (max 6) |
order must be <= 6 | Derivative order too large | Use 1–6 |
accuracy must be even for central | Odd accuracy requested for central scheme | Use 2, 4, 6, ... |
scheme must be central, forward, or backward | Invalid --scheme value | Use central, forward, or backward |
Interpretation Guidance
Stencil Properties
| Property | Meaning |
|---|---|
| Symmetric offsets | Central scheme (no directional bias) |
| Asymmetric offsets | One-sided or upwind scheme |
| More points | Higher accuracy but wider stencil |
Truncation Error Scaling
| Accuracy Order | Error Scales As | Refinement Factor |
|---|---|---|
| 2nd order | O(dx²) | 2× refinement → 4× error reduction |
| 4th order | O(dx⁴) | 2× refinement → 16× error reduction |
| 6th order | O(dx⁶) | 2× refinement → 64× error reduction |
Common Stencils
| Derivative | Accuracy | Points | Coefficients (× 1/dx or 1/dx²) |
|---|---|---|---|
| 1st | 2 | 3 | [-1/2, 0, 1/2] |
| 1st | 4 | 5 | [1/12, -2/3, 0, 2/3, -1/12] |
| 2nd | 2 | 3 | [1, -2, 1] |
| 2nd | 4 | 5 | [-1/12, 4/3, -5/2, 4/3, -1/12] |
Verification checklist
Before trusting a generated stencil or accepting a scheme recommendation, record concrete evidence for each item below:
- Ran
stencil_generator.py --jsonand confirmedresults.accuracymatches the requested order AND thatlen(results.offsets)equals the expected stencil width (e.g. 5 points for a 4th-order central second derivative); for acentralscheme also verified the offsets are symmetric about 0. - Sanity-checked the returned
coefficientsagainstreferences/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²). - For a
centralscheme, confirmed--accuracyis even (odd values exit 2 withaccuracy must be even for central); recorded the actual exit code rather than assuming the requested order was achieved. - Recorded the
error_scale,order, andreduction_if_halvedfromtruncation_error.pyand confirmedreduction_if_halved == 2**accuracy, then comparederror_scaleagainst the smallest physical feature size (dx/L_feature fromreferences/error_guidance.md) to confirm the grid actually resolves the physics. - 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 formalaccuracybefore quoting that order. - For a bounded (non-periodic) domain, confirmed boundary stencils were generated/selected explicitly (
--scheme forward|backwardor--boundaryguidance) perreferences/boundary_handling.md, since the interior stencil alone does not define the scheme order at the boundary. - For non-smooth fields (shocks/fronts), confirmed
scheme_selector.pydid NOT recommend high-order central FD and that a limiter/WENO/upwind path was chosen instead.
Common pitfalls & rationalizations
| Tempting shortcut | Why it's wrong / what to do |
|---|---|
| "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. |
"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. |
| "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. |
| "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). |
| "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). |
| "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. |
"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. |
Security
Input Validation
--order(derivative order) is validated as a positive integer with an upper bound (order <= 6)--accuracyis validated as a positive integer (<= 8), and additionally must be even for central schemes--schemeis validated against a fixed allowlist (central,forward,backward)--offsets(custom stencil) is length-capped (max 51), parsed as distinct integers, and must exceed the derivative order--dxand--scaleare validated as finite, non-negative numbers (--dxstrictly positive)- No user-supplied strings are interpolated into code paths or shell commands
File Access
- Scripts read no external files; all inputs are provided via CLI arguments
- Scripts write only to stdout (JSON output); no files are created unless the agent explicitly uses the Write tool
Tool Restrictions
- Read: Used to inspect script source, references, and user configuration files
- Bash: Used to execute the three Python scripts (
stencil_generator.py,scheme_selector.py,truncation_error.py) with explicit argument lists - Write: Used to save generated stencil coefficients or scheme recommendations; writes are scoped to the user's working directory
- Grep/Glob: Used to locate relevant files and search references
Safety Measures
- No
eval(),exec(), or dynamic code generation - All subprocess calls use explicit argument lists (no
shell=True) - Stencil computation uses only small, bounded arrays (derivative order capped at 6, accuracy at 8, and custom offset lists capped at 51 points)
- All output is deterministic JSON with no shell-interpretable content
Limitations
- Boundary handling: Stencil generator provides interior stencils; boundaries need special treatment
- Nonuniform grids: Standard stencils assume uniform spacing
- Spectral: Not covered by stencil generator
References
references/stencil_catalog.md- Common stencilsreferences/boundary_handling.md- One-sided schemesreferences/scheme_selection.md- FD/FV/spectral comparisonreferences/error_guidance.md- Truncation error scaling
Version History
- 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.
- 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 validation
- v1.1.0 (2024-12-24): Enhanced documentation, decision guidance, examples
- v1.0.0: Initial release with 3 differentiation scripts
示例提示词
帮我为这个对流扩散方程选择合适的迎风差分格式并估计截断误差。
所属插件
安装该插件会一并获得同领域的 23 个 Skill / MCP。
同插件的其他科研 Skill
- 制造解法验证与基准测试规划Plans verification and validation campaigns using manufactured solutions, canonical benchmarks. Use when an agent must prove a solver is correct before trusting results.
- 数值解空间时间收敛性分析Performs spatial/temporal convergence analysis for solution verification: observed order, Richardson extrapolation. Use when checking that a simulation result is grid/timestep independent.
- 仿真结果FAIR归档打包Creates FAIR-minded reproducibility bundles for simulations: file inventories, hashes, units, engine versions. Use before publishing or archiving a simulation dataset.
- HPC作业运行诊断Diagnoses HPC runtime and scheduler problems for materials simulations: MPI/OpenMP/GPU layout, modules, scratch paths, walltime. Use when a cluster job fails, hangs, or underperforms.
- 线性方程组求解器选型Selects and configures linear solvers for Ax=b systems: direct (LU, Cholesky) versus iterative (CG, GMRES, BiCGSTAB) methods, sparsity. Use when choosing a linear solver for a simulation.
- 分子动力学分析方案规划Plans molecular dynamics post-processing for materials simulations: RDF, MSD/diffusion, VACF/VDOS, coordination numbers. Use when deciding which MD analysis to run and in what order.
- 数值模拟网格生成规划Plans and evaluates mesh generation for numerical simulations: grid resolution from physics scales, aspect ratio/skewness checks. Use when designing or auditing a simulation mesh.
- 非线性方程组求解器选型Selects and configures nonlinear solvers for root-finding, optimization, and least-squares problems: Newton, quasi-Newton, Broyden, Anderson acceleration. Use when choosing a nonlinear solver.
- 时间积分方法选择Selects and configures time-integration methods for ODE/PDE simulations: explicit Runge-Kutta, BDF, Rosenbrock. Use when choosing a time-stepping scheme for a solver.
- 偏微分方程数值稳定性分析Analyzes numerical stability for time-dependent PDE simulations: CFL/Fourier criteria, von Neumann analysis. Use when a simulation blows up or to check a scheme’s stability limits.
- 材料科学本体浏览查询Parses, navigates, and queries materials science ontology structures: class hierarchies, property domain/range lookup. Use when exploring an unfamiliar materials ontology.
- 材料术语本体映射Maps materials science terms, crystal structures, and sample descriptions to standardized ontology classes with confidence scores. Use when annotating data for ontology interoperability.
- 本体标注一致性校验Validates material sample annotations against ontology constraints: class/property existence, domain/range consistency. Use before publishing ontology-annotated materials data.
- 仿真参数优化与敏感性分析Explores and optimizes simulation parameters via design of experiments, sensitivity analysis, and optimizer selection: Latin Hypercube, quasi-random. Use when calibrating simulation parameters.
- 仿真计算性能剖析Identifies computational bottlenecks, parallel scaling, and memory requirements for materials simulations: parses timing logs for dominant phases. Use when a simulation is slow or scales poorly.
- 仿真输出数据后处理Extracts, analyzes, and summarizes simulation output data: spatial fields at timesteps, time-series trends, steady-state detection. Use when turning raw simulation output into summary statistics.
- 多代码仿真故障分诊Provides first-response triage for cross-code LAMMPS/VASP/QE/MOOSE simulation failures: classifies nonconvergence, NaN/Inf. Use when a simulation crashes and the cause is unclear.
- 多任务仿真批量编排Orchestrates multi-simulation campaigns: generates parameter sweeps (grid, linspace, Latin Hypercube), tracks batch job status. Use when running and managing many related simulation jobs.
- 仿真三阶段有效性校验Validates simulations across three stages: pre-flight config checks, runtime log monitoring for NaN/Inf and residual growth. Use to catch simulation errors before, during, and after a run.
- SLURM作业脚本生成Generates correct SLURM sbatch job scripts and sanity-checks HPC resource requests: nodes, MPI/OpenMP layout, memory, GPUs, walltime. Use when writing or debugging a SLURM submission script.
- 瞬态仿真时间步策略Plans and controls time-step policies for transient simulations: CFL and physics-based stability limits, adaptive stepping. Use when setting up a time-stepping strategy for a solver.
- 计算材料工作流引擎选型Maps computational materials tasks onto workflow engines (atomate2, jobflow, AiiDA, pyiron) or a one-off script. Use when deciding how to structure a reproducible campaign or DAG.
常见问题
PDE数值微分格式选择能做什么?
Selects and applies numerical differentiation schemes for PDE/ODE discretization: finite-difference stencils. Use when choosing a spatial discretization scheme。
如何安装PDE数值微分格式选择?
在科搭 Codar 左侧点击「插件」,在「组件」页签搜索「PDE数值微分格式选择」并安装;在 Claude Code 或 Codex 中可以发送本页的安装提示词,或下载 Skill 包后解压到 ~/.claude/skills 或 ~/.codex/skills。
PDE数值微分格式选择需要哪些权限?
该科研 Skill没有声明额外权限;执行具体操作时仍由 Agent 按自身规则请求确认。
PDE数值微分格式选择经过官方审核吗?
是。SpeedSkills 收录的每个版本都会记录内容摘要与权限声明,当前版本已通过安全审核。