Debian Codegraph @

FaCT++.Python/lib/Kernel/Preprocess.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 <fstream>
21 #include <iostream>
22
23 #include "dlTBox.h"
24
25 #include "procTimer.h"
26 #include "logging.h"
27
28 //#define DEBUG_PREPROCESSING
29
30 #ifdef DEBUG_PREPROCESSING
31 # define BEGIN_PASS(str) std::cerr << "\n" str "... "
32 # define END_PASS() std::cerr << "done"
33 #else
34 # define BEGIN_PASS(str)
35 # define END_PASS()
36 #endif
37
38 void TBox :: Preprocess ( void )
39 {
40 if ( verboseOutput )
41 std::cerr << "Preprocessing...";
42 TsProcTimer pt;
43 pt.Start();
44
45 // builds role hierarchy
46 BEGIN_PASS("Build role hierarchy");
47 ORM.initAncDesc();
48 DRM.initAncDesc();
49 END_PASS();
50
51 if ( verboseOutput )
52 {
53 std::ofstream oroles("Taxonomy.ORoles");
54 ORM.getTaxonomy()->print(oroles);
55 std::ofstream droles("Taxonomy.DRoles");
56 DRM.getTaxonomy()->print(droles);
57 }
58
59 // all concept descriptions contains synonyms. Remove them now
60 BEGIN_PASS("Replace synonyms in expressions");
61 if ( countSynonyms() > 0 )
62 replaceAllSynonyms();
63 END_PASS();
64
65 // preprocess Related structure (before classification tags are defined)
66 BEGIN_PASS("Preprocess related axioms");
67 preprocessRelated();
68 END_PASS();
69
70 // FIXME!! find a proper place for this
71 TransformExtraSubsumptions();
72
73 // init told subsumers as they would be used soon
74 BEGIN_PASS("Init told subsumers");
75 initToldSubsumers();
76 END_PASS();
77
78 // locate told (definitional) cycles and transform them into synonyms
79 BEGIN_PASS("Detect and replace told cycles");
80 transformToldCycles();
81 END_PASS();
82
83 // detect singleton with singleton parents and make them synonyms
84 BEGIN_PASS("Detect and transform singleton hierarchy");
85 transformSingletonHierarchy();
86 END_PASS();
87
88 // absorb axioms (move some Axioms to Role and Concept Description)
89 BEGIN_PASS("Perform absorption");
90 AbsorbAxioms();
91 END_PASS();
92
93 // set told TOP concepts whether necessary
94 BEGIN_PASS("Set told TOP");
95 setToldTop();
96 END_PASS();
97
98 // no more axiom transformations allowed
99
100 // create DAG (concept normalisation etc)
101 BEGIN_PASS("Build DAG");
102 buildDAG();
103 END_PASS();
104
105 // fills classification tag (strictly after told cycles)
106 BEGIN_PASS("Detect classification tags");
107 fillsClassificationTag();
108 END_PASS();
109
110 // set up TS depth
111 BEGIN_PASS("Calculate told subsumer depth");
112 calculateTSDepth();
113 END_PASS();
114
115 // set indexes for model caching
116 BEGIN_PASS("Set all indexes");
117 setAllIndexes();
118 END_PASS();
119
120 // create sorts for KB
121 BEGIN_PASS("Determine sorts");
122 determineSorts();
123 END_PASS();
124
125 // calculate statistic for the whole KB:
126 BEGIN_PASS("Gather relevance info");
127 gatherRelevanceInfo();
128 END_PASS();
129
130 // here it is safe to print KB features (all are known; the last one was in Relevance)
131 printFeatures();
132
133 // GALEN-like flag is known here, so we can set OR defaults
134 BEGIN_PASS("Set defaults for OR orderings");
135 DLHeap.setOrderDefaults (
136 isGalenLikeTBox() ? "Fdn" : isWineLikeTBox() ? "Sdp" : "Sap", // SAT settings
137 isGalenLikeTBox() ? "Ban" : isWineLikeTBox() ? "Fdn" : "Dap" // SUB settings
138 );
139 END_PASS();
140
141 // now we can gather DAG statistics (if necessary)
142 BEGIN_PASS("Gather usage statistics");
143 DLHeap.gatherStatistic();
144 END_PASS();
145
146 // calculate statistic on DAG and Roles
147 BEGIN_PASS("Gather concept-related statistics");
148 CalculateStatistic();
149 END_PASS();
150
151 // free extra memory
152 BEGIN_PASS("Free unused memory");
153 RemoveExtraDescriptions();
154 END_PASS();
155
156 pt.Stop();
157 preprocTime = pt;
158 if ( verboseOutput )
159 std::cerr << " done in " << pt << " seconds\n";
160 }
161
162 static bool
163 replaceSynonymsFromTree ( DLTree* desc )
164 {
165 if ( desc == nullptr )
166 return false;
167
168 if ( isName(desc) )
169 {
170 TLexeme& cur = desc->Element(); // not const
171 ClassifiableEntry* entry = static_cast<ClassifiableEntry*>(cur.getNE());
172
173 if ( entry->isSynonym() )
174 {
175 entry = resolveSynonym(entry);
176 // check for TOP/BOTTOM
177 if ( entry->isTop() )
178 cur = TLexeme(TOP);
179 else if ( entry->isBottom() )
180 cur = TLexeme(BOTTOM);
181 else
182 cur = TLexeme ( static_cast<TConcept*>(entry)->isSingleton() ? INAME : CNAME, entry );
183 return true;
184 }
185 else
186 return false;
187 }
188 else
189 {
190 bool ret = replaceSynonymsFromTree ( desc->Left() );
191 ret |= replaceSynonymsFromTree ( desc->Right() );
192 return ret;
193 }
194 }
195
196 void TBox :: replaceAllSynonyms ( void )
197 {
198 // replace synonyms in role's domain
199 for ( const auto& oRole: ORM )
200 if ( !oRole->isSynonym() )
201 replaceSynonymsFromTree ( oRole->getTDomain() );
202 for ( const auto& dRole: DRM )
203 if ( !dRole->isSynonym() )
204 replaceSynonymsFromTree ( dRole->getTDomain() );
205
206 for ( c_iterator pc = c_begin(); pc != c_end(); ++pc )
207 if ( replaceSynonymsFromTree ( (*pc)->Description ) )
208 (*pc)->initToldSubsumers();
209 for ( i_iterator pi = i_begin(); pi != i_end(); ++pi )
210 if ( replaceSynonymsFromTree ( (*pi)->Description ) )
211 (*pi)->initToldSubsumers();
212 }
213
214 void TBox :: preprocessRelated ( void )
215 {
216 for ( auto& related: RelatedI )
217 related->simplify();
218 }
219
220 void TBox :: transformToldCycles ( void )
221 {
222 // remember number of synonyms appeared in KB
223 unsigned int nSynonyms = countSynonyms();
224
225 clearRelevanceInfo();
226 for ( c_iterator pc = c_begin(); pc != c_end(); ++pc )
227 if ( !(*pc)->isSynonym() )
228 checkToldCycle(*pc);
229
230 for ( i_iterator pi = i_begin(); pi != i_end(); ++pi )
231 if ( !(*pi)->isSynonym() )
232 checkToldCycle(*pi);
233 clearRelevanceInfo();
234
235 // update number of synonyms
236 nSynonyms = countSynonyms() - nSynonyms;
237 if ( nSynonyms )
238 {
239 if ( LLM.isWritable(llAlways) )
240 LL << "\nTold cycle elimination done with " << nSynonyms << " synonyms created";
241
242 replaceAllSynonyms();
243 }
244 }
245
246 TConcept* TBox :: checkToldCycle ( TConcept* p )
247 {
248 fpp_assert ( p != nullptr ); // safety check
249
250 // resolve synonym (if happens) to prevent cases like A[=B[=C[=A, A[=D[=B
251 p = resolveSynonym(p);
252
253 // no reason to process TOP here
254 if ( p == pTop )
255 return nullptr;
256
257 // if we found a cycle...
258 if ( CInProcess.find(p) != CInProcess.end() )
259 {
260 // std::cout << "Cycle with " << p->getName() << std::endl;
261 return p;
262 }
263
264 if ( isRelevant(p) )
265 {
266 // std::cout << "Already checked: " << p->getName() << std::endl;
267 return nullptr;
268 }
269
270 TConcept* ret = nullptr;
271
272 // add concept in processing
273 CInProcess.insert(p);
274
275 redo:
276
277 // std::cout << "Start from " << p->getName() << std::endl;
278
279 for ( auto r: p->told() )
280 // if cycle was detected
281 if ( (ret = checkToldCycle(static_cast<TConcept*>(r))) != nullptr )
282 {
283 if ( ret == p )
284 {
285 // std::cout << "Fill cycle with " << p->getName() << std::endl;
286 ToldSynonyms.push_back(p);
287
288 // find a representative for the cycle; nominal is preferable
289 for ( auto& rep: ToldSynonyms )
290 if ( rep->isSingleton() )
291 p = rep;
292 // now p is a representative for all the synonyms
293
294 // fill the description
295 DLTree* desc = nullptr;
296 for ( auto& syn: ToldSynonyms )
297 if ( syn != p ) // make it a synonym of RET, save old desc
298 {
299 desc = createSNFAnd ( desc, makeNonPrimitive ( syn, getTree(p) ) );
300 // check whether we had an extra definition for Q
301 ConceptDefMap::iterator extra = ExtraConceptDefs.find(syn);
302 if ( extra != ExtraConceptDefs.end() )
303 {
304 desc = createSNFAnd ( desc, extra->second );
305 ExtraConceptDefs.erase(extra);
306 }
307 }
308
309 ToldSynonyms.clear();
310
311 // mark the returned concept primitive (to allow addDesc to work)
312 p->setPrimitive();
313 p->addDesc(desc);
314
315 // replace all synonyms with TOP
316 p->removeSelfFromDescription();
317
318 // re-run the search starting from new sample
319 if ( ret != p ) // need to fix the stack
320 {
321 CInProcess.erase(ret);
322 CInProcess.insert(p);
323 ret->setRelevant(relevance);
324 p->dropRelevant(relevance);
325 }
326
327 ret = nullptr;
328 goto redo;
329 }
330 else
331 {
332 ToldSynonyms.push_back(p);
333 // no need to continue; finish with this cycle first
334 break;
335 }
336 }
337
338 // remove processed concept from set
339 CInProcess.erase(p);
340
341 p->setRelevant(relevance);
342 // std::cout << "Done with " << p->getName() << std::endl;
343
344 return ret;
345 }
346
347 /// transform i [= C [= j into i=C=j for i,j nominals
348 void
349 TBox :: transformSingletonHierarchy ( void )
350 {
351 // remember number of synonyms appeared in KB
352 unsigned int nSynonyms = countSynonyms();
353
354 // cycle until no new synonyms are created
355 bool changed;
356
357 do
358 {
359 changed = false;
360
361 for ( i_iterator pi = i_begin(); pi != i_end(); ++pi )
362 if ( !(*pi)->isSynonym() && (*pi)->isHasSP() )
363 {
364 TIndividual* i = transformSingletonWithSP(*pi);
365 i->removeSelfFromDescription();
366 changed = true;
367 }
368 } while ( changed );
369
370 // update number of synonyms
371 nSynonyms = countSynonyms() - nSynonyms;
372 if ( nSynonyms )
373 replaceAllSynonyms();
374 }
375
376 /// helper to the transformSingletonWithSP() function
377 TIndividual*
378 TBox :: getSPForConcept ( TConcept* p )
379 {
380 for ( auto r: p->told() )
381 {
382 TConcept* i = static_cast<TConcept*>(r);
383 if ( i->isSingleton() ) // found the end of the chain
384 return static_cast<TIndividual*>(i);
385 if ( i->isHasSP() ) // found the continuation of the chain
386 return transformSingletonWithSP(i);
387 }
388 // will always found the entry
389 fpp_unreachable();
390 }
391
392 /// make P and all its non-singleton parents synonyms to its singleton parent
393 TIndividual*
394 TBox :: transformSingletonWithSP ( TConcept* p )
395 {
396 TIndividual* i = getSPForConcept(p);
397
398 // make p a synonym of i
399 if ( p->isSingleton() )
400 i->addRelated(static_cast<TIndividual*>(p));
401 addSubsumeAxiom ( i, makeNonPrimitive ( p, getTree(i) ) );
402
403 return i;
404 }
405
406 /// @return true if C is referenced in TREE; use PROCESSED to record explored names
407 bool
408 TBox :: isReferenced ( TConcept* C, DLTree* tree, ConceptSet& processed ) const
409 {
410 fpp_assert ( tree != nullptr );
411 switch ( tree->Element().getToken() )
412 {
413 // names
414 case CNAME:
415 case INAME:
416 {
417 TConcept* D = toConcept(tree->Element().getNE());
418 // check whether we found cycle
419 if ( C == D )
420 return true;
421 // check if we already processed D
422 if ( processed.count(D) > 0 )
423 return false;
424 // recurse here
425 return isReferenced ( C, D, processed );
426 }
427
428 // binary concept operations
429 case AND:
430 case OR:
431 return isReferenced ( C, tree->Left(), processed ) || isReferenced ( C, tree->Right(), processed );
432
433 // operations with a single concept
434 case NOT:
435 return isReferenced ( C, tree->Left(), processed );
436 case EXISTS:
437 case FORALL:
438 case GE:
439 case LE:
440 return isReferenced ( C, tree->Right(), processed );
441
442 // operations w/o concept
443 case SELF:
444 case TOP:
445 case BOTTOM:
446 return false;
447
448 // non-concept expressions: should not be here
449 case INV:
450 case RCOMPOSITION: // role composition
451 case PROJINTO: // role projection into
452 case PROJFROM: // role projection from
453 case DATAEXPR: // any data expression: data value, [constrained] datatype
454 case RNAME:
455 case DNAME:
456 fpp_unreachable();
457
458 default: // just for safety: all possible options were checked
459 fpp_unreachable();
460 }
461 }
462
463 /// transform C [= E with C = D into GCIs
464 void
465 TBox :: TransformExtraSubsumptions ( void )
466 {
467 auto p = ExtraConceptDefs.begin(), p_end = ExtraConceptDefs.end();
468
469 while ( p != p_end )
470 {
471 TConcept* C = p->first;
472 DLTree* E = p->second;
473 // for every C here we have C = D in KB and C [= E in ExtraConceptDefs
474 // if there is a cycle for C
475 if ( isCyclic(C) )
476 {
477 DLTree* D = clone(C->Description);
478 // then we should make C [= (D and E) and go with GCI D [= C
479 makeDefinitionPrimitive ( C, E, D );
480 }
481 else // it is safe to keep definition C = D and go with GCI C [= E
482 processGCI ( getTree(C), E );
483 // remove processed entry from the set, reset the pointer
484 p = ExtraConceptDefs.erase(p);
485 }
486 }
487
488 void
489 TBox :: setAllIndexes ( void )
490 {
491 ++nC; // place for the query concept
492 nR = 0; // start with 1 to make index 0 an indicator of "not processed"
493 auto setRoleIndex = [&] (TRole* R) { if ( !R->isSynonym() ) R->setIndex(++nR); };
494 std::for_each ( ORM.begin(), ORM.end(), setRoleIndex );
495 std::for_each ( DRM.begin(), DRM.end(), setRoleIndex );
496 // make nR be a number of indexed roles
497 ++nR;
498 }
499
500 /// determine all sorts in KB (make job only for SORTED_REASONING)
501 void TBox :: determineSorts ( void )
502 {
503 #ifdef RKG_USE_SORTED_REASONING
504 // Related individuals does not appears in DLHeap,
505 // so their sorts shall be determined explicitly
506 for ( RelatedCollection::const_iterator p = RelatedI.begin(), p_end = RelatedI.end(); p < p_end; ++p, ++p )
507 DLHeap.updateSorts ( (*p)->a->pName, (*p)->R, (*p)->b->pName );
508
509 // simple rules needs the same treatment
510 for ( const auto& rule: SimpleRules )
511 {
512 mergeableLabel& lab = DLHeap[rule->bpHead].getSort();
513 for ( const auto& atom: rule->Body )
514 DLHeap.merge ( lab, atom->pName );
515 }
516
517 // create sorts for concept and/or roles
518 DLHeap.determineSorts ( ORM, DRM );
519 #endif // RKG_USE_SORTED_REASONING
520 }
521
522 // Told stuff is used here, so run this AFTER fillTold*()
523 void TBox :: CalculateStatistic ( void )
524 {
525 // skip all statistic if no logging needed
526 CHECK_LL_RETURN(llAlways);
527
528 unsigned int npFull = 0, nsFull = 0; // number of completely defined concepts
529 unsigned int nPC = 0, nNC = 0, nSing = 0; // number of primitive, non-prim and singleton concepts
530 unsigned int nNoTold = 0; // number of concepts w/o told subsumers
531
532 auto getCStat = [&] (const TConcept* C) {
533 if ( isValid(C->pName) )
534 {
535 if ( C->isSingleton() )
536 ++nSing;
537 if ( C->isPrimitive() )
538 ++nPC;
539 else if ( C->isNonPrimitive() )
540 ++nNC;
541
542 if ( C->isSynonym () )
543 ++nsFull;
544
545 if ( C->isCompletelyDefined() )
546 {
547 if ( C->isPrimitive() )
548 ++npFull;
549 }
550 else
551 if ( !C->hasToldSubsumers() )
552 ++nNoTold;
553 }
554 };
555 // calculate statistic for all concepts
556 std::for_each ( c_begin(), c_end(), getCStat );
557 // calculate statistic for all individuals
558 std::for_each ( i_begin(), i_end(), getCStat );
559 // output all statistics
560 LL << "There are " << nPC << " primitive concepts used\n";
561 LL << " of which " << npFull << " completely defined\n";
562 LL << " and " << nNoTold << " has no told subsumers\n";
563 LL << "There are " << nNC << " non-primitive concepts used\n";
564 LL << " of which " << nsFull << " synonyms\n";
565 LL << "There are " << nSing << " individuals or nominals used\n";
566 }
567
568 void TBox::RemoveExtraDescriptions ( void )
569 {
570 // remove DLTree* from all named concepts
571 auto removeDescription = [] (TConcept* C) { C->removeDescription(); };
572 std::for_each ( c_begin(), c_end(), removeDescription );
573 std::for_each ( i_begin(), i_end(), removeDescription );
574 }
575