Drools recursive rules 2013

View previous topic View next topic Go down

Drools recursive rules 2013

Post by Admin on Sun Sep 15, 2013 4:01 am

2013 2013 2013 <div dir="ltr" style="text-align: left;" trbidi="on">The most common example of recursion is a Fibonacci series. In drools, the implementation is done using the insert and modify keywords.</br>There are three most important parts in this implementation, one is insert keyword that is used in then part and other is not keyword that gets used in when part to satisify the breaking condition. As in Fibnocci series example, the breaking condition would be {sequence == 1} Consider below class and DRL file : </br></br><u><b>Fibonacci.java</b></u></br><pre style="font-family:arial;font-size:12px;border:1px solid #CCCCCC;width:99%;height:auto;overflow:auto;background:#f0f0f0;;;padding:0px;color:#000000;text-align:left;line-height:20px;"><code style="color:#000000;word-wrap:normal;">package com.recursion;<br /><br />public class Fibonacci {<br /><br /> private int sequence;<br /> private long value;<br /><br /> public Fibonacci(final int sequence) {<br /> this.sequence = sequence;<br /> this.value = -1;<br /> }<br /><br /> public int getSequence() {<br /> return sequence;<br /> }<br /><br /> public void setSequence(int sequence) {<br /> this.sequence = sequence;<br /> }<br /><br /> public long getValue() {<br /> return value;<br /> }<br /><br /> public void setValue(long value) {<br /> this.value = value;<br /> }<br /><br />}<br /></code></pre> <u><b>TestRecursion.java</b></u></br><pre style="font-family:arial;font-size:12px;border:1px solid #CCCCCC;width:99%;height:auto;overflow:auto;background:#f0f0f0;;;padding:0px;color:#000000;text-align:left;line-height:20px;"><code style="color:#000000;word-wrap:normal;">public class TestRecursion {<br /><br /> public static final void main(String[] args) {<br /> try {<br /> // load up the knowledge base<br /><br /> KnowledgeBase kbase = readKnowledgeBase();<br /> StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();<br /> KnowledgeRuntimeLogger logger = KnowledgeRuntimeLoggerFactory.newFileLogger(ksession, "test");<br /><br /> ksession.insert(new Fibonacci(10));<br /> ksession.fireAllRules();<br /><br /> ksession.dispose();<br /> logger.close();<br /> } catch (Throwable t) {<br /> t.printStackTrace();<br /> }<br /> }<br /><br /> private static KnowledgeBase readKnowledgeBase() throws Exception {<br /> KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();<br /> kbuilder.add(ResourceFactory.newClassPathResource("Fibonacci.drl"), ResourceType.DRL);<br /> KnowledgeBuilderErrors errors = kbuilder.getErrors();<br /> if (errors.size() > 0) {<br /> for (KnowledgeBuilderError error : errors) {<br /> System.err.println(error);<br /> }<br /> throw new IllegalArgumentException("Could not parse knowledge.");<br /> }<br /> KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();<br /> kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());<br /> return kbase;<br /> }<br />}</code></pre> The implementation in terms of rules in drl file has three rules as shown below: </br> <u><b>Recurse rule</b></u>: This rule checks if the sequence is not reached to 1 and value is -1 then insert new Fibonacci class object with sequence value one less than previous object. The salience of this rule is highest, because all Fibnocci class object need to be inserted into working memory before calculation the value field of the class. The not conditional element is used to stop the rule's matching once we have all 50 Fibonacci objects in memory. </br><pre style="font-family:arial;font-size:12px;border:1px solid #CCCCCC;width:99%;height:auto;overflow:auto;background:#f0f0f0;;;padding:0px;color:#000000;text-align:left;line-height:20px;"><code style="color:#000000;word-wrap:normal;">rule "Recurse"<br /> salience 10<br /> when<br /> f : Fibonacci ( value == -1 )<br /> not ( Fibonacci ( sequence == 1 ) )<br /> then<br /> insert( new Fibonacci( f.getSequence() - 1 ) );<br /> System.out.println( "recurse for " + f.getSequence() + "--" + f.getValue());<br />end</code></pre> <u><b>Bootstrap rule</b></u>: Fibonacci series for 1 is 1 and for 2 is 1, 1. This rule gets activated for 2 Fibonacci class object that were inserted in the working memory in the earlier rule.</br>For Fibonacci object, sequence == 1 & </br>For Fibonacci object, sequence == 2 </br>So when the sequence == 1 or sequence == 2, we need to update the value field in Fibonacci series to 1 as done below.</br><pre style="font-family:arial;font-size:12px;border:1px solid #CCCCCC;width:99%;height:auto;overflow:auto;background:#f0f0f0;;;padding:0px;color:#000000;text-align:left;line-height:20px;"><code style="color:#000000;word-wrap:normal;">rule "Bootstrap"<br />dialect "mvel"<br /> when<br /> f : Fibonacci( sequence == 1 || == 2, value == -1 ) // multi-restriction<br /> then <br /> modify ( f ){ value = 1 };<br /> System.out.println( f.getSequence() + " == " + f.getValue() );<br />end</code></pre> <u><b>Calculate rule</b></u>: For the remaining 48 objects in the working memory where sequence > 2, below rule gets activated.</br>The "Calculate" rule uses field constraints to correctly constraint the thee Fibonacci patterns in the correct order; this technique is called cross product matching. The first pattern finds any Fibonacci with a value != -1 and binds both the pattern and the field. The second Fibonacci does this, too, but it adds an additional field constraint to ensure that its sequence is greater by one than the Fibonacci bound to f1. When this rule fires for the first time, we know that only sequences 1 and 2 have values of 1, and the two constraints ensure that f1 references sequence 1 and f2 references sequence 2. The final pattern finds the Fibonacci with a value equal to -1 and with a sequence one greater than f2. At this point, we have three Fibonacci objects correctly selected from the available cross products, and we can calculate the value for the third Fibonacci object that's bound to f3.</br><pre style="font-family:arial;font-size:12px;border:1px solid #CCCCCC;width:99%;height:auto;overflow:auto;background:#f0f0f0;;;padding:0px;color:#000000;text-align:left;line-height:20px;"><code style="color:#000000;word-wrap:normal;">rule "Calculate"<br />dialect "mvel"<br /> when<br /> // Bind f1 and s1<br /> f1 : Fibonacci( s1 : sequence, v1 : value != -1 )<br /> // Bind f2 and v2; refer to bound variable s1<br /> f2 : Fibonacci( sequence == (s1 + 1), v2 : value != -1 )<br /> // Bind f3 and s3; alternative reference of f2.sequence<br /> f3 : Fibonacci( s3 : sequence == (f2.sequence + 1 ), value == -1 ) <br /> then<br /> // Note the various referencing rechniques.<br /> modify ( f3 ) { value = v1 + v2 };<br /> System.out.println( s3 + " == " + f3.value );<br />end </code></pre>The modify statement updated the value of the Fibonacci object bound to f3. This means we now have another new Fibonacci object with a value not equal to -1, which allows the "Calculate" rule to rematch and calculate the next Fibonacci number.</br></div><br> 2013 2013 2013 <br><div dir="ltr" style="text-align: left;" trbidi="on">The most common example of recursion is a Fibonacci series. In drools, the implementation is done using the insert and modify keywords.</br>There are three most important parts in this implementation, one is insert keyword that is used in then part and other is not keyword that gets used in when part to satisify the breaking condition. As in Fibnocci series example, the breaking condition would be {sequence == 1} Consider below class and DRL file : </br></br><u><b>Fibonacci.java</b></u></br><pre style="font-family:arial;font-size:12px;border:1px solid #CCCCCC;width:99%;height:auto;overflow:auto;background:#f0f0f0;;;padding:0px;color:#000000;text-align:left;line-height:20px;"><code style="color:#000000;word-wrap:normal;">package com.recursion;<br /><br />public class Fibonacci {<br /><br /> private int sequence;<br /> private long value;<br /><br /> public Fibonacci(final int sequence) {<br /> this.sequence = sequence;<br /> this.value = -1;<br /> }<br /><br /> public int getSequence() {<br /> return sequence;<br /> }<br /><br /> public void setSequence(int sequence) {<br /> this.sequence = sequence;<br /> }<br /><br /> public long getValue() {<br /> return value;<br /> }<br /><br /> public void setValue(long value) {<br /> this.value = value;<br /> }<br /><br />}<br /></code></pre> <u><b>TestRecursion.java</b></u></br><pre style="font-family:arial;font-size:12px;border:1px solid #CCCCCC;width:99%;height:auto;overflow:auto;background:#f0f0f0;;;padding:0px;color:#000000;text-align:left;line-height:20px;"><code style="color:#000000;word-wrap:normal;">public class TestRecursion {<br /><br /> public static final void main(String[] args) {<br /> try {<br /> // load up the knowledge base<br /><br /> KnowledgeBase kbase = readKnowledgeBase();<br /> StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();<br /> KnowledgeRuntimeLogger logger = KnowledgeRuntimeLoggerFactory.newFileLogger(ksession, "test");<br /><br /> ksession.insert(new Fibonacci(10));<br /> ksession.fireAllRules();<br /><br /> ksession.dispose();<br /> logger.close();<br /> } catch (Throwable t) {<br /> t.printStackTrace();<br /> }<br /> }<br /><br /> private static KnowledgeBase readKnowledgeBase() throws Exception {<br /> KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();<br /> kbuilder.add(ResourceFactory.newClassPathResource("Fibonacci.drl"), ResourceType.DRL);<br /> KnowledgeBuilderErrors errors = kbuilder.getErrors();<br /> if (errors.size() > 0) {<br /> for (KnowledgeBuilderError error : errors) {<br /> System.err.println(error);<br /> }<br /> throw new IllegalArgumentException("Could not parse knowledge.");<br /> }<br /> KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();<br /> kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());<br /> return kbase;<br /> }<br />}</code></pre> The implementation in terms of rules in drl file has three rules as shown below: </br> <u><b>Recurse rule</b></u>: This rule checks if the sequence is not reached to 1 and value is -1 then insert new Fibonacci class object with sequence value one less than previous object. The salience of this rule is highest, because all Fibnocci class object need to be inserted into working memory before calculation the value field of the class. The not conditional element is used to stop the rule's matching once we have all 50 Fibonacci objects in memory. </br><pre style="font-family:arial;font-size:12px;border:1px solid #CCCCCC;width:99%;height:auto;overflow:auto;background:#f0f0f0;;;padding:0px;color:#000000;text-align:left;line-height:20px;"><code style="color:#000000;word-wrap:normal;">rule "Recurse"<br /> salience 10<br /> when<br /> f : Fibonacci ( value == -1 )<br /> not ( Fibonacci ( sequence == 1 ) )<br /> then<br /> insert( new Fibonacci( f.getSequence() - 1 ) );<br /> System.out.println( "recurse for " + f.getSequence() + "--" + f.getValue());<br />end</code></pre> <u><b>Bootstrap rule</b></u>: Fibonacci series for 1 is 1 and for 2 is 1, 1. This rule gets activated for 2 Fibonacci class object that were inserted in the working memory in the earlier rule.</br>For Fibonacci object, sequence == 1 & </br>For Fibonacci object, sequence == 2 </br>So when the sequence == 1 or sequence == 2, we need to update the value field in Fibonacci series to 1 as done below.</br><pre style="font-family:arial;font-size:12px;border:1px solid #CCCCCC;width:99%;height:auto;overflow:auto;background:#f0f0f0;;;padding:0px;color:#000000;text-align:left;line-height:20px;"><code style="color:#000000;word-wrap:normal;">rule "Bootstrap"<br />dialect "mvel"<br /> when<br /> f : Fibonacci( sequence == 1 || == 2, value == -1 ) // multi-restriction<br /> then <br /> modify ( f ){ value = 1 };<br /> System.out.println( f.getSequence() + " == " + f.getValue() );<br />end</code></pre> <u><b>Calculate rule</b></u>: For the remaining 48 objects in the working memory where sequence > 2, below rule gets activated.</br>The "Calculate" rule uses field constraints to correctly constraint the thee Fibonacci patterns in the correct order; this technique is called cross product matching. The first pattern finds any Fibonacci with a value != -1 and binds both the pattern and the field. The second Fibonacci does this, too, but it adds an additional field constraint to ensure that its sequence is greater by one than the Fibonacci bound to f1. When this rule fires for the first time, we know that only sequences 1 and 2 have values of 1, and the two constraints ensure that f1 references sequence 1 and f2 references sequence 2. The final pattern finds the Fibonacci with a value equal to -1 and with a sequence one greater than f2. At this point, we have three Fibonacci objects correctly selected from the available cross products, and we can calculate the value for the third Fibonacci object that's bound to f3.</br><pre style="font-family:arial;font-size:12px;border:1px solid #CCCCCC;width:99%;height:auto;overflow:auto;background:#f0f0f0;;;padding:0px;color:#000000;text-align:left;line-height:20px;"><code style="color:#000000;word-wrap:normal;">rule "Calculate"<br />dialect "mvel"<br /> when<br /> // Bind f1 and s1<br /> f1 : Fibonacci( s1 : sequence, v1 : value != -1 )<br /> // Bind f2 and v2; refer to bound variable s1<br /> f2 : Fibonacci( sequence == (s1 + 1), v2 : value != -1 )<br /> // Bind f3 and s3; alternative reference of f2.sequence<br /> f3 : Fibonacci( s3 : sequence == (f2.sequence + 1 ), value == -1 ) <br /> then<br /> // Note the various referencing rechniques.<br /> modify ( f3 ) { value = v1 + v2 };<br /> System.out.println( s3 + " == " + f3.value );<br />end </code></pre>The modify statement updated the value of the Fibonacci object bound to f3. This means we now have another new Fibonacci object with a value not equal to -1, which allows the "Calculate" rule to rematch and calculate the next Fibonacci number.</br></div><br>2013 2013 2013 <br> <a href="http://www.matrixar.com/" title="Matrix ">المصفوفة : أجمل الخلفيات والصور</a>

Admin
Admin

Posts : 64122
Join date : 2013-02-22

View user profile http://prowebsites1.forumaroc.net

Back to top Go down

View previous topic View next topic Back to top

- Similar topics

 
Permissions in this forum:
You cannot reply to topics in this forum