Vous êtes sur la page 1sur 21

20/12/2014

APDL:Chapter4:APDLasaMacroLanguage(UP19980820)

Chapter4:APDLasaMacroLanguage
GototheNextChapter
GotothePreviousChapter
GototheTableofContentsforThisManual.
Chapter1*Chapter2*Chapter3*Chapter4*Chapter5*Chapter6

4.1WhatisanAPDLMacro?
YoucanrecordafrequentlyusedsequenceofANSYScommandsinamacrofile(thesearesometimes
calledcommandfiles).Creatingamacroenablesyouto,ineffect,createyourowncustomANSYS
command.Forexample,calculatingpowerlossduetoeddycurrentsinamagneticanalysiswouldrequire
aseriesofANSYScommandsinthepostprocessor.Byrecordingthissetofcommandsinamacro,you
haveanew,singlecommandthatexecutesallofthecommandsrequiredforthatcalculation.Inaddition
toexecutingaseriesofANSYScommands,amacrocancallGUIfunctionsorpassvaluesinto
arguments.
Youcanalsonestmacros.Thatis,onemacrocancallasecondmacro,thesecondmacrocancallathird
macro,andsoon.Youcanuseupto20nestinglevels,includinganyfileswitchescausedbytheANSYS
/INPUTcommand.Aftereachnestedmacroexecutes,theANSYSprogramreturnscontroltothe
previousmacrolevel.
Thefollowingisaverysimpleexamplemacrofile.Inthisexample,themacrocreatesablockwith
dimensions4,3,and,2andaspherewitharadiusof1.Itthensubtractsthespherefromonecornerofthe
block.
/prep7
/view,,1,2,3
block,,4,,3,,2
sphere,1
vsbv,1,2
finish

Ifthismacrowerecalledmymacro.mac,youcouldexecutethissequenceofcommandswiththe
followingsingleANSYScommand
*use,mymacro

or(becausetheextensionis.mac)
mymacro

Clearly,thisisn'taterriblyusefulmacro,butitdoesillustratetheprinciple.
Thischapterprovidesinformationonthevariouswaysyoucancreate,store,andexecutemacros.Italso
discussesthebasicinformationyouneedtouseAPDLasascriptinglanguageincreatingmacros.

http://mostreal.sk/html/prog_55/gapdl/AS4.htm#S4.1

1/21

20/12/2014

APDL:Chapter4:APDLasaMacroLanguage(UP19980820)

4.2CreatingaMacro
YoucancreatemacroseitherwithinANSYSitselforusingyourtexteditorofchoice(suchasemacs,vi,
orwordpad).Ifyourmacroisfairlysimpleandshort,creatingitinANSYScanbeveryconvenient.If
youarecreatingalonger,morecomplexmacrooreditinganexistingmacrothenyou'llneedatexteditor.
Also,usingatexteditorallowsyoutouseasimilarmacroorANSYSlogfileasthesourceforyour
macro.
Foranylong,complexmacroyoushouldalwaysconsidereitherusingasimilarmacroasastartingpoint
orrunningthetaskinteractivelyinANSYSandusingtheresultinglogfileasthebasisofyourmacro.
Eithermethodcangreatlyreducethetimeandeffortrequiredtocreateasuitablemacro.

4.2.1MacroFileNamingConventions
MacrosarenothingmorethanasequenceofANSYScommandsstoredinafile.Macrosshouldnothave
thesamenameasanexistingANSYScommandANSYSwillexecutetheinternalcommandinsteadof
themacro.Thefollowingnamingrestrictionsapplytomacrofiles:
Thefilenamecannotexceed32characters.
Thefilenamecannotbeginwithanumeral.
Thefileextensioncannotcontainmorethaneightcharacters(ifyouareexecutingthemacroasifit
wereanANSYScommanditshouldhavetheextension.mac.)
Thefilenameorextensioncannotcontainspaces.
Thefilenameorextensioncannotcontainanycharactersprohibitedbyyourfilesystemandfor
portabilityshouldn'tcontainanycharactersprohibitedbyeitherUNIXorWindowsfilesystems.
Toensurethatyouaren'tusingthenameofanANSYScommand,beforecreatingamacrotryrunning
thefilenamethatyouwishtouseasanANSYScommand.IfANSYSreturnsthemessageshownbelow,
you'llknowthatthecommandisnotusedinthecurrentprocessor.Tobe"safe,"youshouldcheckthe
macrofilenameineachprocessorinwhichyouplantousethemacro.(Youcouldalsocheckifthe
macrofilenamematchesanycommandlistedintheonlinedocumentationhowever,thismethodcan't
locatethenamesofundocumentedcommands.)
Figure41ANSYSmessageboxstatingthatanunknowncommandwasissued.

Usingthe.macextensionallowsANSYStoexecutethemacroasitwouldanyinternalcommand.The
extension.MACisusedforANSYSinternalmacrosandyoushouldavoidusingthis.

4.2.2MacroSearchPath
Bydefault,ANSYSsearchesforausermacrofile(.macextension)inthefollowinglocations:
http://mostreal.sk/html/prog_55/gapdl/AS4.htm#S4.1

2/21

20/12/2014

APDL:Chapter4:APDLasaMacroLanguage(UP19980820)

1.Thedirectory(ordirectories)designatedbytheANSYS_MACROLIBenvironmentvariable(if
defined)orthelogin(home)directory.ThisenvironmentvariableisdocumentedintheANSYS
installationandconfigurationguideforyourplatform.
2.Thedirectorydesignatedby/PSEARCHcommand(ifdefined).Thisdirectoryissearchedbeforethe
logindirectory,butafterthedirectorydesignatedbytheANSYS_MACROLIBenvironmentvariable.
3.Thecurrentdirectory.
Youcanplacemacrosforyourpersonaluseinyourhomedirectory.Macrosthatshouldbeavailable
acrossyoursiteshouldbeplacedintheANSYSdocumentationdirectoryorsomecommonlyaccessible
directorythateveryonecanreferencethroughtheANSYS_MACROLIBenvironmentvariable.
ForWindows95users:Youmustdesignatethe"homedirectory"anddriveusingenvironment
variables,seetheANSYSInstallationandConfigurationGuideforWindows.
ForWindowsNTusers:The"currentdirectory"isthedefaultdirectory(usuallyanetwork
resource)setbyadministratorsandyoushouldaskyournetworkadministratorforitslocation.You
canuseenvironmentvariablestocreatealocal"homedirectory."Thelocalhomedirectoryis
checkedafterthedefaultdirectorydesignatedinyourdomainprofile.SeetheANSYSInstallation
andConfigurationGuideforWindowsformoreinformation.

4.2.3CreatingaMacroWithinANSYS
YoucancreateamacrobythreemethodsfromwithinANSYS
Issuingthe*CREATEcommandintheinputwindow.Parametervaluesarenotresolvedand
parameternamesarewrittentothefile.
Usingthe*CFOPEN,*CFWRITE,and*CFCLOScommands.Parameternamesareresolvedto
theircurrentvaluesandthosevaluesarewrittentothemacrofile.
ChoosingtheUtilityMenu>Macro>CreateMacromenuitem.Thismethodopensadialogbox
thatcanbeusedasasimple,multilineeditorforcreatingmacros.Parametervaluesarenot
resolvedandparameternamesarewrittentothefile.
Thefollowingsectionsdetaileachofthesemethods.

4.2.3.1Using*CREATE
Issuing*CREATEredirectsANSYScommandsenteredinthecommandinputwindowtothefile
designatedbythecommand.Allcommandsareredirecteduntilyouissuethe*ENDcommand.Ifan
existingfilehasthesamenameasthemacrofilenameyouspecify,theANSYSprogramoverwritesthe
existingfile.
Forexample,supposethatyouwanttocreateamacrocalledmatprop.mac,whichautomaticallydefines
asetofmaterialproperties.Thesetofcommandsenteredintotheinputwindowforthismacromight
looklikethis:
*CREATE,matprop,mac,macros\
MP,EX,1,2.07E11
MP,NUXY,1,.27
MP,DENS,1,7835
MP,KXX,1,42
http://mostreal.sk/html/prog_55/gapdl/AS4.htm#S4.1

3/21

20/12/2014

APDL:Chapter4:APDLasaMacroLanguage(UP19980820)

*END

The*CREATEcommandtakesargumentsofthefilename,thefileextension,andthedirectorypath(in
thiscase,themacrosdirectoryisspecified).NotethatUNIXusersmustappendaslashtotheendofthe
directorypath.
Whenusing*CREATE,allparametersusedincommandsarewrittentothefile(thecurrentlyassigned
valuesfortheparameterarenotsubstituted).Ifyourcurrentparametervaluesareimportant,youcansave
theparameterstoafileusingthePARSAVcommand.

4.2.3.2Using*CFWRITE
Ifyouwishtocreateamacrofileinwhichcurrentvaluesaresubstitutedforparametersyoucanuse
*CFWRITE.Unlike*CREATE,the*CFWRITEcommandcan'tspecifyamacronameyoumustfirst
specifythemacrofilewiththe*CFOPENcommand.OnlythoseANSYScommandsthatareexplicitly
prefacedwitha*CFWRITEcommandarethenwrittentothedesignatedfileallothercommands
enteredinthecommandinputwindowareexecuted.Aswiththe*CREATEcommand,*CFOPENcan
specifyafilename,afileextension,andapath.ThefollowingexamplewritesaBLOCKcommandto
thecurrentlyopenmacrofile.
*cfwrite,block,,a,,b,,c

NotethatparameterswereusedforargumentstotheBLOCKcommand.Thecurrentvalueofthose
parameters(andnottheparameternames)arewrittentothefile.So,forthisexample,thelinewrittento
themacrofilemightbe
*cfwrite,block,,4,,2.5,,2

Toclosethemacrofile,issuethe*CFCLOScommand.
NoteWhileitispossibletocreateamacrothroughthismethod,thesecommandsaremostusefulasa
methodforwritingANSYScommandstoafileduringmacroexecution.

4.2.3.3UsingUtilityMenu>Macro>CreateMacro
ChoosingthismenuitemopensanANSYSdialogboxthatyoucanuseasasimpleeditorforcreating
macros.Youcannotopenandeditanexistingmacrowiththisfacilityifyouusethenameofanexisting
macroastheargumentsforthe*CREATEfieldtheexistingfilewillbeoverwritten.
Figure42TheUtilityMenu>Macro>CreateMacrodialog,shownwithasimplemacro.

http://mostreal.sk/html/prog_55/gapdl/AS4.htm#S4.1

4/21

20/12/2014

APDL:Chapter4:APDLasaMacroLanguage(UP19980820)

Aswiththe*CREATEcommand,parametersarenotevaluatedbutarewrittenverbatimintothemacro
file.Notethatyoudonotmakethelastlinea*ENDcommand.

4.2.4CreatingMacroswithaTextEditor
Youcanuseyourfavoritetexteditortocreateoreditmacrofiles.AnyASCIIeditorwillwork.
Moreover,ANSYSmacroscanhavetheirlinesterminatedbyeitherUNIXorWindowslineending
conventions(carriagereturn,linefeedpairsorsimplylinefeeds)soyoucancreateamacroonone
platformanduseitonseveralplatforms.
Ifyouusethismethodtocreatemacros,don'tincludethe*CREATEand*ENDcommands.
Figure43ASimpleMacroCreatedinaTextEditor.

4.2.5UsingMacroLibraryFiles
http://mostreal.sk/html/prog_55/gapdl/AS4.htm#S4.1

5/21

20/12/2014

APDL:Chapter4:APDLasaMacroLanguage(UP19980820)

Asaconvenience,ANSYSallowsyoutoplaceasetofmacrosinasinglefile,calledamacrolibraryfile.
Youcancreatetheseeitherthroughthe*CREATEcommandorthroughatexteditor.Giventhatmacro
librariestendtobelongerthansinglemacros,usingatexteditornormallyprovidesthebestapproach.
Macroslibrarieshavenoexplicitfileextensionandfollowthesamefilenamingconventionsasmacro
files.Amacrolibraryfilehasthefollowingstructure:
MACRONAME1
.
.
.
/EOF
MACRONAME2
.
.
.
/EOF
MACRONAME3
.
.
.
./EOF

Forexample,thefollowingmacrofilecontainstwosimplemacros:
mybloc
/prep7
/view,,1,2,3
block,,4,,3,,2
finish
/EOF
mysphere
/prep7
/view,,1,2,3
sphere,1
finish
/EOF

Notethateachmacroisprefacedwithamacroname(sometimesreferedtoasadatablockname)and
endswitha/EOFcommand.
Amacrolibraryfilecanresideanywhereonyoursystem,althoughforconvenienceyoushouldplaceit
withinthemacrosearchpath.Unlikemacrofiles,amacrolibraryfilecanhaveanyextensionuptoeight
characters.

4.3ExecutingMacrosandMacroLibraries
Youcanexecuteanymacrofilebyissuingthe*USEcommand.Forexample,toexecutethemacro
calledMYMACRO(noextension)residingsomewhereinthemacrosearchpath,youwouldissue
*use,mymacro

Inthiscase,themacrotakesnoarguments.IfinsteadthemacrowascalledMYMACRO.MACROand
residedin/myaccount/macros,youcouldcallitwith
http://mostreal.sk/html/prog_55/gapdl/AS4.htm#S4.1

6/21

20/12/2014

APDL:Chapter4:APDLasaMacroLanguage(UP19980820)

*use,/myaccount/macros/mymacro.macro

Notethatthe*USEcommandallowsyoutoenterthepathandextensionalongwiththefilenameand
thatthesearenotenteredasseparatearguments.
Ifamacrohasa.macfileextensionandresidesinthesearchpath,youcanexecuteitasifitwerean
ANSYScommandbysimplyenteringitinthecommandinputwindow.Forexample,tocall
mymacro.macyoucouldsimplyenter
mymacro

Youcanalsoexecutemacroswitha.macextensionthroughtheUtilityMenu>Macro>ExecuteMacro
menuitem.
Ifthesamemacrotakesarguments(seeSection4.4.1formoreinformationaboutpassingargumentsto
macros),thenthesecanbeenteredonthecommandlineasfollows
mymacro,4,3,2,1.5

or
*use,mymacro.mac,4,3,2,1.5

TheUtilityMenu>Macro>ExecuteMacromenuitemdialogprovidesfieldsforarguments.
Executingmacroscontainedinmacrolibrariesissimilar.Youmustfirstspecifythelibraryfileusingthe
*ULIBcommand.Forexample,tospecifythatmacrosareinthemymacros.mlibfile,whichresidesin
the/myaccount/macrosdirectory,youwouldissuethefollowingcommand:
*ulib,mymacros,mlib,/myaccount/macros/

Afterselectingamacrolibrary,youcanexecuteanymacrocontainedinthelibrarybyspecifyingit
throughthe*USEcommand.Aswithmacroscontainedinindividualfiles,youcanspecifyargumentsas
parametersinthe*USEcommand.
NoteYoucan'tusethe*USEcommandtoaccessmacrosnotcontainedinthespecifiedmacrolibraryfile
afterissuingthe*ULIBcommand.

4.4LocalVariables
APDLprovidestwosetsofspeciallynamedscalarparameterswhichareavailableforuseaslocal
variables.Theseconsistof
Asetofscalarparametersthatprovideawayofpassingcommandlineargumentstothemacro.
Asetofscalarparametersthatcanbeusedwithinthemacro.Theseprovideasetoflocalvariables
thatcanbeusedtodefinevaluesonlywithinthatmacro.
Thefollowingsectionsdiscussbothofthesevariabletypesindetail.

4.4.1PassingArgumentstoaMacro
http://mostreal.sk/html/prog_55/gapdl/AS4.htm#S4.1

7/21

20/12/2014

APDL:Chapter4:APDLasaMacroLanguage(UP19980820)

Thereare19scalarparametersthatyoucanusetopassargumentsfromthemacroexecutioncommand
linetothemacro.Thesescalarparameterscanbereusedwithmultiplemacrosthatis,theirvaluesare
localtoeachmacro.TheparametersarenamedARG1throughAR19andtheycanbeusedforanyofthe
followingitems:
Numbers
Alphanumericcharacterstrings(uptoeightcharactersenclosedinsinglequotes)
Numericorcharacterparameters
Parametricexpressions
NoteYoucanpassonlythevaluesofparametersARG1throughAR18toamacroasargumentswiththe
*USEcommand.IfyoucreateamacrothatcanbeusedasanANSYScommand(themacrofileshasa
.macextension),youcanpassthevaluesofparametersARG1throughAR19tothemacro.
Forexample,thefollowingsimplemacrorequiresfourarguments,ARG1,ARG2,ARG3,andARG4:
/prep7
/view,,1,2,3
block,,arg1,,arg2,,arg3
sphere,arg4
vsbv,1,2
finish

Toexecutethismacro,ausermightenter
mymacro,4,3,2.2,1

4.4.2LocalVariablesWithinMacros
Eachmacrocanhaveupto79scalarparametersusedaslocalvariables(AR20throughAR99).These
parametersarecompletelylocaltothemacro,andmultiplemacroscaneachhavetheirownunique
valuesassignedtotheseparameters.Theseparametersarenotpassedtomacroscalledfrommacros
(nestedmacros).Theyarepassedtoanyfilesprocessedthrougha/INPUTcommandora"doloop"
processedwithinthemacro.

4.4.3LocalVariablesOutsideofMacros
ANSYSalsohasasimilarsetofARG1throughAR99scalarparametersthatarelocaltoaninputfile,
andarenotpassedtoanymacroscalledbythatinputfile.Thus,onceamacrofinishesandexecution
returnstoaninputfile,thevaluesofARG1throughARG99reverttowhatevervaluesweredefined
withintheinputfile.

4.5ControllingProgramFlowinAPDL
Whenexecutinganinputfile,ANSYSisnormallyrestrictedtolinearprogramflowthatis,each
statementisexecutedintheorderthatitisencounteredinthelisting.However,APDLprovidesarichset
ofcommandsthatyoucanusetocontrolprogramflow.
Callsubroutines(nestedmacros).
Branchunconditionallytoaspecifiedlocationwithamacro.
http://mostreal.sk/html/prog_55/gapdl/AS4.htm#S4.1

8/21

20/12/2014

APDL:Chapter4:APDLasaMacroLanguage(UP19980820)

Branchbaseduponaconditiontoaspecifiedlocationwithinamacro.
Repeattheexecutionofasinglecommand,incrementingoneormorecommandparameters.
Loopthroughasectionofamacroaspecifiednumberoftimes.
Thefollowingsectionsdetaileachoftheseprogramcontrolcapabilities.Fortheexactsyntaxofthe
commands,refertotheANSYSCommandsReference.

4.5.1NestedMacros:CallingSubroutinesWithinaMacro
APDLallowsyoutonestmacrosupto20levelsdeep,providingfunctionallysimilarcapabilitytoa
FORTRAN77CALLstatementortoafunctioncall.Youcanpassupto19argumentstothemacroand,
attheconclusionofeachnestedmacro,executionreturnstothelevelthatcalledthemacro.Forexample,
thefollowingextremelysimplymacrolibraryfileshowstheMYSTARTmacro,whichcallsthe
MYSPHEREmacrotocreatethesphere.
mystart
/prep7
/view,,1,2,3
mysphere,1.2
finish
/eof
mysphere
sphere,arg1
/eof

4.5.2UnconditionalBranching:Goto
Thesimplestbranchingcommand,*GO,instructstheprogramtogotoaspecifiedlabelwithout
executinganycommandsinbetween.Programflowcontinuesfromthespecifiedlabel.Forexample
*GO,:BRANCH1
!Thisblockofcommandsisskipped(notexecuted)

:BRANCH1

Thelabelspecifiedbythe*GOcommandmuststartwithacolon(:)andmustnotcontainmorethan
eightcharacters,includingthecolon.Thelabelcanresideanywherewithinthesamefile.
NoteTheuseof*GOisnowconsideredobsoleteandisdiscouraged.Seetheotherbranchingcommands
forbettermethodsofcontrollingprogramflow.

4.5.3ConditionalBranching:The*IFCommand
APDLallowsyoutoexecuteoneofasetofalternativeblocksbasedontheevaluationofacondition.
Theconditionsareevaluatedbycomparingtwonumericalvalues(orparametersthatevaluateto
numericalvalues).
The*IFcommandhasthefollowingsyntax
http://mostreal.sk/html/prog_55/gapdl/AS4.htm#S4.1

9/21

20/12/2014

APDL:Chapter4:APDLasaMacroLanguage(UP19980820)

*IF,VAL1,Oper,VAL2,Base
Where
VAL1isthefirstnumericalvalue(ornumericalparameter)inthecomparison.
Operisthecomparisonoperator.
VAL2isthesecondnumericalvalue(ornumericalparameter)inthecomparison.
Baseistheactionthatoccursifthecomparisonevaluatesastrue.
APDLofferseightcomparisonoperators,whicharediscussedindetailinthe*IFcommandreference.
Brieflytheseare:
EQ
Equal(forVAL1=VAL2).
NE
Notequal(forVAL1#VAL2).
LT
Lessthan(forVAL1<VAL2).
GT
Greaterthan(forVAL1>VAL2).
LE
Lessthanorequal(forVAL1vVAL2).
GE
Greaterthanorequal(forVAL1>=VAL2).
ABLT
AbsolutevaluesofVAL1andVAL2before<operation.
ABGT
AbsolutevaluesofVAL1andVAL2before>operation.
BygivingtheBaseargumentavalueofTHEN,the*IFcommandbecomesthebeginningofanifthen
elseconstruct(similartotheFORTRANequivalent).Theconstructconsistsof
An*IFcommand,followedby
Oneormoreoptional*ELSEIFcommands
Anoptional*ELSEcommand
Arequired*ENDIFcommand,markingtheendoftheconstruct.
Initssimplestform,the*IFcommandevaluatesthecomparisonand,iftrue,branchestoalabelspecified
http://mostreal.sk/html/prog_55/gapdl/AS4.htm#S4.1

10/21

20/12/2014

APDL:Chapter4:APDLasaMacroLanguage(UP19980820)

intheBaseargument.Thisissimilartothe"computedgoto"inFORTRAN77.(Incombination,asetof
such*IFcommandscouldfunctionsimilarlytotheCASEstatementsinotherprogramminglanguages.)
Takecarenottobranchtoalabelwithinanifthenelseconstructordoloop.
BysettingtheBaseargumenttoavalueofSTOP,youcanexitfromANSYSbasedonaparticular
condition.
Anifthenelseconstructsimplyevaluatesaconditionandexecutesthefollowingblockorjumpstothe
nextstatementfollowingthe*ENDIFcommand(shownwiththe"Continue"comment).
*IF,A,EQ,1,THEN
!Block1
.
.
*ENDIF
!Continue

Thefollowingexampleshowsamorecomplexstructure.Notethatonlyoneblockcanbeexecuted.Ifno
comparisonevaluatestotrue,theblockfollowingthe*ELSEcommandisexecuted.
Figure44Asampleifthenelseconstruct,usingallofthepossibleAPDLbranchingcommands.

NoteYoucanissuea/CLEARcommandwithinanifthenelseconstruct.The/CLEARcommanddoes
notclearthe*IFstackandthenumberof*IFlevelsisretained.An*ENDIFisnecessarytocloseany
branchinglogic.Also,keepinmindthatthe/CLEARcommanddeletesallparameters,includingany
thatareusedinyourbranchingcommands.Youcanavoidanyproblemsthatmightarisefromthe
deletionofparametersbyissuinga/PARSAVcommandbeforethe/CLEARcommand,andthen
followingthe/CLEARcommandwitha/PARREScommand.

4.5.4RepeatingaCommand
Thesimplestloopingcapability,the*REPEATcommand,allowsyoutoexecutethedirectlypreceding
commandaspecifiednumberoftimes,incrementinganyfieldinthatcommandbyaconstantvalue.In
http://mostreal.sk/html/prog_55/gapdl/AS4.htm#S4.1

11/21

20/12/2014

APDL:Chapter4:APDLasaMacroLanguage(UP19980820)

theexample
E,1,2
*REPEAT,5,0,1

theEcommandgeneratesoneelementbetweennodes1and2andthefollowing*REPEATcommand
specifiesthatEexecutesatotaloffivetimes(includingtheoriginalEcommand),incrementingthe
secondnodenumberbyoneforeachadditionalexecution.Theresultisfivetotalelementswithnode
connectivities12,13,14,15,and16.
NoteMostcommandsthatbeginwithaslash(/)oranasterisk(*),aswellasmacrosexecutedas
"unknowncommands,"cannotberepeated.However,graphicscommandsthatbeginwithaslashcanbe
repeated.Also,avoidusingthe*REPEATcommandwithinteractivecommands,suchasthosethat
requirepickingorthosethatrequireauserresponse.

4.5.5Looping:DoLoops
Adoloopallowsyoutoloopthroughaseriesofcommandsaspecifiednumberoftimes.The*DOand
*ENDDOcommandsmarkthebeginningandendingpointsfortheloop.*DOcommandhasthe
followingsyntax:
Thefollowingexampledoloopeditsfiveloadstepfiles(numbered1through5)andmakesthesame
changesineachfile.
*DO,I,1,5!ForI=1to5:
LSREAD,I!ReadloadstepfileI
OUTPR,ALL,NONE!Changeoutputcontrols
ERESX,NO
LSWRITE,I!RewriteloadstepfileI
*ENDDO

Youcanaddyourownloopcontrolsbyusingthe*IF,*EXIT,or*CYCLEcommands.
Keepthefollowingguidelinesinmindwhenconstructingdoloops.
Donotbranchoutofadoloopwitha:Labelonthe*IFor*GOcommands.
Avoidusinga:Labeltobranchtoadifferentlinewithinadoloop.Useifthenelseendifinstead.
Outputfromcommandswithinadoloopisautomaticallysuppressedafterthefirstloop.Use
/GOPRor/GO(noresponseline)withinthedoloopifyouneedtoseeoutputforallloops.
Takecareifyouincludea/CLEARcommandwithinadoloop.The/CLEARcommanddoesnot
clearthedoloopstack,butitdoesclearallparametersincludingtheloopparameterinthe*DO
statementitself.Youcanavoidtheproblemofhavinganundefinedloopingvaluebyissuinga
/PARSAVcommandbeforethe/CLEARcommand,andthenfollowingthe/CLEARcommand
witha/PARREScommand.

4.6ControlFunctionsQuickReference
ThetablebelowdescribesAPDLcommandsthatperformcontrolfunctionswithinmacros.
Mostoftheimportantinformationaboutthesecommandsappearshere,butyoumaywanttolookatthe
http://mostreal.sk/html/prog_55/gapdl/AS4.htm#S4.1

12/21

20/12/2014

APDL:Chapter4:APDLasaMacroLanguage(UP19980820)

completecommanddescriptionsintheANSYSCommandsReference.
APDL
ActionItTakes
Command

UsageTips
Commandformatis*DO,Par,IVAL,FVAL,INC,where:
Parisascalarparametertobeusedastheloopindex.
IVALandFVALaretheinitialandfinalparametervalues.

*DO

Definesthestartofa
"do"loop.The
commandsfollowing
the*DOcommand
execute(uptothe
*ENDDOcommand)
repeatedlyuntilsome
loopcontrolis
satisfied.

INCistheamountbywhichIVALisincrementedateachloop
execution.
Youalsocancontrolloopingviathe*IFcommand.
ANSYSallowsupto20levelsofnested"do"loops,although"do"
loopsthatinclude/INPUT,*USE,oran"unknown"command
macrosupportfewernestinglevelsbecausetheydointernalfile
switching.*DO,*ENDDO,*CYCLE,and*EXITcommandsina
"do"loopmustallreadfromthesamefileorthekeyboard.Don't
includepickingoperationsina"do"loop.

Takecareifyouincludea/CLEARcommandwithinadoloop.The
/CLEARcommanddoesnotclearthedoloopstack,butitdoes
clearallparametersincludingtheloopparameterinthe*DO
statementitself.Youcanavoidtheproblemofhavinganundefined
loopingvaluebyissuinga/PARSAVcommandbeforethe/CLEAR
command,andthenfollowingthe/CLEARcommandwitha
/PARREScommand.
Endsa"do"loopand Youmustuseone*ENDDOcommandforeachnested"do"loop.
*ENDDO startsthelooping
The*ENDDOand*DOcommandsforaloopmustbeonthesame
action.
file.
Whenexecutinga
"do"loop,the
ANSYSprogram
bypassesall
commandsbetween Youcanusethecycleoptionconditionally(viathe*IFcommand).
*CYCLE the*CYCLE
The*CYCLEcommandmustappearonthesamefileasthe*DO
commandandthe
*ENDDOcommand, commandandmustappearbeforethe*ENDDOcommand.
then(ifapplicable)
initiatesthenext
loop.

*EXIT

Exitsfroma"do"
loop.

http://mostreal.sk/html/prog_55/gapdl/AS4.htm#S4.1

Thecommandfollowingthe*ENDDOcommandexecutesnext.The
*EXITand*DOcommandsforaloopmustbeonthesamefile.
Youcanusetheexitoptionconditionally(viathe*IFcommand).
13/21

20/12/2014

APDL:Chapter4:APDLasaMacroLanguage(UP19980820)

Commandformatis*IF,VAL1,Oper,Val2,Base,
where:
VAL1isthefirstnumericvalue(orparameterthatevaluatestoa
numericvalue)intheconditionalcomparison.
Operistheoperationlabel:EQ(equal),NE(notequal),LT(less
than),GT(greaterthan),LE(lessthanorequal),GE(greaterthanor
equal),ABLT(absolutevaluesofVAL1andVAL2before<
operation)orABGT(absolutevaluesofVAL1andVAL2before>
operation).
VAL2isthesecondnumericvalue(ornumericparametervalue)in
theconditionalcomparison.
Baseisanactionbasedonthelogicaloperationbeingtrue.(Ifit's
false,thenextlineintheblockisread.)Possibleactionsare:
:label(skipstothefirstlinestartingwiththematchinglabel)
*IF

Causescommandsto
STOP(exitsfromtheANSYSprogram)
beread
conditionally.
EXIT(exitsthecurrent"do"loop)
CYCLE(skipstotheendofthecurrent"do"loop
THEN(makesthisIFanifthenelseconstruct)
Youcanhaveupto10nestedlevelsof*IFblocks.Youcan'tjump
into,outof,orwithina"do"looporanifthenelseconstructtoa
:labelline,andjumpingtoa:labellineisn'tallowedwithkeyboard
entry.
Youcanissuea/CLEARcommandwithinanifthenelseconstruct.
The/CLEARcommanddoesnotclearthe*IFstackandthenumber
of*IFlevelsisretained.An*ENDIFisnecessarytocloseany
branchinglogic.Also,keepinmindthatthe/CLEARcommand
deletesallparameters,includinganythatareusedinyourbranching
commands.Youcanavoidanyproblemsthatmightarisefromthe
deletionofparametersbyissuinga/PARSAVcommandbeforethe
/CLEARcommand,andthenfollowingthe/CLEARcommand
witha/PARREScommand.

*ENDIF

Terminatesanif
thenelseconstruct.
(Seethe*IF
discussionfor
details.)

The*IFand*ENDIFcommandsmustappearinthesamefile.

Createsafinal,
optionalblock
http://mostreal.sk/html/prog_55/gapdl/AS4.htm#S4.1

14/21

20/12/2014

*ELSE

APDL:Chapter4:APDLasaMacroLanguage(UP19980820)

separatorwithinan
ifthenelse
construct.(Seethe
*IFdiscussionfor
details.)

The*ELSEand*IFcommandsmustappearinthesamefile.

Commandformatis*ELSEIF,VAL1,Oper,VAL2,where:
VAL1isthefirstnumericvalue(orparameterthatevaluatestoa
numericvalue)intheconditionalcomparison.
Createsanoptional,
intermediateblock
*ELSEIF separatorwithinan
ifthenelse
construct.

Operistheoperationlabel:EQ(equal),NE(notequal),LT(less
than),GT(greaterthan),LE(lessthanorequal),GE(greaterthanor
equal),ABLT(absolutevaluesofVAL1andVAL2before<operation)
orABGT(absolutevaluesofVAL1andVAL2before>operation).
VAL2isthesecondnumericvalue(ornumericparametervalue)in
theconditionalcomparison.
IfOper=EQorNE,VAL1andVAL2canalsobecharacterstrings
(enclosedinquotes)orparameters.
The*IFand*ELSEIFcommandsmustbeonthesamefile.

4.7Usingthe_STATUSand_RETURN
ParametersinMacros
TheANSYSprogramgeneratestwoparameters,_STATUSand_RETURN,thatyoucanalsouseinyour
macros.Forexample,youmightusethe_STATUSor_RETURNvalueinan"ifthenelse"constructto
havethemacrotakesomeactionbasedontheoutcomeofexecutinganANSYScommandorfunction.
Solidmodelingfunctionsgeneratethe_RETURNparameter,whichcontainstheresultofexecutingthe
function.Thefollowingtabledefinesthe_RETURNvaluesforthevarioussolidmodelingfunctions:
Command Function

_RETURNValue

Keypoints
K

Definesakeypoint

Keypointnumber

KL

Keypointonline

Keypointnumber

KNODE

Keypointatnode

Keypointnumber

KBET

Keypointbetweentwokeypoints

KPnumber

http://mostreal.sk/html/prog_55/gapdl/AS4.htm#S4.1

15/21

20/12/2014

KCENT

APDL:Chapter4:APDLasaMacroLanguage(UP19980820)

Keypointatcenter

KPnumber

BSPLIN

Generatespline

Linenumber

CIRCLE

Generatecirculararclines

Firstlinenumber

Linebetweentwokeypoints

Linenumber

L2ANG

Lineatanglewithtwolines

Linenumber

LANG

Linetangenttotwolines

Linenumber

LARC

Definesacirculararc

Linenumber

LAREA

Linebetweentwokeypoints

Linenumber

LCOMB

Combinetwolinesintoone

Linenumber

LDIV

Dividelineintotwoormorelines Firstkeypointnumber

LDRAG

Linebykeypointsweep

Firstlinenumber

LFILLT

Filletlinebetweentwolines

Filletlinenumber

LRCS

Rotatepointaroundtwokeypoints Linenumber

Lines

LROTATE Arcbykeypointrotation

Firstlinenumber

LSPA

Projectlinesegmentonanarea

Linenumber

LSTR

Straightline

Linenumber

LTAN

Lineatendandtangent

Linenumber

SPLINE

Segmentedspline

Firstlinenumber

Areaconnectingkeypoints

Areanumber

ACCAT

Concatenatetwoormoreareas

Areanumber

ADRAG

Draglinesalongpath

Firstareanumber

Areas

http://mostreal.sk/html/prog_55/gapdl/AS4.htm#S4.1

16/21

20/12/2014

APDL:Chapter4:APDLasaMacroLanguage(UP19980820)

AFILLT

Filletatintersectionoftwoareas

Filletareanumber

AL

Areaboundedbylines

Areanumber

ALLP

Allloops

Areanumber

AOFFST

Areaoffsetfromgivenarea

Areanumber

AROTAT

Rotatelinesaroundaxis

Firstareanumber

ASKIN

Skinsurfacethroughguidinglines Firstareanumber

ASUB

Areausingshapeofexistingarea Areanumber

Volumes
V

Volumethroughkeypoints

Volumenumber

VA

Volumeboundedthroughareas

Volumenumber

VDRAG

Dragareapatterntocreatevolume Firstvolumenumber

VEXT

Volumebyextrudingareas

Firstvolumenumber

VOFFST

Volumeoffsetfromgivenarea

Volumenumber

VROTATE Volumebyrotatingareas

Firstvolumenumber

ExecutinganANSYScommand,whetherinamacroorelsewhere,generatestheparameter_STATUS.
Thisparameterreflectstheerrorstatusofthatcommand:
0,fornoerror
1,foranote
2,forawarning
3,foranerror

4.8UsingMacroswithComponentsand
Assemblies
Tomakelargemodelseasiertomanage,youmaywishtodivideamodelintodiscretecomponentsbased
ondifferenttypesofentities:nodes,elements,keypoints,lines,areas,orvolumes.Eachcomponentcan
containonlyonetypeofentity.Doingthisenablesyoutoperformtaskssuchasapplyingloadsor
producinggraphicsdisplaysconvenientlyandseparatelyondifferentportionsofthemodel.
http://mostreal.sk/html/prog_55/gapdl/AS4.htm#S4.1

17/21

20/12/2014

APDL:Chapter4:APDLasaMacroLanguage(UP19980820)

Youalsocancreateassembliesgroupsthatcombinetwoormorecomponentsorevenmultiple
assemblies.Youcannestassembliesuptofivelevelsdeep.Forexample,youcouldbuildanassembly
namedMOTORfromcomponentscalledSTATOR,PERMMAG,ROTOR,andWINDINGS.
Thetablebelowdescribessomeofthecommandsyoucanissuetobuildcomponentsandassemblies.For
moredetaileddiscussionsofthesecommands,seetheANSYSCommandsReference.Forfurther
informationoncomponentsandassemblies,seeChapter7oftheANSYSBasicAnalysisProcedures
Guide.
Command

Description
Groupsgeometryitemsintoacomponent.Argumentsare:

CM,Cname,Entity

Cnameacomponentname,whichcontainsuptoeightcharactersandmust
beginwithaletter
Entityafourcharacterlabelidentifyingthetypeofgeometryitemstobe
grouped.PossiblevaluesareVOLU,AREA,LINE,KP(keypoints),ELEM,
andNODE.

CMDELE,Name

Deletesacomponentorassembly.TheNameargumentidentifiestheentityto
bedeleted.
Editsanexistingcomponentorassembly.TheANSYSprogramupdates
assembliesautomaticallytoreflectdeletionsoflowerlevelorassemblies.
Commandargumentsare:

CMEDIT,
Anamethenameoftheassemblytoedit
Aname,Oper,Cnam1,...
Operanoperationlabel(ADDtoaddcomponents,orDELEtoremove
Cnam7
components)
Cnam1,...Cnam7thenamesofcomponentsandassembliestobeaddedtoor
deletedfromtheassembly.Youmustseparatethecomponentorassembly
nameswithcommas.
Groupscomponentsandassembliesintooneassembly.Oncedefined,an
assemblycanbelisted,deleted,selected,orunselectedusingthesame
commandsasforacomponent.Argumentsare:
CMGRP,
Anamethenameoftheassembly.Thenamecanhaveuptoeightcharacters
Aname,Oper,Cnam1,... andmustbeginwithaletter.
Cnam8
Cnam1,...Cnam8thenamesofexistingcomponentsandassembliestobe
includedinthisassembly.Youmustseparatethecomponentorassembly
nameswithcommas.Youcanspecifyuptofivelevelsofassemblieswithinan
assembly.
CMLIST,Name

Liststheentitiescontainedinacomponentorassembly.Nameisthenameof
thecomponentorassemblytobelisted.IfyouspecifynoName,theprogram
listsallcomponentsandassemblies.
Selectsasubsetofcomponentsandassemblies.Typeisalabelidentifyingthe

http://mostreal.sk/html/prog_55/gapdl/AS4.htm#S4.1

18/21

20/12/2014

APDL:Chapter4:APDLasaMacroLanguage(UP19980820)

typeofselectoperation:
1.Sselectanewsetdefault
CMSEL,Type,Name

2.RReselectaset
3.AAdditionallyselectasetandextendthecurrentset
4.UUnselectaset
5.ALLSelectallcomponents
6.NONEUnselectallcomponents

4.9ReviewingExampleMacros
Followingaretwoexamplemacros.Theexamplemacrobelow,calledoffset.mac,offsetsselectednodes
inthePREP7preprocessor.ThismacroisfordemonstrationpurposesonlyastheNGENcommand
providesamoreconvenientmethod.
!MacrotooffsetselectednodesinPREP7
!Thebelowfileissavedas:offset.mac(mustbelowercase)
!Usage:offset,dx,dy,dz
/nop

!suppressprintoutforthismacro

*get,nnode,node,,num,max

!getnumberofnodes

*dim,x,,nnode
*dim,y,,nnode
*dim,z,,nnode

!setuparraysfornodelocations

*dim,sel,,nnode

!setuparrayforselectvector

*vget,x(1),node,1,loc,x
*vget,y(1),node,1,loc,y
*vget,z(1),node,1,loc,z

!getcoordinates

*vget,sel(1),node,1,nsel

!getselectedset

*voper,x(1),x(1),add,arg1
*voper,y(1),y(1),add,arg2
*voper,z(1),z(1),add,arg3

!offsetlocations

!*do,i,1,nnode
!*if,sel(i),gt,0,then
!n,i,x(i),y(i),z(i)
!*endif
!*enddo

!storenewpositions
!thisformtakes98secfor100,000nodes

!*****NEWFORMAT5.3*****
*vmask,sel(1) !thisformtakes3secondsfor100,000nodes
!NOTE:AT5.3NNODEMUSTbecapsinthefollowing:
n,(1:NNODE),x(1:NNODE),y(1:NNODE),z(1:NNODE)
x(1)=!deleteparameters(cleanup)
http://mostreal.sk/html/prog_55/gapdl/AS4.htm#S4.1

19/21

20/12/2014

APDL:Chapter4:APDLasaMacroLanguage(UP19980820)

y(1)=
z(1)=
sel(1)=
i=
nnode=
/go!resumeprintout

Thefollowingexamplemacro,calledbilinear.mac,evaluatestwobilinearmaterials.Thisisauseful
macrothatcanberunaftersolvingastaticanalysis.Material1isthetensionproperties,andMaterial2is
thecompressionproperties.ARG1isthenumberofiterations(defaultis2).
/nop
_niter=arg1!setnumberofiterations
*if,_niter,lt,2,then
_Niter=2
*endif
*do,iter,1,_niter!looponnumberofiterations
/post1
set,1,1
ar11,=elmiqr(0,14)!callelmiqrfunctiontogetno.ofelements
*dim,_s1,,ar11!arrayforelements1
*dim,_s3,,ar11!arrayforelements3
etable,sigmax,s,1!s1isinelementtablesigmax
etable,sigmin,s,3!s3isinelementtablesigmin
*vget,_s1(1),elem,1,etab,sigmax!getelementmaximumstressins1
*vget,_s3(1),elem,1,etab,sigmin!getelementminimumstressins3
*dim,_mask,,ar11!arrayformaskvector
*voper,_mask(1),_s1(1),lt,0!trueifmax.stress<0
*vcum,1!accumulatecompressionelements
*vabs,0,1!absolutevalueofs3
*voper,_mask(1),_s3(1),gt,_s1(1)!trueifabs(minstr)>maxstr
finish
/prep7!gotoprep7forelementmaterialmods
mat,1!setallmaterialstotensionproperties
emod,all
*vput,_mask(1),elem,1,esel!selectcompressionelements
mat,2!changeselectedelementstocompression
emod,all
call!selectallelements
finish
_s1(1)=!cleanupallvectors(settozero)
_s3(1)=
_mask(1)=
/solve!reruntheanalysis
solve
finish
*enddo!endofiterations
_niter=!cleanupiterationcounters
_iter=
/gop

http://mostreal.sk/html/prog_55/gapdl/AS4.htm#S4.1

20/21

20/12/2014

APDL:Chapter4:APDLasaMacroLanguage(UP19980820)

Gotothebeginningofthischapter

http://mostreal.sk/html/prog_55/gapdl/AS4.htm#S4.1

21/21

Vous aimerez peut-être aussi