
Mesh Generation
- 16 installs
- 869 repo stars
- Updated June 8, 2026
- beita6969/scienceclaw
mesh-generation is a Claude skill for planning and evaluating mesh resolution and quality for numerical PDE simulations.
About
This skill provides a workflow for choosing mesh resolution and checking mesh quality for PDE simulations. It runs stdlib Python scripts to compute grid sizing and evaluate aspect ratio and skewness against thresholds. Developers use it when planning grid resolution or adaptive mesh refinement, but it only recommends sizing and does not generate meshes.
- Plan and evaluate mesh generation for numerical PDE simulations
- Selects grid resolution and checks aspect ratio and skewness
- Pure-stdlib Python scripts for grid sizing and mesh quality
Mesh Generation by the numbers
- 16 all-time installs (skills.sh)
- Ranked #1,318 of 2,065 Data Science & ML skills by installs in the Skillselion catalog
- Data as of Aug 2, 2026 (Skillselion catalog sync)
mesh-generation capabilities & compatibility
Free; requires only Python 3.8+ with no external dependencies.
- Capabilities
- molecular dynamics · math computation · materials screening
- Use cases
- data analysis · research
- Pricing
- Free
What mesh-generation says it does
Plan and evaluate mesh generation for numerical simulations.
Python 3.8+ - No external dependencies (uses stdlib)
**No mesh generation**: Sizing recommendations only
npx skills add https://github.com/beita6969/scienceclaw --skill mesh-generationAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 16 |
|---|---|
| repo stars | ★ 869 |
| Last updated | June 8, 2026 |
| Repository | beita6969/scienceclaw ↗ |
What it does
Select grid resolution and check aspect ratio and skewness for PDE simulation meshes using stdlib Python scripts.
Who is it for?
Choosing grid resolution, checking aspect ratios/skewness, and planning adaptive mesh refinement.
Skip if: Actual unstructured mesh generation (sizing recommendations only).
When should I use this skill?
You need to select mesh resolution or evaluate mesh quality for a PDE discretization.
What you get
Recommends grid sizing and flags aspect-ratio and skewness quality issues.
- Grid sizing JSON (dx, nx, ny, nz)
- Mesh quality JSON (aspect_ratio, skewness, quality_flags)
By the numbers
- 2 mesh quality scripts
- 5-item pre-mesh checklist
- Aspect ratio threshold 5:1, skewness threshold 0.8
Files
Mesh Generation
Goal
Provide a consistent workflow for selecting mesh resolution and checking mesh quality for PDE simulations.
Requirements
- Python 3.8+
- 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) / 2Mesh 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)
| Script | Key Outputs |
|---|---|
scripts/grid_sizing.py | dx, nx, ny, nz, notes |
scripts/mesh_quality.py | aspect_ratio, skewness, quality_flags |
Workflow
1. Estimate resolution - From physics scales 2. Compute grid sizing - Run scripts/grid_sizing.py 3. Check quality metrics - Run scripts/mesh_quality.py 4. Adjust if needed - Fix aspect ratios, reduce skewness 5. 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: 1. Compute grid sizing:
python3 scripts/grid_sizing.py --length 0.001 --resolution 200 --json2. Verify interface is resolved: dx = 5 μm, interface width = 10 μm → 2 points per interface width. 3. Recommend: Increase to 500 points (dx = 2 μm) for 5 points across interface.
Pre-Mesh Checklist
- [ ] Define target resolution per feature/interface
- [ ] Ensure dx meets stability constraints (see numerical-stability)
- [ ] Check aspect ratio < limit (typically 5:1)
- [ ] Check skewness < threshold (typically 0.8)
- [ ] Validate mesh convergence with refinement study
CLI Examples
# Compute grid sizing for 1D domain
python3 scripts/grid_sizing.py --length 1.0 --resolution 200 --json
# Check mesh quality
python3 scripts/mesh_quality.py --dx 1.0 --dy 0.5 --dz 0.5 --json
# High aspect ratio check
python3 scripts/mesh_quality.py --dx 1.0 --dy 0.1 --jsonError Handling
| Error | Cause | Resolution |
|---|---|---|
length must be positive | Invalid domain size | Use positive value |
resolution must be > 1 | Insufficient points | Use at least 2 |
dx, dy must be positive | Invalid spacing | Use positive values |
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 | 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 |
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 |
Limitations
- 2D/3D only: No unstructured mesh generation
- Quality metrics: Basic aspect ratio and skewness only
- No mesh generation: Sizing recommendations only
References
references/mesh_types.md- Structured vs unstructuredreferences/quality_metrics.md- Aspect ratio/skewness thresholds
Version History
- v1.1.0 (2024-12-24): Enhanced documentation, decision guidance, examples
- v1.0.0: Initial release with 2 mesh quality scripts
Mesh Types
Comprehensive guide for selecting mesh types in numerical simulations.
Structured Meshes
Cartesian (Regular)
Uniform spacing in each direction.
Grid points at: (i×dx, j×dy, k×dz)
where i, j, k are integersProperties:
| Property | Value |
|---|---|
| Indexing | Simple (i,j,k) |
| Storage | Minimal (just dx, dy, dz) |
| Stencils | Efficient, regular |
| Parallelization | Easy domain decomposition |
| Complex geometry | Poor fit |
Best for:
- Phase-field simulations
- Spectral methods
- Regular domains (boxes)
- Prototyping and testing
Rectilinear (Non-uniform Cartesian)
Variable spacing, still axis-aligned.
Grid points at: (x_i, y_j, z_k)
where x_i, y_j, z_k are 1D arraysProperties:
| Property | Value |
|---|---|
| Indexing | Still (i,j,k) |
| Storage | 1D arrays for coordinates |
| Stencils | Variable coefficients |
| Refinement | Local stretching |
Use for:
- Boundary layer refinement
- Interface refinement
- Graded meshes
Stretching functions:
Geometric: dx_i = dx_0 × r^i
Hyperbolic tangent: concentrated at boundaries
Polynomial: smooth variationCurvilinear (Body-Fitted)
General structured mesh, not axis-aligned.
Physical: (x, y, z)
Computational: (ξ, η, ζ) on [0,1]³
Mapping: x = x(ξ,η,ζ), etc.Properties:
| Property | Value |
|---|---|
| Indexing | Still (i,j,k) |
| Storage | Full coordinate arrays |
| Stencils | Metric terms required |
| Geometry | Good for smooth boundaries |
Metric terms:
∂/∂x = (1/J)[∂ξ/∂x × ∂/∂ξ + ∂η/∂x × ∂/∂η + ∂ζ/∂x × ∂/∂ζ]
where J = Jacobian of mappingCommon transformations:
- Polar/cylindrical
- Elliptic smoothing
- Algebraic stretching
Block-Structured
Multiple structured blocks patched together.
Block 1: (i,j,k) ∈ [0,N1] × [0,M1] × [0,P1]
Block 2: (i,j,k) ∈ [0,N2] × [0,M2] × [0,P2]
...
Interface: matching or non-matchingProperties:
| Property | Value |
|---|---|
| Flexibility | Better than single block |
| Parallelism | Block = parallel unit |
| Complexity | Interface handling |
| Geometry | Moderate complexity |
Unstructured Meshes
Triangular (2D) / Tetrahedral (3D)
Elements: triangles (2D) or tetrahedra (3D).
Properties:
| Property | Value |
|---|---|
| Geometry | Arbitrary boundaries |
| Adaptivity | Easy local refinement |
| Stencils | Variable, need connectivity |
| Storage | Element-node connectivity |
| Generation | Delaunay, advancing front |
Data structures:
Nodes: [(x_0, y_0), (x_1, y_1), ...]
Elements: [(n_0, n_1, n_2), ...] # node indices
Edges: derived from elementsQuality metrics:
- Aspect ratio
- Minimum angle
- Circumradius/inradius ratio
Quadrilateral (2D) / Hexahedral (3D)
Elements: quads (2D) or hexahedra (3D).
Properties:
| Property | Value |
|---|---|
| Efficiency | Better per-element accuracy |
| Stiffness | Can be over-constrained |
| Generation | Harder than tri/tet |
| Quality control | More challenging |
Advantages over tri/tet:
- Fewer elements for same accuracy
- Better alignment with flow/field directions
- Lower numerical diffusion for advection
Mixed/Hybrid
Combine different element types.
Near walls: structured quad/hex (boundary layer)
Interior: unstructured tri/tet (flexibility)Common patterns:
- Prism layers near walls + tets in bulk
- Quad faces on boundaries + tet interior
- Hanging nodes with transitions
Special Mesh Types
Octree/Quadtree
Hierarchical refinement by recursive subdivision.
Root cell covers domain
Subdivide cells based on criterion
Continue until resolution satisfiedProperties:
| Property | Value |
|---|---|
| Adaptivity | Automatic, hierarchical |
| Load balancing | Natural with Z-ordering |
| Hanging nodes | At refinement interfaces |
| Conservation | Needs special treatment |
Refinement criteria:
- Gradient magnitude
- Error estimator
- Geometric features
- Distance to interface
Voronoi/Polyhedral
Cells are general polygons/polyhedra.
Properties:
| Property | Value |
|---|---|
| Flexibility | Maximum |
| Quality | Depends on generation |
| FV methods | Natural fit |
| Stencils | Per-cell connectivity |
Overset (Chimera)
Multiple overlapping meshes.
Background mesh: covers domain
Body-fitted mesh: around objects
Interpolation: at overlap boundariesUse for:
- Moving bodies
- Multiple components
- Complex geometry with relative motion
Mesh Selection Guide
By Geometry Complexity
| Geometry | Recommended |
|---|---|
| Box/rectangle | Cartesian |
| Cylinder/sphere | Curvilinear |
| Single body, smooth | Body-fitted structured |
| Complex single body | Unstructured |
| Multiple bodies | Block-structured or overset |
| Arbitrary | Unstructured |
By Physics
| Physics | Recommended |
|---|---|
| Diffusion only | Any (Cartesian often sufficient) |
| Advection-dominated | Aligned with flow if possible |
| Boundary layers | Structured near wall |
| Shocks | Adaptive (octree/AMR) |
| Interface tracking | Refined at interface |
| Phase-field | Uniform or locally refined |
By Method
| Method | Compatible Meshes |
|---|---|
| Finite difference | Structured (Cartesian, curvilinear) |
| Finite volume | Any |
| Finite element | Any (often unstructured) |
| Spectral | Structured |
| Lattice Boltzmann | Cartesian |
Mesh Refinement Strategies
H-Refinement
Subdivide cells/elements.
Original: element of size h
Refined: 4 elements (2D) or 8 elements (3D) of size h/2P-Refinement
Increase polynomial order within elements.
Original: linear elements (p=1)
Refined: quadratic elements (p=2)R-Refinement (Mesh Movement)
Move existing nodes without changing connectivity.
Nodes move toward regions needing resolution
Total node count unchangedHP-Refinement
Combine h and p adaptively.
Smooth regions: increase p
Non-smooth regions: decrease hMesh Generation Considerations
Input Requirements
| Input | Purpose |
|---|---|
| Geometry (CAD, STL) | Domain boundary |
| Target element size | Resolution control |
| Refinement regions | Local sizing |
| Boundary conditions | Layer requirements |
Output Quality Checks
- [ ] No inverted elements
- [ ] Aspect ratio within bounds
- [ ] Skewness within bounds
- [ ] Minimum angle acceptable
- [ ] Smooth size transitions
- [ ] Boundary conformity
Common Tools
| Tool | Type | Mesh Types |
|---|---|---|
| Gmsh | Open source | Tri, tet, structured |
| Triangle | Open source | 2D Delaunay |
| TetGen | Open source | 3D Delaunay |
| CGAL | Library | Various |
| ANSYS Meshing | Commercial | All types |
| Pointwise | Commercial | High quality |
Quick Reference
Mesh Type Trade-offs
| Property | Structured | Unstructured |
|---|---|---|
| Setup time | Low (simple) | Higher |
| Memory | Low | Higher |
| Solver efficiency | High | Lower |
| Geometry flexibility | Low | High |
| Adaptivity | Harder | Easier |
| Parallelism | Easy | More complex |
Quality Metrics
Comprehensive guide for evaluating and ensuring mesh quality.
Why Quality Matters
Poor mesh quality leads to:
- Reduced accuracy (truncation error increases)
- Solver convergence problems
- Non-physical solutions
- Instability
Primary Quality Metrics
Aspect Ratio
Ratio of longest to shortest edge (or dimension).
AR = L_max / L_min
For rectangle: AR = max(dx, dy) / min(dx, dy)
For triangle: AR = L_max / h_min (height to opposite edge)| 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 - 10:1 | Poor | Accuracy degradation |
| > 10:1 | Bad | Solver issues likely |
Effect by physics:
| Physics | AR Tolerance |
|---|---|
| Isotropic diffusion | AR < 5 |
| Anisotropic diffusion | Can align with anisotropy |
| Advection | Align with flow: AR ~ 10 OK |
| Boundary layer | AR ~ 100 along wall OK |
Skewness
Measures deviation from ideal shape.
For quadrilaterals/hexahedra:
Skewness = max(|90° - θ_i|) / 90°
where θ_i are the angles at vertices
Ideal: all angles = 90°, skewness = 0For triangles:
Equilateral skewness:
Skewness = (θ_max - 60°) / (180° - 60°)
= (θ_max - 60°) / 120°
Or: Skewness = 1 - (θ_min / 60°)| Skewness | Quality | Notes |
|---|---|---|
| 0 - 0.25 | Excellent | Ideal for any simulation |
| 0.25 - 0.50 | Good | Acceptable |
| 0.50 - 0.75 | Fair | May affect accuracy |
| 0.75 - 0.90 | Poor | Significant errors |
| > 0.90 | Bad | Likely problems |
Orthogonality
Alignment of cell faces with face normals.
Non-orthogonality angle θ:
θ = angle between face normal and line connecting cell centers
Perfect: θ = 0°| Non-orthogonality | Quality | Notes |
|---|---|---|
| < 20° | Excellent | Standard schemes work |
| 20° - 40° | Good | May need correction |
| 40° - 60° | Fair | Correction required |
| 60° - 70° | Poor | Strong correction needed |
| > 70° | Bad | Likely convergence issues |
Correction in FV:
Standard gradient: uses face normal
Corrected gradient: adds non-orthogonal correction termCell Volume/Area Ratio
Ratio of neighboring cell sizes.
Volume ratio = max(V_i, V_j) / min(V_i, V_j)
for adjacent cells i, j| Volume Ratio | Quality | Impact |
|---|---|---|
| < 1.5 | Excellent | Smooth variation |
| 1.5 - 2.0 | Good | Acceptable |
| 2.0 - 3.0 | Fair | May affect accuracy |
| > 3.0 | Poor | Large interpolation errors |
Element-Specific Metrics
Triangle Quality Measures
Radius ratio:
q = 2 × r_inscribed / r_circumscribed
Ideal: q = 1 (equilateral)
Acceptable: q > 0.5
Poor: q < 0.25Area-based:
q = 4√3 × Area / (L₁² + L₂² + L₃²)
Ideal: q = 1 (equilateral)Minimum angle:
θ_min ≥ 20° (minimum recommended)
θ_min ≥ 30° (good quality)Quadrilateral Quality Measures
Jacobian ratio:
J_ratio = J_min / J_max
where J is the Jacobian at each corner
Ideal: J_ratio = 1 (parallelogram)
Acceptable: J_ratio > 0.3
Poor: J_ratio < 0.1Warpage (3D faces):
Maximum angle between sub-triangle normals
Flat: warpage = 0°
Acceptable: warpage < 15°Tetrahedral Quality Measures
Radius ratio:
q = 3 × r_inscribed / r_circumscribed
Ideal: q = 1 (regular tetrahedron)
Acceptable: q > 0.2Dihedral angles:
θ_min: smallest angle between faces
θ_max: largest angle between faces
Good: 40° < θ < 120°Volume ratio:
q = 6√2 × Volume / sum(face_areas × opposite_edge_length)
Ideal: q = 1
Acceptable: q > 0.2Hexahedral Quality Measures
Jacobian:
J_min / J_max at all integration points
Good: > 0.3
Poor: < 0.1
Invalid: ≤ 0 (inverted element)Edge ratio:
max(L_edge) / min(L_edge)
Good: < 5
Acceptable: < 10Quality Thresholds by Application
Phase-Field Simulations
| Metric | Threshold | Reason |
|---|---|---|
| Aspect ratio | < 3:1 | Interface resolution |
| Skewness | < 0.5 | Gradient accuracy |
| Size ratio | < 2.0 | Smooth interpolation |
Fluid Dynamics
| Region | AR Limit | Skewness Limit |
|---|---|---|
| Interior | < 5 | < 0.85 |
| Boundary layer | < 100 (aligned) | < 0.75 |
| Wake region | < 10 | < 0.80 |
Structural Analysis
| Metric | Threshold |
|---|---|
| Jacobian ratio | > 0.2 |
| Aspect ratio | < 10 |
| Warpage | < 15° |
Heat Transfer
| Metric | Threshold |
|---|---|
| Aspect ratio | < 5 |
| Non-orthogonality | < 40° |
| Size ratio | < 2.0 |
Improving Mesh Quality
Smoothing Techniques
Laplacian smoothing:
Move node to average of neighbors
x_new = (1/n) × Σ x_neighbors
Caution: can invert elements
Use with quality checkOptimization-based smoothing:
Minimize: Σ (quality penalty)
Subject to: no inverted elementsLocal Reconnection
Edge/face swapping:
If swap improves minimum quality:
Perform swapNode insertion/deletion:
Insert node in poor element
Delete nodes causing poor qualityRefinement/Coarsening
Poor quality from size variation:
Refine large cells
Coarsen too-fine cells
Maintain 2:1 balanceQuality Checking Workflow
Pre-Solve Check
1. Statistics:
- Minimum/maximum of each metric
- Distribution histograms
- Location of worst elements
2. Thresholds:
- Flag elements below threshold
- Count problem elements
- Identify clusters
3. Visualization:
- Color by quality metric
- Highlight problem regions
- Check boundary layers
During Solve (Adaptive)
def check_quality_runtime(mesh):
"""Check quality at runtime for adaptive methods."""
min_quality = compute_min_quality(mesh)
if min_quality < threshold_critical:
raise MeshQualityError("Mesh degenerated")
if min_quality < threshold_warning:
log_warning(f"Poor mesh quality: {min_quality}")
trigger_remesh()Post-Solve Verification
1. Compare solution smoothness to mesh quality 2. Check conservation errors vs quality 3. Identify if quality limited accuracy
Quality Metrics Implementation
def triangle_quality(p1, p2, p3):
"""Compute triangle quality measures."""
# Edge lengths
L1 = np.linalg.norm(p2 - p1)
L2 = np.linalg.norm(p3 - p2)
L3 = np.linalg.norm(p1 - p3)
# Semi-perimeter and area
s = (L1 + L2 + L3) / 2
area = np.sqrt(s * (s - L1) * (s - L2) * (s - L3))
# Inscribed and circumscribed radii
r_in = area / s
r_circ = L1 * L2 * L3 / (4 * area)
# Quality measures
radius_ratio = 2 * r_in / r_circ
area_quality = 4 * np.sqrt(3) * area / (L1**2 + L2**2 + L3**2)
# Angles
angles = []
for i, (a, b, c) in enumerate([(L1, L2, L3), (L2, L3, L1), (L3, L1, L2)]):
cos_angle = (b**2 + c**2 - a**2) / (2 * b * c)
angles.append(np.arccos(np.clip(cos_angle, -1, 1)))
min_angle = np.min(angles) * 180 / np.pi
max_angle = np.max(angles) * 180 / np.pi
return {
'radius_ratio': radius_ratio,
'area_quality': area_quality,
'min_angle': min_angle,
'max_angle': max_angle,
'aspect_ratio': max(L1, L2, L3) / min(L1, L2, L3),
'skewness': (max_angle - 60) / 120
}Quick Reference
Acceptable Ranges Summary
| Metric | Good | Acceptable | Poor |
|---|---|---|---|
| Aspect ratio | < 3 | < 5 | > 10 |
| Skewness | < 0.25 | < 0.50 | > 0.75 |
| Non-orthogonality | < 20° | < 40° | > 60° |
| Min angle (tri) | > 30° | > 20° | < 10° |
| Jacobian ratio | > 0.5 | > 0.2 | < 0.1 |
| Volume ratio | < 1.5 | < 2.0 | > 3.0 |
Priority by Problem Type
| Problem | Priority Metrics |
|---|---|
| FD diffusion | Aspect ratio, uniformity |
| FV flow | Skewness, non-orthogonality |
| FE structural | Jacobian, aspect ratio |
| Phase-field | Aspect ratio, size ratio |
| Boundary layer | Near-wall AR, growth rate |
#!/usr/bin/env python3
import argparse
import json
import math
import sys
from typing import Dict, Optional
def compute_grid(
length: float,
resolution: int,
dims: int,
dx: Optional[float],
) -> Dict[str, object]:
if length <= 0:
raise ValueError("length must be positive")
if resolution <= 0:
raise ValueError("resolution must be positive")
if dims <= 0:
raise ValueError("dims must be positive")
if dx is None:
dx = length / resolution
if dx <= 0:
raise ValueError("dx must be positive")
counts = [int(math.ceil(length / dx)) for _ in range(dims)]
notes = []
if dx * counts[0] < length:
notes.append("Grid does not fully cover length; consider smaller dx.")
return {
"dx": dx,
"counts": counts,
"notes": notes,
}
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Estimate grid spacing and cell counts.",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
parser.add_argument("--length", type=float, required=True, help="Domain length")
parser.add_argument(
"--resolution",
type=int,
required=True,
help="Target number of cells along length",
)
parser.add_argument("--dims", type=int, default=2, help="Dimensions (1,2,3)")
parser.add_argument("--dx", type=float, default=None, help="Override dx")
parser.add_argument("--json", action="store_true", help="Emit JSON output")
return parser.parse_args()
def main() -> None:
args = parse_args()
try:
result = compute_grid(
length=args.length,
resolution=args.resolution,
dims=args.dims,
dx=args.dx,
)
except ValueError as exc:
print(str(exc), file=sys.stderr)
sys.exit(2)
payload = {
"inputs": {
"length": args.length,
"resolution": args.resolution,
"dims": args.dims,
"dx": args.dx,
},
"results": result,
}
if args.json:
print(json.dumps(payload, indent=2, sort_keys=True))
return
print("Grid sizing")
print(f" dx: {result['dx']:.6g}")
print(f" counts: {result['counts']}")
for note in result["notes"]:
print(f" note: {note}")
if __name__ == "__main__":
main()
#!/usr/bin/env python3
import argparse
import json
import math
import sys
from typing import Dict
def compute_quality(dx: float, dy: float, dz: float) -> Dict[str, object]:
for name, val in [("dx", dx), ("dy", dy), ("dz", dz)]:
if not math.isfinite(val) or val <= 0:
raise ValueError(f"{name} must be a finite positive number, got {val}")
sizes = [dx, dy, dz]
aspect_ratio = max(sizes) / min(sizes)
skewness = (max(sizes) - min(sizes)) / max(sizes)
flags = []
if aspect_ratio > 5.0:
flags.append("high_aspect_ratio")
if skewness > 0.5:
flags.append("high_skewness")
return {
"aspect_ratio": aspect_ratio,
"skewness": skewness,
"quality_flags": flags,
}
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Estimate mesh quality metrics from spacing.",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
parser.add_argument("--dx", type=float, required=True, help="Cell size in x")
parser.add_argument("--dy", type=float, required=True, help="Cell size in y")
parser.add_argument("--dz", type=float, required=True, help="Cell size in z")
parser.add_argument("--json", action="store_true", help="Emit JSON output")
return parser.parse_args()
def main() -> None:
args = parse_args()
try:
result = compute_quality(args.dx, args.dy, args.dz)
except ValueError as exc:
print(str(exc), file=sys.stderr)
sys.exit(2)
payload = {
"inputs": {"dx": args.dx, "dy": args.dy, "dz": args.dz},
"results": result,
}
if args.json:
print(json.dumps(payload, indent=2, sort_keys=True))
return
print("Mesh quality")
print(f" aspect_ratio: {result['aspect_ratio']:.6g}")
print(f" skewness: {result['skewness']:.6g}")
for flag in result["quality_flags"]:
print(f" flag: {flag}")
if __name__ == "__main__":
main()
Related skills
FAQ
Does it generate meshes?
No, it provides sizing recommendations and quality checks only; it does not generate unstructured meshes.
What are the quality thresholds?
Aspect ratio typically under 5:1 and skewness under 0.8.