Debian Codegraph @

Kernel/DLConceptTaxonomy.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 /*******************************************************\
21 |* Implementation of taxonomy building for the FaCT++ *|
22 \*******************************************************/
23
24 #include <queue>
25 #include <iostream>
26 #include <fstream>
27
28 #include "Reasoner.h"
29 #include "DLConceptTaxonomy.h"
30 #include "globaldef.h"
31 #include "logging.h"
32
33 /********************************************************\
34 |* Implementation of class Taxonomy *|
35 \********************************************************/
36
37 bool DLConceptTaxonomy :: testSub ( const TConcept* p, const TConcept* q )
38 {
39 fpp_assert ( p != nullptr );
40 fpp_assert ( q != nullptr );
41
42 // std::cout << "Testing sub " << p->getName() << " [= " << q->getName() << std::endl;
43 if ( q->isSingleton() // singleton on the RHS is useless iff...
44 && q->isPrimitive() // it is primitive
45 && !q->isNominal() ) // nominals should be classified as usual concepts
46 return false;
47
48 if ( LLM.isWritable(llTaxTrying) )
49 LL << "\nTAX: trying '" << p->getName() << "' [= '" << q->getName() << "'... ";
50
51 if ( tBox.testSortedNonSubsumption ( p, q ) )
52 {
53 if ( LLM.isWritable(llTaxTrying) )
54 LL << "NOT holds (sorted result)";
55
56 ++nSortedNegative;
57 return false;
58 }
59
60 if ( isNotInModule(q->getEntity()) )
61 {
62 if ( LLM.isWritable(llTaxTrying) )
63 LL << "NOT holds (module result)";
64
65 ++nModuleNegative;
66 return false;
67 }
68
69 switch ( tBox.testCachedNonSubsumption ( p, q ) )
70 {
71 case csValid: // cached result: satisfiable => non-subsumption
72 if ( LLM.isWritable(llTaxTrying) )
73 LL << "NOT holds (cached result)";
74
75 ++nCachedNegative;
76 return false;
77
78 case csInvalid: // cached result: unsatisfiable => subsumption holds
79 if ( LLM.isWritable(llTaxTrying) )
80 LL << "holds (cached result)";
81
82 ++nCachedPositive;
83 return true;
84
85 default: // need extra tests
86 if ( LLM.isWritable(llTaxTrying) )
87 LL << "wasted cache test";
88
89 break;
90 }
91
92 return testSubTBox ( p, q );
93 }
94
95 bool
96 DLConceptTaxonomy :: isNotInModule ( const TNamedEntity* entity ) const
97 {
98 if ( upDirection ) // bottom-up phase
99 return false;
100 const TSignature* sig = sigStack.top();
101 if ( sig && entity && !sig->contains(entity) )
102 return true;
103 return false;
104 }
105
106 TaxonomyCreator::KnownSubsumers*
107 DLConceptTaxonomy :: buildKnownSubsumers ( ClassifiableEntry* ce )
108 {
109 return TaxonomyCreator::buildKnownSubsumers(ce);
110 }
111
112 /// prepare signature for given entry
113 const TSignature*
114 DLConceptTaxonomy :: buildSignature ( ClassifiableEntry* p )
115 {
116 if ( tBox.pName2Sig == nullptr )
117 return nullptr;
118 if ( p->getEntity() == nullptr )
119 return nullptr;
120 TBox::NameSigMap::iterator found = tBox.pName2Sig->find(p->getEntity());
121 if ( found == tBox.pName2Sig->end() )
122 return nullptr;
123 return found->second;
124 }
125
126 void DLConceptTaxonomy :: print ( std::ostream& o ) const
127 {
128 o << "Totally " << nTries << " subsumption tests was made\nAmong them ";
129
130 unsigned long n = ( nTries ? nTries : 1 );
131
132 o << nPositives << " (" << nPositives*100/n << "%) successful\n";
133 o << "Besides that " << nCachedPositive << " successful and " << nCachedNegative
134 << " unsuccessful subsumption tests were cached\n";
135 if ( nSortedNegative )
136 o << "Sorted reasoning deals with " << nSortedNegative << " non-subsumptions\n";
137 if ( nModuleNegative )
138 o << "Modular reasoning deals with " << nModuleNegative << " non-subsumptions\n";
139 o << "There were made " << nSearchCalls << " search calls\nThere were made " << nSubCalls
140 << " Sub calls, of which " << nNonTrivialSubCalls << " non-trivial\n";
141 o << "Current efficiency (wrt Brute-force) is " << nEntries*(nEntries-1)/n << "\n";
142
143 TaxonomyCreator::print(o);
144 }
145
146 // Baader procedures
147 void
148 DLConceptTaxonomy :: searchBaader ( TaxonomyVertex* cur )
149 {
150 // label 'visited'
151 pTax->setVisited(cur);
152
153 ++nSearchCalls;
154 bool noPosSucc = true;
155
156 // check if there are positive successors; use DFS on them.
157 for ( TaxonomyVertex::iterator p = cur->begin(upDirection), p_end = cur->end(upDirection); p != p_end; ++p )
158 if ( enhancedSubs(*p) )
159 {
160 if ( !pTax->isVisited(*p) )
161 searchBaader(*p);
162
163 noPosSucc = false;
164 }
165
166 // in case current node is unchecked (no BOTTOM node) -- check it explicitly
167 if ( !isValued(cur) )
168 setValue ( cur, testSubsumption(cur) );
169
170 // mark labelled leaf node as a parent (self check for incremental)
171 if ( noPosSucc && cur->getValue() && cur != pTax->getCurrent() )
172 pTax->getCurrent()->addNeighbour ( !upDirection, cur );
173 }
174
175 bool
176 DLConceptTaxonomy :: enhancedSubs1 ( TaxonomyVertex* cur )
177 {
178 ++nNonTrivialSubCalls;
179
180 // need to be valued -- check all parents
181 // propagate false
182 for ( TaxonomyVertex::iterator p = cur->begin(!upDirection), p_end = cur->end(!upDirection); p != p_end; ++p )
183 if ( !enhancedSubs(*p) )
184 return false;
185
186 // all subsumptions holds -- test current for subsumption
187 return testSubsumption(cur);
188 }
189
190 bool
191 DLConceptTaxonomy :: testSubsumption ( TaxonomyVertex* cur )
192 {
193 const TConcept* testC = static_cast<const TConcept*>(cur->getPrimer());
194 if ( upDirection )
195 return testSub ( testC, curConcept() );
196 else
197 return testSub ( curConcept(), testC );
198 }
199
200 void
201 DLConceptTaxonomy :: propagateOneCommon ( TaxonomyVertex* node )
202 {
203 // checked if node already was visited this session
204 if ( pTax->isVisited(node) )
205 return;
206
207 // mark node visited
208 pTax->setVisited(node);
209 node->setCommon();
210 if ( node->correctCommon(nCommon) )
211 Common.push_back(node);
212
213 // mark all children
214 for ( TaxonomyVertex::iterator p = node->begin(/*upDirection=*/false), p_end = node->end(/*upDirection=*/false); p != p_end; ++p )
215 propagateOneCommon(*p);
216 }
217
218 bool DLConceptTaxonomy :: propagateUp ( void )
219 {
220 // including node always have some parents (TOP at least)
221 TaxonomyVertex* Current = pTax->getCurrent();
222 TaxonomyVertex::iterator p = Current->begin(/*upDirection=*/true), p_end = Current->end(/*upDirection=*/true);
223 fpp_assert ( p != p_end ); // there is at least one parent (TOP)
224
225 TaxVertexVec aux; // aux set for the vertices in ...
226 nCommon = 1; // number of common parents
227 clearCommon();
228
229 // define possible successors of the node
230 propagateOneCommon(*p);
231 pTax->clearVisited();
232
233 for ( ++p; p != p_end; ++p )
234 {
235 if ( (*p)->noNeighbours(/*upDirection=*/false) )
236 return true;
237 if ( Common.empty() )
238 return true;
239
240 ++nCommon;
241 // now Aux contain data from previous run
242 aux.swap(Common);
243 Common.clear();
244 propagateOneCommon(*p);
245 pTax->clearVisited();
246
247 // clear all non-common nodes (visited on a previous run)
248 for ( TaxVertexVec::iterator q = aux.begin(), q_end = aux.end(); q < q_end; ++q )
249 (*q)->correctCommon(nCommon);
250 }
251
252 return false;
253 }
254
255 /// check if no BU classification is required as C=TOP
256 bool
257 DLConceptTaxonomy :: isEqualToTop ( void )
258 {
259 // check this up-front to avoid Sorted check's flaw wrt equals-to-top
260 const modelCacheInterface* cache = tBox.initCache ( curConcept(), /*sub=*/true );
261 if ( cache->getState() != csInvalid )
262 return false;
263 // here concept = TOP
264 pTax->getCurrent()->addNeighbour ( /*upDirection=*/false, pTax->getTopVertex() );
265 return true;
266 }
267
268 /// @return true iff curEntry is classified as a synonym
269 bool
270 DLConceptTaxonomy :: classifySynonym ( void )
271 {
272 if ( TaxonomyCreator::classifySynonym() )
273 return true;
274
275 if ( curConcept()->isSingleton() )
276 {
277 TIndividual* curI = (TIndividual*)const_cast<TConcept*>(curConcept());
278
279 if ( unlikely(tBox.isBlockedInd(curI)) )
280 { // check whether current entry is the same as another individual
281 TIndividual* syn = tBox.getBlockingInd(curI);
282 fpp_assert ( syn->getTaxVertex() != nullptr );
283
284 if ( tBox.isBlockingDet(curI) )
285 { // deterministic merge => curI = syn
286 pTax->addCurrentToSynonym(syn->getTaxVertex());
287 return true;
288 }
289 else // non-det merge: check whether it is the same
290 {
291 if ( LLM.isWritable(llTaxTrying) )
292 LL << "\nTAX: trying '" << curI->getName() << "' = '" << syn->getName() << "'... ";
293 if ( testSubTBox ( curI, syn ) ) // they are actually the same
294 {
295 pTax->addCurrentToSynonym(syn->getTaxVertex());
296 return true;
297 }
298 }
299 }
300 }
301
302 return false;
303 }
304
305 void /// fill candidates
306 DLConceptTaxonomy :: fillCandidates ( TaxonomyVertex* cur )
307 {
308 // std::cout << "fill candidates: " << cur->getPrimer()->getName() << std::endl;
309 if ( isValued(cur) )
310 {
311 if ( getValue(cur) ) // positive value -- nothing to do
312 return;
313 }
314 else
315 candidates.insert(cur);
316
317 for ( TaxonomyVertex::iterator p = cur->begin(true), p_end = cur->end(true); p != p_end; ++p )
318 fillCandidates(*p);
319 }
320
321 void
322 DLConceptTaxonomy :: reclassify ( const std::set<const TNamedEntity*>& plus, const std::set<const TNamedEntity*>& minus )
323 {
324 MPlus = plus;
325 MMinus = minus;
326 pTax->deFinalise();
327
328 // fill in an order to
329 std::queue<TaxonomyVertex*> queue;
330 std::vector<const ClassifiableEntry*> toProcess;
331 queue.push(pTax->getTopVertex());
332 while ( !queue.empty() )
333 {
334 TaxonomyVertex* cur = queue.front();
335 queue.pop();
336 if ( pTax->isVisited(cur) )
337 continue;
338 pTax->setVisited(cur);
339 const ClassifiableEntry* entry = cur->getPrimer();
340 const TNamedEntity* entity = entry->getEntity();
341 if ( MPlus.find(entity) != MPlus.end() || MMinus.find(entity) != MMinus.end() )
342 toProcess.push_back(entry);
343 for ( TaxonomyVertex::iterator p = cur->begin(/*upDirection=*/false), p_end = cur->end(/*upDirection=*/false); p != p_end; ++p )
344 queue.push(*p);
345 }
346 pTax->clearVisited();
347 // std::cout << "Add/Del names Taxonomy:\n";
348 // pTax->print(std::cout);
349
350 for ( const ClassifiableEntry* entry : toProcess )
351 {
352 TaxonomyVertex* node = entry->getTaxVertex();
353 const TNamedEntity* entity = entry->getEntity();
354 std::cout << "Reclassify " << entity->getName() << " (" << (MPlus.count(entity) > 0 ?"Added":"") << (MMinus.count(entity) > 0 ?" Removed":"") << ")";
355
356 TsProcTimer timer;
357 timer.Start();
358 reclassify ( node, (*tBox.pName2Sig)[entity] );
359 timer.Stop();
360 std::cout << "; reclassification time: " << timer << std::endl;
361 // tax->print(std::cout);
362 // std::cout.flush();
363 }
364
365 pTax->finalise();
366 // print(std::cout);
367 // std::cout.flush();
368 }
369
370 void
371 DLConceptTaxonomy :: reclassify ( TaxonomyVertex* node, const TSignature* s )
372 {
373 upDirection = false;
374 sigStack.push(s);
375 curEntry = node->getPrimer();
376 TaxonomyVertex* oldCur = pTax->getCurrent();
377 pTax->setCurrent(node);
378
379 // FIXME!! check the unsatisfiability later
380
381 bool added = MPlus.count(curEntry->getEntity()) > 0;
382 bool removed = MMinus.count(curEntry->getEntity()) > 0;
383 fpp_assert ( added || removed );
384 typedef std::vector<TaxonomyVertex*> TVArray;
385 clearLabels();
386
387 setValue ( pTax->getTopVertex(), true );
388 if ( node->noNeighbours(true) )
389 node->addNeighbour(true, pTax->getTopVertex());
390
391 // we use candidates set if nothing was added (so no need to look further from current subs)
392 useCandidates = !added;
393 candidates.clear();
394 if ( removed ) // re-check all parents
395 {
396 TVArray pos, neg;
397 for ( TaxonomyVertex::iterator p = node->begin(true), p_end = node->end(true); p != p_end; ++p )
398 {
399 if ( isValued(*p) && getValue(*p) )
400 continue;
401 bool sub = testSubsumption(*p);
402 if ( sub )
403 {
404 pos.push_back(*p);
405 propagateTrueUp(*p);
406 }
407 else
408 {
409 setValue ( *p, sub );
410 neg.push_back(*p);
411 }
412 }
413 node->removeLinks(true);
414 // for ( TVArray::iterator q = pos.begin(), q_end = pos.end(); q != q_end; ++q )
415 // node->addNeighbour(true, *q);
416 if ( useCandidates )
417 for ( TaxonomyVertex* vertex : neg )
418 fillCandidates(vertex);
419 }
420 else // all parents are there
421 {
422 for ( TaxonomyVertex::iterator p = node->begin(true), p_end = node->end(true); p != p_end; ++p )
423 propagateTrueUp(*p);
424 node->removeLinks(true);
425 }
426
427 // FIXME!! for now. later check the equivalence etc
428 setValue ( node, true );
429 // the landscape is prepared
430 searchBaader(pTax->getTopVertex());
431 node->incorporate();
432 clearLabels();
433 sigStack.pop();
434 pTax->setCurrent(oldCur);
435 }
436
437 /********************************************************\
438 |* Implementation of class TBox *|
439 \********************************************************/
440
441 void TBox :: createTaxonomy ( bool needIndividual )
442 {
443 bool needConcept = !needIndividual;
444
445 // if there were SAT queries before -- the query (or other) concepts are there. Delete it
446 clearQueryConcept();
447
448 // here we sure that ontology is consistent
449 // FIXME!! distinguish later between the 1st run and the following runs
450 if ( pTax == nullptr ) // 1st run
451 initTaxonomy();
452
453 DLHeap.setSubOrder(); // init priorities in order to do subsumption tests
454 pTaxCreator->setBottomUp(GCIs);
455 needConcept |= needIndividual; // together with concepts
456 // else // not a first run
457 // return; // FIXME!! now we don't perform staged reasoning, so everything is done
458 /*
459 {
460 fpp_assert ( needIndividual );
461 pTax->deFinalise();
462 }
463 */
464 if ( verboseOutput )
465 std::cerr << "Processing query...";
466
467 TsProcTimer locTimer;
468 locTimer.Start();
469
470 // calculate number of items to be classified
471 unsigned int nItems = 0;
472
473 // fills collections
474 arrayCD.clear();
475 arrayNoCD.clear();
476 arrayNP.clear();
477
478 // if ( needConcept )
479 nItems += fillArrays ( c_begin(), c_end() );
480 // if ( needIndividual || nNominalReferences > 0 ) // TODO ORE
481 nItems += fillArrays ( i_begin(), i_end() );
482
483 // taxonomy progress
484 if ( pMonitor )
485 {
486 pMonitor->setClassificationStarted(nItems);
487 pTaxCreator->setProgressIndicator(pMonitor);
488 }
489
490 // sort ( arrayCD.begin(), arrayCD.end(), TSDepthCompare() );
491 classifyConcepts ( arrayCD, true, "completely defined" );
492 // sort ( arrayNoCD.begin(), arrayNoCD.end(), TSDepthCompare() );
493 classifyConcepts ( arrayNoCD, false, "regular" );
494 // sort ( arrayNP.begin(), arrayNP.end(), TSDepthCompare() );
495 classifyConcepts ( arrayNP, false, "non-primitive" );
496
497 if ( pMonitor )
498 {
499 pMonitor->setFinished();
500 setProgressMonitor(nullptr); // no need of PM after classification done
501 pTaxCreator->setProgressIndicator(nullptr);
502 }
503 pTax->finalise();
504
505 locTimer.Stop();
506 if ( verboseOutput )
507 std::cerr << " done in " << locTimer << " seconds\n";
508
509 if ( needConcept && Status < kbClassified )
510 Status = kbClassified;
511 if ( needIndividual )
512 Status = kbRealised;
513
514 if ( verboseOutput/* && needIndividual*/ )
515 {
516 std::ofstream of("Taxonomy.log");
517 pTaxCreator->print(of);
518 }
519 }
520
521 void
522 TBox :: classifyConcepts ( const ConceptVector& collection, bool curCompletelyDefined, const char* type )
523 {
524 // set CD for taxonomy
525 pTaxCreator->setCompletelyDefined(curCompletelyDefined);
526
527 if ( LLM.isWritable(llStartCfyConcepts) )
528 LL << "\n\n---Start classifying " << type << " concepts";
529
530 unsigned int n = 0;
531
532 for ( ConceptVector::const_iterator q = collection.begin(), q_end = collection.end(); q < q_end; ++q )
533 // check if concept is already classified
534 if ( !isCancelled() && !(*q)->isClassified () /*&& (*q)->isClassifiable(curCompletelyDefined)*/ )
535 {
536 classifyEntry(*q); // need to classify concept
537 if ( (*q)->isClassified() )
538 ++n;
539 }
540
541 if ( LLM.isWritable(llStartCfyConcepts) )
542 LL << "\n---Done: " << n << " " << type << " concepts classified";
543 }