Vous êtes sur la page 1sur 15

FuzzyLogicinC

Creatingafuzzybasedinferenceengine
GregViot,Dr.Dobb'sJournal,February1993
GregisamemberoftheMotorolatechnicalladderandiscurrentlymergingfuzzylogicwith
microcontrollers.HehasanMSEEfromNationalTechnologicalUniversityandaBSEEfromthe
UniversityofTexasatAustin.GregcanbecontactedatMotorolaAdvancedMicrocontroller
Division,6501WilliamCannonDriveWest,Austin,Texas787358598.
Fuzzylogicisapowerful,yetstraightforward,problemsolvingtechniquewithwidespread
applicability,especiallyintheareasofcontrolanddecisionmaking.Ingeneral,itismostusefulin
handlingproblemsnoteasilydefinablebypracticalmathematicalmodels.Forinstance,fuzzylogic
hasbeenemployedinsuchtasksasmanagingstockmarketportfoliosandcontrollingsubway
systems.
Fuzzyderivesmuchofitspowerfromitsabilitytodrawconclusionsandgenerateresponses
basedonvague,ambiguous,qualitative,incomplete,orimpreciseinformation.Inthisrespect,
fuzzybasedsystemshaveareasoningabilitysimilartothatofhumans.Infact,thebehaviorofa
fuzzysystemisrepresentedinaverysimpleandnaturalway.Thisallowsquickconstructionof
understandable,maintainable,androbustsystems.Inaddition,afuzzyapproachgenerally
requiresmuchlessmemoryandcomputingpowerthanconventionalmethods,therebypermitting
smallerandlessexpensivesystems.
LotfiZadeh,aprofessorattheUniversityofCaliforniaatBerkeley,isthepersonmostwidely
associatedwithfuzzylogic.In1965hepresentedtheoriginalpaperformallydefiningfuzzyset
theory,fromwhichfuzzylogicemerged.Zadehextendedtraditionaltheorytoresolvethe
paradoxessometimesgeneratedfromthe"nothingorall"classificationsofAristotelianlogic.
Traditionally,alogicpremisehastwoextremes:eithercompletelytrueorcompletelyfalse.
However,inthefuzzyworld,apremiserangesindegreeoftruthfrom0to100percent,which
allowsittobepartiallytrueandpartiallyfalse.
Byincorporatingthis"degreeoftruth"concept,fuzzylogicextendstraditionallogicintwoways.
First,setsarelabeledqualitatively(usinglinguistictermssuchas"tall,""warm,""active,""nearby,"
andsoon),andtheelementsofthesesetsareassignedvaryingdegreesofmembership.For
instance,a5'11"mananda6'4"manmaybothbemembersofasetof"tall"men,althoughthe
6'4"manhasahigherdegreeofmembership.Secondly,anyactionoroutputresultingfroma
premisebeingtrueexecutestoastrengthreflectingthedegreetowhichthatpremiseistrue.
Asanexample,imagineafanmotor,thespeedofwhichisafunctionoftemperature,asshownin
Table1.Thecurrentsuppliedtothefanmotorisregulatedbysetsoftemperature:cold,cool,
warm,andhot.Inthissystem,asthetemperaturegraduallymovesfromwarmtocool,thecurrent
graduallymovesfrom50to15.Bycontinuouslytrackinginputs,outputscanavoidabrupt
changes,evenasinputstranscendsetboundaries.Fuzzybasedsystemsareconstructedsothat
generatedoutputschangeinasmoothandcontinuousmanner,regardlessofinputscrossingset
boundaries.
Table1:Fanspeedcontrol.
TemperatureFanSpeedRelativeMotor
Current

ColdOff0
CoolSlow15
WarmMedium50
HotFast100

OrganizationofaFuzzySystem
Figure1illustratestheflowofdatathroughafuzzysystem.Systeminputsundergothree
transformationstobecomesystemoutputs.First,afuzzificationprocessthatusespredefined
membershipfunctionsmapseachsysteminputintooneormoredegreesofmembership.Then,
therulesintherulebase(alsopredefined)areevaluatedbycombiningdegreesofmembershipto
formoutputstrengths.Andlastly,thedefuzzificationprocesscomputessystemoutputsbasedon
strengthsandmembershipfunctions.

FuzzificationofInputs
Fuzzificationistheprocessofassigningorcalculatingavaluetorepresentaninput'sdegreeof
membershipinoneormorequalitativegroupings,called"fuzzysets."Figure2showsasystem
input,temperature,withfuzzysetscold,cool,warm,andhot.Eachtemperaturevaluehasa
degreeofmembershipineachofthesesets.Thedegreeofmembershipisdeterminedbya
membershipfunction,whichisdefinedbasedonexperienceorintuition.Figure9illustratesthe
degreeofmembershipcalculationforatrapezoidalmembershipfunction.Itisacceptedthat
membershipfunctionschangeseveraltimesasthesystemistunedtoachievedesiredresponses
togiveninputs.

Generally,oncethesystemisinoperation,themembershipfunctionsdonotchange.Simple
shapessuchastrapezoidsandtrianglesareoftenusedtodefinemembershipinfuzzysets,but
anysuitablefunctioncanbeused.Inaddition,youmustdecideuponthenumberoffuzzysetsper
systeminput.
InFigure2,afuzzysetlabeledcomfortablecouldbeinsertedbetweencoolandwarm.The
numberoffuzzysetmembershipfunctionsandtheshapesyouchoosedependonsuchthingsas
requiredaccuracy,responsivenessandstabilityofthesystem,easeofimplementation,
manipulation,andmaintenance,andsoon.Thetrapezoidalandtriangularmembershipfunctions
aremostcommonandhaveproventobegoodcompromisesbetweeneffectivenessand
efficiency.ThefuzzysetsmustspantheXaxiscoveringtheentirerange,oruniverseofdiscourse,
forasysteminput.MappingtotheYaxisrangesfrom0to1andrepresentsthedegreetowhich
aninputvalueisamemberofthatparticularfuzzyset.Overlappingbetweensetboundariesis
desirableandkeytothesmoothoperationofthesystem.Itpermitsmembershipinmultipleeven
seeminglycontradictorysets.InFigure2,63degreescanbebothcoolandwarm,butitiscoolto
agreaterdegree.Anoverlapof25percentbetweenadjacentfuzzysetsisageneralruleof
thumb.
Thefuzzificationprocesspermitsabindingtotakeplacebetweenlinguisticterms(cold,nearby,
active,large,andsoon)andmembershipfunctions,makingthetermsmeaningfultoacomputer.
Asaresult,adesignercanexpressormodifythebehaviorofasystemusingsuchnatural
language,thusenhancingthepossibilityofclearandconcisedescriptionsofcomplextasks.
EvaluationofRules
Togovernthesystem'sbehavior,thedesignerdevelopsasetofrulesthathavetheformofIfThen
statements.TheIfsideofarulecontainsoneormoreconditions,called"antecedents"theThen
sidecontainsoneormoreactions,called"consequences."Theantecedentsofrulescorrespond
directlytodegreesofmembershipcalculatedduringthefuzzificationprocess.
Forexample,considerapotentialrulefromthestockmarketsystemshowninFigure3:Ifshare
priceisdecreasingAndtradingvolumeisheavy,Thenorderissell.Thetwoconditions"share
priceisdecreasing"and"tradingvolumeisheavy"aretherule'santecedents.Eachantecedent
hasadegreeoftruth(membership)valueassignedtoitasaresultoffuzzification.Theactionof
therule(or"fuzzyoutput")istosellshares.Duringruleevaluation,strengthsarecomputedbased
onantecedentvaluesandthenassignedtotherules'fuzzyoutputs.Generally,aminimum
functionisusedsothatthestrengthofaruleisassignedthevalueofitsweakestorleasttrue
antecedent.Othermethodstocomputerulestrengthcanbeused,suchasmultiplyingantecedent
valuestogether.Theactionofsellingsharesiscarriedouttoadegreethatreflectstherule's

strength.Inotherwords,theamountofsharessoldisbasedonthedegreetowhichsharepriceis
decreasingandtradingvolumeisheavy.Often,morethanoneruleappliestothesamespecific
action,inwhichcasethecommonpracticeistousethestrongestormosttrueruleseeFigure4.

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,further
processing,or"defuzzification,"isrequiredfortworeasons.Thefirstistodecipherthemeaningof
vague(fuzzy)actions,suchas"orderissell,"usingmembershipfunctions.Thesecondisto
resolveconflictsbetweencompetingactionssuchas"orderissell"and"orderishold,"whichmay
havebeentriggeredbycertainconditionsduringruleevaluation.Defuzzificationemploys
compromisingtechniquestoresolveboththevaguenessandconflictissues.
Onecommondefuzzificationtechnique,the"centerofgravitymethod,"consistsofseveralsteps.
Initially,acentroidpointontheXaxisisdeterminedforeachoutputmembershipfunction.Then,
themembershipfunctionsarelimitedinheightbytheappliedrulestrength,andtheareasofthe
membershipfunctionsarecomputed.Finally,thedefuzzifiedoutputisderivedbyaweighted
averageoftheXaxiscentroidpointsandthecomputedareas,withtheareasservingasthe
weights.ThecenterofgravitymethodisillustratedinFigure5.

Sometimes,"singletons"areusedtosimplifythedefuzzificationprocessseeFigure6.Asingleton
isanoutputmembershipfunctionrepresentedbyasingleverticalline.Sinceasingletonintersects
theXaxisatonlyonepoint,thecenterofgravitycalculationreducestojustaweightedaverage
calculationofXaxispointsandrulestrengths,withtherulestrengthsusedasweights.

FuzzyDataStructures
ToimplementafuzzysysteminC,thefollowingtypesofdatamustbeaccommodated:
Systeminputs.
Inputmembershipfunctions.
Antecedentvalues.
Rules.
Ruleoutputstrengths.
Outputmembershipfunctions.
Systemoutputs.
Figure7illustratesanoveralllinkedlistarrangementofsysteminputandmembershipfunction
nodes.ThedetailsofthesestructuresareshowninFigure8.Thesysteminputnodeisstraight
forwardandcontainsaninputname,amembershipfunctionpointer,andanextinputpointer.
Moreinterestingisthemembershipfunctionstructure,whichcontainstwoXaxispointsandtwo
slopevaluesthatdescribeatrapezoidalmembershipfunction.Thisinformationisusedto
calculateantecedentvalues(degreesofmembership),asshowninFigure9andListingThree
(page94).Theresultingantecedentvalueisstoredinthe"value"fieldofthemembershipfunction
structure.RulescanberepresentedbytwosetsofpointersseeFigure10.Thefirstsetindicates
whichantecedentvaluesareusedtodeterminetherule'sstrength,andthesecondsetpointsto
outputlocationswherethestrengthistobeapplied.Finally,adataarrangementsimilartothe
inputdatastructurehandlesoutputsandoutputmembershipfunctionsseeFigure11.ListingOne
(page94)includestheCcodedefinitionofthesedatastructures.ArticlesbyJamesM.Sibigtroth
(see"References")explaintheimplementationoffuzzysystemsattheassemblylanguagelevel.

InvertedpendulumExample
Figure12showsaclassictwodimensionalcontrolproblemknownasthe"invertedpendulum."
Theideaistokeepapoleverticallybalanced.Thepoleisweightedatthetopandattachedatthe
bottombyamovablebase.Ifthepolefallstotherightorleft,thebasemovesinthesame
directiontocompensate.Bymonitoringtheangleandangularvelocityofthependulum,afuzzy
systemcandeterminetheproperforcetoapplyatthebasetokeepitbalanced.Figure13shows
thefuzzysetsassociatedwiththesysteminputsandoutput.Theexactsetofrulesdependson
thedynamicsofthephysicalcomponents,requiredrobustness,andrangeofoperatingconditions.

Theoretically,therulebaseinFigure14issufficienttobalancethependulum,butothersolutions
exist.AgeneralpurposefuzzyinferenceenginelikethatinListingsOnethroughFourcanbe
appliedtomanyapplications.ListingOneprovidestheheaderanddatastructures,ListingsTwo
andThree(page94)presentthemajorfuzzyprocesses,andListingFour(page94)liststhemath
supportfunctions.Theinputconfigurationfilesdescribingsysteminput/output,themembership
functions,andtherulebasedifferfromapplicationtoapplication.Figures14and15containthe

necessaryinformationtoimplementtheinvertedpendulumproblem.
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/outputandmembershipinformationshownFigure13inaformatthat
canbeeasilyparsedbyaninitializationroutine.Suchaninitializationroutine(notshowninthe
listings)setsuptherequireddatastructures,convertingthefourpointsdescribingamembership
functionintotwopointsandtwoslopesseeFigure16.

Generally,fourpointsdescribeatrapezoid,butatrianglecanbeformedbymakingthetwo
midpointsidentical,asinFigure16.
ClosingRemarks
Theemergenceoffuzzylogicisexcitingbecauseitisreadilyapplicabletomanyproblemstoo
awkwardtosolvewithconventionaltechniques.Anyprogrammercaneasilywritecodeto
implementafuzzyinferenceengineliketheonepresentedhere.However,excellentfuzzy
developmenttoolsexistwhichallowthedesignertofocusmoreontheapplicationandbehaviorof
thesystemandlessontheimplementation.Thesetoolsprovideuserfriendly,graphicalinterfaces
witharichsetofsupportfunctionsforanalyzing,debugging,andsimulatingthesystem.Examples
ofsuchtoolsare:FIDEfromAptronix(SanJose,CA),CubiCalcfromHyperlogic(Escondido,CA),
andTILShellfromTogaiInfraLogic(Irvine,CA).Inaddition,Motoroladistributesfreefuzzy
developmenttoolsthroughtheirelectronicBBS."FreewareDataServices,"at5128913733(in
thesubdirectoryamcu/amcull).
Implementingthefuzzyenginemanually,however,affordstheabilitytounderstand,optimize,or
customizethefuzzyinferenceengine.Thisisespeciallyimportantwhenexperimentingwithnew
fuzzyparadigms,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).
[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/output;Rules,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_Inputs;si!=NULL;si=si>next)
for(mf=si>membership_functions;mf!=NULL;mf=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_Base;rule!=NULL;rule=rule>next){
strength=UPPER_LIMIT;/*maxrulestrengthallowed*/
/*processifsideofruletodeterminestrength*/
for(ip=rule>if_side;ip!=NULL;ip=ip>next)
strength=min(strength,*(ip>value));
/*processthensideofruletoapplystrength*/
for(tp=rule>then_side;tp!=NULL;tp=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_Outputs;so!=NULL;so=so>next){
sum_of_products=0;
sum_of_areas=0;
for(mf=so>membership_functions;mf!=NULL;mf=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);
}

GregViot,1993:FuzzylogicinC,Dr.Dobb'sJournal,February1993(specialissueonCognitive
Computing),pgs.4049and94.

Vous aimerez peut-être aussi