科研 Skill
SciPy工程参数优化
scipy-optimization
Applies scipy.optimize methods, including constrained, global, and multi-objective optimization, to engineering design problems. Use when a design problem needs numerical optimization.
SKILL.md
SciPy Optimization for Engineering Design
Overview
The scipy.optimize module provides a comprehensive suite of optimization algorithms for solving engineering design problems. This skill focuses on applying these methods to pump design optimization, system parameter tuning, and performance analysis.
Key capabilities:
- Unconstrained optimization: Find optimal parameters without restrictions
- Constrained optimization: Optimize with design constraints and bounds
- Curve fitting: Fit models to experimental data
- Global optimization: Find global minima in multi-modal problems
- Multi-objective optimization: Balance competing design objectives
Optimization Methods
1. minimize() - Unconstrained and Constrained Optimization
The workhorse function for most optimization tasks.
from scipy.optimize import minimize
import numpy as np
# Basic usage
def objective(x):
"""Objective function to minimize"""
return x[0]**2 + x[1]**2
result = minimize(objective, x0=[1.0, 1.0])
print(f"Optimal point: {result.x}")
print(f"Optimal value: {result.fun}")
Common algorithms:
'Nelder-Mead': Derivative-free, robust but slower'BFGS': Quasi-Newton method, fast for smooth functions'L-BFGS-B': BFGS with bounds'SLSQP': Sequential Least Squares with constraints'trust-constr': General constrained optimization (preferred)
2. least_squares() - Curve Fitting and Residual Minimization
Specialized for problems of the form: minimize sum(residuals^2)
from scipy.optimize import least_squares
def residuals(params, x_data, y_data):
"""Calculate residuals between model and data"""
a, b, c = params
y_model = a * x_data**2 + b * x_data + c
return y_model - y_data
# Fit quadratic to data
x_data = np.array([1, 2, 3, 4, 5])
y_data = np.array([2.1, 3.9, 9.2, 15.8, 25.1])
result = least_squares(residuals, x0=[1, 1, 1], args=(x_data, y_data))
Key features:
- Handles bounds on variables
- Robust loss functions (handles outliers)
- Efficient for large residual problems
- Returns Jacobian information
3. differential_evolution() - Global Optimization
Finds global minimum using evolutionary algorithms. Essential for multi-modal problems.
from scipy.optimize import differential_evolution
def complex_function(x):
"""Function with multiple local minima"""
return np.sin(x[0]) * np.cos(x[1]) + (x[0] - 1)**2 + (x[1] + 2)**2
# Search over bounds
bounds = [(-5, 5), (-5, 5)]
result = differential_evolution(complex_function, bounds)
When to use:
- Multiple local minima expected
- No gradient information available
- Need robust global solution
- Can afford longer computation time
4. Constrained Optimization
Optimize subject to equality and inequality constraints.
from scipy.optimize import minimize, NonlinearConstraint, LinearConstraint
def objective(x):
return x[0]**2 + x[1]**2
# Equality constraint: x[0] + x[1] = 1
def eq_constraint(x):
return x[0] + x[1] - 1
# Inequality constraint: x[0]^2 + x[1]^2 >= 0.5
def ineq_constraint(x):
return x[0]**2 + x[1]**2 - 0.5
constraints = [
{'type': 'eq', 'fun': eq_constraint},
{'type': 'ineq', 'fun': ineq_constraint}
]
result = minimize(objective, x0=[0.5, 0.5],
method='SLSQP', constraints=constraints)
Engineering Applications
1. Pump Efficiency Maximization
Optimize pump geometry (impeller diameter, blade angle, width) to maximize efficiency at design point.
Problem formulation:
- Objective: Maximize efficiency η(D, β, b)
- Constraints:
- Minimum flow rate requirement
- Maximum power consumption
- Geometric constraints (e.g., D_min ≤ D ≤ D_max)
- NPSH requirements
Approach:
def pump_efficiency(params):
"""Calculate pump efficiency (negative for minimization)"""
D, beta, b = params # diameter, blade angle, width
# Simplified efficiency model
Q = calculate_flow_rate(D, beta, b)
H = calculate_head(D, beta, b)
P = calculate_power(D, beta, b)
eta = (rho * g * Q * H) / P
return -eta # Negative for maximization
bounds = [(0.1, 0.5), (20, 45), (0.02, 0.1)] # D, beta, b
result = minimize(pump_efficiency, x0=[0.3, 30, 0.05],
method='L-BFGS-B', bounds=bounds)
2. Impeller Geometry Optimization
Optimize blade profile, shroud contour, and hub geometry for specific duty point.
Key considerations:
- Velocity triangles at inlet/outlet
- Blade loading distribution
- Cavitation performance (NPSH)
- Structural integrity (stress limits)
3. System Cost Minimization
Find optimal pump size and operating speed to minimize total lifecycle cost.
Cost components:
- Capital cost (pump + motor + VFD)
- Energy cost (operating hours × efficiency)
- Maintenance cost
- Replacement cost (NPV)
Formulation:
def total_cost(params):
"""Total lifecycle cost"""
pump_size, speed_rpm = params
# Capital cost
capital = cost_pump(pump_size) + cost_motor(pump_size, speed_rpm)
# Operating cost (20 year life)
annual_energy = operating_hours * power(pump_size, speed_rpm) * electricity_rate
operating = annual_energy * 20
# Maintenance
maintenance = maintenance_rate * capital * 20
return capital + operating + maintenance
4. Multi-Objective Optimization
Balance competing objectives (e.g., efficiency vs cost, flow vs head).
Pareto front approach:
def weighted_objectives(params, weight):
"""Combine objectives with weighting"""
eta = pump_efficiency(params)
cost = pump_cost(params)
# Normalize and combine
return -weight * eta + (1 - weight) * cost
# Sweep weights to find Pareto front
pareto_solutions = []
for w in np.linspace(0, 1, 21):
result = minimize(lambda x: weighted_objectives(x, w),
x0=[0.3, 30, 0.05], bounds=bounds)
pareto_solutions.append(result.x)
5. Curve Fitting to Experimental Data
Fit pump characteristic curves (H-Q, η-Q, P-Q) to test data.
Applications:
- Develop performance models from test data
- Extrapolate performance to off-design conditions
- Identify empirical coefficients in analytical models
Example:
from scipy.optimize import curve_fit
def pump_curve(Q, a, b, c):
"""Quadratic head-flow relationship"""
return a - b * Q - c * Q**2
# Fit to test data
Q_test = np.array([0, 50, 100, 150, 200]) # m³/h
H_test = np.array([120, 115, 105, 90, 70]) # m
params, covariance = curve_fit(pump_curve, Q_test, H_test)
print(f"H = {params[0]:.2f} - {params[1]:.4f}*Q - {params[2]:.6f}*Q²")
Best Practices
1. Problem Formulation
- Scale variables: Normalize to similar magnitudes (0-1 or -1 to 1)
- Choose good initial guess: Start near expected solution
- Define clear bounds: Prevent physically impossible solutions
- Formulate smooth objectives: Avoid discontinuities
2. Algorithm Selection
- Smooth, gradient-available: Use
'BFGS'or'L-BFGS-B' - With constraints: Use
'SLSQP'or'trust-constr' - Noisy/discontinuous: Use
'Nelder-Mead'or derivative-free methods - Multiple local minima: Use
differential_evolutionfirst, then refine - Curve fitting: Use
curve_fitorleast_squares
3. Convergence Tips
- Try multiple initial guesses
- Use reasonable tolerances (not too tight)
- Provide analytical gradients if possible
- Check optimization success flag
- Validate physical feasibility of results
4. Constraint Formulation
- Express as g(x) ≥ 0 for inequality constraints
- Express as h(x) = 0 for equality constraints
- Keep constraints smooth and differentiable
- Avoid redundant constraints
Common Pitfalls
- Poor scaling: Variables of vastly different magnitudes
- Bad initial guess: Starting far from feasible region
- Wrong algorithm: Using gradient-based methods on non-smooth functions
- Tight tolerances: Asking for more precision than achievable
- Ignoring bounds: Not constraining to physical limits
- No validation: Not checking if solution makes engineering sense
Performance Optimization Tips
- Vectorize operations: Use NumPy arrays instead of loops
- Provide Jacobians: Analytical gradients are faster and more accurate
- Use appropriate method: Don't use global optimization if local is sufficient
- Cache expensive computations: Store intermediate results
- Start with simple model: Refine complexity iteratively
Integration with Pump Design Workflow
1. Define design variables (D, β, b, ω, etc.)
2. Establish objective function (maximize η, minimize cost)
3. Define constraints (Q_min, NPSH, stress limits)
4. Set bounds (physical limits)
5. Choose optimization algorithm
6. Run optimization with multiple initial guesses
7. Validate results (CFD, analytical checks)
8. Perform sensitivity analysis
9. Generate documentation and plots
Example Workflow
import numpy as np
from scipy.optimize import minimize, differential_evolution
import matplotlib.pyplot as plt
# Step 1: Define problem
def objective(x):
D, beta = x
return -calculate_efficiency(D, beta)
def constraint_flow(x):
D, beta = x
return calculate_flow_rate(D, beta) - Q_min
def constraint_power(x):
D, beta = x
return P_max - calculate_power(D, beta)
# Step 2: Set up optimization
bounds = [(0.2, 0.6), (20, 50)]
constraints = [
{'type': 'ineq', 'fun': constraint_flow},
{'type': 'ineq', 'fun': constraint_power}
]
# Step 3: Solve with global optimizer first
result_global = differential_evolution(
objective, bounds, constraints=constraints
)
# Step 4: Refine with local optimizer
result_local = minimize(
objective, x0=result_global.x,
method='SLSQP', bounds=bounds,
constraints=constraints
)
# Step 5: Report results
print(f"Optimal diameter: {result_local.x[0]:.3f} m")
print(f"Optimal blade angle: {result_local.x[1]:.1f}°")
print(f"Maximum efficiency: {-result_local.fun:.2%}")
References
- SciPy Optimization Documentation
- Optimization Methods Tutorial
- Engineering optimization textbooks for problem formulation
- Pump design handbooks for realistic constraints and models
示例提示词
帮我用scipy.optimize优化这台泵叶轮的几何参数以提高效率。
所属插件
安装该插件会一并获得同领域的 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.
- 管道流动与泵选型计算Computes pipe flow, pump sizing, friction factor, and compressible flow results with the fluids Python package. Use for quick, code-based fluid mechanics calculations.
- 工程工具与数据库清点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.
常见问题
SciPy工程参数优化能做什么?
Applies scipy.optimize methods, including constrained, global, and multi-objective optimization, to engineering design problems. Use when a design problem needs numerical optimization。
如何安装SciPy工程参数优化?
在科搭 Codar 左侧点击「插件」,在「组件」页签搜索「SciPy工程参数优化」并安装;在 Claude Code 或 Codex 中可以发送本页的安装提示词,或下载 Skill 包后解压到 ~/.claude/skills 或 ~/.codex/skills。
SciPy工程参数优化需要哪些权限?
该科研 Skill没有声明额外权限;执行具体操作时仍由 Agent 按自身规则请求确认。
SciPy工程参数优化经过官方审核吗?
是。SpeedSkills 收录的每个版本都会记录内容摘要与权限声明,当前版本已通过安全审核。