I think Computer Scientists are so cute when they pretend that they can build robots. Now I'm not knocking all of them, but there's a select group of shall we say unworldly computer scientists who are too far up in the clouds for robotics. Software is of course very necessary for robots but so are electronics and mechanics. Just TRY to build a robot on your own or even work with a pre-made robotic base if you don't understand the first thing about torque vs angular velocity and how it relates to power. Or beat your head against a wall when your robot takes a heading of 3 degrees vs the 0 degrees you told it to. Why DOES it do that? Surprise! Your sensors aren't that accurate even though your numerical precision is.
Anything having to do with kinematics is going to confuse the bejeezus out of someone who isn't familiar with it. True, it's all stuff you learned in physics but the devil is in the details. It took me a good month to really internalize the roles of current and voltage when dealing with motors (in short - current is torque, voltage is speed but it's only this simple at steady state!). And while it's very straightforward to say the reason your car can't turn on a dime at 50mph is momentum, it's a much harder thing to tell me exactly how quickly your car CAN turn at that speed. This is the realm of physicists, mechanical engineers and me - the controls engineer. It's part of my job to do the calculations that tell you how much effort you will expend to turn your car at that speed (and whether it's safe).
So it's no surprise to me that I hear more about what data structures to use for pathfinding, how to make it computationally less complex and whether it always produces the shortest-cost path (all GREAT fodder for computer scientists) than I hear about whether the path is actually something useful. Most discussions I've heard ignore what will actually happen when you attempt to follow that path. For instance - if your GPS has you making 90 degree turns every 5 seconds I don't care how 'least-cost' your path is in terms of the criteria you assigned because it requires too much effort (starting, stopping, slowing, turning, etc). It also certainly won't be the least time intensive path.
The level of 'smoothness' of motion is a concern in controls. Jerky motion requires much more power than nice smooth motion. It's hard to get things to stop and change direction all the time. I once worked with a digital servoamplifier which had several different 'motion profile' modes. I needed to feed it position commands every .1s. So the first mode I tried had it move as fast as possible to the commanded position and then STOP. Then start up again when it got the next command, move as fast as possible and then STOP when it reached the position. That's the first thing you'd try if you had never designed anything like this before and it turns out to be an awful approach. A much better approach was the second motion profile - attempt to arrive at the commanded position but keep moving in the expectation of the next position command.
Now apply this to pathfinding: Are you going to go from Point1 to Point2 then STOP, change direction and go to Point3 (then STOP)? Not ideally. You want a smooth path. You need to take into effect several things: current speed, heading, difficulty of turning, etc. You make a model of your vehicle and compute how difficult it would be to actually execute all of those crazy moves the algorithm things up. So instead of just finding the shortest (distance) path and you weigh the two factors against each other. Just make sure that your weights prevent impossible actions ('Go straight ahead at 50MPH then stop after 50.18 yards and make an instant right turn and immediately resume 50MPH. It'll get ya there in 23 seconds flat. LEAST COST BABY YEAH!'). This will lead to more realistic paths whose costs more accurately affect realistic situations. That's better for everyone.
A quick implementation of this would be to add it to the movement cost in A* (I've heard this called the G score of a square). In the simplest A* algorithm I implemented the movement cost for a 90 degree movment (forward, back, left, right) was always 10, and for a diagonal movement was 14 (sqrt(2)*10 because of the added distance to reach a diagonal square). I would keep track of my current heading in terms of degrees. Assume that the top of the screen is zero and right is 90 degrees, bottom is 180 degrees left is 270 degrees. Heading in this case will be either 0, 45, 90, 135, 180, 225, 270 or 325 degrees. Just add a cost proportional to the change in heading to the G score - this will keep your path from having too many jerky motions. You'll have to fiddle with the weight to balance least cost vs. least effort (you don't want a lazy robot do you?). You can then get more advanced by incorporating speed and momentum into the model. To incorporate speed, allow the pathfinding algorithm to search more than just the squares around it but with a caveat: it's difficult to speed up and slow down. Thus, my normal speed is 1 square/turn - that gets me to the forward, back, left and right squares for a cost of 10 usually. When I want to go to the diagonal squares I have to increase my speed to 14. If I want to go to the forward square two squares ahead of me my speed has to be 20 - I have to speed up. Speeding up takes effort so add to the G score a cost proportional to the absolute value (absolute value because any change in speed requires an effort - you don't gain effort for going from hi speed to low speed) of the difference between my current speed and next speed AND use the speed in the effort cost calculation for turning (higher speeds make turning harder).
Once you start down this path there are many physical parameters you can add to the system. I have yet to implement this but I look forward to some excellent pathfinding in the future!
Wednesday, March 4, 2009
Thursday, February 19, 2009
Process Process Process!
I know I probably won't make any friends with some engineers when I champion process. Many (younger) engineers are free spirits that love to do things their own way. To them each problem is a unique flower that requires a highly-specialized engineering ninja to swoop in, dismember the flower's head, toss it in the air, slice it up and carefully place a decorative plate underneath the pieces as they fall to form an intricate and subtle artistic pattern which he will present to the customer. At least that's his intent. Conversely, a more seasoned engineer will look at the problem and say 'Oh God not THIS again....' and go back to his back of tricks to pull out the Excel spreadsheet or Python script or piece of hardware that solved this problem for him in minutes last time (after taking hours if not days to create in the first place!). The seasoned engineer isn't trying to impress anyone - he's trying to get the job done. Last time he had this problem he DID try to impress someone and ended up hurting himself by taking way too much time to finish - he probably missed a deadline and maybe a large chunk of money by trying to be clever and 'unique'. So he figured out a process to get the job done quicker with fewer missteps. He wants to help the younger engineer by teaching him how the process will help him save time and effort, but what the younger engineer hears is 'Don't be creative! Don't be clever! Fit into this box!'
The truth is we all want to be creative to some degree. It's part of our hierarchy of needs - right at the top. Many people see process as drudgery that inhibits creativity. Who wants to file a bunch of forms to design something? Who wants to document when they could invent? And I agree. I would question the truthfulness or sanity of someone who said they truly enjoyed documenting their latest Lego creation rather than spreading the pieces all over the floor and putting them together. But we have to have a sense of perspective about this. Documentation and process save us from drudgery and boring work. It's not FUN to have code that just won't compile, or a bug you can't track down for the life of you. It's not FUN to build a Simulink model that does nothing other than vibrate itself to pieces. It's frustrating and sometime humiliating. It certainly doesn't help my self-esteem to fail so much.
So when you DO figure out how to make the program compile or the model work, you write it down. You share it with everyone - partly to prove you're smart, but partly so they don't have to go through it like you did. And then when you get a few more good tips you compile them together, format them, codify them, and put them somewhere that everyone can see. You keep track of the resources you used, the rules you followed, the steps you took - all so no one has to go through the same experience you went through: just follow this process and go right from A to F, skipping B-E! Yep, you just created a process, and now some young blood is telling you that you're cramping his style and he's going to do things his own way. Oy.
Folks, process may not be glamorous but it's there to help you! It's there to make sure you don't have to do extra, unnecessary work. It's there to help you get to the fun part more quickly. Trust me - someone who was there before you figured all this out and wants to save you the trouble. Just go with it.
The truth is we all want to be creative to some degree. It's part of our hierarchy of needs - right at the top. Many people see process as drudgery that inhibits creativity. Who wants to file a bunch of forms to design something? Who wants to document when they could invent? And I agree. I would question the truthfulness or sanity of someone who said they truly enjoyed documenting their latest Lego creation rather than spreading the pieces all over the floor and putting them together. But we have to have a sense of perspective about this. Documentation and process save us from drudgery and boring work. It's not FUN to have code that just won't compile, or a bug you can't track down for the life of you. It's not FUN to build a Simulink model that does nothing other than vibrate itself to pieces. It's frustrating and sometime humiliating. It certainly doesn't help my self-esteem to fail so much.
So when you DO figure out how to make the program compile or the model work, you write it down. You share it with everyone - partly to prove you're smart, but partly so they don't have to go through it like you did. And then when you get a few more good tips you compile them together, format them, codify them, and put them somewhere that everyone can see. You keep track of the resources you used, the rules you followed, the steps you took - all so no one has to go through the same experience you went through: just follow this process and go right from A to F, skipping B-E! Yep, you just created a process, and now some young blood is telling you that you're cramping his style and he's going to do things his own way. Oy.
Folks, process may not be glamorous but it's there to help you! It's there to make sure you don't have to do extra, unnecessary work. It's there to help you get to the fun part more quickly. Trust me - someone who was there before you figured all this out and wants to save you the trouble. Just go with it.
Thursday, February 12, 2009
The Dangers of Object-Oriented Programming
In theory I love OOP (Object Oriented Programming) - up to a point. I love having properties. If I want to set one of my discrete I/O ports active then I like to be able to say something like DIO[0].State = Hi. Perfect right? It's at least better than, say: DIO_State[0] = Hi. I think that's a little sloppy.
I'm not so hot on methods. Someone who is might try this: DIO[0].Assert(). Of course you'll also need DIO[0].Decline() (? I'm not fully sure on the opposite of assert at the moment. It's been a long day.) But then you also need something like DIO[0].Tristate() and DIO[0].UnTristate() and DIO[0].Toggle() which start to get a little hairy.
But why do you need those? Oh, that's because you made the State property 'protected' so that people can't set it directly. That's another tenant of OOP - don't let people touch things that they shouldn't. Instead provide 'safe' methods to change properties instead of letting people do it themselves (because they're EVIL! EEEEEVIL! They'd set your properties to invalid values and THEN what would you do?)
And then you go farther! Obviously since you save time when you use objects (another tenant of OOP) you decide to use them everywhere. So you've got relays too, and relays are kinda like DIO right? They go on and off - it's perfect! We'll just extend the DIO type to encompass relays too. So I can Assert() and Decline() relays to close and open them, and I can toggle them and I can Tristate() them... Ummm... wait... Relays don't tristate, do they? But it's a method of the relay object type so maybe they do? I forget...
Ok! Wait! I've got the answer! OOP also has this thing called inheritance where you can define an object type and then create more specific types from it (and from reading the tenants of OOP it seems this is good design practice). So I'll create an object with basic on/off functions and then extend that into DIO which will have tristate functions!
So now we have a parent type that I'll call a, ummm, 'Boolean' object. And Boolean will have a 'Open_Switch' method for the relays and a 'Close_Switch' method.. Or, hmmm. It won't make sense to 'Open_Switch' a DIO port, so we'll just have to call it something more general like 'Frob'. Yeah, 'Frob' will set the DIO high or close a relay and 'UnFrob' will do the opposite. And then 'XFrob' will toggle.
This is really coming together!
Of course that was all in my imagination and I made it worse than it had to be (a little anyhow). But it shows the problem with using OOP which is OVERusing it. Writing methods for toggling and setting a DIO port - sure go ahead. Extending a DIO type to relays? No, too far. Don't get sucked in to using things like inheritance just because it exists. A relay is not a specialized DIO port even if they have a couple of the same functions and properties!
PS - It seems Jeff Atwood agrees with me somewhat.
PPS - And again
Now I know he doesn't perfectly champion every single word in my post but I think we agree on general principles here.
I'm not so hot on methods. Someone who is might try this: DIO[0].Assert(). Of course you'll also need DIO[0].Decline() (? I'm not fully sure on the opposite of assert at the moment. It's been a long day.) But then you also need something like DIO[0].Tristate() and DIO[0].UnTristate() and DIO[0].Toggle() which start to get a little hairy.
But why do you need those? Oh, that's because you made the State property 'protected' so that people can't set it directly. That's another tenant of OOP - don't let people touch things that they shouldn't. Instead provide 'safe' methods to change properties instead of letting people do it themselves (because they're EVIL! EEEEEVIL! They'd set your properties to invalid values and THEN what would you do?)
And then you go farther! Obviously since you save time when you use objects (another tenant of OOP) you decide to use them everywhere. So you've got relays too, and relays are kinda like DIO right? They go on and off - it's perfect! We'll just extend the DIO type to encompass relays too. So I can Assert() and Decline() relays to close and open them, and I can toggle them and I can Tristate() them... Ummm... wait... Relays don't tristate, do they? But it's a method of the relay object type so maybe they do? I forget...
Ok! Wait! I've got the answer! OOP also has this thing called inheritance where you can define an object type and then create more specific types from it (and from reading the tenants of OOP it seems this is good design practice). So I'll create an object with basic on/off functions and then extend that into DIO which will have tristate functions!
So now we have a parent type that I'll call a, ummm, 'Boolean' object. And Boolean will have a 'Open_Switch' method for the relays and a 'Close_Switch' method.. Or, hmmm. It won't make sense to 'Open_Switch' a DIO port, so we'll just have to call it something more general like 'Frob'. Yeah, 'Frob' will set the DIO high or close a relay and 'UnFrob' will do the opposite. And then 'XFrob' will toggle.
This is really coming together!
Of course that was all in my imagination and I made it worse than it had to be (a little anyhow). But it shows the problem with using OOP which is OVERusing it. Writing methods for toggling and setting a DIO port - sure go ahead. Extending a DIO type to relays? No, too far. Don't get sucked in to using things like inheritance just because it exists. A relay is not a specialized DIO port even if they have a couple of the same functions and properties!
PS - It seems Jeff Atwood agrees with me somewhat.
PPS - And again
Now I know he doesn't perfectly champion every single word in my post but I think we agree on general principles here.
Thursday, January 1, 2009
Killer Tip
Well, it's not killer per se. If you've had a bit of experience you probably already do this. I've just started to document what I'm doing with each of my projects so I can start right off the next time I want to work on it (instead of spending a half hour figuring out what the next step is). I just create a file called TODO.txt in the main directory for each of my projects and I update it every time I work on the project saying what I did and what's probably next. Hopefully that will keep me up to date on what I've done.
Now here's the REAL killer tip: automatic timestamp. If you use Notepad++ hit Ctrl+F5 to automatically enter the date/time where the cursor is. And this, THIS is the real killer. It comes from good old Notepad. That's right, Notepad.exe takes the cake for awesome features with this beauty: create a new TXT document and type '.LOG' (no quotes) on the first line. Save it, close it, then reopen it. The date and time is automatically entered right above your cursor. Just start typing.
I can't believe Notepad of all things has such a useful feature. It doesn't even have proper 80 character line wrapping.
(Edit) I've done a little searching and found out that you can also add the timestamp in Notepad by hitting F5. Not nearly as cool though.
Now here's the REAL killer tip: automatic timestamp. If you use Notepad++ hit Ctrl+F5 to automatically enter the date/time where the cursor is. And this, THIS is the real killer. It comes from good old Notepad. That's right, Notepad.exe takes the cake for awesome features with this beauty: create a new TXT document and type '.LOG' (no quotes) on the first line. Save it, close it, then reopen it. The date and time is automatically entered right above your cursor. Just start typing.
I can't believe Notepad of all things has such a useful feature. It doesn't even have proper 80 character line wrapping.
(Edit) I've done a little searching and found out that you can also add the timestamp in Notepad by hitting F5. Not nearly as cool though.
Wednesday, December 31, 2008
More Fuzzy Logic

Ok, so it may have been hard to follow my previous post, especially with no graphics. Well fear not, I just dug up some old materials from my senior project and there is a nice graphical explanation of fuzzy logic. It's a little big because it was meant as my poster for the final competition, but it should be followable.
Monday, December 29, 2008
Fuzzy Logic
We all have our little pet methods that we like to use. I for instance will try to use microprocessors (specifically Atmel or PIC) to solve a problem I encounter. You may use FPGAs or CPLDs. Some crazy people will use .NET and embedded WinCE or somesuch. Everyone has different tools and methods that they are familiar and comfortable with.
One of the tools that I use to solve problems is fuzzy logic. I want to say it's not very well known, at least, I don't get many appreciative nods when I mention it to colleagues. I plan to talk about it as a solution to various problems so it will be useful for you listening (Hello? Anyone out there yet?) if I were to explain it and its use.
Where to start? It might be best to start mathematically. In a mathy sense, fuzzy logic is a method to map m-dimensional input space to n-dimensional output space in a continuous nonlinear fashion. The output may or may not be 'smooth' (ie, differentiable at all valid points in both directions), but my gut feeling is that it is. Don't ask me to prove it, I won't. I'm sure it's proved in some paper somewhere. If math is really your thing then I'm sure this will matter to you, so by all means, look it up.
So what does that mean? Fuzzy logic is basically a function. It can take any number of inputs and produce any number of outputs. The output can depend on one or many of the input variables. So if we have a fuzzy logic function that takes two inputs and produce two outputs: [a,b]=fuzzy(c,d) The inputs and outputs are usually limited to a certain range (If you're mathy, it's called input space and output space. Non-mathy types: you too can feel important and smart by saying things like My fuzzy logic function maps a three-dimensional input space to a two-dimensional output space. And I always drink my tea with my pinky sticking out - I'm distinguished that way.). An input may be limited to values from 0 to 20, and for values outside that range you'd either cut it off to the limit value (ie, 0 or 20 depending on where you go outside the range) or extrapolate somehow. I generally choose to cut the values off. Outputs are also limited as a result of the limitations to the input - since the input space is limited so is the output space.
Now there are all kinds of multi-dimensional nonlinear functions. Usually they're defined something like this:
z=f(x,y)
x varies from 0 to infinity
y varies from 0 to infinity
for x=0 and y=0, z=0
for x>0 and y=0, z=0
for x>0 and y>0, z=x*y
This scheme covers all values, is nonlinear, and if you're careful enough in the definition produces a continuous function. The beauty of fuzzy logic isn't the fact that it IS a nonlinear mapping of multi-dimensional input space to multi-dimensional output space (say THAT five times fast!), but the HOW of how it accomplishes that mapping.
This is where the 'fuzzy' part of fuzzy logic comes in. In the above example we have some logic and it's very precise. Inputs have precise values, EXACT values even. And we have logic: If x IS 1 AND y IS 1 THEN z IS 1. What if I don't want to be so exact? What if I want to say IF x is BIG and y is SMALL THEN z IS MEDIUM?
You might be asking yourself 'Why would I want to create a function to express such a concept?' If you're starting off from a mathy 'multi-dimensional input space' type of position then you probably don't see the need for such a statement, or a means to evaluate it. If you're mathy then you like numbers and variables and ranges - oh my! But if you're an actual person (the jury is still out on whether mathy 'people' are actually human) then fuzzy logic is for you. Take the example of tipping at a restaurant.
At a restaurant you usually have to give a tip which is some percentage of your total bill. I evaluate this percentage based on the level of service I receive and the quality of the food. We'll score them both based on a ten-point scale with 0 being the worst, 10 the best. I will generally tip between 0 and 33% of a bill. Let's functionize that:
0 < Tip% < .33
0 < Food < 10
0 < Service < 10
Tip% = f(Service,Food)
Ok, so how much should I tip? Fuzzy logic has the answer.
The first step in fuzzy logic is to 'fuzzify' the inputs. We do this with what are called 'input membership functions'. That's just a mathy way of expressing a concept like: '0 is definitely (100%) awful service while 2.5 is definitely not (0%). All values in between that vary linearly'. If you graph it, that would be a triangle with your peak at the 'definitely' point and then a straight line drawn to your 'definitely not point/points' Since 'awful service' was at the low end of our range for service it only has one 'definitely not' point. For 'OK' service we might place the peak at 5 and the low points at 10 and 0. It will be a triangle that spans the whole range with its peak at 5.
For both Service and Food we'll define 'Awful','OK', and 'Great' levels. Awful peaks at 0 and bottoms out at 5, OK peaks at 5 and bottoms out at 0 and 10, and Great peaks at 10 and bottoms out at 5. Now for any numeric input value from 0 to 10 we can describe how accurately the service is 'Awful', 'OK', and 'Great'. For instance:
Service = 5
0 = Awful(Service) %The service is not at all Awful
1 = OK(Service) %The service is definitely OK
0 = Great(Service) %The service is not at all Great
Service = 7.5
0 = Awful(Service) %The service is not at all awful
.5 = OK(Service) %The service is somewhat OK
.5 = Great(Service)%The service is somewhat Great
It is worth noting that these membership functions don't have to look like triangles - they can look like squares or gaussian functions or trapezoids. The complexity of the calculations to determine value of the membership function increases, but not the general idea.
Now that we know to what extent the level of Service or Food matches our descriptions (Awful,OK,Great), we can create the output with rules. This requires output membership functions. These work pretty much like the input membership functions but in reverse. Each output membership function has an output number associated with it as well as the degree to which it is asserted. For tipping I'll say that the tip is 'Small' if it's 0%, it's 'Normal' if it's 16.5% and it's 'Big' if it's 33%. These membership functions also have shapes associated with them but for an expedited example it only matters where their nominal output values (or center points if you're thinking with shapes) are on the output axis. The output number is determined by doing a weighted sum of each nominal output value times the degree to which it is asserted. Thus we can say that the tip should be 33% Low, 50% Normal and 75% Big, and if we do a weighted sum we get:
0*.33+16.5*.5+.75*33 = ~8.5% tip (roughly)
So once we know how much each output membership function is 'asserted' we can tell how much we should tip. How do we tell how much each output membership function is asserted?
That's where rules come in. To determine the level of assertion we make rules that read like:
1) IF SERVICE IS GOOD AND FOOD IS GOOD THEN TIP IS NORMAL
2) IF SERVICE IS BAD AND FOOD IS GOOD THEN TIP IS NORMAL
3) IF SERVICE IS GREAT AND FOOD IS BAD THEN TIP IS LOW
etc...
You'd probably make a lot of these rules for a tipping system, and depending on how much you value food versus service your rules would be different than everyone elses. So in the above example if the degree to which the Service is Good is .5, and the degree to which Food is Good, how do we evaluate the AND? There are several ways. You can multiply the two .5's and get .25 for the level of the tip being Normal or we could choose the maximum of the two values. There are other ways, but it has to make some sense. You can also have OR's as logical operations (the OR operation is usually a minimum of the two) and NOT (usually 1-value). How the operations are evaluated changes based on the type of system you are putting together, so don't be too shy about the 'right' way. My AND's are usually the product and my OR's are usually minimum.
So using these operations you assign some weight to each output (Normal, Big, Low). As seen above, multiple rules produce weight for Normal. When this happens, you either add all of the weights together or select the highest. When you've gone through each rule you'll have a weight for each output:
Low = 0
Normal = .5
High = .5
Then you go back two steps above and perform the weighted average of the output values. In this case you'd get:
0*0+.5*16.5+.5*33 = 24.75% tip
That must have been some good service (or maybe food)!
So, if you've followed me this far, you can see that fuzzy logic excels at creating nonlinear multidimensional functions in a way that humans can relate to (ie, in a way that matches our decision-making process). It produces real number outputs from real-number inputs, and it has a firm mathematical basis (that you can look up if you want, I'm satisfied that it works). I hope you can see all of the potential uses for this, because my hands are getting tired from typing so I'm signing off. Tune in later for some practical controls-related uses of fuzzy logic.
One of the tools that I use to solve problems is fuzzy logic. I want to say it's not very well known, at least, I don't get many appreciative nods when I mention it to colleagues. I plan to talk about it as a solution to various problems so it will be useful for you listening (Hello? Anyone out there yet?) if I were to explain it and its use.
Where to start? It might be best to start mathematically. In a mathy sense, fuzzy logic is a method to map m-dimensional input space to n-dimensional output space in a continuous nonlinear fashion. The output may or may not be 'smooth' (ie, differentiable at all valid points in both directions), but my gut feeling is that it is. Don't ask me to prove it, I won't. I'm sure it's proved in some paper somewhere. If math is really your thing then I'm sure this will matter to you, so by all means, look it up.
So what does that mean? Fuzzy logic is basically a function. It can take any number of inputs and produce any number of outputs. The output can depend on one or many of the input variables. So if we have a fuzzy logic function that takes two inputs and produce two outputs: [a,b]=fuzzy(c,d) The inputs and outputs are usually limited to a certain range (If you're mathy, it's called input space and output space. Non-mathy types: you too can feel important and smart by saying things like My fuzzy logic function maps a three-dimensional input space to a two-dimensional output space. And I always drink my tea with my pinky sticking out - I'm distinguished that way.). An input may be limited to values from 0 to 20, and for values outside that range you'd either cut it off to the limit value (ie, 0 or 20 depending on where you go outside the range) or extrapolate somehow. I generally choose to cut the values off. Outputs are also limited as a result of the limitations to the input - since the input space is limited so is the output space.
Now there are all kinds of multi-dimensional nonlinear functions. Usually they're defined something like this:
z=f(x,y)
x varies from 0 to infinity
y varies from 0 to infinity
for x=0 and y=0, z=0
for x>0 and y=0, z=0
for x>0 and y>0, z=x*y
This scheme covers all values, is nonlinear, and if you're careful enough in the definition produces a continuous function. The beauty of fuzzy logic isn't the fact that it IS a nonlinear mapping of multi-dimensional input space to multi-dimensional output space (say THAT five times fast!), but the HOW of how it accomplishes that mapping.
This is where the 'fuzzy' part of fuzzy logic comes in. In the above example we have some logic and it's very precise. Inputs have precise values, EXACT values even. And we have logic: If x IS 1 AND y IS 1 THEN z IS 1. What if I don't want to be so exact? What if I want to say IF x is BIG and y is SMALL THEN z IS MEDIUM?
You might be asking yourself 'Why would I want to create a function to express such a concept?' If you're starting off from a mathy 'multi-dimensional input space' type of position then you probably don't see the need for such a statement, or a means to evaluate it. If you're mathy then you like numbers and variables and ranges - oh my! But if you're an actual person (the jury is still out on whether mathy 'people' are actually human) then fuzzy logic is for you. Take the example of tipping at a restaurant.
At a restaurant you usually have to give a tip which is some percentage of your total bill. I evaluate this percentage based on the level of service I receive and the quality of the food. We'll score them both based on a ten-point scale with 0 being the worst, 10 the best. I will generally tip between 0 and 33% of a bill. Let's functionize that:
0 < Tip% < .33
0 < Food < 10
0 < Service < 10
Tip% = f(Service,Food)
Ok, so how much should I tip? Fuzzy logic has the answer.
The first step in fuzzy logic is to 'fuzzify' the inputs. We do this with what are called 'input membership functions'. That's just a mathy way of expressing a concept like: '0 is definitely (100%) awful service while 2.5 is definitely not (0%). All values in between that vary linearly'. If you graph it, that would be a triangle with your peak at the 'definitely' point and then a straight line drawn to your 'definitely not point/points' Since 'awful service' was at the low end of our range for service it only has one 'definitely not' point. For 'OK' service we might place the peak at 5 and the low points at 10 and 0. It will be a triangle that spans the whole range with its peak at 5.
For both Service and Food we'll define 'Awful','OK', and 'Great' levels. Awful peaks at 0 and bottoms out at 5, OK peaks at 5 and bottoms out at 0 and 10, and Great peaks at 10 and bottoms out at 5. Now for any numeric input value from 0 to 10 we can describe how accurately the service is 'Awful', 'OK', and 'Great'. For instance:
Service = 5
0 = Awful(Service) %The service is not at all Awful
1 = OK(Service) %The service is definitely OK
0 = Great(Service) %The service is not at all Great
Service = 7.5
0 = Awful(Service) %The service is not at all awful
.5 = OK(Service) %The service is somewhat OK
.5 = Great(Service)%The service is somewhat Great
It is worth noting that these membership functions don't have to look like triangles - they can look like squares or gaussian functions or trapezoids. The complexity of the calculations to determine value of the membership function increases, but not the general idea.
Now that we know to what extent the level of Service or Food matches our descriptions (Awful,OK,Great), we can create the output with rules. This requires output membership functions. These work pretty much like the input membership functions but in reverse. Each output membership function has an output number associated with it as well as the degree to which it is asserted. For tipping I'll say that the tip is 'Small' if it's 0%, it's 'Normal' if it's 16.5% and it's 'Big' if it's 33%. These membership functions also have shapes associated with them but for an expedited example it only matters where their nominal output values (or center points if you're thinking with shapes) are on the output axis. The output number is determined by doing a weighted sum of each nominal output value times the degree to which it is asserted. Thus we can say that the tip should be 33% Low, 50% Normal and 75% Big, and if we do a weighted sum we get:
0*.33+16.5*.5+.75*33 = ~8.5% tip (roughly)
So once we know how much each output membership function is 'asserted' we can tell how much we should tip. How do we tell how much each output membership function is asserted?
That's where rules come in. To determine the level of assertion we make rules that read like:
1) IF SERVICE IS GOOD AND FOOD IS GOOD THEN TIP IS NORMAL
2) IF SERVICE IS BAD AND FOOD IS GOOD THEN TIP IS NORMAL
3) IF SERVICE IS GREAT AND FOOD IS BAD THEN TIP IS LOW
etc...
You'd probably make a lot of these rules for a tipping system, and depending on how much you value food versus service your rules would be different than everyone elses. So in the above example if the degree to which the Service is Good is .5, and the degree to which Food is Good, how do we evaluate the AND? There are several ways. You can multiply the two .5's and get .25 for the level of the tip being Normal or we could choose the maximum of the two values. There are other ways, but it has to make some sense. You can also have OR's as logical operations (the OR operation is usually a minimum of the two) and NOT (usually 1-value). How the operations are evaluated changes based on the type of system you are putting together, so don't be too shy about the 'right' way. My AND's are usually the product and my OR's are usually minimum.
So using these operations you assign some weight to each output (Normal, Big, Low). As seen above, multiple rules produce weight for Normal. When this happens, you either add all of the weights together or select the highest. When you've gone through each rule you'll have a weight for each output:
Low = 0
Normal = .5
High = .5
Then you go back two steps above and perform the weighted average of the output values. In this case you'd get:
0*0+.5*16.5+.5*33 = 24.75% tip
That must have been some good service (or maybe food)!
So, if you've followed me this far, you can see that fuzzy logic excels at creating nonlinear multidimensional functions in a way that humans can relate to (ie, in a way that matches our decision-making process). It produces real number outputs from real-number inputs, and it has a firm mathematical basis (that you can look up if you want, I'm satisfied that it works). I hope you can see all of the potential uses for this, because my hands are getting tired from typing so I'm signing off. Tune in later for some practical controls-related uses of fuzzy logic.
Sunday, December 28, 2008
Timekeeping Cont'd
As the idea has been rolling around in my head I've thought up some logical extensions. Both timekeeping units - master and slave - could be implemented in programmable logic, probably a CPLD. The slaves could have an internal delay oscillator (several inverters in a row) which would be the basis of measurement of the incoming clock signal. The slaves could also do clock doubling or tripling of the incoming clock signal to provide a fast clock to whatever programmable logic or microcontroller is their client. That would be accomplished by use of the internal timer/counter in the timekeeping slave unit - determine how many ticks the external period is in your internal clock, then divide by 2,4,8,16, whatever and get a faster clock that OUGHT to be fairly correct compared to the incoming clock signal. The unit could also provide the bare external clock signal (suitably buffered) for use with an RTC timer/counter on the client device.
I was also thinking that due to all of that transmission line stuff that I try to ignore it might be better to transmit the clock signal as a sine wave. Doing that with programmable logic would be harder, but it might be required in certain circumstances. Certainly a differential signal is probably necessary in most environments. I would say that repeaters might be necessary, but repeaters will introduce delay. It might not be too much but it wouldn't be consistent. You may hook one slave up after a single repeater, and hook another up after 10 repeaters, and the signal will be more delay for the second slave.
I'm beginning to wonder if this is patentable. In my miniscule experience (<2 years in the controls field) I haven't seen anyone use this system, nor have I seen anyone attempt to synchronize different subsystems to this degree. Usually if you want everything to be on the same clock you put it in the same unit - programmable logic, microcontroller, whatever. For hard real time applications that's pretty necessary. The question is whether people have thought of this but ignored it, not thought of it, or not thought it practical?
I was also thinking that due to all of that transmission line stuff that I try to ignore it might be better to transmit the clock signal as a sine wave. Doing that with programmable logic would be harder, but it might be required in certain circumstances. Certainly a differential signal is probably necessary in most environments. I would say that repeaters might be necessary, but repeaters will introduce delay. It might not be too much but it wouldn't be consistent. You may hook one slave up after a single repeater, and hook another up after 10 repeaters, and the signal will be more delay for the second slave.
I'm beginning to wonder if this is patentable. In my miniscule experience (<2 years in the controls field) I haven't seen anyone use this system, nor have I seen anyone attempt to synchronize different subsystems to this degree. Usually if you want everything to be on the same clock you put it in the same unit - programmable logic, microcontroller, whatever. For hard real time applications that's pretty necessary. The question is whether people have thought of this but ignored it, not thought of it, or not thought it practical?
Subscribe to:
Posts (Atom)