Debian Codegraph @

FaCT++.Python/lib/Kernel/dlTBox.cpp

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 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
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 #include "dlTBox.h"
21
22 #include <fstream>
23
24 #include "cppi.h"
25
26 #include "globaldef.h"
27 #include "ReasonerNom.h"
28 #include "DLConceptTaxonomy.h"
29 #include "procTimer.h"
30 #include "dumpLisp.h"
31 #include "logging.h"
32
33 // uncomment the following line to print currently checking subsumption
34 //#define FPP_DEBUG_PRINT_CURRENT_SUBSUMPTION
35
36 TBox :: TBox ( const ifOptionSet* Options, const std::string& TopORoleName, const std::string& BotORoleName, const std::string& TopDRoleName, const std::string& BotDRoleName )
37 : DLHeap(Options)
38 , pOptions (Options)
39 , Concepts("concept")
40 , Individuals("individual")
41 , ORM ( /*data=*/false, TopORoleName, BotORoleName )
42 , DRM ( /*data=*/true, TopDRoleName, BotDRoleName )
43 , Axioms(*this)
44 {
45 readConfig ( Options );
46 initTopBottom ();
47
48 setForbidUndefinedNames(false);
49 }
50
51 TBox :: ~TBox()
52 {
53 // remove all RELATED structures
54 for ( RelatedCollection::iterator p = RelatedI.begin(), p_end = RelatedI.end(); p < p_end; ++p )
55 delete *p;
56
57 // remove all simple rules
58 for ( TSimpleRules::iterator q = SimpleRules.begin(), q_end = SimpleRules.end(); q < q_end; ++q )
59 delete *q;
60
61 // empty R-C cache
62 for ( TRCCache::iterator r = RCCache.begin(), r_end = RCCache.end(); r < r_end; ++r )
63 deleteTree(r->first);
64
65 // remove all concepts
66 delete pTop;
67 delete pBottom;
68 delete pTemp;
69 delete pQuery;
70
71 // remove aux structures
72 delete stdReasoner;
73 delete nomReasoner;
74 delete pTax;
75 delete pTaxCreator;
76 }
77
78 /// get unique aux concept
79 TConcept* TBox :: getAuxConcept ( DLTree* desc )
80 {
81 std::string name {" aux"};
82 name += std::to_string(++auxConceptID);
83 bool old = setForbidUndefinedNames(false);
84 TConcept* C = getConcept(name);
85 setForbidUndefinedNames(old);
86 C->setSystem();
87 C->setNonClassifiable();
88 C->setPrimitive();
89 C->Description = desc;
90 C->initToldSubsumers(); // it is created after this is done centrally
91 return C;
92 }
93
94 /// replace (AR:C) with X such that C [= AR^-:X for fresh X. @return X
95 TConcept*
96 TBox :: replaceForall ( DLTree* RC )
97 {
98 // check whether we already did this before for given R,C
99 TConcept* X = getRCCache(RC);
100
101 if ( X != nullptr )
102 {
103 deleteTree(RC);
104 return X;
105 }
106
107 // see R and C at the first time
108 X = getAuxConcept();
109 DLTree* C = createSNFNot(clone(RC->Right()));
110 DLTree* Forall = createSNFForall ( createInverse(clone(RC->Left())), getTree(X) );
111 #ifdef RKG_DEBUG_ABSORPTION
112 std::cout << "\nReplaceForall: add" << C << " [=" << Forall;
113 #endif
114 // create ax axiom C [= AR^-.X
115 addSubsumeAxiom ( C, Forall );
116 // save cache for R,C
117 setRCCache ( RC, X );
118
119 return X;
120 }
121
122 void TBox :: initTopBottom ( void )
123 {
124 // create BOTTOM concept
125 TConcept* p = new TConcept ("BOTTOM");
126 p->setBottom();
127 p->setId(-1);
128 p->pName = p->pBody = bpBOTTOM;
129 pBottom = p;
130
131 // create TOP concept
132 p = new TConcept ("TOP");
133 p->setTop();
134 p->setId(-1);
135 p->pName = p->pBody = bpTOP;
136 p->tsDepth=1;
137 p->classTag = cttTrueCompletelyDefined;
138 pTop = p;
139
140 // "fresh" concept
141 p = new TConcept (" ");
142 p->setId(-1);
143 p->tsDepth=1;
144 p->classTag = cttTrueCompletelyDefined;
145 pTemp = p;
146
147 // query concept
148 p = new TConcept("FaCT++.default");
149 p->setSystem();
150 pQuery = p;
151 }
152
153 void TBox :: prepareReasoning ( void )
154 {
155 // do the preprocessing
156 Preprocess();
157
158 // init reasoner (if not exist)
159 initReasoner();
160
161 // check if it is necessary to dump relevant part TBox
162 if ( dumpQuery )
163 {
164 // set up relevance info
165 markAllRelevant();
166 std::ofstream of ( "tbox" );
167 fpp_assert ( of.good() );
168 dumpLisp lDump(of);
169 dump(&lDump);
170 clearRelevanceInfo();
171 }
172
173 // init values for SAT tests -- either cache, or consistency check
174 DLHeap.setSatOrder();
175 }
176
177 /// prepare features for SAT(P), or SUB(P,Q) test
178 void TBox :: prepareFeatures ( const TConcept* pConcept, const TConcept* qConcept )
179 {
180 auxFeatures = GCIFeatures;
181 if ( pConcept != nullptr )
182 updateAuxFeatures(pConcept->posFeatures);
183 if ( qConcept != nullptr )
184 updateAuxFeatures(qConcept->negFeatures);
185 if ( auxFeatures.hasSingletons() )
186 updateAuxFeatures(NCFeatures);
187 curFeature = &auxFeatures;
188
189 // set blocking method for the current reasoning session
190 getReasoner()->setBlockingMethod ( isIRinQuery(), isNRinQuery() );
191 }
192
193 void
194 TBox :: buildSimpleCache ( void )
195 {
196 // set cache for BOTTOM entry
197 initConstCache(bpBOTTOM);
198
199 // set all the caches for the temp concept
200 initSingletonCache ( pTemp, /*pos=*/true );
201 initSingletonCache ( pTemp, /*pos=*/false );
202
203 // inapplicable if KB contains CGIs in any form
204 if ( GCIs.isGCI() || GCIs.isReflexive() )
205 return;
206
207 // it is now safe to make a TOP cache
208 initConstCache(bpTOP);
209
210 for ( c_const_iterator c = c_begin(), cend = c_end(); c < cend; ++c )
211 if ( (*c)->isPrimitive() )
212 initSingletonCache ( (*c), /*pos=*/false );
213
214 for ( i_const_iterator i = i_begin(), iend = i_end(); i < iend; ++i )
215 if ( (*i)->isPrimitive() )
216 initSingletonCache ( (*i), /*pos=*/false );
217 }
218
219 /// check if the ontology is consistent
220 bool
221 TBox :: performConsistencyCheck ( void )
222 {
223 if ( verboseOutput )
224 std::cerr << "Consistency checking...";
225 TsProcTimer pt;
226 pt.Start();
227
228 buildSimpleCache();
229
230 TConcept* test = ( NCFeatures.hasSingletons() ? *i_begin() : nullptr );
231 prepareFeatures ( test, nullptr );
232 // DlSatTester* Reasoner = getReasoner();
233 bool ret = false;
234
235 if ( test )
236 {
237 // make a cache for TOP if it is not there
238 if ( DLHeap.getCache(bpTOP) == nullptr )
239 initConstCache(bpTOP);
240
241 ret = static_cast<NominalReasoner*>(nomReasoner)->consistentNominalCloud();
242 }
243 else
244 ret = isSatisfiable(pTop);
245
246 // setup cache for GCI
247 if ( GCIs.isGCI() )
248 {
249 // there is no much win to have it together with special-domains-as-GCIs ATM.
250 // DLHeap.setCache ( T_G, Reasoner->buildCacheByCGraph(ret) );
251 DLHeap.setCache ( inverse(T_G), new modelCacheConst(/*sat=*/false) );
252 }
253
254 pt.Stop();
255 consistTime = pt;
256 if ( verboseOutput )
257 std::cerr << " done in " << pt << " seconds\n";
258
259 return ret;
260 }
261
262 bool
263 TBox :: isSatisfiable ( const TConcept* pConcept )
264 {
265 fpp_assert ( pConcept != nullptr );
266
267 // check whether we already does the test
268 const modelCacheInterface* cache = DLHeap.getCache(pConcept->pName);
269 if ( cache != nullptr )
270 return ( cache->getState() != csInvalid );
271
272 // logging the startpoint
273 if ( LLM.isWritable(llBegSat) )
274 LL << "\n--------------------------------------------\n"
275 "Checking satisfiability of '" << pConcept->getName() << "':";
276 if ( LLM.isWritable(llGTA) )
277 LL << "\n";
278
279 // perform reasoning with a proper logical features
280 prepareFeatures ( pConcept, nullptr );
281 bool result = getReasoner()->runSat ( pConcept->resolveId(), bpTOP );
282 // save cache
283 DLHeap.setCache ( pConcept->pName, getReasoner()->buildCacheByCGraph(result) );
284 clearFeatures();
285
286 CHECK_LL_RETURN_VALUE(llSatResult,result);
287
288 #if 1
289 LL << "\n"; // usual checking -- time is extra info
290 #else
291 LL << " "; // time tests -- time is necessary info
292 #endif
293
294 LL << "The '" << pConcept->getName() << "' concept is ";
295 if ( !result )
296 LL << "un";
297 LL << "satisfiable w.r.t. TBox";
298
299 return result;
300 }
301
302 bool
303 TBox :: isSubHolds ( const TConcept* pConcept, const TConcept* qConcept )
304 {
305 fpp_assert ( pConcept != nullptr && qConcept != nullptr );
306
307 #ifdef FPP_DEBUG_PRINT_CURRENT_SUBSUMPTION
308 std::cerr << "Checking '" << pConcept->getName() << "' [= '" << qConcept->getName() << "'...";
309 #endif
310
311 // logging the startpoint
312 if ( LLM.isWritable(llBegSat) )
313 LL << "\n--------------------------------------------\nChecking subsumption '"
314 << pConcept->getName() << " [= " << qConcept->getName() << "':";
315 if ( LLM.isWritable(llGTA) )
316 LL << "\n";
317
318 // perform reasoning with a proper logical features
319 prepareFeatures ( pConcept, qConcept );
320 bool result = !getReasoner()->runSat ( pConcept->resolveId(), inverse(qConcept->resolveId()) );
321 clearFeatures();
322
323 #ifdef FPP_DEBUG_PRINT_CURRENT_SUBSUMPTION
324 std::cerr << " done\n";
325 #endif
326
327 CHECK_LL_RETURN_VALUE(llSatResult,result);
328
329 #if 1
330 LL << "\n"; // usual checking -- time is extra info
331 #else
332 LL << " "; // time tests -- time is necessary info
333 #endif
334
335 LL << "The '" << pConcept->getName() << " [= " << qConcept->getName() << "' subsumption";
336 if (!result)
337 LL << " NOT";
338 LL << " holds w.r.t. TBox";
339
340 return result;
341 }
342
343 /// check that 2 individuals are the same
344 bool TBox :: isSameIndividuals ( const TIndividual* a, const TIndividual* b )
345 {
346 a = resolveSynonym(a);
347 b = resolveSynonym(b);
348 if ( a == b ) // known synonyms
349 return true;
350 if ( !isIndividual(a) || !isIndividual(b) )
351 throw EFaCTPlusPlus("Individuals are expected in the isSameIndividuals() query");
352 if ( a->node == nullptr || b->node == nullptr ) // fresh individuals couldn't be the same
353 return false;
354 return a->getTaxVertex() == b->getTaxVertex();
355 }
356
357 /// check if 2 roles are disjoint
358 bool
359 TBox :: isDisjointRoles ( const TRole* R, const TRole* S )
360 {
361 fpp_assert ( R != nullptr && S != nullptr );
362
363 // object roles are disjoint with data roles
364 if ( R->isDataRole() != S->isDataRole() )
365 return true;
366 // prepare feature that are KB features
367 // FIXME!! overkill, but fine for now as it is sound
368 curFeature = &KBFeatures;
369 getReasoner()->setBlockingMethod ( isIRinQuery(), isNRinQuery() );
370 bool result = getReasoner()->checkDisjointRoles ( R, S );
371 clearFeatures();
372 return result;
373 }
374
375 /// check if the role R is irreflexive
376 bool
377 TBox :: isIrreflexive ( const TRole* R )
378 {
379 fpp_assert ( R != nullptr );
380
381 // data roles are irreflexive
382 if ( R->isDataRole() )
383 return true;
384 // prepare feature that are KB features
385 // FIXME!! overkill, but fine for now as it is sound
386 curFeature = &KBFeatures;
387 getReasoner()->setBlockingMethod ( isIRinQuery(), isNRinQuery() );
388 bool result = getReasoner()->checkIrreflexivity(R);
389 clearFeatures();
390 return result;
391 }
392
393 // load init values from config file
394 void TBox :: readConfig ( const ifOptionSet* Options )
395 {
396 fpp_assert ( Options != nullptr ); // safety check
397
398 // define a macro for registering boolean option
399 # define addBoolOption(name) \
400 name = Options->getBool ( #name ); \
401 if ( LLM.isWritable(llAlways) ) \
402 LL << "Init " #name " = " << name << "\n"
403
404 // TBox options
405 addBoolOption(useCompletelyDefined);
406 addBoolOption(dumpQuery);
407 addBoolOption(alwaysPreferEquals);
408 addBoolOption(useSpecialDomains);
409 // reasoner's options
410 addBoolOption(useSemanticBranching);
411 addBoolOption(useBackjumping);
412 addBoolOption(useLazyBlocking);
413 addBoolOption(useAnywhereBlocking);
414 addBoolOption(precacheRelated);
415
416 if ( Axioms.initAbsorptionFlags(Options->getText("absorptionFlags")) )
417 throw EFaCTPlusPlus ( "Incorrect absorption flags given" );
418
419 testTimeout = (unsigned)Options->getInt("testTimeout");
420 if ( LLM.isWritable(llAlways) )
421 LL << "Init testTimeout = " << testTimeout << "\n";
422
423 PriorityMatrix.initPriorities ( Options->getText("IAOEFLG"), "IAOEFLG" );
424
425 if ( RKG_USE_FAIRNESS )
426 {
427 nSkipBeforeBlock = Options->getInt("skipBeforeBlock");
428 if ( LLM.isWritable(llAlways) )
429 LL << "Init nSkipBeforeBlock = " << nSkipBeforeBlock << "\n";
430 }
431 else
432 nSkipBeforeBlock = 0;
433
434 verboseOutput = false;
435 #undef addBoolOption
436 }
437
438 /// create (and DAG-ify) query concept via its definition
439 TConcept*
440 TBox :: createQueryConcept ( const DLTree* desc )
441 {
442 fpp_assert ( desc != nullptr );
443
444 // make sure that an old query is gone
445 clearQueryConcept();
446 // create description
447 // std::cerr << "Create new temp concept with description =" << desc << "\n";
448 deleteTree ( makeNonPrimitive ( pQuery, clone(desc) ) );
449 pQuery->setIndex(nC-1);
450
451 return pQuery;
452 }
453
454 /// preprocess query concept: put description into DAG
455 void
456 TBox :: preprocessQueryConcept ( TConcept* query )
457 {
458 // build DAG entries for the default concept
459 addConceptToHeap(query);
460
461 // gather statistics about the concept
462 setConceptRelevant(query);
463
464 // DEBUG_ONLY: print the DAG info
465 // std::ofstream debugPrint ( defConceptName, std::ios::app|std::ios::out );
466 // Print (debugPrint);
467 // debugPrint << std::endl;
468
469 // check satisfiability of the concept
470 initCache(query);
471 }
472
473 /// classify query concept
474 void
475 TBox :: classifyQueryConcept ( void )
476 {
477 // prepare told subsumers for classification; as it is non-primitive, it is not CD
478 pQuery->initToldSubsumers();
479
480 // setup taxonomy behaviour flags
481 fpp_assert ( pTax != nullptr );
482 pTaxCreator->setCompletelyDefined(false); // non-primitive concept
483 // printf("qz 3\n");
484
485 // classify the concept
486 pTaxCreator->classifyEntry(pQuery);
487 // printf("qz 4\n");
488 }
489
490 /// knowledge exploration: build a model and return a link to the root
491 const DlCompletionTree*
492 TBox :: buildCompletionTree ( const TConcept* pConcept )
493 {
494 const DlCompletionTree* ret = nullptr;
495 // perform reasoning with a proper logical features
496 prepareFeatures ( pConcept, nullptr );
497 // turn off caching of CT nodes during reasoning
498 setUseNodeCache(false);
499 // do the SAT test, save the CT if satisfiable
500 if ( getReasoner()->runSat ( pConcept->resolveId() ) )
501 ret = getReasoner()->getRootNode();
502 // turn on caching of CT nodes during reasoning
503 setUseNodeCache(true);
504 clearFeatures();
505 return ret;
506 }
507
508 /// dump QUERY processing time, reasoning statistics and a (preprocessed) TBox
509 void
510 TBox :: writeReasoningResult ( std::ostream& o, float time ) const
511 {
512 if ( nomReasoner )
513 {
514 o << "Query processing reasoning statistic: Nominals";
515 nomReasoner->writeTotalStatistic(o);
516 }
517 o << "Query processing reasoning statistic: Standard";
518 stdReasoner->writeTotalStatistic(o);
519
520 // we know here whether KB is consistent
521 fpp_assert ( getStatus() >= kbCChecked );
522 if ( Consistent )
523 o << "Required";
524 else
525 o << "KB is inconsistent. Query is NOT processed\nConsistency";
526
527 float sum = preprocTime + consistTime;
528 o << " check done in " << time << " seconds\nof which:\nPreproc. takes "
529 << preprocTime << " seconds\nConsist. takes " << consistTime << " seconds";
530
531 if ( nomReasoner )
532 {
533 o << "\nReasoning NOM:";
534 sum += nomReasoner->printReasoningTime(o);
535 }
536 o << "\nReasoning STD:";
537 sum += stdReasoner->printReasoningTime(o);
538
539 o << "\nThe rest takes ";
540 // determine and normalize the rest
541 float f = time - sum;
542 if ( f < 0 )
543 f = 0;
544 f = ((unsigned long)(f*100))/100.f;
545 o << f << " seconds\n";
546 Print(o);
547 }
548
549 void TBox :: PrintDagEntry ( std::ostream& o, BipolarPointer p ) const
550 {
551 fpp_assert ( isValid (p) );
552
553 // primitive ones -- check first
554 if ( p == bpTOP )
555 {
556 o << " *TOP*";
557 return;
558 }
559 else if ( p == bpBOTTOM )
560 {
561 o << " *BOTTOM*";
562 return;
563 }
564
565 // checks inversion
566 if ( isNegative(p) )
567 {
568 o << " (not";
569 PrintDagEntry ( o, inverse(p) );
570 o << ")";
571 return;
572 }
573
574 const DLVertex& v = DLHeap[p];
575
576 switch ( v.Type() )
577 {
578 case dtTop:
579 o << " *TOP*";
580 return;
581
582 case dtName:
583 case dtDataType:
584 case dtDataValue:
585 o << ' ' << v.getConcept()->getName();
586 return;
587
588 case dtDataExpr:
589 o << ' ' << *getDataEntryByBP(p)->getFacet();
590 return;
591
592 case dtIrr:
593 o << " (" << v.getTagName() << ' ' << v.getRole()->getName() << ")";
594 return;
595
596 case dtAnd:
597 o << " (" << v.getTagName();
598 for ( DLVertex::const_iterator q = v.begin(); q != v.end(); ++q )
599 PrintDagEntry ( o, *q );
600 o << ")";
601 return;
602
603 case dtForall:
604 case dtLE:
605 o << " (" << v.getTagName();
606 if ( v.Type() == dtLE )
607 o << ' ' << v.getNumberLE();
608 o << ' ' << v.getRole()->getName();
609 PrintDagEntry ( o, v.getC() );
610 o << ")";
611 return;
612
613 case dtProj:
614 o << " (" << v.getTagName() << ' ' << v.getRole()->getName() << ' ';
615 PrintDagEntry ( o, v.getC() );
616 o << " => " << v.getProjRole()->getName() << ")";
617 return;
618
619 case dtNN: // shouldn't appears in the expressions
620 case dtChoose:
621 fpp_unreachable();
622
623 default: // invalid value
624 std::cerr << "Error printing vertex of type " << v.getTagName() << "(" << v.Type () << ")";
625 fpp_unreachable();
626 return;
627 }
628 }
629
630 void TBox :: PrintConcept ( std::ostream& o, const TConcept* p ) const
631 {
632 // print only relevant concepts
633 if ( isValid(p->pName) )
634 {
635 o << getCTTagName(p->getClassTag());
636
637 if ( p->isSingleton() )
638 o << (p->isNominal() ? 'o' : '!');
639
640 o << '.' << p->getName() << " [" << p->tsDepth
641 << "] " << (p->isNonPrimitive() ? "=" : "[=");
642
643 if ( isValid (p->pBody) )
644 PrintDagEntry ( o, p->pBody );
645
646 // if you want to check correctness of translation (print following info)
647 // you should comment out RemoveExtraDescription() in TBox::Preprocess()
648 // but check hasSynonym assignment
649 if ( p->Description != nullptr )
650 o << (p->isNonPrimitive() ? "\n-=" : "\n-[=") << p->Description;
651
652 o << "\n";
653 }
654 }
655
656 void
657 TBox :: printFeatures ( void ) const
658 {
659 KBFeatures.writeState();
660
661 if ( LLM.isWritable(llAlways) )
662 LL << "KB contains " << (GCIs.isGCI() ? "" : "NO ") << "GCIs\nKB contains "
663 << (GCIs.isReflexive() ? "" : "NO ") << "reflexive roles\nKB contains "
664 << (GCIs.isRnD() ? "" : "NO ") << "range and domain restrictions\n";
665 }