科研 Skill
管道流动与泵选型计算
fluids-package
Computes pipe flow, pump sizing, friction factor, and compressible flow results with the fluids Python package. Use for quick, code-based fluid mechanics calculations.
SKILL.md
Fluids Package Skill
Overview
The fluids library is a comprehensive Python package for mechanical and chemical engineers working with fluid flow problems. It provides validated correlations and functions for:
- Pipe flow and friction factor calculations
- Pump sizing and performance analysis
- Compressible and incompressible flow
- Heat exchanger design
- Two-phase flow
- Pressure drop calculations
- Fluid properties
The library implements over 100 correlations from the literature with extensive validation against published test cases.
Prerequisites
- Python 3 with network access to install the package below.
- The function names and module locations below were checked against
fluids1.3.1; verify withhelp()ordir()before relying on an unfamiliar function, since module organization has changed between releases.
Installation
pip install fluids
For full functionality including optimization routines:
pip install fluids[complete]
Key Modules
fluids.core
Core utilities and dimensional analysis functions, including Reynolds and Mach.
fluids.friction
Friction factor calculations for pipe flow including:
- Darcy-Weisbach equation
- Colebrook-White correlation
- Moody diagram implementations
- Turbulent and laminar flow regimes
fluids.pump
Pump performance calculations:
- Specific speed and specific diameter
- Motor and efficiency lookups
- NPSH-related and affinity-law-style scaling (affinity laws themselves are simple algebra, not separate functions — see below)
fluids.compressible
Compressible flow calculations:
- Mach number relationships (via
fluids.core.Mach) - Choked flow conditions
- Isentropic flow
- Normal shock waves
fluids.fittings
Pressure drop through valves, fittings, and pipe components.
Common Functions with Engineering Context
Reynolds Number Calculation
The Reynolds number (Re) determines flow regime and is fundamental to all pipe flow calculations.
from fluids.core import Reynolds
# For pipe flow: Re = ρVD/μ
Re = Reynolds(V=2.5, D=0.05, rho=1000, mu=0.001)
# Result: 125000 (turbulent flow)
# Interpretation:
# Re < 2300: Laminar flow
# 2300 < Re < 4000: Transition
# Re > 4000: Turbulent flow
Friction Factor (Darcy-Weisbach)
The friction factor (f) is used in the Darcy-Weisbach equation: ΔP = f(L/D)(ρV²/2)
from fluids.friction import friction_factor
# Colebrook-White correlation (implicit, most accurate)
f = friction_factor(Re=125000, eD=0.0001) # eD = roughness/diameter
# Result: ~0.0178
# Moody correlation (explicit approximation) is named `Moody`, not `friction_factor_Moody`
from fluids.friction import Moody
f_moody = Moody(Re=125000, eD=0.0001)
# For laminar flow (Re < 2300):
f_laminar = friction_factor(Re=1500, eD=0.0001)
# Result: 0.0427 (f = 64/Re)
Head Loss in Pipes
Calculate pressure drop and head loss in piping systems. head_from_P is a top-level function
(from fluids import head_from_P), not part of fluids.friction.
from fluids.friction import friction_factor
from fluids.core import Reynolds
from fluids import head_from_P
# Given: Water flow through steel pipe
D = 0.1 # m, pipe diameter
L = 100 # m, pipe length
V = 2.0 # m/s, velocity
rho = 1000 # kg/m³, density
mu = 0.001 # Pa·s, viscosity
epsilon = 0.000045 # m, roughness (steel)
# Step 1: Calculate Reynolds number
Re = Reynolds(V=V, D=D, rho=rho, mu=mu)
# Step 2: Calculate friction factor
eD = epsilon / D
f = friction_factor(Re=Re, eD=eD)
# Step 3: Calculate pressure drop
# Darcy-Weisbach: ΔP = f(L/D)(ρV²/2)
dP = f * (L/D) * (rho * V**2 / 2)
# Step 4: Convert to head loss
h_loss = head_from_P(dP, rho) # meters of fluid
print(f"Reynolds: {Re:.0f}")
print(f"Friction factor: {f:.5f}")
print(f"Pressure drop: {dP:.0f} Pa")
print(f"Head loss: {h_loss:.2f} m")
Pump Affinity Laws
The fluids.pump module does not provide affinity_law_volume / affinity_law_head /
affinity_law_power functions — they do not exist in the package. The affinity laws are plain
algebra; apply them directly:
# Original pump operating point
Q1 = 100 # m³/h, flow rate
H1 = 50 # m, head
P1 = 20 # kW, power
N1 = 1450 # rpm, speed
# New speed
N2 = 1750 # rpm
# Affinity laws (constant impeller diameter):
# Q2/Q1 = N2/N1
# H2/H1 = (N2/N1)²
# P2/P1 = (N2/N1)³
Q2 = Q1 * (N2 / N1)
H2 = H1 * (N2 / N1) ** 2
P2 = P1 * (N2 / N1) ** 3
print(f"New flow: {Q2:.1f} m³/h")
print(f"New head: {H2:.1f} m")
print(f"New power: {P2:.1f} kW")
Specific Speed Calculations
Specific speed (Ns) characterizes pump type and efficiency.
from fluids.pump import specific_speed
# Pump operating conditions
Q = 0.05 # m³/s, flow rate
H = 40 # m, head
N = 1450 # rpm, rotational speed
# fluids.pump.specific_speed(Q, H, n) returns n*sqrt(Q)/H**0.75 in mixed units
# (rpm, m^3/s, m) — it is NOT the small dimensionless Ns (0.1-4) used in some
# textbooks. Interpret the number against charts that use the same unit
# convention, or compute the dimensionless form yourself if that is what you need.
Ns = specific_speed(Q, H, N)
print(f"Specific speed (rpm, m^3/s, m convention): {Ns:.1f}")
Compressible Flow - Mach Number
For gas flow in pipes and nozzles. Mach lives in fluids.core, not fluids.compressible.
from fluids.core import Mach
# Calculate Mach number from velocity
V = 200 # m/s, velocity
c = 340 # m/s, speed of sound in air at 15°C
Ma = Mach(V, c)
# Result: 0.588
# Flow classification:
# Ma < 0.3: Incompressible
# 0.3 < Ma < 0.8: Subsonic
# 0.8 < Ma < 1.2: Transonic
# Ma > 1.2: Supersonic
Compressible Flow - Choked Flow
Determine if flow is choked in a nozzle or orifice.
from fluids.compressible import P_critical_flow
# Gas properties
P_upstream = 500000 # Pa, upstream pressure
k = 1.4 # heat capacity ratio (air)
# Critical pressure for choked flow
P_crit = P_critical_flow(P=P_upstream, k=k)
# Result: ~264,000 Pa
# If downstream pressure < P_crit, flow is choked
P_downstream = 200000 # Pa
if P_downstream < P_crit:
print("Flow is choked - mass flow is at maximum")
print(f"Critical pressure: {P_crit:.0f} Pa")
else:
print("Flow is not choked")
Complete Engineering Examples
Example 1: Pump Selection and System Curve
import numpy as np
from fluids.friction import friction_factor
from fluids.core import Reynolds
import matplotlib.pyplot as plt
def system_curve(Q_range, static_head, pipe_specs):
"""
Calculate system head curve for a piping system.
Parameters:
-----------
Q_range : array, flow rates (m³/s)
static_head : float, static lift (m)
pipe_specs : dict with keys:
- L: pipe length (m)
- D: pipe diameter (m)
- epsilon: roughness (m)
- rho: fluid density (kg/m³)
- mu: fluid viscosity (Pa·s)
Returns:
--------
H_system : array, required head at each flow rate (m)
"""
L = pipe_specs['L']
D = pipe_specs['D']
rho = pipe_specs['rho']
mu = pipe_specs['mu']
epsilon = pipe_specs['epsilon']
# Calculate cross-sectional area
A = np.pi * D**2 / 4
H_system = np.zeros_like(Q_range)
for i, Q in enumerate(Q_range):
if Q == 0:
H_system[i] = static_head
continue
# Calculate velocity
V = Q / A
# Reynolds number
Re = Reynolds(V=V, D=D, rho=rho, mu=mu)
# Friction factor
eD = epsilon / D
f = friction_factor(Re=Re, eD=eD)
# Friction head loss (Darcy-Weisbach)
h_friction = f * (L/D) * (V**2 / (2*9.81))
# Total system head
H_system[i] = static_head + h_friction
return H_system
# Define system
pipe_specs = {
'L': 200, # m
'D': 0.15, # m
'epsilon': 0.000045, # m (steel)
'rho': 1000, # kg/m³
'mu': 0.001 # Pa·s
}
static_head = 30 # m
# Generate system curve
Q_range = np.linspace(0, 0.1, 50) # m³/s
H_system = system_curve(Q_range, static_head, pipe_specs)
# Example pump curve (quadratic fit)
# H = H0 - A*Q - B*Q²
H0 = 80 # m, shutoff head
A = 200 # head loss coefficient
B = 3000 # quadratic coefficient
H_pump = H0 - A*Q_range - B*Q_range**2
# Find operating point (intersection)
idx = np.argmin(np.abs(H_pump - H_system))
Q_op = Q_range[idx]
H_op = H_system[idx]
print(f"Operating Point:")
print(f" Flow rate: {Q_op*3600:.1f} m³/h ({Q_op:.4f} m³/s)")
print(f" Head: {H_op:.1f} m")
Example 2: Parallel Pump Configuration
def parallel_pumps(Q_total, n_pumps, single_pump_curve):
"""
Calculate operating point for parallel pump configuration.
For pumps in parallel:
- Flow rates add: Q_total = n * Q_single
- Head remains the same: H_total = H_single
"""
# Single pump flow rate
Q_single = Q_total / n_pumps
# Head from single pump curve
H = single_pump_curve(Q_single)
return Q_single, H
# Single pump curve: H = 60 - 500*Q² (simplified)
def pump_curve(Q):
return 60 - 500*Q**2
# System requires 150 m³/h at 40 m head
Q_required = 150/3600 # m³/s
n_pumps = 2
Q_single, H_operating = parallel_pumps(Q_required, n_pumps, pump_curve)
print(f"Parallel Pump Configuration ({n_pumps} pumps):")
print(f" Total flow: {Q_required*3600:.1f} m³/h")
print(f" Flow per pump: {Q_single*3600:.1f} m³/h")
print(f" Operating head: {H_operating:.1f} m")
Example 3: Friction Factor Validation
from fluids.friction import friction_factor
from fluids.core import Reynolds
# Test Case 1: Laminar Flow (Poiseuille)
# Analytical solution: f = 64/Re
Re_laminar = 1000
f_calculated = friction_factor(Re=Re_laminar, eD=0)
f_analytical = 64/Re_laminar
print("Test 1: Laminar Flow")
print(f" Re = {Re_laminar}")
print(f" f (calculated) = {f_calculated:.6f}")
print(f" f (analytical) = {f_analytical:.6f}")
assert abs(f_calculated - f_analytical) < 1e-9, "Laminar flow test failed"
print(" PASSED\n")
# Test Case 2: Turbulent Flow - Smooth Pipe
# From Moody diagram: Re=1e5, smooth pipe -> f approx 0.0183
Re_turbulent = 1e5
f_smooth = friction_factor(Re=Re_turbulent, eD=0)
print("Test 2: Turbulent Flow (Smooth Pipe)")
print(f" Re = {Re_turbulent:.0f}")
print(f" f (calculated) = {f_smooth:.6f}")
# Test Case 3: Crane TP-410 reference case
D = 0.1541 # m (6-inch Schedule 40 ID)
V = 3.05 # m/s
rho = 998 # kg/m³
mu = 0.001 # Pa·s
epsilon = 0.000045 # m (steel)
Re_crane = Reynolds(V=V, D=D, rho=rho, mu=mu)
eD_crane = epsilon/D
f_crane = friction_factor(Re=Re_crane, eD=eD_crane)
print("Test 3: Crane TP-410 Example 4-9")
print(f" Re = {Re_crane:.0f}, eD = {eD_crane:.6f}, f = {f_crane:.6f} (Crane TP-410 reports ~0.0172)")
Example 4: Compressible Flow in Pipe
from fluids.compressible import isothermal_gas
# Gas pipeline calculation
# Problem: Natural gas (methane) pipeline
P1 = 5e6 # Pa, inlet pressure
T = 288.15 # K, temperature (15°C)
L = 5000 # m, pipeline length
D = 0.5 # m, diameter
m = 10 # kg/s, mass flow rate
MW = 16.04e-3 # kg/mol, molecular weight (CH4)
R = 8.314 # J/(mol*K)
Z = 1 # compressibility factor, ideal-gas approximation
# isothermal_gas() takes rho and fd as required positional/keyword args and
# does not accept T or Z directly — compute an inlet density from the ideal
# gas law first, and pass only rho, fd, and the known geometry/flow terms.
rho1 = P1 * MW / (Z * R * T) # kg/m^3, gas density at inlet conditions
fd = 0.012 # Darcy friction factor, assumed here; use fluids.friction for a measured pipe
P2 = isothermal_gas(rho=rho1, fd=fd, P1=P1, L=L, D=D, m=m)
print("Gas Pipeline Calculation:")
print(f" Inlet pressure: {P1/1e6:.2f} MPa")
print(f" Outlet pressure: {P2/1e6:.2f} MPa")
print(f" Pressure drop: {(P1-P2)/1e6:.2f} MPa")
Best Practices
- Always check Reynolds number before selecting friction factor correlation
- Validate results against known test cases or handbook values
- Use consistent units - fluids uses SI units throughout
- Consider safety factors when sizing pumps (typically 10-15% margin)
- Check physical limits - verify Mach number < 0.3 for incompressible assumption
- Use appropriate roughness values from literature (Moody, Crane TP-410)
- Verify a function exists before relying on an example -
dir(module)or the official docs beat guessing at a plausible name.
Common Pipe Roughness Values
| Material | Roughness ε (m) |
|---|---|
| Drawn tubing | 0.0000015 |
| Commercial steel | 0.000045 |
| Galvanized iron | 0.00015 |
| Cast iron | 0.00026 |
| Concrete | 0.0003 to 0.003 |
| Riveted steel | 0.0009 to 0.009 |
Troubleshooting
Issue: Friction factor doesn't converge
- Cause: Invalid Reynolds number or ε/D ratio
- Solution: Check that Re > 0 and 0 ≤ ε/D < 0.5
Issue: AttributeError or TypeError on an imported function
- Cause: The function name, module, or signature does not match this version of
fluids. - Solution: Run
dir(fluids.<module>)andhelp(fluids.<module>.<name>)to confirm the real signature before trusting an example (including the ones in this file).
Issue: Compressible flow results unrealistic
- Cause: Mach number > 0.3 but using incompressible equations
- Solution: Use compressible flow functions from fluids.compressible
Limitations
- Function names and module locations in this file were verified against
fluids1.3.1; a different installed version may differ. - The pump affinity laws here are algebraic, not calls into the library —
fluids.pumphas no built-in affinity-law function.
References
- Crane Technical Paper 410 (TP-410): "Flow of Fluids Through Valves, Fittings, and Pipe"
- Moody, L.F. (1944): "Friction factors for pipe flow"
- Colebrook, C.F. (1939): "Turbulent flow in pipes"
- Karassik's Pump Handbook (4th Edition)
- GPSA Engineering Data Book (14th Edition)
Further Reading
- Official documentation: https://fluids.readthedocs.io/
- Source code: https://github.com/CalebBell/fluids
- Chemical Engineering Design Library: https://chemicals.readthedocs.io/
示例提示词
帮我用fluids库算一下这段DN100管道的沿程压降和摩擦因子。
所属插件
安装该插件会一并获得同领域的 36 个 Skill / MCP。
同插件的其他科研 Skill
- ANSYS Fluent CFD仿真自动化Automates ANSYS Fluent CFD setup, meshing, and batch runs via Python scripting, journal files, and the PyAnsys ecosystem. Use when a user wants to script or automate an ANSYS Fluent simulation.
- Cantera燃烧仿真Runs Cantera combustion simulations: flame temperature, ignition delay, laminar flame speed, PSR. Use for mechanism-based combustion analysis tasks.
- 离心泵气蚀风险评估Calculates NPSHa and NPSHr and assesses cavitation risk for centrifugal pumps, with prevention and detection guidance. Use when sizing suction piping or diagnosing pump cavitation.
- 气蚀评估物性数据库Looks up vapor pressure, NPSHr data, and correlations for cavitation risk assessment in pumps. Use when cavitation-analysis needs reference property or NPSHr data.
- 离心泵设计计算Designs centrifugal pumps from first principles using Euler equations, velocity triangles, and specific speed. Use for impeller sizing or new centrifugal pump design.
- COMSOL多物理场耦合仿真Sets up coupled fluid-structure interaction simulations in COMSOL Multiphysics, focused on pump vibration analysis. Use when a user wants to script or automate a COMSOL FSI model.
- CoolProp流体物性查询Queries thermodynamic and transport properties for 100+ pure and pseudo-pure fluids via the CoolProp library. Use when a calculation needs fluid density, viscosity, or enthalpy data.
- 工程计算环境初始化Sets up a Python session with engineering constants, Pint units, and plotting defaults. Use at the start of a calculation session.
- 流体计算数值错误校验Handles common numerical errors in fluid calculations, such as division by zero and out-of-range physical values, with validation checks. Use when fluid code fails or returns unphysical results.
- 流体力学分析工作流Guides a systematic fluid dynamics analysis from problem setup and domain definition through model selection to validation. Use when planning a CFD or analytical fluid mechanics study end to end.
- 经验公式流体物性速算Computes quick fluid property estimates (density, viscosity, vapor pressure) from empirical correlations without needing a database. Use for fast order-of-magnitude property checks.
- 工程工具与数据库清点Enumerates installed Python packages, databases, and simulation tools available in the current environment. Use at the start of a session to avoid recommending unavailable tools.
- 管路元件损失系数查询Looks up loss coefficients (K-values) and equivalent lengths for pipes, valves, and fittings in pump and piping systems. Use when computing system head loss.
- 流体与材料物性查询Looks up temperature-dependent fluid viscosities, densities, and other material properties for pump and heat-transfer calculations. Use when a calculation needs property data at a given temperature.
- 泵性能曲线绘制Creates professional engineering plots such as pump performance curves, CFD velocity contours, and publication-quality figures with matplotlib. Use when a result needs a plotted figure.
- NASA大气与航空流体数据Accesses atmospheric property profiles and standard-atmosphere models from NASA Earthdata for high-altitude and aerospace fluid analysis. Use when a task needs altitude-dependent atmospheric data.
- 管网图论建模Models hydraulic piping networks and multi-pump systems as graphs using NetworkX flow algorithms. Use for analyzing flow distribution across a branched or looped piping network.
- REFPROP高精度物性查询Queries high-accuracy thermodynamic and transport properties from the commercial NIST REFPROP database. Use when a calculation needs reference-quality fluid property data and REFPROP is licensed.
- 数值数组计算Performs numerical array operations with NumPy: velocity field processing, pump curve interpolation, linear systems, and matrix methods. Use for general numerical computation in engineering code.
- OpenFOAM仿真与后处理Runs and post-processes OpenFOAM CFD simulations with PyFoam, pyvista, and vtk for mesh setup, solver control, and visualization. Use for scripted OpenFOAM workflows outside ParaView.
- 泵性能曲线与相似定律Generates and interprets pump H-Q/efficiency/power/NPSH curves, applies affinity laws, and predicts off-design performance. Use for pump curve analysis.
- 工程单位换算与量纲分析Handles engineering units with automatic conversion and dimensional-consistency checking using the Pint library. Use whenever a calculation mixes units or needs unit safety.
- 容积式泵设计分析Designs and analyzes gear, piston, and screw positive-displacement pumps, including volumetric efficiency and slip. Use when the pump is positive-displacement rather than centrifugal.
- 泵效率优化Maximizes pump efficiency through hydraulic design changes and operational strategies such as trimming, VFD control, and system matching. Use when a pump is running inefficiently.
常见问题
管道流动与泵选型计算能做什么?
Computes pipe flow, pump sizing, friction factor, and compressible flow results with the fluids Python package. Use for quick, code-based fluid mechanics calculations。
如何安装管道流动与泵选型计算?
在科搭 Codar 左侧点击「插件」,在「组件」页签搜索「管道流动与泵选型计算」并安装;在 Claude Code 或 Codex 中可以发送本页的安装提示词,或下载 Skill 包后解压到 ~/.claude/skills 或 ~/.codex/skills。
管道流动与泵选型计算需要哪些权限?
该科研 Skill没有声明额外权限;执行具体操作时仍由 Agent 按自身规则请求确认。
管道流动与泵选型计算经过官方审核吗?
是。SpeedSkills 收录的每个版本都会记录内容摘要与权限声明,当前版本已通过安全审核。