6 ms·
How can one manage thousands of IF…THEN…ELSE rules?
- tylermauthe 14y agoSuch a great answer. This is why I love Stack Exchange.
- deleted 14y ago[deleted]
- psingh 14y agoagree.
- ynniv 14y agoIf only these questions appeared on one's résumé...
- sliverstorm 14y agoWhat, are you insinuating that asking about great big if-then-else trees means you'd never hire that person? Because, what, you've never been a complete novice programmer before? Considering the question-asker has a specific problem to solve, I would even hazard they probably aren't a programmer by trade.
- jimbobimbo 14y agoI'd say the fact that person is asking this question is a very good sign - they have a gut feeling that something's off with IF-THEN spaghetti.
- ynniv 14y ago... a very good sign that they're still too green. When did HN become so touchy-freely? It's important that people start learning somewhere. If you show any interest in programming, I highly recommend learning more. However, there comes a time when you must have a certain amount of experience. This is a profession where important things are made. Even people who should know better end up building systems that leak our sensitive personal information, or let others impersonate us. I didn't say that such a person shouldn't be hired, but I certainly implied that the original question is a better indicator of their capability than the always positive keyword soup and "years experience" that many people slather on their résumé. If "avoiding IF-THEN spaghetti" is all you require from contributors, fine. Let's not pretend that this is better than an early high school effort.
- ynniv 14y agoConsidering the question-asker has a specific problem to solve, I would even hazard they probably aren't a programmer by trade. So why would someone hire them to be a programmer? And yet, unlike other skilled professions, rank amateurs often present themselves as competent programmers. It would be valuable to include evidence to the contrary with résumés. you've never been a complete novice programmer before? I certainly wasn't hired when I was. What kind of ridiculous statement is this? The poster is asking the wrong question. They are asking about how to manage incidental complexity, when they should be asking how to avoid inherent complexity. Incidentally complex code is the worst possible code to maintain, and you'll thank yourself for not letting contributors commit it.
- jetti 14y agoSo you rather hire somebody who has the same problem but has too much pride to ask somebody for help? Seriously, if all the questions everybody asked ever were on their resume, nobody would ever be able to get a job. At least this individual recognized that there was something wrong and sought out how to fix the problem from people with more experience then them.
- ynniv 14y agoMeh, put a date on it. If you asked this even a couple of years ago, fine. If you asked this last month, I have a pretty good feel for where you're at. You should also learn from your questions, which would make a great interview conversation. I've littered the net with my share of dumb questions, and I have no regrets.
- jlgreco 14y agoThe idea of things on resumes shouldn't be to make hire/no-hire decisions (well, unless your job is to bin all the incoming resumes written in crayon..). Talking about this situation during an interview may provide insight though.
- Dn_Ab 14y agoSuch a great question. Want to predict cow movement while taking into consideration sudden events, food and sun, using thousands of if then rules? Sounds like the perfect problem for one of the following tree learners that not only manage themselves but build the model for you, in order of suitability to the problem* : Genetic Programming ADTree Random Forest Decision Tree Most of the work would be in figuring out the best way to gather all the data. *opinion.
- bicknergseng 14y agoI also thought GP and decision trees. Trying to hard code all the logic of a living being by hand is programmatic masturbation and also not the best way to model an artificial intelligence.
- SeanLuke 14y agoAll machine learning techniques build models for you. ADTrees, Random Forests, and Decision trees are all classifiers, so they serve this guy's needs. Genetic Programming is not a machine learning technique: it is an optimization method for a very specific task and is quite unsuited for his purposes.
- femngi 14y agoCan you explain you think Genetic Programming is unsuitable? I honestly can't see why you think it wouldn't work.
- StavrosK 14y agoAs SeanLuke said, genetic programming is an optimization method. I don't see a function being optimized here, so what would you run it on?
- Retric 14y agoIf you had samples of cow behavior such as videos, you could then simulate behavior at each step and optimize for a genetic algorithm that produces similar behaviors. In this case it's probably not the right solution, but it's not that hard to swap out different learning algorithms when things don't seem to jell.
- deleted 14y ago[deleted]
- lutusp 14y agoYou really don't want to think of this in terms of IF ... THEN ... ELSE but as individual binary or multi-path choices. These are most efficiently handled with hash tables that choose a route through a logic diagram in a way that is more intuitive than If ... THEN ... ELSE as well as more efficient. You start by writing a logic flowchart that you understand, then you reduce the logic flowchart to code, usually automatically. This is how a logic flowchart looks: http://en.wikipedia.org/wiki/File:LampFlowchart.svg http://en.wikipedia.org/wiki/File:LampFlowchart.svg Here is the article it appears in: http://en.wikipedia.org/wiki/Flowchart http://en.wikipedia.org/wiki/Flowchart The single most important parts of this process are: 1. That you understand the logic diagram and see that it meets the program's requirements. 2. That there is a way to turn the logic flowchart into code, ideally without human intervention. 3. That the rebuild time be short between adding a new logical step and testing the resulting program.
- JoeAltmaier 14y agoMaybe I'm off the mark, but whenever I see a long runon procedure full of if-then-else, I think "This is a job for a state machine!" With that approach, you can exhaustively provide actions for every combination of states and events. You can also immediately identify the code responsible for handling any state+event. You can also track which state+event transitions have been tested automatically.
- prunebeads 14y agoYou're not, imho. The problem is : how do we manage the data associated with the structure of this gigantic state-machine. It is likely to change overtime, so it cannot be hard coded (although if it were, one could perhaps use a tool which compiles the state machine to hard code). Basically, many of the solutions proposed are more or less specialized state machines (decision trees, markov chains, rete algorithm).
- lutusp 14y ago> Maybe I'm off the mark, but whenever I see a long runon procedure full of if-then-else, I think "This is a job for a state machine!" I'm a big fan of state machines, but systems like this are often multitasking and (for all practical purposes) stateless. OTOH it might be more accurate to say their state is formally unpredictable. A system like the one being described would be more like a multi-threaded critical-path flowchart, where multiple processes are active at a given time. And at any time a high-level linear programming result might mandate a change of strategy based on available resources, even though individual processes continued to follow the tactical flowchart. So even though a state machine approach looks attractive (as it always does), it's a matter of deciding how many states and how many levels. Because of the nature of the original problem and the number of connections with everyday reality, the fact that it was a state machine might escape the attention of even a careful observer.
- wickedchicken 14y agoMildly unrelated, but I wanted to point out the awesomeness of the K-map[1] for handling simple minimization problems like these. Unfortunately, once your dimensions get large it becomes difficult for humans to visualize the optimizations, which is where Espresso[2][3] comes in handy. [1] http://en.wikipedia.org/wiki/Karnaugh_map http://en.wikipedia.org/wiki/Karnaugh_map [2] http://embedded.eecs.berkeley.edu/pubs/downloads/espresso/index.htm http://embedded.eecs.berkeley.edu/pubs/downloads/espresso/in... [3] ftp://ftp.cs.man.ac.uk/pub/amulet/balsa/other-software/espresso-ab-1.0.tar.gz
- theatrus2 14y ago+1 to espresso. Too bad there aren't any "native" bindings in many languages, but in many cases piping it through stdin/stdout works well enough.
- pjscott 14y agoOoh, espresso. There was also a tool called eqntott for converting boolean logic expressions in a human-readable form into the truth tables that Espresso takes as input. The source code was written in an archaic dialect of C, but here's a resurrected version that should compile on modern compilers: http://code.google.com/p/eqntott/ http://code.google.com/p/eqntott/ I haven't touched this code since 2008, so beware of grues, but I remember it being a really slick system for minimizing boolean logic when you combine eqntott with espresso. Just the thing for an electrical engineering student who's sick of doing K-maps, which described me nicely at the time.
- wickedchicken 14y ago"This program was originally written at Berkeley in the early 80s" This phrase gives me the same feeling I'd get from finding an old Thomas Bangalter track or something.
- anamax 14y agoTrivia - some core parts of espresso are/were part of specmarks, which are used to evaluate computer designs and implementations.
- JustLikeThat 14y agoMy favorite part is the third comment in on the question: "How can one manage thousands of IF…THEN…ELSE rules? By developing a drinking problem"
- indiecore 14y agoThat solution is generalizable to the entire domain of computer science.
- joe_the_user 14y agoEven with the clue that he wants to "predict how cows move around in any landscape", his description seems like it wouldn't be enough any definite design advice. What do the states of the cows and the landscape look like? What is changed by the if-then-else results. Does he already have his rules? Is this for a biology project or a video game, etc. You could use a finite automaton system, an array of cow-states, a cow DSL or something else depending on the answers to these and other questions. [insert joke about "till the cows come home"]
- ShabbyDoo 14y agoYes. The piece missing for me in most answers I've seen is eventing. Does one pump a series of events/state changes into the CowModel and see what actions pop-out? Does the model involve interactions with other cows where the actions of one cow cause actions of others? If so, one must have an event queue to handle chain reactions. How discrete are the events? Is there a "temp is 89F" event where, for every N minutes the cow is in that temperature in direct exposure, it becomes more likely to seek shade? If so, the "it is 89F" event must be triggered multiple times. And, such a rule requires that the past states of the cow be retained. I think the if/then/else logic is only part of the solution to a simulation problem of this sort.
- instakill 14y agoThe question is an interesting one but it's futile in its context. You can't build a prediction engine for cattle movement. Adding factors like weather, food etc. seems well and dandy but there's hundreds if not thousands of other factors that are definitely going to be missing and that will render the prediction events pointless. Never mind the fact that you can throw in black swan type of events into the mix or just unknown unknowns you could never think of (maybe a cow has a frog phobia and panics when it sees the frog and starts a stampede or whatever it is that cattle do).
- Evbn 14y agoYeah, it is as silly as trying to predict the weather.
- mmcnickle 14y agoYou can't predict how an individual cow will move, but it's perfectly acceptable to use models to predict how cattle generally move. Similar to the way we use models to predict how humans navigate hallways and find paths across grass.[1] When you have a bulk of interacting particles, it tends to remove the "personality" of the individual, leaving you with how the group as a whole will move. Philip Ball's (former editor of Nature) book Critical Mass[2] is an excellent read about the interesting effects that happen when you look at large number of complex interacting actors. He discusses the effects in traffic, pedestrian models, finance, plant growth etc. I highly recommend it. [1]http://www.youtube.com/watch?v=8SmRBTJ-jeU http://www.youtube.com/watch?v=8SmRBTJ-jeU This is just a video I picked out quickly, there are much better resources, I just can't find them on my phone. [2]http://www.amazon.co.uk/Critical-Mass-Thing-Leads-Another/dp/0099457865/ http://www.amazon.co.uk/Critical-Mass-Thing-Leads-Another/dp...
- _delirium 14y agoWhile I'm not sure thousands of if/then/else rules are actually the best knowledge representation for his domain (it sounds like he really wants to learn some model from data, in which case throwing some off-the-shelf machine learning may be a better fit), the area of "expert systems" may be relevant if they really are rules extracted directly from some source that need to be managed, such as a human domain expert. Expert systems were particularly big in AI in the '80s, and considerably less hot now, but still widely used in industry. There are a lot of issues that come up, most of which aren't really purely technical, such as: 1) how you extract knowledge from people who might know it; and 2) how you validate that the knowledge you've extracted is actually what they know, for example by validating that it produces the same decisions that they would make; and 3) how you allow updates/revisions to the knowledge base over time. Once you have the rules and some reason to believe that they're any good, actually managing and applying them can be done through one of several rule engines, such as Drools or Jess. The keyword "knowledge engineering" may also turn up relevant info.
- Dn_Ab 14y agoI don't think thousands should be taken literally. I don't think he has actually built it yet - I sort of saw it as an optimistic estimate =)
- ck2 14y agoIs it just me? It's not a good question, it shows lack of core coding experience. For example a video game consists of millions of possibilities/results in movement based on environment - it's not approached as a collection of thousands of if/then/else statements. In fact the movement of cows seems very much like video game coding, it needs a "cow engine".
- bowmessage 14y agoTotally agreed -- that's the first thing I thought while reading the question. OOP made this kind of problem easy to tackle long ago.
- Dn_Ab 14y agoLast I checked (been a couple years now) Hierarchical Finite State Machines and Behaviour Trees were big for that sort of thing.
- toddmorey 14y agoI think it was a really good question. It showed that he had the intuitive instinct that there had to be a better way. He just didn't know how to ask for a "cow engine" by name.
- ck2 14y agoI am not so certain. Note their question is not if there is another way - they are asking how to manage all the statements they are planning to write. Imagine being given a problem such as "add any two given integers but do not use math operators". A person without anything but if/then/else knowledge would proceed to try to write if (a==1 && b==2) c==3 and repeat it for every variation until they gave up. Someone with more core experience and coding instinct would immediately recognize there must be away to set patterns for 0-9 and then analyze each decimal place, apply a matrix, or a number of other approaches.
- dave_sullivan 14y agoThis really sounds like a machine learning problem--why hand engineer all these rules yourself (which can be error prone in any case) when a program could do it for you? If you can figure out how to get a large data set together and come up with a good general representation of the data, you're half way there. I'd consider taking a look at recurrent neural networks if you're looking at your data as a time series or if its more of a static problem that doesn't take into account the last N things that came before, you might consider tree based methods or even DBNs if you can get a lot of data together (say 50000-100000 samples) Potential pitfall: if you're using a NN based approach, you will judge results based on test performance, but you won't get as much insight into the "rules" your network has learned.
- gavanwoolery 14y agoA finite state machine is actually not a great solution for this particular problem (in fact, FSMs are often over-used), IMHO. An expert system is a far better solution (as one commenter mentioned). The problem with a FSM is that you still must explicitly specify ALL of the nodes (without some complex algorithm to automate such a task). An expert system, like prolog, only requires you to state all of the rules, and then it will figure out any query for you (via propositional logic, backwards chaining, etc). The number of nodes typically grows exponentially with the number of rules (if the rules are inter-related), so for a problem of any significant size an expert system would probably be the method of choice.
- Swizec 14y agoWouldn't this best be handled by something like a decision tree? http://en.wikipedia.org/wiki/Decision_tree http://en.wikipedia.org/wiki/Decision_tree It's basically thousands of if-this-then-that statements, but dressed up into something you can reason about and most importantly train and build automagically.
- yabadab 14y agoThis problem smells like one that should be tackled with a supervised ML approach. Even something as simple as a Decision Tree might be enough?
- kos_mos 14y agoof course this is a machine learning problem.
- mark_l_watson 14y agoI am late to this discussion, but I would like to ad my experiences with compiling rules to a Rete network. I have done a lot of hacking on the old Lisp OPS5 code and found it easy to work with, once you read and understood Charles Forgy's papers. I hacked OPS5 to support multiple data worlds and a few other enhancements for specific projects. The more modern Rete based software projects are probably also easy to work with.
- xarien 14y agoMan, I must be getting old, first thing I thought of when I saw the question was a FSM implemented with function pointers in C.
- tlogan 14y agoProlog.
- sandGorgon 14y agoI have an axiom "any sufficiently complex if-then-else ruleset can be modeled as a search problem with boosts". I have modeled a logistics lookup system (assign "best" courier for an ecommerce setup) using a search solution. The rules were modeled as documents in a search index and looked up using weights. Fundamentally, what I did was flatten an if-then-else hierarchy and assign weights based on (roughly) level of nesting. The con of this model is obvious - it is at best a heuristic. However, with clever overrides built in (as a separate search index?), you can get pretty close to the ideal solution. The pro of this model is scalability - when your rules are in millions, this system scales beautifully.
- exDM69 14y agoI suggested using Prolog in the comments. His problem description was not quite good enough for me to assess whether or not Prolog will be a good choice, but at least it's a candidate. A Prolog program is essentially a list of rules that are written as an implication. Something like: moves_to(Cow, Location) :- hungry(Cow), current_location(Cow, OldLoc), food_in(OldLoc, OldFood), food_in(Location, Food), Food > OldFood. In human language: a cow moves to a location if it's hungry and there's more food in that location than in current location. I should probably write a proper answer. edit: Added a proper answer to the stackoverflow with an almost complete introductory Prolog example. It's waiting for your upvotes :)
- cartosys 14y agoAnd we're waiting for a link.
- exDM69 14y agoThere you go: http://programmers.stackexchange.com/a/165126/65434 http://programmers.stackexchange.com/a/165126/65434
- bumbledraven 14y agoGood answer. Nice to see the original questioner accepted it. To take it a bit further, so-called "answer set solvers" like clasp (http://potassco.sourceforge.net/ http://potassco.sourceforge.net/) provide a fast way to run these kinds of logic programs.