Beruflich Dokumente
Kultur Dokumente
Fuzzy Logic in C
FuzzyLogicinC
Creatingafuzzybasedinferenceengine
GregViot,Dr.Dobb'sJournal,February1993
GregisamemberoftheMotorolatechnicalladderandiscurrentlymergingfuzzylogicwith
microcontrollers.HehasanMSEEfromNationalTechnologicalUniversityandaBSEEfromthe
UniversityofTexasatAustin.GregcanbecontactedatMotorolaAdvancedMicrocontrollerDivision,
6501WilliamCannonDriveWest,Austin,Texas787358598.
Fuzzylogicisapowerful,yetstraightforward,problemsolvingtechniquewithwidespreadapplicability,
especiallyintheareasofcontrolanddecisionmaking.Ingeneral,itismostusefulinhandling
problemsnoteasilydefinablebypracticalmathematicalmodels.Forinstance,fuzzylogichasbeen
employedinsuchtasksasmanagingstockmarketportfoliosandcontrollingsubwaysystems.
Fuzzyderivesmuchofitspowerfromitsabilitytodrawconclusionsandgenerateresponsesbased
onvague,ambiguous,qualitative,incomplete,orimpreciseinformation.Inthisrespect,fuzzybased
systemshaveareasoningabilitysimilartothatofhumans.Infact,thebehaviorofafuzzysystemis
representedinaverysimpleandnaturalway.Thisallowsquickconstructionofunderstandable,
maintainable,androbustsystems.Inaddition,afuzzyapproachgenerallyrequiresmuchlessmemory
andcomputingpowerthanconventionalmethods,therebypermittingsmallerandlessexpensive
systems.
LotfiZadeh,aprofessorattheUniversityofCaliforniaatBerkeley,isthepersonmostwidely
associatedwithfuzzylogic.In1965hepresentedtheoriginalpaperformallydefiningfuzzysettheory,
fromwhichfuzzylogicemerged.Zadehextendedtraditionaltheorytoresolvetheparadoxes
sometimesgeneratedfromthe"nothingorall"classificationsofAristotelianlogic.Traditionally,alogic
premisehastwoextremes:eithercompletelytrueorcompletelyfalse.However,inthefuzzyworld,a
premiserangesindegreeoftruthfrom0to100percent,whichallowsittobepartiallytrueand
partiallyfalse.
Byincorporatingthis"degreeoftruth"concept,fuzzylogicextendstraditionallogicintwoways.First,
setsarelabeledqualitatively(usinglinguistictermssuchas"tall,""warm,""active,""nearby,"andso
on),andtheelementsofthesesetsareassignedvaryingdegreesofmembership.Forinstance,a
5'11"mananda6'4"manmaybothbemembersofasetof"tall"men,althoughthe6'4"manhasa
higherdegreeofmembership.Secondly,anyactionoroutputresultingfromapremisebeingtrue
executestoastrengthreflectingthedegreetowhichthatpremiseistrue.
Asanexample,imagineafanmotor,thespeedofwhichisafunctionoftemperature,asshownin
Table1.Thecurrentsuppliedtothefanmotorisregulatedbysetsoftemperature:cold,cool,warm,
andhot.Inthissystem,asthetemperaturegraduallymovesfromwarmtocool,thecurrentgradually
movesfrom50to15.Bycontinuouslytrackinginputs,outputscanavoidabruptchanges,evenas
inputstranscendsetboundaries.Fuzzybasedsystemsareconstructedsothatgeneratedoutputs
changeinasmoothandcontinuousmanner,regardlessofinputscrossingsetboundaries.
Table1:Fanspeedcontrol.
Temperature
Relative Motor
Current
-----------------------------------------Cold
Cool
Fan Speed
Off
Slow
0
15
http://www.chebucto.ns.ca/Science/AIMET/archive/ddj/fuzzy_logic_in_C/
1/16
6/5/2016
Fuzzy Logic in C
Warm
Hot
Medium
Fast
50
100
OrganizationofaFuzzySystem
Figure1illustratestheflowofdatathroughafuzzysystem.Systeminputsundergothree
transformationstobecomesystemoutputs.First,afuzzificationprocessthatusespredefined
membershipfunctionsmapseachsysteminputintooneormoredegreesofmembership.Then,the
rulesintherulebase(alsopredefined)areevaluatedbycombiningdegreesofmembershiptoform
outputstrengths.Andlastly,thedefuzzificationprocesscomputessystemoutputsbasedonstrengths
andmembershipfunctions.
FuzzificationofInputs
Fuzzificationistheprocessofassigningorcalculatingavaluetorepresentaninput'sdegreeof
membershipinoneormorequalitativegroupings,called"fuzzysets."Figure2showsasysteminput,
temperature,withfuzzysetscold,cool,warm,andhot.Eachtemperaturevaluehasadegreeof
membershipineachofthesesets.Thedegreeofmembershipisdeterminedbyamembership
function,whichisdefinedbasedonexperienceorintuition.Figure9illustratesthedegreeof
membershipcalculationforatrapezoidalmembershipfunction.Itisacceptedthatmembership
functionschangeseveraltimesasthesystemistunedtoachievedesiredresponsestogiveninputs.
http://www.chebucto.ns.ca/Science/AIMET/archive/ddj/fuzzy_logic_in_C/
2/16
6/5/2016
Fuzzy Logic in C
Generally,oncethesystemisinoperation,themembershipfunctionsdonotchange.Simpleshapes
suchastrapezoidsandtrianglesareoftenusedtodefinemembershipinfuzzysets,butanysuitable
functioncanbeused.Inaddition,youmustdecideuponthenumberoffuzzysetspersysteminput.
InFigure2,afuzzysetlabeledcomfortablecouldbeinsertedbetweencoolandwarm.Thenumberof
fuzzysetmembershipfunctionsandtheshapesyouchoosedependonsuchthingsasrequired
accuracy,responsivenessandstabilityofthesystem,easeofimplementation,manipulation,and
maintenance,andsoon.Thetrapezoidalandtriangularmembershipfunctionsaremostcommonand
haveproventobegoodcompromisesbetweeneffectivenessandefficiency.Thefuzzysetsmustspan
theXaxiscoveringtheentirerange,oruniverseofdiscourse,forasysteminput.MappingtotheY
axisrangesfrom0to1andrepresentsthedegreetowhichaninputvalueisamemberofthat
particularfuzzyset.Overlappingbetweensetboundariesisdesirableandkeytothesmoothoperation
ofthesystem.Itpermitsmembershipinmultipleevenseeminglycontradictorysets.InFigure2,63
degreescanbebothcoolandwarm,butitiscooltoagreaterdegree.Anoverlapof25percent
betweenadjacentfuzzysetsisageneralruleofthumb.
Thefuzzificationprocesspermitsabindingtotakeplacebetweenlinguisticterms(cold,nearby,
active,large,andsoon)andmembershipfunctions,makingthetermsmeaningfultoacomputer.Asa
result,adesignercanexpressormodifythebehaviorofasystemusingsuchnaturallanguage,thus
enhancingthepossibilityofclearandconcisedescriptionsofcomplextasks.
EvaluationofRules
Togovernthesystem'sbehavior,thedesignerdevelopsasetofrulesthathavetheformofIfThen
statements.TheIfsideofarulecontainsoneormoreconditions,called"antecedents"theThenside
containsoneormoreactions,called"consequences."Theantecedentsofrulescorresponddirectlyto
degreesofmembershipcalculatedduringthefuzzificationprocess.
Forexample,considerapotentialrulefromthestockmarketsystemshowninFigure3:Ifshareprice
isdecreasingAndtradingvolumeisheavy,Thenorderissell.Thetwoconditions"sharepriceis
decreasing"and"tradingvolumeisheavy"aretherule'santecedents.Eachantecedenthasadegree
oftruth(membership)valueassignedtoitasaresultoffuzzification.Theactionoftherule(or"fuzzy
output")istosellshares.Duringruleevaluation,strengthsarecomputedbasedonantecedentvalues
andthenassignedtotherules'fuzzyoutputs.Generally,aminimumfunctionisusedsothatthe
strengthofaruleisassignedthevalueofitsweakestorleasttrueantecedent.Othermethodsto
computerulestrengthcanbeused,suchasmultiplyingantecedentvaluestogether.Theactionof
http://www.chebucto.ns.ca/Science/AIMET/archive/ddj/fuzzy_logic_in_C/
3/16
6/5/2016
Fuzzy Logic in C
sellingsharesiscarriedouttoadegreethatreflectstherule'sstrength.Inotherwords,theamountof
sharessoldisbasedonthedegreetowhichsharepriceisdecreasingandtradingvolumeisheavy.
Often,morethanoneruleappliestothesamespecificaction,inwhichcasethecommonpracticeisto
usethestrongestormosttrueruleseeFigure4.
Figure4:Ruleevaluationcomputation.
Rule 1: if A & B then Z & X
Rule 2: if C & D then Z & Y
Strength of Rule 1 = min (A,B)
Strength of Rule 2 = min (C,D)
X = Strength of Rule 1
http://www.chebucto.ns.ca/Science/AIMET/archive/ddj/fuzzy_logic_in_C/
4/16
6/5/2016
Fuzzy Logic in C
Y = Strength of Rule 2
Z = max (Strength of Rule 1
Strength of Rule 2)
= max (min(A,B), min(C,D))
DefuzzificationofOutputs
Eventhoughtheruleevaluationprocessassignsstrengthstoeachspecificaction,furtherprocessing,
or"defuzzification,"isrequiredfortworeasons.Thefirstistodecipherthemeaningofvague(fuzzy)
actions,suchas"orderissell,"usingmembershipfunctions.Thesecondistoresolveconflicts
betweencompetingactionssuchas"orderissell"and"orderishold,"whichmayhavebeentriggered
bycertainconditionsduringruleevaluation.Defuzzificationemployscompromisingtechniquesto
resolveboththevaguenessandconflictissues.
Onecommondefuzzificationtechnique,the"centerofgravitymethod,"consistsofseveralsteps.
Initially,acentroidpointontheXaxisisdeterminedforeachoutputmembershipfunction.Then,the
membershipfunctionsarelimitedinheightbytheappliedrulestrength,andtheareasofthe
membershipfunctionsarecomputed.Finally,thedefuzzifiedoutputisderivedbyaweightedaverage
oftheXaxiscentroidpointsandthecomputedareas,withtheareasservingastheweights.The
centerofgravitymethodisillustratedinFigure5.
Sometimes,"singletons"areusedtosimplifythedefuzzificationprocessseeFigure6.Asingletonis
anoutputmembershipfunctionrepresentedbyasingleverticalline.Sinceasingletonintersectsthe
http://www.chebucto.ns.ca/Science/AIMET/archive/ddj/fuzzy_logic_in_C/
5/16
6/5/2016
Fuzzy Logic in C
Xaxisatonlyonepoint,thecenterofgravitycalculationreducestojustaweightedaverage
calculationofXaxispointsandrulestrengths,withtherulestrengthsusedasweights.
FuzzyDataStructures
ToimplementafuzzysysteminC,thefollowingtypesofdatamustbeaccommodated:
Systeminputs.
Inputmembershipfunctions.
Antecedentvalues.
Rules.
Ruleoutputstrengths.
Outputmembershipfunctions.
Systemoutputs.
Figure7illustratesanoveralllinkedlistarrangementofsysteminputandmembershipfunctionnodes.
ThedetailsofthesestructuresareshowninFigure8.Thesysteminputnodeisstraightforwardand
containsaninputname,amembershipfunctionpointer,andanextinputpointer.Moreinterestingis
themembershipfunctionstructure,whichcontainstwoXaxispointsandtwoslopevaluesthat
describeatrapezoidalmembershipfunction.Thisinformationisusedtocalculateantecedentvalues
(degreesofmembership),asshowninFigure9andListingThree(page94).Theresultingantecedent
valueisstoredinthe"value"fieldofthemembershipfunctionstructure.Rulescanberepresentedby
twosetsofpointersseeFigure10.Thefirstsetindicateswhichantecedentvaluesareusedto
determinetherule'sstrength,andthesecondsetpointstooutputlocationswherethestrengthistobe
applied.Finally,adataarrangementsimilartotheinputdatastructurehandlesoutputsandoutput
membershipfunctionsseeFigure11.ListingOne(page94)includestheCcodedefinitionofthese
datastructures.ArticlesbyJamesM.Sibigtroth(see"References")explaintheimplementationof
fuzzysystemsattheassemblylanguagelevel.
http://www.chebucto.ns.ca/Science/AIMET/archive/ddj/fuzzy_logic_in_C/
6/16
6/5/2016
Fuzzy Logic in C
http://www.chebucto.ns.ca/Science/AIMET/archive/ddj/fuzzy_logic_in_C/
7/16
6/5/2016
Fuzzy Logic in C
http://www.chebucto.ns.ca/Science/AIMET/archive/ddj/fuzzy_logic_in_C/
8/16
6/5/2016
Fuzzy Logic in C
InvertedpendulumExample
Figure12showsaclassictwodimensionalcontrolproblemknownasthe"invertedpendulum."The
ideaistokeepapoleverticallybalanced.Thepoleisweightedatthetopandattachedatthebottom
byamovablebase.Ifthepolefallstotherightorleft,thebasemovesinthesamedirectionto
compensate.Bymonitoringtheangleandangularvelocityofthependulum,afuzzysystemcan
determinetheproperforcetoapplyatthebasetokeepitbalanced.Figure13showsthefuzzysets
http://www.chebucto.ns.ca/Science/AIMET/archive/ddj/fuzzy_logic_in_C/
9/16
6/5/2016
Fuzzy Logic in C
associatedwiththesysteminputsandoutput.Theexactsetofrulesdependsonthedynamicsofthe
physicalcomponents,requiredrobustness,andrangeofoperatingconditions.
http://www.chebucto.ns.ca/Science/AIMET/archive/ddj/fuzzy_logic_in_C/
10/16
6/5/2016
Fuzzy Logic in C
Theoretically,therulebaseinFigure14issufficienttobalancethependulum,butothersolutions
exist.AgeneralpurposefuzzyinferenceenginelikethatinListingsOnethroughFourcanbeapplied
tomanyapplications.ListingOneprovidestheheaderanddatastructures,ListingsTwoandThree
http://www.chebucto.ns.ca/Science/AIMET/archive/ddj/fuzzy_logic_in_C/
11/16
6/5/2016
Fuzzy Logic in C
(page94)presentthemajorfuzzyprocesses,andListingFour(page94)liststhemathsupport
functions.Theinputconfigurationfilesdescribingsysteminput/output,themembershipfunctions,and
therulebasedifferfromapplicationtoapplication.Figures14and15containthenecessary
informationtoimplementtheinvertedpendulumproblem.
Figure14:Invertedpendulumrulebase.
Rule 1:
Rule 2:
Rule 3:
Rule 4:
Rule 5:
Rule 6:
Rule 7:
Rule 8:
Rule 9:
Rule 10:
Rule 11:
Rule 12:
Rule 13:
Rule 14:
Rule 15:
IF (angle is NL)
IF (angle is ZE)
IF (angle is NM)
IF (angle is ZE)
IF (angle is NS)
IF (angle is ZE)
IF (angle is NS)
IF (angle is ZE)
IF (angle is ZE)
IF (angle is PS)
IF (angle is PS)
IF (angle is ZE)
IF (angle is NM)
IF (angle is ZE)
IF (angle is PL)
Figure15:Samplemembershipfunctioninputfile.
input: angle
NL:
0 31
NM: 31 63
NS: 63 95
ZE: 95 127
PS: 127 159
PM: 159 191
PL: 191 223
31
63
95
127
159
191
223
63
95
127
159
191
223
255
input: velocity
NL:
0 31 31
NM: 31 63 63
NS: 63 95 95
ZE: 95 127 127
PS: 127 159 159
PM: 159 191 191
PL: 191 223 223
63
95
127
159
191
223
255
output: force
NL:
0 31
NM: 31 63
NS: 63 95
ZE: 95 127
PS: 127 159
PM: 159 191
PL: 191 223
31
63
95
127
159
191
223
63
95
127
159
191
223
255
Figure15repeatstheinput/outputandmembershipinformationshownFigure13inaformatthatcan
beeasilyparsedbyaninitializationroutine.Suchaninitializationroutine(notshowninthelistings)
setsuptherequireddatastructures,convertingthefourpointsdescribingamembershipfunctioninto
twopointsandtwoslopesseeFigure16.
http://www.chebucto.ns.ca/Science/AIMET/archive/ddj/fuzzy_logic_in_C/
12/16
6/5/2016
Fuzzy Logic in C
Generally,fourpointsdescribeatrapezoid,butatrianglecanbeformedbymakingthetwomidpoints
identical,asinFigure16.
ClosingRemarks
Theemergenceoffuzzylogicisexcitingbecauseitisreadilyapplicabletomanyproblemstoo
awkwardtosolvewithconventionaltechniques.Anyprogrammercaneasilywritecodetoimplementa
fuzzyinferenceengineliketheonepresentedhere.However,excellentfuzzydevelopmenttoolsexist
whichallowthedesignertofocusmoreontheapplicationandbehaviorofthesystemandlessonthe
implementation.Thesetoolsprovideuserfriendly,graphicalinterfaceswitharichsetofsupport
functionsforanalyzing,debugging,andsimulatingthesystem.Examplesofsuchtoolsare:FIDEfrom
Aptronix(SanJose,CA),CubiCalcfromHyperlogic(Escondido,CA),andTILShellfromTogai
InfraLogic(Irvine,CA).Inaddition,Motoroladistributesfreefuzzydevelopmenttoolsthroughtheir
electronicBBS."FreewareDataServices,"at5128913733(inthesubdirectoryamcu/amcull).
Implementingthefuzzyenginemanually,however,affordstheabilitytounderstand,optimize,or
customizethefuzzyinferenceengine.Thisisespeciallyimportantwhenexperimentingwithnewfuzzy
paradigms,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).
http://www.chebucto.ns.ca/Science/AIMET/archive/ddj/fuzzy_logic_in_C/
13/16
6/5/2016
Fuzzy Logic in C
Sibigtroth,JamesM."ImplementingFuzzyExpertRules."AIExpert(April,1992).
Williams,Tom."FuzzyLogicisAnythingbutFuzzy."ComputerDesign(April,1992).
[LISTINGONE]
/* General-purpose fuzzy inference engine supporting any number of system
inputs and outputs, membership functions, and rules. Membership functions can
be any shape defineable by 2 points and 2 slopes--trapezoids, triangles,
rectanlges, etc. Rules can have any number of antecedents and outputs, and can
vary from rule to rule. "Min" method is used to compute rule strength, "Max"
for applying rule strengths, "Center-of-Gravity" for defuzzification. This
implementation of Inverted Pendulum control problem has: System Inputs, 2
(pendulum angle and velocity); System Outputs, 1 (force supplied to base of
pendulum); Membership Functions, 7 per system input/output; Rules, 15 (each
with 2 antecedents & 1 output). If more precision is required, integers can
be changed to real numbers.*/
#include <stdio.h>
#define MAXNAME 10
#define UPPER_LIMIT 255
[LISTINGTWO]
http://www.chebucto.ns.ca/Science/AIMET/archive/ddj/fuzzy_logic_in_C/
14/16
6/5/2016
Fuzzy Logic in C
main()
{
initialize_system();
while(1){
get_system_inputs();
fuzzification();
rule_evaluation();
defuzzification();
put_system_outputs();
}
}
[LISTINGTHREE]
/* Fuzzification--Degree of membership value is calculated for each membership
function of each system input. Values correspond to antecedents in rules. */
fuzzification()
{
struct io_type *si;
/* system input pointer
*/
struct mf_type *mf;
/* membership function pointer */
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);
}
/* Rule Evaluation--Each rule consists of a list of pointers to antecedents
(if side), list of pointers to outputs (then side), and pointer to next rule
in rule base. When a rule is evaluated, its antecedents are ANDed together,
using a minimum function, to form strength of rule. Then strength is applied
to each of listed rule outputs. If an output has already been assigned a rule
strength, during current inference pass, a maximum function is used to
determine which strength should apply. */
rule_evaluation()
{
struct rule_type *rule;
struct rule_element_type *ip;
/* pointer of antecedents (if-parts) */
struct rule_element_type *tp;
/* pointer to consequences (then-parts) */
int strength;
/* strength of rule currently being evaluated */
for(rule=Rule_Base; rule != NULL; rule=rule->next){
strength = UPPER_LIMIT;
/* max rule strength allowed */
/* process if-side of rule to determine strength */
for(ip=rule->if_side; ip != NULL; ip=ip->next)
strength = min(strength,*(ip->value));
/* process then-side of rule to apply strength */
for(tp=rule->then_side; tp != NULL; tp=tp->next)
*(tp->value) = max(strength,*(tp->value));
}
}
/* Defuzzification */
defuzzification()
{
struct io_type *so;
/* system output pointer
*/
struct mf_type *mf;
/* output membership function pointer
*/
int sum_of_products; /* sum of products of area & centroid */
int sum_of_areas;
/* sum of shortend trapezoid area
*/
int area;
int centroid;
/* compute a defuzzified value for each system output */
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){
http://www.chebucto.ns.ca/Science/AIMET/archive/ddj/fuzzy_logic_in_C/
15/16
6/5/2016
Fuzzy Logic in C
area = compute_area_of_trapezoid(mf);
centroid = mf->point1 + (mf->point2 - mf->point1)/2;
sum_of_products += area * centroid;
sum_of_areas += area;
}
so->value = sum_of_products/sum_of_areas; /* weighted average */
}
[LISTINGFOUR]
/* Compute Degree of Membership--Degree to which input is a member of mf is
calculated as follows: 1. Compute delta terms to determine if input is inside
or outside membership function. 2. If outside, then degree of membership is 0.
Otherwise, smaller of delta_1 * slope1 and delta_2 * slope2 applies.
3. Enforce upper limit. */
compute_degree_of_membership(mf,input)
struct mf_type *mf;
int input;
{
int delta_1;
int delta_2;
delta_1 = input - mf->point1;
delta_2 = mf->point2 - input;
if ((delta_1 <= 0) || (delta_2 <= 0)) /* input outside mem. function ? */
mf->value = 0;
/* then degree of membership is 0 */
else
mf->value = min( (mf->slope1*delta_1),(mf->slope2*delta_2) );
mf->value = min(mf->value,UPPER_LIMIT); /* enforce upper limit */
}
/* Compute Area of Trapezoid--Each inference pass produces a new set of output
strengths which affect the areas of trapezoidal membership functions used in
center-of-gravity defuzzification. Area values must be recalculated with each
pass. Area of trapezoid is h*(a+b)/2 where h=height=output_strength=mf->value
b=base=mf->point2-mf->point1 a=top= must be derived from h,b, and slopes1&2 */
compute_area_of_trapezoid(mf)
struct mf_type *mf;
{
int run_1;
int run_2;
int base;
int top;
int area;
base = mf->point2 - mf->point1;
run_1 = mf->value/mf->slope1;
run_2 = mf->value/mf->slope2;
top = base - run_1 - run_2;
area = mf->value * ( base + top)/2;
return(area);
}
GregViot,1993:FuzzylogicinC,Dr.Dobb'sJournal,February1993(specialissueonCognitive
Computing),pgs.4049and94.
http://www.chebucto.ns.ca/Science/AIMET/archive/ddj/fuzzy_logic_in_C/
16/16