Debian Codegraph @

FaCT++.Python/lib/Kernel/Reasoner.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 <iomanip>
21
22 #include "Reasoner.h"
23 #include "logging.h"
24 #include "eFPPTimeout.h"
25
26 // comment the line out for printing tree info before save and after restoring
27 //#define __DEBUG_SAVE_RESTORE
28 // comment the line out for flushing LL after dumping significant piece of info
29 //#define __DEBUG_FLUSH_LL
30
31 #ifdef USE_REASONING_STATISTICS
32 AccumulatedStatistic* AccumulatedStatistic::root = nullptr;
33 #endif
34
35 DlSatTester :: DlSatTester ( TBox& tbox )
36 : tBox(tbox)
37 , DLHeap(tbox.DLHeap)
38 , Manager(64)
39 , CGraph(1,this)
40 , TODO(tBox.PriorityMatrix,CGraph.getRareStack())
41 , DTReasoner(tbox.DLHeap)
42 // It's unsafe to have a cache that touches a nominal in a node; set flagNominals to prevent it
43 , newNodeCache ( true, tBox.nC, tBox.nR )
44 , newNodeEdges ( false, tBox.nC, tBox.nR )
45 , GCIs(tbox.GCIs)
46 {
47 // init static part of CTree
48 CGraph.initContext ( tBox.nSkipBeforeBlock, tBox.useLazyBlocking, tBox.useAnywhereBlocking );
49 // init datatype reasoner
50 tBox.getDataTypeCenter().initDataTypeReasoner(DTReasoner);
51 // init set of reflexive roles
52 tBox.getORM().fillReflexiveRoles(ReflexiveRoles);
53 // init blocking statistics
54 clearBlockingStat();
55
56 resetSessionFlags();
57 }
58
59 /// prepare Nominal Reasoner to a new job
60 void
61 DlSatTester :: prepareReasoner ( void )
62 {
63 CGraph.clear();
64 Stack.clear();
65 TODO.clear();
66
67 pUsed.clear();
68 nUsed.clear();
69 SessionGCIs.clear();
70
71 curNode = nullptr;
72 bContext = nullptr;
73 tryLevel = InitBranchingLevelValue;
74
75 // clear last session information
76 resetSessionFlags();
77 }
78
79 bool
80 DlSatTester :: findConcept ( const CWDArray& lab, BipolarPointer p )
81 {
82 #ifdef ENABLE_CHECKING
83 fpp_assert ( isCorrect(p) ); // sanity checking
84 // constants are not allowed here
85 fpp_assert ( p != bpTOP );
86 fpp_assert ( p != bpBOTTOM );
87 #endif
88
89 incStat(nLookups);
90 return lab.contains(p);
91 }
92
93 bool
94 DlSatTester :: findConceptClash ( const CWDArray& lab, BipolarPointer p, const DepSet& dep )
95 {
96 #ifdef ENABLE_CHECKING
97 fpp_assert ( isCorrect(p) ); // sanity checking
98 // constants are not allowed here
99 fpp_assert ( p != bpTOP );
100 fpp_assert ( p != bpBOTTOM );
101 #endif
102
103 incStat(nLookups);
104
105 for ( const auto& C: lab )
106 if ( C.bp() == p )
107 {
108 // create clashSet
109 clashSet = C.getDep();
110 clashSet.add(dep);
111 return true;
112 }
113
114 // we are able to insert a concept
115 return false;
116 }
117
118 addConceptResult
119 DlSatTester :: checkAddedConcept ( const CWDArray& lab, BipolarPointer p, const DepSet& dep )
120 {
121 #ifdef ENABLE_CHECKING
122 fpp_assert ( isCorrect(p) ); // sanity checking
123 // constants are not allowed here
124 fpp_assert ( p != bpTOP );
125 fpp_assert ( p != bpBOTTOM );
126 #endif
127
128 if ( findConcept ( lab, p ) )
129 return acrExist;
130
131 if ( findConceptClash ( lab, inverse(p), dep ) )
132 return acrClash;
133
134 // we are able to insert a concept
135 return acrDone;
136 }
137
138 addConceptResult
139 DlSatTester :: tryAddConcept ( const CWDArray& lab, BipolarPointer bp, const DepSet& dep )
140 {
141 // check whether C or ~C can occurs in a node label
142 const BipolarPointer inv_p = inverse(bp);
143 bool canC = isUsed(bp);
144 bool canNegC = isUsed(inv_p);
145
146 // if either C or ~C is used already, it's not new in a label
147 if ( canC )
148 {
149 if ( canNegC ) // both C and ~C can be in the label
150 return checkAddedConcept ( lab, bp, dep );
151 else // C but not ~C can be in the label
152 return findConcept ( lab, bp ) ? acrExist : acrDone;
153 }
154 else
155 {
156 if ( canNegC ) // ~C but not C can be in the label
157 return findConceptClash ( lab, inv_p, dep ) ? acrClash : acrDone;
158 else // neither C nor ~C can be in the label
159 return acrDone;
160 }
161 }
162
163 bool
164 DlSatTester :: addToDoEntry ( DlCompletionTree* node, const ConceptWDep& C, const char* reason )
165 {
166 if ( C == bpTOP ) // simplest things first
167 return false;
168 if ( C == bpBOTTOM )
169 {
170 setClashSet(C.getDep());
171 if ( LLM.isWritable(llGTA) )
172 logClash ( node, C );
173 return true;
174 }
175
176 const DLVertex& v = DLHeap[C];
177 DagTag tag = v.Type();
178
179 // try to add a concept to a node label
180 switch ( tryAddConcept ( node->label().getLabel(tag), C.bp(), C.getDep() ) )
181 {
182 case acrClash: // clash -- return
183 if ( LLM.isWritable(llGTA) )
184 logClash ( node, C );
185 return true;
186 case acrExist: // already exists -- nothing new
187 return false;
188 case acrDone: // try was done
189 return insertToDoEntry ( node, C, tag, reason );
190 default: // safety check
191 fpp_unreachable();
192 }
193 }
194
195 /// insert P to the label of N; do necessary updates; may return Clash in case of data node N
196 bool
197 DlSatTester :: insertToDoEntry ( DlCompletionTree* node, const ConceptWDep& C,
198 DagTag tag, const char* reason = nullptr )
199 {
200 // we will change current Node => save it if necessary
201 updateLevel ( node, C.getDep() );
202 CGraph.addConceptToNode ( node, C, CGLabel::isComplexConcept(tag) );
203
204 auto bp = C.bp();
205 setUsed(bp);
206
207 if ( node->isCached() )
208 return correctCachedEntry(node);
209
210 // add new info in TODO list
211 TODO.addEntry ( node, tag, bp );
212
213 if ( node->isDataNode() ) // data concept -- run data center for it
214 return checkDataNode ? checkDataClash(node) : false;
215 else if ( LLM.isWritable(llGTA) ) // inform about it
216 logEntry ( node, C, reason );
217
218 return false;
219 }
220
221 //-----------------------------------------------------------------------------
222 //-- internal cache support
223 //-----------------------------------------------------------------------------
224
225 bool
226 DlSatTester :: canBeCached ( DlCompletionTree* node )
227 {
228 DlCompletionTree::const_label_iterator p;
229 bool shallow = true;
230 unsigned int size = 0;
231
232 // check whether node cache is allowed
233 if ( unlikely(!tBox.useNodeCache) )
234 return false;
235
236 // nominal nodes can not be cached
237 if ( unlikely(node->isNominalNode()) )
238 return false;
239
240 incStat(nCacheTry);
241
242 // check applicability of the caching
243 for ( p = node->beginl_sc(); p != node->endl_sc(); ++p )
244 {
245 if ( DLHeap.getCache(p->bp()) == nullptr )
246 {
247 incStat(nCacheFailedNoCache);
248 if ( LLM.isWritable(llGTA) )
249 LL << " cf(" << p->bp() << ")";
250 return false;
251 }
252
253 shallow &= DLHeap.getCache(p->bp())->shallowCache();
254 ++size;
255 }
256
257 for ( p = node->beginl_cc(); p != node->endl_cc(); ++p )
258 {
259 if ( DLHeap.getCache(p->bp()) == nullptr )
260 {
261 incStat(nCacheFailedNoCache);
262 if ( LLM.isWritable(llGTA) )
263 LL << " cf(" << p->bp() << ")";
264 return false;
265 }
266
267 shallow &= DLHeap.getCache(p->bp())->shallowCache();
268 ++size;
269 }
270
271 // it's useless to cache shallow nodes
272 if ( shallow && size != 0 )
273 {
274 incStat(nCacheFailedShallow);
275 if ( LLM.isWritable(llGTA) )
276 LL << " cf(s)";
277 return false;
278 }
279
280 return true;
281 }
282
283 /// perform caching of the node (it is known that caching is possible)
284 void
285 DlSatTester :: doCacheNode ( DlCompletionTree* node )
286 {
287 DlCompletionTree::const_label_iterator p;
288 DepSet dep;
289
290 newNodeCache.clear();
291
292 for ( p = node->beginl_sc(); p != node->endl_sc(); ++p )
293 {
294 dep.add(p->getDep());
295 // try to merge cache of a node label element with accumulator
296 switch ( newNodeCache.merge(DLHeap.getCache(p->bp())) )
297 {
298 case csValid: // continue
299 break;
300 case csInvalid: // clash: set the clash-set
301 setClashSet(dep);
302 // fall through
303 default: // caching of node fails
304 return;
305 }
306 }
307
308 for ( p = node->beginl_cc(); p != node->endl_cc(); ++p )
309 {
310 dep.add(p->getDep());
311 // try to merge cache of a node label element with accumulator
312 switch ( newNodeCache.merge(DLHeap.getCache(p->bp())) )
313 {
314 case csValid: // continue
315 break;
316 case csInvalid: // clash: set the clash-set
317 setClashSet(dep);
318 // fall through
319 default: // caching of node fails
320 return;
321 }
322 }
323
324 // all concepts in label are mergeable; now try to add input arc
325 newNodeEdges.clear();
326 newNodeEdges.initRolesFromArcs(node);
327 newNodeCache.merge(&newNodeEdges);
328 }
329
330 modelCacheState
331 DlSatTester :: reportNodeCached ( DlCompletionTree* node )
332 {
333 doCacheNode(node);
334 enum modelCacheState status = newNodeCache.getState();
335 switch ( status )
336 {
337 case csValid:
338 incStat(nCachedSat);
339 if ( LLM.isWritable(llGTA) )
340 LL << " cached(" << node->getId() << ")";
341 break;
342 case csInvalid:
343 incStat(nCachedUnsat);
344 break;
345 case csFailed:
346 case csUnknown:
347 incStat(nCacheFailed);
348 if ( LLM.isWritable(llGTA) )
349 LL << " cf(c)";
350 status = csFailed;
351 break;
352 default:
353 fpp_unreachable();
354 }
355 return status;
356 }
357
358 bool DlSatTester :: correctCachedEntry ( DlCompletionTree* n )
359 {
360 fpp_assert ( n->isCached() ); // safety check
361
362 // FIXME!! check if it is possible to leave node cached in more efficient way
363 modelCacheState status = tryCacheNode(n);
364
365 // uncheck cached node status and add all elements in TODO list
366 if ( status == csFailed )
367 redoNodeLabel ( n, "uc" );
368
369 return usageByState(status);
370 }
371
372 //-----------------------------------------------------------------------------
373 //-- internal datatype support
374 //-----------------------------------------------------------------------------
375
376 /// @return true iff given data node contains data contradiction
377 bool
378 DlSatTester :: hasDataClash ( const DlCompletionTree* Node )
379 {
380 fpp_assert ( Node && Node->isDataNode() ); // safety check
381
382 DTReasoner.clear();
383
384 // data node may contain only "simple" concepts in there
385 for ( DlCompletionTree::const_label_iterator p = Node->beginl_sc(), p_end = Node->endl_sc(); p != p_end; ++p )
386 if ( DTReasoner.addDataEntry ( p->bp(), p->getDep() ) ) // clash found
387 return true;
388
389 return false;
390 }
391
392 bool DlSatTester :: runSat ( void )
393 {
394 testTimer.Start();
395 bool result = checkSatisfiability ();
396 testTimer.Stop();
397
398 if ( LLM.isWritable(llSatTime) )
399 LL << "\nChecking time was " << testTimer << " seconds";
400
401 testTimer.Reset();
402
403 finaliseStatistic();
404
405 if ( result )
406 writeRoot(llRStat);
407
408 return result;
409 }
410
411 void
412 DlSatTester :: finaliseStatistic ( void )
413 {
414 #ifdef USE_REASONING_STATISTICS
415 // add the integer stat values
416 nNodeSaves.set(CGraph.getNNodeSaves());
417 nNodeRestores.set(CGraph.getNNodeRestores());
418
419 // log statistics data
420 if ( LLM.isWritable(llRStat) )
421 logStatisticData ( LL, /*needLocal=*/true );
422
423 // merge local statistics with the global one
424 AccumulatedStatistic::accumulateAll();
425 #endif
426
427 // clear global statistics
428 CGraph.clearStatistics();
429 }
430
431 bool DlSatTester :: applyReflexiveRoles ( DlCompletionTree* node, const DepSet& dep )
432 {
433 for ( const auto& R: ReflexiveRoles )
434 {
435 // create R-loop through the NODE
436 DlCompletionTreeArc* pA = CGraph.addRoleLabel ( node, node, /*isPredEdge=*/false, R, dep );
437 if ( setupEdge ( pA, dep ) )
438 return true;
439 }
440
441 // no clash found
442 return false;
443 }
444
445 bool DlSatTester :: checkSatisfiability ( void )
446 {
447 unsigned int loop = 0;
448 for (;;)
449 {
450 if ( curNode == nullptr )
451 {
452 if ( TODO.empty() ) // no applicable rules
453 { // do run-once things
454 if ( performAfterReasoning() ) // clash found
455 if ( tunedRestore() ) // no more alternatives
456 return false;
457 // if nothing added -- that's it
458 if ( TODO.empty() )
459 return true;
460 }
461
462 const ToDoEntry* curTDE = TODO.getNextEntry ();
463 fpp_assert ( curTDE != nullptr );
464
465 // setup current context
466 curNode = curTDE->Node;
467 curConcept = curNode->label().getConcept(curTDE->offset);
468 }
469
470 if ( ++loop == 5000 )
471 {
472 loop = 0;
473 if ( tBox.isCancelled() )
474 return false;
475 unsigned long timeout = getSatTimeout();
476 if ( unlikely(timeout > 0) && 1000*(float)testTimer >= timeout )
477 throw EFPPTimeout();
478 }
479 // here curNode/curConcept are set
480 if ( commonTactic() ) // clash found
481 {
482 if ( tunedRestore() ) // the concept is unsatisfiable
483 return false;
484 }
485 else
486 curNode = nullptr;
487 }
488 }
489
490 /// perform all the actions that should be done once, after all normal rules are not applicable. @return true if the concept is unsat
491 bool
492 DlSatTester :: performAfterReasoning ( void )
493 {
494 // make sure all blocked nodes are still blocked
495 if ( LLM.isWritable(llGTA) )
496 {
497 logIndentation();
498 LL << "ub:";
499 }
500 CGraph.retestCGBlockedStatus();
501 if ( LLM.isWritable(llGTA) )
502 LL << "]";
503 if ( !TODO.empty() )
504 return false;
505
506 // check fairness constraints
507 if ( RKG_USE_FAIRNESS && tBox.hasFC() )
508 {
509 DlCompletionTree* violator = nullptr;
510 // for every given FC, if it is violated, reject current model
511 for ( TBox::ConceptVector::const_iterator p = tBox.Fairness.begin(), p_end = tBox.Fairness.end(); p < p_end; ++p )
512 {
513 violator = CGraph.getFCViolator((*p)->pName);
514 if ( violator )
515 {
516 incStat(nFairnessViolations);
517 // try to fix violators
518 if ( addToDoEntry ( violator, (*p)->pName, getCurDepSet(), "fair" ) )
519 return true;
520 }
521 }
522
523 if ( !TODO.empty() )
524 return false;
525 }
526
527 return false;
528 }
529
530 /********************************************************************************
531 *
532 * Save/Restore section
533 *
534 ******************************************************************************/
535
536 /// restore local state from BContext
537 void DlSatTester :: restoreBC ( void )
538 {
539 // restore reasoning context
540 curNode = bContext->curNode;
541 curConcept = bContext->curConcept;
542 pUsed.resize(bContext->pUsedIndex);
543 nUsed.resize(bContext->nUsedIndex);
544 if ( unlikely ( !SessionGCIs.empty() ) )
545 SessionGCIs.resize(bContext->SGsize);
546
547 // we here after the clash so choose the next branching option
548 nextBranchingOption();
549 }
550
551 void DlSatTester :: save ( void )
552 {
553 // save tree
554 CGraph.save();
555
556 // save ToDoList
557 TODO.save();
558
559 // increase tryLevel
560 ++tryLevel;
561 Manager.ensureLevel(getCurLevel());
562
563 // init BC
564 clearBC();
565
566 incStat(nStateSaves);
567
568 if ( LLM.isWritable(llSRState) )
569 LL << " ss(" << getCurLevel()-1 << ")";
570 #ifdef __DEBUG_SAVE_RESTORE
571 writeRoot(llSRState);
572 #endif
573 }
574
575 void DlSatTester :: restore ( unsigned int newTryLevel )
576 {
577 fpp_assert ( !Stack.empty () );
578 fpp_assert ( newTryLevel > 0 );
579
580 // skip all intermediate restores
581 setCurLevel(newTryLevel);
582
583 // restore local
584 bContext = Stack.top(getCurLevel());
585 restoreBC();
586
587 // restore tree
588 CGraph.restore(getCurLevel());
589
590 // restore TODO list
591 TODO.restore(getCurLevel());
592
593 incStat(nStateRestores);
594
595 if ( LLM.isWritable(llSRState) )
596 LL << " sr(" << getCurLevel() << ")";
597 #ifdef __DEBUG_SAVE_RESTORE
598 writeRoot(llSRState);
599 #endif
600 }
601
602 /**
603 * logging methods
604 */
605
606 void DlSatTester :: logIndentation ( void ) const
607 {
608 CHECK_LL_RETURN(llGTA); // useless but safe
609 int level = int(getCurLevel());
610 LL << "\n" << std::setw(level) << "[";
611 }
612 void DlSatTester :: logStartEntry ( void ) const
613 {
614 CHECK_LL_RETURN(llGTA); // useless but safe
615 logIndentation();
616 LL << "(";
617 curNode->logNode ();
618 LL << "," << curConcept << "){";
619 if ( isNegative (curConcept.bp()) )
620 LL << "~";
621 const DLVertex& v = DLHeap[curConcept];
622 LL << v.getTagName();
623 if ( const TNamedEntry* entry = v.getConcept() )
624 LL << "(" << entry->getName() << ")";
625 LL << "}:";
626 }
627
628 void DlSatTester :: logFinishEntry ( bool res ) const
629 {
630 CHECK_LL_RETURN(llGTA); // useless but safe
631
632 LL << "]";
633 if ( res )
634 LL << " Clash" << getClashSet();
635 #ifdef __DEBUG_FLUSH_LL
636 LL.flush ();
637 #endif
638 }
639
640 void DlSatTester :: logStatisticData ( std::ostream& o, bool needLocal ) const
641 {
642 #ifdef USE_REASONING_STATISTICS
643 nTacticCalls.Print ( o, needLocal, "\nThere were made ", " tactic operations, of which:" );
644 nIdCalls.Print ( o, needLocal, "\n CN operations: ", "" );
645 nSingletonCalls.Print(o, needLocal, "\n including ", " singleton ones" );
646 nOrCalls.Print ( o, needLocal, "\n OR operations: ", "" );
647 nOrBrCalls.Print ( o, needLocal, "\n ", " of which are branching" );
648 nAndCalls.Print ( o, needLocal, "\n AND operations: ", "" );
649 nSomeCalls.Print ( o, needLocal, "\n SOME operations: ", "" );
650 nAllCalls.Print ( o, needLocal, "\n ALL operations: ", "" );
651 nFuncCalls.Print ( o, needLocal, "\n Func operations: ", "" );
652 nLeCalls.Print ( o, needLocal, "\n LE operations: ", "" );
653 nGeCalls.Print ( o, needLocal, "\n GE operations: ", "" );
654 nUseless.Print ( o, needLocal, "\n N/A operations: ", "" );
655
656 nNNCalls.Print ( o, needLocal, "\nThere were made ", " NN rule application" );
657 nMergeCalls.Print ( o, needLocal, "\nThere were made ", " merging operations" );
658
659 nAutoEmptyLookups.Print ( o, needLocal, "\nThere were made ", " RA empty transition lookups" );
660 nAutoTransLookups.Print ( o, needLocal, "\nThere were made ", " RA applicable transition lookups" );
661
662 nSRuleAdd.Print ( o, needLocal, "\nThere were made ", " simple rule additions" );
663 nSRuleFire.Print ( o, needLocal, "\n of which ", " simple rules fired" );
664
665 nStateSaves.Print ( o, needLocal, "\nThere were made ", " save(s) of global state" );
666 nStateRestores.Print ( o, needLocal, "\nThere were made ", " restore(s) of global state" );
667 nNodeSaves.Print ( o, needLocal, "\nThere were made ", " save(s) of tree state" );
668 nNodeRestores.Print ( o, needLocal, "\nThere were made ", " restore(s) of tree state" );
669 nLookups.Print ( o, needLocal, "\nThere were made ", " concept lookups" );
670 if ( RKG_USE_FAIRNESS )
671 nFairnessViolations.Print ( o, needLocal, "\nThere were ", " fairness constraints violation" );
672
673 nCacheTry.Print ( o, needLocal, "\nThere were made ", " tries to cache completion tree node, of which:" );
674 nCacheFailedNoCache.Print ( o, needLocal, "\n ", " fails due to cache absence" );
675 nCacheFailedShallow.Print ( o, needLocal, "\n ", " fails due to shallow node" );
676 nCacheFailed.Print ( o, needLocal, "\n ", " fails due to cache merge failure" );
677 nCachedSat.Print ( o, needLocal, "\n ", " cached satisfiable nodes" );
678 nCachedUnsat.Print ( o, needLocal, "\n ", " cached unsatisfiable nodes" );
679 #endif
680
681 if ( !needLocal )
682 o << "\nThe maximal graph size is " << CGraph.maxSize() << " nodes";
683 }
684
685 float
686 DlSatTester :: printReasoningTime ( std::ostream& o ) const
687 {
688 o << "\n SAT takes " << satTimer << " seconds\n SUB takes " << subTimer << " seconds";
689 return satTimer + subTimer;
690 }
691