My favorites | Sign in
Project Hosting will be READ-ONLY Thursday at 3:00pm UTC for up to 3 hours for network maintenance.
Project Home Downloads Wiki Issues Source
Repository:
Checkout   Browse   Changes   Clones    
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
package net.willware.semweb;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.hp.hpl.jena.graph.Node;
import com.hp.hpl.jena.graph.Triple;
import com.hp.hpl.jena.query.*;
import com.hp.hpl.jena.rdf.model.*;
import com.hp.hpl.jena.reasoner.InfGraph;
import com.hp.hpl.jena.reasoner.TriplePattern;
import com.hp.hpl.jena.reasoner.rulesys.*;
import com.hp.hpl.jena.reasoner.rulesys.builtins.BaseBuiltin;

/**
* A collection of utilities and convenience methods to simplify
* Jena usage.
* @author wware
*/
public class JenaUtil {

/**
* Read a Model from a file on disk, or from a URI
* on the web somewhere.
* @param filename either a filename or a URI
* @param model the model to be loaded
* @param baseUri a base URI for the model
*/
public static void modelReadFile(
String filename,
Model model,
String baseUri) {
try {
File f = new File(filename);
FileReader fr = new FileReader(f);
model.read(fr, baseUri);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}

/**
* Print all the statements in a model.
* @param model the model to be printed
*/
public static void printModel(Model model) {
String queryString =
"SELECT ?x ?y ?z " +
"WHERE {" +
" ?x ?y ?z . " +
"}";
Query query = QueryFactory.create(queryString);
QueryExecution qe = QueryExecutionFactory.create(query, model);
ResultSet results = qe.execSelect();
ResultSetFormatter.out(System.out, results, query);
qe.close();
}

/**
* Just like a Runnable, except the RuleContext method
* takes a RuleContext, so it can be used in the head of a rule to
* operate on a Jena model.
*/
public static interface Action {
/**
* Just like Runnable.run(), except it takes a
* RuleContext so it can operate on a Jena model.
* @param context the RuleContext
*/
public void run(RuleContext context);
}

public RDFNode findInModel(Model model, String uri) {
StmtIterator iter = model.listStatements();
RDFNode x;
while (iter.hasNext()) {
Statement s = iter.next();
x = s.getSubject();
if (x.isURIResource() && uri.equals(((Resource)x).getURI())) {
return x;
}
x = s.getPredicate();
if (x.isURIResource() && uri.equals(((Resource)x).getURI())) {
return x;
}
x = s.getObject();
if (x.isURIResource() && uri.equals(((Resource)x).getURI())) {
return x;
}
}
return null;
}

/**
* This is a wrapper to be placed around an {@link Action} to avoid a
* problem with infinite regression. The enclosed action is performed
* only once for each variable assignment. If you're updating a triple,
* e.g. from ":Car :is :red" to ":Car :is :blue", and Jena's inference
* engine will see a new statement that fits the rule antecedent, and
* so perform the update again ad infinitum.
*/
public static class ActionOnlyOncePerBinding implements Action {
private Action action;
private List<Node_RuleVariable> varlist;
private List<String> alreadyDone;
public ActionOnlyOncePerBinding() {
this.action = null;
this.varlist = null;
alreadyDone = new ArrayList<String>();
}
public void setAction(Action action) {
this.action = action;
}
public void setVarlist(List<Node_RuleVariable> varlist) {
this.varlist = varlist;
}
public void setVarlist(Node_RuleVariable[] varlist) {
this.varlist = new ArrayList<Node_RuleVariable>();
for (Node_RuleVariable var : varlist)
this.varlist.add(var);
}
public void run(RuleContext context) {
BindingEnvironment be = context.getEnv();
String values = getValuesKey(be, varlist);
if (!alreadyDone.contains(values)) {
alreadyDone.add(values);
action.run(context);
}
}
}

/**
* This is a RuleContext that can add and remove triples to/from a
* model.
*/
public static class LocalRuleContext implements RuleContext {
Binding binding;
Model model;
Resource s;
Property p;
RDFNode o;
public LocalRuleContext(Binding b, Model m) {
binding = b;
model = m;
}
private void readTriple(Triple t) {
if (t.getSubject() == null) s = null;
else s = model.createResource(t.getSubject().getURI());
if (t.getPredicate() == null) p = null;
else p = model.createProperty(t.getPredicate().getURI());
if (t.getObject() == null) o = null;
else o = model.createResource(t.getObject().getURI());
}
public void add(Triple t) {
readTriple(t);
model.add(s, p, o);
}
public boolean contains(Node s1, Node p1, Node o1) {
s = (Resource) s1;
p = (Property) p1;
o = (RDFNode) o1;
return model.contains(s, p, o);
}
public boolean contains(Triple t) {
readTriple(t);
return model.contains(s, p, o);
}
public com.hp.hpl.jena.util.iterator.ClosableIterator<Triple>
find(Node s, Node p, Node o) { throw new NotImplemented(); }
public BindingEnvironment getEnv() { return binding; }
public InfGraph getGraph() { throw new NotImplemented(); }
public Rule getRule() { throw new NotImplemented(); }
public void remove(Triple t) {
readTriple(t);
model.removeAll(s, p, o);
}
public void setRule(Rule rule) { throw new NotImplemented(); }
public void silentAdd(Triple t) { throw new NotImplemented(); }
}

/**
* To conveniently do something with all the variables in a Binding,
* implement this interface and pass an instance of the implementation
* to the {@link Binding#iterateOver(BindingIteration)} method.
*/
public static interface BindingIteration {
public void iter(Node_RuleVariable var);
}

/**
* A BindingEnvironment implementation with some handy convenience methods.
* A Binding is fundamentally a mapping from variables (instances of
* Node_RuleVariable) to values (instances of Node).
* Everything else is convenience fluff.
*/
protected static class Binding implements BindingEnvironment {
private Map<Node_RuleVariable,Node> mapping;
/**
* Constructor for a {@link Binding}
*/
public Binding() {
mapping = new HashMap<Node_RuleVariable,Node>();
}
public String toString() {
final StringBuffer r = new StringBuffer("<Binding");
final Binding self = this;
iterateOver(new BindingIteration() {
public void iter(Node_RuleVariable var) {
Node value = self.getGroundVersion(var);
if (value == null) {
r.append("\n " + var.toString() +
": [null]");
} else if (value != var) {
r.append("\n " + var.toString() +
": " + value.toString());
} else {
r.append("\n " + var.toString() +
"? " + value.toString());
}
}
});
return r.toString() + ">";
}
public boolean equals(Object other) {
try {
return mapping.equals(((Binding)other).mapping);
} catch (ClassCastException cce) {
return false;
}
}
public boolean bind(Node var, Node value) {
try {
mapping.put((Node_RuleVariable)var, value);
return true;
} catch (ClassCastException cce) {
return false;
}
}
public Node getGroundVersion(Node var) {
if (!hasKey(var)) return var;
return mapping.get(var);
}
public Triple instantiate(TriplePattern pattern) {
throw new NotImplemented();
}
public boolean hasKey(Node var) {
return mapping.containsKey(var);
}
/**
* Iterate over the variables in this Binding, applying the
* argument iteration to each of them in turn. If you need to
* look up the value of the variable, do something like this.
* <pre> final Binding b = ... ;
* b.iterateOver(new BindingIteration() {
* public void iter(Node_RuleVariable var) {
* Node value = b.getGroundVersion(var);
* if (value != var) { ... }
* }
* });</pre>
* @param iteration an implementor of the
* {@link BindingIteration} interface
*/
public void iterateOver(BindingIteration iteration) {
Iterator<Node_RuleVariable> varIter =
mapping.keySet().iterator();
while (varIter.hasNext()) {
iteration.iter(varIter.next());
}
}
public Binding merge(final Binding other) {
final Binding result = new Binding();
iterateOver(new BindingIteration() {
public void iter(Node_RuleVariable var) {
if (!result.bind(var, mapping.get(var)))
throw new Trouble();
}
});
other.iterateOver(new BindingIteration() {
public void iter(Node_RuleVariable var) {
if (!result.hasKey(var) &&
!result.bind(var, other.mapping.get(var)))
throw new Trouble();
}
});
return result;
}
}

/**
* Given a {@link BindingEnvironment} and a list of
* Node_RuleVariables, run through the list
* and ground them against the BindingEnvironment, i.e. look up the
* string values of the variables. Concatenate them all into one big
* string and return them. The purpose is to produce keys for Maps
* which can distinguish one binding from another.
* @param binding the BindingEnvironment to ground against
* @param nodelist the list of Node_RuleVariable instances
* @return a string that uniquely identifies that binding
*/
protected static String getValuesKey(BindingEnvironment binding,
List<Node_RuleVariable> nodelist) {
String r = "";
for (Node node : nodelist) {
Node n2 = binding.getGroundVersion(node);
if (n2 != null && node != n2)
r += n2.toString();
else
r += "<>";
}
return r;
}

/**
* For stuff that has not yet been implemented.
*/
public static class NotImplemented extends RuntimeException {
public static final long serialVersionUID = 0;
}

/**
* General-purpose exception for when anything bad happens
* in this code.
*/
public static class Trouble extends RuntimeException {
public static final long serialVersionUID = 0;
}

/**
* Given an {@link Action}, create a Functor that can be
* used in the head list of a Rule
* @param action the action to be taken when the rule fires
* @return a functor that goes in the rule's head list
*/
public static Functor buildFunctor(final Action action) {
BaseBuiltin bb = new BaseBuiltin() {
public String getName() { return "anonymous functor"; };
public void headAction(Node[] args, int length,
RuleContext context) {
action.run(context);
}
};
Functor functor = new Functor(null, new Node[] { });
functor.setImplementor(bb);
return functor;
}

/**
* Create a custom Rule where the variable list has extracted manually.
* @param runOnce if true, wrap the action in an ActionOnceOnlyPerBinding to
* avoid infinite regression.
* @param varlist a list of rule variables that must match for the binding
* @param antecedents the triplet patterns that need to match for the rule to fire
* @param action the action to be performed when the rule is fired
* @return the created rule
*/
public static Rule buildCustomRule(
final boolean runOnce,
final Node_RuleVariable[] varlist,
final ClauseEntry[] antecedents,
Action action) {
if (runOnce) {
ActionOnlyOncePerBinding actionOnce =
new ActionOnlyOncePerBinding();
actionOnce.setAction(action);
actionOnce.setVarlist(varlist);
action = actionOnce;
}
return new Rule("",
new ClauseEntry[] {
buildFunctor(action)
},
antecedents);
}

/**
* Create a custom Rule
* @param runOnce if true, wrap the action in an {@link ActionOnlyOncePerBinding} to
* avoid infinite regression.
* @param antecedents the conditions to be met (with variables matched) in order
* for the rule to fire; the list of variables to be matched is picked from these
* @param action the action to be performed when the rule is fired
* @return the created rule
*/
public static Rule buildCustomRule(
final boolean runOnce,
final ClauseEntry[] antecedents,
Action action) {
if (runOnce) {
List<Node_RuleVariable> varlist =
new ArrayList<Node_RuleVariable>();
for (ClauseEntry ce : antecedents) {
TriplePattern tp = null;
try {
tp = (TriplePattern) ce;
Node s = tp.getSubject();
Node p = tp.getSubject();
Node o = tp.getSubject();
if (s instanceof Node_RuleVariable &&
!varlist.contains(s))
varlist.add((Node_RuleVariable)s);
if (p instanceof Node_RuleVariable &&
!varlist.contains(p))
varlist.add((Node_RuleVariable)p);
if (o instanceof Node_RuleVariable &&
!varlist.contains(o))
varlist.add((Node_RuleVariable)o);
} catch (ClassCastException cce) { }
}
ActionOnlyOncePerBinding actionOnce =
new ActionOnlyOncePerBinding();
actionOnce.setAction(action);
actionOnce.setVarlist(varlist);
action = actionOnce;
}
return new Rule("",
new ClauseEntry[] {
buildFunctor(action)
},
antecedents);
}

/**
* Given a RuleContext, a Model, and a rule variable, look up the
* model's corresponding Resource and return it.
* @param context the RuleContext
* @param model the Model
* @param var the rule variable
* @return the corresponding Resource
*/
public static Resource ruleVarToResource(RuleContext context,
Model model, Node_RuleVariable var) {
Node x = context.getEnv().getGroundVersion(var);
return (Resource) model.getRDFNode(x);
}

/**
* Given a RuleContext, a Model, and a rule variable, look up the
* model's corresponding Literal and return it.
* @param context the RuleContext
* @param model the Model
* @param var the rule variable
* @return the corresponding Literal
*/
public static Literal ruleVarToLiteral(RuleContext context,
Model model, Node_RuleVariable var) {
Node x = context.getEnv().getGroundVersion(var);
return (Literal) model.getRDFNode(x);
}

/**
* Given a RuleContext, a Model, and a rule variable, look up the
* value of the rule variable as a double and return it.
* @param context the RuleContext
* @param model the Model
* @param var the rule variable
* @return the double gotten from looking up the variable
*/
public static float ruleVarToFloat(RuleContext context,
Model model, Node_RuleVariable var) {
return ruleVarToLiteral(context, model, var).getFloat();
}

/**
* Given a RuleContext, a Model, and a rule variable, look up the
* value of the rule variable as a boolean and return it.
* @param context the RuleContext
* @param model the Model
* @param var the rule variable
* @return the boolean gotten from looking up the variable
*/
public static boolean ruleVarToBoolean(RuleContext context,
Model model, Node_RuleVariable var) {
return ruleVarToLiteral(context, model, var).getBoolean();
}
}

Change log

cb0571c896fb by ww...@localhost.localdomain on Feb 24, 2010   Diff
clean up the makefile and the way
bayesInf.rdf gets built
Go to: 
Project members, sign in to write a code review

Older revisions

0bc7d5933da4 by ww...@localhost.localdomain on Feb 24, 2010   Diff
When we observe a value for B, we put
it in the graph. We don't just
set some private variable in the BI
class. That way the graph is doing
our knowledge representation rather
...
2792b5e517e5 by ww...@localhost.localdomain on Feb 23, 2010   Diff
Lots of good progress, including
Javadoc, and getting the Bayesian
stuff working again.
a9d587bb6d94 by ww...@localhost.localdomain on Feb 12, 2010   Diff
mo' better
All revisions of this file

File info

Size: 17853 bytes, 481 lines
Powered by Google Project Hosting