Mesh Generation
Goal
Provide a consistent workflow for selecting mesh resolution and checking mesh quality for PDE simulations.
Requirements
- Python 3.10+
- No external dependencies (uses stdlib)
Inputs to Gather
| Input |
Description |
Example |
| Domain size |
Physical dimensions |
1.0 × 1.0 m |
| Feature size |
Smallest feature to resolve |
0.01 m |
| Points per feature |
Resolution requirement |
10 points |
| Aspect ratio limit |
Maximum dx/dy ratio |
5:1 |
| Quality threshold |
Skewness limit |
< 0.8 |
Decision Guidance
Resolution Selection
What is the smallest feature size?
├── Interface width → dx ≤ width / 5
├── Boundary layer → dx ≤ layer_thickness / 10
├── Wave length → dx ≤ lambda / 20
└── Diffusion length → dx ≤ sqrt(D × dt) / 2
Mesh Type Selection
| Problem |
Recommended Mesh |
| Simple geometry, uniform |
Structured Cartesian |
| Complex geometry |
Unstructured triangular/tetrahedral |
| Boundary layers |
Hybrid (structured near walls) |
| Adaptive refinement |
Quadtree/Octree or AMR |
Script Outputs (JSON Fields)
All scripts emit a top-level object with inputs (the echoed CLI values) and
results (the computed fields below). Index as result["results"]["..."].
| Script |
results Fields |
scripts/grid_sizing.py |
dx, counts (list of per-dimension cell counts, length == dims), notes |
scripts/mesh_quality.py |
aspect_ratio, skewness, size_anisotropy, quality_flags, dims, notes |
mesh_quality.py describes axis-aligned (orthogonal Cartesian) cells defined
purely by edge spacings. For such cells every interior angle is 90°, so the true
angular skewness is always 0.0 and high_skewness is never flagged.
Cell elongation is reported separately via aspect_ratio and the redundant
convenience field size_anisotropy (= 1 - 1/aspect_ratio).
Workflow
- Estimate resolution - From physics scales
- Compute grid sizing - Run
scripts/grid_sizing.py
- Check quality metrics - Run
scripts/mesh_quality.py
- Adjust if needed - Fix aspect ratios, reduce skewness
- Validate - Mesh convergence study
Conversational Workflow Example
User: I need to mesh a 1mm × 1mm domain for a phase-field simulation with interface width of 10 μm.
Agent workflow:
- Compute grid sizing:
python3 scripts/grid_sizing.py --length 0.001 --resolution 200 --json
- Verify interface is resolved: dx = 5 μm, interface width = 10 μm → 2 points per interface width.
- Recommend: Increase to 500 points (dx = 2 μm) for 5 points across interface.
Pre-Mesh Checklist
CLI Examples
# Compute grid sizing for 1D domain
python3 scripts/grid_sizing.py --length 1.0 --resolution 200 --json
# Check mesh quality (3D cell)
python3 scripts/mesh_quality.py --dx 1.0 --dy 0.5 --dz 0.5 --json
# High aspect ratio check (2D cell; --dz omitted is treated as 2D)
python3 scripts/mesh_quality.py --dx 1.0 --dy 0.1 --json
Error Handling
All validation errors are written to stderr and the script exits with code 2.
| Error message |
Cause |
Resolution |
length must be positive, got ... |
Non-positive domain size |
Use a positive value |
resolution must be positive, got ... |
Non-positive resolution (resolution=1 is a valid single-cell mesh) |
Use a positive integer |
dims must be one of (1, 2, 3), got ... |
Unsupported dimension count |
Use 1, 2, or 3 |
<name> must be a finite positive number, got ... |
dx/dy/dz not finite or not positive |
Use a finite positive value |
<name> exceeds maximum (...), got ... |
Input above the resource-exhaustion bound |
Use a smaller value |
Interpretation Guidance
Aspect Ratio
| Aspect Ratio |
Quality |
Impact |
| 1:1 |
Excellent |
Optimal accuracy |
| 1:1 - 3:1 |
Good |
Acceptable |
| 3:1 - 5:1 |
Fair |
May affect accuracy |
| > 5:1 |
Poor |
Solver issues likely |
Skewness
Skewness is the angular deviation from the ideal cell shape
(max(|90° - θ_i|) / 90° for quads/hexes — see references/quality_metrics.md).
mesh_quality.py works from axis-aligned edge spacings, which describe
orthogonal Cartesian cells whose interior angles are all exactly 90°; it
therefore always reports skewness = 0.0 for these cells. The thresholds below
apply when a genuine skewness value is obtained from real cell-corner geometry
(e.g. from an unstructured mesh), not from dx/dy/dz spacings.
| Skewness |
Quality |
Impact |
| 0 - 0.25 |
Excellent |
Optimal |
| 0.25 - 0.50 |
Good |
Acceptable |
| 0.50 - 0.80 |
Fair |
May affect accuracy |
| > 0.80 |
Poor |
Likely problems |
Note: cell elongation is not skewness. An anisotropic but orthogonal cell
(e.g. a wall-aligned boundary-layer cell) has high aspect_ratio /
size_anisotropy but zero skewness, and is often perfectly acceptable.
Resolution Guidelines
| Application |
Points per Feature |
| Phase-field interface |
5-10 |
| Boundary layer |
10-20 |
| Shock |
3-5 (with capturing) |
| Wave propagation |
10-20 per wavelength |
| Smooth gradients |
5-10 |
Verification checklist
Common pitfalls & rationalizations
| Tempting shortcut |
Why it's wrong / what to do |
"skewness came back 0.0, so the mesh quality is fine." |
mesh_quality.py always returns skewness = 0.0 for axis-aligned spacings — it is a definitional property of orthogonal cells, not a measurement. Real skewness needs cell-corner angles from an unstructured mesh; don't read 0.0 as a passing quality check. |
| "Two grids gave nearly the same answer, so the mesh is converged." |
Two grids cannot establish the observed order or the asymptotic range. Use ≥3 successively refined grids and confirm the quantity of interest is converging before quoting any result as mesh-independent. |
"High aspect_ratio was flagged, so the cell is bad." |
Elongation is not skewness. A wall-aligned boundary-layer cell with AR up to ~100 is acceptable when aligned with the flow/field; check size_anisotropy and the physics, not just the high_aspect_ratio flag. |
"I'll set one --length and reuse the counts for all axes." |
grid_sizing.py is isotropic per call — it applies the single derived count to every dimension. For unequal edges this over/under-resolves axes; run it per edge length or supply --dx per axis. |
"dx = length/resolution resolves my feature because resolution is large." |
Points-per-domain is not points-per-feature. A fine global dx can still place too few cells across a thin interface/layer; check feature_size / dx against the Resolution Guidelines (5-10 for interfaces, 10-20 for boundary layers). |
| "The mesh is fine enough, so I can ignore the time step." |
Mesh resolution and temporal stability are coupled: shrinking dx tightens explicit CFL/diffusion limits. A refined mesh that violates the solver's stability constraint diverges — re-check dt against numerical-stability after any refinement. |
Security
Input Validation
- All inputs (
length, resolution, dx, dy, dz) are validated as finite positive numbers with upper bounds to prevent resource exhaustion
dims is restricted to {1, 2, 3}
argparse type parameters reject non-numeric input at the CLI boundary before any processing occurs
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
- Write: Used to save grid sizing results or mesh quality reports; writes are scoped to the user's working directory
- Grep/Glob: Used to locate relevant files and search references
- The skill's
allowed-tools excludes Bash to prevent the agent from executing arbitrary commands when processing user-provided inputs
Safety Measures
- No
eval(), exec(), or dynamic code generation
- All subprocess calls use explicit argument lists (no
shell=True)
- Reduced tool surface (no Bash) means the agent should use
Read and Write to prepare inputs and capture outputs rather than constructing shell commands from user text
- All output is deterministic JSON with no shell-interpretable content
Limitations
- 2D/3D only: No unstructured mesh generation
- Quality metrics: Aspect ratio and size anisotropy from axis-aligned spacings only; skewness is reported as 0 for these orthogonal cells (true angular skewness requires real cell-corner geometry)
- No mesh generation: Sizing recommendations only
- Isotropic per call:
grid_sizing.py takes a single --length and applies the resulting count to every dimension. For an anisotropic domain (e.g. 10 cm × 5 cm), run it once per differing edge length, or compute dx from physics and apply it per axis (e.g. --length 0.10 --dx 5e-5, then --length 0.05 --dx 5e-5).
References
references/mesh_types.md - Structured vs unstructured
references/quality_metrics.md - Aspect ratio/skewness thresholds
Version History
- v1.2.0 (2026-06-23): Corrected skewness science (orthogonal cells now report skewness 0), added
size_anisotropy, made mesh_quality.py --dz optional (2D cells), fixed grid_sizing off-by-one for resolution-derived counts, surfaced dx-override note, corrected output/error-handling docs
- v1.1.0 (2024-12-24): Enhanced documentation, decision guidance, examples
- v1.0.0: Initial release with 2 mesh quality scripts
1---2name: mesh-generation3description: Plan and evaluate mesh generation for numerical simulations — estimate grid resolution from physics scales (interface width, boundary layers, wavelengths), check aspect ratios and skewness against quality thresholds, choose between structured, unstructured, and adaptive mesh refinement strategies, and compute grid sizing for 1D/2D/3D domains. Use when setting up a new mesh, diagnosing poor solver convergence caused by mesh quality, deciding how many points to place across a phase-field interface or boundary layer, or preparing a mesh convergence study, even if the user only asks "what resolution do I need" or "why is my solver failing."4---56# Mesh Generation78## Goal910Provide a consistent workflow for selecting mesh resolution and checking mesh quality for PDE simulations.1112## Requirements1314- Python 3.10+15- No external dependencies (uses stdlib)1617## Inputs to Gather1819| Input | Description | Example |20|-------|-------------|---------|21| Domain size | Physical dimensions | `1.0 × 1.0 m` |22| Feature size | Smallest feature to resolve | `0.01 m` |23| Points per feature | Resolution requirement | `10 points` |24| Aspect ratio limit | Maximum dx/dy ratio | `5:1` |25| Quality threshold | Skewness limit | `< 0.8` |2627## Decision Guidance2829### Resolution Selection3031```32What is the smallest feature size?33├── Interface width → dx ≤ width / 534├── Boundary layer → dx ≤ layer_thickness / 1035├── Wave length → dx ≤ lambda / 2036└── Diffusion length → dx ≤ sqrt(D × dt) / 237```3839### Mesh Type Selection4041| Problem | Recommended Mesh |42|---------|------------------|43| Simple geometry, uniform | Structured Cartesian |44| Complex geometry | Unstructured triangular/tetrahedral |45| Boundary layers | Hybrid (structured near walls) |46| Adaptive refinement | Quadtree/Octree or AMR |4748## Script Outputs (JSON Fields)4950All scripts emit a top-level object with `inputs` (the echoed CLI values) and51`results` (the computed fields below). Index as `result["results"]["..."]`.5253| Script | `results` Fields |54|--------|------------------|55| `scripts/grid_sizing.py` | `dx`, `counts` (list of per-dimension cell counts, length == `dims`), `notes` |56| `scripts/mesh_quality.py` | `aspect_ratio`, `skewness`, `size_anisotropy`, `quality_flags`, `dims`, `notes` |5758`mesh_quality.py` describes axis-aligned (orthogonal Cartesian) cells defined59purely by edge spacings. For such cells every interior angle is 90°, so the true60angular `skewness` is always `0.0` and `high_skewness` is never flagged.61Cell elongation is reported separately via `aspect_ratio` and the redundant62convenience field `size_anisotropy` (= `1 - 1/aspect_ratio`).6364## Workflow65661. **Estimate resolution** - From physics scales672. **Compute grid sizing** - Run `scripts/grid_sizing.py`683. **Check quality metrics** - Run `scripts/mesh_quality.py`694. **Adjust if needed** - Fix aspect ratios, reduce skewness705. **Validate** - Mesh convergence study7172## Conversational Workflow Example7374**User**: I need to mesh a 1mm × 1mm domain for a phase-field simulation with interface width of 10 μm.7576**Agent workflow**:771. Compute grid sizing:78 ```bash79 python3 scripts/grid_sizing.py --length 0.001 --resolution 200 --json80 ```812. Verify interface is resolved: dx = 5 μm, interface width = 10 μm → 2 points per interface width.823. Recommend: Increase to 500 points (dx = 2 μm) for 5 points across interface.8384## Pre-Mesh Checklist8586- [ ] Define target resolution per feature/interface87- [ ] Ensure dx meets stability constraints (see numerical-stability)88- [ ] Check aspect ratio < limit (typically 5:1)89- [ ] Check skewness < threshold (typically 0.8)90- [ ] Validate mesh convergence with refinement study9192## CLI Examples9394```bash95# Compute grid sizing for 1D domain96python3 scripts/grid_sizing.py --length 1.0 --resolution 200 --json9798# Check mesh quality (3D cell)99python3 scripts/mesh_quality.py --dx 1.0 --dy 0.5 --dz 0.5 --json100101# High aspect ratio check (2D cell; --dz omitted is treated as 2D)102python3 scripts/mesh_quality.py --dx 1.0 --dy 0.1 --json103```104105## Error Handling106107All validation errors are written to stderr and the script exits with code `2`.108109| Error message | Cause | Resolution |110|---------------|-------|------------|111| `length must be positive, got ...` | Non-positive domain size | Use a positive value |112| `resolution must be positive, got ...` | Non-positive resolution (`resolution=1` is a valid single-cell mesh) | Use a positive integer |113| `dims must be one of (1, 2, 3), got ...` | Unsupported dimension count | Use `1`, `2`, or `3` |114| `<name> must be a finite positive number, got ...` | `dx`/`dy`/`dz` not finite or not positive | Use a finite positive value |115| `<name> exceeds maximum (...), got ...` | Input above the resource-exhaustion bound | Use a smaller value |116117## Interpretation Guidance118119### Aspect Ratio120121| Aspect Ratio | Quality | Impact |122|--------------|---------|--------|123| 1:1 | Excellent | Optimal accuracy |124| 1:1 - 3:1 | Good | Acceptable |125| 3:1 - 5:1 | Fair | May affect accuracy |126| > 5:1 | Poor | Solver issues likely |127128### Skewness129130Skewness is the angular deviation from the ideal cell shape131(`max(|90° - θ_i|) / 90°` for quads/hexes — see `references/quality_metrics.md`).132`mesh_quality.py` works from axis-aligned edge spacings, which describe133orthogonal Cartesian cells whose interior angles are all exactly 90°; it134therefore always reports `skewness = 0.0` for these cells. The thresholds below135apply when a genuine skewness value is obtained from real cell-corner geometry136(e.g. from an unstructured mesh), not from `dx/dy/dz` spacings.137138| Skewness | Quality | Impact |139|----------|---------|--------|140| 0 - 0.25 | Excellent | Optimal |141| 0.25 - 0.50 | Good | Acceptable |142| 0.50 - 0.80 | Fair | May affect accuracy |143| > 0.80 | Poor | Likely problems |144145> Note: cell elongation is **not** skewness. An anisotropic but orthogonal cell146> (e.g. a wall-aligned boundary-layer cell) has high `aspect_ratio` /147> `size_anisotropy` but zero skewness, and is often perfectly acceptable.148149### Resolution Guidelines150151| Application | Points per Feature |152|-------------|-------------------|153| Phase-field interface | 5-10 |154| Boundary layer | 10-20 |155| Shock | 3-5 (with capturing) |156| Wave propagation | 10-20 per wavelength |157| Smooth gradients | 5-10 |158159## Verification checklist160161- [ ] Recorded `dx` and `counts` from `grid_sizing.py --json` and confirmed the smallest physical feature gets enough points (interface ≥5×dx, boundary layer ≥10×dx, wavelength ≥20×dx per Resolution Selection above).162- [ ] For an anisotropic domain, ran `grid_sizing.py` once per differing edge length (or applied `--dx` per axis) — did NOT apply a single `--length`-derived count to unequal edges.163- [ ] Checked the `notes` field for "Grid does not fully cover length" and resolved any partial-coverage warning before trusting `counts`.164- [ ] Logged `aspect_ratio` and `quality_flags` from `mesh_quality.py --json`; confirmed `high_aspect_ratio` is absent OR that the elongation is intentional and physics-aligned (e.g. wall-aligned boundary-layer cell with AR≤100 along the wall).165- [ ] Confirmed the reported `skewness = 0.0` is the expected orthogonal-Cartesian result, NOT a measured quality pass — for unstructured/non-orthogonal cells, obtained a real angle-based skewness from cell-corner geometry and checked it against the <0.8 threshold.166- [ ] Verified `dx` also satisfies the solver's stability constraint (cross-check with numerical-stability) before committing to the resolution.167- [ ] Ran a mesh convergence study (≥3 successively refined grids) and confirmed the quantity of interest changes monotonically/asymptotically before declaring the mesh adequate.168169## Common pitfalls & rationalizations170171| Tempting shortcut | Why it's wrong / what to do |172|-------------------|------------------------------|173| "`skewness` came back 0.0, so the mesh quality is fine." | `mesh_quality.py` always returns `skewness = 0.0` for axis-aligned spacings — it is a definitional property of orthogonal cells, not a measurement. Real skewness needs cell-corner angles from an unstructured mesh; don't read 0.0 as a passing quality check. |174| "Two grids gave nearly the same answer, so the mesh is converged." | Two grids cannot establish the observed order or the asymptotic range. Use ≥3 successively refined grids and confirm the quantity of interest is converging before quoting any result as mesh-independent. |175| "High `aspect_ratio` was flagged, so the cell is bad." | Elongation is not skewness. A wall-aligned boundary-layer cell with AR up to ~100 is acceptable when aligned with the flow/field; check `size_anisotropy` and the physics, not just the `high_aspect_ratio` flag. |176| "I'll set one `--length` and reuse the `counts` for all axes." | `grid_sizing.py` is isotropic per call — it applies the single derived count to every dimension. For unequal edges this over/under-resolves axes; run it per edge length or supply `--dx` per axis. |177| "`dx = length/resolution` resolves my feature because resolution is large." | Points-per-domain is not points-per-feature. A fine global `dx` can still place too few cells across a thin interface/layer; check `feature_size / dx` against the Resolution Guidelines (5-10 for interfaces, 10-20 for boundary layers). |178| "The mesh is fine enough, so I can ignore the time step." | Mesh resolution and temporal stability are coupled: shrinking `dx` tightens explicit CFL/diffusion limits. A refined mesh that violates the solver's stability constraint diverges — re-check `dt` against numerical-stability after any refinement. |179180## Security181182### Input Validation183- All inputs (`length`, `resolution`, `dx`, `dy`, `dz`) are validated as finite positive numbers with upper bounds to prevent resource exhaustion184- `dims` is restricted to `{1, 2, 3}`185- `argparse` type parameters reject non-numeric input at the CLI boundary before any processing occurs186187### File Access188- Scripts read no external files; all inputs are provided via CLI arguments189- Scripts write only to stdout (JSON output); no files are created unless the agent explicitly uses the Write tool190191### Tool Restrictions192- **Read**: Used to inspect script source, references, and user configuration files193- **Write**: Used to save grid sizing results or mesh quality reports; writes are scoped to the user's working directory194- **Grep/Glob**: Used to locate relevant files and search references195- The skill's `allowed-tools` excludes `Bash` to prevent the agent from executing arbitrary commands when processing user-provided inputs196197### Safety Measures198- No `eval()`, `exec()`, or dynamic code generation199- All subprocess calls use explicit argument lists (no `shell=True`)200- Reduced tool surface (no Bash) means the agent should use `Read` and `Write` to prepare inputs and capture outputs rather than constructing shell commands from user text201- All output is deterministic JSON with no shell-interpretable content202203## Limitations204205- **2D/3D only**: No unstructured mesh generation206- **Quality metrics**: Aspect ratio and size anisotropy from axis-aligned spacings only; skewness is reported as 0 for these orthogonal cells (true angular skewness requires real cell-corner geometry)207- **No mesh generation**: Sizing recommendations only208- **Isotropic per call**: `grid_sizing.py` takes a single `--length` and applies the resulting count to every dimension. For an anisotropic domain (e.g. 10 cm × 5 cm), run it once per differing edge length, or compute `dx` from physics and apply it per axis (e.g. `--length 0.10 --dx 5e-5`, then `--length 0.05 --dx 5e-5`).209210## References211212- `references/mesh_types.md` - Structured vs unstructured213- `references/quality_metrics.md` - Aspect ratio/skewness thresholds214215## Version History216217- **v1.2.0** (2026-06-23): Corrected skewness science (orthogonal cells now report skewness 0), added `size_anisotropy`, made `mesh_quality.py --dz` optional (2D cells), fixed grid_sizing off-by-one for resolution-derived counts, surfaced dx-override note, corrected output/error-handling docs218- **v1.1.0** (2024-12-24): Enhanced documentation, decision guidance, examples219- **v1.0.0**: Initial release with 2 mesh quality scripts