Sie sind auf Seite 1von 31

Chapter 1 Customer Training Material

Introduction to Fluent
from the Inside
14.0Release

Advanced Fluent
User-Defined Functions
1 2012ANSYS,Inc. March14,2012 Release14.0
Introduction to UDF Programming Customer Training Material

WhyuseUDFs?

Fluentisageneralpurposetoolandcannotanticipateallusersneeds.

Additionofnewphysicalmodelsforacademicresearchorcustomer
proprietaryphysics.

Customizationofboundaryconditions.

2 2012ANSYS,Inc. March14,2012 Release14.0


WhatisaUserDefinedFunction(UDF)? Customer Training Material

AUDFisafunctionorsetoffunctionsprogrammedbytheuserinClanguageand
linkedtoFluenttoperformawidevarietyofoperationsincluding:

Initialization
Customboundaryconditions(bothspaceortimedependent)
Materialproperties
Sourcetermsintoanyoftheflowequations
Chemicalreactionrates
Postprocessingandreportingofmodifieddata
Addingextraflowequations
Meshmotion
Discretephasemodelmodification
Andmanymore...

3 2012ANSYS,Inc. March14,2012 Release14.0


User Access to the Fluent Solver Customer Training Material

There are many places within the solution cycle where a UDF
can be added:
Segregated PBCS DBCS

User-
Initialize Begin Loop defined Solver? Solve U-Momentum Source terms
ADJUST
Solve Mass,
Source terms Solve V-Momentum Momentum,
Solve Mass Source terms
User Defined Energy,
& Momentum
INITIALIZE Species
Solve W-Momentum

Repeat
Solve Mass Continuity;
Update Velocity

Exit Loop Check Convergence


Solve Energy

Update Properties Solve Species Source


terms
User-Defined Properties Solve Turbulence Equation(s)
User-Defined BCs
Solve Other Transport Equations as required

4 2012ANSYS,Inc. March14,2012 Release14.0


Data Structures Customer Training Material

EachtypeofUDFispasseddifferentvaluesanddatastructures
dependingonitsfunction.

MostUDFswillneedgeometricaldata.Thisisstoredinahierarchy:

Domains arecollectionsofthreadsthatmakethewholemesh
Threads (orzones)arecollectionsofcellsorfaces
Cells andfaces aremadeofNodes

5 2012ANSYS,Inc. March14,2012 Release14.0


Geometrical Entities Customer Training Material

Thepartsofameshare:

6 2012ANSYS,Inc. March14,2012 Release14.0


Data Structures Customer Training Material

ThetermsThreadandZoneareinterchangeable.Theboundary
andcellzonesdefinedintheUserInterfacearestoredinternallyas
threads.

ZoneshaveanassociatedintegerIDseeninthesettingspanel
InaUDF,thecorrespondingthreadcanbeidentifiedusingthisID
Threadsareaninternaldatatypewhichstoresinformationaboutthemesh,
models,properties,BCsallinoneplace

Acellhasinformationaboutitsboundingfacesandafacehasaccessto
itsneighbouringcells.

7 2012ANSYS,Inc. March14,2012 Release14.0


Customer Training Material

Introduction to the C
Programming Language

14.0Release

Advanced Fluent
User-Defined Functions
8 2012ANSYS,Inc. March14,2012 Release14.0
C Programming (1) Customer Training Material

Basicsyntaxrules:
Eachstatementmustbeterminatedwithasemicolon;
Commentscanbeinsertedanywherebetween/* and*/
Allvariablesmustbeexplicitlydeclared(unlikeinFORTRAN)
Compoundstatementscanbecreatedbyenclosingmultiplestatementsbybraces:
{}
Functiondefinitionshavethefollowingformat:
return-value-type function-name(parameter-list)
{ function body }
Builtindatatypes:int,float,double,enum,boolean:
int niter, a; /* Declare niter and a as integers */
float dx[10]; /* dx is an array of 10 numbers indexed from 0-9:
dx[0], dx[1] dx[8], dx[9] */

enum {X, Y, Z}; /* X, Y, Z are enumeration constants = 0, 1, 2 */

9 2012ANSYS,Inc. March14,2012 Release14.0


C Programming (2) Customer Training Material

APointerisaspecialkindofvariablethatcontainsanaddress inmemory,notcontent,of
anothervariable

Pointersaredeclaredusingthe*notation:
int *ip; /* ip is declared as a pointer to integer */

WecanmakeaPointerpointtotheaddressofpredefinedvariableasfollows:
int a = 1;
int *ip; /* (*ip) contains an integer */

ip = &a; /* &a returns the address of variable a */


printf(ip is a pointer with value %p\n, ip);
printf(The integer stored at ip = %d\n,*ip);

ip is a pointer with value 0x40b2


The integer stored at ip = 1

10 2012ANSYS,Inc. March14,2012 Release14.0


C Programming (3) Customer Training Material

Pointersandarraysarecloselyrelated:

int ar[10]; /* ar is an array of 10 integers */


int *ip; /* (*ip) contains an integer, */

Thenameofanarraywithoutanindexcanbe
usedasapointertothestartofthearray

ip = ar; /* ar is the address of its first integer


so this is equivalent to ip = &(ar[0]); */

BUT:
Anarraynamecannotbesettoanewvalue.
Itisfixedtothevaluesetwhenitisdefinedasanarray.

ar = &i; /* This will cause a compilation error */

11 2012ANSYS,Inc. March14,2012 Release14.0


C Programming (4) Customer Training Material

Operators
= (assignment)
+, -, *, /, % (modulus)
<, >, >=, <= , ==, !=
++ increment;i++ ispostincrement:usethecurrent valueofi inthe
expression,thenincrementi by1(i=i+1)

-- decrement:j-- postdecrement,usethecurrentvalueof j, then


decrement j by 1 (j=j-1)

+= additionassignment:
agg += single; /* means: agg = agg + single; */
*= multiplicationassignment,
-= subtractionassignment,
/= divisionassignment
12 2012ANSYS,Inc. March14,2012 Release14.0
C Programming (5) Customer Training Material

Basiccontrolstructures
for loops:
for ( k=0; k < NUM; k++ )
if ( )
<statement>;
<statement>;
while loops:
if ( )
<statement>; while ( )
<statement>;
else
<statement>;

Conditional Operator (? : )
if ( )
( condition ? operand a : operand b )
<statement>; example:
else if ( ) real At = (rp_axi ? At*2*M_PI : At );
<statement>;

13 2012ANSYS,Inc. March14,2012 Release14.0


C Programming (6) Customer Training Material

Compoundstatementsmaybeplacedwhereverasimplestatementis
allowed:
and in loops:

if ( k > 2 ) for ( k=0; k < NUM; k++ )


{ {
<statement>; <statement>;
<statement>;
<statement>;

}
}
else while ( k < NUM )
{ {
<statement>;
<statement>;
k++;
<statement>;
}
}
14 2012ANSYS,Inc. March14,2012 Release14.0
C Programming (7) Customer Training Material

Structures
Structuresarecollectionsofdatathatareofdifferenttypes.

struct car_struct
{
char model_name[25];
int number_of_wheels;
int engine_cc;
real top_speed;
}; /* Need a ; as variables can be defined here */

struct car_struct alices_car, bobs_car; /* or here */

/* Set and get values like this: */


alices_car.top_speed = 120.0;
if(bobs_car.top_speed > alices_car.top_speed)

15 2012ANSYS,Inc. March14,2012 Release14.0


C Programming (8) Customer Training Material

InFluent,structuresareusedformanythings.
ThemostcommononeisThread.
Thisisactuallydefinedusingthetypedef statementsowedontneedto
usethewordstruct whendefiningnewThreads:
typedef struct thread_struct
{
...
int id;
...
} Thread; /* typedef makes a new Thread type */

Thread *ct; /* Usually we use pointers to structures */

/* Macros are defined to access structure elements */


#define THREAD_ID(t)((t)->id)

/* Note -> operator: t->id is the same as (*t).id */


16 2012ANSYS,Inc. March14,2012 Release14.0
Customer Training Material

Introduction to UDF
Implementation Using C

14.0Release

Advanced Fluent
User-Defined Functions
17 2012ANSYS,Inc. March14,2012 Release14.0
Why UDFs are written in the C Customer Training Material

Language
FluentiswritteninCbecauseitisaverypowerfullanguage.Itprovidesaccesstohigh
leveloperationssuchasgraphicsandnetworkingandlowlevelcapabilitiessuchas
mathematicalfunctionsandmemoryoperations.

ItenablesthelinkingofextrafunctionalityusingsharedobjectsinUnixandDynamic
LinkedLibraries(DLLs)inwindowssystems.

ThisisaveryconvenientmechanismforlinkinginUDFswhichallowsaseamless
connectionbetweenthemainprogramandtheuserfunctions

UsersfamiliarwithotherprocedurallanguagessuchasFORTRANwillbefamiliarwith
mostoftheideasandsyntaxusedinC

18 2012ANSYS,Inc. March14,2012 Release14.0


Mesh Data Types (1) Customer Training Material

ThereareseveralFluentspecificdatatypesthatareassociatedwithmesh
components.
Someofthemorecommonlyusedonesare:
Node storesdataassociatedwithagridpoint
face_t identifiesafacewithinafacethread
cell_t identifiesacellwithinacellthread
Thread storesdatathatiscommontoacollectionofcellsorfaces
Domain storesdataassociatedwithacollectionoffaceandcellthreadsinamesh
Eachindividualcellcanbeaccessedbyusingacellindexoftypecell_t andthe
cellthread(thezonewhichcontainsthecell)
Similarly,eachindividualface(boundaryorinternal)canbeaccessedbyusing
thefaceindexoftypeface_t andthefacethread(thezonewhichcontainsthe
face)

19 2012ANSYS,Inc. March14,2012 Release14.0


Mesh Data Types (2) Customer Training Material

Somemeshorsolverdatatypeshaveacapitalletter.Theseareactuallydata
structuresintheClanguageandareusuallypassedbetweenfunctionsas
pointerstothesestructures.

Examplesofhowthesedatatypesaredefinedareshownbelow:

Type Example Declaration


Domain *d; d is a pointer to a Domain structure

Thread *t; t is a pointer to a Thread structure

cell_t c; c is cell index, a simple integer

face_t f; f is a face index, a simple integer

Node *node; node is pointer to a Node structure

20 2012ANSYS,Inc. March14,2012 Release14.0


MeshDataTypes(3) Customer Training Material

EveryZoneisassociatedtoasingleIDavailableintheBCpanelortheTUIusing:
/grid/modify-zones/list-zones

GiventheID,thethreadassociatedwith
thatzonecanberetrievedas:
int t_id = 7;
Thread *ft;
ft = Lookup_Thread(domain, t_id);

Oncewehavethethreadwecanaccess
itsassociateddata

Similarly,athreadsIDcanberetrievedusing:
t_id = THREAD_ID(ft);
21 2012ANSYS,Inc. March14,2012 Release14.0
CmacrosandUDFProgramming Customer Training Material

Chasaverypowerfulmacrodefinitioncapabilities.Theseareused
extensivelyinFluentinmanyways.Notableexampleinclude
definitionsof:

Datastructureloopingmacros
Geometrymacros
FielddataMacros
Logicandstatuscontrolmacros
Safearithmeticandtrigonometryfunctions
Completesetofvectorarithmeticoperations

ThedefinitionofeachUDFalsousesaspecificDEFINE_macro.

22 2012ANSYS,Inc. March14,2012 Release14.0


Loop Macros in a UDF Customer Training Material

thread_loop_c(t,d) Loopoverthecellthreadsinadomaind
thread_loop_f(t,d) Loopoverfacethreadsinadomaind

begin_c_loop(c,t) Loopoverthecellsinagivencellthread
end_c_loop (c,t)

begin_f_loop(f,t) Loopoverthefacesinagivenfacethread
end_f_loop(f,t)

23 2012ANSYS,Inc. March14,2012 Release14.0


Geometry Macros Customer Training Material

C_CENTROID(pos,c, t) x,y,zcoords ofcellcentroid


F_CENTROID(pos, f, t) x,y,zcoords offacecentroid A Hex cell
F_AREA(A, f, t) Areavectorofaface; Faces
NV_MAG(A) Vectormagnitude
C_VOLUME(c, t) Volumeofacell Nodes
C_VOLUME_2D(c, t) Volumeofa2Dcell
Location of cell variables
(pos &A arevectorswhicharediscussedlater) C_NNODES(c,t) = 8
C_NFACES(c,t) = 6
F_NNODES(f,t) = 4 each
(Depthis1min2D;2* radiansinaxisymmetric)

NODE_X(nn) Nodexcoord;(withNode *nn;)

NODE_Y(nn) Nodexcoord;
NODE_Z(nn) Nodexcoord;

Manymoreareavailable.SeetheFluentUDFManual

24 2012ANSYS,Inc. March14,2012 Release14.0


CellFaceConnectivity Customer Training Material

Thecellseithersideofaface(f,ft)canbeaccessedusingthemacros:

ct0 = THREAD_T0(ft); C0
ct1 = THREAD_T1(ft);
c0 = F_C0(f,ft);
C1
c1 = F_C1(f,ft);

ThemacrosTHREAD_T0(ft)&THREAD_T1(ft)onlyneedthefacethread,
notthefaceindex.ThisisbecauseinFluent,aninteriorzonemustconnecttothe
samefluidorsolidzonesoneitherside.

Boundaryzonessuchasinletswillconnecttoacellzoneononesidewith
THREAD_T0(ft) butTHREAD_T1(ft) willreturnNULL ,aspecialpointer
whichsignifiesthereisnozoneontheotherside.

25 2012ANSYS,Inc. March14,2012 Release14.0


CellFaceConnectivity(2) Customer Training Material

Afacesareaisobtainedasavectorusing:

C0
real A[3];
f = F_AREA(A,f,ft); C1

A faces area vector


points from C0 to C1
Theareacanbeusedtocalculatethefacenormal
Thefacesthatboundacellcanbeaccessedusingthisloop:
int nf;
for(nf=0;nf<C_NFACES(c,ct);nf++)
{
f = C_FACE(c,ct,nf);
ft = C_FACE_THREAD(c,ct,nf);
26 }
2012ANSYS,Inc. March14,2012 Release14.0
Field Variables Macros - Cell Customer Training Material

C_R(c,t) Density
C_P(c,t) Pressure
C_U(c,t)
C_V(c,t) X,Y&ZVelocityComponents
C_W(c,t)
C_T(c,t) Temperature
C_H(c,t) Enthalpy
C_K(c,t) TurbulentKineticEnergy
C_D(c,t) TurbulentEnergyDissipation
C_YI(c,t,i) ith SpeciesMassFraction
C_UDSI(c,t,i) ith UserDefinedScalar
C_UDMI(c,t,i) ith UserDefinedMemory
t isacellthreadpointer,c isacellindex,andi isanintegerforindexingwhich
species,UDSandUDMrequire.
27 2012ANSYS,Inc. March14,2012 Release14.0
MacrosusedforControl Customer Training Material

Data_Valid_P()
Equals1ifdataisavailable0ifnot.
if (!Data_Valid_P()) return;
FLUID_THREAD_P(t0)
Checkstoseeifthreadt0isafluidthread

NULLP(ct)
NULLP checksifapointerisNULL

NNULLP(ct)
NNULLP checksifapointerisNOTNULL
if(NNULLP(THREAD_T1(ft)))
{ ... Do things on neighbouring cell thread.}

28 2012ANSYS,Inc. March14,2012 Release14.0


UDF Defining Macros Customer Training Material

All UDFs that will be used in Fluent must be defined using a specific DEFINE_
macro
Some examples are:

Profiles : DEFINE_PROFILE
Source terms : DEFINE_SOURCE
Properties : DEFINE_PROPERTY
User-defined Scalars : DEFINE_UNSTEADY
DEFINE_FLUX
DEFINE_DIFFUSIVITY
Initialization : DEFINE_INIT
Global Functions : DEFINE_ADJUST
DEFINE_ON_DEMAND
DEFINE_RW_FILE

Refer to the UDF Manual for a complete list

29 2012ANSYS,Inc. March14,2012 Release14.0


AdditionalInformation Customer Training Material

Manyadditionalmacrosareavailabletoimplementdifferentphysicalmodels
including:
combustionmodels
particlesbasedmodels

Itisalsopossibletodevelopadditionalnumericalmethods,particularlywhen
usingUserDefinedScalars.Accesstolowleveloperationsispossible,suchas:

fluxdiscretisation
variablereconstructionandclipping

30 2012ANSYS,Inc. March14,2012 Release14.0


The Header Files Customer Training Material

The UDF macros are defined in the udf.h file, for instance:
#define DEFINE_PROFILE(name, t, i) void name(Thread *t, int i)
#define DEFINE_PROPERTY(name,c,t) real name(cell_t c, Thread *t)
#define DEFINE_SOURCE(name, c, t, dS, i) \
real name(cell_t c, Thread *t, real dS[], int i)
#define DEFINE_INIT(name, domain) void name(Domain *domain)
#define DEFINE_ADJUST(name, domain) void name(Domain *domain)

The file udf.h is a fluent header file in the {Fluent installed


directory}/FluentX.Y/src/ directory
The line:
include udf.h
must be at the top of every file defining any UDFs
A file may contain more than one UDF function definition
Multiple files can be used to define different related sets of functions

Therearemanymoreheaderfilesstoredinthesamedirectorywhich
canbebrowsedbyusersbutmostarealreadyincludedautomatically
withinudf.h
31 2012ANSYS,Inc. March14,2012 Release14.0