mcpField
A
ansys-simulation

ansys-simulation

github.com/soljourner其他9572 次安装51 周前更新
代码仓库

关于 ansys-simulation

ansys-simulation 是一份使用 Python、Journal 文件和 PyAnsys 自动化 ANSYS Fluent CFD 仿真的指南,面向仿真工程师及编写仿真脚本的开发者。内容涵盖从几何导入、网格与物理设置到批量求解和后处理。

主要功能

  1. 01PyFluent 会话与仿真设置控制
  2. 02Journal 文件批处理脚本
  3. 03几何导入与网格生成流程
  4. 04湍流、边界条件及求解器配置
  5. 05结果提取与后处理
  6. 06许可证、收敛和故障排查建议

适用场景

  1. 01自动运行 Fluent 批量仿真
  2. 02改变入口速度开展参数研究
  3. 03配置网格、物理模型和边界条件
  4. 04提取并检查仿真结果

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/soljourner/claude-engineering-skills --skill ansys-simulation

安装后在 Claude Code 中输入/ansys-simulation确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

api-reference.md
examples/
batch_simulation.py
pump_cfd_setup.py
turbulence_model_config.py

详细介绍

ANSYS 仿真集成

本指南全面介绍如何使用 Python 脚本、journal 文件和 PyAnsys 生态系统自动执行 ANSYS Fluent CFD(计算流体动力学)仿真。

概述

ANSYS Fluent 是一款领先的商用 CFD 求解器,用于模拟复杂几何结构中的流体流动、热传递及相关现象。本指南涵盖以下自动化方法:

  • ANSYS Workbench:用于 CAD 集成、网格划分和工作流管理的统一平台
  • ANSYS Fluent:具备丰富物理模型的高级 CFD 求解器
  • PyAnsys:用于程序化控制的 Python API 生态系统
  • Journal 文件:用于批量操作的文本脚本

ANSYS Workbench 和 Fluent 架构

ANSYS Workbench
  • 基于项目的工作流环境
  • 集成多个 ANSYS 工具(Fluent、CFX、Mechanical 等)
  • 支持参数化研究和设计优化
  • 提供几何建模和网格划分工具(DesignModeler、SpaceClaim、Meshing)
ANSYS Fluent
  • 基于有限体积法的 CFD 求解器
  • 丰富的湍流模型(k-epsilon、k-omega SST、LES、DES)
  • 多相流计算能力
  • 热传递和燃烧建模
  • 使用 C 编写的用户自定义函数(UDF)
  • 用于脚本编写的文本用户界面(TUI)

许可要求

商业许可

ANSYS 产品需要通过 ANSYS License Manager 管理的商业许可证:

  • Fluent 许可证类型:

    • 用于并行计算的 HPC 许可证
    • 求解器许可证(按增量计费)
    • 用于前后处理的 PrepPost 许可证
  • 许可证服务器设置:

    # Set license server environment variable
    export [email protected]
    
    # Or in Windows
    set [email protected]
    
  • 许可证检出:启动 Fluent 时检出许可证,退出时归还

  • HPC 许可:并行运行需要额外许可证(通常为每 4 个核心 1 个)

学术许可
  • 提供有使用限制的学生版/教学版许可证
  • 通常限制网格规模和求解器功能
  • 需要单独的许可证文件
重要说明
  • 批量运行前务必确认许可证可用
  • 在自动化工作流中考虑许可证使用情况
  • 使用 -t 标志指定 HPC 许可所需的处理器数量

PyAnsys - Python API 简介

PyAnsys 提供了面向 Python 的 ANSYS 产品接口,支持:

  • 远程或本地会话管理
  • 以编程方式控制仿真设置
  • 数据提取和后处理
  • 与 Python 数据科学技术栈集成
安装
# Install PyFluent (for Fluent automation)
pip install ansys-fluent-core

# Install other PyAnsys packages as needed
pip install ansys-mapdl-core      # For Mechanical
pip install ansys-dpf-core        # For post-processing
pip install ansys-geometry        # For geometry operations
PyFluent 基本用法
from ansys.fluent.core import launch_fluent

# Launch Fluent session
session = launch_fluent(precision='double', processor_count=4, mode='solver')

# Access TUI commands
session.tui.file.read_case('case_file.cas')

# Execute commands
session.tui.solve.iterate(100)

# Clean exit
session.exit()
PyAnsys 主要组件
  • ansys-fluent-core:Fluent 自动化的主要软件包
  • ansys-fluent-visualization:后处理和可视化
  • ansys-geometry:CAD 操作和几何处理
  • ansys-meshing:自动化网格划分工作流

Journal 文件脚本编写

Journal 文件是基于文本的脚本,包含由 Fluent 按顺序执行的 TUI 命令。

Journal 文件格式
; Comments start with semicolon
; Commands follow TUI menu structure

/file/read-case case_file.cas

/solve/initialize/initialize-flow
/solve/iterate 1000

/file/write-data result.dat

/exit yes
运行 Journal 文件
# Run Fluent in batch mode with journal file
fluent 3ddp -g -i journal.jou > fluent.log

# Flags:
# 3ddp: 3D double precision
# -g: Run without GUI
# -i: Input journal file
# -t4: Use 4 processors
Journal 文件最佳实践
  • 文件输入/输出使用绝对路径
  • 尽可能加入错误检查
  • 添加注释以便维护
  • 批量执行前先进行交互式测试
  • 将输出重定向到日志文件以便调试

常见工作流

1. 导入几何

通过 PyFluent:

from ansys.fluent.core import launch_fluent

solver = launch_fluent(precision='double', processor_count=4)

# Import geometry
solver.tui.file.import_.cad_geometry(
    'geometry.scdoc',
    'yes'  # Confirm import
)

通过 Journal 文件:

/file/import/cad-geometry geometry.step yes
2. 网格划分设置

网格生成策略:

  • 从 CAD 提取表面网格
  • 生成体网格(四面体、六面体、多面体)
  • 对壁面边界流动进行边界层细化
  • 检查网格质量

PyFluent 网格划分:

from ansys.fluent.core import launch_fluent

meshing = launch_fluent(precision='double', processor_count=4, mode='meshing')

# Import geometry
meshing.workflow.InitializeWorkflow(WorkflowType='Watertight Geometry')

# Set meshing parameters
meshing.meshing.GlobalSettings.set_state({
    'MaxSize': 0.1,
    'MinSize': 0.001,
    'GrowthRate': 1.2
})

# Generate mesh
meshing.meshing.GenerateMesh()

# Switch to solver
solver = meshing.switch_to_solver()

Journal 文件网格划分:

/mesh/scale 0.001 0.001 0.001
/mesh/check
/mesh/repair-improve/repair
3. 物理模型设置

湍流模型:

  • k-epsilon:通用型,使用壁面函数
  • k-omega SST:更适用于不利压力梯度和边界层
  • LES/DES:用于非定常、高保真模拟的大涡模拟

材料属性:

  • 流体属性(密度、黏度、热导率)
  • 共轭传热中的固体属性

PyFluent 物理模型设置:

# Enable energy equation
solver.tui.define.models.energy('yes')

# Set turbulence model (k-omega SST)
solver.tui.define.models.viscous.kw_sst('yes')

# Define material properties
solver.tui.define.materials.change_create(
    'water-liquid',
    'water',
    'yes',
    'constant',
    998.2,  # Density
    'yes',
    'constant',
    0.001003  # Viscosity
)

# Assign material to cell zone
solver.tui.define.boundary_conditions.fluid(
    'fluid-zone',
    'yes',
    'water',
    'no',
    'no',
    'no',
    'no',
    0,
    'no',
    0,
    'no',
    0,
    'no',
    'no'
)

Journal 文件物理模型:

/define/models/energy yes no no no no
/define/models/viscous kw-sst yes
/define/materials/change-create air air yes constant 1.225 yes constant 1.7894e-05
4. 边界条件

常见边界条件类型:

  • 速度入口
  • 压力出口
  • 壁面(静止、移动、旋转)
  • 对称
  • 周期

PyFluent 边界条件设置:

# Velocity inlet
solver.tui.define.boundary_conditions.velocity_inlet(
    'inlet',
    'yes',
    'no',
    'yes',
    'yes',
    'no',
    10,  # Velocity magnitude (m/s)
    'no',
    0,
    'no',
    0,
    'no',
    300,  # Temperature
    'no'
)

# Pressure outlet
solver.tui.define.boundary_conditions.pressure_outlet(
    'outlet',
    'yes',
    'no',
    0,  # Gauge pressure
    'no',
    300,
    'no',
    'yes'
)

# Wall with no-slip
solver.tui.define.boundary_conditions.wall(
    'wall',
    'yes',
    'no',
    'no',
    0,
    'no',
    0,
    'no',
    'yes',
    'no',
    0
)
5. 求解器设置

求解方法:

  • 压力-速度耦合(SIMPLE、SIMPLEC、PISO、Coupled)
  • 离散格式(一阶、二阶迎风、QUICK)
  • 梯度计算(最小二乘、Green-Gauss)

PyFluent 求解器配置:

# Set pressure-velocity coupling
solver.tui.solve.set.p_v_coupling(24)  # 24 = Coupled

# Set discretization schemes
solver.tui.solve.set.discretization_scheme.pressure(12)  # Second order
solver.tui.solve.set.discretization_scheme.mom(1)  # Second order upwind
solver.tui.solve.set.discretization_scheme.k(1)
solver.tui.solve.set.discretization_scheme.omega(1)

# Set under-relaxation factors
solver.tui.solve.set.under_relaxation.pressure(0.3)
solver.tui.solve.set.under_relaxation.mom(0.7)

# Initialize flow field
solver.tui.solve.initialize.initialize_flow()

# Run iterations
solver.tui.solve.iterate(1000)

收敛标准:

# Set residual convergence criteria
solver.tui.solve.monitors.residual.convergence_criteria(
    '1e-6',  # continuity
    '1e-6',  # x-velocity
    '1e-6',  # y-velocity
    '1e-6',  # z-velocity
    '1e-6',  # energy
    '1e-6',  # k
    '1e-6'   # omega
)
6. 后处理

数据提取:

# Create surface for reporting
solver.tui.surface.iso_surface(
    'pressure',
    'iso-surface-1',
    'fluid-zone',
    '()',
    101325
)

# Export data
solver.tui.file.export.ascii(
    'surface-data.csv',
    'iso-surface-1',
    '()',
    'yes',
    'pressure',
    'velocity-magnitude',
    '()'
)

# Calculate force on wall
solver.tui.report.forces.wall_forces(
    'yes',
    'wall-zone',
    '()',
    'yes',
    'no',
    'yes'
)

可视化:

# Generate contour plot (requires GUI mode or visualization package)
solver.tui.display.set.contours.filled_contours('yes')
solver.tui.display.contour(
    'pressure',
    'pressure',
    0,
    0,
    'surface-1',
    '()'
)

# Save image
solver.tui.display.save_picture('pressure_contour.png')

批处理模式执行

Linux/Unix 批处理执行
#!/bin/bash
# batch_fluent.sh

# Set license server
export [email protected]

# Set number of processors
NPROCS=8

# Run Fluent in batch mode
fluent 3ddp -g -t${NPROCS} -i simulation.jou > fluent_${NPROCS}cores.log 2>&1

# Check exit status
if [ $? -eq 0 ]; then
    echo "Simulation completed successfully"
else
    echo "Simulation failed - check log file"
    exit 1
fi
Windows 批处理执行
@echo off
REM batch_fluent.bat

set [email protected]
set NPROCS=8

"C:\Program Files\ANSYS Inc\v241\fluent\ntbin\win64\fluent.exe" 3ddp -g -t%NPROCS% -i simulation.jou > fluent.log 2>&1

if %ERRORLEVEL% EQU 0 (
    echo Simulation completed successfully
) else (
    echo Simulation failed - check log file
    exit /b 1
)
基于 Python 的批处理执行
import subprocess
import os
from pathlib import Path

def run_fluent_batch(journal_file, num_procs=4, log_file='fluent.log'):
    """
    Run Fluent in batch mode with journal file.

    Args:
        journal_file: Path to journal file
        num_procs: Number of processors
        log_file: Output log file name

    Returns:
        bool: True if successful, False otherwise
    """
    # Set license server
    os.environ['ANSYSLMD_LICENSE_FILE'] = '[email protected]'

    # Build command
    cmd = [
        'fluent',
        '3ddp',           # 3D double precision
        '-g',             # No GUI
        f'-t{num_procs}', # Number of processors
        '-i', journal_file
    ]

    # Run simulation
    with open(log_file, 'w') as log:
        result = subprocess.run(
            cmd,
            stdout=log,
            stderr=subprocess.STDOUT,
            text=True
        )

    return result.returncode == 0

# Example usage
if __name__ == '__main__':
    success = run_fluent_batch(
        journal_file='simulation.jou',
        num_procs=8,
        log_file='fluent_run.log'
    )

    if success:
        print("Simulation completed successfully")
    else:
        print("Simulation failed - check log file")
参数化研究
import numpy as np
from ansys.fluent.core import launch_fluent

def parametric_study(velocities, case_file):
    """
    Run parametric study varying inlet velocity.

    Args:
        velocities: List of inlet velocities to test
        case_file: Base case file
    """
    results = {}

    for velocity in velocities:
        print(f"Running simulation with velocity = {velocity} m/s")

        # Launch Fluent
        solver = launch_fluent(precision='double', processor_count=4)

        # Read base case
        solver.tui.file.read_case(case_file)

        # Modify inlet velocity
        solver.tui.define.boundary_conditions.velocity_inlet(
            'inlet',
            'yes', 'no', 'yes', 'yes', 'no',
            velocity,
            'no', 0, 'no', 0, 'no', 300, 'no'
        )

        # Initialize and solve
        solver.tui.solve.initialize.initialize_flow()
        solver.tui.solve.iterate(500)

        # Extract results
        # (Add result extraction here)

        # Save case and data
        output_file = f'result_v{velocity}.cas.h5'
        solver.tui.file.write_case_data(output_file)

        solver.exit()

        results[velocity] = output_file

    return results

# Run parametric study
velocities = np.linspace(5, 25, 5)  # 5 to 25 m/s
results = parametric_study(velocities, 'base_case.cas.h5')

最佳实践

  1. 许可证管理:长时间批处理运行前,务必检查许可证是否可用
  2. 网格质量:求解前验证网格质量(偏斜度、纵横比)
  3. 收敛监控:设置适当的收敛标准并监控残差
  4. 文件管理:为参数化研究采用清晰的命名约定
  5. 错误处理:在自动化脚本中实施稳健的错误检查
  6. 文档编写:为 journal 文件和 Python 脚本编写详尽注释
  7. 版本控制:在版本控制中跟踪 journal 文件和脚本
  8. 测试:在正式运行前,先在小型案例上测试自动化工作流
  9. 资源管理:监控大型模拟的内存和磁盘使用情况
  10. 可复现性:记录所有设置,以确保结果可复现

故障排除

常见问题
  • 许可证检出失败:检查许可证服务器的连接和可用性
  • 网格问题:检查网格质量指标并细化有问题的区域
  • 收敛问题:调整欠松弛因子,检查边界条件的一致性
  • 内存错误:减小网格规模或使用更多节点进行并行计算
  • 文件 I/O 错误:验证文件路径和权限
调试提示
  • 先以交互方式运行,验证工作流
  • 检查 transcript 文件中的 TUI 命令语法
  • 在 journal 文件中使用 -print 标志进行调试
  • 监控残差图,了解收敛情况
  • 查看日志文件中的警告和错误消息

更多资源

  • ANSYS 文档:ANSYS 产品中的帮助系统
  • PyAnsys 文档:https://docs.pyansys.com
  • ANSYS Learning Hub:在线培训和教程
  • ANSYS Community:用户论坛和知识库
  • Fluent 用户指南:全面的理论与使用手册
  • Fluent TUI 参考:完整的 TUI 命令列表

评论

支持 Markdown