Debian Codegraph @

Kernel/dlCompletionGraph.h

raw symbols SCIP
1 /* This file is part of the FaCT++ DL reasoner
2 Copyright (C) 2005-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 #ifndef DLCOMPLETIONGRAPH_H
21 #define DLCOMPLETIONGRAPH_H
22
23 #include <vector>
24
25 #include "globaldef.h"
26 #include "DeletelessAllocator.h"
27 #include "dlCompletionTree.h"
28 #include "dlCompletionTreeArc.h"
29 #include "tSaveStack.h"
30 #include "tRareSaveStack.h"
31
32 class DlSatTester;
33
34 /**
35 * Class for maintaining graph of CT nodes. Behaves like
36 * deleteless allocator for nodes, plus some obvious features
37 */
38 class DlCompletionGraph
39 {
40 protected: // typedefs
41 /// type of the heap
42 typedef std::vector<DlCompletionTree*> nodeBaseType;
43
44 public: // typedefs
45 /// heap's RW iterator
46 typedef nodeBaseType::iterator iterator;
47 /// heap's RO iterator
48 typedef nodeBaseType::const_iterator const_iterator;
49
50 protected: // types
51 /// class for S/R local state
52 class SaveState
53 {
54 public: // members
55 /// number of valid nodes
56 size_t nNodes = 0;
57 /// end pointer of saved nodes
58 size_t sNodes = 0;
59 /// number of used edges
60 size_t nEdges = 0;
61 }; // SaveState
62
63 private: // constants
64 /// initial value of IR level
65 static const BipolarPointer initIRLevel = 0;
66
67 private: // members
68 /// allocator for edges
69 DeletelessAllocator<DlCompletionTreeArc> CTEdgeHeap;
70
71 protected: // members
72 /// heap itself
73 nodeBaseType NodeBase;
74 /// nodes, saved on current branching level
75 nodeBaseType SavedNodes;
76 /// host reasoner
77 DlSatTester* pReasoner;
78 /// remember the last generated ID for the node
79 unsigned int nodeId = 0;
80 /// index of the next unallocated entry
81 size_t endUsed = 0;
82 /// current branching level (synchronised with reasoner's one)
83 unsigned int branchingLevel;
84 /// current IR level (should be valid BP)
85 BipolarPointer IRLevel;
86 /// stack for rarely changed information
87 TRareSaveStack RareStack;
88 /// stack for usual saving/restoring
89 TSaveStack<SaveState> Stack;
90
91 // helpers for the output
92
93 /// bitmap to remember which node was printed
94 std::vector<bool> CGPFlag;
95 /// indent to print CGraph nodes
96 unsigned int CGPIndent = 0;
97
98 // statistical members
99
100 /// number of node' saves
101 unsigned int nNodeSaves = 0;
102 /// number of node' saves
103 unsigned int nNodeRestores = 0;
104 /// maximal size of the graph
105 size_t maxGraphSize = 0;
106
107 // flags
108
109 /// how many nodes skip before block; work only with FAIRNESS
110 int nSkipBeforeBlock = 0;
111 /// use or not lazy blocking (ie test blocking only expanding exists)
112 bool useLazyBlocking = true;
113 /// whether to use Anywhere blocking as opposed to an ancestor one
114 bool useAnywhereBlocking = true;
115
116 /// check if session has inverse roles
117 bool sessionHasInverseRoles = false;
118 /// check if session has number restrictions
119 bool sessionHasNumberRestrictions = false;
120
121 protected: // methods
122 /// init vector [B,E) with new objects T
123 void initNodeArray ( iterator b, iterator e )
124 {
125 for ( iterator p = b; p != e; ++p )
126 *p = new DlCompletionTree(nodeId++);
127 }
128 /// increase heap size
129 void grow ( void )
130 {
131 NodeBase.resize(NodeBase.size()*2);
132 initNodeArray ( NodeBase.begin()+NodeBase.size()/2, NodeBase.end() );
133 }
134 /// init root node
135 void initRoot ( void )
136 {
137 fpp_assert ( endUsed == 0 );
138 getNewNode();
139 }
140 /// create edge between nodes with given label and creation level; @return from->to arc
141 DlCompletionTreeArc* createEdge (
142 DlCompletionTree* from,
143 DlCompletionTree* to,
144 bool isPredEdge,
145 const TRole* roleName,
146 const DepSet& dep );
147
148 /// Aux method for Merge(): add EDGE to the NODE wrt flag ISPREDEDGE and dep-set DEP
149 DlCompletionTreeArc* moveEdge (
150 DlCompletionTree* node,
151 DlCompletionTreeArc* edge,
152 bool isPredEdge, const DepSet& dep );
153
154 /// invalidate EDGE, save restoring info
155 void invalidateEdge ( DlCompletionTreeArc* edge ) { saveRareCond(edge->save()); }
156
157 //----------------------------------------------
158 // inequality relation methods
159 //----------------------------------------------
160
161 /// update IR in P with IR from Q and additional dep-set
162 void updateIR ( DlCompletionTree* p, const DlCompletionTree* q, const DepSet& toAdd );
163
164 //----------------------------------------------
165 // re-building blocking hierarchy
166 //----------------------------------------------
167
168 /// check whether NODE is blocked by a BLOCKER
169 bool isBlockedBy ( const DlCompletionTree* node, const DlCompletionTree* blocker ) const;
170 /// check if d-blocked node is still d-blocked
171 bool isStillDBlocked ( const DlCompletionTree* node ) const { return node->isDBlocked() && isBlockedBy ( node, node->Blocker ); }
172 /// try to find d-blocker for a node using ancestor blocking
173 void findDAncestorBlocker ( DlCompletionTree* node );
174 /// try to find d-blocker for a node using anywhere blocking
175 void findDAnywhereBlocker ( DlCompletionTree* node );
176 /// try to find d-blocker for a node
177 void findDBlocker ( DlCompletionTree* node )
178 {
179 saveNode ( node, branchingLevel );
180 node->clearAffected();
181 if ( node->isBlocked() )
182 saveRareCond(node->setUBlocked());
183 if ( useAnywhereBlocking )
184 findDAnywhereBlocker(node);
185 else
186 findDAncestorBlocker(node);
187 }
188 /// unblock all the children of the node
189 void unblockNodeChildren ( DlCompletionTree* node )
190 {
191 for ( DlCompletionTree::const_edge_iterator q = node->begin(), q_end = node->end(); q < q_end; ++q )
192 if ( (*q)->isSuccEdge() && !(*q)->isIBlocked() && !(*q)->isReflexiveEdge() ) // all of them are i-blocked
193 unblockNode ( (*q)->getArcEnd(), false );
194 }
195 /// mark node unblocked; unblock all the hierarchy
196 void unblockNode ( DlCompletionTree* node, bool wasDBlocked );
197
198 /// mark NODE as a d-blocked by a BLOCKER
199 void setNodeDBlocked ( DlCompletionTree* node, const DlCompletionTree* blocker )
200 {
201 saveRareCond(node->setDBlocked(blocker));
202 propagateIBlockedStatus ( node, node );
203 }
204 /// mark NODE as an i-blocked by a BLOCKER
205 void setNodeIBlocked ( DlCompletionTree* node, const DlCompletionTree* blocker )
206 {
207 // nominal nodes can't be blocked
208 if ( node->isPBlocked() || node->isNominalNode() )
209 return;
210
211 node->clearAffected();
212
213 // already iBlocked -- nothing changes
214 if ( node->isIBlocked() && node->Blocker == blocker )
215 return;
216 // prevent node to be IBlocked due to reflexivity
217 if ( node == blocker )
218 return;
219
220 saveRareCond(node->setIBlocked(blocker));
221 propagateIBlockedStatus ( node, blocker );
222 }
223 /// propagate i-blocked status to all children of NODE
224 void propagateIBlockedStatus ( DlCompletionTree* node, const DlCompletionTree* blocker )
225 {
226 for ( DlCompletionTree::const_edge_iterator q = node->begin(), q_end = node->end(); q < q_end; ++q )
227 if ( (*q)->isSuccEdge() && !(*q)->isIBlocked() )
228 setNodeIBlocked ( (*q)->getArcEnd(), blocker );
229 }
230 /// @return true iff node might became unblocked
231 bool canBeUnBlocked ( DlCompletionTree* node ) const
232 {
233 // in presence of inverse roles it is not enough
234 // to check the affected flag for both node and its blocker
235 // see tModal* for example
236 if ( sessionHasInverseRoles )
237 return true;
238 // if node is affected -- it can be unblocked;
239 // if blocker became blocked itself -- the same
240 return node->isAffected() || node->isIllegallyDBlocked();
241 }
242
243 // helpers for the graph printing
244
245 /// print proper indentation
246 void PrintIndent ( std::ostream& o )
247 {
248 o << "\n|";
249 for ( unsigned int i = 1; i < CGPIndent; ++i )
250 o << " |";
251 }
252 /// print node of the graph with proper indentation
253 void PrintNode ( const DlCompletionTree* node, std::ostream& o );
254 /// print edge of the graph with proper indentation
255 void PrintEdge ( DlCompletionTree::const_edge_iterator edge, const DlCompletionTree* parent, std::ostream& o );
256
257 public: // interface
258 /// c'tor: make INIT_SIZE objects
259 DlCompletionGraph ( unsigned int initSize, DlSatTester* p )
260 : NodeBase(initSize)
261 , pReasoner(p)
262 , branchingLevel(InitBranchingLevelValue)
263 , IRLevel(initIRLevel)
264 {
265 initNodeArray ( NodeBase.begin(), NodeBase.end() );
266 clearStatistics();
267 initRoot();
268 }
269 /// no copy c'tor
270 DlCompletionGraph ( const DlCompletionGraph& ) = delete;
271 /// no assignment
272 DlCompletionGraph& operator = ( const DlCompletionGraph& ) = delete;
273 /// d'tor: delete all allocated nodes
274 ~DlCompletionGraph()
275 {
276 for ( DlCompletionTree* node : NodeBase )
277 delete node;
278 }
279
280 // flag setting
281
282 /// set flags for blocking
283 void initContext ( int nSkip, bool useLB, bool useAB )
284 {
285 nSkipBeforeBlock = nSkip;
286 useLazyBlocking = useLB;
287 useAnywhereBlocking = useAB;
288 }
289 /// set blocking method for a session
290 void setBlockingMethod ( bool hasInverse, bool hasQCR )
291 {
292 sessionHasInverseRoles = hasInverse;
293 sessionHasNumberRestrictions = hasQCR;
294 }
295 /// add concept C of a type TAG to NODE; call blocking check if appropriate
296 void addConceptToNode ( DlCompletionTree* node, const ConceptWDep& c, bool isComplex )
297 {
298 node->addConcept ( c, isComplex );
299
300 if ( useLazyBlocking )
301 node->setAffected();
302 else
303 detectBlockedStatus(node);
304 }
305
306 // access to nodes
307
308 /// get a root node (non-const)
309 DlCompletionTree* getRoot ( void ) { return NodeBase[0]->resolvePBlocker(); }
310 /// get a root node (const)
311 const DlCompletionTree* getRoot ( void ) const { return NodeBase[0]->resolvePBlocker(); }
312 /// get a node by it's ID
313 DlCompletionTree* getNode ( unsigned int id )
314 {
315 if ( id >= endUsed )
316 return nullptr;
317 return NodeBase[id];
318 }
319 /// get new node (with internal level)
320 DlCompletionTree* getNewNode ( void )
321 {
322 if ( endUsed >= NodeBase.size() )
323 grow();
324 DlCompletionTree* ret = NodeBase[endUsed++];
325 ret->init(branchingLevel);
326 return ret;
327 }
328
329 /// begin (RO) of USED nodes
330 const_iterator begin ( void ) const { return NodeBase.begin(); }
331 /// end (RO) of USED nodes
332 const_iterator end ( void ) const { return NodeBase.begin()+(long)endUsed; }
333 /// begin (RW) of USED nodes
334 iterator begin ( void ) { return NodeBase.begin(); }
335 /// end (RW) of USED nodes
336 iterator end ( void ) { return NodeBase.begin()+(long)endUsed; }
337
338 // blocking
339
340 /// detect blocked status of current node by checking whether NODE and/or its ancestors are d-blocked
341 void detectBlockedStatus ( DlCompletionTree* node );
342 /// update blocked status for d-blocked node
343 void updateDBlockedStatus ( DlCompletionTree* node )
344 {
345 if ( !canBeUnBlocked(node) )
346 return;
347 if ( isStillDBlocked(node) )
348 // FIXME!! clear affected in all children
349 node->clearAffected();
350 else
351 detectBlockedStatus(node);
352 fpp_assert ( !node->isAffected() );
353 }
354 /// retest every d-blocked node in the CG. Use it after the CG was build
355 void retestCGBlockedStatus ( void )
356 {
357 bool repeat;
358 iterator p, p_beg = begin(), p_end = end();
359 do
360 {
361 for ( p = p_beg; p < p_end; ++p )
362 if ( (*p)->isDBlocked() )
363 updateDBlockedStatus(*p);
364
365 // we need to repeat the thing if something became unblocked and then blocked again,
366 // in case one of the blockers became blocked itself; see tModal3 for such an example
367 repeat = false;
368 for ( p = p_beg; p < p_end; ++p )
369 if ( (*p)->isIllegallyDBlocked() )
370 {
371 repeat = true;
372 break;
373 }
374 } while ( repeat );
375 }
376
377 // fairness support
378
379 /// @ return true if a fairness constraint C is violated in one of the loops in the CGraph
380 DlCompletionTree* getFCViolator ( BipolarPointer C ) const
381 {
382 for ( const_iterator p = begin(), p_end = end(); p < p_end; ++p )
383 if ( (*p)->isDBlocked() && !(*p)->isLoopLabelled(C) )
384 return const_cast<DlCompletionTree*>((*p)->Blocker);
385 return nullptr;
386 }
387
388 /// clear all the session statistics
389 void clearStatistics ( void )
390 {
391 nNodeSaves = 0;
392 nNodeRestores = 0;
393 if ( maxGraphSize < endUsed )
394 maxGraphSize = endUsed;
395 }
396 /// mark all heap elements as unused
397 void clear ( void )
398 {
399 CTEdgeHeap.clear();
400 endUsed = 0;
401 branchingLevel = InitBranchingLevelValue;
402 IRLevel = initIRLevel;
403 RareStack.clear();
404 Stack.clear();
405 SavedNodes.clear();
406 initRoot();
407 }
408 /// get number of nodes in the CGraph
409 size_t maxSize ( void ) const { return maxGraphSize; }
410
411 /// save rarely appeared info if P is non-NULL
412 void saveRareCond ( TRestorer* p ) { if (p) RareStack.push(p); }
413 /// get the rare stack
414 TRareSaveStack* getRareStack ( void ) { return &RareStack; }
415
416 //----------------------------------------------
417 // role/node
418 //----------------------------------------------
419
420 /// add role R with dep-set DEP to the label of the TO arc
421 DlCompletionTreeArc* addRoleLabel (
422 DlCompletionTree* from,
423 DlCompletionTree* to,
424 bool isPredEdge,
425 const TRole* R, // name of role (arc label)
426 const DepSet& dep ) // dep-set of the arc label
427 {
428 // check if CGraph already has FROM->TO edge labelled with RNAME
429 DlCompletionTreeArc* ret = from->getEdgeLabelled ( R, to );
430 if ( ret == nullptr )
431 ret = createEdge ( from, to, isPredEdge, R, dep );
432 else
433 saveRareCond(ret->addDep(dep));
434
435 return ret;
436 }
437 /// Create an empty R-neighbour of FROM; @return an edge to created node
438 DlCompletionTreeArc* createNeighbour (
439 DlCompletionTree* from,
440 bool isPredEdge,
441 const TRole* r, // name of role (arc label)
442 const DepSet& dep ) // dep-set of the arc label
443 {
444 if ( RKG_USE_DYNAMIC_BACKJUMPING )
445 fpp_assert ( branchingLevel == dep.level()+1 );
446
447 return createEdge ( from, getNewNode(), isPredEdge, r, dep );
448 }
449 /// Create an R-loop of NODE wrt dep-set DEP; @return a loop edge
450 DlCompletionTreeArc* createLoop ( DlCompletionTree* node, const TRole* r, const DepSet& dep )
451 {
452 return addRoleLabel ( node, node, /*isPredEdge=*/false, r, dep );
453 }
454
455 /// merge node FROM to node TO (do NOT copy label); fill EDGES with new edges added to TO
456 void Merge ( DlCompletionTree* from, DlCompletionTree* to, const DepSet& toAdd,
457 std::vector<DlCompletionTreeArc*>& edges );
458 /// purge node P with given ROOT and DEP-set
459 void purgeNode ( DlCompletionTree* p, const DlCompletionTree* root, const DepSet& dep );
460 /// purge edge E with given ROOT and DEP-set
461 void purgeEdge ( DlCompletionTreeArc* e, const DlCompletionTree* root, const DepSet& dep );
462
463 //----------------------------------------------
464 // inequality relation interface
465 //----------------------------------------------
466
467 /// init new IR set
468 void initIR ( void );
469 /// make given NODE member of current IR set; @return true iff clash occurs
470 bool setCurIR ( DlCompletionTree* node, const DepSet& ds );
471 /// finalise current IR set
472 void finiIR ( void );
473
474 /// check if P and Q are in IR; if so, put the clash-set to DEP
475 bool nonMergeable ( const DlCompletionTree* p, const DlCompletionTree* q, DepSet& dep ) const;
476
477 //----------------------------------------------
478 // save/restore
479 //----------------------------------------------
480
481 /// save given node wrt level
482 void saveNode ( DlCompletionTree* node, unsigned int level )
483 {
484 if ( node->needSave(level) )
485 {
486 node->save(level);
487 SavedNodes.push_back(node);
488 ++nNodeSaves;
489 }
490 }
491 /// restore given node wrt level
492 void restoreNode ( DlCompletionTree* node, unsigned int level )
493 {
494 if ( node->needRestore(level) )
495 {
496 node->restore(level);
497 ++nNodeRestores;
498 }
499 }
500 /// save local state
501 void save ( void );
502 /// restore state for the given LEVEL
503 void restore ( unsigned int level );
504
505 // statistics
506
507 /// get number of nodes saved during session
508 unsigned int getNNodeSaves ( void ) const { return nNodeSaves; }
509 /// get number of nodes restored during session
510 unsigned int getNNodeRestores ( void ) const { return nNodeRestores; }
511
512 // print
513
514 /// print graph starting from the root
515 void Print ( std::ostream& o );
516 }; // DlCompletionGraph
517
518 // blocking
519
520 #if defined(RKG_IR_IN_NODE_LABEL)
521 inline bool
522 DlCompletionGraph :: nonMergeable ( const DlCompletionTree* p, const DlCompletionTree* q, DepSet& dep ) const
523 {
524 return p->nonMergeable ( q, dep );
525 }
526
527 inline void
528 DlCompletionGraph :: updateIR ( DlCompletionTree* p, const DlCompletionTree* q, const DepSet& toAdd )
529 {
530 saveRareCond ( p->updateIR ( q, toAdd ) );
531 }
532
533 inline void
534 DlCompletionGraph :: initIR ( void )
535 {
536 ++IRLevel;
537 }
538
539 inline bool
540 DlCompletionGraph :: setCurIR ( DlCompletionTree* node, const DepSet& ds )
541 {
542 return node->initIR ( IRLevel, ds );
543 }
544
545 inline void
546 DlCompletionGraph :: finiIR ( void ) {}
547
548 #endif // RKG_IR_IN_NODE_LABEL
549
550 #endif