Debian Codegraph @

Kernel/Kernel.h

raw symbols SCIP
1 /* This file is part of the FaCT++ DL reasoner
2 Copyright (C) 2003-2015 Dmitry Tsarkov and The University of Manchester
3 Copyright (C) 2015-2017 Dmitry Tsarkov
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18 */
19
20 #ifndef KERNEL_H
21 #define KERNEL_H
22
23 #include <string>
24
25 #include "fpp_assert.h"
26 #include "eFPPInconsistentKB.h"
27 #include "dlTBox.h"
28 #include "ifOptions.h"
29 #include "DLConceptTaxonomy.h" // for getRelatives()
30 #include "tExpressionTranslator.h"
31 #include "tOntology.h"
32 #include "KnowledgeExplorer.h"
33 #include "tOntologyAtom.h" // types for AD
34 #include "ModuleType.h"
35 #include "ModuleMethod.h"
36
37 class OntologyBasedModularizer;
38 class AtomicDecomposer;
39 class TJNICache; // cached JNI information
40 class SaveLoadManager;
41
42 class ReasoningKernel
43 {
44 public: // types interface
45 /*
46 The type system for DL expressions used in the input language:
47
48 TExpr;
49 TConceptExpr: TExpr;
50 TIndividualExpr : TExpr;
51 TRoleExpr: TExpr;
52 TORoleComplexExpr: TRoleExpr;
53 TORoleExpr: TORoleComplexExpr;
54 TDRoleExpr: TRoleExpr;
55 TDataExpr: TExpr;
56 TDataValueExpr: TDataExpr;
57
58 Right now all the expressions are of the type DLTree*.
59 Later on the appropriate classes from tDlExpression.h
60
61 As a transition step, the intermediate structure is introduced.
62 */
63
64 /// general expression
65 typedef const TDLExpression TExpr;
66 /// concept expression
67 typedef const TDLConceptExpression TConceptExpr;
68 /// individual expression
69 typedef const TDLIndividualExpression TIndividualExpr;
70 /// role expression
71 typedef const TDLRoleExpression TRoleExpr;
72 /// object role complex expression (including role chains and projections)
73 typedef const TDLObjectRoleComplexExpression TORoleComplexExpr;
74 /// object role expression
75 typedef const TDLObjectRoleExpression TORoleExpr;
76 /// data role expression
77 typedef const TDLDataRoleExpression TDRoleExpr;
78 /// data expression
79 typedef const TDLDataExpression TDataExpr;
80 /// data type expression
81 typedef TDLDataTypeExpression TDataTypeExpr;
82 /// data value expression
83 typedef const TDLDataValue TDataValueExpr;
84 /// data facet expression
85 typedef const TDLFacetExpression TFacetExpr;
86
87 // name sets
88
89 /// set of arbitrary named expressions
90 typedef std::vector<const TNamedEntry*> NamesVector;
91 // IndividualSet is just set of named individual expressions
92 typedef NamesVector IndividualSet;
93
94 /// typedef for intermediate instance related type
95 typedef TRelatedMap::CIVec CIVec;
96
97 // types for knowledge exploration
98
99 /// type for the node in the completion graph
100 typedef KnowledgeExplorer::TCGNode TCGNode;
101 /// type for the node vector
102 typedef KnowledgeExplorer::TCGNodeVec TCGNodeVec;
103 /// type for a set of role expressions (used in KE to return stuff)
104 typedef KnowledgeExplorer::TCGRoleSet TCGRoleSet;
105 /// type for a vector of data/concept expressions (used in KE to return stuff)
106 typedef KnowledgeExplorer::TCGItemVec TCGItemVec;
107
108 protected: // types
109 /// arguments for property chain querying and friends
110 typedef const std::vector<const TDLExpression*> TExprVec;
111 /// names to module signature map
112 typedef TBox::NameSigMap NameSigMap;
113
114 public: // members
115 /// options for the kernel and all related substructures
116 ifOptionSet KernelOptions;
117
118 private: // constants
119 static const char* Version;
120 static const char* SupportedDL;
121 static const char* Copyright;
122 static const char* ReleaseDate;
123 /// header of the file with internal state; defined in SaveLoad.cpp
124 static const char* InternalStateFileHeader;
125
126 protected: // types
127 /// enumeration for the cache
128 enum cacheStatus { csEmpty, csSat, csClassified };
129
130 protected: // members
131 /// local TBox (to be created)
132 TBox* pTBox = nullptr;
133 /// set of axioms
134 TOntology Ontology;
135 /// expression translator to work with queries
136 TExpressionTranslator* pET = nullptr;
137 /// name-signature map
138 NameSigMap Name2Sig;
139 /// ontology signature (used in incremental)
140 TSignature OntoSig;
141 /// trace vector for the last operation (set from the TBox trace-sets)
142 AxiomVec TraceVec;
143 /// knowledge exploration support
144 KnowledgeExplorer* KE = nullptr;
145 /// atomic decomposer
146 AtomicDecomposer* AD = nullptr;
147 /// syntactic locality based module extractor
148 OntologyBasedModularizer* ModSyn = nullptr;
149 /// syntactic with counting locality based module extractor
150 OntologyBasedModularizer* ModSynCount = nullptr;
151 /// semantic locality based module extractor
152 OntologyBasedModularizer* ModSem = nullptr;
153 /// set to return by the locality checking procedure
154 AxiomVec Result;
155 /// JNI cache corresponding to a kernel. External, created and deleted outside
156 TJNICache* JNICache = nullptr;
157 /// name of an S/L context. do nothing if empty
158 SaveLoadManager* pSLManager = nullptr;
159
160 // Top/Bottom role names: if set, they will appear in all hierarchy-related output
161
162 /// top object role name
163 std::string TopORoleName;
164 /// bottom object role name
165 std::string BotORoleName;
166 /// top data role name
167 std::string TopDRoleName;
168 /// bottom data role name
169 std::string BotDRoleName;
170
171 // values to propagate to the new KB in case of clearance
172
173 /// progress monitor (if any)
174 TProgressMonitor* pMonitor = nullptr;
175 /// timeout value
176 unsigned long OpTimeout = 0;
177 /// tell reasoner to use verbose output
178 bool verboseOutput = false;
179 /// allow reasoner to use undefined names in queries
180 bool useUndefinedNames = true;
181
182 // reasoning cache
183
184 /// cache level
185 enum cacheStatus cacheLevel = csEmpty;
186 /// cached query input description
187 TConceptExpr* cachedQuery = nullptr;
188 /// cached query concept description
189 DLTree* cachedQueryTree = nullptr;
190 /// cached concept (either defConcept or existing one)
191 TConcept* cachedConcept = nullptr;
192 /// cached query result (taxonomy position)
193 TaxonomyVertex* cachedVertex = nullptr;
194
195 // internal flags
196
197 /// set if TBox throws an exception during preprocessing/classification
198 bool reasoningFailed = false;
199 /// flag to gather trace information for the next reasoner's call
200 bool NeedTracing = false;
201 /// ignore cache for the TExpr* (useful for semantic AD)
202 bool ignoreExprCache = false;
203 /// use incremental reasoning
204 bool useIncrementalReasoning = false;
205 /// flag to dump LISP-like ontology
206 bool dumpOntology = false;
207
208 protected: // methods
209
210 // register all necessary options in local option set
211 bool initOptions ( void );
212
213 /// get status of the KB
214 KBStatus getStatus ( void ) const
215 {
216 if ( pTBox == nullptr )
217 return kbEmpty;
218 // if the ontology is changed, it needs to be reclassified
219 if ( Ontology.isChanged() )
220 return kbLoading;
221 return pTBox->getStatus();
222 }
223 /// process KB wrt STATUS
224 void processKB ( KBStatus status );
225 /// classify/realise KB only if it is impossible to load results
226 void ClassifyOrLoad ( bool needIndividuals );
227
228 /// get DLTree corresponding to an expression EXPR
229 DLTree* e ( const TExpr* expr )
230 {
231 fpp_assert ( pET != nullptr );
232 expr->accept(*pET);
233 return *pET;
234 }
235 /// get fresh filled depending of a type of R
236 DLTree* getFreshFiller ( const TRole* R )
237 {
238 if ( R->isDataRole() )
239 return getTBox()->getDataTypeCenter().getFreshDataType();
240 else
241 return getTBox()->getFreshConcept();
242 }
243
244 //-----------------------------------------------------------------------------
245 //-- internal query cache manipulation
246 //-----------------------------------------------------------------------------
247
248 /// clear query cache
249 void clearQueryCache ( void )
250 {
251 // clear cached query
252 cachedQuery = nullptr;
253 deleteTree(cachedQueryTree);
254 cachedQueryTree = nullptr;
255 // clear the rest of cache
256 cacheLevel = csEmpty;
257 cachedConcept = nullptr;
258 cachedVertex = nullptr;
259 }
260 /// @return true if the cache is not set
261 bool isCacheEmpty ( void ) const { return (cachedQuery == nullptr) && (cachedQueryTree == nullptr); }
262 /// set query cache value to QUERY
263 void setQueryCache ( TConceptExpr* query ) { fpp_assert(isCacheEmpty()); cachedQuery = query; }
264 /// set query cache value to QUERY
265 void setQueryCache ( DLTree* query ) { fpp_assert(isCacheEmpty()); cachedQueryTree = query; }
266 /// check whether query cache is the same as QUERY
267 bool checkQueryCache ( TConceptExpr* query ) const { return ignoreExprCache ? false : cachedQuery == query; }
268 /// check whether query cache is the same as QUERY
269 bool checkQueryCache ( DLTree* query ) const { return ignoreExprCache ? false : equalTrees ( cachedQueryTree, query ); }
270 /// set the query concept
271 void setQueryConcept ( const DLTree* query )
272 { // setup cached concept depending on whether an entity is queries
273 cachedConcept = isCN(query) ? getTBox()->getCI(query) : getTBox()->createQueryConcept(query);
274 fpp_assert ( cachedConcept != nullptr );
275 // preprocess concept is necessary (fresh concept in query or complex one)
276 if ( !isValid(cachedConcept->pName) )
277 getTBox()->preprocessQueryConcept(cachedConcept);
278 }
279 /// classify query; cache is ready at the point
280 void classifyQuery ( void );
281 /// set up cache for sat query
282 void setUpSatCache ( DLTree* query );
283 /// set up cache for query, performing additional (re-)classification if necessary
284 void setUpCache ( TConceptExpr* query, cacheStatus level );
285 /// clear cache and flags
286 void initCacheAndFlags ( void )
287 {
288 clearQueryCache();
289 NeedTracing = false;
290 }
291
292 /// build and set a cache for an individual I wrt role R
293 CIVec buildRelatedCache ( TIndividual* I, const TRole* R );
294 /// get related cache for an individual I
295 const CIVec& getRelated ( TIndividual* I, const TRole* R )
296 {
297 if ( !I->hasRelatedCache(R) )
298 I->setRelatedCache ( R, buildRelatedCache ( I, R ) );
299 return I->getRelatedCache(R);
300 }
301
302 /// get role expression based on the R
303 TDLRoleExpression* Role ( const TRole* R )
304 {
305 if ( unlikely(R->isDataRole()) )
306 return getExpressionManager()->DataRole(R->getName());
307 else
308 return getExpressionManager()->ObjectRole(R->getName());
309 }
310
311 //-----------------------------------------------------------------------------
312 //-- internal reasoning methods
313 //-----------------------------------------------------------------------------
314
315 /// @return true iff C is satisfiable
316 bool checkSatTree ( DLTree* C )
317 {
318 if ( unlikely(C->Element().getToken() == TOP) )
319 {
320 deleteTree(C);
321 return true;
322 }
323 if ( unlikely(C->Element().getToken() == BOTTOM) )
324 {
325 deleteTree(C);
326 return false;
327 }
328 setUpSatCache(C);
329 return getTBox()->isSatisfiable(cachedConcept);
330 }
331 /// @return true iff C is satisfiable
332 bool checkSat ( const TConceptExpr* C )
333 {
334 setUpCache ( C, csSat );
335 return getTBox()->isSatisfiable(cachedConcept);
336 }
337 /// @return true iff C [= D holds
338 bool checkSub ( TConcept* C, TConcept* D );
339 /// helper; @return true iff C is either named concept of Top/Bot
340 static bool isNameOrConst ( const TConceptExpr* C )
341 {
342 return likely ( dynamic_cast<const TDLConceptName*>(C) != nullptr ) ||
343 unlikely ( dynamic_cast<const TDLConceptTop*>(C) != nullptr ) ||
344 unlikely ( dynamic_cast<const TDLConceptBottom*>(C) != nullptr );
345 }
346
347 // helper methods to query properties of roles
348
349 /// @return true if R is functional wrt ontology
350 bool checkFunctionality ( TRole* R )
351 {
352 // R is transitive iff \ER.C and \ER.\not C is unsatisfiable
353 DLTree* tmp = createSNFExists ( createRole(R), createSNFNot(getFreshFiller(R)) );
354 tmp = createSNFAnd ( tmp, createSNFExists ( createRole(R), getFreshFiller(R) ) );
355 return !checkSatTree(tmp);
356 }
357 /// @return true if R is functional; set the value for R if necessary
358 bool getFunctionality ( TRole* R )
359 {
360 if ( !R->isFunctionalityKnown() ) // calculate functionality
361 R->setFunctional(checkFunctionality(R));
362 return R->isFunctional();
363 }
364 /// @return true if R is transitive wrt ontology
365 bool checkTransitivity ( DLTree* R )
366 {
367 // R is transitive iff \ER.\ER.C and \AR.\not C is unsatisfiable
368 DLTree* tmp = createSNFExists ( clone(R), createSNFNot(getTBox()->getFreshConcept()) );
369 tmp = createSNFExists ( clone(R), tmp );
370 tmp = createSNFAnd ( tmp, createSNFForall ( R, getTBox()->getFreshConcept() ) );
371 return !checkSatTree(tmp);
372 }
373 /// @return true if R is symmetric wrt ontology
374 bool checkSymmetry ( DLTree* R )
375 {
376 // R is symmetric iff C and \ER.\AR.(not C) is unsatisfiable
377 DLTree* tmp = createSNFForall ( clone(R), createSNFNot(getTBox()->getFreshConcept()) );
378 tmp = createSNFAnd ( getTBox()->getFreshConcept(), createSNFExists ( R, tmp ) );
379 return !checkSatTree(tmp);
380 }
381 /// @return true if R is reflexive wrt ontology
382 bool checkReflexivity ( DLTree* R )
383 {
384 // R is reflexive iff C and \AR.(not C) is unsatisfiable
385 DLTree* tmp = createSNFForall ( R, createSNFNot(getTBox()->getFreshConcept()) );
386 tmp = createSNFAnd ( getTBox()->getFreshConcept(), tmp );
387 return !checkSatTree(tmp);
388 }
389 /// @return true if R [= S wrt ontology
390 bool checkRoleSubsumption ( TRole* R, TRole* S )
391 {
392 if ( unlikely ( R->isDataRole() != S->isDataRole() ) )
393 return false;
394 // R [= S iff \ER.C and \AS.(not C) is unsatisfiable
395 DLTree* tmp = createSNFForall ( createRole(S), createSNFNot(getFreshFiller(S)) );
396 tmp = createSNFAnd ( createSNFExists ( createRole(R), getFreshFiller(R) ), tmp );
397 return !checkSatTree(tmp);
398 }
399 /// @return true iff the chain contained in the arg-list is a sub-property of R
400 bool checkSubChain ( const TExprVec& Chain, TRole* R )
401 {
402 // R1 o ... o Rn [= R iff \ER1.\ER2....\ERn.(notC) and AR.C is unsatisfiable
403 DLTree* tmp = createSNFNot(getTBox()->getFreshConcept());
404 for ( TExprVec::const_reverse_iterator p = Chain.rbegin(), p_end = Chain.rend(); p != p_end; ++p )
405 if ( TORoleExpr* Ri = dynamic_cast<TORoleExpr*>(*p) )
406 {
407 TRole* S = getRole ( Ri, "Role expression expected in chain of isSubChain()" );
408 if ( unlikely(S->isBottom()) ) // bottom in a chain makes it super of any role
409 {
410 deleteTree(tmp);
411 return true;
412 }
413 tmp = createSNFExists ( createRole(S), tmp );
414 }
415 else
416 throw EFaCTPlusPlus("Role expression expected in the role chain construct");
417
418 tmp = createSNFAnd ( tmp, createSNFForall ( createEntry(RNAME,R), getTBox()->getFreshConcept() ) );
419 return !checkSatTree(tmp);
420 }
421
422 // get access to internal structures
423
424 /// @throw an exception if no TBox found
425 void checkTBox ( void ) const
426 {
427 if ( pTBox == nullptr )
428 throw EFaCTPlusPlus("FaCT++ Kernel: KB Not Initialised");
429 }
430 /// clear TBox and related structures; keep ontology in place
431 void clearTBox ( void );
432
433 /// get RW access to Object RoleMaster from TBox
434 RoleMaster& getORM ( void ) { return getTBox()->getORM(); }
435 /// get RO access to Object RoleMaster from TBox
436 const RoleMaster& getORM ( void ) const { return getTBox()->getORM(); }
437 /// get RW access to Data RoleMaster from TBox
438 RoleMaster& getDRM ( void ) { return getTBox()->getDRM(); }
439 /// get RO access to Data RoleMaster from TBox
440 const RoleMaster& getDRM ( void ) const { return getTBox()->getDRM(); }
441
442 /// get access to the concept hierarchy
443 Taxonomy* getCTaxonomy ( void )
444 {
445 // if ( !isKBClassified() )
446 // throw EFaCTPlusPlus("No access to concept taxonomy: ontology not classified");
447 return getTBox()->getTaxonomy();
448 }
449 /// get access to the object role hierarchy
450 Taxonomy* getORTaxonomy ( void )
451 {
452 if ( !isKBPreprocessed() )
453 throw EFaCTPlusPlus("No access to the object role taxonomy: ontology not preprocessed");
454 return getORM().getTaxonomy();
455 }
456 /// get access to the data role hierarchy
457 Taxonomy* getDRTaxonomy ( void )
458 {
459 if ( !isKBPreprocessed() )
460 throw EFaCTPlusPlus("No access to the data role taxonomy: ontology not preprocessed");
461 return getDRM().getTaxonomy();
462 }
463
464 // transformation methods
465
466 /// get concept by the TConceptExpr
467 TConcept* getConcept ( const TConceptExpr* i, const char* reason )
468 {
469 try { return static_cast<TConcept*>(getTBox()->getCI(TreeDeleter(e(i)))); }
470 catch(...) { throw EFaCTPlusPlus(reason); }
471 }
472 /// get individual by the TIndividualExpr
473 TIndividual* getIndividual ( const TIndividualExpr* i, const char* reason )
474 {
475 try { return static_cast<TIndividual*>(getTBox()->getCI(TreeDeleter(e(i)))); }
476 catch(...) { throw EFaCTPlusPlus(reason); }
477 }
478 /// get role by the TRoleExpr
479 TRole* getRole ( const TRoleExpr* r, const char* reason )
480 {
481 try { return resolveRole(TreeDeleter(e(r))); }
482 catch(...) { throw EFaCTPlusPlus(reason); }
483 }
484
485 /// get taxonomy of the property wrt it's name
486 Taxonomy* getTaxonomy ( TRole* R )
487 {
488 return R->isDataRole() ? getDRTaxonomy() : getORTaxonomy();
489 }
490 /// get taxonomy vertex of the property wrt it's name
491 TaxonomyVertex* getTaxVertex ( TRole* R )
492 {
493 return R->getTaxVertex();
494 }
495
496 /// check whether it is necessary to reload the ontology
497 bool needForceReload ( void ) const;
498 /// force the re-classification of the changed ontology
499 void forceReload ( void );
500
501 //----------------------------------------------
502 //-- incremental reasoning support; implementation in Incremental.cpp
503 //----------------------------------------------
504
505 /// setup Name2Sig for a given ENTITY
506 void setupSig ( const TNamedEntity* entity, const AxiomVec& Module );
507 /// setup Name2Sig for a given ENTITY
508 void setupSig ( const TNamedEntity* entity ) { setupSig ( entity, Ontology.getAxioms() ); }
509 /// build signature for ENTITY and all dependent entities from toProcess; look for modules in Module;
510 void buildSignature ( const TNamedEntity* entity, const AxiomVec& Module, std::set<const TNamedEntity*>& toProcess );
511 /// initialise the incremental bits on full reload
512 void initIncremental ( void );
513 /// incrementally classify changes
514 void doIncremental ( void );
515
516 //----------------------------------------------
517 //-- save/load support; implementation in SaveLoad.cpp
518 //----------------------------------------------
519
520 /// save the header of the kernel
521 void SaveHeader ( SaveLoadManager& m ) const;
522 /// save the set of Kernel's options
523 void SaveOptions ( SaveLoadManager& m ) const;
524 /// save the status of the KB and the appropriate part of KB
525 void SaveKB ( SaveLoadManager& m );
526 /// save incremental
527 void SaveIncremental ( SaveLoadManager& m ) const;
528 /// load the header for the kernel
529 void LoadHeader ( SaveLoadManager& m );
530 /// load the set of Kernel's options
531 void LoadOptions ( SaveLoadManager& m );
532 /// load the status of the KB and the appropriate part of KB
533 void LoadKB ( SaveLoadManager& m );
534 /// load incremental
535 void LoadIncremental ( SaveLoadManager& m );
536 /// save internal state of the Kernel to a file NAME
537 void Save ( SaveLoadManager& m );
538 /// load internal state of the Kernel from a file NAME
539 void Load ( SaveLoadManager& m );
540 /// save internal state of the Kernel using S/L Manager
541 void Save ( void );
542 /// load internal state of the Kernel using S/L Manager
543 void Load ( void );
544
545 //----------------------------------------------------------------------------------
546 // knowledge exploration queries
547 //----------------------------------------------------------------------------------
548
549 /// @return a pointer to a modularizer according to given method
550 OntologyBasedModularizer*& getModPointer ( ModuleMethod moduleMethod )
551 {
552 switch ( moduleMethod )
553 {
554 case SYN_LOC_STD: return ModSyn;
555 case SYN_LOC_COUNT: return ModSynCount;
556 case SEM_LOC: return ModSem;
557 default: fpp_unreachable();
558 }
559 }
560 /// check whether the modularizer need initialisation, init it and return a proper one
561 OntologyBasedModularizer* getModExtractor ( ModuleMethod moduleMethod );
562
563 public: // interface
564 /// default c'tor
565 ReasoningKernel ( void );
566 /// no copy c'tor
567 ReasoningKernel ( const ReasoningKernel& ) = delete;
568 /// no assignment
569 ReasoningKernel& operator = ( const ReasoningKernel& ) = delete;
570 /// d'tor
571 ~ReasoningKernel();
572
573 ifOptionSet* getOptions ( void ) { return &KernelOptions; }
574 const ifOptionSet* getOptions ( void ) const { return &KernelOptions; }
575
576 static const char* getVersion ( void ) { return Version; }
577
578 /// return classification status of KB
579 bool isKBPreprocessed ( void ) const { return getStatus() >= kbCChecked; }
580 /// return classification status of KB
581 bool isKBClassified ( void ) const { return getStatus() >= kbClassified; }
582 /// return realisation status of KB
583 bool isKBRealised ( void ) const { return getStatus() >= kbRealised; }
584
585 /// set Progress monitor to control the classification process
586 void setProgressMonitor ( TProgressMonitor* pMon )
587 {
588 delete pMonitor;
589 pMonitor = pMon;
590 if ( pTBox != nullptr )
591 pTBox->setProgressMonitor(pMon);
592 }
593 /// set verbose output (ie, concept and role taxonomies) wrt given VALUE
594 void setVerboseOutput ( bool value )
595 {
596 verboseOutput = value;
597 if ( pTBox != nullptr )
598 pTBox->setVerboseOutput(value);
599 }
600 /// (dis-)allow reasoner to use the undefined names in queries
601 void setUseUndefinedNames ( bool value )
602 {
603 useUndefinedNames = value;
604 if ( pTBox != nullptr )
605 pTBox->setUseUndefinedNames(value);
606 }
607
608 TaxonomyVertex *setUpCache ( const TConceptExpr *C )
609 {
610 realiseKB(); // ensure KB is ready to answer the query
611 setUpCache ( C, csClassified );
612 return cachedVertex;
613 }
614
615 /// set top/bottom role names to use them in the related output
616 void setTopBottomRoleNames ( const char* topORoleName, const char* botORoleName, const char* topDRoleName, const char* botDRoleName )
617 {
618 TopORoleName = topORoleName;
619 BotORoleName = botORoleName;
620 TopDRoleName = topDRoleName;
621 BotDRoleName = botDRoleName;
622 // make sure expression manager knows the top/bot names
623 Ontology.getExpressionManager()->setTopBottomRoles ( topORoleName, botORoleName,topDRoleName, botDRoleName );
624 }
625
626 /// dump query processing TIME, reasoning statistics and a (preprocessed) TBox
627 void writeReasoningResult ( std::ostream& o, float time )
628 {
629 getTBox()->clearQueryConcept(); // get rid of the query leftovers
630 getTBox()->writeReasoningResult ( o, time );
631 }
632
633 /// set timeout value to VALUE
634 void setOperationTimeout ( unsigned long value )
635 {
636 OpTimeout = value;
637 if ( pTBox != nullptr )
638 pTBox->setTestTimeout(value);
639 }
640 /// choose whether TExpr cache should be ignored
641 void setIgnoreExprCache ( bool value ) { ignoreExprCache = value; }
642 /// choose whether incremental reasoning should be used
643 void setUseIncrementalReasoning ( bool value ) { useIncrementalReasoning = value; }
644 /// set the signature of the expression translator
645 void setSignature ( const TSignature* sig ) { if ( pET != nullptr ) pET->setSignature(sig); }
646 /// choose whether the loaded ontology should be dumped as a LISP one
647 void setDumpOntology ( bool value ) { dumpOntology = value; }
648
649 /// dump ontology as a LISP one
650 void dumpLISP ( std::ostream& );
651
652 //----------------------------------------------
653 //-- Tracing support
654 //----------------------------------------------
655
656 /// tells reasoner that the next reasoning operation shall gather the trace
657 void needTracing ( void ) { NeedTracing = true; }
658 /// @return the trace-set of the last reasoning operation
659 const AxiomVec& getTrace ( void )
660 {
661 TraceVec.clear();
662 return TraceVec;
663 }
664
665 /// get access to an expression manager
666 TExpressionManager* getExpressionManager ( void ) { return Ontology.getExpressionManager(); }
667 /// get RW access to the ontology
668 TOntology& getOntology ( void ) { return Ontology; }
669 /// get RO access to the ontology
670 const TOntology& getOntology ( void ) const { return Ontology; }
671
672 /// set JNI cache
673 void setJNICache ( TJNICache* cache ) { JNICache = cache; }
674 /// get JNI cache
675 TJNICache* getJNICache ( void ) const { return JNICache; }
676
677 public:
678 //******************************************
679 //* KB Management
680 //******************************************
681
682 /// create new KB
683 bool newKB ( void )
684 {
685 if ( pTBox != nullptr )
686 return true;
687
688 pTBox = new TBox ( getOptions(), TopORoleName, BotORoleName, TopDRoleName, BotDRoleName );
689 pTBox->setTestTimeout(OpTimeout);
690 pTBox->setProgressMonitor(pMonitor);
691 pTBox->setVerboseOutput(verboseOutput);
692 pTBox->setUseUndefinedNames(useUndefinedNames);
693 pET = new TExpressionTranslator(*pTBox);
694 initCacheAndFlags();
695 return false;
696 }
697 /// delete existed KB
698 bool releaseKB ( void )
699 {
700 clearTBox();
701 Ontology.clear();
702 // the new KB is coming so the failures of the precious one doesn't matter
703 reasoningFailed = false;
704
705 return false;
706 }
707 /// reset current KB
708 bool clearKB ( void )
709 {
710 if ( pTBox == nullptr )
711 return true;
712 return releaseKB () || newKB ();
713 }
714
715 /// get RW access to TBox
716 TBox* getTBox(void)
717 {
718 checkTBox(); return pTBox;
719 }
720 /// get RO access to TBox
721 const TBox* getTBox(void) const
722 {
723 checkTBox(); return pTBox;
724 }
725
726 //----------------------------------------------------
727 // TELLS interface
728 //----------------------------------------------------
729
730 // Declaration axioms
731
732 /// axiom declare(x)
733 TDLAxiom* declare ( TExpr* C ) { return Ontology.add(new TDLAxiomDeclaration(C)); }
734
735 // Concept axioms
736
737 /// axiom C [= D
738 TDLAxiom* impliesConcepts ( TConceptExpr* C, TConceptExpr* D )
739 { return Ontology.add ( new TDLAxiomConceptInclusion ( C, D ) ); }
740 /// axiom C1 = ... = Cn
741 TDLAxiom* equalConcepts ( void )
742 { return Ontology.add ( new TDLAxiomEquivalentConcepts(getExpressionManager()->getArgList()) ); }
743 /// axiom C1 != ... != Cn
744 TDLAxiom* disjointConcepts ( void )
745 { return Ontology.add ( new TDLAxiomDisjointConcepts(getExpressionManager()->getArgList()) ); }
746 /// axiom C = C1 or ... or Cn; C1 != ... != Cn
747 TDLAxiom* disjointUnion ( TConceptExpr* C )
748 { return Ontology.add ( new TDLAxiomDisjointUnion ( C, getExpressionManager()->getArgList() ) ); }
749
750
751 // Role axioms
752
753 /// R = Inverse(S)
754 TDLAxiom* setInverseRoles ( TORoleExpr* R, TORoleExpr* S )
755 { return Ontology.add ( new TDLAxiomRoleInverse(R,S) ); }
756 /// axiom (R [= S)
757 TDLAxiom* impliesORoles ( TORoleComplexExpr* R, TORoleExpr* S )
758 { return Ontology.add ( new TDLAxiomORoleSubsumption ( R, S ) ); }
759 /// axiom (R [= S)
760 TDLAxiom* impliesDRoles ( TDRoleExpr* R, TDRoleExpr* S )
761 { return Ontology.add ( new TDLAxiomDRoleSubsumption ( R, S ) ); }
762 /// axiom R1 = R2 = ...
763 TDLAxiom* equalORoles ( void )
764 { return Ontology.add ( new TDLAxiomEquivalentORoles(getExpressionManager()->getArgList()) ); }
765 /// axiom R1 = R2 = ...
766 TDLAxiom* equalDRoles ( void )
767 { return Ontology.add ( new TDLAxiomEquivalentDRoles(getExpressionManager()->getArgList()) ); }
768 /// axiom R1 != R2 != ...
769 TDLAxiom* disjointORoles ( void )
770 { return Ontology.add ( new TDLAxiomDisjointORoles(getExpressionManager()->getArgList()) ); }
771 /// axiom R1 != R2 != ...
772 TDLAxiom* disjointDRoles ( void )
773 { return Ontology.add ( new TDLAxiomDisjointDRoles(getExpressionManager()->getArgList()) ); }
774
775 /// Domain (R C)
776 TDLAxiom* setODomain ( TORoleExpr* R, TConceptExpr* C )
777 { return Ontology.add ( new TDLAxiomORoleDomain ( R, C ) ); }
778 /// Domain (R C)
779 TDLAxiom* setDDomain ( TDRoleExpr* R, TConceptExpr* C )
780 { return Ontology.add ( new TDLAxiomDRoleDomain ( R, C ) ); }
781 /// Range (R C)
782 TDLAxiom* setORange ( TORoleExpr* R, TConceptExpr* C )
783 { return Ontology.add ( new TDLAxiomORoleRange ( R, C ) ); }
784 /// Range (R E)
785 TDLAxiom* setDRange ( TDRoleExpr* R, TDataExpr* E )
786 { return Ontology.add ( new TDLAxiomDRoleRange ( R, E ) ); }
787
788 /// Transitive (R)
789 TDLAxiom* setTransitive ( TORoleExpr* R )
790 { return Ontology.add ( new TDLAxiomRoleTransitive(R) ); }
791 /// Reflexive (R)
792 TDLAxiom* setReflexive ( TORoleExpr* R )
793 { return Ontology.add ( new TDLAxiomRoleReflexive(R) ); }
794 /// Irreflexive (R): Domain(R) = \neg ER.Self
795 TDLAxiom* setIrreflexive ( TORoleExpr* R )
796 { return Ontology.add ( new TDLAxiomRoleIrreflexive(R) ); }
797 /// Symmetric (R): R [= R^-
798 TDLAxiom* setSymmetric ( TORoleExpr* R )
799 { return Ontology.add ( new TDLAxiomRoleSymmetric(R) ); }
800 /// Asymmetric (R): disjoint(R,R^-)
801 TDLAxiom* setAsymmetric ( TORoleExpr* R )
802 { return Ontology.add ( new TDLAxiomRoleAsymmetric(R) ); }
803 /// Functional (R)
804 TDLAxiom* setOFunctional ( TORoleExpr* R )
805 { return Ontology.add ( new TDLAxiomORoleFunctional(R) ); }
806 /// Functional (R)
807 TDLAxiom* setDFunctional ( TDRoleExpr* R )
808 { return Ontology.add ( new TDLAxiomDRoleFunctional(R) ); }
809 /// InverseFunctional (R)
810 TDLAxiom* setInverseFunctional ( TORoleExpr* R )
811 { return Ontology.add ( new TDLAxiomRoleInverseFunctional(R) ); }
812
813
814 // Individual axioms
815
816 /// axiom I e C
817 TDLAxiom* instanceOf ( TIndividualExpr* I, TConceptExpr* C )
818 { return Ontology.add ( new TDLAxiomInstanceOf(I,C) ); }
819 /// axiom <I,J>:R
820 TDLAxiom* relatedTo ( TIndividualExpr* I, TORoleExpr* R, TIndividualExpr* J )
821 { return Ontology.add ( new TDLAxiomRelatedTo(I,R,J) ); }
822 /// axiom <I,J>:\neg R
823 TDLAxiom* relatedToNot ( TIndividualExpr* I, TORoleExpr* R, TIndividualExpr* J )
824 { return Ontology.add ( new TDLAxiomRelatedToNot(I,R,J) ); }
825 /// axiom (value I A V)
826 TDLAxiom* valueOf ( TIndividualExpr* I, TDRoleExpr* A, TDataValueExpr* V )
827 { return Ontology.add ( new TDLAxiomValueOf(I,A,V) ); }
828 /// axiom <I,V>:\neg A
829 TDLAxiom* valueOfNot ( TIndividualExpr* I, TDRoleExpr* A, TDataValueExpr* V )
830 { return Ontology.add ( new TDLAxiomValueOfNot(I,A,V) ); }
831 /// same individuals
832 TDLAxiom* processSame ( void )
833 { return Ontology.add ( new TDLAxiomSameIndividuals(getExpressionManager()->getArgList()) ); }
834 /// different individuals
835 TDLAxiom* processDifferent ( void )
836 { return Ontology.add ( new TDLAxiomDifferentIndividuals(getExpressionManager()->getArgList()) ); }
837 /// let all concept expressions in the ArgQueue to be fairness constraints
838 TDLAxiom* setFairnessConstraint ( void )
839 { return Ontology.add ( new TDLAxiomFairnessConstraint(getExpressionManager()->getArgList()) ); }
840
841 /// retract an axiom
842 void retract ( TDLAxiom* axiom ) { Ontology.retract(axiom); }
843
844 //******************************************
845 //* ASK part
846 //******************************************
847
848 /*
849 * Before execution of any query the Kernel make sure that the KB is in an appropriate
850 * state: Preprocessed, Classified or Realised. If the ontology was changed between asks,
851 * incremental classification is performed and the corrected result is returned.
852 */
853
854 /// return consistency status of KB
855 bool isKBConsistent ( void )
856 {
857 try {
858 if ( getStatus() <= kbLoading )
859 processKB(kbCChecked);
860 return getTBox()->isConsistent();
861 }
862 catch ( const EFPPInconsistentKB& )
863 { return false; }
864 }
865 /// ensure that KB is preprocessed/consistence checked
866 void preprocessKB ( void )
867 {
868 if ( !isKBConsistent() )
869 throw EFPPInconsistentKB();
870 }
871 /// ensure that KB is classified
872 void classifyKB ( void )
873 {
874 if ( !isKBClassified() )
875 processKB(kbClassified);
876 if ( !isKBConsistent() )
877 throw EFPPInconsistentKB();
878 }
879 /// ensure that KB is realised
880 void realiseKB ( void )
881 {
882 if ( !isKBRealised() )
883 processKB(kbRealised);
884 if ( !isKBConsistent() )
885 throw EFPPInconsistentKB();
886 }
887
888 // role info retrieval
889
890 /// @return true iff object role is functional
891 bool isFunctional ( const TORoleExpr* R )
892 {
893 preprocessKB(); // ensure KB is ready to answer the query
894 TRole* r = getRole ( R, "Role expression expected in isFunctional()" );
895 if ( unlikely(r->isTop()) )
896 return false; // universal role is not functional
897 if ( unlikely(r->isBottom()) )
898 return true; // empty role is functional
899
900 return getFunctionality(r);
901 }
902 /// @return true iff data role is functional
903 bool isFunctional ( const TDRoleExpr* R )
904 {
905 preprocessKB(); // ensure KB is ready to answer the query
906 TRole* r = getRole ( R, "Role expression expected in isFunctional()" );
907 if ( unlikely(r->isTop()) )
908 return false; // universal role is not functional
909 if ( unlikely(r->isBottom()) )
910 return true; // empty role is functional
911
912 return getFunctionality(r);
913 }
914 /// @return true iff role is inverse-functional
915 bool isInverseFunctional ( const TORoleExpr* R )
916 {
917 preprocessKB(); // ensure KB is ready to answer the query
918 TRole* r = getRole ( R, "Role expression expected in isInverseFunctional()" )->inverse();
919 if ( unlikely(r->isTop()) )
920 return false; // universal role is not functional
921 if ( unlikely(r->isBottom()) )
922 return true; // empty role is functional
923
924 return getFunctionality(r);
925 }
926 /// @return true iff role is transitive
927 bool isTransitive ( const TORoleExpr* R )
928 {
929 preprocessKB(); // ensure KB is ready to answer the query
930 TRole* r = getRole ( R, "Role expression expected in isTransitive()" );
931 if ( unlikely(r->isTop()) )
932 return true; // universal role is transitive
933 if ( unlikely(r->isBottom()) )
934 return true; // empty role is transitive
935
936 if ( !r->isTransitivityKnown() ) // calculate transitivity
937 r->setTransitive(checkTransitivity(e(R)));
938 return r->isTransitive();
939 }
940 /// @return true iff role is symmetric
941 bool isSymmetric ( const TORoleExpr* R )
942 {
943 preprocessKB(); // ensure KB is ready to answer the query
944 TRole* r = getRole ( R, "Role expression expected in isSymmetric()" );
945 if ( unlikely(r->isTop()) )
946 return true; // universal role is symmetric
947 if ( unlikely(r->isBottom()) )
948 return true; // empty role is symmetric
949
950 if ( !r->isSymmetryKnown() ) // calculate symmetry
951 r->setSymmetric(checkSymmetry(e(R)));
952 return r->isSymmetric();
953 }
954 /// @return true iff role is asymmetric
955 bool isAsymmetric ( const TORoleExpr* R )
956 {
957 preprocessKB(); // ensure KB is ready to answer the query
958 TRole* r = getRole ( R, "Role expression expected in isAsymmetric()" );
959 if ( unlikely(r->isTop()) )
960 return false; // universal role is not asymmetric
961 if ( unlikely(r->isBottom()) )
962 return true; // empty role is asymmetric
963
964 if ( !r->isAsymmetryKnown() ) // calculate asymmetry
965 r->setAsymmetric(getTBox()->isDisjointRoles(r,r->inverse()));
966 return r->isAsymmetric();
967 }
968 /// @return true iff role is reflexive
969 bool isReflexive ( const TORoleExpr* R )
970 {
971 preprocessKB(); // ensure KB is ready to answer the query
972 TRole* r = getRole ( R, "Role expression expected in isReflexive()" );
973 if ( unlikely(r->isTop()) )
974 return true; // universal role is reflexive
975 if ( unlikely(r->isBottom()) )
976 return false; // empty role is not reflexive
977
978 if ( !r->isReflexivityKnown() ) // calculate reflexivity
979 r->setReflexive(checkReflexivity(e(R)));
980 return r->isReflexive();
981 }
982 /// @return true iff role is irreflexive
983 bool isIrreflexive ( const TORoleExpr* R )
984 {
985 preprocessKB(); // ensure KB is ready to answer the query
986 TRole* r = getRole ( R, "Role expression expected in isIrreflexive()" );
987 if ( unlikely(r->isTop()) )
988 return false; // universal role is not irreflexive
989 if ( unlikely(r->isBottom()) )
990 return true; // empty role is irreflexive
991
992 if ( !r->isIrreflexivityKnown() ) // calculate irreflexivity
993 r->setIrreflexive(getTBox()->isIrreflexive(r));
994 return r->isIrreflexive();
995 }
996 /// @return true if R is a sub-role of S
997 bool isSubRoles ( const TORoleExpr* R, const TORoleExpr* S )
998 {
999 preprocessKB(); // ensure KB is ready to answer the query
1000 TRole* r = getRole ( R, "Role expression expected in isSubRoles()" );
1001 TRole* s = getRole ( S, "Role expression expected in isSubRoles()" );
1002 if ( unlikely(r->isBottom()) || unlikely(s->isTop()) )
1003 return true; // \bot [= X [= \top
1004 if ( unlikely(r->isTop()) && unlikely(s->isBottom()) )
1005 return false; // as \top [= \bot leads to inconsistent ontology
1006
1007 // told case first
1008 if ( likely(!r->isTop() && !s->isBottom()) )
1009 {
1010 if ( *r <= *s )
1011 return true;
1012 }
1013 // check the general case
1014 // FIXME!! cache it later
1015 return checkRoleSubsumption ( r, s );
1016 }
1017 /// @return true if R is a sub-role of S
1018 bool isSubRoles ( const TDRoleExpr* R, const TDRoleExpr* S )
1019 {
1020 preprocessKB(); // ensure KB is ready to answer the query
1021 TRole* r = getRole ( R, "Role expression expected in isSubRoles()" );
1022 TRole* s = getRole ( S, "Role expression expected in isSubRoles()" );
1023 if ( unlikely(r->isBottom()) || unlikely(s->isTop()) )
1024 return true; // \bot [= X [= \top
1025 if ( unlikely(r->isTop()) && unlikely(s->isBottom()) )
1026 return false; // as \top [= \bot leads to inconsistent ontology
1027
1028 // told case first
1029 if ( likely(!r->isTop() && !s->isBottom()) )
1030 {
1031 if ( *r <= *s )
1032 return true;
1033 }
1034 // check the general case
1035 // FIXME!! cache it later
1036 return checkRoleSubsumption ( r, s );
1037 }
1038 /// @return true iff two roles are disjoint
1039 bool isDisjointRoles ( const TORoleExpr* R, const TORoleExpr* S )
1040 {
1041 preprocessKB(); // ensure KB is ready to answer the query
1042 TRole* r = getRole ( R, "Role expression expected in isDisjointRoles()" );
1043 TRole* s = getRole ( S, "Role expression expected in isDisjointRoles()" );
1044 if ( unlikely(r->isTop()) || unlikely(s->isTop()) )
1045 return false; // universal role is not disjoint with anything
1046 if ( unlikely(r->isBottom()) || unlikely(s->isBottom()) )
1047 return true; // empty role is disjoint with everything
1048 return getTBox()->isDisjointRoles ( r, s );
1049 }
1050 /// @return true iff two roles are disjoint
1051 bool isDisjointRoles ( const TDRoleExpr* R, const TDRoleExpr* S )
1052 {
1053 preprocessKB(); // ensure KB is ready to answer the query
1054 TRole* r = getRole ( R, "Role expression expected in isDisjointRoles()" );
1055 TRole* s = getRole ( S, "Role expression expected in isDisjointRoles()" );
1056 if ( unlikely(r->isTop()) || unlikely(s->isTop()) )
1057 return false; // universal role is not disjoint with anything
1058 if ( unlikely(r->isBottom()) || unlikely(s->isBottom()) )
1059 return true; // empty role is disjoint with everything
1060 return getTBox()->isDisjointRoles ( r, s );
1061 }
1062 /// @return true iff all the roles in a arg-list are pairwise disjoint
1063 bool isDisjointRoles ( void );
1064 /// @return true if R is a super-role of a chain holding in the args
1065 bool isSubChain ( const TORoleExpr* R )
1066 {
1067 preprocessKB(); // ensure KB is ready to answer the query
1068 TRole* r = getRole ( R, "Role expression expected in isSubChain()" );
1069 if ( unlikely(r->isTop()) )
1070 return true; // universal role is a super of any chain
1071 return checkSubChain ( getExpressionManager()->getArgList(), r );
1072 }
1073
1074 // single satisfiability
1075
1076 /// @return true iff C is satisfiable
1077 bool isSatisfiable ( const TConceptExpr* C )
1078 {
1079 preprocessKB();
1080 try { return checkSat(C); }
1081 catch ( const EFPPCantRegName& crn )
1082 {
1083 if ( dynamic_cast<const TDLConceptName*>(C) != nullptr ) // this is an unknown concept
1084 return true;
1085 // complex expression, involving unknown names
1086 throw crn;
1087 }
1088 }
1089 /// @return true iff C [= D holds
1090 bool isSubsumedBy ( const TConceptExpr* C, const TConceptExpr* D )
1091 {
1092 preprocessKB();
1093 if ( isNameOrConst(D) && likely(isNameOrConst(C)) )
1094 return checkSub ( getTBox()->getCI(TreeDeleter(e(C))), getTBox()->getCI(TreeDeleter(e(D))) );
1095 DLTree* nD = createSNFNot(e(D));
1096 return !checkSatTree ( createSNFAnd (e(C), nD) );
1097 }
1098 /// @return true iff C is disjoint with D; that is, (C and D) is unsatisfiable
1099 bool isDisjoint ( const TConceptExpr* C, const TConceptExpr* D ) { return !isSatisfiable(getExpressionManager()->And(C,D)); }
1100 /// @return true iff C is equivalent to D
1101 bool isEquivalent ( const TConceptExpr* C, const TConceptExpr* D )
1102 {
1103 if ( C == D ) // easy case
1104 return true;
1105 preprocessKB();
1106 if ( isKBClassified() )
1107 { // try to detect C=D wrt named concepts
1108 if ( isNameOrConst(D) && likely(isNameOrConst(C)) )
1109 {
1110 const TaxonomyVertex* cV = getTBox()->getCI(TreeDeleter(e(C)))->getTaxVertex();
1111 const TaxonomyVertex* dV = getTBox()->getCI(TreeDeleter(e(D)))->getTaxVertex();
1112 if ( unlikely(cV == nullptr) && unlikely(dV == nullptr) )
1113 return false; // 2 different fresh names
1114 return cV == dV;
1115 }
1116 }
1117 // not classified or not named constants
1118 return isSubsumedBy ( C, D ) && isSubsumedBy ( D, C );
1119 }
1120 // concept hierarchy
1121
1122 /// apply actor::apply() to all DIRECT super-concepts of [complex] C
1123 template <typename Actor>
1124 void getSupConcepts ( const TConceptExpr* C, bool direct, Actor& actor, bool needCurrent = false )
1125 {
1126 classifyKB(); // ensure KB is ready to answer the query
1127 setUpCache ( C, csClassified );
1128 actor.clear();
1129 Taxonomy* tax = getCTaxonomy();
1130 if (direct)
1131 if (needCurrent)
1132 tax->getRelativesInfo</*needCurrent=*/true, /*onlyDirect=*/true, /*upDirection=*/true>(cachedVertex, actor);
1133 else
1134 tax->getRelativesInfo</*needCurrent=*/false, /*onlyDirect=*/true, /*upDirection=*/true>(cachedVertex, actor);
1135 else
1136 if (needCurrent)
1137 tax->getRelativesInfo</*needCurrent=*/true, /*onlyDirect=*/false, /*upDirection=*/true>(cachedVertex, actor);
1138 else
1139 tax->getRelativesInfo</*needCurrent=*/false, /*onlyDirect=*/false, /*upDirection=*/true>(cachedVertex, actor);
1140 }
1141 /// apply actor::apply() to all DIRECT sub-concepts of [complex] C
1142 template <typename Actor>
1143 void getSubConcepts ( const TConceptExpr* C, bool direct, Actor& actor, bool needCurrent = false)
1144 {
1145 classifyKB(); // ensure KB is ready to answer the query
1146 setUpCache ( C, csClassified );
1147 actor.clear();
1148 Taxonomy* tax = getCTaxonomy();
1149 if (direct)
1150 if (needCurrent)
1151 tax->getRelativesInfo</*needCurrent=*/true, /*onlyDirect=*/true, /*upDirection=*/false>(cachedVertex, actor);
1152 else
1153 tax->getRelativesInfo</*needCurrent=*/false, /*onlyDirect=*/true, /*upDirection=*/false>(cachedVertex, actor);
1154 else
1155 if (needCurrent)
1156 tax->getRelativesInfo</*needCurrent=*/true, /*onlyDirect=*/false, /*upDirection=*/false>(cachedVertex, actor);
1157 else
1158 tax->getRelativesInfo</*needCurrent=*/false, /*onlyDirect=*/false, /*upDirection=*/false>(cachedVertex, actor);
1159 }
1160 /// apply actor::apply() to all synonyms of [complex] C
1161 template <typename Actor>
1162 void getEquivalentConcepts ( const TConceptExpr* C, Actor& actor )
1163 {
1164 classifyKB(); // ensure KB is ready to answer the query
1165 setUpCache ( C, csClassified );
1166 actor.clear();
1167 actor.apply(*cachedVertex);
1168 }
1169 /// apply actor::apply() to all named concepts disjoint with [complex] C
1170 template <typename Actor>
1171 void getDisjointConcepts ( const TConceptExpr* C, Actor& actor )
1172 {
1173 classifyKB(); // ensure KB is ready to answer the query
1174 setUpCache ( getExpressionManager()->Not(C), csClassified );
1175 actor.clear();
1176 Taxonomy* tax = getCTaxonomy();
1177 // we are looking for all sub-concepts of (not C) (including synonyms to it)
1178 tax->getRelativesInfo</*needCurrent=*/true, /*onlyDirect=*/false, /*upDirection=*/false> ( cachedVertex, actor );
1179 }
1180
1181 // role hierarchy
1182
1183 /// apply actor::apply() to all DIRECT super-roles of [complex] R
1184 template <typename Actor>
1185 void getSupRoles ( const TRoleExpr* r, bool direct, Actor& actor )
1186 {
1187 preprocessKB(); // ensure KB is ready to answer the query
1188 TRole* R = getRole ( r, "Role expression expected in getSupRoles()" );
1189 actor.clear();
1190 Taxonomy* tax = getTaxonomy(R);
1191 if ( direct )
1192 tax->getRelativesInfo</*needCurrent=*/false, /*onlyDirect=*/true, /*upDirection=*/true> ( getTaxVertex(R), actor );
1193 else
1194 tax->getRelativesInfo</*needCurrent=*/false, /*onlyDirect=*/false, /*upDirection=*/true> ( getTaxVertex(R), actor );
1195 }
1196 /// apply actor::apply() to all DIRECT sub-roles of [complex] R
1197 template <typename Actor>
1198 void getSubRoles ( const TRoleExpr* r, bool direct, Actor& actor )
1199 {
1200 preprocessKB(); // ensure KB is ready to answer the query
1201 TRole* R = getRole ( r, "Role expression expected in getSubRoles()" );
1202 actor.clear();
1203 Taxonomy* tax = getTaxonomy(R);
1204 if ( direct )
1205 tax->getRelativesInfo</*needCurrent=*/false, /*onlyDirect=*/true, /*upDirection=*/false> ( getTaxVertex(R), actor );
1206 else
1207 tax->getRelativesInfo</*needCurrent=*/false, /*onlyDirect=*/false, /*upDirection=*/false> ( getTaxVertex(R), actor );
1208 }
1209 /// apply actor::apply() to all synonyms of [complex] R
1210 template <typename Actor>
1211 void getEquivalentRoles ( const TRoleExpr* r, Actor& actor )
1212 {
1213 preprocessKB(); // ensure KB is ready to answer the query
1214 TRole* R = getRole ( r, "Role expression expected in getEquivalentRoles()" );
1215 actor.clear();
1216 actor.apply(*getTaxVertex(R));
1217 }
1218
1219 // domain and range as a set of named concepts
1220
1221 /// apply actor::apply() to all DIRECT NC that are in the domain of [complex] object role R
1222 template <typename Actor>
1223 void getORoleDomain ( const TORoleExpr* r, bool direct, Actor& actor )
1224 {
1225 classifyKB(); // ensure KB is ready to answer the query
1226 setUpCache ( getExpressionManager()->Exists ( r, getExpressionManager()->Top() ), csClassified );
1227 actor.clear();
1228 Taxonomy* tax = getCTaxonomy();
1229 if ( direct ) // gets an exact domain is named concept; otherwise, set of the most specific concepts
1230 tax->getRelativesInfo</*needCurrent=*/true, /*onlyDirect=*/true, /*upDirection=*/true> ( cachedVertex, actor );
1231 else // gets all named classes that are in the domain of a role
1232 tax->getRelativesInfo</*needCurrent=*/true, /*onlyDirect=*/false, /*upDirection=*/true> ( cachedVertex, actor );
1233 }
1234 /// apply actor::apply() to all DIRECT NC that are in the domain of data role R
1235 template <typename Actor>
1236 void getDRoleDomain ( const TDRoleExpr* r, bool direct, Actor& actor )
1237 {
1238 classifyKB(); // ensure KB is ready to answer the query
1239 setUpCache ( getExpressionManager()->Exists ( r, getExpressionManager()->DataTop() ), csClassified );
1240 actor.clear();
1241 Taxonomy* tax = getCTaxonomy();
1242 if ( direct ) // gets an exact domain is named concept; otherwise, set of the most specific concepts
1243 tax->getRelativesInfo</*needCurrent=*/true, /*onlyDirect=*/true, /*upDirection=*/true> ( cachedVertex, actor );
1244 else // gets all named classes that are in the domain of a role
1245 tax->getRelativesInfo</*needCurrent=*/true, /*onlyDirect=*/false, /*upDirection=*/true> ( cachedVertex, actor );
1246 }
1247 /// apply actor::apply() to all DIRECT NC that are in the range of [complex] R
1248 template <typename Actor>
1249 void getRoleRange ( const TORoleExpr* r, bool direct, Actor& actor )
1250 { getORoleDomain ( getExpressionManager()->Inverse(r), direct, actor ); }
1251
1252 // instances
1253
1254 /// apply actor::apply() to all direct instances of given [complex] C
1255 template <typename Actor>
1256 void getDirectInstances ( const TConceptExpr* C, Actor& actor )
1257 {
1258 realiseKB(); // ensure KB is ready to answer the query
1259 setUpCache ( C, csClassified );
1260 actor.clear();
1261
1262 // implement 1-level check by hand
1263
1264 // if the root vertex contains individuals -- we are done
1265 if ( actor.apply(*cachedVertex) )
1266 return;
1267
1268 // if not, just go 1 level down and apply the actor regardless of what's found
1269 // FIXME!! check again after bucket-method will be implemented
1270 for ( TaxonomyVertex::iterator p = cachedVertex->begin(/*upDirection=*/false),
1271 p_end = cachedVertex->end(/*upDirection=*/false); p != p_end; ++p )
1272 actor.apply(**p);
1273 }
1274
1275 /// apply actor::apply() to all instances of given [complex] C
1276 template <typename Actor>
1277 void getInstances ( const TConceptExpr* C, Actor& actor )
1278 { // FIXME!! check for Racer's/IS approach
1279 realiseKB(); // ensure KB is ready to answer the query
1280 setUpCache ( C, csClassified );
1281 actor.clear();
1282 Taxonomy* tax = getCTaxonomy();
1283 tax->getRelativesInfo</*needCurrent=*/true, /*onlyDirect=*/false, /*upDirection=*/false> ( cachedVertex, actor );
1284 }
1285
1286 /// apply actor::apply() to all DIRECT concepts that are types of an individual I
1287 template <typename Actor>
1288 void getTypes ( const TIndividualExpr* I, bool direct, Actor& actor )
1289 {
1290 realiseKB(); // ensure KB is ready to answer the query
1291 setUpCache ( getExpressionManager()->OneOf(I), csClassified );
1292 actor.clear();
1293 Taxonomy* tax = getCTaxonomy();
1294 if ( direct )
1295 tax->getRelativesInfo</*needCurrent=*/true, /*onlyDirect=*/true, /*upDirection=*/true> ( cachedVertex, actor );
1296 else
1297 tax->getRelativesInfo</*needCurrent=*/true, /*onlyDirect=*/false, /*upDirection=*/true> ( cachedVertex, actor );
1298 }
1299 /// apply actor::apply() to all synonyms of an individual I
1300 template <typename Actor>
1301 void getSameAs ( const TIndividualExpr* I, Actor& actor )
1302 {
1303 realiseKB(); // ensure KB is ready to answer the query
1304 getEquivalentConcepts ( getExpressionManager()->OneOf(I), actor );
1305 }
1306 /// @return true iff I and J refer to the same individual
1307 bool isSameIndividuals ( const TIndividualExpr* I, const TIndividualExpr* J )
1308 {
1309 realiseKB();
1310 TIndividual* i = getIndividual ( I, "Only known individuals are allowed in the isSameAs()" );
1311 TIndividual* j = getIndividual ( J, "Only known individuals are allowed in the isSameAs()" );
1312 return getTBox()->isSameIndividuals(i,j);
1313 }
1314 /// @return true iff individual I is instance of given [complex] C
1315 bool isInstance ( const TIndividualExpr* I, const TConceptExpr* C )
1316 {
1317 realiseKB(); // ensure KB is ready to answer the query
1318 getIndividual ( I, "individual name expected in the isInstance()" );
1319 // FIXME!! this way a new concept is created; could be done more optimal
1320 return isSubsumedBy ( getExpressionManager()->OneOf(I), C );
1321 }
1322 /// @return in Rs all (DATA)-roles R s.t. (I,x):R; add inverses if NEEDI is true
1323 void getRelatedRoles ( const TIndividualExpr* I, NamesVector& Rs, bool data, bool needI );
1324 /// set RESULT into set of J's such that R(I,J)
1325 void getRoleFillers ( const TIndividualExpr* I, const TORoleExpr* R, IndividualSet& Result );
1326 const CIVec& getRoleFillers ( const TIndividualExpr* I, const TORoleExpr* R);
1327 /// @return true iff R(I,J) holds
1328 bool isRelated ( const TIndividualExpr* I, const TORoleExpr* R, const TIndividualExpr* J );
1329 /// @return true iff A(I,V) holds
1330 bool isRelated ( const TIndividualExpr* I, const TDRoleExpr* A, const TDataValueExpr* V );
1331
1332 /// set RESULT into set of individuals such that they do have data roles R and S, and R op S
1333 void getDataRelatedIndividuals ( TDRoleExpr* R, TDRoleExpr* S, int op, IndividualSet& Result );
1334
1335 TDLConceptExpression* parseConcept(const std::string& name);
1336 TDLObjectRoleExpression* parseObjectRole(const std::string& name);
1337 TDLDataRoleExpression* parseDataRole(const std::string& name);
1338 const TConcept* getConcept(TDLIndividualName* i_exp, TDLConceptExpression* c_exp);
1339 const TRole* getRole(TDLObjectRoleExpression* o_exp, TDLDataRoleExpression* d_exp);
1340 const char* getXsdType(const TDataEntry* dataValue) const;
1341 void getTriples(const std::string& q_subj_name, const std::string& q_role_name, const std::string& q_obj_name, std::set<std::vector<std::string>>& triples);
1342
1343 //----------------------------------------------------------------------------------
1344 // knowledge exploration queries
1345 //----------------------------------------------------------------------------------
1346
1347 /// build a completion tree for a concept expression C (no caching as it breaks the idea of KE). @return the root node
1348 const TCGNode* buildCompletionTree ( const TConceptExpr* C )
1349 {
1350 preprocessKB();
1351 setUpCache ( C, csSat );
1352 const TCGNode* ret = getTBox()->buildCompletionTree(cachedConcept);
1353 if ( KE == nullptr ) // init KB after the sat test to reduce the number of DAG adjustments
1354 KE = new KnowledgeExplorer ( getTBox(), getExpressionManager() );
1355 return ret;
1356 }
1357 /// build the set of data neighbours of a NODE, put the set of data roles into the RESULT variable
1358 void getDataRoles ( const TCGNode* node, TCGRoleSet& Result, bool onlyDet ) { Result = KE->getDataRoles ( node, onlyDet ); }
1359 /// build the set of object neighbours of a NODE, put the set of object roles and inverses into the RESULT variable
1360 void getObjectRoles ( const TCGNode* node, TCGRoleSet& Result, bool onlyDet, bool needIncoming ) { Result = KE->getObjectRoles ( node, onlyDet, needIncoming ); }
1361 /// build the set of neighbours of a NODE via role ROLE; put the resulting list into RESULT
1362 void getNeighbours ( const TCGNode* node, TRoleExpr* role, TCGNodeVec& Result )
1363 { Result = KE->getNeighbours ( node, getRole ( role, "Role expression expected in getNeighbours() method" ) ); }
1364 /// put into RESULT all the expressions from the NODE label; if ONLYDET is true, return only deterministic elements
1365 void getLabel ( const TCGNode* node, TCGItemVec& Result, bool onlyDet ) { Result = KE->getLabel ( node, onlyDet ); }
1366 /// @return blocker of a blocked node NODE or NULL if node is not blocked
1367 const TCGNode* getBlocker ( const TCGNode* node ) const { return KE->getBlocker(node); }
1368
1369 //----------------------------------------------------------------------------------
1370 // atomic decomposition queries
1371 //----------------------------------------------------------------------------------
1372
1373 /// create new atomic decomposition of the loaded ontology using TYPE. @return size of the AD
1374 size_t getAtomicDecompositionSize ( ModuleMethod moduleMethod, ModuleType moduleType );
1375 /// get a set of axioms that corresponds to the atom with the id INDEX
1376 const TOntologyAtom::AxiomSet& getAtomAxioms ( unsigned int index ) const;
1377 /// get a set of axioms that corresponds to the module of the atom with the id INDEX
1378 const TOntologyAtom::AxiomSet& getAtomModule ( unsigned int index ) const;
1379 /// get a set of atoms on which atom with index INDEX depends
1380 const TOntologyAtom::AtomSet& getAtomDependents ( unsigned int index ) const;
1381 /// get a number of locality checks performed for creating an AD
1382 unsigned long long getLocCheckNumber ( void ) const;
1383
1384 //----------------------------------------------------------------------------------
1385 // modularity queries
1386 //----------------------------------------------------------------------------------
1387
1388 /// get a module of an ontology wrt given method.
1389 const AxiomVec& getModule ( ModuleMethod moduleMethod, ModuleType moduleType );
1390 /// get a set of non-local axioms of an ontology wrt given method.
1391 const AxiomVec& getNonLocal ( ModuleMethod moduleMethod, ModuleType moduleType );
1392
1393 //----------------------------------------------------------------------------------
1394 // save/load interface
1395 //----------------------------------------------------------------------------------
1396
1397 /// check whether @return true if a file with reasoner state with a given NAME exists.
1398 bool checkSaveLoadContext ( const std::string& name ) const;
1399 /// set a save/load file to a given NAME
1400 bool setSaveLoadContext ( const std::string& name );
1401 /// clear a cache for a given name
1402 bool clearSaveLoadContext ( const std::string& name ) const;
1403 }; // ReasoningKernel
1404
1405 #endif