KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > hp > hpl > jena > reasoner > rulesys > test > TestGenericRules


1 /******************************************************************
2  * File: TestGenericRules.java
3  * Created by: Dave Reynolds
4  * Created on: 08-Jun-2003
5  *
6  * (c) Copyright 2003, 2004, 2005 Hewlett-Packard Development Company, LP
7  * [See end of file]
8  * $Id: TestGenericRules.java,v 1.16 2005/04/12 16:40:16 der Exp $
9  *****************************************************************/

10 package com.hp.hpl.jena.reasoner.rulesys.test;
11
12 import com.hp.hpl.jena.mem.GraphMem;
13 import com.hp.hpl.jena.rdf.model.*;
14 import com.hp.hpl.jena.reasoner.*;
15 import com.hp.hpl.jena.reasoner.rulesys.*;
16 import com.hp.hpl.jena.reasoner.test.TestUtil;
17 import com.hp.hpl.jena.util.PrintUtil;
18 import com.hp.hpl.jena.vocabulary.RDF;
19 import com.hp.hpl.jena.vocabulary.RDFS;
20 import com.hp.hpl.jena.vocabulary.ReasonerVocabulary;
21 import com.hp.hpl.jena.graph.*;
22
23 import junit.framework.TestCase;
24 import junit.framework.TestSuite;
25
26 import java.util.*;
27
28 import org.apache.commons.logging.Log;
29 import org.apache.commons.logging.LogFactory;
30
31
32 /**
33  * Test the packaging of all the reasoners into the GenericRuleReasoner.
34  * The other tests check out this engine. These tests just need to touch
35  * enough to validate the packaging.
36  *
37  * @author <a HREF="mailto:der@hplb.hpl.hp.com">Dave Reynolds</a>
38  * @version $Revision: 1.16 $ on $Date: 2005/04/12 16:40:16 $
39  */

40 public class TestGenericRules extends TestCase {
41     
42     protected static Log logger = LogFactory.getLog(TestFBRules.class);
43
44     // Useful constants
45
Node p = Node.createURI("p");
46     Node q = Node.createURI("q");
47     Node r = Node.createURI("r");
48     Node s = Node.createURI("s");
49     Node t = Node.createURI("t");
50     Node a = Node.createURI("a");
51     Node b = Node.createURI("b");
52     Node c = Node.createURI("c");
53     Node d = Node.createURI("d");
54     Node C1 = Node.createURI("C1");
55     Node C2 = Node.createURI("C2");
56     Node C3 = Node.createURI("C3");
57     Node ty = RDF.type.getNode();
58     Node sC = RDFS.subClassOf.getNode();
59
60     List ruleList = Rule.parseRules("[r1: (?a p ?b), (?b p ?c) -> (?a p ?c)]" +
61                                     "[r2: (?a q ?b) -> (?a p ?c)]" +
62                                     "-> table(p). -> table(q).");
63     Triple[] ans = new Triple[] { new Triple(a, p, b),
64                                    new Triple(b, p, c),
65                                    new Triple(a, p, c) };
66                                  
67     /**
68      * Boilerplate for junit
69      */

70     public TestGenericRules( String JavaDoc name ) {
71         super( name );
72     }
73
74     /**
75      * Boilerplate for junit.
76      * This is its own test suite
77      */

78     public static TestSuite suite() {
79         return new TestSuite( TestGenericRules.class );
80 // TestSuite suite = new TestSuite();
81
// suite.addTest(new TestGenericRules( "testAddRemove2" ));
82
// return suite;
83
}
84     
85      
86     /**
87      * Minimal rule tester to check basic pattern match, forward style.
88      */

89     public void testForward() {
90         Graph test = new GraphMem();
91         test.add(new Triple(a, p, b));
92         test.add(new Triple(b, p, c));
93         
94         GenericRuleReasoner reasoner = (GenericRuleReasoner)GenericRuleReasonerFactory.theInstance().create(null);
95         reasoner.setRules(ruleList);
96         reasoner.setMode(GenericRuleReasoner.FORWARD);
97         
98         // Check data bind version
99
InfGraph infgraph = reasoner.bind(test);
100         TestUtil.assertIteratorValues(this, infgraph.find(null, p, null), ans);
101         
102         // Check schema bind version
103
infgraph = reasoner.bindSchema(test).bind(new GraphMem());
104         TestUtil.assertIteratorValues(this, infgraph.find(null, p, null), ans);
105     }
106      
107     /**
108      * Minimal rule tester to check basic pattern match, backward style.
109      */

110     public void testBackward() {
111         Graph test = new GraphMem();
112         test.add(new Triple(a, p, b));
113         test.add(new Triple(b, p, c));
114         
115         GenericRuleReasoner reasoner = (GenericRuleReasoner)GenericRuleReasonerFactory.theInstance().create(null);
116         reasoner.setRules(ruleList);
117         reasoner.setMode(GenericRuleReasoner.BACKWARD);
118         
119         // Check data bind version
120
InfGraph infgraph = reasoner.bind(test);
121         TestUtil.assertIteratorValues(this, infgraph.find(null, p, null), ans);
122         
123         // Check schema bind version
124
infgraph = reasoner.bindSchema(test).bind(new GraphMem());
125         TestUtil.assertIteratorValues(this, infgraph.find(null, p, null), ans);
126     }
127     
128     /**
129      * Test example hybrid rule.
130      */

131     public void testHybrid() {
132         Graph data = new GraphMem();
133         data.add(new Triple(a, r, b));
134         data.add(new Triple(p, ty, s));
135         List rules = Rule.parseRules(
136         "[a1: -> (a rdf:type t)]" +
137         "[r0: (?x r ?y) -> (?x p ?y)]" +
138         "[r1: (?p rdf:type s) -> [r1b: (?x ?p ?y) <- (?y ?p ?x)]]" +
139         "[r2: (?p rdf:type s) -> [r2b: (?x ?p ?x) <- (?x rdf:type t)]]" +
140         "-> tableAll()."
141                           );
142         GenericRuleReasoner reasoner = (GenericRuleReasoner)GenericRuleReasonerFactory.theInstance().create(null);
143         reasoner.setRules(rules);
144         reasoner.setMode(GenericRuleReasoner.HYBRID);
145         
146         InfGraph infgraph = reasoner.bind(data);
147         infgraph.setDerivationLogging(true);
148         TestUtil.assertIteratorValues(this,
149               infgraph.find(null, p, null), new Object JavaDoc[] {
150                   new Triple(a, p, a),
151                   new Triple(a, p, b),
152                   new Triple(b, p, a)
153               } );
154               
155         // Check derivation tracing as well
156
Iterator di = infgraph.getDerivation(new Triple(b, p, a));
157         assertTrue(di.hasNext());
158         RuleDerivation d = (RuleDerivation)di.next();
159 // java.io.PrintWriter out = new java.io.PrintWriter(System.out);
160
// d.printTrace(out, true);
161
// out.close();
162
assertTrue(d.getRule().getName().equals("r1b"));
163         TestUtil.assertIteratorValues(this, d.getMatches().iterator(), new Object JavaDoc[] { new Triple(a, p, b) });
164         assertTrue(! di.hasNext());
165     }
166     
167     /**
168      * Test example parameter setting
169      */

170     public void testParameters() {
171         Graph data = new GraphMem();
172         data.add(new Triple(a, r, b));
173         data.add(new Triple(p, ty, s));
174
175         Model m = ModelFactory.createDefaultModel();
176         Resource configuration= m.createResource(GenericRuleReasonerFactory.URI);
177         configuration.addProperty(ReasonerVocabulary.PROPderivationLogging, "true");
178         configuration.addProperty(ReasonerVocabulary.PROPruleMode, "hybrid");
179         configuration.addProperty(ReasonerVocabulary.PROPruleSet, "testing/reasoners/genericRuleTest.rules");
180         GenericRuleReasoner reasoner = (GenericRuleReasoner)GenericRuleReasonerFactory.theInstance().create(configuration);
181         
182         InfGraph infgraph = reasoner.bind(data);
183         TestUtil.assertIteratorValues(this,
184               infgraph.find(null, p, null), new Object JavaDoc[] {
185                   new Triple(a, p, a),
186                   new Triple(a, p, b),
187                   new Triple(b, p, a)
188               } );
189               
190         // Check derivation tracing as well
191
Iterator di = infgraph.getDerivation(new Triple(b, p, a));
192         assertTrue(di.hasNext());
193         RuleDerivation d = (RuleDerivation)di.next();
194         assertTrue(d.getRule().getName().equals("r1b"));
195         TestUtil.assertIteratorValues(this, d.getMatches().iterator(), new Object JavaDoc[] { new Triple(a, p, b) });
196         assertTrue(! di.hasNext());
197         
198         // Check retrieval of configuration
199
Model m2 = ModelFactory.createDefaultModel();
200         Resource newConfig = m2.createResource();
201         reasoner.addDescription(m2, newConfig);
202         TestUtil.assertIteratorValues(this, newConfig.listProperties(), new Statement[] {
203             m2.createStatement(newConfig, ReasonerVocabulary.PROPderivationLogging, "true"),
204             m2.createStatement(newConfig, ReasonerVocabulary.PROPruleMode, "hybrid"),
205             m2.createStatement(newConfig, ReasonerVocabulary.PROPruleSet, "testing/reasoners/genericRuleTest.rules")
206             } );
207        
208         // Manual reconfig and check retrieval of changes
209
reasoner.setParameter(ReasonerVocabulary.PROPderivationLogging, "false");
210         newConfig = m2.createResource();
211         reasoner.addDescription(m2, newConfig);
212         TestUtil.assertIteratorValues(this, newConfig.listProperties(), new Statement[] {
213             m2.createStatement(newConfig, ReasonerVocabulary.PROPderivationLogging, "false"),
214             m2.createStatement(newConfig, ReasonerVocabulary.PROPruleMode, "hybrid"),
215             m2.createStatement(newConfig, ReasonerVocabulary.PROPruleSet, "testing/reasoners/genericRuleTest.rules")
216             } );
217         
218         // Mutiple rule file loading
219
m = ModelFactory.createDefaultModel();
220         configuration= m.createResource(GenericRuleReasonerFactory.URI);
221         configuration.addProperty(ReasonerVocabulary.PROPruleMode, "hybrid");
222         configuration.addProperty(ReasonerVocabulary.PROPruleSet, "testing/reasoners/ruleset1.rules");
223         configuration.addProperty(ReasonerVocabulary.PROPruleSet, "testing/reasoners/ruleset2.rules");
224         reasoner = (GenericRuleReasoner)GenericRuleReasonerFactory.theInstance().create(configuration);
225         
226         infgraph = reasoner.bind(new GraphMem());
227         Node an = Node.createURI(PrintUtil.egNS + "a");
228         Node C = Node.createURI(PrintUtil.egNS + "C");
229         Node D = Node.createURI(PrintUtil.egNS + "D");
230         TestUtil.assertIteratorValues(this,
231               infgraph.find(null, null, null), new Object JavaDoc[] {
232                 new Triple(an, RDF.Nodes.type, C),
233                 new Triple(an, RDF.Nodes.type, D),
234               } );
235      }
236     
237     /**
238      * Test control of functor filtering
239      */

240     public void testHybridFunctorFilter() {
241         Graph data = new GraphMem();
242         data.add(new Triple(a, r, b));
243         data.add(new Triple(a, p, s));
244         List rules = Rule.parseRules( "[r0: (?x r ?y) (?x p ?z) -> (?x q func(?y, ?z)) ]" );
245         GenericRuleReasoner reasoner = (GenericRuleReasoner)GenericRuleReasonerFactory.theInstance().create(null);
246         reasoner.setRules(rules);
247         reasoner.setMode(GenericRuleReasoner.HYBRID);
248         
249         InfGraph infgraph = reasoner.bind(data);
250         TestUtil.assertIteratorValues(this,
251               infgraph.find(null, q, null), new Object JavaDoc[] {
252               } );
253               
254         reasoner.setFunctorFiltering(false);
255         infgraph = reasoner.bind(data);
256         TestUtil.assertIteratorValues(this,
257               infgraph.find(null, q, null), new Object JavaDoc[] {
258                   new Triple(a, q, Functor.makeFunctorNode("func", new Node[]{b, s}))
259               } );
260     }
261     
262     /**
263      * Test the @prefix and @include extensions to the rule parser
264      */

265     public void testExtendedRuleParser() {
266         List rules = Rule.rulesFromURL("file:testing/reasoners/ruleParserTest1.rules");
267         GenericRuleReasoner reasoner = new GenericRuleReasoner(rules);
268         reasoner.setTransitiveClosureCaching(true);
269         Model base = ModelFactory.createDefaultModel();
270         InfModel m = ModelFactory.createInfModel(reasoner, base);
271         
272         // Check prefix case
273
String JavaDoc NS1 = "http://jena.hpl.hp.com/newprefix#";
274         String JavaDoc NS2 = "http://jena.hpl.hp.com/newprefix2#";
275         String JavaDoc NS3 = "http://jena.hpl.hp.com/newprefix3#";
276         Resource A = m.getResource(NS1 + "A");
277         Resource C = m.getResource(NS1 + "C");
278         Property p = m.getProperty(NS2 + "p");
279         Property a = m.getProperty(NS3 + "a");
280         Resource foo = m.getResource(NS1 + "foo");
281         assertTrue("@prefix test", m.contains(A, p, foo));
282         
283         // Check RDFS rule inclusion
284
assertTrue("@include RDFS test", m.contains(A, RDFS.subClassOf, C));
285         assertTrue("@include test", m.contains(a,a,a));
286     }
287
288     /**
289      * Test add/remove support
290      */

291     public void testAddRemove() {
292         doTestAddRemove(false);
293         doTestAddRemove(true);
294     }
295     
296     /**
297      * Internals of add/remove test.
298      * @param useTGC set to true to use transitive caching
299      */

300     public void doTestAddRemove(boolean useTGC) {
301         Graph data = new GraphMem();
302         data.add(new Triple(a, p, C1));
303         data.add(new Triple(C1, sC, C2));
304         data.add(new Triple(C2, sC, C3));
305         List rules = Rule.parseRules(
306         "-> table(rdf:type)." +
307         "[r1: (?x p ?c) -> (?x rdf:type ?c)] " +
308         "[rdfs9: (?x rdfs:subClassOf ?y) -> [ (?a rdf:type ?y) <- (?a rdf:type ?x)] ]"
309                           );
310         if (!useTGC) {
311             rules.add(Rule.parseRule("[rdfs8: (?a rdfs:subClassOf ?b), (?b rdfs:subClassOf ?c) -> (?a rdfs:subClassOf ?c)] "));
312         }
313         GenericRuleReasoner reasoner = (GenericRuleReasoner)GenericRuleReasonerFactory.theInstance().create(null);
314         reasoner.setRules(rules);
315 // reasoner.setTraceOn(true);
316
reasoner.setMode(GenericRuleReasoner.HYBRID);
317         reasoner.setTransitiveClosureCaching(useTGC);
318         
319         InfGraph infgraph = reasoner.bind(data);
320         TestUtil.assertIteratorValues(this,
321               infgraph.find(a, ty, null), new Object JavaDoc[] {
322                   new Triple(a, ty, C1),
323                   new Triple(a, ty, C2),
324                   new Triple(a, ty, C3)
325               } );
326               
327         logger.debug("Checkpoint 1");
328         infgraph.delete(new Triple(C1, sC, C2));
329         TestUtil.assertIteratorValues(this,
330               infgraph.find(a, ty, null), new Object JavaDoc[] {
331                   new Triple(a, ty, C1)
332               } );
333          
334         logger.debug("Checkpoint 2");
335         infgraph.add(new Triple(C1, sC, C3));
336         infgraph.add(new Triple(b, p, C2));
337         TestUtil.assertIteratorValues(this,
338               infgraph.find(a, ty, null), new Object JavaDoc[] {
339                   new Triple(a, ty, C1),
340                   new Triple(a, ty, C3)
341               } );
342         TestUtil.assertIteratorValues(this,
343               infgraph.find(b, ty, null), new Object JavaDoc[] {
344                   new Triple(b, ty, C2),
345                   new Triple(b, ty, C3)
346               } );
347          
348         TestUtil.assertIteratorValues(this,
349               data.find(null, null, null), new Object JavaDoc[] {
350                   new Triple(a, p, C1),
351                   new Triple(b, p, C2),
352                   new Triple(C2, sC, C3),
353                   new Triple(C1, sC, C3)
354               } );
355     }
356     
357     /**
358      * Resolve a bug using remove in rules themselves.
359      */

360     public void testAddRemove2() {
361         Graph data = new GraphMem();
362         data.add(new Triple(a, p, Util.makeIntNode(0)));
363         List rules = Rule.parseRules(
364         "(?x p ?v) noValue(a r 1) -> (?x p inc(1, a)) (?x r 1).\n" +
365         "(?x p ?v) noValue(a r 2) -> (?x p inc(1, b)) (?x r 2).\n" +
366         "(?x p ?v) (?x p inc(?i, ?t)) sum(?v, ?i, ?s) -> remove(0,1), (?x p ?s).\n");
367         
368         // This version doesn't work but its not clear if it should
369
// List rules = Rule.parseRules(
370
// "(?x p ?v) noValue(a r 1) addOne(?v, ?v2) -> remove(0) (?x p ?v2) (?x r 1).\n" +
371
// "(?x p ?v) noValue(a r 2) addOne(?v, ?v2) -> remove(0) (?x p ?v2) (?x r 2).\n");
372
GenericRuleReasoner reasoner = (GenericRuleReasoner)GenericRuleReasonerFactory.theInstance().create(null);
373         reasoner.setRules(rules);
374         reasoner.setMode(GenericRuleReasoner.FORWARD_RETE);
375         
376         InfGraph infgraph = reasoner.bind(data);
377         TestUtil.assertIteratorValues(this,
378               infgraph.find(a, p, null), new Object JavaDoc[] {
379                   new Triple(a, p, Util.makeIntNode(2))
380               } );
381     }
382 }
383
384
385
386 /*
387     (c) Copyright 2003, 2004, 2005 Hewlett-Packard Development Company, LP
388     All rights reserved.
389
390     Redistribution and use in source and binary forms, with or without
391     modification, are permitted provided that the following conditions
392     are met:
393
394     1. Redistributions of source code must retain the above copyright
395        notice, this list of conditions and the following disclaimer.
396
397     2. Redistributions in binary form must reproduce the above copyright
398        notice, this list of conditions and the following disclaimer in the
399        documentation and/or other materials provided with the distribution.
400
401     3. The name of the author may not be used to endorse or promote products
402        derived from this software without specific prior written permission.
403
404     THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
405     IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
406     OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
407     IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
408     INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
409     NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
410     DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
411     THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
412     (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
413     THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
414 */
Popular Tags