科研 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.

发布者 Codar安全审核通过v0.1.0更新于 2026-11-18

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 fluids 1.3.1; verify with help() or dir() 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

  1. Always check Reynolds number before selecting friction factor correlation
  2. Validate results against known test cases or handbook values
  3. Use consistent units - fluids uses SI units throughout
  4. Consider safety factors when sizing pumps (typically 10-15% margin)
  5. Check physical limits - verify Mach number < 0.3 for incompressible assumption
  6. Use appropriate roughness values from literature (Moody, Crane TP-410)
  7. 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

MaterialRoughness ε (m)
Drawn tubing0.0000015
Commercial steel0.000045
Galvanized iron0.00015
Cast iron0.00026
Concrete0.0003 to 0.003
Riveted steel0.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>) and help(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 fluids 1.3.1; a different installed version may differ.
  • The pump affinity laws here are algebraic, not calls into the library — fluids.pump has 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

示例提示词

帮我用fluids库算一下这段DN100管道的沿程压降和摩擦因子。

所属插件

热流体与能源动力面向热流体与能源动力研究:流体与热力学计算(fluids、thermo、CoolProp、REFPROP)、泵与流体机械设计及汽蚀分析、管网与系统集成、OpenFOAM/ANSYS/COMSOL 仿真、Cantera 燃烧计算、单位与物性工具。

安装该插件会一并获得同领域的 36 个 Skill / MCP。

同插件的其他科研 Skill

常见问题

管道流动与泵选型计算能做什么?

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 收录的每个版本都会记录内容摘要与权限声明,当前版本已通过安全审核。