You are on page 1of 5

FUZZYLOGICINC

Creatingafuzzybasedinferenceengine
GregViot
GregisamemberoftheMotorolatechnicalladderandiscurrentlymergingfuzzylogicwithmicrocontrollers.HehasanMSEEfromNationalTechnological
UniversityandaBSEEfromtheUniversityofTexasatAustin.GregcanbecontactedatMotorolaAdvancedMicrocontrollerDivision,6501WilliamCannon
DriveWest,Austin,Texas787358598.
Fuzzylogicisapowerful,yetstraightforward,problemsolvingtechniquewithwidespreadapplicability,especiallyintheareasofcontrolanddecisionmaking.
Ingeneral,itismostusefulinhandlingproblemsnoteasilydefinablebypracticalmathematicalmodels.Forinstance,fuzzylogichasbeenemployedinsuch
tasksasmanagingstockmarketportfoliosandcontrollingsubwaysystems.
Fuzzyderivesmuchofitspowerfromitsabilitytodrawconclusionsandgenerateresponsesbasedonvague,ambiguous,qualitative,incomplete,orimprecise
information.Inthisrespect,fuzzybasedsystemshaveareasoningabilitysimilartothatofhumans.Infact,thebehaviorofafuzzysystemisrepresentedina
verysimpleandnaturalway.Thisallowsquickconstructionofunderstandable,maintainable,androbustsystems.Inaddition,afuzzyapproachgenerally
requiresmuchlessmemoryandcomputingpowerthanconventionalmethods,therebypermittingsmallerandlessexpensivesystems.
LotfiZadeh,aprofessorattheUniversityofCaliforniaatBerkeley,isthepersonmostwidelyassociatedwithfuzzylogic.In1965hepresentedtheoriginal
paperformallydefiningfuzzysettheory,fromwhichfuzzylogicemerged.Zadehextendedtraditionaltheorytoresolvetheparadoxessometimesgenerated
fromthe"nothingorall"classificationsofAristotelianlogic.Traditionally,alogicpremisehastwoextremes:eithercompletelytrueorcompletelyfalse.
However,inthefuzzyworld,apremiserangesindegreeoftruthfrom0to100percent,whichallowsittobepartiallytrueandpartiallyfalse.
Byincorporatingthis"degreeoftruth"concept,fuzzylogicextendstraditionallogicintwoways.First,setsarelabeledqualitatively(usinglinguistictermssuch
as"tall,""warm,""active,""nearby,"andsoon),andtheelementsofthesesetsareassignedvaryingdegreesofmembership.Forinstance,a5'11"mananda
6'4"manmaybothbemembersofasetof"tall"men,althoughthe6'4"manhasahigherdegreeofmembership.Secondly,anyactionoroutputresultingfroma
premisebeingtrueexecutestoastrengthreflectingthedegreetowhichthatpremiseistrue.
Asanexample,imagineafanmotor,thespeedofwhichisafunctionoftemperature,asshowninTable1.Thecurrentsuppliedtothefanmotorisregulatedby
setsoftemperature:cold,cool,warm,andhot.Inthissystem,asthetemperaturegraduallymovesfromwarmtocool,thecurrentgraduallymovesfrom50to
15.Bycontinuouslytrackinginputs,outputscanavoidabruptchanges,evenasinputstranscendsetboundaries.Fuzzybasedsystemsareconstructedsothat
generatedoutputschangeinasmoothandcontinuousmanner,regardlessofinputscrossingsetboundaries.
Table1:Fanspeedcontrol.
TemperatureFanSpeedRelativeMotor
Current

ColdOff0
CoolSlow15
WarmMedium50
HotFast100

OrganizationofaFuzzySystem
Figure1illustratestheflowofdatathroughafuzzysystem.Systeminputsundergothreetransformationstobecomesystemoutputs.First,afuzzification
processthatusespredefinedmembershipfunctionsmapseachsysteminputintooneormoredegreesofmembership.Then,therulesintherulebase(also
predefined)areevaluatedbycombiningdegreesofmembershiptoformoutputstrengths.Andlastly,thedefuzzificationprocesscomputessystemoutputsbased
onstrengthsandmembershipfunctions.
FuzzificationofInputs.Fuzzificationistheprocessofassigningorcalculatingavaluetorepresentaninput'sdegreeofmembershipinoneormorequalitative
groupings,called"fuzzysets."Figure2showsasysteminput,temperature,withfuzzysetscold,cool,warm,andhot.Eachtemperaturevaluehasadegreeof
membershipineachofthesesets.Thedegreeofmembershipisdeterminedbyamembershipfunction,whichisdefinedbasedonexperienceorintuition.Figure
9illustratesthedegreeofmembershipcalculationforatrapezoidalmembershipfunction.Itisacceptedthatmembershipfunctionschangeseveraltimesasthe
systemistunedtoachievedesiredresponsestogiveninputs.
Generally,oncethesystemisinoperation,themembershipfunctionsdonotchange.Simpleshapessuchastrapezoidsandtrianglesareoftenusedtodefine
membershipinfuzzysets,butanysuitablefunctioncanbeused.Inaddition,youmustdecideuponthenumberoffuzzysetspersysteminput.
InFigure2,afuzzysetlabeledcomfortablecouldbeinsertedbetweencoolandwarm.Thenumberoffuzzysetmembershipfunctionsandtheshapesyou
choosedependonsuchthingsasrequiredaccuracy,responsivenessandstabilityofthesystem,easeofimplementation,manipulation,andmaintenance,andso
on.Thetrapezoidalandtriangularmembershipfunctionsaremostcommonandhaveproventobegoodcompromisesbetweeneffectivenessandefficiency.The
fuzzysetsmustspantheXaxiscoveringtheentirerange,oruniverseofdiscourse,forasysteminput.MappingtotheYaxisrangesfrom0to1andrepresents
thedegreetowhichaninputvalueisamemberofthatparticularfuzzyset.Overlappingbetweensetboundariesisdesirableandkeytothesmoothoperationof
thesystem.Itpermitsmembershipinmultipleevenseeminglycontradictorysets.InFigure2,63degreescanbebothcoolandwarm,butitiscooltoagreater
degree.Anoverlapof25percentbetweenadjacentfuzzysetsisageneralruleofthumb.
Thefuzzificationprocesspermitsabindingtotakeplacebetweenlinguisticterms(cold,nearby,active,large,andsoon)andmembershipfunctions,makingthe
termsmeaningfultoacomputer.Asaresult,adesignercanexpressormodifythebehaviorofasystemusingsuchnaturallanguage,thusenhancingthe
possibilityofclearandconcisedescriptionsofcomplextasks.
EvaluationofRules.Togovernthesystem'sbehavior,thedesignerdevelopsasetofrulesthathavetheformofIfThenstatements.TheIfsideofarulecontains
oneormoreconditions,called"antecedents"theThensidecontainsoneormoreactions,called"consequences."Theantecedentsofrulescorresponddirectlyto
degreesofmembershipcalculatedduringthefuzzificationprocess.

Forexample,considerapotentialrulefromthestockmarketsystemshowninFigure3:IfsharepriceisdecreasingAndtradingvolumeisheavy,Thenorderis
sell.Thetwoconditions"sharepriceisdecreasing"and"tradingvolumeisheavy"aretherule'santecedents.Eachantecedenthasadegreeoftruth
(membership)valueassignedtoitasaresultoffuzzification.Theactionoftherule(or"fuzzyoutput")istosellshares.Duringruleevaluation,strengthsare
computedbasedonantecedentvaluesandthenassignedtotherules'fuzzyoutputs.Generally,aminimumfunctionisusedsothatthestrengthofaruleis
assignedthevalueofitsweakestorleasttrueantecedent.Othermethodstocomputerulestrengthcanbeused,suchasmultiplyingantecedentvaluestogether.
Theactionofsellingsharesiscarriedouttoadegreethatreflectstherule'sstrength.Inotherwords,theamountofsharessoldisbasedonthedegreetowhich
sharepriceisdecreasingandtradingvolumeisheavy.Often,morethanoneruleappliestothesamespecificaction,inwhichcasethecommonpracticeistouse
thestrongestormosttrueruleseeFigure4.
Figure4:Ruleevaluationcomputation.
Rule1:ifA&BthenZ&X
Rule2:ifC&DthenZ&Y
StrengthofRule1=min(A,B)
StrengthofRule2=min(C,D)
X=StrengthofRule1
Y=StrengthofRule2
Z=max(StrengthofRule1
StrengthofRule2)
=max(min(A,B),min(C,D))

DefuzzificationofOutputs.Eventhoughtheruleevaluationprocessassignsstrengthstoeachspecificaction,furtherprocessing,or"defuzzification,"is
requiredfortworeasons.Thefirstistodecipherthemeaningofvague(fuzzy)actions,suchas"orderissell,"usingmembershipfunctions.Thesecondisto
resolveconflictsbetweencompetingactionssuchas"orderissell"and"orderishold,"whichmayhavebeentriggeredbycertainconditionsduringrule
evaluation.Defuzzificationemployscompromisingtechniquestoresolveboththevaguenessandconflictissues.
Onecommondefuzzificationtechnique,the"centerofgravitymethod,"consistsofseveralsteps.Initially,acentroidpointontheXaxisisdeterminedforeach
outputmembershipfunction.Then,themembershipfunctionsarelimitedinheightbytheappliedrulestrength,andtheareasofthemembershipfunctionsare
computed.Finally,thedefuzzifiedoutputisderivedbyaweightedaverageoftheXaxiscentroidpointsandthecomputedareas,withtheareasservingasthe
weights.ThecenterofgravitymethodisillustratedinFigure5.
Sometimes,"singletons"areusedtosimplifythedefuzzificationprocessseeFigure6.Asingletonisanoutputmembershipfunctionrepresentedbyasingle
verticalline.SinceasingletonintersectstheXaxisatonlyonepoint,thecenterofgravitycalculationreducestojustaweightedaveragecalculationofXaxis
pointsandrulestrengths,withtherulestrengthsusedasweights.

FuzzyDataStructures
ToimplementafuzzysysteminC,thefollowingtypesofdatamustbeaccommodated:
Systeminputs.
Inputmembershipfunctions.
Antecedentvalues.
Rules.
Ruleoutputstrengths.
Outputmembershipfunctions.
Systemoutputs.
Figure7illustratesanoveralllinkedlistarrangementofsysteminputandmembershipfunctionnodes.ThedetailsofthesestructuresareshowninFigure8.The
systeminputnodeisstraightforwardandcontainsaninputname,amembershipfunctionpointer,andanextinputpointer.Moreinterestingisthemembership
functionstructure,whichcontainstwoXaxispointsandtwoslopevaluesthatdescribeatrapezoidalmembershipfunction.Thisinformationisusedtocalculate
antecedentvalues(degreesofmembership),asshowninFigure9andListingThree(page94).Theresultingantecedentvalueisstoredinthe"value"fieldofthe
membershipfunctionstructure.RulescanberepresentedbytwosetsofpointersseeFigure10.Thefirstsetindicateswhichantecedentvaluesareusedto
determinetherule'sstrength,andthesecondsetpointstooutputlocationswherethestrengthistobeapplied.Finally,adataarrangementsimilartotheinput
datastructurehandlesoutputsandoutputmembershipfunctionsseeFigure11.ListingOne(page94)includestheCcodedefinitionofthesedatastructures.
ArticlesbyJamesM.Sibigtroth(see"References")explaintheimplementationoffuzzysystemsattheassemblylanguagelevel.

InvertedpendulumExample
Figure12showsaclassictwodimensionalcontrolproblemknownasthe"invertedpendulum."Theideaistokeepapoleverticallybalanced.Thepoleis
weightedatthetopandattachedatthebottombyamovablebase.Ifthepolefallstotherightorleft,thebasemovesinthesamedirectiontocompensate.By
monitoringtheangleandangularvelocityofthependulum,afuzzysystemcandeterminetheproperforcetoapplyatthebasetokeepitbalanced.Figure13
showsthefuzzysetsassociatedwiththesysteminputsandoutput.Theexactsetofrulesdependsonthedynamicsofthephysicalcomponents,required
robustness,andrangeofoperatingconditions.
Theoretically,therulebaseinFigure14issufficienttobalancethependulum,butothersolutionsexist.Ageneralpurposefuzzyinferenceenginelikethatin
ListingsOnethroughFourcanbeappliedtomanyapplications.ListingOneprovidestheheaderanddatastructures,ListingsTwoandThree(page94)present
themajorfuzzyprocesses,andListingFour(page94)liststhemathsupportfunctions.Theinputconfigurationfilesdescribingsysteminput/output,the
membershipfunctions,andtherulebasedifferfromapplicationtoapplication.Figures14and15containthenecessaryinformationtoimplementtheinverted
pendulumproblem.
Figure14:Invertedpendulumrulebase.
Rule1:IF(angleisNL)AND(velocityisZE)THEN(forceisPL)
Rule2:IF(angleisZE)AND(velocityisNL)THEN(forceisPL)
Rule3:IF(angleisNM)AND(velocityisZE)THEN(forceisPM)
Rule4:IF(angleisZE)AND(velocityisNM)THEN(forceisPM)

Rule5:IF(angleisNS)AND(velocityisZE)THEN(forceisPS)
Rule6:IF(angleisZE)AND(velocityisNS)THEN(forceisPS)
Rule7:IF(angleisNS)AND(velocityisPS)THEN(forceisPS)
Rule8:IF(angleisZE)AND(velocityisZE)THEN(forceisZE)
Rule9:IF(angleisZE)AND(velocityisPS)THEN(forceisNS)
Rule10:IF(angleisPS)AND(velocityisZE)THEN(forceisNS)
Rule11:IF(angleisPS)AND(velocityisNS)THEN(forceisNS)
Rule12:IF(angleisZE)AND(velocityisPM)THEN(forceisNM)
Rule13:IF(angleisNM)AND(velocityisZE)THEN(forceisNM)
Rule14:IF(angleisZE)AND(velocityisPL)THEN(forceisNL)
Rule15:IF(angleisPL)AND(velocityisZE)THEN(forceisNL)

Figure15:Samplemembershipfunctioninputfile.
input:angleinput:velocityoutput:force
NL:0313163NL:0313163NL:0313163
NM:31636395NM:31636395NM:31636395
NS:639595127NS:639595127NS:639595127
ZE:95127127159ZE:95127127159ZE:95127127159
PS:127159159191PS:127159159191PS:127159159191
PM:159191191223PM:159191191223PM:159191191223
PL:191223223255PL:191223223255PL:191223223255

Figure15repeatstheinput/outputandmembershipinformationshownFigure13inaformatthatcanbeeasilyparsedbyaninitializationroutine.Suchan
initializationroutine(notshowninthelistings)setsuptherequireddatastructures,convertingthefourpointsdescribingamembershipfunctionintotwopoints
andtwoslopesseeFigure16.
Generally,fourpointsdescribeatrapezoid,butatrianglecanbeformedbymakingthetwomidpointsidentical,asinFigure16.

ClosingRemarks
Theemergenceoffuzzylogicisexcitingbecauseitisreadilyapplicabletomanyproblemstooawkwardtosolvewithconventionaltechniques.Any
programmercaneasilywritecodetoimplementafuzzyinferenceengineliketheonepresentedhere.However,excellentfuzzydevelopmenttoolsexistwhich
allowthedesignertofocusmoreontheapplicationandbehaviorofthesystemandlessontheimplementation.Thesetoolsprovideuserfriendly,graphical
interfaceswitharichsetofsupportfunctionsforanalyzing,debugging,andsimulatingthesystem.Examplesofsuchtoolsare:FIDEfromAptronix(SanJose,
CA),CubiCalcfromHyperlogic(Escondido,CA),andTILShellfromTogaiInfraLogic(Irvine,CA).Inaddition,Motoroladistributesfreefuzzydevelopment
toolsthroughtheirelectronicBBS."FreewareDataServices,"at5128913733(inthesubdirectoryamcu/amcull).
Implementingthefuzzyenginemanually,however,affordstheabilitytounderstand,optimize,orcustomizethefuzzyinferenceengine.Thisisespecially
importantwhenexperimentingwithnewfuzzyparadigms,suchasrulebasehierarchiesandadaptiveorhybridsystems.

References
Brubaker,DavidI.IntroductiontoFuzzyLogicSystems.MenloPark,CA:TheHuntingtonGroup,1991.
Kosko,Bart.NeuralNetworksandFuzzySystems.EnglewoodCliffs.,NJ:PrenticeHall,1990.
Self,Kevin."DesigningwithFuzzyLogic."IEEESpectrum(November,1990).
Sibigtroth,JamesM."CreatingFuzzyMicros."EmbeddedSystemsProgramming(December,1991).
Sibigtroth,JamesM."ImplementingFuzzyExpertRules."AIExpert(April,1992).
Williams,Tom."FuzzyLogicisAnythingbutFuzzy."ComputerDesign(April,1992).

_FUZZYLOGICINC_
byGregViot

[LISTINGONE]

/*Generalpurposefuzzyinferenceenginesupportinganynumberofsystem
inputsandoutputs,membershipfunctions,andrules.Membershipfunctionscan
beanyshapedefineableby2pointsand2slopestrapezoids,triangles,
rectanlges,etc.Rulescanhaveanynumberofantecedentsandoutputs,andcan
varyfromruletorule."Min"methodisusedtocomputerulestrength,"Max"
forapplyingrulestrengths,"CenterofGravity"fordefuzzification.This
implementationofInvertedPendulumcontrolproblemhas:SystemInputs,2
(pendulumangleandvelocity)SystemOutputs,1(forcesuppliedtobaseof
pendulum)MembershipFunctions,7persysteminput/outputRules,15(each
with2antecedents&1output).Ifmoreprecisionisrequired,integerscan
bechangedtorealnumbers.*/
#include<stdio.h>
#defineMAXNAME10/*maxnumberofcharactersinnames*/
#defineUPPER_LIMIT255/*maxnumberassignedasdegreeofmembership*/
/*io_typestructurebuildsalistofsysteminputsandalistofsystem
outputs.Afterinitialization,theselistsarefixed,exceptforvaluefield
whichisupdatedoneveryinferencepass.*/
structio_type{
charname[MAXNAME]/*nameofsysteminput/output*/

intvalue/*valueofsysteminput/output*/
structmf_type/*listofmembershipfunctionsfor*/
*membership_functions/*thissysteminput/output*/
structio_type*next/*pointertonextinput/output*/
}
/*Membershipfunctionsareassociatedwitheachsysteminputandoutput.*/
structmf_type{
charname[MAXNAME]/*nameofmembershipfunction(fuzzyset)*/
intvalue/*degreeofmembershiporoutputstrength*/
intpoint1/*leftmostxaxispointofmem.function*/
intpoint2/*rightmostxaxispointofmem.function*/
intslope1/*slopeofleftsideofmembershipfunction*/
intslope2/*slopeofrightsideofmembershipfunction*/
structmf_type*next/*pointertonextmembershipfunction*/
}
/*Eachrulehasanifsideandathenside.Elementsmakingupifsideare
pointerstoantecedentvaluesinsidemf_typestructure.Elementsmakingupthen
sideofrulearepointerstooutputstrengthvalues,alsoinsidemf_type
structure.Eachrulestructurecontainsapointertonextruleinrulebase.*/
structrule_element_type{
int*value/*pointertoantecedent/outputstrengthvalue*/
structrule_element_type*next/*nextantecedent/outputelementinrule*/
}
structrule_type{
structrule_element_type*if_side/*listofantecedentsinrule*/
structrule_element_type*then_side/*listofoutputsinrule*/
structrule_type*next/*nextruleinrulebase*/
}
structrule_type*Rule_Base/*listofallrulesinrulebase*/

[LISTINGTWO]

main()
{
initialize_system()
while(1){
get_system_inputs()
fuzzification()
rule_evaluation()
defuzzification()
put_system_outputs()
}
}

[LISTINGTHREE]

/*FuzzificationDegreeofmembershipvalueiscalculatedforeachmembership
functionofeachsysteminput.Valuescorrespondtoantecedentsinrules.*/
fuzzification()
{
structio_type*si/*systeminputpointer*/
structmf_type*mf/*membershipfunctionpointer*/
for(si=System_Inputssi!=NULLsi=si>next)
for(mf=si>membership_functionsmf!=NULLmf=mf>next)
compute_degree_of_membership(mf,si>value)
}
/*RuleEvaluationEachruleconsistsofalistofpointerstoantecedents
(ifside),listofpointerstooutputs(thenside),andpointertonextrule
inrulebase.Whenaruleisevaluated,itsantecedentsareANDedtogether,
usingaminimumfunction,toformstrengthofrule.Thenstrengthisapplied
toeachoflistedruleoutputs.Ifanoutputhasalreadybeenassignedarule
strength,duringcurrentinferencepass,amaximumfunctionisusedto
determinewhichstrengthshouldapply.*/
rule_evaluation()
{
structrule_type*rule
structrule_element_type*ip/*pointerofantecedents(ifparts)*/
structrule_element_type*tp/*pointertoconsequences(thenparts)*/
intstrength/*strengthofrulecurrentlybeingevaluated*/
for(rule=Rule_Baserule!=NULLrule=rule>next){
strength=UPPER_LIMIT/*maxrulestrengthallowed*/
/*processifsideofruletodeterminestrength*/
for(ip=rule>if_sideip!=NULLip=ip>next)
strength=min(strength,*(ip>value))
/*processthensideofruletoapplystrength*/
for(tp=rule>then_sidetp!=NULLtp=tp>next)
*(tp>value)=max(strength,*(tp>value))

}
}
/*Defuzzification*/
defuzzification()
{
structio_type*so/*systemoutputpointer*/
structmf_type*mf/*outputmembershipfunctionpointer*/
intsum_of_products/*sumofproductsofarea&centroid*/
intsum_of_areas/*sumofshortendtrapezoidarea*/
intarea
intcentroid
/*computeadefuzzifiedvalueforeachsystemoutput*/
for(so=System_Outputsso!=NULLso=so>next){
sum_of_products=0
sum_of_areas=0
for(mf=so>membership_functionsmf!=NULLmf=mf>next){
area=compute_area_of_trapezoid(mf)
centroid=mf>point1+(mf>point2mf>point1)/2
sum_of_products+=area*centroid
sum_of_areas+=area
}
so>value=sum_of_products/sum_of_areas/*weightedaverage*/
}
}

[LISTINGFOUR]

/*ComputeDegreeofMembershipDegreetowhichinputisamemberofmfis
calculatedasfollows:1.Computedeltatermstodetermineifinputisinside
oroutsidemembershipfunction.2.Ifoutside,thendegreeofmembershipis0.
Otherwise,smallerofdelta_1*slope1anddelta_2*slope2applies.
3.Enforceupperlimit.*/
compute_degree_of_membership(mf,input)
structmf_type*mf
intinput
{
intdelta_1
intdelta_2
delta_1=inputmf>point1
delta_2=mf>point2input
if((delta_1<=0)||(delta_2<=0))/*inputoutsidemem.function?*/
mf>value=0/*thendegreeofmembershipis0*/
else
mf>value=min((mf>slope1*delta_1),(mf>slope2*delta_2))
mf>value=min(mf>value,UPPER_LIMIT)/*enforceupperlimit*/
}
/*ComputeAreaofTrapezoidEachinferencepassproducesanewsetofoutput
strengthswhichaffecttheareasoftrapezoidalmembershipfunctionsusedin
centerofgravitydefuzzification.Areavaluesmustberecalculatedwitheach
pass.Areaoftrapezoidish*(a+b)/2whereh=height=output_strength=mf>value
b=base=mf>point2mf>point1a=top=mustbederivedfromh,b,andslopes1&2*/
compute_area_of_trapezoid(mf)
structmf_type*mf
{
intrun_1
intrun_2
intbase
inttop
intarea
base=mf>point2mf>point1
run_1=mf>value/mf>slope1
run_2=mf>value/mf>slope2
top=baserun_1run_2
area=mf>value*(base+top)/2
return(area)
}

Copyright1993,Dr.Dobb'sJournal

You might also like