mcpField
O
openfoam-cfd

openfoam-cfd

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

关于 openfoam-cfd

面向 OpenFOAM CFD 用户的仿真指南,介绍基于有限体积法的案例配置、求解器、网格生成及后处理。还涵盖并行计算、边界条件设置和常见问题排查。

主要功能

  1. 01案例目录与字典配置
  2. 02流体、传热及多相求解器
  3. 03边界条件与湍流参数设置
  4. 04blockMesh 和 snappyHexMesh 网格生成
  5. 05ParaView 后处理与并行运行

适用场景

  1. 01配置稳态或瞬态流动案例
  2. 02设置入口、出口和湍流边界条件
  3. 03为复杂几何生成网格
  4. 04并行运行仿真并检查结果

安装

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

$npx skills add https://github.com/soljourner/claude-engineering-skills --skill openfoam-cfd

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

包含的文件

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

examples/
boundary-conditions-examples.md
README.md
examples/pipe-flow/
README.md
examples/pipe-flow/0/
epsilon
k
nut
p
U
examples/pipe-flow/constant/
transportProperties
turbulenceProperties
examples/pipe-flow/system/
blockMeshDict
controlDict
fvSchemes
fvSolution
examples/pump-impeller/
README.md
examples/pump-impeller/0/
epsilon
k
nut
omega
p
U
examples/pump-impeller/constant/
dynamicMeshDict
transportProperties
turbulenceProperties
examples/pump-impeller/system/
blockMeshDict
controlDict
fvSchemes
fvSolution
examples/scripts/
calculate_turbulence.py
generate_case.py

详细介绍

OpenFOAM CFD 集成

概述

OpenFOAM(Open Field Operation and Manipulation)是一款免费、开源的 CFD 软件包,提供一套全面的工具,用于求解复杂的流体动力学问题。它使用有限体积法对描述流体流动、热传递、湍流和化学反应的偏微分方程进行离散化并求解。

主要特性
  • 开源:采用 GPLv3 许可,完全免费使用和修改
  • 丰富的物理模型:可处理不可压缩/可压缩流、多相流、燃烧、热传递
  • 并行计算:内置基于 MPI 的并行处理支持
  • 可定制:使用 C++ 编写,可高度扩展,以支持自定义物理模型和求解器
  • 行业标准:在学术界和工业界用于研究和商业应用
架构

OpenFOAM 使用基于算例的结构,其中每个模拟都是一个独立目录,包含:

  • 初始条件和边界条件
  • 物理属性
  • 数值格式
  • 求解器设置
  • 网格数据

安装

Ubuntu/Debian 安装
选项 1:官方 Ubuntu 软件源(最新版)
# Add OpenFOAM repository
sudo sh -c "wget -O - https://dl.openfoam.org/gpg.key | apt-key add -"
sudo add-apt-repository http://dl.openfoam.org/ubuntu
sudo apt-get update

# Install OpenFOAM v11 (or latest version)
sudo apt-get install openfoam11

# Source the OpenFOAM environment
echo "source /opt/openfoam11/etc/bashrc" >> ~/.bashrc
source ~/.bashrc
选项 2:ESI-OpenCFD 版本
# Add repository
sudo sh -c "wget -O - https://dl.openfoam.com/add-debian-repo.sh | bash"

# Install OpenFOAM v2312 (or latest version)
sudo apt-get install openfoam2312-default

# Source environment
echo "source /usr/lib/openfoam/openfoam2312/etc/bashrc" >> ~/.bashrc
source ~/.bashrc
选项 3:从源代码构建
# Install dependencies
sudo apt-get install build-essential cmake git ca-certificates \
    flex libfl-dev bison zlib1g-dev libboost-system-dev \
    libboost-thread-dev libopenmpi-dev openmpi-bin \
    gnuplot libreadline-dev libncurses-dev libxt-dev \
    qt5-default libqt5x11extras5-dev libqt5help5 qttools5-dev \
    qtxmlpatterns5-dev-tools libqt5opengl5-dev freeglut3-dev \
    libscotch-dev libcgal-dev

# Clone OpenFOAM
git clone https://github.com/OpenFOAM/OpenFOAM-11.git
cd OpenFOAM-11

# Source and compile
source etc/bashrc
./Allwmake -j
验证安装
# Check OpenFOAM environment
which simpleFoam
foamInstallationTest

# Run tutorial
mkdir -p $FOAM_RUN
cp -r $FOAM_TUTORIALS/incompressible/simpleFoam/pitzDaily $FOAM_RUN/
cd $FOAM_RUN/pitzDaily
blockMesh
simpleFoam
安装 ParaView 进行后处理
# Install ParaView
sudo apt-get install paraview

# Or use OpenFOAM's reader
paraFoam

算例目录结构

每个 OpenFOAM 算例都遵循标准化目录结构:

caseDirectory/
├── 0/                      # Initial and boundary conditions
│   ├── U                   # Velocity field
│   ├── p                   # Pressure field
│   ├── T                   # Temperature field (if applicable)
│   ├── k                   # Turbulent kinetic energy
│   ├── epsilon             # Turbulent dissipation rate
│   ├── omega               # Specific dissipation rate
│   └── nut                 # Turbulent viscosity
├── constant/               # Physical properties and mesh
│   ├── polyMesh/          # Mesh data
│   │   ├── points         # Vertex coordinates
│   │   ├── faces          # Face definitions
│   │   ├── owner          # Cell ownership
│   │   ├── neighbour      # Cell neighbors
│   │   └── boundary       # Boundary patches
│   ├── transportProperties # Fluid properties
│   ├── turbulenceProperties # Turbulence model selection
│   ├── g                  # Gravity vector
│   └── regionProperties   # Multi-region properties
├── system/                 # Numerical settings
│   ├── controlDict        # Simulation control
│   ├── fvSchemes          # Discretization schemes
│   ├── fvSolution         # Solver settings
│   ├── blockMeshDict      # Mesh generation
│   ├── snappyHexMeshDict  # Advanced meshing
│   ├── decomposeParDict   # Parallel decomposition
│   └── sampleDict         # Sampling/probing
└── [time directories]/     # Results at each time step
    ├── U
    ├── p
    └── ...

关键字典

controlDict (system/controlDict)

控制模拟的执行和输出:

FoamFile
{
    version     2.0;
    format      ascii;
    class       dictionary;
    object      controlDict;
}

application     simpleFoam;      // Solver to use

startFrom       startTime;        // latestTime, firstTime
startTime       0;
stopAt          endTime;
endTime         1000;
deltaT          1;                // Time step

writeControl    timeStep;         // runTime, adjustableRunTime, cpuTime
writeInterval   100;              // Write every N steps
purgeWrite      2;                // Keep only last N time directories

writeFormat     ascii;            // binary
writePrecision  6;
writeCompression off;             // on for binary

timeFormat      general;
timePrecision   6;

runTimeModifiable true;           // Re-read dictionaries during run

// Function objects for monitoring and post-processing
functions
{
    forceCoeffs
    {
        type            forceCoeffs;
        libs            ("libforces.so");
        writeControl    timeStep;
        writeInterval   1;

        patches         (wall);
        rho             rhoInf;
        rhoInf          1.225;
        CofR            (0 0 0);
        liftDir         (0 1 0);
        dragDir         (1 0 0);
        pitchAxis       (0 0 1);
        magUInf         10;
        lRef            1;
        Aref            1;
    }

    probes
    {
        type            probes;
        libs            ("libsampling.so");
        writeControl    timeStep;
        writeInterval   1;

        fields          (p U);
        probeLocations
        (
            (0.5 0.5 0.5)
            (1.0 0.5 0.5)
        );
    }
}
fvSchemes (system/fvSchemes)

定义离散格式:

FoamFile
{
    version     2.0;
    format      ascii;
    class       dictionary;
    object      fvSchemes;
}

// Time derivatives
ddtSchemes
{
    default         steadyState;    // Euler, backward, CrankNicolson
}

// Gradient schemes
gradSchemes
{
    default         Gauss linear;   // cellLimited Gauss linear 1
    grad(p)         Gauss linear;
    grad(U)         cellLimited Gauss linear 1;
}

// Divergence schemes (convection)
divSchemes
{
    default         none;
    div(phi,U)      bounded Gauss linearUpwind grad(U);
    div(phi,k)      bounded Gauss upwind;
    div(phi,epsilon) bounded Gauss upwind;
    div(phi,omega)  bounded Gauss upwind;
    div((nuEff*dev2(T(grad(U))))) Gauss linear;
}

// Laplacian schemes (diffusion)
laplacianSchemes
{
    default         Gauss linear corrected;
}

// Interpolation schemes
interpolationSchemes
{
    default         linear;
}

// Surface normal gradient schemes
snGradSchemes
{
    default         corrected;
}

// Wall distance calculation
wallDist
{
    method          meshWave;
}
fvSolution (system/fvSolution)

求解器算法和容差:

FoamFile
{
    version     2.0;
    format      ascii;
    class       dictionary;
    object      fvSolution;
}

solvers
{
    p
    {
        solver          GAMG;           // Geometric-Algebraic Multi-Grid
        tolerance       1e-6;
        relTol          0.01;
        smoother        GaussSeidel;
        nPreSweeps      0;
        nPostSweeps     2;
        cacheAgglomeration on;
        agglomerator    faceAreaPair;
        nCellsInCoarsestLevel 10;
        mergeLevels     1;
    }

    U
    {
        solver          smoothSolver;
        smoother        GaussSeidel;
        tolerance       1e-7;
        relTol          0.1;
        nSweeps         1;
    }

    "(k|epsilon|omega)"
    {
        solver          smoothSolver;
        smoother        GaussSeidel;
        tolerance       1e-8;
        relTol          0.1;
        nSweeps         1;
    }
}

// SIMPLE algorithm for steady-state
SIMPLE
{
    nNonOrthogonalCorrectors 0;
    consistent      yes;            // SIMPLEC algorithm

    residualControl
    {
        p               1e-5;
        U               1e-5;
        "(k|epsilon|omega)" 1e-5;
    }
}

// PIMPLE algorithm for transient
PIMPLE
{
    nOuterCorrectors    50;
    nCorrectors         2;
    nNonOrthogonalCorrectors 1;

    residualControl
    {
        U               1e-5;
        p               1e-5;
    }
}

relaxationFactors
{
    fields
    {
        p               0.3;
    }
    equations
    {
        U               0.7;
        k               0.7;
        epsilon         0.7;
        omega           0.7;
    }
}
transportProperties (constant/transportProperties)

流体的物理属性:

FoamFile
{
    version     2.0;
    format      ascii;
    class       dictionary;
    object      transportProperties;
}

// Single phase
transportModel  Newtonian;

nu              [0 2 -1 0 0 0 0] 1e-05;  // Kinematic viscosity (m²/s)

// For multiphase (interFoam)
phases (water air);

water
{
    transportModel  Newtonian;
    nu              [0 2 -1 0 0 0 0] 1e-06;
    rho             [1 -3 0 0 0 0 0] 1000;
}

air
{
    transportModel  Newtonian;
    nu              [0 2 -1 0 0 0 0] 1.48e-05;
    rho             [1 -3 0 0 0 0 0] 1;
}

sigma           [1 0 -2 0 0 0 0] 0.07;  // Surface tension
turbulenceProperties (constant/turbulenceProperties)

湍流模型选择:

FoamFile
{
    version     2.0;
    format      ascii;
    class       dictionary;
    object      turbulenceProperties;
}

simulationType  RAS;  // laminar, LES, RAS (RANS)

// RANS models
RAS
{
    RASModel        kEpsilon;  // kOmegaSST, realizableKE, SpalartAllmaras

    turbulence      on;
    printCoeffs     on;
}

// LES models
LES
{
    LESModel        Smagorinsky;  // kEqn, WALE, dynamicKEqn

    turbulence      on;
    printCoeffs     on;

    delta           cubeRootVol;

    cubeRootVolCoeffs
    {
        deltaCoeff      1;
    }
}

边界条件

常见边界类型
速度 (U)

固定值(入口)

inlet
{
    type            fixedValue;
    value           uniform (1 0 0);  // 1 m/s in x-direction
}

零梯度(出口)

outlet
{
    type            zeroGradient;
}

无滑移壁面

wall
{
    type            noSlip;  // equivalent to fixedValue uniform (0 0 0)
}

滑移壁面

symmetry
{
    type            slip;
}

带速度分布的入口

inlet
{
    type            codedFixedValue;
    value           uniform (0 0 0);
    name            parabolicVelocity;
    code
    #{
        const fvPatch& boundaryPatch = patch();
        const vectorField& Cf = boundaryPatch.Cf();
        vectorField& field = *this;

        forAll(Cf, faceI)
        {
            scalar y = Cf[faceI].y();
            scalar H = 0.1;  // Channel height
            scalar Umax = 1.5;
            field[faceI] = vector(Umax * 4 * y * (H - y) / (H * H), 0, 0);
        }
    #};
}
压力 (p)

固定值(出口)

outlet
{
    type            fixedValue;
    value           uniform 0;
}

零梯度(入口)

inlet
{
    type            zeroGradient;
}

壁面

wall
{
    type            zeroGradient;
}

总压(入口)

inlet
{
    type            totalPressure;
    p0              uniform 101325;
    U               U;
    phi             phi;
    rho             none;
    psi             none;
    gamma           1;
    value           uniform 101325;
}
湍流 (k, epsilon, omega)

入口 - 固定值

// Turbulent kinetic energy
k_inlet
{
    type            turbulentIntensityKineticEnergyInlet;
    intensity       0.05;  // 5% turbulence intensity
    value           uniform 0.375;
}

// Dissipation rate
epsilon_inlet
{
    type            turbulentMixingLengthDissipationRateInlet;
    mixingLength    0.005;  // 0.5 cm
    value           uniform 14.855;
}

// Specific dissipation rate
omega_inlet
{
    type            turbulentMixingLengthFrequencyInlet;
    mixingLength    0.005;
    value           uniform 440;
}

壁面函数

// k at wall
k_wall
{
    type            kqRWallFunction;
    value           uniform 0.375;
}

// epsilon at wall
epsilon_wall
{
    type            epsilonWallFunction;
    value           uniform 14.855;
}

// omega at wall
omega_wall
{
    type            omegaWallFunction;
    value           uniform 440;
}

// nut at wall
nut_wall
{
    type            nutkWallFunction;
    value           uniform 0;
}

出口

k_outlet
{
    type            zeroGradient;
}

epsilon_outlet
{
    type            zeroGradient;
}

omega_outlet
{
    type            zeroGradient;
}
计算湍流参数

入口条件:

Turbulent intensity: I = u'/U = 0.16 * Re^(-1/8)
Turbulent kinetic energy: k = 3/2 * (U * I)²
Turbulent dissipation: ε = C_μ^(3/4) * k^(3/2) / L
Specific dissipation: ω = k^(1/2) / (C_μ^(1/4) * L)

Where:
- U = mean velocity
- Re = Reynolds number
- L = turbulent length scale ≈ 0.07 * characteristic_length
- C_μ = 0.09

求解器选择

不可压缩求解器

simpleFoam - 稳态、不可压缩、湍流

  • 应用:外部空气动力学、暖通空调、工业流动
  • 算法:SIMPLE
  • 速度:稳态问题收敛快速

pimpleFoam - 瞬态、不可压缩、湍流

  • 应用:涡脱落、瞬态流动、LES
  • 算法:PIMPLE(合并 PISO 和 SIMPLE)
  • 速度:稳定性良好,可处理较大的时间步长

icoFoam - 瞬态、不可压缩、层流

  • 应用:低雷诺数问题、教学
  • 算法:PISO
  • 速度:适用于层流,计算快速

pisoFoam - 瞬态、不可压缩、湍流

  • 应用:LES、DNS
  • 算法:PISO
  • 速度:需要较小的时间步长
多相求解器

interFoam - VOF 方法,适用于两种互不相溶的流体

  • 应用:自由液面流动、晃荡、波浪破碎
  • 跟踪流体之间的界面

multiphaseInterFoam - 适用于多种流体的 VOF 方法

  • 应用:两种以上的相

twoPhaseEulerFoam - 欧拉-欧拉多相流

  • 应用:流化床、气泡流
可压缩求解器

rhoSimpleFoam - 稳态、可压缩、湍流

  • 应用:高速流动、可压缩效应

rhoPimpleFoam - 瞬态、可压缩、湍流

  • 应用:瞬态可压缩流动

sonicFoam - 瞬态、可压缩、超音速

  • 应用:超音速流动、激波
传热求解器

buoyantSimpleFoam - 稳态、浮力驱动

  • 应用:自然对流

buoyantPimpleFoam - 瞬态、浮力驱动

  • 应用:瞬态自然对流

chtMultiRegionFoam - 共轭传热

  • 应用:固体-流体传热

网格生成

blockMesh - 结构化六面体网格

用于矩形区域的基础块网格:

// system/blockMeshDict
FoamFile
{
    version     2.0;
    format      ascii;
    class       dictionary;
    object      blockMeshDict;
}

convertToMeters 1;

vertices
(
    (0 0 0)      // 0
    (1 0 0)      // 1
    (1 1 0)      // 2
    (0 1 0)      // 3
    (0 0 0.1)    // 4
    (1 0 0.1)    // 5
    (1 1 0.1)    // 6
    (0 1 0.1)    // 7
);

blocks
(
    hex (0 1 2 3 4 5 6 7) (20 20 1) simpleGrading (1 1 1)
);

edges
(
);

boundary
(
    inlet
    {
        type patch;
        faces
        (
            (0 4 7 3)
        );
    }
    outlet
    {
        type patch;
        faces
        (
            (1 2 6 5)
        );
    }
    walls
    {
        type wall;
        faces
        (
            (0 1 5 4)
            (3 7 6 2)
        );
    }
    frontAndBack
    {
        type empty;
        faces
        (
            (0 3 2 1)
            (4 5 6 7)
        );
    }
);

mergePatchPairs
(
);

执行:blockMesh

snappyHexMesh - 非结构化、以六面体为主的网格

用于从 STL 文件生成复杂几何体的网格:

// system/snappyHexMeshDict (simplified)
FoamFile
{
    version     2.0;
    format      ascii;
    class       dictionary;
    object      snappyHexMeshDict;
}

castellatedMesh true;
snap            true;
addLayers       true;

geometry
{
    geometry.stl
    {
        type triSurfaceMesh;
        name geometry;
    }
}

castellatedMeshControls
{
    maxLocalCells 100000;
    maxGlobalCells 2000000;
    minRefinementCells 0;
    nCellsBetweenLevels 3;

    features
    (
        {
            file "geometry.eMesh";
            level 2;
        }
    );

    refinementSurfaces
    {
        geometry
        {
            level (2 2);
        }
    }

    resolveFeatureAngle 30;
    refinementRegions
    {
    }

    locationInMesh (0.01 0.01 0.01);
    allowFreeStandingZoneFaces true;
}

snapControls
{
    nSmoothPatch 3;
    tolerance 2.0;
    nSolveIter 30;
    nRelaxIter 5;
}

addLayersControls
{
    relativeSizes true;
    layers
    {
        geometry
        {
            nSurfaceLayers 3;
        }
    }

    expansionRatio 1.2;
    finalLayerThickness 0.3;
    minThickness 0.1;
    nGrow 0;
    featureAngle 30;
    nRelaxIter 3;
    nSmoothSurfaceNormals 1;
    nSmoothNormals 3;
    nSmoothThickness 10;
    maxFaceThicknessRatio 0.5;
    maxThicknessToMedialRatio 0.3;
    minMedianAxisAngle 90;
    nBufferCellsNoExtrude 0;
    nLayerIter 50;
}

meshQualityControls
{
    maxNonOrtho 65;
    maxBoundarySkewness 20;
    maxInternalSkewness 4;
    maxConcave 80;
    minVol 1e-13;
    minTetQuality 1e-30;
    minArea -1;
    minTwist 0.02;
    minDeterminant 0.001;
    minFaceWeight 0.02;
    minVolRatio 0.01;
    minTriangleTwist -1;
    nSmoothScale 4;
    errorReduction 0.75;
}

debug 0;
mergeTolerance 1e-6;

执行:snappyHexMesh -overwrite

使用 ParaView 进行后处理

使用 paraFoam
# In case directory
paraFoam

# With reconstructed parallel case
paraFoam -builtin

# Touch file for newer versions
touch case.foam
paraview case.foam
常见可视化任务
  1. 速度大小

    • Filters → Calculator
    • 结果数组名称:UMag
    • 公式:mag(U)
  2. 流线

    • Filters → Stream Tracer
    • 种子类型:Point Source 或 Line Source
    • 向量:U
  3. 切片/平面

    • Filters → Slice
    • 平面参数:Origin 和 Normal
  4. 等值面

    • Filters → Contour
    • 选择变量和值
  5. 壁面剪切应力

    • Filters → Calculator
    • 公式:nu * mag(wallShearStress)
采样和数据提取

创建 system/sampleDict:

FoamFile
{
    version     2.0;
    format      ascii;
    class       dictionary;
    object      sampleDict;
}

interpolationScheme cellPoint;

setFormat   raw;

sets
(
    centerline
    {
        type    uniform;
        axis    distance;
        start   (0 0.5 0.05);
        end     (10 0.5 0.05);
        nPoints 100;
    }
);

surfaces
(
    plane
    {
        type    cuttingPlane;
        planeType pointAndNormal;
        pointAndNormalDict
        {
            point   (0 0 0);
            normal  (0 0 1);
        }
        interpolate true;
    }
);

fields  (p U k epsilon);

执行:postProcess -func sampleDict

并行处理

分解算例

创建 system/decomposeParDict:

FoamFile
{
    version     2.0;
    format      ascii;
    class       dictionary;
    object      decomposeParDict;
}

numberOfSubdomains 4;

method          scotch;  // simple, hierarchical, manual

// For simple decomposition
simpleCoeffs
{
    n               (2 2 1);
    delta           0.001;
}

// For hierarchical decomposition
hierarchicalCoeffs
{
    n               (2 2 1);
    delta           0.001;
    order           xyz;
}
并行运行
# Decompose the mesh
decomposePar

# Run solver in parallel
mpirun -np 4 simpleFoam -parallel

# Reconstruct results
reconstructPar

# Reconstruct only latest time
reconstructPar -latestTime

工作流总结

# 1. Create case structure
mkdir -p myCase/{0,constant,system}

# 2. Copy base configuration
cp -r $FOAM_TUTORIALS/incompressible/simpleFoam/pitzDaily/* myCase/

# 3. Edit dictionaries
# - system/controlDict
# - system/fvSchemes
# - system/fvSolution
# - constant/transportProperties
# - constant/turbulenceProperties
# - 0/U, 0/p, 0/k, 0/epsilon

# 4. Generate mesh
cd myCase
blockMesh

# 5. Check mesh quality
checkMesh

# 6. Run solver
simpleFoam > log.simpleFoam 2>&1

# 7. Monitor residuals
foamMonitor -l postProcessing/residuals/0/residuals.dat

# 8. Post-process
paraFoam

# For parallel:
decomposePar
mpirun -np 4 simpleFoam -parallel
reconstructPar

最佳实践

  1. 网格质量:模拟前务必运行 checkMesh
  2. 残差:监控收敛情况(工程精度要求下小于 1e-4)
  3. Courant 数:保持 Co < 1,以确保稳定性(瞬态算例)
  4. Y+ 值:壁面函数取 30-300,解析边界层取 < 1
  5. 网格无关性:进行网格加密研究
  6. 初始化:使用 potentialFoam 获得更好的初始速度场
  7. 备份:使用 git 对算例文件进行版本控制

故障排除

常见问题

网格检查失败

checkMesh
# Look for non-orthogonality, skewness
# Increase nNonOrthogonalCorrectors in fvSolution

发散

  • 降低松弛因子
  • 改善初始条件
  • 加密网格
  • 缩短时间步(瞬态算例)

收敛缓慢

  • 检查边界条件
  • 调整求解器容差
  • 使用更好的预条件器(压力求解使用 GAMG)

并行问题

# Check decomposition
decomposePar -cellDist

# Verify MPI installation
mpirun -np 2 hostname

资源

另请参阅

  • examples/pipe-flow/ - 完整的湍流管道流动算例
  • examples/pump-impeller/ - 旋转机械模拟
  • examples/scripts/ - Python 算例生成工具
  • reference.md - 详细的字典和求解器参考

评论

支持 Markdown