You are on page 1of 9

12/14/2015 ModelingInverseKinematicsinaRoboticArmMATLAB&SimulinkExample

ModelingInverseKinematicsinaRoboticArm
Thisexampleshowshowtouseafuzzysystemtomodeltheinversekinematicsinatwojointroboticarm.

WhatIsInverseKinematics?
WhyUseFuzzyLogic?
OverviewofFuzzySolution
WhatIsANFIS?
DataGeneration
BuildingANFISNetworks
ValidatingANFISNetworks
BuildingaSolutionAroundtheTrainedANFISNetworks
Conclusion
Glossary

WhatIsInverseKinematics?
Kinematicsisthescienceofmotion.Inatwojointroboticarm,giventheanglesofthejoints,thekinematicsequations
givethelocationofthetipofthearm.Inversekinematicsreferstothereverseprocess.Givenadesiredlocationforthe
tipoftheroboticarm,whatshouldtheanglesofthejointsbesoastolocatethetipofthearmatthedesiredlocation.
Thereisusuallymorethanonesolutionandcanattimesbeadifficultproblemtosolve.

Thisisatypicalprobleminroboticsthatneedstobesolvedtocontrolaroboticarmtoperformtasksitisdesignatedto
do.Ina2dimensionalinputspace,withatwojointroboticarmandgiventhedesiredcoordinate,theproblemreduces
tofindingthetwoanglesinvolved.Thefirstangleisbetweenthefirstarmandtheground(orwhateveritisattachedto).
Thesecondangleisbetweenthefirstarmandthesecondarm.

Figure1:Illustrationshowingthetwojointroboticarmwiththetwoangles, theta1 and theta2

WhyUseFuzzyLogic?
Forsimplestructureslikethetwojointroboticarm,itispossibletomathematicallydeducetheanglesatthejoints
giventhedesiredlocationofthetipofthearm.Howeverwithmorecomplexstructures(eg:njointroboticarms
12/14/2015 ModelingInverseKinematicsinaRoboticArmMATLAB&SimulinkExample

operatingina3dimensionalinputspace)deducingamathematicalsolutionfortheinversekinematicsmayprove
challenging.

Usingfuzzylogic,wecanconstructaFuzzyInferenceSystemthatdeducestheinversekinematicsiftheforward
kinematicsoftheproblemisknown,hencesidesteppingtheneedtodevelopananalyticalsolution.Also,thefuzzy
solutioniseasilyunderstandableanddoesnotrequirespecialbackgroundknowledgetocomprehendandevaluateit.

Inthefollowingsection,abroadoutlinefordevelopingsuchasolutionisdescribed,andlater,thedetailedstepsare
elaborated.

OverviewofFuzzySolution
Sincetheforwardkinematicsformulaeforthetwojointroboticarmareknown,xandycoordinatesofthetipofthearm
arededucedfortheentirerangeofanglesofrotationofthetwojoints.Thecoordinatesandtheanglesaresavedtobe
usedastrainingdatatotrainANFIS(AdaptiveNeuroFuzzyInferenceSystem)network.

DuringtrainingtheANFISnetworklearnstomapthecoordinates (x,y) totheangles (theta1,theta2) .


ThetrainedANFISnetworkisthenusedasapartofalargercontrolsystemtocontroltheroboticarm.Knowingthe
desiredlocationoftheroboticarm,thecontrolsystemusesthetrainedANFISnetworktodeducetheangularpositions
ofthejointsandappliesforcetothejointsoftheroboticarmaccordinglytomoveittothedesiredlocation.

WhatIsANFIS?
ANFISstandsforAdaptiveNeuroFuzzyInferenceSystem.Itisahybridneurofuzzytechniquethatbringslearning
capabilitiesofneuralnetworkstofuzzyinferencesystems.Thelearningalgorithmtunesthemembershipfunctionsofa
SugenotypeFuzzyInferenceSystemusingthetraininginputoutputdata.

Inthiscase,theinputoutputdatareferstothe"coordinatesangles"dataset.ThecoordinatesactasinputtotheANFIS
andtheanglesactastheoutput.Thelearningalgorithm"teaches"theANFIStomapthecoordinatestotheangles
throughaprocesscalledtraining.Attheendoftraining,thetrainedANFISnetworkwouldhavelearnedtheinputoutput
mapandbereadytobedeployedintothelargercontrolsystemsolution.

DataGeneration
Let theta1 betheanglebetweenthefirstarmandtheground.Let theta2 betheanglebetweenthesecondarm
andthefirstarm(RefertoFigure1forillustration).Letthelengthofthefirstarmbe l1 andthatofthesecondarmbe
l2 .
Letusassumethatthefirstjointhaslimitedfreedomtorotateanditcanrotatebetween0and90degrees.Similarly,
assumethatthesecondjointhaslimitedfreedomtorotateandcanrotatebetween0and180degrees.(This
assumptiontakesawaytheneedtohandlesomespecialcaseswhichwillconfusethediscourse).Hence,
0<=theta1<=pi/2 and 0<=theta2<=pi .
12/14/2015 ModelingInverseKinematicsinaRoboticArmMATLAB&SimulinkExample

Figure2:Illustrationshowingallpossible theta1 and theta2 values.

Now,foreverycombinationof theta1 and theta2 valuesthexandycoordinatesarededucedusingforward


kinematicsformulae.

Thefollowingcodesnippetshowshowdataisgeneratedforallcombinationof theta1 and theta2 valuesand


savedintoamatrixtobeusedastrainingdata.Thereasonforsavingthedataintwomatricesisexplainedinthe
followingsection.

l1=10;%lengthoffirstarm
l2=7;%lengthofsecondarm
theta1=0:0.1:pi/2;%allpossibletheta1values
theta2=0:0.1:pi;%allpossibletheta2values
[THETA1,THETA2]=meshgrid(theta1,theta2);%generateagridoftheta1and
theta2values
X=l1*cos(THETA1)+l2*cos(THETA1+THETA2);%computexcoordinates
Y=l1*sin(THETA1)+l2*sin(THETA1+THETA2);%computeycoordinates
data1=[X(:)Y(:)THETA1(:)];%createxytheta1dataset
data2=[X(:)Y(:)THETA2(:)];%createxytheta2dataset

Clickhereforunvectorizedcode

ThefollowingplotshowsalltheXYdatapointsgeneratedbycyclingthroughdifferentcombinationsof theta1 and

theta2 anddeducingxandycoordinatesforeach.Theplotcanbegeneratedbyusingthecodesnippetshown
12/14/2015 ModelingInverseKinematicsinaRoboticArmMATLAB&SimulinkExample

theta2 anddeducingxandycoordinatesforeach.Theplotcanbegeneratedbyusingthecodesnippetshown
below.Theplotisillustratedfurtherforeasierunderstanding.

plot(X(:),Y(:),'r.');
axisequal;
xlabel('X','fontsize',10)
ylabel('Y','fontsize',10)
title('XYcoordinatesgeneratedforalltheta1andtheta2combinations
usingforwardkinematicsformula','fontsize',10)

Figure3:XYcoordinatesgeneratedforall theta1 and theta2 combinationsusingforwardkinematicsformulae

BuildingANFISNetworks
OneapproachtobuildinganANFISsolutionforthisproblem,istobuildtwoANFISnetworks,onetopredict theta1
andtheothertopredict theta2 .

InorderfortheANFISnetworkstobeabletopredicttheanglestheyhavetobetrainedwithsampleinputoutputdata.
ThefirstANFISnetworkwillbetrainedwithXandYcoordinatesasinputandcorresponding theta1 valuesas
output.Thematrix data1 containsthe xytheta1 datasetrequiredtotrainthefirstANFISnetwork.Therefore
data1 willbeusedasthedatasettotrainthefirstANFISnetwork.
Similarly,thesecondANFISnetworkwillbetrainedwithXandYcoordinatesasinputandcorresponding theta2
valuesasoutput.Thematrix data2 containsthe xytheta2 datasetrequiredtotrainthesecondANFIS
network.Therefore data2 willbeusedasthedatasettotrainthesecondANFISnetwork.
anfis isthefunctionthatisusedtotrainanANFISnetwork.Thereareseveralsyntaxestothefunction.Ifcalled
12/14/2015 ModelingInverseKinematicsinaRoboticArmMATLAB&SimulinkExample

anfis isthefunctionthatisusedtotrainanANFISnetwork.Thereareseveralsyntaxestothefunction.Ifcalled
withthefollowingsyntax, anfis automaticallycreatesaSugenotypeFISandtrainsitusingthetrainingdata
passedtothefunction.

Thefollowingcodemaytakeacoupleofminutestorun:

fprintf('>%s\n','StarttrainingfirstANFISnetwork.Itmaytakeoneminute
dependingonyourcomputersystem.')
anfis1=anfis(data1,7,150,[0,0,0,0]);%trainfirstANFISnetwork
fprintf('>%s\n','StarttrainingsecondANFISnetwork.Itmaytakeone
minutedependingonyourcomputersystem.')
anfis2=anfis(data2,6,150,[0,0,0,0]);%trainsecondANFISnetwork

>StarttrainingfirstANFISnetwork.Itmaytakeoneminutedependingon
yourcomputersystem.
>StarttrainingsecondANFISnetwork.Itmaytakeoneminutedependingon
yourcomputersystem.

Thefirstparameterto anfis isthetrainingdata,thesecondparameteristhenumberofmembershipfunctionsused


tocharacterizeeachinputandoutput,thethirdparameteristhenumberoftrainingepochsandthelastparameteris
theoptionstodisplayprogressduringtraining.Thevaluesfornumberofepochsandthenumberofmembership
functionshavebeenarrivedatafterafairamountofexperimentationwithdifferentvalues.

ThetoolboxcomeswithGUI'sthathelpsbuildandexperimentwithANFISnetworks.

anfis1 and anfis2 representthetwotrainedANFISnetworksthatwillbedeployedinthelargercontrolsystem.


Oncethetrainingiscomplete,thetwoANFISnetworkswouldhavelearnedtoapproximatetheangles( theta1,
theta2 )asafunctionofthecoordinates( x,y ).OneadvantageofusingthefuzzyapproachisthattheANFIS
networkwouldnowapproximatetheanglesforcoordinatesthataresimilarbutnotexactlythesameasitwastrained
with.Forexample,thetrainedANFISnetworksarenowcapableofapproximatingtheanglesforcoordinatesthatlie
betweentwopointsthatwereincludedinthetrainingdataset.Thiswillallowthefinalcontrollertomovethearm
smoothlyintheinputspace.

WenowhavetwotrainedANFISnetworkswhicharereadytobedeployedintothelargersystemthatwillutilizethese
networkstocontroltheroboticarms.

ValidatingANFISNetworks
Havingtrainedthenetworks,animportantfollowupstepistovalidatethenetworkstodeterminehowwelltheANFIS
networkswouldperforminsidethelargercontrolsystem.

Sincethisexampleproblemdealswithatwojointroboticarmwhoseinversekinematicsformulaecanbederived,itis
possibletotesttheanswersthattheANFISnetworksproducewiththeanswersfromthederivedformulae.

Let'sassumethatitisimportantfortheANFISnetworkstohavelowerrorswithintheoperatingrange 0<x<2 and


8<y<10 .

x=0:0.1:2;%xcoordinatesforvalidation
y=8:0.1:10;%ycoordinatesforvalidation
12/14/2015 ModelingInverseKinematicsinaRoboticArmMATLAB&SimulinkExample

The theta1 and theta2 valuesarededucedmathematicallyfromthexandycoordinatesusinginverse


kinematicsformulae.

[X,Y]=meshgrid(x,y);
c2=(X.^2+Y.^2l1^2l2^2)/(2*l1*l2);
s2=sqrt(1c2.^2);
THETA2D=atan2(s2,c2);%theta2isdeduced
k1=l1+l2.*c2;
k2=l2*s2;
THETA1D=atan2(Y,X)atan2(k2,k1);%theta1isdeduced

Clickhereforunvectorizedcode

THETA1D and THETA2D arethevariablesthatholdthevaluesof theta1 and theta2 deducedusingthe


inversekinematicsformulae.

theta1 and theta2 valuespredictedbythetrainedanfisnetworksareobtainedbyusingthecommand


evalfis whichevaluatesaFISforthegiveninputs.
Here, evalfis isusedtofindouttheFISoutputsforthesamexyvaluesusedearlierintheinversekinematics
formulae.

XY=[X(:)Y(:)];
THETA1P=evalfis(XY,anfis1);%theta1predictedbyanfis1
THETA2P=evalfis(XY,anfis2);%theta2predictedbyanfis2

Now,wecanseehowclosetheFISoutputsarewithrespecttothededucedvalues.

theta1diff=THETA1D(:)THETA1P;
theta2diff=THETA2D(:)THETA2P;
subplot(2,1,1);
plot(theta1diff);
ylabel('THETA1DTHETA1P','fontsize',10)
title('Deducedtheta1Predictedtheta1','fontsize',10)
subplot(2,1,2);
plot(theta2diff);
ylabel('THETA2DTHETA2P','fontsize',10)
title('Deducedtheta2Predictedtheta2','fontsize',10)
12/14/2015 ModelingInverseKinematicsinaRoboticArmMATLAB&SimulinkExample

Theerrorsareinthe 1e3 rangewhichisafairlygoodnumberfortheapplicationitisbeingusedin.Howeverthis


maynotbeacceptableforanotherapplication,inwhichcasetheparameterstothe anfis functionmaybetweaked
untilanacceptablesolutionisarrivedat.Also,othertechniqueslikeinputselectionandalternatewaystomodelthe
problemmaybeexplored.

BuildingaSolutionAroundtheTrainedANFISNetworks
Nowgivenaspecifictask,suchasrobotspickingupanobjectinanassemblyline,thelargercontrolsystemwilluse
thetrainedANFISnetworksasareference,muchlikealookuptable,todeterminewhattheanglesofthearmsmust
be,givenadesiredlocationforthetipofthearm.Knowingthedesiredanglesandthecurrentanglesofthejoints,the
systemwillapplyforceappropriatelyonthejointsofthearmstomovethemtowardsthedesiredlocation.

TheinvkinecommandlaunchesaGUIthatshowshowthetwotrainedANFISnetworksperformwhenaskedtotrace
anellipse.
12/14/2015 ModelingInverseKinematicsinaRoboticArmMATLAB&SimulinkExample

Figure4:GUIforInverseKinematicsModeling.

ThetwoANFISnetworksusedintheexamplehavebeenpretrainedandaredeployedintoalargersystemthat
controlsthetipofthetwojointrobotarmtotraceanellipseintheinputspace.

Theellipsetobetracedcanbemovedaround.Movetheellipsetoaslightlydifferentlocationandobservehowthe
systemrespondsbymovingthetipoftheroboticarmfromitscurrentlocationtotheclosestpointonthenewlocation
oftheellipse.Alsoobservethatthesystemrespondssmoothlyaslongastheellipsetobetracedlieswithinthe'x'
markedspotswhichrepresentthedatagridthatwasusedtotrainthenetworks.Oncetheellipseismovedoutsidethe
rangeofdataitwastrainedwith,theANFISnetworksrespondunpredictably.Thisemphasizestheimportanceof
havingrelevantandrepresentativedatafortraining.Datamustbegeneratedbasedontheexpectedrangeofoperation
toavoidsuchunpredictabilityandinstabilityissues.

Conclusion
ThisexampleillustratedusingANFIStosolveaninversekinematicsproblem.Fuzzylogichasalsofoundnumerous
otherapplicationsinotherareasoftechnologylikenonlinearcontrol,automaticcontrol,signalprocessing,system
identification,patternrecognition,timeseriesprediction,datamining,financialapplicationsetc.,

Exploreotherdemosandthedocumentationformoreinsightintofuzzylogicanditsapplications.

Glossary
ANFISAdaptiveNeuroFuzzyInferenceSystem.atechniqueforautomaticallytuningSugenotypeinferencesystems
basedontrainingdata.

membershipfunctionsafunctionthatspecifiesthedegreetowhichagiveninputbelongstoasetorisrelatedtoa
concept.

inputspaceitisatermusedtodefinetherangeofallpossiblevalues
12/14/2015 ModelingInverseKinematicsinaRoboticArmMATLAB&SimulinkExample

FISFuzzyInferenceSystem.Theoverallnameforasystemthatusesfuzzyreasoningtomapaninputspacetoan
outputspace.

epochs1epochoftrainingrepresentsonecompletepresentationofallthesamples/datapoints/rowsofthetraining
datasettotheFIS.TheinputsofeachsamplearepresentedandtheFISoutputsarecomputedwhicharecompared
withthedesiredoutputstocomputetheerrorbetweenthetwo.Theparametersofthemembershipfunctionsarethen
tunedtoreducetheerrorbetweenthedesiredoutputandtheactualFISoutput.

TRYORBUY
ContactSales(http://www.mathworks.com/company/aboutus/contact_us/contact_sales.html?
eventid=1148630771&s_iid=cex_sales_FL_tb)
ProductTrial(http://www.mathworks.com/programs/trials/trial_request.html?
prodcode=FL&eventid=793399040&s_iid=cex_trial_FL_tb)
PricingandLicensing(http://www.mathworks.com/pricinglicensing/?prodcode=FL&s_iid=cex_pl_FL_tb)

You might also like