Professional Documents
Culture Documents
Ansys Fluent Guide: Advanced FLUENT User-Defined Functions
Ansys Fluent Guide: Advanced FLUENT User-Defined Functions
Table of Contents
1 Introduction .................................................................................................................................... 4
2 User Access to the FLUENT Solver................................................................................................... 4
3 C Programming ................................................................................................................................ 5
4 Cfd Programming in FLUENT ........................................................................................................... 7
5 UDF Basics ....................................................................................................................................... 7
6 Using UDFs in the Solvers ................................................................................................................ 8
7 Data structure overview.................................................................................................................. 8
7.1 The Domain ............................................................................................................................. 8
7.2 The Threads ............................................................................................................................. 9
7.3 Cell and Face Datatypes .......................................................................................................... 9
7.4 Some Additional info on Faces ................................................................................................ 9
8 Fluent UDF Data Structure Summary ............................................................................................ 10
9 Geometry Macros ......................................................................................................................... 11
10 Cell Field Variable Macros ......................................................................................................... 12
11 Face Field Variable Macros ....................................................................................................... 13
12 Looping and Thread Macros...................................................................................................... 14
13 Macros ....................................................................................................................................... 15
13.1 DEFINE Macros ...................................................................................................................... 15
13.2 Othe UDF Applications .......................................................................................................... 16
14 User Defined Memories ............................................................................................................ 17
15 User Defined Scalars.................................................................................................................. 18
16 Interpreted vs. Compiled UDF’s ................................................................................................ 19
17 UDF Technical Support .............................................................................................................. 19
18 Example: Parabolic Inlet Velocity Profile .................................................................................. 20
18.1 Step 1: Prepare the Source Code .......................................................................................... 20
18.2 Step 3: Interpret or Compile the UDF ................................................................................... 20
18.3 Step 4: Activate the UDF ....................................................................................................... 21
18.4 Steps 5 and 6: Run the Calculations ...................................................................................... 21
18.5 Numerical Solution of the Example ....................................................................................... 21
19 Example: Checking Effect of Porous Zone on Momentum Equation ........................................ 22
19.1 Using Fluent Built-in Porous Zone ......................................................................................... 22
19.2 Using Momentum Source Terms........................................................................................... 23
20 Example: Modeling Fuel Cell ..................................................................................................... 24
Saeed Sadeghi (msaeedsadeghi@gmail.com)
Pardad Petro Danesh (www.petrodanesh.ir)
Introduction 3
20.1 Preparation............................................................................................................................ 24
20.2 Mesh ...................................................................................................................................... 24
20.3 General Settings .................................................................................................................... 24
20.4 Models ................................................................................................................................... 25
20.5 Materials ............................................................................................................................... 25
20.6 Boundary Conditions ............................................................................................................. 26
20.6.1 Setting Velocity Inlet ..................................................................................................... 29
20.6.2 Pressure Outlet.............................................................................................................. 29
20.7 Writing UDF ........................................................................................................................... 30
20.7.1 Compiling the UDF......................................................................................................... 32
20.8 Checking Oxygen Mass Balance ............................................................................................ 37
21 Fluent Frequently Asked Questions .......................................................................................... 39
21.1 My UDF won't interpret or compile - what is wrong? .......................................................... 39
21.2 How to Set Environment Variables ....................................................................................... 39
21.2.1 On Windows 32 Bit ........................................................................................................ 39
21.2.2 On Windows 64 Bit ........................................................................................................ 39
1 Introduction
3 C Programming
• pointer is a special kind of variable that contains the memory address, not content, of
another variable
• Pointers are declared using the * notation:
int a=1;
int *ip;
ip = &a; /* &a returns the address of variable a */
printf(“content of address pointed to by ip = %d\n”, *ip);
• Pointers are also used to point to the beginning of an array
o Thus pointers are used to address arrays in C
• Array variables can be defined using the notation name[size], where name is the variable
name and size is an integer which defines the number of elements in the array (from 0 to
size-1)
• Operators
= (assignment)
+, -, *, /, % (modulus)
<, >, >=, <=, ==, !=
++ increment; i++ is “pors-increment”; use the current value of I in the expression, then
increment I by 1 (i=i+)
+= addition assignment:
Saeed Sadeghi (msaeedsadeghi@gmail.com)
Pardad Petro Danesh (www.petrodanesh.ir)
C Programming 6
if ( … )
<statement>;
if ( … )
<statement>;
else
<statement>;
if ( … )
<statement>;
else if ( … )
<statement>;
For Loops:
<statement>;
While loops:
While ( … )
<statement>;
Conditional operator ( ? : )
example:
false
real At = (rp_axi ? At*2*M_PI : At );
true
• We (as CFD programmers in FLUENT) want to know how FLUENT organizes data so that we
know:
o How to access mesh information for a particular cell zone or a face zone
Cell centroids, cell volumes, the neighbors, etc.
Face centroids, face areas, face normal directions (vectors), etc.
o How to access field data for cells (and faces): pressure, velocity, density, etc.
o How to efficiently loop through these cells or faces in the codes
• How to sypply customized source terms, boundary conditions, and fluid properties, etc., to
the solver
• How to modify the behaviors or specific model parameters for various physical models as in
turbulence, reactions kinetics, multiphase, and dynamic mesh, etc.
• How to implement user’s own governing equations in the finite-volume framework of
FLUENT solver
5 UDF Basics
STEP 4: Assign the UDF to the appropriate variable and zone in BC panel.
• Domain is the set of connectivity and hierarchy info for the entire data structure in a given
problem for single phase flows. It includes:
o All fluid zones (‘fluid threads’)
o All solid zones (‘solid threads’)
o All boundary zones (‘boundary threads’)
• Cell: cell is the computational unit, conservation equations are solved over each cell
• Face: direction in the outward normal
• Threads: represent the collection of cells or faces; a Thread represents a fluid or solid or
boundary zone
• Multiphase simulations (singlephase simulations use single domain only)
o Each phase has its own “Domain-structure”
o Geometric and common property information are shared among ‘sub-domains’
Saeed Sadeghi (msaeedsadeghi@gmail.com)
Pardad Petro Danesh (www.petrodanesh.ir)
Data structure overview 9
• Control volumes of fluid and solid zones are also called ‘cells’ in FLUENT
o The data structure for the cell zones is typed as ‘cell_t’ (the cell thread index)
o The data structure for the cell faces is typed as ‘face_t’ (the face thread index)
• A fluid or solid zone is called a cell zone, which can be accessed by using cell threads
• Boundary or internal faces can be accessed by using face threads
• The data structure for accessing a cell zone is typed as ‘cell_t’ (the cell thread index); the
data structure for faces is typed as ‘face_t' (the face thread index)
• Once we have the correct pointer (for a specific zone), we can access the members belonging
to the zone without any problem. Thread pointer provides the leading address of the thread
(zone)
9 Geometry Macros
• Face field variables are only available when using the segregated solver and generally, only at
exterior boundaries.
thread_loop_c(t, d)
{
.......... loop that steps through all cell threads in domain
}
thread_loop_f(t, d)
{
………. loop that steps through all face threads in domain
}
begin_c_loop(c, t)
{
………. Loop that steps through all cells in a thread
}
end_c_loop
befing_f_loop(c, t)
{
………. Loop that steps through all faces in a thread
}
C_face_loop(f, t, n)
{
………. Loop that visits all faces of cell c in thread t
}
13 Macros
DEFINE_DELTAT(name, domain); defines variable time step size for unsteady problems
DEFINE_NOX_RATE(name, cell, thread, nox); defines NOx production and destruction rates
• In addition to defining boundary values, source terms and material properties, UDFs can be used
for:
o Initialization
Executes once per initialization
o Adjust
Executes every iteration
o Wall Heat Flux
Defines fluid-side diffusive and radiative wall heat
fluxes in terms of heat transfer coefficients
Applies to all walls
o User Defined Surface and Volumetric Reactions
o Read-Write to/from case and data files
Read order and Write order must be same.
o Execute-on-Demand capability
Not accessible during solve
• User-allocated memory
o Up to 500 field variables can be defined.
o Can be accessed by UDFs:
C_UDMI(cell, thread, index);
F_UDMI(face, thread, index);
o Can be accessed for post-processing.
o Information is stored in data file.
∂φk ∂ ∂φk
+ Fi φk − Γ
= S=
φk k 1,..., N scalars
∂t ∂x i ∂x i
k
• User Specifies:
• Functions can either be read in and interpreted at run time or compiled and grouped into a shared
library that is linked with the standard FLUENT executable.
• Interpreted vs. compiled code
o Interpreter
Interpreter is a large program that sits in the computer’s memory.
Executes code on a “line by line” basis instantaneously
Advantages – does not need a separate compiler
Disadvantage – slow and takes up space in memory
o Compiler (refer to User’s Guide for instructions)
Code is translated “once” into machine language (object modules).
Efficient way to run UDF’s. Uses Makefiles
Creates “shared libraries” which are linked with the rest of the solver
Overcomes interpreter limitations e.g. mixed mode arithmetic, structure references etc.
• Because UDF’s can be very complicated, Fluent Inc. does not assume responsibility for the
accuracy or stability of solutions obtained using UDFs that are user-generated.
o Support will be limited to guidance related to communication between a UDF and the FLUENT
solver.
o Other aspects of the UDF development process that include conceptual function design,
implementation (writing C code), compilation and debugging of C source code, execution of
the UDF, and function design verification will remain the responsibility of the UDF author.
A consulting option is available for complex projects.
y 2
u=
( y ) 20 1 −
0.0745
y =0
• Add the UDF source code to the Source • Add the UDF source code to the Source
File Name list. files list.
• Click Interpret. • Click Build to create UDF library.
• The assembly language code will • Click Load to load the library.
display in the FLUENT console. • You can also unload a library if needed.
Define User-Defined Functions
Manage…
• You can change the UDF Profile Update Interval in the Iterate
panel (default value is 1).
o This setting controls how often (either iterations or
time steps if unsteady) the UDF profile is updated.
• Run the calculation as usual.
Many industrial applications such as filters, catalyst beds and packing, involve modeling the flow
through porous media. This tutorial illustrates how to set up and solve a problem involving gas flow
through porous media.
The problem solved here involves gas flow through a channel using FLUENT in two different ways to
validate it. In the first one we use porous zone parameters and in the second one we write a UDF
includes momentum source terms for porous zone pressure drop.
#include "udf.h"
#define por_gdl 0.4
#define i_permeability 5.68e6 // Inverse Permeability (1/m^2)
#define urf 0.1 // under relaxation factor for stability of momentum source term
real s1=0., s2=0.;
DEFINE_SOURCE(xmom_src,c,t,dS,eqn)
{
real source, mu, u;
mu = C_MU_L(c,t);
u = C_U(c,t);
source = -(mu*u*i_permeability);
dS[eqn] = -(mu*i_permeability);
s1 = s1*(1-urf) + source*urf;
return s1;
}
DEFINE_SOURCE(ymom_src,c,t,dS,eqn)
{
real source, mu, v;
mu = C_MU_L(c,t);
v = C_V(c,t);
source = -(mu*v*i_permeability);
dS[eqn] = -(mu*i_permeability);
s2 = s2*(1-urf) + source*urf;
return s2;
}
20.1 Preparation
Note: The Display Options are enabled by default. Therefore, once you read in the mesh, it will be
displayed in the embedded graphics windows.
20.2 Mesh
ANSYS FLUENT will perform various checks on the mesh and report the progress in the ANSYS
FLUENT console window. Ensure that the minimum volume reported is a positive number.
(a) Select mm (millimeter) from the Mesh Was Created In drop-down list in the Scaling group
box.
(b) Click Scale to scale the mesh.
(c) Close the Scale Mesh dialog box.
4. Check the mesh.
General Check
Note: It is a good idea to check the mesh after you manipulate it (i.e., scale, convert to polyhedral,
merge, separate, fuse, add zones, or smooth and swap). This will ensure that the quality of the mesh
has not been compromised.
20.4 Models
(c) FLUENT will notify that “Available material properties or method have changed. Please
confirm the property values before continuing”. Click OK to close the dialog box.
20.5 Materials
Define Materials…
1. Revise the properties for the mixture materials.
Define Material Mixture
(a) Click the Edit… button to the right of the Mixture Species drop-down list to open Species
dialog box.
You can add or remove species from the mixture material as necessary using the Species dialog box.
i. Retain the default selections from the Selected Species selection list.
ii. Click OK to close the Species dialog box.
Because the effect of gravity can be neglected, Retain setting in Operating Conditions and Click OK to
Close the dialog box.
(a) Set Boundary condition for gdl fluid zone, by clicking on the Set button
Fluent uses these values for calculating momentum source term due to the porous
zone.
(f) Set Boundary condition for cl fluid zone, by clicking on the Set button
(g) Check the porous zone button to enable the cl porous zone.
(h) Set viscous resistance variables for both directions.
(i) Now you should set porosity for cl porous zone that is equal to 0.1, here.
(c) Click the Species Tab to set mass fraction of species. Fluent will automatically calculate the
mass fraction of the last specie, that is equal to 1 minus sum of the mass fraction of the other
species.
(b) Select pressure outlet on the right side of the boundary conditions dialog box, to specify
pressure at the outlet of the fuel cell.
(c) Click set button to enter Pressure Outlet dialog box.
(d) To prevent solution damage by reverse flows, we should specify outlet conditions near to
real condition.
(e) For this, we have chosen inlet species mass fraction for the outlet condition.
(f) Leave the other parameters by default and click OK.
#include "udf.h"
#define i_h2o 0
#define i_o2 1
#define i_n2 2
enum{ current };
C_CENTROID(xyz,c,t);
x=xyz[0];
y=xyz[1];
//z=xyz[2];
// Option 0
// Reraction_Rate_cat = 10000.0;
// Option 1
Reraction_Rate_cat = 100000. *(1.0 - x/L);
// Option 3
// Reraction_Rate_cat = (zita_cat*j_ref_cat)*pow(C_o2/C_ref_o2,lambda_cat)*(exp(-
alpha_cat*F*eta_cat/(R*T)));
return Reraction_Rate_cat;
}
DEFINE_SOURCE(O2_src,c,t,dS,eqn)
{
real source;
source = -mw_o2*R_cat(c,t)/(4.*F) *por_cl;// (kg/kmol)()/(C/kmol)
//Message("%f, %f, %f, %f, %f\n",mw_o2,R_cat(c,t),por_cl, source, F);
C_UDMI(c,t,current)= -4.*F /mw_o2 *source *h_cl; // this is local current density
dS[eqn] = 0.0;
return source;
}
DEFINE_SOURCE(H2O_src,c,t,dS,eqn)
{
real source;
source = +mw_h2o*R_cat(c,t)/(2.*F) *por_cl;
Saeed Sadeghi (msaeedsadeghi@gmail.com)
Pardad Petro Danesh (www.petrodanesh.ir)
Example: Modeling Fuel Cell 32
dS[eqn] = 0.0;
return source;
}
DEFINE_SOURCE(MASS_src,c,t,dS,eqn)
{
real source;
source = ( -mw_o2/(4.*F) + mw_h2o/(2.*F) )*R_cat(c,t) *por_cl;
dS[eqn] = 0.0;
return source;
}
DEFINE_DIFFUSIVITY(mix_diff, c, t, i)
{
real diff;
switch (i)
{
case 0:
diff = diff_h2o*por_cl*sqrt(por_cl);
break;
case 1:
diff = diff_o2*por_cl*sqrt(por_cl);
break;
case 2:
diff = diff_n2*por_cl*sqrt(por_cl);
break;
default:
diff = 0.0;
}
return diff;
}
Build the UDF and then click on Load to load the Library that is named libudf.
Note that the UDF source files should be in the directory that contains your case and data
files. Click OK to build the library.
Now the fluent creates library libudf.lib, object libudf.exp and other required files.
You can load the library if fluent reveal no error and the message “Done” have seen at the
end of the commend window.
By loading the library, fluent command window show all defined functions. Here it shows
“O2_src, H2O_src, MASS_src, …”.
If you have build and load a udf before, be sure to unload it in the Manage dialog box. Else
an error will appear that an libudf is in use.
We have used a UDM in the UDF, so we should specify a UDM for it.
Go to: Define User-Defined Memory… then set the number of UDM-s.
Fluent enables the energy equation by enabling Species Transport equation. In this example,
we don’t need the energy equation. To prevent solving this equation go to Solve Solution
Controls and click on Energy in Equations box.
To have a good initial guess for better and time saving convergence, we can specify the
conditions of inlet to the all domain.
So, Solve Initialize Solution Initialize, Compute from inlet and click on Init to specify its
condition to all domains.
You can change Residual criteria and Residual window settings. Solve Monitors
Residual.
To prevent printing on command window, uncheck print. And to show residual on the
residual window, check the plot box.
On iterate window, Solve Iterate, specify the number iterations and start iteration by
clicking on iterate.
To check Oxygen mass balance, we should calculate the rate of oxygen mass enters the domain at
the inlet (kg/s), the rate of oxygen mass consumes at the catalyst layer (kg/s), and the rate of oxygen
mass exits the domain from outlet.
DEFINE_ON_DEMAND(data)
{
real A[ND_ND];
real sum;
int inlet_ID = 7;
int outlet_ID = 6;
int cl_ID = 2;
Domain *d = Get_Domain(1);
Thread *t_inlet = Lookup_Thread (d,inlet_ID);
Thread *t_outlet = Lookup_Thread (d,outlet_ID);
Thread *t_cl = Lookup_Thread (d,cl_ID);
face_t f;
cell_t c;
///////////////////////////
sum = 0.;
begin_f_loop(f,t_inlet)
{
F_AREA(A,f,t_inlet);
sum += F_FLUX(f,t_inlet) *F_YI(f,t_inlet,i_o2)*1.e6;
}
end_f_loop(f,t_inlet);
Message("inlet = %f *e-6(kg/s)\n", sum);
///////////////////////////
sum =0.;
begin_f_loop(f,t_outlet)
{
F_AREA(A,f,t_outlet);
sum += F_FLUX(f,t_outlet) *F_YI(f,t_outlet,i_o2)*1.e6;
}
end_f_loop(f,t_outlet);
Message("outlet= %f *e-6(kg/s)\n", sum);
///////////////////////////
sum =0.;
begin_c_loop(c,t_cl)
{
sum += -mw_o2*R_cat(c,t_cl)/(4.*F) *por_cl*C_VOLUME(c,t_cl)*1.e6;
}
end_c_loop(f,t_cl);
Message("porous= %f *e-6(kg/s)\n", sum);
}
• The macro “DEFINE_ON_DEMAN” executes when we want. For example at the beginning,
intermediate and at the end of solution, it can be executed.
• The array A is defined in ND_ND dimension to reserve area.
• ND_ND is a Fluent macro that is equal to 2 in 2-dimensioanl and 3 in 3-dimensional case.
• sum is defined to summarize value of cells in a group cells (Threads)
• inlet_ID, outlet_ID and cl_ID are the number of zone that can be found in Boundary
Conditions dialog box.
• If Fluent complains about not being able to find a compiler, then check to make sure that the
compiler is properly installed. On Windows machines, it is possible to install the Visual C++
compiler without fully setting up the command line compiler (which Fluent needs to be able
to find). During the installation process, you need to select the "register environment
variables" option. Failure to do so will likely lead to complaints about things being "not
recognized as an internal or external command, operable program or batch file" or missing
DLL's. It is theoretically possible to fix this issue by setting the appropriate environment
variables, but keep in mind that even when nmake can be found there still may be DLL
issues. The easy path is probably reinstallation of Visual Studio (taking special care to make
sure that the command line interface is set up properly), but the reinstallation path is always
perilous. If you have long term experience using Windows you should probably know the
risks, and if you don't you should consult an expert.
• If you are interpreting, keep in mind that not everything that is supported for compiled UDF's
is supported for interpreted UDF's. This is true both for the UDF interface and the C
language. If you are doing something pretty involved and it fails inexplicably, try compiling to
see if that makes a difference.
• There is also the possibility of coding errors. Keep in mind that your source code gets run
through the C preprocessor (to change the Fluent macros into C code), so unintended
interactions are very possible.