0% found this document useful (0 votes)
360 views31 pages

Fluent - 14.0 Udf

This document discusses user-defined functions in ANSYS Fluent. UDFs allow customization of many aspects of a CFD model through functions written in C. The document covers what UDFs can do, basic steps to write and use a UDF, examples of imposing boundary conditions and initializing conditions, and use of macros to access data in the solver.

Uploaded by

vahidss
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
360 views31 pages

Fluent - 14.0 Udf

This document discusses user-defined functions in ANSYS Fluent. UDFs allow customization of many aspects of a CFD model through functions written in C. The document covers what UDFs can do, basic steps to write and use a UDF, examples of imposing boundary conditions and initializing conditions, and use of macros to access data in the solver.

Uploaded by

vahidss
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

Lecture11

UserDefinedFunctions
14.0Release

IntroductiontoANSYS
FLUENT
1

2011ANSYS,Inc.

January19,2012

Release14.0

Introduction
LectureTheme:
Userdefinedfunctions(UDFs)enablethecustomizationofmanyaspects
ofaCFDmodel,includingboundaryandcellzoneconditions,material
properties,dataoutput,andsolutionexecution.Dataexchangebetween
theUDFandthesolvertakesplaceviapredefinedmacros.
LearningAims:
Youwilllearn:
WhatUDFscando
HowtowriteandcompileabasicUDF
HowtohookUDFstotheFLUENTinterface
LearningObjectives:
AlmostallFLUENTuserswillenduphavingtowriteshortUDFsfromtime
totime.Youwillseehowthiscanbedoneeasily,evenwithonlya
rudimentaryunderstandingoftheCprogramminglanguage.
Intro
2

DataStructure&Macros Examples UserDefinedMemory&Scalars

2011ANSYS,Inc.

January19,2012

Summary
Release14.0

UDFOverview
WhatisaUserDefinedFunction?
AUDFisafunction(programmedbytheuser)writteninCwhichcanbe

dynamicallylinkedwiththeFLUENTsolver.
StandardCfunctions
Trigonometric,exponential,controlblocks,doloops,filei/o,etc.
PreDefinedMacros
Allowsaccesstofieldvariable,materialproperty,andcellgeometry
dataandmanyutilities
AlldataexchangedbetweentheUDFandthesolvermustbeinSIunits

WhyprogramUDFs?
Standardinterfacecannotbeprogrammedtoanticipateallneeds:

Customizationofboundaryconditions,sourceterms,reactionrates,
materialproperties,etc.
Customizationofphysicalmodels
Usersuppliedmodelequations
Adjustfunctions(onceperiteration)
ExecuteonDemandfunctions
SolutionInitialization

Intro
3

DataStructure&Macros Examples UserDefinedMemory&Scalars

2011ANSYS,Inc.

January19,2012

Summary
Release14.0

Interpretedvs.CompiledUDFs
UDFscaneitherberuncompiledorinterpreted.
ThesupportedcompilerforFLUENTonWindowsplatformsisMicrosoft

VisualStudio
MostLinuxsystemsprovideaCcompilerasastandardfeature.

Interpretedcodevs.compiledcode
Interpreted

C++InterpreterbundledwithFLUENT
Interpreterexecutescodeonalinebylinebasisinstantaneously.
Advantage Doesnotrequireathirdpartycompiler.
Disadvantage Interpreterisslow,andcannotdosomefunctions.

Compiled

UDFcodeistranslatedonceintomachinelanguage(objectmodules).
EfficientwaytorunUDFs.
Createssharedlibrarieswhicharelinkedwiththerestofthesolver.
Doesrequireacompilationstepbetweencreating/editingyourUDFand
usingit.

Intro
4

DataStructure&Macros Examples UserDefinedMemory&Scalars

2011ANSYS,Inc.

January19,2012

Summary
Release14.0

FluentUDFDataStructure
Thecellzonesandfacezonesofamodel(inthefinitevolumescheme)areaccessed
inUDFsasThread datatypes

Thread isaFLUENTdefineddatatype
Domain
Cell

Domain

Face
Node

Cell
Thread

Face
Thread

Cells

Faces

Boundary thread e.g. wall

Cell thread e.g. fluid

Inordertoaccessdatainathread(zone),
weneedtoprovidethecorrectthreadpointer,anduseFLUENTprovidedlooping
macrostoaccesseachmember(cellorface)inthatthread.
Intro
5

DataStructure&Macros Examples UserDefinedMemory&Scalars

2011ANSYS,Inc.

January19,2012

Summary
Release14.0

UDFStepbyStep
ThebasicstepsforusingUDFsinFLUENTareasfollows:
1. Identifytheproblemtobesolved
2. Checktheusability&limitationsofthestandardmodelsofFLUENT
3. ProgramtheUDF(mustbewritteninC)
4. CompiletheUDFintheFLUENTsession
5. AssigntheUDFtotheappropriatevariableandzoneinBCpanel
6. Runthecalculation
7. Examinetheresults

Intro
6

DataStructure&Macros Examples UserDefinedMemory&Scalars

2011ANSYS,Inc.

January19,2012

Summary
Release14.0

Example ParabolicInletVelocityProfile
Example ParabolicInletVelocityProfile

Intro
7

DataStructure&Macros Examples UserDefinedMemory&Scalars

2011ANSYS,Inc.

January19,2012

Summary
Release14.0

Step1 IdentifytheProblemtoSolve
Wewouldliketoimposeaparabolicinletvelocitytothe2D
elbowshown.

Thex velocityistobespecifiedas:

y=0

Intro
8

DataStructure&Macros Examples UserDefinedMemory&Scalars

2011ANSYS,Inc.

January19,2012

Summary
Release14.0

Step2 PreparetheSourceCode
Header file udf.h must be included at the top
of the program by the #include command

The DEFINE_PROFILE macroallowsthe


function x_velocity tobedefined.

Thecodeisstoredasatextfile
inlet_bc.c

AllUDFsbeginwithaDEFINE_ macro
ThenamethatwillappearintheGUI
willbex_velocity

Themacrobegin_f_loop loops

#include "udf.h"
DEFINE_PROFILE(x_velocity,thread,nv)
{
float pos[3]; /* an array for the
coordinates */
float y;
face_t f;
/* f is a face
thread index */

overallfacesf,pointedbythread

begin_f_loop(f, thread)
{
F_CENTROID(pos,f,thread);
y = pos[1];
F_PROFILE(f, thread, nv)
= 20.*(1.y*y/(.0745*.0745));
}
end_f_loop(f, thread)

TheF_CENTROID macroassigns
cellpositionvectorto pos[]
pos[0]isthexcoordinate
pos[1]istheycoordinate
pos[2]isthezcoordinate

The F_PROFILE macroappliesthe

velocitycomponenttofacef, using
thedesiredarithmeticfunction

Intro
9

DataStructure&Macros Examples UserDefinedMemory&Scalars

2011ANSYS,Inc.

January19,2012

Summary
Release14.0

Step3 CompiletheUDFintheFLUENTSession
InterpretedUDF

CompiledUDF
Define

User-Defined

Functions

Compiled

AddtheUDFsourcecodetotheSourceFileslist
ClickBuildtocompileandlinkthecode
Ifnoerrors,clickLoadtoloadthelibrary
Youcanalsounloadalibraryifneeded.
/define/user-defined/functions/manage

Intro
10

Define

User-Defined

Functions

AddtheUDFsourcecodetotheSourceFileName
list.
ClickInterpret
Theassemblylanguagecodewilldisplayinthe
FLUENTconsole
ClickCloseifthereisnoerror

DataStructure&Macros Examples UserDefinedMemory&Scalars

2011ANSYS,Inc.

January19,2012

Interpreted

Summary
Release14.0

Step4 HooktheUDFinFLUENTGUI
Opentheboundaryconditionpanelforthesurfacetowhichyouwouldliketo
applytheUDF

SwitchfromConstanttoudf x_velocity inthedropdownlist


ThemacronameisthefirstargumentofDEFINE_PROFILE intheUDFcode

Intro
11

DataStructure&Macros Examples UserDefinedMemory&Scalars

2011ANSYS,Inc.

January19,2012

Summary
Release14.0

Step5 RuntheCalculations
YoucanchangetheProfileUpdateIntervalintheRunCalculation
panel(defaultvalueis1)
Thissettingcontrolshowoften(eitheriterationsortimestepsifunsteady)theUDF
profileisupdated

Runthecalculation
asusual
Intro
12

DataStructure&Macros Examples UserDefinedMemory&Scalars

2011ANSYS,Inc.

January19,2012

Summary
Release14.0

Step6 ExaminetheResults
Thefigureontheleftshowsthevelocityfieldthroughthe2D
elbow

Thefigureontherightshowsthevelocityvectorsattheinlet.
Noticetheimposedparabolicvelocityprofile

Intro
13

DataStructure&Macros Examples UserDefinedMemory&Scalars

2011ANSYS,Inc.

January19,2012

Summary
Release14.0

Example2 CustomInitialization
Initialize:
Atemperatureof600K
insideasphere,withitscenterat(0.5,0.5,

0.5),
radiusof0.25,
and300Kthroughouttherestofthedomain.

ThedomainpointerispassedtothisUDF
throughtheargument

thread_loop_c macroisusedtoaccessall
cellthreads(zones),and begin_c_loop
macroisusedtoaccesscellswithineachcell
thread

C_T(c,ct)allowsaccesstothecell
temperature.

Therearesimilarlynamedmacrosforall

othersolutionvariables
Anextensivelistofthesemacroscanbe
foundintheappendix

DeploythisUDFasauserdefined
functionhookin

Define>UserDefined>FunctionHooks
(moredetailsinAppendix)
Intro
14

#include "udf.h
DEFINE_INIT(my_init_function, domain)
{
cell_t c;
Thread *ct;
real xc[ND_ND];
thread_loop_c(ct,domain)
{
begin_c_loop (c,ct)
{
C_CENTROID(xc,c,ct);
if (sqrt(ND_SUM(pow(xc[0]-0.5,2.),
pow(xc[1] - 0.5,2.),
pow(xc[2] - 0.5,2.))) < 0.25)
C_T(c,ct) = 600.;
else
C_T(c,ct) = 300.;
}
end_c_loop (c,ct)
}
}

DataStructure&Macros Examples UserDefinedMemory&Scalars

2011ANSYS,Inc.

January19,2012

Summary
Release14.0

UseofMacrosintheExamples
UDFscommunicatewiththesolverthroughpredefinedmacros
Macroscanbelooselycategorizedaseither(withexamplesfromthepreviousslides)
DEFINEmacros

DEFINE_PROFILE(x_velocity,thread,nv),DEFINE_INIT(my_init_function,domain)
Loopingmacros
thread_loop_c (ct,domain){...},begin_f_loop(f,thread){...}end_f_loop(f,thread)
Dataaccessmacros
Domain*d;thread*t;cell_t c;face_t f;
Geometrymacros
C_CENTROID(xc,c,ct)
Solutiondatamacros
C_T(c,t)

Moreexamplesofeachtypeofmacroaredescribedintheappendix
StillmanymoreDEFINEmacrosareavailableinthefollowingcategoriesandaredocumented
intheUDFmanual:

Turbulencemodels
Multiphasemodels
Reactingflows
Dynamicmesh
Input/Output

Intro
15

DataStructure&Macros Examples UserDefinedMemory&Scalars

2011ANSYS,Inc.

January19,2012

Summary
Release14.0

UserDefinedMemory
Whilemacrosareavailableforallsolution

Define

User-Defined

Memory

variables,forinstanceC_TinExample2,
sometimesitcanbehelpfultocreate
additionalvariables

Forinstancetostorevalueofcustomsource
terms,orcustompostprocessingvariables

ThiscanbedonewithUserDefined
Memoryvariables,whichareuser
allocatedmemoryforeachcell

Upto500fieldvariablescanbedefined
TheUDFmacrosforcellvaluesandface
values,respectively,are
C_UDMI(cell,thread,index);
F_UDMI(face,thread,index);

InformationisstoredintheFLUENT

datafileandcanbeaccessedinpost
processingoperationssuchascontourplots

Intro
16

DataStructure&Macros Examples UserDefinedMemory&Scalars

2011ANSYS,Inc.

January19,2012

Summary
Release14.0

UserDefinedScalars(UDS)
FLUENTcansolveupto50generictransportequationsforuserdefined
scalars
TheUDSequationscanbesolvedasastandardsteadyortransientconvectiondiffusion
transportequation,ortheycanbecustomizedthroughUDFs,torepresentotherpartial
differentialequations,forinstancetheelectromagneticfieldequations
AlltermsintheequationscanbecontrolledthroughUDFs

Unsteady

Convection Diffusion

DEFINE_UDS_UNSTEADY
DEFINE_UDS_FLUX

Intro
17

Source
DEFINE_SOURCE

DEFINE_DIFFUSIVITY

DataStructure&Macros Examples UserDefinedMemory&Scalars

2011ANSYS,Inc.

January19,2012

Summary
Release14.0

WheretoGetMoreInformationandHelp
UDFUserGuide
Installedonyourmachinealreadyaspartofstandardinstallation
Containsmacrodefinitions,numerouscodeexamplesandcodefragments.

StartyourownUDFprogrambymodifyinganexistingUDFprogramwhich
isclosetowhatyouwanttodo,thenstepbystepaddyourowncodeto
theprogram.

AttendtheAdvancedUDFTrainingcourse
BecauseUDFscanbeverycomplicated,ANSYSdoesnotassume
responsibilityfortheaccuracyorstabilityofsolutionsobtainedusinguser
generatedUDFs.

Supportwillbegenerallybelimitedtoguidancerelatedtocommunication
betweenUDFsandtheFLUENTsolver,wecannothelpdebugclients
UDFs.
Intro
18

DataStructure&Macros Examples UserDefinedMemory&Scalars

2011ANSYS,Inc.

January19,2012

Summary
Release14.0

Appendix

19

2011ANSYS,Inc.

January19,2012

Release14.0

UserAccesstotheFLUENT Solver
SOLVERS

Initialize

Begin Loop

Userdefined
ADJUST

Solver?
Source terms

User Defined
INITIALIZE

Segregated

PBCS

Solve U-Momentum

Source terms

Solve V-Momentum

Solve Mass
& Momentum

Solve W-Momentum
Repeat

Exit Loop

Solve Mass,
Momentum,
Energy,
Species

Source terms

Solve Mass Continuity;


Update Velocity

Check Convergence

Solve Energy
Update Properties

User-Defined Properties

DBCS

Solve Species

Source
terms

Solve Turbulence Equation(s)

User-Defined BCs
Solve Other Transport Equations as required

20

2011ANSYS,Inc.

January19,2012

Release14.0

FLUENTDataStructure
Inordertoaccessdatainathread(zone),weneedto:
ProvidethecorrectThreadpointer:
Type

Variable

Meaning of the declaration

Domain
Thread
cell_t
face_t
Node

*d;
*t;
c;
f;
*node;

d is the user name of a pointer to domain Thread


t is the user name of a pointer to Thread
c is the user name of a Cell thread variable
f is the user name of Face thread variable
node is the user name of a pointer to a Node

useFLUENTprovidedloopmacrotoaccesseachmember
(cellorface)inthatThread:
thread_loop_c(ct,d) {
thread_loop_f(ft,d) {

} Loopoverallcellthreadsindomaind;
} Loopoverallfacethreadsindomaind;

Loopoverallcellsinacellthreadt;
begin_c_loop(c,t)
{}
end_c_loop (c,t)
21

2011ANSYS,Inc.

January19,2012

Release14.0

Step3:ProgramtheUDF
ToprogramtheUDF,weneedtousetwoMacros:
onetoperformtheboundaryconditionassignment(DEFINE_PROFILE),
andanothertoloopoverthecentroids oftheinletfaces(begin_f_loop),
Header File > declaration of all the Fluent data structures used by the source code
include "udf.h
#define U_MAX 20.0
#define PITCH 0.0745

name of the UDF (that would appears in the FLUENTs panels)


Thread of the zone in which the UDF would be assign

DEFINE_PROFILE(velocity_profile, thread, position)


{
declaration of the Face Thread index named : face
real pos[ND_ND];
(the name is given by the user)
face_t face;

}
22

Store the coordinates of the Face Centroids into vector pos[ ]


begin_f_loop(face, thread)
{
F_CENTROID(pos,face,thread);
F_PROFILE(face, thread, position) =U_MAX*(1.0-sqr(pos[1]/PITCH));
}
end_f_loop(face, thread)
F_PROFILE > assign the UDF profile
Loop over all the Faces of the Boundary Condition

2011ANSYS,Inc.

January19,2012

Release14.0

OverviewofFLUENTMacros
Macrosaredefinedinheaderfiles
Theudf.h headerfileMUST beincludedinyoursourcecode
#include udf.h

Theheaderfilesmustbeaccessibleinyourpath
TypicallystoredinFluent.Inc/src/ directory

AlistofoftenusedmacrosisprovidedintheUDFUsersGuide

23

2011ANSYS,Inc.

January19,2012

Release14.0

DEFINE_Macros
AnyUDFyouwriteMUST beginwithaDEFINE_ macro
MostoftenusedDEFINE_macros :
DEFINE_ADJUST(name,domain); generalpurposeUDFcalledeveryiteration
DEFINE_INIT(name,domain); UDFusedtoinitializefieldvariables
DEFINE_ON_DEMAND(name); anexecuteondemandfunction
DEFINE_PROFILE(name,thread,index); boundaryprofiles
DEFINE_SOURCE(name,cell,thread,dS,index); equationsourceterms
DEFINE_PROPERTY(name,cell,thread); materialproperties
DEFINE_DIFFUSIVITY(name,cell,thread,index); UDSandspeciesdiffusivities
DEFINE_UDS_FLUX(name,face,thread,index); definesUDSfluxterms
DEFINE_UDS_UNSTEADY(name,cell,thread,index,apu,su); UDStransientterms
DEFINE_DELTAT(name,domain); variabletimestepsizeforunsteadyproblems
24

2011ANSYS,Inc.

January19,2012

Release14.0

DEFINE_Macros UDFHooks
SomeDEFINE_macrosarehookedintothesolverusingthe
UserDefinedFunctionHookspanel

Define

Initialization

User-Defined

Function Hooks

Executesonceperinitialization

Solutionadjustment
Executeseveryiteration

Wallheatflux
Definesfluidsidediffusiveandradiative
wallheatfluxesintermsofheattransfer
coefficients
Appliestoallwalls

Userdefinedsurfaceandvolumetric
reactions

Read/writeto/fromcaseanddatafiles
Readorderandwriteordermustbesame

ExecuteonDemandcapability
Doesnotparticipateinthesolveriterations

25

2011ANSYS,Inc.

January19,2012

Release14.0

GeometryandTimeMacros

26

C_NNODES(c,t);
C_NFACES(c,t);
F_NNODES(f,t);
C_CENTROID(x,c,t);
F_CENTROID(x,f,t);
F_AREA(A,f,t);
C_VOLUME(c,t);
C_VOLUME_2D(c,t);

Returnsnodes/cell
Returnsfaces/cell
Returnsnodes/face
Returnscoordinatesofcellcentroid inarray x[]
Returnscoordinatesoffacecentroid inarrayx[]
ReturnsareavectorinarrayA[]
Returnscellvolume
Returnscellvolume(axisymmetric domain)

CURRENT_TIME

realcurrentflowtime(inseconds)

CURRENT_TIMESTEP

realcurrentphysicaltimestepsize(inseconds)

PREVIOUS_TIME

realpreviousflowtime(inseconds)

PREVIOUS_2_TIME

realflowtimetwostepsbackintime(inseconds)

PREVIOUS_TIMESTEP

realpreviousphysicaltimestepsize(inseconds)

N_TIME

integernumberoftimesteps

N_ITER

integernumberofiterations

2011ANSYS,Inc.

January19,2012

Release14.0

CellFieldVariableMacros
C_R(c,t);

Density

C_DVDX(c,t);

Velocityderivative

C_P(c,t);

Pressure

C_DVDY(c,t);

Velocityderivative

C_U(c,t);

Uvelocity

Velocityderivative

C_V(c,t);

C_DVDZ(c,t);

Vvelocity

C_W(c,t);

Wvelocity

C_DWDX(c,t);

Velocityderivative

C_T(c,t);

Temperature

C_DWDY(c,t);

Velocityderivative

C_H(c,t);

Enthalpy

C_DWDZ(c,t);

Velocityderivative

C_K(c,t);

Turbulentkineticenergy(k)

C_D(c,t);

Turbulentdissipationrate()

C_MU_L(c,t);

Laminarviscosity

C_O(c,t);

Specificdissipationofk ()

C_MU_T(c,t);

Turbulentviscosity

C_YI(c,t,i);

Speciesmassfraction

C_MU_EFF(c,t); Effectiveviscosity

C_UDSI(c,t,i);

UDSscalars

C_K_L(c,t);

Laminarthermalconductivity

C_UDMI(c,t,i);

UDMscalars

C_K_T(c,t);

Turbulentthermalconductivity

C_DUDX(c,t);

Velocityderivative

C_K_EFF(c,t);

Effectivethermalconductivity

C_DUDY(c,t);

Velocityderivative

C_CP(c,t);

Specificheat

C_DUDZ(c,t);

Velocityderivative

C_RGAS(c,t);

Gasconstant

27

2011ANSYS,Inc.

January19,2012

Release14.0

UserDefinedScalars
UDSMacrosHooks(1):

Define

User-Defined

Scalars

NumberofUDSvariables
ZonesinwhichtheUDSissolved

FluxFunction
DEFINE_UDS_FLUX(name,face,thread,index)

Unsteadyfunction
DEFINE_UDS_UNSTEADY(name,cell,thread,index,apu,su)
Ifstatementsarerequiredinordertoassociatemultiplefluxand
transientfunctionswitheachUDS

28

2011ANSYS,Inc.

January19,2012

Release14.0

UserDefinedScalars
UDSMacrosHooks(2):
Sourceterm
DEFINE_SOURCE(name,cell,thread,dS,index)

29

2011ANSYS,Inc.

January19,2012

Release14.0

UserDefinedScalars
UDSMacrosHooks(3):
Diffusivity
DEFINE_DIFFUSIVITY(name,cell,thread,index)

30

2011ANSYS,Inc.

January19,2012

Release14.0

UserDefinedScalars
UDSMacrosHooks(4):
BoundaryConditions
SpecifiedFluxorSpecifiedValue
DefineasconstantorwithUDF

DEFINE_PROFILE(name,thread,index)

31

2011ANSYS,Inc.

January19,2012

Release14.0

You might also like