KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > hp > hpl > jena > reasoner > dig > DIGInfGraph


1 /*****************************************************************************
2  * Source code information
3  * -----------------------
4  * Original author Ian Dickinson, HP Labs Bristol
5  * Author email Ian.Dickinson@hp.com
6  * Package Jena 2
7  * Web http://sourceforge.net/projects/jena/
8  * Created July 19th 2003
9  * Filename $RCSfile: DIGInfGraph.java,v $
10  * Revision $Revision: 1.13 $
11  * Release status $State: Exp $
12  *
13  * Last modified on $Date: 2005/03/16 18:52:27 $
14  * by $Author: ian_dickinson $
15  *
16  * (c) Copyright 2001, 2002, 2003, 2004, 2005 Hewlett-Packard Development Company, LP
17  * [See end of file]
18  *****************************************************************************/

19
20 // Package
21
///////////////
22
package com.hp.hpl.jena.reasoner.dig;
23
24
25
26
27
28 // Imports
29
///////////////
30
import java.util.Iterator JavaDoc;
31
32 import com.hp.hpl.jena.graph.*;
33 import com.hp.hpl.jena.graph.compose.MultiUnion;
34 import com.hp.hpl.jena.ontology.OntModel;
35 import com.hp.hpl.jena.ontology.Profile;
36 import com.hp.hpl.jena.rdf.model.*;
37 import com.hp.hpl.jena.reasoner.*;
38 import com.hp.hpl.jena.util.iterator.ExtendedIterator;
39 import com.hp.hpl.jena.vocabulary.RDF;
40
41
42 /**
43  * <p>
44  * An InfGraph that performs reasoning via a DIG interface to an external reasoner.
45  * </p>
46  *
47  * @author Ian Dickinson, HP Labs
48  * (<a HREF="mailto:Ian.Dickinson@hp.com" >email</a>)
49  * @version CVS $Id: DIGInfGraph.java,v 1.13 2005/03/16 18:52:27 ian_dickinson Exp $
50  */

51 public class DIGInfGraph
52     extends BaseInfGraph
53 {
54     // Constants
55
//////////////////////////////////
56

57
58     // Static variables
59
//////////////////////////////////
60

61
62     // Instance variables
63
//////////////////////////////////
64

65     /** The DIG adapter we will use to communicate with the external reasoner */
66     protected DIGAdapter m_adapter;
67
68
69     // Constructors
70
//////////////////////////////////
71

72     /**
73      * Constructor
74      * @param data the raw data file to be augmented with entailments
75      * @param reasoner the engine, with associated tbox data, whose find interface
76      * can be used to extract all entailments from the data.
77      */

78     public DIGInfGraph( Graph data, DIGReasoner reasoner ) {
79         super( data, reasoner );
80
81         // we want a union of data and tbox
82
if (reasoner.getSchema() != null) {
83             fdata = new FGraph( new MultiUnion( new Graph[] {data, reasoner.getSchema()} ) );
84         }
85
86         // create or re-use a free connector
87
DIGConnection conn = DIGConnectionPool.getInstance().allocate( reasoner.getReasonerURL() );
88         m_adapter = new DIGAdapter( reasoner.getOntLangModelSpec(), fdata.getGraph(), conn, reasoner.getAxioms() );
89     }
90
91
92     // External signature methods
93
//////////////////////////////////
94

95     /**
96      * Perform any initial processing and caching. This call is optional. Most
97      * engines either have negligable set up work or will perform an implicit
98      * "prepare" if necessary. The call is provided for those occasions where
99      * substantial preparation work is possible (e.g. running a forward chaining
100      * rule system) and where an application might wish greater control over when
101      * this prepration is done.
102      */

103     public void prepare() {
104         if (!isPrepared) {
105             m_adapter.resetKB();
106             m_adapter.uploadKB();
107             isPrepared = true;
108         }
109     }
110
111     /**
112      * <p>Extended find interface used in situations where the implementator
113      * may or may not be able to answer the complete query. It will
114      * attempt to answer the pattern but if its answers are not known
115      * to be complete then it will also pass the request on to the nested
116      * Finder to append more results.</p><p>
117      * <strong>DIG implementation note:</strong> the default call into this
118      * method from the base inference graph makes the continuation a query
119      * of the base graph. Since {@link DIGAdapter} already queries the base
120      * graph, there is no futher need to query it through the continuation.
121      * Consequently, this implementation <em>does not call</em> the continuation.
122      * Client code that wishes to provide a non-default continuation should
123      * sub-class DIGInfGraph and provide a suitable call to the continuation.find().
124      * </p>
125      * @param pattern a TriplePattern to be matched against the data
126      * @param continuation Not used in this implementation
127      */

128     public ExtendedIterator findWithContinuation(TriplePattern pattern, Finder continuation) {
129         prepare();
130         return m_adapter.find( pattern );
131     }
132
133
134     /**
135      * <p>An extension of the {@link Graph#find} interface which allows the caller to
136      * encode complex expressions in RDF and then refer to those expressions
137      * within the query triple. For example, one might encode a class expression
138      * and then ask if there are any instances of this class expression in the
139      * InfGraph. In the case of the DIGInfGraph, this is exactly the use case we assume.
140      * In particular, we expect that the <code>object</code> node is the subject of
141      * one or more sentences in <code>param</code> which completely define the class
142      * description.<p>
143      * @param subject the subject Node of the query triple, may be a Node in
144      * the graph or a node in the parameter micro-graph or null
145      * @param property the property to be retrieved or null
146      * @param object the object Node of the query triple, may be a Node in
147      * the graph or a node in the parameter micro-graph.
148      * @param param a small graph encoding an expression which the subject and/or
149      * object nodes refer.
150      */

151     public ExtendedIterator find( Node subject, Node property, Node object, Graph param ) {
152         OntModel premises = ModelFactory.createOntologyModel( m_adapter.getSourceSpecification(),
153                                                               ModelFactory.createModelForGraph( param ) );
154         premises.setStrictMode( false );
155         prepare();
156         return m_adapter.find( new TriplePattern( subject, property, object ), premises );
157     }
158
159     /**
160      * Return the schema graph, if any, bound into this inference graph.
161      */

162     public Graph getSchemaGraph() {
163         return ((DIGReasoner) reasoner).getSchema();
164     }
165
166     // overriding the BaseInfGraph methods
167

168     /**
169      * <p>Add one triple to the data graph, mark the graph not-prepared,
170      * but don't run prepare() just yet.</p>
171      * @param t A triple to add to the graph
172      */

173     public synchronized void performAdd(Triple t) {
174         fdata.getGraph().add(t);
175         isPrepared = false;
176     }
177
178     /**
179      * <p>Delete one triple from the data graph, mark the graph not-prepared,
180      * but don't run prepare() just yet.</p>
181      * @param t A triple to remove from the graph
182      */

183     public void performDelete(Triple t) {
184         fdata.getGraph().delete(t);
185         isPrepared = false;
186     }
187
188     /**
189      * Replace the underlying data graph for this inference graph and start any
190      * inferences over again. This is primarily using in setting up ontology imports
191      * processing to allow an imports multiunion graph to be inserted between the
192      * inference graph and the raw data, before processing.
193      * @param data the new raw data graph
194      */

195     public void rebind( Graph data ) {
196         if (getSchemaGraph() == null) {
197             fdata = new FGraph(data);
198         }
199         else {
200             fdata = new FGraph( new MultiUnion( new Graph[] {data, getSchemaGraph()} ) );
201         }
202
203         isPrepared = false;
204     }
205
206
207     /**
208      * Switch on/off drivation logging - not supported with DIG reasoner
209      */

210     public void setDerivationLogging(boolean logOn) {
211         throw new UnsupportedOperationException JavaDoc( "Cannot set derivation logging on DIG reasoner" );
212     }
213
214
215     /**
216      * <p>Test the consistency of the model. This looks for overall inconsistency,
217      * and for any unsatisfiable classes.</p>
218      * @return a ValidityReport structure
219      */

220     public ValidityReport validate() {
221         checkOpen();
222         prepare();
223         StandardValidityReport report = new StandardValidityReport();
224
225         // look for incoherent KB by listing the individuals
226
try {
227             m_adapter.collectNamedTerms( DIGProfile.ALL_INDIVIDUALS,
228                                          new String JavaDoc[] {DIGProfile.INDIVIDUAL_SET, DIGProfile.INDIVIDUAL} );
229         }
230         catch (DIGErrorResponseException e) {
231             report.add( true, "DIG KB incoherent", e.getMessage() );
232         }
233
234         // now look for unsatisfiable classes
235
Profile p = m_adapter.getOntLanguage();
236         Node nothing = p.NOTHING().asNode();
237         Property equivClass = p.EQUIVALENT_CLASS();
238         DIGQueryEquivalentsTranslator q = new DIGQueryEquivalentsTranslator( equivClass.getURI(), true );
239         ExtendedIterator i = q.find( new TriplePattern( null, equivClass.asNode(), p.NOTHING().asNode() ), m_adapter );
240
241         while (i.hasNext()) {
242             Triple t = (Triple) i.next();
243             Node subj = t.getSubject();
244             if (subj != nothing) {
245                 report.add( true, "unsatisfiable class", (subj.isBlank() ? subj.getBlankNodeId().toString() : subj.getURI()), t.getSubject() );
246             }
247         }
248
249         // look for incoherent instances
250
DIGQueryTypesTranslator q1 = new DIGQueryTypesTranslator( RDF.type.getURI() );
251         DIGValueToNodeMapper vMap = new DIGValueToNodeMapper();
252         for (Iterator JavaDoc j = m_adapter.getKnownIndividuals().iterator(); j.hasNext(); ) {
253             String JavaDoc ind = (String JavaDoc) j.next();
254             Node indNode = (Node) vMap.map1( ind );
255
256             try {
257                 ExtendedIterator i1 = q1.find( new TriplePattern( indNode, RDF.type.asNode(), null ), m_adapter );
258             }
259             catch (DIGErrorResponseException e) {
260                 // we assume this is an incoherent KB exception - should check
261
report.add( true, "meaningless individual", (indNode.isBlank() ? indNode.getBlankNodeId().toString() : indNode.getURI()), ind );
262             }
263         }
264
265         return report;
266     }
267
268
269
270     // Internal implementation methods
271
//////////////////////////////////
272

273
274     //==============================================================================
275
// Inner class definitions
276
//==============================================================================
277

278
279
280 }
281
282
283 /*
284  * (c) Copyright 2001, 2002, 2003, 2004, 2005 Hewlett-Packard Development Company, LP
285  * All rights reserved.
286  *
287  * Redistribution and use in source and binary forms, with or without
288  * modification, are permitted provided that the following conditions
289  * are met:
290  * 1. Redistributions of source code must retain the above copyright
291  * notice, this list of conditions and the following disclaimer.
292  * 2. Redistributions in binary form must reproduce the above copyright
293  * notice, this list of conditions and the following disclaimer in the
294  * documentation and/or other materials provided with the distribution.
295  * 3. The name of the author may not be used to endorse or promote products
296  * derived from this software without specific prior written permission.
297  *
298  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
299  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
300  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
301  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
302  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
303  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
304  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
305  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
306  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
307  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
308  */

309
Popular Tags