Install
$ agentstack add skill-soljourner-claude-engineering-skills-error-handler-fluids ✓ scanned · ✓ verified, works with Claude Code, Cursor, and more.
Security review
✓ PassedNo issues found. Passed automated security review. · v0.1.0 How review works →
- ✓ Prompt-injection patterns
- ✓ Secret / credential exfiltration
- ✓ Dangerous shell & filesystem operations
- ✓ Untrusted network calls
- ✓ Known-malicious package signatures
What it can access
- ✓ Network access No
- ✓ Filesystem access No
- ✓ Shell / process execution No
- ✓ Environment & secrets No
- ✓ Dynamic code execution No
From automated source analysis of v0.1.0. “Used” means the capability is present in the source — more access means more to trust, not that it’s unsafe.
Verified badge
Passed review? Show it. Paste this badge into your README, it links to the public security report.
Reliability & compatibility
Declared compatibility
Compatibility is declared by the source manifest. End-to-end runtime verification is coming, see below.
We're building live execution health for every listing: tool-call success rate, median latency, uptime, and last-checked timestamps, measured, not self-reported. It isn't live yet, so we don't show numbers we can't stand behind.
How agent discovery & health will work →About
Error Handler for Fluid Calculations
Robust error handling and validation framework for production-ready fluid mechanics calculations. Prevents common numerical errors, validates physical bounds, and provides graceful degradation strategies.
Overview
Fluid calculations are prone to numerical instabilities and physical constraint violations. This helper provides comprehensive error handling, input validation, and debugging tools to create production-ready code.
Common Errors in Fluid Calculations
1. Division by Zero Errors
Mach Number at Zero Velocity
# Dangerous - can divide by zero
M = V / a # If a (speed of sound) = 0, this fails
Causes:
- Zero or near-zero speed of sound at extreme temperatures
- Zero velocity in stagnation point calculations
- Undefined fluid properties at phase boundaries
Prevention:
- Check denominators before division
- Use epsilon values for near-zero comparisons
- Validate property calculations
2. Invalid Reynolds Numbers
Negative Reynolds Numbers
# Can occur with invalid inputs
Re = rho * V * D / mu # If any parameter is negative
Causes:
- Negative density (unphysical)
- Negative viscosity (calculation error)
- Negative dimensions (input error)
- Invalid property correlations
Prevention:
- Validate all inputs are positive
- Check property correlation validity ranges
- Ensure dimensional consistency
3. Temperature Out of Range
Property Correlation Failures
# Most correlations have limited validity
rho = water_density(T) # Fails if T outside 0-100°C range
Causes:
- Input temperatures outside correlation validity
- Supercritical conditions
- Phase change regions
- Cryogenic or high-temperature conditions
Prevention:
- Check temperature bounds before property calculations
- Validate against correlation validity ranges
- Provide appropriate warnings
4. Pressure Below Vapor Pressure
Cavitation Risk
# Physical impossibility in liquid systems
if P T_max:
raise ValueError(f"Temperature {T}{unit} outside valid range [{T_min}, {T_max}]{unit}")
Pressure Bounds
def validate_pressure(P, P_min=0, P_max=None, allow_vacuum=False):
"""
Validate pressure is positive (or allow vacuum if specified).
Absolute pressure must be positive.
Gauge pressure can be negative (vacuum).
"""
if not allow_vacuum and P P_max:
raise ValueError(f"Pressure {P} Pa exceeds maximum {P_max} Pa")
Flow Rate Validation
def validate_flow_rate(Q, Q_min=0, Q_max=None):
"""
Validate volumetric flow rate is non-negative.
"""
if Q Q_max:
raise ValueError(f"Flow rate {Q} m³/s exceeds maximum {Q_max} m³/s")
Dimensionless Number Validation
def validate_reynolds_number(Re, warn_transition=True):
"""
Validate Reynolds number and warn about transition region.
"""
if Re max_val:
warnings.warn(f"Value {value} may cause overflow")
if math.isnan(value):
raise ValueError("Calculation resulted in NaN")
if math.isinf(value):
raise ValueError("Calculation resulted in infinity")
Error Handling Strategies
1. Try-Except Blocks
Basic Error Handling
def safe_reynolds_number(V, D, nu):
"""
Calculate Reynolds number with error handling.
"""
try:
# Validate inputs
if V 100:
errors.append(f"Velocity {V} m/s unusually high (check units)")
# Diameter
if D 10:
errors.append(f"Diameter {D} m unusually large (check units)")
# Density
if rho 20000:
errors.append(f"Density {rho} kg/m³ outside typical range")
# Viscosity
if mu 10:
errors.append(f"Viscosity {mu} Pa·s outside typical range")
# Roughness
if roughness D:
errors.append(f"Roughness {roughness} m cannot exceed diameter {D} m")
if errors:
raise ValueError("Input validation failed:\n" + "\n".join(errors))
return True
3. Graceful Degradation
Fallback Methods
def friction_factor_robust(Re, roughness, diameter, method='auto'):
"""
Calculate friction factor with multiple fallback methods.
"""
# Try exact Colebrook iteration first
if method == 'auto' or method == 'colebrook':
try:
return friction_factor_colebrook(Re, roughness, diameter, max_iter=50)
except (ValueError, RuntimeError) as e:
warnings.warn(f"Colebrook method failed: {e}, trying Swamee-Jain")
# Fallback to Swamee-Jain approximation
if method == 'auto' or method == 'swamee-jain':
try:
return friction_factor_swamee_jain(Re, roughness, diameter)
except (ValueError, RuntimeError) as e:
warnings.warn(f"Swamee-Jain failed: {e}, trying simple correlation")
# Final fallback to simple turbulent correlation
if Re >= 4000:
return 0.316 / Re**0.25
else:
return 64 / Re
4. Bounded Iterations
Safe Iterative Solvers
def solve_colebrook_safe(Re, rel_roughness, max_iter=100, tol=1e-6):
"""
Solve Colebrook equation with convergence monitoring.
"""
# Initial guess
f = 0.02
convergence_history = []
for iteration in range(max_iter):
f_old = f
# Colebrook-White equation
try:
term = rel_roughness/3.7 + 2.51/(Re * math.sqrt(f))
if term 10 and error > convergence_history[iteration-5]:
raise RuntimeError("Iteration diverging")
raise RuntimeError(f"Failed to converge after {max_iter} iterations")
Error Handling Decorators
Input Validation Decorator
def validate_positive(*arg_names):
"""
Decorator to validate that specified arguments are positive.
"""
def decorator(func):
def wrapper(*args, **kwargs):
# Get function signature
import inspect
sig = inspect.signature(func)
bound_args = sig.bind(*args, **kwargs)
bound_args.apply_defaults()
# Check specified arguments
for arg_name in arg_names:
if arg_name in bound_args.arguments:
value = bound_args.arguments[arg_name]
if value max_val:
raise ValueError(f"{param_name} = {value} exceeds maximum {max_val}")
return func(*args, **kwargs)
return wrapper
return decorator
@validate_range('temperature', min_val=0, max_val=100)
def water_density(temperature):
"""Water density with automatic temperature validation."""
return 1000 - 0.1 * temperature # Simplified correlation
Error Logging Decorator
def log_errors(logger=None):
"""
Decorator to log errors and optionally re-raise.
"""
def decorator(func):
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception as e:
import logging
log = logger or logging.getLogger(func.__module__)
log.error(f"Error in {func.__name__}: {e}", exc_info=True)
raise
return wrapper
return decorator
Logging and Debugging
Calculation Logging
import logging
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler('fluid_calculations.log'),
logging.StreamHandler()
]
)
logger = logging.getLogger('fluid_calcs')
def calculate_pressure_drop(Q, D, L, rho, mu, roughness):
"""
Calculate pressure drop with comprehensive logging.
"""
logger.info(f"Starting pressure drop calculation")
logger.debug(f"Inputs: Q={Q}, D={D}, L={L}, rho={rho}, mu={mu}, roughness={roughness}")
try:
# Calculate Reynolds number
V = 4 * Q / (math.pi * D**2)
Re = rho * V * D / mu
logger.debug(f"Velocity: {V:.3f} m/s, Reynolds: {Re:.0f}")
# Calculate friction factor
f = friction_factor(Re, roughness, D)
logger.debug(f"Friction factor: {f:.5f}")
# Calculate pressure drop
dP = f * (L/D) * (rho * V**2 / 2)
logger.info(f"Pressure drop: {dP:.2f} Pa")
return dP
except Exception as e:
logger.error(f"Calculation failed: {e}", exc_info=True)
raise
Debug Mode
class FluidCalculator:
"""
Fluid calculator with debug mode for detailed output.
"""
def __init__(self, debug=False):
self.debug = debug
def _log(self, message):
"""Internal logging."""
if self.debug:
print(f"[DEBUG] {message}")
def calculate_reynolds(self, V, D, nu):
"""Calculate Reynolds number with debug output."""
self._log(f"Input: V={V}, D={D}, nu={nu}")
# Validation
if nu < 1e-15:
self._log("Warning: viscosity very small")
Re = V * D / nu
self._log(f"Result: Re={Re}")
# Flow regime
if Re < 2300:
regime = "laminar"
elif Re < 4000:
regime = "transition"
else:
regime = "turbulent"
self._log(f"Flow regime: {regime}")
return Re
Diagnostic Tools
def diagnose_calculation_failure(func, *args, **kwargs):
"""
Diagnose why a calculation is failing.
"""
print("=" * 60)
print("CALCULATION DIAGNOSTICS")
print("=" * 60)
print(f"\nFunction: {func.__name__}")
print(f"Arguments: {args}")
print(f"Keyword arguments: {kwargs}")
# Check argument types
print("\nArgument types:")
for i, arg in enumerate(args):
print(f" arg[{i}]: {type(arg).__name__} = {arg}")
# Check for NaN/Inf
print("\nNumerical checks:")
for i, arg in enumerate(args):
if isinstance(arg, (int, float)):
if math.isnan(arg):
print(f" arg[{i}] is NaN!")
elif math.isinf(arg):
print(f" arg[{i}] is Inf!")
elif arg == 0:
print(f" arg[{i}] is zero (potential division issue)")
# Try to execute
print("\nAttempting calculation:")
try:
result = func(*args, **kwargs)
print(f" Success! Result: {result}")
return result
except Exception as e:
print(f" Failed with error: {type(e).__name__}: {e}")
import traceback
traceback.print_exc()
return None
Best Practices Summary
- Always validate inputs before calculations
- Check denominators before division operations
- Verify physical constraints (positive values, valid ranges)
- Use try-except blocks for error-prone operations
- Implement fallback methods for iterative solvers
- Log calculations for debugging and auditing
- Test edge cases (zero, very large/small values)
- Document assumptions and validity ranges
- Use decorators for consistent validation
- Provide clear error messages with context
When to Use This Helper
Essential for:
- Production code in safety-critical applications
- Automated calculation pipelines
- User-facing applications
- Long-running simulations
- Systems with varying input quality
May be overkill for:
- Quick prototypes
- Well-controlled research calculations
- Educational examples
- Single-use scripts
Additional Resources
See handler.py for complete implementation examples and best-practices.md for detailed guidance on production-ready fluid calculations.
Source & license
This open-source skill is cataloged on AgentStack and links to its original source — we do not rehost the code.
- Author: Soljourner
- Source: Soljourner/claude-engineering-skills
- License: MIT
Install and usage instructions live in the source repository linked above.
Reviews
No reviews yet, be the first.
Write a review
Versions
- v0.1.0 Imported from the upstream source.