FaCTpp-src-v1.6.2~dfsg/0000755000000000000000000000000012112642532013346 5ustar rootrootFaCTpp-src-v1.6.2~dfsg/README0000644000000000000000000001060212042532200014215 0ustar rootrootThis is a README file for the FaCT++ v1.1.6 reasoner distribution. This file contains following information 1. Introduction 2. Contents of distribution 3. Installation 4. Usage 5. Known problems 6. Contact information 1. Introduction --------------- FaCT++ is re-implementation of the well-known FaCT Description Logic (DL) Reasoner. This reasoner currently supports the SROIQ(D) description Logic language, which corresponds to OWL DL ontology language standard. The current version is 1.1.6. This is source distribution package so it can be used on different platforms. It was tested on Windows, Linux and MacOS X. FaCT++ is distributed under GNU Public License (GPL). Full text of license can be found at http://www.gnu.org/licenses/gpl.txt. Libraries that are provided by the FaCT++ are distributed under the GNU Lesser Public License (LGPL). 2. Contents of distribution --------------------------- file description - src/ FaCT++ source code - bin/ and lib/ FaCT++ precompiled binaries - Models.lisp/ examples and infrastructure for FaCT++ lisp reasoner - licensing/ license information - README this file 3. Installation --------------- 3.1 Building system from sources -------------------------------- For building system you will need GNU c++ compiler and GNU make (version 3.3 and higher were tested). Change GENERAL_DEFINES macro in src/Makefile.include to make it suitable for your computer. Then just run "make". In order to compile DIG part you will also need an XML parsing library Xerces-c (freely avaliable at http://xml.apache.org/xerces-c/). Make sure that Xerces-c package is installed system-wide or you have environment variable XERCESCROOT which points to Xerces-c root directory. In order to compile OWL-API interface (src/FaCTPlusPlusJNI/) it is necessary to have JNI development files (jni.h) available. 4. Usage -------- 4.1 Standalone FaCT++ with lisp-like interface ---------------------------------------------- Models.lisp directory of this distribution contains some files that support FaCT++ reasoning as well as examples of KBs. To use standalone reasoner user should usually perform the following steps: - create an ontology using the FaCT++ input language - create a working directory (i.e. TEST) for FaCT++ using the command create-new-test TEST ontology where "ontology" is the name of the file containing your FaCT++ ontology - inside TEST directory run make This will run FaCT++ reasoner on the newly created config-file for the given ontology. The results of FaCT++'s reasoning appear in following files: - Taxonomy.Roles contains information about the roles taxonomy; - Taxonomy.log contains information about the concept taxonomy (if it was requested); - dl.res contains full information about the ontology and some statistical information about the reasoning process; 4.1.1 Ontology creation ----------------------- There are three ways of creating an ontology for FaCT++ - Hand-made ontology. This way is not recommended for the end user. - Using OilEd (http://oiled.man.ac.uk). Load an ontology to the OilEd then choose Export|FaCT++ lisp. - From the OWL source using the OWL Ontology Converter (http://phoebus.cs.man.ac.uk:9999/OWL/Converter). Set the ontology URL to the OWL ontology, choose FaCT++ as the output language, press Convert and then copy the resulting ontology text to the FaCT++ ontology file. 4.1.2 Reasoning process ----------------------- There are a number of options that could influence the reasoning process. All options, their format and description are given in the config file, which is generated by the create-new-test script. 4.2 FaCT++ as an HTTP DIG reasoner ---------------------------------- Run FaCT++.Server with optional parameter "-port ". Default value of is 3490. This reasoner will avaliable at http://:, where is a name of a computer running FaCT++.Server. 4.3 FaCT++ as an HTTP OWL reasoner --------------------------------- Use FaCT++ as describe in section 4.2. Then connect your OWL editor like Protege (http://protege.stanford.edu/) to the FaCT++ using address http://: 5. Known problems ----------------- 6. Contact information ---------------------- For any problems concerning FaCT++ please contact Dmitry Tsarkov (tsarkov@cs.man.ac.uk). Any questions, suggestions or bug reports are welcome! Last updated: 01/05/2007 FaCTpp-src-v1.6.2~dfsg/licensing/0000755000000000000000000000000012042532200015311 5ustar rootrootFaCTpp-src-v1.6.2~dfsg/licensing/gpl.txt0000644000000000000000000004313112042532200016636 0ustar rootroot GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc. 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Library General Public License instead of this License. FaCTpp-src-v1.6.2~dfsg/licensing/FaCT++.license.txt0000644000000000000000000000167712042532200020411 0ustar rootrootCopyright (c) The Victoria University of Manchester 2004 This program is free software; you can redistribute it and/or modif y it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Any questions relating to this software should be directed to: Dmitry Tsarkov Department of Computer Science University of Manchester Room 2.90 Kilburn Building Oxford Road Manchester M13 9PL UK email: tsarkov@cs.man.ac.uk FaCTpp-src-v1.6.2~dfsg/licensing/README.buddy0000644000000000000000000001143612042532200017304 0ustar rootroot========================================================================== *** BuDDy *** Binary Decision Diagrams Library Package v2.2 -------------------------------------------------------------------------- Copyright (C) 1996-2002 by Jorn Lind-Nielsen All rights reserved Permission is hereby granted, without written agreement and without license or royalty fees, to use, reproduce, prepare derivative works, distribute, and display this software and its documentation for any purpose, provided that (1) the above copyright notice and the following two paragraphs appear in all copies of the source code and (2) redistributions, including without limitation binaries, reproduce these notices in the supporting documentation. Substantial modifications to this software may be copyrighted by their authors and need not follow the licensing terms described here, provided that the new terms are clearly indicated in all files where they apply. IN NO EVENT SHALL JORN LIND-NIELSEN, OR DISTRIBUTORS OF THIS SOFTWARE BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE AUTHORS OR ANY OF THE ABOVE PARTIES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. JORN LIND-NIELSEN SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. ========================================================================== --------------------------------------------------------------------- --- REQUIREMENTS ---------------------------------------------------- --------------------------------------------------------------------- * A (not to old) C++ compiler * A machine that supports 32 bit integers --------------------------------------------------------------------- --- INSTALLING ------------------------------------------------------ --------------------------------------------------------------------- 2) Edit the file "config" to specify your compiler options and where the package is to be installed. 3) type "make" to make the binary. 4) type "make install" to copy the BDD files to their appropriate directories. 5) type "make examples" to make the examples --------------------------------------------------------------------- --- USING ----------------------------------------------------------- --------------------------------------------------------------------- Assuming that the files "bdd.h" and "libbdd.a" are in directories "/usr/local/include" and "/usr/local/lib" then the compile command could be: g++ -I/usr/local/include myfile.cc -o myfile -L/usr/local/lib -lbdd Your machine may be setup to use the above directories auto- matically, so you might be able to do: g++ myfile.cc -o myfile -lbdd --------------------------------------------------------------------- --- FILES ----------------------------------------------------------- --------------------------------------------------------------------- src: All files needed for the BuDDy package. examples: Example files fdd: An example of use of the FDD interface. calculator: An example of a BDD calculator. Uses reordering. adder: Construction of a N-bit adder. Uses reordering. milner: A calculation of the reachable statespace for Milner's scheduler. C++. cmilner: As above but purely in ANSI-C. queen: Solution to the N-queen chess problem. solitare: Solution to a solitare game. money: Solution to the send-more-money problem (bvec demo). internal: Some internal regression tests. doc: Documentation. buddy.ps: Package documentation. bddnotes.ps: BDD introduction notes. --------------------------------------------------------------------- --- FEEDBACK -------------------------------------------------------- --------------------------------------------------------------------- Please do not hesitate to send any questions or bug reports to: Jorn Lind-Nielsen: buddy@itu.dk (or maybe jorn_lind_nielsen@hotmail.com or jln@fjeldgruppen.dk) It may take some time to get an answer since BuDDy do not have that much focus any more - but I'll try to give a reasonable answer in (finite) time. New updates and other info can be found at: http://www.it-c.dk/research/buddy/ (or http://www.itu.dk/research/buddy) Hope you find some use for this software Jorn Lind-Nielsen FaCTpp-src-v1.6.2~dfsg/licensing/xerces-c.license.txt0000644000000000000000000000521112042532200021203 0ustar rootroot/* * The Apache Software License, Version 1.1 * * * Copyright (c) 1999-2004 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com. For more * information on the Apache Software Foundation, please see * . */ FaCTpp-src-v1.6.2~dfsg/licensing/lgpl-2.1.txt0000644000000000000000000006350412042532200017316 0ustar rootroot GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 Free Software Foundation, Inc. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. GNU LESSER GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. , 1 April 1990 Ty Coon, President of Vice That's all there is to it! FaCTpp-src-v1.6.2~dfsg/Models.lisp/0000755000000000000000000000000012042532200015527 5ustar rootrootFaCTpp-src-v1.6.2~dfsg/Models.lisp/Makefile.default0000644000000000000000000000031012042532200020604 0ustar rootroot# this is automatically generate makefile for KB all: sat clean: rm -f dl.res Taxonomy.Roles Taxonomy.log reasoning.log rm -f dl.res.diff Taxonomy.Roles.diff Taxonomy.log.diff reasoning.log.diff FaCTpp-src-v1.6.2~dfsg/Models.lisp/query.default0000644000000000000000000000034712042532200020246 0ustar rootroot[Query] ;-- ;-- targets for single satisfiability (is Target sat) or subsumption (if Target [= Target2 holds) test ;-- ; Target = *TOP* ; Target2 = *BOTTOM* ;*** ;*** please do not change lines below ;*** ;-- ;-- target KB ;-- FaCTpp-src-v1.6.2~dfsg/Models.lisp/options.default0000644000000000000000000001136612042532200020577 0ustar rootroot[LeveLogger] ;--- Logging file name file = reasoning.log ;--- Logging level (the less level you give, the less information will be logged) allowedLevel = 0 [Tuning] ;--- ;--- Option 'IAOEFLG': text --- ;--- ;* Option 'IAOEFLG' define the priorities of different operations in TODO list. Possible values are 7-digit strings with ony possible digit are 0-6. The digits on the places 1, 2, ..., 7 are for priority of Id, And, Or, Exists, Forall, LE and GE operations respectively. The smaller number means the higher priority. All other constructions (TOP, BOTTOM, etc) has priority 0. ;* Default value: '1263005' ; IAOEFLG = 1263005 ;--- ;--- Option 'absorptionFlags': text --- ;--- ;* Option 'absorptionFlags' sets up absorption process for general axioms. It text field of arbitrary length; every symbol means the absorption action: (B)ottom Absorption), (T)op absorption, (E)quivalent concepts replacement, (C)oncept absorption, (N)egated concept absorption, (F)orall expression replacement, (R)ole absorption, (S)plit ;* Default value: 'BTECFSR' ; absorptionFlags = BTECFSR ;--- ;--- Option 'alwaysPreferEquals': boolean --- ;--- ;* Option 'alwaysPreferEquals' allows user to enforce usage of C=D definition instead of C[=D during absorption, even if implication appeares earlier in stream of axioms. ;* Default value: 'true' ; alwaysPreferEquals = 1 ;--- ;--- Option 'checkAD': boolean --- ;--- ;* Option 'checkAD' forces FaCT++ to create the AD and exit instead of performing classification ;* Default value: 'false' ; checkAD = 0 ;--- ;--- Option 'dumpQuery': boolean --- ;--- ;* Option 'dumpQuery' dumps sub-TBox relevant to given satisfiability/subsumption query. ;* Default value: 'false' ; dumpQuery = 0 ;--- ;--- Option 'orSortSat': text --- ;--- ;* Option 'orSortSat' define the sorting order of OR vertices in the DAG used in satisfiability tests (used mostly in caching). Option has form of string 'Mop', see orSortSub for details. ;* Default value: '0' ; orSortSat = 0 ;--- ;--- Option 'orSortSub': text --- ;--- ;* Option 'orSortSub' define the sorting order of OR vertices in the DAG used in subsumption tests. Option has form of string 'Mop', where 'M' is a sort field (could be 'D' for depth, 'S' for size, 'F' for frequency, and '0' for no sorting), 'o' is a order field (could be 'a' for ascending and 'd' for descending mode), and 'p' is a preference field (could be 'p' for preferencing non-generating rules and 'n' for not doing so). ;* Default value: '0' ; orSortSub = 0 ;--- ;--- Option 'skipBeforeBlock': integer --- ;--- ;* Internal use only. Option 'skipBeforeBlock' allow user to skip given number of nodes before make a block. ;* Default value: '0' ; skipBeforeBlock = 0 ;--- ;--- Option 'testTimeout': integer --- ;--- ;* Option 'testTimeout' sets timeout for a single reasoning test in milliseconds. ;* Default value: '0' ; testTimeout = 0 ;--- ;--- Option 'useAnywhereBlocking': boolean --- ;--- ;* Option 'useAnywhereBlocking' allow user to choose between Anywhere and Ancestor blocking. ;* Default value: 'true' ; useAnywhereBlocking = 1 ;--- ;--- Option 'useBackjumping': boolean --- ;--- ;* Option 'useBackjumping' switch backjumping on and off. The usage of backjumping usually leads to much faster reasoning. ;* Default value: 'true' ; useBackjumping = 1 ;--- ;--- Option 'useCompletelyDefined': boolean --- ;--- ;* Option 'useCompletelyDefined' leads to simpler Taxonomy creation if TBox contains no non-primitive concepts. Unfortunately, it is quite rare case. ;* Default value: 'true' ; useCompletelyDefined = 1 ;--- ;--- Option 'useELReasoner': boolean --- ;--- ;* Option 'useELReasoner' forces FaCT++ to use the EL reasoner and exit instead of performing classification ;* Default value: 'false' ; useELReasoner = 0 ;--- ;--- Option 'useLazyBlocking': boolean --- ;--- ;* Option 'useLazyBlocking' makes checking of blocking status as small as possible. This greatly increase speed of reasoning. ;* Default value: 'true' ; useLazyBlocking = 1 ;--- ;--- Option 'useRelevantOnly': boolean --- ;--- ;* Option 'useRelevantOnly' is used when creating internal DAG representation for externally given TBox. If true, DAG contains only concepts, relevant to query. It is safe to leave this option false. ;* Default value: 'false' ; useRelevantOnly = 0 ;--- ;--- Option 'useSemanticBranching': boolean --- ;--- ;* Option 'useSemanticBranching' switch semantic branching on and off. The usage of semantic branching usually leads to faster reasoning, but sometime could give small overhead. ;* Default value: 'true' ; useSemanticBranching = 1 ;--- ;--- Option 'useSpecialDomains': boolean --- ;--- ;* Option 'useSpecialDomains' (development) controls the special processing of R&D for non-simple roles. Should always be set to true. ;* Default value: 'true' ; useSpecialDomains = 1 FaCTpp-src-v1.6.2~dfsg/Models.lisp/create-new-test0000755000000000000000000000224112042532200020463 0ustar rootroot#!/bin/bash # Script for creating new test-suit. # In parameters: # output: # - create directory # - copy into /.tbox # - create Makefile and conf-file # file names MKNAME=./$1/Makefile TBOXNAME=./$1/$1.tbox CONFNAME=./$1/$1.conf # .orig files path OFP=. Usage() { echo echo "Usage: create-new-test " echo " where: -- unique name for new suit" echo " -- test TBox file" exit 1 } Fatal() { echo "Fatal: directory $1 already exists" exit 1 } # check for the parameters if test "$1" = ""; then Usage elif test "$2" = ""; then Usage fi # create new subdir mkdir $1 || Fatal # create Makefile for the test suit cp $OFP/Makefile.default $MKNAME echo "KB_CONF = $1.conf" >> $MKNAME echo "KB = $1.tbox" >> $MKNAME echo >> $MKNAME echo "sat classify:" >> $MKNAME echo " FaCT++ \$(KB_CONF)" >> $MKNAME # create TBox file for the test suit cp $2 $TBOXNAME # create Config file for the test suit cp $OFP/options.default $CONFNAME cat $OFP/query.default >> $CONFNAME echo "TBox = $1.tbox" >> $CONFNAME echo >> $CONFNAME echo "Finished!" FaCTpp-src-v1.6.2~dfsg/Models.lisp/DataTypeTest/0000755000000000000000000000000012042532200020102 5ustar rootrootFaCTpp-src-v1.6.2~dfsg/Models.lisp/DataTypeTest/DataTypeTest.tbox0000644000000000000000000003115612042532200023361 0ustar rootroot; updated 05-04-06 ;;TEST DATA (defdatarole R); ;GT and LT ;testing simple satisfiable and unsatisfiable ranges (defconcept TTa1 (and (some R(gt (number 18))) (some R(lt(number 60))))) (defconcept TTa2 (and (some R(gt (number 60))) (some R(lt(number 18)))));unsat (defconcept TTa3 (and (some R(lt (number 18))) (some R(gt(number 60)))));unsat (defconcept TTa4 (and (some R(lt (number 60))) (some R(gt(number 18))))) (defconcept TTa5 (and (some R(gt (number 18))) (some R(lt(number 18)))));unsat (defconcept TTa6 (and (some R(lt (number 60))) (some R(gt(number 60)))));unsat ;the 4 below should eventually simplify (defconcept TTb1 (and (some R(gt (number 18))) (some R(gt(number 60))))) (defconcept TTb2 (and (some R(gt (number 60))) (some R(gt(number 18))))) (defconcept TTb3 (and (some R(lt (number 18))) (some R(lt(number 60))))) (defconcept TTb4 (and (some R(lt (number 60))) (some R(lt(number 18))))) (defconcept TTb5 (and (some R(gt (number 18))) (some R(gt(number 18))))) (defconcept TTb6 (and (some R(lt (number 60))) (some R(lt(number 60))))) ;testing ranges together with specific values (defconcept TTc1 (and (some R(gt (number 18))) (some R(number 60)))) (defconcept TTc2 (and (some R(gt (number 60))) (some R(number 18))));unsat (defconcept TTc3 (and (some R(lt (number 18))) (some R(number 60))));unsat (defconcept TTc4 (and (some R(lt (number 60))) (some R(number 18)))) (defconcept TTd1 (and (some R(number 18)) (some R(gt (number 60)))));unsat (defconcept TTd2 (and (some R(number 60)) (some R(gt (number 18))))) (defconcept TTd3 (and (some R(number 18)) (some R(lt (number 60))))) (defconcept TTd4 (and (some R(number 60)) (some R(lt (number 18)))));unsat (defconcept TTe1 (and (some R(number 18)) (some R(lt(number 18)))));unsat (defconcept TTe2 (and (some R(number 60)) (some R(gt(number 60)))));unsat (defconcept TTe3 (and (some R(lt (number 60))) (some R(number 60))));unsat (defconcept TTe4 (and (some R(gt (number 18))) (some R(number 18))));unsat ;GE and LT ;testing simple satisfiable and unsatisfiable ranges (defconcept ETa1 (and (some R(ge (number 18))) (some R(lt(number 60))))) (defconcept ETa2 (and (some R(ge (number 60))) (some R(lt(number 18)))));unsat (defconcept ETa3 (and (some R(le (number 18))) (some R(gt(number 60)))));unsat (defconcept ETa4 (and (some R(le (number 60))) (some R(gt(number 18))))) (defconcept ETa5 (and (some R(ge (number 18))) (some R(lt(number 18)))));unsat (defconcept ETa6 (and (some R(le (number 60))) (some R(gt(number 60)))));unsat ;the 4 below should eventually simplify (defconcept ETb1 (and (some R(ge (number 18))) (some R(gt(number 60))))) (defconcept ETb2 (and (some R(ge (number 60))) (some R(gt(number 18))))) (defconcept ETb3 (and (some R(le (number 18))) (some R(lt(number 60))))) (defconcept ETb4 (and (some R(le (number 60))) (some R(lt(number 18))))) (defconcept ETb5 (and (some R(ge (number 18))) (some R(gt(number 18))))) (defconcept ETb6 (and (some R(le (number 60))) (some R(lt(number 60))))) ;testing ranges together with specific values (defconcept ETc1 (and (some R(ge (number 18))) (some R(number 60)))) (defconcept ETc2 (and (some R(ge (number 60))) (some R(number 18))));unsat (defconcept ETc3 (and (some R(le (number 18))) (some R(number 60))));unsat (defconcept ETc4 (and (some R(le (number 60))) (some R(number 18)))) (defconcept ETd1 (and (some R(number 18)) (some R(gt (number 60)))));unsat (defconcept ETd2 (and (some R(number 60)) (some R(gt (number 18))))) (defconcept ETd3 (and (some R(number 18)) (some R(lt (number 60))))) (defconcept ETd4 (and (some R(number 60)) (some R(lt (number 18)))));unsat (defconcept ETe1 (and (some R(number 18)) (some R(lt(number 18)))));unsat (defconcept ETe2 (and (some R(number 60)) (some R(gt(number 60)))));unsat (defconcept ETe3 (and (some R(le (number 60))) (some R(number 60)))) (defconcept ETe4 (and (some R(ge (number 18))) (some R(number 18)))) ;GE and LE ;testing simple satisfiable and unsatisfiable ranges (defconcept EEa1 (and (some R(ge (number 18))) (some R(le(number 60))))) (defconcept EEa2 (and (some R(ge (number 60))) (some R(le(number 18)))));unsat (defconcept EEa3 (and (some R(le (number 18))) (some R(ge(number 60)))));unsat (defconcept EEa4 (and (some R(le (number 60))) (some R(ge(number 18))))) (defconcept EEa5 (and (some R(ge (number 18))) (some R(le(number 18))))) (defconcept EEa6 (and (some R(le (number 60))) (some R(ge(number 60))))) ;the 4 below should eventually simplify (defconcept EEb1 (and (some R(ge (number 18))) (some R(ge(number 60))))) (defconcept EEb2 (and (some R(ge (number 60))) (some R(ge(number 18))))) (defconcept EEb3 (and (some R(le (number 18))) (some R(le(number 60))))) (defconcept EEb4 (and (some R(le (number 60))) (some R(le(number 18))))) (defconcept EEb5 (and (some R(ge (number 18))) (some R(ge(number 18))))) (defconcept EEb6 (and (some R(le (number 60))) (some R(le(number 60))))) ;testing ranges together with specific values (defconcept EEc1 (and (some R(ge (number 18))) (some R(number 60)))) (defconcept EEc2 (and (some R(ge (number 60))) (some R(number 18))));unsat (defconcept EEc3 (and (some R(le (number 18))) (some R(number 60))));unsat (defconcept EEc4 (and (some R(le (number 60))) (some R(number 18)))) (defconcept EEd1 (and (some R(number 18)) (some R(ge (number 60)))));unsat (defconcept EEd2 (and (some R(number 60)) (some R(ge (number 18))))) (defconcept EEd3 (and (some R(number 18)) (some R(le (number 60))))) (defconcept EEd4 (and (some R(number 60)) (some R(le (number 18)))));unsat (defconcept EEe1 (and (some R(number 18)) (some R(le(number 18))))) (defconcept EEe2 (and (some R(number 60)) (some R(ge(number 60))))) (defconcept EEe3 (and (some R(le (number 60))) (some R(number 60)))) (defconcept EEe4 (and (some R(ge (number 18))) (some R(number 18)))) ;GT and LE ;testing simple satisfiable and unsatisfiable ranges (defconcept TEa1 (and (some R(gt (number 18))) (some R(le(number 60))))) (defconcept TEa2 (and (some R(gt (number 60))) (some R(le(number 18)))));unsat (defconcept TEa3 (and (some R(lt (number 18))) (some R(ge(number 60)))));unsat (defconcept TEa4 (and (some R(lt (number 60))) (some R(ge(number 18))))) (defconcept TEa5 (and (some R(gt (number 18))) (some R(le(number 18)))));unsat (defconcept TEa6 (and (some R(lt (number 60))) (some R(ge(number 60)))));unsat ;the 4 below should eventually simplify (defconcept TEb1 (and (some R(gt (number 18))) (some R(ge(number 60))))) (defconcept TEb2 (and (some R(gt (number 60))) (some R(ge(number 18))))) (defconcept TEb3 (and (some R(lt (number 18))) (some R(le(number 60))))) (defconcept TEb4 (and (some R(lt (number 60))) (some R(le(number 18))))) (defconcept TEb5 (and (some R(gt (number 18))) (some R(ge(number 18))))) (defconcept TEb6 (and (some R(lt (number 60))) (some R(le(number 60))))) ;testing ranges together with specific values (defconcept TEc1 (and (some R(gt (number 18))) (some R(number 60)))) (defconcept TEc2 (and (some R(gt (number 60))) (some R(number 18))));unsat (defconcept TEc3 (and (some R(lt (number 18))) (some R(number 60))));unsat (defconcept TEc4 (and (some R(lt (number 60))) (some R(number 18)))) (defconcept TEd1 (and (some R(number 18)) (some R(ge (number 60)))));unsat (defconcept TEd2 (and (some R(number 60)) (some R(ge (number 18))))) (defconcept TEd3 (and (some R(number 18)) (some R(le (number 60))))) (defconcept TEd4 (and (some R(number 60)) (some R(le (number 18)))));unsat (defconcept TEe1 (and (some R(number 18)) (some R(le(number 18))))) (defconcept TEe2 (and (some R(number 60)) (some R(ge(number 60))))) (defconcept TEe3 (and (some R(lt (number 60))) (some R(number 60))));unsat (defconcept TEe4 (and (some R(gt (number 18))) (some R(number 18))));unsat ;Doubles - not supported (defconcept double1 (and (some R(gt (number 18.4))) (some R(lt (number 18.5)))));unsat (defconcept double2 (and (some R(lt (number 18.4))) (some R(gt (number 18.5)))));unsat ;Testing range cross-over (defconcept between1 (and (some R(between (number 28) (number 60))) (some R(between (number 18) (number 50))))) (defconcept inrange1 (and (some R(in-range (number 18) (number 50))) (some R(in-range (number 28) (number 60))))) (defconcept between2 (and (some R(between (number 18) (number 28))) (some R(between (number 50) (number 60)))));unsat (defconcept inrange2 (and (some R(in-range (number 50) (number 60))) (some R(in-range (number 18) (number 28)))));unsat ;Check that 1a and 1b, and 2a and 2b are equivalent (defconcept equiv1a (and (some R(gt (number 18))) (some R(lt (number 60))))) (defconcept equiv1b (some R(between (number 18) (number 60)))) (defconcept equiv2a (and (some R(ge (number 18))) (some R(le (number 60))))) (defconcept equiv2b (some R(in-range (number 18) (number 60)))) ;Strings (defconcept str01 (and (some R(gt(string AWord))) (some R(lt(string BWord))))) (defconcept str02 (and (some R(lt(string AWord))) (some R(gt(string BWord)))));unsat (defconcept str03 (and (some R(gt(string WordA))) (some R(lt(string WordB))))) (defconcept str04 (and (some R(lt(string WordA))) (some R(gt(string WordB)))));unsat (defconcept str05 (and (some R(gt(string A))) (some R(lt(string A)))));unsat (defconcept str06 (and (some R(ge(string A))) (some R(le(string A))))) (defconcept str07 (and (some R(gt(string A))) (some R(gt(string B))))) (defconcept str08 (and (some R(lt(string A))) (some R(lt(string B))))) (defconcept str09 (and (some R(gt(string aa))) (some R(lt(string aaa))))) (defconcept str10 (and (some R(gt(string aaa))) (some R(lt(string aa)))));unsat (defconcept str11 (and (some R(gt(string AWord))) (some R(string BWord)))) (defconcept str12 (and (some R(lt(string AWord))) (some R(string BWord))));unsat ;Subsumption tests (defconcept subNumA (and (some R (ge (number 5))) (some R (le (number 10))))) ; subsumes TOP (defconcept subNumB (and (some R (ge (number 5))) (some R (lt (number 10))))) ; subsumes a (defconcept subNumC (and (some R (gt (number 5))) (some R (le (number 10))))) ; subsumes a (defconcept subNumD (and (some R (gt (number 5))) (some R (lt (number 10))))) ; subsumes b, c (a) (defconcept subNumE (some R (number 5))) ; subsumes b (a) (defconcept subNumF (some R (number 10))) ; subsumes c (a) (defconcept subStrA (and (some R (ge (string a))) (some R (le (string b))))) ; subsumes TOP (defconcept subStrB (and (some R (ge (string a))) (some R (lt (string b))))) ; subsumes a (defconcept subStrC (and (some R (gt (string a))) (some R (le (string b))))) ; subsumes a (defconcept subStrD (and (some R (gt (string a))) (some R (lt (string b))))) ; subsumes b, c (a) (defconcept subStrE (some R (string a))) ; subsumes b (a) (defconcept subStrF (some R (string b))) ; subsumes c (a) ;Mix of types unsatisfiability test (defconcept mix1 (and (some R (gt (number 5))) (some R (lt (string five)))));unsat (defconcept mix2 (and (some R (gt (number 5))) (some R (lt (string 5)))));unsat ;Check that negative type saturation works correcly (defconcept negSat1N (and (some R (number)) (not (some R (le (number 5)))) (not (some R (number 6))) (not(some R (ge (number 7))))));unsat (defconcept negSat2N (and (some R (number)) (not (some R (lt (number 5)))) (not (some R (number 6))) (not(some R (ge (number 7)))))) (defconcept negSat3N (and (some R (number)) (not (some R (le (number 5)))) (not (some R (number 6))) (not(some R (gt (number 7)))))) (defconcept negSat4N (and (some R (number)) (not (some R (lt (number 5)))) (not (some R (number 6))) (not (some R (number 5))) (not(some R (ge (number 7))))));unsat (defconcept negSat5N (and (some R (number)) (not (some R (le (number 5)))) (not (some R (number 6))) (not (some R (number 7))) (not(some R (gt (number 7))))));unsat (defconcept negSat1S (and (some R (string)) (not (some R (le (string a)))) (not (some R (string b))) (not(some R (ge (string c)))))) ;negative subsumption tests ;C = E ;D = F ;I subsumes A ;J subsumes C ;H subsumes B ;G subsumes D ;F subsumes B ;E subsumes A ;M subsumes L (defconcept subSumpA (not (some R(lt (number 2))))) (defconcept subSumpB (not (some R(gt (number 5))))) (defconcept subSumpC (not (some R(le (number 2))))) (defconcept subSumpD (not (some R(ge (number 5))))) (defconcept subSumpE (and (not (some R(lt (number 2)))) (not (some R (number 2))))) (defconcept subSumpF (and (not (some R(gt (number 5)))) (not (some R (number 5))))) (defconcept subSumpG (and (some R(lt (number 5))))) (defconcept subSumpH (and (some R(le (number 5))))) (defconcept subSumpI (and (some R(ge (number 2))))) (defconcept subSumpJ (and (some R(gt (number 2))))) (defconcept subSumpK (and (not (some R(number 2))) (not (some R(number 3))) (not (some R(number 4))) (some R (ge (number 2))) (some R (le (number 4)))));unsat (defconcept subSumpL (and (not (some R(number 2))) (not (some R(number 3))) (not (some R(number 4))))) (defconcept subSumpM (some R(le (number 1)))) (defconcept subSumpN (and (not (some R(number 2))) (some R (number 2))));unsat FaCTpp-src-v1.6.2~dfsg/Models.lisp/DataTypeTest/Makefile0000644000000000000000000000043512042532200021544 0ustar rootroot# this is automatically generate makefile for KB all: sat clean: rm -f dl.res Taxonomy.Roles Taxonomy.log reasoning.log rm -f dl.res.diff Taxonomy.Roles.diff Taxonomy.log.diff reasoning.log.diff KB_CONF = DataTypeTest.conf KB = DataTypeTest.tbox sat classify: FaCT++ $(KB_CONF) FaCTpp-src-v1.6.2~dfsg/Models.lisp/DataTypeTest/DataTypeTest.conf0000644000000000000000000001176712042532200023340 0ustar rootroot[LeveLogger] ;--- Logging file name file = reasoning.log ;--- Logging level (the less level you give, the less information will be logged) allowedLevel = 0 [Tuning] ;--- ;--- Option 'IAOEFLG': text --- ;--- ;* Option 'IAOEFLG' define the priorities of different operations in TODO list. Possible values are 7-digit strings with ony possible digit are 0-6. The digits on the places 1, 2, ..., 7 are for priority of Id, And, Or, Exists, Forall, LE and GE operations respectively. The smaller number means the higher priority. All other constructions (TOP, BOTTOM, etc) has priority 0. ;* Default value: '1263005' ; IAOEFLG = 1263005 ;--- ;--- Option 'absorptionFlags': text --- ;--- ;* Option 'absorptionFlags' sets up absorption process for general axioms. It text field of arbitrary length; every symbol means the absorption action: (B)ottom Absorption), (T)op absorption, (E)quivalent concepts replacement, (C)oncept absorption, (N)egated concept absorption, (F)orall expression replacement, (R)ole absorption, (S)plit ;* Default value: 'BTECFSR' ; absorptionFlags = BTECFSR ;--- ;--- Option 'alwaysPreferEquals': boolean --- ;--- ;* Option 'alwaysPreferEquals' allows user to enforce usage of C=D definition instead of C[=D during absorption, even if implication appeares earlier in stream of axioms. ;* Default value: 'true' ; alwaysPreferEquals = 1 ;--- ;--- Option 'checkAD': boolean --- ;--- ;* Option 'checkAD' forces FaCT++ to create the AD and exit instead of performing classification ;* Default value: 'false' ; checkAD = 0 ;--- ;--- Option 'dumpQuery': boolean --- ;--- ;* Option 'dumpQuery' dumps sub-TBox relevant to given satisfiability/subsumption query. ;* Default value: 'false' ; dumpQuery = 0 ;--- ;--- Option 'orSortSat': text --- ;--- ;* Option 'orSortSat' define the sorting order of OR vertices in the DAG used in satisfiability tests (used mostly in caching). Option has form of string 'Mop', see orSortSub for details. ;* Default value: '0' ; orSortSat = 0 ;--- ;--- Option 'orSortSub': text --- ;--- ;* Option 'orSortSub' define the sorting order of OR vertices in the DAG used in subsumption tests. Option has form of string 'Mop', where 'M' is a sort field (could be 'D' for depth, 'S' for size, 'F' for frequency, and '0' for no sorting), 'o' is a order field (could be 'a' for ascending and 'd' for descending mode), and 'p' is a preference field (could be 'p' for preferencing non-generating rules and 'n' for not doing so). ;* Default value: '0' ; orSortSub = 0 ;--- ;--- Option 'skipBeforeBlock': integer --- ;--- ;* Internal use only. Option 'skipBeforeBlock' allow user to skip given number of nodes before make a block. ;* Default value: '0' ; skipBeforeBlock = 0 ;--- ;--- Option 'testTimeout': integer --- ;--- ;* Option 'testTimeout' sets timeout for a single reasoning test in milliseconds. ;* Default value: '0' ; testTimeout = 0 ;--- ;--- Option 'useAnywhereBlocking': boolean --- ;--- ;* Option 'useAnywhereBlocking' allow user to choose between Anywhere and Ancestor blocking. ;* Default value: 'true' ; useAnywhereBlocking = 1 ;--- ;--- Option 'useBackjumping': boolean --- ;--- ;* Option 'useBackjumping' switch backjumping on and off. The usage of backjumping usually leads to much faster reasoning. ;* Default value: 'true' ; useBackjumping = 1 ;--- ;--- Option 'useCompletelyDefined': boolean --- ;--- ;* Option 'useCompletelyDefined' leads to simpler Taxonomy creation if TBox contains no non-primitive concepts. Unfortunately, it is quite rare case. ;* Default value: 'true' ; useCompletelyDefined = 1 ;--- ;--- Option 'useELReasoner': boolean --- ;--- ;* Option 'useELReasoner' forces FaCT++ to use the EL reasoner and exit instead of performing classification ;* Default value: 'false' ; useELReasoner = 0 ;--- ;--- Option 'useLazyBlocking': boolean --- ;--- ;* Option 'useLazyBlocking' makes checking of blocking status as small as possible. This greatly increase speed of reasoning. ;* Default value: 'true' ; useLazyBlocking = 1 ;--- ;--- Option 'useRelevantOnly': boolean --- ;--- ;* Option 'useRelevantOnly' is used when creating internal DAG representation for externally given TBox. If true, DAG contains only concepts, relevant to query. It is safe to leave this option false. ;* Default value: 'false' ; useRelevantOnly = 0 ;--- ;--- Option 'useSemanticBranching': boolean --- ;--- ;* Option 'useSemanticBranching' switch semantic branching on and off. The usage of semantic branching usually leads to faster reasoning, but sometime could give small overhead. ;* Default value: 'true' ; useSemanticBranching = 1 ;--- ;--- Option 'useSpecialDomains': boolean --- ;--- ;* Option 'useSpecialDomains' (development) controls the special processing of R&D for non-simple roles. Should always be set to true. ;* Default value: 'true' ; useSpecialDomains = 1 [Query] ;-- ;-- targets for single satisfiability (is Target sat) or subsumption (if Target [= Target2 holds) test ;-- ; Target = *TOP* ; Target2 = *BOTTOM* ;*** ;*** please do not change lines below ;*** ;-- ;-- target KB ;-- TBox = DataTypeTest.tbox FaCTpp-src-v1.6.2~dfsg/src/0000755000000000000000000000000012112642440014133 5ustar rootrootFaCTpp-src-v1.6.2~dfsg/src/update.properties.p4.10000644000000000000000000000053712112642425020224 0ustar rootrootname=FaCT++ reasoner id=uk.ac.manchester.cs.owl.factplusplus version=1.6.1 download=http://factplusplus.googlecode.com/files/uk.ac.manchester.cs.owl.factplusplus-P4.1-v1.6.1.jar readme=http://factplusplus.googlecode.com/svn/trunk/version-info-p4.1.html license=http://www.gnu.org/licenses/lgpl.html author=Dmitry Tsarkov, The University of Manchester FaCTpp-src-v1.6.2~dfsg/src/update.properties0000644000000000000000000000053512112642425017541 0ustar rootrootname=FaCT++ reasoner id=uk.ac.manchester.cs.owl.factplusplus version=1.4.0.1 download=http://factplusplus.googlecode.com/files/uk.ac.manchester.cs.owl.factplusplus-P4.0-v1.4.0.1.jar readme=http://factplusplus.googlecode.com/svn/trunk/version-info.html license=http://www.gnu.org/licenses/lgpl.html author=Dmitry Tsarkov, The University of ManchesterFaCTpp-src-v1.6.2~dfsg/src/FaCT++.Java/0000755000000000000000000000000012112642473015724 5ustar rootrootFaCTpp-src-v1.6.2~dfsg/src/FaCT++.Java/uk/0000755000000000000000000000000012112642473016343 5ustar rootrootFaCTpp-src-v1.6.2~dfsg/src/FaCT++.Java/uk/ac/0000755000000000000000000000000012112642473016726 5ustar rootrootFaCTpp-src-v1.6.2~dfsg/src/FaCT++.Java/uk/ac/manchester/0000755000000000000000000000000012112642473021057 5ustar rootrootFaCTpp-src-v1.6.2~dfsg/src/FaCT++.Java/uk/ac/manchester/cs/0000755000000000000000000000000012112642473021464 5ustar rootrootFaCTpp-src-v1.6.2~dfsg/src/FaCT++.Java/uk/ac/manchester/cs/factplusplus/0000755000000000000000000000000012112642473024211 5ustar rootrootFaCTpp-src-v1.6.2~dfsg/src/FaCT++.Java/uk/ac/manchester/cs/factplusplus/FaCTPlusPlusException.java0000644000000000000000000000311512112642405031213 0ustar rootrootpackage uk.ac.manchester.cs.factplusplus; import org.semanticweb.owlapi.model.OWLRuntimeException; /* * Copyright (C) 2007, University of Manchester * * Modifications to the initial code base are copyright of their * respective authors, or their employers as appropriate. Authorship * of the modifications may be determined from the ChangeLog placed at * the end of this file. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ /** * Author: Matthew Horridge
* The University Of Manchester
* Bio-Health Informatics Group
* Date: 21-Sep-2007

*/ public class FaCTPlusPlusException extends OWLRuntimeException { public FaCTPlusPlusException(String message) { super(message); } public FaCTPlusPlusException(String message, Throwable cause) { super(message, cause); } public FaCTPlusPlusException(Throwable cause) { super(cause); } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootFaCTpp-src-v1.6.2~dfsg/src/FaCT++.Java/uk/ac/manchester/cs/factplusplus/FaCTPlusPlusProgressMonitor.javaFaCTpp-src-v1.6.2~dfsg/src/FaCT++.Java/uk/ac/manchester/cs/factplusplus/FaCTPlusPlusProgressMonitor.0000644000000000000000000000072612112642405031574 0ustar rootrootpackage uk.ac.manchester.cs.factplusplus; /** * Author: Matthew Horridge
* The University Of Manchester
* Medical Informatics Group
* Date: 15-Oct-2006

*

* matthew.horridge@cs.man.ac.uk
* www.cs.man.ac.uk/~horridgm

*/ public interface FaCTPlusPlusProgressMonitor { public void setClassificationStarted(int classCount); public void nextClass(); public void setFinished(); public boolean isCancelled(); } FaCTpp-src-v1.6.2~dfsg/src/FaCT++.Java/uk/ac/manchester/cs/factplusplus/ClassPointer.java0000644000000000000000000000214012112642405027452 0ustar rootrootpackage uk.ac.manchester.cs.factplusplus; /* * Copyright (C) 2009-2010, University of Manchester * * Modifications to the initial code base are copyright of their * respective authors, or their employers as appropriate. Authorship * of the modifications may be determined from the ChangeLog placed at * the end of this file. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ public class ClassPointer extends Pointer { } FaCTpp-src-v1.6.2~dfsg/src/FaCT++.Java/uk/ac/manchester/cs/factplusplus/DataPropertyPointer.java0000644000000000000000000000214712112642405031032 0ustar rootrootpackage uk.ac.manchester.cs.factplusplus; /* * Copyright (C) 2009-2010, University of Manchester * * Modifications to the initial code base are copyright of their * respective authors, or their employers as appropriate. Authorship * of the modifications may be determined from the ChangeLog placed at * the end of this file. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ public class DataPropertyPointer extends Pointer { } FaCTpp-src-v1.6.2~dfsg/src/FaCT++.Java/uk/ac/manchester/cs/factplusplus/DataTypePointer.java0000644000000000000000000000216512112642405030127 0ustar rootrootpackage uk.ac.manchester.cs.factplusplus; /* * Copyright (C) 2009-2010, University of Manchester * * Modifications to the initial code base are copyright of their * respective authors, or their employers as appropriate. Authorship * of the modifications may be determined from the ChangeLog placed at * the end of this file. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ public class DataTypePointer extends DataTypeExpressionPointer { } FaCTpp-src-v1.6.2~dfsg/src/FaCT++.Java/uk/ac/manchester/cs/factplusplus/NodePointer.java0000644000000000000000000000214112112642405027273 0ustar rootroot/* * Copyright (C) 2009-2010, University of Manchester * * Modifications to the initial code base are copyright of their * respective authors, or their employers as appropriate. Authorship * of the modifications may be determined from the ChangeLog placed at * the end of this file. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package uk.ac.manchester.cs.factplusplus; public class NodePointer extends Pointer { } FaCTpp-src-v1.6.2~dfsg/src/FaCT++.Java/uk/ac/manchester/cs/factplusplus/DataValuePointer.java0000644000000000000000000000214512112642405030260 0ustar rootroot/* * Copyright (C) 2009-2010, University of Manchester * * Modifications to the initial code base are copyright of their * respective authors, or their employers as appropriate. Authorship * of the modifications may be determined from the ChangeLog placed at * the end of this file. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package uk.ac.manchester.cs.factplusplus; public class DataValuePointer extends Pointer { } FaCTpp-src-v1.6.2~dfsg/src/FaCT++.Java/uk/ac/manchester/cs/factplusplus/AxiomPointer.java0000644000000000000000000000211012112642405027457 0ustar rootrootpackage uk.ac.manchester.cs.factplusplus; /* * Copyright (C) 2007, University of Manchester * * Modifications to the initial code base are copyright of their * respective authors, or their employers as appropriate. Authorship * of the modifications may be determined from the ChangeLog placed at * the end of this file. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ public class AxiomPointer extends Pointer { } FaCTpp-src-v1.6.2~dfsg/src/FaCT++.Java/uk/ac/manchester/cs/factplusplus/Pointer.java0000644000000000000000000000303612112642405026471 0ustar rootrootpackage uk.ac.manchester.cs.factplusplus; /* * Copyright (C) 2009-2010, University of Manchester * * Modifications to the initial code base are copyright of their * respective authors, or their employers as appropriate. Authorship * of the modifications may be determined from the ChangeLog placed at * the end of this file. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ public class Pointer { private long node = 0; public long getNode() { return node; } @Override public int hashCode() { return (int) node; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (this == obj) { return true; } if (!(obj instanceof Pointer)) { return false; } return ((Pointer) obj).node == node; } @Override public final String toString() { return this.getClass().getSimpleName()+"[" + node + "]"; } } FaCTpp-src-v1.6.2~dfsg/src/FaCT++.Java/uk/ac/manchester/cs/factplusplus/FaCTPlusPlus.java0000644000000000000000000006070412112642405027343 0ustar rootrootpackage uk.ac.manchester.cs.factplusplus; import java.util.concurrent.atomic.AtomicBoolean; /** * Author: Matthew Horridge
* The University Of Manchester
* Medical Informatics Group
* Date: 10-Jul-2006
*
*

* matthew.horridge@cs.man.ac.uk
* www.cs.man.ac.uk/~horridgm
*
* * An interface to the native FaCT++ reasoner. Use of this class requires the * FaCT++ JNI library for the appropriate platform. */ public class FaCTPlusPlus { private static final AtomicBoolean initDone = new AtomicBoolean(false); static { if (!initDone.getAndSet(true)) { // Load the FaCT++ JNI library if (System.getProperty("factpp.jni.path", "nope") == "nope") { System.loadLibrary("FaCTPlusPlusJNI"); } else { System.load(System.getProperty("factpp.jni.path")); } // init all the IDs used initMethodsFieldsIDs(); } } public static final boolean test() { // this is only useful to force the native library loading return initDone.get(); } /** * Used to initialise methods and fields that will be used by the native * implementation */ private static native void initMethodsFieldsIDs(); /** * Set internally on the native side - DO NOT ALTER! */ private long KernelId; public FaCTPlusPlus() throws FaCTPlusPlusException { try { initKernel(); } catch (Exception e) { throw new FaCTPlusPlusException(e); } } /** * Use this method to dispose of native resources. This method MUST be * called when the reasoner is no longer required. Failure to call dispose, * may result in memory leaks! */ public void dispose() throws FaCTPlusPlusException { deleteKernel(); } private native void initKernel() throws Exception; private native void deleteKernel() throws FaCTPlusPlusException; /** * Clears told and any cached information from the kernel. * * @throws FaCTPlusPlusException */ public native void clearKernel() throws FaCTPlusPlusException; /** * Set the names of Top/Bottom data and object properties. The call of this * method automatically means that the OWL API v3 (and higher) is used. * Without this call, Top/Bottom properties would not appear in the query * results. */ public native void setTopBottomPropertyNames(String topObjectName, String botObjectName, String topDataName, String botDataName); /** * Causes the whole taxonomy to be computed. * * @throws FaCTPlusPlusException */ public native void classify() throws FaCTPlusPlusException; /** * Causes all individual types to be computed * * @throws FaCTPlusPlusException */ public native void realise() throws FaCTPlusPlusException; /** * @return true iff the KB is realised */ public native boolean isRealised(); /** * Gets the class corresponding to TOP * * @throws FaCTPlusPlusException */ public native ClassPointer getThing() throws FaCTPlusPlusException; /** * Gets the class corresponding to BOTTOM * * @throws FaCTPlusPlusException */ public native ClassPointer getNothing() throws FaCTPlusPlusException; /** * Gets a pointer to a named class. * * @param name * The name of the class. * @return A ClassPointer * @throws FaCTPlusPlusException */ public native ClassPointer getNamedClass(String name) throws FaCTPlusPlusException; public native ObjectPropertyPointer getTopObjectProperty() throws FaCTPlusPlusException; public native ObjectPropertyPointer getBottomObjectProperty() throws FaCTPlusPlusException; /** * Gets a pointer to an object property. * * @param name * The name of the property. * @return A pointer to the object property that has the specified name. * @throws FaCTPlusPlusException */ public native ObjectPropertyPointer getObjectProperty(String name) throws FaCTPlusPlusException; public native DataPropertyPointer getTopDataProperty() throws FaCTPlusPlusException; public native DataPropertyPointer getBottomDataProperty() throws FaCTPlusPlusException; public native DataPropertyPointer getDataProperty(String name) throws FaCTPlusPlusException; public native IndividualPointer getIndividual(String name) throws FaCTPlusPlusException; // ------------------------------------------------------------------------ // Datatype stuff // ------------------------------------------------------------------------ /** * Gets the top data type. */ public native DataTypePointer getDataTop() throws FaCTPlusPlusException; /** * Gets a pointer to a built in data type * * @param name * The name of the datatype. e.g. string, int, float etc. */ public native DataTypePointer getBuiltInDataType(String name) throws FaCTPlusPlusException; /** * Assigns a name to a datatype expression * * @param name * The name to assign to the datatype * @param datatypeExpression */ public native DataTypeExpressionPointer getDataSubType(String name, DataTypeExpressionPointer datatypeExpression) throws FaCTPlusPlusException; /** * Gets a data enumeration using previously added arguments (initArgList, * addArg, closeArgList) */ public native DataTypeExpressionPointer getDataEnumeration() throws FaCTPlusPlusException; public native DataTypeExpressionPointer getRestrictedDataType(DataTypeExpressionPointer d, DataTypeFacet facet) throws FaCTPlusPlusException; // ------------------------------------------------------------------------ // Datatype facets // ------------------------------------------------------------------------ public native DataTypeFacet getLength(DataValuePointer dv) throws FaCTPlusPlusException; public native DataTypeFacet getMinLength(DataValuePointer dv) throws FaCTPlusPlusException; public native DataTypeFacet getMaxLength(DataValuePointer dv) throws FaCTPlusPlusException; public native DataTypeFacet getPattern(DataValuePointer dv) throws FaCTPlusPlusException; public native DataTypeFacet getMinExclusiveFacet(DataValuePointer dv) throws FaCTPlusPlusException; public native DataTypeFacet getMaxExclusiveFacet(DataValuePointer dv) throws FaCTPlusPlusException; public native DataTypeFacet getMinInclusiveFacet(DataValuePointer dv) throws FaCTPlusPlusException; public native DataTypeFacet getMaxInclusiveFacet(DataValuePointer dv) throws FaCTPlusPlusException; public native DataTypeFacet getTotalDigitsFacet(DataValuePointer dv) throws FaCTPlusPlusException; public native DataTypeFacet getFractionDigitsFacet(DataValuePointer dv) throws FaCTPlusPlusException; public native DataTypeExpressionPointer getDataNot(DataTypeExpressionPointer d) throws FaCTPlusPlusException; /** * Gets a data intersection using previously added arguments (initArgList, * addArg, closeArgList) */ public native DataTypeExpressionPointer getDataIntersectionOf() throws FaCTPlusPlusException; /** * Gets a data union using previously added arguments (initArgList, addArg, * closeArgList) */ public native DataTypeExpressionPointer getDataUnionOf() throws FaCTPlusPlusException; public native DataValuePointer getDataValue(String literal, DataTypePointer type) throws FaCTPlusPlusException; // ------------------------------------------------------------------------ // concept expressions // ------------------------------------------------------------------------ /** * Gets an intersection whose operands are in the last closed arg list. */ public native ClassPointer getConceptAnd() throws FaCTPlusPlusException; /** * Gets a union whose operands are in the last closed arg list. */ public native ClassPointer getConceptOr() throws FaCTPlusPlusException; public native ClassPointer getConceptNot(ClassPointer c) throws FaCTPlusPlusException; public native ClassPointer getObjectSome(ObjectPropertyPointer r, ClassPointer c) throws FaCTPlusPlusException; public native ClassPointer getObjectAll(ObjectPropertyPointer r, ClassPointer c) throws FaCTPlusPlusException; public native ClassPointer getObjectValue(ObjectPropertyPointer r, IndividualPointer i) throws FaCTPlusPlusException; public native ClassPointer getObjectAtLeast(int num, ObjectPropertyPointer r, ClassPointer c) throws FaCTPlusPlusException; public native ClassPointer getObjectExact(int num, ObjectPropertyPointer r, ClassPointer c) throws FaCTPlusPlusException; public native ClassPointer getObjectAtMost(int num, ObjectPropertyPointer r, ClassPointer c) throws FaCTPlusPlusException; public native ClassPointer getDataSome(DataPropertyPointer r, DataTypeExpressionPointer d) throws FaCTPlusPlusException; public native ClassPointer getDataAll(DataPropertyPointer r, DataTypeExpressionPointer d) throws FaCTPlusPlusException; public native ClassPointer getDataValue(DataPropertyPointer r, DataValuePointer d) throws FaCTPlusPlusException; public native ClassPointer getDataAtLeast(int num, DataPropertyPointer r, DataTypeExpressionPointer d) throws FaCTPlusPlusException; public native ClassPointer getDataExact(int num, DataPropertyPointer r, DataTypeExpressionPointer d) throws FaCTPlusPlusException; public native ClassPointer getDataAtMost(int num, DataPropertyPointer r, DataTypeExpressionPointer d) throws FaCTPlusPlusException; public native ObjectPropertyPointer getInverseProperty(ObjectPropertyPointer r) throws FaCTPlusPlusException; /** * Gets a property chain whose properties are in the last closed arg list. */ public native ObjectPropertyPointer getPropertyComposition() throws FaCTPlusPlusException; /** * Gets a data key whose properties are in the last closed arg list. */ public native DataPropertyPointer getDataPropertyKey() throws FaCTPlusPlusException; /** * Gets an object key whose properties are in the last closed arg list. */ public native ObjectPropertyPointer getObjectPropertyKey() throws FaCTPlusPlusException; /** * Gets an enumeration whose individuals are in the last closed arg list. */ public native ClassPointer getOneOf() throws FaCTPlusPlusException; public native ClassPointer getSelf(ObjectPropertyPointer r) throws FaCTPlusPlusException; // ------------------------------------------------------------------------ // Axioms // ------------------------------------------------------------------------ public native AxiomPointer tellClassDeclaration(ClassPointer c) throws FaCTPlusPlusException; public native AxiomPointer tellObjectPropertyDeclaration(ObjectPropertyPointer op) throws FaCTPlusPlusException; public native AxiomPointer tellDataPropertyDeclaration(DataPropertyPointer dp) throws FaCTPlusPlusException; public native AxiomPointer tellIndividualDeclaration(IndividualPointer ip) throws FaCTPlusPlusException; public native AxiomPointer tellDatatypeDeclaration(DataTypePointer dp) throws FaCTPlusPlusException; public native AxiomPointer tellSubClassOf(ClassPointer c, ClassPointer d) throws FaCTPlusPlusException; /** * Tells an equivalent classes axiom, whose classes are in the last closed * arg list. */ public native AxiomPointer tellEquivalentClass() throws FaCTPlusPlusException; /** * Tells a disjoint classes axiom, whose classes are in the last closed arg * list. */ public native AxiomPointer tellDisjointClasses() throws FaCTPlusPlusException; /** * Tells a disjoint union axiom, where defined class in CLS and whose * disjoint classes are in the last closed arg list. */ public native AxiomPointer tellDisjointUnion(ClassPointer cls) throws FaCTPlusPlusException; public native AxiomPointer tellHasKey(ClassPointer cls, DataPropertyPointer dataKey, ObjectPropertyPointer objectKey) throws FaCTPlusPlusException; public native AxiomPointer tellSubObjectProperties(ObjectPropertyPointer s, ObjectPropertyPointer r) throws FaCTPlusPlusException; /** * Tells an equivalent object properties axiom, whose properties are in the * last closed arg list. */ public native AxiomPointer tellEquivalentObjectProperties() throws FaCTPlusPlusException; public native AxiomPointer tellInverseProperties(ObjectPropertyPointer s, ObjectPropertyPointer r) throws FaCTPlusPlusException; public native AxiomPointer tellObjectPropertyRange(ObjectPropertyPointer s, ClassPointer c) throws FaCTPlusPlusException; public native AxiomPointer tellDataPropertyRange(DataPropertyPointer s, DataTypeExpressionPointer d) throws FaCTPlusPlusException; public native AxiomPointer tellObjectPropertyDomain(ObjectPropertyPointer s, ClassPointer c) throws FaCTPlusPlusException; public native AxiomPointer tellDataPropertyDomain(DataPropertyPointer s, ClassPointer c) throws FaCTPlusPlusException; /** * Tells a disjoint object properties axiom, whose properties are in the * last closed arg list. */ public native AxiomPointer tellDisjointObjectProperties() throws FaCTPlusPlusException; public native AxiomPointer tellFunctionalObjectProperty(ObjectPropertyPointer s) throws FaCTPlusPlusException; public native AxiomPointer tellInverseFunctionalObjectProperty(ObjectPropertyPointer s) throws FaCTPlusPlusException; public native AxiomPointer tellSymmetricObjectProperty(ObjectPropertyPointer s) throws FaCTPlusPlusException; public native AxiomPointer tellAsymmetricObjectProperty(ObjectPropertyPointer s) throws FaCTPlusPlusException; public native AxiomPointer tellReflexiveObjectProperty(ObjectPropertyPointer s) throws FaCTPlusPlusException; public native AxiomPointer tellIrreflexiveObjectProperty(ObjectPropertyPointer s) throws FaCTPlusPlusException; public native AxiomPointer tellTransitiveObjectProperty(ObjectPropertyPointer s) throws FaCTPlusPlusException; public native AxiomPointer tellSubDataProperties(DataPropertyPointer s, DataPropertyPointer r) throws FaCTPlusPlusException; /** * Tells an equivalent data properties axiom, whose properties are in the * last closed arg list. */ public native AxiomPointer tellEquivalentDataProperties() throws FaCTPlusPlusException; /** * Tells a disjoint data properties axiom, whose properties are in the last * closed arg list. */ public native AxiomPointer tellDisjointDataProperties() throws FaCTPlusPlusException; public native AxiomPointer tellFunctionalDataProperty(DataPropertyPointer s) throws FaCTPlusPlusException; public native AxiomPointer tellIndividualType(IndividualPointer i, ClassPointer c) throws FaCTPlusPlusException; public native AxiomPointer tellRelatedIndividuals(IndividualPointer i, ObjectPropertyPointer r, IndividualPointer j) throws FaCTPlusPlusException; public native AxiomPointer tellNotRelatedIndividuals(IndividualPointer i, ObjectPropertyPointer r, IndividualPointer j) throws FaCTPlusPlusException; public native AxiomPointer tellRelatedIndividualValue(IndividualPointer i, DataPropertyPointer r, DataValuePointer dv) throws FaCTPlusPlusException; public native AxiomPointer tellNotRelatedIndividualValue(IndividualPointer i, DataPropertyPointer r, DataValuePointer dv) throws FaCTPlusPlusException; /** * Tells a same individuals axiom, whose individuals are in the last closed * arg list. */ public native AxiomPointer tellSameIndividuals() throws FaCTPlusPlusException; /** * Tells a different individuals axiom, whose individuals are in the last * closed arg list. */ public native AxiomPointer tellDifferentIndividuals() throws FaCTPlusPlusException; // ------------------------------------------------------------------------ // Retraction // ------------------------------------------------------------------------ public native void retract(AxiomPointer a) throws FaCTPlusPlusException; // ------------------------------------------------------------------------ // ASK queries // ------------------------------------------------------------------------ public native boolean isKBConsistent() throws FaCTPlusPlusException; public native boolean isClassSatisfiable(ClassPointer c) throws FaCTPlusPlusException; public native boolean isClassSubsumedBy(ClassPointer c, ClassPointer d) throws FaCTPlusPlusException; public native boolean isClassEquivalentTo(ClassPointer c, ClassPointer d) throws FaCTPlusPlusException; public native boolean isClassDisjointWith(ClassPointer c, ClassPointer d) throws FaCTPlusPlusException; public native ClassPointer[][] askSubClasses(ClassPointer c, boolean direct) throws FaCTPlusPlusException; public native ClassPointer[][] askSuperClasses(ClassPointer c, boolean direct) throws FaCTPlusPlusException; public native ClassPointer[] askEquivalentClasses(ClassPointer c) throws FaCTPlusPlusException; public native ClassPointer[][] askDisjointClasses(ClassPointer c) throws FaCTPlusPlusException; public native ObjectPropertyPointer[][] askSuperObjectProperties(ObjectPropertyPointer r, boolean direct) throws FaCTPlusPlusException; public native ObjectPropertyPointer[][] askSubObjectProperties(ObjectPropertyPointer r, boolean direct) throws FaCTPlusPlusException; public native ObjectPropertyPointer[] askEquivalentObjectProperties(ObjectPropertyPointer r) throws FaCTPlusPlusException; public native ClassPointer[][] askObjectPropertyDomain(ObjectPropertyPointer r, boolean direct) throws FaCTPlusPlusException; public native ClassPointer[][] askObjectPropertyRange(ObjectPropertyPointer r, boolean direct) throws FaCTPlusPlusException; public native boolean isObjectPropertyFunctional(ObjectPropertyPointer r) throws FaCTPlusPlusException; public native boolean isObjectPropertyInverseFunctional(ObjectPropertyPointer r) throws FaCTPlusPlusException; public native boolean isObjectPropertySymmetric(ObjectPropertyPointer r) throws FaCTPlusPlusException; public native boolean isObjectPropertyAsymmetric(ObjectPropertyPointer r) throws FaCTPlusPlusException; public native boolean isObjectPropertyTransitive(ObjectPropertyPointer r) throws FaCTPlusPlusException; public native boolean isObjectPropertyReflexive(ObjectPropertyPointer r) throws FaCTPlusPlusException; public native boolean isObjectPropertyIrreflexive(ObjectPropertyPointer r) throws FaCTPlusPlusException; // @return true iff R is a sub-property of S public native boolean isObjectSubPropertyOf(ObjectPropertyPointer r, ObjectPropertyPointer s) throws FaCTPlusPlusException; // @return true iff R is disjoint with S public native boolean isObjectPropertyDisjointWith(ObjectPropertyPointer r, ObjectPropertyPointer s) throws FaCTPlusPlusException; // @return true iff R is a super-property of a chain given in the argument // list public native boolean isSubPropertyChainOf(ObjectPropertyPointer r) throws FaCTPlusPlusException; // @return true iff all the properties in the arg-list are disjoint public native boolean arePropertiesDisjoint() throws FaCTPlusPlusException; public native DataPropertyPointer[][] askSuperDataProperties(DataPropertyPointer r, boolean direct) throws FaCTPlusPlusException; public native DataPropertyPointer[][] askSubDataProperties(DataPropertyPointer r, boolean direct) throws FaCTPlusPlusException; public native DataPropertyPointer[] askEquivalentDataProperties(DataPropertyPointer r) throws FaCTPlusPlusException; public native ClassPointer[][] askDataPropertyDomain(DataPropertyPointer r, boolean direct) throws FaCTPlusPlusException; public native boolean isDataPropertyFunctional(DataPropertyPointer r) throws FaCTPlusPlusException; // @return true iff R is a sub-property of S public native boolean isDataSubPropertyOf(DataPropertyPointer r, DataPropertyPointer s) throws FaCTPlusPlusException; // @return true iff R is disjoint with S public native boolean isDataPropertyDisjointWith(DataPropertyPointer r, DataPropertyPointer s) throws FaCTPlusPlusException; public native ClassPointer[][] askIndividualTypes(IndividualPointer i, boolean direct) throws FaCTPlusPlusException; // helper for the askObjectPropertyRelationships() public native ObjectPropertyPointer[] askObjectProperties(IndividualPointer i) throws FaCTPlusPlusException; public native IndividualPointer[] askRelatedIndividuals(IndividualPointer individualPointer, ObjectPropertyPointer r) throws FaCTPlusPlusException; // helper for the askDataPropertyRelationships() public native DataPropertyPointer[] askDataProperties(IndividualPointer i) throws FaCTPlusPlusException; public native DataValuePointer[] askRelatedValues(IndividualPointer individualPointer, DataPropertyPointer r) throws FaCTPlusPlusException; public native boolean hasDataPropertyRelationship(IndividualPointer i, DataPropertyPointer r, DataValuePointer v) throws FaCTPlusPlusException; public native boolean hasObjectPropertyRelationship(IndividualPointer i, ObjectPropertyPointer r, IndividualPointer j) throws FaCTPlusPlusException; public native boolean isInstanceOf(IndividualPointer i, ClassPointer c) throws FaCTPlusPlusException; public native IndividualPointer[] askInstances(ClassPointer c, boolean direct) throws FaCTPlusPlusException; // return instances grouped by the SameAs relation public native IndividualPointer[][] askInstancesGrouped(ClassPointer c, boolean direct) throws FaCTPlusPlusException; public native IndividualPointer[] askSameAs(IndividualPointer i) throws FaCTPlusPlusException; public native boolean isSameAs(IndividualPointer i, IndividualPointer j) throws FaCTPlusPlusException; // ------------------------------------------------------------------------ // Options // ------------------------------------------------------------------------ // sets single operation timeout in milliseconds public native void setOperationTimeout(long millis); // sets single operation timeout in milliseconds public native void setFreshEntityPolicy(boolean allowFresh); public native void setProgressMonitor(FaCTPlusPlusProgressMonitor progressMonitor) throws FaCTPlusPlusException; public native void startChanges(); public native void endChanges(); // ------------------------------------------------------------------------ // Argument list processing // ------------------------------------------------------------------------ /** * Starts an arg list. Note that only ONE arg list may be created at any * given time. For example, it is illegal to call initArgList for a second * time without closing calling closeArgList first. * * @throws FaCTPlusPlusException */ public native void initArgList() throws FaCTPlusPlusException; /** * Adds an argument to the currently open arg list. * * @param p * A pointer to the argument to be added. * @throws FaCTPlusPlusException */ public native void addArg(Pointer p) throws FaCTPlusPlusException; /** * Closes the currently open arg list. It is illegal to close an empty arg * list. It is also illegal to call this method without calling initArgList * first. * * @throws FaCTPlusPlusException */ public native void closeArgList() throws FaCTPlusPlusException; // ------------------------------------------------------------------------ // Tracing (currently unimplemented) // ------------------------------------------------------------------------ /** * Switch on the tracing of the next reasoning operation */ public native void needTracing(); /** * get the trace-set (set of axioms) for the last reasoning operation */ public native AxiomPointer[] getTrace(); // ------------------------------------------------------------------------ // Knowledge Exploration interface // ------------------------------------------------------------------------ public native NodePointer buildCompletionTree(ClassPointer classPointer); public native ObjectPropertyPointer[] getObjectNeighbours(NodePointer object, boolean deterministicOnly); public native DataPropertyPointer[] getDataNeighbours(NodePointer object, boolean deterministicOnly); public native NodePointer[] getObjectNeighbours(NodePointer object, ObjectPropertyPointer property); public native NodePointer[] getDataNeighbours(NodePointer object, DataPropertyPointer property); public native ClassPointer[] getObjectLabel(NodePointer object, boolean deterministicOnly); public native DataTypePointer[] getDataLabel(NodePointer object, boolean deterministicOnly); // ------------------------------------------------------------------------ // Atomic Decomposition interface // ------------------------------------------------------------------------ public native int getAtomicDecompositionSize(boolean useSemantic, int moduleType); public native AxiomPointer[] getAtomAxioms(int index); public native int[] getAtomDependents(int index); // ------------------------------------------------------------------------ // Modularity interface // ------------------------------------------------------------------------ public native AxiomPointer[] getModule(boolean useSemantic, int moduleType); public native AxiomPointer[] getNonLocal(boolean useSemantic, int moduleType); } FaCTpp-src-v1.6.2~dfsg/src/FaCT++.Java/uk/ac/manchester/cs/factplusplus/IndividualPointer.java0000644000000000000000000000214612112642405030503 0ustar rootroot/* * Copyright (C) 2009-2010, University of Manchester * * Modifications to the initial code base are copyright of their * respective authors, or their employers as appropriate. Authorship * of the modifications may be determined from the ChangeLog placed at * the end of this file. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package uk.ac.manchester.cs.factplusplus; public class IndividualPointer extends Pointer { } FaCTpp-src-v1.6.2~dfsg/src/FaCT++.Java/uk/ac/manchester/cs/factplusplus/ObjectPropertyPointer.java0000644000000000000000000000215212112642405031363 0ustar rootroot/* * Copyright (C) 2009-2010, University of Manchester * * Modifications to the initial code base are copyright of their * respective authors, or their employers as appropriate. Authorship * of the modifications may be determined from the ChangeLog placed at * the end of this file. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package uk.ac.manchester.cs.factplusplus; public class ObjectPropertyPointer extends Pointer { } FaCTpp-src-v1.6.2~dfsg/src/FaCT++.Java/uk/ac/manchester/cs/factplusplus/DataTypeFacet.java0000644000000000000000000000047012112642405027526 0ustar rootrootpackage uk.ac.manchester.cs.factplusplus; /** * Author: Matthew Horridge
* The University Of Manchester
* Medical Informatics Group
* Date: 10-Jul-2006

*

* matthew.horridge@cs.man.ac.uk
* www.cs.man.ac.uk/~horridgm

*/ public class DataTypeFacet extends Pointer { } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootFaCTpp-src-v1.6.2~dfsg/src/FaCT++.Java/uk/ac/manchester/cs/factplusplus/DataTypeExpressionPointer.javaFaCTpp-src-v1.6.2~dfsg/src/FaCT++.Java/uk/ac/manchester/cs/factplusplus/DataTypeExpressionPointer.ja0000644000000000000000000000215612112642405031660 0ustar rootrootpackage uk.ac.manchester.cs.factplusplus; /* * Copyright (C) 2009-2010, University of Manchester * * Modifications to the initial code base are copyright of their * respective authors, or their employers as appropriate. Authorship * of the modifications may be determined from the ChangeLog placed at * the end of this file. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ public class DataTypeExpressionPointer extends Pointer { } FaCTpp-src-v1.6.2~dfsg/src/FaCT++.Java/uk/ac/manchester/cs/factplusplus/QuietProgressMonitor.java0000644000000000000000000000273012112642405031235 0ustar rootrootpackage uk.ac.manchester.cs.factplusplus; /* * Copyright (C) 2006, University of Manchester * * Modifications to the initial code base are copyright of their * respective authors, or their employers as appropriate. Authorship * of the modifications may be determined from the ChangeLog placed at * the end of this file. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ /** * Author: Matthew Horridge
* The University Of Manchester
* Bio-Health Informatics Group
* Date: 28-Nov-2006

*/ public class QuietProgressMonitor implements FaCTPlusPlusProgressMonitor { public void setClassificationStarted(int classCount) { } public void nextClass() { } public void setFinished() { } public boolean isCancelled() { return false; } } FaCTpp-src-v1.6.2~dfsg/src/version-info-p4.1.html0000644000000000000000000000025712112642425020126 0ustar rootroot

FaCT++

Reasoner plugin More information here

26 October 2012: Bugfix release FaCTpp-src-v1.6.2~dfsg/src/FaCT++/0000755000000000000000000000000012112642473015044 5ustar rootrootFaCTpp-src-v1.6.2~dfsg/src/FaCT++/AD.cpp0000644000000000000000000000556012112642405016035 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2012 by Dmitry Tsarkov This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ // methods to work with Atomic Decomposition #include #include "AtomicDecomposer.h" #include "tOntologyPrinterLISP.h" // AD prints #include "procTimer.h" #include "cppi.h" // defined in FaCT.cpp extern std::ofstream Out; // print axioms of an atom static void printAtomAxioms ( const TOntologyAtom::AxiomSet& Axioms ) { static TLISPOntologyPrinter LP(Out); // do cycle via set to keep the order typedef std::set AxSet; const AxSet M ( Axioms.begin(), Axioms.end() ); for ( AxSet::const_iterator p = M.begin(); p != M.end(); ++p ) (*p)->accept(LP); } /// print dependencies of an atom static void printAtomDeps ( const TOntologyAtom::AtomSet& Dep ) { if ( unlikely(Dep.empty()) ) Out << "Ground"; else Out << "Depends on:"; for ( TOntologyAtom::AtomSet::const_iterator q = Dep.begin(), q_end = Dep.end(); q != q_end; ++q ) Out << " " << (*q)->getId(); Out << "\n"; } /// print the atom with an index INDEX of the AD static void printADAtom ( TOntologyAtom* atom ) { const TOntologyAtom::AxiomSet& Axioms = atom->getAtomAxioms(); Out << "Atom " << atom->getId() << " (size " << Axioms.size() << ", module size " << atom->getModule().size() << "):\n"; printAtomAxioms(Axioms); printAtomDeps(atom->getDepAtoms()); } /// @return all the axioms in the AD static size_t sizeAD ( AOStructure* AOS ) { size_t ret = 0; for ( AOStructure::iterator p = AOS->begin(), p_end = AOS->end(); p != p_end; ++p ) ret += (*p)->getAtomAxioms().size(); return ret; } void CreateAD ( TOntology* Ontology, bool useSem ) { std::cerr << "\n"; // do the atomic decomposition TsProcTimer timer; timer.Start(); TModularizer mod(useSem); AtomicDecomposer* AD = new AtomicDecomposer(&mod); AD->setProgressIndicator(new CPPI()); AOStructure* AOS = AD->getAOS ( Ontology, M_BOT ); timer.Stop(); Out << "Atomic structure built in " << timer << " seconds\n"; size_t sz = sizeAD(AOS); Out << "Atomic structure (" << sz << " axioms in " << AOS->size() << " atoms; " << Ontology->size()-sz << " tautologies):\n"; for ( AOStructure::iterator p = AOS->begin(), p_end = AOS->end(); p != p_end; ++p ) printADAtom(*p); delete AD; } FaCTpp-src-v1.6.2~dfsg/src/FaCT++/comscanner.h0000644000000000000000000000543112112642405017343 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2011 by Dmitry Tsarkov This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ //------------------------------------------------------------------------- // // Scanner class for FaCT++ // //------------------------------------------------------------------------- #ifndef COMSCANNER_H #define COMSCANNER_H #include #include #include /// max ID length for scanned objects const unsigned int MaxIDLength = 10240; /// more-or-less general simple scanner implementation class CommonScanner { protected: // members /// input stream std::istream* InFile; /// buffer for names char LexBuff [ MaxIDLength + 1 ]; /// currently processed line of input (used in error diagnosis) unsigned int CurLine; protected: // methods /// get next symbol from the stream char NextChar ( void ) const { return InFile->get(); } /// return given symbol back to stream void PutBack ( char c ) const { InFile->putback(c); } /// check whether C is a EOF char static bool eof ( char c ) { return c == std::char_traits::eof(); } public: // interface /// c'tor CommonScanner ( std::istream* inp ) : InFile(inp) , CurLine(1) {} /// d'tor virtual ~CommonScanner ( void ) {} /// get string collected in buffer const char* GetName ( void ) const { return LexBuff; } /// get number by string from buffer unsigned long GetNumber ( void ) const { return atol ( LexBuff ); } /// get current input line unsigned int Line ( void ) const { return CurLine; } /// check if Buffer contains given Word (in any register) bool isKeyword ( const char* Word ) const { return strlen(Word) == strlen(LexBuff) ? !strcmp ( Word, LexBuff ) : false; } /// reset scanner on the same file void ReSet ( void ) { InFile->clear(); InFile->seekg ( 0L, std::ios::beg ); CurLine = 1; } /// reset scanner to a given file void reIn ( std::istream* in ) { InFile = in; CurLine = 1; } /// output an error message void error ( const char* msg = NULL ) const { std::cerr << "\nError at input line " << Line() << ": " << (msg?msg:"illegal syntax") << std::endl; exit (1); } }; // CommonScanner #endif FaCTpp-src-v1.6.2~dfsg/src/FaCT++/comparser.h0000644000000000000000000000357712112642405017217 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2011 by Dmitry Tsarkov This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef COMPARSER_H #define COMPARSER_H #include "comscanner.h" /// generic class for parsing with usage of scanner derived from CommonScanner template class CommonParser { protected: // members /// used scanner Scanner scan; /// last scanned token GenericToken Current; protected: // methods /// get current token GenericToken Code ( void ) const { return Current; } /// receive (and save) next token void NextLex ( void ) { Current = scan. GetLex (); } /// ensure that current token has given value; return error if it's not a case void MustBe ( GenericToken t, const char* p = NULL ) const { if ( Current != t ) scan. error (p); } /// ensure that current token has given value; return error if it's not a case; get new token void MustBeM ( GenericToken t, const char* p = NULL ) { MustBe ( t, p ); NextLex (); } /// general error message void parseError ( const char* p ) const { scan.error(p); } public: // interface /// c'tor CommonParser ( std::istream* in ) : scan ( in ) { NextLex (); } /// empty d'tor virtual ~CommonParser ( void ) {} }; // CommonParser #endif // _COMMON_PARSER_HPP FaCTpp-src-v1.6.2~dfsg/src/FaCT++/scanner.h0000644000000000000000000000400312112642405016636 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2011 by Dmitry Tsarkov This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ //------------------------------------------------------------------------- // // Scanner class for FaCT++ // //------------------------------------------------------------------------- #ifndef SCANNER_H #define SCANNER_H #include "lispgrammar.h" #include "comscanner.h" /// more-or-less general simple scanner implementation class TsScanner: public CommonScanner { protected: // methods /// fill buffer with name in '|'-s; c should be starting '|' void FillNameBuffer ( register char c ); /// fill buffer with legal ID chars, starting from c void FillBuffer ( register char c ); /// check if given character is legal in ID bool isLegalIdChar ( char c ) const; public: // interface /// c'tor TsScanner ( std::istream* inp ) : CommonScanner(inp) {} /// d'tor ~TsScanner ( void ) {} /// get next token from stream LispToken GetLex ( void ); /// get keyword for a command by given text in buffer; @return BAD_LEX if no keyword found LispToken getCommandKeyword ( void ) const; /// get keyword for a concept/role expression; @return BAD_LEX if no keyword found LispToken getExpressionKeyword ( void ) const; /// get keyword for a concept/role special name; @return ID if no keyword found LispToken getNameKeyword ( void ) const; }; // TsScanner #endif FaCTpp-src-v1.6.2~dfsg/src/FaCT++/parser.cpp0000644000000000000000000003745312112642405017053 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2011 by Dmitry Tsarkov This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "parser.h" #include #include #include #include /********************* DLParser implementation ***************************/ void DLLispParser :: Parse ( void ) { while ( Current != LEXEOF ) parseCommand (); } void DLLispParser :: parseCommand ( void ) { MustBeM (LBRACK); MustBe(ID); LispToken t = scan.getCommandKeyword(); NextLex (); switch (t) { case SUBSUMES: case EQUAL_C: { TConceptExpr* left = getConceptExpression(); TConceptExpr* right = getConceptExpression(); try { if ( t == SUBSUMES ) Kernel->impliesConcepts ( left, right ); else { EManager->newArgList(); EManager->addArg(left); EManager->addArg(right); Kernel->equalConcepts(); } } catch ( const EFaCTPlusPlus& ex ) { parseError(ex.what()); } break; } case IMPLIES_R: case EQUAL_R: case DISJOINT_R: case INVERSE: { TRoleExpr* R = (t == IMPLIES_R) ? getComplexRoleExpression() : getRoleExpression(); if ( isDataRole(R) ) tellRoleAxiom ( t, dynamic_cast(R), getDRoleExpression() ); else if ( t != IMPLIES_R ) tellRoleAxiom ( t, dynamic_cast(R), getORoleExpression() ); else // implies_R try { Kernel->impliesORoles ( dynamic_cast(R), getORoleExpression() ); } catch ( const EFaCTPlusPlus& ex ) { parseError(ex.what()); } break; } case FUNCTIONAL: case TRANSITIVE: case REFLEXIVE: case IRREFLEXIVE: case SYMMETRIC: case ASYMMETRIC: { TRoleExpr* R = getRoleExpression(); if ( isDataRole(R) ) tellRoleAxiom ( t, dynamic_cast(R), NULL ); else tellRoleAxiom ( t, dynamic_cast(R), NULL ); break; } case ROLERANGE: case ROLEDOMAIN: { TRoleExpr* R = getRoleExpression(); try { if ( isDataRole(R) ) { TDRoleExpr* S = dynamic_cast(R); if ( t == ROLERANGE ) Kernel->setDRange ( S, getDataExpression() ); else Kernel->setDDomain ( S, getConceptExpression() ); } else { TORoleExpr* S = dynamic_cast(R); if ( t == ROLERANGE ) Kernel->setORange ( S, getConceptExpression() ); else Kernel->setODomain ( S, getConceptExpression() ); } } catch ( const EFaCTPlusPlus& ex ) { parseError(ex.what()); } break; } // disjoint-like operator case DISJOINT: case FAIRNESS: case DIFFERENT: case SAME: parseConceptList ( /*singletonsOnly=*/ (t != DISJOINT) && (t != FAIRNESS) ); try { switch (t) { case DISJOINT: Kernel->disjointConcepts(); return; // already read ')' case FAIRNESS: Kernel->setFairnessConstraint(); return; // already read ')' case SAME: Kernel->processSame(); return; // already read ')' case DIFFERENT: Kernel->processDifferent(); return; // already read ')' default: fpp_unreachable(); } } catch ( const EFaCTPlusPlus& ex ) { parseError(ex.what()); } break; case PCONCEPT: { TConceptExpr* Name = getConcept(); if ( Current != RBRACK ) Kernel->impliesConcepts ( Name, getConceptExpression() ); else Kernel->declare(Name); break; } case CONCEPT: EManager->newArgList(); EManager->addArg(getConcept()); EManager->addArg(getConceptExpression()); Kernel->equalConcepts(); break; case DEFINDIVIDUAL: // just register singleton Kernel->declare(getSingleton()); break; case INSTANCE: { TIndividualExpr* Name = getSingleton(); Kernel->instanceOf ( Name, getConceptExpression() ); break; } case RELATED: // command is (Related id1 R id2); try { TIndividualExpr* id1 = getSingleton(); TORoleExpr* R = getORoleExpression(); MustBe (ID); // second indiv. TIndividualExpr* id2 = getSingleton(); Kernel->relatedTo ( id1, R, id2 ); } catch ( const EFaCTPlusPlus& ex ) { parseError(ex.what()); } break; case PROLE: case PATTR: { TORoleExpr* Name = getObjectRole(); if ( t == PATTR ) try { Kernel->setOFunctional(Name); } catch ( const EFaCTPlusPlus& ex ) { parseError(ex.what()); } if ( Current != RBRACK ) parseRoleArguments(Name); else Kernel->declare(Name); break; } case DATAROLE: // register data role Kernel->declare(getDataRole()); break; default: parseError ( "Unrecognised command" ); } MustBeM ( RBRACK ); // skip bracket } /// generate object role axiom between R and S according to the operation TAG void DLLispParser :: tellRoleAxiom ( LispToken tag, TORoleExpr* R, TORoleExpr* S ) { try { switch(tag) { case INVERSE: Kernel->setInverseRoles ( R, S ); break; case DISJOINT_R: case EQUAL_R: EManager->newArgList(); EManager->addArg(R); EManager->addArg(S); if ( tag == DISJOINT_R ) Kernel->disjointORoles(); else Kernel->equalORoles(); break; case FUNCTIONAL: Kernel->setOFunctional(R); break; case TRANSITIVE: Kernel->setTransitive(R); break; case REFLEXIVE: Kernel->setReflexive(R); break; case IRREFLEXIVE: Kernel->setIrreflexive(R); break; case SYMMETRIC: Kernel->setSymmetric(R); break; case ASYMMETRIC: Kernel->setAsymmetric(R); break; default: parseError("Unrecognised object role command"); } } catch ( const EFaCTPlusPlus& ex ) { parseError(ex.what()); } } /// generate data role axiom between R and S according to the operation TAG void DLLispParser :: tellRoleAxiom ( LispToken tag, TDRoleExpr* R, TDRoleExpr* S ) { try { switch(tag) { case IMPLIES_R: Kernel->impliesDRoles ( R, S ); break; case DISJOINT_R: case EQUAL_R: EManager->newArgList(); EManager->addArg(R); EManager->addArg(S); if ( tag == DISJOINT_R ) Kernel->disjointDRoles(); else Kernel->equalDRoles(); break; case FUNCTIONAL: Kernel->setDFunctional(R); break; default: parseError("Unrecognised data role command"); } } catch ( const EFaCTPlusPlus& ex ) { parseError(ex.what()); } } void DLLispParser :: parseConceptList ( bool singletonsOnly ) { EManager->newArgList(); // continue with all concepts while ( Current != RBRACK ) if ( singletonsOnly ) EManager->addArg(getSingleton()); else EManager->addArg(getConceptExpression()); // skip RBRACK MustBeM (RBRACK); } void DLLispParser :: parseRoleArguments ( TORoleExpr* R ) { while ( Current != RBRACK ) if ( scan.isKeyword ("parents") || scan.isKeyword ("supers") ) { // followed by a list of parent role names NextLex (); MustBeM ( LBRACK ); while ( Current != RBRACK ) { try { // only object roles can have arguments Kernel->impliesORoles ( R, getORoleExpression() ); } catch ( const EFaCTPlusPlus& ex ) { parseError(ex.what()); } } NextLex (); // skip last RBRACK } else if ( scan.isKeyword ("transitive") ) { // followed by NIL or (usually!) T NextLex (); try { Kernel->setTransitive(R); } catch ( const EFaCTPlusPlus& ex ) { parseError(ex.what()); } NextLex (); // skip token } else parseError ( "use either :parents or :transitive command in role description" ); } DLLispParser::TConceptExpr* DLLispParser :: getConceptExpression ( void ) { switch ( Code() ) { case LBRACK: // complex description return getComplexConceptExpression (); case NUM: // numbers in concept expressions are constant names return getConcept(); case ID: { switch ( scan.getNameKeyword() ) { // Top/Bottom or real ID case L_TOP: NextLex(); return EManager->Top(); case L_BOTTOM: NextLex(); return EManager->Bottom(); default: return getConcept(); } } default: // else -- report syntax error MustBe(ID); return NULL; } } DLLispParser::TConceptExpr* DLLispParser :: getComplexConceptExpression ( void ) { MustBeM ( LBRACK ); LispToken T = scan.getExpressionKeyword(); unsigned int n = 0; // number for >= (<=) expression (or just 0) TRoleExpr* R = NULL; TConceptExpr* C = NULL; NextLex (); switch (T) { case L_GE: case L_LE: // hack: id here is a number restriction n = scan.GetNumber (); NextLex (); // hack: throughout case L_FORALL: case L_EXISTS: // first argument -- role name R = getRoleExpression(); if ( isDataRole(R) ) // data expression { TDRoleExpr* A = dynamic_cast(R); TDataExpr* E = NULL; // second argument -- data expression if ( Current == RBRACK ) E = EManager->DataTop(); // for (GE n R) else E = getDataExpression(); // skip right bracket MustBeM(RBRACK); if ( T == L_EXISTS ) return EManager->Exists ( A, E ); else if ( T == L_FORALL ) return EManager->Forall ( A, E ); else if ( T == L_GE ) return EManager->MinCardinality ( n, A, E ); else return EManager->MaxCardinality ( n, A, E ); } else { TORoleExpr* S = dynamic_cast(R); TConceptExpr* C = NULL; // second argument -- data expression if ( Current == RBRACK ) C = EManager->Top(); // for (GE n R) else C = getConceptExpression(); // skip right bracket MustBeM(RBRACK); if ( T == L_EXISTS ) return EManager->Exists ( S, C ); else if ( T == L_FORALL ) return EManager->Forall ( S, C ); else if ( T == L_GE ) return EManager->MinCardinality ( n, S, C ); else return EManager->MaxCardinality ( n, S, C ); } case REFLEXIVE: // self-reference R = getORoleExpression(); // skip right bracket MustBeM(RBRACK); return EManager->SelfReference(dynamic_cast(R)); case L_NOT: C = getConceptExpression(); // skip right bracket MustBeM(RBRACK); return EManager->Not(C); case L_AND: case L_OR: // multiple And's/Or's EManager->newArgList(); do { EManager->addArg(getConceptExpression()); } while ( Current != RBRACK ); // list is parsed here NextLex(); // skip ')' return T == L_AND ? EManager->And() : EManager->Or(); case ONEOF: parseConceptList(/*singletonsOnly=*/true); return EManager->OneOf(); default: // error parseError ( "Unknown concept constructor" ); return NULL; // FSCO } } DLLispParser::TDRoleExpr* DLLispParser :: getDRoleExpression ( void ) { MustBe ( ID, "Data role name expected" ); return getDataRole(); } DLLispParser::TORoleExpr* DLLispParser :: getORoleExpression ( void ) { if ( Current != LBRACK ) return getObjectRole(); NextLex(); // skip '(' if ( scan.getExpressionKeyword() != L_INV ) MustBe ( L_INV, "only role names and their inverses are allowed as a role expression" ); NextLex(); // skip INV TORoleExpr* ret = EManager->Inverse(getORoleExpression()); MustBeM(RBRACK); return ret; } DLLispParser::TRoleExpr* DLLispParser :: getRoleExpression ( void ) { if ( Current != LBRACK ) return getRole(); NextLex(); // skip '(' if ( scan.getExpressionKeyword() != L_INV ) MustBe ( L_INV, "only role names and their inverses are allowed as a role expression" ); NextLex(); // skip INV TORoleExpr* ret = EManager->Inverse(getORoleExpression()); MustBeM(RBRACK); return ret; } DLLispParser::TRoleExpr* DLLispParser :: getComplexRoleExpression ( void ) { if ( Current != LBRACK ) return getRole(); NextLex(); // skip '(' LispToken keyword = scan.getExpressionKeyword(); NextLex(); // skip keyword TORoleComplexExpr* ret = NULL; TORoleExpr* R; switch ( keyword ) { case L_INV: // inverse of a simple role ret = EManager->Inverse(getORoleExpression()); break; case L_RCOMPOSITION: // role composition expression = list of simple roles EManager->newArgList(); while ( Current != RBRACK ) EManager->addArg(getORoleExpression()); ret = EManager->Compose(); break; case L_PROJINTO: // role projection operator, parse simple role and concept R = getORoleExpression(); ret = EManager->ProjectInto ( R, getConceptExpression() ); break; case L_PROJFROM: // role projection operator, parse simple role and concept R = getORoleExpression(); ret = EManager->ProjectFrom ( R, getConceptExpression() ); break; default: MustBe ( L_INV, "unknown expression in complex role constructor" ); } MustBeM(RBRACK); return ret; } DLLispParser::TDataExpr* DLLispParser :: getDataExpression ( void ) { // check for TOP/BOTTOM if ( Code() == ID ) { switch ( scan.getNameKeyword() ) { // Top/Bottom; can not be name case L_TOP: NextLex(); return EManager->DataTop(); case L_BOTTOM: NextLex(); return EManager->DataBottom(); default: parseError ( "Unknown data constructor" ); return NULL; } } MustBeM(LBRACK); // always complex expression LispToken T = scan.getExpressionKeyword(); NextLex (); switch (T) { case DTGT: // facet ">" { TDataValueExpr* value = dynamic_cast(getDataExpression()); MustBeM(RBRACK); if ( value == NULL ) parseError("Data value expected"); // the type of the expression is taken from value; it is basic type, so it is safe to make it RW TDataTypeExpr* type = const_cast(value->getExpr()); return EManager->RestrictedType ( type, EManager->FacetMinExclusive(value) ); } case DTGE: // facet ">=" { TDataValueExpr* value = dynamic_cast(getDataExpression()); MustBeM(RBRACK); if ( value == NULL ) parseError("Data value expected"); // the type of the expression is taken from value; it is basic type, so it is safe to make it RW TDataTypeExpr* type = const_cast(value->getExpr()); return EManager->RestrictedType ( type, EManager->FacetMinInclusive(value) ); } case DTLT: // facet "<" { TDataValueExpr* value = dynamic_cast(getDataExpression()); MustBeM(RBRACK); if ( value == NULL ) parseError("Data value expected"); // the type of the expression is taken from value; it is basic type, so it is safe to make it RW TDataTypeExpr* type = const_cast(value->getExpr()); return EManager->RestrictedType ( type, EManager->FacetMaxExclusive(value) ); } case DTLE: // facet "<=" { TDataValueExpr* value = dynamic_cast(getDataExpression()); MustBeM(RBRACK); if ( value == NULL ) parseError("Data value expected"); // the type of the expression is taken from value; it is basic type, so it is safe to make it RW TDataTypeExpr* type = const_cast(value->getExpr()); return EManager->RestrictedType ( type, EManager->FacetMaxInclusive(value) ); } case L_NOT: { TDataExpr* expr = getDataExpression(); // skip right bracket MustBeM ( RBRACK ); return EManager->DataNot(expr); } case DONEOF: case L_AND: case L_OR: // multiple And's/Or's EManager->newArgList(); do { EManager->addArg(getDataExpression()); } while ( Current != RBRACK ); // list is parsed here NextLex(); // skip ')' return T == L_AND ? EManager->DataAnd() : T == L_OR ? EManager->DataOr() : EManager->DataOneOf(); case STRING: // expression (string ) case NUMBER: // expression (number ) case REAL: // expression (real ) case BOOL: { TDataTypeExpr* type = (T == STRING) ? EManager->getStrDataType(): (T == NUMBER) ? EManager->getIntDataType(): (T == REAL ) ? EManager->getRealDataType(): EManager->getBoolDataType(); if ( Current == RBRACK ) // just datatype { NextLex(); return type; } NextLex(); return getDTValue(type); } default: // error parseError ( "Unknown data constructor" ); return NULL; // FSCO } } FaCTpp-src-v1.6.2~dfsg/src/FaCT++/Makefile0000644000000000000000000000034612112642405016502 0ustar rootroot# # Makefile for FaCT++ # # -- DO NOT CHANGE THE REST OF FILE -- EXECUTABLE = FaCT++ USE_IL = ../Kernel SOURCES = \ scanner.cpp\ parser.cpp\ AD.cpp\ FaCT.cpp include ../Makefile.include FaCTpp-src-v1.6.2~dfsg/src/FaCT++/scanner.cpp0000644000000000000000000001405612112642405017202 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2012 by Dmitry Tsarkov This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ //------------------------------------------------------------------------- // // Scanner implementation for FaCT++ program // //------------------------------------------------------------------------- #include // isalnum #include "scanner.h" // main methods bool TsScanner :: isLegalIdChar ( char c ) const //id=[_a..z0-9[].] { switch (c) { case '(': case ')': case ';': case '|': return false; default: return !isspace(c) && !eof(c); } } // Word must be in a CAPITAL LETTERS void TsScanner :: FillBuffer ( register char c ) { register unsigned int i = 0; LexBuff [0] = c; for ( i = 1; i < MaxIDLength && isLegalIdChar ( c = NextChar () ); LexBuff [i++] = c ) (void)NULL; LexBuff [i] = 0; if ( i == MaxIDLength ) { std::cerr << "Identifier was restricted to " << LexBuff << std::endl; for ( ; isLegalIdChar ( c = NextChar () ); ) (void)NULL; } // OK or read the end of ID PutBack ( c ); } void TsScanner :: FillNameBuffer ( register char c ) { register unsigned int i = 0; const char stop = c; for ( ; i < MaxIDLength && ( ( c = NextChar () ) != stop ); LexBuff [i++] = c ) (void)NULL; LexBuff [i] = 0; if ( i == MaxIDLength ) { std::cerr << "Identifier was restricted to " << LexBuff << std::endl; for ( ; ( c = NextChar () ) != stop; ) (void)NULL; } } LispToken TsScanner :: GetLex ( void ) { register char c; while ( !eof( c = NextChar() ) ) { if ( c == ' ' || c == '\t' || c == 13 ) continue; if ( c == '\n' ) { CurLine++; continue; } if ( c == ';' ) { // Skip comments while ( ( c = NextChar() ) != '\n' && !eof(c) ) (void)NULL; CurLine++; continue; } // one-symbol tokens if ( c == '(' ) return LBRACK; if ( c == ')' ) return RBRACK; if ( c == ':' ) // some keyword { // skip colon FillBuffer ( NextChar () ); return ID; } if ( c == '|' || c == '"' ) { FillNameBuffer ( c ); return ID; } if ( isdigit ( c ) ) //number { FillBuffer ( c ); return NUM; } else // id { FillBuffer ( c ); return ID; } // all alternates was checked => error return BAD_LEX; } // read EOF - end of lex return LEXEOF; } // recognize TOP, BOTTOM or general ID LispToken TsScanner :: getNameKeyword ( void ) const { if ( isKeyword ("*TOP*") || isKeyword ("TOP") ) return L_TOP; if ( isKeyword ("*BOTTOM*") || isKeyword ("BOTTOM") ) return L_BOTTOM; // not a keyword just an ID return ID; } // concept/role constructors; return BAD_LEX in case of error LispToken TsScanner :: getExpressionKeyword ( void ) const { if ( isKeyword ("and") ) return L_AND; if ( isKeyword ("or") ) return L_OR; if ( isKeyword ("not") ) return L_NOT; if ( isKeyword ("inv") || isKeyword ("inverse") ) return L_INV; if ( isKeyword ("compose") ) return L_RCOMPOSITION; if ( isKeyword ("project_into") ) return L_PROJINTO; if ( isKeyword ("project_from") ) return L_PROJFROM; if ( isKeyword ("some") ) return L_EXISTS; if ( isKeyword ("all") ) return L_FORALL; if ( isKeyword("min") || isKeyword("at-least") || isKeyword("atleast") ) return L_GE; if ( isKeyword("max") || isKeyword("at-most") || isKeyword("atmost") ) return L_LE; if ( isKeyword ("one-of") ) return ONEOF; if ( isKeyword ("self-ref") ) return REFLEXIVE; if ( isKeyword ("string") ) return STRING; if ( isKeyword ("number") ) return NUMBER; if ( isKeyword ("real") ) return REAL; if ( isKeyword ("bool") ) return BOOL; if ( isKeyword("gt") ) return DTGT; if ( isKeyword("lt") ) return DTLT; if ( isKeyword("ge") ) return DTGE; if ( isKeyword("le") ) return DTLE; if ( isKeyword("d-one-of") ) return DONEOF; // not a keyword -- error return BAD_LEX; } // recognize FaCT++ keywords; return BAD_LEX if not found LispToken TsScanner :: getCommandKeyword ( void ) const { // definitions if ( isKeyword ("defprimconcept") ) return PCONCEPT; if ( isKeyword ("defconcept") ) return CONCEPT; if ( isKeyword ("defprimrole") ) return PROLE; if ( isKeyword ("defdatarole") ) return DATAROLE; if ( isKeyword ("defprimattribute") ) return PATTR; if ( isKeyword ("defindividual") ) return DEFINDIVIDUAL; // general relations if ( isKeyword ("implies") || isKeyword ("implies_c") ) return SUBSUMES; if ( isKeyword ("equal_c") ) return EQUAL_C; if ( isKeyword ("disjoint") || isKeyword ("disjoint_c") ) return DISJOINT; if ( isKeyword ("implies_r") ) return IMPLIES_R; if ( isKeyword ("equal_r") ) return EQUAL_R; if ( isKeyword ("disjoint_r") ) return DISJOINT_R; if ( isKeyword ("inverse") ) return INVERSE; // role stuff if ( isKeyword ("functional") ) return FUNCTIONAL; if ( isKeyword ("transitive") ) return TRANSITIVE; if ( isKeyword ("reflexive") ) return REFLEXIVE; if ( isKeyword ("irreflexive") ) return IRREFLEXIVE; if ( isKeyword ("symmetric") ) return SYMMETRIC; if ( isKeyword ("asymmetric") ) return ASYMMETRIC; if ( isKeyword ("range") ) return ROLERANGE; if ( isKeyword ("domain") ) return ROLEDOMAIN; // individual stuff if ( isKeyword ("instance") ) return INSTANCE; if ( isKeyword ("related") ) return RELATED; if ( isKeyword ("same") ) return SAME; if ( isKeyword ("different") ) return DIFFERENT; if ( isKeyword ("fairness") ) return FAIRNESS; // not a keyword -- error return BAD_LEX; } FaCTpp-src-v1.6.2~dfsg/src/FaCT++/lispgrammar.h0000644000000000000000000000417012112642405017530 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2011 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ //------------------------------------------------------------------------- // // Grammar for FaCT++ // //------------------------------------------------------------------------- #ifndef LISPGRAMMAR_H #define LISPGRAMMAR_H // constants for symbols enum LispToken { BAD_LEX = 50, UNUSED, // never used one LEXEOF, // symbols LBRACK, RBRACK, L_AND, L_OR, L_NOT, L_INV, L_RCOMPOSITION, // role composition L_PROJINTO, // role projection into L_PROJFROM, // role projection from L_TOP, L_BOTTOM, L_EXISTS, L_FORALL, L_GE, // ATLEAST = GE, L_LE, // ATMOST = LE, // common metasymbols ID, // should NOT appear in KB -- use *NAME instead NUM, L_DATAEXPR, // any data expression: data value, [constrained] datatype // FaCT commands // definitions PCONCEPT, PROLE, PATTR, CONCEPT, DATAROLE, // FaCT++ commands for internal DataTypes NUMBER, STRING, REAL, BOOL, // datatype operations command names -- used only as an external commands DTGT, DTLT, DTGE, DTLE, DONEOF, // general commands SUBSUMES, DISJOINT, EQUAL_C, // new for roles INVERSE, EQUAL_R, IMPLIES_R, DISJOINT_R, FUNCTIONAL, TRANSITIVE, REFLEXIVE, IRREFLEXIVE, SYMMETRIC, ASYMMETRIC, ROLERANGE, ROLEDOMAIN, // new for individuals DEFINDIVIDUAL, INSTANCE, RELATED, ONEOF, SAME, DIFFERENT, // fairness constraints FAIRNESS, }; #endif FaCTpp-src-v1.6.2~dfsg/src/FaCT++/parser.h0000644000000000000000000001241012112642405016502 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2011 by Dmitry Tsarkov This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef PARSER_H #define PARSER_H #include "scanner.h" #define GenericToken LispToken #include "comparser.h" #include "Kernel.h" /// class for parsing LISP-like ontologies class DLLispParser: public CommonParser { protected: // typedefs /// general expression typedef ReasoningKernel::TExpr TExpr; /// concept expression typedef ReasoningKernel::TConceptExpr TConceptExpr; /// individual expression typedef ReasoningKernel::TIndividualExpr TIndividualExpr; /// role expression typedef ReasoningKernel::TRoleExpr TRoleExpr; /// object role complex expression (including role chains and projections) typedef ReasoningKernel::TORoleComplexExpr TORoleComplexExpr; /// object role expression typedef ReasoningKernel::TORoleExpr TORoleExpr; /// data role expression typedef ReasoningKernel::TDRoleExpr TDRoleExpr; /// data expression typedef ReasoningKernel::TDataExpr TDataExpr; /// data type expression typedef ReasoningKernel::TDataTypeExpr TDataTypeExpr; /// data value expression typedef ReasoningKernel::TDataValueExpr TDataValueExpr; protected: // members /// Kernel to be filled ReasoningKernel* Kernel; /// expression manager to be used TExpressionManager* EManager; /// set of known data role names std::set DataRoles; protected: // methods /// error by given exception void errorByException ( const EFPPCantRegName& ex ) const { parseError(ex.what()); } /// @return concept-like Id of just scanned name TConceptExpr* getConcept ( void ) { TConceptExpr* ret = EManager->Concept(scan.GetName()); NextLex(); return ret; } /// @return singleton Id of just scanned name TIndividualExpr* getSingleton ( void ) { TIndividualExpr* ret = EManager->Individual(scan.GetName()); NextLex(); return ret; } /// @return data- or object role build from just scanned name TRoleExpr* getRole ( void ) { TRoleExpr* ret; if ( DataRoles.find(scan.GetName()) != DataRoles.end() ) ret = EManager->DataRole(scan.GetName()); // found data role else // object role ret = EManager->ObjectRole(scan.GetName()); NextLex(); return ret; } /// @return data role build from just scanned name TDRoleExpr* getDataRole ( void ) { DataRoles.insert(scan.GetName()); TDRoleExpr* ret = EManager->DataRole(scan.GetName()); NextLex(); return ret; } /// @return object role build from just scanned name TORoleExpr* getObjectRole ( void ) { TORoleExpr* ret = EManager->ObjectRole(scan.GetName()); NextLex(); return ret; } /// @return datavalue of a data type TYPE with an Id of a just scanned name TDataValueExpr* getDTValue ( TDataTypeExpr* type ) { TDataValueExpr* ret = EManager->DataValue ( scan.GetName(), type ); NextLex(); return ret; } /// check whether expression R is data role bool isDataRole ( const TRoleExpr* R ) const { return dynamic_cast(R) != NULL; } /// generate object role axiom between R and S according to the operation TAG void tellRoleAxiom ( LispToken tag, TORoleExpr* R, TORoleExpr* S ); /// generate data role axiom between R and S according to the operation TAG void tellRoleAxiom ( LispToken tag, TDRoleExpr* R, TDRoleExpr* S ); /// get role expression, ie (data)role or its inverse TRoleExpr* getRoleExpression ( void ); /// get object role expression, ie object role, OR constant or their inverse TORoleExpr* getORoleExpression ( void ); /// get data role expression, ie data role or DR constant TDRoleExpr* getDRoleExpression ( void ); /// get simple role expression or role projection or chain TRoleExpr* getComplexRoleExpression ( void ); /// parse simple DL command void parseCommand ( void ); /// parse role arguments if defprimrole command void parseRoleArguments ( TORoleExpr* role ); /// parse list of concept expressions (in disjoint-like commands) void parseConceptList ( bool singletonsOnly ); /// get concept-like expression for simple variants TConceptExpr* getConceptExpression ( void ); /// get concept-like expression for complex constructors TConceptExpr* getComplexConceptExpression ( void ); /// get data expression TDataExpr* getDataExpression ( void ); public: // interface /// the only c'tor DLLispParser ( std::istream* in, ReasoningKernel* kernel ) : CommonParser(in) , Kernel (kernel) , EManager(kernel->getExpressionManager()) { // locally register Top/Bottom data properties DataRoles.insert("*UDROLE*"); DataRoles.insert("*EDROLE*"); } /// empty d'tor ~DLLispParser ( void ) {} /// main parsing method void Parse ( void ); }; // DLLispParser #endif FaCTpp-src-v1.6.2~dfsg/src/FaCT++/FaCT.cpp0000644000000000000000000002061412112642405016323 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2012 by Dmitry Tsarkov This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include #include #include #include #include "procTimer.h" #include "parser.h" #include "configure.h" #include "logging.h" #include "Kernel.h" #include "cpm.h" #include "ELFNormalizer.h" #include "ELFReasoner.h" TsProcTimer totalTimer, wTimer; Configuration Config; ReasoningKernel Kernel; std::ofstream Out; // defined in AD.cpp void CreateAD ( TOntology* O, bool useSem ); // local methods inline void Usage ( void ) { std::cerr << "\nUsage:\tFaCT++ or\n\tFaCT++ -get-default-options\n\n"; exit (1); } inline void error ( const char* mes ) { std::cerr << mes << "\n"; exit(2); } inline void OutTime ( std::ostream& o ) { o << "Working time = " << totalTimer << " seconds\n"; } //---------------------------------------------------------------------------------- // SAT/SUB queries //---------------------------------------------------------------------------------- std::string Query[2]; /// fill query target names by configure void fillSatSubQuery ( void ) { // founds a target for checking if ( !Config.checkValue ( "Query", "Target" ) ) Query[0] = Config.getString(); if ( !Config.checkValue ( "Query", "Target2" ) ) Query[1] = Config.getString(); } ReasoningKernel::TConceptExpr* getNextName ( TsScanner& sc, TExpressionManager* pEM ) { for (;;) { if ( sc.GetLex() == LEXEOF ) return NULL; LispToken t = sc.getNameKeyword(); if ( t != ID ) return t == L_TOP ? pEM->Top() : pEM->Bottom(); try { return pEM->Concept(sc.GetName()); } catch ( const EFPPCantRegName& ) { try { return pEM->OneOf(pEM->Individual(sc.GetName())); } catch ( const EFPPCantRegName& ) { std::cout << "Query name " << sc.GetName() << " is undefined in TBox\n"; } } } } const char* getConceptName ( ReasoningKernel::TConceptExpr* C ) { if ( dynamic_cast(C) != NULL ) return "*TOP*"; if ( dynamic_cast(C) != NULL ) return "*BOTTOM*"; if ( dynamic_cast(C) != NULL ) return dynamic_cast(C)->getName(); return "concept expression"; } /// try to do a reasoning; react if exception was thrown #define TryReasoning(action) \ do { \ try { action; } \ catch ( const EFPPInconsistentKB& ) {} \ catch ( const EFPPCantRegName& crn ) \ { std::cout << "Query name " << crn.getName() \ << " is undefined in TBox\n"; } \ catch ( const EFPPNonSimpleRole& nsr ) \ { std::cerr << "WARNING: KB is incorrect: " \ << nsr.what() << ". Query is NOT processed\n"; \ exit(0); } \ catch ( const EFPPCycleInRIA& cir ) \ { std::cerr << "WARNING: KB is incorrect: " \ << cir.what() << ". Query is NOT processed\n"; \ exit(0); } \ } while (0) void testSat ( const std::string& names, ReasoningKernel& Kernel ) { std::stringstream s(names); TsScanner sc(&s); ReasoningKernel::TConceptExpr* sat; while ( (sat = getNextName(sc,Kernel.getExpressionManager())) != NULL ) { bool result = false; if ( dynamic_cast(sat) != NULL ) result = Kernel.isKBConsistent(); else TryReasoning ( result = Kernel.isSatisfiable(sat) ); std::cout << "The '" << getConceptName(sat) << "' concept is "; if ( !result ) std::cout << "un"; std::cout << "satisfiable w.r.t. TBox\n"; } } void testSub ( const std::string& names1, const std::string& names2, ReasoningKernel& Kernel ) { std::stringstream s1(names1), s2(names2); TsScanner sc1(&s1), sc2(&s2); ReasoningKernel::TConceptExpr *sub, *sup; TExpressionManager* pEM = Kernel.getExpressionManager(); while ( (sub = getNextName(sc1,pEM)) != NULL ) { sc2.ReSet(); while ( (sup = getNextName(sc2,pEM)) != NULL ) { bool result = false; TryReasoning ( result = Kernel.isSubsumedBy ( sub, sup ) ); std::cout << "The '" << getConceptName(sub) << " [= " << getConceptName(sup) << "' subsumption does"; if ( !result ) std::cout << " NOT"; std::cout << " holds w.r.t. TBox\n"; } } } //********************** Main function ************************************ int main ( int argc, char *argv[] ) { try{ totalTimer. Start (); Kernel.setTopBottomRoleNames ( "*UROLE*", "*EROLE*", "*UDROLE*", "*EDROLE*" ); Kernel.setUseUndefinedNames(false); // parse options if ( argc > 3 || argc < 2 ) Usage (); // test if we asked for default options if ( !strcmp ( argv[1], "-get-default-options" ) ) { // print Kernel's option set Kernel.getOptions()->printConfig ( std::cout ); exit (0); } // loading config file... if ( Config. Load ( argv [1] ) ) error ( "Cannot load Config file" ); else { argv++; argc--; } // fills option values by Config if ( Kernel.getOptions()->initByConfigure ( Config, "Tuning" ) ) error ( "Cannot fill options value by config file" ); // getting TBox file name const char* tBoxName = NULL; if ( Config. checkValue ( "Query", "TBox" ) ) error ( "Config: no TBox file defined" ); else tBoxName = Config. getString (); // Open input file for TBox and so on... std::ifstream iTBox ( tBoxName ); if ( iTBox.fail () ) error ( "Cannot open input TBox file" ); // output file... Out.open ( argc == 3 ? argv [2] : "dl.res" ); if ( Out.fail () ) error ( "Cannot open output file" ); #ifdef _USE_LOGGING // initialize LeveLogger only if not AD if ( !Kernel.getOptions()->getBool("checkAD") ) if ( LLM.initLogger(Config) ) error ( "LeveLogger: couldn't open logging file" ); #endif // init timeout option unsigned long testTimeout = Kernel.getOptions()->getInt("testTimeout"); Kernel.setOperationTimeout(testTimeout); if ( LLM.isWritable(llAlways) ) LL << "Init testTimeout = " << testTimeout << "\n"; // Load the ontology DLLispParser TBoxParser ( &iTBox, &Kernel ); Kernel.setVerboseOutput(true); TProgressMonitor* pMon = new ConsoleProgressMonitor; Kernel.setProgressMonitor(pMon); // parsing input TBox std::cerr << "Loading KB..."; wTimer.Start (); TBoxParser.Parse (); wTimer.Stop (); std::cerr << " done in " << wTimer << " seconds"; Out << "loading time " << wTimer << " seconds\n"; bool useSem = false; if ( argc > 1 && argv[1][0] == 'n' ) useSem = true; if ( Kernel.getOptions()->getBool("checkAD") ) // check atomic decomposition and exit { CreateAD(&Kernel.getOntology(), useSem); return 0; } if ( Kernel.getOptions()->getBool("useELReasoner") ) // run ELF reasoner and exit { ELFAxiomChecker ac; TOntology& Ontology = Kernel.getOntology(); ac.visitOntology(Ontology); if ( ac ) { std::cerr << "Normalizing EL ontology... "; ELFNormalizer normalizer(Kernel.getExpressionManager()); normalizer.visitOntology(Ontology); std::cerr << "done\nLoading EL ontology... "; ELFReasoner reasoner(Ontology); std::cerr << "done\nClassifying EL ontology... "; reasoner.classify(); std::cerr << "done\n"; } else std::cerr << "Not an EL ontology. Nothing to do\n"; return 0; } TsProcTimer pt; pt.Start(); // parsing query targets fillSatSubQuery(); TryReasoning(Kernel.preprocessKB()); // do preprocessing if ( !Kernel.isKBConsistent() ) std::cerr << "WARNING: KB is inconsistent. Query is NOT processed\n"; else // perform reasoning { if ( Query[0].empty() ) { if ( Query[1].empty() ) TryReasoning(Kernel.realiseKB()); else error ( "Query: Incorrect options" ); } else { if ( Query[1].empty() ) // sat testSat ( Query[0], Kernel ); else testSub ( Query[0], Query[1], Kernel ); } } pt.Stop(); // save final TBox Kernel.writeReasoningResult ( Out, pt ); // finish totalTimer.Stop (); OutTime (std::cout); OutTime (Out); delete pMon; } catch ( const EFaCTPlusPlus& e ) { std::cerr << "\n" << e.what() << "\n"; exit(1); } return 0; } FaCTpp-src-v1.6.2~dfsg/src/.gitignore0000644000000000000000000000004512112642425016125 0ustar rootroot*/.deps */obj *.a *.so FaCT++/FaCT++ FaCTpp-src-v1.6.2~dfsg/src/Makefile0000644000000000000000000000051312112642425015575 0ustar rootroot# # Makefile for FaCT++ project # # -- DO NOT CHANGE THE REST OF FILE -- SUBDIRS = Kernel FaCT++ FaCT++.JNI include Makefile.include # Additional targets to build parts of the FaCT++ .PHONY: kernel kernel: make -C Kernel .PHONY: fpp_lisp fpp_lisp: kernel make -C FaCT++ .PHONY: fpp_jni fpp_jni: kernel make -C FaCT++.JNI FaCTpp-src-v1.6.2~dfsg/src/FaCT++.KE/0000755000000000000000000000000012112642473015342 5ustar rootrootFaCTpp-src-v1.6.2~dfsg/src/FaCT++.KE/build.xml0000644000000000000000000000317212112642405017161 0ustar rootroot FaCTpp-src-v1.6.2~dfsg/src/FaCT++.KE/src/0000755000000000000000000000000012112642473016131 5ustar rootrootFaCTpp-src-v1.6.2~dfsg/src/FaCT++.KE/src/uk/0000755000000000000000000000000012112642473016550 5ustar rootrootFaCTpp-src-v1.6.2~dfsg/src/FaCT++.KE/src/uk/ac/0000755000000000000000000000000012112642473017133 5ustar rootrootFaCTpp-src-v1.6.2~dfsg/src/FaCT++.KE/src/uk/ac/manchester/0000755000000000000000000000000012112642473021264 5ustar rootrootFaCTpp-src-v1.6.2~dfsg/src/FaCT++.KE/src/uk/ac/manchester/cs/0000755000000000000000000000000012112642473021671 5ustar rootrootFaCTpp-src-v1.6.2~dfsg/src/FaCT++.KE/src/uk/ac/manchester/cs/factplusplus/0000755000000000000000000000000012112642473024416 5ustar rootrootFaCTpp-src-v1.6.2~dfsg/src/FaCT++.KE/src/uk/ac/manchester/cs/factplusplus/owlapiv3/0000755000000000000000000000000012112642473026162 5ustar rootroot././@LongLink0000000000000000000000000000017700000000000011572 Lustar rootrootFaCTpp-src-v1.6.2~dfsg/src/FaCT++.KE/src/uk/ac/manchester/cs/factplusplus/owlapiv3/OWLKnowledgeExplorationReasonerWrapper.javaFaCTpp-src-v1.6.2~dfsg/src/FaCT++.KE/src/uk/ac/manchester/cs/factplusplus/owlapiv3/OWLKnowledgeExplo0000644000000000000000000003373412112642405031423 0ustar rootroot/* * Copyright (C) 2009-2010, University of Manchester * * Modifications to the initial code base are copyright of their * respective authors, or their employers as appropriate. Authorship * of the modifications may be determined from the ChangeLog placed at * the end of this file. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package uk.ac.manchester.cs.factplusplus.owlapiv3; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Set; import org.semanticweb.owlapi.model.AxiomType; import org.semanticweb.owlapi.model.OWLAxiom; import org.semanticweb.owlapi.model.OWLClass; import org.semanticweb.owlapi.model.OWLClassExpression; import org.semanticweb.owlapi.model.OWLDataProperty; import org.semanticweb.owlapi.model.OWLDataPropertyExpression; import org.semanticweb.owlapi.model.OWLDataRange; import org.semanticweb.owlapi.model.OWLException; import org.semanticweb.owlapi.model.OWLLiteral; import org.semanticweb.owlapi.model.OWLNamedIndividual; import org.semanticweb.owlapi.model.OWLObjectProperty; import org.semanticweb.owlapi.model.OWLObjectPropertyExpression; import org.semanticweb.owlapi.model.OWLOntology; import org.semanticweb.owlapi.model.OWLOntologyChange; import org.semanticweb.owlapi.reasoner.AxiomNotInProfileException; import org.semanticweb.owlapi.reasoner.BufferingMode; import org.semanticweb.owlapi.reasoner.ClassExpressionNotInProfileException; import org.semanticweb.owlapi.reasoner.FreshEntitiesException; import org.semanticweb.owlapi.reasoner.FreshEntityPolicy; import org.semanticweb.owlapi.reasoner.InconsistentOntologyException; import org.semanticweb.owlapi.reasoner.IndividualNodeSetPolicy; import org.semanticweb.owlapi.reasoner.InferenceType; import org.semanticweb.owlapi.reasoner.Node; import org.semanticweb.owlapi.reasoner.NodeSet; import org.semanticweb.owlapi.reasoner.OWLReasonerConfiguration; import org.semanticweb.owlapi.reasoner.ReasonerInterruptedException; import org.semanticweb.owlapi.reasoner.TimeOutException; import org.semanticweb.owlapi.reasoner.UnsupportedEntailmentTypeException; import org.semanticweb.owlapi.reasoner.knowledgeexploration.OWLKnowledgeExplorerReasoner; import org.semanticweb.owlapi.util.Version; import uk.ac.manchester.cs.factplusplus.NodePointer; /**wrapper class for the new interface in the OWL API; it decouples the rest of the reasoner from relying on an OWL API > 3.2.4*/ public class OWLKnowledgeExplorationReasonerWrapper implements OWLKnowledgeExplorerReasoner { private class RootNodeImpl implements RootNode{ private final NodePointer pointer; public RootNodeImpl(NodePointer p) { this.pointer=p; } public T getNode() { return (T)pointer; } @Override public int hashCode() { return pointer.hashCode(); } @Override public boolean equals(Object arg0) { if(arg0==null) { return false; }if(this==arg0) { return true; } if(arg0 instanceof RootNode) { return this.pointer.equals(((RootNode) arg0).getNode()); } return false; } } private final FaCTPlusPlusReasoner r; public OWLKnowledgeExplorationReasonerWrapper(FaCTPlusPlusReasoner r) { this.r = r; } public void ontologiesChanged(List changes) throws OWLException { this.r.ontologiesChanged(changes); } public OWLReasonerConfiguration getReasonerConfiguration() { return this.r.getReasonerConfiguration(); } public BufferingMode getBufferingMode() { return this.r.getBufferingMode(); } public long getTimeOut() { return this.r.getTimeOut(); } public OWLOntology getRootOntology() { return this.r.getRootOntology(); } public List getPendingChanges() { return this.r.getPendingChanges(); } public Set getPendingAxiomAdditions() { return this.r.getPendingAxiomAdditions(); } public Set getPendingAxiomRemovals() { return this.r.getPendingAxiomRemovals(); } public FreshEntityPolicy getFreshEntityPolicy() { return this.r.getFreshEntityPolicy(); } public IndividualNodeSetPolicy getIndividualNodeSetPolicy() { return this.r.getIndividualNodeSetPolicy(); } public String getReasonerName() { return this.r.getReasonerName(); } public Version getReasonerVersion() { return this.r.getReasonerVersion(); } public void interrupt() { this.r.interrupt(); } public void precomputeInferences(InferenceType... inferenceTypes) throws ReasonerInterruptedException, TimeOutException, InconsistentOntologyException { this.r.precomputeInferences(inferenceTypes); } public boolean isPrecomputed(InferenceType inferenceType) { return this.r.isPrecomputed(inferenceType); } public Set getPrecomputableInferenceTypes() { return this.r.getPrecomputableInferenceTypes(); } public boolean isConsistent() throws ReasonerInterruptedException, TimeOutException { return this.r.isConsistent(); } public boolean isSatisfiable(OWLClassExpression classExpression) throws ReasonerInterruptedException, TimeOutException, ClassExpressionNotInProfileException, FreshEntitiesException, InconsistentOntologyException { return this.r.isSatisfiable(classExpression); } public Node getUnsatisfiableClasses() throws ReasonerInterruptedException, TimeOutException, InconsistentOntologyException { return this.r.getUnsatisfiableClasses(); } public boolean isEntailed(OWLAxiom axiom) throws ReasonerInterruptedException, UnsupportedEntailmentTypeException, TimeOutException, AxiomNotInProfileException, FreshEntitiesException, InconsistentOntologyException { return this.r.isEntailed(axiom); } public boolean isEntailed(Set axioms) throws ReasonerInterruptedException, UnsupportedEntailmentTypeException, TimeOutException, AxiomNotInProfileException, FreshEntitiesException, InconsistentOntologyException { return this.r.isEntailed(axioms); } public boolean isEntailmentCheckingSupported(AxiomType axiomType) { return this.r.isEntailmentCheckingSupported(axiomType); } public Set getTrace(OWLAxiom axiom) { return this.r.getTrace(axiom); } public Node getTopClassNode() { return this.r.getTopClassNode(); } public Node getBottomClassNode() { return this.r.getBottomClassNode(); } public NodeSet getSubClasses(OWLClassExpression ce, boolean direct) throws ReasonerInterruptedException, TimeOutException, FreshEntitiesException, InconsistentOntologyException { return this.r.getSubClasses(ce, direct); } public NodeSet getSuperClasses(OWLClassExpression ce, boolean direct) throws InconsistentOntologyException, ClassExpressionNotInProfileException, ReasonerInterruptedException, TimeOutException { return this.r.getSuperClasses(ce, direct); } public Node getEquivalentClasses(OWLClassExpression ce) throws InconsistentOntologyException, ClassExpressionNotInProfileException, ReasonerInterruptedException, TimeOutException { return this.r.getEquivalentClasses(ce); } public Node getTopObjectPropertyNode() { return this.r.getTopObjectPropertyNode(); } public Node getBottomObjectPropertyNode() { return this.r.getBottomObjectPropertyNode(); } public NodeSet getSubObjectProperties( OWLObjectPropertyExpression pe, boolean direct) throws InconsistentOntologyException, ReasonerInterruptedException, TimeOutException { return this.r.getSubObjectProperties(pe, direct); } public NodeSet getSuperObjectProperties( OWLObjectPropertyExpression pe, boolean direct) throws InconsistentOntologyException, ReasonerInterruptedException, TimeOutException { return this.r.getSuperObjectProperties(pe, direct); } public Node getEquivalentObjectProperties( OWLObjectPropertyExpression pe) throws InconsistentOntologyException, ReasonerInterruptedException, TimeOutException { return this.r.getEquivalentObjectProperties(pe); } public NodeSet getDisjointObjectProperties( OWLObjectPropertyExpression pe) throws InconsistentOntologyException, ReasonerInterruptedException, TimeOutException { return this.r.getDisjointObjectProperties(pe); } public Node getInverseObjectProperties( OWLObjectPropertyExpression pe) throws InconsistentOntologyException, ReasonerInterruptedException, TimeOutException { return this.r.getInverseObjectProperties(pe); } public NodeSet getObjectPropertyDomains(OWLObjectPropertyExpression pe, boolean direct) throws InconsistentOntologyException, ReasonerInterruptedException, TimeOutException { return this.r.getObjectPropertyDomains(pe, direct); } public NodeSet getObjectPropertyRanges(OWLObjectPropertyExpression pe, boolean direct) throws InconsistentOntologyException, ReasonerInterruptedException, TimeOutException { return this.r.getObjectPropertyRanges(pe, direct); } public Node getTopDataPropertyNode() { return this.r.getTopDataPropertyNode(); } public Node getBottomDataPropertyNode() { return this.r.getBottomDataPropertyNode(); } public NodeSet getSubDataProperties(OWLDataProperty pe, boolean direct) throws InconsistentOntologyException, ReasonerInterruptedException, TimeOutException { return this.r.getSubDataProperties(pe, direct); } public NodeSet getSuperDataProperties(OWLDataProperty pe, boolean direct) throws InconsistentOntologyException, ReasonerInterruptedException, TimeOutException { return this.r.getSuperDataProperties(pe, direct); } public Node getEquivalentDataProperties(OWLDataProperty pe) throws InconsistentOntologyException, ReasonerInterruptedException, TimeOutException { return this.r.getEquivalentDataProperties(pe); } public NodeSet getTypes(OWLNamedIndividual ind, boolean direct) throws InconsistentOntologyException, ReasonerInterruptedException, TimeOutException { return this.r.getTypes(ind, direct); } public NodeSet getInstances(OWLClassExpression ce, boolean direct) throws InconsistentOntologyException, ClassExpressionNotInProfileException, ReasonerInterruptedException, TimeOutException { return this.r.getInstances(ce, direct); } public NodeSet getObjectPropertyValues(OWLNamedIndividual ind, OWLObjectPropertyExpression pe) throws InconsistentOntologyException, ReasonerInterruptedException, TimeOutException { return this.r.getObjectPropertyValues(ind, pe); } public Node getSameIndividuals(OWLNamedIndividual ind) throws InconsistentOntologyException, ReasonerInterruptedException, TimeOutException { return this.r.getSameIndividuals(ind); } public void dispose() { this.r.dispose(); } public void flush() { this.r.flush(); } public NodeSet getDisjointClasses(OWLClassExpression ce) { return this.r.getDisjointClasses(ce); } public NodeSet getDisjointDataProperties(OWLDataPropertyExpression pe) throws InconsistentOntologyException, ReasonerInterruptedException, TimeOutException { return this.r.getDisjointDataProperties(pe); } public NodeSet getDataPropertyDomains(OWLDataProperty pe, boolean direct) throws InconsistentOntologyException, ReasonerInterruptedException, TimeOutException { return this.r.getDataPropertyDomains(pe, direct); } public Set getDataPropertyValues(OWLNamedIndividual ind, OWLDataProperty pe) throws InconsistentOntologyException, ReasonerInterruptedException, TimeOutException { return this.r.getDataPropertyValues(ind, pe); } public NodeSet getDifferentIndividuals(OWLNamedIndividual ind) throws InconsistentOntologyException, ReasonerInterruptedException, TimeOutException { return this.r.getDifferentIndividuals(ind); } public RootNode getRoot(OWLClassExpression expression) { return new RootNodeImpl( this.r.getRoot(expression)); } public Node getObjectNeighbours( RootNode object, boolean deterministicOnly) { return this.r.getObjectNeighbours((NodePointer)object.getNode(), deterministicOnly); } public Node getDataNeighbours(RootNode object, boolean deterministicOnly) { return this.r.getDataNeighbours((NodePointer)object.getNode(), deterministicOnly); } public Collection getObjectNeighbours(RootNode object, OWLObjectProperty property) { Collection toReturn=new ArrayList(); for(NodePointer p:this.r.getObjectNeighbours((NodePointer)object.getNode(), property)) { toReturn.add(new RootNodeImpl(p)); } return toReturn; } public Collection getDataNeighbours(RootNode object, OWLDataProperty property) { Collection toReturn=new ArrayList(); for(NodePointer p:this.r.getDataNeighbours((NodePointer)object.getNode(), property)) { toReturn.add(new RootNodeImpl(p)); } return toReturn; } public Node getObjectLabel(RootNode object, boolean deterministicOnly) { return this.r.getObjectLabel((NodePointer)object.getNode(), deterministicOnly); } public Node getDataLabel(RootNode object, boolean deterministicOnly) { return this.r.getDataLabel((NodePointer)object.getNode(), deterministicOnly); } } FaCTpp-src-v1.6.2~dfsg/src/FaCT++.C/0000755000000000000000000000000012112642473015225 5ustar rootrootFaCTpp-src-v1.6.2~dfsg/src/FaCT++.C/fact.cpp0000644000000000000000000006615012112642405016651 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2011-2012 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "fact.h" #include "Kernel.h" #include "Actor.h" // type declarations #define DECLARE_STRUCT(name,type) \ struct name ## _st { type* p; name ## _st(type* q) : p(q) {} } // FaCT++ kernel DECLARE_STRUCT(fact_reasoning_kernel,ReasoningKernel); // progress monitor DECLARE_STRUCT(fact_progress_monitor,TProgressMonitor); // axiom DECLARE_STRUCT(fact_axiom,TDLAxiom); // expression DECLARE_STRUCT(fact_expression,ReasoningKernel::TExpr); // concept expression DECLARE_STRUCT(fact_concept_expression,ReasoningKernel::TConceptExpr); // data- or object-role expression DECLARE_STRUCT(fact_role_expression,ReasoningKernel::TRoleExpr); // object role expression DECLARE_STRUCT(fact_o_role_expression,ReasoningKernel::TORoleExpr); // complex object role expression DECLARE_STRUCT(fact_o_role_complex_expression,ReasoningKernel::TORoleComplexExpr); // data role expression DECLARE_STRUCT(fact_d_role_expression,ReasoningKernel::TDRoleExpr); // individual expression DECLARE_STRUCT(fact_individual_expression,ReasoningKernel::TIndividualExpr); // general data expression DECLARE_STRUCT(fact_data_expression,ReasoningKernel::TDataExpr); // data type expression DECLARE_STRUCT(fact_data_type_expression,ReasoningKernel::TDataTypeExpr); // data value expression DECLARE_STRUCT(fact_data_value_expression,ReasoningKernel::TDataValueExpr); // facet expression DECLARE_STRUCT(fact_facet_expression,ReasoningKernel::TFacetExpr); // actor to traverse taxonomy DECLARE_STRUCT(fact_actor,Actor); const char *fact_get_version () { return ReasoningKernel::getVersion(); } fact_reasoning_kernel *fact_reasoning_kernel_new () { fact_reasoning_kernel *ret = new fact_reasoning_kernel_st(new ReasoningKernel()); /* need this to work properly with top/bot roles */ ret->p->setTopBottomRoleNames("*UROLE*","*EROLE*","*UDROLE*","*EDROLE*"); return ret; } void fact_reasoning_kernel_free (fact_reasoning_kernel *k) { delete k->p; delete k; } /* ifOptionSet* getOptions ( ); const ifOptionSet* getOptions ( ); */ int fact_is_kb_preprocessed (fact_reasoning_kernel *k) { return k->p->isKBPreprocessed(); } int fact_is_kb_classified (fact_reasoning_kernel *k) { return k->p->isKBRealised(); } int fact_is_kb_realised (fact_reasoning_kernel *k) { return k->p->isKBRealised(); } void fact_set_progress_monitor (fact_reasoning_kernel *k, fact_progress_monitor *m) { return k->p->setProgressMonitor(m->p); } void fact_set_verbose_output (fact_reasoning_kernel *k, int value) { k->p->setVerboseOutput(value); } void fact_set_top_bottom_role_names (fact_reasoning_kernel *k, const char *top_o_role_name, const char *bot_o_role_name, const char *top_d_role_name, const char *bot_d_role_name) { k->p->setTopBottomRoleNames(top_o_role_name,bot_o_role_name,top_d_role_name,bot_d_role_name); } void fact_set_operation_timeout (fact_reasoning_kernel *k, unsigned long timeout) { k->p->setOperationTimeout(timeout); } int fact_new_kb (fact_reasoning_kernel *k) { return k->p->newKB(); } int fact_release_kb (fact_reasoning_kernel *k) { return k->p->releaseKB(); } int fact_clear_kb (fact_reasoning_kernel *k) { return k->p->clearKB(); } fact_axiom *fact_declare (fact_reasoning_kernel *k, fact_expression *c) { return new fact_axiom_st(k->p->declare(c->p)); } fact_axiom *fact_implies_concepts (fact_reasoning_kernel *k, fact_concept_expression *c, fact_concept_expression *d) { return new fact_axiom_st(k->p->impliesConcepts(c->p,d->p)); } fact_axiom *fact_equal_concepts (fact_reasoning_kernel *k) { return new fact_axiom_st(k->p->equalConcepts()); } fact_axiom *fact_disjoint_concepts (fact_reasoning_kernel *k) { return new fact_axiom_st(k->p->disjointConcepts()); } fact_axiom *fact_disjoint_union (fact_reasoning_kernel *k, fact_concept_expression *C) { return new fact_axiom_st(k->p->disjointUnion(C->p)); } fact_axiom *fact_set_inverse_roles (fact_reasoning_kernel *k, fact_o_role_expression *r, fact_o_role_expression *s) { return new fact_axiom_st(k->p->setInverseRoles(r->p,s->p)); } fact_axiom *fact_implies_o_roles (fact_reasoning_kernel *k, fact_o_role_complex_expression *r, fact_o_role_expression *s) { return new fact_axiom_st(k->p->impliesORoles(r->p,s->p)); } fact_axiom *fact_implies_d_roles (fact_reasoning_kernel *k, fact_d_role_expression *r, fact_d_role_expression *s) { return new fact_axiom_st(k->p->impliesDRoles(r->p,s->p)); } fact_axiom *fact_equal_o_roles (fact_reasoning_kernel *k) { return new fact_axiom_st(k->p->equalORoles()); } fact_axiom *fact_equal_d_roles (fact_reasoning_kernel *k) { return new fact_axiom_st(k->p->equalDRoles()); } fact_axiom *fact_disjoint_o_roles (fact_reasoning_kernel *k) { return new fact_axiom_st(k->p->disjointORoles()); } fact_axiom *fact_disjoint_d_roles (fact_reasoning_kernel *k) { return new fact_axiom_st(k->p->disjointDRoles()); } fact_axiom* fact_set_o_domain (fact_reasoning_kernel *k, fact_o_role_expression *r, fact_concept_expression *c) { return new fact_axiom_st(k->p->setODomain(r->p,c->p)); } fact_axiom *fact_set_d_domain (fact_reasoning_kernel *k, fact_d_role_expression *r, fact_concept_expression *c) { return new fact_axiom_st(k->p->setDDomain(r->p,c->p)); } fact_axiom *fact_set_o_range (fact_reasoning_kernel *k, fact_o_role_expression *r, fact_concept_expression *c) { return new fact_axiom_st(k->p->setORange(r->p,c->p)); } fact_axiom *fact_set_d_range (fact_reasoning_kernel *k, fact_d_role_expression *r, fact_data_expression *e) { return new fact_axiom_st(k->p->setDRange(r->p,e->p)); } fact_axiom *fact_set_transitive (fact_reasoning_kernel *k, fact_o_role_expression *r) { return new fact_axiom_st(k->p->setTransitive(r->p)); } fact_axiom *fact_set_reflexive (fact_reasoning_kernel *k, fact_o_role_expression *r) { return new fact_axiom_st(k->p->setReflexive(r->p)); } fact_axiom *fact_set_irreflexive (fact_reasoning_kernel *k, fact_o_role_expression *r) { return new fact_axiom_st(k->p->setIrreflexive(r->p)); } fact_axiom *fact_set_symmetric (fact_reasoning_kernel *k, fact_o_role_expression *r) { return new fact_axiom_st(k->p->setSymmetric(r->p)); } fact_axiom *fact_set_asymmetric (fact_reasoning_kernel *k, fact_o_role_expression *r) { return new fact_axiom_st(k->p->setAsymmetric(r->p)); } fact_axiom *fact_set_o_functional (fact_reasoning_kernel *k, fact_o_role_expression *r) { return new fact_axiom_st(k->p->setOFunctional(r->p)); } fact_axiom *fact_set_d_functional (fact_reasoning_kernel *k, fact_d_role_expression *r) { return new fact_axiom_st(k->p->setDFunctional(r->p)); } fact_axiom *fact_set_inverse_functional (fact_reasoning_kernel *k, fact_o_role_expression *r) { return new fact_axiom_st(k->p->setInverseFunctional(r->p)); } fact_axiom *fact_instance_of (fact_reasoning_kernel *k, fact_individual_expression *i, fact_concept_expression *c) { return new fact_axiom_st(k->p->instanceOf(i->p,c->p)); } fact_axiom *fact_related_to (fact_reasoning_kernel *k, fact_individual_expression *i, fact_o_role_expression *r, fact_individual_expression *j) { return new fact_axiom_st(k->p->relatedTo(i->p,r->p,j->p)); } fact_axiom *fact_related_to_not (fact_reasoning_kernel *k, fact_individual_expression *i, fact_o_role_expression *r, fact_individual_expression *j) { return new fact_axiom_st(k->p->relatedToNot(i->p,r->p,j->p)); } fact_axiom *fact_value_of (fact_reasoning_kernel *k, fact_individual_expression *i, fact_d_role_expression *a, fact_data_value_expression *v) { return new fact_axiom_st(k->p->valueOf(i->p,a->p,v->p)); } fact_axiom *fact_value_of_not (fact_reasoning_kernel *k, fact_individual_expression *i, fact_d_role_expression *a, fact_data_value_expression *v) { return new fact_axiom_st(k->p->valueOfNot(i->p,a->p,v->p)); } fact_axiom *fact_process_same (fact_reasoning_kernel *k) { return new fact_axiom_st(k->p->processSame()); } fact_axiom *fact_process_different (fact_reasoning_kernel *k) { return new fact_axiom_st(k->p->processDifferent()); } fact_axiom *fact_set_fairness_constraint (fact_reasoning_kernel *k) { return new fact_axiom_st(k->p->setFairnessConstraint()); } void fact_retract (fact_reasoning_kernel *k, fact_axiom *axiom) { k->p->retract(axiom->p); } int fact_is_kb_consistent (fact_reasoning_kernel *k) { return k->p->isKBConsistent(); } void fact_preprocess_kb (fact_reasoning_kernel *k) { k->p->preprocessKB(); } void fact_classify_kb (fact_reasoning_kernel *k) { k->p->classifyKB(); } void fact_realise_kb (fact_reasoning_kernel *k) { k->p->realiseKB(); } int fact_is_o_functional (fact_reasoning_kernel *k, fact_o_role_expression *r) { return k->p->isFunctional(r->p); } int fact_is_d_functional (fact_reasoning_kernel *k, fact_d_role_expression *r) { return k->p->isFunctional(r->p); } int fact_is_inverse_functional (fact_reasoning_kernel *k, fact_o_role_expression *r) { return k->p->isInverseFunctional(r->p); } int fact_is_transitive (fact_reasoning_kernel *k, fact_o_role_expression *r) { return k->p->isTransitive(r->p); } int fact_is_symmetric (fact_reasoning_kernel *k, fact_o_role_expression *r) { return k->p->isSymmetric(r->p); } int fact_is_asymmetric (fact_reasoning_kernel *k, fact_o_role_expression *r) { return k->p->isAsymmetric(r->p); } int fact_is_reflexive (fact_reasoning_kernel *k, fact_o_role_expression *r) { return k->p->isReflexive(r->p); } int fact_is_irreflexive (fact_reasoning_kernel *k, fact_o_role_expression *r) { return k->p->isIrreflexive(r->p); } int fact_is_sub_o_roles (fact_reasoning_kernel *k, fact_o_role_expression *r, fact_o_role_expression *s) { return k->p->isSubRoles(r->p,s->p); } int fact_is_sub_d_roles (fact_reasoning_kernel *k, fact_d_role_expression *r, fact_d_role_expression *s) { return k->p->isSubRoles(r->p,s->p); } int fact_is_disjoint_o_roles (fact_reasoning_kernel *k, fact_o_role_expression *r, fact_o_role_expression *s) { return k->p->isDisjointRoles(r->p,s->p); } int fact_is_disjoint_d_roles (fact_reasoning_kernel *k, fact_d_role_expression *r, fact_d_role_expression *s) { return k->p->isDisjointRoles(r->p,s->p); } int fact_is_disjoint_roles (fact_reasoning_kernel *k) { return k->p->isDisjointRoles(); } int fact_is_sub_chain (fact_reasoning_kernel *k, fact_o_role_expression *r) { return k->p->isSubChain(r->p); } int fact_is_satisfiable (fact_reasoning_kernel *k, fact_concept_expression *c) { return k->p->isSatisfiable(c->p); } int fact_is_subsumed_by (fact_reasoning_kernel *k, fact_concept_expression *c, fact_concept_expression *d) { return k->p->isSubsumedBy(c->p,d->p); } int fact_is_disjoint (fact_reasoning_kernel *k, fact_concept_expression *c, fact_concept_expression *d) { return k->p->isDisjoint(c->p,d->p); } int fact_is_equivalent (fact_reasoning_kernel *k, fact_concept_expression *c, fact_concept_expression *d) { return k->p->isEquivalent(c->p,d->p); } void fact_get_sup_concepts (fact_reasoning_kernel *k, fact_concept_expression *c, int direct, fact_actor **actor) { k->p->getSupConcepts(c->p,direct,*(*actor)->p); } void fact_get_sub_concepts (fact_reasoning_kernel *k, fact_concept_expression *c, int direct, fact_actor **actor) { k->p->getSubConcepts(c->p,direct,*(*actor)->p); } void fact_get_equivalent_concepts (fact_reasoning_kernel *k, fact_concept_expression *c, fact_actor **actor) { k->p->getEquivalentConcepts(c->p,*(*actor)->p); } void fact_get_disjoint_concepts (fact_reasoning_kernel *k, fact_concept_expression *c, fact_actor **actor) { k->p->getDisjointConcepts(c->p,*(*actor)->p); } void fact_get_sup_roles (fact_reasoning_kernel *k, fact_role_expression *r, int direct, fact_actor **actor) { k->p->getSupRoles(r->p,direct,*(*actor)->p); } void fact_get_sub_roles (fact_reasoning_kernel *k, fact_role_expression *r, int direct, fact_actor **actor) { k->p->getSubRoles(r->p,direct,*(*actor)->p); } void fact_get_equivalent_roles (fact_reasoning_kernel *k, fact_role_expression *r, fact_actor **actor) { k->p->getEquivalentRoles(r->p,*(*actor)->p); } void fact_get_o_role_domain (fact_reasoning_kernel *k, fact_o_role_expression *r, int direct, fact_actor **actor) { k->p->getORoleDomain(r->p,direct,*(*actor)->p); } void fact_get_d_role_domain (fact_reasoning_kernel *k, fact_d_role_expression *r, int direct, fact_actor **actor) { k->p->getDRoleDomain(r->p,direct,*(*actor)->p); } void fact_get_role_range (fact_reasoning_kernel *k, fact_o_role_expression *r, int direct, fact_actor **actor) { k->p->getRoleRange(r->p,direct,*(*actor)->p); } void fact_get_direct_instances (fact_reasoning_kernel *k, fact_concept_expression *c, fact_actor **actor) { k->p->getDirectInstances(c->p,*(*actor)->p); } void fact_get_instances (fact_reasoning_kernel *k, fact_concept_expression *c, fact_actor **actor) { k->p->getInstances(c->p,*(*actor)->p); } void fact_get_types (fact_reasoning_kernel *k, fact_individual_expression *i, int direct, fact_actor **actor) { k->p->getTypes(i->p,direct,*(*actor)->p); } void fact_get_same_as (fact_reasoning_kernel *k, fact_individual_expression *i, fact_actor **actor) { k->p->getSameAs(i->p,*(*actor)->p); } int fact_is_same_individuals (fact_reasoning_kernel *k, fact_individual_expression *i, fact_individual_expression *j) { return k->p->isSameIndividuals(i->p,j->p); } int fact_is_instance (fact_reasoning_kernel *k, fact_individual_expression *i, fact_concept_expression *c) { return k->p->isInstance(i->p,c->p); } int fact_is_related (fact_reasoning_kernel *k, fact_individual_expression *i, fact_o_role_expression *r, fact_individual_expression *j) { return k->p->isRelated(i->p,r->p,j->p); } fact_actor* fact_concept_actor_new() { fact_actor* ret = new fact_actor(new Actor()); ret->p->needConcepts(); return ret; } fact_actor* fact_individual_actor_new() { fact_actor* ret = new fact_actor(new Actor()); ret->p->needIndividuals(); return ret; } fact_actor* fact_o_role_actor_new() { fact_actor* ret = new fact_actor(new Actor()); ret->p->needObjectRoles(); return ret; } fact_actor* fact_d_role_actor_new() { fact_actor* ret = new fact_actor(new Actor()); ret->p->needDataRoles(); return ret; } void fact_actor_free ( fact_actor* actor ) { delete actor->p; delete actor; } /// get 1-d NULL-terminated array of synonyms of the 1st entry(necessary for Equivalents, for example) const char** fact_get_synonyms ( fact_actor* actor ) { return actor->p->getSynonyms(); } /// get NULL-terminated 2D array of all required elements of the taxonomy const char*** fact_get_elements_2d ( fact_actor* actor ) { return actor->p->getElements2D(); } /// get NULL-terminated 1D array of all required elements of the taxonomy const char** fact_get_elements_1d ( fact_actor* actor ) { return actor->p->getElements1D(); } /// opens new argument list void fact_new_arg_list ( fact_reasoning_kernel *k ) { k->p->getExpressionManager()->newArgList(); } /// add argument E to the current argument list void fact_add_arg ( fact_reasoning_kernel *k,fact_expression* e ) { k->p->getExpressionManager()->addArg(e->p); } // create expressions methods // concepts /// get TOP concept fact_concept_expression* fact_top ( fact_reasoning_kernel *k ) { return new fact_concept_expression(k->p->getExpressionManager()->Top()); } /// get BOTTOM concept fact_concept_expression* fact_bottom ( fact_reasoning_kernel *k ) { return new fact_concept_expression(k->p->getExpressionManager()->Bottom()); } /// get named concept fact_concept_expression* fact_concept ( fact_reasoning_kernel *k,const char* name ) { return new fact_concept_expression(k->p->getExpressionManager()->Concept(name)); } /// get negation of a concept c fact_concept_expression* fact_not ( fact_reasoning_kernel *k,fact_concept_expression* c ) { return new fact_concept_expression(k->p->getExpressionManager()->Not(c->p)); } /// get an n-ary conjunction expression; take the arguments from the last argument list fact_concept_expression* fact_and ( fact_reasoning_kernel *k ) { return new fact_concept_expression(k->p->getExpressionManager()->And()); } /// get an n-ary disjunction expression; take the arguments from the last argument list fact_concept_expression* fact_or ( fact_reasoning_kernel *k ) { return new fact_concept_expression(k->p->getExpressionManager()->Or()); } /// get an n-ary one-of expression; take the arguments from the last argument list fact_concept_expression* fact_one_of ( fact_reasoning_kernel *k ) { return new fact_concept_expression(k->p->getExpressionManager()->OneOf()); } /// get self-reference restriction of an object role r fact_concept_expression* fact_self_reference ( fact_reasoning_kernel *k,fact_o_role_expression* r ) { return new fact_concept_expression(k->p->getExpressionManager()->SelfReference(r->p)); } /// get value restriction wrt an object role r and an individual i fact_concept_expression* fact_o_value ( fact_reasoning_kernel *k,fact_o_role_expression* r, fact_individual_expression* i ) { return new fact_concept_expression(k->p->getExpressionManager()->Value(r->p,i->p)); } /// get existential restriction wrt an object role r and a concept c fact_concept_expression* fact_o_exists ( fact_reasoning_kernel *k,fact_o_role_expression* r, fact_concept_expression* c ) { return new fact_concept_expression(k->p->getExpressionManager()->Exists(r->p,c->p)); } /// get universal restriction wrt an object role r and a concept c fact_concept_expression* fact_o_forall ( fact_reasoning_kernel *k,fact_o_role_expression* r, fact_concept_expression* c ) { return new fact_concept_expression(k->p->getExpressionManager()->Forall(r->p,c->p)); } /// get min cardinality restriction wrt number _n, an object role r and a concept c fact_concept_expression* fact_o_min_cardinality ( fact_reasoning_kernel *k,unsigned int n, fact_o_role_expression* r, fact_concept_expression* c ) { return new fact_concept_expression(k->p->getExpressionManager()->MinCardinality(n,r->p,c->p)); } /// get max cardinality restriction wrt number _n, an object role r and a concept c fact_concept_expression* fact_o_max_cardinality ( fact_reasoning_kernel *k,unsigned int n, fact_o_role_expression* r, fact_concept_expression* c ) { return new fact_concept_expression(k->p->getExpressionManager()->MaxCardinality(n,r->p,c->p)); } /// get exact cardinality restriction wrt number _n, an object role r and a concept c fact_concept_expression* fact_o_cardinality ( fact_reasoning_kernel *k,unsigned int n, fact_o_role_expression* r, fact_concept_expression* c ) { return new fact_concept_expression(k->p->getExpressionManager()->Cardinality(n,r->p,c->p)); } /// get value restriction wrt a data role r and a data value v fact_concept_expression* fact_d_value ( fact_reasoning_kernel *k,fact_d_role_expression* r, fact_data_value_expression* v ) { return new fact_concept_expression(k->p->getExpressionManager()->Value(r->p,v->p)); } /// get existential restriction wrt a data role r and a data expression e fact_concept_expression* fact_d_exists ( fact_reasoning_kernel *k,fact_d_role_expression* r, fact_data_expression* e ) { return new fact_concept_expression(k->p->getExpressionManager()->Exists(r->p,e->p)); } /// get universal restriction wrt a data role r and a data expression e fact_concept_expression* fact_d_forall ( fact_reasoning_kernel *k,fact_d_role_expression* r, fact_data_expression* e ) { return new fact_concept_expression(k->p->getExpressionManager()->Forall(r->p,e->p)); } /// get min cardinality restriction wrt number _n, a data role r and a data expression e fact_concept_expression* fact_d_min_cardinality ( fact_reasoning_kernel *k,unsigned int n, fact_d_role_expression* r, fact_data_expression* e ) { return new fact_concept_expression(k->p->getExpressionManager()->MinCardinality(n,r->p,e->p)); } /// get max cardinality restriction wrt number _n, a data role r and a data expression e fact_concept_expression* fact_d_max_cardinality ( fact_reasoning_kernel *k,unsigned int n, fact_d_role_expression* r, fact_data_expression* e ) { return new fact_concept_expression(k->p->getExpressionManager()->MaxCardinality(n,r->p,e->p)); } /// get exact cardinality restriction wrt number _n, a data role r and a data expression e fact_concept_expression* fact_d_cardinality ( fact_reasoning_kernel *k,unsigned int n, fact_d_role_expression* r, fact_data_expression* e ) { return new fact_concept_expression(k->p->getExpressionManager()->Cardinality(n,r->p,e->p)); } // individuals /// get named individual fact_individual_expression* fact_individual ( fact_reasoning_kernel *k,const char* name ) { return new fact_individual_expression(k->p->getExpressionManager()->Individual(name)); } // object roles /// get TOP object role fact_o_role_expression* fact_object_role_top ( fact_reasoning_kernel *k ) { return new fact_o_role_expression(k->p->getExpressionManager()->ObjectRoleTop()); } /// get BOTTOM object role fact_o_role_expression* fact_object_role_bottom ( fact_reasoning_kernel *k ) { return new fact_o_role_expression(k->p->getExpressionManager()->ObjectRoleBottom()); } /// get named object role fact_o_role_expression* fact_object_role ( fact_reasoning_kernel *k,const char* name ) { return new fact_o_role_expression(k->p->getExpressionManager()->ObjectRole(name)); } /// get an inverse of a given object role expression r fact_o_role_expression* fact_inverse ( fact_reasoning_kernel *k,fact_o_role_expression* r ) { return new fact_o_role_expression(k->p->getExpressionManager()->Inverse(r->p)); } /// get a role chain corresponding to _r1 o ... o _rn; take the arguments from the last argument list fact_o_role_complex_expression* fact_compose ( fact_reasoning_kernel *k ) { return new fact_o_role_complex_expression(k->p->getExpressionManager()->Compose()); } /// get a expression corresponding to r projected from c fact_o_role_complex_expression* fact_project_from ( fact_reasoning_kernel *k,fact_o_role_expression* r, fact_concept_expression* c ) { return new fact_o_role_complex_expression(k->p->getExpressionManager()->ProjectFrom(r->p,c->p)); } /// get a expression corresponding to r projected into c fact_o_role_complex_expression* fact_project_into ( fact_reasoning_kernel *k,fact_o_role_expression* r, fact_concept_expression* c ) { return new fact_o_role_complex_expression(k->p->getExpressionManager()->ProjectInto(r->p,c->p)); } // data roles /// get TOP data role fact_d_role_expression* fact_data_role_top ( fact_reasoning_kernel *k ) { return new fact_d_role_expression(k->p->getExpressionManager()->DataRoleTop()); } /// get BOTTOM data role fact_d_role_expression* fact_data_role_bottom ( fact_reasoning_kernel *k ) { return new fact_d_role_expression(k->p->getExpressionManager()->DataRoleBottom()); } /// get named data role fact_d_role_expression* fact_data_role ( fact_reasoning_kernel *k,const char* name ) { return new fact_d_role_expression(k->p->getExpressionManager()->DataRole(name)); } // data expressions /// get TOP data element fact_data_expression* fact_data_top ( fact_reasoning_kernel *k ) { return new fact_data_expression(k->p->getExpressionManager()->DataTop()); } /// get BOTTOM data element fact_data_expression* fact_data_bottom ( fact_reasoning_kernel *k ) { return new fact_data_expression(k->p->getExpressionManager()->DataBottom()); } /// get named data type fact_data_type_expression* fact_data_type ( fact_reasoning_kernel *k,const char* name ) { return new fact_data_type_expression(k->p->getExpressionManager()->DataType(name)); } /// get basic string data type fact_data_type_expression* fact_get_str_data_type ( fact_reasoning_kernel *k ) { return new fact_data_type_expression(k->p->getExpressionManager()->getStrDataType()); } /// get basic integer data type fact_data_type_expression* fact_get_int_data_type ( fact_reasoning_kernel *k ) { return new fact_data_type_expression(k->p->getExpressionManager()->getIntDataType()); } /// get basic floating point data type fact_data_type_expression* fact_get_real_data_type ( fact_reasoning_kernel *k ) { return new fact_data_type_expression(k->p->getExpressionManager()->getRealDataType()); } /// get basic boolean data type fact_data_type_expression* fact_get_bool_data_type ( fact_reasoning_kernel *k ) { return new fact_data_type_expression(k->p->getExpressionManager()->getBoolDataType()); } /// get basic date-time data type fact_data_type_expression* fact_get_time_data_type ( fact_reasoning_kernel *k ) { return new fact_data_type_expression(k->p->getExpressionManager()->getTimeDataType()); } /// get basic boolean data type fact_data_type_expression* fact_restricted_type ( fact_reasoning_kernel *k,fact_data_type_expression* type, fact_facet_expression* facet ) { return new fact_data_type_expression(k->p->getExpressionManager()->RestrictedType(type->p,facet->p)); } /// get data value with given VALUE and TYPE; fact_data_value_expression* fact_data_value ( fact_reasoning_kernel *k,const char* value, fact_data_type_expression* type ) { return new fact_data_value_expression(k->p->getExpressionManager()->DataValue(value,type->p)); } /// get negation of a data expression e fact_data_expression* fact_data_not ( fact_reasoning_kernel *k,fact_data_expression* e ) { return new fact_data_expression(k->p->getExpressionManager()->DataNot(e->p)); } /// get an n-ary data conjunction expression; take the arguments from the last argument list fact_data_expression* fact_data_and ( fact_reasoning_kernel *k ) { return new fact_data_expression(k->p->getExpressionManager()->DataAnd()); } /// get an n-ary data disjunction expression; take the arguments from the last argument list fact_data_expression* fact_data_or ( fact_reasoning_kernel *k ) { return new fact_data_expression(k->p->getExpressionManager()->DataOr()); } /// get an n-ary data one-of expression; take the arguments from the last argument list fact_data_expression* fact_data_one_of ( fact_reasoning_kernel *k ) { return new fact_data_expression(k->p->getExpressionManager()->DataOneOf()); } /// get min_inclusive facet with a given _v fact_facet_expression* fact_facet_min_inclusive ( fact_reasoning_kernel *k,fact_data_value_expression* v ) { return new fact_facet_expression(k->p->getExpressionManager()->FacetMinInclusive(v->p)); } /// get min_exclusive facet with a given _v fact_facet_expression* fact_facet_min_exclusive ( fact_reasoning_kernel *k,fact_data_value_expression* v ) { return new fact_facet_expression(k->p->getExpressionManager()->FacetMinExclusive(v->p)); } /// get max_inclusive facet with a given _v fact_facet_expression* fact_facet_max_inclusive ( fact_reasoning_kernel *k,fact_data_value_expression* v ) { return new fact_facet_expression(k->p->getExpressionManager()->FacetMaxInclusive(v->p)); } /// get max_exclusive facet with a given _v fact_facet_expression* fact_facet_max_exclusive ( fact_reasoning_kernel *k,fact_data_value_expression* v ) { return new fact_facet_expression(k->p->getExpressionManager()->FacetMaxExclusive(v->p)); } FaCTpp-src-v1.6.2~dfsg/src/FaCT++.C/fact.h0000644000000000000000000004464612112642405016324 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2011-2012 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef __FACT_H__ #define __FACT_H__ #ifdef __cplusplus extern "C" { #endif /* type declarations */ #define DECLARE_STRUCT(name) typedef struct name ## _st name /* FaCT++ kernel */ DECLARE_STRUCT(fact_reasoning_kernel); /* progress monitor */ DECLARE_STRUCT(fact_progress_monitor); /* axiom */ DECLARE_STRUCT(fact_axiom); /* expression */ DECLARE_STRUCT(fact_expression); /* concept expression */ DECLARE_STRUCT(fact_concept_expression); /* data- or object-role expression */ DECLARE_STRUCT(fact_role_expression); /* object role expression */ DECLARE_STRUCT(fact_o_role_expression); /* complex object role expression */ DECLARE_STRUCT(fact_o_role_complex_expression); /* data role expression */ DECLARE_STRUCT(fact_d_role_expression); /* individual expression */ DECLARE_STRUCT(fact_individual_expression); /* general data expression */ DECLARE_STRUCT(fact_data_expression); /* data type expression */ DECLARE_STRUCT(fact_data_type_expression); /* data value expression */ DECLARE_STRUCT(fact_data_value_expression); /* facet expression */ DECLARE_STRUCT(fact_facet_expression); /* actor to traverse taxonomy */ DECLARE_STRUCT(fact_actor); #undef DECLARE_STRUCT const char *fact_get_version (); fact_reasoning_kernel *fact_reasoning_kernel_new (void); void fact_reasoning_kernel_free (fact_reasoning_kernel *); /* ifOptionSet* getOptions ( ); const ifOptionSet* getOptions ( ); */ int fact_is_kb_preprocessed (fact_reasoning_kernel *); int fact_is_kb_classified (fact_reasoning_kernel *); int fact_is_kb_realised (fact_reasoning_kernel *); void fact_set_progress_monitor (fact_reasoning_kernel *, fact_progress_monitor *); void fact_set_verbose_output (fact_reasoning_kernel *, int value); void fact_set_top_bottom_role_names (fact_reasoning_kernel *, const char *top_b_role_name, const char *bot_b_role_name, const char *top_d_role_name, const char *bot_d_role_name); void fact_set_operation_timeout (fact_reasoning_kernel *, unsigned long timeout); int fact_new_kb (fact_reasoning_kernel *); int fact_release_kb (fact_reasoning_kernel *); int fact_clear_kb (fact_reasoning_kernel *); fact_axiom *fact_declare (fact_reasoning_kernel *, fact_expression *c); fact_axiom *fact_implies_concepts (fact_reasoning_kernel *, fact_concept_expression *c, fact_concept_expression *d); fact_axiom *fact_equal_concepts (fact_reasoning_kernel *); fact_axiom *fact_disjoint_concepts (fact_reasoning_kernel *); fact_axiom *fact_disjoint_union (fact_reasoning_kernel *, fact_concept_expression *c); fact_axiom *fact_set_inverse_roles (fact_reasoning_kernel *, fact_o_role_expression *r, fact_o_role_expression *s); fact_axiom *fact_implies_o_roles (fact_reasoning_kernel *, fact_o_role_complex_expression *r, fact_o_role_expression *s); fact_axiom *fact_implies_d_roles (fact_reasoning_kernel *, fact_d_role_expression *r, fact_d_role_expression *s); fact_axiom *fact_equal_o_roles (fact_reasoning_kernel *); fact_axiom *fact_equal_d_roles (fact_reasoning_kernel *); fact_axiom *fact_disjoint_o_roles (fact_reasoning_kernel *); fact_axiom *fact_disjoint_d_roles (fact_reasoning_kernel *); fact_axiom* fact_set_o_domain (fact_reasoning_kernel *, fact_o_role_expression *r, fact_concept_expression *c); fact_axiom *fact_set_d_domain (fact_reasoning_kernel *, fact_d_role_expression *r, fact_concept_expression *c); fact_axiom *fact_set_o_range (fact_reasoning_kernel *, fact_o_role_expression *r, fact_concept_expression *c); fact_axiom *fact_set_d_range (fact_reasoning_kernel *, fact_d_role_expression *r, fact_data_expression *e); fact_axiom *fact_set_transitive (fact_reasoning_kernel *, fact_o_role_expression *r); fact_axiom *fact_set_reflexive (fact_reasoning_kernel *, fact_o_role_expression *r); fact_axiom *fact_set_irreflexive (fact_reasoning_kernel *, fact_o_role_expression *r); fact_axiom *fact_set_symmetric (fact_reasoning_kernel *, fact_o_role_expression *r); fact_axiom *fact_set_asymmetric (fact_reasoning_kernel *, fact_o_role_expression *r); fact_axiom *fact_set_o_functional (fact_reasoning_kernel *, fact_o_role_expression *r); fact_axiom *fact_set_d_functional (fact_reasoning_kernel *, fact_d_role_expression *r); fact_axiom *fact_set_inverse_functional (fact_reasoning_kernel *, fact_o_role_expression *r); fact_axiom *fact_instance_of (fact_reasoning_kernel *, fact_individual_expression *i, fact_concept_expression *c); fact_axiom *fact_related_to (fact_reasoning_kernel *, fact_individual_expression *i, fact_o_role_expression *r, fact_individual_expression *j); fact_axiom *fact_related_to_not (fact_reasoning_kernel *, fact_individual_expression *i, fact_o_role_expression *r, fact_individual_expression *j); fact_axiom *fact_value_of (fact_reasoning_kernel *, fact_individual_expression *i, fact_d_role_expression *a, fact_data_value_expression *v); fact_axiom *fact_value_of_not (fact_reasoning_kernel *, fact_individual_expression *i, fact_d_role_expression *a, fact_data_value_expression *v); fact_axiom *fact_process_same (fact_reasoning_kernel *); fact_axiom *fact_process_different (fact_reasoning_kernel *); fact_axiom *fact_set_fairness_constraint (fact_reasoning_kernel *); void fact_retract (fact_reasoning_kernel *, fact_axiom *axiom); int fact_is_kb_consistent (fact_reasoning_kernel *); void fact_preprocess_kb (fact_reasoning_kernel *); void fact_classify_kb (fact_reasoning_kernel *); void fact_realise_kb (fact_reasoning_kernel *); int fact_is_o_functional (fact_reasoning_kernel *, fact_o_role_expression *r); int fact_is_d_functional (fact_reasoning_kernel *, fact_d_role_expression *r); int fact_is_inverse_functional (fact_reasoning_kernel *, fact_o_role_expression *r); int fact_is_transitive (fact_reasoning_kernel *, fact_o_role_expression *r); int fact_is_symmetric (fact_reasoning_kernel *, fact_o_role_expression *r); int fact_is_asymmetric (fact_reasoning_kernel *, fact_o_role_expression *r); int fact_is_reflexive (fact_reasoning_kernel *, fact_o_role_expression *r); int fact_is_irreflexive (fact_reasoning_kernel *, fact_o_role_expression *r); int fact_is_sub_o_roles (fact_reasoning_kernel *, fact_o_role_expression *r, fact_o_role_expression *s); int fact_is_sub_d_roles (fact_reasoning_kernel *, fact_d_role_expression *r, fact_d_role_expression *s); int fact_is_disjoint_o_roles (fact_reasoning_kernel *, fact_o_role_expression *r, fact_o_role_expression *s); int fact_is_disjoint_d_roles (fact_reasoning_kernel *, fact_d_role_expression *r, fact_d_role_expression *s); int fact_is_disjoint_roles (fact_reasoning_kernel *); int fact_is_sub_chain (fact_reasoning_kernel *, fact_o_role_expression *r); int fact_is_satisfiable (fact_reasoning_kernel *, fact_concept_expression *c); int fact_is_subsumed_by (fact_reasoning_kernel *, fact_concept_expression *c, fact_concept_expression *d); int fact_is_disjoint (fact_reasoning_kernel *, fact_concept_expression *c, fact_concept_expression *d); int fact_is_equivalent (fact_reasoning_kernel *, fact_concept_expression *c, fact_concept_expression *d); void fact_get_sup_concepts (fact_reasoning_kernel *, fact_concept_expression *c, int direct, fact_actor **actor); void fact_get_sub_concepts (fact_reasoning_kernel *, fact_concept_expression *c, int direct, fact_actor **actor); void fact_get_equivalent_concepts (fact_reasoning_kernel *, fact_concept_expression *c, fact_actor **actor); void fact_get_disjoint_concepts (fact_reasoning_kernel *, fact_concept_expression *c, fact_actor **actor); void fact_get_sup_roles (fact_reasoning_kernel *, fact_role_expression *r, int direct, fact_actor **actor); void fact_get_sub_roles (fact_reasoning_kernel *, fact_role_expression *r, int direct, fact_actor **actor); void fact_get_equivalent_roles (fact_reasoning_kernel *, fact_role_expression *r, fact_actor **actor); void fact_get_o_role_domain (fact_reasoning_kernel *, fact_o_role_expression *r, int direct, fact_actor **actor); void fact_get_d_role_domain (fact_reasoning_kernel *, fact_d_role_expression *r, int direct, fact_actor **actor); void fact_get_role_range (fact_reasoning_kernel *, fact_o_role_expression *r, int direct, fact_actor **actor); void fact_get_direct_instances (fact_reasoning_kernel *, fact_concept_expression *c, fact_actor **actor); void fact_get_instances (fact_reasoning_kernel *, fact_concept_expression *c, fact_actor **actor); void fact_get_types (fact_reasoning_kernel *, fact_individual_expression *i, int direct, fact_actor **actor); void fact_get_same_as (fact_reasoning_kernel *, fact_individual_expression *i, fact_actor **actor); int fact_is_same_individuals (fact_reasoning_kernel *, fact_individual_expression *i, fact_individual_expression *j); int fact_is_instance (fact_reasoning_kernel *, fact_individual_expression *i, fact_concept_expression *c); /* void fact_get_related_roles (fact_reasoning_kernel *, fact_individual_expression *i, int data, int needI, fact_names_vector **result); void fact_get_role_fillers (fact_reasoning_kernel *, fact_individual_expression *i, fact_o_role_expression *r, fact_individual_set **result); */ int fact_is_related (fact_reasoning_kernel *, fact_individual_expression *i, fact_o_role_expression *r, fact_individual_expression *j); fact_actor* fact_concept_actor_new(); fact_actor* fact_individual_actor_new(); fact_actor* fact_o_role_actor_new(); fact_actor* fact_d_role_actor_new(); void fact_actor_free(fact_actor*); /* get 1-d NULL-terminated array of synonyms of the 1st entry(necessary for Equivalents, for example) */ const char** fact_get_synonyms ( fact_actor* ); /* get NULL-terminated 2D array of all required elements of the taxonomy */ const char*** fact_get_elements_2d ( fact_actor* ); /* get NULL-terminated 1D array of all required elements of the taxonomy */ const char** fact_get_elements_1d ( fact_actor* ); /* opens new argument list */ void fact_new_arg_list ( fact_reasoning_kernel *k ); /* add argument _a_rG to the current argument list */ void fact_add_arg ( fact_reasoning_kernel *k,fact_expression* e ); /* create expressions methods */ /* concepts */ /* get _t_o_p concept */ fact_concept_expression* fact_top ( fact_reasoning_kernel *k ); /* get _b_o_t_t_o_m concept */ fact_concept_expression* fact_bottom ( fact_reasoning_kernel *k ); /* get named concept */ fact_concept_expression* fact_concept ( fact_reasoning_kernel *k,const char* name ); /* get negation of a concept c */ fact_concept_expression* fact_not ( fact_reasoning_kernel *k,fact_concept_expression* c ); /* get an n-ary conjunction expression; take the arguments from the last argument list */ fact_concept_expression* fact_and ( fact_reasoning_kernel *k ); /* get an n-ary disjunction expression; take the arguments from the last argument list */ fact_concept_expression* fact_or ( fact_reasoning_kernel *k ); /* get an n-ary one-of expression; take the arguments from the last argument list */ fact_concept_expression* fact_one_of ( fact_reasoning_kernel *k ); /* get self-reference restriction of an object role r */ fact_concept_expression* fact_self_reference ( fact_reasoning_kernel *k,fact_o_role_expression* r ); /* get value restriction wrt an object role r and an individual i */ fact_concept_expression* fact_o_value ( fact_reasoning_kernel *k,fact_o_role_expression* r, fact_individual_expression* i ); /* get existential restriction wrt an object role r and a concept c */ fact_concept_expression* fact_o_exists ( fact_reasoning_kernel *k,fact_o_role_expression* r, fact_concept_expression* c ); /* get universal restriction wrt an object role r and a concept c */ fact_concept_expression* fact_o_forall ( fact_reasoning_kernel *k,fact_o_role_expression* r, fact_concept_expression* c ); /* get min cardinality restriction wrt number _n, an object role r and a concept c */ fact_concept_expression* fact_o_min_cardinality ( fact_reasoning_kernel *k,unsigned int n, fact_o_role_expression* r, fact_concept_expression* c ); /* get max cardinality restriction wrt number _n, an object role r and a concept c */ fact_concept_expression* fact_o_max_cardinality ( fact_reasoning_kernel *k,unsigned int n, fact_o_role_expression* r, fact_concept_expression* c ); /* get exact cardinality restriction wrt number _n, an object role r and a concept c */ fact_concept_expression* fact_o_cardinality ( fact_reasoning_kernel *k,unsigned int n, fact_o_role_expression* r, fact_concept_expression* c ); /* get value restriction wrt a data role r and a data value v */ fact_concept_expression* fact_d_value ( fact_reasoning_kernel *k,fact_d_role_expression* r, fact_data_value_expression* v ); /* get existential restriction wrt a data role r and a data expression e */ fact_concept_expression* fact_d_exists ( fact_reasoning_kernel *k,fact_d_role_expression* r, fact_data_expression* e ); /* get universal restriction wrt a data role r and a data expression e */ fact_concept_expression* fact_d_forall ( fact_reasoning_kernel *k,fact_d_role_expression* r, fact_data_expression* e ); /* get min cardinality restriction wrt number _n, a data role r and a data expression e */ fact_concept_expression* fact_d_min_cardinality ( fact_reasoning_kernel *k,unsigned int n, fact_d_role_expression* r, fact_data_expression* e ); /* get max cardinality restriction wrt number _n, a data role r and a data expression e */ fact_concept_expression* fact_d_max_cardinality ( fact_reasoning_kernel *k,unsigned int n, fact_d_role_expression* r, fact_data_expression* e ); /* get exact cardinality restriction wrt number _n, a data role r and a data expression e */ fact_concept_expression* fact_d_cardinality ( fact_reasoning_kernel *k,unsigned int n, fact_d_role_expression* r, fact_data_expression* e ); /* individuals */ /* get named individual */ fact_individual_expression* fact_individual ( fact_reasoning_kernel *k,const char* name ); /* object roles */ /* get _t_o_p object role */ fact_o_role_expression* fact_object_role_top ( fact_reasoning_kernel *k ); /* get _b_o_t_t_o_m object role */ fact_o_role_expression* fact_object_role_bottom ( fact_reasoning_kernel *k ); /* get named object role */ fact_o_role_expression* fact_object_role ( fact_reasoning_kernel *k,const char* name ); /* get an inverse of a given object role expression r */ fact_o_role_expression* fact_inverse ( fact_reasoning_kernel *k,fact_o_role_expression* r ); /* get a role chain corresponding to _r1 o ... o _rn; take the arguments from the last argument list */ fact_o_role_complex_expression* fact_compose ( fact_reasoning_kernel *k ); /* get a expression corresponding to r projected from c */ fact_o_role_complex_expression* fact_project_from ( fact_reasoning_kernel *k,fact_o_role_expression* r, fact_concept_expression* c ); /* get a expression corresponding to r projected into c */ fact_o_role_complex_expression* fact_project_into ( fact_reasoning_kernel *k,fact_o_role_expression* r, fact_concept_expression* c ); /* data roles */ /* get _t_o_p data role */ fact_d_role_expression* fact_data_role_top ( fact_reasoning_kernel *k ); /* get _b_o_t_t_o_m data role */ fact_d_role_expression* fact_data_role_bottom ( fact_reasoning_kernel *k ); /* get named data role */ fact_d_role_expression* fact_data_role ( fact_reasoning_kernel *k,const char* name ); /* data expressions */ /* get _t_o_p data element */ fact_data_expression* fact_data_top ( fact_reasoning_kernel *k ); /* get _b_o_t_t_o_m data element */ fact_data_expression* fact_data_bottom ( fact_reasoning_kernel *k ); /* get named data type */ fact_data_type_expression* fact_data_type ( fact_reasoning_kernel *k,const char* name ); /* get basic string data type */ fact_data_type_expression* fact_get_str_data_type ( fact_reasoning_kernel *k ); /* get basic integer data type */ fact_data_type_expression* fact_get_int_data_type ( fact_reasoning_kernel *k ); /* get basic floating point data type */ fact_data_type_expression* fact_get_real_data_type ( fact_reasoning_kernel *k ); /* get basic boolean data type */ fact_data_type_expression* fact_get_bool_data_type ( fact_reasoning_kernel *k ); /* get basic date-time data type */ fact_data_type_expression* fact_get_time_data_type ( fact_reasoning_kernel *k ); /* get basic boolean data type */ fact_data_type_expression* fact_restricted_type ( fact_reasoning_kernel *k,fact_data_type_expression* type, fact_facet_expression* facet ); /* get data value with given _v_a_lU_e and _tY_p_e; */ /* _f_iX_m_e!! now change the type to the basic type of the given one */ /* _that is, value of a type positive_integer will be of a type _integer */ fact_data_value_expression* fact_data_value ( fact_reasoning_kernel *k,const char* value, fact_data_type_expression* type ); /* get negation of a data expression e */ fact_data_expression* fact_data_not ( fact_reasoning_kernel *k,fact_data_expression* e ); /* get an n-ary data conjunction expression; take the arguments from the last argument list */ fact_data_expression* fact_data_and ( fact_reasoning_kernel *k ); /* get an n-ary data disjunction expression; take the arguments from the last argument list */ fact_data_expression* fact_data_or ( fact_reasoning_kernel *k ); /* get an n-ary data one-of expression; take the arguments from the last argument list */ fact_data_expression* fact_data_one_of ( fact_reasoning_kernel *k ); /* get min_inclusive facet with a given _v */ fact_facet_expression* fact_facet_min_inclusive ( fact_reasoning_kernel *k,fact_data_value_expression* v ); /* get min_exclusive facet with a given _v */ fact_facet_expression* fact_facet_min_exclusive ( fact_reasoning_kernel *k,fact_data_value_expression* v ); /* get max_inclusive facet with a given _v */ fact_facet_expression* fact_facet_max_inclusive ( fact_reasoning_kernel *k,fact_data_value_expression* v ); /* get max_exclusive facet with a given _v */ fact_facet_expression* fact_facet_max_exclusive ( fact_reasoning_kernel *k,fact_data_value_expression* v ); #ifdef __cplusplus } #endif #endif FaCTpp-src-v1.6.2~dfsg/src/FaCT++.C/Makefile0000644000000000000000000000033012112642405016654 0ustar rootroot# # Makefile for FaCT++ # # -- DO NOT CHANGE THE REST OF FILE -- #EXECUTABLE=fact LIBRARY = fact LTYPE = shared USE_IL = ../Kernel SOURCES = \ fact.cpp\ # test.cpp include ../Makefile.include FaCTpp-src-v1.6.2~dfsg/src/FaCT++.C/test.c0000644000000000000000000000450612112642405016350 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2011-2012 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include #include "fact.h" void print2Darray ( const char*** names ) { printf("[\n"); int n=0; const char** syns = names[0]; while ( syns != NULL ) { printf("["); int m = 0; const char* name; while ( (name = syns[m++]) != NULL ) printf("%s ", name); printf("]\n"); syns=names[++n]; } printf("]\n"); } int main ( void ) { // create kernel fact_reasoning_kernel* k = fact_reasoning_kernel_new(); // create classes C,D, property R fact_concept_expression* c = fact_concept(k,"C"); fact_concept_expression* d = fact_concept(k,"D"); fact_o_role_expression* r = fact_object_role(k,"R"); // create C [= ER.T, ER.T [= D fact_concept_expression* some = fact_o_exists ( k, r, fact_top(k)); fact_implies_concepts ( k, c, some ); fact_implies_concepts ( k, some, d ); // classify KB is not necessary: it's done automatically depending on a query fact_classify_kb(k); // check whether C [= D if ( fact_is_subsumed_by(k,c,d) ) puts("yes!\n"); else puts("No...\n"); // create a concept actor and use it to get all superclasses of D fact_actor* actor = fact_concept_actor_new(); fact_get_sup_concepts(k,c,0,&actor); print2Darray(fact_get_elements_2d(actor)); fact_actor_free(actor); // get all the properties fact_o_role_expression* o_top = fact_object_role_top(k); actor = fact_o_role_actor_new(); fact_get_sub_roles(k,(fact_role_expression*)o_top,0,&actor); print2Darray(fact_get_elements_2d(actor)); fact_actor_free(actor); // we done so let's free memory fact_reasoning_kernel_free(k); return 0; } FaCTpp-src-v1.6.2~dfsg/src/Kernel/0000755000000000000000000000000012112642474015362 5ustar rootrootFaCTpp-src-v1.6.2~dfsg/src/Kernel/Actor.h0000644000000000000000000000742212112642405016602 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2006-2011 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef ACTOR_H #define ACTOR_H #include "taxVertex.h" /// class for acting with concept taxonomy class Actor { protected: // types /// array of TNEs typedef std::vector SynVector; /// array for a set of taxonomy verteces typedef std::vector SetOfNodes; protected: // members /// 2D array to return SetOfNodes acc; /// 1D array to return SynVector plain; /// temporary vector to keep synonyms SynVector syn; /// flag to look at concept-like or role-like entities bool isRole; /// flag to look at concepts or object roles bool isStandard; /// flag to throw exception at the 1st found bool interrupt; protected: // methods /// check whether actor is applicable to the ENTRY bool applicable ( const ClassifiableEntry* entry ); /// try current entry void tryEntry ( const ClassifiableEntry* p ) { if ( p->isSystem() ) return; if ( applicable(p) ) syn.push_back(p); /* if ( unlikely(interrupt) ) { plain.push_back(p); }*/ } /// build the NULL-terminated array of names of entries const char** buildArray ( const SynVector& vec ) const { const char** ret = new const char*[vec.size()+1]; for ( size_t i = 0; i < vec.size(); ++i ) ret[i] = vec[i]->getName(); ret[vec.size()] = NULL; return ret; } public: // interface /// empty c'tor Actor ( void ) {} /// empty d'tor virtual ~Actor ( void ) {} // flags setup /// set the actor to look for classes void needConcepts ( void ) { isRole = false; isStandard = true; } /// set the actor to look for individuals void needIndividuals ( void ) { isRole = false; isStandard = false; } /// set the actor to look for object properties void needObjectRoles ( void ) { isRole = true; isStandard = true; } /// set the actor to look for individuals void needDataRoles ( void ) { isRole = true; isStandard = false; } /// set the interrupt parameter to VALUE void setInterruptAfterFirstFound ( bool value ) { interrupt = value; } // return values /// get 1-d NULL-terminated array of synonyms of the 1st entry(necessary for Equivalents, for example) const char** getSynonyms ( void ) const { return buildArray ( acc.empty() ? SynVector() : acc[0] ); } /// get NULL-terminated 2D array of all required elements of the taxonomy const char*** getElements2D ( void ) const { const char*** ret = new const char**[acc.size()+1]; for ( size_t i = 0; i < acc.size(); ++i ) ret[i] = buildArray(acc[i]); ret[acc.size()] = NULL; return ret; } /// get NULL-terminated 1D array of all required elements of the taxonomy const char** getElements1D ( void ) const { SynVector vec; for ( SetOfNodes::const_iterator p = acc.begin(), p_end = acc.end(); p != p_end; ++p ) vec.insert ( vec.end(), p->begin(), p->end() ); return buildArray(vec); } /// taxonomy walking method. /// @return true if node was processed, and there is no need to go further /// @return false if node can not be processed in current settings bool apply ( const TaxonomyVertex& v ); }; // Actor #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/BuildDAG.cpp0000644000000000000000000002235012112642405017435 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2012 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ // This file contains methods for creating DAG representation of KB #include "dlTBox.h" void TBox :: buildDAG ( void ) { nNominalReferences = 0; // init concept indexing nC = 1; // start with 1 to make index 0 an indicator of "not processed" ConceptMap.push_back(NULL); // make fresh concept and datatype concept2dag(pTemp); DLTree* freshDT = DTCenter.getFreshDataType(); addDataExprToHeap ( static_cast(freshDT->Element().getNE()) ); deleteTree(freshDT); for ( c_const_iterator pc = c_begin(); pc != c_end(); ++pc ) concept2dag(*pc); for ( i_const_iterator pi = i_begin(); pi != i_end(); ++pi ) concept2dag(*pi); // init heads of simple rules for ( TSimpleRules::iterator q = SimpleRules.begin(), q_end = SimpleRules.end(); q < q_end; ++q ) (*q)->bpHead = tree2dag((*q)->tHead); // builds Roles range and domain initRangeDomain(ORM); initRangeDomain(DRM); // build all splits for ( TSplitVars::iterator s = getSplits()->begin(), s_end = getSplits()->end(); s != s_end; ++s ) split2dag(*s); RoleMaster::iterator p, p_end; // build all GCIs DLTree* GCI = Axioms.getGCI(); // add special domains to the GCIs if ( likely(useSpecialDomains) ) for ( p = ORM.begin(), p_end = ORM.end(); p < p_end; ++p ) if ( !(*p)->isSynonym() && (*p)->hasSpecialDomain() ) GCI = createSNFAnd ( GCI, clone((*p)->getTSpecialDomain()) ); // take chains that lead to Bot role into account if ( !ORM.getBotRole()->isSimple() ) GCI = createSNFAnd ( GCI, new DLTree ( TLexeme(FORALL), createRole(ORM.getBotRole()), createBottom() ) ); T_G = tree2dag(GCI); deleteTree(GCI); // mark GCI flags GCIs.setGCI(T_G != bpTOP); GCIs.setReflexive(ORM.hasReflexiveRoles()); // builds functional labels for roles for ( p = ORM.begin(), p_end = ORM.end(); p < p_end; ++p ) if ( !(*p)->isSynonym() && (*p)->isTopFunc() ) (*p)->setFunctional ( atmost2dag ( 1, *p, bpTOP ) ); for ( p = DRM.begin(), p_end = DRM.end(); p < p_end; ++p ) if ( !(*p)->isSynonym() && (*p)->isTopFunc() ) (*p)->setFunctional ( atmost2dag ( 1, *p, bpTOP ) ); // check the type of the ontology if ( nNominalReferences > 0 ) { unsigned int nInd = i_end() - i_begin(); if ( nInd > 100 && nNominalReferences > nInd ) isLikeWINE = true; } // here DAG is complete; set its final size DLHeap.setFinalSize(); } void TBox :: initRangeDomain ( RoleMaster& RM ) { RoleMaster::iterator p, p_end = RM.end(); for ( p = RM.begin(); p < p_end; ++p ) if ( !(*p)->isSynonym() ) { TRole* R = *p; # ifdef RKG_UPDATE_RND_FROM_SUPERROLES // add R&D from super-roles (do it AFTER axioms are transformed into R&D) R->collectDomainFromSupers(); # endif DLTree* dom = R->getTDomain(); BipolarPointer bp = bpTOP; if ( dom ) { bp = tree2dag(dom); GCIs.setRnD(); } R->setBPDomain(bp); // special domain for R is AR.Range R->initSpecialDomain(); if ( R->hasSpecialDomain() ) R->setSpecialDomain(tree2dag(R->getTSpecialDomain())); } } /// register data expression in the DAG BipolarPointer TBox :: addDataExprToHeap ( TDataEntry* p ) { if ( isValid(p->getBP()) ) // already registered value return p->getBP(); // determine the type of an entry DagTag dt = p->isBasicDataType() ? dtDataType : p->isDataValue() ? dtDataValue : dtDataExpr; BipolarPointer hostBP = bpTOP; // register host type first (if any) if ( p->getType() != NULL ) hostBP = addDataExprToHeap(const_cast(p->getType())); // create new DAG entry for the data value DLVertex* ver = new DLVertex ( dt, hostBP ); ver->setConcept(p); p->setBP(DLHeap.directAdd(ver)); return p->getBP(); } void TBox :: addConceptToHeap ( TConcept* pConcept ) { // choose proper tag by concept DagTag tag = pConcept->isPrimitive() ? (pConcept->isSingleton() ? dtPSingleton : dtPConcept): (pConcept->isSingleton() ? dtNSingleton : dtNConcept); // NSingleton is a nominal if ( tag == dtNSingleton && !pConcept->isSynonym() ) static_cast(pConcept)->setNominal(); // new concept's addition DLVertex* ver = new DLVertex(tag); ver->setConcept(pConcept); pConcept->pName = DLHeap.directAdd(ver); BipolarPointer desc = bpTOP; // translate body of a concept if ( pConcept->Description != NULL ) // complex concept desc = tree2dag(pConcept->Description); else // only primivive concepts here fpp_assert ( pConcept->isPrimitive() ); // update concept's entry pConcept->pBody = desc; ver->setChild(desc); if ( !pConcept->isSynonym() && pConcept->index() == 0 ) setConceptIndex(pConcept); } BipolarPointer TBox :: tree2dag ( const DLTree* t ) { if ( t == NULL ) return bpINVALID; // invalid value const TLexeme& cur = t->Element(); BipolarPointer ret = bpINVALID; switch ( cur.getToken() ) { case BOTTOM: // it is just !top ret = bpBOTTOM; break; case TOP: // the 1st node ret = bpTOP; break; case DATAEXPR: // data-related expression ret = addDataExprToHeap ( static_cast(cur.getNE()) ); break; case CNAME: // concept name ret = concept2dag(toConcept(cur.getNE())); break; case INAME: // individual name { ++nNominalReferences; // definitely a nominal TIndividual* ind = toIndividual(cur.getNE()); ind->setNominal(); ret = concept2dag(ind); break; } case NOT: ret = inverse ( tree2dag ( t->Left() ) ); break; case AND: ret = and2dag(t); break; case FORALL: ret = forall2dag ( resolveRole(t->Left()), tree2dag(t->Right()) ); break; case SELF: ret = reflexive2dag(resolveRole(t->Left())); break; case LE: ret = atmost2dag ( cur.getData(), resolveRole(t->Left()), tree2dag(t->Right()) ); break; case PROJFROM: // note: no PROJINTO as already unified ret = DLHeap.directAdd ( new DLVertex ( resolveRole(t->Left()), tree2dag(t->Right()->Right()), resolveRole(t->Right()->Left()) ) ); break; default: fpp_assert ( isSNF(t) ); // safety check fpp_unreachable(); // extra safety check ;) } return ret; } /// fills AND-like vertex V with an AND-like expression T; process result BipolarPointer TBox :: and2dag ( const DLTree* t ) { BipolarPointer ret = bpBOTTOM; DLVertex* v = new DLVertex(dtAnd); if ( fillANDVertex ( v, t ) ) // clash found delete v; else // AND vertex switch ( v->end() - v->begin() ) { case 0: // and(TOP) = TOP delete v; return bpTOP; case 1: // and(C) = C ret = *v->begin(); delete v; break; default: ret = DLHeap.add(v); break; } return ret; } BipolarPointer TBox :: forall2dag ( const TRole* R, BipolarPointer C ) { if ( R->isDataRole() ) return dataForall2dag(R,C); // create \all R.C == \all R{0}.C BipolarPointer ret = DLHeap.add ( new DLVertex ( dtForall, 0, R, C ) ); if ( R->isSimple() ) // don't care about the rest return ret; // check if the concept is not last if ( !DLHeap.isLast(ret) ) return ret; // all sub-roles were added before // have appropriate concepts for all the automata states for ( unsigned int i = 1; i < R->getAutomaton().size(); ++i ) DLHeap.directAddAndCache ( new DLVertex ( dtForall, i, R, C ) ); return ret; } BipolarPointer TBox :: atmost2dag ( unsigned int n, const TRole* R, BipolarPointer C ) { // input check: only simple roles are allowed in the (non-trivial) NR if ( !R->isSimple() ) throw EFPPNonSimpleRole(R->getName()); if ( R->isDataRole() ) return dataAtMost2dag(n,R,C); if ( unlikely ( C == bpBOTTOM ) ) // can happen as A & ~A return bpTOP; BipolarPointer ret = DLHeap.add ( new DLVertex ( dtLE, n, R, C ) ); // check if the concept is not last if ( !DLHeap.isLast(ret) ) return ret; // all elements were added before // create entries for the transitive sub-roles for ( unsigned int m = n-1; m > 0; --m ) DLHeap.directAddAndCache ( new DLVertex ( dtLE, m, R, C ) ); // create a blocker for the NN-rule DLHeap.directAddAndCache(new DLVertex(dtNN)); return ret; } /// transform splitted concept registered in SPLIT to a dag representation void TBox :: split2dag ( TSplitVar* split ) { DLVertex* v = new DLVertex(dtSplitConcept); for ( TSplitVar::iterator p = split->begin(), p_end = split->end(); p != p_end; ++p ) v->addChild(p->C->pName); split->C->pBody = DLHeap.directAdd(v); split->C->setPrimitive(false); DLHeap.replaceVertex ( split->C->pName, new DLVertex ( dtNConcept, split->C->pBody ), split->C ); DLHeap.directAdd(new DLVertex ( dtChoose, split->C->pName )); } bool TBox :: fillANDVertex ( DLVertex* v, const DLTree* t ) { if ( t->Element().getToken() == AND ) return fillANDVertex ( v, t->Left() ) || fillANDVertex ( v, t->Right() ); else return v->addChild ( tree2dag(t) ); } FaCTpp-src-v1.6.2~dfsg/src/Kernel/ProgressIndicatorInterface.h0000644000000000000000000000441512112642405023013 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2010 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef PROGRESSINDICATORINTERFACE_H #define PROGRESSINDICATORINTERFACE_H /// interface of the progress indicator class ProgressIndicatorInterface { protected: // members /// limit of the progress: indicate [0..uLimit] unsigned long uLimit; /// current value of an indicator unsigned long uCurrent; protected: // methods /// initial exposure method: can be overriden in derived classes virtual void initExposure ( void ) {} /// indicate current value somehow virtual void expose ( void ) = 0; /// check whether the limit is reached bool checkMax ( void ) { if ( uCurrent > uLimit ) { uCurrent = uLimit; return true; } else return false; } public: // interface /// empty c'tor ProgressIndicatorInterface ( void ) : uLimit (0), uCurrent (0) {} /// init c'tor ProgressIndicatorInterface ( unsigned long limit ) : uCurrent (0) { setLimit (limit); } /// empty d'tor virtual ~ProgressIndicatorInterface ( void ) {} /// set indicator to a given VALUE void setIndicator ( unsigned long value ) { if ( uCurrent != value ) { uCurrent = value; checkMax (); expose (); } } /// increment current value of an indicator to DELTA steps void incIndicator ( unsigned long delta = 1 ) { setIndicator(uCurrent+delta); } /// set indicator to 0 void reset ( void ) { setIndicator (0); } /// set the limit of an indicator to a given VALUE void setLimit ( unsigned long limit ) { uLimit = limit; reset(); initExposure(); } }; // ProgressIndicatorInterface #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/tNameSet.h0000644000000000000000000000647712112642405017263 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2012 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef TNAMESET_H #define TNAMESET_H #include #include /// base class for creating Named Entries; template parameter should be derived from TNamedEntry template class TNameCreator { public: // interface /// empty c'tor TNameCreator ( void ) {} /// empty d'tor virtual ~TNameCreator ( void ) {} /// create new Named Entry virtual T* makeEntry ( const std::string& name ) const { return new T(name); } }; // TNameCreator /// Implementation of NameSets by binary trees; template parameter should be derived from TNamedEntry template class TNameSet { protected: // types /// base type typedef std::map NameTree; /// RO iterator typedef typename NameTree::const_iterator const_iterator; public: // types /// RW iterator typedef typename NameTree::iterator iterator; protected: // members /// Base holding all names NameTree Base; /// creator of new name TNameCreator* Creator; private: // no copy /// no copy c'tor TNameSet ( const TNameSet& ); /// no assignment TNameSet& operator = ( const TNameSet& ); public: // interface /// c'tor (empty) TNameSet ( void ) : Creator(new TNameCreator) {} /// c'tor (with given Name Creating class) TNameSet ( TNameCreator* p ) : Creator(p) {} /// d'tor (delete all entries) virtual ~TNameSet ( void ) { clear(); delete Creator; } /// return pointer to existing id or NULL if no such id defined T* get ( const std::string& id ) const { const_iterator p = Base.find(id); return p == Base.end() ? NULL : p->second; } /// unconditionally add new element with name ID to the set; return new element T* add ( const std::string& id ) { T* pne = Creator->makeEntry(id); Base[id] = pne; return pne; } /// Insert id to a nameset (if necessary); @return pointer to id structure created by external creator T* insert ( const std::string& id ) { T* pne = get(id); if ( pne == NULL ) // no such Id pne = add(id); return pne; } /// remove given entry from the set void remove ( const std::string& id ) { iterator p = Base.find(id); if ( p != Base.end () ) // founs such Id { delete p->second; Base.erase(p); } } /// clear name set void clear ( void ) { for ( iterator p = Base.begin(); p != Base.end(); ++p ) delete p->second; Base.clear(); } /// get size of a name set unsigned int size ( void ) const { return Base.size(); } /// RW begin iterator iterator begin ( void ) { return Base.begin(); } /// RW end iterator iterator end ( void ) { return Base.end(); } }; // TNameSet #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/DLConceptTaxonomy.cpp0000644000000000000000000003160512112642405021437 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2012 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /*******************************************************\ |* Implementation of taxonomy building for the FaCT++ *| \*******************************************************/ #include "Reasoner.h" #include "DLConceptTaxonomy.h" #include "procTimer.h" #include "globaldef.h" #include "logging.h" /********************************************************\ |* Implementation of class Taxonomy *| \********************************************************/ bool DLConceptTaxonomy :: testSub ( const TConcept* p, const TConcept* q ) { fpp_assert ( p != NULL ); fpp_assert ( q != NULL ); if ( q->isSingleton() // singleton on the RHS is useless iff... && q->isPrimitive() // it is primitive && !q->isNominal() ) // nominals should be classified as usual concepts return false; if ( unlikely(inSplitCheck) ) { if ( q->isPrimitive() ) // only defined ones in split checks return false; return testSubTBox ( p, q ); } if ( LLM.isWritable(llTaxTrying) ) LL << "\nTAX: trying '" << p->getName() << "' [= '" << q->getName() << "'... "; if ( tBox.testSortedNonSubsumption ( p, q ) ) { if ( LLM.isWritable(llTaxTrying) ) LL << "NOT holds (sorted result)"; ++nSortedNegative; return false; } switch ( tBox.testCachedNonSubsumption ( p, q ) ) { case csValid: // cached result: satisfiable => non-subsumption if ( LLM.isWritable(llTaxTrying) ) LL << "NOT holds (cached result)"; ++nCachedNegative; return false; case csInvalid: // cached result: unsatisfiable => subsumption holds if ( LLM.isWritable(llTaxTrying) ) LL << "holds (cached result)"; ++nCachedPositive; return true; default: // need extra tests if ( LLM.isWritable(llTaxTrying) ) LL << "wasted cache test"; break; } return testSubTBox ( p, q ); } Taxonomy::KnownSubsumers* DLConceptTaxonomy :: buildKnownSubsumers ( ClassifiableEntry* ce ) { return Taxonomy::buildKnownSubsumers(ce); } void DLConceptTaxonomy :: print ( std::ostream& o ) const { o << "Totally " << nTries << " subsumption tests was made\nAmong them "; unsigned int n = ( nTries ? nTries : 1 ); o << nPositives << " (" << (unsigned long)(nPositives*100/n) << "%) successfull\n"; o << "Besides that " << nCachedPositive << " successfull and " << nCachedNegative << " unsuccessfull subsumption tests were cached\n"; if ( nSortedNegative ) o << "Sorted reasoning deals with " << nSortedNegative << " non-subsumptions\n"; o << "There were made " << nSearchCalls << " search calls\nThere were made " << nSubCalls << " Sub calls, of which " << nNonTrivialSubCalls << " non-trivial\n"; o << "Current efficiency (wrt Brute-force) is " << nEntries*(nEntries-1)/n << "\n"; Taxonomy::print(o); } // Baader procedures void DLConceptTaxonomy :: searchBaader ( bool upDirection, TaxonomyVertex* cur ) { // label 'visited' cur->setChecked(checkLabel); ++nSearchCalls; bool noPosSucc = true; // check if there are positive successors; use DFS on them. for ( TaxonomyVertex::iterator p = cur->begin(upDirection), p_end = cur->end(upDirection); p != p_end; ++p ) if ( enhancedSubs ( upDirection, *p ) ) { if ( !(*p)->isChecked(checkLabel) ) searchBaader ( upDirection, *p ); noPosSucc = false; } // in case current node is unchecked (no BOTTOM node) -- check it explicitely if ( !cur->isValued(valueLabel) ) cur->setValued ( testSubsumption ( upDirection, cur ), valueLabel ); // mark labelled leaf node as a parent if ( noPosSucc && cur->getValue() ) Current->addNeighbour ( !upDirection, cur ); } bool DLConceptTaxonomy :: enhancedSubs1 ( bool upDirection, TaxonomyVertex* cur ) { ++nNonTrivialSubCalls; // need to be valued -- check all parents // propagate false for ( TaxonomyVertex::iterator p = cur->begin(!upDirection), p_end = cur->end(!upDirection); p != p_end; ++p ) if ( !enhancedSubs ( upDirection, *p ) ) return false; // all subsumptions holds -- test current for subsumption return testSubsumption ( upDirection, cur ); } bool DLConceptTaxonomy :: testSubsumption ( bool upDirection, TaxonomyVertex* cur ) { const TConcept* testC = static_cast(cur->getPrimer()); if ( upDirection ) return testSub ( testC, curConcept() ); else return testSub ( curConcept(), testC ); } void DLConceptTaxonomy :: propagateOneCommon ( TaxonomyVertex* node ) { // checked if node already was visited this session if ( node->isChecked(checkLabel) ) return; // mark node visited node->setChecked(checkLabel); node->setCommon(); if ( node->correctCommon(nCommon) ) Common.push_back(node); // mark all children for ( TaxonomyVertex::iterator p = node->begin(/*upDirection=*/false), p_end = node->end(/*upDirection=*/false); p != p_end; ++p ) propagateOneCommon(*p); } bool DLConceptTaxonomy :: propagateUp ( void ) { const bool upDirection = true; // including node always have some parents (TOP at least) TaxonomyVertex::iterator p = Current->begin(upDirection), p_end = Current->end(upDirection); fpp_assert ( p != p_end ); // there is at least one parent (TOP) TaxVertexVec aux; // aux set for the verteces in ... nCommon = 1; // number of common parents clearCommon(); // define possible successors of the node propagateOneCommon(*p); clearCheckedLabel(); for ( ++p; p != p_end; ++p ) { if ( (*p)->noNeighbours(!upDirection) ) return true; if ( Common.empty() ) return true; ++nCommon; // now Aux contain data from previous run aux.swap(Common); Common.clear(); propagateOneCommon(*p); clearCheckedLabel(); // clear all non-common nodes (visited on a previous run) for ( TaxVertexVec::iterator q = aux.begin(), q_end = aux.end(); q < q_end; ++q ) (*q)->correctCommon(nCommon); } return false; } void DLConceptTaxonomy :: clearCommon ( void ) { for ( TaxVertexVec::iterator p = Common.begin(), p_end = Common.end(); p < p_end; ++p ) (*p)->clearCommon(); Common.clear(); } /// check if no BU classification is required as C=TOP bool DLConceptTaxonomy :: isEqualToTop ( void ) { // check this up-front to avoid Sorted check's flaw wrt equals-to-top const modelCacheInterface* cache = tBox.initCache ( curConcept(), /*sub=*/true ); if ( cache->getState() != csInvalid ) return false; // here concept = TOP Current->addNeighbour ( /*upDirection=*/false, getTopVertex() ); return true; } /// @return true iff curEntry is classified as a synonym bool DLConceptTaxonomy :: classifySynonym ( void ) { if ( Taxonomy::classifySynonym() ) return true; if ( curConcept()->isSingleton() ) { TIndividual* curI = (TIndividual*)const_cast(curConcept()); if ( unlikely(tBox.isBlockedInd(curI)) ) { // check whether current entry is the same as another individual TIndividual* syn = tBox.getBlockingInd(curI); fpp_assert ( syn->getTaxVertex() != NULL ); if ( tBox.isBlockingDet(curI) ) { // deterministic merge => curI = syn addCurrentToSynonym(syn->getTaxVertex()); return true; } else // non-det merge: check whether it is the same { if ( LLM.isWritable(llTaxTrying) ) LL << "\nTAX: trying '" << curI->getName() << "' = '" << syn->getName() << "'... "; if ( testSubTBox ( curI, syn ) ) // they are actually the same { addCurrentToSynonym(syn->getTaxVertex()); return true; } } } } return false; } void DLConceptTaxonomy :: checkExtraParents ( void ) { inSplitCheck = true; TaxonomyVertex::iterator p, p_end; for ( p = Current->begin(/*upDirection=*/true), p_end = Current->end(/*upDirection=*/true); p != p_end; ++p ) propagateTrueUp(*p); Current->clearLinks(/*upDirection=*/true); runTopDown(); // save all indirect parents to remove them later (to avoid iterator invalidation) TaxVertexVec vec; for ( p = Current->begin(/*upDirection=*/true), p_end = Current->end(/*upDirection=*/true); p != p_end; ++p ) if ( !isDirectParent(*p) ) vec.push_back(*p); // now it is time to remove links for ( TaxVertexVec::iterator q = vec.begin(), q_end = vec.end(); q != q_end; ++q ) { (*q)->removeLink ( /*upDirection=*/false, Current ); Current->removeLink ( /*upDirection=*/true, *q ); } clearLabels(); inSplitCheck = false; } /// merge vars came from a given SPLIT together void DLConceptTaxonomy :: mergeSplitVars ( TSplitVar* split ) { typedef std::set TVSet1; TVSet1 splitVertices; TaxonomyVertex* v = split->C->getTaxVertex(); bool cIn = ( v != NULL ); if ( v != NULL ) // there is C-node in the taxonomy splitVertices.insert(v); TSplitVar::iterator q = split->begin(), q_end = split->end(); for ( ; q != q_end; ++q ) splitVertices.insert(q->C->getTaxVertex()); // set V to be a node-to-add // FIXME!! check later the case whether both TOP and BOT are there if ( splitVertices.count(getBottomVertex()) > 0 ) v = getBottomVertex(); else if ( splitVertices.count(getTopVertex()) > 0 ) v = getTopVertex(); else { setCurrentEntry(split->C); v = Current; } if ( v != Current && !cIn ) v->addSynonym(split->C); for ( TVSet1::iterator p = splitVertices.begin(), p_end = splitVertices.end(); p != p_end; ++p ) mergeVertex ( v, *p, splitVertices ); if ( v == Current ) { checkExtraParents(); insertCurrentNode(); } } /********************************************************\ |* Implementation of class TBox *| \********************************************************/ void TBox :: createTaxonomy ( bool needIndividual ) { bool needConcept = !needIndividual; // if there were SAT queries before -- the query (or other) concepts are there. Delete it clearQueryConcept(); // here we sure that ontology is consistent // FIXME!! distinguish later between the 1st run and the following runs if ( pTax == NULL ) // 1st run pTax = new DLConceptTaxonomy ( pTop, pBottom, *this ); DLHeap.setSubOrder(); // init priorities in order to do subsumption tests pTax->setBottomUp(GCIs); needConcept |= needIndividual; // together with concepts // else // not a first run // return; // FIXME!! now we don't perform staged reasoning, so everything is done /* { fpp_assert ( needIndividual ); pTax->deFinalise(); } */ if ( verboseOutput ) std::cerr << "Processing query..."; TsProcTimer locTimer; locTimer.Start(); // calculate number of items to be classified unsigned int nItems = 0; // fills collections arrayCD.clear(); arrayNoCD.clear(); arrayNP.clear(); // if ( needConcept ) nItems += fillArrays ( c_begin(), c_end() ); // if ( needIndividual ) nItems += fillArrays ( i_begin(), i_end() ); // taxonomy progress if ( pMonitor ) { pMonitor->setClassificationStarted(nItems); pTax->setProgressIndicator(pMonitor); } duringClassification = true; // sort ( arrayCD.begin(), arrayCD.end(), TSDepthCompare() ); classifyConcepts ( arrayCD, true, "completely defined" ); // sort ( arrayNoCD.begin(), arrayNoCD.end(), TSDepthCompare() ); classifyConcepts ( arrayNoCD, false, "regular" ); // sort ( arrayNP.begin(), arrayNP.end(), TSDepthCompare() ); classifyConcepts ( arrayNP, false, "non-primitive" ); duringClassification = false; pTax->processSplits(); if ( pMonitor ) { pMonitor->setFinished(); setProgressMonitor(NULL); // no need of PM after classification done pTax->setProgressIndicator(NULL); } pTax->finalise(); locTimer.Stop(); if ( verboseOutput ) std::cerr << " done in " << locTimer << " seconds\n"; if ( needConcept && Status < kbClassified ) Status = kbClassified; if ( needIndividual ) Status = kbRealised; if ( verboseOutput/* && needIndividual*/ ) { std::ofstream of ( "Taxonomy.log" ); pTax->print (of); } } void TBox :: classifyConcepts ( const ConceptVector& collection, bool curCompletelyDefined, const char* type ) { // set CD for taxonomy pTax->setCompletelyDefined (curCompletelyDefined); if ( LLM.isWritable(llStartCfyConcepts) ) LL << "\n\n---Start classifying " << type << " concepts"; unsigned int n = 0; for ( ConceptVector::const_iterator q = collection.begin(), q_end = collection.end(); q < q_end; ++q ) // check if concept is already classified if ( !isCancelled() && !(*q)->isClassified () /*&& (*q)->isClassifiable(curCompletelyDefined)*/ ) { classifyEntry(*q); // need to classify concept if ( (*q)->isClassified() ) ++n; } if ( LLM.isWritable(llStartCfyConcepts) ) LL << "\n---Done: " << n << " " << type << " concepts classified"; } FaCTpp-src-v1.6.2~dfsg/src/Kernel/grammar.h0000644000000000000000000000313612112642405017156 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2011 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ //------------------------------------------------------------------------- // // Grammar for FaCT++ // //------------------------------------------------------------------------- #ifndef GRAMMAR_H #define GRAMMAR_H // constants for symbols enum Token { AND, OR, NOT, INV, RCOMPOSITION, // role composition PROJINTO, // role projection into PROJFROM, // role projection from SELF, TOP, BOTTOM, EXISTS, FORALL, GE, // ATLEAST = GE, LE, // ATMOST = LE, // common metasymbols DATAEXPR, // any data expression: data value, [constrained] datatype // more precise ID's discretion CNAME, // name of a concept INAME, // name of a singleton RNAME, // name of a role DNAME, // name of a data role }; // some multi-case defines // any name (like ID) #define NAME CNAME: case INAME: case RNAME: case DNAME #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/KnowledgeExplorer.cpp0000644000000000000000000001242712112642405021526 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2011-2012 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "KnowledgeExplorer.h" #include "dlCompletionTree.h" #include "dlTBox.h" /// init c'tor KnowledgeExplorer :: KnowledgeExplorer ( const TBox* box, TExpressionManager* pEM ) : D2I ( box->getDag(), pEM ) { // init all concepts for ( TBox::c_const_iterator c = box->c_begin(), c_end = box->c_end(); c != c_end; ++c ) addE ( Cs, *c ); // init all individuals for ( TBox::i_const_iterator i = box->i_begin(), i_end = box->i_end(); i != i_end; ++i ) addE ( Is, *i ); RoleMaster::const_iterator r, r_end; // init all object roles for ( r = box->getORM()->begin(), r_end = box->getORM()->end(); r != r_end; ++r ) { TRole* R = *r; addE ( ORs, R ); for ( TRole::const_iterator p = R->begin_anc(), p_end = R->end_anc(); p != p_end; ++p ) ORs.add ( R, *p ); } // init all data roles for ( r = box->getDRM()->begin(), r_end = box->getDRM()->end(); r != r_end; ++r ) { TRole* R = *r; addE ( DRs, R ); for ( TRole::const_iterator p = R->begin_anc(), p_end = R->end_anc(); p != p_end; ++p ) DRs.add ( R, *p ); } } /* * # measurement update H.show() x.show() y = matrix([[measurements[n]]]).__sub__(H.__mul__(x)) y.show() S = R.__add__(H.__mul__(P.__mul__(H.transpose()))) K = P.__mul__(H.transpose().__mul__(S.inverse())) K.show() # y is constant yy = y.__repr__() print yy[0][0] x = x.__add__(K.__mul__(yy)) P = (I.__sub(K.__mul__(H))).__mul__(P) # prediction x = u.__add__(F.__mul__(x)) P = F.__mul__(P.__mul__(transpose(F))) print 'x= ' x.show() print 'P= ' P.show() */ /// add concept-like entity E (possibly with synonyms) to CONCEPTS void KnowledgeExplorer :: addC ( const TDLExpression* e ) { // check named concepts const TDLConceptName* C = dynamic_cast(e); if ( C != NULL ) { for ( EE2Map::iterator p = Cs.begin(C), p_end = Cs.end(C); p != p_end; ++p ) if ( unlikely(*p == NULL) ) std::cerr << "Null found while processing class " << C->getName() << "\n"; else Concepts.push_back(*p); return; } // check named individuals const TDLIndividualName* I = dynamic_cast(e); if ( I != NULL ) { for ( EE2Map::iterator p = Is.begin(I), p_end = Is.end(I); p != p_end; ++p ) if ( unlikely(*p == NULL) ) std::cerr << "Null found while processing individual " << I->getName() << "\n"; else Concepts.push_back(*p); return; } Concepts.push_back(e); } // couldn't get it as a method, so #define addAll(S) do { Roles.insert(S.begin(),S.end()); } while(0) const KnowledgeExplorer::TCGRoleSet& KnowledgeExplorer :: getDataRoles ( const TCGNode* node, bool onlyDet ) { Roles.clear(); for ( DlCompletionTree::const_edge_iterator p = node->begin(), p_end = node->end(); p != p_end; ++p ) if ( likely(!(*p)->isIBlocked()) && (*p)->getArcEnd()->isDataNode() && (!onlyDet || (*p)->getDep().empty()) ) addAll(DRs.get((*p)->getRole()->getEntity())); return Roles; } /// build the set of object neighbours of a NODE; incoming edges are counted iff NEEDINCOMING is true const KnowledgeExplorer::TCGRoleSet& KnowledgeExplorer :: getObjectRoles ( const TCGNode* node, bool onlyDet, bool needIncoming ) { Roles.clear(); for ( DlCompletionTree::const_edge_iterator p = node->begin(), p_end = node->end(); p != p_end; ++p ) if ( likely(!(*p)->isIBlocked()) && !(*p)->getArcEnd()->isDataNode() && (!onlyDet || (*p)->getDep().empty()) && (needIncoming || (*p)->isSuccEdge() ) ) addAll(ORs.get((*p)->getRole()->getEntity())); return Roles; } /// build the set of neighbours of a NODE via role ROLE; put the resulting list into RESULT const KnowledgeExplorer::TCGNodeVec& KnowledgeExplorer :: getNeighbours ( const TCGNode* node, const TRole* R ) { Nodes.clear(); for ( DlCompletionTree::const_edge_iterator p = node->begin(), p_end = node->end(); p != p_end; ++p ) if ( likely(!(*p)->isIBlocked()) && (*p)->isNeighbour(R) ) Nodes.push_back((*p)->getArcEnd()); return Nodes; } /// put into RESULT all the data expressions from the NODE label const KnowledgeExplorer::TCGItemVec& KnowledgeExplorer :: getLabel ( const TCGNode* node, bool onlyDet ) { // prepare D2I translator D2I.ensureDagSize(); DlCompletionTree::const_label_iterator p, p_end; bool data = node->isDataNode(); Concepts.clear(); for ( p = node->beginl_sc(), p_end = node->endl_sc(); p != p_end; ++p ) if ( !onlyDet || p->getDep().empty() ) addC(D2I.getExpr(p->bp(),data)); for ( p = node->beginl_cc(), p_end = node->endl_cc(); p != p_end; ++p ) if ( !onlyDet || p->getDep().empty() ) addC(D2I.getExpr(p->bp(),data)); return Concepts; } FaCTpp-src-v1.6.2~dfsg/src/Kernel/modelCacheConst.h0000644000000000000000000000502612112642405020563 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2007-2010 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef MODELCACHECONST_H #define MODELCACHECONST_H #include "modelCacheInterface.h" #include "BiPointer.h" #include "fpp_assert.h" /// Model caching implementation for TOP/BOTTOM nodes. class modelCacheConst: public modelCacheInterface { protected: // members /// the const itself bool isTop; public: /// c'tor: no nominals can be here modelCacheConst ( bool top ) : modelCacheInterface(/*flagNominals=*/false) , isTop(top) {} /// copy c'tor modelCacheConst ( const modelCacheConst& m ) : modelCacheInterface(m.hasNominalNode) , isTop(m.isTop) {} /// empty d'tor virtual ~modelCacheConst ( void ) {} /// Check if the model contains clash virtual modelCacheState getState ( void ) const { return isTop ? csValid : csInvalid; } /// get the value of the constant bool getConst ( void ) const { return isTop; } // mergable part /// check whether two caches can be merged; @return state of "merged" model modelCacheState canMerge ( const modelCacheInterface* p ) const { if ( p->getCacheType() == mctConst ) return isTop && static_cast(p)->isTop ? csValid : csInvalid; else return p->canMerge(this); } /// Get the tag identifying the cache type virtual modelCacheType getCacheType ( void ) const { return mctConst; } #ifdef _USE_LOGGING /// log this cache entry (with given level) virtual void logCacheEntry ( unsigned int level ) const { if ( LLM.isWritable(level) ) LL << "\nConst cache: element " << (isTop ? "TOP" : "BOTTOM"); } #endif }; // modelCacheConst // create const cache by BP; BP should be either bpTOP or bpBOTTOM inline modelCacheConst* createConstCache ( BipolarPointer bp ) { fpp_assert ( bp == bpTOP || bp == bpBOTTOM ); return new modelCacheConst(bp==bpTOP); } #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/eFPPTimeout.h0000644000000000000000000000201612112642405017665 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2009-2013 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef EFPPTIMEOUT_H #define EFPPTIMEOUT_H #include "eFaCTPlusPlus.h" class EFPPTimeout: public EFaCTPlusPlus { public: // interface EFPPTimeout ( void ) : EFaCTPlusPlus("FaCT++ Kernel: operation timeout") {} }; // EFPPTimeout #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/tHeadTailCache.h0000644000000000000000000000400012112642405020302 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2010 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef THEADTAILCACHE_H #define THEADTAILCACHE_H /// Template class for the cache element. Assumes that new elements of a HEADTYPE /// are constructed using a single argument of a TAILTYPE. Uniqueness of a tails /// leads to the uniqueness of a constructed object template class THeadTailCache { protected: // types /// auxiliary map typedef std::map CacheMap; /// map RW iterator typedef typename CacheMap::iterator iterator; /// map RO iterator typedef typename CacheMap::const_iterator const_iterator; protected: // members /// map tail into an object head(tail) CacheMap Map; protected: // methods /// the way to create an object by a given tail virtual HeadType* build ( TailType* ) = 0; public: // interface /// empty c'tor THeadTailCache ( void ) {} /// empty d'tor virtual ~THeadTailCache ( void ) {} /// get an object corresponding to Head.Tail HeadType* get ( TailType* tail ) { // try to find cached dep-set const_iterator p = Map.find(tail); if ( p != Map.end() ) return p->second; // no cached entry -- create a new one and cache it HeadType* concat = build(tail); Map[tail] = concat; return concat; } }; // THeadTailCache #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/KnowledgeExplorer.h0000644000000000000000000001100512112642405021162 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2011-2012 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef KNOWLEDGEEXPLORER_H #define KNOWLEDGEEXPLORER_H #include "taxNamEntry.h" #include "tDag2Interface.h" // forward declarations class TBox; class DlCompletionTree; /// class to perform a knowledge exploration class KnowledgeExplorer { public: // types /// type for the node in the completion graph typedef const DlCompletionTree TCGNode; /// type for the node vector typedef std::vector TCGNodeVec; /// type for a set of role expressions (used in KE to return stuff) typedef std::set TCGRoleSet; /// type for a vector of data/concept expressions (used in KE to return stuff) typedef std::vector TCGItemVec; protected: // classes /// class that maps named entity to a set of ENTITIES template class EE2Map { public: // type interface /// set of entities typedef std::set ESet; /// RO iterator to the ESet typedef typename ESet::const_iterator iterator; protected: // members /// the map itself std::map Base; public: // interface /// empty c'tor EE2Map ( void ) {} /// empty d'tor ~EE2Map ( void ) {} /// add an entity corresponding E to a map corresponding to E0 void add ( const TNamedEntry* e0, const TNamedEntry* e ) { const TNamedEntity* E0 = e0->getEntity(), *E = e->getEntity(); // check for artificial constructions if ( E0 == NULL || E == NULL ) { std::cerr << "No entity found for"; if ( E0 == NULL ) std::cerr << " '" << e0->getName() << "'"; if ( E == NULL ) std::cerr << " '" << e->getName() << "'"; std::cerr << "\n"; return; } Base[E0].insert(dynamic_cast(E)); } /// get the set corresponding to the entity E const ESet& get ( const TNamedEntity* e ) { return Base[e]; } /// get the begin iterator of a set corresponding to the entity E iterator begin ( const TNamedEntity* e ) { return Base[e].begin(); } /// get the end iterator of a set corresponding to the entity E iterator end ( const TNamedEntity* e ) { return Base[e].end(); } }; // EE2Map protected: // members /// map concept into set of its synonyms EE2Map Cs; /// map individual into set of its synonyms EE2Map Is; /// map object role to the set of its super-roles (self included) EE2Map ORs; /// map data role to the set of its super-roles (self included) EE2Map DRs; /// dag-2-interface translator used in knowledge exploration TDag2Interface D2I; /// node vector to return TCGNodeVec Nodes; /// role set to return TCGRoleSet Roles; /// concept vector to return TCGItemVec Concepts; protected: // methods /// adds an entity as a synonym to a map MAP template void addE ( EE2Map& map, const ClassifiableEntry* entry ) { map.add(entry,entry); if ( entry->isSynonym() ) map.add ( entry->getSynonym(), entry ); } /// add concept-like expression E (possibly with synonyms) to CONCEPTS void addC ( const TDLExpression* e ); public: // interface /// init c'tor KnowledgeExplorer ( const TBox* box, TExpressionManager* pEM ); /// empty d'tor ~KnowledgeExplorer ( void ) {} /// @return the set of data neighbours of a NODE const TCGRoleSet& getDataRoles ( const TCGNode* node, bool onlyDet ); /// @return the set of object neighbours of a NODE const TCGRoleSet& getObjectRoles ( const TCGNode* node, bool onlyDet, bool needIncoming ); /// @return the set of neighbours of a NODE via role ROLE const TCGNodeVec& getNeighbours ( const TCGNode* node, const TRole* role ); /// @return the set of all the expressions from the NODE label const TCGItemVec& getLabel ( const TCGNode* node, bool onlyDet ); }; // KnowledgeExplorer #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/parseTime.cpp0000644000000000000000000000246012112642405020013 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2011 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "parseTime.h" /// fills TM with a time value from string STR; @return true iff fail to load static bool fillTmByString ( const char* str, struct tm* tm ) { return strptime ( str, "%Y-%m-%dT%H:%M:%S%z", tm ) != NULL; } /// this function gets a string representing time in an ISO 8601 format and returns time_t value built out of it time_t parseTimeString ( const char* str ) { struct tm temp; // decode time value in format YYYY-MM-DDThh:mm:ssTZ, as in xsd:dateTime fillTmByString ( str, &temp ); return timegm(&temp); } FaCTpp-src-v1.6.2~dfsg/src/Kernel/tRestorer.h0000644000000000000000000000264712112642405017527 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2011 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef TRESTORER_H #define TRESTORER_H /** * Generic class for restore some property. * Usually inherited class has a pointer to object to be restored and restore info */ class TRestorer { protected: // members /// restore level unsigned int lev; public: // interface /// empty c'tor TRestorer ( void ) {} /// empty d'tor virtual ~TRestorer ( void ) {} /// restore an object based on saved information virtual void restore ( void ) = 0; // level operations /// set restore level void setLevel ( unsigned int l ) { lev = l; } /// get restore level unsigned int level ( void ) const { return lev; } }; // TRestorer #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/tExpressionManager.h0000644000000000000000000003720212112642405021347 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2010-2012 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef TEXPRESSIONMANAGER_H #define TEXPRESSIONMANAGER_H #include "tDLExpression.h" #include "tNameSet.h" #include "tNAryQueue.h" #include "tDataTypeManager.h" #include "tHeadTailCache.h" /// manager to work with all DL expressions in the kernel class TExpressionManager { protected: // types /// cache for the one-of expressions class TOneOfCache: public THeadTailCache { protected: // members /// host expression manager TExpressionManager* pManager; protected: // methods /// the way to create an object by a given tail virtual TDLConceptExpression* build ( const TDLIndividualExpression* tail ); public: // interface /// empty c'tor TOneOfCache ( TExpressionManager* p ) : THeadTailCache(), pManager(p) {} /// empty d'tor virtual ~TOneOfCache ( void ) {} /// clear the cache void clear ( void ) { Map.clear(); } }; // TOneOfCache /// Cache for the inverse roles class TInverseRoleCache : public THeadTailCache { protected: // members /// host expression manager TExpressionManager* pManager; protected: // methods /// the way to create an object by a given tail virtual TDLObjectRoleExpression* build ( const TDLObjectRoleExpression* tail ); public: // interface /// empty c'tor TInverseRoleCache ( TExpressionManager* p ) : THeadTailCache(), pManager(p) {} /// empty d'tor virtual ~TInverseRoleCache ( void ) {} /// clear the cache void clear ( void ) { Map.clear(); } }; // TInverseRoleCache protected: // members /// nameset for concepts TNameSet NS_C; /// nameset for individuals TNameSet NS_I; /// nameset for object roles TNameSet NS_OR; /// nameset for data roles TNameSet NS_DR; /// nameset for data types TDataTypeManager NS_DT; /// n-ary queue for arguments TNAryQueue ArgQueue; /// TOP concept TDLConceptTop* CTop; /// BOTTOM concept TDLConceptBottom* CBottom; /// TOP data element TDLDataTop* DTop; /// BOTTOM data element TDLDataBottom* DBottom; /// TOP object role TDLObjectRoleExpression* ORTop; /// BOTTOM object role TDLObjectRoleExpression* ORBottom; /// TOP data role TDLDataRoleExpression* DRTop; /// BOTTOM data role TDLDataRoleExpression* DRBottom; /// record all the references std::vector RefRecorder; /// cache for the role inverses TInverseRoleCache InverseRoleCache; /// cache for the one-of singletons TOneOfCache OneOfCache; protected: // methods /// record the reference; @return the argument template T* record ( T* arg ) { RefRecorder.push_back(arg); return arg; } /// clear the TNamedEntry cache for all elements of a name-set NS template void clearNameCache ( TNameSet& ns ) { for ( typename TNameSet::iterator p = ns.begin(), p_end = ns.end(); p != p_end; ++p ) p->second->setEntry(NULL); } public: // interface /// empty c'tor TExpressionManager ( void ); /// d'tor ~TExpressionManager ( void ); /// clear the ontology void clear ( void ); /// clear the TNamedEntry cache for all elements of all name-sets void clearNameCache ( void ); // top/bottom roles /// set Top/Bot properties void setTopBottomRoles ( const char* topORoleName, const char* botORoleName, const char* topDRoleName, const char* botDRoleName ) { delete ORTop; ORTop = new TDLObjectRoleName(topORoleName); delete ORBottom; ORBottom = new TDLObjectRoleName(botORoleName); delete DRTop; DRTop = new TDLDataRoleName(topDRoleName); delete DRBottom; DRBottom = new TDLDataRoleName(botDRoleName); } /// @return true iff R is a top object role bool isUniversalRole ( const TDLObjectRoleExpression* R ) const { return R == ORTop; } /// @return true iff R is a top data role bool isUniversalRole ( const TDLDataRoleExpression* R ) const { return R == DRTop; } /// @return true iff R is a bottom object role bool isEmptyRole ( const TDLObjectRoleExpression* R ) const { return R == ORBottom; } /// @return true iff R is a bottom data role bool isEmptyRole ( const TDLDataRoleExpression* R ) const { return R == DRBottom; } // entries count /// get number of registered concepts unsigned int nConcepts ( void ) const { return NS_C.size(); } /// get number of registered individuals unsigned int nIndividuals ( void ) const { return NS_I.size(); } /// get number of registered object roles unsigned int nORoles ( void ) const { return NS_OR.size(); } /// get number of registered data roles unsigned int nDRoles ( void ) const { return NS_DR.size(); } // argument lists /// opens new argument list void newArgList ( void ) { ArgQueue.openArgList(); } /// add argument ARG to the current argument list void addArg ( const TDLExpression* arg ) { ArgQueue.addArg(arg); } /// get the latest argument list const std::vector& getArgList ( void ) { return ArgQueue.getLastArgList(); } // create expressions methods // concepts /// get TOP concept TDLConceptExpression* Top ( void ) const { return CTop; } /// get BOTTOM concept TDLConceptExpression* Bottom ( void ) const { return CBottom; } /// get named concept TDLConceptExpression* Concept ( const std::string& name ) { return NS_C.insert(name); } /// get negation of a concept C TDLConceptExpression* Not ( const TDLConceptExpression* C ) { return record(new TDLConceptNot(C)); } /// get an n-ary conjunction expression; take the arguments from the last argument list TDLConceptExpression* And ( void ) { return record(new TDLConceptAnd(getArgList())); } /// @return C and D TDLConceptExpression* And ( const TDLConceptExpression* C, const TDLConceptExpression* D ) { newArgList(); addArg(C); addArg(D); return And(); } /// get an n-ary disjunction expression; take the arguments from the last argument list TDLConceptExpression* Or ( void ) { return record(new TDLConceptOr(getArgList())); } /// @return C or D TDLConceptExpression* Or ( const TDLConceptExpression* C, const TDLConceptExpression* D ) { newArgList(); addArg(C); addArg(D); return Or(); } /// get an n-ary one-of expression; take the arguments from the last argument list TDLConceptExpression* OneOf ( void ) { const std::vector& v = getArgList(); if ( v.size() == 1 ) return OneOfCache.get(static_cast(v.front())); return record(new TDLConceptOneOf(v)); } /// @return concept {I} for the individual I TDLConceptExpression* OneOf ( const TDLIndividualExpression* I ) { return OneOfCache.get(I); } /// get self-reference restriction of an object role R TDLConceptExpression* SelfReference ( const TDLObjectRoleExpression* R ) { return record(new TDLConceptObjectSelf(R)); } /// get value restriction wrt an object role R and an individual I TDLConceptExpression* Value ( const TDLObjectRoleExpression* R, const TDLIndividualExpression* I ) { return record(new TDLConceptObjectValue(R,I)); } /// get existential restriction wrt an object role R and a concept C TDLConceptExpression* Exists ( const TDLObjectRoleExpression* R, const TDLConceptExpression* C ) { return record(new TDLConceptObjectExists(R,C)); } /// get universal restriction wrt an object role R and a concept C TDLConceptExpression* Forall ( const TDLObjectRoleExpression* R, const TDLConceptExpression* C ) { return record(new TDLConceptObjectForall(R,C)); } /// get min cardinality restriction wrt number N, an object role R and a concept C TDLConceptExpression* MinCardinality ( unsigned int n, const TDLObjectRoleExpression* R, const TDLConceptExpression* C ) { return record(new TDLConceptObjectMinCardinality(n,R,C)); } /// get max cardinality restriction wrt number N, an object role R and a concept C TDLConceptExpression* MaxCardinality ( unsigned int n, const TDLObjectRoleExpression* R, const TDLConceptExpression* C ) { return record(new TDLConceptObjectMaxCardinality(n,R,C)); } /// get exact cardinality restriction wrt number N, an object role R and a concept C TDLConceptExpression* Cardinality ( unsigned int n, const TDLObjectRoleExpression* R, const TDLConceptExpression* C ) { return record(new TDLConceptObjectExactCardinality(n,R,C)); } /// get value restriction wrt a data role R and a data value V TDLConceptExpression* Value ( const TDLDataRoleExpression* R, const TDLDataValue* V ) { return record(new TDLConceptDataValue(R,V)); } /// get existential restriction wrt a data role R and a data expression E TDLConceptExpression* Exists ( const TDLDataRoleExpression* R, const TDLDataExpression* E ) { return record(new TDLConceptDataExists(R,E)); } /// get universal restriction wrt a data role R and a data expression E TDLConceptExpression* Forall ( const TDLDataRoleExpression* R, const TDLDataExpression* E ) { return record(new TDLConceptDataForall(R,E)); } /// get min cardinality restriction wrt number N, a data role R and a data expression E TDLConceptExpression* MinCardinality ( unsigned int n, const TDLDataRoleExpression* R, const TDLDataExpression* E ) { return record(new TDLConceptDataMinCardinality(n,R,E)); } /// get max cardinality restriction wrt number N, a data role R and a data expression E TDLConceptExpression* MaxCardinality ( unsigned int n, const TDLDataRoleExpression* R, const TDLDataExpression* E ) { return record(new TDLConceptDataMaxCardinality(n,R,E)); } /// get exact cardinality restriction wrt number N, a data role R and a data expression E TDLConceptExpression* Cardinality ( unsigned int n, const TDLDataRoleExpression* R, const TDLDataExpression* E ) { return record(new TDLConceptDataExactCardinality(n,R,E)); } // individuals /// get named individual TDLIndividualExpression* Individual ( const std::string& name ) { return NS_I.insert(name); } // object roles /// get TOP object role TDLObjectRoleExpression* ObjectRoleTop ( void ) const { return ORTop; } /// get BOTTOM object role TDLObjectRoleExpression* ObjectRoleBottom ( void ) const { return ORBottom; } /// get named object role TDLObjectRoleExpression* ObjectRole ( const std::string& name ) { return NS_OR.insert(name); } /// get an inverse of a given object role expression R TDLObjectRoleExpression* Inverse ( const TDLObjectRoleExpression* R ) { return InverseRoleCache.get(R); } /// get a role chain corresponding to R1 o ... o Rn; take the arguments from the last argument list TDLObjectRoleComplexExpression* Compose ( void ) { return record(new TDLObjectRoleChain(getArgList())); } /// get a expression corresponding to R projected from C TDLObjectRoleComplexExpression* ProjectFrom ( const TDLObjectRoleExpression* R, const TDLConceptExpression* C ) { return record(new TDLObjectRoleProjectionFrom(R,C)); } /// get a expression corresponding to R projected into C TDLObjectRoleComplexExpression* ProjectInto ( const TDLObjectRoleExpression* R, const TDLConceptExpression* C ) { return record(new TDLObjectRoleProjectionInto(R,C)); } // data roles /// get TOP data role TDLDataRoleExpression* DataRoleTop ( void ) const { return DRTop; } /// get BOTTOM data role TDLDataRoleExpression* DataRoleBottom ( void ) const { return DRBottom; } /// get named data role TDLDataRoleExpression* DataRole ( const std::string& name ) { return NS_DR.insert(name); } // data expressions /// get TOP data element TDLDataExpression* DataTop ( void ) const { return DTop; } /// get BOTTOM data element TDLDataExpression* DataBottom ( void ) const { return DBottom; } /// get named data type TDLDataTypeName* DataType ( const std::string& name ) { return NS_DT.insert(name); } /// get basic string data type TDLDataTypeName* getStrDataType ( void ) { return DataType(TDataTypeManager::getStrTypeName()); } /// get basic integer data type TDLDataTypeName* getIntDataType ( void ) { return DataType(TDataTypeManager::getIntTypeName()); } /// get basic floating point data type TDLDataTypeName* getRealDataType ( void ) { return DataType(TDataTypeManager::getRealTypeName()); } /// get basic boolean data type TDLDataTypeName* getBoolDataType ( void ) { return DataType(TDataTypeManager::getBoolTypeName()); } /// get basic date-time data type TDLDataTypeName* getTimeDataType ( void ) { return DataType(TDataTypeManager::getTimeTypeName()); } /// get basic boolean data type TDLDataTypeRestriction* RestrictedType ( TDLDataTypeExpression* type, const TDLFacetExpression* facet ) { TDLDataTypeRestriction* ret = dynamic_cast(type); if ( ret == NULL ) { // get a type and build an appropriate restriction of it TDLDataTypeName* hostType = dynamic_cast(type); fpp_assert ( hostType != NULL ); ret = record(new TDLDataTypeRestriction(hostType)); } ret->add(facet); return ret; } /// get data value with given VALUE and TYPE; // FIXME!! now change the type to the basic type of the given one // That is, value of a type positiveInteger will be of a type Integer const TDLDataValue* DataValue ( const std::string& value, TDLDataTypeExpression* type ) { return getBasicDataType(type)->getValue(value); } /// get negation of a data expression E TDLDataExpression* DataNot ( const TDLDataExpression* E ) { return record(new TDLDataNot(E)); } /// get an n-ary data conjunction expression; take the arguments from the last argument list TDLDataExpression* DataAnd ( void ) { return record(new TDLDataAnd(getArgList())); } /// get an n-ary data disjunction expression; take the arguments from the last argument list TDLDataExpression* DataOr ( void ) { return record(new TDLDataOr(getArgList())); } /// get an n-ary data one-of expression; take the arguments from the last argument list TDLDataExpression* DataOneOf ( void ) { return record(new TDLDataOneOf(getArgList())); } /// get minInclusive facet with a given VALUE const TDLFacetExpression* FacetMinInclusive ( const TDLDataValue* V ) { return record(new TDLFacetMinInclusive(V)); } /// get minExclusive facet with a given VALUE const TDLFacetExpression* FacetMinExclusive ( const TDLDataValue* V ) { return record(new TDLFacetMinExclusive(V)); } /// get maxInclusive facet with a given VALUE const TDLFacetExpression* FacetMaxInclusive ( const TDLDataValue* V ) { return record(new TDLFacetMaxInclusive(V)); } /// get maxExclusive facet with a given VALUE const TDLFacetExpression* FacetMaxExclusive ( const TDLDataValue* V ) { return record(new TDLFacetMaxExclusive(V)); } }; // TExpressionManager inline TDLObjectRoleExpression* TExpressionManager::TInverseRoleCache::build ( const TDLObjectRoleExpression* tail ) { return pManager->record(new TDLObjectRoleInverse(tail)); } inline TDLConceptExpression* TExpressionManager::TOneOfCache::build ( const TDLIndividualExpression* tail ) { pManager->newArgList(); pManager->addArg(tail); return pManager->record(new TDLConceptOneOf(pManager->getArgList())); } #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/dltree.cpp0000644000000000000000000002340312112642405017341 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2012 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include #include "dltree.h" #include "fpp_assert.h" #include "tDataEntry.h" #include "tRole.h" /// create entry for the role R DLTree* createRole ( TRole* R ) { return createEntry ( R->isDataRole() ? DNAME : RNAME, R ); } /// create inverse of role R DLTree* createInverse ( DLTree* R ) { fpp_assert ( R != NULL ); // sanity check switch ( R->Element().getToken() ) { case INV: // R-- = R { DLTree* p = clone(R->Left()); deleteTree(R); return p; } case RNAME: // object role name if ( unlikely(isTopRole(R)) || unlikely(isBotRole(R)) ) return R; // top/bottom roles are inverses of themselves return new DLTree ( TLexeme(INV), R ); default: // no other elements can have inverses fpp_unreachable(); } } /// create negation of given formula DLTree* createSNFNot ( DLTree* C ) { fpp_assert ( C != NULL ); // sanity check if ( C->Element() == BOTTOM ) { // \not F = T deleteTree(C); return createTop(); } if ( C->Element() == TOP ) { // \not T = F deleteTree(C); return createBottom(); } if ( C->Element () == NOT ) { // \not\not C = C DLTree* p = clone(C->Left()); deleteTree(C); return p; } // general case return new DLTree ( TLexeme(NOT), C ); } /// create conjunction of given formulas DLTree* createSNFAnd ( DLTree* C, DLTree* D ) { // try to simplify conjunction if ( C == NULL ) // single element return D; if ( D == NULL ) return C; if ( C->Element() == TOP || // T\and D = D D->Element() == BOTTOM ) // C\and F = F { deleteTree(C); return D; } if ( D->Element() == TOP || // C\and T = C C->Element() == BOTTOM ) // F\and D = F { deleteTree(D); return C; } // no simplification possible -- return actual conjunction return new DLTree ( TLexeme(AND), C, D ); } static bool containsC ( DLTree* C, DLTree* D ) { switch ( C->Element().getToken() ) { case CNAME: return equalTrees ( C, D ); case AND: return containsC ( C->Left(), D ) || containsC ( C->Right(), D ); default: return false; } } DLTree* createSNFReducedAnd ( DLTree* C, DLTree* D ) { if ( C == NULL || D == NULL ) return createSNFAnd ( C, D ); if ( D->Element().getToken() == CNAME && containsC ( C, D ) ) { deleteTree(D); return C; } else if ( D->Element().getToken() == AND ) { C = createSNFReducedAnd ( C, D->Left() ); C = createSNFReducedAnd ( C, D->Right() ); delete D; // just an AND return C; } else // can't optimise return createSNFAnd ( C, D ); } // Semantic Locality checking support. DO NOT used in usual reasoning /// @return true iff a data range DR is semantically equivalent to TOP. FIXME!! good approximation for now static bool isSemanticallyDataTop ( DLTree* dr ) { return dr->Element().getToken() == TOP; } /// @return true iff a data range DR is semantically equivalent to BOTTOM. FIXME!! good approximation for now static bool isSemanticallyDataBottom ( DLTree* dr ) { return dr->Element().getToken() == BOTTOM; } /// @return true iff the cardinality of a given data range DR is greater than N. FIXME!! good approximation for now static bool isDataRangeBigEnough ( DLTree* dr ATTR_UNUSED, unsigned int n ATTR_UNUSED ) { return true; } /// simplify universal restriction with top data role static DLTree* simplifyDataTopForall ( DLTree* dr ) { TreeDeleter td(dr); // if the filler (dr) is TOP (syntactically or semantically), then the forall is top if ( isSemanticallyDataTop(dr) ) return createTop(); // in any other case the attempt to restrict the data domain will fail return createBottom(); } /// simplify minimal cardinality restriction with top data role static DLTree* simplifyDataTopLE ( unsigned int n, DLTree* dr ) { TreeDeleter td(dr); // if the filler (dr) is BOTTOM (syntactically or semantically), then the LE is top if ( isSemanticallyDataBottom(dr) ) return createTop(); // if the size of a filler is smaller than the cardinality, then it's always possible to make a restriction if ( !isDataRangeBigEnough ( dr, n ) ) return createTop(); // in any other case the attempt to restrict the data domain will fail return createBottom(); } /// create universal restriction of given formulas (\AR.C) DLTree* createSNFForall ( DLTree* R, DLTree* C ) { if ( C->Element() == TOP ) // \AR.T = T { deleteTree(R); return C; } if ( unlikely(isBotRole(R)) ) { // \A Bot.C = T deleteTree(R); deleteTree(C); return createTop(); } if ( unlikely(isTopRole(R)) && resolveRole(R)->isDataRole() ) { deleteTree(R); return simplifyDataTopForall(C); } // no simplification possible return new DLTree ( TLexeme(FORALL), R, C ); } /// create at-most (LE) restriction of given formulas (<= n R.C) DLTree* createSNFLE ( unsigned int n, DLTree* R, DLTree* C ) { if ( C->Element() == BOTTOM ) { // <= n R.F -> T; deleteTree(R); deleteTree(C); return createTop(); } if ( n == 0 ) // <= 0 R.C -> \AR.\not C return createSNFForall ( R, createSNFNot(C) ); if ( unlikely(isBotRole(R)) ) { // <=n Bot.C = T deleteTree(R); deleteTree(C); return createTop(); } if ( unlikely(isTopRole(R)) && resolveRole(R)->isDataRole() ) { deleteTree(R); return simplifyDataTopLE ( n, C ); } return new DLTree ( TLexeme ( LE, n ), R, C ); } /// create at-least (GE) restriction of given formulas (>= n R.C) DLTree* createSNFGE ( unsigned int n, DLTree* R, DLTree* C ) { if ( n == 0 ) { // >= 0 R.C -> T deleteTree(R); deleteTree(C); return createTop(); } if ( C->Element() == BOTTOM ) { // >=n R.F -> F deleteTree(R); return C; } else // >= n R.C -> !<= (n-1) R.C return createSNFNot ( createSNFLE ( n-1 , R, C ) ); } //******************************************************************************************** //** equalTrees implementation //******************************************************************************************** bool equalTrees ( const DLTree* t1, const DLTree* t2 ) { // empty trees are equal if ( t1 == NULL && t2 == NULL ) return true; // empty and non-empty trees are not equal if ( t1 == NULL || t2 == NULL ) return false; // non-empty trees are checked recursively return ( t1->Element() == t2->Element() ) && equalTrees ( t1->Left(), t2->Left() ) && equalTrees ( t1->Right(), t2->Right() ); } bool isSubTree ( const DLTree* t1, const DLTree* t2 ) { if ( t1 == NULL || t1->Element() == TOP ) return true; if ( t2 == NULL ) return false; if ( t1->Element() == AND ) return isSubTree ( t1->Left(), t2 ) && isSubTree ( t1->Right(), t2 ); // t1 is a single elem, t2 is a (probably) AND-tree if ( t2->Element() == AND ) return isSubTree ( t1, t2->Left() ) || isSubTree ( t1, t2->Right() ); // t1 and t2 are non-single elements return equalTrees(t1,t2); } //******************************************************************************************** //** OnlySNF realization //******************************************************************************************** bool isSNF ( const DLTree* t ) { if ( t == NULL ) return true; switch ( t -> Element (). getToken () ) { case TOP: case BOTTOM: case NAME: case DATAEXPR: case NOT: case INV: case AND: case FORALL: case LE: case SELF: case RCOMPOSITION: case PROJFROM: case PROJINTO: return ( isSNF (t->Left()) && isSNF (t->Right()) ); default: return false; } } //******************************************************************************************** const char* TokenName ( Token t ) { switch ( t ) { case TOP: return "*TOP*"; case BOTTOM: return "*BOTTOM*"; case CNAME: return "cname"; case INAME: return "iname"; case RNAME: return "rname"; case DNAME: return "dname"; case DATAEXPR: return "dataexpr"; case INV: return "inv"; case OR: return "or"; case AND: return "and"; case NOT: return "not"; case EXISTS: return "some"; case FORALL: return "all"; case GE: return "at-least"; case LE: return "at-most"; case RCOMPOSITION: return "compose"; case SELF: return "self-ref"; case PROJINTO: return "project_into"; case PROJFROM: return "project_from"; default: std::cerr << "token " << t << "has no name"; fpp_unreachable(); return NULL; }; } std::ostream& operator << ( std::ostream& o, const DLTree *form ) { if ( form == NULL ) return o; const TLexeme& lex = form->Element(); switch ( lex.getToken() ) { case TOP: case BOTTOM: o << ' ' << TokenName(lex.getToken()); break; case RNAME: case DNAME: case CNAME: o << ' ' << lex.getName(); break; case INAME: o << " (one-of " << lex.getName() << ')'; break; case DATAEXPR: static_cast(lex.getNE())->printLISP(o); break; case NOT: case INV: case SELF: o << " (" << TokenName (lex.getToken()) << form->Left() << ')'; break; case AND: case OR: case EXISTS: case FORALL: case RCOMPOSITION: case PROJINTO: case PROJFROM: o << " (" << TokenName (lex.getToken()) << form->Left() << form->Right() << ')'; break; case GE: case LE: o << " (" << TokenName (lex.getToken()) << ' ' << lex.getData() << form->Left() << form->Right() << ')'; break; default: break; } return o; } //******************************************************************************************** FaCTpp-src-v1.6.2~dfsg/src/Kernel/CWDArray.h0000644000000000000000000001032312112642405017140 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2012 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef CWDARRAY_H #define CWDARRAY_H #include #include // find #include "globaldef.h" #include "growingArray.h" #include "ConceptWithDep.h" enum addConceptResult { acrClash, acrExist, acrDone }; class TRestorer; /// array of concepts with dep-set, which may be viewed as a label of a completion-graph class CWDArray { protected: // internal typedefs /// base type typedef growingArray ConceptSet; /// RW iterator typedef ConceptSet::iterator iterator; /// restorer for the merge friend class UnMerge; public: // type interface /// class for saving one label class SaveState { public: /// end pointer of the label size_t ep; public: // interface /// empty c'tor SaveState ( void ) {} /// copy c'tor SaveState ( const SaveState& node ) : ep(node.ep) {} /// empty d'tor ~SaveState ( void ) {} }; // SaveState /// const iterator on label typedef ConceptSet::const_iterator const_iterator; protected: // members /// array of concepts together with dep-sets ConceptSet Base; public: // interface /// init/clear label with given size void init ( unsigned int size ) { Base.reserve(size); Base.clear(); } /// empty c'tor CWDArray ( void ) {} /// copy c'tor CWDArray ( const CWDArray& copy ) : Base(copy.Base) {} /// assignment CWDArray& operator = ( const CWDArray& copy ) { Base = copy.Base; return *this; } /// empty d'tor ~CWDArray ( void ) {} //---------------------------------------------- // Label access interface //---------------------------------------------- // label iterators /// begin RO iterator const_iterator begin ( void ) const { return Base.begin(); } /// end RO iterator const_iterator end ( void ) const { return Base.end(); } // add concept /// adds concept P to a label void add ( const ConceptWDep& p ) { Base.add(p); } /// update concept BP with a dep-set DEP; @return the appropriate restorer TRestorer* updateDepSet ( BipolarPointer bp, const DepSet& dep ); // access concepts /// check whether label contains BP (ignoring dep-set) bool contains ( BipolarPointer bp ) const { return std::find ( begin(), end(), bp ) != end(); } /// get the concept by given index in the node's label const ConceptWDep& getConcept ( int n ) const { return Base[n]; } //---------------------------------------------- // Blocking support //---------------------------------------------- /// check whether LABEL is a superset of a current one bool operator <= ( const CWDArray& label ) const { for ( const_iterator p = begin(), p_end = end(); p < p_end; ++p ) if ( !label.contains(p->bp()) ) return false; return true; } /// check whether LABEL is a subset of a current one bool operator >= ( const CWDArray& label ) const { return label <= *this; } /// check whether LABEL is the same as a current one bool operator == ( const CWDArray& label ) const { return (*this <= label) && (label <= *this); } //---------------------------------------------- // Save/restore interface //---------------------------------------------- /// save label using given SS void save ( SaveState& ss ) const { ss.ep = Base.size(); } /// restore label to given LEVEL using given SS void restore ( const SaveState& ss, unsigned int level ); //---------------------------------------------- // Output //---------------------------------------------- /// print the whole label void print ( std::ostream& o ) const; }; // CWDArray #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/tConcept.h0000644000000000000000000002214212112642405017305 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2011 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef TCONCEPT_H #define TCONCEPT_H #include #include "taxNamEntry.h" #include "tNameSet.h" #include "tLabeller.h" #include "dltree.h" #include "dlVertex.h" #include "LogicFeature.h" /// type of concept wrt classifiability enum CTTag { /// not specified cttUnspecified, /// concept with all parents -- TCD cttTrueCompletelyDefined, /// concept w/o any told subsumers cttOrphan, /// concept with all parents -- LCD, TCD or Orptans cttLikeCompletelyDefined, /// concept with non-primitive TS cttHasNonPrimitiveTS, /// any other primitive concept cttRegular, /// any non-primitive concept (except synonyms) cttNonPrimitive, }; inline char getCTTagName ( CTTag tag ) { switch(tag) { case cttUnspecified: return 'u'; case cttTrueCompletelyDefined: return 'T'; case cttOrphan: return 'O'; case cttLikeCompletelyDefined: return 'L'; case cttHasNonPrimitiveTS: return 'N'; case cttRegular: return 'r'; case cttNonPrimitive: return 'n'; default: return char(); } } class TRole; /// class for representing concept-like entries class TConcept: public ClassifiableEntry { private: // members /// label to use in relevant-only checks TLabeller::LabelType rel; protected: // types /// set of extra rules typedef std::vector ERSet; /// set of roles typedef std::set RoleSSet; public: // type interface /// extra rules iterators typedef ERSet::const_iterator er_iterator; public: // members /// description of a concept DLTree* Description; /// classification type of concept: completely defined (true- or like-), no TS, other CTTag classTag; /// depth of the concept wrt told subsumers unsigned int tsDepth; /// pointer to the entry in DAG with concept name BipolarPointer pName; /// pointer to the entry in DAG with concept definition BipolarPointer pBody; /// features for C LogicFeatures posFeatures; /// features for ~C LogicFeatures negFeatures; /// all extra rules for a given concept ERSet erSet; private: // no copy /// no copy c'tor TConcept ( const TConcept& ); /// no assignment TConcept& operator = ( const TConcept& ); protected: // methods // classification TAGs manipulation /// calculate value of classification TAG based on told subsumers. WARNING: no TS cycles allowed CTTag determineClassTag ( void ); /// @return true iff description contains references to THIS concept bool hasSelfInDesc ( const DLTree* p ) const; /// @return copy of P with every entry of THIS replaced with true DLTree* replaceSelfWithConst ( const DLTree* p ) const; // told subsumers interface /// adds concept as a told subsumer of current one; @return value for CDC analisys bool addToldSubsumer ( TConcept* p ) { if ( p != this ) { addParentIfNew(p); if ( p->isSingleton() || p->isHasSP() ) setHasSP(); // this has singleton parent } // if non-primitive concept was found in a description, it's not CD return p->isPrimitive(); } /// init told subsumers of the concept by given DESCription; @return TRUE iff concept is CD bool initToldSubsumers ( const DLTree* desc, RoleSSet& RolesProcessed ); /// init told subsumers of the concept by given DESCription; @return TRUE iff concept is CD bool initToldSubsumers ( const DLTree* desc ) { RoleSSet RolesProcessed; return initToldSubsumers ( desc, RolesProcessed ); } /// find told subsumers by given role's domain void SearchTSbyRole ( const TRole* R, RoleSSet& RolesProcessed ); /// find told subsumers by given role and its supers domains void SearchTSbyRoleAndSupers ( const TRole* R, RoleSSet& RolesProcessed ); public: // methods /// the only c'tor explicit TConcept ( const std::string& name ) : ClassifiableEntry (name) , rel(0) , Description(NULL) , classTag(cttUnspecified) , tsDepth(0) , pName (bpINVALID) , pBody (bpINVALID) { setPrimitive(); } /// d'tor virtual ~TConcept ( void ) { deleteTree(Description); } /// clear all info of the concept. Use it in removeConcept() void clear ( void ); // simple rules support /// add index of a simple rule in TBox to the ER set void addExtraRule ( unsigned int p ) { erSet.push_back(p); setCompletelyDefined(false); } /// check if a concept is in a disjoint relation with anything bool hasExtraRules ( void ) const { return !erSet.empty(); } /// iterator for accessing DJ elements er_iterator er_begin ( void ) const { return erSet.begin(); } /// iterator for accessing DJ elements er_iterator er_end ( void ) const { return erSet.end(); } // classification TAGs manipulation /// get value of tag as it is CTTag getClassTag ( void ) const { return classTag; } /// get value of a tag; determine it if unset CTTag getClassTag ( void ) { if ( classTag == cttUnspecified ) classTag = determineClassTag(); return classTag; } // description manipulation /// add concept expression to concept description void addDesc ( DLTree* Desc ); /// remove concept from its own definition (like in case C [= (or C ...) void removeSelfFromDescription ( void ) { if ( hasSelfInDesc(Description) ) { DLTree* desc = Description; Description = replaceSelfWithConst(desc); deleteTree(desc); } initToldSubsumers(); } /// remove concept description (to save space) void removeDescription ( void ) { // save Synonym value deleteTree(Description); Description = NULL; } /// check whether it is possible to init this as a non-primitive concept with DESC bool canInitNonPrim ( DLTree* desc ) { if ( Description == NULL ) return true; if ( isNonPrimitive() && equalTrees(Description,desc) ) return true; return false; } /// switch primitive concept to non-primitive with new definition; @return old definition DLTree* makeNonPrimitive ( DLTree* desc ) { DLTree* ret = Description; Description = desc; setPrimitive(false); return ret; } /// init told subsumers of the concept by it's description virtual void initToldSubsumers ( void ) { toldSubsumers.clear(); clearHasSP(); // normalise description if the only parent is TOP if ( isPrimitive() && Description && Description->Element() == TOP ) removeDescription(); bool CD = !hasExtraRules() && isPrimitive(); // not a completely defined if there are extra rules if ( Description != NULL ) // init (additional) told subsumers from definition CD &= initToldSubsumers(Description); setCompletelyDefined(CD); } /// init TOP told subsumer if necessary void setToldTop ( TConcept* top ) { if ( Description == NULL && !hasToldSubsumers() ) addParent(top); } /// calculate depth wrt told subsumers; return the depth unsigned int calculateTSDepth ( void ); // used in the start procedure of SAT/SUBSUME tests BipolarPointer resolveId ( void ) const; // returns either pName or pBody /// register a Primitive flag FPP_ADD_FLAG(Primitive,0x10); /// register a HasSingletonParent flag FPP_ADD_FLAG(HasSP,0x20); /// register a Nominal flag FPP_ADD_FLAG(Nominal,0x40); /// register a Singleton flag FPP_ADD_FLAG(Singleton,0x80); // concept non-primitivity methods /// check if concept is non-primitive concept bool isNonPrimitive ( void ) const { return !isPrimitive(); } // relevance part /// is given concept relevant to given Labeller's state bool isRelevant ( const TLabeller& lab ) const { return lab.isLabelled(rel); } /// make given concept relevant to given Labeller's state void setRelevant ( const TLabeller& lab ) { lab.set(rel); } /// make given concept irrelevant to given Labeller's state void dropRelevant ( const TLabeller& lab ) { lab.clear(rel); } // save/load interface; implementation is in SaveLoad.cpp /// save entry virtual void Save ( std::ostream& o ) const; /// load entry virtual void Load ( std::istream& i ); }; // TConcept /// Class for comparison of TConcepts wrt told subsumer depth class TSDepthCompare { public: bool operator() ( const TConcept* p, const TConcept* q ) const { return p->tsDepth < q->tsDepth; } }; // TSDepthCompare //---------------------------------------------------------------------------- //-- implementation //---------------------------------------------------------------------------- inline BipolarPointer TConcept :: resolveId ( void ) const { // check for Top/Bottom if ( pName == bpINVALID ) return pBody; if ( isSynonym() ) // resolve synonyms return resolveSynonym(this)->resolveId(); return pName; // return concept's name } #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/tExpressionManager.cpp0000644000000000000000000000371612112642405021705 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2010-2011 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "tExpressionManager.h" TExpressionManager :: TExpressionManager ( void ) : CTop(new TDLConceptTop) , CBottom(new TDLConceptBottom) , DTop(new TDLDataTop) , DBottom(new TDLDataBottom) , ORTop(new TDLObjectRoleTop) , ORBottom(new TDLObjectRoleBottom) , DRTop(new TDLDataRoleTop) , DRBottom(new TDLDataRoleBottom) , InverseRoleCache(this) , OneOfCache(this) { } TExpressionManager :: ~TExpressionManager ( void ) { clear(); delete CTop; delete CBottom; delete ORTop; delete ORBottom; delete DRTop; delete DRBottom; delete DTop; delete DBottom; } void TExpressionManager :: clear ( void ) { // clear all the names but the datatypes NS_C.clear(); NS_I.clear(); NS_OR.clear(); NS_DR.clear(); InverseRoleCache.clear(); OneOfCache.clear(); // delete all the recorded references for ( std::vector::iterator p = RefRecorder.begin(), p_end = RefRecorder.end(); p < p_end; ++p ) delete *p; RefRecorder.clear(); } /// clear the TNamedEntry cache for all elements of all name-sets void TExpressionManager :: clearNameCache ( void ) { clearNameCache(NS_C); clearNameCache(NS_I); clearNameCache(NS_OR); clearNameCache(NS_DR); clearNameCache(NS_DT); } FaCTpp-src-v1.6.2~dfsg/src/Kernel/CGLabel.h0000644000000000000000000001461512112642405016765 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2006-2011 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef CGLABEL_H #define CGLABEL_H #include "CWDArray.h" #include "dlVertex.h" // for DagTag /// class implementing a label in a node of a completion graph class CGLabel { public: // type interface /// RO iterator on label typedef CWDArray::const_iterator const_iterator; public: // external classes /// class for save/restore class SaveState { public: /// states for simple-, complex- and extra labels CWDArray::SaveState sc, cc; public: // interface /// empty c'tor SaveState ( void ) {} /// copy c'tor SaveState ( const SaveState& ss ) : sc(ss.sc), cc(ss.cc) {} /// empty d'tor ~SaveState ( void ) {} }; // SaveState protected: // members /// all simple concepts, labelled a node CWDArray scLabel; /// all complex concepts (ie, FORALL, GE), labelled a node CWDArray ccLabel; protected: // methods /// @return true iff TAG represents complex concept static bool isComplexConcept ( DagTag tag ) { switch(tag) { case dtForall: case dtLE: case dtIrr: case dtNN: case dtChoose: return true; default: return false; } } public: // interface /// init newly created node void init ( void ); /// empty c'tor CGLabel ( void ) {} /// copy c'tor CGLabel ( const CGLabel& copy ) : scLabel(copy.scLabel), ccLabel(copy.ccLabel) {} /// assignment CGLabel& operator = ( const CGLabel& copy ) { scLabel = copy.scLabel; ccLabel = copy.ccLabel; return *this; } /// empty d'tor ~CGLabel ( void ) {} //---------------------------------------------- // Label access interface //---------------------------------------------- // label iterators /// begin() iterator for a label with simple concepts const_iterator begin_sc ( void ) const { return scLabel.begin(); } /// end() iterator for a label with simple concepts const_iterator end_sc ( void ) const { return scLabel.end(); } /// begin() iterator for a label with complex concepts const_iterator begin_cc ( void ) const { return ccLabel.begin(); } /// end() iterator for a label with complex concepts const_iterator end_cc ( void ) const { return ccLabel.end(); } //---------------------------------------------- // Label access interface //---------------------------------------------- /// get (RW) label associated with the concepts defined by TAG CWDArray& getLabel ( DagTag tag ) { return isComplexConcept(tag) ? ccLabel : scLabel; } /// get (RO) label associated with the concepts defined by TAG const CWDArray& getLabel ( DagTag tag ) const { return isComplexConcept(tag) ? ccLabel : scLabel; } // TODO table interface /// get ToDoEntry offset by given SC labels' iterator int getSCOffset ( const_iterator p ) const { return p-begin_sc(); } /// get ToDoEntry offset by given CC labels' iterator int getCCOffset ( const_iterator p ) const { return -(p-begin_cc()+1); } /// get the index of the latest (ie just inserted) concept in the label int getLast ( DagTag tag ) const { if ( isComplexConcept(tag) ) return getCCOffset(end_cc()-1); // complex concept else return getSCOffset(end_sc()-1); // simple concept } /// get the concept by given index in the node's label const ConceptWDep& getConcept ( int n ) const { if ( n < 0 ) return ccLabel.getConcept(-n-1); else return scLabel.getConcept(n); } /// get CC offset of a complex concept BP that appears in the label int getCCOffset ( BipolarPointer bp ) const { for ( const_iterator p = begin_cc(), p_end = end_cc(); p < p_end; ++p ) if ( *p == bp ) return getCCOffset(p); // BP should appear in the label fpp_unreachable(); return 0; } // check if node is labelled by given concept /// check whether node is labelled by (arbitrary) concept P bool contains ( BipolarPointer p ) const; /// check whether node is labelled by simple concept P bool containsSC ( BipolarPointer p ) const { return scLabel.contains(p); } /// check whether node is labelled by complex concept P bool containsCC ( BipolarPointer p ) const { return ccLabel.contains(p); } //---------------------------------------------- // Blocking support //---------------------------------------------- /// check whether LABEL is a superset of a current one bool operator <= ( const CGLabel& label ) const { return ( scLabel <= label.scLabel ) && ( ccLabel <= label.ccLabel ); } /// check whether LABEL is a subset of a current one bool operator >= ( const CGLabel& label ) const { return label <= *this; } /// check whether LABEL is the same as a current one bool operator == ( const CGLabel& label ) const { return (*this <= label) && (label <= *this); } //---------------------------------------------- // Save/restore interface //---------------------------------------------- /// save label using given SS void save ( SaveState& ss ) const { scLabel.save(ss.sc); ccLabel.save(ss.cc); } /// restore label to given LEVEL using given SS void restore ( const SaveState& ss, unsigned int level ) { scLabel.restore(ss.sc,level); ccLabel.restore(ss.cc,level); } //---------------------------------------------- // Output //---------------------------------------------- /// print the whole label void print ( std::ostream& o ) const { scLabel.print(o); ccLabel.print(o); } }; // CGLabel inline void CGLabel :: init ( void ) { // init label with reasonable size scLabel.init(8); // FIXME!! correct size later on ccLabel.init(4); // FIXME!! correct size later on } inline bool CGLabel :: contains ( BipolarPointer p ) const { #ifdef ENABLE_CHECKING fpp_assert ( isCorrect(p) ); // sanity checking #endif switch(p) { case bpTOP: return true; case bpBOTTOM: return false; default: return containsSC(p) || containsCC(p); } } #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/tNECollection.h0000644000000000000000000001064712112642405020237 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2005-2012 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef TNECOLLECTION_H #define TNECOLLECTION_H #include #include "globaldef.h" #include "tNamedEntry.h" #include "tNameSet.h" #include "eFPPCantRegName.h" /** class for collect TNamedEntry'es together. Template parameter should be inherited from TNamedEntry. Implemented as vector of T*, with Base[i]->getId() == i. **/ template class TNECollection { protected: // typedefs typedef std::vector BaseType; public: // typedefs typedef typename BaseType::iterator iterator; typedef typename BaseType::const_iterator const_iterator; protected: // members /// vector of elements BaseType Base; /// nameset to hold the elements TNameSet NameSet; /// name of the type std::string TypeName; /// flag to lock the nameset (ie, prohibit to add new names there) bool locked; /// if true, allow fresh entities even when locked. treat them as System in this case bool allowFresh; protected: // methods /// virtual method for additional tuning of newly created element virtual void registerNew ( T* p ATTR_UNUSED ) {} /// register new element in a collection; return this element T* registerElem ( T* p ) { p->setId(Base.size()); Base.push_back(p); registerNew(p); return p; } public: // interface /// c'tor: clear 0-th element TNECollection ( const std::string& name ) : TypeName(name) , locked(false) , allowFresh(false) { Base.push_back(NULL); } /// empty d'tor: all elements will be deleted in other place virtual ~TNECollection ( void ) {} // locked interface /// check if collection is locked bool isLocked ( void ) const { return locked; } /// set LOCKED value to a VAL; @return old value of LOCKED bool setLocked ( bool val ) { bool old = locked; locked = val; return old; } /// set FRESH value to a VAL; @return the old value bool setAllowFresh ( bool val ) { bool old = allowFresh; allowFresh = val; return old; } // add/remove elements /// check if entry with a NAME is registered in given collection bool isRegistered ( const std::string& name ) const { return NameSet.get(name) != NULL; } /// get entry by NAME from the collection; register it if necessary T* get ( const std::string& name ) { T* p = NameSet.get(name); // check if name is already defined if ( p != NULL ) return p; // check if it is possible to insert name if ( isLocked() && !allowFresh ) throw EFPPCantRegName ( name, TypeName ); // create name in name set, and register it p = registerElem(NameSet.add(name)); // if fresh entity -- mark it System if ( isLocked() ) { p->setSystem(); if ( dynamic_cast(p) != NULL ) dynamic_cast(p)->setNonClassifiable(); } return p; } /// remove given entry from the collection; @return true iff it was NOT the last entry. bool Remove ( T* p ) { if ( !isRegistered(p->getName()) ) // not in a name-set: just delete it { delete p; return false; } // we might delete vars in order (6,7), so the resize should be done to 6 if ( p->getId() > 0 && Base.size() > (size_t)p->getId() ) Base.resize(p->getId()); NameSet.remove(p->getName()); return false; } // access to elements iterator begin ( void ) { return Base.begin()+1; } const_iterator begin ( void ) const { return Base.begin()+1; } iterator end ( void ) { return Base.end(); } const_iterator end ( void ) const { return Base.end(); } size_t size ( void ) const { return Base.size()-1; } // save/load interface; implementation is in SaveLoad.cpp /// Save all the objects in the collection void Save ( std::ostream& o ) const; /// Load all the objects into the collection void Load ( std::istream& i ); }; // TNECollection #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/tLexeme.h0000644000000000000000000000470012112642405017131 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2011 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef TLEXEME_H #define TLEXEME_H #include "grammar.h" #include "tNamedEntry.h" /// Lexeme (smallest lexical element) in a syntax tree class TLexeme { private: // members /// Lexeme's Token Token token; /// pointer to information (for names) union { TNamedEntry* pNE; unsigned int data; } value; public: // interface /// default c'tor for pointers explicit TLexeme ( Token tok, TNamedEntry* p = NULL ) : token(tok) { value.pNE = p; } /// default c'tor for numbers TLexeme ( Token tok, unsigned int val ) : token(tok) { value.data = val; } /// Copy c'tor TLexeme ( const TLexeme& lex ) : token(lex.token), value(lex.value) {} /// Assignment TLexeme& operator = ( const TLexeme& lex ) { token = lex.token; value = lex.value; return *this; } // access /// get Token of given Lexeme Token getToken ( void ) const { return token; } /// get name pointer of given lexeme TNamedEntry* getNE ( void ) const { return value.pNE; } /// get name pointer of given lexeme const char* getName ( void ) const { return value.pNE->getName(); } /// get data value of given lexeme unsigned int getData ( void ) const { return value.data; } // comparison /// full lexeme comparison (equality) bool operator == ( const TLexeme& lex ) const { return ( token == lex.token && value.data == lex.value.data ); } /// full lexeme comparison (inequality) bool operator != ( const TLexeme& lex ) const { return !( *this == lex ); } /// just token comparison (equality) bool operator == ( Token tok ) const { return ( token == tok ); } /// just token comparison (inequality) bool operator != ( Token tok ) const { return ( token != tok ); } }; // TLexeme #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/DeletelessAllocator.h0000644000000000000000000000255112112642405021462 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2005 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef _DELETELESSALLOCATOR_H #define _DELETELESSALLOCATOR_H #include "growingArrayP.h" /** * Class for the allocator that does not allowed 'delete'. Instead * it allows user to reuse all allocated memory. */ template class DeletelessAllocator: public growingArrayP { public: /// c'tor: do nothing DeletelessAllocator ( void ) {} /// d'tor: do nothing (all done in ~gaP) virtual ~DeletelessAllocator ( void ) {} /// get a new object from the heap T* get ( void ) { this->ensureHeapSize(); return this->Base[this->last++]; } }; // DeletelessAllocator #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/tExpressionPrinterLISP.h0000644000000000000000000002004512112642405022105 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2010-2012 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef TEXPRESSIONPRINTERLISP_H #define TEXPRESSIONPRINTERLISP_H #include #include "tDLExpression.h" class TLISPExpressionPrinter: public DLExpressionVisitor { protected: // members /// main stream std::ostream& o; /// define str-str map typedef std::map SSMap; /// map between OWL datatype names and FaCT++ ones SSMap DTNames; /// helper class for brackets class BR { protected: std::ostream& o; public: BR ( std::ostream& o_, const char* command ) : o(o_) { o << " (" << command; } ~BR () { o << ")"; } }; // BR protected: // methods /// array helper template void printArray ( const TDLNAryExpression& expr ) { for ( typename TDLNAryExpression::iterator p = expr.begin(), p_end = expr.end(); p != p_end; ++p ) (*p)->accept(*this); } /// datatype helper to get a LISP datatype name by a OWL one const char* getDTName ( const char* owlName ) const { SSMap::const_iterator p = DTNames.find(owlName); if ( p != DTNames.end() ) // known name return p->second.c_str(); return owlName; } public: // interface /// init c'tor TLISPExpressionPrinter ( std::ostream& o_ ) : o(o_) { DTNames["http://www.w3.org/1999/02/22-rdf-syntax-ns#PlainLiteral"] = "string"; DTNames["http://www.w3.org/2001/XMLSchema#string"] = "string"; DTNames["http://www.w3.org/2001/XMLSchema#anyURI"] = "string"; DTNames["http://www.w3.org/2001/XMLSchema#integer"] = "number"; DTNames["http://www.w3.org/2001/XMLSchema#int"] = "number"; DTNames["http://www.w3.org/2001/XMLSchema#float"] = "real"; DTNames["http://www.w3.org/2001/XMLSchema#double"] = "real"; DTNames["http://www.w3.org/2001/XMLSchema#real"] = "real"; } /// empty d'tor virtual ~TLISPExpressionPrinter ( void ) {} public: // visitor interface // concept expressions virtual void visit ( const TDLConceptTop& expr ATTR_UNUSED ) { o << " *TOP*"; } virtual void visit ( const TDLConceptBottom& expr ATTR_UNUSED ) { o << " *BOTTOM*"; } virtual void visit ( const TDLConceptName& expr ) { o << " " << expr.getName(); } virtual void visit ( const TDLConceptNot& expr ) { BR b(o,"not"); expr.getC()->accept(*this); } virtual void visit ( const TDLConceptAnd& expr ) { BR b(o,"and"); printArray(expr); } virtual void visit ( const TDLConceptOr& expr ) { BR b(o,"or"); printArray(expr); } virtual void visit ( const TDLConceptOneOf& expr ) { BR b(o,"one-of"); printArray(expr); } virtual void visit ( const TDLConceptObjectSelf& expr ) { BR b(o,"self-ref"); expr.getOR()->accept(*this); } virtual void visit ( const TDLConceptObjectValue& expr ) { BR b(o,"some"); expr.getOR()->accept(*this); BR i(o,"one-of"); expr.getI()->accept(*this); } virtual void visit ( const TDLConceptObjectExists& expr ) { BR b(o,"some"); expr.getOR()->accept(*this); expr.getC()->accept(*this); } virtual void visit ( const TDLConceptObjectForall& expr ) { BR b(o,"all"); expr.getOR()->accept(*this); expr.getC()->accept(*this); } virtual void visit ( const TDLConceptObjectMinCardinality& expr ) { BR b(o,"atleast"); o << " " << expr.getNumber(); expr.getOR()->accept(*this); expr.getC()->accept(*this); } virtual void visit ( const TDLConceptObjectMaxCardinality& expr ) { BR b(o,"atmost"); o << " " << expr.getNumber(); expr.getOR()->accept(*this); expr.getC()->accept(*this); } virtual void visit ( const TDLConceptObjectExactCardinality& expr ) { BR a(o,"and"); { BR b(o,"atleast"); o << " " << expr.getNumber(); expr.getOR()->accept(*this); expr.getC()->accept(*this); } { BR b(o,"atmost"); o << " " << expr.getNumber(); expr.getOR()->accept(*this); expr.getC()->accept(*this); } } virtual void visit ( const TDLConceptDataValue& expr ) { BR b(o,"some"); expr.getDR()->accept(*this); expr.getExpr()->accept(*this); } virtual void visit ( const TDLConceptDataExists& expr ) { BR b(o,"some"); expr.getDR()->accept(*this); expr.getExpr()->accept(*this); } virtual void visit ( const TDLConceptDataForall& expr ) { BR b(o,"all"); expr.getDR()->accept(*this); expr.getExpr()->accept(*this); } virtual void visit ( const TDLConceptDataMinCardinality& expr ) { BR b(o,"atleast"); o << " " << expr.getNumber(); expr.getDR()->accept(*this); expr.getExpr()->accept(*this); } virtual void visit ( const TDLConceptDataMaxCardinality& expr ) { BR b(o,"atmost"); o << " " << expr.getNumber(); expr.getDR()->accept(*this); expr.getExpr()->accept(*this); } virtual void visit ( const TDLConceptDataExactCardinality& expr ) { BR a(o,"and"); { BR b(o,"atleast"); o << " " << expr.getNumber(); expr.getDR()->accept(*this); expr.getExpr()->accept(*this); } { BR b(o,"atmost"); o << " " << expr.getNumber(); expr.getDR()->accept(*this); expr.getExpr()->accept(*this); } } // individual expressions virtual void visit ( const TDLIndividualName& expr ) { o << " " << expr.getName(); } // object role expressions virtual void visit ( const TDLObjectRoleTop& expr ATTR_UNUSED ) { o << " *UROLE*"; } virtual void visit ( const TDLObjectRoleBottom& expr ATTR_UNUSED ) { o << " *EROLE*"; } virtual void visit ( const TDLObjectRoleName& expr ) { o << " " << expr.getName(); } virtual void visit ( const TDLObjectRoleInverse& expr ) { BR b(o,"inv"); expr.getOR()->accept(*this); } virtual void visit ( const TDLObjectRoleChain& expr ) { BR b(o,"compose"); printArray(expr); } virtual void visit ( const TDLObjectRoleProjectionFrom& expr ) { BR b(o,"project_from"); expr.getOR()->accept(*this); expr.getC()->accept(*this); } virtual void visit ( const TDLObjectRoleProjectionInto& expr ) { BR b(o,"project_into"); expr.getOR()->accept(*this); expr.getC()->accept(*this); } // data role expressions virtual void visit ( const TDLDataRoleTop& expr ATTR_UNUSED ) { o << " *UDROLE*"; } virtual void visit ( const TDLDataRoleBottom& expr ATTR_UNUSED ) { o << " *EDROLE*"; } virtual void visit ( const TDLDataRoleName& expr ) { o << " " << expr.getName(); } // data expressions virtual void visit ( const TDLDataTop& expr ATTR_UNUSED ) { o << " *TOP*"; } virtual void visit ( const TDLDataBottom& expr ATTR_UNUSED ) { o << " *BOTTOM*"; } virtual void visit ( const TDLDataTypeName& expr ) { o << " (" << getDTName(expr.getName()) << ")"; } // no need to use a type of a restriction here, as all contains in constants virtual void visit ( const TDLDataTypeRestriction& expr ) { BR b(o,"and"); printArray(expr); } virtual void visit ( const TDLDataValue& expr ) { o << " (" << getDTName(getBasicDataType(const_cast(expr.getExpr()))->getName()) << " " << expr.getName() << ")"; } virtual void visit ( const TDLDataNot& expr ) { BR b(o,"not"); expr.getExpr()->accept(*this); } virtual void visit ( const TDLDataAnd& expr ) { BR b(o,"and"); printArray(expr); } virtual void visit ( const TDLDataOr& expr ) { BR b(o,"or"); printArray(expr); } virtual void visit ( const TDLDataOneOf& expr ) { BR b(o,"d-one-of"); printArray(expr); } // facets virtual void visit ( const TDLFacetMinInclusive& expr ) { BR b(o,"ge"); expr.getExpr()->accept(*this); } virtual void visit ( const TDLFacetMinExclusive& expr ) { BR b(o,"gt"); expr.getExpr()->accept(*this); } virtual void visit ( const TDLFacetMaxInclusive& expr ) { BR b(o,"le"); expr.getExpr()->accept(*this); } virtual void visit ( const TDLFacetMaxExclusive& expr ) { BR b(o,"lt"); expr.getExpr()->accept(*this); } }; // TLISPExpressionPrinter #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/dltree.h0000644000000000000000000001347212112642405017013 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2012 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef DLTREE_H #define DLTREE_H #include #include #include "globaldef.h" #include "fpp_assert.h" #include "tLexeme.h" #include "tsttree.h" typedef TsTTree DLTree; class TRole; // checking if the tree is in Simplified Normal Form extern bool isSNF ( const DLTree* t ); // checks if two trees are the same (syntactically) extern bool equalTrees ( const DLTree* t1, const DLTree* t2 ); // check whether t1=(and c1..cn), t2 = (and d1..dm) and ci = dj for all i extern bool isSubTree ( const DLTree* t1, const DLTree* t2 ); // builds a copy of the formula t inline DLTree* clone ( const DLTree* t ) { return (t==NULL) ? NULL : t->clone(); } // check if DL tree is a concept constant inline bool isConst ( const DLTree* t ) { if ( t == NULL ) return false; switch (t->Element().getToken()) { case TOP: case BOTTOM: return true; default: return false; } } // check if DL tree is a concept/individual name inline bool isName ( const DLTree* t ) { if ( t == NULL ) return false; switch (t->Element().getToken()) { case CNAME: case INAME: return true; default: return false; } } // check if DL tree is a (data)role name inline bool isRName ( const DLTree* t ) { if ( t == NULL ) return false; switch (t->Element().getToken()) { case RNAME: case DNAME: return true; default: return false; } } // check if DL tree is a concept-like name inline bool isCN ( const DLTree* t ) { return isConst(t) || isName(t); } /// check whether T is a bottom (empty) role inline bool isBotRole ( const DLTree* t ) { return likely(isRName(t)) && unlikely(t->Element().getNE()->isBottom()); } /// check whether T is a top (universal) role inline bool isTopRole ( const DLTree* t ) { return likely(isRName(t)) && unlikely(t->Element().getNE()->isTop()); } /// check whether T is an expression in the form (atmost 1 RNAME) inline bool isFunctionalExpr ( const DLTree* t, const TNamedEntry* R ) { return t && t->Element().getToken() == LE && R == t->Left()->Element().getNE() && t->Element().getData() == 1 && t->Right()->Element().getToken() == TOP; } // check if DL Tree represents negated ONE-OF constructor inline bool isNegOneOf ( const DLTree* t ) { if ( t == NULL ) return false; switch (t->Element().getToken()) { case AND: return isNegOneOf(t->Left()) && isNegOneOf(t->Right()); case NOT: return t->Left()->Element().getToken() == INAME; default: return false; } } // check if DL Tree represents ONE-OF constructor inline bool isOneOf ( const DLTree* t ) { if ( t == NULL ) return false; switch (t->Element().getToken()) { case INAME: return true; case NOT: return isNegOneOf(t->Left()); default: return false; } } // create SNF from given parts /// create TOP element inline DLTree* createTop ( void ) { return new DLTree(TLexeme(TOP)); } /// create BOTTOM element inline DLTree* createBottom ( void ) { return new DLTree(TLexeme(BOTTOM)); } /// create a tree with tag TAG and an entry ENTRY inline DLTree* createEntry ( Token tag, TNamedEntry* entry ) { return new DLTree ( TLexeme ( tag, entry ) ); } /// create entry for the role R extern DLTree* createRole ( TRole* R ); /// create inverse of role R extern DLTree* createInverse ( DLTree* R ); /// create negation of given formula extern DLTree* createSNFNot ( DLTree* C ); /// create conjunction of given formulas extern DLTree* createSNFAnd ( DLTree* C, DLTree* D ); /// create conjunction of given formulas; aggressively reduce for the case C = (and D ...) extern DLTree* createSNFReducedAnd ( DLTree* C, DLTree* D ); /// create disjunction of given formulas inline DLTree* createSNFOr ( DLTree* C, DLTree* D ) { // C\or D -> \not(\not C\and\not D) return createSNFNot ( createSNFAnd ( createSNFNot(C), createSNFNot(D) ) ); } /// create universal restriction of given formulas (\AR.C) extern DLTree* createSNFForall ( DLTree* R, DLTree* C ); /// create existential restriction of given formulas (\ER.C) inline DLTree* createSNFExists ( DLTree* R, DLTree* C ) { // \ER.C -> \not\AR.\not C return createSNFNot ( createSNFForall ( R, createSNFNot(C) ) ); } /// create SELF restriction for role R inline DLTree* createSNFSelf ( DLTree* R ) { if ( unlikely(isBotRole(R)) ) return createBottom(); // loop on bottom role is always unsat if ( unlikely(isTopRole(R)) ) return createTop(); // top role is reflexive return new DLTree ( TLexeme(SELF), R ); } /// create at-least (GE) restriction of given formulas (>= n R.C) extern DLTree* createSNFGE ( unsigned int n, DLTree* R, DLTree* C ); /// create at-most (LE) restriction of given formulas (<= n R.C) extern DLTree* createSNFLE ( unsigned int n, DLTree* R, DLTree* C ); // prints formula extern const char* TokenName ( Token t ); extern std::ostream& operator << ( std::ostream& o, const DLTree *form ); /// helper that deletes temporary trees class TreeDeleter { protected: DLTree* ptr; public: TreeDeleter ( DLTree* p ) : ptr(p) {} ~TreeDeleter ( void ) { deleteTree(ptr); } operator DLTree* ( void ) { return ptr; } operator const DLTree* ( void ) const { return ptr; } }; // TreeDeleter #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/RoleMaster.h0000644000000000000000000001341612112642405017607 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2012 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef ROLEMASTER_H #define ROLEMASTER_H #include "globaldef.h" #include "tNameSet.h" #include "eFPPCantRegName.h" #include "tRole.h" #include "Taxonomy.h" class RoleMaster { public: // types /// vector of roles typedef TRole::TRoleVec TRoleVec; /// RW access to roles typedef TRoleVec::iterator iterator; /// RO access to roles typedef TRoleVec::const_iterator const_iterator; protected: // members /// number of the last registered role int newRoleId; /// all registered roles TRoleVec Roles; /// internal empty role (bottom in the taxonomy) TRole emptyRole; /// internal universal role (top in the taxonomy) TRole universalRole; /// roles nameset TNameSet roleNS; /// Taxonomy of roles Taxonomy* pTax; /// two halves of disjoint roles axioms TRoleVec DJRolesA, DJRolesB; /// flag whether to create data roles or not bool DataRoles; /// flag if it is possible to introduce new names bool useUndefinedNames; private: // methods /// no copy c'tor RoleMaster ( const RoleMaster& ); /// no assignment RoleMaster& operator = ( const RoleMaster& ); /// constant defining first user role in the RBox static unsigned int firstRoleIndex ( void ) { return 2; } protected: // methods /// register TRole and it's inverse in RoleBox void registerRole ( TRole* r ); /// @return true if P is a role that is registered in the RM bool isRegisteredRole ( const TNamedEntry* p ) const { const TRole* R = reinterpret_cast(p); if ( R == NULL ) return false; unsigned int ind = R->getIndex(); return ( ind >= firstRoleIndex() && ind < Roles.size() && Roles[ind] == p ); } /// add parent for the input role; both roles are not synonyms void addRoleParentProper ( TRole* role, TRole* parent ) const; /// get number of roles size_t size ( void ) const { return Roles.size()/2-1; } public: // interface /// the only c'tor RoleMaster ( bool dataRoles, const std::string& TopRoleName, const std::string& BotRoleName ); /// d'tor (delete taxonomy) ~RoleMaster ( void ) { delete pTax; } /// create role entry with given name TNamedEntry* ensureRoleName ( const std::string& name ); /// add parent for the input role or role composition; delete ROLE afterwards void addRoleParent ( DLTree* role, TRole* parent ) const; /// add parent for the input role void addRoleParent ( TRole* role, TRole* parent ) const { addRoleParentProper ( resolveSynonym(role), resolveSynonym(parent) ); } /// add synonym to existing role void addRoleSynonym ( TRole* role, TRole* syn ) const { // no synonyms // role = resolveSynonym(role); // syn = resolveSynonym(syn); // FIXME!! 1st call can make one of them a synonym of a const addRoleParentProper ( resolveSynonym(role), resolveSynonym(syn) ); addRoleParentProper ( resolveSynonym(syn), resolveSynonym(role) ); } /// register a pair of disjoint roles void addDisjointRoles ( TRole* R, TRole* S ) { // object- and data roles are always disjoint if ( R->isDataRole() != S->isDataRole() ) return; DJRolesA.push_back(R); DJRolesB.push_back(S); } /// create taxonomy of roles (using the Parent data) void initAncDesc ( void ); /// change the undefined names usage policy void setUndefinedNames ( bool val ) { useUndefinedNames = val; } // access to roles /// @return pointer to a TOP role TRole* getTopRole ( void ) { return &universalRole; } /// @return pointer to a BOTTOM role TRole* getBotRole ( void ) { return &emptyRole; } /// RW pointer to the first user-defined role iterator begin ( void ) { return Roles.begin()+firstRoleIndex(); } /// RW pointer after the last user-defined role iterator end ( void ) { return Roles.end(); } /// RO pointer to the first user-defined role const_iterator begin ( void ) const { return Roles.begin()+firstRoleIndex(); } /// RO pointer after the last user-defined role const_iterator end ( void ) const { return Roles.end(); } /// get access to the taxonomy Taxonomy* getTaxonomy ( void ) const { return pTax; } /// @return true iff there is a reflexive role bool hasReflexiveRoles ( void ) const; /// put all reflexive roles to a RR array void fillReflexiveRoles ( TRoleVec& RR ) const; // output interface void Print ( std::ostream& o, const char* type ) const { if ( size() == 0 ) return; o << type << " Roles (" << size() << "):\n"; emptyRole.Print(o); for ( const_iterator p = begin(); p != end(); ++p ) (*p)->Print(o); } // save/load interface; implementation is in SaveLoad.cpp /// save entry void Save ( std::ostream& o ) const; /// load entry void Load ( std::istream& i ); }; // RoleMaster inline bool RoleMaster :: hasReflexiveRoles ( void ) const { for ( const_iterator p = begin(), p_end = end(); p < p_end; ++p ) if ( (*p)->isReflexive() ) return true; return false; } inline void RoleMaster :: fillReflexiveRoles ( TRoleVec& RR ) const { RR.clear(); for ( const_iterator p = begin(), p_end = end(); p < p_end; ++p ) if ( !(*p)->isSynonym() && (*p)->isReflexive() ) RR.push_back(*p); } #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/tRole.cpp0000644000000000000000000002715712112642405017161 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2012 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include #include #include #include "tRole.h" #include "Taxonomy.h" void TRole :: fillsComposition ( TRoleVec& Composition, const DLTree* tree ) const { if ( tree->Element() == RCOMPOSITION ) { fillsComposition ( Composition, tree->Left() ); fillsComposition ( Composition, tree->Right() ); } else Composition.push_back(resolveRole(tree)); } /// copy role information (like transitivity, functionality, R&D etc) to synonym void TRole :: addFeaturesToSynonym ( void ) { if ( !isSynonym() ) return; TRole* syn = resolveSynonym(this); // don't copy parents: they are already copied during ToldSubsumers processing // copy functionality if ( isFunctional() && !syn->isFunctional() ) syn->setFunctional(); // copy transitivity if ( isTransitive() ) syn->setTransitive (); // copy reflexivity if ( isReflexive() ) syn->setReflexive(); // copy data type if ( isDataRole() ) syn->setDataRole(); // copy R&D if ( pDomain != NULL ) syn->setDomain (clone(pDomain)); // copy disjoint if ( isDisjoint() ) syn->Disjoint.insert ( Disjoint.begin(), Disjoint.end() ); // copy subCompositions syn->subCompositions.insert ( syn->subCompositions.end(), subCompositions.begin(), subCompositions.end() ); // syn should be the only parent for synonym toldSubsumers.clear(); addParent(syn); } // compare 2 TRoles wrt order of synonyms class TRoleCompare { public: bool operator() ( TRole* p, TRole* q ) const { int n = p->getId(), m = q->getId(); if ( n > 0 && m < 0 ) return true; if ( n < 0 && m > 0 ) return false; return abs(n) < abs(m); } }; // TRoleCompare TRole* TRole :: eliminateToldCycles ( TRoleSet& RInProcess, TRoleVec& ToldSynonyms ) { // skip synonyms if ( isSynonym() ) return NULL; // if we found a cycle... if ( RInProcess.find(this) != RInProcess.end() ) { ToldSynonyms.push_back(this); return this; } TRole* ret = NULL; // start processing role RInProcess.insert(this); // ensure that parents does not contain synonyms removeSynonymsFromParents(); // not involved in cycle -- check all told subsumers for ( ClassifiableEntry::const_iterator r = told_begin(); r != told_end(); ++r ) // if cycle was detected if ( (ret = static_cast(*r)->eliminateToldCycles ( RInProcess, ToldSynonyms )) != NULL ) { if ( ret == this ) { std::sort ( ToldSynonyms.begin(), ToldSynonyms.end(), TRoleCompare() ); // now first element is representative; save it as RET ret = *ToldSynonyms.begin(); // make all others synonyms of RET for ( std::vector::iterator p = ToldSynonyms.begin()+1, p_end = ToldSynonyms.end(); p < p_end; ++p ) { (*p)->setSynonym(ret); ret->addParents ( (*p)->told_begin(), (*p)->told_end() ); } ToldSynonyms.clear(); // restart search for the representative RInProcess.erase(this); return ret->eliminateToldCycles ( RInProcess, ToldSynonyms ); } else // some role inside a cycle: save it and return { ToldSynonyms.push_back(this); break; } } // finish processing role RInProcess.erase(this); return ret; } void TRole :: Print ( std::ostream& o ) const { o << "Role \"" << getName() << "\"(" << getId() << ")"; //FIXME!! while it's not necessary // o << " [" << r.nUsageFreq << "]"; // transitivity if ( isTransitive() ) o << "T"; // reflexivity if ( isReflexive() ) o << "R"; // functionality if ( isTopFunc() ) o << "t"; if ( isFunctional() ) o << "F"; // data role if ( isDataRole() ) o << "D"; if ( isSynonym() ) { o << " = \"" << getSynonym()->getName() << "\"\n"; return; } if ( !toldSubsumers.empty() ) { ClassifiableEntry::linkSet::const_iterator q = toldSubsumers.begin(); o << " parents={\"" << (*q)->getName(); for ( ++q; q != toldSubsumers.end(); ++q ) o << "\", \"" << (*q)->getName(); o << "\"}"; } if ( !Disjoint.empty() ) { TRoleSet::const_iterator p = Disjoint.begin(), p_end = Disjoint.end(); o << " disjoint with {\"" << (*p)->getName(); for ( ++p; p != p_end; ++p ) o << "\", \"" << (*p)->getName(); o << "\"}"; } // range/domain if ( getTDomain() != NULL ) o << " Domain=(" << getBPDomain() << ")=" << getTDomain(); if ( getTRange() != NULL ) o << " Range=(" << getBPRange() << ")=" << getTRange(); if ( !isDataRole() ) { o << "\nAutomaton (size " << A.size() << "): " << ( A.isISafe() ? "I" : "i" ) << ( A.isOSafe() ? "O" : "o" ); A.Print(o); } o << "\n"; } // actor to fill vector by traversing taxonomy in a proper direction class AddRoleActor { protected: TRole::TRoleVec& rset; public: AddRoleActor ( TRole::TRoleVec& v ) : rset(v) {} ~AddRoleActor ( void ) {} bool apply ( const TaxonomyVertex& v ) { if ( v.getPrimer()->getId() == 0 ) return false; rset.push_back(const_cast(static_cast(v.getPrimer()))); return true; } }; // AddRoleActor /// init ancestors and descendants using Taxonomy void TRole :: initADbyTaxonomy ( Taxonomy* pTax, unsigned int nRoles ) { fpp_assert ( isClassified() ); // safety check fpp_assert ( Ancestor.empty() && Descendant.empty() ); // Note that Top/Bottom are not connected to taxonomy yet. // fills ancestors by the taxonomy AddRoleActor anc(Ancestor); pTax->getRelativesInfo ( getTaxVertex(), anc ); // fills descendants by the taxonomy AddRoleActor desc(Descendant); pTax->getRelativesInfo ( getTaxVertex(), desc ); // resize maps for fast access DJRoles.resize(nRoles); AncMap.resize(nRoles); // init map for fast Anc/Desc access addAncestorsToBitMap(AncMap); } void TRole :: postProcess ( void ) { // set Topmost-Functional field initTopFunc(); // init DJ roles map if ( isDisjoint() ) initDJMap(); } /// check if the role is topmost-functional (internal-use only) // not very efficient, but good enough bool TRole :: isRealTopFunc ( void ) const { if ( !isFunctional() ) // all REAL top-funcs have their self-ref in TopFunc already return false; // if any of the parent is self-proclaimed top-func -- this one is not top-func for ( const_iterator p = begin_anc(), p_end = end_anc(); p != p_end; ++p ) if ( (*p)->isTopFunc() ) return false; // functional role with no functional parents is top-most functional return true; } /// set up TopFunc member (internal-use only) // not very efficient, but good enough void TRole :: initTopFunc ( void ) { if ( isRealTopFunc() ) // TF already set up -- nothing to do return; if ( isTopFunc() ) // sefl-proclaimed TF but not real -- need to be updated TopFunc.clear(); // register all real TFs for ( const_iterator p = begin_anc(), p_end = end_anc(); p != p_end; ++p ) if ( (*p)->isRealTopFunc() ) TopFunc.push_back(*p); if ( !TopFunc.empty() ) Functionality.setValue(true); } // disjoint-related implementation /// check (and correct) case whether R != S for R [= S void TRole :: checkHierarchicalDisjoint ( TRole* R ) { // if element is disjoint with itself -- the role is empty if ( Disjoint.count(R) ) { setDomain(createBottom()); Disjoint.clear(); return; } // check whether a sub-role is disjoint with the given one for ( const_iterator p = R->begin_desc(), p_end = R->end_desc(); p != p_end; ++p ) if ( Disjoint.count(*p) ) { (*p)->setDomain(createBottom()); Disjoint.erase(*p); (*p)->Disjoint.clear(); } } /// init map of all disjoint roles (N is a size of a bitmap) void TRole :: initDJMap ( void ) { // role R is disjoint with every role S' [= S such that R != S for ( TRoleSet::iterator q = Disjoint.begin(), q_end = Disjoint.end(); q != q_end; ++q ) DJRoles[(*q)->getIndex()] = true; } // automaton-related implementation void TRole :: preprocessComposition ( TRoleVec& RS ) { bool same = false; unsigned int last = RS.size()-1; unsigned int i = 0; // current element of the composition for ( TRoleVec::iterator p = RS.begin(), p_end = RS.end(); p != p_end; ++p, ++i ) { TRole* R = resolveSynonym(*p); if ( R->isBottom() ) // empty role in composition -- nothing to do { RS.clear(); return; } if ( R == this ) // found R in composition { if ( i != 0 && i != last ) // R in the middle of the composition throw EFPPCycleInRIA(getName()); if ( same ) // second one { if ( last == 1 ) // transitivity { RS.clear(); setTransitive(); return; } else // wrong (undecidable) axiom throw EFPPCycleInRIA(getName()); } else // first one same = true; } *p = R; // replace possible synonyms } } /// complete role automaton void TRole :: completeAutomaton ( TRoleSet& RInProcess ) { // check whether RA is already complete if ( A.isCompleted() ) return; // if we found a cycle... if ( RInProcess.find(this) != RInProcess.end() ) throw EFPPCycleInRIA(getName()); // start processing role RInProcess.insert(this); // make sure that all sub-roles already have completed automata for ( const_iterator p = begin_desc(), p_end = end_desc(); p != p_end; ++p ) (*p)->completeAutomaton(RInProcess); // add automata for complex role inclusions for ( std::vector::iterator q = subCompositions.begin(), q_end = subCompositions.end(); q != q_end; ++q ) addSubCompositionAutomaton ( *q, RInProcess ); // check for the transitivity if ( isTransitive() ) A.addTransitionSafe ( A.final(), new RATransition(A.initial()) ); // here automaton is complete A.setCompleted(); if ( likely(!isBottom()) ) // FIXME!! for now; need better Top/Bot synonyms processing for ( ClassifiableEntry::iterator p = told_begin(), p_end = told_end(); p != p_end; ++p ) { TRole* R = static_cast(resolveSynonym(*p)); if ( R->isTop() ) // do not propagate anything to a top-role continue; R->addSubRoleAutomaton(this); if ( hasSpecialDomain() ) R->SpecialDomain = true; } // finish processing role RInProcess.erase(this); } /// add automaton for a role composition void TRole :: addSubCompositionAutomaton ( TRoleVec& RS, TRoleSet& RInProcess ) { // first preprocess the role chain preprocessComposition(RS); if ( RS.empty() ) // fallout from transitivity axiom return; // here we need a special treatment for R&D SpecialDomain = true; // tune iterators and states const_iterator p = RS.begin(), p_last = RS.end() - 1; RAState from = A.initial(), to = A.final(); if ( RS.front() == this ) { ++p; from = A.final(); } else if ( RS.back() == this ) { --p_last; to = A.initial(); } // make sure the role chain contain at least one element fpp_assert ( p <= p_last ); // create a chain bool oSafe = false; // we couldn't assume that the current role automaton is i- or o-safe A.initChain(from); for ( ; p != p_last; ++p ) oSafe = A.addToChain ( completeAutomatonByRole ( *p, RInProcess ), oSafe ); // add the last automaton to chain A.addToChain ( completeAutomatonByRole ( *p, RInProcess ), oSafe, to ); } FaCTpp-src-v1.6.2~dfsg/src/Kernel/SortedReasoning.cpp0000644000000000000000000001105512112642405021170 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2011 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "globaldef.h" #ifdef RKG_USE_SORTED_REASONING #include "RoleMaster.h" #include "dlDag.h" #include "logging.h" /// merge label of given role and all its super-roles void TRole :: mergeSupersDomain ( void ) { for ( const_iterator p = begin_anc(), p_end = end_anc(); p != p_end; ++p ) domLabel.merge((*p)->domLabel); // for reflexive role -- merge domain and range labels if ( isReflexive() ) domLabel.merge(getRangeLabel()); // for R1*R2*...*Rn [= R, merge dom(R) with dom(R1) and ran(R) with ran(Rn) for ( std::vector::iterator q = subCompositions.begin(), q_end = subCompositions.end(); q != q_end; ++q ) if ( !q->empty() ) { domLabel.merge((*q->begin())->domLabel); getRangeLabel().merge(q->back()->getRangeLabel()); } } /// merge sorts for a given role void DLDag :: mergeSorts ( TRole* R ) { // associate role domain labels R->mergeSupersDomain(); merge ( R->getDomainLabel(), R->getBPDomain() ); // also associate functional nodes (if any) for ( TRole::const_iterator q = R->begin_topfunc(), q_end = R->end_topfunc(); q != q_end; ++q ) merge ( R->getDomainLabel(), (*q)->getFunctional() ); } /// merge sorts for a given vertex void DLDag :: mergeSorts ( DLVertex& v ) { switch ( v.Type() ) { case dtLE: // set R&D for role case dtForall: v.merge(const_cast(v.getRole())->getDomainLabel()); // domain(role)=cur merge ( const_cast(v.getRole())->getRangeLabel(), v.getC() ); break; case dtProj: // projection: equate R&D of R and ProjR, and D(R) with C v.merge(const_cast(v.getRole())->getDomainLabel()); v.merge(const_cast(v.getProjRole())->getDomainLabel()); merge ( const_cast(v.getRole())->getDomainLabel(), v.getC() ); const_cast(v.getRole())->getRangeLabel().merge(const_cast(v.getProjRole())->getRangeLabel()); break; case dtIrr: // equate R&D for role v.merge(const_cast(v.getRole())->getDomainLabel()); v.merge(const_cast(v.getRole())->getRangeLabel()); break; case dtAnd: case dtSplitConcept: for ( DLVertex::const_iterator q = v.begin(), q_end = v.end(); q < q_end; ++q ) merge ( v.getSort(), *q ); break; case dtNSingleton: case dtPSingleton: case dtPConcept: case dtNConcept: // merge with description case dtChoose: merge ( v.getSort(), v.getC() ); break; case dtDataType: // nothing to do case dtDataValue: case dtDataExpr: case dtNN: break; case dtTop: default: fpp_unreachable(); } } /// build the sort system for given TBox void DLDag :: determineSorts ( RoleMaster& ORM, RoleMaster& DRM ) { sortArraySize = Heap.size(); RoleMaster::iterator p, p_end; HeapType::iterator i, i_end = Heap.end(); // init roles R&D sorts for ( p = ORM.begin(), p_end = ORM.end(); p < p_end; ++p ) if ( !(*p)->isSynonym() ) mergeSorts(*p); for ( p = DRM.begin(), p_end = DRM.end(); p < p_end; ++p ) if ( !(*p)->isSynonym() ) mergeSorts(*p); for ( i = Heap.begin()+2; i < i_end; ++i ) mergeSorts(**i); unsigned int sum = 0; for ( i = Heap.begin()+2; i < i_end; ++i ) { mergableLabel& lab = (*i)->getSort(); lab.resolve(); if ( lab.isSample() ) ++sum; } for ( p = ORM.begin(), p_end = ORM.end(); p < p_end; ++p ) if ( !(*p)->isSynonym() ) { mergableLabel& lab = const_cast(*p)->getDomainLabel(); lab.resolve(); if ( lab.isSample() ) ++sum; } for ( p = DRM.begin(), p_end = DRM.end(); p < p_end; ++p ) if ( !(*p)->isSynonym() ) { mergableLabel& lab = const_cast(*p)->getDomainLabel(); lab.resolve(); if ( lab.isSample() ) ++sum; } CHECK_LL_RETURN(llAlways); // we added a temp concept here; don't count it if ( sum > 0 ) sum--; LL << "\nThere are "; if ( sum > 1 ) LL << sum; else LL << "no"; LL << " different sorts in TBox\n"; } #endif // RKG_USE_SORTED_REASONING FaCTpp-src-v1.6.2~dfsg/src/Kernel/ELFAxiomChecker.h0000644000000000000000000001150212112642405020415 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2011 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef ELFAXIOMCHECKER_H #define ELFAXIOMCHECKER_H #include "tDLAxiom.h" #include "ELFExpressionChecker.h" class ELFAxiomChecker: public DLAxiomVisitor { protected: ELFExpressionChecker eCh; bool value; bool v ( const TDLExpression* expr ) { value = eCh.v(expr); return value; } public: // visitor interface virtual void visit ( const TDLAxiomDeclaration& axiom ) { v(axiom.getDeclaration()); } virtual void visit ( const TDLAxiomEquivalentConcepts& axiom ) { value = false; for ( TDLAxiomEquivalentConcepts::iterator p = axiom.begin(), p_end = axiom.end(); p != p_end; ++p ) if ( !v(*p) ) return; value = true; } virtual void visit ( const TDLAxiomDisjointConcepts& axiom ) { value = false; for ( TDLAxiomDisjointConcepts::iterator p = axiom.begin(), p_end = axiom.end(); p != p_end; ++p ) if ( !v(*p) ) return; value = true; } virtual void visit ( const TDLAxiomDisjointUnion& axiom ATTR_UNUSED ) { value = (axiom.size() > 1); } virtual void visit ( const TDLAxiomEquivalentORoles& axiom ) { value = false; for ( TDLAxiomEquivalentORoles::iterator p = axiom.begin(), p_end = axiom.end(); p != p_end; ++p ) if ( !v(*p) ) return; value = true; } virtual void visit ( const TDLAxiomEquivalentDRoles& axiom ATTR_UNUSED ) { value = false; } virtual void visit ( const TDLAxiomDisjointORoles& axiom ATTR_UNUSED ) { value = false; } virtual void visit ( const TDLAxiomDisjointDRoles& axiom ATTR_UNUSED ) { value = false; } virtual void visit ( const TDLAxiomSameIndividuals& axiom ATTR_UNUSED ) { value = false; } virtual void visit ( const TDLAxiomDifferentIndividuals& axiom ATTR_UNUSED ) { value = false; } virtual void visit ( const TDLAxiomFairnessConstraint& axiom ATTR_UNUSED ) { value = false; } virtual void visit ( const TDLAxiomRoleInverse& axiom ATTR_UNUSED ) { value = false; } virtual void visit ( const TDLAxiomORoleSubsumption& axiom ) { if ( v(axiom.getSubRole()) ) v(axiom.getRole()); } virtual void visit ( const TDLAxiomDRoleSubsumption& axiom ATTR_UNUSED ) { value = false; } // FIXME!! check later virtual void visit ( const TDLAxiomORoleDomain& axiom ATTR_UNUSED ) { value = false; } virtual void visit ( const TDLAxiomDRoleDomain& axiom ATTR_UNUSED ) { value = false; } // FIXME!! check later virtual void visit ( const TDLAxiomORoleRange& axiom ATTR_UNUSED ){ value = false; } virtual void visit ( const TDLAxiomDRoleRange& axiom ATTR_UNUSED ) { value = false; } virtual void visit ( const TDLAxiomRoleTransitive& axiom ATTR_UNUSED ) { value = true; } virtual void visit ( const TDLAxiomRoleReflexive& axiom ATTR_UNUSED ) { value = false; } virtual void visit ( const TDLAxiomRoleIrreflexive& axiom ATTR_UNUSED ) { value = false; } virtual void visit ( const TDLAxiomRoleSymmetric& axiom ATTR_UNUSED ) { value = false; } virtual void visit ( const TDLAxiomRoleAsymmetric& axiom ATTR_UNUSED ) { value = false; } virtual void visit ( const TDLAxiomORoleFunctional& axiom ATTR_UNUSED ) { value = false; } virtual void visit ( const TDLAxiomDRoleFunctional& axiom ATTR_UNUSED ) { value = false; } virtual void visit ( const TDLAxiomRoleInverseFunctional& axiom ATTR_UNUSED ) { value = false; } virtual void visit ( const TDLAxiomConceptInclusion& axiom ) { if ( v(axiom.getSubC()) ) v(axiom.getSupC()); } virtual void visit ( const TDLAxiomInstanceOf& axiom ATTR_UNUSED ) { value = false; } virtual void visit ( const TDLAxiomRelatedTo& axiom ATTR_UNUSED ) { value = false; } virtual void visit ( const TDLAxiomRelatedToNot& axiom ATTR_UNUSED ) { value = false; } virtual void visit ( const TDLAxiomValueOf& axiom ATTR_UNUSED ) { value = false; } virtual void visit ( const TDLAxiomValueOfNot& axiom ATTR_UNUSED ) { value = false; } virtual void visitOntology ( TOntology& ontology ) { value = true; for ( TOntology::iterator p = ontology.begin(), p_end = ontology.end(); value && p != p_end; ++p ) if ( (*p)->isUsed() ) (*p)->accept(*this); } ELFAxiomChecker ( void ) : value(true) {} virtual ~ELFAxiomChecker ( void ) {} operator bool ( void ) const { return value; } }; // ELFAxiomChecker #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/dlCompletionTree.cpp0000644000000000000000000001310212112642405021326 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2012 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "dlCompletionTree.h" /// check if transitive R-successor of the NODE labelled with C const DlCompletionTree* DlCompletionTree :: isTSuccLabelled ( const TRole* R, BipolarPointer C ) const { if ( isLabelledBy(C) ) return this; // don't check nominal nodes (prevent cycles) if ( isNominalNode() ) return NULL; // check all other successors const DlCompletionTree* ret = NULL; for ( const_edge_iterator p = begin(), p_end = end(); p < p_end; ++p ) if ( (*p)->isSuccEdge() && (*p)->isNeighbour(R) && !(*p)->isReflexiveEdge() && // prevent cycles (ret = (*p)->getArcEnd()->isTSuccLabelled(R,C)) != NULL ) return ret; // not happens return NULL; } /// check if transitive R-predcessor of the NODE labelled with C; skip FROM node const DlCompletionTree* DlCompletionTree :: isTPredLabelled ( const TRole* R, BipolarPointer C, const DlCompletionTree* from ) const { if ( isLabelledBy(C) ) return this; // don't check nominal nodes (prevent cycles) if ( isNominalNode() ) return NULL; // check all other successors const DlCompletionTree* ret = NULL; for ( const_edge_iterator p = begin(), p_end = end(); p < p_end; ++p ) if ( (*p)->isSuccEdge() && (*p)->isNeighbour(R) && (*p)->getArcEnd() != from && (ret = (*p)->getArcEnd()->isTSuccLabelled(R,C)) != NULL ) return ret; // check predecessor if ( hasParent() && isParentArcLabelled(R) ) return getParentNode()->isTPredLabelled ( R, C, this ); else return NULL; } const DlCompletionTree* DlCompletionTree :: isNSomeApplicable ( const TRole* R, BipolarPointer C ) const { for ( DlCompletionTree::const_edge_iterator p = begin(), p_end = end(); p < p_end; ++p ) if ( (*p)->isNeighbour(R) && (*p)->getArcEnd()->isLabelledBy(C) ) return (*p)->getArcEnd(); // already contained such a label return NULL; } const DlCompletionTree* DlCompletionTree :: isTSomeApplicable ( const TRole* R, BipolarPointer C ) const { const DlCompletionTree* ret = NULL; for ( DlCompletionTree::const_edge_iterator p = begin(), p_end = end(); p < p_end; ++p ) if ( (*p)->isNeighbour(R) ) { if ( (*p)->isPredEdge() ) ret = (*p)->getArcEnd()->isTPredLabelled(R,C,this); else ret = (*p)->getArcEnd()->isTSuccLabelled(R,C); if ( ret ) return ret; // already contained such a label } return NULL; } #ifdef RKG_IR_IN_NODE_LABEL //---------------------------------------------- // inequality relation methods //---------------------------------------------- // check if IR for the node contains C bool DlCompletionTree :: inIRwithC ( const ConceptWDep& C, DepSet& dep ) const { if ( IR.empty() ) return false; for ( IRInfo::const_iterator p = IR.begin(); p != IR.end(); ++p ) if ( p->bp() == C.bp() ) { dep += p->getDep(); dep += C.getDep(); return true; } return false; } // check if the NODE's and current node's IR are labelled with the same level bool DlCompletionTree :: nonMergable ( const DlCompletionTree* node, DepSet& dep ) const { if ( IR.empty() || node->IR.empty() ) return false; for ( IRInfo::const_iterator p = node->IR.begin(); p != node->IR.end(); ++p ) if ( inIRwithC ( *p, dep ) ) return true; return false; } /// update IR of the current node with IR from NODE and additional clash-set; @return restorer TRestorer* DlCompletionTree :: updateIR ( const DlCompletionTree* node, const DepSet& toAdd ) { if ( node->IR.empty() ) return NULL; // nothing to do // save current state TRestorer* ret = new IRRestorer(this); // copy all elements from NODE's IR to current node. // FIXME!! do not check if some of them are already in there for ( IRInfo::const_iterator p = node->IR.begin(); p != node->IR.end(); ++p ) IR.add ( ConceptWDep ( *p, toAdd ) ); return ret; } #endif // RKG_IR_IN_NODE_LABEL // saving/restoring void DlCompletionTree :: save ( SaveState* nss ) const { nss->curLevel = curLevel; nss->nNeighbours = Neighbour.size(); Label.save(nss->lab); logSRNode("SaveNode"); } void DlCompletionTree :: restore ( SaveState* nss ) { if ( nss == NULL ) return; // level restore curLevel = nss->curLevel; // label restore Label.restore ( nss->lab, getCurLevel() ); // remove new neighbours #ifndef RKG_USE_DYNAMIC_BACKJUMPING Neighbour.resize(nss->nNeighbours); #else for ( int j = Neighbour.size()-1; j >= 0; --j ) if ( Neighbour[j]->Node->creLevel <= getCurLevel() ) { Neighbour.resize(j+1); break; } #endif // it's cheaper to dirty affected flag than to consistently save nodes affected = true; // clear memory delete nss; logSRNode("RestNode"); } // output void DlCompletionTree :: PrintBody ( std::ostream& o ) const { o << id; if ( isNominalNode() ) o << "o" << getNominalLevel(); o << '(' << getCurLevel() << ')'; // data node? if ( isDataNode() ) o << "d"; // label (if any) Label.print(o); // blocking status information logNodeBStatus(o); } FaCTpp-src-v1.6.2~dfsg/src/Kernel/dlCompletionGraph.h0000644000000000000000000004053612112642405021150 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2005-2012 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef DLCOMPLETIONGRAPH_H #define DLCOMPLETIONGRAPH_H #include #include "globaldef.h" #include "DeletelessAllocator.h" #include "dlCompletionTree.h" #include "dlCompletionTreeArc.h" #include "tSaveStack.h" #include "tRareSaveStack.h" class DlSatTester; /** * Class for maintaining graph of CT nodes. Behaves like * deleteless allocator for nodes, plus some obvious features */ class DlCompletionGraph { protected: // typedefs /// type of the heap typedef std::vector nodeBaseType; public: // typedefs /// heap's RW iterator typedef nodeBaseType::iterator iterator; /// heap's RO iterator typedef nodeBaseType::const_iterator const_iterator; protected: // types /// class for S/R local state class SaveState { public: // members /// number of valid nodes unsigned int nNodes; /// end pointer of saved nodes unsigned int sNodes; /// number of used edges unsigned int nEdges; public: // interface /// empty c'tor SaveState ( void ) : nNodes(0), sNodes(0), nEdges(0) {} /// empty d'tor ~SaveState ( void ) {} }; // SaveState private: // constants /// initial value of IR level static const unsigned int initIRLevel = 0; private: // members /// allocator for edges DeletelessAllocator CTEdgeHeap; protected: // members /// heap itself nodeBaseType NodeBase; /// nodes, saved on current branching level nodeBaseType SavedNodes; /// host reasoner DlSatTester* pReasoner; /// remember the last generated ID for the node unsigned int nodeId; /// index of the next unallocated entry unsigned int endUsed; /// current branching level (synchronised with resoner's one) unsigned int branchingLevel; /// current IR level (should be valid BP) unsigned int IRLevel; /// stack for rarely changed information TRareSaveStack RareStack; /// stack for usual saving/restoring TSaveStack Stack; // helpers for the output /// bitmap to remember which node was printed std::vector CGPFlag; /// indent to print CGraph nodes unsigned int CGPIndent; // statistical members /// number of node' saves unsigned int nNodeSaves; /// number of node' saves unsigned int nNodeRestores; /// maximal size of the graph unsigned int maxGraphSize; // flags /// how many nodes skip before block; work only with FAIRNESS int nSkipBeforeBlock; /// use or not lazy blocking (ie test blocking only expanding exists) bool useLazyBlocking; /// whether to use Anywhere blocking as opposed to an ancestor one bool useAnywhereBlocking; /// check if session has inverse roles bool sessionHasInverseRoles; /// check if session has number restrictions bool sessionHasNumberRestrictions; protected: // methods /// init vector [B,E) with new objects T void initNodeArray ( iterator b, iterator e ) { for ( iterator p = b; p != e; ++p ) *p = new DlCompletionTree(nodeId++); } /// increase heap size void grow ( void ) { NodeBase.resize(NodeBase.size()*2); initNodeArray ( NodeBase.begin()+NodeBase.size()/2, NodeBase.end() ); } /// init root node void initRoot ( void ) { fpp_assert ( endUsed == 0 ); getNewNode(); } /// create edge between nodes with given label and creation level; @return from->to arc DlCompletionTreeArc* createEdge ( DlCompletionTree* from, DlCompletionTree* to, bool isPredEdge, const TRole* roleName, const DepSet& dep ); /// Aux method for Merge(): add EDGE to the NODE wrt flag ISPREDEDGE and dep-set DEP DlCompletionTreeArc* moveEdge ( DlCompletionTree* node, DlCompletionTreeArc* edge, bool isPredEdge, const DepSet& dep ); /// invalidate EDGE, save restoring info void invalidateEdge ( DlCompletionTreeArc* edge ) { saveRareCond(edge->save()); } //---------------------------------------------- // inequality relation methods //---------------------------------------------- /// update IR in P with IR from Q and additional dep-set void updateIR ( DlCompletionTree* p, const DlCompletionTree* q, const DepSet& toAdd ); //---------------------------------------------- // re-building blocking hierarchy //---------------------------------------------- /// check whether NODE is blocked by a BLOCKER bool isBlockedBy ( const DlCompletionTree* node, const DlCompletionTree* blocker ) const; /// check if d-blocked node is still d-blocked bool isStillDBlocked ( const DlCompletionTree* node ) const { return node->isDBlocked() && isBlockedBy ( node, node->Blocker ); } /// try to find d-blocker for a node using ancestor blocking void findDAncestorBlocker ( DlCompletionTree* node ); /// try to find d-blocker for a node using anywhere blocking void findDAnywhereBlocker ( DlCompletionTree* node ); /// try to find d-blocker for a node void findDBlocker ( DlCompletionTree* node ) { saveNode ( node, branchingLevel ); node->clearAffected(); if ( node->isBlocked() ) saveRareCond(node->setUBlocked()); if ( useAnywhereBlocking ) findDAnywhereBlocker(node); else findDAncestorBlocker(node); } /// unblock all the children of the node void unblockNodeChildren ( DlCompletionTree* node ) { for ( DlCompletionTree::const_edge_iterator q = node->begin(), q_end = node->end(); q < q_end; ++q ) if ( (*q)->isSuccEdge() && !(*q)->isIBlocked() && !(*q)->isReflexiveEdge() ) // all of them are i-blocked unblockNode ( (*q)->getArcEnd(), false ); } /// mark node unblocked; unblock all the hierarchy void unblockNode ( DlCompletionTree* node, bool wasDBlocked ); /// mark NODE as a d-blocked by a BLOCKER void setNodeDBlocked ( DlCompletionTree* node, const DlCompletionTree* blocker ) { saveRareCond(node->setDBlocked(blocker)); propagateIBlockedStatus ( node, node ); } /// mark NODE as an i-blocked by a BLOCKER void setNodeIBlocked ( DlCompletionTree* node, const DlCompletionTree* blocker ) { // nominal nodes can't be blocked if ( node->isPBlocked() || node->isNominalNode() ) return; node->clearAffected(); // already iBlocked -- nothing changes if ( node->isIBlocked() && node->Blocker == blocker ) return; // prevent node to be IBlocked due to reflexivity if ( node == blocker ) return; saveRareCond(node->setIBlocked(blocker)); propagateIBlockedStatus ( node, blocker ); } /// propagate i-blocked status to all children of NODE void propagateIBlockedStatus ( DlCompletionTree* node, const DlCompletionTree* blocker ) { for ( DlCompletionTree::const_edge_iterator q = node->begin(), q_end = node->end(); q < q_end; ++q ) if ( (*q)->isSuccEdge() && !(*q)->isIBlocked() ) setNodeIBlocked ( (*q)->getArcEnd(), blocker ); } /// @return true iff node might became unblocked bool canBeUnBlocked ( DlCompletionTree* node ) const { // in presence of inverse roles it is not enough // to check the affected flag for both node and its blocker // see tModal* for example if ( sessionHasInverseRoles ) return true; // if node is affected -- it can be unblocked; // if blocker became blocked itself -- the same return node->isAffected() || node->isIllegallyDBlocked(); } // helpers for the graph printing /// print proper indentation void PrintIndent ( std::ostream& o ) { o << "\n|"; for ( unsigned int i = 1; i < CGPIndent; ++i ) o << " |"; } /// print node of the graph with proper indentation void PrintNode ( const DlCompletionTree* node, std::ostream& o ); /// print edge of the graph with proper indentation void PrintEdge ( DlCompletionTree::const_edge_iterator edge, const DlCompletionTree* parent, std::ostream& o ); public: // interface /// c'tor: make INIT_SIZE objects DlCompletionGraph ( unsigned int initSize, DlSatTester* p ) : NodeBase(initSize) , pReasoner(p) , nodeId(0) , endUsed(0) , branchingLevel(InitBranchingLevelValue) , IRLevel(initIRLevel) , maxGraphSize(0) { initNodeArray ( NodeBase.begin(), NodeBase.end() ); clearStatistics(); initRoot(); } /// d'tor: delete all allocated nodes ~DlCompletionGraph ( void ) { for ( iterator p = NodeBase.begin(); p != NodeBase.end(); ++p ) delete *p; } // flag setting /// set flags for blocking void initContext ( int nSkip, bool useLB, bool useAB ) { nSkipBeforeBlock = nSkip; useLazyBlocking = useLB; useAnywhereBlocking = useAB; } /// set blocking method for a session void setBlockingMethod ( bool hasInverse, bool hasQCR ) { sessionHasInverseRoles = hasInverse; sessionHasNumberRestrictions = hasQCR; } /// add concept C of a type TAG to NODE; call blocking check if appropriate void addConceptToNode ( DlCompletionTree* node, const ConceptWDep& c, DagTag tag ) { node->addConcept(c,tag); if ( useLazyBlocking ) node->setAffected(); else detectBlockedStatus(node); } // access to nodes /// get a root node (non-const) DlCompletionTree* getRoot ( void ) { return NodeBase[0]->resolvePBlocker(); } /// get a root node (const) const DlCompletionTree* getRoot ( void ) const { return NodeBase[0]->resolvePBlocker(); } /// get a node by it's ID DlCompletionTree* getNode ( unsigned int id ) { if ( id >= endUsed ) return NULL; return NodeBase[id]; } /// get new node (with internal level) DlCompletionTree* getNewNode ( void ) { if ( endUsed >= NodeBase.size() ) grow(); DlCompletionTree* ret = NodeBase[endUsed++]; ret->init(branchingLevel); return ret; } /// begin (RO) of USED nodes const_iterator begin ( void ) const { return NodeBase.begin(); } /// end (RO) of USED nodes const_iterator end ( void ) const { return NodeBase.begin()+endUsed; } /// begin (RW) of USED nodes iterator begin ( void ) { return NodeBase.begin(); } /// end (RW) of USED nodes iterator end ( void ) { return NodeBase.begin()+endUsed; } // blocking /// detect blocked status of current node by checking whether NODE and/or its ancestors are d-blocked void detectBlockedStatus ( DlCompletionTree* node ); /// update blocked status for d-blocked node void updateDBlockedStatus ( DlCompletionTree* node ) { if ( !canBeUnBlocked(node) ) return; if ( isStillDBlocked(node) ) // FIXME!! clear affected in all children node->clearAffected(); else detectBlockedStatus(node); fpp_assert ( !node->isAffected() ); } /// retest every d-blocked node in the CG. Use it after the CG was build void retestCGBlockedStatus ( void ) { bool repeat; iterator p, p_beg = begin(), p_end = end(); do { for ( p = p_beg; p < p_end; ++p ) if ( (*p)->isDBlocked() ) updateDBlockedStatus(*p); // we need to repeat the thing if something became unblocked and then blocked again, // in case one of the blockers became blocked itself; see tModal3 for such an example repeat = false; for ( p = p_beg; p < p_end; ++p ) if ( (*p)->isIllegallyDBlocked() ) { repeat = true; break; } } while ( repeat ); } // fairness support /// @ return true if a fairness constraint C is violated in one of the loops in the CGraph DlCompletionTree* getFCViolator ( BipolarPointer C ) const { for ( const_iterator p = begin(), p_end = end(); p < p_end; ++p ) if ( (*p)->isDBlocked() && !(*p)->isLoopLabelled(C) ) return const_cast((*p)->Blocker); return NULL; } /// clear all the session statistics void clearStatistics ( void ) { nNodeSaves = 0; nNodeRestores = 0; if ( maxGraphSize < endUsed ) maxGraphSize = endUsed; } /// mark all heap elements as unused void clear ( void ) { CTEdgeHeap.clear(); endUsed = 0; branchingLevel = InitBranchingLevelValue; IRLevel = initIRLevel; RareStack.clear(); Stack.clear(); SavedNodes.clear(); initRoot(); } /// get number of nodes in the CGraph size_t maxSize ( void ) const { return maxGraphSize; } /// save rarely appeared info if P is non-NULL void saveRareCond ( TRestorer* p ) { if (p) RareStack.push(p); } //---------------------------------------------- // role/node //---------------------------------------------- /// add role R with dep-set DEP to the label of the TO arc DlCompletionTreeArc* addRoleLabel ( DlCompletionTree* from, DlCompletionTree* to, bool isPredEdge, const TRole* R, // name of role (arc label) const DepSet& dep ) // dep-set of the arc label { // check if GCraph already has FROM->TO edge labelled with RNAME DlCompletionTreeArc* ret = from->getEdgeLabelled ( R, to ); if ( ret == NULL ) ret = createEdge ( from, to, isPredEdge, R, dep ); else saveRareCond(ret->addDep(dep)); return ret; } /// Create an empty R-neighbour of FROM; @return an edge to created node DlCompletionTreeArc* createNeighbour ( DlCompletionTree* from, bool isPredEdge, const TRole* r, // name of role (arc label) const DepSet& dep ) // dep-set of the arc label { # ifdef RKG_IMPROVE_SAVE_RESTORE_DEPSET fpp_assert ( branchingLevel == r.getDep().level()+1 ); # endif return createEdge ( from, getNewNode(), isPredEdge, r, dep ); } /// Create an R-loop of NODE wrt dep-set DEP; @return a loop edge DlCompletionTreeArc* createLoop ( DlCompletionTree* node, const TRole* r, const DepSet& dep ) { return addRoleLabel ( node, node, /*isPredEdge=*/false, r, dep ); } /// merge node FROM to node TO (do NOT copy label); fill EDGES with new edges added to TO void Merge ( DlCompletionTree* from, DlCompletionTree* to, const DepSet& toAdd, std::vector& edges ); /// purge node P with given ROOT and DEP-set void purgeNode ( DlCompletionTree* p, const DlCompletionTree* root, const DepSet& dep ); /// purge edge E with given ROOT and DEP-set void purgeEdge ( DlCompletionTreeArc* e, const DlCompletionTree* root, const DepSet& dep ); //---------------------------------------------- // inequality relation interface //---------------------------------------------- /// init new IR set void initIR ( void ); /// make given NODE member of current IR set; @return true iff clash occurs bool setCurIR ( DlCompletionTree* node, const DepSet& ds ); /// finilise current IR set void finiIR ( void ); /// check if P and Q are in IR; if so, put the clash-set to DEP bool nonMergable ( const DlCompletionTree* p, const DlCompletionTree* q, DepSet& dep ) const; //---------------------------------------------- // save/restore //---------------------------------------------- /// save given node wrt level void saveNode ( DlCompletionTree* node, unsigned int level ) { if ( node->needSave(level) ) { node->save(level); SavedNodes.push_back(node); ++nNodeSaves; } } /// restore given node wrt level void restoreNode ( DlCompletionTree* node, unsigned int level ) { if ( node->needRestore(level) ) { node->restore(level); ++nNodeRestores; } } /// save local state void save ( void ); /// restore state for the given LEVEL void restore ( unsigned int level ); // statistics /// get number of nodes saved during session unsigned int getNNodeSaves ( void ) const { return nNodeSaves; } /// get number of nodes restored during session unsigned int getNNodeRestores ( void ) const { return nNodeRestores; } // print /// print graph starting from the root void Print ( std::ostream& o ); }; // DlCompletionGraph // blocking #if defined(RKG_IR_IN_NODE_LABEL) inline bool DlCompletionGraph :: nonMergable ( const DlCompletionTree* p, const DlCompletionTree* q, DepSet& dep ) const { return p->nonMergable ( q, dep ); } inline void DlCompletionGraph :: updateIR ( DlCompletionTree* p, const DlCompletionTree* q, const DepSet& toAdd ) { saveRareCond ( p->updateIR ( q, toAdd ) ); } inline void DlCompletionGraph :: initIR ( void ) { ++IRLevel; } inline bool DlCompletionGraph :: setCurIR ( DlCompletionTree* node, const DepSet& ds ) { return node->initIR ( IRLevel, ds ); } inline void DlCompletionGraph :: finiIR ( void ) {} #endif // RKG_IR_IN_NODE_LABEL #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/Tactic.cpp0000644000000000000000000014717712112642405017310 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2012 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "globaldef.h" #include // for std::sort #include "Reasoner.h" #include "logging.h" #define switchResult(expr)\ do { if (unlikely(expr)) return true; } while(0) /******************************************************************************** * Tactics section; * * Each Tactic should have a (small) Usability function * and a Real tactic function Body * * Each tactic returns: * - true - if expansion of CUR lead to clash * - false - overwise * ******************************************************************************/ // main local Tactic bool DlSatTester :: commonTactic ( void ) { #ifdef ENABLE_CHECKING fpp_assert ( curConcept.bp() != bpINVALID ); #endif // check if Node is cached and we tries to expand existing result // also don't do anything for p-blocked nodes (can't be unblocked) if ( curNode->isCached() || curNode->isPBlocked() ) return false; // informs about starting calculations... if ( LLM.isWritable(llGTA) ) logStartEntry(); bool ret = false; // apply tactic only if Node is not an i-blocked if ( !isIBlocked() ) ret = commonTacticBody ( DLHeap[curConcept] ); if ( LLM.isWritable(llGTA) ) logFinishEntry(ret); return ret; } //------------------------------------------------------------------------------- // Simple tactics //------------------------------------------------------------------------------- bool DlSatTester :: commonTacticBody ( const DLVertex& cur ) { // show DAG usage #ifdef RKG_PRINT_DAG_USAGE const_cast(cur).incUsage(isPositive(curConcept.bp())); #endif incStat(nTacticCalls); // call proper tactic switch ( cur.Type() ) { case dtTop: fpp_unreachable(); // can't appear here; addToDoEntry deals with constants return false; case dtDataType: // data things are checked by data inferer case dtDataValue: incStat(nUseless); return false; case dtPSingleton: case dtNSingleton: if ( isPositive (curConcept.bp()) ) // real singleton return commonTacticBodySingleton(cur); else // negated singleton -- nothing to do with. return commonTacticBodyId(cur); case dtNConcept: case dtPConcept: return commonTacticBodyId(cur); case dtAnd: if ( isPositive (curConcept.bp()) ) // this is AND vertex return commonTacticBodyAnd(cur); else // OR return commonTacticBodyOr(cur); case dtForall: if ( isNegative(curConcept.bp()) ) // SOME vertex return commonTacticBodySome(cur); // ALL vertex return commonTacticBodyAll(cur); case dtIrr: if ( isNegative(curConcept.bp()) ) // SOME R.Self vertex return commonTacticBodySomeSelf(cur.getRole()); else // don't need invalidate cache, as IRREFL can only lead to CLASH return commonTacticBodyIrrefl(cur.getRole()); case dtLE: if ( isNegative (curConcept.bp()) ) // >= vertex return commonTacticBodyGE(cur); // <= vertex if ( isFunctionalVertex(cur) ) return commonTacticBodyFunc(cur); else return commonTacticBodyLE(cur); case dtProj: fpp_assert ( isPositive (curConcept.bp()) ); return commonTacticBodyProj ( cur.getRole(), cur.getC(), cur.getProjRole() ); case dtSplitConcept: return commonTacticBodySplit(cur); case dtChoose: fpp_assert ( isPositive (curConcept.bp()) ); return applyChooseRule ( curNode, cur.getC() ); default: fpp_unreachable(); return false; } } bool DlSatTester :: commonTacticBodyId ( const DLVertex& cur ) { #ifdef ENABLE_CHECKING fpp_assert ( isCNameTag(cur.Type()) ); // safety check #endif incStat(nIdCalls); const DepSet& dep = curConcept.getDep(); #ifdef RKG_USE_SIMPLE_RULES // check if we have some simple rules if ( isPositive(curConcept.bp()) ) switchResult ( applyExtraRulesIf(static_cast(cur.getConcept())) ); #endif // get either body(p) or inverse(body(p)), depends on sign of current ID BipolarPointer C = isPositive(curConcept.bp()) ? cur.getC() : inverse(cur.getC()); return addToDoEntry ( curNode, C, dep ); } /// @return true if the rule is applicable; set the dep-set accordingly bool DlSatTester :: applicable ( const TBox::TSimpleRule& rule ) { BipolarPointer bp = curConcept.bp(); const CWDArray& lab = curNode->label().getLabel(dtPConcept); // dep-set to keep track for all the concepts in a rule-head DepSet loc = curConcept.getDep(); for ( TBox::TSimpleRule::const_iterator p = rule.Body.begin(), p_end = rule.Body.end(); p < p_end; ++p ) { if ( (*p)->pName == bp ) continue; if ( findConceptClash ( lab, (*p)->pName, loc ) ) loc = getClashSet(); // such a concept exists -- rememeber clash set else // no such concept -- can not fire a rule return false; } // rule will be fired -- set the dep-set setClashSet(loc); return true; } bool DlSatTester :: applyExtraRules ( const TConcept* C ) { for ( TConcept::er_iterator p = C->er_begin(), p_end=C->er_end(); p < p_end; ++p ) { const TBox::TSimpleRule* rule = tBox.getSimpleRule(*p); incStat(nSRuleAdd); if ( rule->applicable(*this) ) // apply the rule's head { incStat(nSRuleFire); switchResult ( addToDoEntry ( curNode, rule->bpHead, getClashSet() ) ); } } return false; } /// add C to a set of session GCIs; init all nodes with (C,dep) bool DlSatTester :: addSessionGCI ( BipolarPointer C, const DepSet& dep ) { SessionGCIs.push_back(C); for ( DlCompletionGraph::iterator p = CGraph.begin(), p_end = CGraph.end(); p != p_end; ++p ) if ( isNodeGloballyUsed(*p) && addToDoEntry ( *p, C, dep, "sg" ) ) return true; return false; } bool DlSatTester :: commonTacticBodySingleton ( const DLVertex& cur ) { #ifdef ENABLE_CHECKING fpp_assert ( cur.Type() == dtPSingleton || cur.Type() == dtNSingleton ); // safety check #endif incStat(nSingletonCalls); // can use this rule only in the Nominal reasoner fpp_assert ( hasNominals() ); // if the test REALLY uses nominals, remember this encounterNominal = true; const TIndividual* C = static_cast(cur.getConcept()); fpp_assert ( C->node != NULL ); // if node for C was purged due to merge -- find proper one DepSet dep = curConcept.getDep(); DlCompletionTree* realNode = C->node->resolvePBlocker(dep); if ( realNode != curNode ) // check if o-rule is applicable // apply o-rule: merge 2 nodes // don't need to actually expand P: it was/will be done in C->node return Merge ( curNode, realNode, dep ); // singleton behaves as a general named concepts besides nominal cloud return commonTacticBodyId(cur); } //------------------------------------------------------------------------------- // AND/OR processing //------------------------------------------------------------------------------- bool DlSatTester :: commonTacticBodyAnd ( const DLVertex& cur ) { #ifdef ENABLE_CHECKING fpp_assert ( isPositive(curConcept.bp()) && ( cur.Type() == dtAnd ) ); // safety check #endif incStat(nAndCalls); const DepSet& dep = curConcept.getDep(); // FIXME!! I don't know why, but performance is usually BETTER if using r-iters. // It's their only usage, so after investigation they can be dropped for ( DLVertex::const_reverse_iterator q = cur.rbegin(); q != cur.rend(); ++q ) switchResult ( addToDoEntry ( curNode, *q, dep ) ); return false; } bool DlSatTester :: commonTacticBodyOr ( const DLVertex& cur ) // for C \or D concepts { #ifdef ENABLE_CHECKING fpp_assert ( isNegative(curConcept.bp()) && cur.Type() == dtAnd ); // safety check #endif incStat(nOrCalls); if ( isFirstBranchCall() ) // check the structure of OR operation (number of applicable concepts) { DepSet dep; if ( planOrProcessing ( cur, dep ) ) { // found existing component if ( LLM.isWritable(llGTA) ) LL << " E(" << OrConceptsToTest.back() << ")"; return false; } if ( OrConceptsToTest.empty() ) { // no more applicable concepts: // set global dep-set using accumulated deps setClashSet(dep); return true; } // not a branching: just add a single concept if ( OrConceptsToTest.size() == 1 ) { ConceptWDep C = OrConceptsToTest.back(); return insertToDoEntry ( curNode, ConceptWDep(C,dep), DLHeap[C].Type(), "bcp" ); } // more than one alternative: use branching context createBCOr(); bContext->branchDep = dep; static_cast(bContext)->applicableOrEntries.swap(OrConceptsToTest); } // now it is OR case with 1 or more applicable concepts return processOrEntry(); } bool DlSatTester :: planOrProcessing ( const DLVertex& cur, DepSet& dep ) { OrConceptsToTest.clear(); dep = curConcept.getDep(); // check all OR components for the clash const CGLabel& lab = curNode->label(); for ( DLVertex::const_iterator q = cur.begin(), q_end = cur.end(); q < q_end; ++q ) { ConceptWDep C(inverse(*q)); switch ( tryAddConcept ( lab.getLabel(DLHeap[C].Type()), C.bp(), C.getDep() ) ) { case acrClash: // clash found -- OK dep.add(getClashSet()); continue; case acrExist: // already have such concept -- save it to the 1st position OrConceptsToTest.resize(1); OrConceptsToTest[0] = C; return true; case acrDone: OrConceptsToTest.push_back(C); continue; default: // safety check fpp_unreachable(); } } return false; } bool DlSatTester :: processOrEntry ( void ) { // save the context here as after save() it would be lost const BCOr* bcOr = static_cast(bContext); BCOr::or_iterator p = bcOr->orBeg(), p_end = bcOr->orCur(); ConceptWDep C = *p_end; const char* reason = NULL; DepSet dep; if ( bcOr->isLastOrEntry() ) { // cumulative dep-set will be used prepareBranchDep(); dep = getBranchDep(); // no more branching decisions determiniseBranchingOp(); reason = "bcp"; } else { // save current state save(); // new (just branched) dep-set dep = getCurDepSet(); incStat(nOrBrCalls); } // if semantic branching is in use -- add previous entries to the label if ( useSemanticBranching() ) for ( ; p < p_end; ++p ) if ( addToDoEntry ( curNode, ConceptWDep(inverse(*p),dep), "sb" ) ) fpp_unreachable(); // Both Exists and Clash are errors // add new entry to current node; we know the result would be DONE return # ifdef RKG_USE_DYNAMIC_BACKJUMPING addToDoEntry ( curNode, ConceptWDep(C,dep), reason ); # else insertToDoEntry ( curNode, ConceptWDep(C,dep), DLHeap[C].Type(), reason ); # endif } //------------------------------------------------------------------------------- // ALL processing //------------------------------------------------------------------------------- bool DlSatTester :: commonTacticBodyAllComplex ( const DLVertex& cur ) { const DepSet& dep = curConcept.getDep(); unsigned int state = cur.getState(); BipolarPointer C = curConcept.bp()-state; // corresponds to AR{0}.X const RAStateTransitions& RST = cur.getRole()->getAutomaton()[state]; RAStateTransitions::const_iterator q, end = RST.end(); // apply all empty transitions if ( RST.hasEmptyTransition() ) for ( q = RST.begin(); q != end; ++q ) { incStat(nAutoEmptyLookups); if ( (*q)->empty() ) switchResult ( addToDoEntry ( curNode, C+(*q)->final(), dep, "e" ) ); } // apply all top-role transitions if ( unlikely(RST.hasTopTransition()) ) for ( q = RST.begin(); q != end; ++q ) if ( (*q)->isTop() ) switchResult ( addSessionGCI ( C+(*q)->final(), dep ) ); // apply final-state rule if ( state == 1 ) switchResult ( addToDoEntry ( curNode, cur.getC(), dep ) ); // check whether automaton applicable to any edges incStat(nAllCalls); // check all neighbours for ( DlCompletionTree::const_edge_iterator p = curNode->begin(), p_end = curNode->end(); p < p_end; ++p ) if ( RST.recognise((*p)->getRole()) ) switchResult ( applyTransitions ( (*p), RST, C, dep+(*p)->getDep() ) ); return false; } bool DlSatTester :: commonTacticBodyAllSimple ( const DLVertex& cur ) { const RAStateTransitions& RST = cur.getRole()->getAutomaton()[0]; const DepSet& dep = curConcept.getDep(); BipolarPointer C = cur.getC(); // check whether automaton applicable to any edges incStat(nAllCalls); // check all neighbours; as the role is simple then recognise() == applicable() for ( DlCompletionTree::const_edge_iterator p = curNode->begin(), p_end = curNode->end(); p < p_end; ++p ) if ( RST.recognise((*p)->getRole()) ) switchResult ( addToDoEntry ( (*p)->getArcEnd(), C, dep+(*p)->getDep() ) ); return false; } //------------------------------------------------------------------------------- // Support for ALL processing //------------------------------------------------------------------------------- /** Perform expansion of (C=\AR{state}.X).DEP to an EDGE with a given reason */ bool DlSatTester :: applyTransitions ( const DlCompletionTreeArc* edge, const RAStateTransitions& RST, BipolarPointer C, const DepSet& dep, const char* reason ) { DlCompletionTree* node = edge->getArcEnd(); // fast lane: the single transition which is applicable if ( RST.isSingleton() ) return addToDoEntry ( node, C+RST.getTransitionEnd(), dep, reason ); RAStateTransitions::const_iterator q, end = RST.end(); const TRole* R = edge->getRole(); // try to apply all transitions to edge for ( q = RST.begin(); q != end; ++q ) { incStat(nAutoTransLookups); if ( (*q)->applicable(R) ) switchResult ( addToDoEntry ( node, C+(*q)->final(), dep, reason ) ); } return false; } //------------------------------------------------------------------------------- // SOME processing //------------------------------------------------------------------------------- bool DlSatTester :: commonTacticBodySome ( const DLVertex& cur ) // for ER.C concepts { #ifdef ENABLE_CHECKING fpp_assert ( isNegative(curConcept.bp()) && cur.Type() == dtForall ); #endif const DepSet& dep = curConcept.getDep(); const TRole* R = cur.getRole(); BipolarPointer C = inverse(cur.getC()); if ( unlikely(R->isTop()) ) return commonTacticBodySomeUniv(cur); // check if we already have R-neighbour labelled with C if ( isSomeExists ( R, C ) ) return false; // try to check the case (some R (or C D)), where C is in the label of an R-neighbour if ( isNegative(C) && DLHeap[C].Type() == dtAnd ) for ( DLVertex::const_iterator q = DLHeap[C].begin(), q_end = DLHeap[C].end(); q < q_end; ++q ) if ( isSomeExists ( R, inverse(*q) ) ) return false; // check for the case \ER.{o} if ( tBox.testHasNominals() && isPositive(C) ) { const DLVertex& nom = DLHeap[C]; if ( nom.Type() == dtPSingleton || nom.Type() == dtNSingleton ) return commonTacticBodyValue ( R, static_cast(nom.getConcept()) ); } incStat(nSomeCalls); // check if we have functional role if ( R->isFunctional() ) for ( TRole::const_iterator r = R->begin_topfunc(), r_end = R->end_topfunc(); r != r_end; ++r ) switch ( tryAddConcept ( curNode->label().getLabel(dtLE), (*r)->getFunctional(), dep ) ) { case acrClash: // addition leads to clash return true; case acrDone: // should be add to a label { // we are changing current Node => save it updateLevel ( curNode, dep ); ConceptWDep rFuncRestriction ( (*r)->getFunctional(), dep ); // NOTE! not added into TODO (because will be checked right now) CGraph.addConceptToNode ( curNode, rFuncRestriction, dtLE ); setUsed(rFuncRestriction.bp()); if ( LLM.isWritable(llGTA) ) LL << " nf(" << rFuncRestriction << ")"; } break; case acrExist: // already exists break; default: // safety check fpp_unreachable(); } bool rFunc = false; // flag is true if we have functional restriction with this Role name const TRole* RF = R; // most general functional super-role of given one ConceptWDep rFuncRestriction; // role's functional restriction w/dep // set up rFunc; rfRole contains more generic functional superrole of rName for ( DlCompletionTree::const_label_iterator pc = curNode->beginl_cc(); pc != curNode->endl_cc(); ++pc ) { // found such vertex (<=1 R) const ConceptWDep& LC = *pc; const DLVertex& ver = DLHeap[LC]; if ( isPositive(LC.bp()) && isFunctionalVertex(ver) && *ver.getRole() >= *R ) if ( !rFunc || // 1st functional restriction found or another one... *ver.getRole() >= *RF ) // ... with more generic role { rFunc = true; RF = ver.getRole(); rFuncRestriction = LC; } } if ( rFunc ) // functional role found => add new concept to existing node { const DlCompletionTreeArc* functionalArc = NULL; DepSet newDep; // check if we have an (R)-successor or (R-)-predecessor for ( DlCompletionTree::const_edge_iterator pr = curNode->begin(), pr_end = curNode->end(); !functionalArc && pr < pr_end ; ++pr ) if ( (*pr)->isNeighbour ( RF, newDep ) ) functionalArc = *pr; // perform actions if such arc was found if ( functionalArc != NULL ) { if ( LLM.isWritable(llGTA) ) LL << " f(" << rFuncRestriction << "):"; DlCompletionTree* succ = functionalArc->getArcEnd(); // add current dependences (from processed entry) newDep.add(dep); // check if merging will lead to clash because of disjoint roles if ( R->isDisjoint() && checkDisjointRoleClash ( curNode, succ, R, newDep ) ) return true; // add current role label (to both arc and its reverse) functionalArc = CGraph.addRoleLabel ( curNode, succ, functionalArc->isPredEdge(), R, newDep ); // adds concept to the end of arc switchResult ( addToDoEntry ( succ, C, newDep ) ); // if new role label was added... if ( RF != R ) { // add Range and Domain of a new role; this includes functional, so remove it from the latter switchResult ( initHeadOfNewEdge ( curNode, R, newDep, "RD" ) ); switchResult ( initHeadOfNewEdge ( succ, R->inverse(), newDep, "RR" ) ); // check AR.C in both sides of functionalArc // FIXME!! for simplicity, check the functionality here (see bEx017). It seems // only necessary when R has several functional super-roles, so the condition // can be simplified switchResult ( applyUniversalNR ( curNode, functionalArc, newDep, redoForall | redoFunc ) ); // if new role label was added to a functionalArc, some functional restrictions // in the SUCC node might became applicable. See bFunctional1x test switchResult ( applyUniversalNR ( succ, functionalArc->getReverse(), newDep, redoForall | redoFunc | redoAtMost ) ); } return false; } } //------------------------------------------------ // no functional role or 1st arc -- create new arc //------------------------------------------------ // there no such neighbour - create new successor // all FUNCs are already checked; no (new) irreflexivity possible return createNewEdge ( cur.getRole(), C, redoForall|redoAtMost ); } /// expansion rule for existential quantifier in the form ER {o} bool DlSatTester :: commonTacticBodyValue ( const TRole* R, const TIndividual* nom ) { DepSet dep(curConcept.getDep()); // check blocking conditions if ( isCurNodeBlocked() ) return false; incStat(nSomeCalls); fpp_assert ( nom->node != NULL ); // if node for NOM was purged due to merge -- find proper one DlCompletionTree* realNode = nom->node->resolvePBlocker(dep); // check if merging will lead to clash because of disjoint roles if ( R->isDisjoint() && checkDisjointRoleClash ( curNode, realNode, R, dep ) ) return true; // here we are sure that there is a nominal connected to a root node encounterNominal = true; // create new edge between curNode and the given nominal node DlCompletionTreeArc* edge = CGraph.addRoleLabel ( curNode, realNode, /*linkToParent=*/false, R, dep ); // add all necessary concepts to both ends of the edge return setupEdge ( edge, dep, redoForall|redoFunc|redoAtMost|redoIrr ); } bool DlSatTester :: commonTacticBodySomeUniv ( const DLVertex& cur ) { // check blocking conditions if ( isCurNodeBlocked() ) return false; incStat(nSomeCalls); BipolarPointer C = inverse(cur.getC()); // check whether C is already in CGraph for ( DlCompletionGraph::iterator p = CGraph.begin(), p_end = CGraph.end(); p != p_end; ++p ) if ( isObjectNodeUnblocked(*p) && (*p)->label().contains(C) ) return false; // make new node labeled with C return initNewNode ( CGraph.getNewNode(), curConcept.getDep(), C ); } //------------------------------------------------------------------------------- // Support for SOME processing //------------------------------------------------------------------------------- bool DlSatTester :: createNewEdge ( const TRole* R, BipolarPointer C, unsigned int flags ) { const DepSet& dep = curConcept.getDep(); // check blocking conditions if ( isCurNodeBlocked() ) { incStat(nUseless); return false; } DlCompletionTreeArc* pA = createOneNeighbour ( R, dep ); // add necessary label return initNewNode ( pA->getArcEnd(), dep, C ) || setupEdge ( pA, dep, flags ); } /// create new ROLE-neighbour to curNode; return edge to it DlCompletionTreeArc* DlSatTester :: createOneNeighbour ( const TRole* R, const DepSet& dep, CTNominalLevel level ) { // check whether is called from NN-rule bool forNN = level != BlockableLevel; // create a proper neighbour DlCompletionTreeArc* pA = CGraph.createNeighbour ( curNode, /*isPredEdge=*/forNN, R, dep ); DlCompletionTree* node = pA->getArcEnd(); // set nominal node's level if necessary if ( forNN ) node->setNominalLevel(level); // check whether created node is data node if ( R->isDataRole() ) node->setDataNode(); // log newly created node CHECK_LL_RETURN_VALUE(llGTA,pA); if ( R->isDataRole() ) LL << " DN("; else LL << " cn("; LL << node->getId() << dep << ")"; return pA; } bool DlSatTester :: isCurNodeBlocked ( void ) { // for non-lazy blocking blocked status is correct if ( !useLazyBlocking() ) return curNode->isBlocked(); // update node's blocked status if ( !curNode->isBlocked() && curNode->isAffected() ) { updateLevel ( curNode, curConcept.getDep() ); CGraph.detectBlockedStatus(curNode); } return curNode->isBlocked(); } void DlSatTester :: applyAllGeneratingRules ( DlCompletionTree* node ) { const CGLabel& label = node->label(); for ( CGLabel::const_iterator p = label.begin_cc(), p_end = label.end_cc(); p != p_end; ++p ) { // need only ER.C or >=nR.C concepts if ( isPositive(p->bp()) ) continue; switch ( DLHeap[*p].Type() ) { case dtForall: case dtLE: addExistingToDoEntry ( node, label.getCCOffset(p), "ubd" ); break; default: break; } } } bool DlSatTester :: setupEdge ( DlCompletionTreeArc* pA, const DepSet& dep, unsigned int flags ) { DlCompletionTree* child = pA->getArcEnd(); DlCompletionTree* from = pA->getReverse()->getArcEnd(); // adds Range and Domain switchResult ( initHeadOfNewEdge ( from, pA->getRole(), dep, "RD" ) ); switchResult ( initHeadOfNewEdge ( child, pA->getReverse()->getRole(), dep, "RR" ) ); // check if we have any AR.X concepts in current node switchResult ( applyUniversalNR ( from, pA, dep, flags ) ); // for nominal children and loops -- just apply things for the inverses if ( pA->isPredEdge() || child->isNominalNode() || child == from ) switchResult ( applyUniversalNR ( child, pA->getReverse(), dep, flags ) ); else { if ( child->isDataNode() ) { checkDataNode = true; switchResult ( checkDataClash(child) ); } else // check if it is possible to use cache for new node switchResult ( usageByState(tryCacheNode(child)) ); } // all done return false; } bool DlSatTester :: applyUniversalNR ( DlCompletionTree* Node, const DlCompletionTreeArc* arcSample, const DepSet& dep_, unsigned int flags ) { // check whether a flag is set if ( flags == 0 ) return false; const TRole* R = arcSample->getRole(); DepSet dep = dep_ + arcSample->getDep(); for ( DlCompletionTree::const_label_iterator p = Node->beginl_cc(), p_end = Node->endl_cc(); p != p_end; ++p ) { // need only AR.C concepts where ARC is labelled with R if ( isNegative(p->bp()) ) continue; const DLVertex& v = DLHeap[*p]; const TRole* vR = v.getRole(); switch ( v.Type() ) { case dtIrr: if ( flags & redoIrr ) switchResult ( checkIrreflexivity ( arcSample, vR, dep ) ); break; case dtForall: { if ( (flags & redoForall) == 0 ) break; if ( unlikely(vR->isTop()) ) break; /// check whether transition is possible const RAStateTransitions& RST = vR->getAutomaton()[v.getState()]; if ( !RST.recognise(R) ) break; if ( vR->isSimple() ) // R is recognised so just add the final state! switchResult ( addToDoEntry ( arcSample->getArcEnd(), v.getC(), dep+p->getDep(), "ae" ) ); else switchResult ( applyTransitions ( arcSample, RST, p->bp()-v.getState(), dep+p->getDep(), "ae" ) ); break; } case dtLE: if ( isFunctionalVertex(v) ) { if ( (flags & redoFunc) && (*vR >= *R) ) addExistingToDoEntry ( Node, Node->label().getCCOffset(p), "f" ); } else if ( (flags & redoAtMost) && (*vR >= *R) ) addExistingToDoEntry ( Node, Node->label().getCCOffset(p), "le" ); break; default: break; } } return false; } /// add necessary concepts to the head of the new EDGE bool DlSatTester :: initHeadOfNewEdge ( DlCompletionTree* node, const TRole* R, const DepSet& dep, const char* reason ) { // define return value TRole::const_iterator r, r_end; // if R is functional, then add FR with given DEP-set to NODE if ( R->isFunctional() ) for ( r = R->begin_topfunc(), r_end = R->end_topfunc(); r != r_end; ++r ) switchResult ( addToDoEntry ( node, (*r)->getFunctional(), dep, "fr" ) ); // setup Domain for R switchResult ( addToDoEntry ( node, R->getBPDomain(), dep, reason ) ); # ifndef RKG_UPDATE_RND_FROM_SUPERROLES for ( r = R->begin_anc(), r_end = R->end_anc(); r < r_end; ++r ) switchResult ( addToDoEntry ( node, (*r)->getBPDomain(), dep, reason ) ); # endif return false; } //------------------------------------------------------------------------------- // Func/LE/GE processing //------------------------------------------------------------------------------- bool DlSatTester :: commonTacticBodyFunc ( const DLVertex& cur ) // for <=1 R concepts { #ifdef ENABLE_CHECKING fpp_assert ( isPositive(curConcept.bp()) && isFunctionalVertex(cur) ); #endif const TRole* R = cur.getRole(); if ( unlikely(R->isTop()) ) return processTopRoleFunc(cur); // check whether we need to apply NN rule first if ( isNNApplicable ( R, bpTOP, curConcept.bp()+1 ) ) return commonTacticBodyNN(cur); // after application func-rule would be checked again incStat(nFuncCalls); if ( isQuickClashLE(cur) ) return true; // locate all R-neighbours of curNode DepSet dummy; // not used findNeighbours ( R, bpTOP, dummy ); // check if we have nodes to merge if ( EdgesToMerge.size() < 2 ) return false; // merge all nodes to the first (the least wrt nominal hierarchy) found node EdgeVector::iterator q = EdgesToMerge.begin(), q_end = EdgesToMerge.end(); DlCompletionTree* sample = (*q)->getArcEnd(); DepSet depF (curConcept.getDep()); // dep-set for merging depF.add((*q)->getDep()); // merge all elements to sample (sample wouldn't be merge) while ( ++q != q_end ) // during merge EdgesToMerge may became purged (see Nasty4) => check this if ( !(*q)->getArcEnd()->isPBlocked() ) switchResult ( Merge ( (*q)->getArcEnd(), sample, depF+(*q)->getDep() ) ); return false; } bool DlSatTester :: commonTacticBodyLE ( const DLVertex& cur ) // for <=nR.C concepts { #ifdef ENABLE_CHECKING fpp_assert ( isPositive(curConcept.bp()) && ( cur.Type() == dtLE ) ); #endif incStat(nLeCalls); const TRole* R = cur.getRole(); if ( unlikely(R->isTop()) ) return processTopRoleLE(cur); BipolarPointer C = cur.getC(); bool needInit = true; if ( !isFirstBranchCall() ) { if ( dynamic_cast(bContext) != NULL ) return commonTacticBodyNN(cur); // after application <=-rule would be checked again if ( dynamic_cast*>(bContext) != NULL ) needInit = false; // clash in LE-rule: skip the initial checks else // the only possible case is choose-rule; in this case just continue fpp_assert ( dynamic_cast(bContext) != NULL ); } else // if we are here that it IS first LE call if ( isQuickClashLE(cur) ) return true; // initial phase: choose-rule, NN-rule if ( needInit ) { // check if we have Qualified NR if ( C != bpTOP ) switchResult ( commonTacticBodyChoose ( R, C ) ); // check whether we need to apply NN rule first if ( isNNApplicable ( R, C, /*stopper=*/curConcept.bp()+cur.getNumberLE() ) ) return commonTacticBodyNN(cur); // after application <=-rule would be checked again } // we need to repeat merge until there will be necessary amount of edges while (1) { if ( isFirstBranchCall() ) if ( initLEProcessing(cur) ) return false; BCLE* bcLE = static_cast*>(bContext); if ( bcLE->noMoreLEOptions() ) { // set global clashset to cumulative one from previous branch failures useBranchDep(); return true; } // get from- and to-arcs using corresponding indexes in Edges DlCompletionTreeArc* fromArc = bcLE->getFrom(); DlCompletionTreeArc* toArc = bcLE->getTo(); DlCompletionTree* from = fromArc->getArcEnd(); DlCompletionTree* to = toArc->getArcEnd(); DepSet dep; // empty dep-set // fast check for FROM =/= TO if ( CGraph.nonMergable ( from, to, dep ) ) { // need this for merging two nominal nodes dep.add(fromArc->getDep()); dep.add(toArc->getDep()); // add dep-set from labels if ( C == bpTOP ) // dep-set is known now setClashSet(dep); else // QCR: update dep-set wrt C { // here we know that C is in both labels; set a proper clash-set DagTag tag = DLHeap[C].Type(); bool test; // here dep contains the clash-set test = findConceptClash ( from->label().getLabel(tag), C, dep ); fpp_assert(test); dep += getClashSet(); // save new dep-set test = findConceptClash ( to->label().getLabel(tag), C, dep ); fpp_assert(test); // both clash-sets are now in common clash-set } updateBranchDep(); bContext->nextOption(); fpp_assert(!isFirstBranchCall()); continue; } save(); // add depset from current level and FROM arc and to current dep.set DepSet curDep(getCurDepSet()); curDep.add(fromArc->getDep()); switchResult ( Merge ( from, to, curDep ) ); // it might be the case (see bIssue28) that after the merge there is an R-neigbour // that have neither C or ~C in its label (it was far in the nominal cloud) if ( C != bpTOP ) switchResult ( commonTacticBodyChoose ( R, C ) ); } } bool DlSatTester :: initLEProcessing ( const DLVertex& cur ) { DepSet dep; // check the amount of neighbours we have findNeighbours ( cur.getRole(), cur.getC(), dep ); // if the number of R-neighbours satisfies condition -- nothing to do if ( EdgesToMerge.size() <= cur.getNumberLE() ) return true; // init context createBCLE(); bContext->branchDep += dep; // setup BCLE BCLE* bcLE = static_cast*>(bContext); bcLE->ItemsToMerge.swap(EdgesToMerge); bcLE->resetMCI(); return false; } bool DlSatTester :: commonTacticBodyGE ( const DLVertex& cur ) // for >=nR.C concepts { #ifdef ENABLE_CHECKING fpp_assert ( isNegative(curConcept.bp()) && cur.Type() == dtLE ); #endif // check blocking conditions if ( isCurNodeBlocked() ) return false; const TRole* R = cur.getRole(); if ( unlikely(R->isTop()) ) return processTopRoleGE(cur); incStat(nGeCalls); if ( isQuickClashGE(cur) ) return true; // create N new different edges return createDifferentNeighbours ( R, cur.getC(), curConcept.getDep(), cur.getNumberGE(), BlockableLevel ); } //------------------------------------------------------------------------------- // Func/LE/GE with top role processing //------------------------------------------------------------------------------- bool DlSatTester :: processTopRoleFunc ( const DLVertex& cur ) // for <=1 R concepts { #ifdef ENABLE_CHECKING fpp_assert ( isPositive(curConcept.bp()) && isFunctionalVertex(cur) ); #endif incStat(nFuncCalls); if ( isQuickClashLE(cur) ) return true; // locate all R-neighbours of curNode DepSet dummy; // not used findCLabelledNodes ( bpTOP, dummy ); // check if we have nodes to merge if ( NodesToMerge.size() < 2 ) return false; // merge all nodes to the first (the least wrt nominal hierarchy) found node NodeVector::iterator q = NodesToMerge.begin(), q_end = NodesToMerge.end(); DlCompletionTree* sample = *q; DepSet dep (curConcept.getDep()); // dep-set for merging // merge all elements to sample (sample wouldn't be merge) while ( ++q != q_end ) // during merge EdgesToMerge may became purged (see Nasty4) => check this if ( !(*q)->isPBlocked() ) switchResult ( Merge ( *q, sample, dep ) ); return false; } bool DlSatTester :: processTopRoleLE ( const DLVertex& cur ) // for <=nR.C concepts { #ifdef ENABLE_CHECKING fpp_assert ( isPositive(curConcept.bp()) && ( cur.Type() == dtLE ) ); #endif BipolarPointer C = cur.getC(); bool needInit = true; if ( !isFirstBranchCall() ) { if ( dynamic_cast*>(bContext) != NULL ) needInit = false; // clash in LE-rule: skip the initial checks else // the only possible case is choose-rule; in this case just continue fpp_assert ( dynamic_cast(bContext) != NULL ); } else // if we are here that it IS first LE call if ( isQuickClashLE(cur) ) return true; // initial phase: choose-rule, NN-rule if ( needInit ) { // check if we have Qualified NR if ( C != bpTOP ) switchResult ( applyChooseRuleGlobally(C) ); } // we need to repeat merge until there will be necessary amount of edges while (1) { if ( isFirstBranchCall() ) if ( initTopLEProcessing(cur) ) return false; BCLE* bcLE = static_cast*>(bContext); if ( bcLE->noMoreLEOptions() ) { // set global clashset to cumulative one from previous branch failures useBranchDep(); return true; } // get from- and to-arcs using corresponding indexes in Edges DlCompletionTree* from = bcLE->getFrom(); DlCompletionTree* to = bcLE->getTo(); DepSet dep; // empty dep-set // fast check for FROM =/= TO if ( CGraph.nonMergable ( from, to, dep ) ) { // add dep-set from labels if ( C == bpTOP ) // dep-set is known now setClashSet(dep); else // QCR: update dep-set wrt C { // here we know that C is in both labels; set a proper clash-set DagTag tag = DLHeap[C].Type(); bool test; // here dep contains the clash-set test = findConceptClash ( from->label().getLabel(tag), C, dep ); fpp_assert(test); dep += getClashSet(); // save new dep-set test = findConceptClash ( to->label().getLabel(tag), C, dep ); fpp_assert(test); // both clash-sets are now in common clash-set } updateBranchDep(); bContext->nextOption(); fpp_assert(!isFirstBranchCall()); continue; } save(); // add depset from current level and FROM arc and to current dep.set DepSet curDep(getCurDepSet()); switchResult ( Merge ( from, to, curDep ) ); } } bool DlSatTester :: processTopRoleGE ( const DLVertex& cur ) // for >=nR.C concepts { #ifdef ENABLE_CHECKING fpp_assert ( isNegative(curConcept.bp()) && cur.Type() == dtLE ); fpp_assert ( !isCurNodeBlocked() ); #endif incStat(nGeCalls); if ( isQuickClashGE(cur) ) return true; // create N new different edges // FIXME!! for now return createDifferentNeighbours ( cur.getRole(), cur.getC(), curConcept.getDep(), cur.getNumberGE(), BlockableLevel ); } bool DlSatTester :: initTopLEProcessing ( const DLVertex& cur ) { DepSet dep; // check the amount of neighbours we have findCLabelledNodes ( cur.getC(), dep ); // if the number of R-neighbours satisfies condition -- nothing to do if ( NodesToMerge.size() <= cur.getNumberLE() ) return true; // init context createBCTopLE(); bContext->branchDep += dep; // setup BCLE BCLE* bcLE = static_cast*>(bContext); bcLE->ItemsToMerge.swap(NodesToMerge); bcLE->resetMCI(); return false; } //------------------------------------------------------------------------------- // Support for Func/LE/GE processing //------------------------------------------------------------------------------- /// create N R-neighbours of curNode with given Nominal LEVEL labelled with C bool DlSatTester :: createDifferentNeighbours ( const TRole* R, BipolarPointer C, const DepSet& dep, unsigned int n, CTNominalLevel level ) { // create N new edges with the same IR DlCompletionTreeArc* pA = NULL; CGraph.initIR(); for ( unsigned int i = 0; i < n; ++i ) { pA = createOneNeighbour ( R, dep, level ); DlCompletionTree* child = pA->getArcEnd(); // make CHILD different from other created nodes // don't care about return value as clash can't occur CGraph.setCurIR ( child, dep ); // add necessary new node labels and setup new edge switchResult ( initNewNode ( child, dep, C ) ); switchResult ( setupEdge ( pA, dep, redoForall ) ); } CGraph.finiIR(); // re-apply all <= NR in curNode; do it only once for all created nodes; no need for Irr return applyUniversalNR ( curNode, pA, dep, redoFunc|redoAtMost ); } /// check if ATLEAST and ATMOST restrictions are in clash; setup depset from CUR bool DlSatTester :: isNRClash ( const DLVertex& atleast, const DLVertex& atmost, const ConceptWDep& reason ) { if ( atmost.Type() != dtLE || atleast.Type() != dtLE ) return false; if ( !checkNRclash ( atleast, atmost ) ) // no clash between them return false; // clash exists: create dep-set setClashSet ( curConcept.getDep() + reason.getDep() ); // log clash reason if ( LLM.isWritable(llGTA) ) logClash ( curNode, reason ); return true; } /// aux method that checks whether clash occurs during the merge of labels bool DlSatTester :: checkMergeClash ( const CGLabel& from, const CGLabel& to, const DepSet& dep, unsigned int nodeId ) { CGLabel::const_iterator p, p_end; DepSet clashDep(dep); bool clash = false; for ( p = from.begin_sc(), p_end = from.end_sc(); p < p_end; ++p ) if ( isUsed(inverse(p->bp())) && findConceptClash ( to.getLabel(dtPConcept), inverse(*p) ) ) { clash = true; clashDep.add(getClashSet()); // log the clash if ( LLM.isWritable(llGTA) ) LL << " x(" << nodeId << "," << p->bp() << getClashSet()+dep << ")"; } for ( p = from.begin_cc(), p_end = from.end_cc(); p < p_end; ++p ) if ( isUsed(inverse(p->bp())) && findConceptClash ( to.getLabel(dtForall), inverse(*p) ) ) { clash = true; clashDep.add(getClashSet()); // log the clash if ( LLM.isWritable(llGTA) ) LL << " x(" << nodeId << "," << p->bp() << getClashSet()+dep << ")"; } if ( clash ) setClashSet(clashDep); return clash; } bool DlSatTester :: mergeLabels ( const CGLabel& from, DlCompletionTree* to, const DepSet& dep ) { CGLabel::const_iterator p, p_end; CGLabel& lab(to->label()); // arrays for simple- and complex concepts in the merged-to vector CWDArray& sc(lab.getLabel(dtPConcept)); CWDArray& cc(lab.getLabel(dtForall)); // due to merging, all the concepts in the TO label // should be updated to the new dep-set DEP for ( p = sc.begin(), p_end = sc.end(); p < p_end; ++p ) CGraph.saveRareCond ( sc.updateDepSet ( p->bp(), dep ) ); for ( p = cc.begin(), p_end = cc.end(); p < p_end; ++p ) CGraph.saveRareCond ( cc.updateDepSet ( p->bp(), dep ) ); // if the concept is already exists in the node label -- // we still need to update it with a new dep-set (due to merging) // note that DEP is already there for ( p = from.begin_sc(), p_end = from.end_sc(); p < p_end; ++p ) if ( findConcept ( sc, *p ) ) CGraph.saveRareCond ( sc.updateDepSet ( p->bp(), p->getDep() ) ); else switchResult ( insertToDoEntry ( to, ConceptWDep(*p,dep), DLHeap[*p].Type(), "M" ) ); for ( p = from.begin_cc(), p_end = from.end_cc(); p < p_end; ++p ) if ( findConcept ( cc, *p ) ) CGraph.saveRareCond ( cc.updateDepSet ( p->bp(), p->getDep() ) ); else switchResult ( insertToDoEntry ( to, ConceptWDep(*p,dep), DLHeap[*p].Type(), "M" ) ); return false; } bool DlSatTester :: Merge ( DlCompletionTree* from, DlCompletionTree* to, const DepSet& depF ) { // if node is already purged -- nothing to do fpp_assert ( !from->isPBlocked() ); // prevent node to be merged to itself fpp_assert ( from != to ); // never merge nominal node to blockable one fpp_assert ( to->getNominalLevel() <= from->getNominalLevel() ); if ( LLM.isWritable(llGTA) ) LL << " m(" << from->getId() << "->" << to->getId() << ")"; incStat(nMergeCalls); // can't merge 2 nodes which are in inequality relation DepSet dep(depF); if ( CGraph.nonMergable ( from, to, dep ) ) { setClashSet(dep); return true; } // check for the clash before doing anything else if ( checkMergeClash ( from->label(), to->label(), depF, to->getId() ) ) return true; // copy all node labels switchResult ( mergeLabels ( from->label(), to, depF ) ); // correct graph structure typedef std::vector edgeVector; edgeVector edges; CGraph.Merge ( from, to, depF, edges ); // check whether a disjoint roles lead to clash edgeVector::const_iterator q, q_end = edges.end(); for ( q = edges.begin(); q != q_end; ++q ) if ( (*q)->getRole()->isDisjoint() && checkDisjointRoleClash ( (*q)->getReverse()->getArcEnd(), (*q)->getArcEnd(), (*q)->getRole(), depF ) ) return true; // nothing more to do with data nodes if ( to->isDataNode() ) // data concept -- run data center for it return checkDataClash(to); // for every node added to TO, every ALL, Irr and <=-node should be checked for ( q = edges.begin(); q != q_end; ++q ) switchResult ( applyUniversalNR ( to, *q, depF, redoForall|redoFunc|redoAtMost|redoIrr ) ); // we do real action here, so the return value return false; } bool DlSatTester :: checkDisjointRoleClash ( DlCompletionTree* from, DlCompletionTree* to, const TRole* R, const DepSet& dep ) { // try to check whether link from->to labelled with something disjoint with R for ( DlCompletionTree::const_edge_iterator p = from->begin(), p_end = from->end(); p != p_end; ++p ) if ( checkDisjointRoleClash ( *p, to, R, dep ) ) return true; return false; } // compare 2 CT edges wrt blockable/nominal nodes at their ends class EdgeCompare { public: bool operator() ( DlCompletionTreeArc* pa, DlCompletionTreeArc* qa ) const { return *(pa)->getArcEnd() < *(qa)->getArcEnd(); } }; // EdgeCompare /// aux method to check whether edge ended to NODE should be added to EdgetoMerge template bool isNewEdge ( const DlCompletionTree* node, Iterator begin, Iterator end ) { for ( Iterator q = begin; q != end; ++q ) if ( (*q)->getArcEnd() == node ) // skip edges to the same node return false; return true; } void DlSatTester :: findNeighbours ( const TRole* Role, BipolarPointer C, DepSet& Dep ) { EdgesToMerge.clear(); DagTag tag = DLHeap[C].Type(); for ( DlCompletionTree::const_edge_iterator p = curNode->begin(), p_end = curNode->end(); p < p_end; ++p ) if ( (*p)->isNeighbour(Role) && isNewEdge ( (*p)->getArcEnd(), EdgesToMerge.begin(), EdgesToMerge.end() ) && findChooseRuleConcept ( (*p)->getArcEnd()->label().getLabel(tag), C, Dep ) ) EdgesToMerge.push_back(*p); // sort EdgesToMerge: From named nominals to generated nominals to blockable nodes std::sort ( EdgesToMerge.begin(), EdgesToMerge.end(), EdgeCompare() ); } class NodeCompare { public: bool operator() ( DlCompletionTree* p, DlCompletionTree* q ) const { return *p < *q; } }; void DlSatTester :: findCLabelledNodes ( BipolarPointer C, DepSet& Dep ) { NodesToMerge.clear(); DagTag tag = DLHeap[C].Type(); // FIXME!! do we need this for d-blocked nodes? for ( DlCompletionGraph::iterator p = CGraph.begin(), p_end = CGraph.end(); p != p_end; ++p ) if ( isNodeGloballyUsed(*p) && findChooseRuleConcept ( (*p)->label().getLabel(tag), C, Dep ) ) NodesToMerge.push_back(*p); // sort EdgesToMerge: From named nominals to generated nominals to blockable nodes std::sort ( NodesToMerge.begin(), NodesToMerge.end(), NodeCompare() ); } //------------------------------------------------------------------------------- // Choose-rule processing //------------------------------------------------------------------------------- bool DlSatTester :: commonTacticBodyChoose ( const TRole* R, BipolarPointer C ) { // apply choose-rule for every R-neighbour for ( DlCompletionTree::const_edge_iterator p = curNode->begin(), p_end = curNode->end(); p < p_end; ++p ) if ( (*p)->isNeighbour(R) ) switchResult ( applyChooseRule ( (*p)->getArcEnd(), C ) ); return false; } /// apply choose-rule for all vertices (necessary for Top role in QCR) bool DlSatTester :: applyChooseRuleGlobally ( BipolarPointer C ) { for ( DlCompletionGraph::iterator p = CGraph.begin(), p_end = CGraph.end(); p != p_end; ++p ) if ( isObjectNodeUnblocked(*p) ) // FIXME!! think about d-blocked nodes switchResult ( applyChooseRule ( *p, C ) ); return false; } //------------------------------------------------------------------------------- // Support for choose-rule processing //------------------------------------------------------------------------------- /// apply choose-rule to given node bool DlSatTester :: applyChooseRule ( DlCompletionTree* node, BipolarPointer C ) { if ( node->isLabelledBy(C) || node->isLabelledBy(inverse(C)) ) return false; // now node will be labelled with ~C or C if ( isFirstBranchCall() ) { createBCCh(); // save current state save(); return addToDoEntry ( node, inverse(C), getCurDepSet(), "cr0" ); } else { prepareBranchDep(); DepSet dep(getBranchDep()); determiniseBranchingOp(); return addToDoEntry ( node, C, dep, "cr1" ); } } //------------------------------------------------------------------------------- // NN rule processing //------------------------------------------------------------------------------- bool DlSatTester :: commonTacticBodyNN ( const DLVertex& cur ) // NN-rule { // here we KNOW that NN-rule is applicable, so skip some tests incStat(nNNCalls); if ( isFirstBranchCall() ) createBCNN(); const BCNN* bcNN = static_cast(bContext); // check whether we did all possible tries if ( bcNN->noMoreNNOptions(cur.getNumberLE()) ) { // set global clashset to cummulative one from previous branch failures useBranchDep(); return true; } // take next NN number; save it as SAVE() will reset it to 0 unsigned int NN = bcNN->value; // prepare to addition to the label save(); // new (just branched) dep-set const DepSet curDep(getCurDepSet()); // make a stopper to mark that NN-rule is applied switchResult ( addToDoEntry ( curNode, curConcept.bp() + cur.getNumberLE(), DepSet(), "NNs" ) ); // create curNN new different edges switchResult ( createDifferentNeighbours ( cur.getRole(), cur.getC(), curDep, NN, curNode->getNominalLevel()+1 ) ); // now remember NR we just created: it is (<= curNN R), so have to find it return addToDoEntry ( curNode, curConcept.bp() + (cur.getNumberLE()-NN), curDep, "NN" ); } //------------------------------------------------------------------------------- // Support for NN rule processing //------------------------------------------------------------------------------- /// @return true iff NN-rule wrt (<= R) is applicable to the curNode bool DlSatTester :: isNNApplicable ( const TRole* r, BipolarPointer C, BipolarPointer stopper ) const { // NN rule is only applicable to nominal nodes if ( !curNode->isNominalNode() ) return false; // check whether the NN-rule was already applied here for a given concept if ( isUsed(stopper) && curNode->isLabelledBy(stopper) ) return false; // check for the real applicability of the NN-rule here DlCompletionTree::const_edge_iterator p, p_end = curNode->end(), q; for ( p = curNode->begin(); p != p_end; ++p ) { const DlCompletionTree* suspect = (*p)->getArcEnd(); // if there is an edge that require to run the rule, then we need it if ( (*p)->isPredEdge() && suspect->isBlockableNode() && (*p)->isNeighbour(r) && suspect->isLabelledBy(C) ) { if ( LLM.isWritable(llGTA) ) LL << " NN(" << suspect->getId() << ")"; return true; } } // can't apply NN-rule return false; } //------------------------------------------------------------------------------- // Support for (\neg) \E R.Self //------------------------------------------------------------------------------- bool DlSatTester :: commonTacticBodySomeSelf ( const TRole* R ) { // check blocking conditions if ( isCurNodeBlocked() ) return false; // nothing to do if R-loop already exists for ( DlCompletionTree::const_edge_iterator p = curNode->begin(), p_end = curNode->end(); p < p_end; ++p ) if ( (*p)->getArcEnd() == curNode && (*p)->isNeighbour(R) ) return false; // create an R-loop through curNode const DepSet& dep = curConcept.getDep(); DlCompletionTreeArc* pA = CGraph.createLoop ( curNode, R, dep ); return setupEdge ( pA, dep, redoForall|redoFunc|redoAtMost|redoIrr ); } bool DlSatTester :: commonTacticBodyIrrefl ( const TRole* R ) { // return clash if R-loop is found for ( DlCompletionTree::const_edge_iterator p = curNode->begin(), p_end = curNode->end(); p < p_end; ++p ) if ( checkIrreflexivity ( *p, R, curConcept.getDep() ) ) return true; return false; } //------------------------------------------------------------------------------- // Support for projection R\C -> P //------------------------------------------------------------------------------- bool DlSatTester :: commonTacticBodyProj ( const TRole* R, BipolarPointer C, const TRole* ProjR ) { // find an R-edge, try to apply projection-rule to it // if ~C is in the label of curNode, do nothing if ( curNode->isLabelledBy(inverse(C)) ) return false; // checkProjection() might change curNode's edge vector and thusly invalidate iterators DlCompletionTree::const_edge_iterator p = curNode->begin(), p_end = curNode->end(); for ( int i = 0, n = p_end - p; i < n; ++i ) { p = curNode->begin() + i; if ( (*p)->isNeighbour(R) ) switchResult ( checkProjection ( *p, C, ProjR ) ); } return false; } bool DlSatTester :: checkProjection ( DlCompletionTreeArc* pA, BipolarPointer C, const TRole* ProjR ) { // nothing to do if pA is labelled by ProjR as well if ( pA->isNeighbour(ProjR) ) return false; // if ~C is in the label of curNode, do nothing if ( curNode->isLabelledBy(inverse(C)) ) return false; // neither C nor ~C are in the label: make a choice DepSet dep(curConcept.getDep()); dep.add(pA->getDep()); if ( !curNode->isLabelledBy(C) ) { if ( isFirstBranchCall() ) { createBCCh(); // save current state save(); return addToDoEntry ( curNode, inverse(C), getCurDepSet(), "cr0" ); } else { prepareBranchDep(); dep.add(getBranchDep()); determiniseBranchingOp(); switchResult ( addToDoEntry ( curNode, C, dep, "cr1" ) ); } } // here C is in the label of curNode: add ProjR to the edge if necessary DlCompletionTree* child = pA->getArcEnd(); pA = CGraph.addRoleLabel ( curNode, child, pA->isPredEdge(), ProjR, dep ); return setupEdge ( pA, dep, redoForall|redoFunc|redoAtMost|redoIrr ); } /// expansion rule for split bool DlSatTester :: commonTacticBodySplit ( const DLVertex& cur ) { if ( tBox.duringClassification && likely ( ActiveSplits.count(getValue(curConcept.bp())) == 0 ) ) return false; const DepSet& dep = curConcept.getDep(); bool pos = isPositive(curConcept.bp()); for ( DLVertex::const_iterator q = cur.begin(), q_end = cur.end(); q != q_end; ++q ) switchResult ( addToDoEntry ( curNode, createBiPointer(*q, pos), dep ) ); return false; } FaCTpp-src-v1.6.2~dfsg/src/Kernel/Modularity.h0000644000000000000000000001625012112642405017662 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2011-2012 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef MODULARITY_H #define MODULARITY_H #include // uncomment the next line to use AD to speed up modularisation //#define RKG_USE_AD_IN_MODULE_EXTRACTION #include "tOntology.h" #include "SigIndex.h" // locality checking #include "SemanticLocalityChecker.h" #include "SyntacticLocalityChecker.h" #include "ModuleType.h" #ifdef RKG_USE_AD_IN_MODULE_EXTRACTION # include "tOntologyAtom.h" #endif /// class to create modules of an ontology wrt module type class TModularizer { protected: // types /// RO iterator over axiom vector typedef AxiomVec::const_iterator const_iterator; protected: // members /// shared signature signature TSignature sig; /// internal syntactic locality checker LocalityChecker* Checker; /// module as a list of axioms AxiomVec Module; /// pointer to a sig index; if not NULL then use optimized algo SigIndex sigIndex; /// queue of unprocessed entities std::queue WorkQueue; /// number of locality check calls unsigned long long nChecks; /// number of non-local axioms unsigned long long nNonLocal; /// true if no atoms are processed ATM bool noAtomsProcessing; protected: // methods /// update SIG wrt the axiom signature void addAxiomSig ( const TSignature& axiomSig ) { for ( TSignature::iterator p = axiomSig.begin(), p_end = axiomSig.end(); p != p_end; ++p ) if ( !sig.contains(*p) ) // new one { WorkQueue.push(*p); sig.add(*p); } } /// add an axiom to a module void addAxiomToModule ( TDLAxiom* axiom ) { axiom->setInModule(true); Module.push_back(axiom); // update the signature addAxiomSig(axiom->getSignature()); } /// @return true iff an AXiom is non-local bool isNonLocal ( const TDLAxiom* ax ) { ++nChecks; if ( Checker->local(ax) ) return false; ++nNonLocal; return true; } /// add an axiom if it is non-local (or in noCheck is true) void addNonLocal ( TDLAxiom* ax, bool noCheck ) { if ( unlikely(noCheck) || unlikely(isNonLocal(ax)) ) { addAxiomToModule(ax); # ifdef RKG_USE_AD_IN_MODULE_EXTRACTION if ( noAtomsProcessing && ax->getAtom() != NULL ) { noAtomsProcessing = false; addNonLocal ( ax->getAtom()->getModule(), /*noCheck=*/true ); noAtomsProcessing = true; } # endif } } /// add all the non-local axioms from given axiom-set AxSet void addNonLocal ( const AxiomVec& AxSet, bool noCheck ) { for ( SigIndex::const_iterator q = AxSet.begin(), q_end = AxSet.end(); q != q_end; ++q ) if ( !(*q)->isInModule() && (*q)->isInSS() ) // in the given range but not in module yet addNonLocal ( *q, noCheck ); } /// build a module traversing axioms by a signature void extractModuleQueue ( void ) { // init queue with a sig for ( TSignature::iterator p = sig.begin(), p_end = sig.end(); p != p_end; ++p ) WorkQueue.push(*p); // add all the axioms that are non-local wrt given value of a top-locality addNonLocal ( sigIndex.getNonLocal(sig.topCLocal()), /*noCheck=*/true ); // main cycle while ( !WorkQueue.empty() ) { const TNamedEntity* entity = WorkQueue.front(); WorkQueue.pop(); // for all the axioms that contains entity in their signature addNonLocal ( sigIndex.getAxioms(entity), /*noCheck=*/false ); } } /// extract module wrt presence of a sig index void extractModule ( const_iterator begin, const_iterator end ) { Module.clear(); Module.reserve(end-begin); // clear the module flag in the input const_iterator p; for ( p = begin; p != end; ++p ) (*p)->setInModule(false); for ( p = begin; p != end; ++p ) if ( (*p)->isUsed() ) (*p)->setInSS(true); extractModuleQueue(); for ( p = begin; p != end; ++p ) (*p)->setInSS(false); } public: // interface /// init c'tor TModularizer ( bool useSem ) : Checker ( useSem ? (LocalityChecker*) new SemanticLocalityChecker(&sig) : (LocalityChecker*) new SyntacticLocalityChecker(&sig) ) , sigIndex(Checker) , nChecks(0) , nNonLocal(0) , noAtomsProcessing(true) {} // d'tor ~TModularizer ( void ) { delete Checker; } /// allow the checker to preprocess an ontology if necessary void preprocessOntology ( const AxiomVec& vec ) { Checker->preprocessOntology(vec); sigIndex.clear(); sigIndex.preprocessOntology(vec); } /// extract module wrt SIGNATURE and TYPE from the set of axioms [BEGIN,END) void extract ( const_iterator begin, const_iterator end, const TSignature& signature, ModuleType type ) { bool topLocality = (type == M_TOP); sig = signature; sig.setLocality(topLocality); extractModule ( begin, end ); if ( type != M_STAR ) return; // here there is a star: do the cycle until stabilization size_t size; AxiomVec oldModule; do { size = Module.size(); oldModule.swap(Module); topLocality = !topLocality; sig = signature; sig.setLocality(topLocality); extractModule ( oldModule.begin(), oldModule.end() ); } while ( size != Module.size() ); } /// extract module wrt SIGNATURE and TYPE from the axiom vector VEC void extract ( const AxiomVec& Vec, const TSignature& signature, ModuleType type ) { extract ( Vec.begin(), Vec.end(), signature, type ); } /// extract module wrt SIGNATURE and TYPE from O void extract ( TOntology& O, const TSignature& signature, ModuleType type ) { extract ( O.begin(), O.end(), signature, type ); } /// @return true iff the axiom AX is a tautology wrt given type bool isTautology ( TDLAxiom* ax, ModuleType type ) { bool topLocality = (type == M_TOP); sig = ax->getSignature(); sig.setLocality(topLocality); // axiom is a tautology if it is local wrt its own signature bool toReturn = Checker->local(ax); if ( likely ( type != M_STAR || !toReturn ) ) return toReturn; // here it is STAR case and AX is local wrt BOT sig.setLocality(!topLocality); return Checker->local(ax); } /// get RW access to the sigIndex (mainly to (un-)register axioms on the fly) SigIndex* getSigIndex ( void ) { return &sigIndex; } /// get the last computed module const AxiomVec& getModule ( void ) const { return Module; } /// get access to a signature const TSignature& getSignature ( void ) const { return sig; } /// get access to the Locality checker LocalityChecker* getLocalityChecker ( void ) { return Checker; } /// get number of checks made unsigned long long getNChecks ( void ) const { return nChecks; } /// get number of axioms that were local unsigned long long getNNonLocal ( void ) const { return nNonLocal; } }; // TModularizer #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/DLConceptTaxonomy.h0000644000000000000000000002473612112642405021113 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2012 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef DLCONCEPTTAXONOMY_H #define DLCONCEPTTAXONOMY_H #include "Taxonomy.h" #include "dlTBox.h" #include "tProgressMonitor.h" #include "tSplitVars.h" /// Taxonomy of named DL concepts (and mapped individuals) class DLConceptTaxonomy: public Taxonomy { protected: // types /// all the derived subsumers of a class (came from the model) class DerivedSubsumers: public KnownSubsumers { protected: // typedefs /// set of the subsumers typedef Taxonomy::SubsumerSet SubsumerSet; /// SS RW iterator typedef SubsumerSet::iterator ss_iterator; protected: // members /// set of sure- and possible subsumers SubsumerSet Sure, Possible; public: // interface /// c'tor: copy given sets DerivedSubsumers ( const SubsumerSet& sure, const SubsumerSet& possible ) : KnownSubsumers() , Sure(sure) , Possible(possible) {} /// empty d'tor virtual ~DerivedSubsumers ( void ) {} // iterators /// begin of the Sure subsumers interval virtual ss_iterator s_begin ( void ) { return Sure.begin(); } /// end of the Sure subsumers interval virtual ss_iterator s_end ( void ) { return Sure.end(); } /// begin of the Possible subsumers interval virtual ss_iterator p_begin ( void ) { return Possible.begin(); } /// end of the Possible subsumers interval virtual ss_iterator p_end ( void ) { return Possible.end(); } }; // DerivedSubsumers protected: // members /// host tBox TBox& tBox; /// common descendants of all parents of currently classified concept TaxVertexVec Common; /// number of processed common parents unsigned int nCommon; // statistic counters unsigned long nConcepts; unsigned long nTries; unsigned long nPositives; unsigned long nNegatives; unsigned long nSearchCalls; unsigned long nSubCalls; unsigned long nNonTrivialSubCalls; /// number of positive cached subsumptions unsigned long nCachedPositive; /// number of negative cached subsumptions unsigned long nCachedNegative; /// number of non-subsumptions detected by a sorted reasoning unsigned long nSortedNegative; /// indicator of taxonomy creation progress TProgressMonitor* pTaxProgress; // flags /// flag to use Bottom-Up search bool flagNeedBottomUp; /// flag shows that subsumption check could be simplified bool inSplitCheck; private: // no copy /// no copy c'tor DLConceptTaxonomy ( const DLConceptTaxonomy& ); /// no assignment DLConceptTaxonomy& operator = ( const DLConceptTaxonomy& ); protected: // methods //----------------------------------------------------------------- //-- General support for DL concept classification //----------------------------------------------------------------- /// get access to curEntry as a TConcept const TConcept* curConcept ( void ) const { return static_cast(curEntry); } /// tests subsumption (via tBox) and gather statistics. Use cache and other optimisations. bool testSub ( const TConcept* p, const TConcept* q ); /// test subsumption via TBox explicitely bool testSubTBox ( const TConcept* p, const TConcept* q ) { bool res = tBox.isSubHolds ( p, q ); // update statistic ++nTries; if ( res ) ++nPositives; else ++nNegatives; return res; } // interface from BAADER paper /// SEARCH procedure from Baader et al paper void searchBaader ( bool upDirection, TaxonomyVertex* cur ); /// ENHANCED_SUBS procedure from Baader et al paper bool enhancedSubs1 ( bool upDirection, TaxonomyVertex* cur ); /// short-cuf from ENHANCED_SUBS bool enhancedSubs2 ( bool upDirection, TaxonomyVertex* cur ) { // if bottom-up search and CUR is not a successor of checking entity -- return false if ( unlikely(upDirection && !cur->isCommon()) ) return false; // for top-down search it's enough to look at defined concepts and non-det ones if ( likely(!inSplitCheck && !upDirection) && !possibleSub(cur) ) return false; return enhancedSubs1 ( upDirection, cur ); } // wrapper for the ENHANCED_SUBS inline bool enhancedSubs ( bool upDirection, TaxonomyVertex* cur ) { ++nSubCalls; if ( cur->isValued(valueLabel) ) return cur->getValue(); else return cur->setValued ( enhancedSubs2 ( upDirection, cur ), valueLabel ); } /// explicetely test appropriate subsumption relation bool testSubsumption ( bool upDirection, TaxonomyVertex* cur ); /// test whether a node could be a super-node of CUR bool possibleSub ( TaxonomyVertex* v ) const { const TConcept* C = static_cast(v->getPrimer()); // non-prim concepts are candidates if ( !C->isPrimitive() ) return true; // all others should be in the possible sups list return ksStack.top()->isPossibleSub(C); } /// propagate common value from NODE to all its descendants; save visited nodes void propagateOneCommon ( TaxonomyVertex* node ); /// mark as COMMON all vertexes that are sub-concepts of every parent of CURRENT bool propagateUp ( void ); /// clear all COMMON infornation void clearCommon ( void ); /// check if concept is unsat; add it as a synonym of BOTTOM if necessary bool isUnsatisfiable ( void ); //----------------------------------------------------------------- //-- Tunable methods (depending on taxonomy type) //----------------------------------------------------------------- /// prepare told subsumers for given entry if necessary virtual KnownSubsumers* buildKnownSubsumers ( ClassifiableEntry* p ); /// check if no classification needed (synonym, orphan, unsatisfiable) virtual bool immediatelyClassified ( void ); /// check if no BU classification is required as C=TOP bool isEqualToTop ( void ); /// check if it is possible to skip TD phase virtual bool needTopDown ( void ) const { return !(useCompletelyDefined && curEntry->isCompletelyDefined ()); } /// explicitely run TD phase virtual void runTopDown ( void ) { searchBaader ( /*upDirection=*/false, getTopVertex() ); } /// check if it is possible to skip BU phase virtual bool needBottomUp ( void ) const { // we DON'T need bottom-up phase for primitive concepts during CD-like reasoning // if no GCIs are in the TBox (C [= T, T [= X or Y, X [= D, Y [= D) or (T [= {o}) // or no reflexive roles w/RnD precent (Refl(R), Range(R)=D) return flagNeedBottomUp || !useCompletelyDefined || curConcept()->isNonPrimitive(); } /// explicitely run BU phase virtual void runBottomUp ( void ) { if ( propagateUp() ) // Common is set up here return; if ( isEqualToTop() ) // nothing to do return; if ( queryMode() ) // after classification -- bottom set up already searchBaader ( /*upDirection=*/true, getBottomVertex() ); else // during classification -- have to find leaf nodes for ( TaxVertexVec::iterator p = Common.begin(), p_end = Common.end(); p < p_end; ++p ) if ( (*p)->noNeighbours(/*upDirection=*/false) ) searchBaader ( /*upDirection=*/true, *p ); } /// actions that to be done BEFORE entry will be classified virtual void preClassificationActions ( void ) { ++nConcepts; if ( pTaxProgress != NULL ) pTaxProgress->nextClass(); } /// @return true iff curEntry is classified as a synonym virtual bool classifySynonym ( void ); /// merge vars came from a given SPLIT together void mergeSplitVars ( TSplitVar* split ); /// merge a single vertex V to a node represented by CUR void mergeVertex ( TaxonomyVertex* cur, TaxonomyVertex* v, const std::set& excludes ) { if ( likely ( cur != v ) ) { cur->mergeIndepNode ( v, excludes, curEntry ); removeNode(v); } } /// after merging, check whether there are extra neighbours that should be taken into account void checkExtraParents ( void ); /// check if it is necessary to log taxonomy action virtual bool needLogging ( void ) const { return true; } public: // interface /// the only c'tor DLConceptTaxonomy ( const TConcept* pTop, const TConcept* pBottom, TBox& kb ) : Taxonomy ( pTop, pBottom ) , tBox(kb) , nConcepts (0), nTries (0), nPositives (0), nNegatives (0) , nSearchCalls(0) , nSubCalls(0) , nNonTrivialSubCalls(0) , nCachedPositive(0) , nCachedNegative(0) , nSortedNegative(0) , pTaxProgress (NULL) , inSplitCheck(false) { } /// d'tor virtual ~DLConceptTaxonomy ( void ) {} /// process all splits void processSplits ( void ) { for ( TSplitVars::iterator p = tBox.Splits->begin(), p_end = tBox.Splits->end(); p != p_end; ++p ) mergeSplitVars(*p); } /// set bottom-up flag void setBottomUp ( const TKBFlags& GCIs ) { flagNeedBottomUp = (GCIs.isGCI() || (GCIs.isReflexive() && GCIs.isRnD())); } /// set progress indicator void setProgressIndicator ( TProgressMonitor* pMon ) { pTaxProgress = pMon; } /// output taxonomy to a stream virtual void print ( std::ostream& o ) const; }; // DLConceptTaxonomy // // DLConceptTaxonomy implementation // inline bool DLConceptTaxonomy :: isUnsatisfiable ( void ) { const TConcept* p = curConcept(); if ( tBox.isSatisfiable(p) ) return false; addCurrentToSynonym(getBottomVertex()); return true; } inline bool DLConceptTaxonomy :: immediatelyClassified ( void ) { if ( classifySynonym() ) return true; if ( curConcept()->getClassTag() == cttTrueCompletelyDefined ) return false; // true CD concepts can not be unsat // after SAT testing plan would be implemented tBox.initCache(const_cast(curConcept())); return isUnsatisfiable(); } //----------------------------------------------------------------------------- //-- implemenation of taxonomy-related parts of TBox //----------------------------------------------------------------------------- inline void TBox :: classifyEntry ( TConcept* entry ) { if ( unlikely(isBlockedInd(entry)) ) classifyEntry(getBlockingInd(entry)); // make sure that the possible synonym is already classified if ( !entry->isClassified() ) pTax->classifyEntry(entry); } #endif // DLCONCEPTTAXONOMY_H FaCTpp-src-v1.6.2~dfsg/src/Kernel/logging.h0000644000000000000000000000327312112642405017160 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2006-2008 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef _LOGGING_H #define _LOGGING_H #include "LeveLogger.h" // constants for use by different logger users enum { llAlways = 0, llStartCfyConcepts = 0, // "start classifying * concepts" message llStartCfyEntry = 1, // "start classifying entry" message llBegSat = 1, // "begin sat/sub test" message llSatResult = 1, // "sat/sub does [NOT] holds" message llTaxTrying = 2, // "Try C [= D" message llCDConcept = 2, // "completely defines concept" message llTSList = 2, // print list of TS's llTaxInsert = 2, // "insert C with parents={} and children={}" message llDagSat = 3, // "checking SAT of DAG entry" message llSatTime = 3, // print time for the test llRStat = 5, // local reasoning statistic llSRInfo = 15, // node save/restore info llSRState = 15, // s/r info of the reasoning state llGTA = 10, // general tactic action llCDAction = llGTA, // any concrete domain info }; #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/tAxiomSet.h0000644000000000000000000001152512112642405017446 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2010 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef TAXIOMSET_H #define TAXIOMSET_H #include #include "tAxiom.h" class TBox; namespace Stat { class SAbsInput: public counter {}; class SAbsAction: public counter {}; } /// set of GCIs, absorbable and not class TAxiomSet { protected: // internal types /// set of GCIs typedef std::vector AxiomCollection; /// method applying to the axiom typedef bool (TAxiomSet::*AbsMethod)(const TAxiom*); /// array of methods in application order typedef std::vector AbsActVector; protected: // members /// host TBox that holds all concepts/etc TBox& Host; /// set of axioms that accumilates incoming (and newly created) axioms; Tg AxiomCollection Accum; /// sett of absorption action, in order AbsActVector ActionVector; protected: // methods /// add already built GCI p void insertGCI ( TAxiom* p ) { # ifdef RKG_DEBUG_ABSORPTION std::cout << "\n new axiom (" << Accum.size() << "):"; p->dump(std::cout); # endif Accum.push_back(p); } /// @return true iff axiom Q is new in the set bool needed ( TAxiom* q ) { for ( AxiomCollection::const_iterator p = Accum.begin(), p_end = Accum.end(); p != p_end; ++p ) if ( *q == **p ) { # ifdef RKG_DEBUG_ABSORPTION std::cout << " same as (" << p-Accum.begin() << ")"; # endif return false; } return true; } /// insert GCI if new; @return true iff already exists bool insertIfNew ( TAxiom* q ) { if ( needed(q) ) { insertGCI(q); return false; } return true; } /// absorb single GCI wrt absorption flags bool absorbGCI ( const TAxiom* p ); /// split given axiom bool split ( const TAxiom* p ); /// helper that inserts an axiom into Accum; @return bool if success bool processNewAxiom ( TAxiom* q ) { if ( q == NULL ) return false; if ( insertIfNew(q) ) { delete q; return false; } return true; } /// replace a defined concept with its description bool simplifyCN ( const TAxiom* p ) { return processNewAxiom(p->simplifyCN()); } /// replace a universal restriction with a fresh concept bool simplifyForall ( const TAxiom* p ) { return processNewAxiom(p->simplifyForall(Host)); } /// absorb single axiom AX into BOTTOM; @return true if succeed bool absorbIntoBottom ( const TAxiom* ax ) { return ax->absorbIntoBottom(); } /// absorb single axiom AX into TOP; @return true if succeed bool absorbIntoTop ( const TAxiom* ax ) { return ax->absorbIntoTop(Host); } /// absorb single axiom AX into concept; @return true if succeed bool absorbIntoConcept ( const TAxiom* ax ) { return ax->absorbIntoConcept(Host); } /// absorb single axiom AX into negated concept; @return true if succeed bool absorbIntoNegConcept ( const TAxiom* ax ) { return ax->absorbIntoNegConcept(Host); } /// absorb single axiom AX into role domain; @return true if succeed bool absorbIntoDomain ( const TAxiom* ax ) { return ax->absorbIntoDomain(); } public: // interface /// c'tor TAxiomSet ( TBox& host ) : Host(host) {} /// d'tor ~TAxiomSet ( void ); /// init all absorption-related flags using given set of option bool initAbsorptionFlags ( const std::string& flags ); /// add axiom for the GCI C [= D void addAxiom ( DLTree* C, DLTree* D ) { Stat::SAbsInput(); TAxiom* p = new TAxiom(); p->add(C); p->add(createSNFNot(D)); insertGCI(p); } /// absorb set of axioms; @return size of not absorbed set unsigned int absorb ( void ); /// get number of (not absorbed) GCIs unsigned int size ( void ) const { return Accum.size(); } /// @return true if non-concept aborption were executed bool wasRoleAbsorptionApplied ( void ) const { return Stat::SAbsRApply::objects_created > 0; } /// get GCI of all non-absorbed axioms DLTree* getGCI ( void ) const { DLTree* ret = createTop(); for ( AxiomCollection::const_iterator p = Accum.begin(), p_end = Accum.end(); p != p_end; ++p ) ret = createSNFAnd ( ret, (*p)->createAnAxiom() ); return ret; } /// print (not absorbed) GCIs void Print ( std::ostream& o ) const; /// print absorption statistics void PrintStatistics ( void ) const; }; // TAxiomSet #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/TriRelation.cpp0000644000000000000000000001631312112642405020320 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2009-2010 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "TriRelation.h" void TriRelation :: init ( unsigned int n ) { // empty vecs bvec bZero ( n, false ); nvec nZero ( n, 0 ); // create all matrices M.insert ( M.end(), n, bZero ); MStar.insert ( MStar.end(), n, bZero ); MMinus.insert ( MMinus.end(), n, bZero ); #ifndef FPP_NO_DELETE_EDGE N.insert ( N.end(), n, nZero ); #endif M_c.insert ( M_c.end(), n, nZero ); // every node is in it's own component V_c.insert ( V_c.end(), n, true ); #ifndef FPP_NO_DELETE_EDGE e_c.insert ( e_c.end(), n, 0 ); #endif C_c.resize(n); for ( Vertex i = 0; i < n; ++i ) { L.push_back(i); C_c[i].push_back(i); } // empty successors/predecessors #ifndef FPP_NO_DELETE_EDGE S.resize(n); P.resize(n); #endif S_c.resize(n); P_c.resize(n); last = n; } TriRelation::Vertex TriRelation :: newVertex ( void ) { #ifdef FPP_DEBUG_TRI_RELATION std::cerr << "New vertex " << last << "\n"; #endif // make existing arrays bigger for ( unsigned int i = 0; i < last; ++i ) { M[i].push_back(false); MStar[i].push_back(false); MMinus[i].push_back(false); # ifndef FPP_NO_DELETE_EDGE N[i].push_back(0); # endif M_c[i].push_back(0); } // every node is in it's own component V_c.push_back(true); #ifndef FPP_NO_DELETE_EDGE e_c.push_back(0); #endif C_c.resize(last+1); L.push_back(last); C_c.back().push_back(last); ++last; // empty vecs bvec bZero ( last, false ); nvec nZero ( last, 0 ); // reserve space for new vertex M.push_back(bZero); MStar.push_back(bZero); MMinus.push_back(bZero); #ifndef FPP_NO_DELETE_EDGE N.push_back(nZero); #endif M_c.push_back(nZero); // empty successors/predecessors #ifndef FPP_NO_DELETE_EDGE S.resize(last); P.resize(last); #endif S_c.resize(last); P_c.resize(last); return last-1; } bool TriRelation :: insertNew ( Vertex i, Vertex j ) { setM(i,j); Vertex Li = L[i], Lj = L[j]; #ifdef FPP_DEBUG_TRI_RELATION std::cerr << "Insert new R(" << i << "," << j << "):"; #endif // the link is in the same component if ( Li == Lj ) { # ifdef FPP_DEBUG_TRI_RELATION std::cerr << " in the same component\n"; # endif adjustEc(i,j); # ifndef FPP_NO_DELETE_EDGE for ( Vertex k = 0; k < size(); ++k ) if ( RStar(k,i) ) ++N[k][j]; # endif return false; } // the link is between components bool newCycle = RStar(j,i); setMc(Li,Lj); // check all the condenced verteces k with a path to i for ( Vertex k = 0; k < size(); ++k ) if ( V_c[k] && RStar(k,i) ) { # ifndef FPP_NO_DELETE_EDGE for ( nvec::iterator p = C_c[k].begin(), p_end = C_c[k].end(); p < p_end; ++p ) ++N[k][j]; # endif if ( RStar(k,j) ) { // there is path from k to j as well if ( (k != Li) && (k != Lj) ) MMinus[k][Lj] = false; } else { if ( k == Li ) MMinus[Li][Lj] = true; redStack.push_back(Lj); adapt(k); } } // join components if a new cycle happen if ( newCycle ) joinComponents(j); #ifdef FPP_DEBUG_TRI_RELATION std::cerr << "\n"; #endif return newCycle; } void TriRelation :: adapt ( Vertex k ) { #ifdef FPP_DEBUG_TRI_RELATION std::cerr << " adapt(" << k << ")"; #endif nvec::iterator ki, mi, li, ki_end = C_c[k].end(), mi_end, li_end; do { /// L is the red leader Vertex l = redStack.back(); # ifdef FPP_DEBUG_TRI_RELATION std::cerr << " red(" << l << ")"; # endif // unmark l redStack.pop_back(); li_end = C_c[l].end(); // there is a path between K and L for ( ki = C_c[k].begin(); ki < ki_end; ++ki ) for ( li = C_c[l].begin(); li < li_end; ++li ) MStar[*ki][*li] = true; # ifndef FPP_NO_DELETE_EDGE // update input information for ( li = C_c[l].begin(); li < li_end; ++li ) for ( mi = S[*li].begin(), mi_end = S[*li].end(); mi < mi_end; ++mi ) for ( ki = C_c[k].begin(); ki < ki_end; ++ki ) ++N[*ki][*mi]; # endif // check all the successors of L for ( mi = S_c[l].begin(), mi_end = S_c[l].end(); mi < mi_end; ++mi ) if ( MStar[k][*mi] ) MMinus[k][*mi] = false; else redStack.push_back(*mi); } while ( !redStack.empty() ); } void TriRelation :: joinComponents ( Vertex j ) { nvec::iterator ki, mi, li, ki_end, mi_end, li_end; #ifdef FPP_DEBUG_TRI_RELATION std::cerr << " join components with " << j << "..."; #endif const Vertex n = size(); // record size nvec La; // \Lambda Vertex l, l0 = n; // \lambda_0 // build \Lambda, lambda0 for ( l = 0; l < n; ++l ) if ( MStar[l][j] && MStar[j][l] ) { if ( l0 > l ) // here we init l_0 l0 = l; // line 3 La.push_back(l); // line 2 } // Make M-[k,m] = 0 for k, m \in V_c s.t. either k or m is in La: for ( li = La.begin(), li_end = La.end(); li != li_end; ++li ) if ( V_c[*li] ) for ( l = 0; l < n; ++l ) if ( V_c[l] ) { MMinus[l][*li] = false; // line 4 part 1 MMinus[*li][l] = false; // line 4 part 2 } // line 5: // clear M_c M_c.clear(); nvec nZero ( n, 0 ); M_c.insert ( M_c.end(), n, nZero ); // clear P_c P_c.clear(); P_c.resize(n); // clear S_c S_c.clear(); S_c.resize(n); #ifndef FPP_NO_DELETE_EDGE // clear e_c e_c.clear(); e_c.insert ( e_c.end(), n, 0 ); #endif // Make M-[k,k+1] = 0 for k, m \in C(l) where l\in V_c and La: for ( li = La.begin(); li != li_end; ++li ) if ( V_c[*li] ) // line 6 { nvec& Ck = C_c[*li]; for ( ki = Ck.begin(), ki_end = Ck.end(); ki+1 != ki_end; ++ki ) MMinus[*ki][*(ki+1)] = false; // line 7 // here ki points to the last element of Ck MMinus[*ki][*(Ck.begin())] = false; // line 7 } // mark leader for Lambda for ( li = La.begin(); li != li_end; ++li ) L[*li] = l0; // line 10 // copy Lambda as a C_c of l0 C_c[l0] = La; // line 11 // adjust M_c and e_c by enumerating all edges for ( Vertex i = 0; i < n; ++i ) { Vertex Li = L[i]; for ( Vertex j = 0; j < n; ++j ) if ( M[i][j] ) { Vertex Lj = L[j]; if ( Li == Lj ) // same component adjustEc(i,j); // line 12 else setMc(Li,Lj); // line 12 } } // adjust V_c for ( li = La.begin(); li != li_end; ++li ) V_c[*li] = false; // line 13 V_c[l0] = true; // line 13 // adjust M- for the component Lambda for ( li = La.begin(); li+1 != li_end; ++li ) MMinus[*li][*(li+1)] = true; // line 14 // here li points to the last element of Lambda MMinus[*li][*(La.begin())] = true; // line 15 // adjust M-(l0,*) and M-(*,l0) for ( l = 0; l < n; ++l ) { Vertex Li = L[l]; if ( M_c[l0][Li] ) // line 20 MMinus[l0][Li] = true; // line 21 if ( M_c[Li][l0] ) // line 26 MMinus[Li][l0] = true; // line 27 } #ifdef FPP_DEBUG_TRI_RELATION std::cerr << " done"; #endif } FaCTpp-src-v1.6.2~dfsg/src/Kernel/tsttree.h0000644000000000000000000000406612112642405017225 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2008 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef _TSTTREE_HH_ #define _TSTTREE_HH_ #include // NULL //#include "SmallObj.h" template < class T > class TsTTree//: public Loki::SmallObject<> { private: // members /// element in the tree node T elem; /// pointer to left subtree TsTTree *left; /// pointer to right subtree TsTTree *right; private: // prevent copy /// no copy c'tor TsTTree ( const TsTTree& ); /// no assignment TsTTree& operator = ( const TsTTree& ); public: // interface /// default c'tor TsTTree ( const T& Init, TsTTree *l = NULL, TsTTree *r = NULL ) : elem(Init) , left(l) , right(r) {} /// d'tor ~TsTTree ( void ) {} // access to members T& Element ( void ) { return elem; } const T& Element ( void ) const { return elem; } TsTTree* Left ( void ) const { return left; } TsTTree* Right ( void ) const { return right; } void SetLeft ( TsTTree *l ) { left = l; } void SetRight ( TsTTree *r ) { right = r; } TsTTree* clone ( void ) const { TsTTree* p = new TsTTree(Element()); if ( left ) p->SetLeft(left->clone()); if ( right ) p->SetRight(right->clone()); return p; } }; // TsTTree /// delete the whole tree template void deleteTree ( TsTTree* t ) { if ( t ) { deleteTree(t->Left()); deleteTree(t->Right()); delete t; } } #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/AtomicDecomposer.cpp0000644000000000000000000001165012112642405021320 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2011-2012 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "AtomicDecomposer.h" #include "logging.h" #include "ProgressIndicatorInterface.h" //#define RKG_DEBUG_AD /// d'tor AtomicDecomposer :: ~AtomicDecomposer ( void ) { delete AOS; delete PI; } /// remove tautologies (axioms that are always local) from the ontology temporarily void AtomicDecomposer :: removeTautologies ( TOntology* O ) { // we might use it for another decomposition Tautologies.clear(); unsigned long nAx = 0; for ( TOntology::iterator p = O->begin(), p_end = O->end(); p != p_end; ++p ) if ( likely((*p)->isUsed()) ) { if ( unlikely(pModularizer->isTautology(*p,type)) ) { Tautologies.push_back(*p); (*p)->setUsed(false); } else ++nAx; } if ( PI ) PI->setLimit(nAx); } /// build a module for given axiom AX; use parent atom's module as a base for the module search TOntologyAtom* AtomicDecomposer :: buildModule ( const TSignature& sig, TOntologyAtom* parent ) { // build a module for a given signature pModularizer->extract ( parent->getModule().begin(), parent->getModule().end(), sig, type ); const AxiomVec& Module = pModularizer->getModule(); // if module is empty (empty bottom atom) -- do nothing if ( Module.empty() ) return NULL; // here the module is created; report it if ( PI ) PI->incIndicator(); // check if the module corresponds to a PARENT one; modules are the same iff their sizes are the same if ( parent != rootAtom && Module.size() == parent->getModule().size() ) // same module means same atom return parent; // create new atom with that module TOntologyAtom* atom = AOS->newAtom(); atom->setModule(Module); return atom; } /// create atom for given axiom AX; use parent atom's module as a base for the module search TOntologyAtom* AtomicDecomposer :: createAtom ( TDLAxiom* ax, TOntologyAtom* parent ) { // check whether axiom already has an atom if ( ax->getAtom() != NULL ) return const_cast(ax->getAtom()); // build an atom: use a module to find atomic dependencies TOntologyAtom* atom = buildModule( ax->getSignature(), parent ); // no empty modules should be here fpp_assert ( atom != NULL ); // register axiom as a part of an atom atom->addAxiom(ax); // if atom is the same as parent -- nothing more to do if ( atom == parent ) return parent; // not the same as parent: for all atom's axioms check their atoms and make ATOM depend on them #ifdef RKG_DEBUG_AD // do cycle via set to keep the order typedef std::set AxSet; const AxSet M ( atom->getModule().begin(), atom->getModule().end() ); for ( AxSet::iterator q = M.begin(); q != M.end(); ++q ) #else for ( TOntologyAtom::AxiomSet::const_iterator q = atom->getModule().begin(), q_end = atom->getModule().end(); q != q_end; ++q ) #endif if ( likely ( *q != ax ) ) atom->addDepAtom ( createAtom ( *q, atom ) ); return atom; } /// get the atomic structure for given module type T AOStructure* AtomicDecomposer :: getAOS ( TOntology* O, ModuleType t ) { // remember the type of the module type = t; // prepare a new AO structure delete AOS; AOS = new AOStructure(); // init semantic locality checker pModularizer->preprocessOntology(O->getAxioms()); // we don't need tautologies here removeTautologies(O); // init the root atom rootAtom = new TOntologyAtom(); rootAtom -> setModule ( TOntologyAtom::AxiomSet ( O->begin(), O->end() ) ); // build the "bottom" atom for an empty signature TOntologyAtom* BottomAtom = buildModule ( TSignature(), rootAtom ); if ( BottomAtom ) for ( TOntologyAtom::AxiomSet::const_iterator q = BottomAtom->getModule().begin(), q_end = BottomAtom->getModule().end(); q != q_end; ++q ) BottomAtom->addAxiom(*q); // create atoms for all the axioms in the ontology for ( TOntology::iterator p = O->begin(), p_end = O->end(); p != p_end; ++p ) if ( (*p)->isUsed() && (*p)->getAtom() == NULL ) createAtom ( *p, rootAtom ); // restore tautologies in the ontology restoreTautologies(); if ( LLM.isWritable(llAlways) ) LL << "\nThere were " << pModularizer->getNNonLocal() << " non-local axioms out of " << pModularizer->getNChecks() << " totally checked\n"; // clear the root atom delete rootAtom; // reduce graph AOS->reduceGraph(); return AOS; } FaCTpp-src-v1.6.2~dfsg/src/Kernel/ReasonerNom.cpp0000644000000000000000000001120012112642405020302 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2011 by Dmitry Tsarkov This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "ReasonerNom.h" //----------------------------------------------------------------------------- //-- internal nominal reasoning interface //----------------------------------------------------------------------------- // register all nominals defined in TBox void NominalReasoner :: initNominalVector ( void ) { Nominals.clear(); for ( TBox::i_iterator pi = tBox.i_begin(); pi != tBox.i_end(); ++pi ) if ( !(*pi)->isSynonym() ) Nominals.push_back(*pi); } /// prerpare Nominal Reasoner to a new job void NominalReasoner :: prepareReasoner ( void ) { if ( LLM.isWritable(llSRState) ) LL << "\nInitNominalReasoner:"; restore(1); // check whether branching op is not a barrier... if ( dynamic_cast(bContext) == NULL ) { // replace it with a barrier Stack.pop(); createBCBarrier(); } // save the barrier (also remember the entry to be produced) save(); // free the memory used in the pools before Stack.clearPools(); // clear last session information resetSessionFlags(); } bool NominalReasoner :: consistentNominalCloud ( void ) { if ( LLM.isWritable(llBegSat) ) LL << "\n--------------------------------------------\n" "Checking consistency of an ontology with individuals:"; if ( LLM.isWritable(llGTA) ) LL << "\n"; bool result = false; // reserve the root for the forthcoming reasoning if ( initNewNode ( CGraph.getRoot(), DepSet(), bpTOP ) || initNominalCloud() ) // clash during initialisation result = false; else // perform a normal reasoning result = runSat(); if ( result && noBranchingOps() ) { // all nominal cloud is classified w/o branching -- make a barrier if ( LLM.isWritable(llSRState) ) LL << "InitNominalReasoner["; curNode = NULL; createBCBarrier(); save(); nonDetShift = 1; // the barrier doesn't introduce branching itself if ( LLM.isWritable(llSRState) ) LL << "]"; } if ( LLM.isWritable(llSatResult) ) LL << "\nThe ontology is " << (result ? "consistent" : "INCONSISTENT"); if ( !result ) return false; // ABox is consistent -> create cache for every nominal in KB for ( SingletonVector::iterator p = Nominals.begin(); p != Nominals.end(); ++p ) updateClassifiedSingleton(*p); return true; } /// create nominal nodes for all individuals in TBox bool NominalReasoner :: initNominalCloud ( void ) { // create nominal nodes and fills them with initial values for ( SingletonVector::iterator p = Nominals.begin(); p != Nominals.end(); ++p ) if ( initNominalNode(*p) ) return true; // ABox is inconsistent // create edges between related nodes for ( TBox::RelatedCollection::const_iterator q = tBox.RelatedI.begin(); q != tBox.RelatedI.end(); ++q, ++q ) if ( initRelatedNominals(*q) ) return true; // ABox is inconsistent // create disjoint markers on nominal nodes if ( tBox.Different.empty() ) return false; DepSet dummy; // empty dep-set for the CGraph for ( TBox::DifferentIndividuals::const_iterator r = tBox.Different.begin(); r != tBox.Different.end(); ++r ) { CGraph.initIR(); for ( SingletonVector::const_iterator p = r->begin(); p != r->end(); ++p ) if ( CGraph.setCurIR ( resolveSynonym(*p)->node, dummy ) ) // different(c,c) return true; CGraph.finiIR(); } // init was OK return false; } bool NominalReasoner :: initRelatedNominals ( const TRelated* rel ) { DlCompletionTree* from = resolveSynonym(rel->a)->node; DlCompletionTree* to = resolveSynonym(rel->b)->node; TRole* R = resolveSynonym(rel->R); DepSet dep; // empty dep-set // check if merging will lead to clash because of disjoint roles if ( R->isDisjoint() && checkDisjointRoleClash ( from, to, R, dep ) ) return true; // create new edge between FROM and TO DlCompletionTreeArc* pA = CGraph.addRoleLabel ( from, to, /*isPredEdge=*/false, R, dep ); // return OK iff setup new enge didn't lead to clash // do NOT need to re-check anything: nothing was processed yet return setupEdge ( pA, dep, 0 ); } FaCTpp-src-v1.6.2~dfsg/src/Kernel/cpm.h0000644000000000000000000000273212112642405016310 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2006-2010 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef CPM_H #define CPM_H #include "tProgressMonitor.h" #include "cppi.h" /// console-based progress monitor class ConsoleProgressMonitor: public TProgressMonitor { protected: /// real indication CPPI ind; public: /// empty c'tor ConsoleProgressMonitor ( void ) {} /// empty d'tor virtual ~ConsoleProgressMonitor ( void ) {} // interface /// informs about beginning of classification with number of concepts to be classified virtual void setClassificationStarted ( unsigned int nConcepts ) { ind.setLimit(nConcepts); } /// informs about beginning of classification of a given CONCEPT virtual void nextClass ( void ) { ind.incIndicator(); } }; // ConsoleProgressMonitor #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/modelCacheSingleton.h0000644000000000000000000000533012112642405021435 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2010 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef MODELCACHESINGLETON_H #define MODELCACHESINGLETON_H #include "modelCacheConst.h" #include "BiPointer.h" /** Model caching implementation for singleton models. Such models contains only one [negated] concept in completion tree. Reduced set of operations, but very efficient. */ class modelCacheSingleton: public modelCacheInterface { protected: // members /// the singleton itself BipolarPointer Singleton; public: /// c'tor: no nominals can be here modelCacheSingleton ( BipolarPointer bp ) : modelCacheInterface(/*flagNominals=*/false) , Singleton(bp) {} /// copy c'tor modelCacheSingleton ( const modelCacheSingleton& m ) : modelCacheInterface(m.hasNominalNode) , Singleton(m.Singleton) {} /// empty d'tor virtual ~modelCacheSingleton ( void ) {} /// Check if the model contains clash virtual modelCacheState getState ( void ) const { return csValid; } /// access to internal value BipolarPointer getValue ( void ) const { return Singleton; } // mergable part /// check whether two caches can be merged; @return state of "merged" model modelCacheState canMerge ( const modelCacheInterface* p ) const { switch ( p->getCacheType() ) { case mctConst: // TOP/BOTTOM: the current node can't add anything to the result return p->getState(); case mctSingleton: // it can be a clash return static_cast(p)->getValue() == inverse(getValue()) ? csInvalid : csValid; case mctIan: // ask more intellegent object return p->canMerge(this); case mctBadType: // error default: return csUnknown; } } /// Get the tag identifying the cache type virtual modelCacheType getCacheType ( void ) const { return mctSingleton; } #ifdef _USE_LOGGING /// log this cache entry (with given level) virtual void logCacheEntry ( unsigned int level ) const { if ( LLM.isWritable(level) ) LL << "\nSingleton cache: element " << getValue(); } #endif }; // modelCacheSingleton #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/QR.h0000644000000000000000000001526012112642405016053 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2011 by Dmitry Tsarkov This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef QR_H #define QR_H #include #include "tDLExpression.h" //--------------------------------------------------------- // this header contains an interface for queries and rules //--------------------------------------------------------- //--------------------------------------------------------- // i-objects (vars and individuals) //--------------------------------------------------------- /// i-object (from SWRL proposal), which is variable or an individual class QRiObject { public: // interface /// empty d'tor virtual ~QRiObject ( void ) {} }; // QRiObject /// QR variable replacing the individual class QRVariable: public QRiObject { protected: // members /// name of a var std::string Name; public: // interface /// empty c'tor QRVariable ( void ) {} /// init c'tor QRVariable ( const std::string& name ) : Name(name) {} /// empty d'tor virtual ~QRVariable ( void ) {} // access methods /// get the name const std::string& getName ( void ) const { return Name; } }; // QRVariable /// individual in a query class QRIndividual: public QRiObject { protected: // members /// original individual from Expression Manager const TDLIndividualName* Ind; public: // interface /// init c'tor QRIndividual ( const TDLIndividualName* ind ) : Ind(ind) {} /// empty d'tor virtual ~QRIndividual ( void ) {} // access methods /// get the name const TDLIndividualName* getIndividual ( void ) const { return Ind; } }; // QRIndividual //--------------------------------------------------------- // var factory //--------------------------------------------------------- class VariableFactory { protected: // members /// class for the base typedef std::vector BaseClass; /// base itself BaseClass Base; public: // interface /// empty c'tor VariableFactory ( void ) {} /// d'tor: delete all registered vars ~VariableFactory ( void ) { for ( BaseClass::iterator p = Base.begin(), p_end = Base.end(); p != p_end; ++p ) delete *p; } // access /// get fresh variable const QRVariable* getNewVar ( void ) { QRVariable* ret = new QRVariable(); Base.push_back(ret); return ret; } }; // VariableFactory //--------------------------------------------------------- // atoms in the query //--------------------------------------------------------- /// general atom interface class QRAtom { public: // interface /// empty d'tor virtual ~QRAtom ( void ) {} }; // QRAtom /// concept atom: C(x) class QRConceptAtom: public QRAtom { protected: // members /// pointer to a concept (named one atm) const TDLConceptExpression* Concept; /// argument const QRiObject* Arg; public: // interface /// init c'tor QRConceptAtom ( const TDLConceptExpression* C, const QRiObject* A ) : Concept(C), Arg(A) {} /// empty d'tor ~QRConceptAtom ( void ) {} // access /// get concept expression const TDLConceptExpression* getConcept ( void ) const { return Concept; } /// get i-object const QRiObject* getArg ( void ) const { return Arg; } }; // QRConceptAtom /// interface for general 2-arg atom class QR2ArgAtom: public QRAtom { protected: // members /// argument 1 const QRiObject* Arg1; /// argument 2 const QRiObject* Arg2; public: // interface /// init c'tor QR2ArgAtom ( const QRiObject* A1, const QRiObject* A2 ) : Arg1(A1), Arg2(A2) {} /// empty d'tor ~QR2ArgAtom ( void ) {} // access /// get first i-object const QRiObject* getArg1 ( void ) const { return Arg1; } /// get second i-object const QRiObject* getArg2 ( void ) const { return Arg2; } }; // QR2ArgAtom /// role atom R(x,y) class QRRoleAtom: public QR2ArgAtom { protected: // members /// role between two i-objects const TDLObjectRoleExpression* Role; public: // interface /// init c'tor QRRoleAtom ( const TDLObjectRoleExpression* R, const QRiObject* A1, const QRiObject* A2 ) : QR2ArgAtom ( A1, A2 ), Role(R) {} /// empty d'tor ~QRRoleAtom ( void ) {} // access /// get role expression const TDLObjectRoleExpression* getRole ( void ) const { return Role; } }; /// equality atom x=y class QREqAtom: public QR2ArgAtom { public: // interface /// init c'tor QREqAtom ( const QRiObject* A1, const QRiObject* A2 ) : QR2ArgAtom ( A1, A2 ) {} /// empty d'tor ~QREqAtom ( void ) {} }; // QREqAtom /// inequality atom x!=y class QRNeqAtom: public QR2ArgAtom { public: // interface /// init c'tor QRNeqAtom ( const QRiObject* A1, const QRiObject* A2 ) : QR2ArgAtom ( A1, A2 ) {} /// empty d'tor ~QRNeqAtom ( void ) {} }; // QRNeqAtom /// general QR conjunctions of atoms class QRSetAtoms { private: // prevent copy /// no copy c'tor QRSetAtoms ( const QRSetAtoms& ); /// no assignment QRSetAtoms& operator= ( const QRSetAtoms& ); protected: // members /// set of atoms itself std::vector Base; /// typedef for RW iterator typedef std::vector::iterator iterator; public: // interface /// type for a constant iterator typedef std::vector::const_iterator const_iterator; /// empty c'tor QRSetAtoms ( void ) {} /// d'tor: delete all atoms ~QRSetAtoms ( void ) { for ( iterator p = Base.begin(), p_end = Base.end(); p != p_end; ++p ) delete *p; } /// add atom to a set void addAtom ( QRAtom* atom ) { Base.push_back(atom); } /// RO iterator begin const_iterator begin ( void ) const { return Base.begin(); } /// RO iterator end const_iterator end ( void ) const { return Base.end(); } }; /// class for the queries class QRQuery { public: // members /// query as a set of atoms QRSetAtoms Body; /// set of free variables std::set FreeVars; public: // interface /// empty c'tor QRQuery ( void ) {} /// empty d'tor ~QRQuery ( void ) {} // fill the query /// add atom to a query body void addAtom ( QRAtom* atom ) { Body.addAtom(atom); } /// mark a variable as a free one void setVarFree ( const QRVariable* var ) { FreeVars.insert(var); } }; // QRQuery /// rule in a general form body -> head class QRRule { protected: // members }; // QRRule #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/CascadedCache.cpp0000644000000000000000000000765512112642405020510 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2012 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "Reasoner.h" // uncomment the following line to debug cascaded caching //#define TMP_CACHE_DEBUG const modelCacheInterface* DlSatTester :: createCache ( BipolarPointer p ) { fpp_assert ( isValid(p) ); // safety check const modelCacheInterface* cache; // check if cache already calculated if ( (cache = DLHeap.getCache(p)) != NULL ) return cache; #ifdef TMP_CACHE_DEBUG std::cerr << "\nCCache for " << p << ":"; #endif if ( !unlikely(tBox.testHasTopRole()) ) prepareCascadedCache(p); // it may be a cycle and the cache for p is already calculated if ( (cache = DLHeap.getCache(p)) != NULL ) return cache; // need to build cache DLHeap.setCache ( p, buildCache(p) ); return DLHeap.getCache(p); } void DlSatTester :: prepareCascadedCache ( BipolarPointer p ) { /// cycle found -- shall be processed without caching if ( inProcess.find(p) != inProcess.end() ) { # ifdef TMP_CACHE_DEBUG std::cerr << " cycle with " << p << ";"; # endif return; } const DLVertex& v = DLHeap[p]; bool pos = isPositive(p); // check if a concept already cached if ( v.getCache(pos) != NULL ) return; switch ( v.Type() ) { case dtTop: case dtSplitConcept: // no need to put cache for this break; case dtDataType: // data things are checked by data inferer case dtDataValue: case dtDataExpr: break; case dtAnd: { for ( DLVertex::const_iterator q = v.begin(), q_end = v.end(); q < q_end; ++q ) prepareCascadedCache(createBiPointer(*q,pos)); break; } case dtPSingleton: case dtNSingleton: case dtNConcept: case dtPConcept: if ( isNegative(p) && isPNameTag(v.Type()) ) return; inProcess.insert(p); # ifdef TMP_CACHE_DEBUG std::cerr << " expanding " << p << ";"; # endif prepareCascadedCache(createBiPointer(v.getC(),pos)); inProcess.erase(p); break; case dtForall: case dtLE: { const TRole* R = v.getRole(); if ( R->isDataRole() ) // skip data-related stuff break; if ( unlikely(R->isTop()) ) // no need to cache top-role stuff break; BipolarPointer x = createBiPointer(v.getC(),pos); // build cache for C in \AR.C if ( x != bpTOP ) { inProcess.insert(x); # ifdef TMP_CACHE_DEBUG std::cerr << " caching " << x << ";"; # endif createCache(x); inProcess.erase(x); } // build cache for the Range(R) if necessary x = R->getBPRange(); if ( x != bpTOP ) { inProcess.insert(x); # ifdef TMP_CACHE_DEBUG std::cerr << " caching range(" << v.getRole()->getName() << ") = " << x << ";"; # endif createCache(x); inProcess.erase(x); } break; } case dtIrr: break; default: fpp_unreachable(); } } /// build cache for given DAG node using SAT tests; @return cache modelCacheInterface* DlSatTester :: buildCache ( BipolarPointer p ) { if ( LLM.isWritable(llDagSat) ) { LL << "\nChecking satisfiability of DAG entry " << p; tBox.PrintDagEntry(LL,p); LL << ":\n"; } #ifdef TMP_CACHE_DEBUG std::cerr << " building cache for " << p << "..."; #endif bool sat = runSat(p); #ifdef TMP_CACHE_DEBUG std::cerr << " done"; #endif // unsat => P -> \bot if ( !sat && LLM.isWritable(llAlways) ) LL << "\nDAG entry " << p << " is unsatisfiable\n"; return buildCacheByCGraph(sat); } FaCTpp-src-v1.6.2~dfsg/src/Kernel/modelCacheInterface.h0000644000000000000000000000676112112642405021404 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2010 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef MODELCACHEINTERFACE_H #define MODELCACHEINTERFACE_H #include "globaldef.h" #ifdef _USE_LOGGING # include "logging.h" #endif /// status of model cache or merge operation enum modelCacheState { csInvalid, ///> clash in model/merging fails because of direct contradiction; csValid, ///> valid model/success in merging; csFailed, ///> incorrect model/merging fails because of incompleteness of procedure; csUnknown ///> untested model cache. }; /// create united status for 2 given statuses inline modelCacheState mergeStatus ( modelCacheState s1, modelCacheState s2 ) { // if one of caches is definitely UNSAT, then merge will be the same if ( s1 == csInvalid || s2 == csInvalid ) return csInvalid; // if one of caches is unsure then result will be the same if ( s1 == csFailed || s2 == csFailed ) return csFailed; // if one of caches is not inited, than result would be the same if ( s1 == csUnknown || s2 == csUnknown ) return csUnknown; else // valid+valid = valid return csValid; } /// interface for general model caching. class modelCacheInterface { public: // types enum modelCacheType { mctBadType, // not implemented mctConst, // TOP/BOTTOM mctSingleton, // contains just one named concept mctIan, // root-level concepts, ER and AR concepts are cached }; protected: // members /// flag to show that model contains nominals bool hasNominalNode; public: // interface /// Create cache model with given precense of nominals modelCacheInterface ( bool flagNominals ) : hasNominalNode(flagNominals) {} /// empty d'tor virtual ~modelCacheInterface ( void ) {} /// check whether both models have nominals; in this case, merge is impossible bool hasNominalClash ( const modelCacheInterface* p ) const { return hasNominalNode && p->hasNominalNode; } /// update knoweledge about nominals in the model after merging void updateNominalStatus ( const modelCacheInterface* p ) { hasNominalNode |= p->hasNominalNode; } /// state the precense of a nominals in cache wrt FLAG void setFlagNominals ( bool flag ) { hasNominalNode = flag; } // mergable part /// Check the model cache internal state. virtual modelCacheState getState ( void ) const = 0; /// check whether two caches can be merged; @return state of "merged" model virtual modelCacheState canMerge ( const modelCacheInterface* p ) const = 0; /// Get the tag identifying the cache type virtual modelCacheType getCacheType ( void ) const { return mctBadType; } /// get type of cache (deep or shallow) virtual bool shallowCache ( void ) const { return true; } #ifdef _USE_LOGGING /// log this cache entry (with given level) virtual void logCacheEntry ( unsigned int level ATTR_UNUSED ) const {} #endif }; // modelCacheInterface #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/tSplitExpansionRules.h0000644000000000000000000001453112112642405021710 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2011-2012 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef TSPLITEXPANSIONRULES_H #define TSPLITEXPANSIONRULES_H // this file contains new expansion rules corresponding to split concepts #include #include #include "BiPointer.h" #include "tDLExpression.h" #include "tNamedEntry.h" #include "tSplitVars.h" #include "DepSet.h" class DLDag; /// all split rules: vector of rules with init and access methods class TSplitRules { protected: // types /// class to check whether there is a need to unsplit splitted var class TSplitRule { public: // typedefs /// set of signature elements typedef std::set SigSet; /// map from entities to dep-sets typedef std::map SigDeps; protected: // members /// signature of equivalent part of the split SigSet eqSig; /// signature of subsumption part of the split SigSet impSig; /// pointer to split vertex to activate BipolarPointer bpSplit; protected: // methods /// check whether set SUB contains in the set SUP static bool containsIn ( const SigSet& Sub, const SigSet& Sup ) { return includes ( Sup.begin(), Sup.end(), Sub.begin(), Sub.end() ); } /// check whether set S1 intersects with the set S2 static bool intersectsWith ( const SigSet& S1, const SigSet& S2 ) { SigSet::const_iterator q = S1.begin(), q_end = S1.end(), p = S2.begin(), p_end = S2.end(); while ( p != p_end && q != q_end ) { if ( *p == *q ) return true; if ( *p < *q ) ++p; else ++q; } return false; } public: // interface /// empty c'tor TSplitRule ( void ) {} /// init c'tor TSplitRule ( const SigSet& es, const SigSet& is, BipolarPointer p ) : eqSig(es), impSig(is), bpSplit(p) {} /// copy c'tor TSplitRule ( const TSplitRule& copy ) : eqSig(copy.eqSig), impSig(copy.impSig), bpSplit(copy.bpSplit) {} /// assignment TSplitRule& operator= ( const TSplitRule& copy ) { eqSig = copy.eqSig; impSig = copy.impSig; bpSplit = copy.bpSplit; return *this; } /// empty d'tor ~TSplitRule ( void ) {} // access methods /// get bipolar pointer of the rule BipolarPointer bp ( void ) const { return bpSplit; } /// check whether signatures of a rule are related to current signature in such a way that allows rule to fire bool canFire ( const SigSet& CurrentSig ) const { return containsIn ( eqSig, CurrentSig ) && intersectsWith ( impSig, CurrentSig ); } /// calculates dep-set for a rule that can fire, write it to DEP. void fireDep ( const SigSet& CurrentSig, SigDeps& SigDep, DepSet& dep ) const { SigSet::const_iterator p, p_end; // eqSig is contained in current, so need all for ( p = eqSig.begin(), p_end = eqSig.end(); p != p_end; ++p ) dep += SigDep[*p]; // impSig has partial intersect with current; 1st common entity is fine for ( p = impSig.begin(), p_end = impSig.end(); p != p_end; ++p ) if ( CurrentSig.count(*p) != 0 ) { dep += SigDep[*p]; return; } } }; // TSplitRule /// base typedef typedef std::vector BaseType; /// base type RW iterator typedef BaseType::iterator iterator; /// vector of a signature elements typedef std::vector SigVec; public: // type interface /// set of signature elements typedef TSplitRule::SigSet SigSet; /// RO iterator typedef BaseType::const_iterator const_iterator; /// map from entities to dep-sets typedef TSplitRule::SigDeps SigDeps; protected: // members /// all known rules BaseType Base; /// all entities that appears in all the splits in a set SigSet PossibleSignature; /// map between BP and TNamedEntities SigVec EntityMap; protected: // methods /// add new split rule void addSplitRule ( const SigSet& eqSig, const SigSet impSig, BipolarPointer bp ) { Base.push_back(TSplitRule(eqSig,impSig,bp)); } /// build a set out of signature SIG w/o given ENTITY SigSet buildSet ( const TSignature& sig, const TNamedEntity* entity ); /// init split as a set-of-sets void initSplit ( TSplitVar* split ); /// prepare start signature void prepareStartSig ( const AxiomVec& Module, TSignature& FinalSig, SigVec& Allowed ) const; /// build all the seed signatures void BuildAllSeedSigs ( const SigVec& Allowed, const TSignature& sig, AxiomVec& Module, std::set& Out ) const; /// calculate single entity based on a named entry ENTRY and possible signature const TNamedEntity* getSingleEntity ( const TNamedEntry* entry ) const { if ( likely ( entry == NULL ) ) return NULL; const TNamedEntity* ret = entry->getEntity(); // now keep only known signature concepts return PossibleSignature.count(ret) > 0 ? ret : NULL; } public: // interface /// empty c'tor TSplitRules ( void ) {} /// empty d'tor ~TSplitRules ( void ) {} // fill methods /// create all the split rules by given split set SPLITS void createSplitRules ( TSplitVars* Splits ) { for ( TSplitVars::iterator p = Splits->begin(), p_end = Splits->end(); p != p_end; ++p ) initSplit(*p); } /// init entity map using given DAG. note that this should be done AFTER rule splits are created! void initEntityMap ( const DLDag& Dag ); /// ensure that Map has the same size as DAG, so there would be no access violation void ensureDagSize ( size_t dagSize ) { EntityMap.resize(dagSize); } // access methods /// RO begin iterator const_iterator begin ( void ) const { return Base.begin(); } /// RO end iterator const_iterator end ( void ) const { return Base.end(); } /// @return named entity corresponding to a given bp const TNamedEntity* getEntity ( BipolarPointer bp ) const { return EntityMap[getValue(bp)]; } }; // TSplitRules #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/tLabeller.h0000644000000000000000000000424512112642405017440 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2010 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef TLABELLER_H #define TLABELLER_H #include "fpp_assert.h" #include "tCounter.h" /** define class that implements support for labelling entries with * cheap 'unselect' operation. An external entity is 'marked' iff * it's value equal to the internal counter. */ class TLabeller { private: // internal type definition /// type of a counter typedef TCounter LabelCounter; public: // type interface /// define integral type of a label typedef LabelCounter::IntType LabelType; protected: // members /// counter LabelCounter counter; public: // interface /// init c'tor TLabeller ( void ) : counter(1) {} /// copy c'tor TLabeller ( const TLabeller& copy ) : counter(copy.counter) {} /// assignment TLabeller& operator= ( const TLabeller& copy ) { counter = copy.counter; return *this; } /// d'tor ~TLabeller ( void ) {} // operations with Labeller /// create a new label value void newLabel ( void ) { counter.inc(); fpp_assert ( counter.val() != 0 ); } // operations with Labels /// set given label's value to the counter's one void set ( LabelType& lab ) const { lab = counter.val(); } /// clear given label's value (independent of a labeller) static void clear ( LabelType& lab ) { lab = 0; } /// check if given label is labelled bool isLabelled ( const LabelType& lab ) const { return (lab == counter.val()); } }; // TLabeller #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/tDataTypeBool.h0000644000000000000000000000217512112642405020245 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2009 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef TDATATYPEBOOL_H #define TDATATYPEBOOL_H #include "tDataType.h" class TDataTypeBool: public TDataType { public: /// c'tor: make 2 elements of the domain and lock the type TDataTypeBool ( void ) : TDataType("bool") { get("false"); get("true"); setLocked(true); } /// empty d'tor ~TDataTypeBool ( void ) {} }; // TDataTypeBool #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/dumpLisp.cpp0000644000000000000000000000361412112642405017661 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2009 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "dumpLisp.h" void dumpLisp :: startOp ( diOp Op ) { if ( Op == diAnd || Op == diOr ) incIndent(); o << "("; switch (Op) { case diErrorOp: default: fpp_unreachable(); // concept expressions case diNot: o << "not"; break; case diAnd: o << "and"; break; case diOr: o << "or"; break; case diExists: o << "some"; break; case diForall: o << "all"; break; case diGE: o << "atleast"; break; case diLE: o << "atmost"; break; } contOp(Op); } void dumpLisp :: startAx ( diAx Ax ) { o << "("; switch (Ax) { case diErrorAx: default: fpp_unreachable(); // concept axioms case diDefineC: o << "defprimconcept"; break; case diImpliesC: o << "implies_c"; break; case diEqualsC: o << "equal_c"; break; // role axioms case diDefineR: o << "defprimrole"; break; case diTransitiveR: o << "transitive"; break; case diFunctionalR: o << "functional"; break; case diImpliesR: o << "implies_r"; break; case diEqualsR: o << "equal_r"; break; case diDomainR: o << "domain"; break; case diRangeR: o << "range"; break; }; contAx(Ax); } FaCTpp-src-v1.6.2~dfsg/src/Kernel/tDepSet.h0000644000000000000000000001656112112642405017106 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2006-2011 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef TDEPSET_H #define TDEPSET_H #include #include #include "fpp_assert.h" #include "growingArrayP.h" #include "tHeadTailCache.h" /** * dep-set implementation based on lists that shared tails */ class TDepSetManager; /// implementation of DSE class TDepSetElement { protected: // members /// reference to the containing manager TDepSetManager* Manager; /// current dependency level unsigned int Level; /// pointer to the rest of the dep-set TDepSetElement* Tail; public: // interface /// init c'tor explicit TDepSetElement ( TDepSetManager* manager, unsigned int level, TDepSetElement* tail ) : Manager(manager) , Level(level) , Tail(tail) { # ifdef TMP_DEPSET_DEBUG std::cout << "Created DSE "; Print(std::cout); std::cout << std::endl; # endif } /// d'tor ~TDepSetElement ( void ) { # ifdef TMP_DEPSET_DEBUG std::cout << "Deleted DSE "; Print(std::cout); std::cout << std::endl; # endif } /// get level of DSE unsigned int level ( void ) const { return Level; } /// get pointer to the Tail DSE TDepSetElement* tail ( void ) const { return Tail; } /// merge this element with ELEM; use Manager for this TDepSetElement* merge ( TDepSetElement* elem ); /// Print given dep-set to a standart stream template void Print ( O& o ) const { if ( Tail ) // print the rest of dep-set, then current element { Tail->Print(o); o << ',' << level(); } else // leaf element (from basement) o << level(); } }; // TDepSetElement /// class for the cache element. Contains all the pointers to the dep-sets /// started from the same element class TDepSetCache: public THeadTailCache { protected: // members /// reference to the containing manager TDepSetManager* Manager; /// element head.NULL TDepSetElement* HeadDepSet; /// head element of the given cache unsigned int Level; protected: // methods /// the way to create an object by a given tail virtual TDepSetElement* build ( TDepSetElement* tail ) { return new TDepSetElement ( Manager, Level, tail ); } public: // interface /// stub c'tor for growingArrayP() TDepSetCache ( void ) { fpp_unreachable(); } /// c'tor: create head dep-set explicit TDepSetCache ( TDepSetManager* manager, unsigned int level ) : Manager(manager) , Level(level) { HeadDepSet = new TDepSetElement ( Manager, Level, NULL ); } /// d'tor: delete all the cached dep-sets and the head element virtual ~TDepSetCache ( void ) { // don't delete tails as they are referenced outside for ( iterator p = Map.begin(), p_end = Map.end(); p != p_end; ++p ) delete p->second; delete HeadDepSet; } /// get dep-set corresponding to a Head.Tail; treat NULL tail separately TDepSetElement* getDS ( TDepSetElement* tail ) { // special case the empty tail: most common case if ( tail == NULL ) return HeadDepSet; return get(tail); } }; // TDepSetCache /// implementation of Manager class TDepSetManager: public growingArrayP { protected: // methods /// create a new entry with an improved level virtual TDepSetCache* createNew ( void ) { return new TDepSetCache ( this, last++ ); } public: // interface /// c'tor: init N basement elements TDepSetManager ( unsigned int n ) : growingArrayP(0) { ensureHeapSize(n); } /// d'tor: delete all basement elements virtual ~TDepSetManager ( void ) {} /// ensure that size of vector is enough to keep N elements void ensureLevel ( unsigned int n ) { ensureHeapSize(n); } /// get concatenation of N'th level element and TAIL TDepSetElement* get ( unsigned int n, TDepSetElement* tail = NULL ) const { return Base[n]->getDS(tail); } /// merge two dep-sets into a single one TDepSetElement* merge ( TDepSetElement* d1, TDepSetElement* d2 ) { // if any dep-set is NULL -- return another one if ( d1 == NULL ) return d2; if ( d2 == NULL ) return d1; if ( d1 == d2 ) return d1; // take the largest level, and add to it the result of merging tails if ( d1->level() > d2->level() ) return get ( d1->level(), merge(d1->tail(),d2) ); if ( d1->level() < d2->level() ) return get ( d2->level(), merge(d1,d2->tail()) ); // here d1.level == d2.level return get ( d1->level(), merge(d1->tail(),d2->tail()) ); } }; // TDepSetManager /// merge this element with ELEM; use Manager for this inline TDepSetElement* TDepSetElement :: merge ( TDepSetElement* elem ) { #ifdef ENABLE_CHECKING if ( elem == NULL ) return this; fpp_assert ( Manager == elem->Manager ); #endif return Manager->merge ( this, elem ); } class TDepSet { protected: // members /// pointer to the appropriate dep-set element TDepSetElement* dep; public: // interface /// default c'tor: create empty dep-set TDepSet ( void ) : dep(NULL) {} /// main c'tor explicit TDepSet ( TDepSetElement* depp ) { dep = depp; } /// copy c'tor TDepSet ( const TDepSet& d ) : dep(d.dep) {} /// assignment TDepSet& operator = ( const TDepSet& d ) { dep = d.dep; return *this; } /// empty d'tor: no need to delete element as it is registered in manager ~TDepSet ( void ) {} // access methods /// return latest branching point in the dep-set unsigned int level ( void ) const { return dep ? dep->level() : 0; } /// check if the dep-set is empty bool empty ( void ) const { return dep == NULL; } /// check if the dep-set contains given level bool contains ( unsigned int level ) const { for ( TDepSetElement* p = dep; p; p = p->tail() ) if ( level > p->level() ) // missed one return false; else if ( level == p->level() ) // found one return true; // not found return false; } /// check the equivalence of the two dep-sets bool operator == ( const TDepSet& ds ) const { return dep == ds.dep; } /// Adds given dep-set to current dep-set void add ( const TDepSet& toAdd ) { dep = dep ? dep->merge(toAdd.dep) : toAdd.dep; } /// Adds given dep-set to current dep-set TDepSet& operator += ( const TDepSet& toAdd ) { add(toAdd); return *this; } /// Remove all information from dep-set void clear ( void ) { dep = NULL; } /// remove parts of the current dep-set that larger than given level void restrict ( unsigned int level ) { if ( empty() ) return; if ( dep->level() == level ) { dep = dep->tail(); return; } TDepSetElement* p = dep; // find part of the dep-set with level <= given while ( p && level <= p->level() ) p = p->tail(); // check for empty dep-set if ( p ) dep = p; else clear(); } /// Print given dep-set to a standart stream template void Print ( O& o ) const { if ( !empty() ) { o << "{"; dep->Print(o); o << "}"; } } }; // TDepSet #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/growingArrayP.h0000644000000000000000000000610412112642405020321 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2005-2010 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef _GROWINGARRAYP_H #define _GROWINGARRAYP_H #include /** * Generic class for structures which creates elements (by pointers) and re-use * them (does not delete things). Derived types may add operations. */ template class growingArrayP { protected: // typedefs /// type of the heap typedef std::vector baseType; /// heap's reverse iterator (used in the destructor) typedef typename baseType::reverse_iterator riterator; public: // typedefs /// heap's iterator typedef typename baseType::iterator iterator; /// heap's const iterator typedef typename baseType::const_iterator const_iterator; protected: // members /// heap itself baseType Base; /// index of the next unallocated entry unsigned int last; private: // prevent from copying /// no copy c'tor growingArrayP ( const growingArrayP& ); /// no assignment growingArrayP& operator= ( const growingArrayP& ); protected: // methods /// tunable method for creating new object virtual T* createNew ( void ) { return new T; } /// init vector [B,E) with new objects T void initArray ( iterator b, iterator e ) { for ( iterator p = b; p != e; ++p ) *p = createNew(); } /// increase heap size void grow ( void ) { unsigned int size = Base.size(); Base.resize(size?size*2:1); initArray ( Base.begin()+size, Base.end() ); } /// ensure that size of vector is enough to fit the last element void ensureHeapSize ( void ) { if ( last >= Base.size() ) grow(); } /// ensure that size of vector is enough to keep N elements void ensureHeapSize ( unsigned int n ) { while ( n >= Base.size() ) grow(); } public: // interface /// c'tor: make SIZE objects growingArrayP ( unsigned int size = 0 ) : Base(size), last(0) { initArray ( Base.begin(), Base.end() ); } /// d'tor: delete all allocated objects virtual ~growingArrayP ( void ) { for ( riterator p = Base.rbegin(), p_end = Base.rend(); p != p_end; ++p ) delete *p; } /// resize an array void resize ( unsigned int n ) { ensureHeapSize(n); last = n; } /// get the number of elements unsigned int size ( void ) const { return last; } /// check if heap is empty bool empty ( void ) const { return last == 0; } /// mark all array elements as unused virtual void clear ( void ) { last = 0; } }; // growingArrayP #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/tSignatureUpdater.h0000644000000000000000000002274712112642405021213 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2011 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef TSIGNATUREUPDATER_H #define TSIGNATUREUPDATER_H #include "tDLExpression.h" #include "tSignature.h" /// update the signature by adding all signature elements from the expression class TExpressionSignatureUpdater: public DLExpressionVisitor { protected: // members /// Signature to be filled TSignature& sig; protected: // methods /// helper for concept arguments void vC ( const TConceptArg& expr ) { expr.getC()->accept(*this); } /// helper for individual arguments void vI ( const TIndividualArg& expr ) { expr.getI()->accept(*this); } /// helper for object role arguments void vOR ( const TObjectRoleArg& expr ) { expr.getOR()->accept(*this); } /// helper for object role arguments void vDR ( const TDataRoleArg& expr ) { expr.getDR()->accept(*this); } /// helper for the named entity void vE ( const TNamedEntity& e ) { sig.add(e.getEntity()); } /// array helper template void processArray ( const TDLNAryExpression& expr ) { for ( typename TDLNAryExpression::iterator p = expr.begin(), p_end = expr.end(); p != p_end; ++p ) (*p)->accept(*this); } public: // interface /// init c'tor TExpressionSignatureUpdater ( TSignature& s ) : sig(s) {} /// empty d'tor virtual ~TExpressionSignatureUpdater ( void ) {} public: // visitor interface // concept expressions virtual void visit ( const TDLConceptTop& expr ATTR_UNUSED ) {} virtual void visit ( const TDLConceptBottom& expr ATTR_UNUSED ) {} virtual void visit ( const TDLConceptName& expr ) { vE(expr); } virtual void visit ( const TDLConceptNot& expr ) { vC(expr); } virtual void visit ( const TDLConceptAnd& expr ) { processArray(expr); } virtual void visit ( const TDLConceptOr& expr ) { processArray(expr); } virtual void visit ( const TDLConceptOneOf& expr ) { processArray(expr); } virtual void visit ( const TDLConceptObjectSelf& expr ) { vOR(expr); } virtual void visit ( const TDLConceptObjectValue& expr ) { vOR(expr); vI(expr); } virtual void visit ( const TDLConceptObjectExists& expr ) { vOR(expr); vC(expr); } virtual void visit ( const TDLConceptObjectForall& expr ) { vOR(expr); vC(expr); } virtual void visit ( const TDLConceptObjectMinCardinality& expr ) { vOR(expr); vC(expr); } virtual void visit ( const TDLConceptObjectMaxCardinality& expr ) { vOR(expr); vC(expr); } virtual void visit ( const TDLConceptObjectExactCardinality& expr ) { vOR(expr); vC(expr); } virtual void visit ( const TDLConceptDataValue& expr ) { vDR(expr); } virtual void visit ( const TDLConceptDataExists& expr ) { vDR(expr); } virtual void visit ( const TDLConceptDataForall& expr ) { vDR(expr); } virtual void visit ( const TDLConceptDataMinCardinality& expr ) { vDR(expr); } virtual void visit ( const TDLConceptDataMaxCardinality& expr ) { vDR(expr); } virtual void visit ( const TDLConceptDataExactCardinality& expr ) { vDR(expr); } // individual expressions virtual void visit ( const TDLIndividualName& expr ) { vE(expr); } // object role expressions virtual void visit ( const TDLObjectRoleTop& expr ATTR_UNUSED ) {} virtual void visit ( const TDLObjectRoleBottom& expr ATTR_UNUSED ) {} virtual void visit ( const TDLObjectRoleName& expr ) { vE(expr); } virtual void visit ( const TDLObjectRoleInverse& expr ) { vOR(expr); } virtual void visit ( const TDLObjectRoleChain& expr ) { processArray(expr); } virtual void visit ( const TDLObjectRoleProjectionFrom& expr ) { vOR(expr); vC(expr); } virtual void visit ( const TDLObjectRoleProjectionInto& expr ) { vOR(expr); vC(expr); } // data role expressions virtual void visit ( const TDLDataRoleTop& expr ATTR_UNUSED ) {} virtual void visit ( const TDLDataRoleBottom& expr ATTR_UNUSED ) {} virtual void visit ( const TDLDataRoleName& expr ) { vE(expr); } // data expressions virtual void visit ( const TDLDataTop& expr ATTR_UNUSED ) {} virtual void visit ( const TDLDataBottom& expr ATTR_UNUSED ) {} virtual void visit ( const TDLDataTypeName& expr ATTR_UNUSED ) {} virtual void visit ( const TDLDataTypeRestriction& expr ATTR_UNUSED ) {} virtual void visit ( const TDLDataValue& expr ATTR_UNUSED ) {} virtual void visit ( const TDLDataNot& expr ATTR_UNUSED ) {} virtual void visit ( const TDLDataAnd& expr ATTR_UNUSED ) {} virtual void visit ( const TDLDataOr& expr ATTR_UNUSED ) {} virtual void visit ( const TDLDataOneOf& expr ATTR_UNUSED ) {} // facets virtual void visit ( const TDLFacetMinInclusive& expr ATTR_UNUSED ) {} virtual void visit ( const TDLFacetMinExclusive& expr ATTR_UNUSED ) {} virtual void visit ( const TDLFacetMaxInclusive& expr ATTR_UNUSED ) {} virtual void visit ( const TDLFacetMaxExclusive& expr ATTR_UNUSED ) {} }; // TExpressionSignatureUpdater /// update signature by adding the signature of a given axiom to it class TSignatureUpdater: public DLAxiomVisitor { protected: // members /// helper with expressions TExpressionSignatureUpdater Updater; protected: // methods /// helper for the expression processing void v ( const TDLExpression* E ) { E->accept(Updater); } /// helper for the [begin,end) interval template void v ( Iterator begin, Iterator end ) { for ( ; begin != end; ++begin ) v(*begin); } public: // visitor interface virtual void visit ( const TDLAxiomDeclaration& axiom ) { v(axiom.getDeclaration()); } virtual void visit ( const TDLAxiomEquivalentConcepts& axiom ) { v ( axiom.begin(), axiom.end() ); } virtual void visit ( const TDLAxiomDisjointConcepts& axiom ) { v ( axiom.begin(), axiom.end() ); } virtual void visit ( const TDLAxiomDisjointUnion& axiom ) { v(axiom.getC()); v ( axiom.begin(), axiom.end() ); } virtual void visit ( const TDLAxiomEquivalentORoles& axiom ) { v ( axiom.begin(), axiom.end() ); } virtual void visit ( const TDLAxiomEquivalentDRoles& axiom ) { v ( axiom.begin(), axiom.end() ); } virtual void visit ( const TDLAxiomDisjointORoles& axiom ) { v ( axiom.begin(), axiom.end() ); } virtual void visit ( const TDLAxiomDisjointDRoles& axiom ) { v ( axiom.begin(), axiom.end() ); } virtual void visit ( const TDLAxiomSameIndividuals& axiom ) { v ( axiom.begin(), axiom.end() ); } virtual void visit ( const TDLAxiomDifferentIndividuals& axiom ) { v ( axiom.begin(), axiom.end() ); } virtual void visit ( const TDLAxiomFairnessConstraint& axiom ) { v ( axiom.begin(), axiom.end() ); } virtual void visit ( const TDLAxiomRoleInverse& axiom ) { v(axiom.getRole()); v(axiom.getInvRole()); } virtual void visit ( const TDLAxiomORoleSubsumption& axiom ) { v(axiom.getRole()); v(axiom.getSubRole()); } virtual void visit ( const TDLAxiomDRoleSubsumption& axiom ) { v(axiom.getRole()); v(axiom.getSubRole()); } virtual void visit ( const TDLAxiomORoleDomain& axiom ) { v(axiom.getRole()); v(axiom.getDomain()); } virtual void visit ( const TDLAxiomDRoleDomain& axiom ) { v(axiom.getRole()); v(axiom.getDomain()); } virtual void visit ( const TDLAxiomORoleRange& axiom ) { v(axiom.getRole()); v(axiom.getRange()); } virtual void visit ( const TDLAxiomDRoleRange& axiom ) { v(axiom.getRole()); v(axiom.getRange()); } virtual void visit ( const TDLAxiomRoleTransitive& axiom ) { v(axiom.getRole()); } virtual void visit ( const TDLAxiomRoleReflexive& axiom ) { v(axiom.getRole()); } virtual void visit ( const TDLAxiomRoleIrreflexive& axiom ) { v(axiom.getRole()); } virtual void visit ( const TDLAxiomRoleSymmetric& axiom ) { v(axiom.getRole()); } virtual void visit ( const TDLAxiomRoleAsymmetric& axiom ) { v(axiom.getRole()); } virtual void visit ( const TDLAxiomORoleFunctional& axiom ) { v(axiom.getRole()); } virtual void visit ( const TDLAxiomDRoleFunctional& axiom ) { v(axiom.getRole()); } virtual void visit ( const TDLAxiomRoleInverseFunctional& axiom ) { v(axiom.getRole()); } virtual void visit ( const TDLAxiomConceptInclusion& axiom ) { v(axiom.getSubC()); v(axiom.getSupC()); } virtual void visit ( const TDLAxiomInstanceOf& axiom ) { v(axiom.getIndividual()); v(axiom.getC()); } virtual void visit ( const TDLAxiomRelatedTo& axiom ) { v(axiom.getIndividual()); v(axiom.getRelation()); v(axiom.getRelatedIndividual()); } virtual void visit ( const TDLAxiomRelatedToNot& axiom ) { v(axiom.getIndividual()); v(axiom.getRelation()); v(axiom.getRelatedIndividual()); } virtual void visit ( const TDLAxiomValueOf& axiom ) { v(axiom.getIndividual()); v(axiom.getAttribute()); } virtual void visit ( const TDLAxiomValueOfNot& axiom ) { v(axiom.getIndividual()); v(axiom.getAttribute()); } public: // interface /// init c'tor TSignatureUpdater ( TSignature& sig ) : Updater(sig) {} /// empty d'tor virtual ~TSignatureUpdater ( void ) {} /// load ontology to a given KB virtual void visitOntology ( TOntology& ontology ) { for ( TOntology::iterator p = ontology.begin(), p_end = ontology.end(); p < p_end; ++p ) if ( (*p)->isUsed() ) { (*p)->accept(*this); } } }; // TSignatureUpdater #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/tSubsumptionMap.h0000644000000000000000000000603712112642405020705 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2010 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef TSUBSUMPTIONMAP_H #define TSUBSUMPTIONMAP_H #include "TriRelation.h" #include "tIndividual.h" class TSubsumptionMap { protected: // typedefs /// vertex type typedef TriRelation::Vertex Vertex; /// boolean vector typedef TriRelation::bvec bvec; /// boolean matrix typedef TriRelation::bMatrix bMatrix; protected: // members /// set of known subsumptions TriRelation K; /// set of possible subsumptions TriRelation::bMatrix P; /// reduction of P wrt K TriRelation::bMatrix P_K; /// index of a TOP vertex static const Vertex TopVertex = 0; /// index of a BOTTOM vertex static const Vertex BotVertex = 1; protected: // methods /// add vertex to the map Vertex addVertex ( void ); /// add known subsumption between X and Y; @return true iff cycle was found bool addKnoSub ( Vertex x, Vertex y ); /// add known non-subsumption between X and Y void addNonSub ( Vertex x, Vertex y ); public: // interface /// c'tor: create Top/Bottom TSubsumptionMap ( void ); /// c'tor: create Top/Bottom and N verteces TSubsumptionMap ( unsigned int n ); /// empty d'tor ~TSubsumptionMap ( void ) {} /// register new classifiable entry in the map void registerEntry ( ClassifiableEntry* p ) { Vertex v = addVertex(); addKnoSub ( BotVertex, v ); addKnoSub ( v, TopVertex ); if ( dynamic_cast(p) != NULL ) addNonSub ( v, BotVertex ); // FIXME!! now the level is given for ModelCache, revisit later p->setIndex(v); } /// size of the matrix unsigned int size ( void ) const { return K.size(); } /// add known subsumption between P and Q bool addKnoSub ( const ClassifiableEntry* p, const ClassifiableEntry* q ) { return addKnoSub ( p->index(), q->index() ); } /// add known non-subsumption between P and Q void addNonSub ( const ClassifiableEntry* p, const ClassifiableEntry* q ) { addNonSub ( p->index(), q->index() ); } /// @return true iff subsumption between P and Q is possible bool isSubPossible ( const ClassifiableEntry* p, const ClassifiableEntry* q ) const { return P_K[p->index()][q->index()]; } /// @return true iff subsumption between P and Q is known bool isSubKnown ( const ClassifiableEntry* p, const ClassifiableEntry* q ) const { return K.RStar ( p->index(), q->index() ); } }; // TSubsumptionMap #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/tExpressionTranslator.h0000644000000000000000000002667612112642405022143 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2010-2012 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef TEXPRESSIONTRANSLATOR_H #define TEXPRESSIONTRANSLATOR_H #include "tDLExpression.h" #include "tDataTypeManager.h" #include "dlTBox.h" class TExpressionTranslator: public DLExpressionVisitor { protected: // members /// tree corresponding to a processing expression DLTree* tree; /// TBox to get access to the named entities TBox& KB; /// signature of non-trivial entities; used in semantic locality checkers only const TSignature* sig; #define THROW_UNSUPPORTED(name) \ throw EFaCTPlusPlus("Unsupported expression '" name "' in transformation") protected: // methods /// create DLTree of given TAG and named ENTRY; set the entry's ENTITY if necessary TNamedEntry* matchEntry ( TNamedEntry* entry, const TNamedEntity* entity ) { entry->setEntity(entity); const_cast(entity)->setEntry(entry); return entry; } /// @return true iff ENTRY is not in signature bool nc ( const TNamedEntity* entity ) const { return unlikely(sig != NULL) && !sig->contains(entity); } public: // interface /// empty c'tor TExpressionTranslator ( TBox& kb ) : tree(NULL), KB(kb), sig(NULL) {} /// empty d'tor virtual ~TExpressionTranslator ( void ) { deleteTree(tree); } /// get (single) access to the tree operator DLTree* ( void ) { DLTree* ret = tree; tree = NULL; return ret; } /// set internal signature to a given signature S void setSignature ( const TSignature* s ) { sig = s; } public: // visitor interface // concept expressions virtual void visit ( const TDLConceptTop& expr ATTR_UNUSED ) { tree = createTop(); } virtual void visit ( const TDLConceptBottom& expr ATTR_UNUSED ) { tree = createBottom(); } virtual void visit ( const TDLConceptName& expr ) { if ( nc(&expr) ) tree = sig->topCLocal() ? createTop() : createBottom(); else { TNamedEntry* entry = expr.getEntry(); if ( entry == NULL ) entry = matchEntry ( KB.getConcept(expr.getName()), &expr ); tree = createEntry(CNAME,entry); } } virtual void visit ( const TDLConceptNot& expr ) { expr.getC()->accept(*this); tree = createSNFNot(*this); } virtual void visit ( const TDLConceptAnd& expr ) { DLTree* acc = createTop(); for ( TDLConceptAnd::iterator p = expr.begin(), p_end = expr.end(); p != p_end; ++p ) { (*p)->accept(*this); acc = createSNFAnd ( acc, *this ); } tree = acc; } virtual void visit ( const TDLConceptOr& expr ) { DLTree* acc = createBottom(); for ( TDLConceptOr::iterator p = expr.begin(), p_end = expr.end(); p != p_end; ++p ) { (*p)->accept(*this); acc = createSNFOr ( acc, *this ); } tree = acc; } virtual void visit ( const TDLConceptOneOf& expr ) { DLTree* acc = createBottom(); for ( TDLConceptOneOf::iterator p = expr.begin(), p_end = expr.end(); p != p_end; ++p ) { (*p)->accept(*this); acc = createSNFOr ( acc, *this ); } tree = acc; } virtual void visit ( const TDLConceptObjectSelf& expr ) { expr.getOR()->accept(*this); tree = createSNFSelf(*this); } virtual void visit ( const TDLConceptObjectValue& expr ) { expr.getOR()->accept(*this); DLTree* R = *this; expr.getI()->accept(*this); tree = createSNFExists ( R, *this ); } virtual void visit ( const TDLConceptObjectExists& expr ) { expr.getOR()->accept(*this); DLTree* R = *this; expr.getC()->accept(*this); tree = createSNFExists ( R, *this ); } virtual void visit ( const TDLConceptObjectForall& expr ) { expr.getOR()->accept(*this); DLTree* R = *this; expr.getC()->accept(*this); tree = createSNFForall ( R, *this ); } virtual void visit ( const TDLConceptObjectMinCardinality& expr ) { expr.getOR()->accept(*this); DLTree* R = *this; expr.getC()->accept(*this); tree = createSNFGE ( expr.getNumber(), R, *this ); } virtual void visit ( const TDLConceptObjectMaxCardinality& expr ) { expr.getOR()->accept(*this); DLTree* R = *this; expr.getC()->accept(*this); tree = createSNFLE ( expr.getNumber(), R, *this ); } virtual void visit ( const TDLConceptObjectExactCardinality& expr ) { expr.getOR()->accept(*this); DLTree* R = *this; expr.getC()->accept(*this); DLTree* C = *this; DLTree* LE = createSNFLE ( expr.getNumber(), clone(R), clone(C) ); DLTree* GE = createSNFGE ( expr.getNumber(), R, C ); tree = createSNFAnd ( GE, LE ); } virtual void visit ( const TDLConceptDataValue& expr ) { expr.getDR()->accept(*this); DLTree* R = *this; expr.getExpr()->accept(*this); tree = createSNFExists ( R, *this ); } virtual void visit ( const TDLConceptDataExists& expr ) { expr.getDR()->accept(*this); DLTree* R = *this; expr.getExpr()->accept(*this); tree = createSNFExists ( R, *this ); } virtual void visit ( const TDLConceptDataForall& expr ) { expr.getDR()->accept(*this); DLTree* R = *this; expr.getExpr()->accept(*this); tree = createSNFForall ( R, *this ); } virtual void visit ( const TDLConceptDataMinCardinality& expr ) { expr.getDR()->accept(*this); DLTree* R = *this; expr.getExpr()->accept(*this); tree = createSNFGE ( expr.getNumber(), R, *this ); } virtual void visit ( const TDLConceptDataMaxCardinality& expr ) { expr.getDR()->accept(*this); DLTree* R = *this; expr.getExpr()->accept(*this); tree = createSNFLE ( expr.getNumber(), R, *this ); } virtual void visit ( const TDLConceptDataExactCardinality& expr ) { expr.getDR()->accept(*this); DLTree* R = *this; expr.getExpr()->accept(*this); DLTree* C = *this; DLTree* LE = createSNFLE ( expr.getNumber(), clone(R), clone(C) ); DLTree* GE = createSNFGE ( expr.getNumber(), R, C ); tree = createSNFAnd ( GE, LE ); } // individual expressions virtual void visit ( const TDLIndividualName& expr ) { TNamedEntry* entry = expr.getEntry(); if ( entry == NULL ) entry = matchEntry ( KB.getIndividual(expr.getName()), &expr ); tree = createEntry(INAME,entry); } // object role expressions virtual void visit ( const TDLObjectRoleTop& expr ATTR_UNUSED ) { THROW_UNSUPPORTED("top object role"); } virtual void visit ( const TDLObjectRoleBottom& expr ATTR_UNUSED ) { THROW_UNSUPPORTED("bottom object role"); } virtual void visit ( const TDLObjectRoleName& expr ) { RoleMaster* RM = KB.getORM(); TNamedEntry* role; if ( nc(&expr) ) role = sig->topRLocal() ? RM->getTopRole() : RM->getBotRole(); else { role = expr.getEntry(); if ( role == NULL ) role = matchEntry ( RM->ensureRoleName(expr.getName()), &expr ); } tree = createEntry(RNAME,role); } virtual void visit ( const TDLObjectRoleInverse& expr ) { expr.getOR()->accept(*this); tree = createInverse(*this); } virtual void visit ( const TDLObjectRoleChain& expr ) { TDLObjectRoleChain::iterator p = expr.begin(), p_end = expr.end(); if ( p == p_end ) THROW_UNSUPPORTED("empty role chain"); (*p)->accept(*this); DLTree* acc = *this; while ( ++p != p_end ) { (*p)->accept(*this); acc = new DLTree ( TLexeme(RCOMPOSITION), acc, *this ); } tree = acc; } virtual void visit ( const TDLObjectRoleProjectionFrom& expr ) { expr.getOR()->accept(*this); DLTree* R = *this; expr.getC()->accept(*this); DLTree* C = *this; tree = new DLTree ( TLexeme(PROJFROM), R, C ); } virtual void visit ( const TDLObjectRoleProjectionInto& expr ) { expr.getOR()->accept(*this); DLTree* R = *this; expr.getC()->accept(*this); DLTree* C = *this; tree = new DLTree ( TLexeme(PROJINTO), R, C ); } // data role expressions virtual void visit ( const TDLDataRoleTop& expr ATTR_UNUSED ) { THROW_UNSUPPORTED("top data role"); } virtual void visit ( const TDLDataRoleBottom& expr ATTR_UNUSED ) { THROW_UNSUPPORTED("bottom data role"); } virtual void visit ( const TDLDataRoleName& expr ) { RoleMaster* RM = KB.getDRM(); TNamedEntry* role; if ( nc(&expr) ) role = sig->topRLocal() ? RM->getTopRole() : RM->getBotRole(); else { role = expr.getEntry(); if ( role == NULL ) role = matchEntry ( RM->ensureRoleName(expr.getName()), &expr ); } tree = createEntry(DNAME,role); } // data expressions virtual void visit ( const TDLDataTop& expr ATTR_UNUSED ) { tree = createTop(); } virtual void visit ( const TDLDataBottom& expr ATTR_UNUSED ) { tree = createBottom(); } virtual void visit ( const TDLDataTypeName& expr ) { DataTypeCenter& DTC = KB.getDataTypeCenter(); if ( isStrDataType(&expr) ) tree = DTC.getStringType(); else if ( isIntDataType(&expr) ) tree = DTC.getNumberType(); else if ( isRealDataType(&expr) ) tree = DTC.getRealType(); else if ( isBoolDataType(&expr) ) tree = DTC.getBoolType(); // get-by-name("bool")?? else if ( isTimeDataType(&expr) ) tree = DTC.getTimeType(); else THROW_UNSUPPORTED("data type name"); } virtual void visit ( const TDLDataTypeRestriction& expr ) { DLTree* acc = createTop(); for ( TDLDataTypeRestriction::iterator p = expr.begin(), p_end = expr.end(); p != p_end; ++p ) { (*p)->accept(*this); acc = createSNFAnd ( acc, *this ); } tree = acc; } virtual void visit ( const TDLDataValue& expr ) { expr.getExpr()->accept(*this); // process type DLTree* type = *this; tree = KB.getDataTypeCenter().getDataValue(expr.getName(),type); deleteTree(type); } virtual void visit ( const TDLDataNot& expr ) { expr.getExpr()->accept(*this); tree = createSNFNot(*this); } virtual void visit ( const TDLDataAnd& expr ) { DLTree* acc = createTop(); for ( TDLDataAnd::iterator p = expr.begin(), p_end = expr.end(); p != p_end; ++p ) { (*p)->accept(*this); acc = createSNFAnd ( acc, *this ); } tree = acc; } virtual void visit ( const TDLDataOr& expr ) { DLTree* acc = createBottom(); for ( TDLDataOr::iterator p = expr.begin(), p_end = expr.end(); p != p_end; ++p ) { (*p)->accept(*this); acc = createSNFOr ( acc, *this ); } tree = acc; } virtual void visit ( const TDLDataOneOf& expr ) { DLTree* acc = createBottom(); for ( TDLDataOneOf::iterator p = expr.begin(), p_end = expr.end(); p != p_end; ++p ) { (*p)->accept(*this); acc = createSNFOr ( acc, *this ); } tree = acc; } // facets virtual void visit ( const TDLFacetMinInclusive& expr ) { expr.getExpr()->accept(*this); tree = KB.getDataTypeCenter().getIntervalFacetExpr ( tree, /*min=*/true, /*excl=*/false ); } virtual void visit ( const TDLFacetMinExclusive& expr ) { expr.getExpr()->accept(*this); tree = KB.getDataTypeCenter().getIntervalFacetExpr ( tree, /*min=*/true, /*excl=*/true ); } virtual void visit ( const TDLFacetMaxInclusive& expr ) { expr.getExpr()->accept(*this); tree = KB.getDataTypeCenter().getIntervalFacetExpr ( tree, /*min=*/false, /*excl=*/false ); } virtual void visit ( const TDLFacetMaxExclusive& expr ) { expr.getExpr()->accept(*this); tree = KB.getDataTypeCenter().getIntervalFacetExpr ( tree, /*min=*/false, /*excl=*/true ); } #undef THROW_UNSUPPORTED }; // TExpressionTranslator #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/SemanticLocalityChecker.h0000644000000000000000000002460212112642405022262 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2011-2013 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef SEMLOCCHECKER_H #define SEMLOCCHECKER_H #include "LocalityChecker.h" #include "Kernel.h" /// semantic locality checker for DL axioms class SemanticLocalityChecker: public LocalityChecker { protected: // members /// Reasoner to detect the tautology ReasoningKernel Kernel; /// Expression manager of a kernel TExpressionManager* pEM; /// map between axioms and concept expressions std::map ExprMap; protected: // methods /// @return expression necessary to build query for a given type of an axiom; @return NULL if none necessary const TDLConceptExpression* getExpr ( const TDLAxiom* axiom ) { if ( const TDLAxiomRelatedTo* art = dynamic_cast(axiom) ) return pEM->Value ( art->getRelation(), art->getRelatedIndividual() ); if ( const TDLAxiomValueOf* avo = dynamic_cast(axiom) ) return pEM->Value ( avo->getAttribute(), avo->getValue() ); if ( const TDLAxiomORoleDomain* ord = dynamic_cast(axiom) ) return pEM->Exists ( ord->getRole(), pEM->Top() ); if ( const TDLAxiomORoleRange* orr = dynamic_cast(axiom) ) return pEM->Exists ( orr->getRole(), pEM->Not(orr->getRange()) ); if ( const TDLAxiomDRoleDomain* drd = dynamic_cast(axiom) ) return pEM->Exists ( drd->getRole(), pEM->DataTop() ); if ( const TDLAxiomDRoleRange* drr = dynamic_cast(axiom) ) return pEM->Exists ( drr->getRole(), pEM->DataNot(drr->getRange()) ); if ( const TDLAxiomRelatedToNot* rtn = dynamic_cast(axiom) ) return pEM->Not ( pEM->Value ( rtn->getRelation(), rtn->getRelatedIndividual() ) ); if ( const TDLAxiomValueOfNot* von = dynamic_cast(axiom) ) return pEM->Not ( pEM->Value ( von->getAttribute(), von->getValue() ) ); // everything else doesn't require expression to be build return NULL; } public: // interface /// init c'tor SemanticLocalityChecker ( const TSignature* sig ) : LocalityChecker(sig) { pEM = Kernel.getExpressionManager(); // for tests we will need TB names to be from the OWL 2 namespace pEM->setTopBottomRoles( "http://www.w3.org/2002/07/owl#topObjectProperty", "http://www.w3.org/2002/07/owl#bottomObjectProperty", "http://www.w3.org/2002/07/owl#topDataProperty", "http://www.w3.org/2002/07/owl#bottomDataProperty"); } /// empty d'tor virtual ~SemanticLocalityChecker ( void ) {} /// init kernel with the ontology signature and init expression map virtual void preprocessOntology ( const AxiomVec& Axioms ) { TSignature s; ExprMap.clear(); for ( AxiomVec::const_iterator q = Axioms.begin(), q_end = Axioms.end(); q != q_end; ++q ) { ExprMap[*q] = getExpr(*q); s.add((*q)->getSignature()); } Kernel.clearKB(); // register all the objects in the ontology signature for ( TSignature::iterator p = s.begin(), p_end = s.end(); p != p_end; ++p ) Kernel.declare(dynamic_cast(*p)); // prepare the reasoner to check tautologies Kernel.realiseKB(); // after TBox appears there, set signature to translate Kernel.setSignature(getSignature()); // disallow usage of the expression cache as same expressions will lead to different translations Kernel.setIgnoreExprCache(true); } public: // visitor interface virtual void visit ( const TDLAxiomDeclaration& ) { isLocal = true; } virtual void visit ( const TDLAxiomEquivalentConcepts& axiom ) { isLocal = false; TDLAxiomEquivalentConcepts::iterator p = axiom.begin(), p_end = axiom.end(); const TDLConceptExpression* C = *p; while ( ++p != p_end ) if ( !Kernel.isEquivalent ( C, *p ) ) return; isLocal = true; } virtual void visit ( const TDLAxiomDisjointConcepts& axiom ) { isLocal = false; for ( TDLAxiomDisjointConcepts::iterator p = axiom.begin(), q, p_end = axiom.end(); p != p_end; ++p ) for ( q = p+1; q != p_end; ++q ) if ( !Kernel.isDisjoint ( *p, *q ) ) return; isLocal = true; } virtual void visit ( const TDLAxiomDisjointUnion& axiom ) { isLocal = false; // check A = (or C1... Cn) TDLAxiomDisjointUnion::iterator p, q, p_end = axiom.end(); pEM->newArgList(); for ( p = axiom.begin(); p != p_end; ++p ) pEM->addArg(*p); if ( !Kernel.isEquivalent ( axiom.getC(), pEM->Or() ) ) return; // check disjoint(C1... Cn) for ( p = axiom.begin(); p != p_end; ++p ) for ( q = p+1; q != p_end; ++q ) if ( !Kernel.isDisjoint ( *p, *q ) ) return; isLocal = true; } virtual void visit ( const TDLAxiomEquivalentORoles& axiom ) { isLocal = false; TDLAxiomEquivalentORoles::iterator p = axiom.begin(), p_end = axiom.end(); const TDLObjectRoleExpression* R = *p; while ( ++p != p_end ) if ( !(Kernel.isSubRoles ( R, *p ) && Kernel.isSubRoles ( *p, R )) ) return; isLocal = true; } // tautology if all the subsumptions Ri [= Rj holds virtual void visit ( const TDLAxiomEquivalentDRoles& axiom ) { isLocal = false; TDLAxiomEquivalentDRoles::iterator p = axiom.begin(), p_end = axiom.end(); const TDLDataRoleExpression* R = *p; while ( ++p != p_end ) if ( !(Kernel.isSubRoles ( R, *p ) && Kernel.isSubRoles ( *p, R )) ) return; isLocal = true; } virtual void visit ( const TDLAxiomDisjointORoles& axiom ) { pEM->newArgList(); for ( TDLAxiomDisjointORoles::iterator p = axiom.begin(), p_end = axiom.end(); p != p_end; ++p ) pEM->addArg(*p); isLocal = Kernel.isDisjointRoles(); } virtual void visit ( const TDLAxiomDisjointDRoles& axiom ) { pEM->newArgList(); for ( TDLAxiomDisjointDRoles::iterator p = axiom.begin(), p_end = axiom.end(); p != p_end; ++p ) pEM->addArg(*p); isLocal = Kernel.isDisjointRoles(); } // never local virtual void visit ( const TDLAxiomSameIndividuals& ) { isLocal = false; } // never local virtual void visit ( const TDLAxiomDifferentIndividuals& ) { isLocal = false; } /// there is no such axiom in OWL API, but I hope nobody would use Fairness here virtual void visit ( const TDLAxiomFairnessConstraint& ) { isLocal = true; } // R = inverse(S) is tautology iff R [= S- and S [= R- virtual void visit ( const TDLAxiomRoleInverse& axiom ) { isLocal = Kernel.isSubRoles ( axiom.getRole(), pEM->Inverse(axiom.getInvRole()) ) && Kernel.isSubRoles ( axiom.getInvRole(), pEM->Inverse(axiom.getRole()) ); } virtual void visit ( const TDLAxiomORoleSubsumption& axiom ) { // check whether the LHS is a role chain if ( const TDLObjectRoleChain* Chain = dynamic_cast(axiom.getSubRole()) ) { pEM->newArgList(); for ( TDLObjectRoleChain::iterator p = Chain->begin(), p_end = Chain->end(); p != p_end; ++p ) pEM->addArg(*p); isLocal = Kernel.isSubChain(axiom.getRole()); } // check whether the LHS is a plain role or inverse else if ( const TDLObjectRoleExpression* Sub = dynamic_cast(axiom.getSubRole()) ) isLocal = Kernel.isSubRoles ( Sub, axiom.getRole() ); else // here we have a projection expression. FIXME!! for now isLocal = true; } virtual void visit ( const TDLAxiomDRoleSubsumption& axiom ) { isLocal = Kernel.isSubRoles ( axiom.getSubRole(), axiom.getRole() ); } // Domain(R) = C is tautology iff ER.Top [= C virtual void visit ( const TDLAxiomORoleDomain& axiom ) { isLocal = Kernel.isSubsumedBy ( ExprMap[&axiom], axiom.getDomain() ); } virtual void visit ( const TDLAxiomDRoleDomain& axiom ) { isLocal = Kernel.isSubsumedBy ( ExprMap[&axiom], axiom.getDomain() ); } // Range(R) = C is tautology iff ER.~C is unsatisfiable virtual void visit ( const TDLAxiomORoleRange& axiom ) { isLocal = !Kernel.isSatisfiable(ExprMap[&axiom]); } virtual void visit ( const TDLAxiomDRoleRange& axiom ) { isLocal = !Kernel.isSatisfiable(ExprMap[&axiom]); } virtual void visit ( const TDLAxiomRoleTransitive& axiom ) { isLocal = Kernel.isTransitive(axiom.getRole()); } virtual void visit ( const TDLAxiomRoleReflexive& axiom ) { isLocal = Kernel.isReflexive(axiom.getRole()); } virtual void visit ( const TDLAxiomRoleIrreflexive& axiom ) { isLocal = Kernel.isIrreflexive(axiom.getRole()); } virtual void visit ( const TDLAxiomRoleSymmetric& axiom ) { isLocal = Kernel.isSymmetric(axiom.getRole()); } virtual void visit ( const TDLAxiomRoleAsymmetric& axiom ) { isLocal = Kernel.isAsymmetric(axiom.getRole()); } virtual void visit ( const TDLAxiomORoleFunctional& axiom ) { isLocal = Kernel.isFunctional(axiom.getRole()); } virtual void visit ( const TDLAxiomDRoleFunctional& axiom ) { isLocal = Kernel.isFunctional(axiom.getRole()); } virtual void visit ( const TDLAxiomRoleInverseFunctional& axiom ) { isLocal = Kernel.isInverseFunctional(axiom.getRole()); } virtual void visit ( const TDLAxiomConceptInclusion& axiom ) { isLocal = Kernel.isSubsumedBy ( axiom.getSubC(), axiom.getSupC() ); } // for top locality, this might be local virtual void visit ( const TDLAxiomInstanceOf& axiom ) { isLocal = Kernel.isInstance ( axiom.getIndividual(), axiom.getC() ); } // R(i,j) holds if {i} [= \ER.{j} virtual void visit ( const TDLAxiomRelatedTo& axiom ) { isLocal = Kernel.isInstance ( axiom.getIndividual(), ExprMap[&axiom] ); } ///!R(i,j) holds if {i} [= \AR.!{j}=!\ER.{j} virtual void visit ( const TDLAxiomRelatedToNot& axiom ) { isLocal = Kernel.isInstance ( axiom.getIndividual(), ExprMap[&axiom] ); } // R(i,v) holds if {i} [= \ER.{v} virtual void visit ( const TDLAxiomValueOf& axiom ) { isLocal = Kernel.isInstance ( axiom.getIndividual(), ExprMap[&axiom] ); } // !R(i,v) holds if {i} [= !\ER.{v} virtual void visit ( const TDLAxiomValueOfNot& axiom ) { isLocal = Kernel.isInstance ( axiom.getIndividual(), ExprMap[&axiom] ); } }; // SemanticLocalityChecker #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/ReasonerNom.h0000644000000000000000000000657012112642405017765 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2010 by Dmitry Tsarkov This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef REASONERNOM_H #define REASONERNOM_H #include "Reasoner.h" class NominalReasoner: public DlSatTester { protected: // type definition /// vector of singletons typedef TBox::SingletonVector SingletonVector; protected: // members /// all nominals defined in TBox SingletonVector Nominals; protected: // methods /// prepare reasoning virtual void prepareReasoner ( void ); /// there are nominals virtual bool hasNominals ( void ) const { return true; } //----------------------------------------------------------------------------- //-- internal nominal reasoning interface //----------------------------------------------------------------------------- /// init vector of nominals defined in TBox void initNominalVector ( void ); /// create cache entry for given singleton void registerNominalCache ( TIndividual* p ) { DLHeap.setCache ( p->pName, createModelCache(p->node->resolvePBlocker()) ); } /// init single nominal node bool initNominalNode ( const TIndividual* nom ) { DlCompletionTree* node = CGraph.getNewNode(); node->setNominalLevel(); const_cast(nom)->node = node; // init nominal with associated node return initNewNode ( node, DepSet(), nom->pName ); // ABox is inconsistent } /// create nominal nodes for all individuals in TBox bool initNominalCloud ( void ); /// make an R-edge between related nominals bool initRelatedNominals ( const TRelated* rel ); /// use classification information for the nominal P void updateClassifiedSingleton ( TIndividual* p ) { registerNominalCache(p); if ( unlikely(p->node->isPBlocked()) ) { // BP of the individual P is merged to BipolarPointer bp = p->node->getBlocker()->label().begin_sc()->bp(); TIndividual* blocker = (TIndividual*)DLHeap[bp].getConcept(); fpp_assert ( blocker->node == p->node->getBlocker() ); tBox.SameI[p] = std::make_pair ( blocker, p->node->getPurgeDep().empty() ); } } public: /// c'tor NominalReasoner ( TBox& tbox ) : DlSatTester(tbox) { initNominalVector(); } /// empty d'tor virtual ~NominalReasoner ( void ) {} /// check whether ontology with nominals is consistent bool consistentNominalCloud ( void ); }; // NominalReasoner //----------------------------------------------------------------------------- //-- implemenation of nominal reasoner-related parts of TBox //----------------------------------------------------------------------------- inline void TBox :: initReasoner ( void ) { fpp_assert ( !reasonersInited() ); // do init only once stdReasoner = new DlSatTester(*this); if ( NCFeatures.hasSingletons() ) { nomReasoner = new NominalReasoner(*this); } } #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/tOntologyPrinterLISP.h0000644000000000000000000001550212112642405021562 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2009-2012 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef TONTOLOGYPRINTERLISP_H #define TONTOLOGYPRINTERLISP_H #include "tExpressionPrinterLISP.h" #include "tDLAxiom.h" #include "tOntology.h" class TLISPOntologyPrinter: public DLAxiomVisitor { protected: // members /// main stream std::ostream& o; /// printer for the expressions TLISPExpressionPrinter LEP; protected: // methods /// helper to print several expressions in a row template void print ( Iterator beg, Iterator end ) { for ( ; beg < end; ++beg ) (*beg)->accept(LEP); } /// helper to print a string TLISPOntologyPrinter& operator << ( const char* str ) { o << str; o.flush(); return *this; } /// helper to print an expression TLISPOntologyPrinter& operator << ( const TDLExpression* expr ) { expr->accept(LEP); return *this; } public: // visitor interface virtual void visit ( const TDLAxiomDeclaration& axiom ) { const TDLExpression* decl = axiom.getDeclaration(); bool cname = dynamic_cast(decl) != NULL; bool iname = dynamic_cast(decl) != NULL; bool rname = dynamic_cast(decl) != NULL; bool dname = dynamic_cast(decl) != NULL; // do not print TOP/BOT/datatypes if ( !cname && !iname && !rname && !dname ) return; *this << "(def" << (cname ? "primconcept" : iname ? "individual" : rname ? "primrole" : "datarole") << decl << ")\n"; } virtual void visit ( const TDLAxiomEquivalentConcepts& axiom ) { o << "(equal_c"; print ( axiom.begin(), axiom.end() ); o << ")\n"; } virtual void visit ( const TDLAxiomDisjointConcepts& axiom ) { o << "(disjoint_c"; print ( axiom.begin(), axiom.end() ); o << ")\n"; } virtual void visit ( const TDLAxiomDisjointUnion& axiom ) { o << "(disjoint_c"; print ( axiom.begin(), axiom.end() ); o << ")\n(equal_c (or" << axiom.getC(); print ( axiom.begin(), axiom.end() ); o << "))\n"; } virtual void visit ( const TDLAxiomEquivalentORoles& axiom ) { o << "(equal_r"; print ( axiom.begin(), axiom.end() ); o << ")\n"; } virtual void visit ( const TDLAxiomEquivalentDRoles& axiom ) { o << "(equal_r"; print ( axiom.begin(), axiom.end() ); o << ")\n"; } virtual void visit ( const TDLAxiomDisjointORoles& axiom ) { o << "(disjoint_r"; print ( axiom.begin(), axiom.end() ); o << ")\n"; } virtual void visit ( const TDLAxiomDisjointDRoles& axiom ) { o << "(disjoint_r"; print ( axiom.begin(), axiom.end() ); o << ")\n"; } virtual void visit ( const TDLAxiomSameIndividuals& axiom ) { o << "(same"; print ( axiom.begin(), axiom.end() ); o << ")\n"; } virtual void visit ( const TDLAxiomDifferentIndividuals& axiom ) { o << "(different"; print ( axiom.begin(), axiom.end() ); o << ")\n"; } virtual void visit ( const TDLAxiomFairnessConstraint& axiom ) { o << "(fairness"; print ( axiom.begin(), axiom.end() ); o << ")\n"; } virtual void visit ( const TDLAxiomRoleInverse& axiom ) { *this << "(equal_r" << axiom.getRole() << " (inv" << axiom.getInvRole() << "))\n"; } virtual void visit ( const TDLAxiomORoleSubsumption& axiom ) { *this << "(implies_r" << axiom.getSubRole() << axiom.getRole() << ")\n"; } virtual void visit ( const TDLAxiomDRoleSubsumption& axiom ) { *this << "(implies_r" << axiom.getSubRole() << axiom.getRole() << ")\n"; } virtual void visit ( const TDLAxiomORoleDomain& axiom ) { *this << "(domain" << axiom.getRole() << axiom.getDomain() << ")\n"; } virtual void visit ( const TDLAxiomDRoleDomain& axiom ) { *this << "(domain" << axiom.getRole() << axiom.getDomain() << ")\n"; } virtual void visit ( const TDLAxiomORoleRange& axiom ) { *this << "(range" << axiom.getRole() << axiom.getRange() << ")\n"; } virtual void visit ( const TDLAxiomDRoleRange& axiom ) { *this << "(range" << axiom.getRole() << axiom.getRange() << ")\n"; } virtual void visit ( const TDLAxiomRoleTransitive& axiom ) { *this << "(transitive" << axiom.getRole() << ")\n"; } virtual void visit ( const TDLAxiomRoleReflexive& axiom ) { *this << "(reflexive" << axiom.getRole() << ")\n"; } virtual void visit ( const TDLAxiomRoleIrreflexive& axiom ) { *this << "(irreflexive" << axiom.getRole() << ")\n"; } virtual void visit ( const TDLAxiomRoleSymmetric& axiom ) { *this << "(symmetric" << axiom.getRole() << ")\n"; } virtual void visit ( const TDLAxiomRoleAsymmetric& axiom ) { *this << "(asymmetric" << axiom.getRole() << ")\n"; } virtual void visit ( const TDLAxiomORoleFunctional& axiom ) { *this << "(functional" << axiom.getRole() << ")\n"; } virtual void visit ( const TDLAxiomDRoleFunctional& axiom ) { *this << "(functional" << axiom.getRole() << ")\n"; } virtual void visit ( const TDLAxiomRoleInverseFunctional& axiom ) { *this << "(functional (inv" << axiom.getRole() << "))\n"; } virtual void visit ( const TDLAxiomConceptInclusion& axiom ) { *this << "(implies_c" << axiom.getSubC() << axiom.getSupC() << ")\n"; } virtual void visit ( const TDLAxiomInstanceOf& axiom ) { *this << "(instance" << axiom.getIndividual() << axiom.getC() << ")\n"; } virtual void visit ( const TDLAxiomRelatedTo& axiom ) { *this << "(related" << axiom.getIndividual() << axiom.getRelation() << axiom.getRelatedIndividual() << ")\n"; } virtual void visit ( const TDLAxiomRelatedToNot& axiom ) { *this<< "(instance" << axiom.getIndividual() << " (all" << axiom.getRelation() << "(not" << axiom.getRelatedIndividual() << ")))\n"; } virtual void visit ( const TDLAxiomValueOf& axiom ) { *this << "(instance" << axiom.getIndividual() << " (some" << axiom.getAttribute() << axiom.getValue() << "))\n"; } virtual void visit ( const TDLAxiomValueOfNot& axiom ) { *this << "(instance" << axiom.getIndividual() << " (all" << axiom.getAttribute() << "(not " << axiom.getValue() << ")))\n"; } public: // interface TLISPOntologyPrinter ( std::ostream& o_ ) : o(o_), LEP(o_) {} virtual ~TLISPOntologyPrinter ( void ) {} void recordDataRole ( const char* name ) { o << "(defdatarole " << name << ")\n"; } virtual void visitOntology ( TOntology& ontology ) { for ( TOntology::iterator p = ontology.begin(), p_end = ontology.end(); p < p_end; ++p ) (*p)->accept(*this); o << std::endl; } }; // TLISPOntologyPrinter #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/dumpLisp.h0000644000000000000000000000462412112642405017330 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2006 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef _DUMPLISP_H #define _DUMPLISP_H #include "dumpInterface.h" #include "dlTBox.h" //TConcept/TRole /// class for dumping ontology to a lisp format class dumpLisp : public dumpInterface { public: // interface /// the only c'tor -- empty dumpLisp ( std::ostream& oo ) : dumpInterface(oo) {} /// empty d'tor virtual ~dumpLisp ( void ) {} // global prologue/epilogue virtual void prologue ( void ) {} virtual void epilogue ( void ) {} // general concept expression virtual void dumpTop ( void ) { o << "*TOP*"; } virtual void dumpBottom ( void ) { o << "*BOTTOM*"; } virtual void dumpNumber ( unsigned int n ) { o << n << " "; } virtual void startOp ( diOp Op ); /// start operation >=/<= with number virtual void startOp ( diOp Op, unsigned int n ) { startOp(Op); dumpNumber(n); } virtual void contOp ( diOp Op ) { if ( Op == diAnd || Op == diOr ) skipIndent(); else o << " "; } virtual void finishOp ( diOp Op ) { if ( Op == diAnd || Op == diOr ) decIndent(); o << ")"; } virtual void startAx ( diAx Ax ); virtual void contAx ( diAx Ax ATTR_UNUSED ) { o << " "; } virtual void finishAx ( diAx Ax ATTR_UNUSED ) { o << ")\n"; } /// obtain name by the named entry virtual void dumpName ( const TNamedEntry* p ) { o << "|" << p->getName() << "|"; } /// dump concept atom (as used in expression) virtual void dumpConcept ( const TConcept* p ) { dumpName(p); } /// dump role atom (as used in expression) virtual void dumpRole ( const TRole* p ) { if ( p->getId() < 0 ) // inverse { o << "(inv "; dumpName(p->inverse()); o << ")"; } else dumpName(p); } }; // dumpLisp #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/dumpInterface.h0000644000000000000000000000755412112642405020326 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2009 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef _DUMPINTERFACE_H #define _DUMPINTERFACE_H #include #include "globaldef.h" #include "tNamedEntry.h" #include "dltree.h" class TConcept; class TRole; /// enumeration of dump interface concept operations enum diOp { // concept expressions diNot, diAnd, diOr, diExists, diForall, diGE, diLE, // role expressions diInv, // individual expressions diOneOf, // wrong operation diErrorOp, // end of the enum diLastOp = diErrorOp }; // diOp /// enumeration of dump interface axioms enum diAx { // wrong axiom diErrorAx = diLastOp, // concept axioms diDefineC, diImpliesC, diEqualsC, diDisjointC, // role axioms diDefineR, diTransitiveR, diFunctionalR, diImpliesR, diEqualsR, diDomainR, diRangeR, // individual axioms diInstanceOf, }; // diAx /// general interface for dumping ontology to a proper format class dumpInterface { protected: // members /// output stream std::ostream& o; /// indentation level unsigned int indent; /// print every axiom on a single line (need for sorting, for example) bool oneliner; protected: // methods /// write necessary amount of TABs void skipIndent ( void ); /// increase indentation level void incIndent ( void ); /// decrease indentation level void decIndent ( void ); public: // interface /// the only c'tor -- empty dumpInterface ( std::ostream& oo ) : o(oo), indent(0), oneliner(false) {} /// empty d'tor virtual ~dumpInterface ( void ) {} /// set ONELINER flag; @return previous value bool useIndentation ( bool val ) { bool ret = oneliner; oneliner = val; return ret; } // global prologue/epilogue virtual void prologue ( void ) {} virtual void epilogue ( void ) {} // general concept expression virtual void dumpTop ( void ) {} virtual void dumpBottom ( void ) {} virtual void dumpNumber ( unsigned int n ATTR_UNUSED ) {} virtual void startOp ( diOp Op ATTR_UNUSED ) {} /// start operation >=/<= with number virtual void startOp ( diOp Op ATTR_UNUSED, unsigned int n ATTR_UNUSED ) {} virtual void contOp ( diOp Op ATTR_UNUSED ) {} virtual void finishOp ( diOp Op ATTR_UNUSED ) {} virtual void startAx ( diAx Ax ATTR_UNUSED ) {} virtual void contAx ( diAx Ax ATTR_UNUSED ) {} virtual void finishAx ( diAx Ax ATTR_UNUSED ) {} /// obtain name by the named entry virtual void dumpName ( const TNamedEntry* p ) { o << p->getName(); } /// dump concept atom (as used in expression) virtual void dumpConcept ( const TConcept* p ATTR_UNUSED ) {} /// dump role atom (as used in expression) virtual void dumpRole ( const TRole* p ATTR_UNUSED ) {} }; // dumpInterface inline void dumpInterface :: skipIndent ( void ) { if ( oneliner ) return; o << "\n"; for ( int i = indent-1; i >= 0; --i ) o << " "; } inline void dumpInterface :: incIndent ( void ) { skipIndent(); ++indent; // operands of AND-like } inline void dumpInterface :: decIndent ( void ) { --indent; skipIndent(); } // dump given concept expression void dumpCExpression ( dumpInterface* dump, const DLTree* C ); // dump given role expression void dumpRExpression ( dumpInterface* dump, const DLTree* R ); #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/dlVHashImpl.h0000644000000000000000000000270312112642405017702 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2006-2008 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef _DLVHASHIMPL_H #define _DLVHASHIMPL_H // implementation of DLVertex Hash; to be included after DLDag definition inline BipolarPointer dlVHashTable :: locate ( const HashLeaf& leaf, const DLVertex& v ) const { for ( HashLeaf::const_iterator p = leaf.begin(), p_end = leaf.end(); p != p_end; ++p ) if ( v == host[*p] ) return *p; return bpINVALID; } inline BipolarPointer dlVHashTable :: locate ( const DLVertex& v ) const { HashTable::const_iterator p = Table.find(hash(v)); return p == Table.end() ? bpINVALID : locate ( p->second, v ); } inline void dlVHashTable :: addElement ( BipolarPointer pos ) { insert ( Table[hash(host[pos])], pos ); } #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/dlTBox.h0000644000000000000000000013035612112642405016731 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2012 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef DLTBOX_H #define DLTBOX_H #include #include #include "tConcept.h" #include "tIndividual.h" #include "modelCacheSingleton.h" #include "RoleMaster.h" #include "LogicFeature.h" #include "dlDag.h" #include "ifOptions.h" #include "PriorityMatrix.h" #include "tRelated.h" #include "tNECollection.h" #include "tAxiomSet.h" #include "DataTypeCenter.h" #include "tProgressMonitor.h" #include "tKBFlags.h" #include "tSplitVars.h" #include "tSplitExpansionRules.h" class DlSatTester; class DLConceptTaxonomy; class dumpInterface; /// enumeration for the reasoner status enum KBStatus { kbEmpty, // no axioms loaded yet; not used in TBox kbLoading, // axioms are added to the KB, no preprocessing done kbCChecked, // KB is preprocessed and consistency checked kbClassified, // KB is classified kbRealised, // KB is realised }; class TBox { friend class DlSatTester; friend class NominalReasoner; friend class ReasoningKernel; friend class TAxiom; // FIXME!! while TConcept can't get rid of told cycles friend class DLConceptTaxonomy; public: // type interface /// vector of CONCEPT-like elements typedef std::vector ConceptVector; /// vector of SINGLETON-like elements typedef std::vector SingletonVector; protected: // types /// type for DISJOINT-like statements typedef std::vector ExpressionArray; /// set of concepts together with creation methods typedef TNECollection ConceptCollection; /// collection of individuals typedef TNECollection IndividualCollection; /// type for the array of Related elements typedef std::vector RelatedCollection; /// type for a collection of DIFFERENT individuals typedef std::vector DifferentIndividuals; /// class for simple rules like Ch :- Cb1, Cbi, CbN; all C are primitive named concepts class TSimpleRule { public: // type interface /// type for the rule body typedef TBox::ConceptVector TRuleBody; /// RW iterator over body typedef TRuleBody::iterator iterator; /// RO iterator over body typedef TRuleBody::const_iterator const_iterator; public: // members /// body of the rule TRuleBody Body; /// head of the rule as a DLTree DLTree* tHead; /// head of the rule as a BP BipolarPointer bpHead; private: // no copy /// no copy c'tor TSimpleRule ( const TSimpleRule& ); /// no assignment TSimpleRule& operator= ( const TSimpleRule& ); public: // interface /// init c'tor TSimpleRule ( const TRuleBody& body, DLTree* head ) : Body(body) , tHead(head) , bpHead(bpINVALID) {} /// empty d'tor virtual ~TSimpleRule ( void ) { deleteTree(tHead); } // apply rule -- implementation in Reasoner.h /// allow reasoner to check the applicability according to the type of the rule virtual bool applicable ( DlSatTester& Reasoner ) const; }; // TSimpleRule /// all simple rules in KB typedef std::vector TSimpleRules; /// R-C cache for the \forall R.C replacement in GCIs typedef std::vector > TRCCache; protected: // typedefs /// RW concept iterator typedef ConceptCollection::iterator c_iterator; /// RW individual iterator typedef IndividualCollection::iterator i_iterator; /// RO ExpressionArray iterator typedef ExpressionArray::const_iterator ea_iterator; public: // interface /// RO concept iterator typedef ConceptCollection::const_iterator c_const_iterator; /// RO individual iterator typedef IndividualCollection::const_iterator i_const_iterator; protected: // members /// relevance label (to determine logical features) TLabeller relevance; /// DAG of all expressions DLDag DLHeap; /// reasoner for TBox-related queries w/o nominals DlSatTester* stdReasoner; /// reasoner for TBox-related queries with nominals DlSatTester* nomReasoner; /// use this macro to do the same action with all available reasoners # define REASONERS_DO(ACT) do { \ nomReasoner->ACT; \ stdReasoner->ACT; } while(0) /// progress monitor TProgressMonitor* pMonitor; /// vectors for Completely defined, Non-CD and Non-primitive concepts ConceptVector arrayCD, arrayNoCD, arrayNP; /// taxonomy structure of a TBox DLConceptTaxonomy* pTax; /// DataType center DataTypeCenter DTCenter; /// set of reasoning options const ifOptionSet* pOptions; /// status of the KB KBStatus Status; /// global KB features LogicFeatures KBFeatures; /// GCI features LogicFeatures GCIFeatures; /// nominal cloud features LogicFeatures NCFeatures; /// aux features LogicFeatures auxFeatures; /// pointer to current feature (in case of local ones) LogicFeatures* curFeature; // auxiliary concepts for Taxonomy /// concept representing Top TConcept* pTop; /// concept representing Bottom TConcept* pBottom; /// concept representing temporary one that can not be used anywhere in the ontology TConcept* pTemp; /// temporary concept that represents query TConcept* pQuery; /// all named concepts ConceptCollection Concepts; /// all named individuals/nominals IndividualCollection Individuals; /// "normal" (object) roles RoleMaster ORM; /// data roles RoleMaster DRM; /// set of GCIs TAxiomSet Axioms; /// given individual-individual relations RelatedCollection RelatedI; /// known disjoint sets of individuals DifferentIndividuals Different; /// all simple rules in KB TSimpleRules SimpleRules; /// map to show the possible equivalence between individuals std::map > SameI; /// split rules TSplitRules SplitRules; /// set of split vars TSplitVars* Splits; /// internalisation of a general axioms BipolarPointer T_G; /// KB flags about GCIs TKBFlags GCIs; /// cache for the \forall R.C replacements during absorption TRCCache RCCache; /// maps from concept index to concept itself ConceptVector ConceptMap; /// number of concepts and individuals; used to set index for modelCache unsigned int nC; /// number of all distinct roles; used to set index for modelCache unsigned int nR; /// current aux concept's ID unsigned int auxConceptID; /// how many times nominals were found during translation to DAG; local to BuildDAG unsigned int nNominalReferences; /// number of relevant calls to named concepts; local to relevance unsigned long nRelevantCCalls; /// number of relevant calls to concept expressions; local to relevance unsigned long nRelevantBCalls; /// searchable stack for the told subsumers std::set CInProcess; /// all the synonyms in the told subsumers' cycle std::vector ToldSynonyms; /// fairness constraints ConceptVector Fairness; /// priority matrix for To-Do lists ToDoPriorMatrix PriorityMatrix; /// single SAT/SUB test timeout in milliseconds unsigned long testTimeout; //--------------------------------------------------------------------------- // Reasoner's members: there are many reasoner classes, some members are shared //--------------------------------------------------------------------------- /// flag for switching semantic branching bool useSemanticBranching; /// flag for switching backjumping bool useBackjumping; /// whether or not check blocking status as late as possible bool useLazyBlocking; /// flag for switching between Anywhere and Ancestor blockings bool useAnywhereBlocking; /// flag to use caching during completion tree construction bool useNodeCache; /// let reasoner know that we are in the classificaton (for splits) bool duringClassification; /// how many nodes skip before block; work only with FAIRNESS int nSkipBeforeBlock; //--------------------------------------------------------------------------- // User-defined flags //--------------------------------------------------------------------------- /// flag for full/short KB bool useRelevantOnly; /// flag for creating taxonomy bool useCompletelyDefined; /// flag for dumping TBox relevant to query bool dumpQuery; /// whether or not we need classification. Set up in checkQueryNames() bool needClassification; /// shall we prefer C=D axioms to C[=E in definition of concepts bool alwaysPreferEquals; /// use special domains as GCIs bool useSpecialDomains; /// shall verbose output be used bool verboseOutput; //--------------------------------------------------------------------------- // Internally defined flags //--------------------------------------------------------------------------- /// whether we use sorted reasoning; depends on some simplifications bool useSortedReasoning; /// flag whether TBox is GALEN-like bool isLikeGALEN; /// flag whether TBox is WINE-like bool isLikeWINE; /// whether KB is consistent bool Consistent; /// time spend for preprocessing float preprocTime; /// time spend for consistency checking float consistTime; private: // no copy /// no copy c'tor TBox ( const TBox& ); /// no assignment TBox& operator = ( const TBox& ); protected: // methods /// init all flags using given set of options void readConfig ( const ifOptionSet* Options ); /// initialise Top and Bottom internal concepts void initTopBottom ( void ); //----------------------------------------------------------------------------- //-- internal iterators //----------------------------------------------------------------------------- /// RW begin() for concepts c_iterator c_begin ( void ) { return Concepts.begin(); } /// RW end() for concepts c_iterator c_end ( void ) { return Concepts.end(); } /// RW begin() for individuals i_iterator i_begin ( void ) { return Individuals.begin(); } /// RW end() for individuals i_iterator i_end ( void ) { return Individuals.end(); } //----------------------------------------------------------------------------- //-- internal ensure*-like interface //----------------------------------------------------------------------------- /// @return concept by given Named Entry ID TConcept* toConcept ( TNamedEntry* id ) { return static_cast(id); } /// @return concept by given Named Entry ID const TConcept* toConcept ( const TNamedEntry* id ) const { return static_cast(id); } /// @return individual by given Named Entry ID TIndividual* toIndividual ( TNamedEntry* id ) { return static_cast(id); } /// @return individual by given Named Entry ID const TIndividual* toIndividual ( const TNamedEntry* id ) const { return static_cast(id); } //----------------------------------------------------------------------------- //-- internal BP-to-concept interface //----------------------------------------------------------------------------- /// set P as a concept corresponding BP void setBPforConcept ( BipolarPointer bp, TConcept* p ) { DLHeap[bp].setConcept(p); p->pName = bp; } /// get concept by it's BP (non-const version) TDataEntry* getDataEntryByBP ( BipolarPointer bp ) { TDataEntry* p = static_cast(DLHeap[bp].getConcept()); fpp_assert ( p != NULL ); return p; } /// get concept by it's BP (const version) const TDataEntry* getDataEntryByBP ( BipolarPointer bp ) const { const TDataEntry* p = static_cast(DLHeap[bp].getConcept()); fpp_assert ( p != NULL ); return p; } //----------------------------------------------------------------------------- //-- internal concept building interface //----------------------------------------------------------------------------- /// add description to a concept; @return true in case of error bool initNonPrimitive ( TConcept* p, DLTree* desc ) { if ( !p->canInitNonPrim(desc) ) return true; // delete return value in case of duplicated desc deleteTree(makeNonPrimitive(p,desc)); return false; } /// make concept non-primitive; @return it's old description DLTree* makeNonPrimitive ( TConcept* p, DLTree* desc ) { DLTree* ret = p->makeNonPrimitive(desc); checkEarlySynonym(p); return ret; } /// checks if C is defined as C=D and set Synonyms accordingly void checkEarlySynonym ( TConcept* p ) { if ( p->isSynonym() ) return; // nothing to do if ( p->isPrimitive() ) return; // couldn't be a synonym if ( !isCN (p->Description) ) return; // complex expression -- not a synonym(imm.) p->setSynonym(getCI(p->Description)); p->initToldSubsumers(); } //----------------------------------------------------------------------------- //-- support for n-ary predicates //----------------------------------------------------------------------------- /// build a construction in the form AND (\neg q_i) template DLTree* buildDisjAux ( Iterator beg, Iterator end ) { DLTree* t = createTop(); for ( Iterator i = beg; i < end; ++i ) t = createSNFAnd ( t, createSNFNot(clone(*i)) ); return t; } /// process a disjoint set [beg,end) in a usual manner template void processDisjoint ( Iterator beg, Iterator end ) { for ( Iterator i = beg; i < end; ++i ) addSubsumeAxiom ( *i, buildDisjAux ( i+1, end ) ); } //----------------------------------------------------------------------------- //-- internal DAG building methods //----------------------------------------------------------------------------- /// build a DAG-structure for concepts and axioms void buildDAG ( void ); /// translate concept P (together with definition) to DAG representation void addConceptToHeap ( TConcept* p ); /// register data-related expression in the DAG; @return it's DAG index BipolarPointer addDataExprToHeap ( TDataEntry* p ); /// builds DAG entry by general concept expression BipolarPointer tree2dag ( const DLTree* ); /// create forall node (together with transitive sub-roles entries) BipolarPointer forall2dag ( const TRole* R, BipolarPointer C ); /// create atmost node (together with NN-rule entries) BipolarPointer atmost2dag ( unsigned int n, const TRole* R, BipolarPointer C ); /// create REFLEXIVE node BipolarPointer reflexive2dag ( const TRole* R ) { // input check: only simple roles are allowed in the reflexivity construction if ( !R->isSimple() ) throw EFPPNonSimpleRole(R->getName()); return inverse ( DLHeap.add ( new DLVertex ( dtIrr, R ) ) ); } /// create node for AND expression T BipolarPointer and2dag ( const DLTree* t ); /// add elements of T to and-like vertex V; @return true if clash occures bool fillANDVertex ( DLVertex* v, const DLTree* t ); /// create forall node for data role BipolarPointer dataForall2dag ( const TRole* R, BipolarPointer C ) { return DLHeap.add ( new DLVertex ( dtForall, 0, R, C ) ); } /// create atmost node for data role BipolarPointer dataAtMost2dag ( unsigned int n, const TRole* R, BipolarPointer C ) { return DLHeap.add ( new DLVertex ( dtLE, n, R, C ) ); } /// @return a pointer to concept representation BipolarPointer concept2dag ( TConcept* p ) { if ( p == NULL ) return bpINVALID; if ( !isValid(p->pName) ) addConceptToHeap(p); return p->resolveId(); } /// transform splitted concept registered in SPLIT to a dag representation void split2dag ( TSplitVar* split ); //----------------------------------------------------------------------------- //-- internal parser (input) interface //----------------------------------------------------------------------------- /// set the flag that forbid usage of undefined names for concepts/roles; @return old value bool setForbidUndefinedNames ( bool val ) { ORM.setUndefinedNames(!val); DRM.setUndefinedNames(!val); Individuals.setLocked(val); return Concepts.setLocked(val); } /// tries to apply axiom D [= CN; @return true if applicable bool applyAxiomCToCN ( DLTree* D, DLTree*& CN ); /// tries to apply axiom CN [= D; @return true if applicable bool applyAxiomCNToC ( DLTree*& CN, DLTree* D ); /// tries to add LEFT = RIGHT for the concept LEFT; @return true if OK bool addNonprimitiveDefinition ( DLTree* left, DLTree* right ); /// tries to add LEFT = RIGHT for the concept LEFT [= X; @return true if OK bool switchToNonprimitive ( DLTree* left, DLTree* right ); // for complex Concept operations /// try to absorb GCI C[=D; if not possible, just record this GCI void processGCI ( DLTree* C, DLTree* D ) { Axioms.addAxiom ( C, D ); } // recognize Range/Domain restriction in an axiom and transform it into role R&D. // return true if transformation was performed bool axiomToRangeDomain ( DLTree* l, DLTree* r ); /// @return true if BP represents a named entry in a DAG bool isNamedConcept ( BipolarPointer bp ) const { DagTag tag = DLHeap[bp].Type(); return isCNameTag(tag) || tag == dtDataType || tag == dtDataValue; } /// get aux concept obtained from C=\AR.~D by forall replacement TConcept* getRCCache ( const DLTree* C ) const { for ( TRCCache::const_iterator p = RCCache.begin(), p_end = RCCache.end(); p < p_end; ++p ) if ( equalTrees ( C, p->first ) ) return p->second; return NULL; } /// add CN as a cache entry for C=\AR.~D> void setRCCache ( DLTree* C, TConcept* CN ) { RCCache.push_back(std::make_pair(C,CN)); } /// check if TBox contains too many GCIs to switch strategy bool isGalenLikeTBox ( void ) const { return isLikeGALEN; } /// check if TBox contains too many nominals and GCIs to switch strategy bool isWineLikeTBox ( void ) const { return isLikeWINE; } //----------------------------------------------------------------------------- //-- internal preprocessing methods //----------------------------------------------------------------------------- /// build a roles taxonomy and a DAG void Preprocess ( void ); /// absorb all axioms void AbsorbAxioms ( void ) { unsigned int nSynonyms = countSynonyms(); Axioms.absorb(); if ( countSynonyms() > nSynonyms ) replaceAllSynonyms(); if ( Axioms.wasRoleAbsorptionApplied() ) initToldSubsumers(); } /// pre-process RELATED axioms: resolve synonyms, mark individuals as related void preprocessRelated ( void ); /// determine all sorts in KB (make job only for SORTED_REASONING) void determineSorts ( void ); /// calculate statistic for DAG and Roles void CalculateStatistic ( void ); /// Remove DLTree* from TConcept after DAG is constructed void RemoveExtraDescriptions ( void ); /// init Range and Domain for all roles of RM; sets hasGCI if R&D was found void initRangeDomain ( RoleMaster& RM ); /// build up split rules for reasoners; create them after DAG is build void buildSplitRules ( void ) { if ( !getSplits()->empty() ) { SplitRules.createSplitRules(getSplits()); SplitRules.initEntityMap(DLHeap); } } /// set told TOP concept whether necessary void initToldSubsumers ( void ) { for ( c_iterator pc = c_begin(); pc != c_end(); ++pc ) if ( !(*pc)->isSynonym() ) (*pc)->initToldSubsumers(); for ( i_iterator pi = i_begin(); pi != i_end(); ++pi ) if ( !(*pi)->isSynonym() ) (*pi)->initToldSubsumers(); } /// set told TOP concept whether necessary void setToldTop ( void ) { TConcept* top = const_cast(pTop); for ( c_iterator pc = c_begin(); pc != c_end(); ++pc ) (*pc)->setToldTop(top); for ( i_iterator pi = i_begin(); pi != i_end(); ++pi ) (*pi)->setToldTop(top); } /// calculate TS depth for all concepts void calculateTSDepth ( void ) { for ( c_iterator pc = c_begin(); pc != c_end(); ++pc ) (*pc)->calculateTSDepth(); for ( i_iterator pi = i_begin(); pi != i_end(); ++pi ) (*pi)->calculateTSDepth(); } /// find referential cycles (like A [= (and B C), B [= A) and transform them to synonyms (B=A, A[=C) void transformToldCycles ( void ); /// check if P appears in referential cycle; /// @return concept which creates cycle, NULL if no such concept exists. TConcept* checkToldCycle ( TConcept* p ); /// transform i [= C [= j into i=C=j for i,j nominals void transformSingletonHierarchy ( void ); /// make P and all its non-singleton parents synonyms to its singleton parent; @return that singleton TIndividual* transformSingletonWithSP ( TConcept* p ); /// helper to the previous function TIndividual* getSPForConcept ( TConcept* p ); /// @return number of synonyms in the KB unsigned int countSynonyms ( void ) const { unsigned int nSynonyms = 0; for ( c_const_iterator pc = c_begin(); pc != c_end(); ++pc ) if ( (*pc)->isSynonym() ) ++nSynonyms; for ( i_const_iterator pi = i_begin(); pi != i_end(); ++pi ) if ( (*pi)->isSynonym() ) ++nSynonyms; return nSynonyms; } /// replace all synonyms in concept descriptions with their definitions void replaceAllSynonyms ( void ); /// init Extra Rule field in concepts given by a vector V with a given INDEX inline void initRuleFields ( const ConceptVector& v, unsigned int index ) const { for ( ConceptVector::const_iterator q = v.begin(), q_end = v.end(); q < q_end; ++q ) (*q)->addExtraRule(index); } /// mark all concepts wrt their classification tag void fillsClassificationTag ( void ) { for ( c_const_iterator pc = c_begin(); pc != c_end(); ++pc ) (*pc)->getClassTag(); for ( i_const_iterator pi = i_begin(); pi != i_end(); ++pi ) (*pi)->getClassTag(); } /// set new concept index for given C wrt existing nC void setConceptIndex ( TConcept* C ) { C->setIndex(nC); ConceptMap.push_back(C); ++nC; } /// set index on all classifiable entries void setAllIndexes ( void ); //----------------------------------------------------------------------------- //-- internal reasoner-related interface //----------------------------------------------------------------------------- /// @return true iff reasoners were initialised bool reasonersInited ( void ) const { return stdReasoner != NULL; } /// get RW reasoner wrt nominal case DlSatTester* getReasoner ( void ) { fpp_assert ( curFeature != NULL ); if ( curFeature->hasSingletons() ) return nomReasoner; else return stdReasoner; } /// get RO reasoner wrt nominal case const DlSatTester* getReasoner ( void ) const { fpp_assert ( curFeature != NULL ); if ( curFeature->hasSingletons() ) return nomReasoner; else return stdReasoner; } /// check whether KB is consistent; @return true if it is bool performConsistencyCheck ( void ); // implemented in Reasoner.h //----------------------------------------------------------------------------- //-- internal reasoning interface //----------------------------------------------------------------------------- /// init reasoning service: create reasoner(s) void initReasoner ( void ); // implemented in Reasoner.h /// creating taxonomy for given TBox; include individuals if necessary void createTaxonomy ( bool needIndividuals ); /// distribute all elements in [begin,end) range wtr theif tags template unsigned int fillArrays ( Iterator begin, Iterator end ) { unsigned int n = 0; for ( Iterator p = begin; p < end; ++p ) { if ( (*p)->isNonClassifiable() ) continue; ++n; switch ( (*p)->getClassTag() ) { case cttTrueCompletelyDefined: arrayCD.push_back(*p); break; default: arrayNoCD.push_back(*p); break; case cttNonPrimitive: case cttHasNonPrimitiveTS: arrayNP.push_back(*p); break; } } return n; } /// classify all concepts from given COLLECTION with given CD value void classifyConcepts ( const ConceptVector& collection, bool curCompletelyDefined, const char* type ); /// classify single concept void classifyEntry ( TConcept* entry ); //----------------------------------------------------------------------------- //-- internal cache-related methods //----------------------------------------------------------------------------- /// init const cache for either bpTOP or bpBOTTOM void initConstCache ( BipolarPointer p ) { DLHeap.setCache ( p, createConstCache(p) ); } /// init [singleton] cache for given concept and polarity void initSingletonCache ( const TConcept* p, bool pos ) { DLHeap.setCache ( createBiPointer(p->pName,pos), new modelCacheSingleton(createBiPointer(p->index(),pos)) ); } /// create cache for ~C where C is a primitive concept (as it is simple) void buildSimpleCache ( void ); //----------------------------------------------------------------------------- //-- internal output helper methods //----------------------------------------------------------------------------- void PrintDagEntry ( std::ostream& o, BipolarPointer p ) const; /// print one concept-like entry void PrintConcept ( std::ostream& o, const TConcept* p ) const; /// print all registered concepts void PrintConcepts ( std::ostream& o ) const { if ( Concepts.size() == 0 ) return; o << "Concepts (" << Concepts.size() << "):\n"; for ( c_const_iterator pc = c_begin(); pc != c_end(); ++pc ) PrintConcept(o,*pc); } /// print all registered individuals void PrintIndividuals ( std::ostream& o ) const { if ( Individuals.size() == 0 ) return; o << "Individuals (" << Individuals.size() << "):\n"; for ( i_const_iterator pi = i_begin(); pi != i_end(); ++pi ) PrintConcept(o,*pi); } void PrintSimpleRules ( std::ostream& o ) const { if ( SimpleRules.empty() ) return; o << "Simple rules (" << SimpleRules.size() << "):\n"; for ( TSimpleRules::const_iterator p = SimpleRules.begin(); p < SimpleRules.end(); ++p ) { ConceptVector::const_iterator q = (*p)->Body.begin(), q_end = (*p)->Body.end(); o << "(" << (*q)->getName(); while ( ++q < q_end ) o << ", " << (*q)->getName(); o << ") => " << (*p)->tHead << "\n"; } } void PrintAxioms ( std::ostream& o ) const { if ( T_G == bpTOP ) return; o << "Axioms:\nT [="; PrintDagEntry ( o, T_G ); } /// print KB features to LL void printFeatures ( void ) const; //----------------------------------------------------------------------------- //-- save/load support; implementation in SaveLoad.cpp //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //-- internal relevance helper methods //----------------------------------------------------------------------------- /// is given concept relevant wrt current TBox bool isRelevant ( const TConcept* p ) const { return p->isRelevant(relevance); } /// set given concept relevant wrt current TBox void setRelevant1 ( TConcept* p ); /// set given concept relevant wrt current TBox if not checked yet void setRelevant ( TConcept* p ) { if ( !isRelevant(p) ) setRelevant1(p); } /// is given role relevant wrt current TBox bool isRelevant ( const TRole* p ) const { return p->isRelevant(relevance); } /// set given role relevant wrt current TBox void setRelevant1 ( TRole* p ); /// set given role relevant wrt current TBox if not checked yet void setRelevant ( TRole* p ) { if ( ( likely(p->getId() != 0) || p->isTop() ) && !isRelevant(p) ) setRelevant1(p); } /// set given DAG entry relevant wrt current TBox void setRelevant ( BipolarPointer p ); /// gather information about logical features of relevant concept void collectLogicFeature ( const TConcept* p ) const { if ( curFeature ) curFeature->fillConceptData(p); } /// gather information about logical features of relevant role void collectLogicFeature ( const TRole* p ) const { if ( curFeature ) // update features w.r.t. current concept curFeature->fillRoleData ( p, isRelevant(p->inverse()) ); } /// gather information about logical features of relevant DAG entry void collectLogicFeature ( const DLVertex& v, bool pos ) const { if ( curFeature ) curFeature->fillDAGData ( v, pos ); } /// mark all active GCIs relevant void markGCIsRelevant ( void ) { setRelevant(T_G); } //----------------------------------------------------------------------------- //-- internal relevance interface //----------------------------------------------------------------------------- /// set all TBox content (namely, concepts and GCIs) relevant void markAllRelevant ( void ) { for ( c_iterator pc = c_begin(); pc != c_end(); ++pc ) setRelevant(*pc); for ( i_iterator pi = i_begin(); pi != i_end(); ++pi ) setRelevant(*pi); markGCIsRelevant(); } /// mark chosen part of TBox (P, Q and GCIs) relevant void calculateRelevant ( TConcept* p, TConcept* q ) { setRelevant(p); if ( q != NULL ) setRelevant(q); markGCIsRelevant(); } /// clear all relevance info void clearRelevanceInfo ( void ) { relevance.newLabel(); } /// gather relevance statistic for the whole KB void gatherRelevanceInfo ( void ); /// put relevance information to a concept's data void setConceptRelevant ( TConcept* p ) { curFeature = &p->posFeatures; setRelevant(p->pBody); KBFeatures |= p->posFeatures; collectLogicFeature(p); clearRelevanceInfo(); // nothing to do for neg-prim concepts if ( p->isPrimitive() ) return; curFeature = &p->negFeatures; setRelevant(inverse(p->pBody)); KBFeatures |= p->negFeatures; clearRelevanceInfo(); } /// update AUX features with the given one; update roles if necessary void updateAuxFeatures ( const LogicFeatures& lf ) { if ( !lf.empty() ) { auxFeatures |= lf; auxFeatures.mergeRoles(); } } /// prepare features for SAT(P), or SUB(P,Q) test void prepareFeatures ( const TConcept* pConcept, const TConcept* qConcept ); /// clear current features void clearFeatures ( void ) { curFeature = NULL; } //----------------------------------------------------------------------------- //-- internal dump output interface //----------------------------------------------------------------------------- /// dump concept-like essence using given dump method void dumpConcept ( dumpInterface* dump, const TConcept* p ) const; /// dump role-like essence using given dump method void dumpRole ( dumpInterface* dump, const TRole* p ) const; /// dump general concept expression using given dump method void dumpExpression ( dumpInterface* dump, BipolarPointer p ) const; /// dump all (relevant) roles void dumpAllRoles ( dumpInterface* dump ) const; public: /// init c'tor TBox ( const ifOptionSet* Options, const std::string& TopORoleName, const std::string& BotORoleName, const std::string& TopDRoleName, const std::string& BotDRoleName ); /// d'tor ~TBox ( void ); /// get RW access to used Role Master RoleMaster* getORM ( void ) { return &ORM; } /// get RO access to used Role Master const RoleMaster* getORM ( void ) const { return &ORM; } /// get RW access to used DataRole Master RoleMaster* getDRM ( void ) { return &DRM; } /// get RO access to used DataRole Master const RoleMaster* getDRM ( void ) const { return &DRM; } /// get RW access to the RoleMaster depending of the R RoleMaster* getRM ( const TRole* R ) { return R->isDataRole() ? getDRM() : getORM(); } /// get RO access to the RoleMaster depending of the R const RoleMaster* getRM ( const TRole* R ) const { return R->isDataRole() ? getDRM() : getORM(); } /// get RW access to a DT center DataTypeCenter& getDataTypeCenter ( void ) { return DTCenter; } /// get RO access to a DT center const DataTypeCenter& getDataTypeCenter ( void ) const { return DTCenter; } /// get RO access to DAG (needed for KE) const DLDag& getDag ( void ) const { return DLHeap; } /// set the value of a test timeout in milliseconds to VALUE void setTestTimeout ( unsigned long value ) { testTimeout = value; } /// (dis-)allow reasoner to use the undefined names in queries void setUseUndefinedNames ( bool value ) { Concepts.setAllowFresh(value); } /// set flag to use node cache to value VAL void setUseNodeCache ( bool val ) { useNodeCache = val; } //----------------------------------------------------------------------------- //-- public parser ensure* interface //----------------------------------------------------------------------------- /// return registered concept by given NAME; @return NULL if can't register TConcept* getConcept ( const std::string& name ) { return Concepts.get(name); } /// return registered individual by given NAME; @return NULL if can't register TIndividual* getIndividual ( const std::string& name ) { return Individuals.get(name); } /// @return true iff given NAME is a name of a registered individual bool isIndividual ( const std::string& name ) const { return Individuals.isRegistered(name); } /// @return true iff given ENTRY is a registered individual bool isIndividual ( const TNamedEntry* entry ) const { return isIndividual(entry->getName()); } /// @return true iff given TREE represents a registered individual bool isIndividual ( const DLTree* tree ) const { return (tree->Element().getToken() == INAME && isIndividual(tree->Element().getNE())); } /// @return true iff given DLTree represents a data value static bool isDataValue ( const DLTree* entry ) { return entry->Element().getToken() == DATAEXPR && static_cast(entry->Element().getNE())->isDataValue(); } /// get TOP/BOTTOM/CN/IN by the DLTree entry TConcept* getCI ( const DLTree* name ) { if ( name->Element() == TOP ) return pTop; if ( name->Element() == BOTTOM ) return pBottom; if ( !isName(name) ) return NULL; if ( name->Element().getToken() == CNAME ) return toConcept(name->Element().getNE()); else return toIndividual(name->Element().getNE()); } /// get a DL tree by a given concept-like C DLTree* getTree ( TConcept* C ) const { if ( C == NULL ) return NULL; if ( C == pTop ) return createTop(); if ( C == pBottom ) return createBottom(); return createEntry ( isIndividual(C) ? INAME : CNAME, C ); } /// get fresh concept DLTree* getFreshConcept ( void ) const { return createEntry ( CNAME, pTemp ); } // n-ary absorption support /// get unique aux concept TConcept* getAuxConcept ( DLTree* desc = NULL ); /// replace RC=(AR:~C) with X such that C [= AR^-:X for fresh X. @return X TConcept* replaceForall ( DLTree* RC ); //----------------------------------------------------------------------------- //-- public input axiom interface //----------------------------------------------------------------------------- /// register individual relation :R void RegisterIndividualRelation ( TNamedEntry* a, TNamedEntry* R, TNamedEntry* b ) { if ( !isIndividual(a) || !isIndividual(b) ) throw EFaCTPlusPlus("Individual expected in related()"); RelatedI.push_back ( new TRelated ( toIndividual(a), toIndividual(b), static_cast(R) ) ); RelatedI.push_back ( new TRelated ( toIndividual(b), toIndividual(a), static_cast(R)->inverse() ) ); } /// add general subsumption axiom C [= D void addSubsumeAxiom ( DLTree* C, DLTree* D ); /// add axiom CN [= D for concept CN void addSubsumeAxiom ( TConcept* C, DLTree* D ) { addSubsumeAxiom ( getTree(C), D ); } /// add an axiom CN [= D for defined CN (CN=E already in base) void addSubsumeForDefined ( TConcept* C, DLTree* D ); /// add an axiom C = D void addEqualityAxiom ( DLTree* left, DLTree* right ); /// add simple rule RULE to the TBox' rules inline void addSimpleRule ( TSimpleRule* Rule ) { initRuleFields ( Rule->Body, SimpleRules.size() ); SimpleRules.push_back(Rule); } /// add binary simple rule (C0,C1)=>H void addBSimpleRule ( TConcept* C0, TConcept* C1, DLTree* H ) { ConceptVector v; v.push_back(C0); v.push_back(C1); addSimpleRule ( new TSimpleRule ( v, H ) ); } // external-set methods for set-of-concept-expressions void processEquivalentC ( ea_iterator beg, ea_iterator end ); void processDisjointC ( ea_iterator beg, ea_iterator end ); void processEquivalentR ( ea_iterator beg, ea_iterator end ); void processDisjointR ( ea_iterator beg, ea_iterator end ); void processSame ( ea_iterator beg, ea_iterator end ); void processDifferent ( ea_iterator beg, ea_iterator end ); /// let TBox know that the whole ontology is loaded void finishLoading ( void ) { setForbidUndefinedNames(true); } /// @return true if KB contains fairness constraints bool hasFC ( void ) const { return !Fairness.empty(); } /// add concept expression C as a fairness constraint void setFairnessConstraint ( ea_iterator beg, ea_iterator end ) { for ( ; beg < end; ++beg ) if ( isName(*beg) ) { Fairness.push_back(getCI(*beg)); deleteTree(*beg); } else { // build a flag for a FC TConcept* fc = getAuxConcept(); Fairness.push_back(fc); // make an axiom: FC = C addEqualityAxiom ( getTree(fc), *beg ); } // in presence of fairness constraints use ancestor blocking if ( useAnywhereBlocking && hasFC() ) { useAnywhereBlocking = false; if ( LLM.isWritable(llAlways) ) LL << "\nFairness constraints: set useAnywhereBlocking = 0"; } } //----------------------------------------------------------------------------- //-- public access interface //----------------------------------------------------------------------------- /// GCI Axioms access BipolarPointer getTG ( void ) const { return T_G; } /// get simple rule by its INDEX const TSimpleRule* getSimpleRule ( unsigned int index ) const { return SimpleRules[index]; } /// check if the relevant part of KB contains inverse roles. bool isIRinQuery ( void ) const { if ( curFeature != NULL ) return curFeature->hasInverseRole(); else return KBFeatures.hasInverseRole(); } /// check if the relevant part of KB contains number restrictions. bool isNRinQuery ( void ) const { const LogicFeatures* p = curFeature ? curFeature : &KBFeatures; return p->hasFunctionalRestriction() || p->hasNumberRestriction() || p->hasQNumberRestriction(); } /// check if the relevant part of KB contains singletons bool testHasNominals ( void ) const { if ( curFeature != NULL ) return curFeature->hasSingletons(); else return KBFeatures.hasSingletons(); } /// check if the relevant part of KB contains top role bool testHasTopRole ( void ) const { if ( curFeature != NULL ) return curFeature->hasTopRole(); else return KBFeatures.hasTopRole(); } /// check if Sorted Reasoning is applicable bool canUseSortedReasoning ( void ) const { return useSortedReasoning && !GCIs.isGCI() && !GCIs.isReflexive(); } /// @return true iff individual C is known to be p-blocked by another one bool isBlockedInd ( TConcept* C ) const { return SameI.find(C) != SameI.end(); } /// get individual that blocks C; works only for blocked individuals C TIndividual* getBlockingInd ( TConcept* C ) const { return SameI.find(C)->second.first; } /// @return true iff an individual blocks C deterministically bool isBlockingDet ( TConcept* C ) const { return SameI.find(C)->second.second; } //----------------------------------------------------------------------------- //-- public iterators //----------------------------------------------------------------------------- /// RO begin() for concepts c_const_iterator c_begin ( void ) const { return Concepts.begin(); } /// RO end() for concepts c_const_iterator c_end ( void ) const { return Concepts.end(); } /// RO begin() for individuals i_const_iterator i_begin ( void ) const { return Individuals.begin(); } /// RO end() for individuals i_const_iterator i_end ( void ) const { return Individuals.end(); } //----------------------------------------------------------------------------- //-- public reasoning interface //----------------------------------------------------------------------------- /// prepare to reasoning void prepareReasoning ( void ); /// perform classification (assuming KB is consistent) void performClassification ( void ) { createTaxonomy ( /*needIndividuals=*/false ); } /// perform realisation (assuming KB is consistent) void performRealisation ( void ) { createTaxonomy ( /*needIndividuals=*/true ); } /// get (READ-WRITE) access to internal Taxonomy of concepts DLConceptTaxonomy* getTaxonomy ( void ) { return pTax; } /// get (READ-ONLY) access to internal Taxonomy of concepts const DLConceptTaxonomy* getTaxonomy ( void ) const { return pTax; } /// get RW access to the splits TSplitVars* getSplits ( void ) { return Splits; } /// set split vars void setSplitVars ( TSplitVars* s ) { Splits = s; } /// set given structure as a progress monitor void setProgressMonitor ( TProgressMonitor* pMon ) { pMonitor = pMon; } /// check that reasoning progress was cancelled by external application bool isCancelled ( void ) const { return pMonitor != NULL && pMonitor->isCancelled(); } /// set verbose output (ie, default progress monitor, concept and role taxonomies) wrt given VALUE void setVerboseOutput ( bool value ) { verboseOutput = value; } /// create (and DAG-ify) query concept via its definition TConcept* createQueryConcept ( const DLTree* query ); /// preprocess query concept: put description into DAG void preprocessQueryConcept ( TConcept* query ); /// classify query concept void classifyQueryConcept ( void ); /// delete all query-related stuff void clearQueryConcept ( void ) { DLHeap.removeQuery(); } //----------------------------------------------------------------------------- //-- public reasoning interface //----------------------------------------------------------------------------- /// get status flag KBStatus getStatus ( void ) const { return Status; } /// set consistency flag void setConsistency ( bool val ) { Status = kbCChecked; Consistent = val; } /// check if the ontology is consistent bool isConsistent ( void ) { if ( Status < kbCChecked ) { prepareReasoning(); if ( Status < kbCChecked && Consistent ) // we can detect inconsistency during preprocessing setConsistency(performConsistencyCheck()); } return Consistent; } /// check if a subsumption C [= D holds bool isSubHolds ( const TConcept* C, const TConcept* D ); /// check if a concept C is satisfiable bool isSatisfiable ( const TConcept* C ); /// check that 2 individuals are the same bool isSameIndividuals ( const TIndividual* a, const TIndividual* b ); /// check if 2 roles are disjoint bool isDisjointRoles ( const TRole* R, const TRole* S ); /// check if the role R is irreflexive bool isIrreflexive ( const TRole* R ); /// fills cache entry for given concept; SUB means that the concept is on the right side of a subsumption test const modelCacheInterface* initCache ( const TConcept* pConcept, bool sub = false ); /// build a completion tree for a concept C (no caching as it breaks the idea of KE). @return the root node const DlCompletionTree* buildCompletionTree ( const TConcept* C ); /// test if 2 concept non-subsumption can be determined by cache merging enum modelCacheState testCachedNonSubsumption ( const TConcept* p, const TConcept* q ); /// test if 2 concept non-subsumption can be determined by sorts checking bool testSortedNonSubsumption ( const TConcept* p, const TConcept* q ) { // sorted reasoning doesn't work in presence of GCIs if ( !canUseSortedReasoning() ) return false; // doesn't work for the SAT tests if ( q == NULL ) return false; return !DLHeap.haveSameSort ( p->pName, q->pName ); } //----------------------------------------------------------------------------- //-- public output interface //----------------------------------------------------------------------------- /// dump query processing TIME, reasoning statistics and a (preprocessed) TBox void writeReasoningResult ( std::ostream& o, float time ) const; /// print TBox as a whole void Print ( std::ostream& o ) const { DLHeap.PrintStat(o); ORM.Print ( o, "Object" ); DRM.Print ( o, "Data" ); PrintConcepts(o); PrintIndividuals(o); PrintSimpleRules(o); PrintAxioms(o); DLHeap.Print(o); } /// create dump of relevant part of query using given method void dump ( dumpInterface* dump ) const; //----------------------------------------------------------------------------- //-- save/load interface; implementation in SaveLoad.cpp //----------------------------------------------------------------------------- /// save the KB into the given stream void Save ( std::ostream& o ) const; /// load the KB from given stream wrt STATUS void Load ( std::istream& o, KBStatus status ); }; // TBox #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/DataReasoning.cpp0000644000000000000000000001110512112642405020575 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2005-2011 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "DataReasoning.h" //toms code start bool DataTypeReasoner :: addDataEntry ( BipolarPointer p, const DepSet& dep ) { switch ( DLHeap[p].Type() ) { case dtDataType: // get appropriate type { DataTypeAppearance* type = getDTAbyType(getDataEntry(p)); if ( LLM.isWritable(llCDAction) ) // level of logging LL << ' ' << (isPositive(p) ? '+' : '-') << getDataEntry(p)->getName(); type->setTypePresence ( isPositive(p), dep ); return type->checkPNTypeClash(); } case dtDataValue: return processDataValue ( isPositive(p), getDataEntry(p), dep ); case dtDataExpr: return processDataExpr ( isPositive(p), getDataEntry(p), dep ); case dtAnd: // processed by general reasoning return false; default: fpp_unreachable(); return true; } } // try to find contradiction: // -- if we have 2 same elements or direct contradiction (like "p" and "(not p)") // then addConcept() will eliminate this; // => negations are not interesting also (p & ~p are eliminated; ~p means "all except p"). // -- all cases with 2 different values of the same class are found in previous search; // -- The remaining problems are // - check if there are 2 different positive classes // - check if some value is present together with negation of its class // - check if some value is present together with the other class // - check if two values of different classes are present at the same time bool DataTypeReasoner :: checkClash ( void ) { DataTypeAppearance* type = NULL; // find a positive class for ( DTAVector::const_iterator p = Types.begin(), p_end = Types.end(); p < p_end; ++p ) if ( (*p)->hasPType() ) { if ( type == NULL ) type = *p; else // 2 different positive classes => contradiction { if ( LLM.isWritable(llCDAction) ) // level of logging LL << " DT-TT"; // inform about clash... clashDep = *(type->PType); clashDep += *((*p)->PType); return true; } } // no clash like (PType, NType) can happen as this will be checked earlier fpp_assert ( !type || !type->checkPNTypeClash() ); return false; } // ---------- Processing different alternatives bool DataTypeAppearance::DepInterval :: checkMinMaxClash ( DepSet& dep ) const { // we are interested in a NEG intervals iff a PType is set if ( !Constraints.closed() ) return false; const ComparableDT& Min = Constraints.min; const ComparableDT& Max = Constraints.max; // normal interval if ( Min < Max ) return false; // >?x and 5 and <5, >=5 and <5, >5 and <=5 leads to clash if ( Max < Min || Constraints.minExcl || Constraints.maxExcl ) { dep += locDep; return true; } return false; } bool DataTypeAppearance :: addPosInterval ( const TDataInterval& Int, const DepSet& dep ) { DTConstraint aux; if ( Int.hasMin() ) { Constraints.swap(aux); setLocal ( /*min=*/true, /*excl=*/Int.minExcl, Int.min, dep ); if ( addIntervals ( aux.begin(), aux.end() ) ) return true; aux.clear(); } if ( Int.hasMax() ) { Constraints.swap(aux); setLocal ( /*min=*/false, /*excl=*/Int.maxExcl, Int.max, dep ); if ( addIntervals ( aux.begin(), aux.end() ) ) return true; aux.clear(); } if ( Constraints.empty() ) return reportClash ( accDep, "C-MM" ); return false; } bool DataTypeAppearance :: addNegInterval ( const TDataInterval& Int, const DepSet& dep ) { // negative interval -- make a copies DTConstraint aux; Constraints.swap(aux); if ( Int.hasMin() ) { setLocal ( /*min=*/false, /*excl=*/!Int.minExcl, Int.min, dep ); if ( addIntervals ( aux.begin(), aux.end() ) ) return true; } if ( Int.hasMax() ) { setLocal ( /*min=*/ true, /*excl=*/!Int.maxExcl, Int.max, dep ); if ( addIntervals ( aux.begin(), aux.end() ) ) return true; } aux.clear(); if ( Constraints.empty() ) return reportClash ( accDep, "C-MM" ); return false; } FaCTpp-src-v1.6.2~dfsg/src/Kernel/dlCompletionGraph.cpp0000644000000000000000000001652312112642405021502 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2010 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "dlCompletionGraph.h" DlCompletionTreeArc* DlCompletionGraph :: createEdge ( DlCompletionTree* from, DlCompletionTree* to, bool isPredEdge, const TRole* roleName, const DepSet& dep ) { // create 2 arcs between FROM and TO DlCompletionTreeArc* forward = CTEdgeHeap.get(); forward->init ( roleName, dep, to ); forward->setSuccEdge(!isPredEdge); DlCompletionTreeArc* backward = CTEdgeHeap.get(); backward->init ( roleName->inverse(), dep, from ); backward->setSuccEdge(isPredEdge); // set the reverse link forward->setReverse(backward); // connect them to nodes saveNode ( from, branchingLevel ); saveNode ( to, branchingLevel ); // add the edges as corresponding neighbours from->addNeighbour(forward); to->addNeighbour(backward); if ( LLM.isWritable(llGTA) ) { LL << " ce("; if ( isPredEdge ) LL << to->getId() << "<-" << from->getId(); else LL << from->getId() << "->" << to->getId(); LL << "," << roleName->getName() << ")"; } return forward; } /// replace the EDGE (that comes from old node to X) with a new one, that comes from NODE to X DlCompletionTreeArc* DlCompletionGraph :: moveEdge ( DlCompletionTree* node, DlCompletionTreeArc* edge, bool isPredEdge, const DepSet& dep ) { // skip already purged edges if ( edge->isIBlocked()) return NULL; // skip edges not leading to nominal nodes if ( !isPredEdge && !edge->getArcEnd()->isNominalNode() ) return NULL; const TRole* R = edge->getRole(); // we shall copy reflexive edges in a specific way if ( edge->isReflexiveEdge() ) return createLoop ( node, R, dep ); DlCompletionTree* to = edge->getArcEnd(); // invalidate old edge invalidateEdge(edge); // try to find for NODE->TO (TO->NODE) whether we // have TO->NODE (NODE->TO) edge already for ( DlCompletionTree::const_edge_iterator p = node->begin(), p_end = node->end(); p < p_end; ++p ) if ( (*p)->getArcEnd() == to && (*p)->isPredEdge() != isPredEdge ) return addRoleLabel ( node, to, !isPredEdge, R, dep ); return addRoleLabel ( node, to, isPredEdge, R, dep ); } // merge labels; see SHOIN paper for detailed description void DlCompletionGraph :: Merge ( DlCompletionTree* from, DlCompletionTree* to, const DepSet& dep, std::vector& edges ) { edges.clear(); // 1. For all x: x->FROM make x->TO // FIXME!! no optimisations (in case there exists an edge TO->x labelled with R-) // 2. For all nominal x: FROM->x make TO->x // FIXME!! no optimisations (in case there exists an edge x->TO labelled with R-) for ( DlCompletionTree::const_edge_iterator p = from->begin(), p_end = from->end(); p < p_end; ++p ) { if ( (*p)->isPredEdge() || (*p)->getArcEnd()->isNominalNode() ) { DlCompletionTreeArc* temp = moveEdge ( to, *p, (*p)->isPredEdge(), dep ); if ( temp != NULL ) edges.push_back(temp); } if ( (*p)->isSuccEdge() ) purgeEdge ( *p, to, dep ); } // 4. For all x: FROM \neq x, add TO \neq x updateIR ( to, from, dep ); // 5. Purge FROM purgeNode ( from, to, dep ); } void DlCompletionGraph :: purgeNode ( DlCompletionTree* p, const DlCompletionTree* root, const DepSet& dep ) { if ( p->isPBlocked() ) return; saveRareCond ( p->setPBlocked ( root, dep ) ); // update successors for ( DlCompletionTree::const_edge_iterator q = p->begin(); q != p->end(); ++q ) if ( (*q)->isSuccEdge() && !(*q)->isIBlocked() ) purgeEdge ( *q, root, dep ); } /// purge edge E with given ROOT and DEP-set void DlCompletionGraph :: purgeEdge ( DlCompletionTreeArc* e, const DlCompletionTree* root, const DepSet& dep ) { invalidateEdge(e); // invalidate given link if ( e->getArcEnd()->isBlockableNode() ) purgeNode ( e->getArcEnd(), root, dep ); // purge blockable successor } // save/restore void DlCompletionGraph :: save ( void ) { SaveState* s = Stack.push(); s->nNodes = endUsed; s->sNodes = SavedNodes.size(); s->nEdges = CTEdgeHeap.size(); RareStack.incLevel(); ++branchingLevel; } void DlCompletionGraph :: restore ( unsigned int level ) { fpp_assert ( level > 0 ); branchingLevel = level; RareStack.restore(level); SaveState* s = Stack.pop(level); endUsed = s->nNodes; unsigned int nSaved = s->sNodes; iterator p = SavedNodes.begin()+nSaved, p_end = SavedNodes.end(); if ( endUsed < unsigned(p_end-p) ) // it's cheaper to restore all nodes for ( p = begin(), p_end = end(); p < p_end; ++p ) restoreNode ( (*p), level ); else for ( ; p < p_end; ++p ) if ( (*p)->getId() < endUsed ) // don't restore nodes that are dead anyway restoreNode ( (*p), level ); SavedNodes.resize(nSaved); CTEdgeHeap.resize(s->nEdges); } // printing CGraph void DlCompletionGraph :: Print ( std::ostream& o ) { // init indentation and node labels CGPIndent = 0; std::vector temp ( endUsed, false ); CGPFlag.swap(temp); const_iterator p = begin(), p_end = end(); unsigned int i = 1; // node id // mark all nominals as already printed: they full subtries will be output with a nominal cloud for ( ++p; p < p_end && (*p)->isNominalNode(); ++p, ++i ) CGPFlag[i] = true; // print tree starting from the root node p = begin(); PrintNode ( *p, o ); // if there are nominals in the graph -- print the nominal cloud for ( ++p; p < p_end && (*p)->isNominalNode(); ++p ) { // print given nominal node in full CGPFlag[(*p)->getId()] = false; PrintNode ( *p, o ); } o << "\n"; } void DlCompletionGraph :: PrintEdge ( DlCompletionTree::const_edge_iterator edge, const DlCompletionTree* parent, std::ostream& o ) { const DlCompletionTree* node = (*edge)->getArcEnd(); bool succEdge = (*edge)->isSuccEdge(); PrintIndent(o); for ( ; edge != parent->end(); ++edge ) if ( (*edge)->getArcEnd() == node && (*edge)->isSuccEdge() == succEdge ) o << " ", (*edge)->Print(o); // print edge's label if ( node == parent ) // print loop { PrintIndent(o); o << "-loop to node " << parent->getId(); } else PrintNode ( node, o ); } /// print node of the graph with proper indentation void DlCompletionGraph :: PrintNode ( const DlCompletionTree* node, std::ostream& o ) { if ( CGPIndent ) { PrintIndent(o); o << "-"; } else o << "\n"; node->PrintBody(o); // print node's label // don't print subtree twice if ( CGPFlag[node->getId()] ) { o << "d"; return; } CGPFlag[node->getId()] = true; // mark node printed // we want to print incoming edges for the nominal cloud bool wantPred = node->isNominalNode(); // print all children ++CGPIndent; for ( DlCompletionTree::const_edge_iterator p = node->begin(); p != node->end(); ++p ) if ( (*p)->isSuccEdge() || ( wantPred && (*p)->getArcEnd()->isNominalNode() ) ) PrintEdge ( p, node, o ); --CGPIndent; } FaCTpp-src-v1.6.2~dfsg/src/Kernel/eFaCTPlusPlus.h0000644000000000000000000000255112112642405020162 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2007-2013 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef EFACTPLUSPLUS_H #define EFACTPLUSPLUS_H #include /// general FaCT++ exception class EFaCTPlusPlus: public std::exception { protected: /// reason of the exception const char* reason; public: /// empty c'tor EFaCTPlusPlus ( void ) : exception() , reason("FaCT++.Kernel: General exception") {} /// init c'tor EFaCTPlusPlus ( const char* str ) : exception() , reason(str) {} /// empty d'tor virtual ~EFaCTPlusPlus ( void ) throw() {} /// reason virtual const char* what ( void ) const throw() { return reason; } }; // EFaCTPlusPlus #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/AtomicDecomposer.h0000644000000000000000000000772712112642405020777 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2011-2012 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef ATOMICDECOMPOSER_H #define ATOMICDECOMPOSER_H #include "tOntologyAtom.h" #include "tSignature.h" #include "Modularity.h" class ProgressIndicatorInterface; /// atomical ontology structure class AOStructure { public: // types /// vector of atoms as a type typedef std::vector AtomVec; /// RW iterator of it typedef AtomVec::iterator iterator; protected: // members /// all the atoms AtomVec Atoms; public: // interface /// empty c'tor AOStructure ( void ) {} /// d'tor: delete all atoms ~AOStructure ( void ) { for ( iterator p = Atoms.begin(), p_end = Atoms.end(); p != p_end; ++p ) delete *p; } /// create a new atom and get a pointer to it TOntologyAtom* newAtom ( void ) { TOntologyAtom* ret = new TOntologyAtom(); ret->setId(Atoms.size()); Atoms.push_back(ret); return ret; } /// reduce graph of the atoms in the structure void reduceGraph ( void ) { TOntologyAtom::AtomSet checked; for ( iterator p = Atoms.begin(), p_end = Atoms.end(); p != p_end; ++p ) (*p)->getAllDepAtoms(checked); } /// RW iterator begin iterator begin ( void ) { return Atoms.begin(); } /// RW iterator end iterator end ( void ) { return Atoms.end(); } /// get RW atom by its index TOntologyAtom* operator[] ( unsigned int index ) { return Atoms[index]; } /// get RO atom by its index const TOntologyAtom* operator[] ( unsigned int index ) const { return Atoms[index]; } /// size of the structure size_t size ( void ) const { return Atoms.size(); } }; // AOStructure /// atomical decomposer of the ontology class AtomicDecomposer { protected: // members /// atomic structure to build AOStructure* AOS; /// modularizer to build modules TModularizer* pModularizer; /// tautologies of the ontology AxiomVec Tautologies; /// progress indicator ProgressIndicatorInterface* PI; /// fake atom that represents the whole ontology TOntologyAtom* rootAtom; /// module type for current AOS creation ModuleType type; protected: // methods /// remove tautologies (axioms that are always local) from the ontology temporarily void removeTautologies ( TOntology* O ); /// restore all tautologies back void restoreTautologies ( void ) { for ( AxiomVec::iterator p = Tautologies.begin(), p_end = Tautologies.end(); p != p_end; ++p ) (*p)->setUsed(true); } /// build a module for given signature SIG; use parent atom's module as a base for the module search TOntologyAtom* buildModule ( const TSignature& sig, TOntologyAtom* parent ); /// create atom for given axiom AX; use parent atom's module as a base for the module search TOntologyAtom* createAtom ( TDLAxiom* ax, TOntologyAtom* parent ); public: // interface /// init c'tor; M would NOT be deleted in d'tor AtomicDecomposer ( TModularizer* m ) : AOS(NULL), pModularizer(m), PI(NULL), rootAtom(NULL) {} /// d'tor ~AtomicDecomposer ( void ); /// get the atomic structure for given module type TYPE AOStructure* getAOS ( TOntology* O, ModuleType type ); /// get already created atomic structure const AOStructure* getAOS ( void ) const { return AOS; } /// set progress indicator to be PI void setProgressIndicator ( ProgressIndicatorInterface* pi ) { PI = pi; } }; // AtomicDecomposer #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/ELFReasoner.h0000644000000000000000000005251712112642405017644 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2011-2012 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef ELFNREASONER_H #define ELFNREASONER_H #include #include #include "tOntology.h" // uncomment the following t use stack instead of a queue as a queue ;) //#define TMP_QUEUE_AS_STACK class ELFReasoner; // forward declaration to allow Rule specification class TELFConcept; /// pattern for the rule. Contains apply() method with updates of the monitored set class TELFRule { protected: // members /// reasoner that is used to add actions. The number of rules = the number of axioms, so the price is not too bad memory-wise. ELFReasoner& ER; public: // interface /// init c'tor TELFRule ( ELFReasoner& er ) : ER(er) {} /// empty d'tor virtual ~TELFRule ( void ) {} /// apply rule with fresh class C added to watching part virtual void apply ( TELFConcept* addedC ATTR_UNUSED ) {} /// apply rule with fresh pair (C,D) added to watching part virtual void apply ( TELFConcept* addedC ATTR_UNUSED, TELFConcept* addedD ATTR_UNUSED ) {} }; // TELFRule //------------------------------------------------------------- // Concepts and roles, i.e. S(C) and R(C,D) //------------------------------------------------------------- /// aux class to support set of rules and rule applications class TRuleSet { protected: // typedefs /// vector of rules typedef std::vector RVec; protected: // members /// set of rules to apply on change RVec Rules; protected: // methods /// apply all rules with a single argument void applyRules ( TELFConcept* addedC ) { for ( RVec::iterator p = Rules.begin(), p_end = Rules.end(); p != p_end; ++p ) (*p)->apply(addedC); } /// apply all rules with two arguments void applyRules ( TELFConcept* addedC, TELFConcept* addedD ) { for ( RVec::iterator p = Rules.begin(), p_end = Rules.end(); p != p_end; ++p ) (*p)->apply(addedC,addedD); } public: // interface /// empty c'tor TRuleSet ( void ) {} /// empty d'tor virtual ~TRuleSet ( void ) { for ( RVec::iterator p = Rules.begin(), p_end = Rules.end(); p != p_end; ++p ) delete *p; } /// add rule to a set void addRule ( TELFRule* rule ) { Rules.push_back(rule); } }; // TRuleSet /// concept, set S(C) and aux things class TELFConcept: public TRuleSet { public: // typedefs typedef std::set CVec; protected: // members /// original concept (if any) const TDLConceptExpression* Origin; /// set of supers (built during classification) CVec Supers; protected: // methods /// add C to supers void addSuper ( TELFConcept* C ) { Supers.insert(C); } public: // interface /// empty c'tor TELFConcept ( void ) : Origin(NULL) {} /// init c'tor TELFConcept ( const TDLConceptExpression* origin ) : Origin(origin) {} /// empty d'tor virtual ~TELFConcept ( void ) {} /// check whether concept C is contained in supers bool hasSuper ( TELFConcept* C ) const { return Supers.count(C) > 0; } /// add an super concept void addC ( TELFConcept* C ) { if ( hasSuper(C) ) return; addSuper(C); applyRules(C); } }; /// role, set R(C,D) class TELFRole: public TRuleSet { public: // types /// set of concepts typedef std::set CSet; /// map between concept and it's predecessors typedef std::map CCMap; /// iterator over a map typedef CCMap::iterator iterator; protected: // members /// original role (if any) const TDLObjectRoleExpression* Origin; /// map itself CCMap PredMap; protected: // methods /// add (C,D) to label void addLabel ( TELFConcept* C, TELFConcept* D ) { PredMap[D].insert(C); } public: // interface /// empty c'tor TELFRole ( void ) : Origin(NULL) {} /// init c'tor TELFRole ( const TDLObjectRoleExpression* origin ) : Origin(origin) {} /// empty d'tor virtual ~TELFRole ( void ) {} /// get the (possibly empty) set of predecessors of given D CSet& getPredSet ( const TELFConcept* D ) { return PredMap[D]; } /// iterator begon over a map iterator begin ( void ) { return PredMap.begin(); } /// iterator end over a map iterator end ( void ) { return PredMap.end(); } /// check whether (C,D) is in the R-set bool hasLabel ( TELFConcept* C, const TELFConcept* D ) { return PredMap[D].count(C) > 0; } /// add pair (C,D) to a set void addR ( TELFConcept* C, TELFConcept* D ) { if ( hasLabel(C,D) ) return; addLabel(C,D); applyRules(C,D); } }; // TELFRole //------------------------------------------------------------- // Action class //------------------------------------------------------------- /// single algorithm action (application of a rule) class ELFAction { protected: // members /// role R corresponded to R(C,D) TELFRole* R; /// concept C; to add TELFConcept* C; /// concept D; to add TELFConcept* D; public: // interface /// init c'tor for C action ELFAction ( TELFConcept* c, TELFConcept* d ) : R(NULL), C(c), D(d) {} /// init c'tor for R action ELFAction ( TELFRole* r, TELFConcept* c, TELFConcept* d ) : R(r), C(c), D(d) {} /// empty d'tor ~ELFAction ( void ) {} /// action itself, depending on the R state void apply ( void ) { if ( R != NULL ) R->addR(C,D); else C->addC(D); } }; // ELFAction //------------------------------------------------------------- // Reasoner class //------------------------------------------------------------- /// EL reasoner class ELFReasoner { protected: // typedefs /// S(C) structure typedef std::vector CVec; protected: // members /// typedef for map concept expression -> concept structure typedef std::map ConceptMap; /// set or all concepts ConceptMap CMap; /// TOP Concept TELFConcept* CTop; /// BOTTOM Concept TELFConcept* CBot; /// typedef for map role expression -> role structure typedef std::map RoleMap; /// map between roles and structures RoleMap RMap; /// queue of actions to perform #ifdef TMP_QUEUE_AS_STACK std::stack #else std::queue #endif queue; /// stat counters unsigned int nC2C, nA2C, nC2E, nE2C, nR2R, nC2R; protected: // methods /// get concept (expression) corresponding to a given DL expression TELFConcept* getC ( const TDLConceptExpression* p ) { ConceptMap::iterator i = CMap.find(p); if ( i != CMap.end() ) return i->second; // add new concept TELFConcept* ret = new TELFConcept(p); CMap[p] = ret; return ret; } /// get role (expression, but actually just a name) TELFRole* getR ( const TDLObjectRoleExpression* p ) { if ( RMap.find(p) != RMap.end() ) return RMap[p]; TELFRole* ret = new TELFRole(p); RMap[p] = ret; return ret; } // process different normalized axioms /// process axiom C [= D void processC2C ( TELFConcept* C, TELFConcept* D ); /// process axiom C1 and C2 [= D void processA2C ( TELFConcept* C1, TELFConcept* C2, TELFConcept* D ); /// process axiom C [= \ER.D void processC2E ( TELFConcept* C, TELFRole* R, TELFConcept* D ); /// process axiom \ER.C [= D void processE2C ( TELFRole* R, TELFConcept* C, TELFConcept* D ); /// process axiom R [= S void processR2R ( TELFRole* R, TELFRole* S ); /// process axiom R1 o R2 [= S void processC2R ( TELFRole* R1, TELFRole* R2, TELFRole* S ); // process original axioms /// process concept inclusion axiom into the internal structures void processCI ( const TDLAxiomConceptInclusion* axiom ); /// process role inclusion axiom into the internal structures void processRI ( const TDLAxiomORoleSubsumption* axiom ); /// process declaration axiom void processDeclaration ( const TDLAxiomDeclaration* axiom ); /// helper that inits \bot-related rules void initBotRules ( void ); public: /// c'tor: take the ontology and init internal structures ELFReasoner ( TOntology& ont ) : nC2C(0), nA2C(0), nC2E(0), nE2C(0), nR2R(0), nC2R(0) { // init top- and bottom entities CBot = getC(ont.getExpressionManager()->Bottom()); CTop = getC(ont.getExpressionManager()->Top()); for ( TOntology::iterator p = ont.begin(), p_end = ont.end(); p != p_end; ++p ) if ( (*p)->isUsed() ) { if ( likely(dynamic_cast(*p) != NULL) ) processCI(dynamic_cast(*p)); else if ( dynamic_cast(*p) != NULL ) processRI(dynamic_cast(*p)); else processDeclaration(dynamic_cast(*p)); } // now prepare rules for \bot with roles (if role filler is \bot, then so do domain) initBotRules(); // dump statistics std::cout << "\nFound " << nC2C << " axioms in the form C [= D\nFound " << nA2C << " axioms in the form C1/\\C2 [= D\nFound " << nC2E << " axioms in the form C [= ER.D\nFound " << nE2C << " axioms in the form ER.C [= D\nFound " << nR2R << " axioms in the form R [= S\nFound " << nC2R << " axioms in the form R o S [= T\n"; } /// empty d'tor ~ELFReasoner ( void ) {} /// add action to a queue void addAction ( ELFAction* action ) { queue.push(action); } /// classification method void classify ( void ) { // init all CIs for ( ConceptMap::iterator p = CMap.begin(), p_end = CMap.end(); p != p_end; ++p ) { TELFConcept* C = p->second; C->addC(CTop); C->addC(C); } // apply all rules int i = 0; while ( !queue.empty() ) { if ( i%100000 == 0 ) std::cerr << "\n" << i << " steps done; queue size is " << queue.size(); ++i; #ifdef TMP_QUEUE_AS_STACK queue.top()->apply(); delete queue.top(); #else queue.front()->apply(); delete queue.front(); #endif queue.pop(); } std::cerr << "\n" << i << " steps "; } }; // ELFReasoner //------------------------------------------------------------- // Rule for C [= D case; CR1 //------------------------------------------------------------- /// the rule for C [= D case class CSubRule: public TELFRule { protected: /// super of a concept; it would be added to S(C) TELFConcept* Sup; public: // interface /// init c'tor: remember D CSubRule ( ELFReasoner& ER, TELFConcept* D ) : TELFRule(ER), Sup(D) {} /// empty d'tor virtual ~CSubRule ( void ) {} /// apply a method with a given S(C) virtual void apply ( TELFConcept* addedC ) { if ( !addedC->hasSuper(Sup) ) ER.addAction ( new ELFAction ( addedC, Sup ) ); } }; // CSubRule //------------------------------------------------------------- // Rule for C1 and C2 [= D case; CR2 //------------------------------------------------------------- /// the rule for C1 and C2 [= D case class CAndSubRule: public TELFRule { protected: /// concept to find in order to fire a rule TELFConcept* Conj; /// super of a concept; it would be added to S(C) TELFConcept* Sup; public: // interface /// init c'tor: remember D CAndSubRule ( ELFReasoner& ER, TELFConcept* C, TELFConcept* D ) : TELFRule(ER), Conj(C), Sup(D) {} /// empty d'tor virtual ~CAndSubRule ( void ) {} /// apply a method with a given S(C) virtual void apply ( TELFConcept* C ) { if ( C->hasSuper(Conj) && !C->hasSuper(Sup) ) ER.addAction ( new ELFAction ( C, Sup ) ); } }; // CAndSubRule //------------------------------------------------------------- // Rule for C [= \Er.D case; CR3 //------------------------------------------------------------- /// the rule for C [= \ER.D case class RAddRule: public TELFRule { protected: /// role to add the pair TELFRole* R; /// filler (D) of the existential TELFConcept* Filler; public: // interface /// init c'tor: remember D RAddRule ( ELFReasoner& ER, TELFRole* r, TELFConcept* C ) : TELFRule(ER), R(r), Filler(C) {} /// empty d'tor virtual ~RAddRule ( void ) {} /// apply a method with a given source S(C) virtual void apply ( TELFConcept* Source ) { // if ( !R->hasLabel ( Source, Filler ) ) ER.addAction ( new ELFAction ( R, Source, Filler ) ); } }; // RAddRule //------------------------------------------------------------- // Rules for \Er.C [= D case; CR4 //------------------------------------------------------------- /// rule that checks an addition of C to S(Y) and checks whether there is X s.t. R(X,Y) class CAddFillerRule: public TELFRule { protected: /// role to add the pair TELFRole* R; /// super (E) of the existential TELFConcept* Sup; public: // interface /// init c'tor: remember E CAddFillerRule ( ELFReasoner& ER, TELFRole* r, TELFConcept* C ) : TELFRule(ER), R(r), Sup(C) {} /// empty d'tor virtual ~CAddFillerRule ( void ) {} /// apply a method with a given source S(C) virtual void apply ( TELFConcept* Source ) { TELFRole::CSet& SupSet = R->getPredSet(Source); if ( !SupSet.empty() ) for ( TELFRole::CSet::iterator p = SupSet.begin(), p_end = SupSet.end(); p != p_end; ++p ) if ( !(*p)->hasSuper(Sup) ) ER.addAction ( new ELFAction ( *p, Sup ) ); } }; // CAddFillerRule /// rule that checks the addition of (X,Y) to R and finds a C in S(Y) class CExistSubRule: public TELFRule { protected: /// filler of an existential TELFConcept* Filler; /// super of an axiom concept; it would be added to S(C) TELFConcept* Sup; public: // interface /// init c'tor: remember D CExistSubRule ( ELFReasoner& ER, TELFConcept* filler, TELFConcept* sup ) : TELFRule(ER), Filler(filler), Sup(sup) {} /// empty d'tor virtual ~CExistSubRule ( void ) {} /// apply a method with an added pair (C,D) virtual void apply ( TELFConcept* addedC, TELFConcept* addedD ) { if ( addedD->hasSuper(Filler) && !addedC->hasSuper(Sup) ) ER.addAction ( new ELFAction ( addedC, Sup ) ); } }; // CExistSubRule //------------------------------------------------------------- // Rule for R(C,D) with \bot\in S(D) case; CR5 //------------------------------------------------------------- // rule that checks whether for R(C,D) S(D) contains \bot class RBotRule: public TELFRule { protected: /// remember the Bottom concept TELFConcept* CBot; public: // interface /// init c'tor: remember E RBotRule ( ELFReasoner& ER, TELFConcept* bot ) : TELFRule(ER), CBot(bot) {} /// empty d'tor virtual ~RBotRule ( void ) {} /// apply a method with a given new pair (C,D) virtual void apply ( TELFConcept* addedC, TELFConcept* addedD ) { // it seems like every other pair is already processed, either via that rule or via add(\bot) if ( addedD->hasSuper(CBot) && !addedC->hasSuper(CBot)) ER.addAction ( new ELFAction ( addedC, CBot ) ); } }; // RBotRule //------------------------------------------------------------- // Rule for R [= S case; CR10 //------------------------------------------------------------- /// the rule for R [= S case class RSubRule: public TELFRule { protected: /// role to add the pair TELFRole* S; public: // interface /// init c'tor: remember S RSubRule ( ELFReasoner& ER, TELFRole* s ) : TELFRule(ER), S(s) {} /// empty d'tor virtual ~RSubRule ( void ) {} /// apply a method with a given pair (C,D) virtual void apply ( TELFConcept* addedC, TELFConcept* addedD ) { // if ( !S->hasLabel ( addedC, addedD ) ) ER.addAction ( new ELFAction ( S, addedC, addedD ) ); } }; // RSubRule //------------------------------------------------------------- // Rules for R o S [= T case; CR11 //------------------------------------------------------------- /// the rule for R in R o S [= T case class RChainLRule: public TELFRule { protected: /// role to check the chain TELFRole* S; /// role to add the pair TELFRole* T; public: // interface /// init c'tor: remember S and T RChainLRule ( ELFReasoner& ER, TELFRole* s, TELFRole* t ) : TELFRule(ER), S(s), T(t) {} /// empty d'tor virtual ~RChainLRule ( void ) {} /// apply a method with a given pair (C,D) virtual void apply ( TELFConcept* addedC, TELFConcept* addedD ) { // we have R(C,D); so for all E in range(S), if S(D,E) then add T(C,E) for ( TELFRole::iterator i = S->begin(), i_end = S->end(); i != i_end; ++i ) if ( i->second.count(addedD) > 0 ) { TELFConcept* E = const_cast(i->first); // if ( !T->hasLabel ( addedC, E ) ) ER.addAction ( new ELFAction ( T, addedC, E ) ); } } }; // RChainLRule /// the rule for S in R o S [= T case class RChainRRule: public TELFRule { protected: /// role to check the chain TELFRole* R; /// role to add the pair TELFRole* T; public: // interface /// init c'tor: remember R and T RChainRRule ( ELFReasoner& ER, TELFRole* r, TELFRole* t ) : TELFRule(ER), R(r), T(t) {} /// empty d'tor virtual ~RChainRRule ( void ) {} /// apply a method with a given pair (C,D) virtual void apply ( TELFConcept* addedC, TELFConcept* addedD ) { // we have S(C,D); so for all E in domain(R), if R(E,C) then add T(E,D) TELFRole::CSet& SupSet = R->getPredSet(addedC); if ( !SupSet.empty() ) for ( TELFRole::CSet::iterator p = SupSet.begin(), p_end = SupSet.end(); p != p_end; ++p ) // if ( !T->hasLabel ( *p, addedD ) ) ER.addAction ( new ELFAction ( T, *p, addedD ) ); } }; // RChainRRule //------------------------------------------------------------- // inline ELFReasoner implementation //------------------------------------------------------------- /// process axiom C [= D inline void ELFReasoner :: processC2C ( TELFConcept* C, TELFConcept* D ) { ++nC2C; C->addRule(new CSubRule(*this,D)); } /// process axiom C1 and C2 [= D inline void ELFReasoner :: processA2C ( TELFConcept* C1, TELFConcept* C2, TELFConcept* D ) { ++nA2C; C1->addRule(new CAndSubRule(*this,C2,D)); C2->addRule(new CAndSubRule(*this,C1,D)); } /// process axiom C [= \ER.D inline void ELFReasoner :: processC2E ( TELFConcept* C, TELFRole* R, TELFConcept* D ) { ++nC2E; C->addRule(new RAddRule(*this, R, D)); } /// process axiom \ER.C [= D inline void ELFReasoner :: processE2C ( TELFRole* R, TELFConcept* C, TELFConcept* D ) { ++nE2C; // C from existential will have a C-adder rule C->addRule(new CAddFillerRule(*this, R, D)); // R from the existential will have a C-adder here R->addRule(new CExistSubRule(*this, C, D)); } /// process axiom R [= S inline void ELFReasoner :: processR2R ( TELFRole* R, TELFRole* S ) { ++nR2R; R->addRule(new RSubRule(*this,S)); } /// process axiom R1 o R2 [= S inline void ELFReasoner :: processC2R ( TELFRole* R1, TELFRole* R2, TELFRole* S ) { ++nC2R; R1->addRule(new RChainLRule(*this, R2, S)); R2->addRule(new RChainRRule(*this, R1, S)); } /// process concept inclusion axiom into the internal structures inline void ELFReasoner :: processCI ( const TDLAxiomConceptInclusion* axiom ) { fpp_assert ( axiom != NULL ); // deal with existentials const TDLConceptObjectExists* Exists = dynamic_cast(axiom->getSupC()); if ( Exists != NULL ) // C [= \E R.D { processC2E ( getC(axiom->getSubC()), getR(Exists->getOR()), getC(Exists->getC()) ); return; } // now RHS is a concept name or \bottom; record it TELFConcept* D = getC(axiom->getSupC()); // try to check if LHS is existential Exists = dynamic_cast(axiom->getSubC()); if ( Exists != NULL ) // \E R.C [= D { processE2C ( getR(Exists->getOR()), getC(Exists->getC()), D ); return; } const TDLConceptAnd* And = dynamic_cast(axiom->getSubC()); if ( And != NULL ) // C1 \and C2 [= D { fpp_assert ( And->size() == 2 ); processA2C ( getC(*(And->begin())), getC(*(And->begin()+1)), D ); return; } // the only possible thing here is C [= D processC2C ( getC(axiom->getSubC()), D ); } /// process role inclusion axiom into the internal structures inline void ELFReasoner :: processRI ( const TDLAxiomORoleSubsumption* axiom ) { const TDLObjectRoleChain* Chain = dynamic_cast(axiom->getSubRole()); TELFRole* rhs = getR(axiom->getRole()); if ( Chain != NULL ) // R o S [= T { fpp_assert ( Chain->size() == 2 ); processC2R ( getR(*(Chain->begin())), getR(*(Chain->begin()+1)), rhs ); } else { const TDLObjectRoleExpression* R = dynamic_cast(axiom->getSubRole()); fpp_assert ( R != NULL ); processR2R ( getR(R), rhs ); } } /// process declaration axiom inline void ELFReasoner :: processDeclaration ( const TDLAxiomDeclaration* axiom ) { fpp_assert ( axiom != NULL ); const TDLConceptExpression* C = dynamic_cast(axiom->getDeclaration()); if ( C != NULL ) { getC(C); return; } const TDLObjectRoleExpression* R = dynamic_cast(axiom->getDeclaration()); if ( R != NULL ) { getR(R); return; } // nothing else could be here fpp_unreachable(); } /// helper that inits \bot-related rules inline void ELFReasoner :: initBotRules ( void ) { for ( RoleMap::iterator i = RMap.begin(), i_end = RMap.end(); i != i_end; ++i ) { // for every R add listener that checks whether for R(C,D) S(D) contains \bot i->second->addRule(new RBotRule(*this, CBot)); // add rule that adds \bot for every C in R(C,D), if S(D) contains \bot CBot->addRule(new CAddFillerRule(*this, i->second, CBot)); } } #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/dlVertex.cpp0000644000000000000000000001325712112642405017665 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2011 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "dlVertex.h" #include "dlDag.h" #include "tDataEntry.h" // adds a child to 'AND' vertex. // if finds a contrary pair of concepts -- returns TRUE and became dtBad; // else return false bool DLVertex :: addChild ( BipolarPointer p ) { // if adds to broken vertex -- do nothing; if ( Op == dtBad ) return true; // if adds TOP -- nothing to do if ( p == bpTOP ) return false; // if adding BOTTOM -- return clash (empty vertex) immediately // this can happen in case of nested simplifications; see bNested1 if ( p == bpBOTTOM ) { clash: // clash found: clear all stuff; returns true Child.resize(0); Op = dtBad; return true; } // find apropiate place to insert unsigned int v = getValue (p); BaseType::iterator q = Child.begin(), q_end = Child.end(); for ( ; q != q_end && getValue(*q) < v; ++q ) (void)NULL; if ( q == q_end ) // finish { Child.push_back(p); return false; } // we finds a place with |Child[i]| >= v if ( *q == p ) // concept already exists return false; else if ( *q == inverse(p) ) goto clash; // we need to insert p into set unsigned int offset = q - Child.begin(); Child.push_back(Child.back()); for ( q_end = Child.begin()+offset, q = Child.end()-1; q != q_end; --q ) *q=*(q-1); // copy the tail *q = p; // FIXME: add some simplification (about AR.C1, AR.c2 etc) return false; } // Sort given entry in the order defined by flags in a DAG. // the overall sorted entry structure looks like // fffA..M..Zlll if sortAscend set, and // fffZ..M..Alll if sortAscend cleared. // here 's' means "always first" entries, like neg-primconcepts, // and 'l' means "always last" entries, like looped concepts void DLVertex :: sortEntry ( const DLDag& dag ) { // safety check if ( Type() != dtAnd ) return; register BipolarPointer x; // value of moved element register int j; unsigned int size = Child.size(); for ( register unsigned int i = 1; i < size; ++i ) { x = Child[i]; // put x to the place s.t. SxL, where S <= x < L wrt dag.less() for ( j = i-1; j >= 0 && dag.less ( x, Child[j] ); --j ) Child[j+1] = Child[j]; // insert new element on it's place Child[j+1] = x; } } /* // sortirovka vstavkami s minimumom (na budushhee) template inline void insertSortGuarded(T a[], long size) { T x; long i, j; T backup = a[0]; // ????????? ?????? ?????? ??????? setMin(a[0]); // ???????? ?? ??????????? // ????????????? ?????? for ( i=1; i < size; i++) { x = a[i]; for ( j=i-1; a[j] > x; j--) a[j+1] = a[j]; a[j+1] = x; } // ???????? backup ?? ?????????? ????? for ( j=1; j(getConcept())->getFacet(); return; case dtDataValue: // named entry -- just like concept names case dtDataType: case dtPConcept: case dtNConcept: case dtPSingleton: case dtNSingleton: o << '(' << getConcept()->getName() << ") " << (isNNameTag(Type()) ? "=" : "[=") << ' ' << getC(); return; case dtLE: o << ' ' << getNumberLE() << ' ' << getRole()->getName() << ' ' << getC(); return; case dtForall: o << ' ' << getRole()->getName() << '{' << getState() << '}' << ' ' << getC(); return; case dtIrr: o << ' ' << getRole()->getName(); return; case dtProj: o << ' ' << getRole()->getName() << ", " << getC() << " => " << getProjRole()->getName(); return; case dtChoose: o << ' ' << getC(); return; default: std::cerr << "Error printing vertex of type " << getTagName() << "(" << Type() << ")"; fpp_unreachable(); } // print operands of the concept constructor for ( const_iterator q = begin(); q != end(); ++q ) o << ' ' << *q; } FaCTpp-src-v1.6.2~dfsg/src/Kernel/dumpInterface.cpp0000644000000000000000000001474512112642405020661 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2011 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "globaldef.h" #include "dumpInterface.h" #include "dlTBox.h" #include "RoleMaster.h" //------------------------------------------------------------------------------- // General dumping methods -- dumping relevant parts of ontology //------------------------------------------------------------------------------- void TBox :: dump ( dumpInterface* dump ) const { dump->prologue(); // dump all (relevant) roles dumpAllRoles(dump); // dump all (relevant) concepts for ( c_const_iterator pc = c_begin(); pc != c_end(); ++pc ) if ( isRelevant(*pc) ) dumpConcept( dump, *pc ); for ( i_const_iterator pi = i_begin(); pi != i_end(); ++pi ) if ( isRelevant(*pi) ) dumpConcept( dump, *pi ); // dump GCIs if ( getTG() != bpTOP ) { dump->startAx (diImpliesC); dump->dumpTop(); dump->contAx (diImpliesC); dumpExpression ( dump, getTG() ); dump->finishAx (diImpliesC); } dump->epilogue(); } void TBox :: dumpConcept ( dumpInterface* dump, const TConcept* p ) const { // dump defConcept dump->startAx (diDefineC); dump->dumpConcept(p); dump->finishAx (diDefineC); // dump "p [= def" if ( p->pBody != bpTOP ) { diAx Ax = p->isNonPrimitive() ? diEqualsC : diImpliesC; dump->startAx (Ax); dump->dumpConcept(p); dump->contAx (Ax); dumpExpression ( dump, p->pBody ); dump->finishAx (Ax); } } void TBox :: dumpRole ( dumpInterface* dump, const TRole* p ) const { // dump defRole and parents if ( p->getId() > 0 || !isRelevant(p->inverse()) ) { const TRole* q = ( p->getId()>0 ? p : p->inverse() ); dump->startAx (diDefineR); dump->dumpRole(q); dump->finishAx (diDefineR); // dump parents for ( ClassifiableEntry::const_iterator i = q->told_begin(); i != q->told_end(); ++i ) { dump->startAx (diImpliesR); dump->dumpRole(q); dump->contAx (diImpliesR); dump->dumpRole(static_cast(*i)); dump->finishAx (diImpliesR); } } // dump transitility if ( p->isTransitive() ) { dump->startAx (diTransitiveR); dump->dumpRole(p); dump->finishAx (diTransitiveR); } // dump functionality (for topmost-functional roles only) if ( p->isTopFunc() ) { dump->startAx (diFunctionalR); dump->dumpRole(p); dump->finishAx (diFunctionalR); } // dump "domain" if ( p->getBPDomain() != bpTOP ) { dump->startAx (diDomainR); dump->dumpRole(p); dump->contAx (diDomainR); dumpExpression ( dump, p->getBPDomain() ); dump->finishAx (diDomainR); } // dump "range" if ( p->getBPRange() != bpTOP ) { dump->startAx (diRangeR); dump->dumpRole(p); dump->contAx (diRangeR); dumpExpression ( dump, p->getBPRange() ); dump->finishAx (diRangeR); } } void TBox :: dumpExpression ( dumpInterface* dump, BipolarPointer p ) const { fpp_assert ( isValid(p) ); if ( p == bpTOP ) return dump->dumpTop(); if ( p == bpBOTTOM ) return dump->dumpBottom(); // checks inversion if ( isNegative(p) ) { dump->startOp (diNot); dumpExpression ( dump, inverse(p) ); return dump->finishOp (diNot); } const DLVertex& v = DLHeap [getValue(p)]; switch ( v.Type() ) { case dtTop: return dump->dumpTop(); case dtName: return dump->dumpConcept(static_cast(v.getConcept())); case dtAnd: dump->startOp (diAnd); for ( DLVertex::const_iterator q = v.begin(); q != v.end(); ++q ) { if ( q != v.begin() ) dump->contOp (diAnd); dumpExpression ( dump, *q ); } dump->finishOp (diAnd); return; case dtForall: dump->startOp (diForall); dump->dumpRole (v.getRole()); dump->contOp(diForall); dumpExpression ( dump, v.getC() ); dump->finishOp (diForall); return; case dtLE: dump->startOp ( diLE, v.getNumberLE() ); dump->dumpRole (v.getRole()); dump->contOp(diLE); dumpExpression ( dump, v.getC() ); dump->finishOp (diLE); return; default: std::cerr << "Error dumping vertex of type " << v.getTagName() << "(" << v.Type () << ")"; fpp_unreachable(); return; // invalid value } } void TBox :: dumpAllRoles ( dumpInterface* dump ) const { RoleMaster::const_iterator p; for ( p = ORM.begin(); p != ORM.end(); ++p ) if ( isRelevant(*p) ) { fpp_assert ( !(*p)->isSynonym() ); dumpRole ( dump, *p ); } for ( p = DRM.begin(); p != DRM.end(); ++p ) if ( isRelevant(*p) ) { fpp_assert ( !(*p)->isSynonym() ); dumpRole ( dump, *p ); } } // dump given concept expression void dumpCExpression ( dumpInterface* dump, const DLTree* C ) { if ( C == NULL ) return; Token t = C->Element().getToken(); diOp tag; switch (t) { case TOP: return dump->dumpTop(); case BOTTOM: return dump->dumpBottom(); case CNAME: case INAME: return dump->dumpConcept(static_cast(C->Element().getNE())); case NOT: dump->startOp(diNot); dumpCExpression ( dump, C->Left() ); return dump->finishOp(diNot); case AND: case OR: tag = t == AND ? diAnd : diOr; dump->startOp(tag); dumpCExpression ( dump, C->Left() ); dump->contOp(tag); dumpCExpression ( dump, C->Right() ); return dump->finishOp(tag); case EXISTS: case FORALL: case LE: case GE: tag = t == EXISTS ? diExists : t == FORALL ? diForall : t == GE ? diGE : diLE; if ( t == GE || t == LE ) dump->startOp ( tag, C->Element().getData() ); else dump->startOp(tag); dumpRExpression ( dump, C->Left() ); dump->contOp(tag); dumpCExpression ( dump, C->Right() ); return dump->finishOp(tag); default: fpp_unreachable(); } } // dump given role expression void dumpRExpression ( dumpInterface* dump, const DLTree* R ) { if ( R == NULL ) return; switch ( R->Element().getToken() ) { case RNAME: case DNAME: return dump->dumpRole(static_cast(R->Element().getNE())); case NOT: case INV: dump->startOp(diInv); dumpRExpression ( dump, R->Left() ); return dump->finishOp(diInv); default: fpp_unreachable(); } } FaCTpp-src-v1.6.2~dfsg/src/Kernel/tDataTypeManager.h0000644000000000000000000000565412112642405020731 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2010-2011 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef TDATATYPEMANAGER_H #define TDATATYPEMANAGER_H #include "tDLExpression.h" #include "tNameSet.h" /// keeps all the TDLDataTypeName datatypes together with the names class TDataTypeManager: public TNameSet { public: // interface /// empty c'tor TDataTypeManager ( void ) {} /// empty d'tor virtual ~TDataTypeManager ( void ) {} // names to build/compare datatypes /// get name of the default string datatype static const char* getStrTypeName ( void ) { return "http://www.w3.org/2001/XMLSchema#string"; } /// get name of the default integer datatype static const char* getIntTypeName ( void ) { return "http://www.w3.org/2001/XMLSchema#integer"; } /// get name of the default floating point datatype static const char* getRealTypeName ( void ) { return "http://www.w3.org/2001/XMLSchema#float"; } /// get name of the default boolean datatype static const char* getBoolTypeName ( void ) { return "http://www.w3.org/2001/XMLSchema#boolean"; } /// get name of the default date-time datatype static const char* getTimeTypeName ( void ) { return "http://www.w3.org/2001/XMLSchema#dateTimeAsLong"; } }; // TDataTypeManager // helpers for the users /// @return true iff TYPE is a default string data type inline bool isStrDataType ( const TDLDataTypeName* type ) { return std::string(type->getName()) == TDataTypeManager::getStrTypeName(); } /// @return true iff TYPE is a default integer data type inline bool isIntDataType ( const TDLDataTypeName* type ) { return std::string(type->getName()) == TDataTypeManager::getIntTypeName(); } /// @return true iff TYPE is a default floating point data type inline bool isRealDataType ( const TDLDataTypeName* type ) { return std::string(type->getName()) == TDataTypeManager::getRealTypeName(); } /// @return true iff TYPE is a default boolean data type inline bool isBoolDataType ( const TDLDataTypeName* type ) { return std::string(type->getName()) == TDataTypeManager::getBoolTypeName(); } /// @return true iff TYPE is a default date-time data type inline bool isTimeDataType ( const TDLDataTypeName* type ) { return std::string(type->getName()) == TDataTypeManager::getTimeTypeName(); } #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/tDag2Interface.h0000644000000000000000000000713212112642405020312 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2011-2012 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef TDAG2INTERFACE_H #define TDAG2INTERFACE_H #include "tDLExpression.h" #include "tExpressionManager.h" #include "dlDag.h" /// class to translate DAG entities into the TDL* expressions class TDag2Interface { protected: // members /// DAG to be translated const DLDag& Dag; /// expression manager TExpressionManager* Manager; /// vector of cached concept expressions std::vector TransC; /// vector of cached data expressions std::vector TransD; protected: // methods /// build concept expression by a vertex V const TDLConceptExpression* buildCExpr ( const DLVertex& v ); /// build data expression by a vertex V const TDLDataExpression* buildDExpr ( const DLVertex& v ); /// create concept name by named entry static const TDLConceptName* CName ( const TNamedEntry* p ) { return dynamic_cast(p->getEntity()); } /// create individual name by named entry static const TDLIndividualName* IName ( const TNamedEntry* p ) { return dynamic_cast(p->getEntity()); } /// create object role name by named entry static const TDLObjectRoleName* ORName ( const TNamedEntry* p ) { return dynamic_cast(p->getEntity()); } /// create data role name by named entry static const TDLDataRoleName* DRName ( const TNamedEntry* p ) { return dynamic_cast(p->getEntity()); } public: // interface /// init c'tor TDag2Interface ( const DLDag& dag, TExpressionManager* manager ) : Dag(dag) , Manager(manager) , TransC(dag.size(),NULL) , TransD(dag.size(),NULL) {} /// empty d'tor: every newly created thing will be destroyed by manager ~TDag2Interface ( void ) {} /// make sure that size of expression cache is the same as the size of a DAG void ensureDagSize ( void ) { size_t ds = Dag.size(), ts = TransC.size(); if ( likely(ds == ts) ) return; TransC.resize(ds); TransD.resize(ds); if ( unlikely(ds>ts) ) for ( ; ts != ds; ++ts ) { TransC[ts] = NULL; TransD[ts] = NULL; } } /// get concept expression corresponding index of vertex const TDLConceptExpression* getCExpr ( BipolarPointer p ) { if ( isNegative(p) ) return Manager->Not(getCExpr(inverse(p))); if ( TransC[p] == NULL ) TransC[p] = buildCExpr(Dag[p]); return TransC[p]; } /// get data expression corresponding index of vertex const TDLDataExpression* getDExpr ( BipolarPointer p ) { if ( isNegative(p) ) return Manager->DataNot(getDExpr(inverse(p))); if ( TransD[p] == NULL ) TransD[p] = buildDExpr(Dag[p]); return TransD[p]; } /// get expression corresponding index of vertex given the DATA flag const TDLExpression* getExpr ( BipolarPointer p, bool data ) { if ( data ) return getDExpr(p); else return getCExpr(p); } }; // TDag2Interface #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/taxNamEntry.h0000644000000000000000000001255512112642405020007 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2012 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef TAXNAMENTRY_H #define TAXNAMENTRY_H #include #include "fpp_assert.h" #include "tNamedEntry.h" #include "globaldef.h" class TaxonomyVertex; class ClassifiableEntry : public TNamedEntry { public: // type definitions /// type for the set of told subsumers typedef std::vector linkSet; /// told subsumers RW iterator typedef linkSet::iterator iterator; /// told subsumers RO iterator typedef linkSet::const_iterator const_iterator; protected: // members /// link to taxonomy entry for current entry TaxonomyVertex* taxVertex; /// links to 'told subsumers' (entryes that are direct super-entries for current) linkSet toldSubsumers; /// pointer to synonym (entry which contains whole information the same as current) ClassifiableEntry* pSynonym; /// index as a vertex in the SubsumptionMap/model cache unsigned int Index; private: // no copy /// no copy c'tor ClassifiableEntry ( const ClassifiableEntry& ); /// no assignment ClassifiableEntry& operator = ( const ClassifiableEntry& ); public: // interface /// C'tor ClassifiableEntry ( const std::string& name ) : TNamedEntry ( name ) , taxVertex (NULL) , pSynonym (NULL) , Index(0) {} /// D'tor virtual ~ClassifiableEntry ( void ) {} // taxonomy entry access /// is current entry classified bool isClassified ( void ) const { return ( taxVertex != NULL ); } /// set up given entry void setTaxVertex ( TaxonomyVertex* vertex ) { taxVertex = vertex; } /// get taxonomy vertex of the entry TaxonomyVertex* getTaxVertex ( void ) const { return taxVertex; } // completely defined interface /// register a Completely Defined flag FPP_ADD_FLAG(CompletelyDefined,0x2); /// register a non-classifiable flag FPP_ADD_FLAG(NonClassifiable,0x4); // told subsumers interface /// begin (RO) of told subsumers const_iterator told_begin ( void ) const { return toldSubsumers.begin(); } /// end (RO) of told subsumers const_iterator told_end ( void ) const { return toldSubsumers.end(); } /// begin (RW) of told subsumers iterator told_begin ( void ) { return toldSubsumers.begin(); } /// end (RW) of told subsumers iterator told_end ( void ) { return toldSubsumers.end(); } /// check whether entry ihas any TS bool hasToldSubsumers ( void ) const { return !toldSubsumers.empty(); } /// add told subsumer of entry (duplications possible) void addParent ( ClassifiableEntry* parent ) { toldSubsumers.push_back (parent); } /// add told subsumer if doesn't already recorded void addParentIfNew ( ClassifiableEntry* parent ); /// add all parents (with duplicates) from the range to current node template void addParents ( Iterator begin, Iterator end ) { for ( Iterator p = begin; p < end; ++p ) addParentIfNew(*p); } // index interface /// get the index value unsigned int index ( void ) const { return Index; } /// set the index value void setIndex ( unsigned int ind ) { Index = ind; } // synonym interface /// check if current entry is a synonym bool isSynonym ( void ) const { return (pSynonym != NULL); } /// get synonym of current entry ClassifiableEntry* getSynonym ( void ) const { return pSynonym; } /// make sure that synonym's representative is not a synonym itself void canonicaliseSynonym ( void ); /// add entry's synonym void setSynonym ( ClassifiableEntry* syn ) { fpp_assert ( pSynonym == NULL ); // do it only once pSynonym = syn; canonicaliseSynonym(); } /// if two synonyms are in 'told' list, merge them void removeSynonymsFromParents ( void ) { linkSet copy; copy.swap(toldSubsumers); addParents ( copy.begin(), copy.end() ); } }; // ClassifiableEntry /// general RW resolving synonym operator template inline T* resolveSynonym ( T* p ) { return !p ? NULL : p->isSynonym() ? resolveSynonym(static_cast(p->getSynonym())) : p; } /// general RW resolving synonym operator template inline const T* resolveSynonym ( const T* p ) { return !p ? NULL : p->isSynonym() ? resolveSynonym(static_cast(p->getSynonym())) : p; } /// make sure that synonym's representative is not a synonym itself inline void ClassifiableEntry :: canonicaliseSynonym ( void ) { fpp_assert(isSynonym()); pSynonym = resolveSynonym(pSynonym); } inline void ClassifiableEntry :: addParentIfNew ( ClassifiableEntry* parent ) { // resolve synonyms parent = resolveSynonym(parent); // node can not be its own parent if ( parent == this ) return; // check if such entry already exists for ( iterator p = told_begin(); p != told_end(); ++p ) if ( parent == *p ) return; addParent(parent); } #endif // TAXNAMENTRY_H FaCTpp-src-v1.6.2~dfsg/src/Kernel/dlDag.h0000644000000000000000000002465212112642405016551 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2012 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef DLDAG_H #define DLDAG_H #include #include // strlen #include "globaldef.h" // for statistic printed #include "fpp_assert.h" #include "dlVertex.h" #include "dlVHash.h" #include "ifOptions.h" #include "tRole.h" #include "ConceptWithDep.h" #include "tNECollection.h" class RoleMaster; class TConcept; /** DAG of DL Verteces used in FaCT++ reasoner */ class DLDag { public: // types typedef std::vector HeapType; typedef std::vector StatVector; /// typedef for the hash-table typedef dlVHashTable HashTable; protected: // members /// body of DAG HeapType Heap; /// all the AND nodes (needs to recompute) StatVector listAnds; /// hash-table for vertices (and, all, LE) fast search HashTable indexAnd, indexAll, indexLE; /// DAG size after the whole ontology is loaded size_t finalDagSize; /// cache efficiency -- statistic purposes unsigned int nCacheHits; #ifdef RKG_USE_SORTED_REASONING /// size of sort array unsigned int sortArraySize; #endif // tunable flags (set by readConfig) /// sort strings: option[0] for SAT/cache tests, option[1] for SUB/classify tests const char* orSortSat; const char* orSortSub; /// sort index (if necessary). Possible values are Size, Depth, Freq unsigned int iSort; /// whether or not sorting order is ascending bool sortAscend; /// prefer non-generating rules in OR orderings bool preferNonGen; /// flag whether cache should be used bool useDLVCache; private: // no copy /// no copy c'tor DLDag ( const DLDag& ); /// no assignment DLDag& operator= ( const DLDag& ); protected: // methods /// setup flags by given option set void readConfig ( const ifOptionSet* Options ); /// check if given string is correct sort ordering representation bool isCorrectOption ( const char* str ) { if ( str == NULL ) return false; unsigned int n = strlen(str); if ( n < 1 || n > 3 ) return false; char Method = str[0], Order = n >= 2 ? str[1] : 'a', NGPref = n == 3 ? str[2] : 'p'; return ( Method == 'S' || Method == 'D' || Method == 'F' || Method == 'B' || Method == 'G' || Method == '0' ) && ( Order == 'a' || Order == 'd' ) && ( NGPref == 'p' || NGPref == 'n' ); } /// gather vertex statistics (no freq) void computeVertexStat ( BipolarPointer p ); /// helper for the recursion void computeVertexStat ( BipolarPointer p, bool pos ) { computeVertexStat ( createBiPointer ( p, pos ) ); } /// update vertex statistics (no freq) wrt calculated values of children void updateVertexStat ( BipolarPointer p ); /// helper for the recursion void updateVertexStat ( DLVertex& v, BipolarPointer p, bool pos ) { const DLVertex& w = (*this)[p]; bool posW = pos == isPositive(p); // update in-cycle information if ( w.isInCycle(posW) ) v.setInCycle(pos); v.updateStatValues ( w, posW, pos ); } /// gather vertex freq statistics void computeVertexFreq ( BipolarPointer p ); /// helper for the recursion void computeVertexFreq ( BipolarPointer p, bool pos ) { computeVertexFreq ( createBiPointer ( p, pos ) ); } /// change order of ADD elements wrt statistic void Recompute ( void ) { for ( StatVector::const_iterator p = listAnds.begin(), p_end = listAnds.end(); p < p_end; ++p ) Heap[*p]->sortEntry(*this); } /// set OR sort flags based on given option string; Recompute if necessary void setOrderOptions ( const char* opt ); /// clear all DFS info from elements of DAG void clearDFS ( void ) { for ( unsigned int i = Heap.size()-1; i > 0; --i ) Heap[i]->clearDFS(); } /// get index corresponding to DLVertex's tag const HashTable& getIndex ( DagTag tag ) const { switch(tag) { case dtAnd: return indexAnd; case dtIrr: case dtForall: return indexAll; case dtLE: return indexLE; default: fpp_unreachable(); // no such index } } /// update index corresponding to DLVertex's tag void updateIndex ( DagTag tag, BipolarPointer value ) { switch(tag) { case dtAnd: indexAnd.addElement(value); listAnds.push_back(value); break; case dtIrr: case dtForall: indexAll.addElement(value); break; case dtLE: indexLE.addElement(value); break; default: break; // nothing to do } } #ifdef RKG_USE_SORTED_REASONING // internal sort interface /// merge sorts for a given role void mergeSorts ( TRole* R ); /// merge sorts for a given vertex void mergeSorts ( DLVertex& v ); #endif #ifdef RKG_PRINT_DAG_USAGE /// print usage of DAG void PrintDAGUsage ( std::ostream& o ) const; #endif public: // interface /// the only c'tor DLDag ( const ifOptionSet* Options ); /// d'tor ~DLDag ( void ); // construction methods /// get index of given vertex; include vertex to DAG if necessary BipolarPointer add ( DLVertex* v ); /// add vertex to the end of DAG and calculate it's statistic if necessary BipolarPointer directAdd ( DLVertex* v ) { Heap.push_back(v); // return an index of just added entry return Heap.size()-1; } /// add vertex to the end of DAG and calculate it's statistic if necessary; put it into cache BipolarPointer directAddAndCache ( DLVertex* v ) { BipolarPointer ret = directAdd(v); if ( useDLVCache ) updateIndex ( v->Type(), ret ); return ret; } /// check if given index points to the last DAG entry bool isLast ( BipolarPointer p ) const { return (getValue(p) == Heap.size()-1); } // access methods /// whether to use cache for nodes void setExpressionCache ( bool val ) { useDLVCache = val; } /// return true if p1 is less than p2 using chosen sort order bool less ( BipolarPointer p1, BipolarPointer p2 ) const; /// access by index (non-const version) DLVertex& operator [] ( BipolarPointer i ) { # ifdef ENABLE_CHECKING fpp_assert ( isValid(i) ); fpp_assert ( getValue(i) < size() ); # endif return *Heap[getValue(i)]; } /// RW access by index in complex concept DLVertex& operator [] ( const ConceptWDep& cwd ) { return (*this)[cwd.bp()]; } /// access by index (const version) const DLVertex& operator [] ( BipolarPointer i ) const { # ifdef ENABLE_CHECKING fpp_assert ( isValid(i) ); fpp_assert ( getValue(i) < size() ); # endif return *Heap[getValue(i)]; } /// RO access by index in complex concept const DLVertex& operator [] ( const ConceptWDep& cwd ) const { return (*this)[cwd.bp()]; } /// replace existing vertex at index I with a vertex V void replaceVertex ( BipolarPointer i, DLVertex* v, TNamedEntry* C ) { delete Heap[getValue(i)]; Heap[getValue(i)] = v; v->setConcept(C); } /// get size of DAG size_t size ( void ) const { return Heap.size (); } /// get approximation of the size after query is added size_t maxSize ( void ) const { return size() + ( size() < 220 ? 10 : size()/20 ); } /// set the final DAG size void setFinalSize ( void ) { finalDagSize = size(); setExpressionCache(false); } /// resize DAG to its original size (to clear intermediate query) void removeQuery ( void ); // option interface /// set defaults of OR orderings void setOrderDefaults ( const char* defSat, const char* defSub ); /// use SUB options to OR ordering void setSubOrder ( void ) { setOrderOptions(orSortSub); } /// use SAT options to OR ordering; void setSatOrder ( void ) { setOrderOptions(orSortSat); } /// gather statistics necessary for the OR ordering void gatherStatistic ( void ); // cache interface /// get cache for given BiPointer (may return NULL if no cache defined) const modelCacheInterface* getCache ( BipolarPointer p ) const { return operator[](p).getCache(isPositive(p)); } /// set cache for given BiPointer; @return given cache void setCache ( BipolarPointer p, modelCacheInterface* cache ) { operator[](p).setCache ( isPositive(p), cache ); } // sort interface #ifdef RKG_USE_SORTED_REASONING /// merge two given DAG entries void merge ( mergableLabel& ml, BipolarPointer p ) { if ( p != bpINVALID && p != bpTOP && p != bpBOTTOM ) (*this)[p].merge(ml); } /// build the sort system for given TBox void determineSorts ( RoleMaster& ORM, RoleMaster& DRM ); /// update sorts for :R construction void updateSorts ( BipolarPointer a, TRole* R, BipolarPointer b ) { merge ( R->getDomainLabel(), a ); merge ( R->getRangeLabel(), b ); } /// check if two BPs are of the same sort bool haveSameSort ( unsigned int p, unsigned int q ) { fpp_assert ( p > 0 && q > 0 ); // sanity check // everything has the same label as TOP if ( p == 1 || q == 1 ) return true; // if some concepts were added to DAG => nothing to say if ( p >= sortArraySize || q >= sortArraySize ) return true; // check whether two sorts are identical return (*this)[p].getSort() == (*this)[q].getSort(); } #else bool haveSameSort ( unsigned int p, unsigned int q ) { return true; } #endif // output interface /// print DAG size and number of cache hits, together with DAG usage void PrintStat ( std::ostream& o ) const { o << "Heap size = " << Heap.size () << " nodes\n" << "There were " << nCacheHits << " cache hits\n"; # ifdef RKG_PRINT_DAG_USAGE PrintDAGUsage(o); # endif } /// print the whole DAG void Print ( std::ostream& o ) const { o << "\nDag structure"; for ( unsigned int i = 1; i < size(); ++i ) { o << "\n" << i << " "; (*this)[i].Print(o); } o << std::endl; } // save/load interface; implementation is in SaveLoad.cpp /// save entry void Save ( std::ostream& o ) const; /// load entry void Load ( std::istream& i ); }; // DLDag #include "dlVHashImpl.h" inline BipolarPointer DLDag :: add ( DLVertex* v ) { BipolarPointer ret = useDLVCache ? getIndex(v->Type()).locate(*v) : bpINVALID; if ( !isValid(ret) ) // we fail to find such vertex -- it's new return directAddAndCache(v); // node was found in cache ++nCacheHits; delete v; return ret; } #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/Preprocess.cpp0000644000000000000000000003235412112642405020214 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2011 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "dlTBox.h" #include #include "procTimer.h" #include "logging.h" //#define DEBUG_PREPROCESSING #ifdef DEBUG_PREPROCESSING # define BEGIN_PASS(str) std::cerr << "\n" str "... " # define END_PASS() std::cerr << "done" #else # define BEGIN_PASS(str) # define END_PASS() #endif void TBox :: Preprocess ( void ) { if ( verboseOutput ) std::cerr << "\nPreprocessing..."; TsProcTimer pt; pt.Start(); // builds role hierarchy BEGIN_PASS("Build role hierarchy"); ORM.initAncDesc(); DRM.initAncDesc(); END_PASS(); if ( verboseOutput ) { std::ofstream oroles("Taxonomy.ORoles"); ORM.getTaxonomy()->print(oroles); std::ofstream droles("Taxonomy.DRoles"); DRM.getTaxonomy()->print(droles); } // all concept descriptions contains synonyms. Remove them now BEGIN_PASS("Replace synonyms in expressions"); if ( countSynonyms() > 0 ) replaceAllSynonyms(); END_PASS(); // preprocess Related structure (before classification tags are defined) BEGIN_PASS("Preprocess related axioms"); preprocessRelated(); END_PASS(); // init told subsumers as they would be used soon BEGIN_PASS("Init told subsumers"); initToldSubsumers(); END_PASS(); // locate told (definitional) cycles and transform them into synonyms BEGIN_PASS("Detect and replace told cycles"); transformToldCycles(); END_PASS(); // detect singleton with singleton parents and make them synonyms BEGIN_PASS("Detect and transform singleton hierarchy"); transformSingletonHierarchy(); END_PASS(); // absorb axioms (move some Axioms to Role and Concept Description) BEGIN_PASS("Perform absorption"); AbsorbAxioms(); END_PASS(); // set told TOP concepts whether necessary BEGIN_PASS("Set told TOP"); setToldTop(); END_PASS(); // no more axiom transformations allowed // create DAG (concept normalisation etc) BEGIN_PASS("Build DAG"); buildDAG(); END_PASS(); // now split expansion rules could be build BEGIN_PASS("Build Split rules"); buildSplitRules(); END_PASS(); // fills classification tag (strictly after told cycles) BEGIN_PASS("Detect classification tags"); fillsClassificationTag(); END_PASS(); // set up TS depth BEGIN_PASS("Calculate told subsumer depth"); calculateTSDepth(); END_PASS(); // set indexes for model caching BEGIN_PASS("Set all indexes"); setAllIndexes(); END_PASS(); // create sorts for KB BEGIN_PASS("Determine sorts"); determineSorts(); END_PASS(); // calculate statistic for the whole KB: BEGIN_PASS("Gather relevance info"); gatherRelevanceInfo(); END_PASS(); // here it is safe to print KB features (all are known; the last one was in Relevance) printFeatures(); // GALEN-like flag is known here, so we can set OR defaults BEGIN_PASS("Set defaults for OR orderings"); DLHeap.setOrderDefaults ( isGalenLikeTBox() ? "Fdn" : isWineLikeTBox() ? "Sdp" : "Sap", // SAT settings isGalenLikeTBox() ? "Ban" : isWineLikeTBox() ? "Fdn" : "Dap" // SUB settings ); END_PASS(); // now we can gather DAG statistics (if necessary) BEGIN_PASS("Gather usage statistics"); DLHeap.gatherStatistic(); END_PASS(); // calculate statistic on DAG and Roles BEGIN_PASS("Gather concept-related statistics"); CalculateStatistic(); END_PASS(); // free extra memory BEGIN_PASS("Free unused memory"); RemoveExtraDescriptions(); END_PASS(); pt.Stop(); preprocTime = pt; if ( verboseOutput ) std::cerr << " done in " << pt << " seconds\n"; } static bool replaceSynonymsFromTree ( DLTree* desc ) { if ( desc == NULL ) return false; if ( isName(desc) ) { TLexeme& cur = desc->Element(); // not const ClassifiableEntry* entry = static_cast(cur.getNE()); if ( entry->isSynonym() ) { entry = resolveSynonym(entry); // check for TOP/BOTTOM if ( entry->isTop() ) cur = TLexeme(TOP); else if ( entry->isBottom() ) cur = TLexeme(BOTTOM); else cur = TLexeme ( static_cast(entry)->isSingleton() ? INAME : CNAME, entry ); return true; } else return false; } else { bool ret = replaceSynonymsFromTree ( desc->Left() ); ret |= replaceSynonymsFromTree ( desc->Right() ); return ret; } } void TBox :: replaceAllSynonyms ( void ) { // replace synonyms in role's domain for ( RoleMaster::iterator r = ORM.begin(), r_end = ORM.end(); r < r_end; ++r ) if ( !(*r)->isSynonym() ) replaceSynonymsFromTree ( (*r)->getTDomain() ); for ( RoleMaster::iterator dr = DRM.begin(), dr_end = DRM.end(); dr < dr_end; ++dr ) if ( !(*dr)->isSynonym() ) replaceSynonymsFromTree ( (*dr)->getTDomain() ); for ( c_iterator pc = c_begin(); pc != c_end(); ++pc ) if ( replaceSynonymsFromTree ( (*pc)->Description ) ) (*pc)->initToldSubsumers(); for ( i_iterator pi = i_begin(); pi != i_end(); ++pi ) if ( replaceSynonymsFromTree ( (*pi)->Description ) ) (*pi)->initToldSubsumers(); } void TBox :: preprocessRelated ( void ) { for ( RelatedCollection::iterator q = RelatedI.begin(), q_end = RelatedI.end(); q != q_end; ++q ) (*q)->simplify(); } void TBox :: transformToldCycles ( void ) { // remember number of synonyms appeared in KB unsigned int nSynonyms = countSynonyms(); clearRelevanceInfo(); for ( c_iterator pc = c_begin(); pc != c_end(); ++pc ) if ( !(*pc)->isSynonym() ) checkToldCycle(*pc); for ( i_iterator pi = i_begin(); pi != i_end(); ++pi ) if ( !(*pi)->isSynonym() ) checkToldCycle(*pi); clearRelevanceInfo(); // update nymber of synonyms nSynonyms = countSynonyms() - nSynonyms; if ( nSynonyms ) { if ( LLM.isWritable(llAlways) ) LL << "\nTold cycle elimination done with " << nSynonyms << " synonyms created"; replaceAllSynonyms(); } } TConcept* TBox :: checkToldCycle ( TConcept* p ) { fpp_assert ( p != NULL ); // safety check // resolve synonym (if happens) to prevent cases like A[=B[=C[=A, A[=D[=B p = resolveSynonym(p); // no reason to process TOP here if ( p == pTop ) return NULL; // if we found a cycle... if ( CInProcess.find(p) != CInProcess.end() ) { // std::cout << "Cycle with " << p->getName() << std::endl; return p; } if ( isRelevant(p) ) { // std::cout << "Already checked: " << p->getName() << std::endl; return NULL; } TConcept* ret = NULL; // add concept in processing CInProcess.insert(p); redo: // std::cout << "Start from " << p->getName() << std::endl; for ( ClassifiableEntry::const_iterator r = p->told_begin(); r != p->told_end(); ++r ) // if cycle was detected if ( (ret = checkToldCycle(static_cast(*r))) != NULL ) { if ( ret == p ) { // std::cout << "Fill cycle with " << p->getName() << std::endl; ToldSynonyms.push_back(p); std::vector::iterator q, q_end = ToldSynonyms.end(); // find a representative for the cycle; nominal is preferable for ( q = ToldSynonyms.begin(); q < q_end; ++q ) if ( (*q)->isSingleton() ) p = *q; // now p is a representative for all the synonyms // fill the description DLTree* desc = NULL; for ( q = ToldSynonyms.begin(); q < q_end; ++q ) if ( *q != p ) // make it a synonym of RET, save old desc desc = createSNFAnd ( desc, makeNonPrimitive ( *q, getTree(p) ) ); ToldSynonyms.clear(); // mark the returned concept primitive (to allow addDesc to work) p->setPrimitive(); p->addDesc(desc); // replace all synonyms with TOP p->removeSelfFromDescription(); // re-run the search starting from new sample if ( ret != p ) // need to fix the stack { CInProcess.erase(ret); CInProcess.insert(p); ret->setRelevant(relevance); p->dropRelevant(relevance); } ret = NULL; goto redo; } else { ToldSynonyms.push_back(p); // no need to continue; finish with this cycle first break; } } // remove processed concept from set CInProcess.erase(p); p->setRelevant(relevance); // std::cout << "Done with " << p->getName() << std::endl; return ret; } /// transform i [= C [= j into i=C=j for i,j nominals void TBox :: transformSingletonHierarchy ( void ) { // remember number of synonyms appeared in KB unsigned int nSynonyms = countSynonyms(); // cycle until no new synonyms are created bool changed; do { changed = false; for ( i_iterator pi = i_begin(); pi != i_end(); ++pi ) if ( !(*pi)->isSynonym() && (*pi)->isHasSP() ) { TIndividual* i = transformSingletonWithSP(*pi); i->removeSelfFromDescription(); changed = true; } } while ( changed ); // update nymber of synonyms nSynonyms = countSynonyms() - nSynonyms; if ( nSynonyms ) replaceAllSynonyms(); } /// helper to the transformSingletonWithSP() function TIndividual* TBox :: getSPForConcept ( TConcept* p ) { for ( ClassifiableEntry::const_iterator r = p->told_begin(); r != p->told_end(); ++r ) { TConcept* i = static_cast(*r); if ( i->isSingleton() ) // found the end of the chain return static_cast(i); if ( i->isHasSP() ) // found the continuation of the chain return transformSingletonWithSP(i); } // will always found the entry fpp_unreachable(); } /// make P and all its non-singleton parents synonyms to its singleton parent TIndividual* TBox :: transformSingletonWithSP ( TConcept* p ) { TIndividual* i = getSPForConcept(p); // make p a synonym of i if ( p->isSingleton() ) i->addRelated(static_cast(p)); addSubsumeAxiom ( i, makeNonPrimitive ( p, getTree(i) ) ); return i; } void TBox :: setAllIndexes ( void ) { ++nC; // place for the query concept nR = 1; // start with 1 to make index 0 an indicator of "not processed" RoleMaster::iterator r, r_end; for ( r = ORM.begin(), r_end = ORM.end(); r < r_end; ++r ) if ( !(*r)->isSynonym() ) (*r)->setIndex(nR++); for ( r = DRM.begin(), r_end = DRM.end(); r < r_end; ++r ) if ( !(*r)->isSynonym() ) (*r)->setIndex(nR++); } /// determine all sorts in KB (make job only for SORTED_REASONING) void TBox :: determineSorts ( void ) { #ifdef RKG_USE_SORTED_REASONING // Related individuals does not appears in DLHeap, // so their sorts shall be determined explicitely for ( RelatedCollection::const_iterator p = RelatedI.begin(), p_end = RelatedI.end(); p < p_end; ++p, ++p ) DLHeap.updateSorts ( (*p)->a->pName, (*p)->R, (*p)->b->pName ); // simple rules needs the same treatement for ( TSimpleRules::iterator q = SimpleRules.begin(); q < SimpleRules.end(); ++q ) { mergableLabel& lab = DLHeap[(*q)->bpHead].getSort(); for ( ConceptVector::const_iterator r = (*q)->Body.begin(), r_end = (*q)->Body.end(); r < r_end; ++r ) DLHeap.merge ( lab, (*r)->pName ); } // create sorts for concept and/or roles DLHeap.determineSorts ( ORM, DRM ); #endif // RKG_USE_SORTED_REASONING } // Told staff used, so run this AFTER fillTold*() void TBox :: CalculateStatistic ( void ) { unsigned int npFull = 0, nsFull = 0; // number of completely defined concepts unsigned int nPC = 0, nNC = 0, nSing = 0; // number of primitive, non-prim and singleton concepts unsigned int nNoTold = 0; // number of concepts w/o told subsumers // calculate statistic for all concepts for ( c_const_iterator pc = c_begin(); pc != c_end(); ++pc ) { const TConcept* n = *pc; // check if concept is not relevant if ( !isValid(n->pName) ) continue; if ( n->isPrimitive() ) ++nPC; else if ( n->isNonPrimitive() ) ++nNC; if ( n->isSynonym () ) ++nsFull; if ( n->isCompletelyDefined() ) { if ( n->isPrimitive() ) ++npFull; } else if ( !n->hasToldSubsumers() ) ++nNoTold; } // calculate statistic for all individuals for ( i_const_iterator pi = i_begin(); pi != i_end(); ++pi ) { const TConcept* n = *pi; // check if concept is not relevant if ( !isValid(n->pName) ) continue; ++nSing; if ( n->isPrimitive() ) ++nPC; else if ( n->isNonPrimitive() ) ++nNC; if ( n->isSynonym () ) ++nsFull; if ( n->isCompletelyDefined() ) { if ( n->isPrimitive() ) ++npFull; } else if ( !n->hasToldSubsumers() ) ++nNoTold; } // FIXME!! check if we can skip all statistic if no logging needed CHECK_LL_RETURN(llAlways); LL << "There are " << nPC << " primitive concepts used\n"; LL << " of which " << npFull << " completely defined\n"; LL << " and " << nNoTold << " has no told subsumers\n"; LL << "There are " << nNC << " non-primitive concepts used\n"; LL << " of which " << nsFull << " synonyms\n"; LL << "There are " << nSing << " individuals or nominals used\n"; } void TBox::RemoveExtraDescriptions ( void ) { // remove DLTree* from all named concepts for ( c_iterator pc = c_begin(); pc != c_end(); ++pc ) (*pc)->removeDescription (); for ( i_iterator pi = i_begin(); pi != i_end(); ++pi ) (*pi)->removeDescription (); } FaCTpp-src-v1.6.2~dfsg/src/Kernel/SyntacticLocalityChecker.h0000644000000000000000000005731012112642405022462 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2011-2013 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef SYNLOCCHECKER_H #define SYNLOCCHECKER_H #include "LocalityChecker.h" // forward declarations class BotEquivalenceEvaluator; class TopEquivalenceEvaluator; /// check whether class expressions are equivalent to bottom wrt given locality class class BotEquivalenceEvaluator: protected SigAccessor, public DLExpressionVisitorEmpty { protected: // members /// corresponding top evaluator TopEquivalenceEvaluator* TopEval; /// keep the value here bool isBotEq; protected: // methods /// check whether the expression is top-equivalent bool isTopEquivalent ( const TDLExpression& expr ); /// convenience helper bool isTopEquivalent ( const TDLExpression* expr ) { return isTopEquivalent(*expr); } // non-empty Concept/Data expression /// @return true iff C^I is non-empty bool isBotDistinct ( const TDLExpression* C ) { // TOP is non-empty if ( isTopEquivalent(C) ) return true; // built-in DT are non-empty if ( dynamic_cast(C) ) return true; // FIXME!! that's it for now return false; } // cardinality of a concept/data expression interpretation /// @return true if #C^I > n bool isCardLargerThan ( const TDLExpression* C, unsigned int n ) { if ( n == 0 ) // non-empty is enough return isBotDistinct(C); if ( const TDLDataTypeName* namedDT = dynamic_cast(C) ) { // string/time are infinite DT std::string name = namedDT->getName(); if ( name == TDataTypeManager::getStrTypeName() || name == TDataTypeManager::getTimeTypeName() ) return true; } // FIXME!! try to be more precise return false; } // QCRs /// @return true iff (>= n R.C) is botEq bool isMinBotEquivalent ( unsigned int n, const TDLRoleExpression* R, const TDLExpression* C ) { return (n > 0) && (isBotEquivalent(R) || isBotEquivalent(C)); } /// @return true iff (<= n R.C) is botEq bool isMaxBotEquivalent ( unsigned int n, const TDLRoleExpression* R, const TDLExpression* C ) { return isTopEquivalent(R) && isCardLargerThan ( C, n ); } public: // interface /// init c'tor BotEquivalenceEvaluator ( const TSignature* s ) : SigAccessor(s), isBotEq(false) {} /// empty d'tor virtual ~BotEquivalenceEvaluator ( void ) {} // set fields /// set the corresponding top evaluator void setTopEval ( TopEquivalenceEvaluator* eval ) { TopEval = eval; } /// @return true iff an EXPRession is equivalent to bottom wrt defined policy bool isBotEquivalent ( const TDLExpression& expr ) { expr.accept(*this); return isBotEq; } /// @return true iff an EXPRession is equivalent to bottom wrt defined policy bool isBotEquivalent ( const TDLExpression* expr ) { return isBotEquivalent(*expr); } public: // visitor interface // concept expressions virtual void visit ( const TDLConceptTop& ) { isBotEq = false; } virtual void visit ( const TDLConceptBottom& ) { isBotEq = true; } virtual void visit ( const TDLConceptName& expr ) { isBotEq = !topCLocal() && nc(expr.getEntity()); } virtual void visit ( const TDLConceptNot& expr ) { isBotEq = isTopEquivalent(expr.getC()); } virtual void visit ( const TDLConceptAnd& expr ) { for ( TDLConceptAnd::iterator p = expr.begin(), p_end = expr.end(); p != p_end; ++p ) if ( isBotEquivalent(*p) ) // here isBotEq is true, so just return return; isBotEq = false; } virtual void visit ( const TDLConceptOr& expr ) { for ( TDLConceptOr::iterator p = expr.begin(), p_end = expr.end(); p != p_end; ++p ) if ( !isBotEquivalent(*p) ) // here isBotEq is false, so just return return; isBotEq = true; } virtual void visit ( const TDLConceptOneOf& expr ) { isBotEq = expr.empty(); } virtual void visit ( const TDLConceptObjectSelf& expr ) { isBotEq = isBotEquivalent(expr.getOR()); } virtual void visit ( const TDLConceptObjectValue& expr ) { isBotEq = isBotEquivalent(expr.getOR()); } virtual void visit ( const TDLConceptObjectExists& expr ) { isBotEq = isMinBotEquivalent ( 1, expr.getOR(), expr.getC() ); } virtual void visit ( const TDLConceptObjectForall& expr ) { isBotEq = isTopEquivalent(expr.getOR()) && isBotEquivalent(expr.getC()); } virtual void visit ( const TDLConceptObjectMinCardinality& expr ) { isBotEq = isMinBotEquivalent ( expr.getNumber(), expr.getOR(), expr.getC() ); } virtual void visit ( const TDLConceptObjectMaxCardinality& expr ) { isBotEq = isMaxBotEquivalent ( expr.getNumber(), expr.getOR(), expr.getC() ); } virtual void visit ( const TDLConceptObjectExactCardinality& expr ) { unsigned int n = expr.getNumber(); const TDLObjectRoleExpression* R = expr.getOR(); const TDLConceptExpression* C = expr.getC(); isBotEq = isMinBotEquivalent ( n, R, C ) || isMaxBotEquivalent ( n, R, C ); } virtual void visit ( const TDLConceptDataValue& expr ) { isBotEq = isBotEquivalent(expr.getDR()); } virtual void visit ( const TDLConceptDataExists& expr ) { isBotEq = isMinBotEquivalent ( 1, expr.getDR(), expr.getExpr() ); } virtual void visit ( const TDLConceptDataForall& expr ) { isBotEq = isTopEquivalent(expr.getDR()) && !isTopEquivalent(expr.getExpr()); } virtual void visit ( const TDLConceptDataMinCardinality& expr ) { isBotEq = isMinBotEquivalent ( expr.getNumber(), expr.getDR(), expr.getExpr() ); } virtual void visit ( const TDLConceptDataMaxCardinality& expr ) { isBotEq = isMaxBotEquivalent ( expr.getNumber(), expr.getDR(), expr.getExpr() ); } virtual void visit ( const TDLConceptDataExactCardinality& expr ) { unsigned int n = expr.getNumber(); const TDLDataRoleExpression* R = expr.getDR(); const TDLDataExpression* D = expr.getExpr(); isBotEq = isMinBotEquivalent ( n, R, D ) || isMaxBotEquivalent ( n, R, D ); } // object role expressions virtual void visit ( const TDLObjectRoleTop& ) { isBotEq = false; } virtual void visit ( const TDLObjectRoleBottom& ) { isBotEq = true; } virtual void visit ( const TDLObjectRoleName& expr ) { isBotEq = !topRLocal() && nc(expr.getEntity()); } virtual void visit ( const TDLObjectRoleInverse& expr ) { isBotEq = isBotEquivalent(expr.getOR()); } virtual void visit ( const TDLObjectRoleChain& expr ) { isBotEq = true; for ( TDLObjectRoleChain::iterator p = expr.begin(), p_end = expr.end(); p != p_end; ++p ) if ( isBotEquivalent(*p) ) // isBotEq is true here return; isBotEq = false; } // equivalent to R(x,y) and C(x), so copy behaviour from ER.X virtual void visit ( const TDLObjectRoleProjectionFrom& expr ) { isBotEq = isMinBotEquivalent ( 1, expr.getOR(), expr.getC() ); } // equivalent to R(x,y) and C(y), so copy behaviour from ER.X virtual void visit ( const TDLObjectRoleProjectionInto& expr ) { isBotEq = isMinBotEquivalent ( 1, expr.getOR(), expr.getC() ); } // data role expressions virtual void visit ( const TDLDataRoleTop& ) { isBotEq = false; } virtual void visit ( const TDLDataRoleBottom& ) { isBotEq = true; } virtual void visit ( const TDLDataRoleName& expr ) { isBotEq = !topRLocal() && nc(expr.getEntity()); } // data expressions virtual void visit ( const TDLDataTop& ) { isBotEq = false; } virtual void visit ( const TDLDataBottom& ) { isBotEq = true; } virtual void visit ( const TDLDataTypeName& ) { isBotEq = false; } virtual void visit ( const TDLDataTypeRestriction& ) { isBotEq = false; } virtual void visit ( const TDLDataValue& ) { isBotEq = false; } virtual void visit ( const TDLDataNot& expr ) { isBotEq = isTopEquivalent(expr.getExpr()); } virtual void visit ( const TDLDataAnd& expr ) { for ( TDLDataAnd::iterator p = expr.begin(), p_end = expr.end(); p != p_end; ++p ) if ( isBotEquivalent(*p) ) // here isBotEq is true, so just return return; isBotEq = false; } virtual void visit ( const TDLDataOr& expr ) { for ( TDLDataOr::iterator p = expr.begin(), p_end = expr.end(); p != p_end; ++p ) if ( !isBotEquivalent(*p) ) // here isBotEq is false, so just return return; isBotEq = true; } virtual void visit ( const TDLDataOneOf& expr ) { isBotEq = expr.empty(); } }; // BotEquivalenceEvaluator /// check whether class expressions are equivalent to top wrt given locality class class TopEquivalenceEvaluator: protected SigAccessor, public DLExpressionVisitorEmpty { protected: // members /// corresponding bottom evaluator BotEquivalenceEvaluator* BotEval; /// keep the value here bool isTopEq; protected: // methods /// check whether the expression is top-equivalent bool isBotEquivalent ( const TDLExpression& expr ) { return BotEval->isBotEquivalent(expr); } /// convenience helper bool isBotEquivalent ( const TDLExpression* expr ) { return isBotEquivalent(*expr); } // non-empty Concept/Data expression /// @return true iff C^I is non-empty bool isBotDistinct ( const TDLExpression* C ) { // TOP is non-empty if ( isTopEquivalent(C) ) return true; // built-in DT are non-empty if ( dynamic_cast(C) ) return true; // FIXME!! that's it for now return false; } // cardinality of a concept/data expression interpretation /// @return true if #C^I > n bool isCardLargerThan ( const TDLExpression* C, unsigned int n ) { if ( n == 0 ) // non-empty is enough return isBotDistinct(C); if ( dynamic_cast(C) && isTopEquivalent(C) ) return true; if ( const TDLDataTypeName* namedDT = dynamic_cast(C) ) { // string/time are infinite DT std::string name = namedDT->getName(); if ( name == TDataTypeManager::getStrTypeName() || name == TDataTypeManager::getTimeTypeName() ) return true; } // FIXME!! try to be more precise return false; } // QCRs /// @return true iff (>= n R.C) is topEq bool isMinTopEquivalent ( unsigned int n, const TDLRoleExpression* R, const TDLExpression* C ) { return (n == 0) || ( isTopEquivalent(R) && isCardLargerThan ( C, n-1 ) ); } /// @return true iff (<= n R.C) is topEq bool isMaxTopEquivalent ( unsigned int n ATTR_UNUSED, const TDLRoleExpression* R, const TDLExpression* C ) { return isBotEquivalent(R) || isBotEquivalent(C); } public: // interface /// init c'tor TopEquivalenceEvaluator ( const TSignature* s ) : SigAccessor(s), isTopEq(false) {} /// empty d'tor virtual ~TopEquivalenceEvaluator ( void ) {} // set fields /// set the corresponding bottom evaluator void setBotEval ( BotEquivalenceEvaluator* eval ) { BotEval = eval; } /// @return true iff an EXPRession is equivalent to top wrt defined policy bool isTopEquivalent ( const TDLExpression& expr ) { expr.accept(*this); return isTopEq; } /// @return true iff an EXPRession is equivalent to top wrt defined policy bool isTopEquivalent ( const TDLExpression* expr ) { return isTopEquivalent(*expr); } public: // visitor interface // concept expressions virtual void visit ( const TDLConceptTop& ) { isTopEq = true; } virtual void visit ( const TDLConceptBottom& ) { isTopEq = false; } virtual void visit ( const TDLConceptName& expr ) { isTopEq = topCLocal() && nc(expr.getEntity()); } virtual void visit ( const TDLConceptNot& expr ) { isTopEq = isBotEquivalent(expr.getC()); } virtual void visit ( const TDLConceptAnd& expr ) { for ( TDLConceptAnd::iterator p = expr.begin(), p_end = expr.end(); p != p_end; ++p ) if ( !isTopEquivalent(*p) ) // here isTopEq is false, so just return return; isTopEq = true; } virtual void visit ( const TDLConceptOr& expr ) { for ( TDLConceptOr::iterator p = expr.begin(), p_end = expr.end(); p != p_end; ++p ) if ( isTopEquivalent(*p) ) // here isTopEq is true, so just return return; isTopEq = false; } virtual void visit ( const TDLConceptOneOf& ) { isTopEq = false; } virtual void visit ( const TDLConceptObjectSelf& expr ) { isTopEq = isTopEquivalent(expr.getOR()); } virtual void visit ( const TDLConceptObjectValue& expr ) { isTopEq = isTopEquivalent(expr.getOR()); } virtual void visit ( const TDLConceptObjectExists& expr ) { isTopEq = isMinTopEquivalent ( 1, expr.getOR(), expr.getC() ); } virtual void visit ( const TDLConceptObjectForall& expr ) { isTopEq = isTopEquivalent(expr.getC()) || isBotEquivalent(expr.getOR()); } virtual void visit ( const TDLConceptObjectMinCardinality& expr ) { isTopEq = isMinTopEquivalent ( expr.getNumber(), expr.getOR(), expr.getC() ); } virtual void visit ( const TDLConceptObjectMaxCardinality& expr ) { isTopEq = isMaxTopEquivalent ( expr.getNumber(), expr.getOR(), expr.getC() ); } virtual void visit ( const TDLConceptObjectExactCardinality& expr ) { unsigned int n = expr.getNumber(); const TDLObjectRoleExpression* R = expr.getOR(); const TDLConceptExpression* C = expr.getC(); isTopEq = isMinTopEquivalent ( n, R, C ) && isMaxTopEquivalent ( n, R, C ); } virtual void visit ( const TDLConceptDataValue& expr ) { isTopEq = isTopEquivalent(expr.getDR()); } virtual void visit ( const TDLConceptDataExists& expr ) { isTopEq = isMinTopEquivalent ( 1, expr.getDR(), expr.getExpr() ); } virtual void visit ( const TDLConceptDataForall& expr ) { isTopEq = isTopEquivalent(expr.getExpr()) || isBotEquivalent(expr.getDR()); } virtual void visit ( const TDLConceptDataMinCardinality& expr ) { isTopEq = isMinTopEquivalent ( expr.getNumber(), expr.getDR(), expr.getExpr() ); } virtual void visit ( const TDLConceptDataMaxCardinality& expr ) { isTopEq = isMaxTopEquivalent ( expr.getNumber(), expr.getDR(), expr.getExpr() ); } virtual void visit ( const TDLConceptDataExactCardinality& expr ) { unsigned int n = expr.getNumber(); const TDLDataRoleExpression* R = expr.getDR(); const TDLDataExpression* D = expr.getExpr(); isTopEq = isMinTopEquivalent ( n, R, D ) && isMaxTopEquivalent ( n, R, D ); } // object role expressions virtual void visit ( const TDLObjectRoleTop& ) { isTopEq = true; } virtual void visit ( const TDLObjectRoleBottom& ) { isTopEq = false; } virtual void visit ( const TDLObjectRoleName& expr ) { isTopEq = topRLocal() && nc(expr.getEntity()); } virtual void visit ( const TDLObjectRoleInverse& expr ) { isTopEq = isTopEquivalent(expr.getOR()); } virtual void visit ( const TDLObjectRoleChain& expr ) { isTopEq = false; for ( TDLObjectRoleChain::iterator p = expr.begin(), p_end = expr.end(); p != p_end; ++p ) if ( !isTopEquivalent(*p) ) // isTopEq is false here return; isTopEq = true; } // equivalent to R(x,y) and C(x), so copy behaviour from ER.X virtual void visit ( const TDLObjectRoleProjectionFrom& expr ) { isTopEq = isMinTopEquivalent ( 1, expr.getOR(), expr.getC() ); } // equivalent to R(x,y) and C(y), so copy behaviour from ER.X virtual void visit ( const TDLObjectRoleProjectionInto& expr ) { isTopEq = isMinTopEquivalent ( 1, expr.getOR(), expr.getC() ); } // data role expressions virtual void visit ( const TDLDataRoleTop& ) { isTopEq = true; } virtual void visit ( const TDLDataRoleBottom& ) { isTopEq = false; } virtual void visit ( const TDLDataRoleName& expr ) { isTopEq = topRLocal() && nc(expr.getEntity()); } // data expressions virtual void visit ( const TDLDataTop& ) { isTopEq = true; } virtual void visit ( const TDLDataBottom& ) { isTopEq = false; } virtual void visit ( const TDLDataTypeName& ) { isTopEq = false; } virtual void visit ( const TDLDataTypeRestriction& ) { isTopEq = false; } virtual void visit ( const TDLDataValue& ) { isTopEq = false; } virtual void visit ( const TDLDataNot& expr ) { isTopEq = isBotEquivalent(expr.getExpr()); } virtual void visit ( const TDLDataAnd& expr ) { for ( TDLDataAnd::iterator p = expr.begin(), p_end = expr.end(); p != p_end; ++p ) if ( !isTopEquivalent(*p) ) // here isTopEq is false, so just return return; isTopEq = true; } virtual void visit ( const TDLDataOr& expr ) { for ( TDLDataOr::iterator p = expr.begin(), p_end = expr.end(); p != p_end; ++p ) if ( isTopEquivalent(*p) ) // here isTopEq is true, so just return return; isTopEq = false; } virtual void visit ( const TDLDataOneOf& ) { isTopEq = false; } }; // TopEquivalenceEvaluator inline bool BotEquivalenceEvaluator :: isTopEquivalent ( const TDLExpression& expr ) { return TopEval->isTopEquivalent(expr); } /// syntactic locality checker for DL axioms class SyntacticLocalityChecker: public LocalityChecker { protected: // members /// top evaluator TopEquivalenceEvaluator TopEval; /// bottom evaluator BotEquivalenceEvaluator BotEval; protected: // methods /// @return true iff EXPR is top equivalent bool isTopEquivalent ( const TDLExpression* expr ) { return TopEval.isTopEquivalent(*expr); } /// @return true iff EXPR is bottom equivalent bool isBotEquivalent ( const TDLExpression* expr ) { return BotEval.isBotEquivalent(*expr); } /// @return true iff role expression in equivalent to const wrt locality bool isREquivalent ( const TDLExpression* expr ) { return topRLocal() ? isTopEquivalent(expr) : isBotEquivalent(expr); } public: // interface /// init c'tor SyntacticLocalityChecker ( const TSignature* s ) : LocalityChecker(s) , TopEval(s) , BotEval(s) { TopEval.setBotEval(&BotEval); BotEval.setTopEval(&TopEval); } /// empty d'tor virtual ~SyntacticLocalityChecker ( void ) {} public: // visitor interface virtual void visit ( const TDLAxiomDeclaration& ) { isLocal = true; } virtual void visit ( const TDLAxiomEquivalentConcepts& axiom ) { // 1 element => local if ( axiom.size() == 1 ) { isLocal = true; return; } // axiom is local iff all the classes are either top- or bot-local isLocal = false; TDLAxiomEquivalentConcepts::iterator p = axiom.begin(), p_end = axiom.end(); if ( isBotEquivalent(*p) ) { for ( ++p; p != p_end; ++p ) if ( !isBotEquivalent(*p) ) return; } else { if ( !isTopEquivalent(*p) ) return; for ( ++p; p != p_end; ++p ) if ( !isTopEquivalent(*p) ) return; } isLocal = true; } virtual void visit ( const TDLAxiomDisjointConcepts& axiom ) { // local iff at most 1 concept is not bot-equiv bool hasNBE = false; isLocal = true; for ( TDLAxiomDisjointConcepts::iterator p = axiom.begin(), p_end = axiom.end(); p != p_end; ++p ) if ( !isBotEquivalent(*p) ) { if ( hasNBE ) { isLocal = false; break; } else hasNBE = true; } } virtual void visit ( const TDLAxiomDisjointUnion& axiom ) { // DisjointUnion(A, C1,..., Cn) is local if // (1) A and all of Ci are bot-equivalent, // or (2) A and one Ci are top-equivalent and the remaining Cj are bot-equivalent isLocal = false; bool lhsIsTopEq; if ( isTopEquivalent(axiom.getC()) ) lhsIsTopEq = true; // need to check (2) else if ( isBotEquivalent(axiom.getC()) ) lhsIsTopEq = false; // need to check (1) else return; // neither (1) nor (2) bool topEqDesc = false; for ( TDLAxiomDisjointUnion::iterator p = axiom.begin(), p_end = axiom.end(); p != p_end; ++p ) if ( !isBotEquivalent(*p) ) { if ( lhsIsTopEq && isTopEquivalent(*p) ) { if ( topEqDesc ) return; // 2nd top in there -- violate (2) -- non-local else topEqDesc = true; } else // either (1) or fail to have a top-eq for (2) return; } isLocal = true; } virtual void visit ( const TDLAxiomEquivalentORoles& axiom ) { isLocal = true; if ( axiom.size() <= 1 ) return; for ( TDLAxiomEquivalentORoles::iterator p = axiom.begin(), p_end = axiom.end(); p != p_end; ++p ) if ( !isREquivalent(*p) ) { isLocal = false; break; } } virtual void visit ( const TDLAxiomEquivalentDRoles& axiom ) { isLocal = true; if ( axiom.size() <= 1 ) return; for ( TDLAxiomEquivalentDRoles::iterator p = axiom.begin(), p_end = axiom.end(); p != p_end; ++p ) if ( !isREquivalent(*p) ) { isLocal = false; break; } } virtual void visit ( const TDLAxiomDisjointORoles& axiom ) { isLocal = false; if ( topRLocal() ) return; bool hasNBE = false; for ( TDLAxiomDisjointORoles::iterator p = axiom.begin(), p_end = axiom.end(); p != p_end; ++p ) if ( !isREquivalent(*p) ) { if ( hasNBE ) return; // false here else hasNBE = true; } isLocal = true; } virtual void visit ( const TDLAxiomDisjointDRoles& axiom ) { isLocal = false; if ( topRLocal() ) return; bool hasNBE = false; for ( TDLAxiomDisjointDRoles::iterator p = axiom.begin(), p_end = axiom.end(); p != p_end; ++p ) if ( !isREquivalent(*p) ) { if ( hasNBE ) return; // false here else hasNBE = true; } isLocal = true; } virtual void visit ( const TDLAxiomSameIndividuals& ) { isLocal = false; } virtual void visit ( const TDLAxiomDifferentIndividuals& ) { isLocal = false; } /// there is no such axiom in OWL API, but I hope nobody would use Fairness here virtual void visit ( const TDLAxiomFairnessConstraint& ) { isLocal = true; } virtual void visit ( const TDLAxiomRoleInverse& axiom ) { isLocal = isREquivalent(axiom.getRole()) && isREquivalent(axiom.getInvRole()); } virtual void visit ( const TDLAxiomORoleSubsumption& axiom ) { isLocal = isTopEquivalent(axiom.getRole()) || isBotEquivalent(axiom.getSubRole()); } virtual void visit ( const TDLAxiomDRoleSubsumption& axiom ) { isLocal = isTopEquivalent(axiom.getRole()) || isBotEquivalent(axiom.getSubRole()); } virtual void visit ( const TDLAxiomORoleDomain& axiom ) { isLocal = isTopEquivalent(axiom.getDomain()) || isBotEquivalent(axiom.getRole()); } virtual void visit ( const TDLAxiomDRoleDomain& axiom ) { isLocal = isTopEquivalent(axiom.getDomain()) || isBotEquivalent(axiom.getRole()); } virtual void visit ( const TDLAxiomORoleRange& axiom ) { isLocal = isTopEquivalent(axiom.getRange()) || isBotEquivalent(axiom.getRole()); } virtual void visit ( const TDLAxiomDRoleRange& axiom ) { isLocal = isTopEquivalent(axiom.getRange()) || isBotEquivalent(axiom.getRole()); } virtual void visit ( const TDLAxiomRoleTransitive& axiom ) { isLocal = isREquivalent(axiom.getRole()); } /// as BotRole is irreflexive, the only local axiom is topEquivalent(R) virtual void visit ( const TDLAxiomRoleReflexive& axiom ) { isLocal = isTopEquivalent(axiom.getRole()); } virtual void visit ( const TDLAxiomRoleIrreflexive& axiom ) { isLocal = isBotEquivalent(axiom.getRole()); } virtual void visit ( const TDLAxiomRoleSymmetric& axiom ) { isLocal = isREquivalent(axiom.getRole()); } virtual void visit ( const TDLAxiomRoleAsymmetric& axiom ) { isLocal = isBotEquivalent(axiom.getRole()); } virtual void visit ( const TDLAxiomORoleFunctional& axiom ) { isLocal = isBotEquivalent(axiom.getRole()); } virtual void visit ( const TDLAxiomDRoleFunctional& axiom ) { isLocal = isBotEquivalent(axiom.getRole()); } virtual void visit ( const TDLAxiomRoleInverseFunctional& axiom ) { isLocal = isBotEquivalent(axiom.getRole()); } virtual void visit ( const TDLAxiomConceptInclusion& axiom ) { isLocal = isBotEquivalent(axiom.getSubC()) || isTopEquivalent(axiom.getSupC()); } virtual void visit ( const TDLAxiomInstanceOf& axiom ) { isLocal = isTopEquivalent(axiom.getC()); } virtual void visit ( const TDLAxiomRelatedTo& axiom ) { isLocal = isTopEquivalent(axiom.getRelation()); } virtual void visit ( const TDLAxiomRelatedToNot& axiom ) { isLocal = isBotEquivalent(axiom.getRelation()); } virtual void visit ( const TDLAxiomValueOf& axiom ) { isLocal = isTopEquivalent(axiom.getAttribute()); } virtual void visit ( const TDLAxiomValueOfNot& axiom ) { isLocal = isBotEquivalent(axiom.getAttribute()); } }; // SyntacticLocalityChecker #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/dlVHash.h0000644000000000000000000000437512112642405017067 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2006-2009 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef _DLVHASH_H #define _DLVHASH_H #include #include #include "dlVertex.h" #include "tRole.h" /// naive and simple hash table for DL Verteces class dlVHashTable { protected: // types /// hashed IDs of the DL verteces typedef std::list HashLeaf; /// hash table by itself typedef std::map HashTable; protected: // members /// host DAG that contains actual nodes; const DLDag& host; /// HT for nodes HashTable Table; protected: // methods /// get a (very simple) hash of the vertex static BipolarPointer hash ( const DLVertex& v ) { BipolarPointer sum = 0; if ( v.getRole() != NULL ) sum += v.getRole()->getId(); if ( v.getProjRole() != NULL ) sum += v.getProjRole()->getId(); sum += v.getC(); sum += v.getNumberLE(); for ( DLVertex::const_iterator p = v.begin(), p_end = v.end(); p < p_end; ++p ) sum += *p; return sum; } /// insert new POSition into a given LEAF void insert ( HashLeaf& leaf, BipolarPointer pos ) { leaf.push_back(pos); } /// locate vertex V in a given LEAF BipolarPointer locate ( const HashLeaf& leaf, const DLVertex& v ) const; public: // interface /// empty c'tor dlVHashTable ( const DLDag& dag ) : host(dag) {} /// empty d'tor ~dlVHashTable ( void ) {} /// add an element (given by a POSition) to hash void addElement ( BipolarPointer pos ); /// locate given vertice in the hash BipolarPointer locate ( const DLVertex& v ) const; }; // dlVHashTable #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/DataTypeCenter.cpp0000644000000000000000000000330712112642405020737 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2010 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "taxNamEntry.h" #include "DataTypeCenter.h" #include "DataReasoning.h" DataTypeCenter :: ~DataTypeCenter ( void ) { for ( iterator p = begin(), p_end = end(); p < p_end; ++p ) delete *p; } TDataType* DataTypeCenter :: getTypeByName ( const std::string& name ) const { // special case whatever you want here // go through all types and check the name for ( const_iterator p = begin(), p_end = end(); p < p_end; ++p ) if ( name == (*p)->getType()->getName() ) return *p; return NULL; } void DataTypeCenter :: setLocked ( bool val ) { if ( val ) return; for ( iterator p = begin(), p_end = end(); p < p_end; ++p ) (*p)->setLocked(val); } void DataTypeCenter :: initDataTypeReasoner ( DataTypeReasoner& DTReasoner ) const { for ( const_iterator p = begin(), p_end = end(); p < p_end; ++p ) { TDataEntry* type = (*p)->getType(); if ( isValid(type->getBP()) ) DTReasoner.registerDataType(type); } } FaCTpp-src-v1.6.2~dfsg/src/Kernel/ifOptions.h0000644000000000000000000001242612112642405017504 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2010 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef IFOPTIONS_H #define IFOPTIONS_H /********************************************************\ |* Interface for the options management for the FaCT++ *| \********************************************************/ #include #include #include #include "fpp_assert.h" class Configuration; /// class for working with general options with boolean, integer or text values class ifOption { public: // type interface /// type of an option enum ioType { iotBool, iotInt, iotText }; private: // preventing copying (unimplemented) /// no empty c'tor ifOption ( void ); /// no copy c'tor ifOption ( const ifOption& o ); /// no assignment ifOption& operator = ( const ifOption& o ); protected: // members /// option name std::string optionName; /// informal descriprion std::string optionDescription; /// default value (name of type) std::string defaultValue; /// textual value [relevant iff (type == iotText)] std::string tValue; /// type of value: bool, int or text ioType type; /// integer value [relevant iff (type == iotInt)] int iValue; /// boolean value [relevant iff (type == iotBool)] bool bValue; public: // interface /// c'tor (init all values including proper ?Value) ifOption ( const std::string& name, const std::string& desc, ioType t, const std::string& defVal ); /// empty d'tor ~ifOption (void ) {} // write methods /// set boolean value; @return false in case of error bool setValue ( bool b ) { bValue = b; return (type != iotBool); } /// set integer value; @return false in case of error bool setValue ( int i ) { iValue = i; return (type != iotInt); } /// set string value; @return false in case of error bool setValue ( const std::string& t ) { tValue = t; return (type != iotText); } /// set textualy given value of current type; @return false in case of error bool setAValue ( const std::string& s ); // access methods /// get value of a Boolean option bool getBool ( void ) const { fpp_assert ( type == iotBool ); return bValue; } /// get value of an integer option int getInt ( void ) const { fpp_assert ( type == iotInt ); return iValue; } /// get value of a string option const std::string& getText ( void ) const { fpp_assert ( type == iotText ); return tValue; } /// output in the form of config file void printConfString ( std::ostream& o ) const; }; // ifOption // implementation of class ifOption inline ifOption :: ifOption ( const std::string& name, const std::string& desc, ioType t, const std::string& defVal ) : optionName(name) , optionDescription(desc) , defaultValue(defVal) , type(t) { setAValue (defVal); } /// set of options with access by name class ifOptionSet { protected: // internal type definitions /// base internal type typedef std::map OptionSet; protected: // members /// set of all avaliable (given) options OptionSet Base; protected: // methods /// get access option structure by name; @return NULL if no such option was registered const ifOption* locateOption ( const std::string& name ) const; public: // interface /// empty c'tor ifOptionSet ( void ) {} /// d'tor (delete all registered options) ~ifOptionSet ( void ) { for ( OptionSet::iterator p = Base.begin(); p != Base.end(); ++p ) delete p->second; } /// register an option with given name, description, type and default. @return true iff such option exists bool RegisterOption ( const std::string& name, const std::string& desc, ifOption::ioType t, const std::string& defVal ) { if ( locateOption (name) != NULL ) return true; Base[name] = new ifOption ( name, desc, t, defVal ); return false; } /// init all registered option using given section of given configuration bool initByConfigure ( Configuration& conf, const std::string& Section ); // read access /// get Boolean value of given option bool getBool ( const std::string& optionName ) const { const ifOption* p = locateOption ( optionName ); fpp_assert ( p != NULL ); return p->getBool (); } /// get integral value of given option int getInt ( const std::string& optionName ) const { const ifOption* p = locateOption ( optionName ); fpp_assert ( p != NULL ); return p->getInt (); } /// get string value of given option const std::string& getText ( const std::string& optionName ) const { const ifOption* p = locateOption ( optionName ); fpp_assert ( p != NULL ); return p->getText (); } /// output option set in the form of config file void printConfig ( std::ostream& o ) const; }; // ifOptionSet #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/eFPPNonSimpleRole.h0000644000000000000000000000306012112642405020765 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2007-2013 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef EFPPNONSIMPLEROLE_H #define EFPPNONSIMPLEROLE_H #include "eFaCTPlusPlus.h" /// exception thrown in case non-simple role used where only simple role can be used class EFPPNonSimpleRole: public EFaCTPlusPlus { private: // members /// saved name of the role const std::string roleName; /// error string std::string str; public: // interface /// c'tor: create an output string EFPPNonSimpleRole ( const std::string& name ) : EFaCTPlusPlus() , roleName(name) { str = "Non-simple role '"; str += name; str += "' is used as a simple one"; reason = str.c_str(); } /// empty d'tor virtual ~EFPPNonSimpleRole ( void ) throw() {} /// access to the role const char* getRoleName ( void ) const { return roleName.c_str(); } }; // EFPPNonSimpleRole #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/RAutomaton.h0000644000000000000000000002652212112642405017625 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2006-2012 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef RAUTOMATON_H #define RAUTOMATON_H #include #include #include "fpp_assert.h" #include "tFastSet.h" class TRole; /// state of the role automaton typedef unsigned int RAState; /// transition in the automaton for the role in RIQ-like languages class RATransition { protected: // typedefs /// set or roles that labels transition typedef std::vector TLabel; public: // typedefs /// iterator over roles typedef TLabel::const_iterator const_iterator; protected: // members /// set of roles that may affect the transition TLabel label; /// final state of the transition RAState state; public: // interface /// create a transition to given state RATransition ( RAState st ) : state(st) {} /// create a transition with a given label R to given state ST RATransition ( RAState st, const TRole* R ) : state(st) { add(R); } /// copy c'tor RATransition ( const RATransition& trans ) : label(trans.label), state(trans.state) {} /// assignment RATransition& operator = ( const RATransition& trans ) { label = trans.label; state = trans.state; return *this; } /// d'tor ~RATransition ( void ) {} // update the transition /// add role R to transition's label void add ( const TRole* R ) { label.push_back(R); } /// add label of transition TRANS to transition's label void add ( const RATransition& trans ) { label.insert ( label.end(), trans.label.begin(), trans.label.end() ); } /// add label of transition TRANS to transition's label only if they are new void addIfNew ( const RATransition& trans ) { for ( const_iterator p = trans.label.begin(), p_end = trans.label.end(); p < p_end; ++p ) if ( !applicable(*p) ) add(*p); } // query the transition /// get the 1st role in (multi-)transition const_iterator begin ( void ) const { return label.begin(); } /// get the last role in (multi-)transition const_iterator end ( void ) const { return label.end(); } /// give a final point of the transition RAState final ( void ) const { return state; } /// check whether transition is applicable wrt role R bool applicable ( const TRole* R ) const { for ( const_iterator p = label.begin(), p_end = label.end(); p < p_end; ++p ) if ( *p == R ) return true; return false; } /// check whether transition is empty bool empty ( void ) const { return label.empty(); } /// check whether transition is TopRole one bool isTop ( void ) const; /// print the transition starting from FROM void Print ( std::ostream& o, RAState from ) const; }; // RATransition /// class to represent transitions from a single state in an automaton class RAStateTransitions { protected: // types /// keep all the transitions typedef std::vector RTBase; /// RW iterators typedef RTBase::iterator iterator; public: // type interface /// RO iterators typedef RTBase::const_iterator const_iterator; protected: // members /// all transitions RTBase Base; /// set of all roles that can be applied by one of the transitions TFastSet ApplicableRoles; /// state from which all the transition starts RAState from; /// check whether there is an empty transition going from this state bool EmptyTransition; /// true iff there is a top transition going from this state bool TopTransition; /// flag whether the role is data or not (valid only for simple automata) bool DataRole; protected: // methods /// RW begin iterator begin ( void ) { return Base.begin(); } /// RW end iterator end ( void ) { return Base.end(); } public: // interface /// empty c'tor RAStateTransitions ( void ) : EmptyTransition(false), TopTransition(false) {} /// copy c'tor RAStateTransitions ( const RAStateTransitions& trans ) : EmptyTransition(trans.EmptyTransition) , TopTransition(trans.TopTransition) { for ( const_iterator p = trans.begin(), p_end = trans.end(); p != p_end; ++p ) Base.push_back(new RATransition(**p)); } /// assignment RAStateTransitions& operator = ( const RAStateTransitions& trans ) { for ( const_iterator p = trans.begin(), p_end = trans.end(); p != p_end; ++p ) Base.push_back(new RATransition(**p)); EmptyTransition = trans.EmptyTransition; TopTransition = trans.TopTransition; return *this; } /// d'tor: delete all transitions ~RAStateTransitions ( void ) { for ( iterator p = begin(), p_end = end(); p != p_end; ++p ) delete *p; } /// set up state transitions: no more additions to the structure void setup ( RAState state, unsigned int nRoles, bool data ); /// add a transition from a given state void add ( RATransition* trans ) { Base.push_back(trans); if ( trans->empty() ) EmptyTransition = true; if ( trans->isTop() ) TopTransition = true; } /// add information from TRANS to existing transition between the same states. @return false if no such transition found bool addToExisting ( const RATransition* trans ); /// @return true iff there are no transitions from this state bool empty ( void ) const { return Base.empty(); } /// @return true iff there is an empty transition from the state bool hasEmptyTransition ( void ) const { return EmptyTransition; } /// @return true iff there is a top-role transition from the state bool hasTopTransition ( void ) const { return TopTransition; } // RO access /// RO begin const_iterator begin ( void ) const { return Base.begin(); } /// RO end const_iterator end ( void ) const { return Base.end(); } /// get FROM state RAState getFrom ( void ) const { return from; } /// check whether one of the transitions accept R; implementation is in tRole.h bool recognise ( const TRole* R ) const; /// @return true iff there is only one transition bool isSingleton ( void ) const { return Base.size() == 1; } /// @return final state of the 1st transition; used for singletons RAState getTransitionEnd ( void ) const { return Base.front()->final(); } /// print all the transitions starting from the state FROM void Print ( std::ostream& o ) const { for ( const_iterator p = begin(), p_end = end(); p != p_end; ++p ) (*p)->Print ( o, from ); } }; // RAStateTransitions /// automaton for the role in RIQ-like languages class RoleAutomaton { protected: // members /// all transitions of the automaton, groupped by a starting state std::vector Base; /// maps original automata state into the new ones (used in copyRA) std::vector map; /// initial state of the next automaton in chain RAState iRA; /// flag whether automaton is input safe bool ISafe; /// flag whether automaton is output safe bool OSafe; /// flag for the automaton to be completed bool Complete; protected: // methods /// make sure that STATE exists in the automaton (update ton's size) void ensureState ( RAState state ) { if ( state >= Base.size() ) Base.resize(state+1); } /// state that the automaton is i-unsafe void setIUnsafe ( void ) { ISafe = false; } /// state that the automaton is o-unsafe void setOUnsafe ( void ) { OSafe = false; } /// check whether transition between FROM and TO breaks safety void checkTransition ( RAState from, RAState to ) { if ( from == final() ) setOUnsafe(); if ( to == initial() ) setIUnsafe(); } /// add TRANSition leading from a state FROM; all states are known to fit the ton void addTransition ( RAState from, RATransition* trans ) { checkTransition ( from, trans->final() ); Base[from].add(trans); } /// make the internal chain transition (between chainState and TO) void nextChainTransition ( RAState to ) { addTransition ( iRA, new RATransition(to) ); iRA = to; } /// add copy of the RA to given one; use internal MAP to renumber the states void addCopy ( const RoleAutomaton& RA ); /// init internal map according to RA size and final (FRA) states void initMap ( unsigned int RASize, RAState fRA ); public: // interface /// empty c'tor RoleAutomaton ( void ) : iRA(0) , ISafe(true) , OSafe(true) , Complete(false) { ensureState(1); } /// copy c'tor RoleAutomaton ( const RoleAutomaton& RA ); /// assignment RoleAutomaton& operator= ( const RoleAutomaton& RA ); /// empty d'tor ~RoleAutomaton ( void ) {} // access to states /// get the initial state RAState initial ( void ) const { return 0; } /// get the final state RAState final ( void ) const { return 1; } /// create new state RAState newState ( void ) { RAState ret = Base.size(); ensureState(ret); return ret; } /// get access to the transitions starting from STATE const RAStateTransitions& operator [] ( RAState state ) const { return Base[state]; } /// set up all transitions passing number of roles void setup ( unsigned int nRoles, bool data ) { for ( RAState i = 0; i < Base.size(); ++i ) Base[i].setup ( i, nRoles, data ); } // automaton's construction /// add TRANSition leading from a given STATE; check whether all states are correct void addTransitionSafe ( RAState state, RATransition* trans ) { ensureState(state); ensureState(trans->final()); addTransition ( state, trans ); } // chain automaton creation /// make the beginning of the chain void initChain ( RAState from ) { iRA = from; } /// add an Automaton to the chain that would start from the iRA; OSAFE shows the safety of a previous automaton in a chain bool addToChain ( const RoleAutomaton& RA, bool oSafe, RAState fRA ); /// add an Automaton to the chain with a default final state bool addToChain ( const RoleAutomaton& RA, bool oSafe ) { return addToChain ( RA, oSafe, size()+1 ); } // i/o safety /// get the i-safe value bool isISafe ( void ) const { return ISafe; } /// get the o-safe value bool isOSafe ( void ) const { return OSafe; } // automaton completeness /// mark an automaton as completed void setCompleted ( void ) { Complete = true; } /// check whether automaton is completed bool isCompleted ( void ) const { return Complete; } // get some stats /// return number of distinct states unsigned int size ( void ) const { return Base.size(); } /// @return true iff the automaton is simple bool isSimple ( void ) const { fpp_assert(isCompleted()); return size() == 2 && ISafe && OSafe; } // add single RA /// add RA from a subrole to given one void addRA ( const RoleAutomaton& RA ) { fpp_assert(!isCompleted()); if ( RA.isSimple() ) { bool ok = Base[initial()].addToExisting(*RA[initial()].begin()); fpp_assert(ok); } else { initChain(initial()); addToChain ( RA, /*oSafe=*/false, final() ); } } /// print an automaton void Print ( std::ostream& o ) const { for ( RAState state = 0; state < Base.size(); ++state ) Base[state].Print(o); } }; // RoleAutomaton #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/CWDArray.cpp0000644000000000000000000000447412112642405017505 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2012 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "CWDArray.h" #include "tRestorer.h" /// restore dep-set of the duplicated label element of the merged node class UnMerge: public TRestorer { protected: CWDArray& label; int offset; DepSet dep; public: UnMerge ( CWDArray& lab, CWDArray::iterator p ) : label(lab), offset(p-lab.begin()), dep(p->getDep()) {} virtual ~UnMerge ( void ) {} void restore ( void ) { CWDArray::iterator p = label.Base.begin() + offset; *p = ConceptWDep(p->bp(),dep); } }; // UnMerge TRestorer* CWDArray :: updateDepSet ( BipolarPointer bp, const DepSet& dep ) { if ( dep.empty() ) return NULL; for ( iterator i = Base.begin(), i_end = Base.end(); i < i_end; ++i ) if ( i->bp() == bp ) { TRestorer* ret = new UnMerge ( *this, i ); // DepSet odep(i->getDep()); i->addDep(dep); /* if ( odep == i->getDep() ) { delete ret; ret = NULL; }*/ return ret; } return NULL; } /// restore label to given LEVEL using given SS void CWDArray :: restore ( const SaveState& ss, unsigned int level ATTR_UNUSED ) { #ifndef RKG_USE_DYNAMIC_BACKJUMPING Base.resize(ss.ep); #else unsigned int j = ss.ep; unsigned int k = j; while ( k < Base.size() ) { if ( Base[k].getDep().level() >= level ) ++k; // remove entry else { Base[j] = Base[k]; ++j; ++k; } } Base.reset(j); #endif } /// print label part between given iterators void CWDArray :: print ( std::ostream& o ) const { o << " ["; const_iterator p = begin(), p_end = end(); if ( p != p_end ) { o << *p; while ( ++p < p_end ) o << ", " << *p; } o << "]"; } FaCTpp-src-v1.6.2~dfsg/src/Kernel/Makefile0000644000000000000000000000234112112642405017014 0ustar rootroot# # Makefile for FaCT++ kernel reasoning library # # -- DO NOT CHANGE THE REST OF FILE -- LIBRARY = Kernel LTYPE = static SOURCES = \ dltree.cpp\ configure.cpp\ LeveLogger.cpp\ dlTBox.cpp\ dlCompletionTree.cpp\ Reasoner.cpp\ dlVertex.cpp\ dlDag.cpp\ RoleMaster.cpp\ LogicFeature.cpp\ ifOptions.cpp\ Blocking.cpp\ Taxonomy.cpp\ Kernel.cpp\ Tactic.cpp\ modelCacheIan.cpp\ DLConceptTaxonomy.cpp\ taxVertex.cpp\ tRole.cpp\ tConcept.cpp\ dumpInterface.cpp\ dumpLisp.cpp\ dlCompletionGraph.cpp\ Relevance.cpp\ BuildDAG.cpp\ DataReasoning.cpp\ SortedReasoning.cpp\ CWDArray.cpp\ RAutomaton.cpp\ tAxiomSet.cpp\ tAxiom.cpp\ DataTypeCenter.cpp\ Preprocess.cpp\ Input.cpp\ SaveLoad.cpp\ ReasonerNom.cpp\ tExpressionManager.cpp\ CascadedCache.cpp\ TriRelation.cpp\ tSubsumptionMap.cpp\ Actor.cpp\ tDag2Interface.cpp\ tSplitExpansionRules.cpp\ tDLAxiom.cpp\ AtomicDecomposer.cpp\ KnowledgeExplorer.cpp\ include ../Makefile.include FaCTpp-src-v1.6.2~dfsg/src/Kernel/Taxonomy.cpp0000644000000000000000000002013212112642405017674 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2013 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /*******************************************************\ |* Implementation of taxonomy building for the FaCT++ *| \*******************************************************/ #include "Taxonomy.h" #include "globaldef.h" #include "logging.h" #include //#define TMP_PRINT_TAXONOMY_INFO /********************************************************\ |* Implementation of class Taxonomy *| \********************************************************/ Taxonomy :: ~Taxonomy ( void ) { delete Current; for ( iterator p = Graph.begin(), p_end = Graph.end(); p < p_end; ++p ) delete *p; } void Taxonomy :: print ( std::ostream& o ) const { o << "Taxonomy consists of " << nEntries << " entries\n"; o << " of which " << nCDEntries << " are completely defined\n\n"; o << "All entries are in format:\n\"entry\" {n: parent_1 ... parent_n} {m: child_1 child_m}\n\n"; TVSet sorted(itop()+1, end()); getTopVertex()->print(o); for ( TVSet::const_iterator p = sorted.begin(), p_end = sorted.end(); p != p_end; ++p ) if ( likely((*p)->isInUse()) ) (*p)->print(o); getBottomVertex()->print(o); } //--------------------------------------------------- // classification part //--------------------------------------------------- void Taxonomy :: addCurrentToSynonym ( TaxonomyVertex* syn ) { if ( queryMode() ) // no need to insert; just mark SYN as a host to curEntry syn->setVertexAsHost(curEntry); else { syn->addSynonym(curEntry); if ( LLM.isWritable(llTaxInsert) ) LL << "\nTAX:set " << curEntry->getName() << " equal " << syn->getPrimer()->getName(); } } void Taxonomy :: insertCurrentNode ( void ) { Current->setSample(curEntry); // put curEntry as a representative of Current if ( !queryMode() ) // insert node into taxonomy { Current->incorporate(); Graph.push_back(Current); // we used the Current so need to create a new one Current = new TaxonomyVertex(); } } void Taxonomy :: performClassification ( void ) { // do something before classification (tunable) preClassificationActions(); ++nEntries; if ( LLM.isWritable(llStartCfyEntry) && needLogging() ) LL << "\n\nTAX: start classifying entry " << curEntry->getName(); // if no classification needed -- nothing to do if ( immediatelyClassified() ) return; // perform main classification generalTwoPhaseClassification(); // create new vertex TaxonomyVertex* syn = Current->getSynonymNode(); if ( syn ) addCurrentToSynonym(syn); else insertCurrentNode(); // clear all labels clearLabels(); } void Taxonomy :: generalTwoPhaseClassification ( void ) { // Top-Down phase // setup TD phase (ie, identify parent candidates) setupTopDown(); // run TD phase if necessary (ie, entry is completely defined) if ( needTopDown() ) { getTopVertex()->setValued ( true, valueLabel ); // C [= TOP == true getBottomVertex()->setValued ( false, valueLabel ); // C [= BOT == false (catched by UNSAT) runTopDown(); } clearLabels(); // Bottom-Up phase // run BU if necessary if ( needBottomUp() ) { getBottomVertex()->setValued ( true, valueLabel ); // BOT [= C == true runBottomUp(); } clearLabels(); } bool Taxonomy :: classifySynonym ( void ) { const ClassifiableEntry* syn = resolveSynonym(curEntry); if ( syn == curEntry ) return false; // not a synonym // update synonym vertex: fpp_assert ( syn->getTaxVertex() != NULL ); addCurrentToSynonym(syn->getTaxVertex()); return true; } bool Taxonomy :: isDirectParent ( TaxonomyVertex* v ) const { for ( TaxonomyVertex::const_iterator q = v->begin(/*upDirection=*/false), q_end = v->end(/*upDirection=*/false); q != q_end; ++q ) if ( (*q)->isValued(valueLabel) && (*q)->getValue() == true ) { # ifdef WARN_EXTRA_SUBSUMPTION std::cout << "\nCTAX!!: Definition (implies '" << curEntry->getName() << "','" << (*p)->getName() << "') is extra because of definition (implies '" << curEntry->getName() << "','" << (*q)->getPrimer()->getName() << "')\n"; # endif return false; } return true; } void Taxonomy :: setNonRedundantCandidates ( void ) { if ( LLM.isWritable(llCDConcept) && needLogging() ) { if ( !curEntry->hasToldSubsumers() ) LL << "\nTAX: TOP"; LL << " completely defines concept " << curEntry->getName(); } // test if some "told subsumer" is not an immediate TS (ie, not a border element) for ( ss_iterator p = told_begin(), p_end = told_end(); p < p_end; ++p ) { TaxonomyVertex* par = (*p)->getTaxVertex(); if ( par == NULL ) // non-classifiable TS continue; if ( isDirectParent(par) ) Current->addNeighbour ( /*upDirection=*/true, par ); } } void Taxonomy :: setToldSubsumers ( void ) { if ( LLM.isWritable(llTSList) && needLogging() && !ksStack.top()->s_empty() ) LL << "\nTAX: told subsumers"; for ( ss_iterator p = told_begin(), p_end = told_end(); p < p_end; ++p ) { if ( !(*p)->isClassified() ) // non-primitive/non-classifiable concept continue; // safety check if ( LLM.isWritable(llTSList) && needLogging() ) LL << " '" << (*p)->getName() << "'"; propagateTrueUp((*p)->getTaxVertex()); } if ( !ksStack.top()->p_empty() && LLM.isWritable(llTSList) && needLogging() ) { LL << " and possibly "; for ( ss_iterator q = ksStack.top()->p_begin(), q_end = ksStack.top()->p_end(); q < q_end; ++q ) LL << " '" << (*q)->getName() << "'"; } } void Taxonomy :: propagateTrueUp ( TaxonomyVertex* node ) { // if taxonomy class already checked -- do nothing if ( node->isValued(valueLabel) ) { fpp_assert ( node->getValue() ); return; } // overwise -- value it... node->setValued ( true, valueLabel ); // ... and value all parents for ( TaxonomyVertex::iterator p = node->begin(/*upDirection=*/true), p_end = node->end(/*upDirection=*/true); p != p_end; ++p ) propagateTrueUp(*p); } //----------------------------------------------------------------- //-- DFS-based classification methods //----------------------------------------------------------------- ClassifiableEntry* Taxonomy :: prepareTS ( ClassifiableEntry* cur ) { // we just found that TS forms a cycle -- return stop-marker if ( waitStack.contains(cur) ) return cur; // starting from the topmost entry addTop(cur); // true iff CUR is a reason of the cycle bool cycleFound = false; // for all the told subsumers... for ( ss_iterator p = told_begin(), p_end = told_end(); p < p_end; ++p ) if ( !(*p)->isClassified() ) // need to classify it first { if ( unlikely((*p)->isNonClassifiable()) ) continue; // prepare TS for *p ClassifiableEntry* v = prepareTS(*p); // if NULL is returned -- just continue if ( v == NULL ) continue; if ( v == cur ) // current cycle is finished, all saved in Syns { // after classification of CUR we need to mark all the Syns as synonyms cycleFound = true; // continue to prepare its classification continue; } else { // arbitrary vertex in a cycle: save in synonyms of a root cause Syns.push_back(cur); // don't need to classify it removeTop(); // return the cycle cause return v; } } // all TS are ready here -- let's classify! classifyTop(); // now if CUR is the reason of cycle mark all SYNs as synonyms if ( cycleFound ) { TaxonomyVertex* syn = cur->getTaxVertex(); for ( std::vector::iterator q = Syns.begin(), q_end = Syns.end(); q != q_end; ++q ) syn->addSynonym(*q); Syns.clear(); } // here the cycle is gone return NULL; } FaCTpp-src-v1.6.2~dfsg/src/Kernel/LeveLogger.h0000644000000000000000000000445112112642405017564 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2006 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef _LEVELOGGER_H #define _LEVELOGGER_H #include // define unused attribute for parameters #if defined(__GNUC__) && (__GNUC__ >= 4) # define ATTR_UNUSED __attribute__((unused)) #else # define ATTR_UNUSED #endif class Configuration; class LeveLogger { private: // members /// the allowed logging level; init it once for the whole session unsigned int allowedLevel; public: // interface /// c'tor LeveLogger ( void ) : allowedLevel(0) {} /// d'tor: just empty ~LeveLogger ( void ) {} /// sets output file and allowedLevel by given values bool initLogger ( unsigned int l, const char* filename ); /** sets output file and allowedLevel by config file. * The values will be taken from Config|[LeveLogger]|{allowedLevel,file} * Default level is 0, but the file name is mandatory. */ bool initLogger ( Configuration& Config ); /// @return true if LEVEL will be allowed bool isWritable ( unsigned int level ATTR_UNUSED ) const { # ifdef _USE_LOGGING return level <= allowedLevel; # else return false; # endif } }; // LeveLogger /// the only main logger/manager for all usage extern LeveLogger LLM; /// file stream to be used by LLM; be sure that every OP with LL is guarded by LLM extern std::ofstream LL; // macro for checking if LL is writable and then return #define CHECK_LL_RETURN(val) \ if (!LLM.isWritable(val)) return // macro for checking if LL is writable and then return value #define CHECK_LL_RETURN_VALUE(val,ret) \ if (!LLM.isWritable(val)) return (ret) #endif // _LEVELOGGER_H FaCTpp-src-v1.6.2~dfsg/src/Kernel/tBranchingContext.h0000644000000000000000000001221612112642405021153 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2012 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef TBRANCHINGCONTEXT_H #define TBRANCHINGCONTEXT_H #include "dlCompletionTree.h" /// class for saving branching context of a Reasoner class BranchingContext { private: // prevent copy /// no copy c'tor BranchingContext ( const BranchingContext& s ); /// no assignment BranchingContext& operator = ( const BranchingContext& s ); public: // members /// currently processed node DlCompletionTree* curNode; /// currently processed concept ConceptWDep curConcept; /// positions of the Used members size_t pUsedIndex, nUsedIndex; /// size of a session GCIs vector size_t SGsize; /// dependences for branching clashes DepSet branchDep; public: // interface /// empty c'tor BranchingContext ( void ) : curNode (NULL), curConcept (bpINVALID) {} /// empty d'tor virtual ~BranchingContext ( void ) {} /// init indices (if necessary) virtual void init ( void ) {} /// give the next branching alternative virtual void nextOption ( void ) {} }; // BranchingContext /// branching context for the OR operations class BCOr: public BranchingContext { public: // types /// short OR indexes typedef std::vector OrIndex; /// short OR index iterator typedef OrIndex::const_iterator or_iterator; public: // members /// current branching index unsigned int branchIndex; /// relevant disjuncts (ready to add) OrIndex applicableOrEntries; public: // interface /// empty c'tor BCOr ( void ) : BranchingContext() {} /// empty d'tor virtual ~BCOr ( void ) {} /// init branch index virtual void init ( void ) { branchIndex = 0; } /// give the next branching alternative virtual void nextOption ( void ) { ++branchIndex; } // access to the fields /// check if the current processing OR entry is the last one bool isLastOrEntry ( void ) const { return applicableOrEntries.size() == branchIndex+1; } /// 1st element of OrIndex or_iterator orBeg ( void ) const { return applicableOrEntries.begin(); } /// current element of OrIndex or_iterator orCur ( void ) const { return orBeg() + branchIndex; } }; // BCOr /// branching context for the Choose-rule class BCChoose: public BranchingContext { public: // interface /// empty c'tor BCChoose ( void ) : BranchingContext() {} /// empty d'tor virtual ~BCChoose ( void ) {} }; // BCChoose /// branching context for the NN-rule class BCNN: public BranchingContext { public: // members /// the value of M used in the NN rule unsigned int value; public: // interface /// empty c'tor BCNN ( void ) : BranchingContext() {} /// empty d'tor virtual ~BCNN ( void ) {} /// init value virtual void init ( void ) { value = 1; } /// give the next branching alternative virtual void nextOption ( void ) { ++value; } // access to the fields /// check if the NN has no option to process bool noMoreNNOptions ( unsigned int n ) const { return value > n; } }; // BCNN /// branching context for the LE operations template class BCLE: public BranchingContext { public: // types /// vector of edges typedef std::vector EdgeVector; public: // members /// index of a edge into which the merge is performing unsigned int toIndex; /// index of a merge candidate unsigned int fromIndex; /// vector of edges to be merged EdgeVector ItemsToMerge; public: // interface /// empty c'tor BCLE ( void ) : BranchingContext() {} /// empty d'tor virtual ~BCLE ( void ) {} /// init indices virtual void init ( void ) { toIndex = 0; fromIndex = 0; } /// correct fromIndex after changing void resetMCI ( void ) { fromIndex = ItemsToMerge.size()-1; } /// give the next branching alternative virtual void nextOption ( void ) { --fromIndex; // get new merge candidate if ( fromIndex == toIndex ) // nothing more can be mergeable to BI node { ++toIndex; // change the candidate to merge to resetMCI(); } } // access to the fields /// get FROM pointer to merge T* getFrom ( void ) const { return ItemsToMerge[fromIndex]; } /// get FROM pointer to merge T* getTo ( void ) const { return ItemsToMerge[toIndex]; } /// check if the LE has no option to process bool noMoreLEOptions ( void ) const { return fromIndex <= toIndex; } }; // BCLE /// branching context for the barrier class BCBarrier: public BranchingContext { public: // interface /// empty c'tor BCBarrier ( void ) : BranchingContext() {} /// empty d'tor virtual ~BCBarrier ( void ) {} }; // BCBarrier #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/dlVertex.h0000644000000000000000000003524312112642405017331 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2012 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef DLVERTEX_H #define DLVERTEX_H #include #include #include // memset #include "globaldef.h" #include "BiPointer.h" #include "modelCacheInterface.h" #include "mergableLabel.h" // for sort inferences class DLDag; class TRole; class TNamedEntry; /// different Concept Expression tags /* * The one who changing this should always check: * - Additional fields in the class DLVertex * => operator == * => hash functions * - DLVertex methods omitStat(), getTagName(), Print() * - DLDag methods *Stat() * - DLDag methods getIndex(), updateIndex() * - tree2dag() * - mergeSorts(v) * - setRelevant() * - PrintDagEntry() * - ToDoPriorMatrix::getIndex() * - CGLabel::isComplexConcept() * - prepareCascadedCache() * - commonTacticBody() */ enum DagTag { // illegal entry dtBad = 0, // operations dtTop, dtAnd, dtForall, dtLE, dtIrr, // \neg\exists R.Self dtProj, // aux vertex with Projection FROM the current node dtNN, // NN-rule was applied dtChoose, // choose-rule // ID's dtPConcept, // primitive concept dtNConcept, // non-primitive concept dtPSingleton, dtNSingleton, dtSplitConcept, // splitted concept dtDataType, dtDataValue, dtDataExpr, // data type with restrictions }; /// check whether given DagTag is a primitive named concept-like entity inline bool isPNameTag ( DagTag tag ) { return (tag == dtPConcept || tag == dtPSingleton); } /// check whether given DagTag is a non-primitive named concept-like entity inline bool isNNameTag ( DagTag tag ) { return (tag == dtNConcept || tag == dtNSingleton); } /// check whether given DagTag is a named concept-like entity inline bool isCNameTag ( DagTag tag ) { return isPNameTag(tag) || isNNameTag(tag); } // define complex switch labels #define dtConcept dtPConcept: case dtNConcept #define dtSingleton dtPSingleton: case dtNSingleton #define dtPrimName dtPConcept: case dtPSingleton #define dtNonPrimName dtNConcept: case dtNSingleton #define dtName dtConcept: case dtSingleton #define dtData dtDataType: case dtDataValue: case dtDataExpr /// interface for the cache of DLVertex class DLVertexCache { protected: // members /// cache for the positive entry modelCacheInterface* pCache; /// cache for the negative entry modelCacheInterface* nCache; public: // interface /// empty c'tor DLVertexCache ( void ) : pCache(NULL), nCache(NULL) {} /// d'tor virtual ~DLVertexCache ( void ) { delete pCache; delete nCache; } // cache interface /// return cache wrt positive flag const modelCacheInterface* getCache ( bool pos ) const { return pos ? pCache : nCache; } /// set cache wrt positive flag; note that cache is set up only once void setCache ( bool pos, modelCacheInterface* p ) { if ( pos ) pCache = p; else nCache = p; } }; // DLVertexCache class DLVertexStatistic { public: // types /// type for a statistic typedef unsigned short int StatType; protected: // members /// maximal depth, size and frequency of reference of the expression StatType stat[10]; public: // static methods /// get access to statistic by the depth of a concept static unsigned int getStatIndexDepth ( bool pos ) { return (pos ? 0 : 1); } /// get access to statistic by the size of a concept static unsigned int getStatIndexSize ( bool pos ) { return (pos ? 2 : 3); } /// get access to statistic by the # of branching rules of a concept static unsigned int getStatIndexBranch ( bool pos ) { return (pos ? 4 : 5); } /// get access to statistic by the # of generating rules of a concept static unsigned int getStatIndexGener ( bool pos ) { return (pos ? 6 : 7); } /// get access to statistic by the freq of a concept static unsigned int getStatIndexFreq ( bool pos ) { return (pos ? 8 : 9); } public: // interface /// default c'tor DLVertexStatistic ( void ) { std::memset ( &stat, 0, sizeof(stat) ); } /// empty d'tor virtual ~DLVertexStatistic ( void ) {} // set methods /// add-up all stat values at once by explicit values void updateStatValues ( StatType d, StatType s, StatType b, StatType g, bool pos ) { stat[getStatIndexSize(pos)] += s; stat[getStatIndexBranch(pos)] += b; stat[getStatIndexGener(pos)] += g; if ( d > stat[getStatIndexDepth(pos)] ) stat[getStatIndexDepth(pos)] = d; } /// add-up all values at once by a given vertex void updateStatValues ( const DLVertexStatistic& v, bool posV, bool pos ) { updateStatValues ( v.getDepth(posV), v.getSize(posV), v.getBranch(posV), v.getGener(posV), pos ); } /// increment frequency value void incFreqValue ( bool pos ) { ++stat[getStatIndexFreq(pos)]; } // get methods /// general access to a stat value by index StatType getStat ( unsigned int i ) const { return stat[i]; } /// general access to a stat value by index StatType getDepth ( bool pos ) const { return stat[getStatIndexDepth(pos)]; } /// general access to a stat value by index StatType getSize ( bool pos ) const { return stat[getStatIndexSize(pos)]; } /// general access to a stat value by index StatType getBranch ( bool pos ) const { return stat[getStatIndexBranch(pos)]; } /// general access to a stat value by index StatType getGener ( bool pos ) const { return stat[getStatIndexGener(pos)]; } /// general access to a stat value by index StatType getFreq ( bool pos ) const { return stat[getStatIndexFreq(pos)]; } }; // DLVertexStatistic /// tag of the vertex and bits and code for efficient DFS algorithms class DLVertexTagDFS { protected: // members /// main operation in concept expression // WARNING: the Visual Studio C++ compiler treat this as a signed integer, // so I've added extra bit to stay in the unsigned field DagTag Op : 6; // 17 types /// aux field for DFS in presence of cycles bool VisitedPos : 1; /// aux field for DFS in presence of cycles bool ProcessedPos : 1; /// true iff node is involved in cycle bool inCyclePos : 1; /// aux field for DFS in presence of cycles bool VisitedNeg : 1; /// aux field for DFS in presence of cycles bool ProcessedNeg : 1; /// true iff node is involved in cycle bool inCycleNeg : 1; /// padding unsigned unused : 4; public: // interface /// default c'tor DLVertexTagDFS ( DagTag op ) : Op(op) , VisitedPos(false) , ProcessedPos(false) , inCyclePos(false) , VisitedNeg(false) , ProcessedNeg(false) , inCycleNeg(false) {} /// empty d'tor virtual ~DLVertexTagDFS ( void ) {} // tag access /// return tag of the CE DagTag Type ( void ) const { return Op; } // DFS-related method /// check whether current Vertex is being visited bool isVisited ( bool pos ) const { return (pos ? VisitedPos : VisitedNeg); } /// check whether current Vertex is processed bool isProcessed ( bool pos ) const { return (pos ? ProcessedPos : ProcessedNeg); } /// set that the node is being visited void setVisited ( bool pos ) { if ( pos ) VisitedPos = true; else VisitedNeg = true; } /// set that the node' DFS processing is completed void setProcessed ( bool pos ) { if ( pos ) { ProcessedPos = true; VisitedPos = false; } else { ProcessedNeg = true; VisitedNeg = false; } } /// clear DFS flags void clearDFS ( void ) { ProcessedPos = VisitedPos = ProcessedNeg = VisitedNeg = false; } /// check whether concept is in cycle bool isInCycle ( bool pos ) const { return (pos ? inCyclePos : inCycleNeg); } /// set concept is in cycle void setInCycle ( bool pos ) { if ( pos ) inCyclePos = true; else inCycleNeg = true; } }; // DLVertexTagDFS /// usage of the particulare vertex during reasoning class DLVertexUsage { public: // types /// type for a statistic typedef unsigned long UsageType; protected: // members /// usage statistic for pos- and neg occurences of a vertex UsageType posUsage, negUsage; public: // interface /// empty c'tor DLVertexUsage ( void ) : posUsage(0), negUsage(0) {} /// empty d'tor virtual ~DLVertexUsage ( void ) {} /// get access to a usage wrt POS UsageType getUsage ( bool pos ) const { return pos ? posUsage : negUsage; } /// increment usage of the node void incUsage ( bool pos ) { if ( pos ) ++posUsage; else ++negUsage; } }; // DLVertexUsage class DLVertexSort { protected: // members /// maximal depth, size and frequency of reference of the expression mergableLabel Sort; public: // interface /// default c'tor DLVertexSort ( void ) {} /// empty d'tor virtual ~DLVertexSort ( void ) {} // label access methods /// get RW access to the label mergableLabel& getSort ( void ) { return Sort; } /// get RO access to the label const mergableLabel& getSort ( void ) const { return Sort; } /// merge local label to label LABEL void merge ( mergableLabel& label ) { Sort.merge(label); } }; // DLVertexSort /// Class for normalised Concept Expressions class DLVertex : public DLVertexCache , public DLVertexStatistic #ifdef RKG_PRINT_DAG_USAGE , public DLVertexUsage #endif , public DLVertexTagDFS #ifdef RKG_USE_SORTED_REASONING , public DLVertexSort #endif { private: // prevent copying // no copy c'tor DLVertex ( const DLVertex& v ); /// no assignment DLVertex& operator = ( const DLVertex& v ); protected: // typedefs /// base type for array of BPs typedef std::vector BaseType; public: // typedefs /// RO access to the elements of node typedef BaseType::const_iterator const_iterator; /// RO access to the elements of node in reverse order typedef BaseType::const_reverse_iterator const_reverse_iterator; protected: // members /// set of arguments (CEs, numbers for NR) BaseType Child; /// pointer to concept-like entry (for PConcept, etc) TNamedEntry* Concept; /// pointer to role (for E\A, NR) const TRole* Role; /// projection role (used for projection op only) const TRole* ProjRole; /// C if available BipolarPointer C; /// n if available unsigned int n; public: // interface /// c'tor for Top/CN/And (before adding any operands) explicit DLVertex ( DagTag op ) : DLVertexTagDFS(op) , Concept(NULL) , Role(NULL) , ProjRole(NULL) , C(bpINVALID) , n(0) {} /// c'tor for Refl/Irr DLVertex ( DagTag op, const TRole* R ) : DLVertexTagDFS(op) , Concept(NULL) , Role(R) , ProjRole(NULL) , C(bpINVALID) , n(0) {} /// c'tor for CN/DE; C is an operand DLVertex ( DagTag op, BipolarPointer c ) : DLVertexTagDFS(op) , Concept(NULL) , Role(NULL) , ProjRole(NULL) , C(c) , n(0) {} /// c'tor for <= n R_C; and for \A R{n}_C; Note order C, n, R->pointer DLVertex ( DagTag op, BipolarPointer m, const TRole* R, BipolarPointer c ) : DLVertexTagDFS(op) , Concept(NULL) , Role(R) , ProjRole(NULL) , C(c) , n(m) {} /// c'tor for ProjFrom R C ProjR DLVertex ( const TRole* R, BipolarPointer c, const TRole* ProjR ) : DLVertexTagDFS(dtProj) , Concept(NULL) , Role(R) , ProjRole(ProjR) , C(c) , n(0) {} /// d'tor (empty) virtual ~DLVertex ( void ) {} /// compare 2 CEs bool operator == ( const DLVertex& v ) const { return (Type() == v.Type()) && (Role == v.Role) && (ProjRole == v.ProjRole) && (C == v.C) && (n == v.n) && (Child == v.Child); } /// return C for concepts/quantifiers/NR verteces BipolarPointer getC ( void ) const { return C; } /// return N for the (<= n R) vertex unsigned int getNumberLE ( void ) const { return n; } /// return N for the (>= n R) vertex unsigned int getNumberGE ( void ) const { return n+1; } /// return STATE for the (\all R{state}.C) vertex unsigned int getState ( void ) const { return n; } /// return pointer to the first concept name of the entry const_iterator begin ( void ) const { return Child.begin(); } /// return pointer after the last concept name of the entry const_iterator end ( void ) const { return Child.end(); } /// return pointer to the last concept name of the entry; WARNING!! works for AND only const_reverse_iterator rbegin ( void ) const { return Child.rbegin(); } /// return pointer before the first concept name of the entry; WARNING!! works for AND only const_reverse_iterator rend ( void ) const { return Child.rend(); } /// return pointer to Role for the Role-like verteces const TRole* getRole ( void ) const { return Role; } /// return pointer to Projection Role for the Projection verteces const TRole* getProjRole ( void ) const { return ProjRole; } /// get (RW) TConcept for concept-like fields TNamedEntry* getConcept ( void ) { return Concept; } /// get (RO) TConcept for concept-like fields const TNamedEntry* getConcept ( void ) const { return Concept; } /// set TConcept value to entry void setConcept ( TNamedEntry* p ) { Concept = p; } /// set a concept (child) to Name-like vertex void setChild ( BipolarPointer p ) { C = p; } /// adds a child to 'AND' vertex; returns TRUE if contradiction found bool addChild ( BipolarPointer p ); // methods for choosing ordering in the OR fields /// whether statistic's gathering should be omitted due to the type of a vertex bool omitStat ( bool pos ) const; /// sort entry using DAG's compare method void sortEntry ( const DLDag& dag ); // output /// get text name for CE tag const char* getTagName ( void ) const; /// print the whole node void Print ( std::ostream& o ) const; // save/load interface; implementation is in SaveLoad.cpp /// save entry void Save ( std::ostream& o ) const; /// load entry void Load ( std::istream& i ); }; // DLVertex /// whether statistic's gathering should be omitted due to the type of a vertex inline bool DLVertex :: omitStat ( bool pos ) const { switch ( Type() ) { case dtDataType: case dtDataValue: case dtDataExpr: case dtNN: // no way to get it in expressions case dtChoose: // same case dtBad: case dtTop: return true; case dtPConcept: case dtPSingleton: case dtProj: return !pos; default: return false; } } /** * returns true iff corresponding NRs may clash. * Clash may appears for (>= n R) and (<= m R) if n > m. * Since \neg (<= n R) represents (>= (n+1) R), so * comparison became (n+1) > m, or n >= m */ inline bool mayClashNR ( unsigned int geNR, unsigned int leNR ) { return geNR >= leNR; } #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/tSubsumptionMap.cpp0000644000000000000000000000610012112642405021227 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2010 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "tSubsumptionMap.h" TSubsumptionMap :: TSubsumptionMap ( void ) : K(2) { P.resize(2); P_K.resize(2); P[0].push_back(true); P[0].push_back(true); P[1].push_back(true); P[1].push_back(true); P_K[0].push_back(true); P_K[0].push_back(true); P_K[1].push_back(true); P_K[1].push_back(true); addKnoSub ( TopVertex, TopVertex ); addKnoSub ( BotVertex, BotVertex ); addKnoSub ( BotVertex, TopVertex ); } TSubsumptionMap :: TSubsumptionMap ( unsigned int n ) : K(n+2) { n += 2; // top/bottom bvec bTrue ( n, true ); P.insert ( P.end(), n, bTrue ); P_K.insert ( P_K.end(), n, bTrue ); // init subsumptions Bot [= C [= Top, C [= C for ( Vertex v = 0; v < n; ++v ) { addKnoSub ( v, v ); addKnoSub ( BotVertex, v ); addKnoSub ( v, TopVertex ); } } TSubsumptionMap::Vertex TSubsumptionMap :: addVertex ( void ) { // add new vertex to K Vertex ret = K.newVertex(); // add new vertex to existing rows of P, P_K for ( unsigned int i = 0; i < ret; ++i ) { P[i].push_back(true); P_K[i].push_back(true); } // add new tautology vec to P, P_K bvec bTrue ( ret+1, true ); P.push_back(bTrue); P_K.push_back(bTrue); // subsumption relation is reflexive addKnoSub ( ret, ret ); return ret; } void TSubsumptionMap :: addNonSub ( Vertex x, Vertex y ) { fpp_assert ( x < size() ); fpp_assert ( y < size() ); P[x][y] = false; if ( P_K[x][y] == false ) return; // adjust [P]K (Prune-possibles, lines 2-4) P_K[x][y] = false; for ( Vertex i = 0; i < K.size(); ++i ) if ( K.R(x,i) ) for ( Vertex j = 0; j < K.size(); ++j ) if ( K.R(j,y) ) P_K[i][j] = false; } bool TSubsumptionMap :: addKnoSub ( Vertex x, Vertex y ) { fpp_assert ( x < size() ); fpp_assert ( y < size() ); if ( K.R(x,y) ) return false; // no new cycles here bool ret = K.insert(x,y); // adjust [P]K (Prune-possibles, lines 6-13) Vertex i, j; for ( i = 0; i < K.size(); ++i ) if ( P_K[y][i] ) // in [P]K for ( j = 0; j < K.size(); ++j ) if ( K.R(i,j) && !P[x][j] ) { P_K[y][i] = false; break; } for ( i = 0; i < K.size(); ++i ) if ( P_K[i][x] ) // in [P]K for ( j = 0; j < K.size(); ++j ) if ( K.R(j,i) && !P[j][y] ) { P_K[i][x] = false; break; } if ( ret ) std::cerr << "Cycle found with " << x << " and " << y << "\n"; return ret; } FaCTpp-src-v1.6.2~dfsg/src/Kernel/Kernel.h0000644000000000000000000013760112112642405016755 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2013 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef KERNEL_H #define KERNEL_H #include #include "fpp_assert.h" #include "eFPPInconsistentKB.h" #include "dlTBox.h" #include "ifOptions.h" #include "DLConceptTaxonomy.h" // for getRelatives() #include "tExpressionTranslator.h" #include "tOntology.h" #include "KnowledgeExplorer.h" #include "tOntologyAtom.h" // types for AD #include "ModuleType.h" class TModularizer; class AtomicDecomposer; class TJNICache; // cached JNI information class ReasoningKernel { public: // types interface /* The type system for DL expressions used in the input language: TExpr; TConceptExpr: TExpr; TIndividualExpr : TExpr; TRoleExpr: TExpr; TORoleComplexExpr: TRoleExpr; TORoleExpr: TORoleComplexExpr; TDRoleExpr: TRoleExpr; TDataExpr: TExpr; TDataValueExpr: TDataExpr; Right now all the expressions are of the type DLTree*. Later on the appropriate classes from tDlExpression.h As a transition step, the intermediate structure is introduced. */ /// general expression typedef const TDLExpression TExpr; /// concept expression typedef const TDLConceptExpression TConceptExpr; /// individual expression typedef const TDLIndividualExpression TIndividualExpr; /// role expression typedef const TDLRoleExpression TRoleExpr; /// object role complex expression (including role chains and projections) typedef const TDLObjectRoleComplexExpression TORoleComplexExpr; /// object role expression typedef const TDLObjectRoleExpression TORoleExpr; /// data role expression typedef const TDLDataRoleExpression TDRoleExpr; /// data expression typedef const TDLDataExpression TDataExpr; /// data type expression typedef TDLDataTypeExpression TDataTypeExpr; /// data value expression typedef const TDLDataValue TDataValueExpr; /// data facet expression typedef const TDLFacetExpression TFacetExpr; // name sets /// set of arbitrary named expressions typedef std::vector NamesVector; // IndividualSet is just set of named individual expressions typedef NamesVector IndividualSet; /// typedef for intermediate instance related type typedef TRelatedMap::CIVec CIVec; // types for knowledge exploration /// type for the node in the completion graph typedef KnowledgeExplorer::TCGNode TCGNode; /// type for the node vector typedef KnowledgeExplorer::TCGNodeVec TCGNodeVec; /// type for a set of role expressions (used in KE to return stuff) typedef KnowledgeExplorer::TCGRoleSet TCGRoleSet; /// type for a vector of data/concept expressions (used in KE to return stuff) typedef KnowledgeExplorer::TCGItemVec TCGItemVec; protected: // types /// arguments for property chain querying and friends typedef const std::vector TExprVec; private: /// options for the kernel and all related substructures ifOptionSet KernelOptions; private: static const char* Version; static const char* SupportedDL; static const char* Copyright; static const char* ReleaseDate; /// header of the file with internal state; defined in SaveLoad.cpp static const char* InternalStateFileHeader; protected: // types /// enumeration for the cache enum cacheStatus { csEmpty, csSat, csClassified }; /// set of TreeNE /* class TreeNESet: public TNameSet { public: /// dirty hack for the LISP ontology printing template void fill ( T& x ) const { for ( const_iterator p = Base.begin(); p != Base.end(); ++p ) x.recordDataRole(p->second->getName()); } }; // TreeNESet */ protected: // members /// local TBox (to be created) TBox* pTBox; /// set of axioms TOntology Ontology; /// expression translator to work with queries TExpressionTranslator* pET; /// trace vector for the last operation (set from the TBox trace-sets) AxiomVec TraceVec; /// knowledge exploration support KnowledgeExplorer* KE; /// atomic decomposer AtomicDecomposer* AD; /// syntactic locality based module extractor TModularizer* ModSyn; /// semantic locality based module extractor TModularizer* ModSem; /// set to return by the locality checking procedure AxiomVec Result; /// JNI cache corresponding to a kernel. External, created and deleted outside TJNICache* JNICache; // Top/Bottom role names: if set, they will appear in all hierarchy-related output /// top object role name std::string TopORoleName; /// bottom object role name std::string BotORoleName; /// top data role name std::string TopDRoleName; /// bottom data role name std::string BotDRoleName; // values to propagate to the new KB in case of clearance /// progress monitor (if any) TProgressMonitor* pMonitor; /// timeout value unsigned long OpTimeout; /// tell reasoner to use verbose output bool verboseOutput; /// allow reasoner to use undefined names in queries bool useUndefinedNames; // reasoning cache /// cache level enum cacheStatus cacheLevel; /// cached query input description TConceptExpr* cachedQuery; /// cached query concept description DLTree* cachedQueryTree; /// cached concept (either defConcept or existing one) TConcept* cachedConcept; /// cached query result (taxonomy position) TaxonomyVertex* cachedVertex; // internal flags /// set if TBox throws an exception during preprocessing/classification bool reasoningFailed; /// flag to gather trace information for the next reasoner's call bool NeedTracing; /// whether axiom splitting should be used bool useAxiomSplitting; /// ignore cache for the TExpr* (useful for semantic AD) bool ignoreExprCache; private: // no copy /// no copy c'tor ReasoningKernel ( const ReasoningKernel& ); /// no assignment ReasoningKernel& operator = ( const ReasoningKernel& ); protected: // methods // register all necessary options in local option set bool initOptions ( void ); /// get status of the KB KBStatus getStatus ( void ) const { if ( pTBox == NULL ) return kbEmpty; // if the ontology is changed, it needs to be reclassified if ( Ontology.isChanged() ) return kbLoading; return pTBox->getStatus(); } /// process KB wrt STATUS void processKB ( KBStatus status ); /// get DLTree corresponding to an expression EXPR DLTree* e ( const TExpr* expr ) { fpp_assert ( pET != NULL ); expr->accept(*pET); return *pET; } /// get fresh filled depending of a type of R DLTree* getFreshFiller ( const TRole* R ) { if ( R->isDataRole() ) return getTBox()->getDataTypeCenter().getFreshDataType(); else return getTBox()->getFreshConcept(); } //----------------------------------------------------------------------------- //-- internal query cache manipulation //----------------------------------------------------------------------------- /// clear query cache void clearQueryCache ( void ) { cachedQuery = NULL; deleteTree(cachedQueryTree); cachedQueryTree = NULL; } /// set query cache value to QUERY void setQueryCache ( TConceptExpr* query ) { clearQueryCache(); cachedQuery = query; } /// set query cache value to QUERY void setQueryCache ( DLTree* query ) { clearQueryCache(); cachedQueryTree = query; } /// check whether query cache is the same as QUERY bool checkQueryCache ( TConceptExpr* query ) const { return ignoreExprCache ? false : cachedQuery == query; } /// check whether query cache is the same as QUERY bool checkQueryCache ( DLTree* query ) const { return equalTrees ( cachedQueryTree, query ); } /// classify query; cache is ready at the point. NAMED means whether concept is just a name void classifyQuery ( bool named ); /// set up cache for query, performing additional (re-)classification if necessary void setUpCache ( DLTree* query, cacheStatus level ); /// set up cache for query, performing additional (re-)classification if necessary void setUpCache ( TConceptExpr* query, cacheStatus level ); /// clear cache and flags void initCacheAndFlags ( void ) { cacheLevel = csEmpty; clearQueryCache(); cachedConcept = NULL; cachedVertex = NULL; reasoningFailed = false; NeedTracing = false; } /// build and set a cache for an individual I wrt role R CIVec buildRelatedCache ( TIndividual* I, const TRole* R ); /// get related cache for an individual I const CIVec& getRelated ( TIndividual* I, const TRole* R ) { if ( !I->hasRelatedCache(R) ) I->setRelatedCache ( R, buildRelatedCache ( I, R ) ); return I->getRelatedCache(R); } /// get role expression based on the R TDLRoleExpression* Role ( const TRole* R ) { if ( unlikely(R->isDataRole()) ) return getExpressionManager()->DataRole(R->getName()); else return getExpressionManager()->ObjectRole(R->getName()); } //----------------------------------------------------------------------------- //-- internal reasoning methods //----------------------------------------------------------------------------- /// @return true iff C is satisfiable bool checkSatTree ( DLTree* C ) { if ( unlikely(C->Element().getToken() == TOP) ) { deleteTree(C); return true; } if ( unlikely(C->Element().getToken() == BOTTOM) ) { deleteTree(C); return false; } setUpCache ( C, csSat ); return getTBox()->isSatisfiable(cachedConcept); } /// @return true iff C is satisfiable bool checkSat ( const TConceptExpr* C ) { setUpCache ( C, csSat ); return getTBox()->isSatisfiable(cachedConcept); } /// @return true iff C [= D holds bool checkSub ( TConcept* C, TConcept* D ); /// helper; @return true iff C is either named concept of Top/Bot static bool isNameOrConst ( const TConceptExpr* C ) { return likely ( dynamic_cast(C) != NULL ) || unlikely ( dynamic_cast(C) != NULL ) || unlikely ( dynamic_cast(C) != NULL ); } // helper methods to query properties of roles /// @return true if R is functional wrt ontology bool checkFunctionality ( TRole* R ) { // R is transitive iff \ER.C and \ER.\not C is unsatisfiable DLTree* tmp = createSNFExists ( createRole(R), createSNFNot(getFreshFiller(R)) ); tmp = createSNFAnd ( tmp, createSNFExists ( createRole(R), getFreshFiller(R) ) ); return !checkSatTree(tmp); } /// @return true if R is functional; set the value for R if necessary bool getFunctionality ( TRole* R ) { if ( !R->isFunctionalityKnown() ) // calculate functionality R->setFunctional(checkFunctionality(R)); return R->isFunctional(); } /// @return true if R is transitive wrt ontology bool checkTransitivity ( DLTree* R ) { // R is transitive iff \ER.\ER.C and \AR.\not C is unsatisfiable DLTree* tmp = createSNFExists ( clone(R), createSNFNot(getTBox()->getFreshConcept()) ); tmp = createSNFExists ( clone(R), tmp ); tmp = createSNFAnd ( tmp, createSNFForall ( R, getTBox()->getFreshConcept() ) ); return !checkSatTree(tmp); } /// @return true if R is symmetric wrt ontology bool checkSymmetry ( DLTree* R ) { // R is symmetric iff C and \ER.\AR.(not C) is unsatisfiable DLTree* tmp = createSNFForall ( clone(R), createSNFNot(getTBox()->getFreshConcept()) ); tmp = createSNFAnd ( getTBox()->getFreshConcept(), createSNFExists ( R, tmp ) ); return !checkSatTree(tmp); } /// @return true if R is reflexive wrt ontology bool checkReflexivity ( DLTree* R ) { // R is reflexive iff C and \AR.(not C) is unsatisfiable DLTree* tmp = createSNFForall ( R, createSNFNot(getTBox()->getFreshConcept()) ); tmp = createSNFAnd ( getTBox()->getFreshConcept(), tmp ); return !checkSatTree(tmp); } /// @return true if R [= S wrt ontology bool checkRoleSubsumption ( TRole* R, TRole* S ) { if ( unlikely ( R->isDataRole() != S->isDataRole() ) ) return false; // R [= S iff \ER.C and \AS.(not C) is unsatisfiable DLTree* tmp = createSNFForall ( createRole(S), createSNFNot(getFreshFiller(S)) ); tmp = createSNFAnd ( createSNFExists ( createRole(R), getFreshFiller(R) ), tmp ); return !checkSatTree(tmp); } /// @return true iff the chain contained in the arg-list is a sub-property of R bool checkSubChain ( const TExprVec& Chain, TRole* R ) { // R1 o ... o Rn [= R iff \ER1.\ER2....\ERn.(notC) and AR.C is unsatisfiable DLTree* tmp = createSNFNot(getTBox()->getFreshConcept()); for ( TExprVec::const_reverse_iterator p = Chain.rbegin(), p_end = Chain.rend(); p != p_end; ++p ) if ( TORoleExpr* Ri = dynamic_cast(*p) ) { TRole* S = getRole ( Ri, "Role expression expected in chain of isSubChain()" ); if ( unlikely(S->isBottom()) ) // bottom in a chain makes it super of any role { deleteTree(tmp); return true; } tmp = createSNFExists ( createRole(S), tmp ); } else throw EFaCTPlusPlus("Role expression expected in the role chain construct"); tmp = createSNFAnd ( tmp, createSNFForall ( createEntry(RNAME,R), getTBox()->getFreshConcept() ) ); return !checkSatTree(tmp); } // get access to internal structures /// @throw an exception if no TBox found void checkTBox ( void ) const { if ( pTBox == NULL ) throw EFaCTPlusPlus("FaCT++ Kernel: KB Not Initialised"); } /// get RW access to TBox TBox* getTBox ( void ) { checkTBox(); return pTBox; } /// get RO access to TBox const TBox* getTBox ( void ) const { checkTBox(); return pTBox; } /// clear TBox and related structures; keep ontology in place void clearTBox ( void ); /// get RW access to Object RoleMaster from TBox RoleMaster* getORM ( void ) { return getTBox()->getORM(); } /// get RO access to Object RoleMaster from TBox const RoleMaster* getORM ( void ) const { return getTBox()->getORM(); } /// get RW access to Data RoleMaster from TBox RoleMaster* getDRM ( void ) { return getTBox()->getDRM(); } /// get RO access to Data RoleMaster from TBox const RoleMaster* getDRM ( void ) const { return getTBox()->getDRM(); } /// get access to the concept hierarchy Taxonomy* getCTaxonomy ( void ) { if ( !isKBClassified() ) throw EFaCTPlusPlus("No access to concept taxonomy: ontology not classified"); return getTBox()->getTaxonomy(); } /// get access to the object role hierarchy Taxonomy* getORTaxonomy ( void ) { if ( !isKBPreprocessed() ) throw EFaCTPlusPlus("No access to the object role taxonomy: ontology not preprocessed"); return getORM()->getTaxonomy(); } /// get access to the data role hierarchy Taxonomy* getDRTaxonomy ( void ) { if ( !isKBPreprocessed() ) throw EFaCTPlusPlus("No access to the data role taxonomy: ontology not preprocessed"); return getDRM()->getTaxonomy(); } // transformation methods /// get individual by the TIndividualExpr TIndividual* getIndividual ( const TIndividualExpr* i, const char* reason ) { try { return static_cast(getTBox()->getCI(TreeDeleter(e(i)))); } catch(...) { throw EFaCTPlusPlus(reason); } } /// get role by the TRoleExpr TRole* getRole ( const TRoleExpr* r, const char* reason ) { try { return resolveRole(TreeDeleter(e(r))); } catch(...) { throw EFaCTPlusPlus(reason); } } /// get taxonomy of the property wrt it's name Taxonomy* getTaxonomy ( TRole* R ) { return R->isDataRole() ? getDRTaxonomy() : getORTaxonomy(); } /// get taxonomy vertex of the property wrt it's name TaxonomyVertex* getTaxVertex ( TRole* R ) { return R->getTaxVertex(); } /// try to perform the incremental reasoning on the changed ontology bool tryIncremental ( void ); /// force the re-classification of the changed ontology void forceReload ( void ); //---------------------------------------------- //-- save/load support; implementation in SaveLoad.cpp //---------------------------------------------- /// save the header of the kernel void SaveHeader ( std::ostream& o ) const; /// save the set of Kernel's options void SaveOptions ( std::ostream& o ) const; /// save the status of the KB and the appropriate part of KB void SaveKB ( std::ostream& o ) const; /// load the header for the kernel bool LoadHeader ( std::istream& i ); /// load the set of Kernel's options void LoadOptions ( std::istream& i ); /// load the status of the KB and the appropriate part of KB void LoadKB ( std::istream& i ); //---------------------------------------------------------------------------------- // knowledge exploration queries //---------------------------------------------------------------------------------- /// add the role R and all its supers to a set RESULT void addRoleWithSupers ( const TRole* R, TCGRoleSet& Result ); /// check whether the modularizer need initialisation, init it and return a proper one TModularizer* getModExtractor ( bool useSemantic ); public: // general staff /// default c'tor ReasoningKernel ( void ); /// d'tor ~ReasoningKernel ( void ); ifOptionSet* getOptions ( void ) { return &KernelOptions; } const ifOptionSet* getOptions ( void ) const { return &KernelOptions; } static const char* getVersion ( void ) { return Version; } /// return classification status of KB bool isKBPreprocessed ( void ) const { return getStatus() >= kbCChecked; } /// return classification status of KB bool isKBClassified ( void ) const { return getStatus() >= kbClassified; } /// return realistion status of KB bool isKBRealised ( void ) const { return getStatus() >= kbRealised; } /// set Progress monitor to control the classification process void setProgressMonitor ( TProgressMonitor* pMon ) { delete pMonitor; pMonitor = pMon; if ( pTBox != NULL ) pTBox->setProgressMonitor(pMon); } /// set verbose output (ie, concept and role taxonomies) wrt given VALUE void setVerboseOutput ( bool value ) { verboseOutput = value; if ( pTBox != NULL ) pTBox->setVerboseOutput(value); } /// (dis-)allow reasoner to use the undefined names in queries void setUseUndefinedNames ( bool value ) { useUndefinedNames = value; if ( pTBox != NULL ) pTBox->setUseUndefinedNames(value); } /// set top/bottom role names to use them in the related output void setTopBottomRoleNames ( const char* topORoleName, const char* botORoleName, const char* topDRoleName, const char* botDRoleName ) { TopORoleName = topORoleName; BotORoleName = botORoleName; TopDRoleName = topDRoleName; BotDRoleName = botDRoleName; // make sure expression manager knows the top/bot names Ontology.getExpressionManager()->setTopBottomRoles ( topORoleName, botORoleName,topDRoleName, botDRoleName ); } /// dump query processing TIME, reasoning statistics and a (preprocessed) TBox void writeReasoningResult ( std::ostream& o, float time ) { getTBox()->clearQueryConcept(); // get rid of the query leftovers getTBox()->writeReasoningResult ( o, time ); } /// set timeout value to VALUE void setOperationTimeout ( unsigned long value ) { OpTimeout = value; if ( pTBox != NULL ) pTBox->setTestTimeout(value); } /// choose whether axiom splitting should be used void setAxiomSplitting ( bool value ) { useAxiomSplitting = value; } /// choose whether TExpr cache should be ignored void setIgnoreExprCache ( bool value ) { ignoreExprCache = value; } /// set the signature of the expression translator void setSignature ( const TSignature* sig ) { if ( pET != NULL ) pET->setSignature(sig); } //---------------------------------------------- //-- Tracing support //---------------------------------------------- /// tells reasoner that the next reasoning operation shall gather the trace void needTracing ( void ) { NeedTracing = true; } /// @return the trace-set of the last reasoning operation const AxiomVec& getTrace ( void ) { TraceVec.clear(); return TraceVec; } //---------------------------------------------- //-- save/load interface; implementation in SaveLoad.cpp //---------------------------------------------- /// save internal state of the Kernel to a file NAME void Save ( std::ostream& o ) const; /// load internal state of the Kernel from a file NAME void Load ( std::istream& i ); /// save internal state of the Kernel to a file NAME void Save ( const char* name ) const; /// load internal state of the Kernel from a file NAME void Load ( const char* name ); /// get access to an expression manager TExpressionManager* getExpressionManager ( void ) { return Ontology.getExpressionManager(); } /// get RW access to the ontology TOntology& getOntology ( void ) { return Ontology; } /// get RO access to the ontology const TOntology& getOntology ( void ) const { return Ontology; } /// set JNI cache void setJNICache ( TJNICache* cache ) { JNICache = cache; } /// get JNI cache TJNICache* getJNICache ( void ) const { return JNICache; } public: //****************************************** //* KB Management //****************************************** /// create new KB bool newKB ( void ) { if ( pTBox != NULL ) return true; pTBox = new TBox ( getOptions(), TopORoleName, BotORoleName, TopDRoleName, BotDRoleName ); pTBox->setTestTimeout(OpTimeout); pTBox->setProgressMonitor(pMonitor); pTBox->setVerboseOutput(verboseOutput); pTBox->setUseUndefinedNames(useUndefinedNames); pET = new TExpressionTranslator(*pTBox); initCacheAndFlags(); return false; } /// delete existed KB bool releaseKB ( void ) { clearTBox(); Ontology.clear(); return false; } /// reset current KB bool clearKB ( void ) { if ( pTBox == NULL ) return true; return releaseKB () || newKB (); } //---------------------------------------------------- // TELLS interface //---------------------------------------------------- // Declaration axioms /// axiom declare(x) TDLAxiom* declare ( TExpr* C ) { return Ontology.add(new TDLAxiomDeclaration(C)); } // Concept axioms /// axiom C [= D TDLAxiom* impliesConcepts ( TConceptExpr* C, TConceptExpr* D ) { return Ontology.add ( new TDLAxiomConceptInclusion ( C, D ) ); } /// axiom C1 = ... = Cn TDLAxiom* equalConcepts ( void ) { return Ontology.add ( new TDLAxiomEquivalentConcepts(getExpressionManager()->getArgList()) ); } /// axiom C1 != ... != Cn TDLAxiom* disjointConcepts ( void ) { return Ontology.add ( new TDLAxiomDisjointConcepts(getExpressionManager()->getArgList()) ); } /// axiom C = C1 or ... or Cn; C1 != ... != Cn TDLAxiom* disjointUnion ( TConceptExpr* C ) { return Ontology.add ( new TDLAxiomDisjointUnion ( C, getExpressionManager()->getArgList() ) ); } // Role axioms /// R = Inverse(S) TDLAxiom* setInverseRoles ( TORoleExpr* R, TORoleExpr* S ) { return Ontology.add ( new TDLAxiomRoleInverse(R,S) ); } /// axiom (R [= S) TDLAxiom* impliesORoles ( TORoleComplexExpr* R, TORoleExpr* S ) { return Ontology.add ( new TDLAxiomORoleSubsumption ( R, S ) ); } /// axiom (R [= S) TDLAxiom* impliesDRoles ( TDRoleExpr* R, TDRoleExpr* S ) { return Ontology.add ( new TDLAxiomDRoleSubsumption ( R, S ) ); } /// axiom R1 = R2 = ... TDLAxiom* equalORoles ( void ) { return Ontology.add ( new TDLAxiomEquivalentORoles(getExpressionManager()->getArgList()) ); } /// axiom R1 = R2 = ... TDLAxiom* equalDRoles ( void ) { return Ontology.add ( new TDLAxiomEquivalentDRoles(getExpressionManager()->getArgList()) ); } /// axiom R1 != R2 != ... TDLAxiom* disjointORoles ( void ) { return Ontology.add ( new TDLAxiomDisjointORoles(getExpressionManager()->getArgList()) ); } /// axiom R1 != R2 != ... TDLAxiom* disjointDRoles ( void ) { return Ontology.add ( new TDLAxiomDisjointDRoles(getExpressionManager()->getArgList()) ); } /// Domain (R C) TDLAxiom* setODomain ( TORoleExpr* R, TConceptExpr* C ) { return Ontology.add ( new TDLAxiomORoleDomain ( R, C ) ); } /// Domain (R C) TDLAxiom* setDDomain ( TDRoleExpr* R, TConceptExpr* C ) { return Ontology.add ( new TDLAxiomDRoleDomain ( R, C ) ); } /// Range (R C) TDLAxiom* setORange ( TORoleExpr* R, TConceptExpr* C ) { return Ontology.add ( new TDLAxiomORoleRange ( R, C ) ); } /// Range (R E) TDLAxiom* setDRange ( TDRoleExpr* R, TDataExpr* E ) { return Ontology.add ( new TDLAxiomDRoleRange ( R, E ) ); } /// Transitive (R) TDLAxiom* setTransitive ( TORoleExpr* R ) { return Ontology.add ( new TDLAxiomRoleTransitive(R) ); } /// Reflexive (R) TDLAxiom* setReflexive ( TORoleExpr* R ) { return Ontology.add ( new TDLAxiomRoleReflexive(R) ); } /// Irreflexive (R): Domain(R) = \neg ER.Self TDLAxiom* setIrreflexive ( TORoleExpr* R ) { return Ontology.add ( new TDLAxiomRoleIrreflexive(R) ); } /// Symmetric (R): R [= R^- TDLAxiom* setSymmetric ( TORoleExpr* R ) { return Ontology.add ( new TDLAxiomRoleSymmetric(R) ); } /// Asymmetric (R): disjoint(R,R^-) TDLAxiom* setAsymmetric ( TORoleExpr* R ) { return Ontology.add ( new TDLAxiomRoleAsymmetric(R) ); } /// Functional (R) TDLAxiom* setOFunctional ( TORoleExpr* R ) { return Ontology.add ( new TDLAxiomORoleFunctional(R) ); } /// Functional (R) TDLAxiom* setDFunctional ( TDRoleExpr* R ) { return Ontology.add ( new TDLAxiomDRoleFunctional(R) ); } /// InverseFunctional (R) TDLAxiom* setInverseFunctional ( TORoleExpr* R ) { return Ontology.add ( new TDLAxiomRoleInverseFunctional(R) ); } // Individual axioms /// axiom I e C TDLAxiom* instanceOf ( TIndividualExpr* I, TConceptExpr* C ) { return Ontology.add ( new TDLAxiomInstanceOf(I,C) ); } /// axiom :R TDLAxiom* relatedTo ( TIndividualExpr* I, TORoleExpr* R, TIndividualExpr* J ) { return Ontology.add ( new TDLAxiomRelatedTo(I,R,J) ); } /// axiom :\neg R TDLAxiom* relatedToNot ( TIndividualExpr* I, TORoleExpr* R, TIndividualExpr* J ) { return Ontology.add ( new TDLAxiomRelatedToNot(I,R,J) ); } /// axiom (value I A V) TDLAxiom* valueOf ( TIndividualExpr* I, TDRoleExpr* A, TDataValueExpr* V ) { return Ontology.add ( new TDLAxiomValueOf(I,A,V) ); } /// axiom :\neg A TDLAxiom* valueOfNot ( TIndividualExpr* I, TDRoleExpr* A, TDataValueExpr* V ) { return Ontology.add ( new TDLAxiomValueOfNot(I,A,V) ); } /// same individuals TDLAxiom* processSame ( void ) { return Ontology.add ( new TDLAxiomSameIndividuals(getExpressionManager()->getArgList()) ); } /// different individuals TDLAxiom* processDifferent ( void ) { return Ontology.add ( new TDLAxiomDifferentIndividuals(getExpressionManager()->getArgList()) ); } /// let all concept expressions in the ArgQueue to be fairness constraints TDLAxiom* setFairnessConstraint ( void ) { return Ontology.add ( new TDLAxiomFairnessConstraint(getExpressionManager()->getArgList()) ); } /// retract an axiom void retract ( TDLAxiom* axiom ) { Ontology.retract(axiom); } //****************************************** //* ASK part //****************************************** /* * Before execution of any query the Kernel make sure that the KB is in an appropriate * state: Preprocessed, Classified or Realised. If the ontology was changed between asks, * incremental classification is performed and the corrected result is returned. */ /// return consistency status of KB bool isKBConsistent ( void ) { try { if ( getStatus() <= kbLoading ) processKB(kbCChecked); return getTBox()->isConsistent(); } catch ( const EFPPInconsistentKB& ) { return false; } } /// ensure that KB is preprocessed/consistence checked void preprocessKB ( void ) { if ( !isKBConsistent() ) throw EFPPInconsistentKB(); } /// ensure that KB is classified void classifyKB ( void ) { if ( !isKBClassified() ) processKB(kbClassified); if ( !isKBConsistent() ) throw EFPPInconsistentKB(); } /// ensure that KB is realised void realiseKB ( void ) { if ( !isKBRealised() ) processKB(kbRealised); if ( !isKBConsistent() ) throw EFPPInconsistentKB(); } // role info retrieval /// @return true iff object role is functional bool isFunctional ( const TORoleExpr* R ) { preprocessKB(); // ensure KB is ready to answer the query TRole* r = getRole ( R, "Role expression expected in isFunctional()" ); if ( unlikely(r->isTop()) ) return false; // universal role is not functional if ( unlikely(r->isBottom()) ) return true; // empty role is functional return getFunctionality(r); } /// @return true iff data role is functional bool isFunctional ( const TDRoleExpr* R ) { preprocessKB(); // ensure KB is ready to answer the query TRole* r = getRole ( R, "Role expression expected in isFunctional()" ); if ( unlikely(r->isTop()) ) return false; // universal role is not functional if ( unlikely(r->isBottom()) ) return true; // empty role is functional return getFunctionality(r); } /// @return true iff role is inverse-functional bool isInverseFunctional ( const TORoleExpr* R ) { preprocessKB(); // ensure KB is ready to answer the query TRole* r = getRole ( R, "Role expression expected in isInverseFunctional()" )->inverse(); if ( unlikely(r->isTop()) ) return false; // universal role is not functional if ( unlikely(r->isBottom()) ) return true; // empty role is functional return getFunctionality(r); } /// @return true iff role is transitive bool isTransitive ( const TORoleExpr* R ) { preprocessKB(); // ensure KB is ready to answer the query TRole* r = getRole ( R, "Role expression expected in isTransitive()" ); if ( unlikely(r->isTop()) ) return true; // universal role is transitive if ( unlikely(r->isBottom()) ) return true; // empty role is transitive if ( !r->isTransitivityKnown() ) // calculate transitivity r->setTransitive(checkTransitivity(e(R))); return r->isTransitive(); } /// @return true iff role is symmetric bool isSymmetric ( const TORoleExpr* R ) { preprocessKB(); // ensure KB is ready to answer the query TRole* r = getRole ( R, "Role expression expected in isSymmetric()" ); if ( unlikely(r->isTop()) ) return true; // universal role is symmetric if ( unlikely(r->isBottom()) ) return true; // empty role is symmetric if ( !r->isSymmetryKnown() ) // calculate symmetry r->setSymmetric(checkSymmetry(e(R))); return r->isSymmetric(); } /// @return true iff role is asymmetric bool isAsymmetric ( const TORoleExpr* R ) { preprocessKB(); // ensure KB is ready to answer the query TRole* r = getRole ( R, "Role expression expected in isAsymmetric()" ); if ( unlikely(r->isTop()) ) return false; // universal role is not asymmetric if ( unlikely(r->isBottom()) ) return true; // empty role is asymmetric if ( !r->isAsymmetryKnown() ) // calculate asymmetry r->setAsymmetric(getTBox()->isDisjointRoles(r,r->inverse())); return r->isAsymmetric(); } /// @return true iff role is reflexive bool isReflexive ( const TORoleExpr* R ) { preprocessKB(); // ensure KB is ready to answer the query TRole* r = getRole ( R, "Role expression expected in isReflexive()" ); if ( unlikely(r->isTop()) ) return true; // universal role is reflexive if ( unlikely(r->isBottom()) ) return false; // empty role is not reflexive if ( !r->isReflexivityKnown() ) // calculate reflexivity r->setReflexive(checkReflexivity(e(R))); return r->isReflexive(); } /// @return true iff role is irreflexive bool isIrreflexive ( const TORoleExpr* R ) { preprocessKB(); // ensure KB is ready to answer the query TRole* r = getRole ( R, "Role expression expected in isIrreflexive()" ); if ( unlikely(r->isTop()) ) return false; // universal role is not irreflexive if ( unlikely(r->isBottom()) ) return true; // empty role is irreflexive if ( !r->isIrreflexivityKnown() ) // calculate irreflexivity r->setIrreflexive(getTBox()->isIrreflexive(r)); return r->isIrreflexive(); } /// @return true if R is a sub-role of S bool isSubRoles ( const TORoleExpr* R, const TORoleExpr* S ) { preprocessKB(); // ensure KB is ready to answer the query TRole* r = getRole ( R, "Role expression expected in isSubRoles()" ); TRole* s = getRole ( S, "Role expression expected in isSubRoles()" ); if ( unlikely(r->isBottom()) || unlikely(s->isTop()) ) return true; // \bot [= X [= \top if ( unlikely(r->isTop()) && unlikely(s->isBottom()) ) return false; // as \top [= \bot leads to inconsistent ontology // told case first if ( likely(!r->isTop() && !s->isBottom()) ) { if ( *r <= *s ) return true; } // check the general case // FIXME!! cache it later return checkRoleSubsumption ( r, s ); } /// @return true if R is a sub-role of S bool isSubRoles ( const TDRoleExpr* R, const TDRoleExpr* S ) { preprocessKB(); // ensure KB is ready to answer the query TRole* r = getRole ( R, "Role expression expected in isSubRoles()" ); TRole* s = getRole ( S, "Role expression expected in isSubRoles()" ); if ( unlikely(r->isBottom()) || unlikely(s->isTop()) ) return true; // \bot [= X [= \top if ( unlikely(r->isTop()) && unlikely(s->isBottom()) ) return false; // as \top [= \bot leads to inconsistent ontology // told case first if ( likely(!r->isTop() && !s->isBottom()) ) { if ( *r <= *s ) return true; } // check the general case // FIXME!! cache it later return checkRoleSubsumption ( r, s ); } /// @return true iff two roles are disjoint bool isDisjointRoles ( const TORoleExpr* R, const TORoleExpr* S ) { preprocessKB(); // ensure KB is ready to answer the query TRole* r = getRole ( R, "Role expression expected in isDisjointRoles()" ); TRole* s = getRole ( S, "Role expression expected in isDisjointRoles()" ); if ( unlikely(r->isTop()) || unlikely(s->isTop()) ) return false; // universal role is not disjoint with anything if ( unlikely(r->isBottom()) || unlikely(s->isBottom()) ) return true; // empty role is disjoint with everything return getTBox()->isDisjointRoles ( r, s ); } /// @return true iff two roles are disjoint bool isDisjointRoles ( const TDRoleExpr* R, const TDRoleExpr* S ) { preprocessKB(); // ensure KB is ready to answer the query TRole* r = getRole ( R, "Role expression expected in isDisjointRoles()" ); TRole* s = getRole ( S, "Role expression expected in isDisjointRoles()" ); if ( unlikely(r->isTop()) || unlikely(s->isTop()) ) return false; // universal role is not disjoint with anything if ( unlikely(r->isBottom()) || unlikely(s->isBottom()) ) return true; // empty role is disjoint with everything return getTBox()->isDisjointRoles ( r, s ); } /// @return true iff all the roles in a arg-list are pairwise disjoint bool isDisjointRoles ( void ); /// @return true if R is a super-role of a chain holding in the args bool isSubChain ( const TORoleExpr* R ) { preprocessKB(); // ensure KB is ready to answer the query TRole* r = getRole ( R, "Role expression expected in isSubChain()" ); if ( unlikely(r->isTop()) ) return true; // universal role is a super of any chain return checkSubChain ( getExpressionManager()->getArgList(), r ); } // single satisfiability /// @return true iff C is satisfiable bool isSatisfiable ( const TConceptExpr* C ) { preprocessKB(); try { return checkSat(C); } catch ( const EFPPCantRegName& crn ) { if ( dynamic_cast(C) != NULL ) // this is an unknown concept return true; // complex expression, involving unknown names throw crn; } } /// @return true iff C [= D holds bool isSubsumedBy ( const TConceptExpr* C, const TConceptExpr* D ) { preprocessKB(); if ( isNameOrConst(D) && likely(isNameOrConst(C)) ) return checkSub ( getTBox()->getCI(TreeDeleter(e(C))), getTBox()->getCI(TreeDeleter(e(D))) ); DLTree* nD = createSNFNot(e(D)); return !checkSatTree ( createSNFAnd (e(C), nD) ); } /// @return true iff C is disjoint with D; that is, (C and D) is unsatisfiable bool isDisjoint ( const TConceptExpr* C, const TConceptExpr* D ) { return !isSatisfiable(getExpressionManager()->And(C,D)); } /// @return true iff C is equivalent to D bool isEquivalent ( const TConceptExpr* C, const TConceptExpr* D ) { if ( C == D ) // easy case return true; preprocessKB(); if ( isKBClassified() ) { // try to detect C=D wrt named concepts if ( isNameOrConst(D) && likely(isNameOrConst(C)) ) { const TaxonomyVertex* cV = getTBox()->getCI(TreeDeleter(e(C)))->getTaxVertex(); const TaxonomyVertex* dV = getTBox()->getCI(TreeDeleter(e(D)))->getTaxVertex(); if ( unlikely(cV == NULL) && unlikely(dV == NULL) ) return false; // 2 different fresh names return cV == dV; } } // not classified or not named constants return isSubsumedBy ( C, D ) && isSubsumedBy ( D, C ); } // concept hierarchy /// apply actor::apply() to all DIRECT super-concepts of [complex] C template void getSupConcepts ( const TConceptExpr* C, bool direct, Actor& actor ) { classifyKB(); // ensure KB is ready to answer the query setUpCache ( C, csClassified ); Taxonomy* tax = getCTaxonomy(); if ( direct ) tax->getRelativesInfo ( cachedVertex, actor ); else tax->getRelativesInfo ( cachedVertex, actor ); } /// apply actor::apply() to all DIRECT sub-concepts of [complex] C template void getSubConcepts ( const TConceptExpr* C, bool direct, Actor& actor ) { classifyKB(); // ensure KB is ready to answer the query setUpCache ( C, csClassified ); Taxonomy* tax = getCTaxonomy(); if ( direct ) tax->getRelativesInfo ( cachedVertex, actor ); else tax->getRelativesInfo ( cachedVertex, actor ); } /// apply actor::apply() to all synonyms of [complex] C template void getEquivalentConcepts ( const TConceptExpr* C, Actor& actor ) { classifyKB(); // ensure KB is ready to answer the query setUpCache ( C, csClassified ); actor.apply(*cachedVertex); } /// apply actor::apply() to all named concepts disjoint with [complex] C template void getDisjointConcepts ( const TConceptExpr* C, Actor& actor ) { classifyKB(); // ensure KB is ready to answer the query setUpCache ( getExpressionManager()->Not(C), csClassified ); Taxonomy* tax = getCTaxonomy(); // we are looking for all sub-concepts of (not C) (including synonyms to it) tax->getRelativesInfo ( cachedVertex, actor ); } // role hierarchy /// apply actor::apply() to all DIRECT super-roles of [complex] R template void getSupRoles ( const TRoleExpr* r, bool direct, Actor& actor ) { preprocessKB(); // ensure KB is ready to answer the query TRole* R = getRole ( r, "Role expression expected in getSupRoles()" ); Taxonomy* tax = getTaxonomy(R); if ( direct ) tax->getRelativesInfo ( getTaxVertex(R), actor ); else tax->getRelativesInfo ( getTaxVertex(R), actor ); } /// apply actor::apply() to all DIRECT sub-roles of [complex] R template void getSubRoles ( const TRoleExpr* r, bool direct, Actor& actor ) { preprocessKB(); // ensure KB is ready to answer the query TRole* R = getRole ( r, "Role expression expected in getSubRoles()" ); Taxonomy* tax = getTaxonomy(R); if ( direct ) tax->getRelativesInfo ( getTaxVertex(R), actor ); else tax->getRelativesInfo ( getTaxVertex(R), actor ); } /// apply actor::apply() to all synonyms of [complex] R template void getEquivalentRoles ( const TRoleExpr* r, Actor& actor ) { preprocessKB(); // ensure KB is ready to answer the query TRole* R = getRole ( r, "Role expression expected in getEquivalentRoles()" ); actor.apply(*getTaxVertex(R)); } // domain and range as a set of named concepts /// apply actor::apply() to all DIRECT NC that are in the domain of [complex] object role R template void getORoleDomain ( const TORoleExpr* r, bool direct, Actor& actor ) { classifyKB(); // ensure KB is ready to answer the query setUpCache ( getExpressionManager()->Exists ( r, getExpressionManager()->Top() ), csClassified ); Taxonomy* tax = getCTaxonomy(); if ( direct ) // gets an exact domain is named concept; otherwise, set of the most specific concepts tax->getRelativesInfo ( cachedVertex, actor ); else // gets all named classes that are in the domain of a role tax->getRelativesInfo ( cachedVertex, actor ); } /// apply actor::apply() to all DIRECT NC that are in the domain of data role R template void getDRoleDomain ( const TDRoleExpr* r, bool direct, Actor& actor ) { classifyKB(); // ensure KB is ready to answer the query setUpCache ( getExpressionManager()->Exists ( r, getExpressionManager()->DataTop() ), csClassified ); Taxonomy* tax = getCTaxonomy(); if ( direct ) // gets an exact domain is named concept; otherwise, set of the most specific concepts tax->getRelativesInfo ( cachedVertex, actor ); else // gets all named classes that are in the domain of a role tax->getRelativesInfo ( cachedVertex, actor ); } /// apply actor::apply() to all DIRECT NC that are in the range of [complex] R template void getRoleRange ( const TORoleExpr* r, bool direct, Actor& actor ) { getORoleDomain ( getExpressionManager()->Inverse(r), direct, actor ); } // instances /// apply actor::apply() to all direct instances of given [complex] C template void getDirectInstances ( const TConceptExpr* C, Actor& actor ) { realiseKB(); // ensure KB is ready to answer the query setUpCache ( C, csClassified ); // implement 1-level check by hand // if the root vertex contains individuals -- we are done if ( actor.apply(*cachedVertex) ) return; // if not, just go 1 level down and apply the actor regardless of what's found // FIXME!! check again after bucket-method will be implemented for ( TaxonomyVertex::iterator p = cachedVertex->begin(/*upDirection=*/false), p_end = cachedVertex->end(/*upDirection=*/false); p != p_end; ++p ) actor.apply(**p); } /// apply actor::apply() to all instances of given [complex] C template void getInstances ( const TConceptExpr* C, Actor& actor ) { // FIXME!! check for Racer's/IS approach realiseKB(); // ensure KB is ready to answer the query setUpCache ( C, csClassified ); Taxonomy* tax = getCTaxonomy(); tax->getRelativesInfo ( cachedVertex, actor ); } /// apply actor::apply() to all DIRECT concepts that are types of an individual I template void getTypes ( const TIndividualExpr* I, bool direct, Actor& actor ) { realiseKB(); // ensure KB is ready to answer the query setUpCache ( getExpressionManager()->OneOf(I), csClassified ); Taxonomy* tax = getCTaxonomy(); if ( direct ) tax->getRelativesInfo ( cachedVertex, actor ); else tax->getRelativesInfo ( cachedVertex, actor ); } /// apply actor::apply() to all synonyms of an individual I template void getSameAs ( const TIndividualExpr* I, Actor& actor ) { realiseKB(); // ensure KB is ready to answer the query getEquivalentConcepts ( getExpressionManager()->OneOf(I), actor ); } /// @return true iff I and J refer to the same individual bool isSameIndividuals ( const TIndividualExpr* I, const TIndividualExpr* J ) { realiseKB(); TIndividual* i = getIndividual ( I, "Only known individuals are allowed in the isSameAs()" ); TIndividual* j = getIndividual ( J, "Only known individuals are allowed in the isSameAs()" ); return getTBox()->isSameIndividuals(i,j); } /// @return true iff individual I is instance of given [complex] C bool isInstance ( const TIndividualExpr* I, const TConceptExpr* C ) { realiseKB(); // ensure KB is ready to answer the query getIndividual ( I, "individual name expected in the isInstance()" ); // FIXME!! this way a new concept is created; could be done more optimal return isSubsumedBy ( getExpressionManager()->OneOf(I), C ); } /// @return in Rs all (DATA)-roles R s.t. (I,x):R; add inverses if NEEDI is true void getRelatedRoles ( const TIndividualExpr* I, NamesVector& Rs, bool data, bool needI ); /// set RESULT into set of J's such that R(I,J) void getRoleFillers ( const TIndividualExpr* I, const TORoleExpr* R, IndividualSet& Result ); /// set RESULT into set of J's such that R(I,J) bool isRelated ( const TIndividualExpr* I, const TORoleExpr* R, const TIndividualExpr* J ); //---------------------------------------------------------------------------------- // knowledge exploration queries //---------------------------------------------------------------------------------- /// build a completion tree for a concept expression C (no caching as it breaks the idea of KE). @return the root node const TCGNode* buildCompletionTree ( const TConceptExpr* C ) { preprocessKB(); setUpCache ( C, csSat ); const TCGNode* ret = getTBox()->buildCompletionTree(cachedConcept); if ( KE == NULL ) // init KB after the sat test to reduce the number of DAG adjustments KE = new KnowledgeExplorer ( getTBox(), getExpressionManager() ); return ret; } /// build the set of data neighbours of a NODE, put the set of data roles into the RESULT variable void getDataRoles ( const TCGNode* node, TCGRoleSet& Result, bool onlyDet ) { Result = KE->getDataRoles ( node, onlyDet ); } /// build the set of object neighbours of a NODE, put the set of object roles and inverses into the RESULT variable void getObjectRoles ( const TCGNode* node, TCGRoleSet& Result, bool onlyDet, bool needIncoming ) { Result = KE->getObjectRoles ( node, onlyDet, needIncoming ); } /// build the set of neighbours of a NODE via role ROLE; put the resulting list into RESULT void getNeighbours ( const TCGNode* node, TRoleExpr* role, TCGNodeVec& Result ) { Result = KE->getNeighbours ( node, getRole ( role, "Role expression expected in getNeighbours() method" ) ); } /// put into RESULT all the expressions from the NODE label; if ONLYDET is true, return only deterministic elements void getLabel ( const TCGNode* node, TCGItemVec& Result, bool onlyDet ) { Result = KE->getLabel ( node, onlyDet ); } //---------------------------------------------------------------------------------- // atomic decomposition queries //---------------------------------------------------------------------------------- /// create new atomic decomposition of the loaded ontology using TYPE. @return size of the AD unsigned int getAtomicDecompositionSize ( bool useSemantic, ModuleType moduleType ); /// get a set of axioms that corresponds to the atom with the id INDEX const TOntologyAtom::AxiomSet& getAtomAxioms ( unsigned int index ) const; /// get a set of axioms that corresponds to the module of the atom with the id INDEX const TOntologyAtom::AxiomSet& getAtomModule ( unsigned int index ) const; /// get a set of atoms on which atom with index INDEX depends const TOntologyAtom::AtomSet& getAtomDependents ( unsigned int index ) const; //---------------------------------------------------------------------------------- // modularity queries //---------------------------------------------------------------------------------- /// get a set of axioms that corresponds to the atom with the id INDEX const AxiomVec& getModule ( bool useSemantic, ModuleType moduleType ); /// get a set of axioms that corresponds to the atom with the id INDEX const AxiomVec& getNonLocal ( bool useSemantic, ModuleType moduleType ); }; // ReasoningKernel #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/tNamedEntry.h0000644000000000000000000000463412112642405017766 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2011 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef TNAMEDENTRY_H #define TNAMEDENTRY_H #include #include #include "flags.h" //#include "SmallObj.h" class TNamedEntity; class TNamedEntry: public Flags//: public Loki::SmallObject<> { private: // no copy /// copy c'tor (unimplemented) TNamedEntry ( const TNamedEntry& ); /// assignment (unimplemented) TNamedEntry& operator = ( const TNamedEntry& ); protected: // members /// name of the entry std::string extName; /// entry identifier int extId; /// original entity const TNamedEntity* entity; public: // interface /// the only c'tor explicit TNamedEntry ( const std::string& name ) : extName (name) // copy name , extId (0) // sets local id , entity(NULL) {} /// empty d'tor virtual ~TNamedEntry ( void ) {} /// gets name of given entry const char* getName ( void ) const { return extName.c_str(); } /// set internal ID void setId ( int id ) { extId = id; } /// get internal ID int getId ( void ) const { return extId; } /// set entity void setEntity ( const TNamedEntity* e ) { entity = e; } /// get entity const TNamedEntity* getEntity ( void ) const { return entity; } /// register a System flag FPP_ADD_FLAG(System,0x1); // hierarchy interface /// register a Top-of-the-hierarchy flag FPP_ADD_FLAG(Top,0x1000); /// register a Bottom-of-the-hierarchy flag FPP_ADD_FLAG(Bottom,0x2000); virtual void Print ( std::ostream& o ) const { o << getName (); } // save/load interface; implementation is in SaveLoad.cpp /// save entry virtual void Save ( std::ostream& o ) const; /// load entry virtual void Load ( std::istream& i ); }; // TNamedEntry #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/tAxiom.h0000644000000000000000000002255112112642405016773 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2010 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef TAXIOM_H #define TAXIOM_H #include #include "globaldef.h" #include "dltree.h" #include "tConcept.h" #include "tRole.h" #include "counter.h" // uncomment this to have absorption debug messages //#define RKG_DEBUG_ABSORPTION class TBox; // statistical counters lives here namespace Stat { class SAbsRepCN: public counter {}; class SAbsRepForall: public counter {}; class SAbsSplit: public counter {}; class SAbsBApply: public counter {}; class SAbsTApply: public counter {}; class SAbsCApply: public counter {}; class SAbsCAttempt: public counter {}; class SAbsNApply: public counter {}; class SAbsNAttempt: public counter {}; class SAbsRApply: public counter {}; class SAbsRAttempt: public counter {}; } // NS for different DLTree matchers for trees in axiom namespace InAx { /// build an RW concept from a given [C|I]NAME-rooted DLTree inline TConcept* getConcept ( DLTree* p ) { return static_cast(p->Element().getNE()); } /// build an RO concept from a given [C|I]NAME-rooted DLTree inline const TConcept* getConcept ( const DLTree* p ) { return static_cast(p->Element().getNE()); } /// @return true iff P is a TOP inline bool isTop ( const DLTree* p ) { return p->Element() == BOTTOM; } /// @return true iff P is a BOTTOM inline bool isBot ( const DLTree* p ) { return p->Element() == TOP; } /// @return true iff P is a positive concept name inline bool isPosCN ( const DLTree* p ) { return p->Element() == NOT && isName(p->Left()); } /// @return true iff P is a positive non-primitive CN inline bool isPosNP ( const DLTree* p ) { return isPosCN(p) && !getConcept(p->Left())->isPrimitive(); } /// @return true iff P is a positive primitive CN inline bool isPosPC ( const DLTree* p ) { return isPosCN(p) && getConcept(p->Left())->isPrimitive(); } /// @return true iff P is a negative concept name inline bool isNegCN ( const DLTree* p ) { return isName(p); } /// @return true iff P is a negative non-primitive CN inline bool isNegNP ( const DLTree* p ) { return isNegCN(p) && !getConcept(p)->isPrimitive(); } /// @return true iff P is a negative primitive CN inline bool isNegPC ( const DLTree* p ) { return isNegCN(p) && getConcept(p)->isPrimitive(); } /// @return true iff P is an AND expression inline bool isAnd ( const DLTree* p ) { return p->Element() == NOT && p->Left()->Element() == AND; } /// @return true iff P is an OR expression inline bool isOr ( const DLTree* p ) { return p->Element() == AND; } /// @return true iff P is a general FORALL expression inline bool isForall ( const DLTree* p ) { return p->Element() == NOT && p->Left()->Element() == FORALL; } /// @return true iff P is an object FORALL expression inline bool isOForall ( const DLTree* p ) { return isForall(p) && !resolveRole(p->Left()->Left())->isDataRole(); } /// @return true iff P is a FORALL expression suitable for absorption inline bool isAbsForall ( const DLTree* p ) { if ( !isOForall(p) ) return false; const DLTree* C = p->Left()->Right(); if ( isTop(C) ) // no sense to replace \AR.BOTTOM as it well lead to the same GCI return false; return !isName(C) || !getConcept(C)->isSystem(); } } // InAx class TAxiom { private: // no assignment TAxiom& operator = ( const TAxiom& ax ); protected: // types /// type for axiom's representation, suitable for absorption typedef std::vector absorptionSet; /// RW iterator for the elements of GCI typedef absorptionSet::iterator iterator; /// RO iterator for the elements of GCI typedef absorptionSet::const_iterator const_iterator; /// set of iterators to work with typedef absorptionSet WorkSet; protected: // members /// GCI is presented in the form (or Disjuncts); absorptionSet Disjuncts; protected: // methods // access to labels /// RW begin iterator begin ( void ) { return Disjuncts.begin(); } /// RW end iterator end ( void ) { return Disjuncts.end(); } /// RO begin const_iterator begin ( void ) const { return Disjuncts.begin(); } /// RO end const_iterator end ( void ) const { return Disjuncts.end(); } /// create a copy of a given GCI; ignore SKIP entry TAxiom* copy ( const DLTree* skip ) const { TAxiom* ret = new TAxiom(); for ( const_iterator i = begin(), i_end = end(); i != i_end; ++i ) if ( *i != skip ) ret->Disjuncts.push_back(clone(*i)); return ret; } // single disjunct's optimisations /// simplify (OR C ...) for a non-primitive C in a given position TAxiom* simplifyPosNP ( const DLTree* rep ) const { Stat::SAbsRepCN(); TAxiom* ret = copy(rep); ret->add(createSNFNot(clone(InAx::getConcept(rep->Left())->Description))); # ifdef RKG_DEBUG_ABSORPTION std::cout << " simplify CN expression for" << rep->Left(); # endif return ret; } /// simplify (OR ~C ...) for a non-primitive C in a given position TAxiom* simplifyNegNP ( const DLTree* rep ) const { Stat::SAbsRepCN(); TAxiom* ret = copy(rep); ret->add(clone(InAx::getConcept(rep)->Description)); # ifdef RKG_DEBUG_ABSORPTION std::cout << " simplify ~CN expression for" << rep; # endif return ret; } /// simplify (OR (SOME R C) ...)) in a given position TAxiom* simplifyForall ( const DLTree* rep, TBox& KB ) const; /// split (OR (AND...) ...) in a given position void split ( std::vector& acc, const DLTree* rep, DLTree* pAnd ) const { if ( pAnd->Element().getToken() == AND ) { // split the AND split ( acc, rep, pAnd->Left() ); split ( acc, rep, pAnd->Right() ); } else { TAxiom* ret = copy(rep); ret->add(createSNFNot(clone(pAnd))); acc.push_back(ret); } } /// create a concept expression corresponding to a given GCI; ignore SKIP entry DLTree* createAnAxiom ( const DLTree* skip ) const; public: // interface /// create an empty GCI TAxiom ( void ) {} /// create a copy of a given GCI TAxiom ( const TAxiom& ax ) { for ( const_iterator i = ax.begin(), i_end = ax.end(); i != i_end; ++i ) Disjuncts.push_back(clone(*i)); } /// d'tor: delete elements if AX is not in use ~TAxiom ( void ) { for ( iterator i = begin(), i_end = end(); i != i_end; ++i ) deleteTree(*i); } /// add DLTree to an axiom void add ( DLTree* p ); /// check whether 2 axioms are the same bool operator == ( const TAxiom& ax ) const { # ifdef RKG_DEBUG_ABSORPTION // std::cout << "\n comparing "; dump(std::cout); // std::cout << " with "; ax.dump(std::cout); # endif if ( Disjuncts.size() != ax.Disjuncts.size() ) { # ifdef RKG_DEBUG_ABSORPTION // std::cout << " different size"; # endif return false; } const_iterator p = begin(), q = ax.begin(), p_end = end(); for ( ; p != p_end; ++p, ++q ) if ( !equalTrees(*p,*q) ) { # ifdef RKG_DEBUG_ABSORPTION // std::cout << " different tree:" << *p << " vs" << *q; # endif return false; } # ifdef RKG_DEBUG_ABSORPTION // std::cout << " equal!"; # endif return true; } /// replace a defined concept with its description TAxiom* simplifyCN ( void ) const; /// replace a universal restriction with a fresh concept TAxiom* simplifyForall ( TBox& KB ) const; /// split an axiom; @return new axiom and/or NULL bool split ( std::vector& acc ) const { acc.clear(); for ( const_iterator p = begin(), p_end = end(); p != p_end; ++p ) if ( InAx::isAnd(*p) ) { Stat::SAbsSplit(); # ifdef RKG_DEBUG_ABSORPTION std::cout << " split AND expression" << (*p)->Left(); # endif split ( acc, *p, (*p)->Left() ); // no need to split more than once: // every extra splits would be together with unsplitted parts // like: (A or B) and (C or D) would be transform into // A and (C or D), B and (C or D), (A or B) and C, (A or B) and D // so just return here return true; } return false; } /// absorb into BOTTOM; @return true if absorption is performed bool absorbIntoBottom ( void ) const; /// absorb into TOP; @return true if absorption is performed bool absorbIntoTop ( TBox& KB ) const; /// absorb into concept; @return true if absorption is performed bool absorbIntoConcept ( TBox& KB ) const; /// absorb into negation of a concept; @return true if absorption is performed bool absorbIntoNegConcept ( TBox& KB ) const; /// absorb into role domain; @return true if absorption is performed bool absorbIntoDomain ( void ) const; /// create a concept expression corresponding to a given GCI DLTree* createAnAxiom ( void ) const { return createAnAxiom(NULL); } #ifdef RKG_DEBUG_ABSORPTION /// dump GCI for debug purposes void dump ( std::ostream& o ) const; #endif }; // TAxiom; #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/tDLAxiom.cpp0000644000000000000000000000216712112642405017547 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2011 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "tDLAxiom.h" #include "tSignature.h" #include "tOntology.h" #include "tSignatureUpdater.h" /// d'tor: delete signature if it was created TDLAxiom :: ~TDLAxiom ( void ) { delete sig; } /// build signature of an axiom void TDLAxiom :: buildSignature ( void ) { sig = new TSignature(); TSignatureUpdater Updater(*sig); accept(Updater); } FaCTpp-src-v1.6.2~dfsg/src/Kernel/SearchableStack.h0000644000000000000000000000510612112642405020546 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2009 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef _SEARCHABLESTACK_H #define _SEARCHABLESTACK_H // template class for stack with opportunity of search duplicate elements #include template class SearchableStack { protected: std::vector Base; public: // from vector.h typedef T value_type; typedef typename std::vector::pointer pointer; typedef typename std::vector::const_pointer const_pointer; typedef typename std::vector::iterator iterator; typedef typename std::vector::const_iterator const_iterator; typedef typename std::vector::reference reference; typedef typename std::vector::const_reference const_reference; public: /*********** constructors **************/ SearchableStack ( void ) {} SearchableStack ( const SearchableStack& v ) : Base (v.Base) {} SearchableStack& operator = ( const SearchableStack& v ) { Base = v.Base; return *this; } /*********** iterators **************/ iterator begin() { return Base.begin(); } const_iterator begin() const { return Base.begin(); } iterator end() { return Base.end(); } const_iterator end() const { return Base.end(); } /*********** stack operations **************/ void push ( const T& val ) { Base.push_back(val); } reference top ( void ) { return Base.back(); } const_reference top ( void ) const { return Base.back(); } void pop ( void ) { Base.pop_back(); } /* iterator find ( const T& val ) const { for ( iterator p = begin(); p != end(); ++p ) if ( *p == val ) return p; return end(); }*/ const_iterator find ( const T& val ) const { for ( const_iterator p = begin(); p != end(); ++p ) if ( *p == val ) return p; return end(); } bool contains ( const T& val ) const { return ( find(val) != end() ); } bool empty ( void ) const { return Base.empty (); } }; // SearchableStack #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/tDLAxiom.h0000644000000000000000000010441012112642405017206 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2008-2012 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef TDLAXIOM_H #define TDLAXIOM_H #include "tDLExpression.h" // forward declaration for all axiom classes: necessary for the visitor pattern class TDLAxiomDeclaration; class TDLAxiomEquivalentConcepts; class TDLAxiomDisjointConcepts; class TDLAxiomDisjointUnion; class TDLAxiomEquivalentORoles; class TDLAxiomEquivalentDRoles; class TDLAxiomDisjointORoles; class TDLAxiomDisjointDRoles; class TDLAxiomSameIndividuals; class TDLAxiomDifferentIndividuals; class TDLAxiomFairnessConstraint; class TDLAxiomRoleInverse; class TDLAxiomORoleSubsumption; class TDLAxiomDRoleSubsumption; class TDLAxiomORoleDomain; class TDLAxiomDRoleDomain; class TDLAxiomORoleRange; class TDLAxiomDRoleRange; class TDLAxiomRoleTransitive; class TDLAxiomRoleReflexive; class TDLAxiomRoleIrreflexive; class TDLAxiomRoleSymmetric; class TDLAxiomRoleAsymmetric; class TDLAxiomORoleFunctional; class TDLAxiomDRoleFunctional; class TDLAxiomRoleInverseFunctional; class TDLAxiomConceptInclusion; class TDLAxiomInstanceOf; class TDLAxiomRelatedTo; class TDLAxiomRelatedToNot; class TDLAxiomValueOf; class TDLAxiomValueOfNot; class TOntology; /// general visitor for DL axioms class DLAxiomVisitor { public: // visitor interface virtual void visit ( const TDLAxiomDeclaration& axiom ) = 0; virtual void visit ( const TDLAxiomEquivalentConcepts& axiom ) = 0; virtual void visit ( const TDLAxiomDisjointConcepts& axiom ) = 0; virtual void visit ( const TDLAxiomDisjointUnion& axiom ) = 0; virtual void visit ( const TDLAxiomEquivalentORoles& axiom ) = 0; virtual void visit ( const TDLAxiomEquivalentDRoles& axiom ) = 0; virtual void visit ( const TDLAxiomDisjointORoles& axiom ) = 0; virtual void visit ( const TDLAxiomDisjointDRoles& axiom ) = 0; virtual void visit ( const TDLAxiomSameIndividuals& axiom ) = 0; virtual void visit ( const TDLAxiomDifferentIndividuals& axiom ) = 0; virtual void visit ( const TDLAxiomFairnessConstraint& axiom ) = 0; virtual void visit ( const TDLAxiomRoleInverse& axiom ) = 0; virtual void visit ( const TDLAxiomORoleSubsumption& axiom ) = 0; virtual void visit ( const TDLAxiomDRoleSubsumption& axiom ) = 0; virtual void visit ( const TDLAxiomORoleDomain& axiom ) = 0; virtual void visit ( const TDLAxiomDRoleDomain& axiom ) = 0; virtual void visit ( const TDLAxiomORoleRange& axiom ) = 0; virtual void visit ( const TDLAxiomDRoleRange& axiom ) = 0; virtual void visit ( const TDLAxiomRoleTransitive& axiom ) = 0; virtual void visit ( const TDLAxiomRoleReflexive& axiom ) = 0; virtual void visit ( const TDLAxiomRoleIrreflexive& axiom ) = 0; virtual void visit ( const TDLAxiomRoleSymmetric& axiom ) = 0; virtual void visit ( const TDLAxiomRoleAsymmetric& axiom ) = 0; virtual void visit ( const TDLAxiomORoleFunctional& axiom ) = 0; virtual void visit ( const TDLAxiomDRoleFunctional& axiom ) = 0; virtual void visit ( const TDLAxiomRoleInverseFunctional& axiom ) = 0; virtual void visit ( const TDLAxiomConceptInclusion& axiom ) = 0; virtual void visit ( const TDLAxiomInstanceOf& axiom ) = 0; virtual void visit ( const TDLAxiomRelatedTo& axiom ) = 0; virtual void visit ( const TDLAxiomRelatedToNot& axiom ) = 0; virtual void visit ( const TDLAxiomValueOf& axiom ) = 0; virtual void visit ( const TDLAxiomValueOfNot& axiom ) = 0; virtual void visitOntology ( TOntology& ontology ) = 0; virtual ~DLAxiomVisitor ( void ) {} }; // DLAxiomVisitor /// empty implementation of DL axioms visitor class DLAxiomVisitorEmpty: public DLAxiomVisitor { public: // visitor interface virtual void visit ( const TDLAxiomDeclaration& axiom ATTR_UNUSED ) {} virtual void visit ( const TDLAxiomEquivalentConcepts& axiom ATTR_UNUSED ) {} virtual void visit ( const TDLAxiomDisjointConcepts& axiom ATTR_UNUSED ) {} virtual void visit ( const TDLAxiomDisjointUnion& axiom ATTR_UNUSED ) {} virtual void visit ( const TDLAxiomEquivalentORoles& axiom ATTR_UNUSED ) {} virtual void visit ( const TDLAxiomEquivalentDRoles& axiom ATTR_UNUSED ) {} virtual void visit ( const TDLAxiomDisjointORoles& axiom ATTR_UNUSED ) {} virtual void visit ( const TDLAxiomDisjointDRoles& axiom ATTR_UNUSED ) {} virtual void visit ( const TDLAxiomSameIndividuals& axiom ATTR_UNUSED ) {} virtual void visit ( const TDLAxiomDifferentIndividuals& axiom ATTR_UNUSED ) {} virtual void visit ( const TDLAxiomFairnessConstraint& axiom ATTR_UNUSED ) {} virtual void visit ( const TDLAxiomRoleInverse& axiom ATTR_UNUSED ) {} virtual void visit ( const TDLAxiomORoleSubsumption& axiom ATTR_UNUSED ) {} virtual void visit ( const TDLAxiomDRoleSubsumption& axiom ATTR_UNUSED ) {} virtual void visit ( const TDLAxiomORoleDomain& axiom ATTR_UNUSED ) {} virtual void visit ( const TDLAxiomDRoleDomain& axiom ATTR_UNUSED ) {} virtual void visit ( const TDLAxiomORoleRange& axiom ATTR_UNUSED ) {} virtual void visit ( const TDLAxiomDRoleRange& axiom ATTR_UNUSED ) {} virtual void visit ( const TDLAxiomRoleTransitive& axiom ATTR_UNUSED ) {} virtual void visit ( const TDLAxiomRoleReflexive& axiom ATTR_UNUSED ) {} virtual void visit ( const TDLAxiomRoleIrreflexive& axiom ATTR_UNUSED ) {} virtual void visit ( const TDLAxiomRoleSymmetric& axiom ATTR_UNUSED ) {} virtual void visit ( const TDLAxiomRoleAsymmetric& axiom ATTR_UNUSED ) {} virtual void visit ( const TDLAxiomORoleFunctional& axiom ATTR_UNUSED ) {} virtual void visit ( const TDLAxiomDRoleFunctional& axiom ATTR_UNUSED ) {} virtual void visit ( const TDLAxiomRoleInverseFunctional& axiom ATTR_UNUSED ) {} virtual void visit ( const TDLAxiomConceptInclusion& axiom ATTR_UNUSED ) {} virtual void visit ( const TDLAxiomInstanceOf& axiom ATTR_UNUSED ) {} virtual void visit ( const TDLAxiomRelatedTo& axiom ATTR_UNUSED ) {} virtual void visit ( const TDLAxiomRelatedToNot& axiom ATTR_UNUSED ) {} virtual void visit ( const TDLAxiomValueOf& axiom ATTR_UNUSED ) {} virtual void visit ( const TDLAxiomValueOfNot& axiom ATTR_UNUSED ) {} virtual void visitOntology ( TOntology& ontology ) = 0; virtual ~DLAxiomVisitorEmpty ( void ) {} }; // DLAxiomVisitor /// signature of an axiom class TSignature; /// atom that the axiom belongs to class TOntologyAtom; /// base class for the DL axiom, which include T-, A- and RBox ones class TDLAxiom { protected: // members /// id of the axiom unsigned int id; /// signature (built lazily on demand) TSignature* sig; /// atom of the ontology (build lazily on demand) const TOntologyAtom* Atom; /// flag to show whether it is used (to support retraction) bool used; /// flag to show whether or not the axiom is in the module bool inModule; /// flag to show whether or not the axiom is in the search space for the optimised modularization algorithm bool inSearchSpace; protected: // methods /// build signature of an axiom void buildSignature ( void ); public: // interface /// empty c'tor TDLAxiom ( void ) : sig(NULL) , Atom(NULL) , used(true) , inModule(false) , inSearchSpace(false) {} /// d'tor: delete signature if it was created virtual ~TDLAxiom ( void ); // id management /// set the id void setId ( unsigned int Id ) { id = Id; } /// get the id unsigned int getId ( void ) const { return id; } // used management /// set the used flag void setUsed ( bool Used ) { used = Used; } /// get the value of the used flag bool isUsed ( void ) const { return used; } // modularity management /// set the inModule flag void setInModule ( bool flag ) { inModule = flag; } /// get the value of the inModule flag bool isInModule ( void ) const { return inModule; } /// set the isSearchSpace flag void setInSS ( bool flag ) { inSearchSpace = flag; } /// get the value of the isSearchSpace flag bool isInSS ( void ) const { return inSearchSpace; } // signature access const TSignature& getSignature ( void ) { if ( sig == NULL ) // 1st access: build it buildSignature(); return *sig; } // ontological atomic structure management /// set atom to which the axiom belongs void setAtom ( const TOntologyAtom* atom ) { Atom = atom; } /// get the atom an axiom belongs to const TOntologyAtom* getAtom ( void ) const { return Atom; } // visitor interface /// accept method for the visitor pattern virtual void accept ( DLAxiomVisitor& visitor ) const = 0; }; // TDLAxiom //------------------------------------------------------------------ /// globally visible axiom vector //------------------------------------------------------------------ typedef std::vector AxiomVec; //------------------------------------------------------------------ /// general declaration axiom //------------------------------------------------------------------ class TDLAxiomDeclaration: public TDLAxiom { protected: // members const TDLExpression* D; public: // interface /// c'tor: create an axiom TDLAxiomDeclaration ( const TDLExpression* d ) : TDLAxiom(), D(d) {} /// d'tor virtual ~TDLAxiomDeclaration ( void ) {} /// access const TDLExpression* getDeclaration ( void ) const { return D; } /// accept method for the visitor pattern void accept ( DLAxiomVisitor& visitor ) const { visitor.visit(*this); } }; // TDLAxiomIndividual //------------------------------------------------------------------ // n-ary axioms //------------------------------------------------------------------ //------------------------------------------------------------------ /// Concept equivalence axiom //------------------------------------------------------------------ class TDLAxiomEquivalentConcepts: public TDLAxiom, public TDLNAryExpression { public: // interface /// c'tor: create an axiom for C1 = ... = Cn TDLAxiomEquivalentConcepts ( const ExpressionArray& v ) : TDLAxiom() , TDLNAryExpression("concept expression","equivalent concepts") { add(v); } /// d'tor virtual ~TDLAxiomEquivalentConcepts ( void ) {} /// accept method for the visitor pattern void accept ( DLAxiomVisitor& visitor ) const { visitor.visit(*this); } }; // TDLAxiomEquivalentConcepts //------------------------------------------------------------------ /// Concept disjointness axiom //------------------------------------------------------------------ class TDLAxiomDisjointConcepts: public TDLAxiom, public TDLNAryExpression { public: // interface /// c'tor: create an axiom for C1 != ... != Cn TDLAxiomDisjointConcepts ( const ExpressionArray& v ) : TDLAxiom() , TDLNAryExpression("concept expression","disjoint concepts") { add(v); } /// d'tor virtual ~TDLAxiomDisjointConcepts ( void ) {} /// accept method for the visitor pattern void accept ( DLAxiomVisitor& visitor ) const { visitor.visit(*this); } }; // TDLAxiomDisjointConcepts //------------------------------------------------------------------ /// Disjoint Union axiom //------------------------------------------------------------------ class TDLAxiomDisjointUnion: public TDLAxiom, public TDLNAryExpression { protected: // members const TDLConceptExpression* C; public: // interface /// c'tor: create an axiom TDLAxiomDisjointUnion ( const TDLConceptExpression* c, const ExpressionArray& v ) : TDLAxiom() , TDLNAryExpression("concept expression","disjoint union") , C(c) { add(v); } /// d'tor virtual ~TDLAxiomDisjointUnion ( void ) {} /// accept method for the visitor pattern void accept ( DLAxiomVisitor& visitor ) const { visitor.visit(*this); } /// access const TDLConceptExpression* getC ( void ) const { return C; } }; // TDLAxiomInstanceOf //------------------------------------------------------------------ /// Object Role equivalence axiom //------------------------------------------------------------------ class TDLAxiomEquivalentORoles: public TDLAxiom, public TDLNAryExpression { public: // interface /// c'tor: create an axiom for OR1 = ... = ORn TDLAxiomEquivalentORoles ( const ExpressionArray& v ) : TDLAxiom() , TDLNAryExpression("object role expression","equivalent roles") { add(v); } /// d'tor virtual ~TDLAxiomEquivalentORoles ( void ) {} /// accept method for the visitor pattern void accept ( DLAxiomVisitor& visitor ) const { visitor.visit(*this); } }; // TDLAxiomEquivalentORoles //------------------------------------------------------------------ /// Data Role equivalence axiom //------------------------------------------------------------------ class TDLAxiomEquivalentDRoles: public TDLAxiom, public TDLNAryExpression { public: // interface /// c'tor: create an axiom for DR1 = ... = DRn TDLAxiomEquivalentDRoles ( const ExpressionArray& v ) : TDLAxiom() , TDLNAryExpression("data role expression","equivalent roles") { add(v); } /// d'tor virtual ~TDLAxiomEquivalentDRoles ( void ) {} /// accept method for the visitor pattern void accept ( DLAxiomVisitor& visitor ) const { visitor.visit(*this); } }; // TDLAxiomEquivalentDRoles //------------------------------------------------------------------ /// Object Role disjointness axiom //------------------------------------------------------------------ class TDLAxiomDisjointORoles: public TDLAxiom, public TDLNAryExpression { public: // interface /// c'tor: create an axiom for OR1 != ... != ORn TDLAxiomDisjointORoles ( const ExpressionArray& v ) : TDLAxiom() , TDLNAryExpression("object role expression","disjoint roles") { add(v); } /// d'tor virtual ~TDLAxiomDisjointORoles ( void ) {} /// accept method for the visitor pattern void accept ( DLAxiomVisitor& visitor ) const { visitor.visit(*this); } }; // TDLAxiomDisjointORoles //------------------------------------------------------------------ /// Data Role disjointness axiom //------------------------------------------------------------------ class TDLAxiomDisjointDRoles: public TDLAxiom, public TDLNAryExpression { public: // interface /// c'tor: create an axiom for DR1 != ... != DRn TDLAxiomDisjointDRoles ( const ExpressionArray& v ) : TDLAxiom() , TDLNAryExpression("data role expression","disjoint roles") { add(v); } /// d'tor virtual ~TDLAxiomDisjointDRoles ( void ) {} /// accept method for the visitor pattern void accept ( DLAxiomVisitor& visitor ) const { visitor.visit(*this); } }; // TDLAxiomDisjointDRoles //------------------------------------------------------------------ /// Same individuals axiom //------------------------------------------------------------------ class TDLAxiomSameIndividuals: public TDLAxiom, public TDLNAryExpression { public: // interface /// c'tor: create an axiom for i1 = ... = in TDLAxiomSameIndividuals ( const ExpressionArray& v ) : TDLAxiom() , TDLNAryExpression("individual expression","same individuals") { add(v); } /// d'tor virtual ~TDLAxiomSameIndividuals ( void ) {} /// accept method for the visitor pattern void accept ( DLAxiomVisitor& visitor ) const { visitor.visit(*this); } }; // TDLAxiomSameIndividuals //------------------------------------------------------------------ /// Different individuals axiom //------------------------------------------------------------------ class TDLAxiomDifferentIndividuals: public TDLAxiom, public TDLNAryExpression { public: // interface /// c'tor: create an axiom for i1 != ... != in TDLAxiomDifferentIndividuals ( const ExpressionArray& v ) : TDLAxiom() , TDLNAryExpression("individual expression","different individuals") { add(v); } /// d'tor virtual ~TDLAxiomDifferentIndividuals ( void ) {} /// accept method for the visitor pattern void accept ( DLAxiomVisitor& visitor ) const { visitor.visit(*this); } }; // TDLAxiomDifferentIndividuals //------------------------------------------------------------------ /// Fairness constraint axiom //------------------------------------------------------------------ class TDLAxiomFairnessConstraint: public TDLAxiom, public TDLNAryExpression { public: // interface /// c'tor: create an axiom for Fair(C1), ... Fair(Cn) constraints TDLAxiomFairnessConstraint ( const ExpressionArray& v ) : TDLAxiom() , TDLNAryExpression("concept expression","fairness") { add(v); } /// d'tor virtual ~TDLAxiomFairnessConstraint ( void ) {} /// accept method for the visitor pattern void accept ( DLAxiomVisitor& visitor ) const { visitor.visit(*this); } }; // TDLAxiomFairnessConstraint //------------------------------------------------------------------ // Role-related axiom //------------------------------------------------------------------ //------------------------------------------------------------------ /// General axiom that contains a single object role //------------------------------------------------------------------ class TDLAxiomSingleORole: public TDLAxiom { protected: // members const TDLObjectRoleExpression* Role; public: // interface /// c'tor: create an axiom TDLAxiomSingleORole ( const TDLObjectRoleExpression* role ) : TDLAxiom() , Role(role) {} /// d'tor virtual ~TDLAxiomSingleORole ( void ) {} /// access to role const TDLObjectRoleExpression* getRole ( void ) const { return Role; } }; // TDLAxiomSingleORole //------------------------------------------------------------------ /// General axiom that contains a single data role //------------------------------------------------------------------ class TDLAxiomSingleDRole: public TDLAxiom { protected: // members const TDLDataRoleExpression* Role; public: // interface /// c'tor: create an axiom TDLAxiomSingleDRole ( const TDLDataRoleExpression* role ) : TDLAxiom() , Role(role) {} /// d'tor virtual ~TDLAxiomSingleDRole ( void ) {} /// access to role const TDLDataRoleExpression* getRole ( void ) const { return Role; } }; // TDLAxiomSingleDRole //------------------------------------------------------------------ /// Role inverse axiom //------------------------------------------------------------------ class TDLAxiomRoleInverse: public TDLAxiomSingleORole { protected: // members const TDLObjectRoleExpression* InvRole; public: // interface /// c'tor: create an axiom TDLAxiomRoleInverse ( const TDLObjectRoleExpression* dirRole, const TDLObjectRoleExpression* invRole ) : TDLAxiomSingleORole(dirRole) , InvRole(invRole) {} /// d'tor virtual ~TDLAxiomRoleInverse ( void ) {} /// accept method for the visitor pattern void accept ( DLAxiomVisitor& visitor ) const { visitor.visit(*this); } /// access to role const TDLObjectRoleExpression* getInvRole ( void ) const { return InvRole; } }; // TDLAxiomRoleInverse //------------------------------------------------------------------ /// Object Role subsumption axiom //------------------------------------------------------------------ class TDLAxiomORoleSubsumption: public TDLAxiomSingleORole { protected: // members const TDLObjectRoleComplexExpression* SubRole; public: // interface /// c'tor: create an axiom TDLAxiomORoleSubsumption ( const TDLObjectRoleComplexExpression* subRole, const TDLObjectRoleExpression* supRole ) : TDLAxiomSingleORole(supRole) , SubRole(subRole) {} /// d'tor virtual ~TDLAxiomORoleSubsumption ( void ) {} /// accept method for the visitor pattern void accept ( DLAxiomVisitor& visitor ) const { visitor.visit(*this); } /// access to role const TDLObjectRoleComplexExpression* getSubRole ( void ) const { return SubRole; } }; // TDLAxiomORoleSubsumption //------------------------------------------------------------------ /// Data Role subsumption axiom //------------------------------------------------------------------ class TDLAxiomDRoleSubsumption: public TDLAxiomSingleDRole { protected: // members const TDLDataRoleExpression* SubRole; public: // interface /// c'tor: create an axiom TDLAxiomDRoleSubsumption ( const TDLDataRoleExpression* subRole, const TDLDataRoleExpression* supRole ) : TDLAxiomSingleDRole(supRole) , SubRole(subRole) {} /// d'tor virtual ~TDLAxiomDRoleSubsumption ( void ) {} /// accept method for the visitor pattern void accept ( DLAxiomVisitor& visitor ) const { visitor.visit(*this); } /// access to role const TDLDataRoleExpression* getSubRole ( void ) const { return SubRole; } }; // TDLAxiomDRoleSubsumption //------------------------------------------------------------------ /// Object Role domain axiom //------------------------------------------------------------------ class TDLAxiomORoleDomain: public TDLAxiomSingleORole { protected: // members const TDLConceptExpression* Domain; public: // interface /// c'tor: create an axiom TDLAxiomORoleDomain ( const TDLObjectRoleExpression* role, const TDLConceptExpression* domain ) : TDLAxiomSingleORole(role) , Domain(domain) {} /// d'tor; nothing to do as Domain is consumed virtual ~TDLAxiomORoleDomain ( void ) {} /// accept method for the visitor pattern void accept ( DLAxiomVisitor& visitor ) const { visitor.visit(*this); } /// access const TDLConceptExpression* getDomain ( void ) const { return Domain; } }; // TDLAxiomORoleDomain //------------------------------------------------------------------ /// Data Role domain axiom //------------------------------------------------------------------ class TDLAxiomDRoleDomain: public TDLAxiomSingleDRole { protected: // members const TDLConceptExpression* Domain; public: // interface /// c'tor: create an axiom TDLAxiomDRoleDomain ( const TDLDataRoleExpression* role, const TDLConceptExpression* domain ) : TDLAxiomSingleDRole(role) , Domain(domain) {} /// d'tor; nothing to do as Domain is consumed virtual ~TDLAxiomDRoleDomain ( void ) {} /// accept method for the visitor pattern void accept ( DLAxiomVisitor& visitor ) const { visitor.visit(*this); } /// access const TDLConceptExpression* getDomain ( void ) const { return Domain; } }; // TDLAxiomDRoleDomain //------------------------------------------------------------------ /// Object Role range axiom //------------------------------------------------------------------ class TDLAxiomORoleRange: public TDLAxiomSingleORole { protected: // members const TDLConceptExpression* Range; public: // interface /// c'tor: create an axiom TDLAxiomORoleRange ( const TDLObjectRoleExpression* role, const TDLConceptExpression* range ) : TDLAxiomSingleORole(role) , Range(range) {} /// d'tor; nothing to do as Domain is consumed virtual ~TDLAxiomORoleRange ( void ) {} /// accept method for the visitor pattern void accept ( DLAxiomVisitor& visitor ) const { visitor.visit(*this); } /// access const TDLConceptExpression* getRange ( void ) const { return Range; } }; // TDLAxiomORoleRange //------------------------------------------------------------------ /// Data Role range axiom //------------------------------------------------------------------ class TDLAxiomDRoleRange: public TDLAxiomSingleDRole { protected: // members const TDLDataExpression* Range; public: // interface /// c'tor: create an axiom TDLAxiomDRoleRange ( const TDLDataRoleExpression* role, const TDLDataExpression* range ) : TDLAxiomSingleDRole(role) , Range(range) {} /// d'tor; nothing to do as Domain is consumed virtual ~TDLAxiomDRoleRange ( void ) {} /// accept method for the visitor pattern void accept ( DLAxiomVisitor& visitor ) const { visitor.visit(*this); } /// access const TDLDataExpression* getRange ( void ) const { return Range; } }; // TDLAxiomDRoleRange //------------------------------------------------------------------ /// Role transitivity axiom //------------------------------------------------------------------ class TDLAxiomRoleTransitive: public TDLAxiomSingleORole { public: // interface /// c'tor: create an axiom TDLAxiomRoleTransitive ( const TDLObjectRoleExpression* role ) : TDLAxiomSingleORole(role) {} /// d'tor; virtual ~TDLAxiomRoleTransitive ( void ) {} /// accept method for the visitor pattern void accept ( DLAxiomVisitor& visitor ) const { visitor.visit(*this); } }; // TDLAxiomRoleTransitive //------------------------------------------------------------------ /// Role reflexivity axiom //------------------------------------------------------------------ class TDLAxiomRoleReflexive: public TDLAxiomSingleORole { public: // interface /// c'tor: create an axiom TDLAxiomRoleReflexive ( const TDLObjectRoleExpression* role ) : TDLAxiomSingleORole(role) {} /// d'tor; virtual ~TDLAxiomRoleReflexive ( void ) {} /// accept method for the visitor pattern void accept ( DLAxiomVisitor& visitor ) const { visitor.visit(*this); } }; // TDLAxiomRoleReflexive //------------------------------------------------------------------ /// Role irreflexivity axiom //------------------------------------------------------------------ class TDLAxiomRoleIrreflexive: public TDLAxiomSingleORole { public: // interface /// c'tor: create an axiom TDLAxiomRoleIrreflexive ( const TDLObjectRoleExpression* role ) : TDLAxiomSingleORole(role) {} /// d'tor; virtual ~TDLAxiomRoleIrreflexive ( void ) {} /// accept method for the visitor pattern void accept ( DLAxiomVisitor& visitor ) const { visitor.visit(*this); } }; // TDLAxiomRoleIrreflexive //------------------------------------------------------------------ /// Role symmetry axiom //------------------------------------------------------------------ class TDLAxiomRoleSymmetric: public TDLAxiomSingleORole { public: // interface /// c'tor: create an axiom TDLAxiomRoleSymmetric ( const TDLObjectRoleExpression* role ) : TDLAxiomSingleORole(role) {} /// d'tor; virtual ~TDLAxiomRoleSymmetric ( void ) {} /// accept method for the visitor pattern void accept ( DLAxiomVisitor& visitor ) const { visitor.visit(*this); } }; // TDLAxiomRoleSymmetric //------------------------------------------------------------------ /// Role asymmetry axiom //------------------------------------------------------------------ class TDLAxiomRoleAsymmetric: public TDLAxiomSingleORole { public: // interface /// c'tor: create an axiom TDLAxiomRoleAsymmetric ( const TDLObjectRoleExpression* role ) : TDLAxiomSingleORole(role) {} /// d'tor; virtual ~TDLAxiomRoleAsymmetric ( void ) {} /// accept method for the visitor pattern void accept ( DLAxiomVisitor& visitor ) const { visitor.visit(*this); } }; // TDLAxiomRoleAsymmetric //------------------------------------------------------------------ /// Object Role functionality axiom //------------------------------------------------------------------ class TDLAxiomORoleFunctional: public TDLAxiomSingleORole { public: // interface /// c'tor: create an axiom TDLAxiomORoleFunctional ( const TDLObjectRoleExpression* role ) : TDLAxiomSingleORole(role) {} /// d'tor; virtual ~TDLAxiomORoleFunctional ( void ) {} /// accept method for the visitor pattern void accept ( DLAxiomVisitor& visitor ) const { visitor.visit(*this); } }; // TDLAxiomORoleFunctional //------------------------------------------------------------------ /// Data Role functionality axiom //------------------------------------------------------------------ class TDLAxiomDRoleFunctional: public TDLAxiomSingleDRole { public: // interface /// c'tor: create an axiom TDLAxiomDRoleFunctional ( const TDLDataRoleExpression* role ) : TDLAxiomSingleDRole(role) {} /// d'tor; virtual ~TDLAxiomDRoleFunctional ( void ) {} /// accept method for the visitor pattern void accept ( DLAxiomVisitor& visitor ) const { visitor.visit(*this); } }; // TDLAxiomDRoleFunctional //------------------------------------------------------------------ /// Role inverse functionality axiom //------------------------------------------------------------------ class TDLAxiomRoleInverseFunctional: public TDLAxiomSingleORole { public: // interface /// c'tor: create an axiom TDLAxiomRoleInverseFunctional ( const TDLObjectRoleExpression* role ) : TDLAxiomSingleORole(role) {} /// d'tor; virtual ~TDLAxiomRoleInverseFunctional ( void ) {} /// accept method for the visitor pattern void accept ( DLAxiomVisitor& visitor ) const { visitor.visit(*this); } }; // TDLAxiomRoleInverseFunctional //------------------------------------------------------------------ // Concept/individual axioms //------------------------------------------------------------------ //------------------------------------------------------------------ /// Concept inclusion axiom //------------------------------------------------------------------ class TDLAxiomConceptInclusion: public TDLAxiom { protected: // members const TDLConceptExpression* Sub; const TDLConceptExpression* Sup; public: // interface /// c'tor: create an axiom TDLAxiomConceptInclusion ( const TDLConceptExpression* sub, const TDLConceptExpression* sup ) : TDLAxiom(), Sub(sub), Sup(sup) {} /// d'tor virtual ~TDLAxiomConceptInclusion ( void ) {} /// accept method for the visitor pattern void accept ( DLAxiomVisitor& visitor ) const { visitor.visit(*this); } /// access const TDLConceptExpression* getSubC ( void ) const { return Sub; } /// access const TDLConceptExpression* getSupC ( void ) const { return Sup; } }; // TDLAxiomConceptInclusion //------------------------------------------------------------------ /// general individual-based axiom //------------------------------------------------------------------ class TDLAxiomIndividual: public TDLAxiom { protected: // members const TDLIndividualExpression* I; public: // interface /// c'tor: create an axiom TDLAxiomIndividual ( const TDLIndividualExpression* i ) : TDLAxiom(), I(i) {} /// d'tor virtual ~TDLAxiomIndividual ( void ) {} /// access const TDLIndividualExpression* getIndividual ( void ) const { return I; } }; // TDLAxiomIndividual //------------------------------------------------------------------ /// Instance axiom //------------------------------------------------------------------ class TDLAxiomInstanceOf: public TDLAxiomIndividual { protected: // members const TDLConceptExpression* C; public: // interface /// c'tor: create an axiom TDLAxiomInstanceOf ( const TDLIndividualExpression* i, const TDLConceptExpression* c ) : TDLAxiomIndividual(i), C(c) {} /// d'tor virtual ~TDLAxiomInstanceOf ( void ) {} /// accept method for the visitor pattern void accept ( DLAxiomVisitor& visitor ) const { visitor.visit(*this); } /// access const TDLConceptExpression* getC ( void ) const { return C; } }; // TDLAxiomInstanceOf //------------------------------------------------------------------ /// Related To axiom //------------------------------------------------------------------ class TDLAxiomRelatedTo: public TDLAxiomIndividual { protected: // members const TDLObjectRoleExpression* R; const TDLIndividualExpression* J; public: // interface /// c'tor: create an axiom TDLAxiomRelatedTo ( const TDLIndividualExpression* i, const TDLObjectRoleExpression* r, const TDLIndividualExpression* j ) : TDLAxiomIndividual(i) , R(r) , J(j) {} /// d'tor virtual ~TDLAxiomRelatedTo ( void ) {} /// accept method for the visitor pattern void accept ( DLAxiomVisitor& visitor ) const { visitor.visit(*this); } /// access const TDLObjectRoleExpression* getRelation ( void ) const { return R; } /// access const TDLIndividualExpression* getRelatedIndividual ( void ) const { return J; } }; // TDLAxiomRelatedTo //------------------------------------------------------------------ /// Related To Not axiom //------------------------------------------------------------------ class TDLAxiomRelatedToNot: public TDLAxiomIndividual { protected: // members const TDLObjectRoleExpression* R; const TDLIndividualExpression* J; public: // interface /// c'tor: create an axiom TDLAxiomRelatedToNot ( const TDLIndividualExpression* i, const TDLObjectRoleExpression* r, const TDLIndividualExpression* j ) : TDLAxiomIndividual(i) , R(r) , J(j) {} /// d'tor virtual ~TDLAxiomRelatedToNot ( void ) {} /// accept method for the visitor pattern void accept ( DLAxiomVisitor& visitor ) const { visitor.visit(*this); } /// access const TDLObjectRoleExpression* getRelation ( void ) const { return R; } /// access const TDLIndividualExpression* getRelatedIndividual ( void ) const { return J; } }; // TDLAxiomRelatedToNot //------------------------------------------------------------------ /// Value Of axiom //------------------------------------------------------------------ class TDLAxiomValueOf: public TDLAxiomIndividual { protected: // members const TDLDataRoleExpression* A; const TDLDataValue* V; public: // interface /// c'tor: create an axiom TDLAxiomValueOf ( const TDLIndividualExpression* i, const TDLDataRoleExpression* a, const TDLDataValue* v ) : TDLAxiomIndividual(i) , A(a) , V(v) {} /// d'tor virtual ~TDLAxiomValueOf ( void ) {} /// accept method for the visitor pattern void accept ( DLAxiomVisitor& visitor ) const { visitor.visit(*this); } /// access to role const TDLDataRoleExpression* getAttribute ( void ) const { return A; } /// access to value const TDLDataValue* getValue ( void ) const { return V; } }; // TDLAxiomValueOf //------------------------------------------------------------------ /// Related To Not axiom //------------------------------------------------------------------ class TDLAxiomValueOfNot: public TDLAxiomIndividual { protected: // members const TDLDataRoleExpression* A; const TDLDataValue* V; public: // interface /// c'tor: create an axiom TDLAxiomValueOfNot ( const TDLIndividualExpression* i, const TDLDataRoleExpression* a, const TDLDataValue* v ) : TDLAxiomIndividual(i) , A(a) , V(v) {} /// d'tor virtual ~TDLAxiomValueOfNot ( void ) {} /// accept method for the visitor pattern void accept ( DLAxiomVisitor& visitor ) const { visitor.visit(*this); } /// access to role const TDLDataRoleExpression* getAttribute ( void ) const { return A; } /// access to value const TDLDataValue* getValue ( void ) const { return V; } }; // TDLAxiomValueOfNot #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/flags.h0000644000000000000000000000451612112642405016627 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2005-2008 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef _FLAGS_H #define _FLAGS_H /// class for carrying different flags; real users shall inherit from it class Flags { private: /// variable to keep all the flags unsigned int flags; protected: // methods for flags maintainance /// get given flag value bool getFlag ( unsigned int mask ) const { return flags & mask; } /// set given flag to 1 void setFlag ( unsigned int mask ) { flags |= mask; } /// set given flag to 0 void clearFlag ( unsigned int mask ) { flags &= ~mask; } /// set given flag to given value void setFlag ( unsigned int mask, bool Set ) { Set ? setFlag(mask) : clearFlag(mask); } /// get all the flags at once unsigned int getAllFlags ( void ) const { return flags; } /// set all flags to a given value; @return old value of the flags unsigned int setAllFlags ( unsigned int value ) { unsigned int old = flags; flags = value; return old; } public: // interface /// empty c'tor Flags ( void ) : flags(0) {} /// init flags with given set of flags explicit Flags ( unsigned int init ) : flags(init) {} /// copy c'tor Flags ( const Flags& f ) : flags(f.flags) {} /// assignment Flags& operator = ( const Flags& f ) { flags = f.flags; return *this; } /// empty d'tor virtual ~Flags ( void ) {} }; // Flags // use this macro to create a new flag #define FPP_ADD_FLAG(Name,Mask) \ bool is##Name ( void ) const \ { return getFlag(Mask); } \ void set##Name ( void ) \ { setFlag(Mask); } \ void clear##Name ( void ) \ { clearFlag(Mask); } \ void set##Name ( bool action ) \ { setFlag(Mask,action); } \ #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/RoleMaster.cpp0000644000000000000000000002026712112642405020144 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2012 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "RoleMaster.h" #include "eFPPInconsistentKB.h" RoleMaster :: RoleMaster ( bool dataRoles, const std::string& TopRoleName, const std::string& BotRoleName ) : newRoleId(1) , emptyRole(BotRoleName == "" ? "emptyRole" : BotRoleName) , universalRole(TopRoleName == "" ? "universalRole" : TopRoleName) , roleNS() , pTax(NULL) , DataRoles(dataRoles) , useUndefinedNames(true) { // no zero-named roles allowed Roles.push_back(NULL); Roles.push_back(NULL); // setup empty role emptyRole.setId(0); emptyRole.setInverse(&emptyRole); emptyRole.setDataRole(dataRoles); emptyRole.setBPDomain(bpBOTTOM); emptyRole.setBottom(); // setup universal role universalRole.setId(0); universalRole.setInverse(&universalRole); universalRole.setDataRole(dataRoles); universalRole.setBPDomain(bpTOP); universalRole.setTop(); // FIXME!! now it is not transitive => simple const_cast(universalRole.getAutomaton()).setCompleted(); } /// register TRole and it's inverse in RoleBox void RoleMaster :: registerRole ( TRole* r ) { fpp_assert ( r != NULL && r->Inverse == NULL ); // sanity check fpp_assert ( r->getId() == 0 ); // only call it for the new roles if ( DataRoles ) r->setDataRole(); Roles.push_back (r); r->setId (newRoleId); // create new role which would be inverse of R std::string iname ("-"); iname += r->getName(); TRole* ri = new TRole(iname); // set up inverse r->setInverse(ri); ri->setInverse(r); Roles.push_back (ri); ri->setId (-newRoleId); ++newRoleId; } TNamedEntry* RoleMaster :: ensureRoleName ( const std::string& name ) { // check for the Top/Bottom names if ( name == emptyRole.getName() ) return &emptyRole; if ( name == universalRole.getName() ) return &universalRole; // new name from NS TRole* p = roleNS.insert(name); // check what happens if ( p == NULL ) // role registration attempt failed throw EFPPCantRegName ( name, DataRoles ? "data role" : "role" ); if ( isRegisteredRole(p) ) // registered role return p; if ( p->getId() != 0 || // not registered but has non-null ID !useUndefinedNames ) // new names are disallowed throw EFPPCantRegName ( name, DataRoles ? "data role" : "role" ); registerRole(p); return p; } // inverse the role composition DLTree* inverseComposition ( const DLTree* tree ) { if ( tree->Element() == RCOMPOSITION ) return new DLTree ( TLexeme(RCOMPOSITION), inverseComposition(tree->Right()), inverseComposition(tree->Left()) ); else return createEntry ( RNAME, resolveRole(tree)->inverse() ); } void RoleMaster :: addRoleParent ( DLTree* tree, TRole* parent ) const { if ( !tree ) // nothing to do return; if ( tree->Element() == RCOMPOSITION ) { parent->addComposition(tree); DLTree* inv = inverseComposition(tree); parent->inverse()->addComposition(inv); deleteTree(inv); } else if ( tree->Element() == PROJINTO ) { // here -R->C became -PARENT-> // encode this as PROJFROM(R-,PROJINTO(PARENT-,C)), // added to the range of R TRole* R = resolveRole(tree->Left()); // can't do anything ATM for the data roles if ( R->isDataRole() ) throw EFaCTPlusPlus("Projection into not implemented for the data role"); DLTree* C = clone(tree->Right()); DLTree* InvP = createEntry ( RNAME, parent->inverse() ); DLTree* InvR = createEntry ( RNAME, R->inverse() ); // C = PROJINTO(PARENT-,C) C = new DLTree ( TLexeme(PROJINTO), InvP, C ); // C = PROJFROM(R-,PROJINTO(PARENT-,C)) C = new DLTree ( TLexeme(PROJFROM), InvR, C ); R->setRange(C); } else if ( tree->Element() == PROJFROM ) { // here C-R-> became -PARENT-> // encode this as PROJFROM(R,PROJINTO(PARENT,C)), // added to the domain of R TRole* R = resolveRole(tree->Left()); DLTree* C = clone(tree->Right()); DLTree* P = createEntry ( RNAME, parent ); // C = PROJINTO(PARENT,C) C = new DLTree ( TLexeme(PROJINTO), P, C ); // C = PROJFROM(R,PROJINTO(PARENT,C)) C = new DLTree ( TLexeme(PROJFROM), clone(tree->Left()), C ); R->setDomain(C); } else addRoleParent ( resolveRole(tree), parent ); deleteTree(tree); } /// add parent for the input role void RoleMaster :: addRoleParentProper ( TRole* role, TRole* parent ) const { fpp_assert ( !role->isSynonym() && !parent->isSynonym() ); if ( role == parent ) // nothing to do return; if ( role->isDataRole() != parent->isDataRole() ) throw EFaCTPlusPlus("Mixed object and data roles in role subsumption axiom"); // check the inconsistency case *UROLE* [= *EROLE* if ( unlikely(role->isTop() && parent->isBottom()) ) throw EFPPInconsistentKB(); // *UROLE* [= R means R (and R-) are synonym of *UROLE* if ( unlikely(role->isTop()) ) { parent->setSynonym(role); parent->inverse()->setSynonym(role); return; } // R [= *EROLE* means R (and R-) are synonyms of *EROLE* if ( unlikely(parent->isBottom()) ) { role->setSynonym(parent); role->inverse()->setSynonym(parent); return; } role->addParent(parent); role->inverse()->addParent(parent->inverse()); } void RoleMaster :: initAncDesc ( void ) { iterator p, p_begin = begin(), p_end = end(); unsigned int nRoles = Roles.size(); // stage 0.1: eliminate told cycles for ( p = p_begin; p != p_end; ++p ) (*p)->eliminateToldCycles(); // not VERY efficient: quadratic vs (possible) linear // setting up all synonyms for ( p = p_begin; p != p_end; ++p ) if ( (*p)->isSynonym() ) { (*p)->canonicaliseSynonym(); (*p)->addFeaturesToSynonym(); } // change all parents that are synonyms to their primers for ( p = p_begin; p != p_end; ++p ) if ( !(*p)->isSynonym() ) (*p)->removeSynonymsFromParents(); // here TOP-role has no children yet, so it's safe to complete the automaton universalRole.completeAutomaton(nRoles); // make all roles w/o told subsumers have Role TOP instead for ( p = p_begin; p < p_end; ++p ) if ( !(*p)->isSynonym() && !(*p)->hasToldSubsumers() ) (*p)->addParent(&universalRole); // stage 2: perform classification // create roles taxonomy pTax = new Taxonomy ( &universalRole, &emptyRole ); pTax->setCompletelyDefined(true); for ( p = p_begin; p != p_end; ++p ) if ( !(*p)->isClassified() ) pTax->classifyEntry(*p); // stage 3: fills ancestor/descendants using taxonomy for ( p = p_begin; p != p_end; ++p ) if ( !(*p)->isSynonym() ) (*p)->initADbyTaxonomy ( pTax, nRoles ); // complete role automaton's info for ( p = p_begin; p != p_end; ++p ) if ( !(*p)->isSynonym() ) (*p)->completeAutomaton(nRoles); // now all usual roles has their own automata, set up Bottom's automata emptyRole.completeAutomaton(nRoles); // prepare taxonomy to the real usage pTax->finalise(); // stage 3.5: apply Disjoint axioms to roles; check and correct disjoints in hierarchy if ( !DJRolesA.empty() ) { for ( iterator q = DJRolesA.begin(), q_end = DJRolesA.end(), r = DJRolesB.begin(); q != q_end; ++q, ++r ) { TRole* R = resolveSynonym(*q); TRole* S = resolveSynonym(*r); R->addDisjointRole(S); S->addDisjointRole(R); R->inverse()->addDisjointRole(S->inverse()); S->inverse()->addDisjointRole(R->inverse()); } for ( p = p_begin; p != p_end; ++p ) if ( !(*p)->isSynonym() && (*p)->isDisjoint() ) (*p)->checkHierarchicalDisjoint(); } // stage 4: init other fields for the roles. The whole hierarchy is known here for ( p = p_begin; p != p_end; ++p ) if ( !(*p)->isSynonym() ) (*p)->postProcess(); // the last stage: check whether all roles are consistent for ( p = p_begin; p != p_end; ++p ) if ( !(*p)->isSynonym() ) (*p)->consistent(); } FaCTpp-src-v1.6.2~dfsg/src/Kernel/tSignature.h0000644000000000000000000001047012112642405017654 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2011-2012 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef TSIGNATURE_H #define TSIGNATURE_H #include #include #include #include "tDLExpression.h" /// class to hold the signature of a module class TSignature { public: // types typedef std::set BaseType; typedef BaseType::const_iterator iterator; protected: // members /// set to keep all the elements in signature BaseType Set; /// true if concept TOP-locality; false if concept BOTTOM-locality bool topCLocality; /// true if role TOP-locality; false if role BOTTOM-locality bool topRLocality; public: // interface /// empty c'tor TSignature ( void ) : topCLocality(false), topRLocality(false) {} /// copy c'tor TSignature ( const TSignature& copy ) : Set(copy.Set), topCLocality(copy.topCLocality), topRLocality(copy.topRLocality) {} /// assignment TSignature& operator= ( const TSignature& copy ) { Set = copy.Set; topCLocality = copy.topCLocality; topRLocality = copy.topRLocality; return *this; } /// empty d'tor ~TSignature ( void ) {} // add names to signature /// add pointer to named object to signature void add ( const TNamedEntity* p ) { Set.insert(p); } /// add set of named entities to signature void add ( const BaseType& aSet ) { Set.insert ( aSet.begin(), aSet.end() ); } /// add another signature to a given one void add ( const TSignature& Sig ) { add(Sig.Set); } /// remove given element from a signature void remove ( const TNamedEntity* p ) { Set.erase(p); } /// set new locality polarity void setLocality ( bool topC, bool topR ) { topCLocality = topC; topRLocality = topR; } /// set new locality polarity void setLocality ( bool top ) { setLocality ( top, top ); } // comparison /// check whether 2 signatures are the same bool operator == ( const TSignature& sig ) const { return Set == sig.Set; } /// check whether 2 signatures are different bool operator != ( const TSignature& sig ) const { return Set != sig.Set; } /// operator < bool operator < ( const TSignature& sig ) const { return Set < sig.Set; } /// @return true iff signature contains given element bool contains ( const TNamedEntity* p ) const { return Set.count(p) > 0; } /// @return true iff signature contains given element bool contains ( const TDLExpression* p ) const { const TNamedEntity* e = dynamic_cast(p); if ( e != NULL ) return contains(e); const TDLObjectRoleInverse* inv = dynamic_cast(p); if ( inv != NULL ) return contains(inv->getOR()); return false; } /// @return size of the signature size_t size ( void ) const { return Set.size(); } /// clear the signature void clear ( void ) { Set.clear(); } /// RO access to the elements of signature iterator begin ( void ) const { return Set.begin(); } /// RO access to the elements of signature iterator end ( void ) const { return Set.end(); } /// @return true iff concepts are treated as TOPs bool topCLocal ( void ) const { return topCLocality; } /// @return true iff concepts are treated as BOTTOMs bool botCLocal ( void ) const { return !topCLocality; } /// @return true iff roles are treated as TOPs bool topRLocal ( void ) const { return topRLocality; } /// @return true iff roles are treated as BOTTOMs bool botRLocal ( void ) const { return !topRLocality; } }; // TSignature inline std::vector intersect ( const TSignature& s1, const TSignature& s2 ) { std::vector ret; set_intersection(s1.begin(), s1.end(), s2.begin(), s2.end(), inserter(ret, ret.begin())); return ret; } #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/dlDag.cpp0000644000000000000000000001772312112642405017105 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2012 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "dlDag.h" #include "logging.h" #include "tDataEntry.h" #include "tConcept.h" DLDag :: DLDag ( const ifOptionSet* Options ) : indexAnd(*this) , indexAll(*this) , indexLE(*this) , finalDagSize(0) , nCacheHits(0) , useDLVCache(true) { Heap.push_back ( new DLVertex (dtBad) ); // empty vertex -- bpINVALID Heap.push_back ( new DLVertex (dtTop) ); readConfig ( Options ); } DLDag :: ~DLDag ( void ) { for ( HeapType::iterator p = Heap.begin(), p_end = Heap.end(); p < p_end; ++p ) delete *p; } void DLDag :: removeQuery ( void ) { for ( size_t i = size()-1; i >= finalDagSize; --i ) { DLVertex* v = Heap[i]; switch ( v->Type() ) { case dtData: static_cast(v->getConcept())->setBP(bpINVALID); break; case dtConcept: static_cast(v->getConcept())->clear(); break; default: break; } delete v; } Heap.resize(finalDagSize); } void DLDag :: readConfig ( const ifOptionSet* Options ) { fpp_assert ( Options != NULL ); // safety check orSortSat = Options->getText ( "orSortSat" ).c_str(); orSortSub = Options->getText ( "orSortSub" ).c_str(); if ( !isCorrectOption(orSortSat) || !isCorrectOption(orSortSub) ) throw EFaCTPlusPlus ( "DAG: wrong OR sorting options" ); } /// set defaults of OR orderings void DLDag :: setOrderDefaults ( const char* defSat, const char* defSub ) { // defaults should be correct fpp_assert ( isCorrectOption(defSat) && isCorrectOption(defSub) ); if ( LLM.isWritable(llAlways) ) LL << "orSortSat: initial=" << orSortSat << ", default=" << defSat; if ( orSortSat[0] == '0' ) orSortSat = defSat; if ( LLM.isWritable(llAlways) ) LL << ", used=" << orSortSat << "\n" << "orSortSub: initial=" << orSortSub << ", default=" << defSub; if ( orSortSub[0] == '0' ) orSortSub = defSub; if ( LLM.isWritable(llAlways) ) LL << ", used=" << orSortSub << "\n"; } /// set OR sort flags based on given option string void DLDag :: setOrderOptions ( const char* opt ) { // 0x means not to use OR sort if ( opt[0] == '0' ) return; sortAscend = (opt[1] == 'a'); preferNonGen = (opt[2] == 'p'); // all statistics use negative version (as it is used in disjunctions) iSort = opt[0] == 'S' ? DLVertex::getStatIndexSize(false) : opt[0] == 'D' ? DLVertex::getStatIndexDepth(false) : opt[0] == 'B' ? DLVertex::getStatIndexBranch(false) : opt[0] == 'G' ? DLVertex::getStatIndexGener(false) : DLVertex::getStatIndexFreq(false); Recompute(); } void DLDag :: computeVertexStat ( BipolarPointer p ) { DLVertex& v = (*this)[p]; bool pos = isPositive(p); // this vertex is already processed if ( v.isProcessed(pos) ) return; // in case of cycle: mark concept as such if ( v.isVisited(pos) ) { v.setInCycle(pos); return; } v.setVisited(pos); // ensure that the statistic is gather for all sub-concepts of the expression switch ( v.Type() ) { case dtAnd: // check all the conjuncts case dtSplitConcept: for ( DLVertex::const_iterator q = v.begin(), q_end = v.end(); q < q_end; ++q ) computeVertexStat ( *q, pos ); break; case dtProj: if ( !pos ) // ~Proj -- nothing to do break; // fallthrough case dtName: case dtForall: case dtChoose: case dtLE: // check a single referenced concept computeVertexStat ( v.getC(), pos ); break; default: // nothing to do break; } v.setProcessed(pos); // here all the necessary statistics is gathered -- use it in the init updateVertexStat(p); } void DLDag :: updateVertexStat ( BipolarPointer p ) { DLVertex& v = (*this)[p]; bool pos = isPositive(p); DLVertex::StatType d = 0, s = 1, b = 0, g = 0; if ( !v.omitStat(pos) ) { if ( isValid(v.getC()) ) updateVertexStat ( v, v.getC(), pos ); else for ( DLVertex::const_iterator q = v.begin(), q_end = v.end(); q < q_end; ++q ) updateVertexStat ( v, *q, pos ); } // correct values wrt POS d = v.getDepth(pos); switch ( v.Type() ) { case dtAnd: if ( !pos ) ++b; // OR is branching break; case dtForall: ++d; // increase depth if ( !pos ) ++g; // SOME is generating break; case dtLE: ++d; // increase depth if ( !pos ) ++g; // >= is generating else if ( v.getNumberLE() != 1 ) ++b; // <= is branching break; case dtProj: if ( pos ) ++b; // projection sometimes involves branching break; default: break; } v.updateStatValues ( d, s, b, g, pos ); } /// gather vertex freq statistics void DLDag :: computeVertexFreq ( BipolarPointer p ) { DLVertex& v = (*this)[p]; bool pos = isPositive(p); if ( v.isVisited(pos) ) // avoid cycles return; v.incFreqValue(pos); // increment frequence of current vertex v.setVisited(pos); if ( v.omitStat(pos) ) // negation of primitive concept-like return; // increment frequence of all subvertex if ( isValid(v.getC()) ) computeVertexFreq ( v.getC(), pos ); else for ( DLVertex::const_iterator q = v.begin(), q_end = v.end(); q != q_end; ++q ) computeVertexFreq ( *q, pos ); } void DLDag :: gatherStatistic ( void ) { // gather main statistics for disjunctions for ( StatVector::iterator p = listAnds.begin(), p_end = listAnds.end(); p < p_end; ++p ) computeVertexStat(inverse(*p)); // if necessary -- gather frequency if ( orSortSat[0] != 'F' && orSortSub[0] != 'F' ) return; clearDFS(); for ( int i = size()-1; i > 1; --i ) { if ( isCNameTag((*this)[i].Type()) ) computeVertexFreq(i); } } //--------------------------------------------------- // change order of ADD elements with respect to Freq //--------------------------------------------------- /// return true if p1 is less than p2 using chosen sort order // the overall sorted entry structure looks like // fffA..M..Zlll if sortAscend set, and // fffZ..M..Alll if sortAscend cleared. // here 's' means "always first" entries, like neg-primconcepts, // and 'l' means "always last" entries, like looped concepts // note that the statistics is given for disjunctions, // so inversed (neg) values are taken into account bool DLDag :: less ( BipolarPointer p1, BipolarPointer p2 ) const { # ifdef ENABLE_CHECKING fpp_assert ( isValid(p1) && isValid(p2) ); # endif // idea: any positive entry should go first if ( preferNonGen ) { if ( isNegative(p1) && isPositive(p2) ) return true; if ( isPositive(p1) && isNegative(p2) ) return false; } const DLVertex& v1 = (*this)[p1]; const DLVertex& v2 = (*this)[p2]; /* // prefer non-cyclical if ( !v1.isInCycle(false) && v2.isInCycle(false) ) return true; if ( !v2.isInCycle(false) && v1.isInCycle(false) ) return false; */ DLVertex::StatType key1 = v1.getStat(iSort); DLVertex::StatType key2 = v2.getStat(iSort); // return "less" wrt sortAscend if ( sortAscend ) return key1 < key2; else return key2 < key1; } #ifdef RKG_PRINT_DAG_USAGE /// print usage of DAG void DLDag :: PrintDAGUsage ( std::ostream& o ) const { unsigned int n = 0; // number of no-used DAG entries unsigned int total = Heap.size()*2-2; // number of total DAG entries for ( HeapType::const_iterator i = Heap.begin(), i_end = Heap.end(); i < i_end; ++i ) { if ( (*i)->getUsage(true) == 0 ) // positive and... ++n; if ( (*i)->getUsage(false) == 0 ) // negative ones ++n; } o << "There are " << n << " unused DAG entries (" << (unsigned long)(n*100/total) << "% of " << total << " total)\n"; } #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/DepSet.h0000644000000000000000000000221212112642405016706 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2010 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef DEPSET_H #define DEPSET_H #include "tDepSet.h" // define type for dependency set typedef TDepSet DepSet; // common operations with the dep-set template inline O& operator << ( O& o, const DepSet& s ) { s.Print(o); return o; } inline DepSet operator + ( const DepSet& ds1, const DepSet& ds2 ) { DepSet ret(ds1); return ret += ds2; } #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/tFastSet.h0000644000000000000000000001057212112642405017267 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2008-2009 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef TFASTSET_H #define TFASTSET_H #include "growingArray.h" /// the implementation of the set with constant-time "in" check template class TFastSet { protected: // internal types /// type for the array of values typedef growingArray ValArray; /// type of the index typedef size_t indexType; public: // type interface /// RW iterator on values typedef typename ValArray::iterator iterator; /// RO iterator on values typedef typename ValArray::const_iterator const_iterator; protected: // members /// values to be kept in the set ValArray Value; /// indeces of the used values std::vector Index; protected: // methods /// transform element into an integer; is tunable static indexType toInt ( const T& t ) { return static_cast(t); } public: // interface /// ensure that the index can cope with sets not larger that SIZE void ensureMaxSetSize ( size_t size ) { Index.resize(size); } /// empty c'tor TFastSet ( void ) {} /// c'tor with a given max set SIZE TFastSet ( size_t size ) { ensureMaxSetSize(size); } /// copy c'tor TFastSet ( const TFastSet& copy ) : Value(copy.Value), Index(copy.Index) {} /// assignment TFastSet& operator = ( const TFastSet& copy ) { Value = copy.Value; Index = copy.Index; return *this; } /// empty d'tor ~TFastSet ( void ) {} /// reserve the set size to the SIZE elements void reserve ( size_t size ) { Value.reserve(size); } // set iterators /// begin RW iterator iterator begin ( void ) { return Value.begin(); } /// end RW iterator iterator end ( void ) { return Value.end(); } /// begin RO iterator const_iterator begin ( void ) const { return Value.begin(); } /// end RO iterator const_iterator end ( void ) const { return Value.end(); } // set operations -- containment /// check whether T is in set bool in ( const T& t ) const { indexType index = Index[toInt(t)]; return index < Value.size() && Value[index] == t; } /// check whether FS contains all the elements from the given set bool operator <= ( const TFastSet& fs ) const { for ( const_iterator p = begin(), p_end = end(); p < p_end; ++p ) if ( !fs.in(*p) ) return false; return true; } /// check whether given set contains all the elements from FS bool operator >= ( const TFastSet& fs ) const { return fs <= *this; } /// equality of the sets bool operator == ( const TFastSet& fs ) const { return (*this <= fs) && (fs <= *this); } /// strict containment bool operator < ( const TFastSet& fs ) const { return (*this <= fs) && !(fs <= *this); } /// strict containment bool operator > ( const TFastSet& fs ) const { return fs < *this; } // set operations -- adding /// add an element T to a set; assume T is not in the set (unique) void addu ( const T& t ) { Index[toInt(t)] = Value.size(); Value.add(t); } /// add element T to a set void add ( const T& t ) { if ( !in(t) ) addu(t); } /// add a set [begin,end) to a set; assume none of the elements appears in the set template void addu ( Iterator begin, Iterator end ) { for ( ; begin != end; ++ begin ) addu(*begin); } /// add a set [begin,end) to a set template void add ( Iterator begin, Iterator end ) { for ( ; begin != end; ++ begin ) add(*begin); } // misc /// check whether the set is empty bool empty ( void ) const { return Value.empty(); } /// get the size of the set size_t size ( void ) const { return Value.size(); } /// clear the set void clear ( void ) { Value.clear(); } /// set the size of the set to be a VALUE void resize ( size_t value ) { Value.resize(value); } }; // TFastSet #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/Taxonomy.h0000644000000000000000000003313212112642405017345 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2012 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef TAXONOMY_H #define TAXONOMY_H // taxonomy graph for DL #include "taxVertex.h" #include "SearchableStack.h" class Taxonomy { protected: // internal typedefs /// type for a vector of TaxVertex typedef std::vector TaxVertexVec; /// set of the subsumers typedef ClassifiableEntry::linkSet SubsumerSet; /// SS RW iterator typedef SubsumerSet::iterator ss_iterator; /// abstract class to represent the known subsumers of a concept class KnownSubsumers { public: // interface /// empty c'tor KnownSubsumers ( void ) {} /// empty d'tor virtual ~KnownSubsumers ( void ) {} // iterators /// begin of the Sure subsumers interval virtual ss_iterator s_begin ( void ) = 0; /// end of the Sure subsumers interval virtual ss_iterator s_end ( void ) = 0; /// begin of the Possible subsumers interval virtual ss_iterator p_begin ( void ) = 0; /// end of the Possible subsumers interval virtual ss_iterator p_end ( void ) = 0; // flags /// whether there are no sure subsumers bool s_empty ( void ) { return s_begin() == s_end(); } /// whether there are no possible subsumers bool p_empty ( void ) { return p_begin() == p_end(); } /// @return true iff CE is the possible subsumer virtual bool isPossibleSub ( const ClassifiableEntry* ce ATTR_UNUSED ) const { return true; } }; // KnownSubsumers /// class to represent the TS's class ToldSubsumers: public KnownSubsumers { protected: // members /// two iterators for the TS of a concept ss_iterator beg, end; public: // interface /// c'tor ToldSubsumers ( ss_iterator b, ss_iterator e ) : beg(b), end(e) {} /// d'tor virtual ~ToldSubsumers ( void ) {} // iterators /// begin of the Sure subsumers interval virtual ss_iterator s_begin ( void ) { return beg; } /// end of the Sure subsumers interval virtual ss_iterator s_end ( void ) { return end; } /// begin of the Possible subsumers interval virtual ss_iterator p_begin ( void ) { return end; } /// end of the Possible subsumers interval virtual ss_iterator p_end ( void ) { return end; } }; // ToldSubsumers public: // typedefs /// iterator on the set of vertex typedef TaxVertexVec::iterator iterator; /// const_iterator on the set of vertex typedef TaxVertexVec::const_iterator const_iterator; protected: // members /// array of taxonomy vertices TaxVertexVec Graph; /// aux array to keep synonyms found during TS classification std::vector Syns; /// labellers for marking taxonomy TLabeller checkLabel, valueLabel; /// aux vertex to be included to taxonomy TaxonomyVertex* Current; /// vertex with parent Top and child Bot, represents the fresh entity TaxonomyVertex FreshNode; /// pointer to currently classified entry const ClassifiableEntry* curEntry; /// number of tested entries unsigned int nEntries; /// number of completely-defined entries unsigned long nCDEntries; /// optimisation flag: if entry is completely defined by it's told subsumers, no other classification required bool useCompletelyDefined; /// behaviour flag: if true, insert temporary vertex into taxonomy bool willInsertIntoTaxonomy; /// stack for Taxonomy creation SearchableStack waitStack; /// told subsumers corresponding to a given entry SearchableStack ksStack; private: // no copy /// no copy c'tor Taxonomy ( const Taxonomy& ); /// no assignment Taxonomy& operator = ( const Taxonomy& ); protected: // methods /// initialise aux entry with given concept p void setCurrentEntry ( const ClassifiableEntry* p ) { Current->clear(); curEntry = p; } //----------------------------------------------------------------- //-- General classification support //----------------------------------------------------------------- /// make the only parent -- top void setParentTop ( void ) { Current->addNeighbour ( /*upDirection=*/true, getTopVertex() ); } /// make the only child -- bottom void setChildBottom ( void ) { Current->addNeighbour ( /*upDirection=*/false, getBottomVertex() ); } /// return 1 if current entry is classified as a synonym of already classified one virtual bool classifySynonym ( void ); /// set up Told Subsumers for the current entry void setToldSubsumers ( void ); /// add non-redundant candidates for the current entry void setNonRedundantCandidates ( void ); //----------------------------------------------------------------- //-- Tunable methods (depending on taxonomy type) //----------------------------------------------------------------- /// check if no classification needed (synonym, orphan, unsatisfiable) virtual bool immediatelyClassified ( void ) { return classifySynonym(); } /// setup TD phase (ie, identify/set parent candidates) void setupTopDown ( void ) { setToldSubsumers(); if ( !needTopDown() ) { ++nCDEntries; setNonRedundantCandidates(); } } /// check if it is possible to skip TD phase virtual bool needTopDown ( void ) const { return false; } /// explicitly run TD phase virtual void runTopDown ( void ) {} /// check if it is possible to skip BU phase virtual bool needBottomUp ( void ) const { return false; } /// explicitly run BU phase virtual void runBottomUp ( void ) {} /// actions that to be done BEFORE entry will be classified virtual void preClassificationActions ( void ) {} //----------------------------------------------------------------- //-- General classification methods //----------------------------------------------------------------- /// Common pre- and post-action to setup 2-phase algo void performClassification ( void ); /// fills parents and children of Current using tunable general approach void generalTwoPhaseClassification ( void ); /// add current entry to a synonym SYN void addCurrentToSynonym ( TaxonomyVertex* syn ); /// insert current node to a taxonomy (if not in query more) void insertCurrentNode ( void ); /// remove node from the taxonomy; assume no references to the node void removeNode ( TaxonomyVertex* node ) { node->setInUse(false); } /// @return true if V is a direct parent of current wrt labels bool isDirectParent ( TaxonomyVertex* v ) const; /// @return true if taxonomy works in a query mode (no need to insert query vertex) bool queryMode ( void ) const { return !willInsertIntoTaxonomy; } //----------------------------------------------------------------- //-- DFS-based classification //----------------------------------------------------------------- /// prepare known subsumers for given entry if necessary virtual KnownSubsumers* buildKnownSubsumers ( ClassifiableEntry* p ) { return new ToldSubsumers(p->told_begin(), p->told_end()); } /// add top entry together with its known subsumers void addTop ( ClassifiableEntry* p ) { waitStack.push(p); ksStack.push(buildKnownSubsumers(p)); } /// remove top entry void removeTop ( void ) { waitStack.pop(); delete ksStack.top(); ksStack.pop(); } /// ensure that all TS of the top entry are classified. @return the reason of cycle or NULL. ClassifiableEntry* prepareTS ( ClassifiableEntry* cur ); /// classify top entry of the stack void classifyTop ( void ) { fpp_assert ( !waitStack.empty() ); // sanity check setCurrentEntry(waitStack.top()); performClassification(); removeTop(); } /// propagate the TRUE value of the KS subsumption up the taxonomy void propagateTrueUp ( TaxonomyVertex* node ); ss_iterator told_begin ( void ) { return ksStack.top()->s_begin(); } ss_iterator told_end ( void ) { return ksStack.top()->s_end(); } /// check if it is necessary to log taxonomy action virtual bool needLogging ( void ) const { return false; } /// apply ACTOR to subgraph starting from NODE as defined by flags template void getRelativesInfoRec ( TaxonomyVertex* node, Actor& actor ) { // recursive applicability checking if ( node->isChecked(checkLabel) ) return; // label node as visited node->setChecked(checkLabel); // if current node processed OK and there is no need to continue -- exit // if node is NOT processed for some reasons -- go to another level if ( actor.apply(*node) && onlyDirect ) return; // apply method to the proper neighbours with proper parameters for ( TaxonomyVertex::iterator p = node->begin(upDirection), p_end = node->end(upDirection); p != p_end; ++p ) getRelativesInfoRec ( *p, actor ); } public: // interface /// init c'tor Taxonomy ( const ClassifiableEntry* pTop, const ClassifiableEntry* pBottom ) : Current(new TaxonomyVertex()) , curEntry(NULL) , nEntries(0) , nCDEntries(0) , useCompletelyDefined (false) , willInsertIntoTaxonomy (true) { Graph.push_back (new TaxonomyVertex(pBottom)); // bottom Graph.push_back (new TaxonomyVertex(pTop)); // top // set up fresh node FreshNode.addNeighbour ( /*upDirection=*/true, getTopVertex() ); FreshNode.addNeighbour ( /*upDirection=*/false, getBottomVertex() ); } /// d'tor virtual ~Taxonomy ( void ); //------------------------------------------------------------------------------ //-- Access to taxonomy entries //------------------------------------------------------------------------------ iterator begin ( void ) { return Graph.begin(); } iterator end ( void ) { return Graph.end(); } /// iterator for the bottom of the taxonomy iterator ibottom ( void ) { return begin(); } /// iterator for the Top of the taxonomy iterator itop ( void ) { return begin()+1; } const_iterator begin ( void ) const { return Graph.begin(); } const_iterator end ( void ) const { return Graph.end(); } /// iterator for the bottom of the taxonomy const_iterator ibottom ( void ) const { return begin(); } /// iterator for the Top of the taxonomy const_iterator itop ( void ) const { return begin()+1; } /// special access to TOP of taxonomy TaxonomyVertex* getTopVertex ( void ) const { return *itop(); } /// special access to BOTTOM of taxonomy TaxonomyVertex* getBottomVertex ( void ) const { return *ibottom(); } /// get node for fresh entity E TaxonomyVertex* getFreshVertex ( const ClassifiableEntry* e ) { FreshNode.setSample(e,false); return &FreshNode; } /// apply ACTOR to subgraph starting from NODE as defined by flags; template void getRelativesInfo ( TaxonomyVertex* node, Actor& actor ) { // if current node processed OK and there is no need to continue -- exit // this is the helper to the case like getDomain(): // if there is a named concept that represent's a domain -- that's what we need if ( needCurrent ) if ( actor.apply(*node) && onlyDirect ) return; for ( TaxonomyVertex::iterator p = node->begin(upDirection), p_end = node->end(upDirection); p != p_end; ++p ) getRelativesInfoRec ( *p, actor ); clearCheckedLabel(); } //------------------------------------------------------------------------------ //-- classification interface //------------------------------------------------------------------------------ /// classify given entry: general method is by DFS void classifyEntry ( ClassifiableEntry* p ) { fpp_assert ( waitStack.empty() ); // sanity check // don't classify artificial concepts if ( p->isNonClassifiable() ) return; prepareTS(p); } /// clear the CHECKED label from all the taxonomy vertex void clearCheckedLabel ( void ) { checkLabel.newLabel(); } /// clear all labels from Taxonomy vertices void clearLabels ( void ) { checkLabel.newLabel(); valueLabel.newLabel(); } // flags interface /// set Completely Defined flag void setCompletelyDefined ( bool use ) { useCompletelyDefined = use; } /// call this method after taxonomy is built void finalise ( void ) { // create links from leaf concepts to bottom const bool upDirection = false; for ( iterator p = itop(), p_end = end(); p < p_end; ++p ) if ( likely((*p)->isInUse()) && (*p)->noNeighbours(upDirection) ) { (*p)->addNeighbour ( upDirection, getBottomVertex() ); getBottomVertex()->addNeighbour ( !upDirection, *p ); } willInsertIntoTaxonomy = false; // after finalisation one shouldn't add new entries to taxonomy } /// unlink the bottom from the taxonomy void deFinalise ( void ) { const bool upDirection = true; TaxonomyVertex* bot = getBottomVertex(); for ( TaxonomyVertex::iterator p = bot->begin(upDirection), p_end = bot->end(upDirection); p != p_end; ++p ) (*p)->removeLink ( !upDirection, bot ); bot->clearLinks(upDirection); willInsertIntoTaxonomy = true; // it's possible again to add entries } // taxonomy info access /// print taxonomy info to a stream virtual void print ( std::ostream& o ) const; // save/load interface; implementation is in SaveLoad.cpp /// save entry void Save ( std::ostream& o ) const; /// load entry void Load ( std::istream& i ); }; // Taxonomy #endif // TAXONOMY_H FaCTpp-src-v1.6.2~dfsg/src/Kernel/eFPPSaveLoad.h0000644000000000000000000000352412112642405017742 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2006-2013 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef EFPPSAVELOAD_H #define EFPPSAVELOAD_H #include #include "eFaCTPlusPlus.h" /// exception thrown for the save/load operations class EFPPSaveLoad: public EFaCTPlusPlus { private: // members /// error string std::string str; public: // interface /// c'tor with a given "what" string EFPPSaveLoad ( const std::string& why ) : EFaCTPlusPlus() , str(why) { reason = str.c_str(); } /// c'tor "Char not found" explicit EFPPSaveLoad ( const char c ) : EFaCTPlusPlus() { str = "Expected character '"; str += c; str += "' not found"; reason = str.c_str(); } /// c'tor: create an output string for the bad filename EFPPSaveLoad ( const std::string& filename, bool save ) : EFaCTPlusPlus() { const char* action = save ? "save" : "load"; const char* prep = save ? "to" : "from"; str = "Unable to "; str += action; str += " internal state "; str += prep; str += " file '"; str += filename; str += "'"; reason = str.c_str(); } /// empty d'tor virtual ~EFPPSaveLoad ( void ) throw() {} }; // EFppSaveLoad #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/fpp_assert.h0000644000000000000000000000302612112642405017674 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2009 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef FPP_ASSERT_H #define FPP_ASSERT_H #include "eFaCTPlusPlus.h" /// assertion exception class EFPPAssertion: public EFaCTPlusPlus { public: // interface /// the default constructor EFPPAssertion ( const char* reason ) : EFaCTPlusPlus(reason) {} }; // EFPPAssertion #undef fpp_assert #undef fpp_assert_ #undef fpp_assert__ #undef fpp_unreachable /// assert() helpers #define fpp_assert__(e,file,line) \ throw EFPPAssertion(file ":" #line ": assertion '" e "' fails") #define fpp_assert_(e,f,l) fpp_assert__(#e,f,l) #ifdef NDEBUG # define fpp_assert(e) ((void)(0 && (e))) #else # define fpp_assert(e) ((void)((e) ? 0 : fpp_assert_ ( e, __FILE__, __LINE__ ))) #endif #define fpp_unreachable() fpp_assert_ ( unreachable, __FILE__, __LINE__ ) #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/TriRelation.h0000644000000000000000000001140412112642405017761 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2009-2010 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef TRIRELATION_H #define TRIRELATION_H #include #include #include "globaldef.h" // comment this out when TriRelation would need delete edges #define FPP_NO_DELETE_EDGE // uncomment the following line to debug tri-relation //#define FPP_DEBUG_TRI_RELATION /// class for the binary relation, it's transitive closure and its transitive reduction class TriRelation { public: // typedefs /// typedef for the vertex typedef unsigned int Vertex; /// bit vector typedef std::vector bvec; /// bit matrix typedef std::vector bMatrix; /// int vector typedef std::vector nvec; /// int matrix typedef std::vector nMatrix; /// int sets: for every index represents an array of verteces typedef std::vector nSet; protected: // members /// adjacency matrix for the basic relation R bMatrix M; /// adjacency matrix for R's transitive closure R* bMatrix MStar; /// adjacency matrix for R's transitive reduction R- bMatrix MMinus; #ifndef FPP_NO_DELETE_EDGE /// R's input matrix nMatrix N; /// successor's relation for R nSet S; /// predecessor's relation for R nSet P; #endif /// set of verteces of the condencend graph V^c: V_c[v] == true iff v\in V^c bvec V_c; /// map between verteces and SCC representors (leaders) nvec L; /// successor's relation for G^c nSet S_c; /// predecessor's relation for G^c nSet P_c; /// component vectors (maps leader to the set of its component) nSet C_c; /// weighted adjacency matrix of the condenced graph nMatrix M_c; #ifndef FPP_NO_DELETE_EDGE /// array of links from the vertex landing in the same component nvec e_c; #endif /// stack for the red nodes nvec redStack; /// number of verteces Vertex last; protected: // methods /// maps vertex X to its component nvec C ( Vertex x ) { return C_c[L[x]]; } /// add an edge from X to Y in the main relation; adjust S and P void setM ( Vertex x, Vertex y ) { M[x][y] = true; MStar[x][y] = true; # ifndef FPP_NO_DELETE_EDGE S[x].push_back(y); P[y].push_back(x); # endif } /// add condenced node X to a set of condenced nodes S void addCondenced ( nvec& s, Vertex x ) { for ( nvec::iterator p = s.begin(), p_end = s.end(); p < p_end; ++p ) if ( x == *p ) return; s.push_back(x); } /// add an edge between X and Y in the condenced relation M_c; adjust S^c and P^c void setMc ( Vertex x, Vertex y ) { ++M_c[x][y]; addCondenced ( S_c[x], y ); addCondenced ( P_c[y], x ); } /// add an edge from X to Y in the same SCC void adjustEc ( Vertex x ATTR_UNUSED, Vertex y ATTR_UNUSED ) { # ifndef FPP_NO_DELETE_EDGE ++e_c[y]; # endif // S[x].push_back(y); } /// init all the graph structures assuming N verteces and no edges void init ( unsigned int n ); // insert support /// insert a non-existing edge between X and Y; @return true iff a new cycle appears bool insertNew ( Vertex x, Vertex y ); /// ADAPT helper to the insert procedure void adapt ( Vertex k ); /// JOIN COMPONENTS helper to the insert procedure: C(J) will have new members void joinComponents ( Vertex j ); public: // interface /// c'tor for a graph with N nodes TriRelation ( unsigned int n = 1 ) { init(n); } /// empty d'tor ~TriRelation ( void ) {} /// add a vertex to a graph; @return index of a new vertex Vertex newVertex ( void ); /// insert an edge between verteces X and Y; @return true iff a new cycle appears bool insert ( Vertex x, Vertex y ) { if ( !M[x][y] ) return insertNew(x,y); # ifdef FPP_DEBUG_TRI_RELATION std::cerr << "Insert known R(" << x << "," << y << ")\n"; # endif return false; } /// @return true iff R(X,Y) holds bool R ( Vertex x, Vertex y ) const { return M[x][y]; } /// @return true iff R*(X,Y) holds bool RStar ( Vertex x, Vertex y ) const { return MStar[x][y]; } /// @return true iff R-(X,Y) holds bool RMinus ( Vertex x, Vertex y ) const { return MMinus[L[x]][L[y]]; } /// @return number of verteces in a graph Vertex size ( void ) const { return last; } }; // TriRelation #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/tCounter.h0000644000000000000000000000347612112642405017342 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2004 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef _TCOUNTER_H #define _TCOUNTER_H /** define class that allows user to have an integer with restricted * access (i.e. get value, increment and reset). This is useful when * integral value used as a static var of some class */ template class TCounter { public: // type interface /// define integral type of a counter typedef T IntType; protected: // members /// counter itself IntType counter; public: // interface /// init c'tor explicit TCounter ( const IntType n ) : counter(n) {} /// copy c'tor template TCounter ( const TCounter& copy ) : counter(copy.counter) {} /// assignment template TCounter& operator= ( const TCounter& copy ) { counter = copy.counter; return *this; } // operators /// get value of a counter IntType val ( void ) const { return counter; } /// increment value of a counter; @return new value IntType inc ( void ) { return ++counter; } /// set new value of a counter void reset ( const IntType n ) { counter = n; } }; // TCounter #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/PriorityMatrix.h0000644000000000000000000000707612112642405020545 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2011 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef PRIORITYMATRIX_H #define PRIORITYMATRIX_H #include "eFaCTPlusPlus.h" #include "dlVertex.h" // DagTag #include "logging.h" /// number of regular options (o- and NN-rules are not included) const unsigned int nRegularOps = 7; /// priority index for o- and ID operations (note that these ops have the highest priority) const unsigned int iId = nRegularOps+1; /// priority index for <= operation in nominal node const unsigned int iNN = nRegularOps+2; /// Auxiliary class to get priorities on operations class ToDoPriorMatrix { protected: // members // regular operation indexes unsigned int iAnd; unsigned int iOr; unsigned int iExists; unsigned int iForall; unsigned int iLE; unsigned int iGE; public: // interface /// empty c'tor ToDoPriorMatrix ( void ) {} /// empty d'tor ~ToDoPriorMatrix ( void ) {} /// init priorities via given string OPTIONS void initPriorities ( const std::string& options, const char* optionName ); /// get an index corresponding given Op, Sign and NominalNode unsigned int getIndex ( DagTag Op, bool Sign, bool NominalNode ) const; }; // ToDoPriorMatrix inline void ToDoPriorMatrix :: initPriorities ( const std::string& options, const char* optionName ) { // check for correctness if ( options.size () < 7 ) throw EFaCTPlusPlus ( "ToDo List option string should have length 7" ); // init values by symbols loaded iAnd = options[1] - '0'; iOr = options[2] - '0'; iExists = options[3] - '0'; iForall = options[4] - '0'; iLE = options[5] - '0'; iGE = options[6] - '0'; // correctness checking if ( iAnd >= nRegularOps || iOr >= nRegularOps || iExists >= nRegularOps || iForall >= nRegularOps || iGE >= nRegularOps || iLE >= nRegularOps ) throw EFaCTPlusPlus ( "ToDo List option out of range" ); // inform about used rules order if ( LLM.isWritable(llAlways) ) LL << "\nInit " << optionName << " = " << iAnd << iOr << iExists << iForall << iLE << iGE; } inline unsigned int ToDoPriorMatrix :: getIndex ( DagTag Op, bool Sign, bool NominalNode ) const { switch ( Op ) { case dtAnd: return (Sign?iAnd:iOr); case dtSplitConcept: return iAnd; case dtForall: case dtIrr: // process local (ir-)reflexivity as a FORALL return (Sign?iForall:iExists); case dtProj: // it should be the lowest priority but now just OR's one case dtChoose: // probably should be highest branching one return iOr; case dtLE: return (Sign?(NominalNode?iNN:iLE):iGE); case dtDataType: case dtDataValue: case dtDataExpr: case dtNN: case dtTop: // no need to process these ops return nRegularOps; case dtPSingleton: case dtPConcept: // no need to process neg of PC return (Sign?iId:nRegularOps); case dtNSingleton: case dtNConcept: // both NC and neg NC are processed return iId; default: // safety check fpp_unreachable(); } } #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/tOntology.h0000644000000000000000000000702612112642405017530 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2008-2012 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef TONTOLOGY_H #define TONTOLOGY_H #include #include "tDLAxiom.h" #include "tExpressionManager.h" #include "tSplitVars.h" /// define ontology as a set of axioms class TOntology { public: // types /// RW iterator over the base type typedef AxiomVec::iterator iterator; protected: // members /// all the axioms AxiomVec Axioms; /// expression manager that builds all the expressions for the axioms TExpressionManager EManager; /// id to be given to the next axiom unsigned int axiomId; /// index of the 1st unprocessed axiom size_t axiomToProcess; /// true iff ontology was changed bool changed; public: TSplitVars Splits; public: // interface /// empty c'tor TOntology ( void ) : axiomId(0), axiomToProcess(0), changed(false) {} /// d'tor ~TOntology ( void ) { clear(); } /// @return true iff the ontology was changed since its last load bool isChanged ( void ) const { return changed; } /// set the processed marker to the end of the ontology void setProcessed ( void ) { axiomToProcess = Axioms.size(); changed = false; } /// add given axiom to the ontology TDLAxiom* add ( TDLAxiom* p ) { p->setId(++axiomId); Axioms.push_back(p); changed = true; return p; } /// retract given axiom to the ontology void retract ( TDLAxiom* p ) { if ( p->getId() <= Axioms.size() && Axioms[p->getId()-1] == p ) { changed = true; p->setUsed(false); } } /// mark all the axioms as not in the module void clearModuleInfo ( void ) { for ( iterator p = Axioms.begin(), p_end = Axioms.end(); p < p_end; ++p ) (*p)->setInModule(false); } /// clear the ontology void clear ( void ) { for ( iterator p = Axioms.begin(), p_end = Axioms.end(); p < p_end; ++p ) delete *p; Axioms.clear(); EManager.clear(); axiomToProcess = 0; changed = false; } /// get access to an expression manager TExpressionManager* getExpressionManager ( void ) { return &EManager; } // access to axioms /// get RW access to all axioms in the ontology AxiomVec& getAxioms ( void ) { return Axioms; } /// get RO access to all axioms in the ontology const AxiomVec& getAxioms ( void ) const { return Axioms; } /// RW begin() for the whole ontology iterator begin ( void ) { return Axioms.begin(); } /// RW end() for the whole ontology iterator end ( void ) { return Axioms.end(); } /// RW begin() for the unprocessed part of the ontology iterator beginUnprocessed ( void ) { return Axioms.begin()+axiomToProcess; } /// RW end() for the processed part of the ontology iterator endProcessed ( void ) { return beginUnprocessed(); } /// get access to the I'th axiom TDLAxiom* operator [] ( int i ) { return Axioms[i]; } /// size of the ontology size_t size ( void ) const { return Axioms.size(); } }; // TOntology #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/tAxiom.cpp0000644000000000000000000002132312112642405017322 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2010 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "tAxiom.h" #include "tRole.h" #include "dlTBox.h" /// add DLTree to an axiom void TAxiom :: add ( DLTree* p ) { if ( InAx::isBot(p) ) // BOT or X == X return; // nothing to do // flatten the disjunctions on the fly if ( InAx::isOr(p) ) { add(p->Left()); add(p->Right()); delete p; // delete just AND entry, not the trees return; } for ( const_iterator i = begin(), i_end = end(); i != i_end; ++i ) if ( equalTrees(p,*i) ) { deleteTree(p); return; } Disjuncts.push_back(p); } TAxiom* TAxiom :: simplifyCN ( void ) const { for ( const_iterator i = begin(), i_end = end(); i != i_end; ++i ) { const DLTree* p = *i; if ( InAx::isPosNP(p) ) return simplifyPosNP(p); else if ( InAx::isNegNP(p) ) return simplifyNegNP(p); } return NULL; } TAxiom* TAxiom :: simplifyForall ( TBox& KB ) const { for ( const_iterator i = begin(), i_end = end(); i != i_end; ++i ) if ( InAx::isAbsForall(*i) ) return simplifyForall ( *i, KB ); return NULL; } TAxiom* TAxiom :: simplifyForall ( const DLTree* rep, TBox& KB ) const { Stat::SAbsRepForall(); DLTree* pAll = rep->Left(); // (all R ~C) #ifdef RKG_DEBUG_ABSORPTION std::cout << " simplify ALL expression" << pAll; #endif TAxiom* ret = copy(rep); ret->add(KB.getTree(KB.replaceForall(clone(pAll)))); return ret; } DLTree* TAxiom :: createAnAxiom ( const DLTree* skip ) const { // create new OR vertex for the axiom: DLTree* Or = createTop(); for ( const_iterator p = begin(), p_end = end(); p != p_end; ++p ) if ( *p != skip ) Or = createSNFAnd ( clone(*p), Or ); return createSNFNot(Or); } #ifdef RKG_DEBUG_ABSORPTION void TAxiom :: dump ( std::ostream& o ) const { o << " (neg-and"; for ( const_iterator p = begin(), p_end = end(); p != p_end; ++p ) o << *p; o << ")"; } #endif /// absorb into BOTTOM; @return true if absorption is performed bool TAxiom :: absorbIntoBottom ( void ) const { absorptionSet Pos, Neg; for ( const_iterator p = begin(), p_end = end(); p != p_end; ++p ) switch ( (*p)->Element().getToken() ) { case BOTTOM: // axiom in the form T [= T or ...; nothing to do Stat::SAbsBApply(); # ifdef RKG_DEBUG_ABSORPTION std::cout << " Absorb into BOTTOM"; # endif return true; case TOP: // skip it here break; case NOT: // something negated: put it into NEG Neg.push_back((*p)->Left()); break; default: // something positive: save in POS Pos.push_back(*p); break; } // now check whether there is a concept in both POS and NEG for ( const_iterator q = Neg.begin(), q_end = Neg.end(); q != q_end; ++q ) for ( const_iterator s = Pos.begin(), s_end = Pos.end(); s != s_end; ++s ) if ( equalTrees ( *q, *s ) ) { Stat::SAbsBApply(); # ifdef RKG_DEBUG_ABSORPTION std::cout << " Absorb into BOTTOM due to (not" << *q << ") and" << *s; # endif return true; } return false; } bool TAxiom :: absorbIntoTop ( TBox& KB ) const { TConcept* C = NULL; // check whether the axiom is Top [= C for ( const_iterator p = begin(), p_end = end(); p != p_end; ++p ) if ( InAx::isBot(*p) ) // BOTTOMS are fine continue; else if ( InAx::isPosCN(*p) ) // CN found { if ( C != NULL ) // more than one concept return false; C = InAx::getConcept((*p)->Left()); if ( C->isSingleton() ) // doesn't work with nominals return false; } else return false; if ( C == NULL ) return false; // make an absorption Stat::SAbsTApply(); DLTree* desc = KB.makeNonPrimitive ( C, createTop() ); #ifdef RKG_DEBUG_ABSORPTION std::cout << " T-Absorb GCI to axiom"; if ( desc ) std::cout << "s *TOP* [=" << desc << " and"; std::cout << " " << C->getName() << " = *TOP*"; #endif if ( desc ) KB.addSubsumeAxiom ( createTop(), desc ); return true; } bool TAxiom :: absorbIntoConcept ( TBox& KB ) const { WorkSet Cons; DLTree* bestConcept = NULL; // finds all primitive concept names for ( const_iterator p = begin(), p_end = end(); p != p_end; ++p ) if ( InAx::isNegPC(*p) ) // FIXME!! review this during implementation of Nominal Absorption { Stat::SAbsCAttempt(); Cons.push_back(*p); if ( InAx::getConcept(*p)->isSystem() ) bestConcept = *p; } // if no concept names -- return; if ( Cons.empty() ) return false; Stat::SAbsCApply(); // FIXME!! as for now: just take the 1st concept name if ( bestConcept == NULL ) bestConcept = Cons[0]; // normal concept absorption TConcept* Concept = InAx::getConcept(bestConcept); #ifdef RKG_DEBUG_ABSORPTION std::cout << " C-Absorb GCI to concept " << Concept->getName(); if ( Cons.size() > 1 ) { std::cout << " (other options are"; for ( WorkSet::iterator q = Cons.begin(), q_end = Cons.end(); q != q_end; ++q ) if ( *q != bestConcept ) std::cout << " " << InAx::getConcept(*q)->getName(); std::cout << ")"; } #endif // adds a new definition Concept->addDesc(createAnAxiom(bestConcept)); Concept->removeSelfFromDescription(); // in case T [= (A or \neg B) and (B and \neg A) there appears a cycle A [= B [= A // so remove potential cycle // FIXME!! just because TConcept can't get rid of cycle by itself KB.clearRelevanceInfo(); KB.checkToldCycle(Concept); KB.clearRelevanceInfo(); return true; } /// absorb into negation of a concept; @return true if absorption is performed bool TAxiom :: absorbIntoNegConcept ( TBox& KB ) const { WorkSet Cons; TConcept* Concept; const DLTree* bestConcept = NULL; // finds all primitive negated concept names without description for ( const_iterator p = begin(), p_end = end(); p != p_end; ++p ) if ( (*p)->Element().getToken() == NOT && isName((*p)->Left()) && (Concept = InAx::getConcept((*p)->Left()))->isPrimitive() && !Concept->isSingleton() && Concept->Description == NULL ) { Stat::SAbsNAttempt(); Cons.push_back(*p); } // if no concept names -- return; if ( Cons.empty() ) return false; Stat::SAbsNApply(); // FIXME!! as for now: just take the 1st concept name if ( bestConcept == NULL ) bestConcept = Cons[0]; // normal concept absorption Concept = InAx::getConcept(bestConcept->Left()); #ifdef RKG_DEBUG_ABSORPTION std::cout << " N-Absorb GCI to concept " << Concept->getName(); if ( Cons.size() > 1 ) { std::cout << " (other options are"; for ( WorkSet::iterator q = Cons.begin(), q_end = Cons.end(); q != q_end; ++q ) if ( *q != bestConcept ) std::cout << " " << InAx::getConcept((*q)->Left())->getName(); std::cout << ")"; } #endif // replace ~C [= D with C=~notC, notC [= D: // make notC [= D TConcept* nC = KB.getAuxConcept(createAnAxiom(bestConcept)); // define C = ~notC; C had an empty desc, so it's safe not to delete it KB.makeNonPrimitive ( Concept, createSNFNot(KB.getTree(nC)) ); return true; } bool TAxiom :: absorbIntoDomain ( void ) const { WorkSet Cons; const DLTree* bestSome = NULL; // find all forall concepts for ( const_iterator p = begin(), p_end = end(); p != p_end; ++p ) if ( (*p)->Element() == NOT && ( (*p)->Left()->Element() == FORALL // \neg ER.C || (*p)->Left()->Element() == LE )) // \neg >= n R.C { Stat::SAbsRAttempt(); Cons.push_back(*p); // check for the direct domain case if ( (*p)->Left()->Right()->Element() == BOTTOM ) { // found proper absorption candidate bestSome = *p; break; } } // if there are no EXISTS concepts -- return; if ( Cons.empty() ) return false; Stat::SAbsRApply(); TRole* Role; if ( bestSome != NULL ) Role = resolveRole(bestSome->Left()->Left()); else // FIXME!! as for now: just take the 1st role name Role = resolveRole(Cons[0]->Left()->Left()); #ifdef RKG_DEBUG_ABSORPTION std::cout << " R-Absorb GCI to the domain of role " << Role->getName(); if ( Cons.size() > 1 ) { std::cout << " (other options are"; for ( WorkSet::iterator q = Cons.begin(), q_end = Cons.end(); q != q_end; ++q ) if ( *q != bestSome ) std::cout << " " << resolveRole((*q)->Left()->Left())->getName(); std::cout << ")"; } #endif // here bestSome is either actual domain, or END(); both cases are fine Role->setDomain(createAnAxiom(bestSome)); return true; } FaCTpp-src-v1.6.2~dfsg/src/Kernel/tDataType.h0000644000000000000000000000421412112642405017425 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2005-2011 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef TDATATYPE_H #define TDATATYPE_H #include "tDataEntry.h" #include "tNECollection.h" /// class for representing general data type class TDataType: public TNECollection { protected: // members /// data type TDataEntry* Type; /// data type std::vector Expr; private: // no copy /// no copy c'tor TDataType ( const TDataType& ); /// no assignment TDataType& operator = ( const TDataType& ); protected: // methods /// register data value in the datatype virtual void registerNew ( TDataEntry* p ) { p->setHostType(Type); } public: // interface /// c'tor: create the TYPE entry TDataType ( const std::string& name ) : TNECollection(name) { Type = new TDataEntry(name); } /// d'tor: delete data type entry and all the expressions virtual ~TDataType ( void ) { for ( std::vector::iterator p = Expr.begin(), p_end = Expr.end(); p != p_end; ++p ) delete *p; delete Type; } // access to the type /// get RW access to the type entry (useful for relevance etc) TDataEntry* getType ( void ) { return Type; } /// get RO access to the type entry const TDataEntry* getType ( void ) const { return Type; } /// create new expression of the type TDataEntry* getExpr ( void ) { TDataEntry* ret = registerElem(new TDataEntry("expr")); Expr.push_back(ret); return ret; } }; // TDataType #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/LogicFeature.h0000644000000000000000000001012612112642405020076 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2012 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef LOGICFEATURE_H #define LOGICFEATURE_H class TConcept; class TRole; class DLVertex; // contains class for currently used logic's features class LogicFeatures { protected: // types enum lfEnum { lfInvalid = 0, // role description lfTransitiveRoles = (1 << 0), lfRolesSubsumption = (1 << 1), lfDirectRoles = (1 << 2), lfInverseRoles = (1 << 3), lfRangeAndDomain = (1 << 4), lfFunctionalRoles = (1 << 5), // concept description lfSomeConstructor = (1 << 6), lfFConstructor = (1 << 7), lfNConstructor = (1 << 8), lfQConstructor = (1 << 9), lfSingleton = (1 << 10), // global description lfGeneralAxioms = (1 << 11), lfBothRoles = (1 << 12), // new constructions lfSelfRef = (1 << 13), lfTopRole = (1 << 14), }; protected: // members /// all flags in one long unsigned long flags; protected: // methods /// set any flag void setX ( lfEnum val ) { flags |= val; } /// get value of any flag bool getX ( lfEnum val ) const { return !!(flags&val); } public: // interface /// default c'tor LogicFeatures ( void ) : flags(0) {} /// copy c'tor LogicFeatures ( const LogicFeatures& lf ) : flags(lf.flags) {} /// assignment LogicFeatures& operator = ( const LogicFeatures& lf ) { flags = lf.flags; return *this; } /// operator add LogicFeatures& operator |= ( const LogicFeatures& lf ) { flags |= lf.flags; return *this; } /// d'tor ~LogicFeatures ( void ) {} // bool hasInverseRole ( void ) const { return getX(lfDirectRoles) && getX(lfInverseRoles); } bool hasInverseRole ( void ) const { return getX(lfBothRoles); } bool hasRoleHierarchy ( void ) const { return getX(lfRolesSubsumption); } bool hasTransitiveRole ( void ) const { return getX(lfTransitiveRoles); } bool hasSomeAll ( void ) const { return getX(lfSomeConstructor); } bool hasFunctionalRestriction ( void ) const { return getX(lfFConstructor) || getX(lfFunctionalRoles); } bool hasNumberRestriction ( void ) const { return getX(lfNConstructor); } bool hasQNumberRestriction ( void ) const { return getX(lfQConstructor); } bool hasSingletons ( void ) const { return getX(lfSingleton); } bool hasSelfRef ( void ) const { return getX(lfSelfRef); } bool hasTopRole ( void ) const { return getX(lfTopRole); } // overall state /// check whether no flags are set bool empty ( void ) const { return flags == 0; } /// get all the flags at once unsigned long getAllFlags ( void ) const { return flags; } /// set all flags to a given value; @return old value of the flags unsigned long setAllFlags ( unsigned int value ) { unsigned int old = flags; flags = value; return old; } /// clear all the flags void clear ( void ) { setAllFlags(0); } // collect statistic from different things /// get features from given TConcept void fillConceptData ( const TConcept* p ); /// get features from given TRole void fillRoleData ( const TRole* p, bool both ); /// get features from given DAG entry with given sign void fillDAGData ( const DLVertex& v, bool pos ); /// build bothRoles from single Roles flags void mergeRoles ( void ) { if ( getX(lfDirectRoles) && getX(lfInverseRoles) ) setX(lfBothRoles); } /// allow user to set presence of inverse roles void setInverseRoles ( void ) { setX(lfBothRoles); } /// write gathered features void writeState ( void ) const; }; // LogicFeatures #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/counter.h0000644000000000000000000000261212112642405017205 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2010 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef COUNTER_H #define COUNTER_H /// class counter from Wikipedia:curiously recurring template pattern template struct counter { /// number of created T-objects static unsigned int objects_created; /// number of alive T-objects ATM of checking static unsigned int objects_alive; /// c'tor: inc counters counter ( void ) { ++objects_created; ++objects_alive; } /// d'tor: dec counters virtual ~counter ( void ) { --objects_alive; } }; // counter template unsigned int counter::objects_created(0); template unsigned int counter::objects_alive(0); #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/tRareSaveStack.h0000644000000000000000000000445412112642405020416 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2011 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef TRARESAVESTACK_H #define TRARESAVESTACK_H #include #include "globaldef.h" #include "tRestorer.h" /** * Stack for Saving/Restoring rarely changing information. * Uses self-contained Restorer as a way to update state of object. */ class TRareSaveStack { protected: // typedefs /// vector of restorers typedef std::vector TBaseType; protected: // members /// heap of saved objects TBaseType Base; /// current level unsigned int curLevel; public: // interface /// empty c'tor: stack will most likely be empty TRareSaveStack ( void ) : curLevel(InitBranchingLevelValue) {} /// d'tor ~TRareSaveStack ( void ) { clear(); } // stack operations /// inclrement current level void incLevel ( void ) { ++curLevel; } /// check that stack is empty bool empty ( void ) const { return Base.empty(); } /// add a new object to the stack void push ( TRestorer* p ) { p->setLevel(curLevel); Base.push_back(p); } /// get all object from the top of the stack with levels >= LEVEL void restore ( unsigned int level ) { curLevel = level; while ( !Base.empty() ) { TRestorer* cur = Base.back(); if ( cur->level() <= level ) break; // need to restore: restore last element, remove it from stack cur->restore(); delete cur; Base.pop_back(); } } /// clear stack void clear ( void ) { for ( TBaseType::iterator p = Base.begin(), p_end = Base.end(); p < p_end; ++p ) delete *p; Base.clear(); curLevel = InitBranchingLevelValue; } }; // TRareSaveStack #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/mergableLabel.h0000644000000000000000000000421312112642405020243 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2007 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef _MERGABLE_LABEL #define _MERGABLE_LABEL /// implementation of labels that could be compared and merged to each other class mergableLabel { protected: // members /// sample for all equivalent labels mergableLabel* pSample; public: // interface /// empty c'tor mergableLabel ( void ) : pSample(this) {} /// copy c'tor mergableLabel ( mergableLabel& p ) : pSample(p.resolve()) {} /// assignment mergableLabel& operator = ( mergableLabel& p ) { pSample = p.resolve(); return *this; } /// d'tor (does nothing) ~mergableLabel ( void ) {} // general interface /// are 2 labels equal; works only for normalised labels bool operator == ( const mergableLabel& p ) const { return (pSample == p.pSample); } /// are 2 labels different; works only for normalised labels bool operator != ( const mergableLabel& p ) const { return (pSample != p.pSample); } /// make 2 labels equal void merge ( mergableLabel& p ) { mergableLabel* sample = p.resolve(); resolve(); if ( pSample != sample ) pSample->pSample = sample; } /// make label's depth <= 2; @return sample of the label mergableLabel* resolve ( void ) { // check if current node is itself sample if ( !isSample() ) pSample = pSample->resolve(); return pSample; } /// is given lable a sample label bool isSample ( void ) const { return (pSample == this); } }; // mergableLabel #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/ELFNormalizer.h0000644000000000000000000002376212112642405020210 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2011-2012 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef ELFNORMALIZER_H #define ELFNORMALIZER_H #include "ELFAxiomChecker.h" #include "tOntologyPrinterLISP.h" class ELFNormalizer: public DLAxiomVisitorEmpty { protected: /// expression manager to build aux expressions TExpressionManager* pEM; TLISPOntologyPrinter LP; /// set of new/procesed axioms AxiomVec Axioms; /// index of a freah variable unsigned int index; /// true iff the axiom was changed after visiting bool changed; /// true iff RHS is in a form \ER.C bool eRHS; protected: // methods /// process the axiom and mark it unused if necessary void v ( TDLAxiom* ax ) { // std::cout << "Processing "; // ax->accept(LP); ax->accept(*this); if ( changed ) ax->setUsed(false); } /// add axiom to a list void addAxiom ( TDLAxiom* ax ) { // std::cout << "Adding "; // ax->accept(LP); Axioms.push_back(ax); } /// create a new name const TDLConceptExpression* buildFreshName ( void ) { std::stringstream s; s << " ELF_aux_" << ++index; return pEM->Concept(s.str()); } /// split C [= D1 \and \and Dn into C [= D1, C [= Dn bool splitAndRHS ( const TDLConceptExpression* C, const TDLConceptAnd* D ) { if ( D == NULL ) // not an and return false; // make new axioms for ( TDLConceptAnd::iterator p = D->begin(), p_end = D->end(); p != p_end; ++p ) addAxiom(new TDLAxiomConceptInclusion(C,*p)); return true; } /// transform RHS into normalized one. @return a normalized RHS. Set the eRHS flag if it is an existential const TDLConceptExpression* transformExists ( const TDLConceptExpression* D ) { eRHS = false; // RHS now contains only Bot, A, \E R.C const TDLConceptObjectExists* exists = dynamic_cast(D); if ( exists == NULL ) { fpp_assert ( dynamic_cast(D) != NULL || dynamic_cast(D) != NULL || dynamic_cast(D) != NULL); // for LHS return D; } // check the filler const TDLConceptExpression* C = exists->getC(); // if the filler is Bot, then the whole expression is bottom if ( dynamic_cast(C) != NULL ) return C; // if the filler is Top or CN then keep the expression eRHS = true; if ( dynamic_cast(C) != NULL || dynamic_cast(C) != NULL ) return D; // complex filler: replace C with new B and the axiom B = C const TDLConceptExpression* B = buildFreshName(); TDLAxiomEquivalentConcepts::ExpressionArray args; args.push_back(B); args.push_back(C); addAxiom(new TDLAxiomEquivalentConcepts(args)); return pEM->Exists (exists->getOR(), B); } /// transform conjunction into the binary one with named concepts in it; simplify const TDLConceptExpression* normalizeLHSAnd ( const TDLConceptAnd* C ) { if ( C == NULL ) return NULL; std::vector args; TDLConceptAnd::iterator p, p_end = C->end(); // check for bottom argument for ( p = C->begin(); p != p_end; ++p ) if ( dynamic_cast(*p) != NULL ) return *p; // all And is equivalent to bottom // preprocess conjunctions bool change = false; for ( p = C->begin(); p != p_end; ++p ) { if ( unlikely ( dynamic_cast(*p) != NULL ) ) { change = true; continue; // skip Tops there } if ( dynamic_cast(*p) != NULL ) args.push_back(*p); // keep concept name else { // complex expression -- replace with new name const TDLConceptExpression* A = buildFreshName(); // it's enough to use implication here addAxiom(new TDLAxiomConceptInclusion(*p,A)); args.push_back(A); change = true; } } // check already-binary thing if ( !change && args.size() == 2 && !eRHS ) return C; // make conjunction binary // std::cout << "Args.size()==" << args.size() << "\n"; std::vector::iterator q = args.begin(), q_last = args.end()-(eRHS ? 0 : 1); const TDLConceptExpression* B = *q; // check the corner case: singleton conjunction if ( unlikely(args.size() == 1) ) return B; // now we have B1 and ... and Bn [= X while ( ++q != q_last ) { // transform into B1 and B2 [= A, A and... Bn [= X const TDLConceptExpression* A = buildFreshName(); addAxiom(new TDLAxiomConceptInclusion(pEM->And(B,*q),A)); B = A; } // now B and q=q_last are the only conjuncts return eRHS ? B : pEM->And(B,*q); } /// transform LHS into normalized one. @return a normalized LHS const TDLConceptExpression* transformLHS ( const TDLConceptExpression* C ) { // here C is Top, A, AND and Exists // first normalize LHS And to contain only 2 names (or less) const TDLConceptExpression* And = normalizeLHSAnd(dynamic_cast(C)); if ( And != NULL ) C = And; if ( dynamic_cast(C) != NULL ) return C; // LHS is Top,Bot,A and exists bool flag = eRHS; C = transformExists(C); // normalize exists const TDLConceptObjectExists* exists = dynamic_cast(C); if ( likely(exists == NULL) ) return C; if ( flag ) // need intermediate var: can't have ER.X [= ES.D { // make C=ER.X [= B for fresh B const TDLConceptExpression* B = buildFreshName(); addAxiom(new TDLAxiomConceptInclusion(C,B)); return B; } // here ER.X [= A return C; } public: // visitor interface // need only do something with a very few axioms as others doesn't present here /// replace it with C0 [= Ci, Ci [= C0 virtual void visit ( const TDLAxiomEquivalentConcepts& axiom ) { TDLAxiomEquivalentConcepts::iterator p = axiom.begin(), p_end = axiom.end(); const TDLConceptExpression* C = *p; while ( ++p != p_end ) { addAxiom(new TDLAxiomConceptInclusion(C,*p)); addAxiom(new TDLAxiomConceptInclusion(*p,C)); } changed = true; } /// replace with Ci \and Cj [= \bot for 0 <= i < j < n virtual void visit ( const TDLAxiomDisjointConcepts& axiom ) { const TDLConceptExpression* bot = pEM->Bottom(); for ( TDLAxiomDisjointConcepts::iterator p = axiom.begin(), p_end = axiom.end(); p != p_end; ++p ) { // FIXME!! replace with new var strait away if necessary const TDLConceptExpression* C = *p; for ( TDLAxiomDisjointConcepts::iterator q = p+1; q != p_end; ++q ) addAxiom(new TDLAxiomConceptInclusion(pEM->And(C,*q),bot)); } changed = true; } /// the only legal one contains a single element, so is C = D virtual void visit ( const TDLAxiomDisjointUnion& axiom ) { changed = true; // replace it anyway switch ( axiom.size() ) { case 0: // strange, but... return; case 1: // single element, use C=D processing addAxiom(new TDLAxiomConceptInclusion(axiom.getC(),*axiom.begin())); addAxiom(new TDLAxiomConceptInclusion(*axiom.begin(),axiom.getC())); break; default: // impossible here fpp_unreachable(); } } /// normalize equivalence as a number of subsumptions R0 [= Ri, Ri [= R0 virtual void visit ( const TDLAxiomEquivalentORoles& axiom ) { TDLAxiomEquivalentORoles::iterator p = axiom.begin(), p_end = axiom.end(); const TDLObjectRoleExpression* R = *p; while ( ++p != p_end ) { addAxiom(new TDLAxiomORoleSubsumption(R,*p)); addAxiom(new TDLAxiomORoleSubsumption(*p,R)); } changed = true; } /// already canonical virtual void visit ( const TDLAxiomORoleSubsumption& axiom ATTR_UNUSED ) { changed = false; } /// normalize transitivity as role inclusion virtual void visit ( const TDLAxiomRoleTransitive& axiom ) { const TDLObjectRoleExpression* R = axiom.getRole(); pEM->newArgList(); pEM->addArg(R); pEM->addArg(R); addAxiom(new TDLAxiomORoleSubsumption(pEM->Compose(),R)); changed = true; } /// all the job is done here virtual void visit ( const TDLAxiomConceptInclusion& axiom ) { const TDLConceptExpression* C = axiom.getSubC(), *D = axiom.getSupC(); // skip tautologies changed = true; // \bot [= D is skipped if ( unlikely(dynamic_cast(C) != NULL) ) return; // C [= \top is skipped if ( unlikely(dynamic_cast(D) != NULL) ) return; // split the RHS if necessary if ( splitAndRHS (C, dynamic_cast(D)) ) return; // do the transformation itself // RHS now contains only Bot, A, \E R.C const TDLConceptExpression* newD = transformExists(D); const TDLConceptExpression* newC = transformLHS(C); if ( newC == C && newD == D ) changed = false; // nothing changed else // not add axiom if ( likely(dynamic_cast(newC) == NULL) ) addAxiom(new TDLAxiomConceptInclusion(newC,newD)); } virtual void visitOntology ( TOntology& ontology ) { for ( TOntology::iterator p = ontology.begin(), p_end = ontology.end(); p != p_end; ++p ) if ( (*p)->isUsed() ) v(*p); // will add to Axioms during the process, so can't use iterators for ( size_t i = 0; i < Axioms.size(); ++i ) { if ( i%100000 == 0 ) std::cerr << "\nprocessing axiom " << i << " out of " << Axioms.size(); v(Axioms[i]); } for ( AxiomVec::iterator p = Axioms.begin(), p_end = Axioms.end(); p != p_end; ++p ) if ( (*p)->isUsed() ) ontology.add(*p); else delete *p; } ELFNormalizer ( TExpressionManager* p ) : pEM(p), LP(std::cout), index(0) {} virtual ~ELFNormalizer ( void ) {} }; // ELFNormalizer #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/parseTime.h0000644000000000000000000000177112112642405017464 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2011 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef PARSETIME_H #define PARSETIME_H #include /// this function gets a string representing time in an ISO 8601 format and returns time_t value built out of it time_t parseTimeString ( const char* str ); #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/LocalityChecker.h0000644000000000000000000000630112112642405020572 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2011-2012 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef LOCALITYCHECKER_H #define LOCALITYCHECKER_H #include "tSignature.h" /// helper class to set signature and locality class class SigAccessor { protected: // members /// signature of a module const TSignature* sig; public: // interface /// init c'tor SigAccessor ( const TSignature* s ) : sig(s) {} /// empty d'tor virtual ~SigAccessor ( void ) {} // locality flags /// @return true iff concepts not in the signature are treated as TOPs bool topCLocal ( void ) const { return sig->topCLocal(); } /// @return true iff concepts not in the signature are treated as BOTTOMs bool botCLocal ( void ) const { return !topCLocal(); } /// @return true iff roles not in the signature are treated as TOPs bool topRLocal ( void ) const { return sig->topRLocal(); } /// @return true iff roles not in the signature are treated as BOTTOMs bool botRLocal ( void ) const { return !topRLocal(); } // signature-based calls /// @return the signature const TSignature* getSignature ( void ) const { return sig; } /// @return true iff SIGnature does NOT contain given entity bool nc ( const TNamedEntity* entity ) const { return !sig->contains(entity); } }; // SigAccessor /// base class for checking locality of a DL axiom class LocalityChecker: protected SigAccessor, public DLAxiomVisitor { protected: // members /// remember the axiom locality value here bool isLocal; public: // interface /// init c'tor LocalityChecker ( const TSignature* s ) : SigAccessor(s), isLocal(true) {} /// empty d'tor virtual ~LocalityChecker ( void ) {} /// @return true iff an AXIOM is local wrt signature bool local ( const TDLAxiom* axiom ) { axiom->accept(*this); return isLocal; } /// fake method to match the semantic checker's interface virtual void preprocessOntology ( const AxiomVec& s ATTR_UNUSED ) {} /// checking locality of the whole ontology (not very useful, but is required by the interface) virtual void visitOntology ( TOntology& ontology ) { for ( TOntology::iterator p = ontology.begin(), p_end = ontology.end(); p < p_end; ++p ) if ( likely((*p)->isUsed()) ) (*p)->accept(*this); } /// set a new value of a signature (without changing a locality parameters) void setSignatureValue ( const TSignature& Sig ) { TSignature* curSig = const_cast(sig); // bool topC = topCLocal(), topR = topRLocal(); *curSig = Sig; // curSig->setLocality ( topC, topR ); } }; // LocalityChecker #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/tSaveStack.h0000644000000000000000000000351312112642405017577 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2009 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef _TSAVESTACK_H #define _TSAVESTACK_H #include "growingArrayP.h" #include "fpp_assert.h" /** * Template stack for Saving/Restoring internal state of template parameter. * Implemented as a growing array of pointers with more ops */ template class TSaveStack: public growingArrayP { public: // interface /// c'tor: do nothing TSaveStack ( void ) {} /// d'tor: do nothing (all done in ~gaP) virtual ~TSaveStack ( void ) {} // stack operations /// get a new object from the stack;it will be filled by caller T* push ( void ) { this->ensureHeapSize(); return this->Base[this->last++]; } /// get an object from the top of the stack T* pop ( void ) { return this->Base[--this->last]; } /// get an object from a fixed depth T* pop ( unsigned int depth ) { fpp_assert ( this->last >= depth ); this->last = depth; return pop(); } /// get an object from a fixed depth T* top ( unsigned int depth ) { fpp_assert ( this->last >= depth ); this->last = depth; return this->Base[depth-1]; } }; // TSaveStack #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/DataTypeCenter.h0000644000000000000000000001272212112642405020405 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2012 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef DATATYPECENTER_H #define DATATYPECENTER_H #include "tDataType.h" #include "dltree.h" #include "tDataTypeBool.h" class DataTypeReasoner; class DataTypeCenter { protected: // interface /// vector of DATATYPEs typedef std::vector TypesVector; /// iterator (RW) to access types typedef TypesVector::iterator iterator; /// iterator (RO) to access types typedef TypesVector::const_iterator const_iterator; protected: // members /// vector of registered data types; initially contains unrestricted NUMBER and STRING TypesVector Types; protected: // methods /// register new data type void RegisterDataType ( TDataType* p ) { Types.push_back(p); } // iterators /// begin (RW) iterator begin ( void ) { return Types.begin(); } /// end (RW) iterator end ( void ) { return Types.end(); } /// begin (RO) const_iterator begin ( void ) const { return Types.begin(); } /// end (RO) const_iterator end ( void ) const { return Types.end(); } // access to datatypes /// get type corresponding to Numbers TDataType* getNumberDataType ( void ) const { return *begin(); } /// get type corresponding to Strings TDataType* getStringDataType ( void ) const { return *(begin()+1); } /// get type corresponding to Real TDataType* getRealDataType ( void ) const { return *(begin()+2); } /// get type corresponding to Bool TDataType* getBoolDataType ( void ) const { return *(begin()+3); } /// get type corresponding to date-time TDataType* getTimeDataType ( void ) const { return *(begin()+4); } /// get type by name TDataType* getTypeByName ( const std::string& name ) const; /// get type corresponding to given sample TDataType* getTypeBySample ( const TDataEntry* sample ) const { const TDataEntry* type = sample->isBasicDataType() ? sample : sample->getType(); for ( const_iterator p = begin(), p_end = end(); p < p_end; ++p ) if ( type == (*p)->getType() ) return *p; return NULL; } // DLTree wrapping interface /// get DLTree by a given TDE static DLTree* wrap ( const TDataEntry* t ) { return createEntry ( DATAEXPR, const_cast(t) ); } /// get TDE by a given DLTree static TDataEntry* unwrap ( const DLTree* t ) { return static_cast(t->Element().getNE()); } public: // interface // c'tor: create NUMBER and STRING datatypes DataTypeCenter ( void ) { // register primitive DataTypes RegisterDataType(new TDataType("number")); RegisterDataType(new TDataType("string")); RegisterDataType(new TDataType("real")); RegisterDataType(new TDataTypeBool()); RegisterDataType(new TDataType("time")); // fresh DT that doesn't appear in KB. FIXME!! make it as TOP later on RegisterDataType(new TDataType(" ")); } /// d'tor: delete all datatypes ~DataTypeCenter ( void ); // DLTree interface /// get NUMBER DT that can be used in TBox DLTree* getNumberType ( void ) { return wrap(getNumberDataType()->getType()); } /// get STRING DT that can be used in TBox DLTree* getStringType ( void ) { return wrap(getStringDataType()->getType()); } /// get REAL DT that can be used in TBox DLTree* getRealType ( void ) { return wrap(getRealDataType()->getType()); } /// get BOOL DT that can be used in TBox DLTree* getBoolType ( void ) { return wrap(getBoolDataType()->getType()); } /// get TIME DT that can be used in TBox DLTree* getTimeType ( void ) { return wrap(getTimeDataType()->getType()); } /// get fresh DT that can be used in TBox DLTree* getFreshDataType ( void ) { return wrap((*(begin()+5))->getType()); } /// return registered data value by given NAME of a Type, given by SAMPLE DLTree* getDataValue ( const std::string& name, const DLTree* sample ) const { TDataType* type = isConst(sample) ? getStringDataType() : // data top getTypeBySample(unwrap(sample)); return wrap(type->get(name)); // may throw } /// get datatype by its name DLTree* getDataType ( const std::string& name ) { return wrap(getTypeByName(name)->getType()); } /// define named datatype as equal to given EXPR. FIXME!! stub for JNI for now DLTree* getDataType ( const std::string& name ATTR_UNUSED, DLTree* expr ) { return expr; } /// facet for >=/>/getExpr(); // apply appropriate facet to it ret->getFacet()->update ( min, excl, value->getComp() ); deleteTree(val); return wrap(ret); } // reasoning interface /// init DT reasoner void initDataTypeReasoner ( DataTypeReasoner& DTReasoner ) const; /// lock/unlock types for additional elements void setLocked ( bool val ); }; // DataTypeCenter #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/ModuleType.h0000644000000000000000000000157312112642405017622 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2011-2012 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef MODULETYPE_H #define MODULETYPE_H enum ModuleType { M_TOP, M_BOT, M_STAR }; #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/tSplitExpansionRules.cpp0000644000000000000000000001315512112642405022244 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2011-2012 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "tSplitExpansionRules.h" #include "dlDag.h" #include "Modularity.h" #include "tConcept.h" /// init entity map using given DAG. note that this should be done AFTER rule splits are created! void TSplitRules :: initEntityMap ( const DLDag& Dag ) { const size_t size = Dag.size(); EntityMap.resize(size); EntityMap[0] = EntityMap[1] = NULL; for ( size_t i = 2; i < size-1; ++i ) EntityMap[i] = getSingleEntity(Dag[i].getConcept()); } TSplitRules::SigSet TSplitRules :: buildSet ( const TSignature& sig, const TNamedEntity* entity ) { SigSet Set; // std::cout << "Building set for " << entity->getName() << "\n"; for ( TSignature::iterator p = sig.begin(), p_end = sig.end(); p != p_end; ++p ) if ( *p != entity && dynamic_cast(*p) != NULL ) { // std::cout << "In the set: " << (*p)->getName() << "\n"; Set.insert(*p); } // std::cout << "done\n"; // register all elements in the set in PossibleSignature PossibleSignature.insert ( Set.begin(), Set.end() ); return Set; } void TSplitRules :: initSplit ( TSplitVar* split ) { // std::cout << "Processing split for " << split->oldName->getName() << ":\n"; TSplitVar::iterator p = split->begin(), p_end = split->end(); SigSet impSet = buildSet ( p->sig, p->name ); BipolarPointer bp = split->C->pBody+1; // choose-rule stays next to a split-definition of C while ( ++p != p_end ) { if ( p->Module.size() == 1 ) addSplitRule ( buildSet ( p->sig, p->name ), impSet, bp ); else { // make set of all the seed signatures of for p->Module std::set Out; // prepare vector of available entities SigVec Allowed; // std::cout << "\n\n\nMaking split for module with " << p->name->getName(); AxiomVec Module ( p->Module.begin(), p->Module.end() ); // prepare signature for the process TSignature sig = p->sig; prepareStartSig ( Module, sig, Allowed ); // build all the seed sigs for p->sig BuildAllSeedSigs ( Allowed, sig, Module, Out ); for ( std::set::const_iterator q = Out.begin(), q_end = Out.end(); q != q_end; ++q ) addSplitRule ( buildSet ( *q, p->name ), impSet, bp ); } } } void TSplitRules :: prepareStartSig ( const AxiomVec& Module, TSignature& sig, SigVec& Allowed ) const { // remove all defined concepts from signature for ( AxiomVec::const_iterator p = Module.begin(), p_end = Module.end(); p != p_end; ++p ) { const TDLAxiomEquivalentConcepts* ax = dynamic_cast(*p); if ( ax != NULL ) // we don't need class names here for ( TDLAxiomEquivalentConcepts::iterator q = ax->begin(), q_end = ax->end(); q != q_end; ++q ) { // FIXME!! check for the case A=B for named classes const TDLConceptName* cn = dynamic_cast(*q); if ( cn != NULL ) sig.remove(cn); } else { const TDLAxiomConceptInclusion* ci = dynamic_cast(*p); if ( ci == NULL ) continue; // don't need the left-hand part either if it is a name const TDLConceptName* cn = dynamic_cast(ci->getSubC()); if ( cn != NULL ) sig.remove(cn); } } // now put every concept name into Allowed for ( TSignature::iterator r = sig.begin(), r_end = sig.end(); r != r_end; ++r ) if ( dynamic_cast(*r) != NULL ) // concept name Allowed.push_back(*r); } /// build all the seed signatures void TSplitRules :: BuildAllSeedSigs ( const SigVec& Allowed, const TSignature& StartSig, AxiomVec& Module, std::set& Out ) const { // copy the signature TSignature sig = StartSig; // std::cout << "\nBuilding seed signatures:"; // create a set of allowed entities for the next round SigVec RecAllowed, Keepers; TModularizer mod(/*useSem=*/false); SigVec::const_iterator p, p_end; for ( p = Allowed.begin(), p_end = Allowed.end(); p != p_end; ++p ) if ( likely(sig.contains(*p))) { sig.remove(*p); // std::cout << "\nTrying " << (*p)->getName() << ": "; mod.extract ( Module.begin(), Module.end(), sig, M_STAR ); if ( mod.getModule().size() == Module.size() ) { // possible to remove one // std::cout << "remove"; RecAllowed.push_back(*p); } else { // std::cout << "keep"; Keepers.push_back(*p); } sig.add(*p); } // std::cout << "\nDone with " << RecAllowed.size() << " sigs left"; if ( RecAllowed.empty() ) // minimal seed signature { Out.insert(StartSig); return; } if ( !Keepers.empty() ) { for ( p = RecAllowed.begin(), p_end = RecAllowed.end(); p != p_end; ++p ) sig.remove(*p); mod.extract ( Module.begin(), Module.end(), sig, M_STAR ); if ( mod.getModule().size() == Module.size() ) { Out.insert(sig); return; } } // need to try smaller sigs sig = StartSig; for ( p = RecAllowed.begin(), p_end = RecAllowed.end(); p != p_end; ++p ) { sig.remove(*p); BuildAllSeedSigs ( RecAllowed, sig, Module, Out ); sig.add(*p); } } FaCTpp-src-v1.6.2~dfsg/src/Kernel/SigIndex.h0000644000000000000000000001031412112642405017236 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2011-2012 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef SIGINDEX_H #define SIGINDEX_H #include "tDLAxiom.h" #include "tSignature.h" #include "LocalityChecker.h" class SigIndex { public: // types /// RW iterator over set of axioms typedef AxiomVec::iterator iterator; /// RO iterator over set of axioms typedef AxiomVec::const_iterator const_iterator; protected: // types /// map between entities and axioms that contains them in their signature typedef std::map EntityAxiomMap; protected: // members /// map itself EntityAxiomMap Base; /// locality checker LocalityChecker* Checker; /// sets of axioms non-local wrt the empty signature AxiomVec NonLocal[2]; /// empty signature to test the non-locality TSignature emptySig; /// number of registered axioms unsigned int nRegistered; /// number of registered axioms unsigned int nUnregistered; protected: // methods /// add an axiom AX to an axiom set AXIOMS void add ( AxiomVec& axioms, TDLAxiom* ax ) { axioms.push_back(ax); } /// remove an axiom AX from an axiom set AXIOMS void remove ( AxiomVec& axioms, TDLAxiom* ax ) { for ( iterator p = axioms.begin(), p_end = axioms.end(); p != p_end; ++p ) if ( *p == ax ) { *p = axioms.back(); axioms.pop_back(); break; } } /// add axiom AX to the non-local set with top-locality value TOP void checkNonLocal ( TDLAxiom* ax, bool top ) { emptySig.setLocality(top); Checker->setSignatureValue(emptySig); if ( !Checker->local(ax) ) add ( NonLocal[!top], ax ); } // work with axioms /// register an axiom void registerAx ( TDLAxiom* ax ) { for ( TSignature::iterator p = ax->getSignature().begin(), p_end = ax->getSignature().end(); p != p_end; ++p ) add ( Base[*p], ax ); // check whether the axiom is non-local checkNonLocal ( ax, /*top=*/false ); checkNonLocal ( ax, /*top=*/true ); ++nRegistered; } /// unregister an axiom AX void unregisterAx ( TDLAxiom* ax ) { for ( TSignature::iterator p = ax->getSignature().begin(), p_end = ax->getSignature().end(); p != p_end; ++p ) remove ( Base[*p], ax ); // remove from the non-locality remove ( NonLocal[false], ax ); remove ( NonLocal[true], ax ); ++nUnregistered; } public: // interface /// empty c'tor SigIndex ( LocalityChecker* checker ) : Checker(checker), nRegistered(0), nUnregistered(0) {} /// empty d'tor ~SigIndex ( void ) {} // work with axioms /// process an axiom wrt its Used status void processAx ( TDLAxiom* ax ) { if ( ax->isUsed() ) registerAx(ax); else unregisterAx(ax); } /// preprocess given set of axioms void preprocessOntology ( const AxiomVec& axioms ) { for ( const_iterator p = axioms.begin(), p_end = axioms.end(); p != p_end; ++p ) processAx(*p); } /// clear internal structures void clear ( void ) { Base.clear(); NonLocal[0].clear(); NonLocal[1].clear(); } // get the set by the index /// given an entity, return a set of all axioms that tontain this entity in a signature const AxiomVec& getAxioms ( const TNamedEntity* entity ) { return Base[entity]; } /// get the non-local axioms with top-locality value TOP const AxiomVec& getNonLocal ( bool top ) const { return NonLocal[!top]; } // access to statistics /// get number of ever processed axioms unsigned int nProcessedAx ( void ) const { return nRegistered; } /// get number of currently registered axioms unsigned int nRegisteredAx ( void ) const { return nRegistered - nUnregistered; } }; // SigIndex #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/growingArray.h0000644000000000000000000000563412112642405020210 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2009 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef _GROWINGARRAY_H #define _GROWINGARRAY_H #include #include "fpp_assert.h" /// implementation of an array which groves but not shrinkes template class growingArray { public: // types /// define iterator typedef typename std::vector::iterator iterator; /// define const_iterator typedef typename std::vector::const_iterator const_iterator; protected: // members /// body of an aggay std::vector Body; /// index of the element after last actual element in array unsigned int last; public: // interface /// the empty c'tor growingArray ( void ) : last(0) {} /// copy c'tor growingArray ( const growingArray& ga ) : Body(ga.Body), last(ga.last) {} /// assignment growingArray& operator = ( const growingArray& ga ) { Body=ga.Body; last=ga.last; return *this; } /// empty d'tor virtual ~growingArray ( void ) {} /// check whether array is empty bool empty ( void ) const { return ( last == 0 ); } /// make sure array is big enough to keep N elements (leaving 'last' unchanged) void reserve ( unsigned int n ) { if ( n >= Body.size() ) Body.resize(2*n+1); } /// set the last element to given index void resize ( unsigned int n ) { reserve(n); last = n; } /// clear the array void clear ( void ) { last = 0; } /// get the count of elements unsigned int size ( void ) const { return last; } // access to elements /// add the entry to the array void add ( const C& entry ) { reserve(last); Body[last++] = entry; } /// random access (non-const version) C& operator [] ( unsigned int i ) { # ifdef ENABLE_CHECKING fpp_assert ( i < last ); fpp_assert ( last <= Body.size() ); # endif return Body[i]; } /// random access (const version) const C& operator [] ( unsigned int i ) const { # ifdef ENABLE_CHECKING fpp_assert ( i < last ); fpp_assert ( last <= Body.size() ); # endif return Body[i]; } // iterators iterator begin ( void ) { return Body.begin(); } const_iterator begin ( void ) const { return Body.begin(); } iterator end ( void ) { return begin()+last; } const_iterator end ( void ) const { return begin()+last; } }; // growingArray #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/tRelated.h0000644000000000000000000000363112112642405017274 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2010 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef _TRELATED_H #define _TRELATED_H #include "tIndividual.h" #include "tRole.h" /// class for represent individual relation :R class TRelated { public: // members TIndividual* a; TIndividual* b; TRole* R; public: // interface /// empty c'tor TRelated ( void ) : a(NULL), b(NULL), R(NULL) {} /// init c'tor TRelated ( TIndividual* a_, TIndividual* b_, TRole* R_ ) : a(a_), b(b_), R(R_) {} /// copy c'tor TRelated ( const TRelated& c ) : a(c.a), b(c.b), R(c.R) {} /// assignment TRelated& operator = ( const TRelated& c ) { a = c.a; b = c.b; R = c.R; return *this; } /// empty d'tor ~TRelated ( void ) {} /// simplify structure wrt synonyms void simplify ( void ) { R = resolveSynonym(R); a = resolveSynonym(a); b = resolveSynonym(b); a->addRelated(this); } /// get access to role wrt the FROM direction TRole* getRole ( void ) const { return R; } }; // TRelated // TIndividual RELATED-dependent method' implementation inline void TIndividual :: updateToldFromRelated ( void ) { RoleSSet RolesProcessed; updateTold ( RelatedIndex.begin(), RelatedIndex.end(), RolesProcessed ); } #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/Reasoner.cpp0000644000000000000000000005013212112642405017637 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2012 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include #include "Reasoner.h" #include "logging.h" #include "eFPPTimeout.h" // comment the line out for printing tree info before save and after restoring //#define __DEBUG_SAVE_RESTORE // comment the line out for flushing LL after dumping significant piece of info //#define __DEBUG_FLUSH_LL #ifdef USE_REASONING_STATISTICS AccumulatedStatistic* AccumulatedStatistic::root = NULL; #endif DlSatTester :: DlSatTester ( TBox& tbox ) : tBox(tbox) , DLHeap(tbox.DLHeap) , Manager(64) , CGraph(1,this) , TODO(tBox.PriorityMatrix) , DTReasoner(tbox.DLHeap) // It's unsafe to have a cache that touches a nominal in a node; set flagNominals to prevent it , newNodeCache ( true, tBox.nC, tBox.nR ) , newNodeEdges ( false, tBox.nC, tBox.nR ) , GCIs(tbox.GCIs) , bContext(NULL) , tryLevel(InitBranchingLevelValue) , nonDetShift(0) , curNode(NULL) , dagSize(0) { // init static part of CTree CGraph.initContext ( tBox.nSkipBeforeBlock, tBox.useLazyBlocking, tBox.useAnywhereBlocking ); // init datatype reasoner tBox.getDataTypeCenter().initDataTypeReasoner(DTReasoner); // init set of reflexive roles tBox.getORM()->fillReflexiveRoles(ReflexiveRoles); // init blocking statistics clearBlockingStat(); resetSessionFlags(); } /// prerpare Nominal Reasoner to a new job void DlSatTester :: prepareReasoner ( void ) { CGraph.clear(); Stack.clear(); TODO.clear(); pUsed.clear(); nUsed.clear(); SessionGCIs.clear(); curNode = NULL; bContext = NULL; tryLevel = InitBranchingLevelValue; // clear last session information resetSessionFlags(); } bool DlSatTester :: findConcept ( const CWDArray& lab, BipolarPointer p ) { #ifdef ENABLE_CHECKING fpp_assert ( isCorrect(p) ); // sanity checking // constants are not allowed here fpp_assert ( p != bpTOP ); fpp_assert ( p != bpBOTTOM ); #endif incStat(nLookups); return lab.contains(p); } bool DlSatTester :: findConceptClash ( const CWDArray& lab, BipolarPointer p, const DepSet& dep ) { #ifdef ENABLE_CHECKING fpp_assert ( isCorrect(p) ); // sanity checking // constants are not allowed here fpp_assert ( p != bpTOP ); fpp_assert ( p != bpBOTTOM ); #endif incStat(nLookups); for ( const_label_iterator i = lab.begin(), i_end = lab.end(); i < i_end; ++i ) if ( i->bp() == p ) { // create clashSet clashSet = i->getDep(); clashSet.add(dep); return true; } // we are able to insert a concept return false; } addConceptResult DlSatTester :: checkAddedConcept ( const CWDArray& lab, BipolarPointer p, const DepSet& dep ) { #ifdef ENABLE_CHECKING fpp_assert ( isCorrect(p) ); // sanity checking // constants are not allowed here fpp_assert ( p != bpTOP ); fpp_assert ( p != bpBOTTOM ); #endif if ( findConcept ( lab, p ) ) return acrExist; if ( findConceptClash ( lab, inverse(p), dep ) ) return acrClash; // we are able to insert a concept return acrDone; } addConceptResult DlSatTester :: tryAddConcept ( const CWDArray& lab, BipolarPointer bp, const DepSet& dep ) { // check whether C or ~C can occurs in a node label register const BipolarPointer inv_p = inverse(bp); bool canC = isUsed(bp); bool canNegC = isUsed(inv_p); // if either C or ~C is used already, it's not new in a label if ( canC ) { if ( canNegC ) // both C and ~C can be in the label return checkAddedConcept ( lab, bp, dep ); else // C but not ~C can be in the label return findConcept ( lab, bp ) ? acrExist : acrDone; } else { if ( canNegC ) // ~C but not C can be in the label return findConceptClash ( lab, inv_p, dep ) ? acrClash : acrDone; else // neither C nor ~C can be in the label return acrDone; } } bool DlSatTester :: addToDoEntry ( DlCompletionTree* node, const ConceptWDep& C, const char* reason ) { if ( C == bpTOP ) // simplest things first return false; if ( C == bpBOTTOM ) { setClashSet(C.getDep()); if ( LLM.isWritable(llGTA) ) logClash ( node, C ); return true; } const DLVertex& v = DLHeap[C]; DagTag tag = v.Type(); // try to add a concept to a node label switch ( tryAddConcept ( node->label().getLabel(tag), C.bp(), C.getDep() ) ) { case acrClash: // clash -- return if ( LLM.isWritable(llGTA) ) logClash ( node, C ); return true; case acrExist: // already exists -- nothing new return false; case acrDone: // try was done return insertToDoEntry ( node, C, tag, reason ); default: // safety check fpp_unreachable(); } } /// insert P to the label of N; do necessary updates; may return Clash in case of data node N bool DlSatTester :: insertToDoEntry ( DlCompletionTree* node, const ConceptWDep& C, DagTag tag, const char* reason = NULL ) { // we will change current Node => save it if necessary updateLevel ( node, C.getDep() ); CGraph.addConceptToNode ( node, C, tag ); setUsed(C.bp()); if ( node->isCached() ) return correctCachedEntry(node); // add new info in TODO list TODO.addEntry ( node, tag, C ); if ( node->isDataNode() ) // data concept -- run data center for it return checkDataNode ? checkDataClash(node) : false; else if ( LLM.isWritable(llGTA) ) // inform about it logEntry ( node, C, reason ); return false; } //----------------------------------------------------------------------------- //-- internal cache support //----------------------------------------------------------------------------- bool DlSatTester :: canBeCached ( DlCompletionTree* node ) { DlCompletionTree::const_label_iterator p; bool shallow = true; unsigned int size = 0; // check whether node cache is allowed if ( unlikely(!tBox.useNodeCache) ) return false; // nominal nodes can not be cached if ( unlikely(node->isNominalNode()) ) return false; incStat(nCacheTry); // check applicability of the caching for ( p = node->beginl_sc(); p != node->endl_sc(); ++p ) { if ( DLHeap.getCache(p->bp()) == NULL ) { incStat(nCacheFailedNoCache); if ( LLM.isWritable(llGTA) ) LL << " cf(" << p->bp() << ")"; return false; } shallow &= DLHeap.getCache(p->bp())->shallowCache(); ++size; } for ( p = node->beginl_cc(); p != node->endl_cc(); ++p ) { if ( DLHeap.getCache(p->bp()) == NULL ) { incStat(nCacheFailedNoCache); if ( LLM.isWritable(llGTA) ) LL << " cf(" << p->bp() << ")"; return false; } shallow &= DLHeap.getCache(p->bp())->shallowCache(); ++size; } // it's useless to cache shallow nodes if ( shallow && size != 0 ) { incStat(nCacheFailedShallow); if ( LLM.isWritable(llGTA) ) LL << " cf(s)"; return false; } return true; } /// perform caching of the node (it is known that caching is possible) void DlSatTester :: doCacheNode ( DlCompletionTree* node ) { DlCompletionTree::const_label_iterator p; DepSet dep; newNodeCache.clear(); for ( p = node->beginl_sc(); p != node->endl_sc(); ++p ) { dep.add(p->getDep()); // try to merge cache of a node label element with accumulator switch ( newNodeCache.merge(DLHeap.getCache(p->bp())) ) { case csValid: // continue break; case csInvalid: // clash: set the clash-set setClashSet(dep); // fall through default: // caching of node fails return; } } for ( p = node->beginl_cc(); p != node->endl_cc(); ++p ) { dep.add(p->getDep()); // try to merge cache of a node label element with accumulator switch ( newNodeCache.merge(DLHeap.getCache(p->bp())) ) { case csValid: // continue break; case csInvalid: // clash: set the clash-set setClashSet(dep); // fall through default: // caching of node fails return; } } // all concepts in label are mergable; now try to add input arc newNodeEdges.clear(); newNodeEdges.initRolesFromArcs(node); newNodeCache.merge(&newNodeEdges); } modelCacheState DlSatTester :: reportNodeCached ( DlCompletionTree* node ) { doCacheNode(node); enum modelCacheState status = newNodeCache.getState(); switch ( status ) { case csValid: incStat(nCachedSat); if ( LLM.isWritable(llGTA) ) LL << " cached(" << node->getId() << ")"; break; case csInvalid: incStat(nCachedUnsat); break; case csFailed: case csUnknown: incStat(nCacheFailed); if ( LLM.isWritable(llGTA) ) LL << " cf(c)"; status = csFailed; break; default: fpp_unreachable(); } return status; } bool DlSatTester :: correctCachedEntry ( DlCompletionTree* n ) { fpp_assert ( n->isCached() ); // safety check // FIXME!! check if it is possible to leave node cached in more efficient way modelCacheState status = tryCacheNode(n); // uncheck cached node status and add all elements in TODO list if ( status == csFailed ) redoNodeLabel ( n, "uc" ); return usageByState(status); } //----------------------------------------------------------------------------- //-- internal datatype support //----------------------------------------------------------------------------- /// @return true iff given data node contains data contradiction bool DlSatTester :: hasDataClash ( const DlCompletionTree* Node ) { fpp_assert ( Node && Node->isDataNode() ); // safety check DTReasoner.clear(); // data node may contain only "simple" concepts in there for ( DlCompletionTree::const_label_iterator r = Node->beginl_sc(); r != Node->endl_sc(); ++r ) if ( DTReasoner.addDataEntry ( r->bp(), r->getDep() ) ) // clash found return true; return DTReasoner.checkClash(); } bool DlSatTester :: runSat ( void ) { testTimer.Start(); bool result = checkSatisfiability (); testTimer.Stop(); if ( LLM.isWritable(llSatTime) ) LL << "\nChecking time was " << testTimer << " seconds"; testTimer.Reset(); finaliseStatistic(); if ( result ) writeRoot(llRStat); return result; } void DlSatTester :: finaliseStatistic ( void ) { #ifdef USE_REASONING_STATISTICS // add the integer stat values nNodeSaves.set(CGraph.getNNodeSaves()); nNodeRestores.set(CGraph.getNNodeRestores()); // log statistics data if ( LLM.isWritable(llRStat) ) logStatisticData ( LL, /*needLocal=*/true ); // merge local statistics with the global one AccumulatedStatistic::accumulateAll(); #endif // clear global statistics CGraph.clearStatistics(); } bool DlSatTester :: applyReflexiveRoles ( DlCompletionTree* node, const DepSet& dep ) { for ( TRole::const_iterator p = ReflexiveRoles.begin(), p_end = ReflexiveRoles.end(); p != p_end; ++p ) { // create R-loop through the NODE DlCompletionTreeArc* pA = CGraph.addRoleLabel ( node, node, /*isPredEdge=*/false, *p, dep ); if ( setupEdge ( pA, dep, 0 ) ) return true; } // no clash found return false; } bool DlSatTester :: checkSatisfiability ( void ) { unsigned int loop = 0; for (;;) { if ( curNode == NULL ) { if ( TODO.empty() ) // no applicable rules { // do run-once things if ( performAfterReasoning() ) // clash found if ( tunedRestore() ) // no more alternatives return false; // if nothing added -- that's it if ( TODO.empty() ) return true; } const ToDoEntry* curTDE = TODO.getNextEntry (); fpp_assert ( curTDE != NULL ); // setup current context curNode = curTDE->Node; curConcept = curNode->label().getConcept(curTDE->offset); } if ( ++loop == 5000 ) { loop = 0; if ( tBox.isCancelled() ) return false; if ( unlikely(getSatTimeout()) && 1000*(float)testTimer >= getSatTimeout() ) throw EFPPTimeout(); } // here curNode/curConcept are set if ( commonTactic() ) // clash found { if ( tunedRestore() ) // the concept is unsatisfiable return false; } else curNode = NULL; } } /// perform all the actions that should be done once, after all normal rules are not applicable. @return true if the concept is unsat bool DlSatTester :: performAfterReasoning ( void ) { // make sure all blocked nodes are still blocked if ( LLM.isWritable(llGTA) ) { logIndentation(); LL << "ub:"; } CGraph.retestCGBlockedStatus(); if ( LLM.isWritable(llGTA) ) LL << "]"; if ( !TODO.empty() ) return false; // check if any split expansion rule could be fired if ( !tBox.getSplits()->empty() ) { if ( LLM.isWritable(llGTA) ) { logIndentation(); LL << "split:"; } bool clash = checkSplitRules(); if ( LLM.isWritable(llGTA) ) LL << "]"; if ( clash ) return true; if ( !TODO.empty() ) return false; } #ifdef RKG_USE_FAIRNESS // check fairness constraints if ( tBox.hasFC() ) { DlCompletionTree* violator = NULL; // for every given FC, if it is violated, reject current model for ( TBox::ConceptVector::const_iterator p = tBox.Fairness.begin(), p_end = tBox.Fairness.end(); p < p_end; ++p ) { violator = CGraph.getFCViolator((*p)->pName); if ( violator ) { nFairnessViolations.inc(); // try to fix violators if ( addToDoEntry ( violator, (*p)->pName, getCurDepSet(), "fair" ) ) return true; } } if ( !TODO.empty() ) return false; } #endif return false; } //----------------------------------------------------------------------------- // split code implementation //----------------------------------------------------------------------------- /// apply split rule RULE to a reasoner. @return true if clash was found bool DlSatTester :: applySplitRule ( TSplitRules::const_iterator rule ) { DepSet dep; rule->fireDep ( SessionSignature, SessionSigDepSet, dep ); BipolarPointer bp = rule->bp() - 1; // p->bp points to Choose(C) node, p->bp-1 -- to the split node // split became active ActiveSplits.insert(bp); // add corresponding choose to all if ( addSessionGCI ( bp+1, dep ) ) return true; // make sure that all existing splits will be re-applied updateName(bp); return false; } /// check whether any split rules should be run and do it. @return true iff clash was found bool DlSatTester :: checkSplitRules ( void ) { if ( splitRuleLevel == 0 ) // 1st application OR return was made before previous set { ActiveSplits.clear(); SessionSignature.clear(); SessionSigDepSet.clear(); splitRuleLevel = getCurLevel(); } // fills in session signature for current CGraph. combine dep-sets for the same entities updateSessionSignature(); // now for every split expansion rule check whether it can be fired for ( TSplitRules::const_iterator p = tBox.SplitRules.begin(), p_end = tBox.SplitRules.end(); p != p_end; ++p ) if ( likely ( ActiveSplits.count(p->bp()-1) == 0 ) && p->canFire(SessionSignature) ) if ( applySplitRule(p) ) // p->bp points to Choose(C) node, p->bp-1 -- to the split node return true; return false; } /******************************************************************************** * * Save/Restore section * ******************************************************************************/ /// restore local state from BContext void DlSatTester :: restoreBC ( void ) { // restore reasoning context curNode = bContext->curNode; curConcept = bContext->curConcept; pUsed.resize(bContext->pUsedIndex); nUsed.resize(bContext->nUsedIndex); if ( unlikely ( !SessionGCIs.empty() ) ) SessionGCIs.resize(bContext->SGsize); // update branch dep-set updateBranchDep(); bContext->nextOption(); } void DlSatTester :: save ( void ) { // save tree CGraph.save(); // save ToDoList TODO.save(); // increase tryLevel ++tryLevel; Manager.ensureLevel(getCurLevel()); // init BC clearBC(); incStat(nStateSaves); if ( LLM.isWritable(llSRState) ) LL << " ss(" << getCurLevel()-1 << ")"; #ifdef __DEBUG_SAVE_RESTORE writeRoot(llSRState); #endif } void DlSatTester :: restore ( unsigned int newTryLevel ) { fpp_assert ( !Stack.empty () ); fpp_assert ( newTryLevel > 0 ); // skip all intermediate restores setCurLevel(newTryLevel); // update split level if ( getCurLevel() < splitRuleLevel ) splitRuleLevel = 0; // restore local bContext = Stack.top(getCurLevel()); restoreBC(); // restore tree CGraph.restore(getCurLevel()); // restore TODO list TODO.restore(getCurLevel()); incStat(nStateRestores); if ( LLM.isWritable(llSRState) ) LL << " sr(" << getCurLevel() << ")"; #ifdef __DEBUG_SAVE_RESTORE writeRoot(llSRState); #endif } /** * logging methods */ void DlSatTester :: logIndentation ( void ) const { CHECK_LL_RETURN(llGTA); // useless but safe LL << "\n" << std::setw(getCurLevel()) << "["; } void DlSatTester :: logStartEntry ( void ) const { CHECK_LL_RETURN(llGTA); // useless but safe logIndentation(); LL << "("; curNode->logNode (); LL << "," << curConcept << "){"; if ( isNegative (curConcept.bp()) ) LL << "~"; const DLVertex& v = DLHeap[curConcept]; LL << v.getTagName(); if ( const TNamedEntry* entry = v.getConcept() ) LL << "(" << entry->getName() << ")"; LL << "}:"; } void DlSatTester :: logFinishEntry ( bool res ) const { CHECK_LL_RETURN(llGTA); // useless but safe LL << "]"; if ( res ) LL << " Clash" << getClashSet(); #ifdef __DEBUG_FLUSH_LL LL.flush (); #endif } void DlSatTester :: logStatisticData ( std::ostream& o, bool needLocal ) const { #ifdef USE_REASONING_STATISTICS nTacticCalls.Print ( o, needLocal, "\nThere were made ", " tactic operations, of which:" ); nIdCalls.Print ( o, needLocal, "\n CN operations: ", "" ); nSingletonCalls.Print(o, needLocal, "\n including ", " singleton ones" ); nOrCalls.Print ( o, needLocal, "\n OR operations: ", "" ); nOrBrCalls.Print ( o, needLocal, "\n ", " of which are branching" ); nAndCalls.Print ( o, needLocal, "\n AND operations: ", "" ); nSomeCalls.Print ( o, needLocal, "\n SOME operations: ", "" ); nAllCalls.Print ( o, needLocal, "\n ALL operations: ", "" ); nFuncCalls.Print ( o, needLocal, "\n Func operations: ", "" ); nLeCalls.Print ( o, needLocal, "\n LE operations: ", "" ); nGeCalls.Print ( o, needLocal, "\n GE operations: ", "" ); nUseless.Print ( o, needLocal, "\n N/A operations: ", "" ); nNNCalls.Print ( o, needLocal, "\nThere were made ", " NN rule application" ); nMergeCalls.Print ( o, needLocal, "\nThere were made ", " merging operations" ); nAutoEmptyLookups.Print ( o, needLocal, "\nThere were made ", " RA empty transition lookups" ); nAutoTransLookups.Print ( o, needLocal, "\nThere were made ", " RA applicable transition lookups" ); nSRuleAdd.Print ( o, needLocal, "\nThere were made ", " simple rule additions" ); nSRuleFire.Print ( o, needLocal, "\n of which ", " simple rules fired" ); nStateSaves.Print ( o, needLocal, "\nThere were made ", " save(s) of global state" ); nStateRestores.Print ( o, needLocal, "\nThere were made ", " restore(s) of global state" ); nNodeSaves.Print ( o, needLocal, "\nThere were made ", " save(s) of tree state" ); nNodeRestores.Print ( o, needLocal, "\nThere were made ", " restore(s) of tree state" ); nLookups.Print ( o, needLocal, "\nThere were made ", " concept lookups" ); #ifdef RKG_USE_FAIRNESS nFairnessViolations.Print ( o, needLocal, "\nThere were ", " fairness constraints violation" ); #endif nCacheTry.Print ( o, needLocal, "\nThere were made ", " tries to cache completion tree node, of which:" ); nCacheFailedNoCache.Print ( o, needLocal, "\n ", " fails due to cache absence" ); nCacheFailedShallow.Print ( o, needLocal, "\n ", " fails due to shallow node" ); nCacheFailed.Print ( o, needLocal, "\n ", " fails due to cache merge failure" ); nCachedSat.Print ( o, needLocal, "\n ", " cached satisfiable nodes" ); nCachedUnsat.Print ( o, needLocal, "\n ", " cached unsatisfiable nodes" ); #endif if ( !needLocal ) o << "\nThe maximal graph size is " << CGraph.maxSize() << " nodes"; } float DlSatTester :: printReasoningTime ( std::ostream& o ) const { o << "\n SAT takes " << satTimer << " seconds\n SUB takes " << subTimer << " seconds"; return satTimer + subTimer; } FaCTpp-src-v1.6.2~dfsg/src/Kernel/tSaveList.h0000644000000000000000000000604212112642405017445 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2004 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef _TSAVELIST_H #define _TSAVELIST_H /** * template list for Saving/Restoring internal state (saving class is template parameter). * template class should define empty/copy c'tors, member function level() */ template class TSaveList { protected: // internal types /// type of the list element class List : public T { private: // no copy /// copy c'tor (unimplemented) List ( const List& ); /// assignment (unimplemented) List& operator = ( const List& ); public: // members /// pointer to next element List* next; public: // interface /// empty c'tor List ( List* n = NULL ) : next(n) {} /// create object from given one and from given next List ( const T& obj, List* n ) : T(obj), next(n) {} /// d'tor: do nothing ~List ( void ) {} /// clone given sub-list List* clone ( void ) { return new List ( *this, next ? next->clone() : NULL ); } /// clear sub-list void clear ( void ) { if ( next ) { next->clear(); delete next; } } }; // List protected: // members /// pointer to head of list List* head; public: // interface /// empty c'tor TSaveList ( void ) : head(NULL) {} /// copy c'tor TSaveList ( const TSaveList& copy ) : head ( copy.head ? copy.head->clone() : NULL ) {} /// d'tor -- clear stack ~TSaveList ( void ) { clear(); } // stack operations /// check that stack is empty bool empty ( void ) const { return (head == NULL); } /// put empty element to stack; @return pointer to it T* push ( void ) { head = new List ( head ); return head; } /// put given element to stack; @return pointer to it T* push ( const T& el ) { head = new List ( el, head ); return head; } /// get top element from stack T* pop ( void ) { T* ret = head; if ( !empty() ) head = head->next; return ret; } /// get element from stack with given level T* pop ( unsigned int level ) { register List* p = head; while ( p && p->level() > level ) { head = p->next; delete p; p = head; } // here p==head and either both == NULL or points to proper element if ( p ) head = head->next; return p; } // extra operations /// clear the stack void clear ( void ) { if ( !empty() ) { head->clear(); delete head; head = NULL; } } }; // TSaveList #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/configure.cpp0000644000000000000000000001332712112642405020047 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2006 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "configure.h" #include #undef USE_DEBUG Configuration :: ~Configuration ( void ) { for ( ConfSectBase::iterator i = Base.begin (); i != Base.end (); ++i ) delete *i; } ConfSection :: ~ConfSection ( void ) { for ( ConfBase::iterator i = Base.begin (); i != Base.end (); ++i ) delete *i; } ConfSection* Configuration :: FindSection ( const std::string& pc ) const { for ( ConfSectBase::const_iterator i = Base.begin (); i != Base.end (); ++i ) if ( **i == pc ) return *i; // can not find section return (ConfSection*) NULL; } ConfElem* ConfSection :: FindByName ( const std::string& name ) const { for ( ConfBase::const_iterator i = Base.begin (); i != Base.end (); ++i ) if ( (*i)->Name == name ) return *i; // can not find element in section return (ConfElem*) NULL; } // add section; set Section to new pointer. Ret 1 if couldn't. void Configuration :: createSection ( const std::string& name ) { // if section already exists -- nothing to do if ( !useSection ( name ) ) return; Section = new ConfSection ( name ); Base.push_back(Section); isSaved = false; } // add Field.value to current Section; sets Element to new p. bool Configuration :: setValue ( const std::string& Field, const std::string& Value ) { if ( !Section ) return true; //changing things isSaved = false; // check for existing field if ( (Element = Section->FindByName(Field)) ) { Element->Value = Value; return false; } else { Section -> addEntry ( Field, Value ); return !(Element = Section->FindByName(Field)); } } // check if Field exists if Section is set; bool Configuration :: checkValue ( const std::string& Field ) { if ( !Section ) return true; Element = Section->FindByName(Field); return Element == NULL; } // check if Section:Field exists; bool Configuration :: checkValue ( const std::string& Sect, const std::string& Field ) { if ( useSection(Sect) ) return true; Element = Section->FindByName(Field); return Element == NULL; } // Manipulation part void ConfSection :: addEntry ( const std::string& name, const std::string& value ) { #ifdef USE_DEBUG cerr << "\nadd pair \'" << name.c_str() << "\',\'" << value.c_str() << "\' to section \'" << Name.c_str() << "\'"; #endif Base.push_back ( new ConfElem ( name, value ) ); } // Load part int Configuration :: SplitLine ( char*& pName, char*& pValue ) { register char* p = Line; while ( *p && isspace (*p) ) ++p; // skip leading spaces pName = p; // skip the property name for ( ; *p && *p != '='; ++p ) (void)NULL; if (!*p) return 1; // we found '=' pValue = p+1; // the next char after '=' // skip last spaces for ( *p=0, --p; p!=Line && isspace (*p); --p ) *p=0; if ( p == Line && isspace (*p) ) return 2; // here we have name for ( p=pValue; *p && isspace (*p); ++p ) (void)NULL; // skip leading spaces if (!*p) return 3; pValue = p; // skip last spaces for ( p=pValue+strlen(pValue)-1; isspace (*p) && p!=pValue; --p ) *p=0; if ( p == pValue && isspace (*p) ) return 4; #ifdef USE_DEBUG cerr << "\nfound string \'" << pName << "\'=\'" << pValue << "\'"; #endif // all right! return 0; } void Configuration :: loadString ( std::istream& i ) { do i.getline ( Line, MaxConfLineLen ); while ( i && isComment () ); #ifdef USE_DEBUG cerr << "\nload string \'" << Line << "\'"; #endif } bool Configuration :: isComment ( void ) const { size_t n = strlen (Line); if ( n == 0 ) return true; if ( Line [0] == ';' || Line [0] == '#' || ( Line [0] == '/' && Line [1] == '/' ) ) return true; for ( size_t i = 0; i < n; i++ ) if ( !isspace (Line [i]) ) return false; return true; } bool Configuration :: Load ( const char* Filename ) { std::ifstream in ( Filename ); char *pName, *pValue; isLoaded = false; if ( !in ) return true; loadString (in); while ( !in.eof () ) { if ( isSection () ) loadSection (); else return true; do { loadString (in); if ( in.eof () ) break; if ( isSection () ) break; if ( SplitLine ( pName, pValue ) ) return true; if ( setValue ( pName, pValue ) ) return true; } while ( !in.eof () ); } isLoaded = isSaved = true; fileName = Filename; return false; } void Configuration :: loadSection ( void ) { Line [strlen(Line)-1] = (char) 0; // kill ']' of section #ifdef USE_DEBUG cerr << "\nfound section \'" << Line+1 << "\'"; #endif createSection ( Line+1 ); // skip '[' } // Save part void ConfElem :: Save ( std::ostream& o ) const { o << ' ' << Name.c_str () << " = " << Value.c_str () << std::endl; } void ConfSection :: Save ( std::ostream& o ) const { o << "[" << Name.c_str () << "]\n"; for ( ConfBase::const_iterator i = Base.begin (); i != Base.end (); ++i ) (*i)->Save (o); o << std::endl; } bool Configuration :: Save ( const char* Filename ) { std::ofstream o ( Filename ); if ( o.bad () ) return true; for ( ConfSectBase::iterator i = Base.begin (); i != Base.end (); ++i ) (*i)->Save (o); isLoaded = isSaved = true; return false; } FaCTpp-src-v1.6.2~dfsg/src/Kernel/ifOptions.cpp0000644000000000000000000000635512112642405020043 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2009 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "ifOptions.h" #include "configure.h" bool ifOption :: setAValue ( const std::string& s ) { if ( type == iotBool ) // check possible boolean values { if ( s == "0" || s == "off" || s == "no" || s == "false" ) bValue = false; else if ( s == "1" || s == "on" || s == "yes" || s == "true" ) bValue = true; else return true; } else if ( type == iotInt ) // check possible integer values { if ( !isdigit (s[0]) ) return true; else iValue = atoi ( s.c_str() ); } else // text values tValue = s; return false; } /// output in the form of config file void ifOption :: printConfString ( std::ostream& o ) const { // name and type o << "\n;---\n;--- Option '" << optionName.c_str () << "': "; if ( type == iotBool ) o << "boolean"; else if ( type == iotInt ) o << "integer"; else if ( type == iotText ) o << "text"; else // safety check fpp_unreachable(); // description, default, name o << " ---\n;---\n;* " << optionDescription.c_str () << "\n;* Default value: '" << defaultValue.c_str () << "'\n\n; " << optionName.c_str () << " = "; // value if ( type == iotBool ) o << getBool (); else if ( type == iotInt ) o << getInt (); else if ( type == iotText ) o << getText().c_str (); else // safety check fpp_unreachable(); o << "\n"; } const ifOption* ifOptionSet :: locateOption ( const std::string& name ) const { OptionSet::const_iterator p = Base.find ( name ); if ( p == Base.end () ) return NULL; else return p->second; } bool ifOptionSet :: initByConfigure ( Configuration& Config, const std::string& Section ) { // try to load given config section if ( Config.useSection ( Section ) ) return true; // for all registered options for ( OptionSet::iterator p = Base.begin (); p != Base.end (); ++p ) if ( !Config.checkValue ( p->first ) ) // if option located in config file if ( p->second->setAValue ( Config.getValue () ) ) // ... set up its value return true; // can't set value // all done without errors return false; } /// output in the form of config file void ifOptionSet :: printConfig ( std::ostream& o ) const { // print LeveLogger info o << "[LeveLogger]\n\n;--- Logging file name\n file = reasoning.log\n" ";--- Logging level (the less level you give, the less information will be logged)\n allowedLevel = 0\n\n"; // print header o << "\n[Tuning]\n"; for ( OptionSet::const_iterator p = Base.begin (); p != Base.end (); ++p ) p->second->printConfString (o); o << std::endl; } FaCTpp-src-v1.6.2~dfsg/src/Kernel/ToDoList.h0000644000000000000000000002347412112642405017240 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2011 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef TODOLIST_H #define TODOLIST_H #include "globaldef.h" #include "fpp_assert.h" #include "PriorityMatrix.h" /// the entry of TODO table struct ToDoEntry { /// node to include concept DlCompletionTree* Node; /// offset of included concept in Node's label // (it's not possible to use pointers because // std::vector invalidates them) unsigned int offset; /// empty C'tor ToDoEntry ( void ) : Node(NULL), offset(0) {} // for initialisation /// C'tor (init values) ToDoEntry ( DlCompletionTree* n, unsigned int off ) : Node(n), offset(off) {} }; // ToDoEntry /// All-in-one version of arrayToDoTable class ToDoList { protected: // classes /// class for saving/restoring array TODO queue class arrayQueueSaveState { public: // members /// save start point of queue of entries unsigned int sp; /// save end point of queue of entries unsigned int ep; public: // methods /// empty c'tor arrayQueueSaveState ( void ) {} /// empty d'tor ~arrayQueueSaveState ( void ) {} }; // arrayQueueSaveState //-------------------------------------------------------------------------- /// class to represent single queue class arrayQueue { protected: // members /// waiting ops queue growingArray Wait; /// start pointer; points to the 1st element in the queue unsigned int sPointer; public: // interface /// c'tor: init queue with proper size and reset it arrayQueue ( void ) : sPointer(0) { Wait.reserve(50); // initial size Wait.clear(); } /// empty d'tor ~arrayQueue ( void ) {} /// add entry to a queue void add ( DlCompletionTree* node, unsigned int offset ) { Wait.add(ToDoEntry(node,offset)); } /// clear queue void clear ( void ) { sPointer = 0; Wait.clear(); } /// check if queue empty bool empty ( void ) const { return sPointer == Wait.size(); } /// get next entry from the queue; works for non-empty queues const ToDoEntry* get ( void ) { return &(Wait[sPointer++]); } /// save queue content to the given entry void save ( arrayQueueSaveState& tss ) const { tss.sp = sPointer; tss.ep = Wait.size(); } /// restore queue content from the given entry void restore ( const arrayQueueSaveState& tss ) { sPointer = tss.sp; Wait.resize(tss.ep); } }; // arrayQueue //-------------------------------------------------------------------------- /// class for saving/restoring priority queue TODO class queueQueueSaveState { public: // members /// save whole array growingArray Wait; /// save start point of queue of entries unsigned int sp; /// save end point of queue of entries unsigned int ep; /// save flag of queue's consistency bool queueBroken; public: // methods /// empty c'tor queueQueueSaveState ( void ) {} /// empty d'tor ~queueQueueSaveState ( void ) {} }; // queueQueueSaveState //-------------------------------------------------------------------------- /// class to represent single priority queue class queueQueue { protected: // members /// waiting ops queue growingArray Wait; /// start pointer; points to the 1st element in the queue unsigned int sPointer; /// flag for checking whether queue was reordered bool queueBroken; public: // interface /// c'tor: make an empty queue queueQueue ( void ) : sPointer(0), queueBroken(false) {} /// empty d'tor ~queueQueue ( void ) {} /// add entry to a queue void add ( DlCompletionTree* Node, unsigned int offset ) { if ( empty() || // no problems with empty queue and if no priority clashes Wait[Wait.size()-1].Node->getNominalLevel() <= Node->getNominalLevel() ) { Wait.add(ToDoEntry(Node,offset)); return; } // here we need to put e on the proper place unsigned int n = Wait.size(); ToDoEntry e(Node,offset); Wait.add(e); // will be rewritten while ( n > sPointer && Wait[n-1].Node->getNominalLevel() > Node->getNominalLevel() ) { Wait[n] = Wait[n-1]; --n; } Wait[n] = e; queueBroken = true; } /// clear queue void clear ( void ) { sPointer = 0; queueBroken = false; Wait.clear(); } /// check if queue empty bool empty ( void ) const { return sPointer == Wait.size(); } /// get next entry from the queue; works for non-empty queues const ToDoEntry* get ( void ) { return &(Wait[sPointer++]); } /// save queue content to the given entry void save ( queueQueueSaveState& tss ) { tss.queueBroken = queueBroken; tss.sp = sPointer; if ( queueBroken ) // save the whole queue tss.Wait = Wait; else // save just end pointer tss.ep = Wait.size(); queueBroken = false; // clear flag for the next session } /// restore queue content from the given entry void restore ( const queueQueueSaveState& tss ) { queueBroken = tss.queueBroken; sPointer = tss.sp; if ( queueBroken ) // restore the whole queue Wait = tss.Wait; else // save just end pointer Wait.resize(tss.ep); } }; // queueQueue //-------------------------------------------------------------------------- protected: // internal typedefs /// typedef for NN-queue (which should support complete S/R) typedef queueQueue NNQueue; /// typedef for NN-queue's save state typedef queueQueueSaveState NNQueueSaveState; protected: // classes /// class for saving/restoring array TODO table class SaveState { public: // members /// save state for queueID arrayQueueSaveState backupID; /// save state for queueNN NNQueueSaveState backupNN; /// save state of all regular queues arrayQueueSaveState backup[nRegularOps]; /// save number-of-entries to do unsigned int noe; public: // methods /// empty c'tor SaveState ( void ) {} /// empty d'tor ~SaveState ( void ) {} }; // SaveState //-------------------------------------------------------------------------- private: // safety /// no copy c'tor ToDoList ( ToDoList& ); /// no assignment ToDoList& operator = ( ToDoList& ); protected: // members /// waiting ops queue for IDs arrayQueue queueID; /// waiting ops queue for <= ops in nominal nodes NNQueue queueNN; /// waiting ops queues arrayQueue Wait[nRegularOps]; /// stack of saved states TSaveStack SaveStack; /// priority matrix const ToDoPriorMatrix& Matrix; /// number of un-processed entries unsigned int noe; protected: // methods /// save current TODO table content to given saveState entry void saveState ( SaveState* tss ) { queueID.save(tss->backupID); queueNN.save(tss->backupNN); for ( register int i = nRegularOps-1; i >= 0; --i ) Wait[i].save(tss->backup[i]); tss->noe = noe; } /// restore TODO table content from given saveState entry void restoreState ( const SaveState* tss ) { queueID.restore(tss->backupID); queueNN.restore(tss->backupNN); for ( register int i = nRegularOps-1; i >= 0; --i ) Wait[i].restore(tss->backup[i]); noe = tss->noe; } public: /// init c'tor ToDoList ( const ToDoPriorMatrix& matrix ) : Matrix(matrix), noe(0) {} /// d'tor: delete all entries ~ToDoList ( void ) { clear(); } // global methods /// clear TODO table void clear ( void ) { queueID.clear(); queueNN.clear(); for ( register int i = nRegularOps-1; i >= 0; --i ) Wait[i].clear(); SaveStack.clear(); noe = 0; } /// check if TODO table is empty bool empty ( void ) const { return !noe; } // work with entries /// add entry with given NODE and CONCEPT with given OFFSET to the TODO table void addEntry ( DlCompletionTree* node, DagTag type, const ConceptWDep& C, int offset ) { unsigned int index = Matrix.getIndex ( type, isPositive(C.bp()), node->isNominalNode() ); switch ( index ) { case nRegularOps: // unused entry return; case iId: // ID queueID.add(node,offset); break; case iNN: // NN queueNN.add(node,offset); break; default: // regular queue Wait[index].add(node,offset); break; } ++noe; } /// add entry with given NODE and CONCEPT of a TYPE to the ToDo table void addEntry ( DlCompletionTree* node, DagTag type, const ConceptWDep& C ) { addEntry ( node, type, C, node->label().getLast(type) ); } /// get the next TODO entry. @return NULL if the table is empty const ToDoEntry* getNextEntry ( void ); // save/restore methods /// save current state using internal stack void save ( void ) { saveState(SaveStack.push()); } /// restore state using internal stack void restore ( void ) { fpp_assert ( !SaveStack.empty() ); restoreState(SaveStack.pop()); } /// restore state to the given level using internal stack void restore ( unsigned int level ) { restoreState(SaveStack.pop(level)); } }; // ToDoList inline const ToDoEntry* ToDoList :: getNextEntry ( void ) { #ifdef ENABLE_CHECKING fpp_assert ( !empty () ); // safety check #endif // decrease amount of elements-to-process --noe; // check ID queue if ( !queueID.empty() ) return queueID.get(); // check NN queue if ( !queueNN.empty() ) return queueNN.get(); // check regular queues for ( register unsigned int i = 0; i < nRegularOps; ++i ) if ( !Wait[i].empty() ) return Wait[i].get(); // that's impossible, but still... return NULL; } #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/tDataEntry.h0000644000000000000000000002000512112642405017601 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2005-2011 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef TDATAENTRY_H #define TDATAENTRY_H #include #include "tNamedEntry.h" #include "BiPointer.h" #include "tLabeller.h" #include "DataTypeComparator.h" class TDataEntry; // if min() and max() are defined, then they conflicts with a TDI members #undef min #undef max /// class for representing general data restriction class TDataInterval { public: // members /// left border of the interval ComparableDT min; /// right border of the interval ComparableDT max; /// type of the left border bool minExcl; /// type of the right border bool maxExcl; public: // interface /// empty c'tor TDataInterval ( void ) {} /// copy c'tor TDataInterval ( const TDataInterval& copy ) : min(copy.min) , max(copy.max) , minExcl(copy.minExcl) , maxExcl(copy.maxExcl) {} /// assignment TDataInterval& operator = ( const TDataInterval& copy ) { min = copy.min; max = copy.max; minExcl = copy.minExcl; maxExcl = copy.maxExcl; return *this; } /// empty d'tor ~TDataInterval ( void ) {} /// clear an interval void clear ( void ) { min = max = ComparableDT(); } /// check if min value range have been set bool hasMin ( void ) const { return min.inited(); } /// check if max value range have been set bool hasMax ( void ) const { return max.inited(); } /// no constraints bool empty ( void ) const { return !hasMin() && !hasMax(); } /// closed interval bool closed ( void ) const { return hasMin() && hasMax(); } /// update MIN border of an interval with VALUE wrt EXCL bool updateMin ( bool excl, const ComparableDT& value ) { if ( hasMin() ) // another min value: check if we need update { // constraint is >= or > if ( min > value ) // was: {7,}; now: {5,}: no update needed return false; if ( min == value && // was: (5,}; now: [5,}: no update needed minExcl && !excl ) return false; // fallthrough: update is necessary for everything else } min = value; minExcl = min.correctMin(excl); return true; } /// update MAX border of an interval with VALUE wrt EXCL bool updateMax ( bool excl, const ComparableDT& value ) { if ( hasMax() ) // another max value: check if we need update { // constraint is <= or < if ( max < value ) // was: {,5}; now: {,7}: no update needed return false; if ( max == value && // was: {,5); now: {,5]: no update needed maxExcl && !excl ) return false; // fallthrough: update is necessary for everything else } max = value; maxExcl = max.correctMax(excl); return true; } /// update given border of an interval with VALUE wrt EXCL bool update ( bool min, bool excl, const ComparableDT& value ) { return min ? updateMin ( excl, value ) : updateMax ( excl, value ); } /// update wrt another interval bool update ( const TDataInterval& Int ) { bool ret = false; if ( Int.hasMin() ) ret |= updateMin ( Int.minExcl, Int.min ); if ( Int.hasMax() ) ret |= updateMax ( Int.maxExcl, Int.max ); return ret; } /// @return true iff all the data is consistent wrt given TYPE bool consistent ( const ComparableDT& dtype ) const { if ( hasMin() && !min.compatible(dtype) ) return false; if ( hasMax() && !max.compatible(dtype) ) return false; return true; } /// print an interval void Print ( std::ostream& o ) const { if ( hasMin() ) o << (minExcl ? '(' : '[') << min; else o << '{'; o << ','; if ( hasMax() ) o << max << (maxExcl ? ')' : ']'); else o << '}'; } /// print an interval as a LISP; FIXME!! hack void printLISP ( std::ostream& o, const char* type ) const { if ( hasMin() && hasMax() ) o << "(and "; if ( hasMin() ) { o << "(g" << (minExcl ? 't' : 'e') << " (" << type; min.printValue(o); o << "))"; } if ( hasMax() ) { o << "(l" << (maxExcl ? 't' : 'e') << " (" << type; max.printValue(o); o << "))"; } if ( hasMin() && hasMax() ) o << ")"; } }; // TDataInterval /// class for representing general data entry ("name" of data type or data value) class TDataEntry: public TNamedEntry { private: // members /// label to use in relevant-only checks TLabeller::LabelType rel; protected: // members /// corresponding type (Type has NULL in the field) const TDataEntry* Type; /// DAG index of the entry BipolarPointer pName; /// ComparableDT, used only for values ComparableDT comp; /// restriction to the entry TDataInterval Constraints; private: // no copy /// no copy c'tor TDataEntry ( const TDataEntry& ); /// no assignment TDataEntry& operator = ( const TDataEntry& ); protected: // methods /// set COMP for the (typed) data value void setComp ( const std::string& typeName ) { // FIXME!! do the thing properly; unify the usage of DT names if ( typeName == "string" ) comp = ComparableDT(getName()); else if ( typeName == "number" ) comp = ComparableDT(atol(getName())); else if ( typeName == "real" ) comp = ComparableDT((float)atof(getName())); else if ( typeName == "bool" ) // FIXME!! dirty hack comp = ComparableDT(getName()); else if ( typeName == "time" ) comp = ComparableDT ( atol(getName()), 0 ); else // no more types available fpp_unreachable(); } public: // interface /// create data entry with given name TDataEntry ( const std::string& name ) : TNamedEntry(name) , Type(NULL) , pName(bpINVALID) , comp() {} /// empty d'tor ~TDataEntry ( void ) {} // type/value part /// check if data entry represents basic data type bool isBasicDataType ( void ) const { return Type == NULL && Constraints.empty(); } /// check if data entry represents restricted data type bool isRestrictedDataType ( void ) const { return !Constraints.empty(); } /// check if data entry represents data value bool isDataValue ( void ) const { return Type != NULL && Constraints.empty(); } /// set host data type for the data value void setHostType ( const TDataEntry* type ) { Type = type; setComp(type->getName()); } /// get host type const TDataEntry* getType ( void ) const { return Type; } /// get comparable variant of DE const ComparableDT& getComp ( void ) const { return comp; } // facet part /// get RW access to constraints of the DE TDataInterval* getFacet ( void ) { return &Constraints; } /// get RO access to constraints of the DE const TDataInterval* getFacet ( void ) const { return &Constraints; } // relevance part /// is given concept relevant to given Labeller's state bool isRelevant ( const TLabeller& lab ) const { return lab.isLabelled(rel); } /// make given concept relevant to given Labeller's state void setRelevant ( const TLabeller& lab ) { lab.set(rel); } // BP part /// get pointer to DAG entry correstonding to the data entry BipolarPointer getBP ( void ) const { return pName; } /// set DAG index of the data entry void setBP ( BipolarPointer p ) { pName = p; } // printing LISP FIXME!! void printLISP ( std::ostream& o ) const { o << ' '; if ( isBasicDataType() ) o << "(" << getName() << ")"; else if ( isDataValue() ) { o << "(" << getType()->getName(); comp.printValue(o); o << ")"; } else if ( isRestrictedDataType() ) Constraints.printLISP ( o, getType()->getName() ); else fpp_unreachable(); } }; // TDataEntry inline std::ostream& operator << ( std::ostream& o, const TDataInterval& c ) { c.Print(o); return o; } #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/AxiomSplitter.h0000644000000000000000000002746612112642405020350 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2011-2012 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AXIOMSPLITTER_H #define AXIOMSPLITTER_H #include "Modularity.h" #include "SyntacticLocalityChecker.h" #include // possible values: // 0: print nothing // 1: print every start of simplification cycle and final stat // 2: print progress of simplification // 3: print modules #define FPP_DEBUG_SPLIT_MODULES 1 #if FPP_DEBUG_SPLIT_MODULES > 0 # include "procTimer.h" #endif class TAxiomSplitter { protected: // types /// keep the single rename: named concept C in an axiom (C=D or C[=D) into a new name C' and new axiom C'=D or C'[=D struct TRecord { const TDLConceptName* oldName, *newName; AxiomVec oldAxioms; TDLAxiom* newAxiom; TSignature newAxSig; std::set Module; // module for a new axiom /// set old axiom as an equivalent AX; create a new one void setEqAx ( TDLAxiomEquivalentConcepts* ax ) { oldAxioms.push_back(ax); TDLAxiomEquivalentConcepts::ExpressionArray copy; for ( TDLAxiomEquivalentConcepts::iterator p = ax->begin(), p_end = ax->end(); p != p_end; ++p ) if ( *p == oldName ) copy.push_back(newName); else copy.push_back(*p); newAxiom = new TDLAxiomEquivalentConcepts(copy); } /// set a new implication axiom based on a (known) set of old ones void setImpAx ( const TDLConceptExpression* Desc ) { newAxiom = new TDLAxiomConceptInclusion ( newName, Desc ); } }; protected: // members std::set SubNames, Rejects; std::vector Renames, R2; std::map ImpRens; std::map > ImplNames; TLISPOntologyPrinter pr; int newNameId; TModularizer mod; TSignature sig; // seed signature std::set RejSplits; TOntology* O; protected: // methods /// rename old concept into a new one with a fresh name const TDLConceptName* rename ( const TDLConceptName* oldName ) { std::stringstream s; s << oldName->getName() << "+" << ++newNameId; return dynamic_cast(O->getExpressionManager()->Concept(s.str())); } /// process (register/unregister) axioms in a record REC void processRec ( TRecord* rec ) { mod.getSigIndex()->preprocessOntology(rec->oldAxioms); mod.getSigIndex()->processAx(rec->newAxiom); } /// register a record in the ontology void registerRec ( TRecord* rec ) { for ( AxiomVec::iterator p = rec->oldAxioms.begin(), p_end = rec->oldAxioms.end(); p != p_end; ++p ) O->retract(*p); O->add(rec->newAxiom); processRec(rec); } /// unregister a record void unregisterRec ( TRecord* rec ) { for ( AxiomVec::iterator p = rec->oldAxioms.begin(), p_end = rec->oldAxioms.end(); p != p_end; ++p ) (*p)->setUsed(true); rec->newAxiom->setUsed(false); processRec(rec); } /// create a signature of a module corresponding to a new axiom in record void buildSig ( TRecord* rec ) { sig = rec->newAxiom->getSignature(); mod.extract ( *O, sig, M_STAR ); // build a module/signature for the axiom rec->newAxSig = mod.getSignature(); // FIXME!! check that SIG wouldn't change after some axiom retractions rec->Module.clear(); rec->Module.insert ( mod.getModule().begin(), mod.getModule().end() ); #if FPP_DEBUG_SPLIT_MODULES >= 3 std::cout << "\nModule for " << rec->oldName->getName() << ":\n"; for ( std::set::const_iterator z = rec->Module.begin(), z_end = rec->Module.end(); z != z_end; ++z ) (*z)->accept(pr); std::cout << " with module size " << rec->Module.size(); #endif } /// add axiom CI in a form C [= D for D != TOP void addSingleCI ( TDLAxiomConceptInclusion* ci ) { if ( ci != NULL && dynamic_cast(ci->getSupC()) == NULL ) { // skip axioms with RHS=TOP const TDLConceptName* name = dynamic_cast(ci->getSubC()); if ( name != NULL ) { SubNames.insert(name); ImplNames[name].insert(ci); } } } /// register all axioms in a form C [= D void registerCIs ( void ) { // FIXME!! check for the case (not D) [= (not C) later // FIXME!! disjoints here as well for ( TOntology::iterator p = O->begin(), p_end = O->end(); p != p_end; ++p ) if ( (*p)->isUsed() ) addSingleCI(dynamic_cast(*p)); } /// check whether an equivalent axiom is splittable; @return split name or NULL if not splittable const TDLConceptName* getEqSplit ( TDLAxiomEquivalentConcepts* ce ) { // check whether it is not a synonym definition const TDLConceptName* splitName = NULL, *name; size_t size = ce->size(); for ( TDLAxiomEquivalentConcepts::iterator q = ce->begin(), q_end = ce->end(); q != q_end; ++q ) if ( (name = dynamic_cast(*q)) != NULL ) { if ( SubNames.count(name) > 0 ) { // found a split candidate; save the name if ( splitName == NULL ) splitName = name; else // more than one split candidates: do the split right now // FIXME!! now we jump out right now, later on we're going to do the same with changed axiom return splitName; } else --size; } return size > 1 ? splitName : NULL; } /// make the axiom split for the equivalence axiom void makeEqSplit ( TDLAxiomEquivalentConcepts* ce ) { if ( ce == NULL ) return; const TDLConceptName* splitName = getEqSplit(ce); if ( splitName == NULL ) return; // create new record TRecord* rec = new TRecord(); rec->oldName = splitName; rec->newName = rename(splitName); rec->setEqAx(ce); registerRec(rec); // register rec Renames.push_back(rec); // std::cout << "split " << splitName->getName() << " into " << rec->newName->getName() << "\n"; // ce->accept(pr); rec->newAxiom->accept(pr); } /// split all possible EQ axioms void registerEQ ( void ) { // use index instead of iterators will be invalidated during additions for ( size_t i = 0; i < O->size(); ++i ) if ( (*O)[i]->isUsed() ) makeEqSplit(dynamic_cast((*O)[i])); } /// make implication split for a given old NAME TRecord* makeImpSplit ( const TDLConceptName* oldName ) { const TDLConceptName* newName = rename(oldName); // std::cout << "split " << oldName->getName() << " into " << newName->getName() << "\n"; TRecord* rec = new TRecord(); rec->oldName = oldName; rec->newName = newName; O->getExpressionManager()->newArgList(); for ( std::set::iterator s = ImplNames[oldName].begin(), s_end = ImplNames[oldName].end(); s != s_end; ++s ) { rec->oldAxioms.push_back(*s); O->getExpressionManager()->addArg((*s)->getSupC()); // (*s)->accept(pr); } rec->setImpAx(O->getExpressionManager()->And()); registerRec(rec); // rec->newAxiom->accept(pr); return rec; } /// get imp record of a given name; create if necessary TRecord* getImpRec ( const TDLConceptName* oldName ) { if ( ImpRens.find(oldName) == ImpRens.end() ) ImpRens[oldName] = makeImpSplit(oldName); return ImpRens[oldName]; } /// create all the necessary records for the implications void createAllImplications ( void ) { for ( std::vector::iterator r = Renames.begin(), r_end = Renames.end(); r != r_end; ++r ) getImpRec((*r)->oldName); } /// clear modules of Imp and Eq split records void clearModules ( void ) { for ( std::map::iterator p = ImpRens.begin(), p_end = ImpRens.end(); p != p_end; ++p ) p->second->newAxSig.clear(); for ( std::vector::iterator r = Renames.begin(), r_end = Renames.end(); r != r_end; ++r ) (*r)->newAxSig.clear(); } /// check whether the record is independent wrt modularity; @return true iff split was incorrect bool checkSplitCorrectness ( TRecord* rec ) { if ( Rejects.count(rec->oldName) > 0 ) { unsplit: // restore the old axiom, get rid of the new one unregisterRec(rec); // std::cout << "unsplit " << rec->oldName->getName() << "\n"; delete rec; return true; } TRecord* imp = getImpRec(rec->oldName); if ( imp->newAxSig.size() == 0 ) buildSig(imp); buildSig(rec); if ( rec->newAxSig.contains(static_cast(rec->oldName)) || !intersect(rec->newAxSig, imp->newAxSig).empty() ) { // mark name as rejected, un-register imp Rejects.insert(rec->oldName); unregisterRec(imp); goto unsplit; } else // keep the split { R2.push_back(rec); // std::cout << "keep split " << rec->oldName->getName() << "\n"; return false; } } /// move all independent splits in R2; delete all the rest void keepIndependentSplits ( void ) { bool change; # if FPP_DEBUG_SPLIT_MODULES > 0 size_t oSize = Renames.size(); TsProcTimer timer; timer.Start(); # endif do { change = false; # if FPP_DEBUG_SPLIT_MODULES > 0 unsigned int n = Renames.size(); std::cout << "\nCheck split correctness (total " << n << ")..."; # endif clearModules(); for ( std::vector::iterator r = Renames.begin(), r_end = Renames.end(); r != r_end; ++r ) { # if FPP_DEBUG_SPLIT_MODULES > 1 std::cout << "\nCheck split " << r-Renames.begin() << " (of " << n << ")"; # endif change |= checkSplitCorrectness(*r); } Renames.swap(R2); R2.clear(); } while ( change ); # if FPP_DEBUG_SPLIT_MODULES > 0 timer.Stop(); std::cout << "\nThere were made " << Renames.size() << " splits out of " << oSize << " candidates\nIt takes " << timer << " sec"; # endif } /// split all implications corresponding to oldName; @return split pointer TSplitVar* splitImplicationsFor ( const TDLConceptName* oldName ) { // check whether we already did translation for such a name if ( O->Splits.hasCN(oldName) ) return O->Splits.get(oldName); TRecord* rec = getImpRec(oldName); // create new split TSplitVar* split = new TSplitVar(); split->oldName = oldName; split->addEntry ( rec->newName, rec->newAxSig, rec->Module ); O->Splits.set ( oldName, split ); return split; } /// split all implications for which equivalences were split as well void splitImplications ( void ) { for ( std::vector::iterator r = Renames.begin(), r_end = Renames.end(); r != r_end; ++r ) if ( Rejects.count((*r)->oldName) == 0 ) { TSplitVar* split = splitImplicationsFor((*r)->oldName); split->addEntry ( (*r)->newName, (*r)->newAxSig, (*r)->Module ); } else unregisterRec(*r); } public: // interaface /// init c'tor TAxiomSplitter ( TOntology* o ) : pr(std::cout), newNameId(0), mod(/*useSem=*/false), O(o) { mod.preprocessOntology(o->getAxioms()); } /// main split method void buildSplit ( void ) { // first make a set of named concepts C s.t. C [= D is in the ontology registerCIs(); // now check if some of the C's contains in an equivalence axioms registerEQ(); if ( Renames.size() == 0 ) return; // make records for the implications createAllImplications(); // here we have a maximal split; check whether modules are fine keepIndependentSplits(); // now R2 contains all separated axioms; make one replacement for every C [= D axiom splitImplications(); # if FPP_DEBUG_SPLIT_MODULES > 1 std::cout << "\nThere were " << mod.getNNonLocal() << " non-local axioms out of " << mod.getNChecks() << " totally checked"; # endif } }; // TAxiomSplitter #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/DataTypeComparator.h0000644000000000000000000001427412112642405021300 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2005-2011 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef DATATYPECOMPARATOR_H #define DATATYPECOMPARATOR_H #include #include #include #include "fpp_assert.h" #include "globaldef.h" class TDataEntry; /// allows one to compare DataType values wrt appropriate type class ComparableDT { private: /// value as a string std::string strValue; /// value as a number long longIntValue; /// value as a float float floatValue; /// value as a date long timeValue; // FIXME!! FORNOW /// tag of a value enum { UNUSED = 0, INT, STR, FLOAT, TIME } vType; public: /// create empty dt ComparableDT ( void ) : strValue("") , longIntValue(0) , floatValue(0.0) , timeValue(0) , vType(UNUSED) {} /// create NUMBER's dt explicit ComparableDT ( long int value ) : strValue("") , longIntValue(value) , floatValue(0.0) , timeValue(0) , vType(INT) {} /// create STRING's dt explicit ComparableDT ( const char* value ) : strValue(value) , longIntValue(0) , floatValue(0.0) , timeValue(0) , vType(STR) {} /// create FLOAT's dt explicit ComparableDT ( float value ) : strValue("") , longIntValue(0) , floatValue(value) , timeValue(0) , vType(FLOAT) {} /// create dateTime's dt; use dummy to distinguish it from INT one explicit ComparableDT ( long value, int dummy ATTR_UNUSED ) : strValue("") , longIntValue(0) , floatValue(0.0) , timeValue(value) , vType(TIME) {} /// copy c'tor ComparableDT ( const ComparableDT& copy ) : strValue(copy.strValue) , longIntValue(copy.longIntValue) , floatValue(copy.floatValue) , timeValue(copy.timeValue) , vType(copy.vType) {} /// assignment ComparableDT& operator= ( const ComparableDT& copy ) { vType = copy.vType; strValue = copy.strValue; longIntValue = copy.longIntValue; floatValue = copy.floatValue; timeValue = copy.timeValue; return *this; } /// empty d'tor ~ComparableDT ( void ) {} /// get NUMBER long int getLongIntValue ( void ) const { return longIntValue; } /// get STRING const std::string& getStringValue ( void ) const { return strValue; } /// get FLOAT float getFloatValue ( void ) const { return floatValue; } /// get TIME long getTimeValue ( void ) const { return timeValue; } /// check if the datatype is discrete bool hasDiscreteType ( void ) const { return vType == INT || vType == TIME; } /// check whether the comparator is inited bool inited ( void ) const { return vType != UNUSED; } /// check whether the comparator is compatible with another one bool compatible ( const ComparableDT& other ) const { return !inited() || !other.inited() || vType == other.vType; } /// correct min value if the DT is discrete and EXCL is true; @return new EXCL value bool correctMin ( bool excl ) { if ( vType == INT && excl ) { // transform (n,} into [n+1,} longIntValue++; return false; } if ( vType == TIME && excl ) { // transform (n,} into [n+1,} timeValue++; return false; } return excl; } /// correct max value if the DT is discrete and EXCL is true; @return new EXCL value bool correctMax ( bool excl ) { if ( vType == INT && excl ) { // transform (n,} into [n+1,} longIntValue--; return false; } if ( vType == TIME && excl ) { // transform (n,} into [n+1,} timeValue--; return false; } return excl; } // compare 2 values /// check whether 2 DT entries with the same TYPE are equal bool operator == ( const ComparableDT& other ) const { fpp_assert ( vType == other.vType ); // sanity check switch ( vType ) { case INT: return getLongIntValue() == other.getLongIntValue(); case STR: return getStringValue() == other.getStringValue(); case FLOAT: return getFloatValue() == other.getFloatValue(); case TIME: return getTimeValue() == other.getTimeValue(); default: fpp_unreachable(); return false; } } /// check whether 2 DT entries with the same TYPE are NOT equal bool operator != ( const ComparableDT& other ) const { return !(*this == other); } /// check whether 2 DT entries with the same TYPE are in '<' relation bool operator < ( const ComparableDT& other ) const { fpp_assert ( vType == other.vType ); // sanity check switch ( vType ) { case INT: return getLongIntValue() < other.getLongIntValue(); case STR: return getStringValue() < other.getStringValue(); case FLOAT: return getFloatValue() < other.getFloatValue(); case TIME: return getTimeValue() < other.getTimeValue(); default: fpp_unreachable(); return false; } } /// check whether 2 DT entries with the same TYPE are in '>' relation bool operator > ( const ComparableDT& other ) const { return other < *this; } /// print the LISP value of a DTC; FIXME!! hack std::ostream& printValue ( std::ostream& o ) const { o << ' '; switch ( vType ) { case INT: o << getLongIntValue(); break; case FLOAT: o << getFloatValue(); break; case STR: o << '"' << getStringValue().c_str() << '"'; break; case TIME: o << getTimeValue(); break; default: fpp_unreachable(); } return o; } friend std::ostream& operator << ( std::ostream& o, const ComparableDT& cdt ); }; // ComparableDT inline std::ostream& operator << ( std::ostream& o, const ComparableDT& cdt ) { switch ( cdt.vType ) { case ComparableDT::INT: o << cdt.getLongIntValue(); break; case ComparableDT::STR: o << cdt.getStringValue().c_str(); break; case ComparableDT::FLOAT: o << cdt.getFloatValue(); break; case ComparableDT::TIME: o << cdt.getTimeValue(); break; default: fpp_unreachable(); } return o; } #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/tOntologyAtom.h0000644000000000000000000000710512112642405020347 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2011-2012 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef TONTOLOGYATOM_H #define TONTOLOGYATOM_H #include #include "tDLAxiom.h" /// representation of the ontology atom class TOntologyAtom { protected: // internal types /// type to compare 2 atoms struct AtomLess { bool operator()(const TOntologyAtom* a1, const TOntologyAtom* a2) const { return a1->getId() < a2->getId(); } }; public: // typedefs /// set of axioms typedef AxiomVec AxiomSet; /// set of atoms typedef std::set AtomSet; protected: // members /// set of axioms in the atom AxiomSet AtomAxioms; /// set of axioms in the module (Atom's ideal) AxiomSet ModuleAxioms; /// set of atoms current one depends on AtomSet DepAtoms; /// set of all atoms current one depends on AtomSet AllDepAtoms; /// unique atom's identifier size_t Id; protected: // methods /// remove all atoms in AllDepAtoms from DepAtoms void filterDep ( void ) { for ( AtomSet::iterator p = AllDepAtoms.begin(), p_end = AllDepAtoms.end(); p != p_end; ++p ) DepAtoms.erase(*p); } /// build all dep atoms; filter them from DepAtoms void buildAllDepAtoms ( AtomSet& checked ) { // first gather all dep atoms from all known dep atoms for ( AtomSet::iterator p = DepAtoms.begin(), p_end = DepAtoms.end(); p != p_end; ++p ) { AtomSet Dep = (*p)->getAllDepAtoms(checked); AllDepAtoms.insert ( Dep.begin(), Dep.end() ); } // now filter them out from known dep atoms filterDep(); // add direct deps to all deps AllDepAtoms.insert ( DepAtoms.begin(), DepAtoms.end() ); // now the atom is checked checked.insert(this); } public: // interface /// empty c'tor TOntologyAtom ( void ) : Id(0) {} /// d'tor ~TOntologyAtom ( void ) {} // fill in the sets /// set the module axioms void setModule ( const AxiomSet& module ) { ModuleAxioms = module; } /// add axiom AX to an atom void addAxiom ( TDLAxiom* ax ) { AtomAxioms.push_back(ax); ax->setAtom(this); } /// add atom to the dependency set void addDepAtom ( TOntologyAtom* atom ) { if ( likely(atom != NULL) && atom != this ) DepAtoms.insert(atom); } /// get all the atoms the current one depends on; build this set if necessary const AtomSet& getAllDepAtoms ( AtomSet& checked ) { if ( checked.count(this) == 0 ) // not build yet buildAllDepAtoms(checked); return AllDepAtoms; } // access to axioms /// get all the atom's axioms const AxiomSet& getAtomAxioms ( void ) const { return AtomAxioms; } /// get all the module axioms const AxiomSet& getModule ( void ) const { return ModuleAxioms; } /// get atoms a given one depends on const AtomSet& getDepAtoms ( void ) const { return DepAtoms; } /// get the value of the id size_t getId() const { return Id; } /// set the value of the id to ID void setId ( size_t id ) { Id = id; } }; // TOntologyAtom #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/tDLExpression.h0000644000000000000000000015606712112642405020307 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2010-2012 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef TDLEXPRESSION_H #define TDLEXPRESSION_H #include #include #include "globaldef.h" #include "eFaCTPlusPlus.h" #include "fpp_assert.h" #include "tNameSet.h" // forward declaration for all expression classes: necessary for the visitor pattern class TDLExpression; class TDLConceptExpression; class TDLConceptTop; class TDLConceptBottom; class TDLConceptName; class TDLConceptNot; class TDLConceptAnd; class TDLConceptOr; class TDLConceptOneOf; class TDLConceptObjectRoleExpression; class TDLConceptObjectSelf; class TDLConceptObjectValue; class TDLConceptObjectRCExpression; class TDLConceptObjectExists; class TDLConceptObjectForall; class TDLConceptObjectCardinalityExpression; class TDLConceptObjectMinCardinality; class TDLConceptObjectMaxCardinality; class TDLConceptObjectExactCardinality; class TDLConceptDataRoleExpression; class TDLConceptDataValue; class TDLConceptDataRVExpression; class TDLConceptDataExists; class TDLConceptDataForall; class TDLConceptDataCardinalityExpression; class TDLConceptDataMinCardinality; class TDLConceptDataMaxCardinality; class TDLConceptDataExactCardinality; class TDLIndividualExpression; class TDLIndividualName; class TDLRoleExpression; class TDLObjectRoleComplexExpression; class TDLObjectRoleExpression; class TDLObjectRoleTop; class TDLObjectRoleBottom; class TDLObjectRoleName; class TDLObjectRoleInverse; class TDLObjectRoleChain; class TDLObjectRoleProjectionFrom; class TDLObjectRoleProjectionInto; class TDLDataRoleExpression; class TDLDataRoleTop; class TDLDataRoleBottom; class TDLDataRoleName; class TDLDataExpression; class TDLDataTop; class TDLDataBottom; class TDLDataTypeExpression; class TDLDataTypeName; class TDLDataTypeRestriction; class TDLDataValue; class TDLDataNot; class TDLDataAnd; class TDLDataOr; class TDLDataOneOf; class TDLFacetExpression; class TDLFacetMinInclusive; class TDLFacetMinExclusive; class TDLFacetMaxInclusive; class TDLFacetMaxExclusive; //class TDLFacetLength; //class TDLFacetMinLength; //class TDLFacetMaxLength; //class TDLFacetPattern; //class TDLFacetLangRange; /// general visitor for DL expressions class DLExpressionVisitor { public: // visitor interface // concept expressions virtual void visit ( const TDLConceptTop& expr ) = 0; virtual void visit ( const TDLConceptBottom& expr ) = 0; virtual void visit ( const TDLConceptName& expr ) = 0; virtual void visit ( const TDLConceptNot& expr ) = 0; virtual void visit ( const TDLConceptAnd& expr ) = 0; virtual void visit ( const TDLConceptOr& expr ) = 0; virtual void visit ( const TDLConceptOneOf& expr ) = 0; virtual void visit ( const TDLConceptObjectSelf& expr ) = 0; virtual void visit ( const TDLConceptObjectValue& expr ) = 0; virtual void visit ( const TDLConceptObjectExists& expr ) = 0; virtual void visit ( const TDLConceptObjectForall& expr ) = 0; virtual void visit ( const TDLConceptObjectMinCardinality& expr ) = 0; virtual void visit ( const TDLConceptObjectMaxCardinality& expr ) = 0; virtual void visit ( const TDLConceptObjectExactCardinality& expr ) = 0; virtual void visit ( const TDLConceptDataValue& expr ) = 0; virtual void visit ( const TDLConceptDataExists& expr ) = 0; virtual void visit ( const TDLConceptDataForall& expr ) = 0; virtual void visit ( const TDLConceptDataMinCardinality& expr ) = 0; virtual void visit ( const TDLConceptDataMaxCardinality& expr ) = 0; virtual void visit ( const TDLConceptDataExactCardinality& expr ) = 0; // individual expressions virtual void visit ( const TDLIndividualName& expr ) = 0; // object role expressions virtual void visit ( const TDLObjectRoleTop& expr ) = 0; virtual void visit ( const TDLObjectRoleBottom& expr ) = 0; virtual void visit ( const TDLObjectRoleName& expr ) = 0; virtual void visit ( const TDLObjectRoleInverse& expr ) = 0; virtual void visit ( const TDLObjectRoleChain& expr ) = 0; virtual void visit ( const TDLObjectRoleProjectionFrom& expr ) = 0; virtual void visit ( const TDLObjectRoleProjectionInto& expr ) = 0; // data role expressions virtual void visit ( const TDLDataRoleTop& expr ) = 0; virtual void visit ( const TDLDataRoleBottom& expr ) = 0; virtual void visit ( const TDLDataRoleName& expr ) = 0; // data expressions virtual void visit ( const TDLDataTop& expr ) = 0; virtual void visit ( const TDLDataBottom& expr ) = 0; virtual void visit ( const TDLDataTypeName& expr ) = 0; virtual void visit ( const TDLDataTypeRestriction& expr ) = 0; virtual void visit ( const TDLDataValue& expr ) = 0; virtual void visit ( const TDLDataNot& expr ) = 0; virtual void visit ( const TDLDataAnd& expr ) = 0; virtual void visit ( const TDLDataOr& expr ) = 0; virtual void visit ( const TDLDataOneOf& expr ) = 0; // facets virtual void visit ( const TDLFacetMinInclusive& expr ) = 0; virtual void visit ( const TDLFacetMinExclusive& expr ) = 0; virtual void visit ( const TDLFacetMaxInclusive& expr ) = 0; virtual void visit ( const TDLFacetMaxExclusive& expr ) = 0; // other methods virtual ~DLExpressionVisitor ( void ) {} }; // DLExpressionVisitor /// empty visitor for DL expressions implementation class DLExpressionVisitorEmpty: public DLExpressionVisitor { public: // visitor interface // concept expressions virtual void visit ( const TDLConceptTop& expr ATTR_UNUSED ) {} virtual void visit ( const TDLConceptBottom& expr ATTR_UNUSED ) {} virtual void visit ( const TDLConceptName& expr ATTR_UNUSED ) {} virtual void visit ( const TDLConceptNot& expr ATTR_UNUSED ) {} virtual void visit ( const TDLConceptAnd& expr ATTR_UNUSED ) {} virtual void visit ( const TDLConceptOr& expr ATTR_UNUSED ) {} virtual void visit ( const TDLConceptOneOf& expr ATTR_UNUSED ) {} virtual void visit ( const TDLConceptObjectSelf& expr ATTR_UNUSED ) {} virtual void visit ( const TDLConceptObjectValue& expr ATTR_UNUSED ) {} virtual void visit ( const TDLConceptObjectExists& expr ATTR_UNUSED ) {} virtual void visit ( const TDLConceptObjectForall& expr ATTR_UNUSED ) {} virtual void visit ( const TDLConceptObjectMinCardinality& expr ATTR_UNUSED ) {} virtual void visit ( const TDLConceptObjectMaxCardinality& expr ATTR_UNUSED ) {} virtual void visit ( const TDLConceptObjectExactCardinality& expr ATTR_UNUSED ) {} virtual void visit ( const TDLConceptDataValue& expr ATTR_UNUSED ) {} virtual void visit ( const TDLConceptDataExists& expr ATTR_UNUSED ) {} virtual void visit ( const TDLConceptDataForall& expr ATTR_UNUSED ) {} virtual void visit ( const TDLConceptDataMinCardinality& expr ATTR_UNUSED ) {} virtual void visit ( const TDLConceptDataMaxCardinality& expr ATTR_UNUSED ) {} virtual void visit ( const TDLConceptDataExactCardinality& expr ATTR_UNUSED ) {} // individual expressions virtual void visit ( const TDLIndividualName& expr ATTR_UNUSED ) {} // object role expressions virtual void visit ( const TDLObjectRoleTop& expr ATTR_UNUSED ) {} virtual void visit ( const TDLObjectRoleBottom& expr ATTR_UNUSED ) {} virtual void visit ( const TDLObjectRoleName& expr ATTR_UNUSED ) {} virtual void visit ( const TDLObjectRoleInverse& expr ATTR_UNUSED ) {} virtual void visit ( const TDLObjectRoleChain& expr ATTR_UNUSED ) {} virtual void visit ( const TDLObjectRoleProjectionFrom& expr ATTR_UNUSED ) {} virtual void visit ( const TDLObjectRoleProjectionInto& expr ATTR_UNUSED ) {} // data role expressions virtual void visit ( const TDLDataRoleTop& expr ATTR_UNUSED ) {} virtual void visit ( const TDLDataRoleBottom& expr ATTR_UNUSED ) {} virtual void visit ( const TDLDataRoleName& expr ATTR_UNUSED ) {} // data expressions virtual void visit ( const TDLDataTop& expr ATTR_UNUSED ) {} virtual void visit ( const TDLDataBottom& expr ATTR_UNUSED ) {} virtual void visit ( const TDLDataTypeName& expr ATTR_UNUSED ) {} virtual void visit ( const TDLDataTypeRestriction& expr ATTR_UNUSED ) {} virtual void visit ( const TDLDataValue& expr ATTR_UNUSED ) {} virtual void visit ( const TDLDataNot& expr ATTR_UNUSED ) {} virtual void visit ( const TDLDataAnd& expr ATTR_UNUSED ) {} virtual void visit ( const TDLDataOr& expr ATTR_UNUSED ) {} virtual void visit ( const TDLDataOneOf& expr ATTR_UNUSED ) {} // facets virtual void visit ( const TDLFacetMinInclusive& expr ATTR_UNUSED ) {} virtual void visit ( const TDLFacetMinExclusive& expr ATTR_UNUSED ) {} virtual void visit ( const TDLFacetMaxInclusive& expr ATTR_UNUSED ) {} virtual void visit ( const TDLFacetMaxExclusive& expr ATTR_UNUSED ) {} // other methods virtual ~DLExpressionVisitorEmpty ( void ) {} }; // DLExpressionVisitorEmpty /// base class for the DL expression, which include concept-, (data)role-, individual-, and data ones class TDLExpression { public: // interface /// empty c'tor TDLExpression ( void ) {} /// empty d'tor: note that no deep delete is necessary as all the elements are RO virtual ~TDLExpression ( void ) {} /// accept method for the visitor pattern virtual void accept ( DLExpressionVisitor& visitor ) const = 0; }; // TDLExpression //------------------------------------------------------------------ // helper classes //------------------------------------------------------------------ class TNamedEntry; //------------------------------------------------------------------ /// named entity //------------------------------------------------------------------ class TNamedEntity { protected: // members /// name of the entity std::string Name; /// translated version of it TNamedEntry* entry; public: // interface /// c'tor: initialise name TNamedEntity ( const std::string& name ) : Name(name), entry(NULL) {} /// empty d'tor virtual ~TNamedEntity ( void ) {} /// get access to the name const char* getName ( void ) const { return Name.c_str(); } /// get access to the element itself const TNamedEntity* getEntity ( void ) const { return this; } /// set entry void setEntry ( TNamedEntry* e ) { entry = e; } /// get entry TNamedEntry* getEntry ( void ) const { return entry; } }; // TNamedEntity //------------------------------------------------------------------ /// concept argument //------------------------------------------------------------------ class TConceptArg { protected: // members /// concept argument const TDLConceptExpression* C; public: // interface /// init c'tor TConceptArg ( const TDLConceptExpression* c ) : C(c) {} /// empty d'tor virtual ~TConceptArg ( void ) {} /// get access to the argument const TDLConceptExpression* getC ( void ) const { return C; } }; // TConceptArg //------------------------------------------------------------------ /// individual argument //------------------------------------------------------------------ class TIndividualArg { protected: // members /// individual argument const TDLIndividualExpression* I; public: // interface /// init c'tor TIndividualArg ( const TDLIndividualExpression* i ) : I(i) {} /// empty d'tor virtual ~TIndividualArg ( void ) {} /// get access to the argument const TDLIndividualExpression* getI ( void ) const { return I; } }; // TIndividualArg //------------------------------------------------------------------ /// numerical argument //------------------------------------------------------------------ class TNumberArg { protected: // members /// number argument unsigned int N; public: // interface /// init c'tor TNumberArg ( unsigned int n ) : N(n) {} /// empty d'tor virtual ~TNumberArg ( void ) {} /// get access to the argument unsigned int getNumber ( void ) const { return N; } }; // TNumberArg //------------------------------------------------------------------ /// object role argument //------------------------------------------------------------------ class TObjectRoleArg { protected: // members /// object role argument const TDLObjectRoleExpression* OR; public: // interface /// init c'tor TObjectRoleArg ( const TDLObjectRoleExpression* oR ) : OR(oR) {} /// empty d'tor virtual ~TObjectRoleArg ( void ) {} /// get access to the argument const TDLObjectRoleExpression* getOR ( void ) const { return OR; } }; // TObjectRoleArg //------------------------------------------------------------------ /// data role argument //------------------------------------------------------------------ class TDataRoleArg { protected: // members /// data role argument const TDLDataRoleExpression* DR; public: // interface /// init c'tor TDataRoleArg ( const TDLDataRoleExpression* dR ) : DR(dR) {} /// empty d'tor virtual ~TDataRoleArg ( void ) {} /// get access to the argument const TDLDataRoleExpression* getDR ( void ) const { return DR; } }; // TDataRoleArg //------------------------------------------------------------------ /// data expression argument (templated with the exact type) //------------------------------------------------------------------ template class TDataExpressionArg { protected: // members /// data expression argument const TExpression* Expr; public: // interface /// init c'tor TDataExpressionArg ( const TExpression* expr ) : Expr(expr) {} /// empty d'tor virtual ~TDataExpressionArg ( void ) {} /// get access to the argument const TExpression* getExpr ( void ) const { return Expr; } }; // TDataExpressionArg //------------------------------------------------------------------ /// general n-argument expression //------------------------------------------------------------------ template class TDLNAryExpression { public: // types /// base type typedef std::vector ArgumentArray; /// RW iterator over base type typedef typename ArgumentArray::const_iterator iterator; /// input array type typedef std::vector ExpressionArray; /// RW input iterator typedef ExpressionArray::const_iterator i_iterator; protected: // members /// set of equivalent concept descriptions ArgumentArray Base; /// name for excepion depending on class name and direction std::string EString; protected: // methods /// transform general expression into the argument one const Argument* transform ( const TDLExpression* arg ) const { const Argument* p = dynamic_cast(arg); if ( p == NULL ) throw EFaCTPlusPlus(EString.c_str()); return p; } public: // interface /// c'tor: build an error string TDLNAryExpression ( const char* typeName, const char* className ) { EString = "Expected "; EString += typeName; EString += " argument in the '"; EString += className; EString += "' expression"; } /// empty d'tor virtual ~TDLNAryExpression ( void ) {} /// @return true iff the expression has no elements bool empty ( void ) const { return Base.empty(); } /// @return number of elements size_t size ( void ) const { return Base.size(); } // add elements to the array /// add a single element to the array void add ( const TDLExpression* p ) { Base.push_back(transform(p)); } /// add a range to the array void add ( i_iterator b, i_iterator e ) { for ( ; b != e; ++b ) add(*b); } /// add a vector void add ( const ExpressionArray& v ) { add ( v.begin(), v.end() ); } // access to members /// RW begin iterator for array iterator begin ( void ) const { return Base.begin(); } /// RW end iterator for array iterator end ( void ) const { return Base.end(); } }; // TDLNAryExpression //------------------------------------------------------------------ // concept expressions //------------------------------------------------------------------ //------------------------------------------------------------------ /// general concept expression //------------------------------------------------------------------ class TDLConceptExpression: public TDLExpression { public: // interface /// empty c'tor TDLConceptExpression ( void ) : TDLExpression() {} /// empty d'tor virtual ~TDLConceptExpression ( void ) {} /// accept method for the visitor pattern void accept ( DLExpressionVisitor& visitor ) const = 0; }; // TDLConceptExpression //------------------------------------------------------------------ /// concept TOP expression //------------------------------------------------------------------ class TDLConceptTop: public TDLConceptExpression { public: // interface /// empty c'tor TDLConceptTop ( void ) : TDLConceptExpression() {} /// empty d'tor virtual ~TDLConceptTop ( void ) {} /// accept method for the visitor pattern void accept ( DLExpressionVisitor& visitor ) const { visitor.visit(*this); } }; // TDLConceptTop //------------------------------------------------------------------ /// concept BOTTOM expression //------------------------------------------------------------------ class TDLConceptBottom: public TDLConceptExpression { public: // interface /// empty c'tor TDLConceptBottom ( void ) : TDLConceptExpression() {} /// empty d'tor virtual ~TDLConceptBottom ( void ) {} /// accept method for the visitor pattern void accept ( DLExpressionVisitor& visitor ) const { visitor.visit(*this); } }; // TDLConceptBottom //------------------------------------------------------------------ /// named concept expression //------------------------------------------------------------------ class TDLConceptName: public TDLConceptExpression, public TNamedEntity { public: // interface /// init c'tor TDLConceptName ( const std::string& name ) : TDLConceptExpression(), TNamedEntity(name) {} /// empty d'tor virtual ~TDLConceptName ( void ) {} /// accept method for the visitor pattern void accept ( DLExpressionVisitor& visitor ) const { visitor.visit(*this); } }; // TDLConceptName //------------------------------------------------------------------ /// concept NOT expression //------------------------------------------------------------------ class TDLConceptNot: public TDLConceptExpression, public TConceptArg { public: // interface /// init c'tor TDLConceptNot ( const TDLConceptExpression* C ) : TDLConceptExpression() , TConceptArg(C) {} /// empty d'tor virtual ~TDLConceptNot ( void ) {} /// accept method for the visitor pattern void accept ( DLExpressionVisitor& visitor ) const { visitor.visit(*this); } }; // TDLConceptNot //------------------------------------------------------------------ /// concept AND expression //------------------------------------------------------------------ class TDLConceptAnd: public TDLConceptExpression, public TDLNAryExpression { public: // interface /// init c'tor: create AND of expressions from the given array TDLConceptAnd ( const ExpressionArray& v ) : TDLConceptExpression() , TDLNAryExpression("concept expression","AND") { add(v); } /// empty d'tor virtual ~TDLConceptAnd ( void ) {} /// comparison for AND bool operator == ( const TDLConceptAnd& expr ) const { if ( size() != expr.size() ) return false; for ( iterator p = begin(), q = expr.begin(), p_end = end(); p != p_end; ++p, ++q ) if ( *p != *q ) return false; return true; } /// accept method for the visitor pattern void accept ( DLExpressionVisitor& visitor ) const { visitor.visit(*this); } }; // TDLConceptAnd //------------------------------------------------------------------ /// concept OR expression //------------------------------------------------------------------ class TDLConceptOr: public TDLConceptExpression, public TDLNAryExpression { public: // interface /// init c'tor: create OR of expressions from the given array TDLConceptOr ( const ExpressionArray& v ) : TDLConceptExpression() , TDLNAryExpression("concept expression","OR") { add(v); } /// empty d'tor virtual ~TDLConceptOr ( void ) {} /// accept method for the visitor pattern void accept ( DLExpressionVisitor& visitor ) const { visitor.visit(*this); } }; // TDLConceptOr //------------------------------------------------------------------ /// concept one-of expression //------------------------------------------------------------------ class TDLConceptOneOf: public TDLConceptExpression, public TDLNAryExpression { public: // interface /// init c'tor: create one-of from individuals in the given array TDLConceptOneOf ( const ExpressionArray& v ) : TDLConceptExpression() , TDLNAryExpression("individual name","OneOf") { add(v); } /// empty d'tor virtual ~TDLConceptOneOf ( void ) {} /// accept method for the visitor pattern void accept ( DLExpressionVisitor& visitor ) const { visitor.visit(*this); } }; // TDLConceptOneOf //------------------------------------------------------------------ /// general concept expression that contains an object role //------------------------------------------------------------------ class TDLConceptObjectRoleExpression: public TDLConceptExpression, public TObjectRoleArg { public: // interface /// init c'tor TDLConceptObjectRoleExpression ( const TDLObjectRoleExpression* R ) : TDLConceptExpression() , TObjectRoleArg(R) {} /// empty d'tor virtual ~TDLConceptObjectRoleExpression ( void ) {} /// accept method for the visitor pattern void accept ( DLExpressionVisitor& visitor ) const = 0; }; // TDLConceptObjectRoleExpression //------------------------------------------------------------------ /// concept self-ref expression //------------------------------------------------------------------ class TDLConceptObjectSelf: public TDLConceptObjectRoleExpression { public: // interface /// init c'tor TDLConceptObjectSelf ( const TDLObjectRoleExpression* R ) : TDLConceptObjectRoleExpression(R) {} /// empty d'tor virtual ~TDLConceptObjectSelf ( void ) {} /// accept method for the visitor pattern void accept ( DLExpressionVisitor& visitor ) const { visitor.visit(*this); } }; // TDLConceptObjectSelf //------------------------------------------------------------------ /// concept some value restriction expression //------------------------------------------------------------------ class TDLConceptObjectValue: public TDLConceptObjectRoleExpression, public TIndividualArg { public: // interface /// init c'tor TDLConceptObjectValue ( const TDLObjectRoleExpression* R, const TDLIndividualExpression* I ) : TDLConceptObjectRoleExpression(R) , TIndividualArg(I) {} /// empty d'tor virtual ~TDLConceptObjectValue ( void ) {} /// accept method for the visitor pattern void accept ( DLExpressionVisitor& visitor ) const { visitor.visit(*this); } }; // TDLConceptObjectValue //------------------------------------------------------------------ /// general concept expression that contains an object role and a class expression //------------------------------------------------------------------ class TDLConceptObjectRCExpression: public TDLConceptObjectRoleExpression, public TConceptArg { public: // interface /// init c'tor TDLConceptObjectRCExpression ( const TDLObjectRoleExpression* R, const TDLConceptExpression* C ) : TDLConceptObjectRoleExpression(R) , TConceptArg(C) {} /// empty d'tor virtual ~TDLConceptObjectRCExpression ( void ) {} /// accept method for the visitor pattern void accept ( DLExpressionVisitor& visitor ) const = 0; }; // TDLConceptObjectRCExpression //------------------------------------------------------------------ /// concept object existential restriction expression //------------------------------------------------------------------ class TDLConceptObjectExists: public TDLConceptObjectRCExpression { public: // interface /// init c'tor TDLConceptObjectExists ( const TDLObjectRoleExpression* R, const TDLConceptExpression* C ) : TDLConceptObjectRCExpression(R,C) {} /// empty d'tor virtual ~TDLConceptObjectExists ( void ) {} /// accept method for the visitor pattern void accept ( DLExpressionVisitor& visitor ) const { visitor.visit(*this); } }; // TDLConceptObjectExists //------------------------------------------------------------------ /// concept object universal restriction expression //------------------------------------------------------------------ class TDLConceptObjectForall: public TDLConceptObjectRCExpression { public: // interface /// init c'tor TDLConceptObjectForall ( const TDLObjectRoleExpression* R, const TDLConceptExpression* C ) : TDLConceptObjectRCExpression(R,C) {} /// empty d'tor virtual ~TDLConceptObjectForall ( void ) {} /// accept method for the visitor pattern void accept ( DLExpressionVisitor& visitor ) const { visitor.visit(*this); } }; // TDLConceptObjectForall //------------------------------------------------------------------ /// general object role cardinality expression //------------------------------------------------------------------ class TDLConceptObjectCardinalityExpression: public TDLConceptObjectRCExpression, public TNumberArg { public: // interface /// init c'tor TDLConceptObjectCardinalityExpression ( unsigned int n, const TDLObjectRoleExpression* R, const TDLConceptExpression* C ) : TDLConceptObjectRCExpression(R,C) , TNumberArg(n) {} /// empty d'tor virtual ~TDLConceptObjectCardinalityExpression ( void ) {} /// accept method for the visitor pattern void accept ( DLExpressionVisitor& visitor ) const = 0; }; // TDLConceptObjectCardinalityExpression //------------------------------------------------------------------ /// concept object min cardinality expression //------------------------------------------------------------------ class TDLConceptObjectMinCardinality: public TDLConceptObjectCardinalityExpression { public: // interface /// init c'tor TDLConceptObjectMinCardinality ( unsigned int n, const TDLObjectRoleExpression* R, const TDLConceptExpression* C ) : TDLConceptObjectCardinalityExpression(n,R,C) {} /// empty d'tor virtual ~TDLConceptObjectMinCardinality ( void ) {} /// accept method for the visitor pattern void accept ( DLExpressionVisitor& visitor ) const { visitor.visit(*this); } }; // TDLConceptObjectMinCardinality //------------------------------------------------------------------ /// concept object max cardinality expression //------------------------------------------------------------------ class TDLConceptObjectMaxCardinality: public TDLConceptObjectCardinalityExpression { public: // interface /// init c'tor TDLConceptObjectMaxCardinality ( unsigned int n, const TDLObjectRoleExpression* R, const TDLConceptExpression* C ) : TDLConceptObjectCardinalityExpression(n,R,C) {} /// empty d'tor virtual ~TDLConceptObjectMaxCardinality ( void ) {} /// accept method for the visitor pattern void accept ( DLExpressionVisitor& visitor ) const { visitor.visit(*this); } }; // TDLConceptObjectMaxCardinality //------------------------------------------------------------------ /// concept object exact cardinality expression //------------------------------------------------------------------ class TDLConceptObjectExactCardinality: public TDLConceptObjectCardinalityExpression { public: // interface /// init c'tor TDLConceptObjectExactCardinality ( unsigned int n, const TDLObjectRoleExpression* R, const TDLConceptExpression* C ) : TDLConceptObjectCardinalityExpression(n,R,C) {} /// empty d'tor virtual ~TDLConceptObjectExactCardinality ( void ) {} /// accept method for the visitor pattern void accept ( DLExpressionVisitor& visitor ) const { visitor.visit(*this); } }; // TDLConceptObjectExactCardinality //------------------------------------------------------------------ /// general concept expression that contains an data role //------------------------------------------------------------------ class TDLConceptDataRoleExpression: public TDLConceptExpression, public TDataRoleArg { public: // interface /// init c'tor TDLConceptDataRoleExpression ( const TDLDataRoleExpression* R ) : TDLConceptExpression() , TDataRoleArg(R) {} /// empty d'tor virtual ~TDLConceptDataRoleExpression ( void ) {} /// accept method for the visitor pattern void accept ( DLExpressionVisitor& visitor ) const = 0; }; // TDLConceptDataRoleExpression //------------------------------------------------------------------ /// concept some value restriction expression //------------------------------------------------------------------ class TDLConceptDataValue: public TDLConceptDataRoleExpression, public TDataExpressionArg { public: // interface /// init c'tor TDLConceptDataValue ( const TDLDataRoleExpression* R, const TDLDataValue* V ) : TDLConceptDataRoleExpression(R) , TDataExpressionArg(V) {} /// empty d'tor virtual ~TDLConceptDataValue ( void ) {} /// accept method for the visitor pattern void accept ( DLExpressionVisitor& visitor ) const { visitor.visit(*this); } }; // TDLConceptDataValue //------------------------------------------------------------------ /// general concept expression that contains an data role and a data expression //------------------------------------------------------------------ class TDLConceptDataRVExpression: public TDLConceptDataRoleExpression, public TDataExpressionArg { public: // interface /// init c'tor TDLConceptDataRVExpression ( const TDLDataRoleExpression* R, const TDLDataExpression* E ) : TDLConceptDataRoleExpression(R) , TDataExpressionArg(E) {} /// empty d'tor virtual ~TDLConceptDataRVExpression ( void ) {} /// accept method for the visitor pattern void accept ( DLExpressionVisitor& visitor ) const = 0; }; // TDLConceptDataRVExpression //------------------------------------------------------------------ /// concept data existential restriction expression //------------------------------------------------------------------ class TDLConceptDataExists: public TDLConceptDataRVExpression { public: // interface /// init c'tor TDLConceptDataExists ( const TDLDataRoleExpression* R, const TDLDataExpression* E ) : TDLConceptDataRVExpression(R,E) {} /// empty d'tor virtual ~TDLConceptDataExists ( void ) {} /// accept method for the visitor pattern void accept ( DLExpressionVisitor& visitor ) const { visitor.visit(*this); } }; // TDLConceptDataExists //------------------------------------------------------------------ /// concept data universal restriction expression //------------------------------------------------------------------ class TDLConceptDataForall: public TDLConceptDataRVExpression { public: // interface /// init c'tor TDLConceptDataForall ( const TDLDataRoleExpression* R, const TDLDataExpression* E ) : TDLConceptDataRVExpression(R,E) {} /// empty d'tor virtual ~TDLConceptDataForall ( void ) {} /// accept method for the visitor pattern void accept ( DLExpressionVisitor& visitor ) const { visitor.visit(*this); } }; // TDLConceptDataForall //------------------------------------------------------------------ /// general data role cardinality expression //------------------------------------------------------------------ class TDLConceptDataCardinalityExpression: public TDLConceptDataRVExpression, public TNumberArg { public: // interface /// init c'tor TDLConceptDataCardinalityExpression ( unsigned int n, const TDLDataRoleExpression* R, const TDLDataExpression* E ) : TDLConceptDataRVExpression(R,E) , TNumberArg(n) {} /// empty d'tor virtual ~TDLConceptDataCardinalityExpression ( void ) {} /// accept method for the visitor pattern void accept ( DLExpressionVisitor& visitor ) const = 0; }; // TDLConceptDataCardinalityExpression //------------------------------------------------------------------ /// concept data min cardinality expression //------------------------------------------------------------------ class TDLConceptDataMinCardinality: public TDLConceptDataCardinalityExpression { public: // interface /// init c'tor TDLConceptDataMinCardinality ( unsigned int n, const TDLDataRoleExpression* R, const TDLDataExpression* E ) : TDLConceptDataCardinalityExpression(n,R,E) {} /// empty d'tor virtual ~TDLConceptDataMinCardinality ( void ) {} /// accept method for the visitor pattern void accept ( DLExpressionVisitor& visitor ) const { visitor.visit(*this); } }; // TDLConceptDataMinCardinality //------------------------------------------------------------------ /// concept data max cardinality expression //------------------------------------------------------------------ class TDLConceptDataMaxCardinality: public TDLConceptDataCardinalityExpression { public: // interface /// init c'tor TDLConceptDataMaxCardinality ( unsigned int n, const TDLDataRoleExpression* R, const TDLDataExpression* E ) : TDLConceptDataCardinalityExpression(n,R,E) {} /// empty d'tor virtual ~TDLConceptDataMaxCardinality ( void ) {} /// accept method for the visitor pattern void accept ( DLExpressionVisitor& visitor ) const { visitor.visit(*this); } }; // TDLConceptDataMaxCardinality //------------------------------------------------------------------ /// concept data exact cardinality expression //------------------------------------------------------------------ class TDLConceptDataExactCardinality: public TDLConceptDataCardinalityExpression { public: // interface /// init c'tor TDLConceptDataExactCardinality ( unsigned int n, const TDLDataRoleExpression* R, const TDLDataExpression* E ) : TDLConceptDataCardinalityExpression(n,R,E) {} /// empty d'tor virtual ~TDLConceptDataExactCardinality ( void ) {} /// accept method for the visitor pattern void accept ( DLExpressionVisitor& visitor ) const { visitor.visit(*this); } }; // TDLConceptDataExactCardinality //------------------------------------------------------------------ // individual expressions //------------------------------------------------------------------ //------------------------------------------------------------------ /// general individual expression //------------------------------------------------------------------ class TDLIndividualExpression: public TDLExpression { public: // interface /// empty c'tor TDLIndividualExpression ( void ) : TDLExpression() {} /// empty d'tor virtual ~TDLIndividualExpression ( void ) {} /// accept method for the visitor pattern void accept ( DLExpressionVisitor& visitor ) const = 0; }; // TDLIndividualExpression //------------------------------------------------------------------ /// named individual expression //------------------------------------------------------------------ class TDLIndividualName: public TDLIndividualExpression, public TNamedEntity { public: // interface /// init c'tor TDLIndividualName ( const std::string& name ) : TDLIndividualExpression(), TNamedEntity(name) {} /// empty d'tor virtual ~TDLIndividualName ( void ) {} /// accept method for the visitor pattern void accept ( DLExpressionVisitor& visitor ) const { visitor.visit(*this); } }; // TDLIndividualName //------------------------------------------------------------------ // role expressions //------------------------------------------------------------------ //------------------------------------------------------------------ /// general role expression //------------------------------------------------------------------ class TDLRoleExpression: public TDLExpression { public: // interface /// empty c'tor TDLRoleExpression ( void ) : TDLExpression() {} /// empty d'tor virtual ~TDLRoleExpression ( void ) {} /// accept method for the visitor pattern void accept ( DLExpressionVisitor& visitor ) const = 0; }; // TDLRoleExpression //------------------------------------------------------------------ // object role expressions //------------------------------------------------------------------ //------------------------------------------------------------------ /// complex object role expression (general expression, role chain or projection) //------------------------------------------------------------------ class TDLObjectRoleComplexExpression: public TDLRoleExpression { public: // interface /// empty c'tor TDLObjectRoleComplexExpression ( void ) : TDLRoleExpression() {} /// empty d'tor virtual ~TDLObjectRoleComplexExpression ( void ) {} /// accept method for the visitor pattern void accept ( DLExpressionVisitor& visitor ) const = 0; }; // TDLObjectRoleComplexExpression //------------------------------------------------------------------ /// general object role expression //------------------------------------------------------------------ class TDLObjectRoleExpression: public TDLObjectRoleComplexExpression { public: // interface /// empty c'tor TDLObjectRoleExpression ( void ) : TDLObjectRoleComplexExpression() {} /// empty d'tor virtual ~TDLObjectRoleExpression ( void ) {} /// accept method for the visitor pattern void accept ( DLExpressionVisitor& visitor ) const = 0; }; // TDLObjectRoleExpression //------------------------------------------------------------------ /// object role TOP expression //------------------------------------------------------------------ class TDLObjectRoleTop: public TDLObjectRoleExpression { public: // interface /// empty c'tor TDLObjectRoleTop ( void ) : TDLObjectRoleExpression() {} /// empty d'tor virtual ~TDLObjectRoleTop ( void ) {} /// accept method for the visitor pattern void accept ( DLExpressionVisitor& visitor ) const { visitor.visit(*this); } }; // TDLObjectRoleTop //------------------------------------------------------------------ /// object role BOTTOM expression //------------------------------------------------------------------ class TDLObjectRoleBottom: public TDLObjectRoleExpression { public: // interface /// empty c'tor TDLObjectRoleBottom ( void ) : TDLObjectRoleExpression() {} /// empty d'tor virtual ~TDLObjectRoleBottom ( void ) {} /// accept method for the visitor pattern void accept ( DLExpressionVisitor& visitor ) const { visitor.visit(*this); } }; // TDLObjectRoleBottom //------------------------------------------------------------------ /// named object role expression //------------------------------------------------------------------ class TDLObjectRoleName: public TDLObjectRoleExpression, public TNamedEntity { public: // interface /// init c'tor TDLObjectRoleName ( const std::string& name ) : TDLObjectRoleExpression(), TNamedEntity(name) {} /// empty d'tor virtual ~TDLObjectRoleName ( void ) {} /// accept method for the visitor pattern void accept ( DLExpressionVisitor& visitor ) const { visitor.visit(*this); } }; // TDLObjectRoleName //------------------------------------------------------------------ /// inverse object role expression //------------------------------------------------------------------ class TDLObjectRoleInverse: public TDLObjectRoleExpression, public TObjectRoleArg { public: // interface /// init c'tor TDLObjectRoleInverse ( const TDLObjectRoleExpression* R ) : TDLObjectRoleExpression() , TObjectRoleArg(R) {} /// empty d'tor virtual ~TDLObjectRoleInverse ( void ) {} /// accept method for the visitor pattern void accept ( DLExpressionVisitor& visitor ) const { visitor.visit(*this); } }; // TDLObjectRoleInverse //------------------------------------------------------------------ /// object role chain expression //------------------------------------------------------------------ class TDLObjectRoleChain: public TDLObjectRoleComplexExpression, public TDLNAryExpression { public: // interface /// init c'tor: create role chain from given array TDLObjectRoleChain ( const ExpressionArray& v ) : TDLObjectRoleComplexExpression() , TDLNAryExpression("object role expression","role chain") { add(v); } /// empty d'tor virtual ~TDLObjectRoleChain ( void ) {} /// accept method for the visitor pattern void accept ( DLExpressionVisitor& visitor ) const { visitor.visit(*this); } }; // TDLObjectRoleChain //------------------------------------------------------------------ /// object role projection from expression //------------------------------------------------------------------ class TDLObjectRoleProjectionFrom : public TDLObjectRoleComplexExpression , public TObjectRoleArg , public TConceptArg { public: // interface /// init c'tor TDLObjectRoleProjectionFrom ( const TDLObjectRoleExpression* R, const TDLConceptExpression* C ) : TDLObjectRoleComplexExpression() , TObjectRoleArg(R) , TConceptArg(C) {} /// empty d'tor virtual ~TDLObjectRoleProjectionFrom ( void ) {} /// accept method for the visitor pattern void accept ( DLExpressionVisitor& visitor ) const { visitor.visit(*this); } }; // TDLObjectRoleProjectionFrom //------------------------------------------------------------------ /// object role projection from expression //------------------------------------------------------------------ class TDLObjectRoleProjectionInto : public TDLObjectRoleComplexExpression , public TObjectRoleArg , public TConceptArg { public: // interface /// init c'tor TDLObjectRoleProjectionInto ( const TDLObjectRoleExpression* R, const TDLConceptExpression* C ) : TDLObjectRoleComplexExpression() , TObjectRoleArg(R) , TConceptArg(C) {} /// empty d'tor virtual ~TDLObjectRoleProjectionInto ( void ) {} /// accept method for the visitor pattern void accept ( DLExpressionVisitor& visitor ) const { visitor.visit(*this); } }; // TDLObjectRoleProjectionInto //------------------------------------------------------------------ // data role expressions //------------------------------------------------------------------ //------------------------------------------------------------------ /// general data role expression //------------------------------------------------------------------ class TDLDataRoleExpression: public TDLRoleExpression { public: // interface /// empty c'tor TDLDataRoleExpression ( void ) : TDLRoleExpression() {} /// empty d'tor virtual ~TDLDataRoleExpression ( void ) {} /// accept method for the visitor pattern void accept ( DLExpressionVisitor& visitor ) const = 0; }; // TDLDataRoleExpression //------------------------------------------------------------------ /// data role TOP expression //------------------------------------------------------------------ class TDLDataRoleTop: public TDLDataRoleExpression { public: // interface /// empty c'tor TDLDataRoleTop ( void ) : TDLDataRoleExpression() {} /// empty d'tor virtual ~TDLDataRoleTop ( void ) {} /// accept method for the visitor pattern void accept ( DLExpressionVisitor& visitor ) const { visitor.visit(*this); } }; // TDLDataRoleTop //------------------------------------------------------------------ /// data role BOTTOM expression //------------------------------------------------------------------ class TDLDataRoleBottom: public TDLDataRoleExpression { public: // interface /// empty c'tor TDLDataRoleBottom ( void ) : TDLDataRoleExpression() {} /// empty d'tor virtual ~TDLDataRoleBottom ( void ) {} /// accept method for the visitor pattern void accept ( DLExpressionVisitor& visitor ) const { visitor.visit(*this); } }; // TDLDataRoleBottom //------------------------------------------------------------------ /// named data role expression //------------------------------------------------------------------ class TDLDataRoleName: public TDLDataRoleExpression, public TNamedEntity { public: // interface /// init c'tor TDLDataRoleName ( const std::string& name ) : TDLDataRoleExpression(), TNamedEntity(name) {} /// empty d'tor virtual ~TDLDataRoleName ( void ) {} /// accept method for the visitor pattern void accept ( DLExpressionVisitor& visitor ) const { visitor.visit(*this); } }; // TDLDataRoleName //------------------------------------------------------------------ // data expressions //------------------------------------------------------------------ //------------------------------------------------------------------ /// general data expression //------------------------------------------------------------------ class TDLDataExpression: public TDLExpression { public: // interface /// empty c'tor TDLDataExpression ( void ) : TDLExpression() {} /// empty d'tor virtual ~TDLDataExpression ( void ) {} /// accept method for the visitor pattern void accept ( DLExpressionVisitor& visitor ) const = 0; }; // TDLDataExpression //------------------------------------------------------------------ /// data TOP expression //------------------------------------------------------------------ class TDLDataTop: public TDLDataExpression { public: // interface /// empty c'tor TDLDataTop ( void ) : TDLDataExpression() {} /// empty d'tor virtual ~TDLDataTop ( void ) {} /// accept method for the visitor pattern void accept ( DLExpressionVisitor& visitor ) const { visitor.visit(*this); } }; // TDLDataTop //------------------------------------------------------------------ /// data BOTTOM expression //------------------------------------------------------------------ class TDLDataBottom: public TDLDataExpression { public: // interface /// empty c'tor TDLDataBottom ( void ) : TDLDataExpression() {} /// empty d'tor virtual ~TDLDataBottom ( void ) {} /// accept method for the visitor pattern void accept ( DLExpressionVisitor& visitor ) const { visitor.visit(*this); } }; // TDLDataBottom //------------------------------------------------------------------ /// general data type expression //------------------------------------------------------------------ class TDLDataTypeExpression: public TDLDataExpression { public: // interface /// empty c'tor TDLDataTypeExpression ( void ) : TDLDataExpression() {} /// empty d'tor virtual ~TDLDataTypeExpression ( void ) {} /// accept method for the visitor pattern void accept ( DLExpressionVisitor& visitor ) const = 0; }; // TDLDataTypeExpression //------------------------------------------------------------------ /// restricted data type expression //------------------------------------------------------------------ class TDLDataTypeRestriction: public TDLDataTypeExpression, public TDataExpressionArg, public TDLNAryExpression { public: // interface /// init c'tor TDLDataTypeRestriction ( const TDLDataTypeName* T ) : TDLDataTypeExpression() , TDataExpressionArg(T) , TDLNAryExpression("facet expression","Datatype restriction") {} /// empty d'tor virtual ~TDLDataTypeRestriction ( void ) {} /// accept method for the visitor pattern void accept ( DLExpressionVisitor& visitor ) const { visitor.visit(*this); } }; // TDLDataTypeRestriction //------------------------------------------------------------------ /// data value expression //------------------------------------------------------------------ class TDLDataValue: public TDLDataExpression, public TNamedEntity, public TDataExpressionArg { public: // interface /// fake c'tor (to make TNameSet happy); shouldn't be called TDLDataValue ( const std::string& value ) : TDLDataExpression() , TNamedEntity(value) , TDataExpressionArg(NULL) { fpp_unreachable(); } /// init c'tor TDLDataValue ( const std::string& value, const TDLDataTypeExpression* T ) : TDLDataExpression() , TNamedEntity(value) , TDataExpressionArg(T) {} /// empty d'tor virtual ~TDLDataValue ( void ) {} /// accept method for the visitor pattern void accept ( DLExpressionVisitor& visitor ) const { visitor.visit(*this); } }; // TDLDataValue //------------------------------------------------------------------ /// data NOT expression //------------------------------------------------------------------ class TDLDataNot: public TDLDataExpression, public TDataExpressionArg { public: // interface /// init c'tor TDLDataNot ( const TDLDataExpression* E ) : TDLDataExpression() , TDataExpressionArg(E) {} /// empty d'tor virtual ~TDLDataNot ( void ) {} /// accept method for the visitor pattern void accept ( DLExpressionVisitor& visitor ) const { visitor.visit(*this); } }; // TDLDataNot //------------------------------------------------------------------ /// data AND expression //------------------------------------------------------------------ class TDLDataAnd: public TDLDataExpression, public TDLNAryExpression { public: // interface /// init c'tor: create AND of expressions from the given array TDLDataAnd ( const ExpressionArray& v ) : TDLDataExpression() , TDLNAryExpression("data expression","data AND") { add(v); } /// empty d'tor virtual ~TDLDataAnd ( void ) {} /// accept method for the visitor pattern void accept ( DLExpressionVisitor& visitor ) const { visitor.visit(*this); } }; // TDLDataAnd //------------------------------------------------------------------ /// data OR expression //------------------------------------------------------------------ class TDLDataOr: public TDLDataExpression, public TDLNAryExpression { public: // interface /// init c'tor: create OR of expressions from the given array TDLDataOr ( const ExpressionArray& v ) : TDLDataExpression() , TDLNAryExpression("data expression","data OR") { add(v); } /// empty d'tor virtual ~TDLDataOr ( void ) {} /// accept method for the visitor pattern void accept ( DLExpressionVisitor& visitor ) const { visitor.visit(*this); } }; // TDLDataOr //------------------------------------------------------------------ /// data one-of expression //------------------------------------------------------------------ class TDLDataOneOf: public TDLDataExpression, public TDLNAryExpression { public: // interface /// init c'tor: create one-of from individuals in the given array TDLDataOneOf ( const ExpressionArray& v ) : TDLDataExpression() , TDLNAryExpression("data value","data OneOf") { add(v); } /// empty d'tor virtual ~TDLDataOneOf ( void ) {} /// accept method for the visitor pattern void accept ( DLExpressionVisitor& visitor ) const { visitor.visit(*this); } }; // TDLDataOneOf //------------------------------------------------------------------ /// general data facet expression //------------------------------------------------------------------ class TDLFacetExpression: public TDLDataExpression, public TDataExpressionArg { public: // interface /// init c'tor: create facet from a given value V TDLFacetExpression ( const TDLDataValue* V ) : TDLDataExpression() , TDataExpressionArg(V) {} /// empty d'tor virtual ~TDLFacetExpression ( void ) {} /// accept method for the visitor pattern void accept ( DLExpressionVisitor& visitor ) const = 0; }; // TDLFacetExpression //------------------------------------------------------------------ /// min-inclusive facet expression //------------------------------------------------------------------ class TDLFacetMinInclusive: public TDLFacetExpression { public: // interface /// init c'tor TDLFacetMinInclusive ( const TDLDataValue* V ) : TDLFacetExpression(V) {} /// empty d'tor virtual ~TDLFacetMinInclusive ( void ) {} /// accept method for the visitor pattern void accept ( DLExpressionVisitor& visitor ) const { visitor.visit(*this); } }; // TDLFacetMinInclusive //------------------------------------------------------------------ /// min-exclusive facet expression //------------------------------------------------------------------ class TDLFacetMinExclusive: public TDLFacetExpression { public: // interface /// init c'tor TDLFacetMinExclusive ( const TDLDataValue* V ) : TDLFacetExpression(V) {} /// empty d'tor virtual ~TDLFacetMinExclusive ( void ) {} /// accept method for the visitor pattern void accept ( DLExpressionVisitor& visitor ) const { visitor.visit(*this); } }; // TDLFacetMinExclusive //------------------------------------------------------------------ /// max-inclusive facet expression //------------------------------------------------------------------ class TDLFacetMaxInclusive: public TDLFacetExpression { public: // interface /// init c'tor TDLFacetMaxInclusive ( const TDLDataValue* V ) : TDLFacetExpression(V) {} /// empty d'tor virtual ~TDLFacetMaxInclusive ( void ) {} /// accept method for the visitor pattern void accept ( DLExpressionVisitor& visitor ) const { visitor.visit(*this); } }; // TDLFacetMaxInclusive //------------------------------------------------------------------ /// max-exclusive facet expression //------------------------------------------------------------------ class TDLFacetMaxExclusive: public TDLFacetExpression { public: // interface /// init c'tor TDLFacetMaxExclusive ( const TDLDataValue* V ) : TDLFacetExpression(V) {} /// empty d'tor virtual ~TDLFacetMaxExclusive ( void ) {} /// accept method for the visitor pattern void accept ( DLExpressionVisitor& visitor ) const { visitor.visit(*this); } }; // TDLFacetMaxExclusive // data type is defined here as they are more complex than the rest //------------------------------------------------------------------ /// data type implementation for the DL expressions //------------------------------------------------------------------ class TDLDataType { protected: // classes /// class to create a new entry with a given data type as a parameter class DVCreator: public TNameCreator { protected: // members /// type for all the values const TDLDataTypeExpression* type; public: // interface /// init c'tor DVCreator ( const TDLDataTypeExpression* t ) : type(t) {} /// empty d'tor virtual ~DVCreator ( void ) {} /// create new value of a given type virtual TDLDataValue* makeEntry ( const std::string& name ) const { return new TDLDataValue(name,type); } }; // DVCreator protected: // members /// all the values of the datatype TNameSet Values; public: // interface /// empty c'tor TDLDataType ( const TDLDataTypeExpression* type ) : Values(new DVCreator(type)) {} /// empty d'tor virtual ~TDLDataType ( void ) {} /// get new data value of the given type const TDLDataValue* getValue ( const std::string& name ) { return Values.insert(name); } }; // TDLDataType //------------------------------------------------------------------ /// named data type expression //------------------------------------------------------------------ class TDLDataTypeName: public TDLDataTypeExpression, public TDLDataType, public TNamedEntity { public: // interface /// init c'tor TDLDataTypeName ( const std::string& name ) : TDLDataTypeExpression(), TDLDataType(this), TNamedEntity(name) {} /// empty d'tor virtual ~TDLDataTypeName ( void ) {} /// accept method for the visitor pattern void accept ( DLExpressionVisitor& visitor ) const { visitor.visit(*this); } }; // TDLDataTypeName /// @return named data type that is the most basic datatype underlying TYPE inline TDLDataTypeName* getBasicDataType ( TDLDataTypeExpression* type ) { TDLDataTypeName* ret = dynamic_cast(type); if ( ret == NULL ) { TDLDataTypeRestriction* hostType = dynamic_cast(type); fpp_assert ( hostType != NULL ); ret = const_cast(hostType->getExpr()); } return ret; } #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/tRole.h0000644000000000000000000004512212112642405016616 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2012 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef TROLE_H #define TROLE_H #include #include #include "globaldef.h" // sorted reasoning #include "BiPointer.h" #include "dltree.h" #include "taxNamEntry.h" #include "tLabeller.h" #include "RAutomaton.h" #include "eFPPNonSimpleRole.h" #include "eFPPCycleInRIA.h" #ifdef RKG_USE_SORTED_REASONING # include "mergableLabel.h" #endif class TBox; class RoleMaster; class Taxonomy; /// Define class with all information about DL role class TRole: public ClassifiableEntry { friend class RoleMaster; private: // no copy /// no empty c'tor TRole (); /// no copy c'tor TRole ( const TRole& ); /// no assignment TRole& operator = ( const TRole& ); protected: // types /// Class for values that can change wrt ontology class TKnownValue { protected: // members /// flag value bool value; /// whether flag set or not bool known; public: // interface /// init c'tor TKnownValue ( bool val = false ) : value(val), known(false) {} /// empty d'tor ~TKnownValue ( void ) {} /// @return true iff the value is known to be set bool isKnown ( void ) const { return known; } /// @return the value bool getValue ( void ) const { return value; } /// set the value; it is now known void setValue ( bool val ) { value = val; known = true; } }; // TKnownValue public: // types /// vector of roles typedef std::vector TRoleVec; /// RO iterator over role vector typedef TRoleVec::const_iterator const_iterator; /// set of roles typedef std::set TRoleSet; /// bitmap for roles typedef std::vector TRoleBitMap; protected: // members /// role that are inverse of given one TRole* Inverse; /// Domain of role as a concept description; default NULL DLTree* pDomain; /// Domain of role as a concept description; default NULL DLTree* pSpecialDomain; /// Domain of role as a pointer to DAG entry BipolarPointer bpDomain; /// domain in the form AR.Range for the complex roles BipolarPointer bpSpecialDomain; /// pointer to role's functional definition DAG entry (or just TOP) BipolarPointer Functional; /// is role relevant to current query TLabeller::LabelType rel; #ifdef RKG_USE_SORTED_REASONING /// label of a domain (inverse role is used for a range label) mergableLabel domLabel; #endif // for later filling // FIXME!! const was removed for Relevance setting TRoleVec Ancestor, Descendant; /// set of the most functional super-roles TRoleVec TopFunc; /// set of the roles that are disjoint with a given one TRoleSet Disjoint; /// all compositions in the form R1*R2*\ldots*Rn [= R std::vector subCompositions; /// bit-vector of all parents TRoleBitMap AncMap; /// bit-vector of all roles disjoint with current TRoleBitMap DJRoles; /// automaton for role RoleAutomaton A; /// value for functionality TKnownValue Functionality; /// value for symmetry TKnownValue Symmetry; /// value for asymmetricity TKnownValue Asymmetry; /// value for transitivity TKnownValue Transitivity; /// value for reflexivity TKnownValue Reflexivity; /// value for reflexivity TKnownValue Irreflexivity; /// flag to show that this role needs special R&D processing bool SpecialDomain; protected: // methods // support for Anc/Desc filling and such /// check if the role is REALLY topmost-functional (internal-use only) bool isRealTopFunc ( void ) const; /// set up TopFunc member properly (internal-use only) void initTopFunc ( void ); /// init map of all disjoint roles void initDJMap ( void ); /// eliminate told role cycle, carrying aux arrays of processed roles and synonyms TRole* eliminateToldCycles ( TRoleSet& RInProcess, TRoleVec& ToldSynonyms ); // support for automaton construction /// complete role automaton; keep track of processed roles in RINPROCESS void completeAutomaton ( TRoleSet& RInProcess ); /// replace RoR [= R with Trans(R), replace synonyms in RS void preprocessComposition ( TRoleVec& RS ); /// add transition to automaton with the role void addTrivialTransition ( const TRole* r ) { A.addTransitionSafe ( A.initial(), new RATransition ( A.final(), r ) ); } /// add automaton of a sub-role to a given one void addSubRoleAutomaton ( const TRole* R ) { if ( this != R ) // non-trivial addition A.addRA(R->getAutomaton()); } /// get an automaton by a (possibly synonymical) role const RoleAutomaton& completeAutomatonByRole ( TRole* R, TRoleSet& RInProcess ) const { fpp_assert ( !R->isSynonym() ); // no synonyms here fpp_assert ( R != this ); // no case ...*S*... [= S R->completeAutomaton(RInProcess); return R->getAutomaton(); } /// add automaton for a role composition; simplify composition void addSubCompositionAutomaton ( TRoleVec& RS, TRoleSet& RInProcess ); /// check (and correct) case whether R != S for R [= S void checkHierarchicalDisjoint ( TRole* R ); /// check whether there is a sub-property with special domain; propagate this void checkSpecialDomain ( void ) { if ( hasSpecialDomain() ) return; for ( const_iterator p = begin_desc(), p_end = end_desc(); p != p_end; ++p ) if ( (*p)->hasSpecialDomain() ) { SpecialDomain = true; return; } } public: // interface /// the only c'tor TRole ( const std::string& name ); /// d'tor virtual ~TRole ( void ); /// get (unsigned) unique index of the role unsigned int getIndex ( void ) const { int i = 2*getId(); return i > 0 ? i : 1-i; } // synonym operations /// copy role information (like transitivity, functionality, R&D etc) to synonym void addFeaturesToSynonym ( void ); // inverse of the role /// get inverse of given role (non-const version) TRole* inverse ( void ) { fpp_assert (Inverse != NULL); return resolveSynonym(Inverse); } /// get inverse of given role (const version) const TRole* inverse ( void ) const { fpp_assert (Inverse != NULL); return resolveSynonym(Inverse); } /// get real inverse of a role (RO) const TRole* realInverse ( void ) const { fpp_assert (Inverse != NULL); return Inverse; } /// set inverse to given role void setInverse ( TRole* p ) { fpp_assert (Inverse == NULL); Inverse = p; } // different flags /// distinguish data- and non-data role FPP_ADD_FLAG(DataRole,0x10); // simple // @return true iff the role is simple bool isSimple ( void ) const { return A.isSimple(); } // functionality /// test if role is functional (ie, have some functional ancestors) bool isFunctional ( void ) const { return Functionality.getValue(); } /// check whether the functionality of a role is known bool isFunctionalityKnown ( void ) const { return Functionality.isKnown(); } /// check if the role is topmost-functional (ie, has no functional ancestors). bool isTopFunc ( void ) const { // check for emptyness is here due to case where a role is determined to be a functional return !TopFunc.empty() && *TopFunc.begin() == this; } /// set role functionality value void setFunctional ( bool value ) { Functionality.setValue(value); } /// mark role (topmost) functional void setFunctional ( void ) { if ( TopFunc.empty() ) TopFunc.push_back(this); setFunctional(true); } /// set functional attribute to given value (functional DAG vertex) void setFunctional ( BipolarPointer fNode ) { Functional = fNode; } /// get the Functional DAG vertex BipolarPointer getFunctional ( void ) const { return Functional; } // transitivity /// check whether the role is transitive bool isTransitive ( void ) const { return Transitivity.getValue(); } /// check whether the transitivity of a role is known bool isTransitivityKnown ( void ) const { return Transitivity.isKnown(); } /// set the transitivity of both role and it's inverse void setTransitive ( bool value = true ) { Transitivity.setValue(value); inverse()->Transitivity.setValue(value); } // symmetry /// check whether the role is symmetric bool isSymmetric ( void ) const { return Symmetry.getValue(); } /// check whether the symmetry of a role is known bool isSymmetryKnown ( void ) const { return Symmetry.isKnown(); } /// set the symmetry of both role and it's inverse void setSymmetric ( bool value = true ) { Symmetry.setValue(value); inverse()->Symmetry.setValue(value); } // asymmetry /// check whether the role is asymmetric bool isAsymmetric ( void ) const { return Asymmetry.getValue(); } /// check whether the asymmetry of a role is known bool isAsymmetryKnown ( void ) const { return Asymmetry.isKnown(); } /// set the asymmetry of both role and it's inverse void setAsymmetric ( bool value = true ) { Asymmetry.setValue(value); inverse()->Asymmetry.setValue(value); } // reflexivity /// check whether the role is reflexive bool isReflexive ( void ) const { return Reflexivity.getValue(); } /// check whether the reflexivity of a role is known bool isReflexivityKnown ( void ) const { return Reflexivity.isKnown(); } /// set the reflexivity of both role and it's inverse void setReflexive ( bool value = true ) { Reflexivity.setValue(value); inverse()->Reflexivity.setValue(value); } // irreflexivity /// check whether the role is irreflexive bool isIrreflexive ( void ) const { return Irreflexivity.getValue(); } /// check whether the irreflexivity of a role is known bool isIrreflexivityKnown ( void ) const { return Irreflexivity.isKnown(); } /// set the irreflexivity of both role and it's inverse void setIrreflexive ( bool value = true ) { Irreflexivity.setValue(value); inverse()->Irreflexivity.setValue(value); } // relevance /// is given role relevant to given Labeller's state bool isRelevant ( const TLabeller& lab ) const { return lab.isLabelled(rel); } /// make given role relevant to given Labeller's state void setRelevant ( const TLabeller& lab ) { lab.set(rel); } #ifdef RKG_USE_SORTED_REASONING // Sorted reasoning interface /// get label of the role's domain mergableLabel& getDomainLabel ( void ) { return domLabel; } /// get label of the role's range mergableLabel& getRangeLabel ( void ) { return inverse()->getDomainLabel(); } /// merge label of given role and all its super-roles void mergeSupersDomain ( void ); #endif // domain and range /// add p to domain of the role void setDomain ( DLTree* p ) { if ( equalTrees ( pDomain, p ) ) // not just a CName deleteTree(p); // usual case when you have a name for inverse role else if ( isFunctionalExpr ( p, this ) ) { setFunctional(); deleteTree(p); // functional restriction in the role domain means the role is functional } else pDomain = createSNFReducedAnd ( pDomain, p ); } /// add p to range of the role void setRange ( DLTree* p ) { inverse()->setDomain(p); } /// get domain-as-a-tree of the role DLTree* getTDomain ( void ) const { return pDomain; } /// get range-as-a-tree of the role DLTree* getTRange ( void ) const { return inverse()->pDomain; } /// get special-domain-as-a-tree DLTree* getTSpecialDomain ( void ) { return pSpecialDomain; } #ifdef RKG_UPDATE_RND_FROM_SUPERROLES /// merge to Domain all domains from super-roles void collectDomainFromSupers ( void ) { for ( iterator p = begin_anc(); p != end_anc(); ++p ) setDomain ( clone((*p)->getTDomain()) ); } #endif /// set domain-as-a-bipointer to a role void setBPDomain ( BipolarPointer p ) { bpDomain = p; } /// get domain-as-a-bipointer of the role BipolarPointer getBPDomain ( void ) const { return bpDomain; } /// get range-as-a-bipointer of the role BipolarPointer getBPRange ( void ) const { return inverse()->bpDomain; } /// @return true iff role has a special domain bool hasSpecialDomain ( void ) const { return SpecialDomain; } /// init special domain; call this only after *ALL* the domains are known void initSpecialDomain ( void ) { if ( !hasSpecialDomain() || getTRange() == NULL ) pSpecialDomain = createTop(); else pSpecialDomain = createSNFForall ( createRole(this), clone(getTRange()) ); } /// set the special domain value void setSpecialDomain ( BipolarPointer bp ) { bpSpecialDomain = bp; } /// get special domain value BipolarPointer getSpecialDomain ( void ) const { return bpSpecialDomain; } /// get special range value BipolarPointer getSpecialRange ( void ) const { return inverse()->bpSpecialDomain; } // disjoint roles /// set R and THIS as a disjoint; use it after Anc/Desc are determined void addDisjointRole ( TRole* R ) { Disjoint.insert(R); for ( const_iterator p = R->begin_desc(), p_end = R->end_desc(); p != p_end; ++p ) { Disjoint.insert(*p); (*p)->Disjoint.insert(this); } } /// check (and correct) case whether R != S for R [= S void checkHierarchicalDisjoint ( void ) { checkHierarchicalDisjoint(this); if ( isReflexive() ) // for reflexive roles check for R^- is necessary checkHierarchicalDisjoint(inverse()); } /// check whether a role is disjoint with anything bool isDisjoint ( void ) const { return !Disjoint.empty(); } /// check whether a role is disjoint with R bool isDisjoint ( const TRole* r ) const { return DJRoles[r->getIndex()]; } // role relations checking /// two roles are the same iff thy are synonyms of the same role bool operator == ( const TRole& r ) const { return this == &r; } /// check if role is a strict sub-role of R bool operator < ( const TRole& r ) const { return (isDataRole() == r.isDataRole()) && AncMap[r.getIndex()]; } /// check if role is a non-strict sub-role of R bool operator <= ( const TRole& r ) const { return (*this == r) || (*this < r); } /// check if role is a strict super-role of R bool operator > ( const TRole& r ) const { return r < *this; } /// check if role is a non-strict super-role of R bool operator >= ( const TRole& r ) const { return (*this == r) || (*this > r); } // iterators /// get access to all super-roles via iterator const_iterator begin_anc ( void ) const { return Ancestor.begin(); } const_iterator end_anc ( void ) const { return Ancestor.end(); } /// get access to all sub-roles via iterator const_iterator begin_desc ( void ) const { return Descendant.begin(); } const_iterator end_desc ( void ) const { return Descendant.end(); } /// get access to the func super-roles w/o func parents via iterator const_iterator begin_topfunc ( void ) const { return TopFunc.begin(); } const_iterator end_topfunc ( void ) const { return TopFunc.end(); } /// fills BITMAP with the role's ancestors void addAncestorsToBitMap ( TRoleBitMap& bitmap ) const { fpp_assert ( !bitmap.empty() ); // use only after the size is known for ( const_iterator p = begin_anc(), p_end = end_anc(); p != p_end; ++p ) bitmap[(*p)->getIndex()] = true; } // automaton construction /// add composition to a role void addComposition ( const DLTree* tree ) { TRoleVec RS; fillsComposition ( RS, tree ); subCompositions.push_back(RS); } /// get access to a RA for the role const RoleAutomaton& getAutomaton ( void ) const { return A; } // completing internal constructions /// eliminate told role cycle TRole* eliminateToldCycles ( void ) { TRoleSet RInProcess; TRoleVec ToldSynonyms; return eliminateToldCycles ( RInProcess, ToldSynonyms ); } /// init ancestors and descendants using Taxonomy void initADbyTaxonomy ( Taxonomy* pTax, unsigned int ADMapSize ); /// init other fields that requires Anc/Desc for all roles void postProcess ( void ); /// fills role composition by given TREE void fillsComposition ( TRoleVec& Composition, const DLTree* tree ) const; /// complete role automaton void completeAutomaton ( unsigned int nRoles ) { TRoleSet RInProcess; completeAutomaton(RInProcess); A.setup ( nRoles, isDataRole() ); } /// check whether role description is consistent void consistent ( void ) const { if ( isSimple() ) // all simple roles are consistent return; if ( isFunctional() ) // non-simple role can not be functional throw EFPPNonSimpleRole(getName()); if ( isDataRole() ) // data role can not be non-simple throw EFPPNonSimpleRole(getName()); if ( isDisjoint() ) // non-simple role can not be disjoint with any role throw EFPPNonSimpleRole(getName()); } // output /// print role to given stream void Print ( std::ostream& o ) const; // save/load interface; implementation is in SaveLoad.cpp /// save entry virtual void Save ( std::ostream& o ) const; /// load entry virtual void Load ( std::istream& i ); }; // TRole /// @return R or -R for T in the form (inv ... (inv R)...) inline TRole* resolveRoleHelper ( const DLTree* t ) { if ( t == NULL ) // empty tree -- error throw EFaCTPlusPlus("Role expression expected"); switch ( t->Element().getToken() ) { case RNAME: // role name case DNAME: // data role name return static_cast(t->Element().getNE()); case INV: // inversion return resolveRoleHelper(t->Left())->inverse(); default: // error throw EFaCTPlusPlus("Invalid role expression"); } } /// @return R or -R for T in the form (inv ... (inv R)...); remove synonyms inline TRole* resolveRole ( const DLTree* t ) { return resolveSynonym(resolveRoleHelper(t)); } //-------------------------------------------------- // TRole implementation //-------------------------------------------------- inline TRole :: TRole ( const std::string& name ) : ClassifiableEntry(name) , Inverse(NULL) , pDomain(NULL) , pSpecialDomain(NULL) , bpDomain(bpINVALID) , bpSpecialDomain(bpINVALID) , Functional(bpINVALID) , rel(0) , SpecialDomain(false) { setCompletelyDefined (true); // role hierarchy is completely defined by it's parents addTrivialTransition (this); } inline TRole :: ~TRole ( void ) { deleteTree(pDomain); deleteTree(pSpecialDomain); if ( Inverse != NULL && Inverse != this ) { Inverse->Inverse = NULL; delete Inverse; } } //-------------------------------------------------- // RAStateTransitions implementation depending on TRole //-------------------------------------------------- /// check whether one of the transitions accept R inline bool RAStateTransitions :: recognise ( const TRole* R ) const { return R != NULL && R->isDataRole() == DataRole && ApplicableRoles.in(R->getIndex()); } #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/DataReasoning.h0000644000000000000000000002062712112642405020253 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2005-2012 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef DATAREASONING_H #define DATAREASONING_H #include #include #include "tDataEntry.h" #include "DataTypeComparator.h" #include "ConceptWithDep.h" #include "dlDag.h" #include "logging.h" class DataTypeAppearance { protected: // classes /// data interval with dep-sets class DepInterval { protected: // members /// interval itself TDataInterval Constraints; /// local dep-set DepSet locDep; public: // interface /// empty c'tor DepInterval ( void ) {} /// empty d'tor ~DepInterval ( void ) {} /// update MIN border of an TYPE's interval with VALUE wrt EXCL bool update ( bool min, bool excl, const ComparableDT& value, const DepSet& dep ) { if ( !Constraints.update ( min, excl, value ) ) return false; locDep = dep; return true; } /// correct MIN and MAX operands of a type bool checkMinMaxClash ( DepSet& dep ) const; /// check if the interval is consistent wrt given type bool consistent ( const ComparableDT& type, DepSet& dep ) const { if ( Constraints.consistent(type) ) return true; dep += locDep; return false; } /// clear the interval void clear ( void ) { Constraints.clear(); } }; // DepInterval /// datatype restriction is a set of intervals typedef std::vector DTConstraint; typedef DTConstraint::iterator iterator; typedef DTConstraint::const_iterator const_iterator; public: // members /// dep-set for positive type appearance DepSet* PType; /// dep-set for negative type appearance DepSet* NType; protected: // members /// interval of possible values DTConstraint Constraints; /// accumulated dep-set DepSet accDep; /// dep-set for the clash DepSet& clashDep; // local values for the updating /// local value for the min/max flag bool localMin; /// local value for the incl/excl flag bool localExcl; /// local value for the added value ComparableDT localValue; /// local dep-set for the update DepSet localDep; protected: // methods /// set clash dep-set to DEP, report with given REASON; @return true to simplify callers bool reportClash ( const DepSet& dep, const char* reason ) { if ( LLM.isWritable(llCDAction) ) // level of logging LL << " DT-" << reason; // inform about clash... clashDep = dep; return true; } /// set the local parameters for updating void setLocal ( bool min, bool excl, const ComparableDT& value, const DepSet& dep ) { localMin = min; localExcl = excl; localValue = value; localDep = dep; } /// update and add a single interval I to the constraints. @return true iff clash occurs bool addUpdatedInterval ( DepInterval i ) { if ( !i.consistent ( localValue, localDep ) ) // types are mismatch return reportClash ( localDep, "C-IT" ); if ( !i.update ( localMin, localExcl, localValue, localDep ) ) Constraints.push_back(i); else if ( !hasPType() || !i.checkMinMaxClash(accDep) ) Constraints.push_back(i); return false; } /// update and add all the intervals from the given range. @return true iff clash occurs bool addIntervals ( iterator begin, iterator end ) { for ( ; begin != end; ++begin ) if ( addUpdatedInterval(*begin) ) return true; return false; } /// add interval INT positively to the DTA bool addPosInterval ( const TDataInterval& Int, const DepSet& dep ); /// add interval INT negatively to the DTA bool addNegInterval ( const TDataInterval& Int, const DepSet& dep ); public: // methods /// empty c'tor DataTypeAppearance ( DepSet& dep ) : PType(NULL), NType(NULL), clashDep(dep) {} /// empty d'tor ~DataTypeAppearance ( void ) { delete PType; delete NType; } /// clear the appearance flags void clear ( void ) { delete PType; PType = NULL; delete NType; NType = NULL; Constraints.clear(); Constraints.push_back(DepInterval()); accDep.clear(); } // presence interface /// check if type is present positively in the node bool hasPType ( void ) const { return PType != NULL; } /// set the presence of the type depending of polarity (POS) and save a dep-set DEP void setTypePresence ( bool pos, const DepSet& dep ) { DepSet*& pDep = pos ? PType : NType; if ( likely(pDep == NULL) ) // 1st access pDep = new DepSet(dep); else pDep->add(dep); } // complex methods /// add restrictions [POS]INT to intervals bool addInterval ( bool pos, const TDataInterval& Int, const DepSet& dep ) { if ( LLM.isWritable(llCDAction) ) // level of logging LL << ' ' << (pos ? '+' : '-') << Int; return pos ? addPosInterval ( Int, dep ) : addNegInterval ( Int, dep ); } /// @return true iff PType and NType leads to clash bool checkPNTypeClash ( void ) { if ( PType != NULL && NType != NULL ) return reportClash ( *PType+*NType, "TNT" ); return false; } }; // DataTypeAppearance class DataTypeReasoner { protected: // types /// vector of data types typedef std::vector DTAVector; /// map from positive BPs (DT pNames) to corresponding data type typedef std::map TypeMap; protected: // members /// vector of a types DTAVector Types; /// map Type.pName->Type appearance TypeMap Map; /// external DAG const DLDag& DLHeap; /// dep-set for the clash for *all* the types DepSet clashDep; protected: // methods /// process data value bool processDataValue ( bool pos, const TDataEntry* c, const DepSet& dep ) { DataTypeAppearance* type = getDTAbyValue(c); if (pos) type->setTypePresence ( pos, dep ); // create interval [c,c] TDataInterval constraints; constraints.updateMin ( /*excl=*/false, c->getComp() ); constraints.updateMax ( /*excl=*/false, c->getComp() ); return type->addInterval ( pos, constraints, dep ); } /// process data expr bool processDataExpr ( bool pos, const TDataEntry* c, const DepSet& dep ) { const TDataInterval& constraints = *c->getFacet(); if ( constraints.empty() ) return false; DataTypeAppearance* type = getDTAbyValue(c); if (pos) type->setTypePresence ( pos, dep ); return type->addInterval ( pos, constraints, dep ); } /// get data entry structure by a BP const TDataEntry* getDataEntry ( BipolarPointer p ) const { return static_cast(DLHeap[p].getConcept()); } // get access to proper DataTypeAppearance /// get DTA by given data-type pointer DataTypeAppearance* getDTAbyType ( const TDataEntry* dataType ) { # ifdef ENABLE_CHECKING fpp_assert ( Map.find(dataType) != Map.end() ); # endif return Types[Map[dataType]]; } /// get DTA by given data-value pointer DataTypeAppearance* getDTAbyValue ( const TDataEntry* dataValue ) { # ifdef ENABLE_CHECKING fpp_assert ( !dataValue->isBasicDataType() ); # endif return getDTAbyType(dataValue->getType()); } public: // interface /// c'tor: save DAG DataTypeReasoner ( const DLDag& dag ) : DLHeap(dag) {} /// empty d'tor ~DataTypeReasoner ( void ) { for ( DTAVector::iterator p = Types.begin(); p < Types.end(); ++p ) delete *p; } // managing DTR /// add data type to the reasoner void registerDataType ( const TDataEntry* p ) { Map[p] = Types.size(); Types.push_back(new DataTypeAppearance(clashDep)); } /// prepare types for the reasoning void clear ( void ) { for ( DTAVector::iterator p = Types.begin(), p_end = Types.end(); p < p_end; ++p ) (*p)->clear(); } // filling structures and getting answers /// add data entry to the DTAVector; @return true iff data-data clash was found bool addDataEntry ( BipolarPointer p, const DepSet& dep ); /// @return true iff data inconsistency was found in a structure; ClashSet would be set approprietry bool checkClash ( void ); /// get clash-set const DepSet& getClashSet ( void ) const { return clashDep; } }; // DataTypeReasoner #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/tIndividual.h0000644000000000000000000001157212112642405020007 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2011 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef TINDIVIDUAL_H #define TINDIVIDUAL_H #include #include "tConcept.h" class DlCompletionTree; class TRelated; class TIndividual; /// class to map roles to set of individuals class TRelatedMap { public: // interface types /// vector of individuals typedef std::vector CIVec; protected: // types /// base class typedef std::map BaseType; protected: // members /// base that contains all info BaseType Base; public: // interface /// empty c'tor TRelatedMap ( void ) {} /// empty d'tor ~TRelatedMap ( void ) {} // access /// check whether role is in map bool hasRole ( const TRole* R ) const { return Base.find(R) != Base.end(); } /// get array related to role const CIVec& getRelated ( const TRole* R ) const { fpp_assert ( hasRole(R) ); return Base.find(R)->second; } /// add related wrt role void setRelated ( const TRole* R, const CIVec& v ) { fpp_assert ( !hasRole(R) ); Base[R] = v; } }; // TRelatedMap /// class to represent individuals class TIndividual: public TConcept { public: // types /// pointers to RELATED constructors typedef std::vector RelatedSet; /// vector of individuals typedef TRelatedMap::CIVec CIVec; public: // members /// pointer to nominal node (works for singletons only) DlCompletionTree* node; /// index for axioms :R RelatedSet RelatedIndex; /// map for the related individuals: Map[R]={i:R(this,i)} TRelatedMap* pRelatedMap; private: // no copy /// no copy c'tor TIndividual ( const TIndividual& ); /// no asssignment TIndividual& operator = ( const TIndividual& ); public: // interface /// the only c'tor explicit TIndividual ( const std::string& name ) : TConcept(name) , node(NULL) , pRelatedMap(new TRelatedMap()) { setSingleton(true); } /// empty d'tor virtual ~TIndividual ( void ) { delete pRelatedMap; } /// init told subsumers of the individual by it's description virtual void initToldSubsumers ( void ) { toldSubsumers.clear(); clearHasSP(); if ( isRelated() ) // check if domain and range of RELATED axioms affects TS updateToldFromRelated(); // normalise description if the only parent is TOP if ( isPrimitive() && Description && Description->Element() == TOP ) removeDescription(); // not a completely defined if there are extra rules or related individuals bool CD = !hasExtraRules() && isPrimitive() && !isRelated(); if ( Description != NULL || hasToldSubsumers() ) CD &= TConcept::initToldSubsumers(Description); setCompletelyDefined(CD); } // related things /// update told subsumers from the RELATED axioms in a given range template void updateTold ( Iterator begin, Iterator end, RoleSSet& RolesProcessed ) { for ( Iterator p = begin; p < end; ++p ) SearchTSbyRoleAndSupers ( (*p)->getRole(), RolesProcessed); } /// update told subsumers from all relevant RELATED axioms void updateToldFromRelated ( void ); /// check if individual connected to something with RELATED statement bool isRelated ( void ) const { return !RelatedIndex.empty(); } /// set individual related void addRelated ( TRelated* p ) { RelatedIndex.push_back(p); } /// add all the related elements from the given P void addRelated ( TIndividual* p ) { RelatedIndex.insert ( RelatedIndex.end(), p->RelatedIndex.begin(), p->RelatedIndex.end() ); } // related map access /// @return true if has cache for related individuals via role R bool hasRelatedCache ( const TRole* R ) const { return pRelatedMap->hasRole(R); } /// get set of individuals related to THIS via R const CIVec& getRelatedCache ( const TRole* R ) const { return pRelatedMap->getRelated(R); } /// set the cache of individuals related to THIS via R void setRelatedCache ( const TRole* R, const CIVec& v ) { pRelatedMap->setRelated ( R, v ); } /// clear RM void clearRelatedMap ( void ) { delete pRelatedMap; pRelatedMap = new TRelatedMap(); } // save/load interface; implementation is in SaveLoad.cpp /// save entry virtual void Save ( std::ostream& o ) const; /// load entry virtual void Load ( std::istream& i ); }; // TIndividual #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/LeveLogger.cpp0000644000000000000000000000310212112642405020107 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2006 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include #include "LeveLogger.h" #include "configure.h" bool LeveLogger :: initLogger ( unsigned int l, const char* filename ) { // init file LL.open(filename); if ( LL.bad() ) return true; // init level allowedLevel = l; LL << "Init allowedLevel = " << allowedLevel << "\n"; return false; } bool LeveLogger :: initLogger ( Configuration& Config ) { // try to load LeveLogger's config section if ( Config.useSection ( "LeveLogger" ) ) return true; unsigned int l; // try to load allowance level if ( Config.checkValue ( "allowedLevel" ) ) l = 0; else l = Config.getLong (); // try to load input value if ( Config.checkValue ( "file" ) ) return true; return initLogger ( l, Config.getString() ); } // the only element of LL LeveLogger LLM; std::ofstream LL; FaCTpp-src-v1.6.2~dfsg/src/Kernel/tConcept.cpp0000644000000000000000000001444312112642405017645 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2011 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "tConcept.h" #include "tRole.h" void TConcept :: clear ( void ) { // TNamedEntry clean setId(0); // ClassifiableEntry clean taxVertex = NULL; toldSubsumers.clear(); setCompletelyDefined(false); pSynonym = NULL; // TConcept clean removeDescription(); setPrimitive(); pName = pBody = bpINVALID; } void TConcept :: addDesc ( DLTree* Desc ) { fpp_assert (!isNonPrimitive()); // safety check // FIXME!! check about reverse order Description = createSNFAnd ( Desc, Description ); } /// calculate value of classification TAG based on told subsumers. WARNING: no TS cycles allowed CTTag TConcept :: determineClassTag ( void ) { // for synonyms -- set tag as a primer's one if ( isSynonym() ) return resolveSynonym(this)->getClassTag(); // check if it is non-primitive if ( isNonPrimitive() ) return cttNonPrimitive; // no told subsumers if ( !hasToldSubsumers() ) return cttOrphan; // now need to check all the told subsumers bool hasLCD = false; bool hasOther = false; bool hasNP = false; for ( ClassifiableEntry::const_iterator p = told_begin(); p != told_end(); ++p ) switch ( static_cast(*p)->getClassTag() ) { case cttTrueCompletelyDefined: break; case cttOrphan: case cttLikeCompletelyDefined: hasLCD = true; break; case cttRegular: hasOther = true; break; case cttHasNonPrimitiveTS: case cttNonPrimitive: hasNP = true; break; default: fpp_unreachable(); } // there are non-primitive TS if ( hasNP ) return cttHasNonPrimitiveTS; // has something different from CD-like ones (and not CD) if ( hasOther || !isCompletelyDefined() ) return cttRegular; // no more 'other' concepts here, and the CD-like structure if ( hasLCD ) return cttLikeCompletelyDefined; return cttTrueCompletelyDefined; } bool TConcept :: hasSelfInDesc ( const DLTree* t ) const { if ( t == NULL ) return false; switch ( t->Element().getToken() ) { case NAME: // if ID contains synonym of P { const ClassifiableEntry* name = static_cast(t->Element().getNE()); return resolveSynonym(name) == this; } case AND: return hasSelfInDesc(t->Left()) || hasSelfInDesc(t->Right()); case NOT: // a [= (not a) -> a [= BOTTOM; a [= (a or b) -> a [= TOP switch ( t->Left()->Element().getToken() ) { case AND: case NAME: return hasSelfInDesc(t->Left()); default: return false; } default: return false; } } DLTree* TConcept :: replaceSelfWithConst ( const DLTree* t ) const { if ( t == NULL ) return NULL; switch ( t->Element().getToken() ) { case NAME: // if ID contains synonym of P { const ClassifiableEntry* name = static_cast(t->Element().getNE()); if ( resolveSynonym(name) == this ) return createTop(); else break; } case AND: // a [= (and a b) -> a [= b return createSNFAnd ( replaceSelfWithConst(t->Left()), replaceSelfWithConst(t->Right()) ); case NOT: // a [= (not a) -> a [= BOTTOM; a [= (a or b) -> a [= TOP switch ( t->Left()->Element().getToken() ) { case AND: case NAME: return createSNFNot(replaceSelfWithConst(t->Left())); default: break; } default: break; } return clone(t); } /// init told subsumers of the concept by given DESCription; @return TRUE iff concept is CD bool TConcept :: initToldSubsumers ( const DLTree* desc, RoleSSet& RolesProcessed ) { // no description => nothing to do (and yes, it is told) if ( desc == NULL ) return true; switch ( desc->Element().getToken() ) { case TOP: // the 1st node return true; case NAME: // it is a concept ID return addToldSubsumer(static_cast(desc->Element().getNE())); case AND: // add TS from BOTH parts of AND return initToldSubsumers ( desc->Left(), RolesProcessed ) & initToldSubsumers ( desc->Right(), RolesProcessed ); case NOT: // Domains from \ER.C and (>= n R.C) are told concepts { const TLexeme& cur = desc->Left()->Element(); if ( cur.getToken() == FORALL || cur.getToken() == LE ) SearchTSbyRoleAndSupers ( resolveRole(desc->Left()->Left()), RolesProcessed ); return false; } case SELF: // Domains and Range from participating role { const TRole* R = resolveRole(desc->Left()); SearchTSbyRoleAndSupers ( R, RolesProcessed ); SearchTSbyRoleAndSupers ( R->inverse(), RolesProcessed ); return false; } default: // not told one return false; } } void TConcept :: SearchTSbyRole ( const TRole* R, RoleSSet& RolesProcessed ) { const DLTree* Domain = R->getTDomain(); if ( Domain == NULL || isConst(Domain) ) return; // don't process the same role twice if ( RolesProcessed.find(R) != RolesProcessed.end() ) return; // mark role as processed; usually it's the only role, so set hint as a begin() RolesProcessed.insert ( RolesProcessed.begin(), R ); // init TS by the domain of role initToldSubsumers ( Domain, RolesProcessed ); // don't bother about result } void TConcept :: SearchTSbyRoleAndSupers ( const TRole* r, RoleSSet& RolesProcessed ) { SearchTSbyRole ( r, RolesProcessed ); // do the same for all super-roles if necessary // FIXME!! need to do the same for DomSupers (like SoR [= R) for ( TRole::const_iterator q = r->begin_anc(), q_end = r->end_anc(); q != q_end; ++q ) SearchTSbyRole ( *q, RolesProcessed ); } unsigned int TConcept :: calculateTSDepth ( void ) { if ( tsDepth > 0 ) return tsDepth; unsigned int max = 0; for ( ClassifiableEntry::iterator p = told_begin(); p != told_end(); ++p ) { unsigned int cur = static_cast(*p)->calculateTSDepth(); if ( max < cur ) max = cur; } return (tsDepth = max+1); } FaCTpp-src-v1.6.2~dfsg/src/Kernel/configure.h0000644000000000000000000001077012112642405017513 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2008 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef __CONFIGURE_H #define __CONFIGURE_H const unsigned MaxConfLineLen = 1024; #include #include #include #include #include /// configure element in the form Name = Value class ConfElem { public: // members /// name of the field const std::string Name; /// value of the field std::string Value; public: // interface /// empty c'tor ConfElem () {} /// init c'tor ConfElem ( const std::string& n, const std::string& v ) : Name (n), Value (v) {} /// save element to target stream void Save ( std::ostream& o ) const; // interface long GetLong ( void ) const { return atol ( Value.c_str() ); } double GetDouble ( void ) const { return atof ( Value.c_str() ); } const char* GetString ( void ) const { return Value.c_str(); } }; // ConfElem /// class for storing configure section with all the keys class ConfSection { protected: const std::string Name; typedef std::vector ConfBase; ConfBase Base; public: ConfSection ( const std::string& pc ) : Name ( pc ) {} ~ConfSection ( void ); bool operator == ( const std::string& pc ) const { return ( Name == pc ); } bool operator != ( const std::string& pc ) const { return ( Name != pc ); } void addEntry ( const std::string& Name, const std::string& Value ); // find element; return NULL if not found ConfElem* FindByName ( const std::string& name ) const; void Save ( std::ostream& o ) const; }; // ConfSection /// class for reading general configuration file class Configuration { protected: // parsing part std::string fileName; // fileName char Line [MaxConfLineLen+1]; // \0 bool isLoaded, isSaved; // flags // parser methods void loadString ( std::istream& ); bool isComment ( void ) const; bool isSection ( void ) const { return ( Line [0] == '[' && Line [strlen(Line)-1] == ']' ); } void loadSection ( void ); // splits line 'name=value' on 2 ASCIIZ parts int SplitLine ( char*& pName, char*& pValue ); protected: // logic part typedef std::vector ConfSectBase; ConfSectBase Base; ConfSection* Section; ConfElem* Element; // navigation methods ConfSection* FindSection ( const std::string& pc ) const; private: // no copy /// no copy c'tor Configuration ( const Configuration& ); /// no assignment Configuration& operator = ( const Configuration& ); public: Configuration ( void ) : isLoaded(false) , isSaved(false) , Section(NULL) , Element(NULL) {} ~Configuration ( void ); // load config from file; @return true if cannot bool Load ( const char* Filename ); // save config to file; @return true if cannot bool Save ( const char* Filename ); // save config to the loaded file; @return true if cannot bool Save ( void ) { return isLoaded ? Save(fileName.c_str()) : true; } // status methods bool Loaded ( void ) const { return isLoaded; } bool Saved ( void ) const { return isSaved; } /// add section if necessary; set Current to new pointer void createSection ( const std::string& name ); /// check if Sect.Field exists; bool checkValue ( const std::string& Section, const std::string& Element ); /// check if Field exists if Current is set; bool checkValue ( const std::string& Element ); /// add Field.value to current Section; sets Trying to new p. bool setValue ( const std::string& Element, const std::string& Value ); // get checked value std::string getValue ( void ) const { return Element->Value; } long getLong ( void ) const { return Element->GetLong(); } double getDouble ( void ) const { return Element->GetDouble(); } const char* getString ( void ) const { return Element->GetString(); } // set Sect as a default bool useSection ( const std::string& name ) { Section = FindSection(name); return !Section; } }; // Configuration #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/modelCacheIan.cpp0000644000000000000000000001601012112642405020532 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2011 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "modelCacheIan.h" /// clear the cache void modelCacheIan :: clear ( void ) { posDConcepts.clear(); posNConcepts.clear(); negDConcepts.clear(); negNConcepts.clear(); #ifdef RKG_USE_SIMPLE_RULES extraDConcepts.clear(); extraNConcepts.clear(); #endif existsRoles.clear(); forallRoles.clear(); funcRoles.clear(); curState = csValid; } void modelCacheIan :: processConcept ( const DLVertex& cur, bool pos, bool det ) { switch ( cur.Type() ) { case dtTop: // sanity checks case dtDataType: // data entries can not be cached case dtDataValue: case dtDataExpr: fpp_unreachable(); break; case dtNConcept: // add concepts to Concepts case dtPConcept: case dtNSingleton: case dtPSingleton: (det ? getDConcepts(pos) : getNConcepts(pos)).insert(static_cast(cur.getConcept())->index()); break; case dtIrr: // for \neg \ER.Self: add R to AR-set case dtForall: // add AR.C roles to forallRoles case dtLE: // for <= n R: add R to forallRoles if ( unlikely ( cur.getRole()->isTop() ) ) // force clash to every other edge (pos ? forallRoles : existsRoles).completeSet(); else if ( pos ) // no need to deal with existentials here: they would be created through edges { if ( cur.getRole()->isSimple() ) forallRoles.insert(cur.getRole()->index()); else processAutomaton(cur); } break; default: // all other -- nothing to do break; } } void modelCacheIan :: processAutomaton ( const DLVertex& cur ) { const RAStateTransitions& RST = cur.getRole()->getAutomaton()[cur.getState()]; // for every transition starting from a given state, // add the role that is accepted by a transition for ( RAStateTransitions::const_iterator i = RST.begin(), i_end = RST.end(); i < i_end; ++i ) for ( RATransition::const_iterator r = (*i)->begin(), r_end = (*i)->end(); r < r_end; ++r ) forallRoles.insert((*r)->index()); } modelCacheState modelCacheIan :: canMerge ( const modelCacheInterface* p ) const { if ( hasNominalClash(p) ) // fail to merge due to nominal precense return csFailed; // check if something goes wrong if ( p->getState () != csValid || getState () != csValid ) return mergeStatus ( p->getState (), getState () ); // here both models are valid; switch ( p->getCacheType() ) { case mctConst: // check for TOP (as the model is valid) return csValid; case mctSingleton: // check for the Singleton { BipolarPointer Singleton = static_cast(p)->getValue(); return isMergableSingleton ( getValue(Singleton), isPositive(Singleton) ); } case mctIan: return isMergableIan ( static_cast(p) ); default: // something unexpected return csUnknown; } } modelCacheState modelCacheIan :: isMergableSingleton ( unsigned int Singleton, bool pos ) const { fpp_assert ( Singleton != 0 ); // deterministic clash if ( getDConcepts(!pos).contains(Singleton) ) return csInvalid; // non-det clash else if ( getNConcepts(!pos).contains(Singleton) ) return csFailed; return csValid; } modelCacheState modelCacheIan :: isMergableIan ( const modelCacheIan* q ) const { if ( posDConcepts.intersects(q->negDConcepts) || q->posDConcepts.intersects(negDConcepts) # ifdef RKG_USE_SIMPLE_RULES || getExtra(/*det=*/true).intersects(q->getExtra(/*det=*/true)) # endif ) return csInvalid; else if ( posDConcepts.intersects(q->negNConcepts) || posNConcepts.intersects(q->negDConcepts) || posNConcepts.intersects(q->negNConcepts) || q->posDConcepts.intersects(negNConcepts) || q->posNConcepts.intersects(negDConcepts) || q->posNConcepts.intersects(negNConcepts) # ifdef RKG_USE_SIMPLE_RULES || getExtra(/*det=*/true).intersects(q->getExtra(/*det=*/false)) || getExtra(/*det=*/false).intersects(q->getExtra(/*det=*/true)) || getExtra(/*det=*/false).intersects(q->getExtra(/*det=*/false)) # endif || existsRoles.intersects(q->forallRoles) || q->existsRoles.intersects(forallRoles) || funcRoles.intersects(q->funcRoles) ) return csFailed; else // could be merged return csValid; } modelCacheState modelCacheIan :: merge ( const modelCacheInterface* p ) { fpp_assert ( p != NULL ); // check for nominal clash if ( hasNominalClash(p) ) { curState = csFailed; return getState(); } switch ( p->getCacheType() ) { case mctConst: // adds TOP/BOTTOM curState = mergeStatus ( getState(), p->getState() ); break; case mctSingleton: // adds Singleton { BipolarPointer Singleton = static_cast(p)->getValue(); mergeSingleton ( getValue(Singleton), isPositive(Singleton) ); break; } case mctIan: mergeIan(static_cast(p)); break; default: fpp_unreachable(); } updateNominalStatus(p); return getState(); } /// actual merge with a singleton cache void modelCacheIan :: mergeSingleton ( unsigned int Singleton, bool pos ) { modelCacheState newState = isMergableSingleton ( Singleton, pos ); if ( newState != csValid ) // some clash occured: adjust state curState = mergeStatus ( getState(), newState ); else // add singleton; no need to change state here getDConcepts(pos).insert(Singleton); } /// actual merge with an Ian's cache void modelCacheIan :: mergeIan ( const modelCacheIan* p ) { // setup curState curState = isMergableIan(p); // merge all sets: posDConcepts |= p->posDConcepts; posNConcepts |= p->posNConcepts; negDConcepts |= p->negDConcepts; negNConcepts |= p->negNConcepts; #ifdef RKG_USE_SIMPLE_RULES extraDConcepts |= p->extraDConcepts; extraNConcepts |= p->extraNConcepts; #endif existsRoles |= p->existsRoles; forallRoles |= p->forallRoles; funcRoles |= p->funcRoles; } // logging #ifdef _USE_LOGGING void modelCacheIan :: logCacheEntry ( unsigned int level ) const { CHECK_LL_RETURN(level); LL << "\nIan cache: posDConcepts = "; posDConcepts.print(LL); LL << ", posNConcepts = "; posNConcepts.print(LL); LL << ", negDConcepts = "; negDConcepts.print(LL); LL << ", negNConcepts = "; negNConcepts.print(LL); #ifdef RKG_USE_SIMPLE_RULES LL << ", extraDConcepts = "; extraDConcepts.print(LL); LL << ", extraNConcepts = "; extraNConcepts.print(LL); #endif LL << ", existsRoles = "; existsRoles.print(LL); LL << ", forallRoles = "; forallRoles.print(LL); LL << ", funcRoles = "; funcRoles.print(LL); } #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/Actor.cpp0000644000000000000000000000304212112642405017127 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2006-2011 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "Actor.h" #include "tConcept.h" /// check whether actor is applicable to the ENTRY bool Actor :: applicable ( const ClassifiableEntry* entry ) { if ( isRole ) // object- or data-role { if ( isStandard ) // object role return true; else // data role -- need only direct ones return entry->getId() > 0; } else // concept or individual: standard are concepts return static_cast(entry)->isSingleton() != isStandard; } bool Actor :: apply ( const TaxonomyVertex& v ) { syn.clear(); tryEntry(v.getPrimer()); for ( TaxonomyVertex::syn_iterator p = v.begin_syn(), p_end=v.end_syn(); p != p_end; ++p ) tryEntry(*p); /// no applicable elements were found if ( syn.empty() ) return false; acc.push_back(syn); return true; } FaCTpp-src-v1.6.2~dfsg/src/Kernel/eFPPInconsistentKB.h0000644000000000000000000000205712112642405021141 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2007-2013 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef EFPPINCONSISTENTKB_H #define EFPPINCONSISTENTKB_H #include "eFaCTPlusPlus.h" class EFPPInconsistentKB: public EFaCTPlusPlus { public: // interface EFPPInconsistentKB ( void ) : EFaCTPlusPlus("FaCT++ Kernel: Inconsistent KB") {} }; // EFPPInconsistentKB #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/eFPPCycleInRIA.h0000644000000000000000000000304512112642405020124 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2007-2013 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef EFPPCYCLEINRIA_H #define EFPPCYCLEINRIA_H #include "eFaCTPlusPlus.h" /// exception thrown in case there is a (disallowed) cycle in a role-inclusion axiom class EFPPCycleInRIA: public EFaCTPlusPlus { private: // members /// saved name of the role const std::string roleName; /// error string std::string str; public: // interface /// c'tor: create an output string EFPPCycleInRIA ( const std::string& name ) : EFaCTPlusPlus() , roleName(name) { str = "Role '"; str += name; str += "' appears in a cyclic role inclusion axioms"; reason = str.c_str(); } /// empty d'tor virtual ~EFPPCycleInRIA ( void ) throw() {} /// access to the role const char* getRoleName ( void ) const { return roleName.c_str(); } }; // EFPPCycleInRIA #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/Reasoner.h0000644000000000000000000012343312112642405017311 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2012 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef REASONER_H #define REASONER_H #include "globaldef.h" #include "tBranchingContext.h" #include "dlCompletionGraph.h" #include "dlTBox.h" #include "dlDag.h" #include "modelCacheIan.h" #include "tSaveStack.h" #include "procTimer.h" #include "DataReasoning.h" #include "ToDoList.h" #include "tFastSet.h" #ifdef _USE_LOGGING // don't gather statistics w/o logging # define USE_REASONING_STATISTICS #endif #ifdef USE_REASONING_STATISTICS /// class for gathering statistic both for session and totally class AccumulatedStatistic { private: // prohibit copy /// copy c'tor (unimplemented) AccumulatedStatistic ( const AccumulatedStatistic& ); /// assignment (unimplemented) AccumulatedStatistic& operator = ( const AccumulatedStatistic& ); protected: // static members /// all members are linked together static AccumulatedStatistic* root; public: // static methods /// accumulate all registered statistic elements static void accumulateAll ( void ) { for ( AccumulatedStatistic* cur = root; cur; cur = cur->next ) cur->accumulate(); } protected: // members /// accumulated statistic unsigned int total; /// current session statistic unsigned int local; /// link to the next element AccumulatedStatistic* next; public: // interface /// c'tor: link itself to the list AccumulatedStatistic ( void ) : total(0), local(0), next(root) { root = this; } /// d'tor: remove link from the list ~AccumulatedStatistic ( void ) { // all statistic elements are deleted in the inversed creation order if ( root == this ) { root = next; return; } // we are here if it's multi-environment and arbitrary deletion order was chosen AccumulatedStatistic *prev = root, *cur = root->next; // find a pointer to current node for ( ; cur && cur != this; prev = cur, cur = cur->next ) (void)NULL; if ( cur == this ) prev->next = next; } // access to the elements /// get (RO) value of the element unsigned int get ( bool needLocal ) const { return needLocal ? local : total; } // general statistic operators /// increment local value void inc ( void ) { ++local; } /// set local value to particular N void set ( unsigned int n ) { local = n; } /// add local value to a global one void accumulate ( void ) { total += local; local = 0; } // output void Print ( std::ostream& o, bool needLocal, const char* prefix, const char* suffix ) const { if ( get(needLocal) > 0 ) o << prefix << get(needLocal) << suffix; } }; // AccumulatedStatistic #endif class DlSatTester { protected: // type definition /// TODO table type typedef ToDoList ToDoTableType; /// vector of edges typedef std::vector EdgeVector; /// vector of nodes typedef std::vector NodeVector; /// RO label iterator typedef DlCompletionTree::const_label_iterator const_label_iterator; /// set to keep BPs (during cascaded cache creation) typedef std::set BPSet; protected: // types /// possible flags of re-checking ALL-like expressions in new nodes enum { redoForall = 1, redoFunc = 2, redoAtMost = 4, redoIrr = 8 }; protected: // classes /// stack to keep BContext class BCStack: public TSaveStack { protected: // members /// pool for OR contexts DeletelessAllocator PoolOr; /// pool for NN contexts DeletelessAllocator PoolNN; /// pool for LE contexts DeletelessAllocator > PoolLE; /// pool for Top-LE contexts DeletelessAllocator > PoolTopLE; /// pool for Choose contexts DeletelessAllocator PoolCh; /// single entry for the barrier (good for nominal reasoner) BCBarrier* bcBarrier; protected: // methods /// specialise new method as the one doing nothing virtual BranchingContext* createNew ( void ) { return NULL; } /// push method to use BranchingContext* push ( BranchingContext* p ) { p->init(); TSaveStack::push(); this->Base[this->last-1] = p; return p; } public: // interface /// empty c'tor BCStack ( void ) : bcBarrier(new BCBarrier) {} /// empty d'tor virtual ~BCStack ( void ) { // all the members will be deleted in the resp. pools for ( iterator p = this->Base.begin(), p_end = this->Base.end(); p < p_end; ++p ) *p = NULL; delete bcBarrier; } // push methods /// get BC for Or-rule BranchingContext* pushOr ( void ) { return push(PoolOr.get()); } /// get BC for NN-rule BranchingContext* pushNN ( void ) { return push(PoolNN.get()); } /// get BC for LE-rule BranchingContext* pushLE ( void ) { return push(PoolLE.get()); } /// get BC for TopLE-rule BranchingContext* pushTopLE ( void ) { return push(PoolTopLE.get()); } /// get BC for Choose-rule BranchingContext* pushCh ( void ) { return push(PoolCh.get()); } /// get BC for the barrier BranchingContext* pushBarrier ( void ) { return push(bcBarrier); } /// clear all the pools void clearPools ( void ) { PoolOr.clear(); PoolNN.clear(); PoolLE.clear(); PoolTopLE.clear(); PoolCh.clear(); } /// clear the stack and pools virtual void clear ( void ) { clearPools(); TSaveStack::clear(); } }; // BCStack protected: // members /// host TBox TBox& tBox; /// link to dag from TBox DLDag& DLHeap; /// all the reflexive roles RoleMaster::TRoleVec ReflexiveRoles; /// manager for all the dep-sets corresponding to a graph here TDepSetManager Manager; /// Completion Graph of tested concept(s) DlCompletionGraph CGraph; /// TODO list ToDoTableType TODO; /// reasoning subsystem for the datatypes DataTypeReasoner DTReasoner; /// Used sets for pos- and neg- entries TFastSet pUsed, nUsed; /// cache for testing whether it's possible to non-expand newly created node modelCacheIan newNodeCache; /// auxilliary cache that is built from the edges of newly created node modelCacheIan newNodeEdges; /// GCI-related KB flags const TKBFlags& GCIs; /// record nodes that were processed during Cascaded Cache construction std::set inProcess; /// timer for the SAT tests (ie, cache creation) TsProcTimer satTimer; /// timer for the SUB tests (ie, general subsumption) TsProcTimer subTimer; /// timer for a single test; use it as a timeout checker TsProcTimer testTimer; // save/restore option /// stack for the local reasoner's state BCStack Stack; /// context from the restored branching rule BranchingContext* bContext; /// index of last non-det situation unsigned int tryLevel; /// shift in order to determine the 1st non-det application unsigned int nonDetShift; /// last level when split rules were applied unsigned int splitRuleLevel; // statistic elements #ifdef USE_REASONING_STATISTICS AccumulatedStatistic nTacticCalls, nUseless, nIdCalls, nSingletonCalls, nOrCalls, nOrBrCalls, nAndCalls, nSomeCalls, nAllCalls, nFuncCalls, nLeCalls, nGeCalls, nNNCalls, nMergeCalls, nAutoEmptyLookups, nAutoTransLookups, nSRuleAdd, nSRuleFire, nStateSaves, nStateRestores, nNodeSaves, nNodeRestores, nLookups, nFairnessViolations, // reasoning cache nCacheTry, nCacheFailedNoCache, nCacheFailedShallow, nCacheFailed, nCachedSat, nCachedUnsat; #endif // current values /// currently processed CTree node DlCompletionTree* curNode; /// currently processed Concept ConceptWDep curConcept; /// GCIs local to session std::vector SessionGCIs; /// set of active splits std::set ActiveSplits; /// concept signature of current CGraph TSplitRules::SigSet SessionSignature; /// signature to dep-set map for current session TSplitRules::SigDeps SessionSigDepSet; /// size of the DAG with some extra space size_t dagSize; /// temporary array used in OR operation BCOr::OrIndex OrConceptsToTest; /// temporary array used in <= operations EdgeVector EdgesToMerge; /// nodes to merge in the TopRole-LE rules NodeVector NodesToMerge; /// contains clash set if clash is encountered in a node label DepSet clashSet; // session status flags: /// true if nominal-related expansion rule was fired during reasoning bool encounterNominal; /// flag to show if it is necessary to produce DT reasoning immediately bool checkDataNode; private: // no copy /// no copy c'tor DlSatTester ( const DlSatTester& ); /// no assignment DlSatTester& operator = ( const DlSatTester& ); protected: // methods /// increment statistic counter #ifdef USE_REASONING_STATISTICS # define incStat(stat) stat.inc() #else # define incStat(stat) #endif //----------------------------------------------------------------------------- // flags section //----------------------------------------------------------------------------- /// @return timeout value for a single SAT/Sub test in milliseconds; 0 means no timeout unsigned long getSatTimeout ( void ) const { return tBox.testTimeout; } /// @return true iff semantic branching is used bool useSemanticBranching ( void ) const { return tBox.useSemanticBranching; } /// @return true iff lazy blocking is used bool useLazyBlocking ( void ) const { return tBox.useLazyBlocking; } /// @return true iff active signature is in use bool useActiveSignature ( void ) const { return !tBox.getSplits()->empty(); } /// reset all session flags void resetSessionFlags ( void ); /// adds C to the labels of NODE; @return true iff clash occurs bool addToDoEntry ( DlCompletionTree* node, const ConceptWDep& C, const char* reason = NULL ); /// synonym to the above bool addToDoEntry ( DlCompletionTree* node, BipolarPointer c, const DepSet& dep, const char* reason = NULL ) { return addToDoEntry ( node, ConceptWDep(c,dep), reason ); } /// insert C to the label of NODE; do necessary updates; may return Clash in case of data entry C bool insertToDoEntry ( DlCompletionTree* node, const ConceptWDep& C, DagTag tag, const char* reason ); /// if something was added to cached node N, un- or re-cache it; @return result of re-cache bool correctCachedEntry ( DlCompletionTree* n ); // CGraph-wide rules support /// @return true if node is valid for the reasoning bool isNodeGloballyUsed ( const DlCompletionTree* node ) const { return ! ( node->isDataNode() || node->isIBlocked() || node->isPBlocked() ); } /// @return true if node is valid for the reasoning bool isObjectNodeUnblocked ( const DlCompletionTree* node ) const { return isNodeGloballyUsed(node) && !node->isDBlocked(); } /// add C to a set of session GCIs; init all nodes with (C,dep) bool addSessionGCI ( BipolarPointer C, const DepSet& dep ); // split rules support /// apply split rule RULE to a reasoner. @return true if clash was found bool applySplitRule ( TSplitRules::const_iterator rule ); /// check whether any split rules should be run and do it. @return true iff clash was found bool checkSplitRules ( void ); /// add entity->dep to a session structures void updateSessionSignature ( const TNamedEntity* entity, const DepSet& dep ) { if ( unlikely ( entity != NULL ) ) { SessionSignature.insert(entity); SessionSigDepSet[entity].add(dep); } } /// update session signature with all names from a given node void updateSignatureByNode ( DlCompletionTree* node) { const CGLabel& lab = node->label(); for ( CGLabel::const_iterator p = lab.begin_sc(), p_end = lab.end_sc(); p != p_end; ++p ) updateSessionSignature ( tBox.SplitRules.getEntity(p->bp()), p->getDep() ); } /// update session signature for all non-data nodes void updateSessionSignature ( void ) { for ( DlCompletionGraph::iterator p = CGraph.begin(), p_end = CGraph.end(); p != p_end; ++p ) if ( isObjectNodeUnblocked(*p) ) updateSignatureByNode(*p); } /// put TODO entry for either BP or inverse(BP) in NODE's label void updateName ( DlCompletionTree* node, BipolarPointer bp ) { const CGLabel& lab = node->label(); CGLabel::const_iterator p; for ( p = lab.begin_sc(); p != lab.end_sc(); ++p ) if ( unlikely ( p->bp() == bp || p->bp() == inverse(bp) ) ) { addExistingToDoEntry ( node, lab.getSCOffset(p), "sp" ); break; } } /// re-do every BP or inverse(BP) in labels of CGraph void updateName ( BipolarPointer bp ) { for ( DlCompletionGraph::iterator p = CGraph.begin(), p_end = CGraph.end(); p != p_end; ++p ) if ( isNodeGloballyUsed(*p) ) updateName ( *p, bp ); } // label access interface /// try to add a concept to a label given by TAG; ~C can't appear in the label bool findConcept ( const CWDArray& lab, BipolarPointer bp ); /// try to add a concept to a label given by TAG; ~C can't appear in the label bool findConcept ( const CWDArray& lab, const ConceptWDep& C ) { return findConcept ( lab, C.bp() ); } /// try to add a concept to a label given by TAG; ~C can't appear in the label; setup clash-set if found bool findConceptClash ( const CWDArray& lab, BipolarPointer bp, const DepSet& dep ); /// try to add a concept to a label given by TAG; ~C can't appear in the label; setup clash-set if found bool findConceptClash ( const CWDArray& lab, const ConceptWDep& C ) { return findConceptClash ( lab, C.bp(), C.getDep() ); } /// check if it is possible to add a concept to a label given by TAG addConceptResult checkAddedConcept ( const CWDArray& lab, BipolarPointer bp, const DepSet& dep ); /// check if C or ~C is already in LAB addConceptResult tryAddConcept ( const CWDArray& lab, BipolarPointer bp, const DepSet& dep ); /** Adds ToDo entry which already exists in label of NODE. There is no need to add entry to label, but it is necessary to provide offset of existing concept. This is done by providing OFFSET of the concept in NODE's label */ void addExistingToDoEntry ( DlCompletionTree* node, int offset, const char* reason = NULL ) { const ConceptWDep& C = node->label().getConcept(offset); TODO.addEntry ( node, DLHeap[C.bp()].Type(), C, offset ); if ( LLM.isWritable(llGTA) ) logEntry ( node, C, reason ); } /// add all elements from NODE label into TODO list void redoNodeLabel ( DlCompletionTree* node, const char* reason ) { const CGLabel& lab = node->label(); CGLabel::const_iterator p; for ( p = lab.begin_sc(); p != lab.end_sc(); ++p ) addExistingToDoEntry ( node, lab.getSCOffset(p), reason ); for ( p = lab.begin_cc(); p != lab.end_cc(); ++p ) addExistingToDoEntry ( node, lab.getCCOffset(p), reason ); } /// main reasoning function bool checkSatisfiability ( void ); /// perform all the actions that should be done once, after all normal rules are not applicable. @return true if the concept is unsat bool performAfterReasoning ( void ); /// make sure that the DAG does not grow larger than that was recorded void ensureDAGSize ( void ) { if ( unlikely ( dagSize < DLHeap.size() ) ) { dagSize = DLHeap.maxSize(); pUsed.ensureMaxSetSize(dagSize); nUsed.ensureMaxSetSize(dagSize); tBox.SplitRules.ensureDagSize(dagSize); } } //----------------------------------------------------------------------------- //-- internal cache support //----------------------------------------------------------------------------- /// build cache suitable for classification void prepareCascadedCache ( BipolarPointer p ); /// create cache for given DAG node bu building model; @return cache modelCacheInterface* buildCache ( BipolarPointer p ); /// return cache of given completion tree (implementation) modelCacheInterface* createModelCache ( const DlCompletionTree* p ) const { return new modelCacheIan ( DLHeap, p, encounterNominal, tBox.nC, tBox.nR ); } /// check whether given NODE can be cached bool canBeCached ( DlCompletionTree* node ); /// build cache of the node (it is known that caching is possible) in newNodeCache void doCacheNode ( DlCompletionTree* node ); /// mark NODE (un)cached depending on the joint cache STATUS; @return resulting status modelCacheState reportNodeCached ( DlCompletionTree* node ); /// check whether node may be (un)cached; save node if something is changed modelCacheState tryCacheNode ( DlCompletionTree* node ) { modelCacheState ret = canBeCached(node) ? reportNodeCached(node) : csFailed; // node is cached if RET is csValid CGraph.saveRareCond(node->setCached(ret == csValid)); return ret; } /// @return true iff cache status is invalid static bool usageByState ( modelCacheState status ) { return status == csInvalid; } //----------------------------------------------------------------------------- //-- internal nominal reasoning interface //----------------------------------------------------------------------------- /// check whether reasoning with nominals is performed virtual bool hasNominals ( void ) const { return false; } /// check satisfiability of task which is set-up bool runSat ( void ); /* * Tactics description; * * Each tactic represents (possibly combined) expansion rule for * certain type of concept expression (parameter CUR). * * Each tactic returns: * - true - if expansion of CUR lead to clash * - false - overwise */ /// main calling method; wrapper for Body bool commonTactic ( void ); /// choose proper tactic based on type of a concept constructor bool commonTacticBody ( const DLVertex& cur ); /// expansion rule for (non)primitive concept bool commonTacticBodyId ( const DLVertex& cur ); /// expansion rule for (non)primitive singleton concept bool commonTacticBodySingleton ( const DLVertex& cur ); /// expansion rule for conjunction bool commonTacticBodyAnd ( const DLVertex& cur ); /// expansion rule for disjunction bool commonTacticBodyOr ( const DLVertex& cur ); /// expansion rule for general existential quantifier bool commonTacticBodySome ( const DLVertex& cur ); /// expansion rule for existential quantifier in the form \ER{nom} bool commonTacticBodyValue ( const TRole* R, const TIndividual* nom ); /// expansion rule for the existential quantifier with universal role bool commonTacticBodySomeUniv ( const DLVertex& cur ); /// expansion rule for universal restriction bool commonTacticBodyAll ( const DLVertex& cur ); /// expansion rule for universal restriction with simple role using RA bool commonTacticBodyAllSimple ( const DLVertex& cur ); /// expansion rule for universal restriction with non-simple role using RA bool commonTacticBodyAllComplex ( const DLVertex& cur ); /// expansion rule for \E R{Self} bool commonTacticBodySomeSelf ( const TRole* R ); /// expansion rule for \neg\E R{Self} bool commonTacticBodyIrrefl ( const TRole* R ); /// expansion rule for at-least number restriction bool commonTacticBodyGE ( const DLVertex& cur ); /// expansion rule for at-most number restriction bool commonTacticBodyLE ( const DLVertex& cur ); /// expansion rule for choose-rule bool commonTacticBodyChoose ( const TRole* R, BipolarPointer C ); /// expansion rule for functional restriction bool commonTacticBodyFunc ( const DLVertex& cur ); /// expansion rule for at-most restriction in nominal node (NN-rule) bool commonTacticBodyNN ( const DLVertex& cur ); /// expansion rule for auxilliary projection-construction bool commonTacticBodyProj ( const TRole* R, BipolarPointer C, const TRole* ProjR ); /// expansion rule for split bool commonTacticBodySplit ( const DLVertex& cur ); /// expansion rule for the functional restriction with top role bool processTopRoleFunc ( const DLVertex& cur ); /// expansion rule for the at-most restriction with top role bool processTopRoleLE ( const DLVertex& cur ); /// expansion rule for the at-least restriction with top role bool processTopRoleGE ( const DLVertex& cur ); // support for inapplicable tactics /// @return true iff current node is i-blocked (ie, no expansion necessary) bool isIBlocked ( void ) const { return curNode->isIBlocked(); } /// @return true iff NN-rule wrt (<= R.C) is applicable to the curNode bool isNNApplicable ( const TRole* r, BipolarPointer C, BipolarPointer stopper ) const; /// apply rule-like actions for the concept P bool applyExtraRules ( const TConcept* p ); /// apply rule-like actions for the concept P if necessary inline bool applyExtraRulesIf ( const TConcept* p ) { if ( !p->hasExtraRules() ) return false; fpp_assert ( p->isPrimitive() ); return applyExtraRules(p); } // support for choose-rule /// apply choose-rule for given range of edges bool applyChooseRule ( DlCompletionTree* node, BipolarPointer C ); // support for creating/updating edge methods /// check whether current node is blocked bool isCurNodeBlocked ( void ); /// apply all the generating rules for the (unblocked) current node void applyAllGeneratingRules ( DlCompletionTree* node ); /// add C and T_G with given DEP-set to a NODE; @return DONE/CLASH bool initNewNode ( DlCompletionTree* node, const DepSet& dep, BipolarPointer C ); /// apply reflexive roles to the (newly created) NODE with apropriate DEP; @return true for clash bool applyReflexiveRoles ( DlCompletionTree* node, const DepSet& dep ); /// add necessary concepts to the NODE of the new edge, labelled with R bool initHeadOfNewEdge ( DlCompletionTree* node, const TRole* R, const DepSet& dep, const char* reason ); // support for existential-like rules /// @return true iff there is R-neighbour labelled with C bool isSomeExists ( const TRole* R, BipolarPointer C ) const { if ( !isUsed(C) ) return false; const DlCompletionTree* where = curNode->isSomeApplicable ( R, C ); if ( where != NULL ) if ( LLM.isWritable(llGTA) ) LL << " E(" << R->getName() << "," << where->getId() << "," << C << ")"; return where != NULL; } /// aux method for setting up new edge PA bool setupEdge ( DlCompletionTreeArc* pA, const DepSet& curDep, unsigned int flags ); /// aux method for creating new edge from curNode with given ROLE edge label and CONCEPT at the final label bool createNewEdge ( const TRole* Role, BipolarPointer Concept, unsigned int flags ); /// create new ROLE-neighbour with LEVEL to curNode; return edge to it DlCompletionTreeArc* createOneNeighbour ( const TRole* Role, const DepSet& dep, CTNominalLevel level = BlockableLevel ); // support for re-applying expansion rules for FORALL-like concepls in node label /** apply AR.C in and <= nR (if needed) in NODE's label where R is label of arcSample. Set of applicable concepts is defined by redoForallFlags value. */ bool applyUniversalNR ( DlCompletionTree* Node, const DlCompletionTreeArc* arcSample, const DepSet& dep, unsigned int flags ); // support for branching rules /// check if branching rule was called for the 1st time bool isFirstBranchCall ( void ) const { return bContext == NULL; } /// init branching context with given rule type void initBC ( void ) { // save reasoning context bContext->curNode = curNode; bContext->curConcept = curConcept; bContext->branchDep = curConcept.getDep(); bContext->pUsedIndex = pUsed.size(); bContext->nUsedIndex = nUsed.size(); bContext->SGsize = SessionGCIs.size(); } /// clear branching context void clearBC ( void ) { bContext = NULL; } /// create BC for Or rule void createBCOr ( void ) { bContext = Stack.pushOr(); initBC(); } /// create BC for NN-rule void createBCNN ( void ) { bContext = Stack.pushNN(); initBC(); } /// create BC for LE-rule void createBCLE ( void ) { bContext = Stack.pushLE(); initBC(); } /// create BC for LE-rule void createBCTopLE ( void ) { bContext = Stack.pushTopLE(); initBC(); } /// create BC for Choose-rule void createBCCh ( void ) { bContext = Stack.pushCh(); initBC(); } /// create BC for the barrier void createBCBarrier ( void ) { bContext = Stack.pushBarrier(); initBC(); } // support for disjunction /// Aux method for locating OR node characteristics; @return true if node is labelled by one of DJs bool planOrProcessing ( const DLVertex& cur, DepSet& dep ); /// aux method for disjunction processing bool processOrEntry ( void ); // support for (qualified) number restrictions /// create N R-neighbours of curNode with given Nominal LEVEL labelled with C bool createDifferentNeighbours ( const TRole* R, BipolarPointer C, const DepSet& dep, unsigned int n, CTNominalLevel level ); /// check whether a node represents a functional one static bool isFunctionalVertex ( const DLVertex& v ) { return ( v.Type() == dtLE && v.getNumberLE() == 1 && v.getC() == bpTOP ); } /// check if ATLEAST and ATMOST entries are in clash. Both vertex MUST have dtLE type. bool checkNRclash ( const DLVertex& atleast, const DLVertex& atmost ) const { // >= n R.C clash with <= m S.D iff... return (atmost.getC() == bpTOP || atleast.getC() == atmost.getC()) && // either D is TOP or C == D... atleast.getNumberGE() > atmost.getNumberLE() && // and n is greater than m... *atleast.getRole() <= *atmost.getRole(); // and R [= S } /// check if ATLEAST and ATMOST restrictions are in clash; setup depset from CUR bool isNRClash ( const DLVertex& atleast, const DLVertex& atmost, const ConceptWDep& reason ); /// quick check whether CURNODE has a clash with a given ATMOST restriction bool isQuickClashLE ( const DLVertex& atmost ) { for ( DlCompletionTree::const_label_iterator q = curNode->beginl_cc(), q_end = curNode->endl_cc(); q < q_end; ++q ) if ( isNegative(q->bp()) // need at-least restriction && isNRClash ( DLHeap[*q], atmost, *q ) ) return true; return false; } /// quick check whether CURNODE has a clash with a given ATLEAST restriction bool isQuickClashGE ( const DLVertex& atleast ) { for ( DlCompletionTree::const_label_iterator q = curNode->beginl_cc(), q_end = curNode->endl_cc(); q < q_end; ++q ) if ( isPositive(q->bp()) // need at-most restriction && isNRClash ( atleast, DLHeap[*q], *q ) ) return true; return false; } /// init the LE processing (fill in the EdgesToMerge); @return true if the CR is satisfied bool initLEProcessing ( const DLVertex& cur ); /// init the LE processing for the TopRole (fill in the NodesToMerge); @return true if the CR is satisfied bool initTopLEProcessing ( const DLVertex& cur ); /// aux method that fills the dep-set for either C or ~C found in the label; @return whether C was found bool findChooseRuleConcept ( const CWDArray& label, BipolarPointer C, DepSet& Dep ) { if ( C == bpTOP ) return true; if ( findConceptClash ( label, C, Dep ) ) { Dep.add(getClashSet()); return true; } else if ( findConceptClash ( label, inverse(C), Dep ) ) { Dep.add(getClashSet()); return false; } else fpp_unreachable(); } /// apply choose-rule for all vertices (necessary for Top role in QCR) bool applyChooseRuleGlobally ( BipolarPointer C ); /// aux method which fills EdgesToMerge with *different* ROLE-neighbours of curNode void findNeighbours ( const TRole* Role, BipolarPointer C, DepSet& Dep ); /// the same but for universal role void findCLabelledNodes ( BipolarPointer C, DepSet& Dep ); /// aux method that checks whether clash occurs during the merge of labels bool checkMergeClash ( const CGLabel& from, const CGLabel& to, const DepSet& dep, unsigned int nodeId ); /// aux method that merge FROM label to the TO node with an appropriadte dep-set bool mergeLabels ( const CGLabel& from, DlCompletionTree* to, const DepSet& dep ); /// merge FROM node into TO node with additional dep-set DEPF bool Merge ( DlCompletionTree* from, DlCompletionTree* to, const DepSet& depF ); /// check whether clash occures due to new edge from FROM to TO labelled with R bool checkDisjointRoleClash ( DlCompletionTree* from, DlCompletionTree* to, const TRole* R, const DepSet& dep ); /// check whether clash occures EDGE to TO labelled with S disjoint with R bool checkDisjointRoleClash ( const DlCompletionTreeArc* edge, DlCompletionTree* to, const TRole* R, const DepSet& dep ) { // clash found if ( edge->getArcEnd() == to && edge->getRole()->isDisjoint(R) ) { setClashSet(dep); updateClashSet(edge->getDep()); return true; } return false; } // support for FORALL expansion /** Perform expansion of (\neg \ER.Self).DEP to an EDGE */ bool checkIrreflexivity ( const DlCompletionTreeArc* edge, const TRole* R, const DepSet& dep ) { // only loops counts here... if ( edge->getArcEnd() != edge->getReverse()->getArcEnd() ) return false; // which are labelled either with R or with R- if ( !edge->isNeighbour(R) && !edge->isNeighbour(R->inverse()) ) return false; // set up clash setClashSet(dep); updateClashSet(edge->getDep()); return true; } /** Perform expansion of (C=\AR{0}.X).DEP wrt RST to an EDGE with a given reason */ bool applyTransitions ( const DlCompletionTreeArc* edge, const RAStateTransitions& RST, BipolarPointer C, const DepSet& dep, const char* reason = NULL ); // support for the projection /// apply projection to given edge if necessary bool checkProjection ( DlCompletionTreeArc* pA, BipolarPointer C, const TRole* ProjR ); // datatype staff /// @return true iff given data node contains inconsistent data constraints bool hasDataClash ( const DlCompletionTree* node ); /// @return true iff given data node contains inconsistent data constraints bool checkDataClash ( const DlCompletionTree* node ) { if ( hasDataClash(node) ) { setClashSet(DTReasoner.getClashSet()); return true; } else return false; } // logging actions /// log indentation void logIndentation ( void ) const; /// log start of processing of a ToDo entry void logStartEntry ( void ) const; /// log finish of processing of a ToDo entry void logFinishEntry ( bool res ) const; /// log the result of processing ACTION with entry (N,C{DEP})/REASON void logNCEntry ( const DlCompletionTree* n, const ConceptWDep& C, const char* action, const char* reason ) const { CHECK_LL_RETURN(llGTA); // useless, but safe LL << " " << action << "("; n->logNode(); LL << "," << C.bp() << C.getDep() << ")"; if ( reason ) LL << reason; } /// log addition of the entry to ToDo list void logEntry ( const DlCompletionTree* n, const ConceptWDep& C, const char* reason ) const { logNCEntry ( n, C, "+", reason ); } /// log clash happened during node processing void logClash ( const DlCompletionTree* n, const ConceptWDep& C ) const { logNCEntry ( n, C, "x", DLHeap[C].getTagName() ); } /// write root subtree of CG with given LEVEL void writeRoot ( unsigned int level ) { if ( LLM.isWritable(level) ) CGraph.Print(LL); } /// merge session statistics to the global one void finaliseStatistic ( void ); /// write down statistics wrt LOCAL flag void logStatisticData ( std::ostream& o, bool needLocal ) const; // save/restore methods /// restore local state from current branching context void restoreBC ( void ); /// use this method in ALL dependency stuff (never use tryLevel directly) unsigned int getCurLevel ( void ) const { return tryLevel; } /// set new branching level (never use tryLevel directly) void setCurLevel ( unsigned int level ) { tryLevel = level; } /// @return true if no branching ops were applied during reasoners; FIXME!! doesn't work properly with a nominal cloud bool noBranchingOps ( void ) const { return tryLevel == InitBranchingLevelValue + nonDetShift; } /// Get save/restore level based on either current- or DS level unsigned int getSaveRestoreLevel ( const DepSet& ds ATTR_UNUSED ) const { return // FIXME!!! see more precise it later # ifdef RKG_IMPROVE_SAVE_RESTORE_DEPSET ds.level()+1; # else getCurLevel(); # endif } /// save current reasoning state void save ( void ); /// restore reasoning state to the latest saved position void restore ( void ) { return restore(getCurLevel()-1); } /// restore reasoning state to the NEWTRYLEVEL position void restore ( unsigned int newTryLevel ); /// update level in N node and save it's state (if necessary) void updateLevel ( DlCompletionTree* n, const DepSet& ds ) { CGraph.saveNode ( n, getSaveRestoreLevel(ds) ); } /// finalize branching OP processing making deterministic op void determiniseBranchingOp ( void ) { clearBC(); // clear context for the next branching op Stack.pop(); // remove unnecessary context from the stack } // access to global clashset, which contains result of clash during label addition /// get value of global dep-set const DepSet& getClashSet ( void ) const { return clashSet; } /// set value of global dep-set to D void setClashSet ( const DepSet& d ) { clashSet = d; } /// add D to global dep-set void updateClashSet ( const DepSet& d ) { clashSet.add(d); } /// get dep-set wrt current level DepSet getCurDepSet ( void ) const { return DepSet(Manager.get(getCurLevel()-1)); } /// get RW access to current branching dep-set DepSet& getBranchDep ( void ) { return bContext->branchDep; } /// get RO access to current branching dep-set const DepSet& getBranchDep ( void ) const { return bContext->branchDep; } /// update cumulative branch-dep with current clash-set void updateBranchDep ( void ) { getBranchDep().add(getClashSet()); } /// prepare cumulative dep-set to usage void prepareBranchDep ( void ) { getBranchDep().restrict(getCurLevel()); } /// prepare cumulative dep-set and copy itto general clash-set void useBranchDep ( void ) { prepareBranchDep(); setClashSet(getBranchDep()); } /// restore one level (no backjumping) bool straightforwardRestore ( void ); /// restore if backjumping is used bool backJumpedRestore ( void ); /// restore state based on usedBackjumping flag bool tunedRestore ( void ); /// check if P was used during current reasoning session bool isUsed ( BipolarPointer p ) const { return ( isPositive(p) ? pUsed : nUsed ).in(getValue(p)); } /// set P as a used during current reasoning void setUsed ( BipolarPointer p ) { ( isPositive(p) ? pUsed : nUsed ).add(getValue(p)); } public: // rule's support /// @return true if the rule is applicable; set the dep-set accordingly bool applicable ( const TBox::TSimpleRule& rule ); public: // blocking support /// re-apply all the relevant expantion rules to a given unblocked NODE void repeatUnblockedNode ( DlCompletionTree* node, bool direct ) { if ( direct ) // not blocked -- clear blocked cache applyAllGeneratingRules(node); // re-apply all the generating rules else redoNodeLabel ( node, "ubi" ); } /// get access to the DAG associated with it (necessary for the blocking support) const DLDag& getDAG ( void ) const { return tBox.DLHeap; } public: /// c'tor DlSatTester ( TBox& tbox ); /// d'tor virtual ~DlSatTester ( void ) {} /// prepare reasoner to a new run virtual void prepareReasoner ( void ); /// set-up satisfiability task for given pointers and run runSat on it bool runSat ( BipolarPointer p, BipolarPointer q = bpTOP ); /// set-up role disjointness task for given roles and run SAT test bool checkDisjointRoles ( const TRole* R, const TRole* S ); /// set-up role irreflexivity task for R and run SAT test bool checkIrreflexivity ( const TRole* R ); /// get the ROOT node of the completion graph const DlCompletionTree* getRootNode ( void ) const { return CGraph.getRoot(); } /// set blocking method for a session void setBlockingMethod ( bool hasInverse, bool hasQCR ) { CGraph.setBlockingMethod ( hasInverse, hasQCR ); } /// build cache entry for given DAG node, using cascaded schema; @return cache const modelCacheInterface* createCache ( BipolarPointer p ); /// create model cache for the just-classified entry modelCacheInterface* buildCacheByCGraph ( bool sat ) const { if ( sat ) // here we need actual (not a p-blocked) root of the tree return createModelCache(getRootNode()); else // unsat => cache is just bottom return createConstCache(bpBOTTOM); } void writeTotalStatistic ( std::ostream& o ) { # ifdef USE_REASONING_STATISTICS AccumulatedStatistic::accumulateAll(); // ensure that the last reasoning results are in logStatisticData ( o, /*needLocal=*/false ); # endif printBlockingStat (o); clearBlockingStat(); o << "\n"; } /// print SAT/SUB timings to O; @return total time spend during reasoning float printReasoningTime ( std::ostream& o ) const; }; // DlSatTester // implementation inline void DlSatTester :: resetSessionFlags ( void ) { // reflect possible change of DAG size ensureDAGSize(); setUsed(bpTOP); setUsed(bpBOTTOM); encounterNominal = false; checkDataNode = true; splitRuleLevel = 0; } inline bool DlSatTester :: initNewNode ( DlCompletionTree* node, const DepSet& dep, BipolarPointer C ) { if ( node->isDataNode() ) // creating new data node -- do data check once in the end checkDataNode = false; node->setInit(C); if ( unlikely ( addToDoEntry ( node, C, dep ) ) ) return true; if ( node->isDataNode() ) return false; if ( unlikely ( addToDoEntry ( node, tBox.getTG(), dep ) ) ) return true; if ( unlikely ( GCIs.isReflexive() && applyReflexiveRoles ( node, dep ) ) ) return true; if ( unlikely ( !SessionGCIs.empty() ) ) for ( std::vector::iterator p = SessionGCIs.begin(), p_end = SessionGCIs.end(); p != p_end; ++p ) if ( unlikely ( addToDoEntry ( node, *p, dep, "sg" ) ) ) return true; return false; } inline bool DlSatTester :: runSat ( BipolarPointer p, BipolarPointer q ) { prepareReasoner(); // use general method to init node with P and add Q then if ( initNewNode ( CGraph.getRoot(), DepSet(), p ) || addToDoEntry ( CGraph.getRoot(), ConceptWDep(q) ) ) return false; // concept[s] unsatisfiable // check satisfiability explicitly TsProcTimer& timer = q == bpTOP ? satTimer : subTimer; timer.Start(); bool result = runSat(); timer.Stop(); return result; } inline bool DlSatTester :: checkDisjointRoles ( const TRole* R, const TRole* S ) { prepareReasoner(); // use general method to init node... DepSet dummy; if ( initNewNode ( CGraph.getRoot(), dummy, bpTOP ) ) return true; // ... add edges with R and S... curNode = CGraph.getRoot(); DlCompletionTreeArc* edgeR = createOneNeighbour ( R, dummy ); DlCompletionTreeArc* edgeS = createOneNeighbour ( S, dummy ); // init new nodes/edges. No need to apply restrictions, as no reasoning have been done yet. if ( initNewNode ( edgeR->getArcEnd(), dummy, bpTOP ) || initNewNode ( edgeS->getArcEnd(), dummy, bpTOP ) || setupEdge ( edgeR, dummy, /*flags=*/0 ) || setupEdge ( edgeS, dummy, /*flags=*/0 ) || Merge ( edgeS->getArcEnd(), edgeR->getArcEnd(), dummy ) ) return true; // 2 roles are disjoint if current setting is unsatisfiable curNode = NULL; return !runSat(); } inline bool DlSatTester :: checkIrreflexivity ( const TRole* R ) { prepareReasoner(); // use general method to init node... DepSet dummy; if ( initNewNode ( CGraph.getRoot(), dummy, bpTOP ) ) return true; // ... add an R-loop curNode = CGraph.getRoot(); DlCompletionTreeArc* edgeR = createOneNeighbour ( R, dummy ); // init new nodes/edges. No need to apply restrictions, as no reasoning have been done yet. if ( initNewNode ( edgeR->getArcEnd(), dummy, bpTOP ) || setupEdge ( edgeR, dummy, /*flags=*/0 ) || Merge ( edgeR->getArcEnd(), CGraph.getRoot(), dummy ) ) return true; // R is irreflexive if current setting is unsatisfiable curNode = NULL; return !runSat(); } // restore implementation inline bool DlSatTester :: backJumpedRestore ( void ) { // if empty clash dep-set -- concept is unsatisfiable if ( getClashSet().empty () ) return true; // some non-deterministic choices were done restore ( getClashSet().level() ); return false; } inline bool DlSatTester :: straightforwardRestore ( void ) { if ( noBranchingOps() ) // no non-deterministic choices was made return true; // ... the concept is unsatisfiable else { // restoring the state restore (); return false; } } inline bool DlSatTester :: tunedRestore ( void ) { if ( tBox.useBackjumping ) return backJumpedRestore (); else return straightforwardRestore (); } inline bool DlSatTester :: commonTacticBodyAll ( const DLVertex& cur ) { #ifdef ENABLE_CHECKING fpp_assert ( isPositive(curConcept.bp()) && cur.Type() == dtForall ); #endif if ( unlikely(cur.getRole()->isTop()) ) { incStat(nAllCalls); return addSessionGCI ( cur.getC(), curConcept.getDep() ); } // can't skip singleton models for complex roles due to empty transitions if ( cur.getRole()->isSimple() ) return commonTacticBodyAllSimple(cur); else return commonTacticBodyAllComplex(cur); } //----------------------------------------------------------------------------- //-- implemenation of reasoner-related parts of TBox //----------------------------------------------------------------------------- inline bool TBox::TSimpleRule :: applicable ( DlSatTester& Reasoner ) const { return Reasoner.applicable(*this); } inline const modelCacheInterface* TBox :: initCache ( const TConcept* pConcept, bool sub ) { BipolarPointer bp = sub ? inverse(pConcept->pName) : pConcept->pName; const modelCacheInterface* cache = DLHeap.getCache(bp); if ( cache == NULL ) { if ( sub ) prepareFeatures ( NULL, pConcept ); else prepareFeatures ( pConcept, NULL ); cache = getReasoner()->createCache(bp); clearFeatures(); } return cache; } /// test if 2 concept non-subsumption can be determined by cache merging inline enum modelCacheState TBox :: testCachedNonSubsumption ( const TConcept* p, const TConcept* q ) { const modelCacheInterface* pCache = initCache ( p, /*sub=*/false ); const modelCacheInterface* nCache = initCache ( q, /*sub=*/true ); return pCache->canMerge(nCache); } #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/cppi.h0000644000000000000000000000346512112642405016470 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2010 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef CPPI_H #define CPPI_H /* * Console percent progress indicator */ #include #include #include "ProgressIndicatorInterface.h" class CPPI: public ProgressIndicatorInterface { protected: // members /// previous and current numbers shown unsigned int oldPercent, curPercent; protected: // methods /// initial exposition virtual void initExposure ( void ) { std::cerr << " 0%"; } /// expose current value virtual void expose ( void ) { curPercent = (unsigned int)(((float)uCurrent/uLimit)*100); // don't do anything if figure doesn't change if ( curPercent != oldPercent ) { std::cerr << "\b\b\b\b\b" << std::setw(4) << curPercent << '%'; oldPercent = curPercent; } } public: // interface /// empty c'tor CPPI ( void ) : ProgressIndicatorInterface() , oldPercent(0) , curPercent(0) {} /// init c'tor CPPI ( unsigned long limit ) : ProgressIndicatorInterface(limit) , oldPercent(0) , curPercent(0) {} /// empty d'tor virtual ~CPPI ( void ) {} }; // CPPI #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/ConceptWithDep.h0000644000000000000000000000527612112642405020417 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2012 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef CONCEPTWITHDEP_H #define CONCEPTWITHDEP_H #include "BiPointer.h" #include "DepSet.h" /// Concept with dependence: bipolar pointer to concept and a set of dependences class ConceptWDep { protected: // members /// "pointer" to a concept in DAG BipolarPointer Concept; /// dep-set for a concept DepSet depSet; public: // methods /// empty c'tor ConceptWDep ( void ) : Concept (bpINVALID) {} /// c'tor with empty dep-set explicit ConceptWDep ( BipolarPointer p ) : Concept(p) {} /// usual c'tor ConceptWDep ( BipolarPointer p, const DepSet& dep ) : Concept(p), depSet(dep) {} /// copy c'tor ConceptWDep ( const ConceptWDep& c ) : Concept(c.Concept), depSet(c.depSet) {} /// copy c'tor with additional dep-set ConceptWDep ( const ConceptWDep& c, const DepSet& dep ) : Concept(c.Concept), depSet(c.depSet) { depSet.add(dep); } // comparison bool operator == ( const ConceptWDep& ce ) const { return Concept == ce.Concept; } bool operator != ( const ConceptWDep& ce ) const { return Concept != ce.Concept; } bool operator == ( BipolarPointer p ) const { return Concept == p; } bool operator != ( BipolarPointer p ) const { return Concept != p; } // access to elements /// get bp-part BipolarPointer bp ( void ) const { return Concept; } /// get dep-set part const DepSet& getDep ( void ) const { return depSet; } /// create CWD with inversed body and the same dep-set ConceptWDep inverse ( void ) const { return ConceptWDep ( ::inverse(Concept), getDep () ); } /// add dep-set to a CWD void addDep ( const DepSet& d ) { depSet.add(d); } /// print concept and a dep-set template friend O& operator << ( O& o, const ConceptWDep& c ) { o << c.Concept << c.getDep(); return o; } }; // ConceptWDep /// create an inverse of a given CWD with the same dep-set inline ConceptWDep inverse ( const ConceptWDep& C ) { return ConceptWDep ( inverse(C.bp()), C.getDep() ); } #endif // CONCEPTWITHDEP_H FaCTpp-src-v1.6.2~dfsg/src/Kernel/taxVertex.h0000644000000000000000000002023312112642405017517 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2013 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef TAXVERTEX_H #define TAXVERTEX_H #include #include #include #include #include "taxNamEntry.h" #include "tLabeller.h" class TaxonomyVertex { protected: // typedefs /// vertex vector for links to parents and children typedef std::vector TaxVertexLink; /// vector of entries for synonyms typedef std::vector EqualNames; public: // typedefs // accessors type /// RW iterator for the neighbours typedef TaxVertexLink::iterator iterator; /// RO iterator for the neighbours typedef TaxVertexLink::const_iterator const_iterator; /// RO iterator for the synonyms typedef EqualNames::const_iterator syn_iterator; private: // members /// immediate parents and children TaxVertexLink Links[2]; protected: // members /// entry corresponding to current tax vertex const ClassifiableEntry* sample; /// synonyms of the sample entry EqualNames synonyms; // labels for different purposes. all for 2 directions: top-down and bottom-up search /// flag if given vertex was checked; connected with checkLab TLabeller::LabelType theChecked; /// flag if given vertex has value; connected with valuedLab TLabeller::LabelType theValued; /// number of common parents of a node unsigned int common; /// satisfiability value of a valued vertex bool checkValue; /// flag to check whether the vertex is in use bool inUse; protected: // methods /// indirect RW access to Links TaxVertexLink& neigh ( bool upDirection ) { return Links[!upDirection]; } /// indirect RO access to Links const TaxVertexLink& neigh ( bool upDirection ) const { return Links[!upDirection]; } /// print entry name and its synonyms (if any) void printSynonyms ( std::ostream& o ) const; /// print neighbours of a vertex in given direction void printNeighbours ( std::ostream& o, bool upDirection ) const; public: // flags interface // checked part bool isChecked ( const TLabeller& checkLab ) const { return checkLab.isLabelled(theChecked); } void setChecked ( const TLabeller& checkLab ) { checkLab.set(theChecked); } // value part bool isValued ( const TLabeller& valueLab ) const { return valueLab.isLabelled(theValued); } bool getValue ( void ) const { return checkValue; } bool setValued ( bool val, const TLabeller& valueLab ) { valueLab.set(theValued); checkValue = val; return val; } // common part bool isCommon ( void ) const { return common != 0; } void setCommon ( void ) { ++common; } void clearCommon ( void ) { common = 0; } /// keep COMMON flag iff both flags are set; @return true if it is the case bool correctCommon ( unsigned int n ) { if ( common == n ) return true; clearCommon(); return false; } /// put initial values on the flags void initFlags ( void ) { TLabeller::clear(theChecked); TLabeller::clear(theValued); clearCommon(); } // get info about taxonomy structure syn_iterator begin_syn ( void ) const { return synonyms.begin(); } syn_iterator end_syn ( void ) const { return synonyms.end(); } /// mark vertex as the one corresponding to a given ENTRY void setVertexAsHost ( const ClassifiableEntry* entry ) { const_cast(entry)->setTaxVertex(this); } /// set sample to ENTRY void setSample ( const ClassifiableEntry* entry, bool linkBack = true ) { sample = entry; if ( likely(linkBack) ) setVertexAsHost(entry); } public: /// empty c'tor TaxonomyVertex ( void ) : sample(NULL) , inUse(true) { initFlags(); } /// init c'tor; use it only for Top/Bot initialisations TaxonomyVertex ( const ClassifiableEntry* p ) : inUse(true) { setSample(p); initFlags(); } /// copy c'tor TaxonomyVertex ( const TaxonomyVertex& v ) : sample(v.sample) , synonyms(v.synonyms) , theChecked(v.theChecked) , theValued(v.theValued) , common(v.common) , checkValue(v.checkValue) , inUse(v.inUse) { Links[0] = v.Links[0]; Links[1] = v.Links[1]; } /// assignment operator TaxonomyVertex& operator = ( const TaxonomyVertex& v ) { Links[0] = v.Links[0]; Links[1] = v.Links[1]; sample = v.sample; synonyms = v.synonyms; theChecked = v.theChecked; theValued = v.theValued; common = v.common; checkValue = v.checkValue; inUse = v.inUse; return *this; } /// empty d'tor ~TaxonomyVertex ( void ) {} /// add P as a synonym to curent vertex void addSynonym ( const ClassifiableEntry* p ) { synonyms.push_back(p); setVertexAsHost(p); } /// clears the vertex void clear ( void ) { Links[0].clear(); Links[1].clear(); sample = NULL; initFlags(); } /// get RO access to the primer const ClassifiableEntry* getPrimer ( void ) const { return sample; } /// add link in given direction to vertex void addNeighbour ( bool upDirection, TaxonomyVertex* p ) { neigh(upDirection).push_back(p); } /// check if vertex has no neighbours in given direction bool noNeighbours ( bool upDirection ) const { return neigh(upDirection).empty(); } // iterator access to parents/children iterator begin ( bool upDirection ) { return neigh(upDirection).begin(); } iterator end ( bool upDirection ) { return neigh(upDirection).end(); } const_iterator begin ( bool upDirection ) const { return neigh(upDirection).begin(); } const_iterator end ( bool upDirection ) const { return neigh(upDirection).end(); } /** Adds vertex to existing graph. For every Up, Down such that (Up->Down) creates couple of links (Up->this), (this->Down). Don't work with synonyms!!! */ void incorporate ( void ); /// @return v if node represents a synonym (v=Up[i]==Down[j]); @return NULL otherwise TaxonomyVertex* getSynonymNode ( void ) { // try to find Vertex such that Vertex\in Up and Vertex\in Down for ( iterator q = begin(true), q_end = end(true); q != q_end; ++q ) for ( iterator r = begin(false), r_end = end(false); r != r_end; ++r ) if ( *q == *r ) // found such vertex return *q; return NULL; } /// Remove link to P from neighbours (given by flag). @return true if such link was removed bool removeLink ( bool upDirection, TaxonomyVertex* p ); /// clear all links in a given direction void clearLinks ( bool upDirection ) { neigh(upDirection).clear(); } /// merge NODE which is independent to THIS void mergeIndepNode ( TaxonomyVertex* node, const std::set& excludes, const ClassifiableEntry* curEntry ); // usage methods /// @return true iff the node is in use bool isInUse ( void ) const { return inUse; } /// set the inUse value of the node void setInUse ( bool value ) { inUse = value; } // output methods /// print taxonomy vertex in format void print ( std::ostream& o ) const { printSynonyms(o); printNeighbours ( o, true ); printNeighbours ( o, false ); o << "\n"; } // save/load interface; implementation is in SaveLoad.cpp /// save label of the entry void SaveLabel ( std::ostream& o ) const; /// load label of the entry void LoadLabel ( std::istream& i ); /// save neighbours of the entry void SaveNeighbours ( std::ostream& o ) const; /// load neighbours of the entry void LoadNeighbours ( std::istream& i ); }; // TaxonomyVertex /// structure to sort tax vertices struct TaxVertexLess { bool operator()(const TaxonomyVertex* s1, const TaxonomyVertex* s2) const { return strcmp(s1->getPrimer()->getName(), s2->getPrimer()->getName()) < 0; } }; /// sorted vertices set typedef std::set TVSet; #endif // TAXVERTEX_H FaCTpp-src-v1.6.2~dfsg/src/Kernel/tSetAsTree.h0000644000000000000000000000605712112642405017560 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2011 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef TSETASTREE_H #define TSETASTREE_H #include // implement model cache set as a tree-set class TSetAsTree { protected: // types /// base type typedef std::set BaseType; protected: // members /// set implementation BaseType Base; /// maximal number of elements unsigned int nElems; public: // interface /// empty c'tor taking max possible number of elements in the set explicit TSetAsTree ( unsigned int size ) : nElems(size) {} /// copy c'tor TSetAsTree ( const TSetAsTree& is ) : Base(is.Base) {} /// assignment TSetAsTree& operator= ( const TSetAsTree& is ) { Base = is.Base; return *this; } /// empty d'tor ~TSetAsTree ( void ) {} /// adds given index to the set void insert ( unsigned int i ) { # ifdef ENABLE_CHECKING fpp_assert ( i > 0 ); # endif Base.insert(i); } /// completes the set with [1,n) void completeSet ( void ) { for ( unsigned int i = 1; i < nElems; ++i ) Base.insert(i); } /// adds the given set to the current one TSetAsTree& operator |= ( const TSetAsTree& is ) { Base.insert ( is.Base.begin(), is.Base.end() ); return *this; } /// clear the set void clear ( void ) { Base.clear(); } /// check whether the set is empty bool empty ( void ) const { return Base.empty(); } /// check whether I contains in the set bool contains ( unsigned int i ) const { return Base.find(i) != Base.end(); } /// check whether the intersection between the current set and IS is nonempty bool intersects ( const TSetAsTree& is ) const { if ( Base.empty() || is.Base.empty() ) return false; BaseType::const_iterator p1 = Base.begin(), p1_end = Base.end(), p2 = is.Base.begin(), p2_end = is.Base.end(); while ( p1 != p1_end && p2 != p2_end ) if ( *p1 == *p2 ) return true; else if ( *p1 < *p2 ) ++p1; else ++p2; return false; } /// prints the set in a human-readable form void print ( std::ostream& o ) const { o << "{"; if ( !empty() ) { BaseType::const_iterator p = Base.begin(), p_end = Base.end(); o << *p; while ( ++p != p_end ) o << ',' << *p; } o << "}"; } typedef BaseType::const_iterator const_iterator; const_iterator begin ( void ) const { return Base.begin(); } const_iterator end ( void ) const { return Base.end(); } }; // TSetAsTree #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/dlTBox.cpp0000644000000000000000000004240112112642405017255 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2012 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "dlTBox.h" #include #include "dltree.h" #include "cppi.h" #include "globaldef.h" #include "ReasonerNom.h" #include "DLConceptTaxonomy.h" #include "procTimer.h" #include "dumpLisp.h" #include "logging.h" // uncomment the following line to print currently checking subsumption //#define FPP_DEBUG_PRINT_CURRENT_SUBSUMPTION TBox :: TBox ( const ifOptionSet* Options, const std::string& TopORoleName, const std::string& BotORoleName, const std::string& TopDRoleName, const std::string& BotDRoleName ) : DLHeap(Options) , stdReasoner(NULL) , nomReasoner(NULL) , pMonitor(NULL) , pTax(NULL) , pOptions (Options) , Status(kbLoading) , curFeature(NULL) , pQuery(NULL) , Concepts("concept") , Individuals("individual") , ORM ( /*data=*/false, TopORoleName, BotORoleName ) , DRM ( /*data=*/true, TopDRoleName, BotDRoleName ) , Axioms(*this) , Splits(NULL) , T_G(bpTOP) // initialise GCA's concept with Top , nC(0) , nR(0) , auxConceptID(0) , testTimeout(0) , useNodeCache(true) , duringClassification(false) , useSortedReasoning(true) , isLikeGALEN(false) // just in case Relevance part would be omited , isLikeWINE(false) , Consistent(true) , preprocTime(0) , consistTime(0) { readConfig ( Options ); initTopBottom (); setForbidUndefinedNames(false); } TBox :: ~TBox ( void ) { // remove all RELATED structures for ( RelatedCollection::iterator p = RelatedI.begin(), p_end = RelatedI.end(); p < p_end; ++p ) delete *p; // remove all simple rules for ( TSimpleRules::iterator q = SimpleRules.begin(), q_end = SimpleRules.end(); q < q_end; ++q ) delete *q; // empty R-C cache for ( TRCCache::iterator r = RCCache.begin(), r_end = RCCache.end(); r < r_end; ++r ) deleteTree(r->first); // remove all concepts delete pTop; delete pBottom; delete pTemp; delete pQuery; // remove aux structures delete stdReasoner; delete nomReasoner; delete pTax; } /// get unique aux concept TConcept* TBox :: getAuxConcept ( DLTree* desc ) { std::stringstream name; name << " aux" << ++auxConceptID; bool old = setForbidUndefinedNames(false); TConcept* C = getConcept(name.str()); setForbidUndefinedNames(old); C->setSystem(); C->setNonClassifiable(); C->setPrimitive(); C->Description = desc; C->initToldSubsumers(); // it is created after this is done centrally return C; } /// replace (AR:C) with X such that C [= AR^-:X for fresh X. @return X TConcept* TBox :: replaceForall ( DLTree* RC ) { // check whether we already did this before for given R,C TConcept* X = getRCCache(RC); if ( X != NULL ) { deleteTree(RC); return X; } // see R and C at the first time X = getAuxConcept(); DLTree* C = createSNFNot(clone(RC->Right())); // create ax axiom C [= AR^-.X addSubsumeAxiom ( C, createSNFForall ( createInverse(clone(RC->Left())), getTree(X) ) ); // save cache for R,C setRCCache ( RC, X ); return X; } void TBox :: initTopBottom ( void ) { // create BOTTOM concept TConcept* p = new TConcept ("BOTTOM"); p->setBottom(); p->setId(-1); p->pName = p->pBody = bpBOTTOM; pBottom = p; // create TOP concept p = new TConcept ("TOP"); p->setTop(); p->setId(-1); p->pName = p->pBody = bpTOP; p->tsDepth=1; p->classTag = cttTrueCompletelyDefined; pTop = p; // "fresh" concept p = new TConcept (" "); p->setId(-1); p->tsDepth=1; p->classTag = cttTrueCompletelyDefined; pTemp = p; // query concept p = new TConcept("FaCT++.default"); p->setSystem(); pQuery = p; } void TBox :: prepareReasoning ( void ) { // do the preprocessing Preprocess(); // init reasoner (if not exist) initReasoner(); // check if it is necessary to dump relevant part TBox if ( dumpQuery ) { // set up relevance info markAllRelevant(); std::ofstream of ( "tbox" ); fpp_assert ( of.good() ); dumpLisp lDump(of); dump(&lDump); clearRelevanceInfo(); } // init values for SAT tests -- either cache, or consistency check DLHeap.setSatOrder(); } /// prepare features for SAT(P), or SUB(P,Q) test void TBox :: prepareFeatures ( const TConcept* pConcept, const TConcept* qConcept ) { auxFeatures = GCIFeatures; if ( pConcept != NULL ) updateAuxFeatures(pConcept->posFeatures); if ( qConcept != NULL ) updateAuxFeatures(qConcept->negFeatures); if ( auxFeatures.hasSingletons() ) updateAuxFeatures(NCFeatures); curFeature = &auxFeatures; // set blocking method for the current reasoning session getReasoner()->setBlockingMethod ( isIRinQuery(), isNRinQuery() ); } void TBox :: buildSimpleCache ( void ) { // set cache for BOTTOM entry initConstCache(bpBOTTOM); // set all the caches for the temp concept initSingletonCache ( pTemp, /*pos=*/true ); initSingletonCache ( pTemp, /*pos=*/false ); // inapplicable if KB contains CGIs in any form if ( GCIs.isGCI() || GCIs.isReflexive() ) return; // it is now safe to make a TOP cache initConstCache(bpTOP); for ( c_const_iterator c = c_begin(), cend = c_end(); c < cend; ++c ) if ( (*c)->isPrimitive() ) initSingletonCache ( (*c), /*pos=*/false ); for ( i_const_iterator i = i_begin(), iend = i_end(); i < iend; ++i ) if ( (*i)->isPrimitive() ) initSingletonCache ( (*i), /*pos=*/false ); } /// check if the ontology is consistent bool TBox :: performConsistencyCheck ( void ) { if ( verboseOutput ) std::cerr << "Consistency checking..."; TsProcTimer pt; pt.Start(); buildSimpleCache(); TConcept* test = ( NCFeatures.hasSingletons() ? *i_begin() : NULL ); prepareFeatures ( test, NULL ); // DlSatTester* Reasoner = getReasoner(); bool ret = false; if ( test ) { // make a cache for TOP if it is not there if ( DLHeap.getCache(bpTOP) == NULL ) initConstCache(bpTOP); ret = static_cast(nomReasoner)->consistentNominalCloud(); } else ret = isSatisfiable(pTop); // setup cache for GCI if ( GCIs.isGCI() ) { // there is no much win to have it together with special-domains-as-GCIs ATM. // DLHeap.setCache ( T_G, Reasoner->buildCacheByCGraph(ret) ); DLHeap.setCache ( inverse(T_G), new modelCacheConst(/*sat=*/false) ); } pt.Stop(); consistTime = pt; if ( verboseOutput ) std::cerr << " done in " << pt << " seconds\n"; return ret; } bool TBox :: isSatisfiable ( const TConcept* pConcept ) { fpp_assert ( pConcept != NULL ); // check whether we already does the test const modelCacheInterface* cache = DLHeap.getCache(pConcept->pName); if ( cache != NULL ) return ( cache->getState() != csInvalid ); // logging the startpoint if ( LLM.isWritable(llBegSat) ) LL << "\n--------------------------------------------\n" "Checking satisfiability of '" << pConcept->getName() << "':"; if ( LLM.isWritable(llGTA) ) LL << "\n"; // perform reasoning with a proper logical features prepareFeatures ( pConcept, NULL ); bool result = getReasoner()->runSat ( pConcept->resolveId(), bpTOP ); // save cache DLHeap.setCache ( pConcept->pName, getReasoner()->buildCacheByCGraph(result) ); clearFeatures(); CHECK_LL_RETURN_VALUE(llSatResult,result); #if 1 LL << "\n"; // usual checking -- time is extra info #else LL << " "; // time tests -- time is necessary info #endif LL << "The '" << pConcept->getName() << "' concept is "; if ( !result ) LL << "un"; LL << "satisfiable w.r.t. TBox"; return result; } bool TBox :: isSubHolds ( const TConcept* pConcept, const TConcept* qConcept ) { fpp_assert ( pConcept != NULL && qConcept != NULL ); #ifdef FPP_DEBUG_PRINT_CURRENT_SUBSUMPTION std::cerr << "Checking '" << pConcept->getName() << "' [= '" << qConcept->getName() << "'..."; #endif // logging the startpoint if ( LLM.isWritable(llBegSat) ) LL << "\n--------------------------------------------\nChecking subsumption '" << pConcept->getName() << " [= " << qConcept->getName() << "':"; if ( LLM.isWritable(llGTA) ) LL << "\n"; // perform reasoning with a proper logical features prepareFeatures ( pConcept, qConcept ); bool result = !getReasoner()->runSat ( pConcept->resolveId(), inverse(qConcept->resolveId()) ); clearFeatures(); #ifdef FPP_DEBUG_PRINT_CURRENT_SUBSUMPTION std::cerr << " done\n"; #endif CHECK_LL_RETURN_VALUE(llSatResult,result); #if 1 LL << "\n"; // usual checking -- time is extra info #else LL << " "; // time tests -- time is necessary info #endif LL << "The '" << pConcept->getName() << " [= " << qConcept->getName() << "' subsumption"; if (!result) LL << " NOT"; LL << " holds w.r.t. TBox"; return result; } /// check that 2 individuals are the same bool TBox :: isSameIndividuals ( const TIndividual* a, const TIndividual* b ) { a = resolveSynonym(a); b = resolveSynonym(b); if ( a == b ) // known synonyms return true; if ( !isIndividual(a) || !isIndividual(b) ) throw EFaCTPlusPlus("Individuals are expected in the isSameIndividuals() query"); if ( a->node == NULL || b->node == NULL ) // fresh individuals couldn't be the same return false; return a->getTaxVertex() == b->getTaxVertex(); } /// check if 2 roles are disjoint bool TBox :: isDisjointRoles ( const TRole* R, const TRole* S ) { fpp_assert ( R != NULL && S != NULL ); // object roles are disjoint with data roles if ( R->isDataRole() != S->isDataRole() ) return true; // prepare feature that are KB features // FIXME!! overkill, but fine for now as it is sound curFeature = &KBFeatures; getReasoner()->setBlockingMethod ( isIRinQuery(), isNRinQuery() ); bool result = getReasoner()->checkDisjointRoles ( R, S ); clearFeatures(); return result; } /// check if the role R is irreflexive bool TBox :: isIrreflexive ( const TRole* R ) { fpp_assert ( R != NULL ); // data roles are irreflexive if ( R->isDataRole() ) return true; // prepare feature that are KB features // FIXME!! overkill, but fine for now as it is sound curFeature = &KBFeatures; getReasoner()->setBlockingMethod ( isIRinQuery(), isNRinQuery() ); bool result = getReasoner()->checkIrreflexivity(R); clearFeatures(); return result; } // load init values from config file void TBox :: readConfig ( const ifOptionSet* Options ) { fpp_assert ( Options != NULL ); // safety check // define a macro for registering boolean option # define addBoolOption(name) \ name = Options->getBool ( #name ); \ if ( LLM.isWritable(llAlways) ) \ LL << "Init " #name " = " << name << "\n" // TBox options addBoolOption(useCompletelyDefined); addBoolOption(useRelevantOnly); addBoolOption(dumpQuery); addBoolOption(alwaysPreferEquals); addBoolOption(useSpecialDomains); // reasoner's options addBoolOption(useSemanticBranching); addBoolOption(useBackjumping); addBoolOption(useLazyBlocking); addBoolOption(useAnywhereBlocking); if ( Axioms.initAbsorptionFlags(Options->getText("absorptionFlags")) ) throw EFaCTPlusPlus ( "Incorrect absorption flags given" ); testTimeout = Options->getInt("testTimeout"); if ( LLM.isWritable(llAlways) ) LL << "Init testTimeout = " << testTimeout << "\n"; PriorityMatrix.initPriorities ( Options->getText("IAOEFLG"), "IAOEFLG" ); #ifdef RKG_USE_FAIRNESS nSkipBeforeBlock = Options->getInt("skipBeforeBlock"); if ( LLM.isWritable(llAlways) ) LL << "Init nSkipBeforeBlock = " << nSkipBeforeBlock << "\n"; #else nSkipBeforeBlock = 0; #endif verboseOutput = false; #undef addBoolOption } /// create (and DAG-ify) query concept via its definition TConcept* TBox :: createQueryConcept ( const DLTree* desc ) { fpp_assert ( desc != NULL ); // make sure that an old query is gone clearQueryConcept(); // create description // std::cerr << "Create new temp concept with description =" << desc << "\n"; deleteTree ( makeNonPrimitive ( pQuery, clone(desc) ) ); pQuery->setIndex(nC-1); return pQuery; } /// preprocess query concept: put description into DAG void TBox :: preprocessQueryConcept ( TConcept* query ) { // build DAG entries for the default concept addConceptToHeap(query); // gather statistics about the concept setConceptRelevant(query); // DEBUG_ONLY: print the DAG info // std::ofstream debugPrint ( defConceptName, std::ios::app|std::ios::out ); // Print (debugPrint); // debugPrint << std::endl; // check satisfiability of the concept initCache(query); } /// classify query concept void TBox :: classifyQueryConcept ( void ) { // prepare told subsumers for classification; as it is non-primitive, it is not CD pQuery->initToldSubsumers(); // setup taxonomy behaviour flags fpp_assert ( pTax != NULL ); pTax->setCompletelyDefined(false); // non-primitive concept // classify the concept pTax->classifyEntry(pQuery); } /// knowledge exploration: build a model and return a link to the root const DlCompletionTree* TBox :: buildCompletionTree ( const TConcept* pConcept ) { const DlCompletionTree* ret = NULL; // perform reasoning with a proper logical features prepareFeatures ( pConcept, NULL ); // turn off caching of CT nodes during reasoning setUseNodeCache(false); // do the SAT test, save the CT if satisfiable if ( getReasoner()->runSat ( pConcept->resolveId() ) ) ret = getReasoner()->getRootNode(); // turn on caching of CT nodes during reasoning setUseNodeCache(true); clearFeatures(); return ret; } /// dump QUERY processing time, reasoning statistics and a (preprocessed) TBox void TBox :: writeReasoningResult ( std::ostream& o, float time ) const { if ( nomReasoner ) { o << "Query processing reasoning statistic: Nominals"; nomReasoner->writeTotalStatistic(o); } o << "Query processing reasoning statistic: Standard"; stdReasoner->writeTotalStatistic(o); // we know here whether KB is consistent fpp_assert ( getStatus() >= kbCChecked ); if ( Consistent ) o << "Required"; else o << "KB is inconsistent. Query is NOT processed\nConsistency"; float sum = preprocTime + consistTime; o << " check done in " << time << " seconds\nof which:\nPreproc. takes " << preprocTime << " seconds\nConsist. takes " << consistTime << " seconds"; if ( nomReasoner ) { o << "\nReasoning NOM:"; sum += nomReasoner->printReasoningTime(o); } o << "\nReasoning STD:"; sum += stdReasoner->printReasoningTime(o); o << "\nThe rest takes "; // determine and normalize the rest float f = time - sum; if ( f < 0 ) f = 0; f = ((unsigned long)(f*100))/100.f; o << f << " seconds\n"; Print(o); } void TBox :: PrintDagEntry ( std::ostream& o, BipolarPointer p ) const { fpp_assert ( isValid (p) ); // primitive ones -- check first if ( p == bpTOP ) { o << " *TOP*"; return; } else if ( p == bpBOTTOM ) { o << " *BOTTOM*"; return; } // checks inversion if ( isNegative(p) ) { o << " (not"; PrintDagEntry ( o, inverse(p) ); o << ")"; return; } const DLVertex& v = DLHeap [getValue(p)]; switch ( v.Type() ) { case dtTop: o << " *TOP*"; return; case dtName: case dtDataType: case dtDataValue: o << ' ' << v.getConcept()->getName(); return; case dtDataExpr: o << ' ' << *getDataEntryByBP(p)->getFacet(); return; case dtIrr: o << " (" << v.getTagName() << ' ' << v.getRole()->getName() << ")"; return; case dtAnd: case dtSplitConcept: o << " (" << v.getTagName(); for ( DLVertex::const_iterator q = v.begin(); q != v.end(); ++q ) PrintDagEntry ( o, *q ); o << ")"; return; case dtForall: case dtLE: o << " (" << v.getTagName(); if ( v.Type() == dtLE ) o << ' ' << v.getNumberLE(); o << ' ' << v.getRole()->getName(); PrintDagEntry ( o, v.getC() ); o << ")"; return; case dtProj: o << " (" << v.getTagName() << ' ' << v.getRole()->getName() << ' '; PrintDagEntry ( o, v.getC() ); o << " => " << v.getProjRole()->getName() << ")"; return; case dtNN: // shouldn't appears in the expressions case dtChoose: fpp_unreachable(); default: // invalid value std::cerr << "Error printing vertex of type " << v.getTagName() << "(" << v.Type () << ")"; fpp_unreachable(); return; } } void TBox :: PrintConcept ( std::ostream& o, const TConcept* p ) const { // print only relevant concepts if ( isValid(p->pName) ) { o << getCTTagName(p->getClassTag()); if ( p->isSingleton() ) o << (p->isNominal() ? 'o' : '!'); o << '.' << p->getName() << " [" << p->tsDepth << "] " << (p->isNonPrimitive() ? "=" : "[="); if ( isValid (p->pBody) ) PrintDagEntry ( o, p->pBody ); // if you want to check correctness of translation (print following info) // you should comment out RemoveExtraDescription() in TBox::Preprocess() // but check hasSynonym assignment if ( p->Description != NULL ) o << (p->isNonPrimitive() ? "\n-=" : "\n-[=") << p->Description; o << "\n"; } } void TBox :: printFeatures ( void ) const { KBFeatures.writeState(); if ( LLM.isWritable(llAlways) ) LL << "KB contains " << (GCIs.isGCI() ? "" : "NO ") << "GCIs\nKB contains " << (GCIs.isReflexive() ? "" : "NO ") << "reflexive roles\nKB contains " << (GCIs.isRnD() ? "" : "NO ") << "range and domain restrictions\n"; } FaCTpp-src-v1.6.2~dfsg/src/Kernel/procTimer.h0000644000000000000000000000544712112642405017503 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2008 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef _PROCTIMER_H #define _PROCTIMER_H #include /** * Class TsProcTimer definition & implementation * * Useful for calculating processor time intervals up to 10^-3 sec * * Copyright (C) by Tsarkov Dmitry, 2003 * */ class TsProcTimer { private: // members /// save the starting time of the timer clock_t startTime; /// calculated time between Start() and Stop() calls float resultTime; /// flag to show timer is started bool Started; private: // methods /// get time interval between startTime and current time float calcDelta ( void ) const; public: // interface /// the only c'tor TsProcTimer ( void ) : startTime(0), resultTime(0.0), Started(false) {} /// empty d'tor ~TsProcTimer ( void ) {} /// reset timer void Reset ( void ); /// record current time void Start ( void ); /// save time interval from starting point to current moment void Stop ( void ); /// get time interval operator float ( void ) const; }; // TsProcTimer /** * TsTimer implementation */ inline void TsProcTimer :: Reset ( void ) { Started = false; resultTime = 0; } inline float TsProcTimer :: calcDelta ( void ) const { clock_t finishTime = clock(); // calculate difference between cuttent time and start time float realProcTime = float(finishTime>startTime ? finishTime-startTime : ((clock_t)-1)-startTime+finishTime ) / CLOCKS_PER_SEC; // correct times less than a millisecond if ( realProcTime < 1e-3 ) realProcTime = 0; return realProcTime; } inline TsProcTimer :: operator float ( void ) const { const unsigned int norm = 100; // normalisation constant float realProcTime; if ( Started ) realProcTime = calcDelta(); else realProcTime = resultTime; // normalise value up to CONST return ((unsigned long)(realProcTime*norm))/(float)norm; } inline void TsProcTimer :: Start ( void ) { if ( !Started ) { startTime = clock(); Started = true; } } inline void TsProcTimer :: Stop ( void ) { if ( Started ) { Started = false; resultTime += calcDelta (); } } #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/tDag2Interface.cpp0000644000000000000000000000504012112642405020641 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2011-2012 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "tDag2Interface.h" /// build concept expression by a vertex V const TDLConceptExpression* TDag2Interface :: buildCExpr ( const DLVertex& v ) { switch ( v.Type() ) { case dtTop: return Manager->Top(); case dtNConcept: case dtPConcept: return CName(v.getConcept()); case dtPSingleton: case dtNSingleton: return Manager->OneOf(IName(v.getConcept())); case dtAnd: { Manager->newArgList(); for ( DLVertex::const_iterator p = v.begin(), p_end = v.end(); p != p_end; ++p ) Manager->addArg(getCExpr(*p)); return Manager->And(); } case dtForall: if ( v.getRole()->isDataRole() ) return Manager->Forall ( DRName(v.getRole()), getDExpr(v.getC()) ); else return Manager->Forall ( ORName(v.getRole()), getCExpr(v.getC()) ); case dtLE: if ( v.getRole()->isDataRole() ) return Manager->MaxCardinality ( v.getNumberLE(), DRName(v.getRole()), getDExpr(v.getC()) ); else return Manager->MaxCardinality ( v.getNumberLE(), ORName(v.getRole()), getCExpr(v.getC()) ); case dtIrr: return Manager->Not(Manager->SelfReference(ORName(v.getRole()))); case dtProj: case dtNN: case dtChoose: case dtSplitConcept: // these are artificial constructions and shouldn't be visible return Manager->Top(); default: fpp_unreachable(); } } /// build data expression by a vertex V const TDLDataExpression* TDag2Interface :: buildDExpr ( const DLVertex& v ) { switch ( v.Type() ) { case dtTop: return Manager->DataTop(); case dtDataType: case dtDataValue: case dtDataExpr: // TODO: no data stuff yet return Manager->DataTop(); case dtAnd: { Manager->newArgList(); for ( DLVertex::const_iterator p = v.begin(), p_end = v.end(); p != p_end; ++p ) Manager->addArg(getDExpr(*p)); return Manager->DataAnd(); } default: fpp_unreachable(); } } FaCTpp-src-v1.6.2~dfsg/src/Kernel/LogicFeature.cpp0000644000000000000000000000565012112642405020437 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2011 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "LogicFeature.h" #include "logging.h" #include "dlVertex.h" #include "tConcept.h" #include "tRole.h" void LogicFeatures :: fillConceptData ( const TConcept* p ) { if ( p->isSingleton() ) setX(lfSingleton); } void LogicFeatures :: fillRoleData ( const TRole* p, bool both ) { if ( unlikely(p->isTop()) ) { if ( !p->isDataRole() ) setX(lfTopRole); return; } if ( p->getId() > 0 ) // direct role setX(lfDirectRoles); else setX(lfInverseRoles); // inverse roles check if ( both ) setX(lfBothRoles); // transitivity check if ( p->isTransitive() ) setX(lfTransitiveRoles); // subsumption check if ( p->hasToldSubsumers() ) setX(lfRolesSubsumption); // functionality check if ( p->isFunctional() ) setX(lfFunctionalRoles); // R&D check if ( p->getBPDomain() != bpTOP || p->getBPRange() != bpTOP ) setX(lfRangeAndDomain); } void LogicFeatures :: fillDAGData ( const DLVertex& v, bool pos ATTR_UNUSED ) { switch ( v.Type () ) { case dtForall: setX(lfSomeConstructor); break; case dtLE: setX(lfNConstructor); if ( v.getC() != bpTOP ) setX(lfQConstructor); break; case dtPSingleton: case dtNSingleton: setX(lfSingleton); break; case dtIrr: setX(lfSelfRef); break; default: // any other vertex -- nothing to do break; } } void LogicFeatures :: writeState ( void ) const { CHECK_LL_RETURN(llAlways); LL << "\nLoaded KB used DL with following features:\nKB contains "; if ( !hasInverseRole () ) LL << "NO "; LL << "inverse role(s)\nKB contains "; if ( !hasRoleHierarchy () ) LL << "NO "; LL << "role hierarchy\nKB contains "; if ( !hasTransitiveRole () ) LL << "NO "; LL << "transitive role(s)\nKB contains "; if ( !hasTopRole () ) LL << "NO "; LL << "top role expressions\nKB contains "; if ( !hasSomeAll () ) LL << "NO "; LL << "quanitifier(s)\nKB contains "; if ( !hasFunctionalRestriction () ) LL << "NO "; LL << "functional restriction(s)\nKB contains "; if ( !hasNumberRestriction () ) LL << "NO "; else if ( hasQNumberRestriction () ) LL << "qualified "; LL << "number restriction(s)\nKB contains "; if ( !hasSingletons() ) LL << "NO "; LL << "nominal(s)\n"; } FaCTpp-src-v1.6.2~dfsg/src/Kernel/tOntologyLoader.h0000644000000000000000000003417412112642405020663 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2012 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef TONTOLOGYLOADER_H #define TONTOLOGYLOADER_H #include "tOntology.h" #include "tExpressionTranslator.h" #include "dlTBox.h" class TOntologyLoader: public DLAxiomVisitor { protected: // members /// KB to load the ontology TBox& kb; /// Transforms TDLExpression hierarchy to the DLTree* TExpressionTranslator ETrans; /// temporary vector for arguments of TBox n-ary axioms std::vector ArgList; protected: // methods /// get DLTree corresponding to an expression EXPR DLTree* e ( const TDLExpression* expr ) { expr->accept(ETrans); return ETrans; } /// get role by the DLTree; throw exception if unable TRole* getRole ( const TDLRoleExpression* r, const char* reason ) { try { return resolveRole(TreeDeleter(e(r))); } catch ( const EFaCTPlusPlus& e ) { throw EFaCTPlusPlus(reason); } } /// get an individual be the DLTree; throw exception if unable TIndividual* getIndividual ( const TDLIndividualExpression* I, const char* reason ) { try { TreeDeleter i = e(I); if ( i == NULL ) throw EFaCTPlusPlus(reason); return static_cast(kb.getCI(i)); } catch(...) { throw EFaCTPlusPlus(reason); } } /// ensure that the expression EXPR has its named entities linked to the KB ones void ensureNames ( const TDLExpression* Expr ) { fpp_assert ( Expr != NULL ); // FORNOW } /// prepare arguments for the [begin,end) interval template void prepareArgList ( Iterator begin, Iterator end ) { ArgList.clear(); for ( ; begin != end; ++begin ) { ensureNames(*begin); ArgList.push_back(e(*begin)); } } void fillSplit ( TSplitVar* sv ) { sv->C = kb.getConcept(sv->oldName->getName()); sv->C->setNonClassifiable(); for ( TSplitVar::iterator p = sv->begin(), p_end = sv->end(); p != p_end; ++p ) { TConcept* C = kb.getConcept(p->name->getName()); C->setSystem(); p->C = C; } } public: // visitor interface virtual void visit ( const TDLAxiomDeclaration& axiom ) { ensureNames(axiom.getDeclaration()); TreeDeleter(e(axiom.getDeclaration())); // register names in the KB } // n-ary axioms virtual void visit ( const TDLAxiomEquivalentConcepts& axiom ) { prepareArgList(axiom.begin(),axiom.end()); kb.processEquivalentC(ArgList.begin(),ArgList.end()); } virtual void visit ( const TDLAxiomDisjointConcepts& axiom ) { prepareArgList(axiom.begin(),axiom.end()); kb.processDisjointC(ArgList.begin(),ArgList.end()); } virtual void visit ( const TDLAxiomDisjointUnion& axiom ) { // first make a disjoint axiom prepareArgList(axiom.begin(),axiom.end()); kb.processDisjointC(ArgList.begin(),ArgList.end()); // now define C as a union-of axiom ArgList.clear(); ensureNames(axiom.getC()); ArgList.push_back(e(axiom.getC())); DLTree* acc = createBottom(); for ( TDLAxiomDisjointUnion::iterator p = axiom.begin(), p_end = axiom.end(); p != p_end; ++p ) acc = createSNFOr ( acc, e(*p) ); ArgList.push_back(acc); kb.processEquivalentC(ArgList.begin(),ArgList.end()); } virtual void visit ( const TDLAxiomEquivalentORoles& axiom ) { prepareArgList(axiom.begin(),axiom.end()); kb.processEquivalentR(ArgList.begin(),ArgList.end()); } virtual void visit ( const TDLAxiomEquivalentDRoles& axiom ) { prepareArgList(axiom.begin(),axiom.end()); kb.processEquivalentR(ArgList.begin(),ArgList.end()); } virtual void visit ( const TDLAxiomDisjointORoles& axiom ) { prepareArgList(axiom.begin(),axiom.end()); kb.processDisjointR(ArgList.begin(),ArgList.end()); } virtual void visit ( const TDLAxiomDisjointDRoles& axiom ) { prepareArgList(axiom.begin(),axiom.end()); kb.processDisjointR(ArgList.begin(),ArgList.end()); } virtual void visit ( const TDLAxiomSameIndividuals& axiom ) { prepareArgList(axiom.begin(),axiom.end()); kb.processSame(ArgList.begin(),ArgList.end()); } virtual void visit ( const TDLAxiomDifferentIndividuals& axiom ) { prepareArgList(axiom.begin(),axiom.end()); kb.processDifferent(ArgList.begin(),ArgList.end()); } virtual void visit ( const TDLAxiomFairnessConstraint& axiom ) { prepareArgList(axiom.begin(),axiom.end()); kb.setFairnessConstraint(ArgList.begin(),ArgList.end()); } // role axioms virtual void visit ( const TDLAxiomRoleInverse& axiom ) { ensureNames(axiom.getRole()); ensureNames(axiom.getInvRole()); TRole* R = getRole ( axiom.getRole(), "Role expression expected in Role Inverse axiom" ); TRole* iR = getRole ( axiom.getInvRole(), "Role expression expected in Role Inverse axiom" ); kb.getRM(R)->addRoleSynonym ( iR->inverse(), R ); } virtual void visit ( const TDLAxiomORoleSubsumption& axiom ) { ensureNames(axiom.getRole()); ensureNames(axiom.getSubRole()); DLTree* Sub = e(axiom.getSubRole()); TRole* R = getRole ( axiom.getRole(), "Role expression expected in Object Roles Subsumption axiom" ); kb.getRM(R)->addRoleParent ( Sub, R ); } virtual void visit ( const TDLAxiomDRoleSubsumption& axiom ) { ensureNames(axiom.getRole()); ensureNames(axiom.getSubRole()); TRole* R = getRole ( axiom.getRole(), "Role expression expected in Data Roles Subsumption axiom" ); TRole* S = getRole ( axiom.getSubRole(), "Role expression expected in Data Roles Subsumption axiom" ); kb.getDRM()->addRoleParent ( S, R ); } virtual void visit ( const TDLAxiomORoleDomain& axiom ) { ensureNames(axiom.getRole()); ensureNames(axiom.getDomain()); TRole* R = getRole ( axiom.getRole(), "Role expression expected in Object Role Domain axiom" ); DLTree* C = e(axiom.getDomain()); if ( unlikely(R->isTop()) ) // add GCI kb.addSubsumeAxiom ( createTop(), C ); else if ( likely(!R->isBottom()) ) // nothing to do for bottom R->setDomain(C); } virtual void visit ( const TDLAxiomDRoleDomain& axiom ) { ensureNames(axiom.getRole()); ensureNames(axiom.getDomain()); TRole* R = getRole ( axiom.getRole(), "Role expression expected in Data Role Domain axiom" ); DLTree* C = e(axiom.getDomain()); if ( unlikely(R->isTop()) ) // add GCI kb.addSubsumeAxiom ( createTop(), C ); else if ( likely(!R->isBottom()) ) // nothing to do for bottom R->setDomain(C); } virtual void visit ( const TDLAxiomORoleRange& axiom ) { ensureNames(axiom.getRole()); ensureNames(axiom.getRange()); TRole* R = getRole ( axiom.getRole(), "Role expression expected in Object Role Range axiom" ); DLTree* C = e(axiom.getRange()); if ( unlikely(R->isTop()) ) // add GCI kb.addSubsumeAxiom ( createTop(), C ); else if ( likely(!R->isBottom()) ) // nothing to do for bottom R->setRange(C); } virtual void visit ( const TDLAxiomDRoleRange& axiom ) { ensureNames(axiom.getRole()); ensureNames(axiom.getRange()); getRole ( axiom.getRole(), "Role expression expected in Data Role Range axiom" )->setRange(e(axiom.getRange())); } virtual void visit ( const TDLAxiomRoleTransitive& axiom ) { ensureNames(axiom.getRole()); TRole* R = getRole ( axiom.getRole(), "Role expression expected in Role Transitivity axiom" ); if ( !R->isTop() && !R->isBottom() ) // top/bottom roles are always transitive R->setTransitive(); } virtual void visit ( const TDLAxiomRoleReflexive& axiom ) { ensureNames(axiom.getRole()); TRole* R = getRole ( axiom.getRole(), "Role expression expected in Role Reflexivity axiom" ); if ( R->isBottom() ) // empty role can't be reflexive throw EFPPInconsistentKB(); if ( !R->isTop() ) // universal role always reflexive R->setReflexive(true); } virtual void visit ( const TDLAxiomRoleIrreflexive& axiom ) { ensureNames(axiom.getRole()); TRole* R = getRole ( axiom.getRole(), "Role expression expected in Role Irreflexivity axiom" ); if ( R->isTop() ) // KB became inconsistent throw EFPPInconsistentKB(); if ( !R->isBottom() ) // empty role already irreflexive { R->setDomain(createSNFNot(createSNFSelf(e(axiom.getRole())))); R->setIrreflexive(true); } } virtual void visit ( const TDLAxiomRoleSymmetric& axiom ) { ensureNames(axiom.getRole()); TRole* R = getRole ( axiom.getRole(), "Role expression expected in Role Symmetry axiom" ); if ( !R->isTop() && !R->isBottom() ) // both are symmetric { R->setSymmetric(true); kb.getORM()->addRoleParent ( R, R->inverse() ); } } virtual void visit ( const TDLAxiomRoleAsymmetric& axiom ) { ensureNames(axiom.getRole()); TRole* R = getRole ( axiom.getRole(), "Role expression expected in Role Asymmetry axiom" ); if ( R->isTop() ) // KB became inconsistent throw EFPPInconsistentKB(); if ( !R->isBottom() ) { R->setAsymmetric(true); kb.getORM()->addDisjointRoles ( R, R->inverse() ); } } virtual void visit ( const TDLAxiomORoleFunctional& axiom ) { ensureNames(axiom.getRole()); TRole* R = getRole ( axiom.getRole(), "Role expression expected in Object Role Functionality axiom" ); if ( R->isTop() ) // NOTE!! not really the case (1-point models are fine here), but OWL 2 forbid this throw EFPPInconsistentKB(); if ( !R->isBottom() ) R->setFunctional(); } virtual void visit ( const TDLAxiomDRoleFunctional& axiom ) { ensureNames(axiom.getRole()); TRole* R = getRole ( axiom.getRole(), "Role expression expected in Data Role Functionality axiom" ); if ( R->isTop() ) // KB became inconsistent throw EFPPInconsistentKB(); if ( !R->isBottom() ) R->setFunctional(); } virtual void visit ( const TDLAxiomRoleInverseFunctional& axiom ) { ensureNames(axiom.getRole()); TRole* R = getRole ( axiom.getRole(), "Role expression expected in Role Inverse Functionality axiom" ); if ( R->isTop() ) // NOTE!! not really the case (1-point models are fine here), but OWL 2 forbid this throw EFPPInconsistentKB(); if ( !R->isBottom() ) R->inverse()->setFunctional(); } // concept/individual axioms virtual void visit ( const TDLAxiomConceptInclusion& axiom ) { ensureNames(axiom.getSubC()); ensureNames(axiom.getSupC()); DLTree* C = e(axiom.getSubC()); DLTree* D = e(axiom.getSupC()); kb.addSubsumeAxiom ( C, D ); } virtual void visit ( const TDLAxiomInstanceOf& axiom ) { ensureNames(axiom.getIndividual()); ensureNames(axiom.getC()); getIndividual ( axiom.getIndividual(), "Individual expected in Instance axiom" ); DLTree* I = e(axiom.getIndividual()); DLTree* C = e(axiom.getC()); kb.addSubsumeAxiom ( I, C ); } virtual void visit ( const TDLAxiomRelatedTo& axiom ) { ensureNames(axiom.getIndividual()); ensureNames(axiom.getRelation()); ensureNames(axiom.getRelatedIndividual()); TRole* R = getRole ( axiom.getRelation(), "Role expression expected in Related To axiom" ); if ( R->isBottom() ) throw EFPPInconsistentKB(); if ( !R->isTop() ) // nothing to do for universal role { TIndividual* I = getIndividual ( axiom.getIndividual(), "Individual expected in Related To axiom" ); TIndividual* J = getIndividual ( axiom.getRelatedIndividual(), "Individual expected in Related To axiom" ); kb.RegisterIndividualRelation ( I, R, J ); } } virtual void visit ( const TDLAxiomRelatedToNot& axiom ) { ensureNames(axiom.getIndividual()); ensureNames(axiom.getRelation()); ensureNames(axiom.getRelatedIndividual()); TRole* R = getRole ( axiom.getRelation(), "Role expression expected in Related To Not axiom" ); if ( R->isTop() ) // inconsistent ontology throw EFPPInconsistentKB(); // make sure everything is consistent getIndividual ( axiom.getIndividual(), "Individual expected in Related To Not axiom" ), getIndividual ( axiom.getRelatedIndividual(), "Individual expected in Related To Not axiom" ); if ( !R->isBottom() ) // nothing to do kb.addSubsumeAxiom ( // make an axiom i:AR.\neg{j} e(axiom.getIndividual()), createSNFForall ( e(axiom.getRelation()), createSNFNot(e(axiom.getRelatedIndividual())) ) ); } virtual void visit ( const TDLAxiomValueOf& axiom ) { ensureNames(axiom.getIndividual()); ensureNames(axiom.getAttribute()); getIndividual ( axiom.getIndividual(), "Individual expected in Value Of axiom" ); // FIXME!! think about ensuring the value TRole* R = getRole ( axiom.getAttribute(), "Role expression expected in Value Of axiom" ); if ( R->isBottom() ) throw EFPPInconsistentKB(); if ( !R->isTop() ) // nothing to do for universal role kb.addSubsumeAxiom ( // make an axiom i:EA.V e(axiom.getIndividual()), createSNFExists ( e(axiom.getAttribute()), e(axiom.getValue())) ); } virtual void visit ( const TDLAxiomValueOfNot& axiom ) { ensureNames(axiom.getIndividual()); ensureNames(axiom.getAttribute()); getIndividual ( axiom.getIndividual(), "Individual expected in Value Of Not axiom" ); // FIXME!! think about ensuring the value TRole* R = getRole ( axiom.getAttribute(), "Role expression expected in Value Of Not axiom" ); if ( R->isTop() ) throw EFPPInconsistentKB(); if ( !R->isBottom() ) // nothing to do for empty role kb.addSubsumeAxiom ( // make an axiom i:AA.\neg V e(axiom.getIndividual()), createSNFForall ( e(axiom.getAttribute()), createSNFNot(e(axiom.getValue()))) ); } public: // interface /// init c'tor TOntologyLoader ( TBox& KB ) : kb(KB), ETrans(KB) {} /// empty d'tor virtual ~TOntologyLoader ( void ) {} /// load ontology to a given KB virtual void visitOntology ( TOntology& ontology ) { for ( TOntology::iterator p = ontology.begin(), p_end = ontology.end(); p < p_end; ++p ) if ( (*p)->isUsed() ) (*p)->accept(*this); for ( TSplitVars::iterator q = ontology.Splits.begin(), q_end = ontology.Splits.end(); q != q_end; ++q ) fillSplit(*q); kb.setSplitVars(&ontology.Splits); kb.finishLoading(); } }; // TOntologyLoader #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/Blocking.cpp0000644000000000000000000002615212112642405017616 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2011 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "dlDag.h" #include "dlCompletionGraph.h" #include "Reasoner.h" #include "logging.h" #ifdef USE_BLOCKING_STATISTICS // statistic for calling blocking unsigned long tries[6], fails[6], nSucc, failedRule; void printBlockingStat1 ( std::ostream& o ) { if ( *tries == 0 ) // nothing to inform return; // else -- print precize statistics o << "\nThere were made " << *tries << " blocking tests of which " << nSucc << " successfull.\nBlocking rules failure statistic:"; for ( int i = 0; i < 6; ++i ) { if ( i != 0 ) o << ","; o << " " << fails[i] << "/" << tries[i]; } } void clearBlockingStat1 ( void ) { for ( int i = 5; i >= 0; --i ) tries[i] = fails[i] = 0; nSucc = failedRule = 0; } #endif // universal Blocked-By method bool DlCompletionGraph :: isBlockedBy ( const DlCompletionTree* node, const DlCompletionTree* blocker ) const { fpp_assert ( !node->isNominalNode() ); fpp_assert ( !blocker->isNominalNode() ); // blocked node can't be blocked itself if ( blocker->isBlocked() ) return false; // easy check: Init is not in the label if a blocker if ( !blocker->canBlockInit(node) ) return false; bool ret; if ( sessionHasInverseRoles ) // subset blocking { const DLDag& dag = pReasoner->getDAG(); if ( sessionHasNumberRestrictions ) // I+F -- optimised blocking ret = node->isBlockedBy_SHIQ ( dag, blocker ); else // just I -- equality blocking ret = node->isBlockedBy_SHI ( dag, blocker ); } else ret = node->isBlockedBy_SH(blocker); #ifdef USE_BLOCKING_STATISTICS if ( ret ) ++nSucc; else if ( LLM.isWritable(llGTA) ) LL << " fb" << failedRule << "(" << node->getId() << "," << blocker->getId() << ")"; #endif return ret; } // Blocked-by implementation bool DlCompletionTree :: isCommonlyBlockedBy ( const DLDag& dag, const DlCompletionTree* p ) const { // common B1: if ( !B1(p) ) return false; for ( const_label_iterator q = p->beginl_cc(), q_end = p->endl_cc(); q < q_end; ++q ) { BipolarPointer bp = q->bp(); const DLVertex& v = dag[bp]; if ( v.Type() == dtForall && isPositive(bp) ) { // (all S C) \in L(w') if ( !B2 ( v, bp ) ) return false; } } return true; } bool DlCompletionTree :: isABlockedBy ( const DLDag& dag, const DlCompletionTree* p ) const { // current = w; p = w'; parent = v #ifdef ENABLE_CHECKING fpp_assert ( hasParent() ); // there exists v #endif // B3,B4 for ( const_label_iterator q = p->beginl_cc(), q_end = p->endl_cc(); q < q_end; ++q ) { BipolarPointer bp = q->bp(); const DLVertex& v = dag[bp]; if ( v.Type() == dtForall && isNegative(bp) ) { // (some T E) \in L(w') if ( !B4 ( p, 1, v.getRole(), inverse(v.getC()) ) ) return false; } else if ( v.Type() == dtLE ) { if ( isPositive(bp) ) { // (<= n S C) \in L(w') if ( !B3 ( p, v.getNumberLE(), v.getRole(), v.getC() ) ) return false; } else { // (>= m T E) \in L(w') if ( !B4 ( p, v.getNumberGE(), v.getRole(), v.getC() ) ) return false; } } } // all other is OK -- done; return true; } bool DlCompletionTree :: isCBlockedBy ( const DLDag& dag, const DlCompletionTree* p ) const { // current = w; p = w'; parent = v #ifdef ENABLE_CHECKING fpp_assert ( hasParent() ); // there exists v #endif // B5 const_label_iterator q, q_end; for ( q = p->beginl_cc(), q_end = p->endl_cc(); q < q_end; ++q ) { BipolarPointer bp = q->bp(); const DLVertex& v = dag[bp]; if ( v.Type() == dtLE && isPositive(bp) ) { // (<= n T E) \in L(w') if ( !B5 ( v.getRole(), v.getC() ) ) return false; } } // B6 const DlCompletionTree* par = getParentNode(); for ( q = par->beginl_cc(), q_end = par->endl_cc(); q < q_end; ++q ) { BipolarPointer bp = q->bp(); const DLVertex& v = dag[bp]; if ( v.Type() == dtLE && isNegative(bp) ) { // (>= m U F) \in L(v) if ( !B6 ( v.getRole(), v.getC() ) ) return false; } } return true; } //---------------------------------------------------------------------- //-- B1 to B6 conditions implementation //-- WARNING!! 19-06-2005. All blockable nodes has the only parent //-- (with probably several links to it). So we should check all of them //---------------------------------------------------------------------- #ifdef USE_BLOCKING_STATISTICS # define TRY_B(i) ++tries[i-1] # define FAIL_B(i) failedRule = i, ++fails[i-1] #else # define TRY_B(i) (void)NULL # define FAIL_B(i) (void)NULL #endif /// check if B1 holds for a given vertex (p is a candidate for blocker) bool DlCompletionTree :: B1 ( const DlCompletionTree* p ) const { TRY_B(1); if ( Label <= p->Label ) return true; FAIL_B(1); return false; } bool DlCompletionTree :: B2Simple ( const RAStateTransitions& RST, BipolarPointer C ) const { const DlCompletionTree* parent = getParentNode(); const CGLabel& parLab = parent->label(); TRY_B(2); for ( const_edge_iterator p = begin(), p_end = end(); p < p_end; ++p ) if ( !(*p)->isIBlocked() && (*p)->getArcEnd() == parent && RST.recognise((*p)->getRole()) ) { if ( !parLab.contains(C) ) { FAIL_B(2); return false; } else return true; } return true; } bool DlCompletionTree :: B2Complex ( const RAStateTransitions& RST, BipolarPointer C ) const { const DlCompletionTree* parent = getParentNode(); const CGLabel& parLab = parent->label(); RAStateTransitions::const_iterator q, q_end = RST.end(); TRY_B(2); for ( const_edge_iterator p = begin(), p_end = end(); p < p_end; ++p ) { if ( (*p)->isIBlocked() || (*p)->getArcEnd() != parent ) continue; const TRole* R = (*p)->getRole(); if ( !RST.recognise(R) ) continue; for ( q = RST.begin(); q != q_end; ++q ) if ( (*q)->applicable(R) ) if ( !parLab.containsCC(C+(*q)->final()) ) { FAIL_B(2); return false; } } return true; } /// check if B3 holds for (<= n S.C)\in w' (p is a candidate for blocker) bool DlCompletionTree :: B3 ( const DlCompletionTree* p, unsigned int n, const TRole* S, BipolarPointer C ) const { #ifdef ENABLE_CHECKING fpp_assert ( hasParent() ); // safety check #endif TRY_B(3); bool ret; // if (<= n S C) \in L(w') then // a) w is an inv(S)-succ of v or if ( !isParentArcLabelled(S) ) ret = true; // b) w is an inv(S) succ of v and ~C\in L(v) or else if ( getParentNode()->isLabelledBy(inverse(C)) ) ret = true; // c) w is an inv(S) succ of v and C\in L(v)... else if ( !getParentNode()->isLabelledBy(C) ) ret = false; else { // ...and <=n-1 S-succ. z with C\in L(z) register unsigned int m = 0; for ( const_edge_iterator q = p->begin(), q_end = p->end(); q < q_end; ++q ) if ( (*q)->isSuccEdge() && (*q)->isNeighbour(S) && (*q)->getArcEnd()->isLabelledBy(C) ) ++m; ret = ( m < n ); } if ( !ret ) FAIL_B(3); return ret; } /// check if B4 holds for (>= m T.E)\in w' (p is a candidate for blocker) bool DlCompletionTree :: B4 ( const DlCompletionTree* p, unsigned int m, const TRole* T, BipolarPointer E ) const { #ifdef ENABLE_CHECKING fpp_assert ( hasParent() ); // safety check #endif TRY_B(4); // if (>= m T E) \in L(w') then // b) w is an inv(T) succ of v and E\in L(v) and m == 1 or if ( isParentArcLabelled(T) && m == 1 && getParentNode()->isLabelledBy(E) ) return true; // a) w' has at least m T-succ z with E\in L(z) // check all sons register unsigned int n = 0; for ( const_edge_iterator q = p->begin(), q_end = p->end(); q < q_end; ++q ) if ( (*q)->isSuccEdge() && (*q)->isNeighbour(T) && (*q)->getArcEnd()->isLabelledBy(E) ) if ( ++n >= m ) // check if node has enough successors return true; // rule check fails FAIL_B(4); return false; } /// check if B5 holds for (<= n T.E)\in w' bool DlCompletionTree :: B5 ( const TRole* T, BipolarPointer E ) const { #ifdef ENABLE_CHECKING fpp_assert ( hasParent() ); // safety check #endif TRY_B(5); // if (<= n T E) \in L(w'), then // either w is not an inv(T)-successor of v... if ( !isParentArcLabelled(T) ) return true; // or ~E \in L(v) if ( getParentNode()->isLabelledBy ( inverse(E) ) ) return true; FAIL_B(5); return false; } /// check if B6 holds for (>= m U.F)\in v bool DlCompletionTree :: B6 ( const TRole* U, BipolarPointer F ) const { #ifdef ENABLE_CHECKING fpp_assert ( hasParent() ); // safety check #endif TRY_B(6); // if (>= m U F) \in L(v), and // w is U-successor of v... if ( !isParentArcLabelled(U->inverse()) ) return true; // then ~F\in L(w) if ( isLabelledBy ( inverse(F) ) ) return true; FAIL_B(6); return false; } #undef TRY_B #undef FAIL_B //---------------------------------------------------------------------- //-- changing blocked status //---------------------------------------------------------------------- void DlCompletionGraph :: detectBlockedStatus ( DlCompletionTree* node ) { DlCompletionTree* p = node; bool wasBlocked = node->isBlocked(); bool wasDBlocked = node->isDBlocked(); // if we are here, then node *need* to be checked // so this is to prevent from going out of the loop node->setAffected(); while ( p->hasParent() && p->isBlockableNode() && p->isAffected() ) { findDBlocker(p); if ( p->isBlocked() ) return; p = p->getParentNode(); } p->clearAffected(); if ( wasBlocked && !node->isBlocked() ) unblockNode ( node, wasDBlocked ); } void DlCompletionGraph :: unblockNode ( DlCompletionTree* node, bool wasDBlocked ) { if ( node->isPBlocked() || !node->isBlockableNode() ) return; if ( !wasDBlocked ) // if it was DBlocked -- findDBlocker() made it saveRareCond(node->setUBlocked()); pReasoner->repeatUnblockedNode(node,wasDBlocked); unblockNodeChildren(node); } void DlCompletionGraph :: findDAncestorBlocker ( DlCompletionTree* node ) { register const DlCompletionTree* p = node; #ifdef RKG_USE_FAIRNESS if ( nSkipBeforeBlock ) for ( int n = nSkipBeforeBlock-1; n >= 0 && p->hasParent() && p->isBlockableNode(); --n ) p = p->getParentNode(); #endif while ( p->hasParent() ) { p = p->getParentNode(); if ( !p->isBlockableNode() ) return; if ( isBlockedBy ( node, p ) ) { setNodeDBlocked ( node, p ); return; } } } void DlCompletionGraph :: findDAnywhereBlocker ( DlCompletionTree* node ) { for ( const_iterator q = begin(), q_end = end(); q < q_end && *q != node; ++q ) { const DlCompletionTree* p = *q; // node was merge to smth with the larger ID or is cached or blocked itself if ( p->isBlocked() || p->isPBlocked() || p->isNominalNode() || p->isCached() ) continue; if ( isBlockedBy ( node, p ) ) { setNodeDBlocked ( node, p ); return; } } } FaCTpp-src-v1.6.2~dfsg/src/Kernel/BiPointer.h0000644000000000000000000000315012112642405017417 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2004 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef _BIPOINTER_H #define _BIPOINTER_H typedef int BipolarPointer; inline BipolarPointer createBiPointer ( int index, bool pos ) { return (pos ? index : -index); } inline bool isCorrect ( BipolarPointer p ) { return (p!=0); } inline bool isValid ( BipolarPointer p ) { return (p!=0); } inline bool isPositive ( BipolarPointer p ) { return (p>0); } inline bool isNegative ( BipolarPointer p ) { return (p<0); } inline unsigned int getValue ( BipolarPointer p ) { return (p>0?p:-p); } inline BipolarPointer inverse ( BipolarPointer p ) { return -p; } inline BipolarPointer getPositive ( BipolarPointer p ) { return (p>0?p:-p); } inline BipolarPointer getNegative ( BipolarPointer p ) { return (p<0?p:-p); } const BipolarPointer bpINVALID = 0; const BipolarPointer bpTOP = 1; const BipolarPointer bpBOTTOM = -1; #endif // _BIPOINTER_H FaCTpp-src-v1.6.2~dfsg/src/Kernel/taxVertex.cpp0000644000000000000000000001031312112642405020050 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2013 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /*******************************************************\ |* Implementation of taxonomy vertex class *| \*******************************************************/ #include "taxVertex.h" #include "logging.h" // removes given pointer from neigh. bool TaxonomyVertex :: removeLink ( bool upDirection, TaxonomyVertex* p ) { // for all neighbours of current vertex... for ( iterator q = begin(upDirection), q_end = end(upDirection); q < q_end; ++q ) if ( *q == p ) // if given neighbour found... { *q = neigh(upDirection).back(); neigh(upDirection).pop_back(); // remove last entry (by resizing) return true; // there is at most one link for each node } return false; // no such link } void TaxonomyVertex :: incorporate ( void ) { // setup links iterator u, u_end = end(/*upDirection=*/true), d, d_end = end(/*upDirection=*/false); // correct links on lower concepts... for ( d = begin(/*upDirection=*/false); d != d_end; ++d ) { // remove all down links for ( u = begin(/*upDirection=*/true); u != u_end; ++u ) if ( (*d)->removeLink ( /*upDirection=*/true, *u ) ) (*u)->removeLink ( /*upDirection=*/false, *d ); // add new link between v and current (*d)->addNeighbour (/*upDirection=*/true, this); } // add new link between v and current for ( u = begin(/*upDirection=*/true); u != u_end; ++u ) (*u)->addNeighbour ( /*upDirection=*/false, this ); CHECK_LL_RETURN(llTaxInsert); LL << "\nTAX:inserting '" << getPrimer()->getName() << "' with up = {"; u = begin(/*upDirection=*/true); if ( u != u_end ) { LL << (*u)->getPrimer()->getName(); for ( ++u; u != u_end; ++u ) LL << "," << (*u)->getPrimer()->getName(); } LL << "} and down = {"; d = begin(/*upDirection=*/false); if ( d != d_end ) { LL << (*d)->getPrimer()->getName(); for ( ++d; d != d_end; ++d ) LL << "," << (*d)->getPrimer()->getName(); } LL << "}"; } /// merge NODE which is independent to THIS void TaxonomyVertex :: mergeIndepNode ( TaxonomyVertex* node, const std::set& excludes, const ClassifiableEntry* curEntry ) { // copy synonyms here if ( node->getPrimer() != curEntry ) addSynonym(node->getPrimer()); for ( syn_iterator q = node->begin_syn(), q_end = node->end_syn(); q != q_end; ++q ) addSynonym(*q); bool upDirection = true; iterator p, p_end; for ( p = node->begin(upDirection), p_end = node->end(upDirection); p != p_end; ++p ) { if ( excludes.count(*p) == 0 ) addNeighbour ( upDirection, *p ); (*p)->removeLink ( !upDirection, node ); } upDirection = false; for ( p = node->begin(upDirection), p_end = node->end(upDirection); p != p_end; ++p ) { if ( excludes.count(*p) == 0 ) addNeighbour ( upDirection, *p ); (*p)->removeLink ( !upDirection, node ); } } void TaxonomyVertex :: printSynonyms ( std::ostream& o ) const { fpp_assert ( sample != NULL ); if ( likely(synonyms.empty()) ) o << '"' << getPrimer()->getName() << '"'; else { o << "(\"" << getPrimer()->getName(); for ( syn_iterator q = begin_syn(), q_end = end_syn(); q < q_end; ++q ) o << "\"=\"" << (*q)->getName(); o << "\")"; } } void TaxonomyVertex :: printNeighbours ( std::ostream& o, bool upDirection ) const { // write number of elements o << " {" << neigh(upDirection).size() << ":"; TVSet sorted ( begin(upDirection), end(upDirection) ); for ( TVSet::const_iterator p = sorted.begin(), p_end = sorted.end(); p != p_end; ++p ) o << " \"" << (*p)->getPrimer()->getName() << '"'; o << "}"; } FaCTpp-src-v1.6.2~dfsg/src/Kernel/ELFExpressionChecker.h0000644000000000000000000001267512112642405021513 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2011 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef ELFEXPRESSIONCHECKER_H #define ELFEXPRESSIONCHECKER_H #include "tDLExpression.h" class ELFExpressionChecker: public DLExpressionVisitor { protected: // members bool value; public: /// get DLTree corresponding to an expression EXPR bool v ( const TDLExpression* expr ) { expr->accept(*this); return value; } // concept expressions virtual void visit ( const TDLConceptTop& expr ATTR_UNUSED ) { value = true; } virtual void visit ( const TDLConceptBottom& expr ATTR_UNUSED ) { value = true; } virtual void visit ( const TDLConceptName& expr ATTR_UNUSED ) { value = true; } virtual void visit ( const TDLConceptNot& expr ATTR_UNUSED ) { value = false; } virtual void visit ( const TDLConceptAnd& expr ) { value = false; for ( TDLConceptAnd::iterator p = expr.begin(), p_end = expr.end(); p != p_end; ++p ) if ( !v(*p) ) return; value = true; } virtual void visit ( const TDLConceptOr& expr ATTR_UNUSED ) { value = false; } virtual void visit ( const TDLConceptOneOf& expr ATTR_UNUSED ) { value = false; } virtual void visit ( const TDLConceptObjectSelf& expr ATTR_UNUSED ) { value = false; } virtual void visit ( const TDLConceptObjectValue& expr ATTR_UNUSED ) { value = false; } virtual void visit ( const TDLConceptObjectExists& expr ) { value = false; // check role if ( !v(expr.getOR()) ) return; // check concept v(expr.getC()); } virtual void visit ( const TDLConceptObjectForall& expr ATTR_UNUSED ) { value = false; } virtual void visit ( const TDLConceptObjectMinCardinality& expr ATTR_UNUSED ) { value = false; } virtual void visit ( const TDLConceptObjectMaxCardinality& expr ATTR_UNUSED ) { value = false; } virtual void visit ( const TDLConceptObjectExactCardinality& expr ATTR_UNUSED ) { value = false; } virtual void visit ( const TDLConceptDataValue& expr ATTR_UNUSED ) { value = false; } virtual void visit ( const TDLConceptDataExists& expr ATTR_UNUSED ) { value = false; } virtual void visit ( const TDLConceptDataForall& expr ATTR_UNUSED ) { value = false; } virtual void visit ( const TDLConceptDataMinCardinality& expr ATTR_UNUSED ) { value = false; } virtual void visit ( const TDLConceptDataMaxCardinality& expr ATTR_UNUSED ) { value = false; } virtual void visit ( const TDLConceptDataExactCardinality& expr ATTR_UNUSED ) { value = false; } // individual expressions virtual void visit ( const TDLIndividualName& expr ATTR_UNUSED ) { value = false; } // object role expressions virtual void visit ( const TDLObjectRoleTop& expr ATTR_UNUSED ) { value = false; } virtual void visit ( const TDLObjectRoleBottom& expr ATTR_UNUSED ) { value = false; } virtual void visit ( const TDLObjectRoleName& expr ATTR_UNUSED ) { value = true; } virtual void visit ( const TDLObjectRoleInverse& expr ATTR_UNUSED ) { value = false; } virtual void visit ( const TDLObjectRoleChain& expr ) { value = false; for ( TDLObjectRoleChain::iterator p = expr.begin(), p_end = expr.end(); p != p_end; ++p ) if ( !v(*p) ) return; value = true; } virtual void visit ( const TDLObjectRoleProjectionFrom& expr ATTR_UNUSED ) { value = false; } virtual void visit ( const TDLObjectRoleProjectionInto& expr ATTR_UNUSED ) { value = false; } // data role expressions virtual void visit ( const TDLDataRoleTop& expr ATTR_UNUSED ) { value = false; } virtual void visit ( const TDLDataRoleBottom& expr ATTR_UNUSED ) { value = false; } virtual void visit ( const TDLDataRoleName& expr ATTR_UNUSED ) { value = false; } // data expressions virtual void visit ( const TDLDataTop& expr ATTR_UNUSED ) { value = false; } virtual void visit ( const TDLDataBottom& expr ATTR_UNUSED ) { value = false; } virtual void visit ( const TDLDataTypeName& expr ATTR_UNUSED ) { value = false; } virtual void visit ( const TDLDataTypeRestriction& expr ATTR_UNUSED ) { value = false; } virtual void visit ( const TDLDataValue& expr ATTR_UNUSED ) { value = false; } virtual void visit ( const TDLDataNot& expr ATTR_UNUSED ) { value = false; } virtual void visit ( const TDLDataAnd& expr ATTR_UNUSED ) { value = false; } virtual void visit ( const TDLDataOr& expr ATTR_UNUSED ) { value = false; } virtual void visit ( const TDLDataOneOf& expr ATTR_UNUSED ) { value = false; } // facets virtual void visit ( const TDLFacetMinInclusive& expr ATTR_UNUSED ) { value = false; } virtual void visit ( const TDLFacetMinExclusive& expr ATTR_UNUSED ) { value = false; } virtual void visit ( const TDLFacetMaxInclusive& expr ATTR_UNUSED ) { value = false; } virtual void visit ( const TDLFacetMaxExclusive& expr ATTR_UNUSED ) { value = false; } // other methods virtual ~ELFExpressionChecker ( void ) {} /// get (single) access to the tree operator bool ( void ) const { return value; } }; #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/dlCompletionTree.h0000644000000000000000000005456512112642405021015 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2012 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef DLCOMPLETIONTREE_H #define DLCOMPLETIONTREE_H #include #include #include "globaldef.h" #include "dlCompletionTreeArc.h" #include "tSaveList.h" #include "tRestorer.h" #include "CGLabel.h" #include "logging.h" class DLDag; class DlCompletionGraph; // use the following to control logging information about saving/restoring nodes #define RKG_CHECK_BACKJUMPING //#include "SmallObj.h" #ifdef _USE_LOGGING // don't gather statistics w/o logging # define USE_BLOCKING_STATISTICS #endif #ifdef USE_BLOCKING_STATISTICS extern void printBlockingStat1 ( std::ostream& o ); extern void clearBlockingStat1 ( void ); # define printBlockingStat(O) printBlockingStat1(O) # define clearBlockingStat() clearBlockingStat1() #else # define printBlockingStat(O) (void)NULL # define clearBlockingStat() (void)NULL #endif /// level of CTree's nominal node typedef unsigned short CTNominalLevel; /// default level for the Blockable node const CTNominalLevel BlockableLevel = static_cast(-1); class DlCompletionTree//: public Loki::SmallObject<> { friend class DlCompletionGraph; protected: // internal classes /// class for saving Completion Tree nodes state class SaveState { public: // members /// saving status of the label CGLabel::SaveState lab; /// curLevel of the Node structure unsigned int curLevel; /// amount of neighbours unsigned int nNeighbours; private: // protection from copying /// no assignment SaveState& operator = ( const SaveState& node ); public: // interface /// empty c'tor SaveState ( void ) {} /// copy c'tor SaveState ( const SaveState& node ) : lab (node.lab) , curLevel (node.curLevel) , nNeighbours(node.nNeighbours) {} /// empty d'tor virtual ~SaveState ( void ) {} // used in SaveList => virtual /// get level of a saved node unsigned int level ( void ) const { return curLevel; } }; // SaveState /// restore blocked node class UnBlock: public TRestorer { protected: DlCompletionTree* p; const DlCompletionTree* Blocker; DepSet dep; bool pBlocked, dBlocked; public: UnBlock ( DlCompletionTree* q ) : p(q), Blocker(q->Blocker), dep(q->pDep), pBlocked(q->pBlocked), dBlocked(q->dBlocked) {} virtual ~UnBlock ( void ) {} void restore ( void ) { p->Blocker = Blocker; p->pDep = dep; p->pBlocked = pBlocked; p->dBlocked = dBlocked; } }; // UnBlock /// restore (un)cached node class CacheRestorer: public TRestorer { protected: DlCompletionTree* p; bool cached; public: CacheRestorer ( DlCompletionTree* q ) : p(q), cached(q->cached) {} virtual ~CacheRestorer ( void ) {} void restore ( void ) { p->cached = cached; } }; // CacheRestorer #ifdef RKG_IR_IN_NODE_LABEL /// restore node after IR set change class IRRestorer: public TRestorer { protected: DlCompletionTree* p; unsigned int n; public: IRRestorer ( DlCompletionTree* q ) : p(q), n(q->IR.size()) {} virtual ~IRRestorer ( void ) {} void restore ( void ) { p->IR.resize(n); } }; // IRRestorer #endif public: // type interface /// type for set of arcs typedef std::vector ArcCollection; /// iterator on edges typedef ArcCollection::iterator edge_iterator; /// const iterator on edges typedef ArcCollection::const_iterator const_edge_iterator; /// RO iterator on label typedef CGLabel::const_iterator const_label_iterator; #ifdef RKG_IR_IN_NODE_LABEL /// type for inequality relation information typedef growingArray IRInfo; #endif protected: // members /// label of a node CGLabel Label; #ifdef RKG_IR_IN_NODE_LABEL /// inequality relation information respecting current node IRInfo IR; #endif /// Neighbours information ArcCollection Neighbour; /// pointer to last saved node TSaveList saves; /// ID of node (used in print) unsigned int id; /// concept that init the newly created node BipolarPointer Init; /// blocker of a node const DlCompletionTree* Blocker; /// dep-set for Purge op DepSet pDep; // save state information unsigned int curLevel; // current level /// is given node a data node unsigned int flagDataNode : 1; /// flag if node is Cached unsigned int cached : 1; /// flag whether node is permanently/temporarily blocked unsigned int pBlocked : 1; /// flag whether node is directly/indirectly blocked unsigned int dBlocked : 1; /** Whether node is affected by change of some potential blocker. This flag may be viewed as a cache for a 'blocked' status */ unsigned int affected : 1; /// the rest unsigned int unused : 27; /// level of a nominal node; 0 means blockable one CTNominalLevel nominalLevel; private: // methods /// no copy c'tor DlCompletionTree ( const DlCompletionTree& copy ); /// no assignment DlCompletionTree& operator = ( const DlCompletionTree& copy ); protected: // methods //---------------------------------------------- // blocking support methods //---------------------------------------------- // sub-methods for optimal blocking /// check B1 and B2 from optimal blocking for given blocker candidate bool isCommonlyBlockedBy ( const DLDag& dag, const DlCompletionTree* p ) const; /// check B3 and B4 from optimal blocking for given blocker candidate bool isABlockedBy ( const DLDag& dag, const DlCompletionTree* p ) const; /// check B5 and B6 from optimal blocking for given blocker candidate bool isCBlockedBy ( const DLDag& dag, const DlCompletionTree* p ) const; // checking the blocking conditions for optimized blocking /// check if B1 holds for a given vertex (p is a candidate for blocker) bool B1 ( const DlCompletionTree* p ) const; /// check if B2 holds for (AS C) with transitions RST from A[0] using a simple automaton A for S bool B2Simple ( const RAStateTransitions& RST, BipolarPointer C ) const; /// check if B2 holds for C=(AS{n} X) with transitions RST from A[n] using a complex automaton A for S bool B2Complex ( const RAStateTransitions& RST, BipolarPointer C ) const; /// check if B2 holds for given DL vertex with C=V bool B2 ( const DLVertex& v, BipolarPointer C ) const { # ifdef ENABLE_CHECKING fpp_assert ( hasParent() ); // safety # endif const RAStateTransitions& RST = v.getRole()->getAutomaton()[v.getState()]; if ( v.getRole()->isSimple() ) return B2Simple ( RST, v.getC() ); else { if ( RST.empty() ) // no possible applications return true; if ( RST.isSingleton() ) return B2Simple ( RST, C-v.getState()+RST.getTransitionEnd() ); return B2Complex ( RST, C-v.getState() ); } } /// check if B3 holds for (<= n S.C)\in w' (p is a candidate for blocker) bool B3 ( const DlCompletionTree* p, unsigned int n, const TRole* S, BipolarPointer C ) const; /// check if B4 holds for (>= m T.E)\in w' (p is a candidate for blocker) bool B4 ( const DlCompletionTree* p, unsigned int m, const TRole* T, BipolarPointer E ) const; /// check if B5 holds for (<= n T.E)\in w' bool B5 ( const TRole* T, BipolarPointer E ) const; /// check if B6 holds for (>= m U.F)\in v bool B6 ( const TRole* U, BipolarPointer F ) const; //---------------------------------------------- // re-building blocking hierarchy //---------------------------------------------- /// check whether a node can block another one with init concept C bool canBlockInit ( BipolarPointer C ) const { return C == bpTOP || label().contains(C); } /// check if all parent arcs are blocked bool isParentArcIBlocked ( void ) const { for ( const_edge_iterator p = begin(); p != end(); ++p ) if ( (*p)->isPredEdge() && !(*p)->isIBlocked() ) return false; return true; } //---------------------------------------------- // Transitive SOME support interface //---------------------------------------------- /// check if SOME rule is applicable for transitive R const DlCompletionTree* isTSomeApplicable ( const TRole* R, BipolarPointer C ) const; /// check if SOME rule is applicable for non-transitive R const DlCompletionTree* isNSomeApplicable ( const TRole* R, BipolarPointer C ) const; /// check if transitive R-successor labelled with C const DlCompletionTree* isTSuccLabelled ( const TRole* R, BipolarPointer C ) const; /// check if transitive R-predecessor labelled with C; skip FROM node const DlCompletionTree* isTPredLabelled ( const TRole* R, BipolarPointer C, const DlCompletionTree* from ) const; //---------------------------------------------- // inequality relation methods //---------------------------------------------- /// check if the current node is in IR wrt C; if so, write the clash-set to DEP bool inIRwithC ( const ConceptWDep& C, DepSet& dep ) const; //---------------------------------------------- // saving/restoring //---------------------------------------------- /// get current save-level unsigned int getCurLevel ( void ) const { return curLevel; } /// save current state to given SS void save ( SaveState* nss ) const; /// restore state from given SS; delete SS after void restore ( SaveState* nss ); //---------------------------------------------- // logging/output //---------------------------------------------- /// log saving/restoring node void logSRNode ( const char* action ATTR_UNUSED ) const { # if defined(RKG_CHECK_BACKJUMPING) if ( LLM.isWritable(llSRInfo) ) LL << " " << action << "(" << id << "[" << Neighbour.size() << "]," << getCurLevel() << ")"; # undef RKG_CHECK_BACKJUMPING // it is the only user # endif } /// get letter corresponding to the blocking mode const char* getBlockingStatusName ( void ) const { return isPBlocked() ? "p" : isDBlocked() ? "d" : isIBlocked() ? "i" : "u"; } /// log node status (d-,i-,p-blocked or cached void logNodeBStatus ( std::ostream& o ) const { // blocking status information if ( Blocker ) o << getBlockingStatusName() << Blocker->getId(); if ( isCached() ) o << "c"; } /// log if node became p-blocked void logNodeBlocked ( void ) const { if ( LLM.isWritable(llGTA) ) { LL << " " << getBlockingStatusName() << "b(" << id; if ( Blocker ) LL << "," << Blocker->id; LL << ")"; } } public: // methods /// init newly created node with starting LEVEL void init ( unsigned int level ); /// c'tor: create an empty node DlCompletionTree ( unsigned int newId ) : id(newId) {} /// d'tor: delete node ~DlCompletionTree ( void ) { saves.clear(); } /// add given arc P as a neighbour void addNeighbour ( DlCompletionTreeArc* p ) { Neighbour.push_back(p); } /// get Node's id unsigned int getId ( void ) const { return id; } /// check if the node is cached (IE need not to be expanded) bool isCached ( void ) const { return cached; } /// set cached status of given node TRestorer* setCached ( bool val ) { if ( cached == val ) return NULL; TRestorer* ret = new CacheRestorer(this); cached = val; return ret; } // data node methods bool isDataNode ( void ) const { return flagDataNode; } void setDataNode ( void ) { flagDataNode = true; } // nominal node methods bool isBlockableNode ( void ) const { return nominalLevel == BlockableLevel; } bool isNominalNode ( void ) const { return nominalLevel != BlockableLevel; } bool isNominalNode ( CTNominalLevel level ) const { return nominalLevel == level; } void setNominalLevel ( void ) { nominalLevel = 0; } void setNominalLevel ( CTNominalLevel newLevel ) { nominalLevel = newLevel; } CTNominalLevel getNominalLevel ( void ) const { return nominalLevel; } /// compare 2 CT nodes wrt their nominal level/status bool operator < ( const DlCompletionTree& node ) const { return ( getNominalLevel() < node.getNominalLevel() ) || ( ( getNominalLevel() == node.getNominalLevel() ) && ( getId() < node.getId() ) ); } /// adds concept P to a label, defined by TAG; update blocked status if necessary void addConcept ( const ConceptWDep& p, DagTag tag ) { Label.getLabel(tag).add(p); } /// set the Init concept void setInit ( BipolarPointer p ) { Init = p; } //---------------------------------------------- // children/parent access interface //---------------------------------------------- // neighbour iterators const_edge_iterator begin ( void ) const { return Neighbour.begin(); } const_edge_iterator end ( void ) const { return Neighbour.end(); } edge_iterator begin ( void ) { return Neighbour.begin(); } edge_iterator end ( void ) { return Neighbour.end(); } /// return true if node is a non-root; works for reflexive roles bool hasParent ( void ) const { if ( Neighbour.empty() ) return false; return (*begin())->isPredEdge(); } //---------------------------------------------- // Transitive SOME support interface //---------------------------------------------- /// check if SOME rule is applicable; includes transitive SOME support const DlCompletionTree* isSomeApplicable ( const TRole* R, BipolarPointer C ) const { return R->isTransitive() ? isTSomeApplicable(R,C) : isNSomeApplicable(R,C); } //---------------------------------------------- // Label access interface //---------------------------------------------- /// RO access to a label const CGLabel& label ( void ) const { return Label; } /// RW access to a label CGLabel& label ( void ) { return Label; } // label iterators /// begin() iterator for a label with simple concepts const_label_iterator beginl_sc ( void ) const { return Label.begin_sc(); } /// end() iterator for a label with simple concepts const_label_iterator endl_sc ( void ) const { return Label.end_sc(); } /// begin() iterator for a label with complex concepts const_label_iterator beginl_cc ( void ) const { return Label.begin_cc(); } /// end() iterator for a label with complex concepts const_label_iterator endl_cc ( void ) const { return Label.end_cc(); } /// check whether node's label contains P bool isLabelledBy ( BipolarPointer p ) const { return Label.contains(p); } //---------------------------------------------- // blocking interface //---------------------------------------------- // Blocked-By methods for different logics /// check blocking condition for SH logic bool isBlockedBy_SH ( const DlCompletionTree* p ) const { return B1(p); } /// check blocking condition for SHI logic bool isBlockedBy_SHI ( const DLDag& dag, const DlCompletionTree* p ) const { return isCommonlyBlockedBy ( dag, p ); } /// check blocking condition for SHIQ logic using optimised blocking bool isBlockedBy_SHIQ ( const DLDag& dag, const DlCompletionTree* p ) const { return isCommonlyBlockedBy ( dag, p ) && ( isCBlockedBy ( dag, p ) || isABlockedBy ( dag, p ) ); } // WARNING!! works only for blockable nodes // every non-root node will have first upcoming edge pointed to a parent /// return RO pointer to the parent node; WARNING: correct only for nodes with hasParent()==TRUE const DlCompletionTree* getParentNode ( void ) const { return (*begin())->getArcEnd(); } /// return RW pointer to the parent node; WARNING: correct only for nodes with hasParent()==TRUE DlCompletionTree* getParentNode ( void ) { return (*begin())->getArcEnd(); } //---------------------------------------------- // managing AFFECTED flag //---------------------------------------------- /// check whether node is affected by blocking-related changes bool isAffected ( void ) const { return affected; } /// set node (and all subnodes) affected void setAffected ( void ) { // don't mark already affected, nominal or p-blocked nodes if ( isAffected() || isNominalNode() || isPBlocked() ) return; affected = true; for ( const_edge_iterator q = begin(), q_end = end(); q < q_end; ++q ) if ( (*q)->isSuccEdge() ) (*q)->getArcEnd()->setAffected(); } /// clear affected flag void clearAffected ( void ) { affected = false; } // just returns calculated values /// check if node is directly blocked bool isDBlocked ( void ) const { return Blocker != NULL && !pBlocked && dBlocked; } /// check if node is indirectly blocked bool isIBlocked ( void ) const { return Blocker != NULL && !pBlocked && !dBlocked; } /// check if node is purged (and so indirectly blocked) bool isPBlocked ( void ) const { return Blocker != NULL && pBlocked && !dBlocked; } /// check if node is blocked (d/i) bool isBlocked ( void ) const { return Blocker != NULL && !pBlocked; } /// check the legality of the direct block bool isIllegallyDBlocked ( void ) const { return isDBlocked() && Blocker->isBlocked(); } /// get access to the blocker const DlCompletionTree* getBlocker ( void ) const { return Blocker; } /// get RW node to which current one was merged DlCompletionTree* resolvePBlocker ( void ) { if ( unlikely(isPBlocked()) ) return const_cast(Blocker)->resolvePBlocker(); else return this; } /// get RO node to which current one was merged const DlCompletionTree* resolvePBlocker ( void ) const { if ( unlikely(isPBlocked()) ) return Blocker->resolvePBlocker(); else return this; } /// get node to which current one was merged; fills DEP from pDep's DlCompletionTree* resolvePBlocker ( DepSet& dep ) { if ( likely(!isPBlocked()) ) return this; dep += pDep; return const_cast(Blocker)->resolvePBlocker(dep); } /// get purge dep-set of a given node const DepSet& getPurgeDep ( void ) const { return pDep; } /// check whether a node can block node P according to it's Init value bool canBlockInit ( const DlCompletionTree* p ) const { return canBlockInit(p->Init); } /// check whether the loop between a DBlocked NODE and it's parent blocked contains C bool isLoopLabelled ( BipolarPointer c ) { fpp_assert ( isDBlocked() ); if ( Blocker->isLabelledBy(c) ) return true; int n = 1; // Blocker is the 1st node in the loop for ( DlCompletionTree* p = getParentNode(); p->hasParent() && p != Blocker; p = p->getParentNode() ) if ( p->isLabelledBy(c) ) return true; else ++n; if ( LLM.isWritable(llGTA) ) LL << " loop(" << n << ")"; return false; } //---------------------------------------------- // re-building blocking hierarchy //---------------------------------------------- /// set node blocked TRestorer* setBlocked ( const DlCompletionTree* blocker, bool permanently, bool directly ) { TRestorer* ret = new UnBlock(this); Blocker = blocker; pBlocked = permanently; dBlocked = directly; logNodeBlocked(); return ret; } /// mark node d-blocked TRestorer* setDBlocked ( const DlCompletionTree* blocker ) { return setBlocked ( blocker, false, true ); } /// mark node i-blocked TRestorer* setIBlocked ( const DlCompletionTree* blocker ) { return setBlocked ( blocker, false, false ); } /// mark node unblocked TRestorer* setUBlocked ( void ) { return setBlocked ( NULL, true, true ); } /// mark node purged TRestorer* setPBlocked ( const DlCompletionTree* blocker, const DepSet& dep ) { TRestorer* ret = new UnBlock(this); Blocker = blocker; if ( isNominalNode() ) pDep = dep; pBlocked = true; dBlocked = false; logNodeBlocked(); return ret; } //---------------------------------------------- // checking edge labelling //---------------------------------------------- /// check if edge to NODE is labelled by R; return NULL if does not DlCompletionTreeArc* getEdgeLabelled ( const TRole* R, const DlCompletionTree* node ) const { for ( const_edge_iterator p = begin(), p_end = end(); p < p_end; ++p ) if ( (*p)->getArcEnd() == node && (*p)->isNeighbour(R) ) return *p; return NULL; } /// check if parent arc is labelled by R; works only for blockable nodes bool isParentArcLabelled ( const TRole* R ) const { return getEdgeLabelled ( R, getParentNode() ) != NULL; } //---------------------------------------------- // inequality relation interface //---------------------------------------------- #ifdef RKG_IR_IN_NODE_LABEL /// init IR with given entry and dep-set; @return true if IR already has this label bool initIR ( unsigned int level, const DepSet& ds ) { ConceptWDep C(level,ds); DepSet dummy; // we don't need a clash-set here if ( inIRwithC ( C, dummy ) ) return true; IR.add(C); return false; } /// check if the current node is in IR with NODE; if so, write the clash-set to DEP bool nonMergable ( const DlCompletionTree* node, DepSet& dep ) const; /// update IR of the current node with IR from NODE and additional dep-set; @return restorer TRestorer* updateIR ( const DlCompletionTree* node, const DepSet& toAdd ); #endif //---------------------------------------------- // saving/restoring //---------------------------------------------- /// check if node needs to be saved bool needSave ( unsigned int newLevel ) const { return getCurLevel() < newLevel; } /// save node using internal stack void save ( unsigned int level ) { save(saves.push()); curLevel = level; } /// restore node from the topmost entry void restore ( void ) { fpp_assert ( !saves.empty() ); restore (saves.pop()); } /// check if node needs to be restored bool needRestore ( unsigned int restLevel ) const { return getCurLevel() > restLevel; } /// restore node to given level void restore ( unsigned int level ) { restore(saves.pop(level)); } // output /// log node information (number, i/d blockers, cached) void logNode ( void ) const { LL << getId(); logNodeBStatus(LL); } /// print body of the node (without neighbours) void PrintBody ( std::ostream& o ) const; }; // DlCompletionTree /* * Implementation */ inline void DlCompletionTree :: init ( unsigned int level ) { flagDataNode = false; nominalLevel = BlockableLevel; curLevel = level; cached = false; affected = true; // every (newly created) node can be blocked dBlocked = true; pBlocked = true; // unused flag combination Label.init(); Init = bpTOP; // node was used -- clear all previous content saves.clear(); #ifdef RKG_IR_IN_NODE_LABEL IR.clear(); #endif Neighbour.clear(); Blocker = NULL; pDep.clear(); } #endif // DLCOMPLETIONTREE_H FaCTpp-src-v1.6.2~dfsg/src/Kernel/Relevance.cpp0000644000000000000000000001107112112642405017764 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2005-2011 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include #include "dlTBox.h" void TBox :: setRelevant ( BipolarPointer p ) { fpp_assert ( isValid(p) ); if ( p == bpTOP || p == bpBOTTOM ) return; const DLVertex& v = DLHeap[p]; bool pos = isPositive(p); ++nRelevantBCalls; collectLogicFeature(v,pos); switch ( v.Type() ) { case dtDataType: // types and values are not relevant case dtDataValue: case dtDataExpr: case dtNN: // not appear in any expression => not relevant break; case dtPConcept: // negated primitive entries -- does nothing case dtPSingleton: // if ( !pos ) // break; // fall through case dtNConcept: // named concepts case dtNSingleton: setRelevant(const_cast(static_cast(v.getConcept()))); break; case dtForall: case dtLE: setRelevant(const_cast(v.getRole())); setRelevant (v.getC()); break; case dtProj: // no need to set (inverse) roles as it doesn't really matter case dtChoose: setRelevant(v.getC()); break; case dtIrr: setRelevant(const_cast(v.getRole())); break; case dtAnd: case dtSplitConcept: for ( DLVertex::const_iterator q = v.begin(); q != v.end(); ++q ) setRelevant(*q); break; default: std::cerr << "Error setting relevant vertex of type " << v.getTagName() << "(" << v.Type () << ")"; fpp_unreachable(); } } void TBox :: setRelevant1 ( TConcept* p ) { ++nRelevantCCalls; p->setRelevant(relevance); collectLogicFeature(p); setRelevant (p->pBody); } void TBox :: setRelevant1 ( TRole* p ) { p->setRelevant(relevance); collectLogicFeature(p); // Range and Domain are also relevant setRelevant ( p->getBPDomain() ); setRelevant ( p->getBPRange() ); // all super-roles are also relevant for ( TRole::const_iterator q = p->begin_anc(), q_end = p->end_anc(); q != q_end; ++q ) setRelevant(*q); } void TBox :: gatherRelevanceInfo ( void ) { nRelevantCCalls = 0; nRelevantBCalls = 0; unsigned int cSize = 0; unsigned int bSize = 0; // gather GCIs features curFeature = &GCIFeatures; markGCIsRelevant(); clearRelevanceInfo(); KBFeatures |= GCIFeatures; // fills in nominal cloud relevance info NCFeatures = GCIFeatures; // set up relevance info for ( i_iterator pi = i_begin(); pi != i_end(); ++pi ) { setConceptRelevant(*pi); NCFeatures |= (*pi)->posFeatures; } // correct NC inverse role information if ( NCFeatures.hasSomeAll() && !RelatedI.empty() ) NCFeatures.setInverseRoles(); for ( c_iterator pc = c_begin(); pc != c_end(); ++pc ) setConceptRelevant(*pc); cSize = ( c_end() - c_begin() ) + ( i_end() - i_begin() ); bSize = DLHeap.size()-2; curFeature = NULL; float cRatio, bRatio = 0, logCSize = 1, logBSize = 1, sqCSize = 1, sqBSize = 1; if ( cSize > 10 ) { cRatio = ((float)nRelevantCCalls)/cSize; sqCSize = sqrt((float)cSize); if ( cSize > 1 ) logCSize = log((float)cSize); } if ( bSize > 20 ) { bRatio = ((float)nRelevantBCalls)/bSize; sqBSize = sqrt((float)bSize); if ( bSize > 1 ) logBSize = log((float)bSize); } #if 0 if ( LLM.isWritable(llAlways) && cSize > 10 ) LL << "There were made " << nRelevantCCalls << " relevance C calls for " << cSize << " concepts\nRC ratio=" << cRatio << ", ratio/logSize=" << cRatio/logCSize << ", ratio/sqSize=" << cRatio/sqCSize << ", ratio/size=" << cRatio/cSize<< "\n"; if ( LLM.isWritable(llAlways) && bSize > 20 ) LL << "There were made " << nRelevantBCalls << " relevance B calls for " << bSize << " nodes\nRB ratio=" << bRatio << ", ratio/logSize=" << bRatio/logBSize << ", ratio/sqSize=" << bRatio/sqBSize << ", ratio/size=" << bRatio/bSize << "\n"; #endif // set up GALEN-like flag; based on r/n^{3/2}, add r/n^2<1 isLikeGALEN = (bRatio > sqBSize*20) && (bRatio < bSize); // switch off sorted reasoning iff top role appears if ( KBFeatures.hasTopRole() ) useSortedReasoning = false; } FaCTpp-src-v1.6.2~dfsg/src/Kernel/tAxiomSet.cpp0000644000000000000000000001200212112642405017770 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2010 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "tAxiomSet.h" #include "logging.h" #include "dlTBox.h" /// d'tor TAxiomSet :: ~TAxiomSet ( void ) { for ( AxiomCollection::iterator p = Accum.begin(), p_end = Accum.end(); p < p_end; ++p ) delete *p; } bool TAxiomSet :: split ( const TAxiom* p ) { AxiomCollection Splitted; if ( !p->split(Splitted) ) // nothing to split return false; AxiomCollection::iterator q = Splitted.begin(), q_end = Splitted.end(); bool cont = true; for ( ; q != q_end; ++q ) if ( !needed(*q) ) { // there is already such an axiom in process; delete it cont = false; break; } // do the actual insertion if necessary for ( q = Splitted.begin(); q != q_end; ++q ) if ( cont ) insertGCI(*q); else delete *q; return cont; } unsigned int TAxiomSet :: absorb ( void ) { // absorbed- and unabsorbable GCIs AxiomCollection Absorbed, GCIs; // we will change Accum (via split rule), so indexing and compare with size for ( unsigned int i = 0; i < Accum.size(); ++i ) { # ifdef RKG_DEBUG_ABSORPTION std::cout << "\nProcessing (" << i << "):"; # endif TAxiom* ax = Accum[i]; if ( absorbGCI(ax) ) Absorbed.push_back(ax); else GCIs.push_back(ax); } // clear absorbed and remove them from Accum for ( AxiomCollection::iterator p = Absorbed.begin(), p_end = Absorbed.end(); p != p_end; ++p ) delete *p; Accum.swap(GCIs); #ifdef RKG_DEBUG_ABSORPTION std::cout << "\nAbsorption done with " << Accum.size() << " GCIs left\n"; #endif PrintStatistics(); return size(); } bool TAxiomSet :: absorbGCI ( const TAxiom* p ) { Stat::SAbsAction(); for ( AbsActVector::iterator f = ActionVector.begin(), f_end = ActionVector.end(); f != f_end; ++f ) if ( (this->*(*f))(p) ) return true; #ifdef RKG_DEBUG_ABSORPTION std::cout << " keep as GCI"; #endif return false; } bool TAxiomSet :: initAbsorptionFlags ( const std::string& flags ) { ActionVector.clear(); for ( std::string::const_iterator p = flags.begin(), p_end = flags.end(); p != p_end; ++p ) switch ( *p ) { case 'B': ActionVector.push_back(&TAxiomSet::absorbIntoBottom); break; case 'T': ActionVector.push_back(&TAxiomSet::absorbIntoTop); break; case 'E': ActionVector.push_back(&TAxiomSet::simplifyCN); break; case 'C': ActionVector.push_back(&TAxiomSet::absorbIntoConcept); break; case 'N': ActionVector.push_back(&TAxiomSet::absorbIntoNegConcept); break; case 'F': ActionVector.push_back(&TAxiomSet::simplifyForall); break; case 'R': ActionVector.push_back(&TAxiomSet::absorbIntoDomain); break; case 'S': ActionVector.push_back(&TAxiomSet::split); break; default: return true; } if ( LLM.isWritable(llAlways) ) LL << "Init absorption order as " << flags.c_str() << "\n"; return false; } void TAxiomSet :: PrintStatistics ( void ) const { if ( Stat::SAbsAction::objects_created == 0 || !LLM.isWritable(llAlways) ) return; LL << "\nAbsorption dealt with " << Stat::SAbsInput::objects_created << " input axioms\nThere were made " << Stat::SAbsAction::objects_created << " absorption actions, of which:"; if ( Stat::SAbsRepCN::objects_created ) LL << "\n\t" << Stat::SAbsRepCN::objects_created << " concept name replacements"; if ( Stat::SAbsRepForall::objects_created ) LL << "\n\t" << Stat::SAbsRepForall::objects_created << " universals replacements"; if ( Stat::SAbsSplit::objects_created ) LL << "\n\t" << Stat::SAbsSplit::objects_created << " conjunction splits"; if ( Stat::SAbsBApply::objects_created ) LL << "\n\t" << Stat::SAbsBApply::objects_created << " BOTTOM absorptions"; if ( Stat::SAbsTApply::objects_created ) LL << "\n\t" << Stat::SAbsTApply::objects_created << " TOP absorptions"; if ( Stat::SAbsCApply::objects_created ) LL << "\n\t" << Stat::SAbsCApply::objects_created << " concept absorption with " << Stat::SAbsCAttempt::objects_created << " possibilities"; if ( Stat::SAbsNApply::objects_created ) LL << "\n\t" << Stat::SAbsNApply::objects_created << " negated concept absorption with " << Stat::SAbsNAttempt::objects_created << " possibilities"; if ( Stat::SAbsRApply::objects_created ) LL << "\n\t" << Stat::SAbsRApply::objects_created << " role domain absorption with " << Stat::SAbsRAttempt::objects_created << " possibilities"; if ( !Accum.empty() ) LL << "\nThere are " << Accum.size() << " GCIs left"; } FaCTpp-src-v1.6.2~dfsg/src/Kernel/tNAryQueue.h0000644000000000000000000000435512112642405017576 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2010 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef TNARYQUEUE_H #define TNARYQUEUE_H #include /// queue for n-ary operations template class TNAryQueue { public: // types /// type of the array typedef std::vector DLExpressionArray; protected: // types /// type of a base storage typedef std::vector BaseType; /// base storage iterator typedef typename BaseType::iterator iterator; private: // members /// all lists of arguments for n-ary predicates/commands BaseType Base; /// pre-current index of n-ary statement int level; private: // methods /// increase size of internal AUX array void grow ( void ) { unsigned int n = Base.size(); Base.resize(2*n); for ( iterator p = Base.begin()+n, p_end = Base.end(); p < p_end; ++p ) *p = new DLExpressionArray; } public: // interface /// empty c'tor TNAryQueue ( void ) : level(-1) { Base.push_back(new DLExpressionArray); } /// d'tor ~TNAryQueue ( void ) { for ( iterator q = Base.begin(), q_end = Base.end(); q < q_end; ++q ) delete *q; } // queue interface /// init the next argument list void openArgList ( void ) { if ( (unsigned)++level >= Base.size() ) grow(); Base[level]->clear(); } /// add the next element to the current argument list void addArg ( Expression* p ) { Base[level]->push_back(p); } /// get access to the last closed argument list const DLExpressionArray& getLastArgList ( void ) { return *Base[level--]; } }; // TNAryQueue #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/Input.cpp0000644000000000000000000002370012112642405017161 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2012 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "dlTBox.h" //----------------------------------------------------------------------------- //-- Subsumption axioms and support //----------------------------------------------------------------------------- // return true if undefined concept found void TBox :: addSubsumeAxiom ( DLTree* sub, DLTree* sup ) { // for C [= C: nothing to do if ( equalTrees ( sub, sup ) ) { deleteTree(sub); deleteTree(sup); return; } // try to apply C [= CN if ( isCN(sup) ) if ( applyAxiomCToCN ( sub, sup ) ) return; // try to apply CN [= C if ( isCN(sub) ) if ( applyAxiomCNToC ( sub, sup ) ) return; // check if an axiom looks like T [= \AR.C if ( axiomToRangeDomain ( sub, sup ) ) ; else // general axiom processGCI ( sub, sup ); } /// tries to apply axiom D [= CN; @return true if applicable bool TBox :: applyAxiomCToCN ( DLTree* D, DLTree*& CN ) { TConcept* C = resolveSynonym(getCI(CN)); fpp_assert ( C != NULL ); // check whether name is a synonym of a constant (mainly for owl:Thing) if ( C == pBottom ) { deleteTree(CN); CN = createBottom(); return false; } // D [= TOP: nothing to do if ( C == pTop ) deleteTree(D); // check for D [= CN with CN [= D already defined // don't do this for D is a DN and C is an individual as cycle detection will do it better // FIXME!! check for C->isPrimitive() else if ( equalTrees ( C->Description, D ) && !( C->isSingleton() && isName(D) ) ) deleteTree ( makeNonPrimitive(C,D) ); else // n/a return false; deleteTree(CN); return true; } /// tries to apply axiom CN [= D; @return true if applicable bool TBox :: applyAxiomCNToC ( DLTree*& CN, DLTree* D ) { TConcept* C = resolveSynonym(getCI(CN)); fpp_assert ( C != NULL ); // TOP [= D: n/a if ( C == pTop ) { deleteTree(CN); CN = createTop(); return false; } // BOTTOM [= D: nothing to do if ( C == pBottom ) deleteTree(D); else if ( C->isPrimitive() ) C->addDesc(D); else // C is defined addSubsumeForDefined ( C, D ); deleteTree(CN); return true; } /// add an axiom CN [= D for defined CN (CN=E already in base) void TBox :: addSubsumeForDefined ( TConcept* C, DLTree* D ) { // if D is a syntactic sub-class of E, then nothing to do if ( isSubTree ( D, C->Description ) ) { deleteTree(D); return; } DLTree* oldDesc = clone(C->Description); // try to see whether C contains a reference to itself at the top level C->removeSelfFromDescription(); if ( equalTrees ( oldDesc, C->Description ) ) { processGCI ( oldDesc, D ); return; } // note that we don't know exact semantics of C for now; // we need to split it's definition and work via GCIs C->setPrimitive(); // now we have C [= B C->addDesc(D); // here C [= (B and D) // all we need is to add (old C's desc) [= C addSubsumeAxiom ( oldDesc, getTree(C) ); } bool TBox :: axiomToRangeDomain ( DLTree* sub, DLTree* sup ) { // applicability check for T [= A R.C if ( sub->Element() == TOP && sup->Element () == FORALL ) { resolveRole(sup->Left())->setRange(clone(sup->Right())); // free unused memory deleteTree(sub); deleteTree(sup); return true; } // applicability check for E R.T [= D if ( sub->Element() == NOT && sub->Left()->Element() == FORALL && sub->Left()->Right()->Element() == BOTTOM ) { resolveRole(sub->Left()->Left())->setDomain(sup); deleteTree(sub); return true; } return false; } //----------------------------------------------------------------------------- //-- Equality axioms and support //----------------------------------------------------------------------------- // return true if undefined concept found void TBox :: addEqualityAxiom ( DLTree* left, DLTree* right ) { // try to make a concept definition LEFT = RIGHT if ( addNonprimitiveDefinition ( left, right ) ) return; // try to make a concept definition RIGHT = LEFT if ( addNonprimitiveDefinition ( right, left ) ) return; if ( switchToNonprimitive ( left, right ) ) return; if ( switchToNonprimitive ( right, left ) ) return; /// here either C and D are complex expressions, or definition fails addSubsumeAxiom ( clone(left), clone(right) ); addSubsumeAxiom ( right, left ); } /// tries to add LEFT = RIGHT for the concept LEFT; @return true if OK bool TBox :: addNonprimitiveDefinition ( DLTree* left, DLTree* right ) { TConcept* C = resolveSynonym(getCI(left)); // not a named concept if ( C == NULL || C == pTop || C == pBottom ) return false; // check whether the case is C=D for a (concept-like) D TConcept* D = getCI(right); // nothing to do for the case C := D for named concepts C,D with D = C already if ( D && resolveSynonym(D) == C ) { deleteTree(left); deleteTree(right); return true; } // can't have C=D where C is a nominal and D is a concept if ( C->isSingleton() && D != NULL && !D->isSingleton() ) return false; // if axiom is in form C=... or C=D, D [= ... if ( D == NULL || C->Description == NULL || D->isPrimitive() ) { // try to define C if ( !initNonPrimitive ( C, right ) ) { deleteTree(left); return true; } } // can't make definition return false; } /// tries to add LEFT = RIGHT for the concept LEFT [= X; @return true if OK bool TBox :: switchToNonprimitive ( DLTree* left, DLTree* right ) { TConcept* C = resolveSynonym(getCI(left)); // not a named concept if ( C == NULL || C == pTop || C == pBottom ) return false; // make sure that we avoid making an individual equals to smth-else TConcept* D = resolveSynonym(getCI(right)); if ( C->isSingleton() && D && !D->isSingleton() ) return false; // check whether we process C=D where C is defined as C[=E if ( alwaysPreferEquals && C->isPrimitive() ) // change C to C=... with additional GCI C[=x { deleteTree(left); addSubsumeForDefined ( C, makeNonPrimitive(C,right) ); return true; } return false; } //----------------------------------------------------------------------------- //-- N-ary concept axioms //----------------------------------------------------------------------------- void TBox :: processDisjointC ( ea_iterator beg, ea_iterator end ) { ExpressionArray prim, rest; for ( ; beg < end; ++beg ) if ( isName(*beg) && static_cast((*beg)->Element().getNE())->isPrimitive() ) prim.push_back(*beg); else rest.push_back(*beg); // both primitive concept and others are in DISJ statement if ( !prim.empty() && !rest.empty() ) { DLTree* nrest = buildDisjAux ( rest.begin(), rest.end() ); for ( ea_iterator q = prim.begin(), q_end = prim.end(); q < q_end; ++q ) addSubsumeAxiom ( clone(*q), clone(nrest) ); deleteTree(nrest); } // no primitive concepts between DJ elements if ( !rest.empty() ) processDisjoint ( rest.begin(), rest.end() ); // all non-PC are done; prim is non-empty // FIXME!! do it in more optimal way later if ( !prim.empty() ) processDisjoint ( prim.begin(), prim.end() ); } void TBox :: processEquivalentC ( ea_iterator beg, ea_iterator end ) { for ( ; beg+1 < end; ++beg ) addEqualityAxiom ( *beg, clone(*(beg+1)) ); // now beg+1 == end, so beg points to the last element deleteTree(*beg); } //----------------------------------------------------------------------------- //-- N-ary individual axioms //----------------------------------------------------------------------------- void TBox :: processDifferent ( ea_iterator beg, ea_iterator end ) { SingletonVector acc; for ( ; beg < end; ++beg ) if ( isIndividual(*beg) ) // only nominals in DIFFERENT command { acc.push_back(toIndividual((*beg)->Element().getNE())); deleteTree(*beg); } else throw EFaCTPlusPlus("Only individuals allowed in processDifferent()"); // register vector of disjoint nominals in proper place if ( acc.size() > 1 ) Different.push_back(acc); } void TBox :: processSame ( ea_iterator beg, ea_iterator end ) { if ( beg == end ) return; if ( !isIndividual(*beg) ) // only nominals in SAME command throw EFaCTPlusPlus("Only individuals allowed in processSame()"); for ( ; beg+1 < end; ++beg ) { if ( !isIndividual(*(beg+1)) ) throw EFaCTPlusPlus("Only individuals allowed in processSame()"); addEqualityAxiom ( *beg, clone(*(beg+1)) ); } // now beg+1 == end, so beg points to the last element deleteTree(*beg); } //----------------------------------------------------------------------------- //-- N-ary role axioms //----------------------------------------------------------------------------- void TBox :: processDisjointR ( ea_iterator beg, ea_iterator end ) { if ( beg == end ) throw EFaCTPlusPlus("Empty disjoint role axiom"); ea_iterator p, q; // check that all id's are correct role names for ( p = beg; p < end; ++p ) if ( isTopRole(*p) ) throw EFaCTPlusPlus("Universal role in the disjoint roles axiom"); RoleMaster* RM = getRM(resolveRole(*beg)); // make a disjoint roles for ( p = beg; p < end; ++p ) { TRole* r = resolveRole(*p); // FIXME: this could be done more optimal... for ( q = p+1; q < end; ++q ) RM->addDisjointRoles ( r, resolveRole(*q) ); deleteTree(*p); } } void TBox :: processEquivalentR ( ea_iterator beg, ea_iterator end ) { if ( beg != end ) { RoleMaster& RM = *getRM(resolveRole(*beg)); for ( ; beg != end-1; ++beg ) { RM.addRoleSynonym ( resolveRole(*beg), resolveRole(*(beg+1)) ); deleteTree(*beg); } deleteTree(*beg); } } FaCTpp-src-v1.6.2~dfsg/src/Kernel/Kernel.cpp0000644000000000000000000006152312112642405017307 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2013 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "Kernel.h" #include "tOntologyLoader.h" #include "tOntologyPrinterLISP.h" #include "AxiomSplitter.h" #include "AtomicDecomposer.h" const char* ReasoningKernel :: Version = "1.6.2"; const char* ReasoningKernel :: SupportedDL = "SROIQ(D)"; const char* ReasoningKernel :: Copyright = "Copyright (C) Dmitry Tsarkov, 2002-2013"; const char* ReasoningKernel :: ReleaseDate = "19 February 2013"; // print the FaCT++ information only once static bool KernelFirstRun = true; // debug related individual/values switch //#define FPP_DEBUG_PRINT_RELATED_PROGRESS // dump loaded ontology in LISP format to the stdout //#define FPP_DEBUG_DUMP_LISP_ONTOLOGY ReasoningKernel :: ReasoningKernel ( void ) : pTBox (NULL) , pET(NULL) , KE(NULL) , AD(NULL) , ModSyn(NULL) , ModSem(NULL) , JNICache(NULL) , pMonitor(NULL) , OpTimeout(0) , verboseOutput(false) , useUndefinedNames(true) , cachedQuery(NULL) , cachedQueryTree(NULL) , useAxiomSplitting(false) , ignoreExprCache(false) { // Intro if ( KernelFirstRun ) { std::cerr << "FaCT++.Kernel: Reasoner for the " << SupportedDL << " Description Logic, " << 8*sizeof(void*) << "-bit\n" << Copyright << ". Version " << Version << " (" << ReleaseDate << ")\n"; KernelFirstRun = false; } initCacheAndFlags(); // init option set (fill with options): if ( initOptions () ) throw EFaCTPlusPlus("FaCT++ kernel: Cannot init options"); } /// d'tor ReasoningKernel :: ~ReasoningKernel ( void ) { clearTBox(); delete cachedQueryTree; delete pMonitor; } /// clear TBox and related structures; keep ontology in place void ReasoningKernel :: clearTBox ( void ) { delete pTBox; pTBox = NULL; delete pET; pET = NULL; delete KE; KE = NULL; delete AD; AD = NULL; delete ModSem; ModSem = NULL; delete ModSyn; ModSyn = NULL; // during preprocessing the TBox names were cached. clear that cache now. getExpressionManager()->clearNameCache(); } bool ReasoningKernel :: tryIncremental ( void ) { // if no TBox known -- reload if ( pTBox == NULL ) return true; // if ontology wasn't change -- no need to reload if ( !Ontology.isChanged() ) return false; // else -- check whether incremental is possible // FOR NOW!! switch off incremental reasoning while the JNI is unstable (as it is the only user ATM) return true; } /// force the re-classification of the changed ontology void ReasoningKernel :: forceReload ( void ) { // reset TBox clearTBox(); newKB(); // Protege (as the only user of non-trivial monitors with reload) does not accept multiple usage of a monitor // so switch it off after the 1st usage pMonitor = NULL; // split ontological axioms if ( useAxiomSplitting ) { TAxiomSplitter AxiomSplitter(&Ontology); AxiomSplitter.buildSplit(); } // (re)load ontology TOntologyLoader OntologyLoader(*getTBox()); OntologyLoader.visitOntology(Ontology); #ifdef FPP_DEBUG_DUMP_LISP_ONTOLOGY TLISPOntologyPrinter OntologyPrinter(std::cout); // DRoles.fill(OntologyPrinter); OntologyPrinter.visitOntology(Ontology); #endif // after loading ontology became processed completely Ontology.setProcessed(); } //------------------------------------------------- // Prepare reasoning/query //------------------------------------------------- void ReasoningKernel :: processKB ( KBStatus status ) { fpp_assert ( status >= kbCChecked ); // check whether reasoning was failed if ( reasoningFailed ) throw EFaCTPlusPlus("Can't classify KB because of previous errors"); // check if something have to be done if ( getStatus() >= status ) { // nothing to do; but make sure that we are consistent if ( !isKBConsistent() ) throw EFPPInconsistentKB(); return; } // here we have to do something: let's decide what to do switch ( getStatus() ) { case kbEmpty: case kbLoading: break; // need to do the whole cycle -- just after the switch case kbCChecked: goto Classify; // do classification case kbClassified: goto Realise; // do realisation default: // nothing should be here fpp_unreachable(); } // start with loading and preprocessing -- here might be a failures reasoningFailed = true; // load the axioms from the ontology to the TBox if ( tryIncremental() ) forceReload(); // do the consistency check pTBox->isConsistent(); // if there were no exception thrown -- clear the failure status reasoningFailed = false; if ( status == kbCChecked ) return; Classify: // do classification // don't do classification twice if ( status == kbRealised ) goto Realise; if ( !pTBox->isConsistent() ) return; pTBox->performClassification(); return; Realise: // do realisation if ( !pTBox->isConsistent() ) return; pTBox->performRealisation(); } //----------------------------------------------------------------------------- //-- query caching support //----------------------------------------------------------------------------- /// classify query; cache is ready at the point. NAMED means whether concept is just a name void ReasoningKernel :: classifyQuery ( bool named ) { // make sure KB is classified classifyKB(); if ( !named ) // general expression: classify query concept getTBox()->classifyQueryConcept(); cachedVertex = cachedConcept->getTaxVertex(); if ( unlikely(cachedVertex == NULL) ) // fresh concept cachedVertex = getCTaxonomy()->getFreshVertex(cachedConcept); } void ReasoningKernel :: setUpCache ( DLTree* query, cacheStatus level ) { // if KB was changed since it was classified, // we should catch it before fpp_assert ( !Ontology.isChanged() ); // check if the query is already cached if ( checkQueryCache(query) ) { // ... with the same level -- nothing to do deleteTree(query); if ( level <= cacheLevel ) return; else { // concept was defined but not classified yet fpp_assert ( level == csClassified && cacheLevel != csClassified ); if ( cacheLevel == csSat ) // already check satisfiability { classifyQuery(isCN(cachedQueryTree)); return; } } } else // change current query setQueryCache(query); // clean cached info cachedVertex = NULL; cacheLevel = level; // check if concept-to-cache is defined in ontology if ( isCN(cachedQueryTree) ) cachedConcept = getTBox()->getCI(cachedQueryTree); else // case of complex query cachedConcept = getTBox()->createQueryConcept(cachedQueryTree); fpp_assert ( cachedConcept != NULL ); // preprocess concept is necessary (fresh concept in query or complex one) if ( !isValid(cachedConcept->pName) ) getTBox()->preprocessQueryConcept(cachedConcept); if ( level == csClassified ) classifyQuery(isCN(cachedQueryTree)); } void ReasoningKernel :: setUpCache ( TConceptExpr* query, cacheStatus level ) { // if KB was changed since it was classified, // we should catch it before fpp_assert ( !Ontology.isChanged() ); // check if the query is already cached if ( checkQueryCache(query) ) { // ... with the same level -- nothing to do if ( level <= cacheLevel ) return; else { // concept was defined but not classified yet fpp_assert ( level == csClassified && cacheLevel != csClassified ); if ( cacheLevel == csSat ) // already check satisfiability { classifyQuery(isNameOrConst(cachedQuery)); return; } } } else // change current query setQueryCache(query); // clean cached info cachedVertex = NULL; cacheLevel = level; // check if concept-to-cache is defined in ontology if ( isNameOrConst(cachedQuery) ) cachedConcept = getTBox()->getCI(TreeDeleter(e(cachedQuery))); else // case of complex query cachedConcept = getTBox()->createQueryConcept(TreeDeleter(e(cachedQuery))); fpp_assert ( cachedConcept != NULL ); // preprocess concept is necessary (fresh concept in query or complex one) if ( !isValid(cachedConcept->pName) ) getTBox()->preprocessQueryConcept(cachedConcept); if ( level == csClassified ) classifyQuery(isNameOrConst(cachedQuery)); } //------------------------------------------------- // concept subsumption query implementation //------------------------------------------------- /// class for exploring concept taxonomy to find super classes class SupConceptActor { protected: const ClassifiableEntry* pe; void entry ( const ClassifiableEntry* q ) { if ( pe == q ) throw std::exception(); } public: SupConceptActor ( ClassifiableEntry* q ) :pe(q) {} bool apply ( const TaxonomyVertex& v ) { entry(v.getPrimer()); for ( TaxonomyVertex::syn_iterator p = v.begin_syn(), p_end=v.end_syn(); p != p_end; ++p ) entry(*p); return true; } }; // SupConceptActor /// @return true iff C [= D holds bool ReasoningKernel :: checkSub ( TConcept* C, TConcept* D ) { // check whether a concept is fresh if ( unlikely(!isValid(D->pName)) ) // D is fresh { if ( unlikely(!isValid(C->pName)) ) // C is fresh return C == D; // 2 fresh concepts subsumes one another iff they are the same else // C is known return !getTBox()->isSatisfiable(C); // C [= D iff C=\bottom } else // D is known if ( unlikely(!isValid(C->pName)) ) // C is fresh // C [= D iff D = \top, or ~D = \bottom return !checkSatTree(createSNFNot(getTBox()->getTree(C))); // here C and D are known (not fresh) // check the obvious ones if ( unlikely(D->isTop()) || unlikely(C->isBottom()) ) return true; if ( getStatus() < kbClassified ) // unclassified => do via SAT test return getTBox()->isSubHolds ( C, D ); // classified => do the taxonomy traversal SupConceptActor actor(D); Taxonomy* tax = getCTaxonomy(); try { tax->getRelativesInfo ( C->getTaxVertex(), actor ); return false; } catch (...) { tax->clearCheckedLabel(); return true; } } //------------------------------------------------- // all-disjoint query implementation //------------------------------------------------- bool ReasoningKernel :: isDisjointRoles ( void ) { // grab all roles from the arg-list typedef const std::vector TExprVec; typedef std::vector TRoleVec; TExprVec Disj = getExpressionManager()->getArgList(); TRoleVec Roles; Roles.reserve(Disj.size()); unsigned int nTopRoles = 0; for ( TExprVec::const_iterator p = Disj.begin(), p_end = Disj.end(); p != p_end; ++p ) { if ( TORoleExpr* ORole = dynamic_cast(*p) ) { TRole* R = getRole ( ORole, "Role expression expected in isDisjointRoles()" ); if ( R->isBottom() ) continue; // empty role is disjoint with everything if ( R->isTop() ) ++nTopRoles; // count universal roles else Roles.push_back(R); } else if ( TDRoleExpr* DRole = dynamic_cast(*p) ) { TRole* R = getRole ( DRole, "Role expression expected in isDisjointRoles()" ); if ( R->isBottom() ) continue; // empty role is disjoint with everything if ( R->isTop() ) ++nTopRoles; // count universal roles else Roles.push_back(R); } else throw EFaCTPlusPlus ( "Role expression expected in isDisjointRoles()" ); } // deal with top-roles if ( nTopRoles > 0 ) { if ( nTopRoles > 1 || !Roles.empty() ) return false; // universal role is not disjoint with anything but the bottom role else return true; } // test pair-wise disjointness TRoleVec::const_iterator q = Roles.begin(), q_end = Roles.end(), s; for ( ; q != q_end; ++q ) for ( s = q+1; s != q_end; ++s ) if ( !getTBox()->isDisjointRoles(*q,*s) ) return false; return true; } //------------------------------------------------- // related individuals implementation //------------------------------------------------- class RIActor { protected: ReasoningKernel::CIVec acc; /// process single entry in a vertex label bool tryEntry ( const ClassifiableEntry* p ) { // check the applicability if ( p->isSystem() || !static_cast(p)->isSingleton() ) return false; // print the concept acc.push_back(static_cast(p)); return true; } public: RIActor ( void ) {} ~RIActor ( void ) {} bool apply ( const TaxonomyVertex& v ) { bool ret = tryEntry(v.getPrimer()); for ( TaxonomyVertex::syn_iterator p = v.begin_syn(), p_end = v.end_syn(); p != p_end; ++p ) ret |= tryEntry(*p); return ret; } const ReasoningKernel::CIVec& getAcc ( void ) const { return acc; } }; // RIActor ReasoningKernel::CIVec ReasoningKernel :: buildRelatedCache ( TIndividual* I, const TRole* R ) { #ifdef FPP_DEBUG_PRINT_RELATED_PROGRESS std::cout << "Related for " << I->getName() << " via property " << R->getName() << "\n"; #endif // for synonyms: use the representative's cache if ( R->isSynonym() ) return getRelated ( I, resolveSynonym(R) ); // FIXME!! return an empty set for data roles if ( R->isDataRole() ) return CIVec(); // empty role has no fillers if ( R->isBottom() ) return CIVec(); // now fills the query RIActor actor; // ask for instances of \exists R^-.{i} TORoleExpr* InvR = R->getId() > 0 ? getExpressionManager()->Inverse(getExpressionManager()->ObjectRole(R->getName())) : getExpressionManager()->ObjectRole(R->inverse()->getName()); TConceptExpr* query = R->isTop() ? getExpressionManager()->Top() : // universal role has all the named individuals as a filler getExpressionManager()->Value ( InvR, getExpressionManager()->Individual(I->getName()) ); getInstances ( query, actor ); return actor.getAcc(); } /// @return in Rs all (DATA)-roles R s.t. (I,x):R; add inverses if NEEDI is true void ReasoningKernel :: getRelatedRoles ( const TIndividualExpr* I, NamesVector& Rs, bool data, bool needI ) { realiseKB(); // ensure KB is ready to answer the query Rs.clear(); TIndividual* i = getIndividual ( I, "individual name expected in the getRelatedRoles()" ); RoleMaster* RM = data ? getDRM() : getORM(); for ( RoleMaster::iterator p = RM->begin(), p_end = RM->end(); p < p_end; ++p ) { const TRole* R = *p; if ( ( R->getId() > 0 || needI ) && !getRelated(i,R).empty() ) Rs.push_back(R); } } void ReasoningKernel :: getRoleFillers ( const TIndividualExpr* I, const TORoleExpr* R, IndividualSet& Result ) { realiseKB(); // ensure KB is ready to answer the query CIVec vec = getRelated ( getIndividual ( I, "Individual name expected in the getRoleFillers()" ), getRole ( R, "Role expression expected in the getRoleFillers()" ) ); for ( CIVec::iterator p = vec.begin(), p_end = vec.end(); p < p_end; ++p ) Result.push_back(const_cast(*p)); } /// set RESULT into set of J's such that R(I,J) bool ReasoningKernel :: isRelated ( const TIndividualExpr* I, const TORoleExpr* R, const TIndividualExpr* J ) { realiseKB(); // ensure KB is ready to answer the query TIndividual* i = getIndividual ( I, "Individual name expected in the isRelated()" ); TRole* r = getRole ( R, "Role expression expected in the isRelated()" ); if ( r->isDataRole() ) return false; // FIXME!! not implemented TIndividual* j = getIndividual ( J, "Individual name expected in the isRelated()" ); CIVec vec = getRelated ( i, r ); for ( CIVec::iterator p = vec.begin(), p_end = vec.end(); p < p_end; ++p ) if ( j == (*p) ) return true; return false; } //---------------------------------------------------------------------------------- // atomic decomposition queries //---------------------------------------------------------------------------------- /// create new atomic decomposition of the loaded ontology using TYPE. @return size of the AD unsigned int ReasoningKernel :: getAtomicDecompositionSize ( bool useSemantic, ModuleType moduleType ) { // init AD field if ( unlikely(AD != NULL) ) delete AD; AD = new AtomicDecomposer(getModExtractor(useSemantic)); return AD->getAOS ( &Ontology, moduleType )->size(); } /// get a set of axioms that corresponds to the atom with the id INDEX const TOntologyAtom::AxiomSet& ReasoningKernel :: getAtomAxioms ( unsigned int index ) const { return (*AD->getAOS())[index]->getAtomAxioms(); } /// get a set of axioms that corresponds to the module of the atom with the id INDEX const TOntologyAtom::AxiomSet& ReasoningKernel :: getAtomModule ( unsigned int index ) const { return (*AD->getAOS())[index]->getModule(); } /// get a set of atoms on which atom with index INDEX depends const TOntologyAtom::AtomSet& ReasoningKernel :: getAtomDependents ( unsigned int index ) const { return (*AD->getAOS())[index]->getDepAtoms(); } TModularizer* ReasoningKernel :: getModExtractor ( bool useSemantic ) { bool needInit = false; // check whether we need init if ( useSemantic && unlikely(ModSem == NULL) ) { ModSem = new TModularizer(/*useSem=*/true); needInit = true; } if ( !useSemantic && unlikely(ModSyn == NULL) ) { ModSyn = new TModularizer(/*useSem=*/false); needInit = true; } // init if necessary TModularizer* Mod = useSemantic ? ModSem : ModSyn; if ( unlikely(needInit) ) Mod->preprocessOntology(getOntology().getAxioms()); return Mod; } /// get a set of axioms that corresponds to the atom with the id INDEX const AxiomVec& ReasoningKernel :: getModule ( bool useSemantic, ModuleType moduleType ) { // init signature TSignature Sig; Sig.setLocality(false); const std::vector signature = getExpressionManager()->getArgList(); for ( std::vector::const_iterator q = signature.begin(), q_end = signature.end(); q != q_end; ++q ) if ( const TNamedEntity* entity = dynamic_cast(*q) ) Sig.add(entity); TModularizer* Mod = getModExtractor(useSemantic); Mod->extract ( getOntology(), Sig, moduleType ); return Mod->getModule(); } /// get a set of axioms that corresponds to the atom with the id INDEX const AxiomVec& ReasoningKernel :: getNonLocal ( bool useSemantic, ModuleType moduleType ) { // init signature TSignature Sig; Sig.setLocality(moduleType == M_TOP); // true for TOP, false for BOT/STAR const std::vector signature = getExpressionManager()->getArgList(); for ( std::vector::const_iterator q = signature.begin(), q_end = signature.end(); q != q_end; ++q ) if ( const TNamedEntity* entity = dynamic_cast(*q) ) Sig.add(entity); // do check LocalityChecker* LC = getModExtractor(useSemantic)->getLocalityChecker(); LC->setSignatureValue(Sig); Result.clear(); for ( TOntology::iterator p = getOntology().begin(), p_end = getOntology().end(); p != p_end; ++p ) if ( !LC->local(*p) ) Result.push_back(*p); return Result; } //****************************************** //* Initialization //****************************************** bool ReasoningKernel :: initOptions ( void ) { // register all possible options used in FaCT++ Kernel // options for TBox // register "useRelevantOnly" option if ( KernelOptions.RegisterOption ( "useRelevantOnly", "Option 'useRelevantOnly' is used when creating internal DAG representation for externally given TBox. " "If true, DAG contains only concepts, relevant to query. It is safe to leave this option false.", ifOption::iotBool, "false" ) ) return true; // register "dumpQuery" option -- 11-08-04 if ( KernelOptions.RegisterOption ( "dumpQuery", "Option 'dumpQuery' dumps sub-TBox relevant to given satisfiability/subsumption query.", ifOption::iotBool, "false" ) ) return true; // register "absorptionFlags" option (04/05/2005) if ( KernelOptions.RegisterOption ( "absorptionFlags", "Option 'absorptionFlags' sets up absorption process for general axioms. " "It text field of arbitrary length; every symbol means the absorption action: " "(B)ottom Absorption), (T)op absorption, (E)quivalent concepts replacement, (C)oncept absorption, " "(N)egated concept absorption, (F)orall expression replacement, (R)ole absorption, (S)plit", ifOption::iotText, "BTECFSR" ) ) return true; // register "alwaysPreferEquals" option (26/01/2006) if ( KernelOptions.RegisterOption ( "alwaysPreferEquals", "Option 'alwaysPreferEquals' allows user to enforce usage of C=D definition instead of C[=D " "during absorption, even if implication appeares earlier in stream of axioms.", ifOption::iotBool, "true" ) ) return true; // register "useSpecialDomains" option (25/10/2011) if ( KernelOptions.RegisterOption ( "useSpecialDomains", "Option 'useSpecialDomains' (development) controls the special processing of R&D for non-simple roles. " "Should always be set to true.", ifOption::iotBool, "true" ) ) return true; // options for DLDag // register "orSortSub" option (20/12/2004) if ( KernelOptions.RegisterOption ( "orSortSub", "Option 'orSortSub' define the sorting order of OR vertices in the DAG used in subsumption tests. " "Option has form of string 'Mop', where 'M' is a sort field (could be 'D' for depth, 'S' for size, 'F' " "for frequency, and '0' for no sorting), 'o' is a order field (could be 'a' for ascending and 'd' " "for descending mode), and 'p' is a preference field (could be 'p' for preferencing non-generating " "rules and 'n' for not doing so).", ifOption::iotText, "0" ) ) return true; // register "orSortSat" option (20/12/2004) if ( KernelOptions.RegisterOption ( "orSortSat", "Option 'orSortSat' define the sorting order of OR vertices in the DAG used in satisfiability tests " "(used mostly in caching). Option has form of string 'Mop', see orSortSub for details.", ifOption::iotText, "0" ) ) return true; // options for ToDoTable // register "IAOEFLG" option if ( KernelOptions.RegisterOption ( "IAOEFLG", "Option 'IAOEFLG' define the priorities of different operations in TODO list. Possible values are " "7-digit strings with ony possible digit are 0-6. The digits on the places 1, 2, ..., 7 are for " "priority of Id, And, Or, Exists, Forall, LE and GE operations respectively. The smaller number means " "the higher priority. All other constructions (TOP, BOTTOM, etc) has priority 0.", ifOption::iotText, "1263005" ) ) return true; // options for Reasoner // register "useSemanticBranching" option if ( KernelOptions.RegisterOption ( "useSemanticBranching", "Option 'useSemanticBranching' switch semantic branching on and off. The usage of semantic branching " "usually leads to faster reasoning, but sometime could give small overhead.", ifOption::iotBool, "true" ) ) return true; // register "useBackjumping" option if ( KernelOptions.RegisterOption ( "useBackjumping", "Option 'useBackjumping' switch backjumping on and off. The usage of backjumping " "usually leads to much faster reasoning.", ifOption::iotBool, "true" ) ) return true; // register "testTimeout" option -- 21/08/09 if ( KernelOptions.RegisterOption ( "testTimeout", "Option 'testTimeout' sets timeout for a single reasoning test in milliseconds.", ifOption::iotInt, "0" ) ) return true; // options for Blocking // register "useLazyBlocking" option -- 08-03-04 if ( KernelOptions.RegisterOption ( "useLazyBlocking", "Option 'useLazyBlocking' makes checking of blocking status as small as possible. This greatly " "increase speed of reasoning.", ifOption::iotBool, "true" ) ) return true; // register "useAnywhereBlocking" option (18/08/2008) if ( KernelOptions.RegisterOption ( "useAnywhereBlocking", "Option 'useAnywhereBlocking' allow user to choose between Anywhere and Ancestor blocking.", ifOption::iotBool, "true" ) ) return true; // register "skipBeforeBlock" option (28/02/2009) if ( KernelOptions.RegisterOption ( "skipBeforeBlock", "Internal use only. Option 'skipBeforeBlock' allow user to skip given number of nodes before make a block.", ifOption::iotInt, "0" ) ) return true; // options for Taxonomy // register "useCompletelyDefined" option if ( KernelOptions.RegisterOption ( "useCompletelyDefined", "Option 'useCompletelyDefined' leads to simpler Taxonomy creation if TBox contains no non-primitive " "concepts. Unfortunately, it is quite rare case.", ifOption::iotBool, "true" ) ) return true; // options for testing // register "checkAD" option (24/02/2012) if ( KernelOptions.RegisterOption ( "checkAD", "Option 'checkAD' forces FaCT++ to create the AD and exit instead of performing classification", ifOption::iotBool, "false" ) ) return true; // register "useELReasoner" option (24/02/2012) if ( KernelOptions.RegisterOption ( "useELReasoner", "Option 'useELReasoner' forces FaCT++ to use the EL reasoner and exit instead of performing classification", ifOption::iotBool, "false" ) ) return true; // all was registered OK return false; } FaCTpp-src-v1.6.2~dfsg/src/Kernel/tProgressMonitor.h0000644000000000000000000000304712112642405021071 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2006-2010 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef TPROGRESSMONITOR_H #define TPROGRESSMONITOR_H #include "globaldef.h" /// progress monitor and canceller for the classification class TProgressMonitor { public: /// empty c'tor TProgressMonitor ( void ) {} /// empty d'tor virtual ~TProgressMonitor ( void ) {} // interface /// informs about beginning of classification with number of concepts to be classified virtual void setClassificationStarted ( unsigned int nConcepts ATTR_UNUSED ) {} /// informs about beginning of classification of a given CONCEPT virtual void nextClass ( void ) {} /// informs that the reasoning is done virtual void setFinished ( void ) {} // @return true iff reasoner have to be stopped virtual bool isCancelled ( void ) { return false; } }; // TProgressMonitor #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/dlCompletionTreeArc.h0000644000000000000000000001170312112642405021426 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2009 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef _DLCOMPLETIONTREEARC_H #define _DLCOMPLETIONTREEARC_H #include #include "globaldef.h" #include "DeletelessAllocator.h" #include "DepSet.h" #include "tRole.h" #include "tRestorer.h" //#include "SmallObj.h" class DlCompletionTree; class DlCompletionTreeArc//: public Loki::SmallObject<> { friend class DlCompletionGraph; public: // external type definitions /// type for the edges allocator typedef DeletelessAllocator EdgeAllocator; protected: // members /// pointer to "to" node DlCompletionTree* Node; /// role, labelling given arc const TRole* Role; /// dep-set of the arc DepSet depSet; /// pointer to reverse arc DlCompletionTreeArc* Reverse; /// true if the edge going from a predecessor to a successor bool SuccEdge; private: // no copy /// init an arc with R as a label and NODE on given LEVEL; use it inside MAKEARCS only void init ( const TRole* role, const DepSet& dep, DlCompletionTree* node ) { Role = role; depSet = dep; Node = node; Reverse = NULL; } /// no copy c'tor DlCompletionTreeArc ( const DlCompletionTreeArc& v ); /// no assignment DlCompletionTreeArc& operator = ( const DlCompletionTreeArc& v ); protected: // classes /// class for restoring edge class TCTEdgeRestorer: public TRestorer { protected: DlCompletionTreeArc* p; const TRole* r; public: TCTEdgeRestorer ( DlCompletionTreeArc* q ) : p(q), r(q->Role) {} virtual ~TCTEdgeRestorer ( void ) {} void restore ( void ) { p->Role = r; p->Reverse->Role = r->inverse(); } }; // TCTEdgeRestorer /// class for restoring dep-set class TCTEdgeDepRestorer: public TRestorer { protected: DlCompletionTreeArc* p; DepSet dep; public: TCTEdgeDepRestorer ( DlCompletionTreeArc* q ) : p(q), dep(q->getDep()) {} virtual ~TCTEdgeDepRestorer ( void ) {} void restore ( void ) { p->depSet = dep; } }; // TCTEdgeDepRestorer protected: // methods /// set given arc as a reverse of current void setReverse ( DlCompletionTreeArc* v ) { Reverse = v; v->Reverse = this; } public: // interface /// empty c'tor DlCompletionTreeArc ( void ) : SuccEdge(true) {} /// d'tor ~DlCompletionTreeArc ( void ) {} /// get label of the edge const TRole* getRole ( void ) const { return Role; } /// get dep-set of the edge const DepSet& getDep ( void ) const { return depSet; } /// set the successor field void setSuccEdge ( bool val ) { SuccEdge = val; } /// @return true if the edge is the successor one bool isSuccEdge ( void ) const { return SuccEdge; } /// @return true if the edge is the predecessor one bool isPredEdge ( void ) const { return !SuccEdge; } /// get (RW) access to the end of arc DlCompletionTree* getArcEnd ( void ) const { return Node; } /// get access to reverse arc DlCompletionTreeArc* getReverse ( void ) const { return Reverse; } /// check if arc is labelled by a super-role of PROLE bool isNeighbour ( const TRole* pRole ) const { return !isIBlocked() && ( *pRole >= *getRole() ); } /// same as above; fills DEP with current DEPSET if so bool isNeighbour ( const TRole* pRole, DepSet& dep ) const { if ( isNeighbour(pRole) ) { dep = depSet; return true; } return false; } /// is arc merged to another bool isIBlocked ( void ) const { return (Role == NULL); } /// check whether the edge is reflexive bool isReflexiveEdge ( void ) const { return getArcEnd() == getReverse()->getArcEnd(); } //---------------------------------------------- // saving/restoring //---------------------------------------------- /// save and invalidate arc (together with reverse arc) TRestorer* save ( void ) { if ( Role == NULL ) // don't invalidate edge twice return NULL; TRestorer* ret = new TCTEdgeRestorer(this); Role = NULL; Reverse->Role = NULL; return ret; } /// add dep-set to an edge; return restorer TRestorer* addDep ( const DepSet& dep ) { if ( dep.empty() ) return NULL; TRestorer* ret = new TCTEdgeDepRestorer(this); depSet.add(dep); return ret; } // output /// print current arc void Print ( std::ostream& o ) const { o << "<" << ( isIBlocked() ? "-" : Role->getName() ) << depSet << ">"; } }; // DlCompletionTreeArc #endif // _DLCOMPLETIONTREEARC_H FaCTpp-src-v1.6.2~dfsg/src/Kernel/tSplitVars.h0000644000000000000000000000562712112642405017652 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2011 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef TSPLITVARS_H #define TSPLITVARS_H #include #include #include "tSignature.h" #include "tDLAxiom.h" // forward declarations class TDLConceptName; class TConcept; /// this is to keep the track of new vars/axioms for C >< C0, C1, ..., Cn struct TSplitVar { // types struct Entry { const TDLConceptName* name; // entry name TConcept* C; // internal name TSignature sig; std::set Module; }; typedef std::vector::iterator iterator; // members const TDLConceptName* oldName; // name of split concept TConcept* C; // split concept itself std::vector Entries; // methods void addEntry ( const TDLConceptName* name, const TSignature& sig, const std::set& mod ) { Entry e; e.name = name; e.C = NULL; e.sig = sig; e.Module = mod; Entries.push_back(e); } iterator begin ( void ) { return Entries.begin(); } iterator end ( void ) { return Entries.end(); } }; // TSplitVar /// set of all known var splits with access by name class TSplitVars { public: // type interface typedef std::vector::iterator iterator; protected: // members std::vector Base; std::map Index; public: // interface /// empty c'tor TSplitVars ( void ) {} /// d'tor: delete all split vars ~TSplitVars ( void ) { for ( iterator p = Base.begin(), p_end = Base.end(); p != p_end; ++p ) delete *p; } /// @return true iff the NAME has split in the set bool hasCN ( const TDLConceptName* name ) const { return Index.find(name) != Index.end(); } /// @return split corresponding to given name; only correct for known names TSplitVar* get ( const TDLConceptName* name ) { return Index[name]; } /// put SPLIT into the set corresponding to NAME void set ( const TDLConceptName* name, TSplitVar* split ) { Index[name] = split; Base.push_back(split); } /// access to the 1st element iterator begin ( void ) { return Base.begin(); } /// access to the last element iterator end ( void ) { return Base.end(); } /// @return true iff split-set is empty bool empty ( void ) const { return Base.empty(); } }; // TSplitVars #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/eFPPCantRegName.h0000644000000000000000000000304112112642405020362 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2006-2013 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef EFPPCANTREGNAME_H #define EFPPCANTREGNAME_H #include #include "eFaCTPlusPlus.h" /// exception thrown in case name can't be registered class EFPPCantRegName: public EFaCTPlusPlus { private: // members /// error string std::string str; /// name string std::string Name; public: // interface /// c'tor: create an output string EFPPCantRegName ( const std::string& name, const std::string& type ) : EFaCTPlusPlus() , Name(name) { str = "Unable to register '"; str += name; str += "' as a "; str += type; reason = str.c_str(); } /// empty d'tor virtual ~EFPPCantRegName ( void ) throw() {} /// get access to the unregistered name const char* getName ( void ) const { return Name.c_str(); } }; // EFPPCantRegName #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/tKBFlags.h0000644000000000000000000000247012112642405017165 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2006 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef _TKBFLAGS_H #define _TKBFLAGS_H #include "flags.h" /// flags that reflects KB structure: GCIs, etc class TKBFlags: public Flags { public: // interface /// empty c'tor TKBFlags ( void ) : Flags() {} /// copy c'tor TKBFlags ( const TKBFlags& flags ) : Flags(flags) {} /// empty d'tor ~TKBFlags ( void ) {} /// register flag for GCIs FPP_ADD_FLAG(GCI,0x1); /// register flag for Range and Domain axioms FPP_ADD_FLAG(RnD,0x2); /// register flag for Reflexive roles FPP_ADD_FLAG(Reflexive,0x4); }; // TKBFlags #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/RAutomaton.cpp0000644000000000000000000001052512112642405020154 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2006-2012 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "RAutomaton.h" #include "tRole.h" /// check whether transition is TopRole one bool RATransition :: isTop ( void ) const { return label.size() == 1 && unlikely(label.front()->isTop()); } /// set up state transitions: no more additions to the structure void RAStateTransitions :: setup ( RAState state, unsigned int nRoles, bool data ) { from = state; DataRole = data; ApplicableRoles.ensureMaxSetSize(nRoles); // fills the set of recognisable roles for ( const_iterator p = begin(), p_end = end(); p != p_end; ++p ) for ( RATransition::const_iterator q = (*p)->begin(), q_end = (*p)->end(); q != q_end; ++q ) ApplicableRoles.add((*q)->getIndex()); } /// add information from TRANS to existing transition between the same states. @return false if no such transition found bool RAStateTransitions :: addToExisting ( const RATransition* trans ) { RAState to = trans->final(); bool tEmpty = trans->empty(); for ( iterator p = Base.begin(), p_end = Base.end(); p != p_end; ++p ) if ( (*p)->final() == to && (*p)->empty() == tEmpty ) { // found existing transition (*p)->addIfNew(*trans); return true; } // no transition from->to found return false; } void RATransition::Print ( std::ostream& o, RAState from ) const { o << "\n" << from << " -- "; if ( empty() ) o << "e"; else { const_iterator p = label.begin(); o << '"' << (*p)->getName() << '"'; for ( ++p; p != label.end(); ++p ) o << ",\"" << (*p)->getName() << '"'; } o << " -> " << final(); } void RoleAutomaton :: addCopy ( const RoleAutomaton& RA ) { for ( RAState i = 0; i < RA.size(); ++i ) { RAState from = map[i]; RAStateTransitions& RST = Base[from]; const RAStateTransitions& RSTOrig = RA[i]; if ( RSTOrig.empty() ) continue; for ( RAStateTransitions::const_iterator p = RSTOrig.begin(), p_end = RSTOrig.end(); p != p_end; ++p ) { RAState to = (*p)->final(); RATransition* trans = new RATransition(map[to]); checkTransition ( from, trans->final() ); trans->add(**p); // try to merge transitions going to the original final state if ( to == 1 && RST.addToExisting(trans) ) delete trans; else RST.add(trans); } } } /// init internal map according to RA size, with new initial state from chainState and final (FRA) states void RoleAutomaton :: initMap ( unsigned int RASize, RAState fRA ) { map.resize(RASize); // new state in the automaton RAState newState = size()-1; // fill initial state; it is always known in the automata map[0] = iRA; // fills the final state; if it is not known -- adjust newState if ( fRA >= size() ) { fRA = size(); // make sure we don't create an extra unused state ++newState; } map[1] = fRA; // check transitions as it may turns out to be a single transition checkTransition ( iRA, fRA ); // set new initial state iRA = fRA; // fills the rest of map for ( unsigned int i = 2; i < RASize; ++i ) map[i] = ++newState; // reserve enough space for the new automaton ensureState(newState); } /// add an Automaton to the chain that would start from the iRA; OSAFE shows the safety of a previous automaton in a chain bool RoleAutomaton :: addToChain ( const RoleAutomaton& RA, bool oSafe, RAState fRA ) { fpp_assert(!isCompleted()); bool needFinalTrans = ( fRA < size() && !RA.isOSafe() ); // we can skip transition if chaining automata are i- and o-safe if ( !oSafe && !RA.isISafe() ) nextChainTransition(newState()); // check whether we need an output transition initMap ( RA.size(), needFinalTrans ? size() : fRA ); addCopy(RA); if ( needFinalTrans ) nextChainTransition(fRA); return RA.isOSafe(); } FaCTpp-src-v1.6.2~dfsg/src/Kernel/modelCacheIan.h0000644000000000000000000001747112112642405020213 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2010 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef MODELCACHEIAN_H #define MODELCACHEIAN_H #include "modelCacheSingleton.h" #include "dlCompletionTree.h" #include "dlDag.h" #include "tSetAsTree.h" /** model caching implementation of Ian's algorithms. Very fast cache check, but less precise than AsTree one. */ class modelCacheIan: public modelCacheInterface { // FIXME!! for now only friend class DLConceptTaxonomy; protected: // types /// define the type of an index set typedef TSetAsTree IndexSet; /// node label iterator typedef DlCompletionTree::const_label_iterator l_iterator; /// edges iterator typedef DlCompletionTree::const_edge_iterator e_iterator; protected: // members // sets for the cache /// named concepts that appears positively det-lly in a root node of a cache IndexSet posDConcepts; /// named concepts that appears positively non-det in a root node of a cache IndexSet posNConcepts; /// named concepts that appears negatively det-lly in a root node of a cache IndexSet negDConcepts; /// named concepts that appears negatively non-det in a root node of a cache IndexSet negNConcepts; #ifdef RKG_USE_SIMPLE_RULES /// extra det-lly concepts that are (partial) Simple Rule applications IndexSet extraDConcepts; /// extra non-det concepts that are (partial) Simple Rule applications IndexSet extraNConcepts; #endif /// role names that are labels of the outgoing edges from the root node IndexSet existsRoles; /// role names that appears in the \A restrictions in the root node IndexSet forallRoles; /// role names that appears in the atmost restrictions in the root node IndexSet funcRoles; /// current state of cache model; recalculates on every change modelCacheState curState; protected: // methods /// add single concept from label to cache void processConcept ( const DLVertex& cur, bool pos, bool det ); /// add all roles that are accepted by an automaton from a given entry void processAutomaton ( const DLVertex& cur ); /// process CT label in given interval; set Deterministic accordingly void processLabelInterval ( const DLDag& DLHeap, l_iterator start, l_iterator end ) { for ( l_iterator p = start; p != end; ++p ) processConcept ( DLHeap[*p], isPositive(p->bp()), p->getDep().empty() ); } /// fills cache sets by tree->Label; set Deterministic accordingly void initCacheByLabel ( const DLDag& DLHeap, const DlCompletionTree* pCT ) { processLabelInterval ( DLHeap, pCT->beginl_sc(), pCT->endl_sc() ); processLabelInterval ( DLHeap, pCT->beginl_cc(), pCT->endl_cc() ); } /// adds role to exists- and func-role if necessary void addRoleToCache ( const TRole* R ) { existsRoles.insert(R->index()); if ( R->isTopFunc() ) // all other top-funcs would be added separately funcRoles.insert(R->index()); } /// adds role (and all its super-roles) to exists- and funcRoles void addExistsRole ( const TRole* R ) { addRoleToCache(R); for ( TRole::const_iterator r = R->begin_anc(), r_end = R->end_anc(); r != r_end; ++r ) addRoleToCache(*r); } // access to the arrays /// get RW access to D-concepts wrt polarity IndexSet& getDConcepts ( bool pos ) { return pos ? posDConcepts : negDConcepts; } /// get RW access to N-concepts wrt polarity IndexSet& getNConcepts ( bool pos ) { return pos ? posNConcepts : negNConcepts; } /// get RO access to D-concepts wrt polarity const IndexSet& getDConcepts ( bool pos ) const { return pos ? posDConcepts : negDConcepts; } /// get RO access to N-concepts wrt polarity const IndexSet& getNConcepts ( bool pos ) const { return pos ? posNConcepts : negNConcepts; } #ifdef RKG_USE_SIMPLE_RULES /// get RW access to extra concepts wrt deterministic flag IndexSet& getExtra ( bool det ) { return det ? extraDConcepts : extraNConcepts; } /// get RO access to extra concepts wrt deterministic flag const IndexSet& getExtra ( bool det ) const { return det ? extraDConcepts : extraNConcepts; } #endif // merge support /// implementation of merging with Singleton cache type modelCacheState isMergableSingleton ( unsigned int Singleton, bool pos ) const; /// implementation of merging with Ian's cache type modelCacheState isMergableIan ( const modelCacheIan* p ) const; /// actual merge with a singleton cache void mergeSingleton ( unsigned int Singleton, bool pos ); /// actual merge with an Ian's cache void mergeIan ( const modelCacheIan* p ); /// log given concept set void logCacheSet ( const IndexSet& s ) const; public: /// Create cache model of given CompletionTree using given HEAP modelCacheIan ( const DLDag& heap, const DlCompletionTree* p, bool flagNominals, unsigned int nC, unsigned int nR ) : modelCacheInterface(flagNominals) , posDConcepts(nC) , posNConcepts(nC) , negDConcepts(nC) , negNConcepts(nC) # ifdef RKG_USE_SIMPLE_RULES , extraDConcepts(nC) , extraNConcepts(nC) # endif , existsRoles(nR) , forallRoles(nR) , funcRoles(nR) { initCacheByLabel ( heap, p ); initRolesFromArcs(p); } /// empty c'tor modelCacheIan ( bool flagNominals, unsigned int nC, unsigned int nR ) : modelCacheInterface(flagNominals) , posDConcepts(nC) , posNConcepts(nC) , negDConcepts(nC) , negNConcepts(nC) # ifdef RKG_USE_SIMPLE_RULES , extraDConcepts(nC) , extraNConcepts(nC) # endif , existsRoles(nR) , forallRoles(nR) , funcRoles(nR) , curState(csValid) {} /// copy c'tor modelCacheIan ( const modelCacheIan& m ) : modelCacheInterface(m.hasNominalNode) , posDConcepts(m.posDConcepts) , posNConcepts(m.posNConcepts) , negDConcepts(m.negDConcepts) , negNConcepts(m.negNConcepts) # ifdef RKG_USE_SIMPLE_RULES , extraDConcepts(m.extraDConcepts) , extraNConcepts(m.extraNConcepts) # endif , existsRoles(m.existsRoles) , forallRoles(m.forallRoles) , funcRoles(m.funcRoles) , curState(m.getState()) {} /// create a clone of the given cache modelCacheIan* clone ( void ) const { return new modelCacheIan(*this); } /// empty d'tor virtual ~modelCacheIan ( void ) {} /** Check the internal state of the model cache. The check is very fast. Does NOT return csUnknown */ virtual modelCacheState getState ( void ) const { return curState; } /// init existRoles from arcs; can be used to create pseudo-cache with deps of CT edges void initRolesFromArcs ( const DlCompletionTree* pCT ) { for ( e_iterator q = pCT->begin(), q_end = pCT->end(); q < q_end; ++q ) if ( !(*q)->isIBlocked() ) addExistsRole ( (*q)->getRole() ); curState = csValid; } /// clear the cache void clear ( void ); /// check whether two caches can be merged; @return state of "merged" model modelCacheState canMerge ( const modelCacheInterface* p ) const; /// Merge given model to current one; return state of the merged model modelCacheState merge ( const modelCacheInterface* p ); /// Get the tag identifying the cache type virtual modelCacheType getCacheType ( void ) const { return mctIan; } /// get type of cache (deep or shallow) virtual bool shallowCache ( void ) const { return existsRoles.empty(); } #ifdef _USE_LOGGING /// log this cache entry (with given level) virtual void logCacheEntry ( unsigned int level ) const; #endif }; // modelCacheIan #endif FaCTpp-src-v1.6.2~dfsg/src/Kernel/SaveLoad.cpp0000644000000000000000000004333512112642405017566 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2008-2012 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ //------------------------------------------------------- //-- Saving/restoring internal state of the FaCT++ //------------------------------------------------------- #include #include "eFPPSaveLoad.h" #include "Kernel.h" using namespace std; const char* ReasoningKernel :: InternalStateFileHeader = "FaCT++InternalStateDump1.0"; const int bytesInInt = sizeof(int); static inline void expectChar ( istream& i, const char C ) { char c; i >> c; if ( c != C ) throw EFPPSaveLoad(C); } #if 0 // FIXME!! try to avoid recursion later on static inline void saveUIntAux ( ostream& o, unsigned int n, const int rest ) { if ( rest > 1 ) saveUIntAux ( o, n/256, rest-1 ); o << (unsigned char)n%256; } static inline void saveUInt ( ostream& o, unsigned int n ) { saveUIntAux ( o, n, bytesInInt ); } static inline void saveSInt ( ostream& o, int n ) { saveUInt(o,n); } static inline unsigned int loadUInt ( istream& i ) { static unsigned int ret = 0; unsigned char byte; for ( int j = bytesInInt-1; j >= 0; --j ) { i >> byte; ret *= 256; ret += byte; } return ret; } static inline int loadSInt ( istream& i ) { return (int)loadUInt(i); } #else static inline void saveUInt ( ostream& o, unsigned int n ) { o << "(" << n << ")"; } static inline void saveSInt ( ostream& o, int n ) { o << "(" << n << ")"; } static inline unsigned int loadUInt ( istream& i ) { unsigned int ret; expectChar(i,'('); i >> ret; expectChar(i,')'); return ret; } static inline int loadSInt ( istream& i ) { int ret; expectChar(i,'('); i >> ret; expectChar(i,')'); return ret; } #endif // 0 //---------------------------------------------------------- //-- Global structures used for the methods below //---------------------------------------------------------- template class PointerMap { protected: // types /// map int->pointer type typedef std::vector I2PMap; /// map pointer->int type typedef std::map P2IMap; protected: // members /// map i -> pointer I2PMap i2p; /// map pointer -> i P2IMap p2i; /// ID of the last recorded NE unsigned int last; protected: // methods /// @return true if given pointer present in the map bool in ( Pointer p ) const { return p2i.find(p) != p2i.end(); } /// @return true if given index present in the map bool in ( unsigned int i ) const { return i < last; } /// @throw an exception if P is not registered void ensure ( Pointer p ) const { if ( !in(p) ) throw EFPPSaveLoad("Cannot save unregistered pointer"); } /// @throw an exception if I is not registered void ensure ( unsigned int i ) const { if ( !in(i) ) throw EFPPSaveLoad("Cannot load unregistered index"); } public: // interface /// empty c'tor PointerMap ( void ) : last(0) {} /// empty d'tor ~PointerMap ( void ) { clear(); } /// clear the maps void clear ( void ) { i2p.clear(); p2i.clear(); last = 0; } // populate the map /// add an entry void add ( Pointer p ) { if ( in(p) ) return; i2p.push_back(p); p2i[p] = last++; } /// add entries from the [begin,end) range template void add ( Iterator begin, Iterator end ) { for ( ; begin != end; ++begin ) add(*begin); } // access to the mapped element /// get the NE by index I Pointer getP ( unsigned int i ) { ensure(i); return i2p[i]; } /// get the index by NE P unsigned int getI ( Pointer p ) { ensure(p); return p2i[p]; } }; // PointerMap // int -> named entry map for the current taxonomy PointerMap neMap; // uint -> TaxonomyVertex map to update the taxonomy PointerMap tvMap; //---------------------------------------------------------- //-- Implementation of the Kernel methods (Kernel.h) //---------------------------------------------------------- #undef CHECK_FILE_STATE #define CHECK_FILE_STATE() if ( !o.good() ) throw(EFPPSaveLoad(name,/*save=*/true)) void ReasoningKernel :: Save ( const char* name ) const { std::ofstream o(name); CHECK_FILE_STATE(); SaveHeader(o); CHECK_FILE_STATE(); SaveOptions(o); CHECK_FILE_STATE(); SaveKB(o); CHECK_FILE_STATE(); } #undef CHECK_FILE_STATE #define CHECK_FILE_STATE() if ( !i.good() ) throw(EFPPSaveLoad(name,/*save=*/false)) void ReasoningKernel :: Load ( const char* name ) { std::ifstream i(name); CHECK_FILE_STATE(); releaseKB(); // we'll start a new one if necessary if ( LoadHeader(i) ) throw(EFPPSaveLoad(name,/*save=*/false)); CHECK_FILE_STATE(); LoadOptions(i); CHECK_FILE_STATE(); LoadKB(i); CHECK_FILE_STATE(); } //-- save/load header (Kernel.h) void ReasoningKernel :: SaveHeader ( ostream& o ) const { o << InternalStateFileHeader << "\n" << Version << "\n" << bytesInInt << "\n"; } bool ReasoningKernel :: LoadHeader ( istream& i ) { string str; i >> str; if ( str != InternalStateFileHeader ) return true; i >> str; // FIXME!! we don't check version equivalence for now // if ( str != Version ) // return true; int n; i >> n; if ( n != bytesInInt ) return true; return false; } //-- save/load options (Kernel.h) void ReasoningKernel :: SaveOptions ( ostream& o ) const { o << "Options\n"; } void ReasoningKernel :: LoadOptions ( istream& i ) { std::string options; i >> options; } //-- save/load KB (Kernel.h) void ReasoningKernel :: SaveKB ( ostream& o ) const { saveUInt(o,(unsigned int)getStatus()); switch ( getStatus() ) { case kbEmpty: // nothing to do return; case kbLoading: throw EFPPSaveLoad("Can't load internal state of the unclassified reasoner"); default: getTBox()->Save(o); break; } } void ReasoningKernel :: LoadKB ( istream& i ) { KBStatus status = (KBStatus)loadUInt(i); initCacheAndFlags(); // will be done if ( status == kbEmpty ) return; newKB(); getTBox()->Load(i,status); } //---------------------------------------------------------- //-- Implementation of the TBox methods (dlTBox.h) //---------------------------------------------------------- void TBox :: Save ( ostream& o ) const { tvMap.clear(); neMap.clear(); neMap.add(pBottom); neMap.add(pTop); o << "\nC"; Concepts.Save(o); o << "\nI"; Individuals.Save(o); o << "\nOR"; ORM.Save(o); o << "\nDR"; DRM.Save(o); o << "\nD"; DLHeap.Save(o); if ( Status > kbCChecked ) { o << "\nCT"; pTax->Save(o); } } void TBox :: Load ( istream& i, KBStatus status ) { Status = status; string KB; tvMap.clear(); neMap.clear(); neMap.add(pBottom); neMap.add(pTop); expectChar(i,'C'); Concepts.Load(i); expectChar(i,'I'); Individuals.Load(i); expectChar(i,'O'); expectChar(i,'R'); ORM.Load(i); expectChar(i,'D'); expectChar(i,'R'); DRM.Load(i); expectChar(i,'D'); DLHeap.Load(i); if ( Status > kbCChecked ) { pTax->setBottomUp(GCIs); expectChar(i,'C'); expectChar(i,'T'); pTax->Load(i); } } //---------------------------------------------------------- //-- Implementation of the TNECollection methods (tNECollection.h) //---------------------------------------------------------- /// Save all the objects in the collection template void TNECollection :: Save ( ostream& o ) const { const_iterator p, p_beg = begin(), p_end = end(); // get the max length of the identifier in the collection unsigned int maxLength = 0, curLength; for ( p = p_beg; p < p_end; ++p ) if ( maxLength < (curLength = strlen((*p)->getName())) ) maxLength = curLength; // save number of entries and max length of the entry saveUInt(o,size()); saveUInt(o,maxLength); // register all entries in the global map neMap.add ( p_beg, p_end ); // save names of all entries for ( p = p_beg; p < p_end; ++p ) o << (*p)->getName() << "\n"; // save the entries itself for ( p = p_beg; p < p_end; ++p ) (*p)->Save(o); } /// Load all the objects into the collection template void TNECollection :: Load ( istream& i ) { // sanity check: Load shall be done for the empty collection and only once fpp_assert ( size() == 0 ); unsigned int collSize, maxLength; collSize = loadUInt(i); maxLength = loadUInt(i); ++maxLength; char* name = new char[maxLength]; // register all the named entries for ( unsigned int j = 0; j < collSize; ++j ) { i.getline ( name, maxLength, '\n' ); get(name); } delete [] name; // register all entries in the global map neMap.add ( begin(), end() ); // load all the named entries for ( iterator p = begin(); p < end(); ++p ) (*p)->Load(i); } //---------------------------------------------------------- //-- Implementation of the TNamedEntry methods (tNamedEntry.h) //---------------------------------------------------------- void TNamedEntry :: Save ( ostream& o ) const { saveUInt(o,getAllFlags()); } void TNamedEntry :: Load ( istream& i ) { setAllFlags(loadUInt(i)); } //---------------------------------------------------------- //-- Implementation of the TConcept methods (tConcept.h) //---------------------------------------------------------- void TConcept :: Save ( ostream& o ) const { ClassifiableEntry::Save(o); saveUInt(o,(unsigned int)classTag); saveUInt(o,tsDepth); saveSInt(o,pName); saveSInt(o,pBody); saveUInt(o,posFeatures.getAllFlags()); saveUInt(o,negFeatures.getAllFlags()); // ERSet.Save(o); } void TConcept :: Load ( istream& i ) { ClassifiableEntry::Load(i); classTag = CTTag(loadUInt(i)); tsDepth = loadUInt(i); pName = loadSInt(i); pBody = loadSInt(i); posFeatures.setAllFlags(loadUInt(i)); negFeatures.setAllFlags(loadUInt(i)); // ERSet.Load(i); } //---------------------------------------------------------- //-- Implementation of the TIndividual methods (tIndividual.h) //---------------------------------------------------------- void TIndividual :: Save ( ostream& o ) const { TConcept::Save(o); // RelatedIndex.Save(o); } void TIndividual :: Load ( istream& i ) { TConcept::Load(i); // RelatedIndex.Load(i); } //---------------------------------------------------------- //-- Implementation of the RoleMaster methods (RoleMaster.h) //---------------------------------------------------------- void RoleMaster :: Save ( ostream& o ) const { const_iterator p, p_beg = begin(), p_end = end(); // get the max length of the identifier in the collection unsigned int maxLength = 0, curLength; for ( p = p_beg; p < p_end; p += 2 ) if ( maxLength < (curLength = strlen((*p)->getName())) ) maxLength = curLength; // save number of entries and max length of the entry saveUInt(o,size()); saveUInt(o,maxLength); // register all entries in the global map neMap.add(const_cast((const ClassifiableEntry*)&emptyRole)); neMap.add(const_cast((const ClassifiableEntry*)&universalRole)); neMap.add ( p_beg, p_end ); // save names of all (non-inverse) entries for ( p = p_beg; p < p_end; p += 2 ) o << (*p)->getName() << "\n"; // save the entries itself for ( p = p_beg; p < p_end; ++p ) (*p)->Save(o); // save the rest of the RM o << "\nRT"; pTax->Save(o); } void RoleMaster :: Load ( istream& i ) { // sanity check: Load shall be done for the empty collection and only once fpp_assert ( size() == 0 ); unsigned int RMSize, maxLength; RMSize = loadUInt(i); maxLength = loadUInt(i); ++maxLength; char* name = new char[maxLength]; // register all the named entries for ( unsigned int j = 0; j < RMSize; ++j ) { i.getline ( name, maxLength, '\n' ); ensureRoleName(name); } delete [] name; // register all entries in the global map neMap.add(&emptyRole); neMap.add(&universalRole); neMap.add ( begin(), end() ); // load all the named entries for ( iterator p = begin(); p < end(); ++p ) (*p)->Load(i); // load the rest of the RM expectChar(i,'R'); expectChar(i,'T'); pTax->Load(i); useUndefinedNames = false; // no names } //---------------------------------------------------------- //-- Implementation of the TRole methods (tRole.h) //---------------------------------------------------------- void TRole :: Save ( ostream& o ) const { ClassifiableEntry::Save(o); } void TRole :: Load ( istream& i ) { ClassifiableEntry::Load(i); } //---------------------------------------------------------- //-- Implementation of the Taxonomy methods (Taxonomy.h) //---------------------------------------------------------- void Taxonomy :: Save ( ostream& o ) const { const_iterator p, p_beg = begin(), p_end = end(); tvMap.clear(); // it would be it's own map for every taxonomy tvMap.add ( p_beg, p_end ); // save number of taxonomy elements saveUInt(o,Graph.size()); o << "\n"; // save labels for all verteces of the taxonomy for ( p = p_beg; p != p_end; ++p ) (*p)->SaveLabel(o); // save the taxonomys hierarchy for ( p = p_beg; p != p_end; ++p ) (*p)->SaveNeighbours(o); } void Taxonomy :: Load ( istream& i ) { unsigned int size = loadUInt(i); tvMap.clear(); Graph.clear(); // both TOP and BOTTOM elements would be load; // create all the verteces and load their labels for ( unsigned int j = 0; j < size; ++j ) { ClassifiableEntry* p = neMap.getP(loadUInt(i)); TaxonomyVertex* v = new TaxonomyVertex(p); Graph.push_back(v); v->LoadLabel(i); tvMap.add(v); } // load the hierarchy for ( iterator p = begin(), p_end = end(); p < p_end; ++p ) (*p)->LoadNeighbours(i); } //---------------------------------------------------------- //-- Implementation of the TaxonomyVertex methods (taxVertex.h) //---------------------------------------------------------- void TaxonomyVertex :: SaveLabel ( ostream& o ) const { saveUInt(o,neMap.getI(const_cast(sample))); saveUInt(o,synonyms.size()); for ( syn_iterator p = begin_syn(), p_end = end_syn(); p < p_end; ++p ) saveUInt(o,neMap.getI(const_cast(*p))); o << "\n"; } void TaxonomyVertex :: LoadLabel ( istream& i ) { // note that sample is already loaded unsigned int size = loadUInt(i); for ( unsigned int j = 0; j < size; ++j ) addSynonym(neMap.getP(loadUInt(i))); } void TaxonomyVertex :: SaveNeighbours ( ostream& o ) const { const_iterator p, p_end; saveUInt(o,neigh(true).size()); for ( p = begin(true), p_end = end(true); p != p_end; ++p ) saveUInt(o,tvMap.getI(*p)); saveUInt(o,neigh(false).size()); for ( p = begin(false), p_end = end(false); p != p_end; ++p ) saveUInt(o,tvMap.getI(*p)); o << "\n"; } void TaxonomyVertex :: LoadNeighbours ( istream& i ) { unsigned int j, size; size = loadUInt(i); for ( j = 0; j < size; ++j ) addNeighbour ( true, tvMap.getP(loadUInt(i)) ); size = loadUInt(i); for ( j = 0; j < size; ++j ) addNeighbour ( false, tvMap.getP(loadUInt(i)) ); } //---------------------------------------------------------- //-- Implementation of the DLDag methods (dlDag.h) //---------------------------------------------------------- void DLDag :: Save ( ostream& o ) const { saveUInt(o,Heap.size()); o << "\n"; // skip fake vertex and TOP for ( unsigned int i = 2; i < Heap.size(); ++i ) Heap[i]->Save(o); } void DLDag :: Load ( istream& i ) { unsigned int j, size; size = loadUInt(i); for ( j = 2; j < size; ++j ) { DagTag tag = static_cast(loadUInt(i)); DLVertex* v = new DLVertex(tag); v->Load(i); directAdd(v); // FIXME!! think about ..AndCache } // only reasoning now -- no cache useDLVCache = false; } //---------------------------------------------------------- //-- Implementation of the DLVertex methods (dlVertex.h) //---------------------------------------------------------- void DLVertex :: Save ( ostream& o ) const { saveUInt(o,static_cast(Type())); // FIXME!! save Cache if applicable; this will help reasoning switch ( Type() ) { case dtBad: case dtTop: // can't be S/L default: fpp_unreachable(); break; case dtAnd: saveUInt(o,Child.size()); for ( const_iterator p = begin(); p != end(); ++p ) saveSInt(o,*p); break; case dtLE: saveUInt(o,neMap.getI(const_cast(Role))); saveSInt(o,getC()); saveUInt(o,getNumberLE()); break; case dtForall: saveUInt(o,neMap.getI(const_cast(Role))); saveSInt(o,getC()); break; case dtIrr: saveUInt(o,neMap.getI(const_cast(Role))); break; case dtPConcept: case dtNConcept: case dtPSingleton: case dtNSingleton: saveUInt(o,neMap.getI(static_cast(Concept))); saveSInt(o,getC()); break; case dtDataType: case dtDataValue: case dtDataExpr: break; // FIXME!! for now } o << "\n"; } void DLVertex :: Load ( istream& i ) { // now OP is already saved // FIXME!! load Cache if applicable; this will help reasoning switch ( Type() ) { case dtBad: case dtTop: // can't be S/L default: fpp_unreachable(); break; case dtAnd: { unsigned int size = loadUInt(i); for ( unsigned int j = 0; j < size; ++j ) Child.push_back(loadSInt(i)); break; } case dtLE: Role = static_cast(neMap.getP(loadUInt(i))); setChild(loadSInt(i)); Child.push_back(loadUInt(i)); break; case dtForall: Role = static_cast(neMap.getP(loadUInt(i))); setChild(loadSInt(i)); break; case dtIrr: Role = static_cast(neMap.getP(loadUInt(i))); break; case dtPConcept: case dtNConcept: case dtPSingleton: case dtNSingleton: setConcept(neMap.getP(loadUInt(i))); setChild(loadSInt(i)); break; case dtDataType: case dtDataValue: case dtDataExpr: break; // FIXME!! for now } } FaCTpp-src-v1.6.2~dfsg/src/Kernel/globaldef.h0000644000000000000000000000423012112642405017443 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2003-2010 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef GLOBALDEF_H #define GLOBALDEF_H // global definitions for FaCT++ Reasoning Kernel // define unused attribute for parameters and (un)likely macro for conditions #if defined(__GNUC__) && (__GNUC__ >= 4) # define ATTR_UNUSED __attribute__((unused)) # define likely(cond) __builtin_expect((cond),1) # define unlikely(cond) __builtin_expect((cond),0) #else # define ATTR_UNUSED # define likely(cond) (cond) # define unlikely(cond) (cond) #endif // uncomment this to have a DAG usage statistics printed //#define RKG_PRINT_DAG_USAGE // uncomment this to have sorted ontology reasoning #define RKG_USE_SORTED_REASONING //#define _USE_LOGGING //#define ENABLE_CHECKING // uncomment this to allow dynamic backjumping //#define RKG_USE_DYNAMIC_BACKJUMPING #ifdef RKG_USE_DYNAMIC_BACKJUMPING // uncomment this to use improves S/R with better quality # define RKG_IMPROVE_SAVE_RESTORE_DEPSET #endif // uncomment this to update role's R&D from super-roles //#define RKG_UPDATE_RND_FROM_SUPERROLES // uncomment this to allow simple rules processing //#define RKG_USE_SIMPLE_RULES // uncomment this to support fairness constraints //#define RKG_USE_FAIRNESS // uncomment the following line if IR is defined as a list of elements in node label #define RKG_IR_IN_NODE_LABEL // this value is used in classes Reasoner, CGraph and RareSaveStack const unsigned int InitBranchingLevelValue = 1; #endif FaCTpp-src-v1.6.2~dfsg/src/Makefile.include0000644000000000000000000001604712112642425017230 0ustar rootroot# global optimisation options GCC_OPT_OPT = -finline-limit=1200 -ffast-math -W -Wall -Wextra -O3 -fomit-frame-pointer -fPIC # GCC 3.3 optimisation options that are not included in -O3 GCC_33_OPT = -ftracer -fgcse-sm # GCC 3.4 optimisation options that are not included in -O3 GCC_34_OPT = $(GCC_33_OPT) -fgcse-las -fpeel-loops # GCC 4.0 optimisation options that are not included in -O3 GCC_40_OPT = $(GCC_34_OPT) -fmodulo-sched -ftree-loop-linear -ftree-loop-im -fweb\ -ftree-loop-ivcanon -fivopts -ftree-vectorize -fvariable-expansion-in-unroller # GCC 4.1 optimisation options that are not included in -O3 GCC_41_OPT = $(GCC_40_OPT) -funsafe-loop-optimizations # GCC 4.2 optimisation options that are not included in -O3 GCC_42_OPT = $(GCC_41_OPT) # GCC 4.3 optimisation options that are not included in -O3 GCC_43_OPT = $(GCC_42_OPT) -fmodulo-sched-allow-regmoves -fipa-cp -fvect-cost-model # GCC 4.4 optimisation options that are not included in -O3 GCC_44_OPT = $(GCC_43_OPT) # define architecture; it will affect file extentions, dynamic flags. # now LINUX, WINDOWS(untested), MACOSX are supported OS = LINUX # ALL_DEF is an external defines GENERAL_DEFINES = $(GCC_OPT_OPT) $(GCC_43_OPT) $(ALL_DEF) #--------------------------------------------------------- # please do not change following lines #--------------------------------------------------------- # Set default goal immediatly, to make it possible to define rules default_goal: all ifdef INTERNAL_LIBRARY override LIBRARY := $(INTERNAL_LIBRARY) endif # tune some parameters depends on OS EXEEXT = LIBEXT = DLLEXT = OS_DEF = # define Linux flags ifeq ($(OS),LINUX) override EXEEXT := override LIBEXT := .a override DLLEXT := .so override OS_DEF := endif #define Mc OS X flags ifeq ($(OS),MACOSX) override EXEEXT := override LIBEXT := .a override DLLEXT := .jnilib override OS_DEF := -mmacosx-version-min=10.4 endif #define Windows flags (untested) ifeq ($(OS),WINDOWS) override EXEEXT := .exe override LIBEXT := .lib override DLLEXT := .dll override OS_DEF := endif # System variables definitions should be expanded immidiately, # either user defines those or not # (The following lines are written because of their ':=' operator) # We can't set default values here: WIs' rules.cvslvk may use += override INCLUDES := $(INCLUDES) override DEFINES := $(DEFINES) $(GENERAL_DEFINES) override LDFLAGS := $(LDFLAGS) override BUILD_DIR := obj $(BUILD_DIR): mkdir -p $(BUILD_DIR) # Set C++ compilers and linker override CXX := g++$(GCC_SUFFIX) $(OS_DEF) # Library building tools ifdef LIBRARY # If LTYPE is 'shared', gcc -shared is used # $(LIBRARY) is library name. ifeq ($(LTYPE),shared) override LIBRARY_NAME := lib$(LIBRARY)$(DLLEXT) endif ifeq ($(LTYPE),static) override LIBRARY_NAME := lib$(LIBRARY)$(LIBEXT) endif endif # ifdef LIBRARY # Split LDFLAGS into -L..., -l... and others override CL_LDFLAGS_DIRS := $(filter -L%,$(LDFLAGS)) override CL_LDFLAGS_LIBS := $(filter -l%,$(LDFLAGS)) override CL_LDFLAGS_OTHER := $(filter-out $(CL_LDFLAGS_DIRS) $(CL_LDFLAGS_LIBS),$(LDFLAGS)) # Internal library variables # # Executable may use some internal libraries (libraries from the same module). # The subdirs should be in USE_IL variable # Current restrictions: # each library should be in a subdir; # subdir name and library name should be the same # The subdirs of the used internal libraries should be in CL_USE_IL variable # When internal libraries are used, executable is linked separately during build # and during installation. # During build, rpaths to the build directories of the shared libraries are # set, and during install - rpaths for the install directory is set ifneq ($(USE_IL),) # includes may be just added to $(INCLUDES) override INCLUDES += $(USE_IL:%=-I%) # -l flags also may be just added to $(CL_LDFLAGS_LIBS) override CL_LDFLAGS_LIBS += $(patsubst %,-l%,$(notdir $(USE_IL))) # -L flags can't be just added because of rpath logic, so we use $(CL_LDFLAGS_OTHER) override CL_IL_DIRS := $(USE_IL:%=-L%) endif #update LD_FLAGS wrt DEFINES ifneq ($(filter -g,$(DEFINES)),) override CL_LDFLAGS_OTHER += -g else override CL_LDFLAGS_OTHER += -s endif ifneq ($(filter -m64,$(DEFINES)),) override CL_LDFLAGS_OTHER += -m64 endif ifneq ($(filter -m32,$(DEFINES)),) override CL_LDFLAGS_OTHER += -m32 endif ifneq ($(filter -pg,$(DEFINES)),) override CL_LDFLAGS_OTHER += -pg endif ifneq ($(filter -fprofile-generate,$(DEFINES)),) override CL_LDFLAGS_OTHER += -fprofile-generate endif # Compute the final LDFLAGS override LDFLAGS := $(CL_IL_DIRS) $(CL_LDFLAGS_DIRS) $(CL_LDFLAGS_LIBS) $(CL_LDFLAGS_OTHER) # Add $(INCLUDES) and $(DEFINES) to $(CXXFLAGS) override CXXFLAGS += $(INCLUDES) $(DEFINES) # make object files based on sources override OBJECTS := $(addprefix $(BUILD_DIR)/,$(addsuffix .o,$(basename $(notdir $(SOURCES))))) # Rules for building object files override CXX_COMPILE_COMMAND = $(CXX) -c $(CXXFLAGS) -o $@ $< $(BUILD_DIR)/%.o: %.cpp $(CXX_COMPILE_COMMAND) # Make things like "make file.o" work %: $(BUILD_DIR)/% ifdef SUBDIRS all_subdirs clean_subdirs dep_subdirs: for dir in $(SUBDIRS); do \ (cd $$dir && $(MAKE) `echo $@ | cut -d_ -f1`) || exit 1; \ done ifeq ($(EXECUTABLE)$(LIBRARY),) all: all_subdirs endif else # No SUBDIRS all_subdirs clean_subdirs dep_subdirs: endif # SUBDIRS # defining "dep" rule ifeq ($(EXECUTABLE)$(LIBRARY),) dep: dep_subdirs else dep: dep_subdirs .deps #create .deps file that contains dependencies for all *.c[pp] files .deps: $(SOURCES) rm -f .deps touch .deps for file in $(SOURCES); do \ $(CXX) $(CXXFLAGS) -MM $$file > .deps.tmp ; \ sed '1 s/^\(.*\)/$(BUILD_DIR)\/\1/' .deps.tmp > .deps.tmp2 ; \ cat .deps.tmp2 >> .deps ; \ echo >> .deps ; \ done rm -f .deps.tmp .deps.tmp2 # use this file to remember dependencies include .deps # now make libs/executables dependant on the libs they uses # here we have all libraries of which current goal depends override LIB_DEPS := $(filter -l%, $(LDFLAGS)) # make sure that goals for those libraries that are NOT from the project still exists ifneq ($(LIB_DEPS),) $(LIB_DEPS) : endif endif # deps for non-empty dirs # main rule ifdef EXECUTABLE all: all_subdirs $(EXECUTABLE) $(EXECUTABLE): $(BUILD_DIR) $(BUILD_DIR)/$(EXECUTABLE) rm -f $(EXECUTABLE) && ln -s $(BUILD_DIR)/$(EXECUTABLE) $(EXECUTABLE) $(BUILD_DIR)/$(EXECUTABLE): $(OBJECTS) $(LIB_DEPS) $(CXX) $(OBJECTS) $(LDFLAGS) -o $@ endif # EXECUTABLE ifdef LIBRARY all: all_subdirs $(LIBRARY_NAME) $(LIBRARY_NAME): $(BUILD_DIR) $(BUILD_DIR)/$(LIBRARY_NAME) rm -f $@ && ln -s $(BUILD_DIR)/$@ . # define shared flags SHARED_FLAGS = ifeq ($(OS),LINUX) override SHARED_FLAGS := -shared -Wl,-h,$(LIBRARY_NAME) endif ifeq ($(OS),MACOSX) override SHARED_FLAGS := -dynamiclib endif ifeq ($(OS),WINDOWS) override SHARED_FLAGS := endif ifeq ($(LTYPE),shared) $(BUILD_DIR)/$(LIBRARY_NAME): $(OBJECTS) $(LIB_DEPS) $(CXX) $(SHARED_FLAGS) -o $@ $(OBJECTS) $(LDFLAGS) endif ifeq ($(LTYPE),static) $(BUILD_DIR)/$(LIBRARY_NAME): $(OBJECTS) ar cr $@ $(OBJECTS) ranlib $(BUILD_DIR)/$(LIBRARY_NAME) endif endif # The generic "clean" rule clean: clean_subdirs rm -rf $(BUILD_DIR) $(LIBRARY_NAME) $(EXECUTABLE) .deps FaCTpp-src-v1.6.2~dfsg/src/version-info.html0000644000000000000000000000031412112642425017440 0ustar rootroot

FaCT++

Reasoner plugin More information here

14 May 2010: Fix Java 1.5 issue and OWL API3 inconsistencies FaCTpp-src-v1.6.2~dfsg/src/FaCT++.ProtegeOWLAPIv3/0000755000000000000000000000000012112642474017636 5ustar rootrootFaCTpp-src-v1.6.2~dfsg/src/FaCT++.ProtegeOWLAPIv3/META-INF/0000755000000000000000000000000012112642474020776 5ustar rootrootFaCTpp-src-v1.6.2~dfsg/src/FaCT++.ProtegeOWLAPIv3/META-INF/MANIFEST.MF0000644000000000000000000000354412112642425022432 0ustar rootrootManifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: Factplusplus Plug-in Bundle-SymbolicName: uk.ac.manchester.cs.owl.factplusplus;singleton:=true Bundle-Version: 1.5.3 Bundle-Vendor: University of Manchester Bundle-Description: A Protege OWL wrapper for FaCT++ Update-Url: http://factplusplus.googlecode.com/svn/trunk/update.properties.p4.1 Bundle-ClassPath: .,lib/FaCTPlusPlus.jar Import-Package: org.osgi.framework, org.apache.log4j, javax.swing, javax.xml.datatype Require-Bundle: org.protege.common, org.protege.editor.core.application, org.protege.editor.owl, org.semanticweb.owl.owlapi Bundle-NativeCode: lib/native/64bit/FaCTPlusPlusJNI.dll; osname=WindowsNT ; osname=Windows NT ; osname=WinNT ; osname=WindowsXP ; osname=Windows XP ; osname=WinXP ; osname=WindowsVista ; osname=Windows Vista ; osname=Windows2003 ; osname=Windows2008 ; osname=Windows 7 ; osname=Windows7 ; osname=Win7 ; processor=x86_64 ; processor=AMD64 ; processor=amd64 , lib/native/32bit/FaCTPlusPlusJNI.dll; osname=Windows95 ; osname=Windows 95 ; osname=Win95 ; osname=Windows98 ; osname=Windows 98 ; osname=Win98 ; osname=WindowsNT ; osname=Windows NT ; osname=WinNT ; osname=WindowsCE ; osname=Winndows CE ; osname=WinCE ; osname=WindowsXP ; osname=Windows XP ; osname=WinXP ; osname=WindowsVista ; osname=Windows Vista ; osname=Windows2003 ; osname=Windows2008 ; osname=Windows 7 ; osname=Windows7 ; osname=Win7 ; processor=i386 ; processor=x86 , lib/native/64bit/libFaCTPlusPlusJNI.so; osname=Linux ; processor=x86_64 ; processor=amd64 , lib/native/32bit/libFaCTPlusPlusJNI.so; osname=Linux ; processor=i386 , lib/native/64bit/libFaCTPlusPlusJNI.jnilib; osname=MacOSX ; osname=Mac OS X ; processor=ppc64 ; processor=x86_64 , lib/native/32bit/libFaCTPlusPlusJNI.jnilib; osname=MacOSX ; osname=Mac OS X ; processor=ppc ; processor=i386 FaCTpp-src-v1.6.2~dfsg/src/FaCT++.ProtegeOWLAPIv3/plugin.xml0000644000000000000000000000132412112642425021652 0ustar rootroot FaCTpp-src-v1.6.2~dfsg/src/FaCT++.ProtegeOWLAPIv3/lib/0000755000000000000000000000000012112642474020404 5ustar rootrootFaCTpp-src-v1.6.2~dfsg/src/FaCT++.ProtegeOWLAPIv3/lib/version.txt0000644000000000000000000000007112112642425022624 0ustar rootrootFaCT++ based on release of version 1.4.0 (April 29, 2010)FaCTpp-src-v1.6.2~dfsg/src/FaCT++.ProtegeOWLAPIv3/lib/native/0000755000000000000000000000000012112642474021672 5ustar rootrootFaCTpp-src-v1.6.2~dfsg/src/FaCT++.ProtegeOWLAPIv3/lib/native/32bit/0000755000000000000000000000000012112642474022615 5ustar rootrootFaCTpp-src-v1.6.2~dfsg/src/FaCT++.ProtegeOWLAPIv3/lib/native/64bit/0000755000000000000000000000000012112642474022622 5ustar rootrootFaCTpp-src-v1.6.2~dfsg/src/FaCT++.ProtegeOWLAPIv3/build.xml0000644000000000000000000000345312112642425021460 0ustar rootroot FaCTpp-src-v1.6.2~dfsg/src/FaCT++.ProtegeOWLAPIv3/src/0000755000000000000000000000000012112642474020425 5ustar rootrootFaCTpp-src-v1.6.2~dfsg/src/FaCT++.ProtegeOWLAPIv3/src/uk/0000755000000000000000000000000012112642474021044 5ustar rootrootFaCTpp-src-v1.6.2~dfsg/src/FaCT++.ProtegeOWLAPIv3/src/uk/ac/0000755000000000000000000000000012112642474021427 5ustar rootrootFaCTpp-src-v1.6.2~dfsg/src/FaCT++.ProtegeOWLAPIv3/src/uk/ac/manchester/0000755000000000000000000000000012112642474023560 5ustar rootrootFaCTpp-src-v1.6.2~dfsg/src/FaCT++.ProtegeOWLAPIv3/src/uk/ac/manchester/cs/0000755000000000000000000000000012112642474024165 5ustar rootrootFaCTpp-src-v1.6.2~dfsg/src/FaCT++.ProtegeOWLAPIv3/src/uk/ac/manchester/cs/factplusplus/0000755000000000000000000000000012112642474026712 5ustar rootrootFaCTpp-src-v1.6.2~dfsg/src/FaCT++.ProtegeOWLAPIv3/src/uk/ac/manchester/cs/factplusplus/protege/0000755000000000000000000000000012112642474030357 5ustar rootroot././@LongLink0000000000000000000000000000017000000000000011563 Lustar rootrootFaCTpp-src-v1.6.2~dfsg/src/FaCT++.ProtegeOWLAPIv3/src/uk/ac/manchester/cs/factplusplus/protege/FaCTPlusPlusFactory.javaFaCTpp-src-v1.6.2~dfsg/src/FaCT++.ProtegeOWLAPIv3/src/uk/ac/manchester/cs/factplusplus/protege/FaCTP0000644000000000000000000000722212112642425031176 0ustar rootrootpackage uk.ac.manchester.cs.factplusplus.protege; /* * Copyright (C) 2007, University of Manchester * * Modifications to the initial code base are copyright of their * respective authors, or their employers as appropriate. Authorship * of the modifications may be determined from the ChangeLog placed at * the end of this file. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ import javax.swing.JOptionPane; import org.protege.editor.owl.model.inference.AbstractProtegeOWLReasonerInfo; import org.semanticweb.owlapi.model.OWLRuntimeException; import org.semanticweb.owlapi.reasoner.BufferingMode; import org.semanticweb.owlapi.reasoner.OWLReasonerFactory; import uk.ac.manchester.cs.factplusplus.FaCTPlusPlus; import uk.ac.manchester.cs.factplusplus.owlapiv3.FaCTPlusPlusReasonerFactory; /** * Author: Matthew Horridge
* The University Of Manchester
* Bio-Health Informatics Group
* Date: 11-May-2007

*/ public class FaCTPlusPlusFactory extends AbstractProtegeOWLReasonerInfo { private FaCTPlusPlusReasonerFactory fac; // previous interface implementation // public OWLReasoner createReasoner(OWLOntology owlOntology, ReasonerProgressMonitor reasonerProgressMonitor) { // try { // OWLReasonerConfiguration conf = new SimpleConfiguration(reasonerProgressMonitor); // return fac.createNonBufferingReasoner(owlOntology, conf); // } // catch (UnsatisfiedLinkError e) { // JOptionPane.showMessageDialog(null, // "FaCT++ requires platform specific libraries which cannot be found.\n" + // "Supported platforms are OS X, Windows and Linux.", // "Missing libraries or platform not supported", // JOptionPane.ERROR_MESSAGE); // throw new OWLRuntimeException(e); // } // catch (Exception e) { // throw new OWLRuntimeException(e); // } // } public void initialise() throws Exception { fac = new FaCTPlusPlusReasonerFactory(); } public void dispose() throws Exception { fac = null; } public BufferingMode getRecommendedBuffering() { return BufferingMode.BUFFERING; } public OWLReasonerFactory getReasonerFactory() { try { // refer to the FaCTPlusPlus class so the static block that loads the native library is loaded FaCTPlusPlus.test(); } catch (UnsatisfiedLinkError e) { JOptionPane.showMessageDialog(null, "FaCT++ requires platform specific libraries which cannot be found.\n" + "Supported platforms are OS X, Windows and Linux.", "Missing libraries or platform not supported", JOptionPane.ERROR_MESSAGE); throw new OWLRuntimeException(e); } return fac; } } ././@LongLink0000000000000000000000000000020700000000000011564 Lustar rootrootFaCTpp-src-v1.6.2~dfsg/src/FaCT++.ProtegeOWLAPIv3/src/uk/ac/manchester/cs/factplusplus/protege/FaCTPlusPlusRenderingViewComponent.javaFaCTpp-src-v1.6.2~dfsg/src/FaCT++.ProtegeOWLAPIv3/src/uk/ac/manchester/cs/factplusplus/protege/FaCTP0000644000000000000000000000335312112642425031177 0ustar rootrootpackage uk.ac.manchester.cs.factplusplus.protege; import org.protege.editor.owl.ui.view.ontology.AbstractOntologyRenderingViewComponent; import org.semanticweb.owlapi.model.OWLOntology; import java.io.Writer; /* * Copyright (C) 2007, University of Manchester * * Modifications to the initial code base are copyright of their * respective authors, or their employers as appropriate. Authorship * of the modifications may be determined from the ChangeLog placed at * the end of this file. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ /** * Author: Matthew Horridge
* The University Of Manchester
* Bio-Health Informatics Group
* Date: 08-Aug-2007

*/ public class FaCTPlusPlusRenderingViewComponent extends AbstractOntologyRenderingViewComponent { protected void renderOntology(OWLOntology ontology, Writer writer) throws Exception { writer.append("Not implemented for owlapi v3"); // FaCTPlusPlusRenderer renderer = new FaCTPlusPlusRenderer(writer); // ontology.accept(renderer); // writer.flush(); } } FaCTpp-src-v1.6.2~dfsg/src/FaCT++.OWLAPIv3/0000755000000000000000000000000012112642473016307 5ustar rootrootFaCTpp-src-v1.6.2~dfsg/src/FaCT++.OWLAPIv3/lib/0000755000000000000000000000000012116743744017064 5ustar rootrootFaCTpp-src-v1.6.2~dfsg/src/FaCT++.OWLAPIv3/build.xml0000644000000000000000000000312412112642425020125 0ustar rootroot FaCTpp-src-v1.6.2~dfsg/src/FaCT++.OWLAPIv3/src/0000755000000000000000000000000012112642473017076 5ustar rootrootFaCTpp-src-v1.6.2~dfsg/src/FaCT++.OWLAPIv3/src/uk/0000755000000000000000000000000012112642473017515 5ustar rootrootFaCTpp-src-v1.6.2~dfsg/src/FaCT++.OWLAPIv3/src/uk/ac/0000755000000000000000000000000012112642473020100 5ustar rootrootFaCTpp-src-v1.6.2~dfsg/src/FaCT++.OWLAPIv3/src/uk/ac/manchester/0000755000000000000000000000000012112642474022232 5ustar rootrootFaCTpp-src-v1.6.2~dfsg/src/FaCT++.OWLAPIv3/src/uk/ac/manchester/cs/0000755000000000000000000000000012112642474022637 5ustar rootrootFaCTpp-src-v1.6.2~dfsg/src/FaCT++.OWLAPIv3/src/uk/ac/manchester/cs/factplusplus/0000755000000000000000000000000012112642474025364 5ustar rootrootFaCTpp-src-v1.6.2~dfsg/src/FaCT++.OWLAPIv3/src/uk/ac/manchester/cs/factplusplus/owlapiv3/0000755000000000000000000000000012112642474027130 5ustar rootroot././@LongLink0000000000000000000000000000017200000000000011565 Lustar rootrootFaCTpp-src-v1.6.2~dfsg/src/FaCT++.OWLAPIv3/src/uk/ac/manchester/cs/factplusplus/owlapiv3/FaCTPlusPlusReasonerFactory.javaFaCTpp-src-v1.6.2~dfsg/src/FaCT++.OWLAPIv3/src/uk/ac/manchester/cs/factplusplus/owlapiv3/FaCTPlusPlu0000644000000000000000000000505412112642425031155 0ustar rootrootpackage uk.ac.manchester.cs.factplusplus.owlapiv3; import org.semanticweb.owlapi.model.OWLOntology; import org.semanticweb.owlapi.reasoner.*; /* * Copyright (C) 2009, University of Manchester * * Modifications to the initial code base are copyright of their * respective authors, or their employers as appropriate. Authorship * of the modifications may be determined from the ChangeLog placed at * the end of this file. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ /** * Author: Matthew Horridge
* The University of Manchester
* Information Management Group
* Date: 13-Jan-2010 */ public class FaCTPlusPlusReasonerFactory implements OWLReasonerFactory { public String getReasonerName() { return "FaCT++"; } /** * real implementation of the createReasoner method */ protected OWLReasoner createReasoner(OWLOntology ontology, OWLReasonerConfiguration config, boolean buffering) throws IllegalConfigurationException { BufferingMode bufferingMode = buffering ? BufferingMode.BUFFERING : BufferingMode.NON_BUFFERING; final FaCTPlusPlusReasoner reasoner = new FaCTPlusPlusReasoner(ontology, config, bufferingMode); ontology.getOWLOntologyManager().addOntologyChangeListener(reasoner); return reasoner; } public OWLReasoner createReasoner(OWLOntology ontology) { return createReasoner(ontology, new SimpleConfiguration(), true); } public OWLReasoner createNonBufferingReasoner(OWLOntology ontology) { return createReasoner(ontology, new SimpleConfiguration(), false); } public OWLReasoner createReasoner(OWLOntology ontology, OWLReasonerConfiguration config) throws IllegalConfigurationException { return createReasoner(ontology, config, true); } public OWLReasoner createNonBufferingReasoner(OWLOntology ontology, OWLReasonerConfiguration config) throws IllegalConfigurationException { return createReasoner(ontology, config, false); } } ././@LongLink0000000000000000000000000000016300000000000011565 Lustar rootrootFaCTpp-src-v1.6.2~dfsg/src/FaCT++.OWLAPIv3/src/uk/ac/manchester/cs/factplusplus/owlapiv3/FaCTPlusPlusReasoner.javaFaCTpp-src-v1.6.2~dfsg/src/FaCT++.OWLAPIv3/src/uk/ac/manchester/cs/factplusplus/owlapiv3/FaCTPlusPlu0000644000000000000000000017755712112642425031177 0ustar rootrootpackage uk.ac.manchester.cs.factplusplus.owlapiv3; import java.io.PrintStream; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicBoolean; import javax.xml.datatype.*; import org.semanticweb.owlapi.model.*; import org.semanticweb.owlapi.reasoner.*; import org.semanticweb.owlapi.reasoner.impl.*; import org.semanticweb.owlapi.util.Version; import org.semanticweb.owlapi.vocab.*; import uk.ac.manchester.cs.factplusplus.*; /* * Copyright (C) 2009-2010, University of Manchester * * Modifications to the initial code base are copyright of their * respective authors, or their employers as appropriate. Authorship * of the modifications may be determined from the ChangeLog placed at * the end of this file. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ /** * Author: Matthew Horridge
* The University of Manchester
* Information Management Group
* Date: 29-Dec-2009 * * Synchronization policy: all methods for OWLReasoner are synchronized, except * the methods which do not touch the kernel or only affect threadsafe data * structures. inner private classes are not synchronized since methods from * those classes cannot be invoked from outsize synchronized methods. * */ public class FaCTPlusPlusReasoner implements OWLReasoner, OWLOntologyChangeListener { public static final String REASONER_NAME = "FaCT++"; public static final Version VERSION = new Version(1, 6, 2, 0); protected final AtomicBoolean interrupted = new AtomicBoolean(false); private final FaCTPlusPlus kernel = new FaCTPlusPlus(); private volatile AxiomTranslator axiomTranslator = new AxiomTranslator(); private volatile ClassExpressionTranslator classExpressionTranslator; private volatile DataRangeTranslator dataRangeTranslator; private volatile ObjectPropertyTranslator objectPropertyTranslator; private volatile DataPropertyTranslator dataPropertyTranslator; private volatile IndividualTranslator individualTranslator; private volatile EntailmentChecker entailmentChecker; private final Map axiom2PtrMap = new HashMap(); private final Map ptr2AxiomMap = new HashMap(); private static final Set SupportedInferenceTypes = new HashSet(Arrays.asList( InferenceType.CLASS_ASSERTIONS, InferenceType.CLASS_HIERARCHY, InferenceType.DATA_PROPERTY_HIERARCHY, InferenceType.OBJECT_PROPERTY_HIERARCHY, InferenceType.SAME_INDIVIDUAL)); private final OWLOntologyManager manager; private final OWLOntology rootOntology; private final BufferingMode bufferingMode; private final List rawChanges = new ArrayList(); // private final ReentrantReadWriteLock rawChangesLock = new // ReentrantReadWriteLock(); private final List reasonerAxioms = new ArrayList(); private final long timeOut; private final OWLReasonerConfiguration configuration; public void ontologiesChanged(List changes) throws OWLException { handleRawOntologyChanges(changes); } public OWLReasonerConfiguration getReasonerConfiguration() { return configuration; } public BufferingMode getBufferingMode() { return bufferingMode; } public long getTimeOut() { return timeOut; } public OWLOntology getRootOntology() { return rootOntology; } /** * Handles raw ontology changes. If the reasoner is a buffering reasoner * then the changes will be stored in a buffer. If the reasoner is a * non-buffering reasoner then the changes will be automatically flushed * through to the change filter and passed on to the reasoner. * * @param changes * The list of raw changes. */ private final boolean log = false; private synchronized void handleRawOntologyChanges(List changes) { if (log) { System.out.println(Thread.currentThread().getName() + " OWLReasonerBase.handleRawOntologyChanges() " + changes); } rawChanges.addAll(changes); // We auto-flush the changes if the reasoner is non-buffering if (bufferingMode.equals(BufferingMode.NON_BUFFERING)) { flush(); } } public synchronized List getPendingChanges() { return new ArrayList(rawChanges); } public synchronized Set getPendingAxiomAdditions() { if (rawChanges.size() > 0) { Set added = new HashSet(); computeDiff(added, new HashSet()); return added; } return Collections.emptySet(); } public synchronized Set getPendingAxiomRemovals() { if (rawChanges.size() > 0) { Set removed = new HashSet(); computeDiff(new HashSet(), removed); return removed; } return Collections.emptySet(); } /** * Flushes the pending changes from the pending change list. The changes * will be analysed to dermine which axioms have actually been added and * removed from the imports closure of the root ontology and then the * reasoner will be asked to handle these changes via the * {@link #handleChanges(java.util.Set, java.util.Set)} method. */ public synchronized void flush() { // Process the changes if (rawChanges.size() > 0) { final Set added = new HashSet(); final Set removed = new HashSet(); computeDiff(added, removed); reasonerAxioms.removeAll(removed); reasonerAxioms.addAll(added); rawChanges.clear(); if (!added.isEmpty() || !removed.isEmpty()) { handleChanges(added, removed); } } } /** * Computes a diff of what axioms have been added and what axioms have been * removed from the list of pending changes. Note that even if the list of * pending changes is non-empty then there may be no changes for the * reasoner to deal with. * * @param added * The logical axioms that have been added to the imports closure * of the reasoner root ontology * @param removed * The logical axioms that have been removed from the imports * closure of the reasoner root ontology */ private synchronized void computeDiff(Set added, Set removed) { for (OWLOntology ont : rootOntology.getImportsClosure()) { for (OWLAxiom ax : ont.getLogicalAxioms()) { if (!reasonerAxioms.contains(ax.getAxiomWithoutAnnotations())) { added.add(ax); } } for (OWLAxiom ax : ont.getAxioms(AxiomType.DECLARATION)) { if (!reasonerAxioms.contains(ax.getAxiomWithoutAnnotations())) { added.add(ax); } } } for (OWLAxiom ax : reasonerAxioms) { if (!rootOntology.containsAxiomIgnoreAnnotations(ax, true)) { removed.add(ax); } } } /** * Gets the axioms that should be currently being reasoned over. * * @return A collections of axioms (not containing duplicates) that the * reasoner should be taking into consideration when reasoning. This * set of axioms many not correspond to the current state of the * imports closure of the reasoner root ontology if the reasoner is * buffered. */ public synchronized Collection getReasonerAxioms() { return new ArrayList(reasonerAxioms); } public FreshEntityPolicy getFreshEntityPolicy() { return configuration.getFreshEntityPolicy(); } public IndividualNodeSetPolicy getIndividualNodeSetPolicy() { return configuration.getIndividualNodeSetPolicy(); } public OWLDataFactory getOWLDataFactory() { return rootOntology.getOWLOntologyManager().getOWLDataFactory(); } public FaCTPlusPlusReasoner(OWLOntology rootOntology, OWLReasonerConfiguration configuration, BufferingMode bufferingMode) { this.rootOntology = rootOntology; this.bufferingMode = bufferingMode; this.configuration = configuration; this.timeOut = configuration.getTimeOut(); manager = rootOntology.getOWLOntologyManager(); for (OWLOntology ont : rootOntology.getImportsClosure()) { for (OWLAxiom ax : ont.getLogicalAxioms()) { reasonerAxioms.add(ax.getAxiomWithoutAnnotations()); } for (OWLAxiom ax : ont.getAxioms(AxiomType.DECLARATION)) { reasonerAxioms.add(ax.getAxiomWithoutAnnotations()); } } axiomTranslator = new AxiomTranslator(); classExpressionTranslator = new ClassExpressionTranslator(); dataRangeTranslator = new DataRangeTranslator(); objectPropertyTranslator = new ObjectPropertyTranslator(); dataPropertyTranslator = new DataPropertyTranslator(); individualTranslator = new IndividualTranslator(); entailmentChecker = new EntailmentChecker(); kernel.setTopBottomPropertyNames("http://www.w3.org/2002/07/owl#topObjectProperty", "http://www.w3.org/2002/07/owl#bottomObjectProperty", "http://www.w3.org/2002/07/owl#topDataProperty", "http://www.w3.org/2002/07/owl#bottomDataProperty"); kernel.setProgressMonitor(new ProgressMonitorAdapter(configuration.getProgressMonitor(), interrupted)); long millis = configuration.getTimeOut(); if (millis == Long.MAX_VALUE) millis = 0; kernel.setOperationTimeout(millis); kernel.setFreshEntityPolicy(configuration.getFreshEntityPolicy() == FreshEntityPolicy.ALLOW); loadReasonerAxioms(); } // ///////////////////////////////////////////////////////////////////////// // // load/retract axioms // // ///////////////////////////////////////////////////////////////////////// private void loadAxiom(OWLAxiom axiom) { if (axiom2PtrMap.containsKey(axiom)) { return; } final AxiomPointer axiomPointer = axiom.accept(axiomTranslator); if (axiomPointer != null) { axiom2PtrMap.put(axiom, axiomPointer); ptr2AxiomMap.put(axiomPointer, axiom); } } private void retractAxiom(OWLAxiom axiom) { final AxiomPointer ptr = axiom2PtrMap.get(axiom); if (ptr != null) { kernel.retract(ptr); axiom2PtrMap.remove(axiom); ptr2AxiomMap.remove(ptr); } } /** * Asks the reasoner implementation to handle axiom additions and removals * from the imports closure of the root ontology. The changes will not * include annotation axiom additions and removals. * * @param addAxioms * The axioms to be added to the reasoner. * @param removeAxioms * The axioms to be removed from the reasoner */ protected void handleChanges(Set addAxioms, Set removeAxioms) { kernel.startChanges(); for (OWLAxiom ax_a : addAxioms) loadAxiom(ax_a); for (OWLAxiom ax_r : removeAxioms) retractAxiom(ax_r); kernel.endChanges(); } private void loadReasonerAxioms() { getReasonerConfiguration().getProgressMonitor().reasonerTaskStarted(ReasonerProgressMonitor.LOADING); getReasonerConfiguration().getProgressMonitor().reasonerTaskBusy(); kernel.clearKernel(); axiomTranslator = new AxiomTranslator(); classExpressionTranslator = new ClassExpressionTranslator(); dataRangeTranslator = new DataRangeTranslator(); objectPropertyTranslator = new ObjectPropertyTranslator(); dataPropertyTranslator = new DataPropertyTranslator(); individualTranslator = new IndividualTranslator(); axiom2PtrMap.clear(); ptr2AxiomMap.clear(); for (OWLAxiom ax : getReasonerAxioms()) { loadAxiom(ax); } getReasonerConfiguration().getProgressMonitor().reasonerTaskStopped(); } // ///////////////////////////////////////////////////////////////////////////////////////////////////////////// // ///////////////////////////////////////////////////////////////////////////////////////////////////////////// // ///////////////////////////////////////////////////////////////////////////////////////////////////////////// // ///////////////////////////////////////////////////////////////////////////////////////////////////////////// // //// // //// // //// Implementation of reasoner interfaces // //// // //// // ///////////////////////////////////////////////////////////////////////////////////////////////////////////// // ///////////////////////////////////////////////////////////////////////////////////////////////////////////// // ///////////////////////////////////////////////////////////////////////////////////////////////////////////// public String getReasonerName() { return REASONER_NAME; } public Version getReasonerVersion() { return VERSION; } public void interrupt() { interrupted.set(true); } // precompute inferences public synchronized void precomputeInferences(InferenceType... inferenceTypes) throws ReasonerInterruptedException, TimeOutException, InconsistentOntologyException { for (InferenceType it : inferenceTypes) if (SupportedInferenceTypes.contains(it)) { kernel.realise(); return; } } public boolean isPrecomputed(InferenceType inferenceType) { if (SupportedInferenceTypes.contains(inferenceType)) { return kernel.isRealised(); } return true; } public Set getPrecomputableInferenceTypes() { return SupportedInferenceTypes; } // consistency public synchronized boolean isConsistent() throws ReasonerInterruptedException, TimeOutException { return kernel.isKBConsistent(); } private void checkConsistency() { if (interrupted.get()) { throw new ReasonerInterruptedException(); } if (!isConsistent()) { throw new InconsistentOntologyException(); } } public synchronized boolean isSatisfiable(OWLClassExpression classExpression) throws ReasonerInterruptedException, TimeOutException, ClassExpressionNotInProfileException, FreshEntitiesException, InconsistentOntologyException { checkConsistency(); return kernel.isClassSatisfiable(toClassPointer(classExpression)); } public Node getUnsatisfiableClasses() throws ReasonerInterruptedException, TimeOutException, InconsistentOntologyException { return getBottomClassNode(); } // entailments public synchronized boolean isEntailed(OWLAxiom axiom) throws ReasonerInterruptedException, UnsupportedEntailmentTypeException, TimeOutException, AxiomNotInProfileException, FreshEntitiesException, InconsistentOntologyException { checkConsistency(); // if(rootOntology.containsAxiom(axiom, true)) { // return true; // } Boolean entailed = axiom.accept(entailmentChecker); if (entailed == null) { throw new UnsupportedEntailmentTypeException(axiom); } return entailed; } public synchronized boolean isEntailed(Set axioms) throws ReasonerInterruptedException, UnsupportedEntailmentTypeException, TimeOutException, AxiomNotInProfileException, FreshEntitiesException, InconsistentOntologyException { for (OWLAxiom ax : axioms) { if (!isEntailed(ax)) { return false; } } return true; } public boolean isEntailmentCheckingSupported(AxiomType axiomType) { if (axiomType.equals(AxiomType.SWRL_RULE)) { return false; } // FIXME!! check later return true; } // tracing /* * Return tracing set (set of axioms that were participate in achieving * result) for a given entailment. Return empty set if the axiom is not * entailed. */ public Set getTrace(OWLAxiom axiom) { kernel.needTracing(); Set ret = new HashSet(); if (isEntailed(axiom)) { for (AxiomPointer ap : kernel.getTrace()) ret.add(ptr2AxiomMap.get(ap)); } return ret; } // classes public Node getTopClassNode() { return getEquivalentClasses(getOWLDataFactory().getOWLThing()); } public Node getBottomClassNode() { return getEquivalentClasses(getOWLDataFactory().getOWLNothing()); } public synchronized NodeSet getSubClasses(OWLClassExpression ce, boolean direct) throws ReasonerInterruptedException, TimeOutException, FreshEntitiesException, InconsistentOntologyException { checkConsistency(); return classExpressionTranslator.getNodeSetFromPointers(kernel.askSubClasses(toClassPointer(ce), direct)); } public synchronized NodeSet getSuperClasses(OWLClassExpression ce, boolean direct) throws InconsistentOntologyException, ClassExpressionNotInProfileException, ReasonerInterruptedException, TimeOutException { checkConsistency(); return classExpressionTranslator.getNodeSetFromPointers(kernel.askSuperClasses(toClassPointer(ce), direct)); } public synchronized Node getEquivalentClasses(OWLClassExpression ce) throws InconsistentOntologyException, ClassExpressionNotInProfileException, ReasonerInterruptedException, TimeOutException { checkConsistency(); ClassPointer[] pointers = kernel.askEquivalentClasses(toClassPointer(ce)); return classExpressionTranslator.getNodeFromPointers(pointers); } public synchronized NodeSet getDisjointClasses(OWLClassExpression ce) { checkConsistency(); return classExpressionTranslator.getNodeSetFromPointers(kernel.askDisjointClasses(toClassPointer(ce))); } // object properties public Node getTopObjectPropertyNode() { return getEquivalentObjectProperties(getOWLDataFactory().getOWLTopObjectProperty()); } public Node getBottomObjectPropertyNode() { return getEquivalentObjectProperties(getOWLDataFactory().getOWLBottomObjectProperty()); } public synchronized NodeSet getSubObjectProperties(OWLObjectPropertyExpression pe, boolean direct) throws InconsistentOntologyException, ReasonerInterruptedException, TimeOutException { checkConsistency(); return objectPropertyTranslator.getNodeSetFromPointers(kernel.askSubObjectProperties( toObjectPropertyPointer(pe), direct)); } public synchronized NodeSet getSuperObjectProperties(OWLObjectPropertyExpression pe, boolean direct) throws InconsistentOntologyException, ReasonerInterruptedException, TimeOutException { checkConsistency(); return objectPropertyTranslator.getNodeSetFromPointers(kernel.askSuperObjectProperties( toObjectPropertyPointer(pe), direct)); } public synchronized Node getEquivalentObjectProperties(OWLObjectPropertyExpression pe) throws InconsistentOntologyException, ReasonerInterruptedException, TimeOutException { checkConsistency(); return objectPropertyTranslator.getNodeFromPointers(kernel .askEquivalentObjectProperties(toObjectPropertyPointer(pe))); } public synchronized NodeSet getDisjointObjectProperties(OWLObjectPropertyExpression pe) throws InconsistentOntologyException, ReasonerInterruptedException, TimeOutException { checkConsistency(); // TODO: incomplete OWLObjectPropertyNodeSet toReturn = new OWLObjectPropertyNodeSet(); toReturn.addNode(getBottomObjectPropertyNode()); return toReturn; } public synchronized Node getInverseObjectProperties(OWLObjectPropertyExpression pe) throws InconsistentOntologyException, ReasonerInterruptedException, TimeOutException { checkConsistency(); return objectPropertyTranslator.getNodeFromPointers(kernel .askEquivalentObjectProperties(toObjectPropertyPointer(pe.getInverseProperty()))); } public synchronized NodeSet getObjectPropertyDomains(OWLObjectPropertyExpression pe, boolean direct) throws InconsistentOntologyException, ReasonerInterruptedException, TimeOutException { checkConsistency(); return classExpressionTranslator.getNodeSetFromPointers(kernel.askObjectPropertyDomain( objectPropertyTranslator.createPointerForEntity(pe), direct)); } public NodeSet getObjectPropertyRanges(OWLObjectPropertyExpression pe, boolean direct) throws InconsistentOntologyException, ReasonerInterruptedException, TimeOutException { checkConsistency(); return classExpressionTranslator.getNodeSetFromPointers(kernel.askObjectPropertyRange( objectPropertyTranslator.getPointerFromEntity(pe), direct)); } // data properties public Node getTopDataPropertyNode() { OWLDataPropertyNode toReturn = new OWLDataPropertyNode(); toReturn.add(getOWLDataFactory().getOWLTopDataProperty()); return toReturn; } public Node getBottomDataPropertyNode() { return getEquivalentDataProperties(getOWLDataFactory().getOWLBottomDataProperty()); } public synchronized NodeSet getSubDataProperties(OWLDataProperty pe, boolean direct) throws InconsistentOntologyException, ReasonerInterruptedException, TimeOutException { checkConsistency(); return dataPropertyTranslator.getNodeSetFromPointers(kernel.askSubDataProperties(toDataPropertyPointer(pe), direct)); } public synchronized NodeSet getSuperDataProperties(OWLDataProperty pe, boolean direct) throws InconsistentOntologyException, ReasonerInterruptedException, TimeOutException { checkConsistency(); return dataPropertyTranslator.getNodeSetFromPointers(kernel.askSuperDataProperties(toDataPropertyPointer(pe), direct)); } public synchronized Node getEquivalentDataProperties(OWLDataProperty pe) throws InconsistentOntologyException, ReasonerInterruptedException, TimeOutException { checkConsistency(); return dataPropertyTranslator .getNodeFromPointers(kernel.askEquivalentDataProperties(toDataPropertyPointer(pe))); } public synchronized NodeSet getDisjointDataProperties(OWLDataPropertyExpression pe) throws InconsistentOntologyException, ReasonerInterruptedException, TimeOutException { checkConsistency(); // TODO: return new OWLDataPropertyNodeSet(); } public NodeSet getDataPropertyDomains(OWLDataProperty pe, boolean direct) throws InconsistentOntologyException, ReasonerInterruptedException, TimeOutException { checkConsistency(); return classExpressionTranslator.getNodeSetFromPointers(kernel.askDataPropertyDomain( dataPropertyTranslator.createPointerForEntity(pe), direct)); } // individuals public synchronized NodeSet getTypes(OWLNamedIndividual ind, boolean direct) throws InconsistentOntologyException, ReasonerInterruptedException, TimeOutException { checkConsistency(); return classExpressionTranslator.getNodeSetFromPointers(kernel.askIndividualTypes(toIndividualPointer(ind), direct)); } public synchronized NodeSet getInstances(OWLClassExpression ce, boolean direct) throws InconsistentOntologyException, ClassExpressionNotInProfileException, ReasonerInterruptedException, TimeOutException { checkConsistency(); return translateIndividualPointersToNodeSet(kernel.askInstances(toClassPointer(ce), direct)); } public synchronized NodeSet getObjectPropertyValues(OWLNamedIndividual ind, OWLObjectPropertyExpression pe) throws InconsistentOntologyException, ReasonerInterruptedException, TimeOutException { checkConsistency(); return translateIndividualPointersToNodeSet(kernel.askRelatedIndividuals(toIndividualPointer(ind), toObjectPropertyPointer(pe))); } public synchronized Set getDataPropertyValues(OWLNamedIndividual ind, OWLDataProperty pe) throws InconsistentOntologyException, ReasonerInterruptedException, TimeOutException { // TODO: checkConsistency(); return Collections.emptySet(); } public synchronized Node getSameIndividuals(OWLNamedIndividual ind) throws InconsistentOntologyException, ReasonerInterruptedException, TimeOutException { checkConsistency(); return individualTranslator.getNodeFromPointers(kernel.askSameAs(toIndividualPointer(ind))); } public NodeSet getDifferentIndividuals(OWLNamedIndividual ind) throws InconsistentOntologyException, ReasonerInterruptedException, TimeOutException { OWLClassExpression ce = getOWLDataFactory().getOWLObjectOneOf(ind).getObjectComplementOf(); return getInstances(ce, false); } // /////////////////////////////////////////////////////////////////////////////////////////////////////////////// // /////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // // // Translation to FaCT++ structures and back // // // /////////////////////////////////////////////////////////////////////////////////////////////////////////////// // /////////////////////////////////////////////////////////////////////////////////////////////////////////////// private abstract class OWLEntityTranslator { private final Map entity2PointerMap = new ConcurrentHashMap(); protected final Map pointer2EntityMap = new ConcurrentHashMap(); protected void fillEntityPointerMaps(E entity, P pointer) { entity2PointerMap.put(entity, pointer); pointer2EntityMap.put(pointer, entity); } protected OWLEntityTranslator() { E topEntity = getTopEntity(); if (topEntity != null) { fillEntityPointerMaps(topEntity, getTopEntityPointer()); } E bottomEntity = getBottomEntity(); if (bottomEntity != null) { fillEntityPointerMaps(bottomEntity, getBottomEntityPointer()); } } protected P registerNewEntity(E entity) { P pointer = createPointerForEntity(entity); fillEntityPointerMaps(entity, pointer); return pointer; } public E getEntityFromPointer(P pointer) { return pointer2EntityMap.get(pointer); } public P getPointerFromEntity(E entity) { if (entity.isTopEntity()) { return getTopEntityPointer(); } else if (entity.isBottomEntity()) { return getBottomEntityPointer(); } else { P pointer = entity2PointerMap.get(entity); if (pointer == null) { pointer = registerNewEntity(entity); } return pointer; } } public Node getNodeFromPointers(P[] pointers) { DefaultNode node = createDefaultNode(); for (P pointer : pointers) { final E entityFromPointer = getEntityFromPointer(pointer); if (entityFromPointer != null) { node.add(entityFromPointer); } } return node; } public NodeSet getNodeSetFromPointers(P[][] pointers) { DefaultNodeSet nodeSet = createDefaultNodeSet(); for (P[] pointerArray : pointers) { nodeSet.addNode(getNodeFromPointers(pointerArray)); } return nodeSet; } protected abstract DefaultNode createDefaultNode(); protected abstract DefaultNodeSet createDefaultNodeSet(); protected abstract P getTopEntityPointer(); protected abstract P getBottomEntityPointer(); protected abstract P createPointerForEntity(E entity); protected abstract E getTopEntity(); protected abstract E getBottomEntity(); } protected ClassPointer toClassPointer(OWLClassExpression classExpression) { return classExpression.accept(classExpressionTranslator); } protected DataTypeExpressionPointer toDataTypeExpressionPointer(OWLDataRange dataRange) { return dataRange.accept(dataRangeTranslator); } protected ObjectPropertyPointer toObjectPropertyPointer(OWLObjectPropertyExpression propertyExpression) { OWLObjectPropertyExpression simp = propertyExpression.getSimplified(); if (simp.isAnonymous()) { OWLObjectInverseOf inv = (OWLObjectInverseOf) simp; return kernel.getInverseProperty(objectPropertyTranslator.getPointerFromEntity(inv.getInverse() .asOWLObjectProperty())); } else { return objectPropertyTranslator.getPointerFromEntity(simp.asOWLObjectProperty()); } } protected DataPropertyPointer toDataPropertyPointer(OWLDataPropertyExpression propertyExpression) { return dataPropertyTranslator.getPointerFromEntity(propertyExpression.asOWLDataProperty()); } protected synchronized IndividualPointer toIndividualPointer(OWLIndividual individual) { if (!individual.isAnonymous()) { return individualTranslator.getPointerFromEntity(individual.asOWLNamedIndividual()); } else { return kernel.getIndividual(individual.toStringID()); } } protected synchronized DataTypePointer toDataTypePointer(OWLDatatype datatype) { if (datatype == null) { throw new IllegalArgumentException("datatype cannot be null"); } String name = checkDateTime(datatype); return kernel.getBuiltInDataType(name); } protected static final String checkDateTime(OWLDatatype datatype) { String name = datatype.toStringID(); if (datatype.isBuiltIn()) { OWL2Datatype builtInDatatype = datatype.getBuiltInDatatype(); OWL2Datatype xsdDateTime = OWL2Datatype.XSD_DATE_TIME; if (builtInDatatype == xsdDateTime) { name = name + "AsLong"; } } return name; } protected synchronized DataValuePointer toDataValuePointer(OWLLiteral literal) { String value = literal.getLiteral(); if (literal.isRDFPlainLiteral()) { value = value + "@" + literal.getLang(); } if (literal.getDatatype().isBuiltIn() && literal.getDatatype().getBuiltInDatatype() == OWL2Datatype.XSD_DATE_TIME) { return kernel.getDataValue(convertToLongDateTime(value), toDataTypePointer(literal.getDatatype())); } return kernel.getDataValue(value, toDataTypePointer(literal.getDatatype())); } private static final String convertToLongDateTime(String input) { XMLGregorianCalendar calendar; try { calendar = DatatypeFactory.newInstance().newXMLGregorianCalendar(input); if (calendar.getTimezone() == DatatypeConstants.FIELD_UNDEFINED) { // set it to 0 (UTC) in this case; not perfect but avoids // indeterminate situations where two datetime literals cannot // be compared calendar.setTimezone(0); } long l = calendar.toGregorianCalendar().getTimeInMillis(); System.out.println("FaCTPlusPlusReasoner.convertToLongDateTime()\n" + input + "\n" + Long.toString(l)); return Long.toString(l); } catch (DatatypeConfigurationException e) { throw new OWLRuntimeException("Error: the datatype support in the Java VM is broken! Cannot parse: " + input, e); } } private NodeSet translateIndividualPointersToNodeSet(IndividualPointer[] pointers) { OWLNamedIndividualNodeSet ns = new OWLNamedIndividualNodeSet(); for (IndividualPointer pointer : pointers) { if (pointer != null) { OWLNamedIndividual ind = individualTranslator.getEntityFromPointer(pointer); // XXX skipping anonymous individuals - counterintuitive but // that's the specs for you if (ind != null) { ns.addEntity(ind); } } } return ns; } protected synchronized void translateIndividualSet(Set inds) { kernel.initArgList(); for (OWLIndividual ind : inds) { IndividualPointer ip = toIndividualPointer(ind); kernel.addArg(ip); } kernel.closeArgList(); } private class ClassExpressionTranslator extends OWLEntityTranslator implements OWLClassExpressionVisitorEx { public ClassExpressionTranslator() { } @Override protected ClassPointer getTopEntityPointer() { return kernel.getThing(); } @Override protected ClassPointer getBottomEntityPointer() { return kernel.getNothing(); } @Override protected OWLClass getTopEntity() { return getOWLDataFactory().getOWLThing(); } @Override protected OWLClass getBottomEntity() { return getOWLDataFactory().getOWLNothing(); } @Override protected ClassPointer createPointerForEntity(OWLClass entity) { return kernel.getNamedClass(entity.toStringID()); } @Override protected DefaultNode createDefaultNode() { return new OWLClassNode(); } @Override protected DefaultNodeSet createDefaultNodeSet() { return new OWLClassNodeSet(); } public ClassPointer visit(OWLClass desc) { return getPointerFromEntity(desc); } public ClassPointer visit(OWLObjectIntersectionOf desc) { translateClassExpressionSet(desc.getOperands()); return kernel.getConceptAnd(); } private void translateClassExpressionSet(Set classExpressions) { kernel.initArgList(); for (OWLClassExpression ce : classExpressions) { ClassPointer cp = ce.accept(this); kernel.addArg(cp); } kernel.closeArgList(); } public ClassPointer visit(OWLObjectUnionOf desc) { translateClassExpressionSet(desc.getOperands()); return kernel.getConceptOr(); } public ClassPointer visit(OWLObjectComplementOf desc) { return kernel.getConceptNot(desc.getOperand().accept(this)); } public ClassPointer visit(OWLObjectSomeValuesFrom desc) { return kernel.getObjectSome(toObjectPropertyPointer(desc.getProperty()), desc.getFiller().accept(this)); } public ClassPointer visit(OWLObjectAllValuesFrom desc) { return kernel.getObjectAll(toObjectPropertyPointer(desc.getProperty()), desc.getFiller().accept(this)); } public ClassPointer visit(OWLObjectHasValue desc) { return kernel.getObjectValue(toObjectPropertyPointer(desc.getProperty()), toIndividualPointer(desc.getValue())); } public ClassPointer visit(OWLObjectMinCardinality desc) { return kernel.getObjectAtLeast(desc.getCardinality(), toObjectPropertyPointer(desc.getProperty()), desc .getFiller().accept(this)); } public ClassPointer visit(OWLObjectExactCardinality desc) { return kernel.getObjectExact(desc.getCardinality(), toObjectPropertyPointer(desc.getProperty()), desc .getFiller().accept(this)); } public ClassPointer visit(OWLObjectMaxCardinality desc) { return kernel.getObjectAtMost(desc.getCardinality(), toObjectPropertyPointer(desc.getProperty()), desc .getFiller().accept(this)); } public ClassPointer visit(OWLObjectHasSelf desc) { return kernel.getSelf(toObjectPropertyPointer(desc.getProperty())); } public ClassPointer visit(OWLObjectOneOf desc) { translateIndividualSet(desc.getIndividuals()); return kernel.getOneOf(); } public ClassPointer visit(OWLDataSomeValuesFrom desc) { return kernel.getDataSome(toDataPropertyPointer(desc.getProperty()), toDataTypeExpressionPointer(desc.getFiller())); } public ClassPointer visit(OWLDataAllValuesFrom desc) { return kernel.getDataAll(toDataPropertyPointer(desc.getProperty()), toDataTypeExpressionPointer(desc.getFiller())); } public ClassPointer visit(OWLDataHasValue desc) { return kernel.getDataValue(toDataPropertyPointer(desc.getProperty()), toDataValuePointer(desc.getValue())); } public ClassPointer visit(OWLDataMinCardinality desc) { return kernel.getDataAtLeast(desc.getCardinality(), toDataPropertyPointer(desc.getProperty()), toDataTypeExpressionPointer(desc.getFiller())); } public ClassPointer visit(OWLDataExactCardinality desc) { return kernel.getDataExact(desc.getCardinality(), toDataPropertyPointer(desc.getProperty()), toDataTypeExpressionPointer(desc.getFiller())); } public ClassPointer visit(OWLDataMaxCardinality desc) { return kernel.getDataAtMost(desc.getCardinality(), toDataPropertyPointer(desc.getProperty()), toDataTypeExpressionPointer(desc.getFiller())); } } private class DataRangeTranslator extends OWLEntityTranslator implements OWLDataRangeVisitorEx { public DataRangeTranslator() { } @Override protected DataTypePointer getTopEntityPointer() { return kernel.getDataTop(); } @Override protected DataTypePointer getBottomEntityPointer() { return null; } @Override protected DefaultNode createDefaultNode() { return new OWLDatatypeNode(); } @Override protected OWLDatatype getTopEntity() { return getOWLDataFactory().getTopDatatype(); } @Override protected OWLDatatype getBottomEntity() { return null; } @Override protected DefaultNodeSet createDefaultNodeSet() { return new OWLDatatypeNodeSet(); } @Override protected DataTypePointer createPointerForEntity(OWLDatatype entity) { return kernel.getBuiltInDataType(checkDateTime(entity)); } public DataTypeExpressionPointer visit(OWLDatatype node) { return kernel.getBuiltInDataType(checkDateTime(node)); } public DataTypeExpressionPointer visit(OWLDataOneOf node) { kernel.initArgList(); for (OWLLiteral literal : node.getValues()) { DataValuePointer dvp = toDataValuePointer(literal); kernel.addArg(dvp); } kernel.closeArgList(); return kernel.getDataEnumeration(); } public DataTypeExpressionPointer visit(OWLDataComplementOf node) { return kernel.getDataNot(node.getDataRange().accept(this)); } public DataTypeExpressionPointer visit(OWLDataIntersectionOf node) { translateDataRangeSet(node.getOperands()); return kernel.getDataIntersectionOf(); } private void translateDataRangeSet(Set dataRanges) { kernel.initArgList(); for (OWLDataRange op : dataRanges) { DataTypeExpressionPointer dtp = op.accept(this); kernel.addArg(dtp); } kernel.closeArgList(); } public DataTypeExpressionPointer visit(OWLDataUnionOf node) { translateDataRangeSet(node.getOperands()); return kernel.getDataUnionOf(); } public DataTypeExpressionPointer visit(OWLDatatypeRestriction node) { DataTypeExpressionPointer dte = node.getDatatype().accept(this); for (OWLFacetRestriction restriction : node.getFacetRestrictions()) { DataValuePointer dv = toDataValuePointer(restriction.getFacetValue()); DataTypeFacet facet; if (restriction.getFacet().equals(OWLFacet.MIN_INCLUSIVE)) { facet = kernel.getMinInclusiveFacet(dv); } else if (restriction.getFacet().equals(OWLFacet.MAX_INCLUSIVE)) { facet = kernel.getMaxInclusiveFacet(dv); } else if (restriction.getFacet().equals(OWLFacet.MIN_EXCLUSIVE)) { facet = kernel.getMinExclusiveFacet(dv); } else if (restriction.getFacet().equals(OWLFacet.MAX_EXCLUSIVE)) { facet = kernel.getMaxExclusiveFacet(dv); } else if (restriction.getFacet().equals(OWLFacet.LENGTH)) { facet = kernel.getLength(dv); } else if (restriction.getFacet().equals(OWLFacet.MIN_LENGTH)) { facet = kernel.getMinLength(dv); } else if (restriction.getFacet().equals(OWLFacet.MAX_LENGTH)) { facet = kernel.getMaxLength(dv); } else if (restriction.getFacet().equals(OWLFacet.FRACTION_DIGITS)) { facet = kernel.getFractionDigitsFacet(dv); } else if (restriction.getFacet().equals(OWLFacet.PATTERN)) { facet = kernel.getPattern(dv); } else if (restriction.getFacet().equals(OWLFacet.TOTAL_DIGITS)) { facet = kernel.getTotalDigitsFacet(dv); } else { throw new OWLRuntimeException("Unsupported facet: " + restriction.getFacet()); } dte = kernel.getRestrictedDataType(dte, facet); } return dte; } } private class IndividualTranslator extends OWLEntityTranslator { public IndividualTranslator() { } @Override protected IndividualPointer getTopEntityPointer() { return null; } @Override protected IndividualPointer getBottomEntityPointer() { return null; } @Override protected IndividualPointer createPointerForEntity(OWLNamedIndividual entity) { return kernel.getIndividual(entity.toStringID()); } @Override protected OWLNamedIndividual getTopEntity() { return null; } @Override protected OWLNamedIndividual getBottomEntity() { return null; } @Override protected DefaultNode createDefaultNode() { return new OWLNamedIndividualNode(); } @Override protected DefaultNodeSet createDefaultNodeSet() { return new OWLNamedIndividualNodeSet(); } } private class ObjectPropertyTranslator extends OWLEntityTranslator { public ObjectPropertyTranslator() { } @Override protected ObjectPropertyPointer getTopEntityPointer() { return kernel.getTopObjectProperty(); } @Override protected ObjectPropertyPointer getBottomEntityPointer() { return kernel.getBottomObjectProperty(); } // TODO: add implementation of registerNewEntity @Override protected ObjectPropertyPointer registerNewEntity(OWLObjectPropertyExpression entity) { ObjectPropertyPointer pointer = createPointerForEntity(entity); fillEntityPointerMaps(entity, pointer); entity = entity.getInverseProperty().getSimplified(); fillEntityPointerMaps(entity, createPointerForEntity(entity)); return pointer; } @Override protected ObjectPropertyPointer createPointerForEntity(OWLObjectPropertyExpression entity) { // FIXME!! think later!! ObjectPropertyPointer p = kernel.getObjectProperty(entity.getNamedProperty().toStringID()); if (entity.isAnonymous()) // inverse! p = kernel.getInverseProperty(p); return p; } @Override protected OWLObjectProperty getTopEntity() { return getOWLDataFactory().getOWLTopObjectProperty(); } @Override protected OWLObjectProperty getBottomEntity() { return getOWLDataFactory().getOWLBottomObjectProperty(); } @Override protected DefaultNode createDefaultNode() { return new OWLObjectPropertyNode(); } @Override protected DefaultNodeSet createDefaultNodeSet() { return new OWLObjectPropertyNodeSet(); } } private class DataPropertyTranslator extends OWLEntityTranslator { public DataPropertyTranslator() { } @Override protected DataPropertyPointer getTopEntityPointer() { return kernel.getTopDataProperty(); } @Override protected DataPropertyPointer getBottomEntityPointer() { return kernel.getBottomDataProperty(); } @Override protected DataPropertyPointer createPointerForEntity(OWLDataProperty entity) { return kernel.getDataProperty(entity.toStringID()); } @Override protected OWLDataProperty getTopEntity() { return getOWLDataFactory().getOWLTopDataProperty(); } @Override protected OWLDataProperty getBottomEntity() { return getOWLDataFactory().getOWLBottomDataProperty(); } @Override protected DefaultNode createDefaultNode() { return new OWLDataPropertyNode(); } @Override protected DefaultNodeSet createDefaultNodeSet() { return new OWLDataPropertyNodeSet(); } } private class AxiomTranslator implements OWLAxiomVisitorEx { private final class DeclarationVisitorEx implements OWLEntityVisitorEx { public AxiomPointer visit(OWLClass cls) { return kernel.tellClassDeclaration(toClassPointer(cls)); } public AxiomPointer visit(OWLObjectProperty property) { return kernel.tellObjectPropertyDeclaration(toObjectPropertyPointer(property)); } public AxiomPointer visit(OWLDataProperty property) { return kernel.tellDataPropertyDeclaration(toDataPropertyPointer(property)); } public AxiomPointer visit(OWLNamedIndividual individual) { return kernel.tellIndividualDeclaration(toIndividualPointer(individual)); } public AxiomPointer visit(OWLDatatype datatype) { return kernel.tellDatatypeDeclaration(toDataTypePointer(datatype)); } public AxiomPointer visit(OWLAnnotationProperty property) { return null; } } private final DeclarationVisitorEx v; public AxiomTranslator() { v = new DeclarationVisitorEx(); } public AxiomPointer visit(OWLSubClassOfAxiom axiom) { return kernel.tellSubClassOf(toClassPointer(axiom.getSubClass()), toClassPointer(axiom.getSuperClass())); } public AxiomPointer visit(OWLNegativeObjectPropertyAssertionAxiom axiom) { return kernel.tellNotRelatedIndividuals(toIndividualPointer(axiom.getSubject()), toObjectPropertyPointer(axiom.getProperty()), toIndividualPointer(axiom.getObject())); } public AxiomPointer visit(OWLAsymmetricObjectPropertyAxiom axiom) { return kernel.tellAsymmetricObjectProperty(toObjectPropertyPointer(axiom.getProperty())); } public AxiomPointer visit(OWLReflexiveObjectPropertyAxiom axiom) { return kernel.tellReflexiveObjectProperty(toObjectPropertyPointer(axiom.getProperty())); } public AxiomPointer visit(OWLDisjointClassesAxiom axiom) { translateClassExpressionSet(axiom.getClassExpressions()); return kernel.tellDisjointClasses(); } private void translateClassExpressionSet(Collection classExpressions) { kernel.initArgList(); for (OWLClassExpression ce : classExpressions) { ClassPointer cp = toClassPointer(ce); kernel.addArg(cp); } kernel.closeArgList(); } public AxiomPointer visit(OWLDataPropertyDomainAxiom axiom) { return kernel.tellDataPropertyDomain(toDataPropertyPointer(axiom.getProperty()), toClassPointer(axiom.getDomain())); } public AxiomPointer visit(OWLObjectPropertyDomainAxiom axiom) { return kernel.tellObjectPropertyDomain(toObjectPropertyPointer(axiom.getProperty()), toClassPointer(axiom.getDomain())); } public AxiomPointer visit(OWLEquivalentObjectPropertiesAxiom axiom) { translateObjectPropertySet(axiom.getProperties()); return kernel.tellEquivalentObjectProperties(); } private void translateObjectPropertySet(Collection properties) { kernel.initArgList(); for (OWLObjectPropertyExpression property : properties) { ObjectPropertyPointer opp = toObjectPropertyPointer(property); kernel.addArg(opp); } kernel.closeArgList(); } public AxiomPointer visit(OWLNegativeDataPropertyAssertionAxiom axiom) { return kernel.tellNotRelatedIndividualValue(toIndividualPointer(axiom.getSubject()), toDataPropertyPointer(axiom.getProperty()), toDataValuePointer(axiom.getObject())); } public AxiomPointer visit(OWLDifferentIndividualsAxiom axiom) { translateIndividualSet(axiom.getIndividuals()); return kernel.tellDifferentIndividuals(); } public AxiomPointer visit(OWLDisjointDataPropertiesAxiom axiom) { translateDataPropertySet(axiom.getProperties()); return kernel.tellDisjointDataProperties(); } private void translateDataPropertySet(Set properties) { kernel.initArgList(); for (OWLDataPropertyExpression property : properties) { DataPropertyPointer dpp = toDataPropertyPointer(property); kernel.addArg(dpp); } kernel.closeArgList(); } public AxiomPointer visit(OWLDisjointObjectPropertiesAxiom axiom) { translateObjectPropertySet(axiom.getProperties()); return kernel.tellDisjointObjectProperties(); } public AxiomPointer visit(OWLObjectPropertyRangeAxiom axiom) { return kernel.tellObjectPropertyRange(toObjectPropertyPointer(axiom.getProperty()), toClassPointer(axiom.getRange())); } public AxiomPointer visit(OWLObjectPropertyAssertionAxiom axiom) { return kernel.tellRelatedIndividuals(toIndividualPointer(axiom.getSubject()), toObjectPropertyPointer(axiom.getProperty()), toIndividualPointer(axiom.getObject())); } public AxiomPointer visit(OWLFunctionalObjectPropertyAxiom axiom) { return kernel.tellFunctionalObjectProperty(toObjectPropertyPointer(axiom.getProperty())); } public AxiomPointer visit(OWLSubObjectPropertyOfAxiom axiom) { return kernel.tellSubObjectProperties(toObjectPropertyPointer(axiom.getSubProperty()), toObjectPropertyPointer(axiom.getSuperProperty())); } public AxiomPointer visit(OWLDisjointUnionAxiom axiom) { translateClassExpressionSet(axiom.getClassExpressions()); return kernel.tellDisjointUnion(toClassPointer(axiom.getOWLClass())); } public AxiomPointer visit(OWLDeclarationAxiom axiom) { OWLEntity entity = axiom.getEntity(); return entity.accept(v); } public AxiomPointer visit(OWLAnnotationAssertionAxiom axiom) { // Ignore return null; } public AxiomPointer visit(OWLSymmetricObjectPropertyAxiom axiom) { return kernel.tellSymmetricObjectProperty(toObjectPropertyPointer(axiom.getProperty())); } public AxiomPointer visit(OWLDataPropertyRangeAxiom axiom) { return kernel.tellDataPropertyRange(toDataPropertyPointer(axiom.getProperty()), toDataTypeExpressionPointer(axiom.getRange())); } public AxiomPointer visit(OWLFunctionalDataPropertyAxiom axiom) { return kernel.tellFunctionalDataProperty(toDataPropertyPointer(axiom.getProperty())); } public AxiomPointer visit(OWLEquivalentDataPropertiesAxiom axiom) { translateDataPropertySet(axiom.getProperties()); return kernel.tellEquivalentDataProperties(); } public AxiomPointer visit(OWLClassAssertionAxiom axiom) { return kernel.tellIndividualType(toIndividualPointer(axiom.getIndividual()), toClassPointer(axiom.getClassExpression())); } public AxiomPointer visit(OWLEquivalentClassesAxiom axiom) { translateClassExpressionSet(axiom.getClassExpressions()); return kernel.tellEquivalentClass(); } public AxiomPointer visit(OWLDataPropertyAssertionAxiom axiom) { return kernel.tellRelatedIndividualValue(toIndividualPointer(axiom.getSubject()), toDataPropertyPointer(axiom.getProperty()), toDataValuePointer(axiom.getObject())); } public AxiomPointer visit(OWLTransitiveObjectPropertyAxiom axiom) { return kernel.tellTransitiveObjectProperty(toObjectPropertyPointer(axiom.getProperty())); } public AxiomPointer visit(OWLIrreflexiveObjectPropertyAxiom axiom) { return kernel.tellIrreflexiveObjectProperty(toObjectPropertyPointer(axiom.getProperty())); } public AxiomPointer visit(OWLSubDataPropertyOfAxiom axiom) { return kernel.tellSubDataProperties(toDataPropertyPointer(axiom.getSubProperty()), toDataPropertyPointer(axiom.getSuperProperty())); } public AxiomPointer visit(OWLInverseFunctionalObjectPropertyAxiom axiom) { return kernel.tellInverseFunctionalObjectProperty(toObjectPropertyPointer(axiom.getProperty())); } public AxiomPointer visit(OWLSameIndividualAxiom axiom) { translateIndividualSet(axiom.getIndividuals()); return kernel.tellSameIndividuals(); } public AxiomPointer visit(OWLSubPropertyChainOfAxiom axiom) { translateObjectPropertySet(axiom.getPropertyChain()); return kernel.tellSubObjectProperties(kernel.getPropertyComposition(), toObjectPropertyPointer(axiom.getSuperProperty())); } public AxiomPointer visit(OWLInverseObjectPropertiesAxiom axiom) { return kernel.tellInverseProperties(toObjectPropertyPointer(axiom.getFirstProperty()), toObjectPropertyPointer(axiom.getSecondProperty())); } public AxiomPointer visit(OWLHasKeyAxiom axiom) { translateObjectPropertySet(axiom.getObjectPropertyExpressions()); ObjectPropertyPointer objectPropertyPointer = kernel.getObjectPropertyKey(); translateDataPropertySet(axiom.getDataPropertyExpressions()); DataPropertyPointer dataPropertyPointer = kernel.getDataPropertyKey(); return kernel.tellHasKey(toClassPointer(axiom.getClassExpression()), dataPropertyPointer, objectPropertyPointer); } public AxiomPointer visit(OWLDatatypeDefinitionAxiom axiom) { kernel.getDataSubType(axiom.getDatatype().getIRI().toString(), toDataTypeExpressionPointer(axiom.getDataRange())); return null; } public AxiomPointer visit(SWRLRule rule) { // Ignore return null; } public AxiomPointer visit(OWLSubAnnotationPropertyOfAxiom axiom) { // Ignore return null; } public AxiomPointer visit(OWLAnnotationPropertyDomainAxiom axiom) { // Ignore return null; } public AxiomPointer visit(OWLAnnotationPropertyRangeAxiom axiom) { // Ignore return null; } } private class EntailmentChecker implements OWLAxiomVisitorEx { public EntailmentChecker() { } public Boolean visit(OWLSubClassOfAxiom axiom) { if (axiom.getSuperClass().equals(getOWLDataFactory().getOWLThing())) { return true; } if (axiom.getSubClass().equals(getOWLDataFactory().getOWLNothing())) { return true; } return kernel.isClassSubsumedBy(toClassPointer(axiom.getSubClass()), toClassPointer(axiom.getSuperClass())); } public Boolean visit(OWLNegativeObjectPropertyAssertionAxiom axiom) { return axiom.asOWLSubClassOfAxiom().accept(this); } public Boolean visit(OWLAsymmetricObjectPropertyAxiom axiom) { return kernel.isObjectPropertyAsymmetric(toObjectPropertyPointer(axiom.getProperty())); } public Boolean visit(OWLReflexiveObjectPropertyAxiom axiom) { return kernel.isObjectPropertyReflexive(toObjectPropertyPointer(axiom.getProperty())); } public Boolean visit(OWLDisjointClassesAxiom axiom) { Set classExpressions = axiom.getClassExpressions(); if (classExpressions.size() == 2) { Iterator it = classExpressions.iterator(); return kernel.isClassDisjointWith(toClassPointer(it.next()), toClassPointer(it.next())); } else { for (OWLAxiom ax : axiom.asOWLSubClassOfAxioms()) { if (!ax.accept(this)) { return false; } } return true; } } public Boolean visit(OWLDataPropertyDomainAxiom axiom) { return axiom.asOWLSubClassOfAxiom().accept(this); } public Boolean visit(OWLObjectPropertyDomainAxiom axiom) { return axiom.asOWLSubClassOfAxiom().accept(this); } public Boolean visit(OWLEquivalentObjectPropertiesAxiom axiom) { for (OWLAxiom ax : axiom.asSubObjectPropertyOfAxioms()) { if (!ax.accept(this)) { return false; } } return true; } public Boolean visit(OWLNegativeDataPropertyAssertionAxiom axiom) { return axiom.asOWLSubClassOfAxiom().accept(this); } public Boolean visit(OWLDifferentIndividualsAxiom axiom) { for (OWLSubClassOfAxiom ax : axiom.asOWLSubClassOfAxioms()) { if (!ax.accept(this)) { return false; } } return true; } // TODO: this check is incomplete public Boolean visit(OWLDisjointDataPropertiesAxiom axiom) { kernel.initArgList(); for (OWLDataPropertyExpression p : axiom.getProperties()) { kernel.addArg(toDataPropertyPointer(p)); } kernel.closeArgList(); return kernel.arePropertiesDisjoint(); } public Boolean visit(OWLDisjointObjectPropertiesAxiom axiom) { kernel.initArgList(); for (OWLObjectPropertyExpression p : axiom.getProperties()) { kernel.addArg(toObjectPropertyPointer(p)); } kernel.closeArgList(); return kernel.arePropertiesDisjoint(); } public Boolean visit(OWLObjectPropertyRangeAxiom axiom) { return axiom.asOWLSubClassOfAxiom().accept(this); } public Boolean visit(OWLObjectPropertyAssertionAxiom axiom) { return axiom.asOWLSubClassOfAxiom().accept(this); } public Boolean visit(OWLFunctionalObjectPropertyAxiom axiom) { return kernel.isObjectPropertyFunctional(toObjectPropertyPointer(axiom.getProperty())); } public Boolean visit(OWLSubObjectPropertyOfAxiom axiom) { return kernel.isObjectSubPropertyOf(toObjectPropertyPointer(axiom.getSubProperty()), toObjectPropertyPointer(axiom.getSuperProperty())); } public Boolean visit(OWLDisjointUnionAxiom axiom) { return axiom.getOWLEquivalentClassesAxiom().accept(this) && axiom.getOWLDisjointClassesAxiom().accept(this); } public Boolean visit(OWLDeclarationAxiom axiom) { // TODO uhm might be needed? return false; } public Boolean visit(OWLAnnotationAssertionAxiom axiom) { return false; } public Boolean visit(OWLSymmetricObjectPropertyAxiom axiom) { return kernel.isObjectPropertySymmetric(toObjectPropertyPointer(axiom.getProperty())); } public Boolean visit(OWLDataPropertyRangeAxiom axiom) { return axiom.asOWLSubClassOfAxiom().accept(this); } public Boolean visit(OWLFunctionalDataPropertyAxiom axiom) { return kernel.isDataPropertyFunctional(toDataPropertyPointer(axiom.getProperty())); } public Boolean visit(OWLEquivalentDataPropertiesAxiom axiom) { // TODO check // this is not implemented in OWL API // for (OWLAxiom ax : axiom.asSubDataPropertyOfAxioms()) { // if (!ax.accept(this)) { // return false; // } // } // return true; return null; } public Boolean visit(OWLClassAssertionAxiom axiom) { return kernel.isInstanceOf(toIndividualPointer(axiom.getIndividual()), toClassPointer(axiom.getClassExpression())); } public Boolean visit(OWLEquivalentClassesAxiom axiom) { Set classExpressionSet = axiom.getClassExpressions(); if (classExpressionSet.size() == 2) { Iterator it = classExpressionSet.iterator(); return kernel.isClassEquivalentTo(toClassPointer(it.next()), toClassPointer(it.next())); } else { for (OWLAxiom ax : axiom.asOWLSubClassOfAxioms()) { if (!ax.accept(this)) { return false; } } return true; } } public Boolean visit(OWLDataPropertyAssertionAxiom axiom) { return axiom.asOWLSubClassOfAxiom().accept(this); } public Boolean visit(OWLTransitiveObjectPropertyAxiom axiom) { return kernel.isObjectPropertyTransitive(toObjectPropertyPointer(axiom.getProperty())); } public Boolean visit(OWLIrreflexiveObjectPropertyAxiom axiom) { return kernel.isObjectPropertyIrreflexive(toObjectPropertyPointer(axiom.getProperty())); } // TODO: this is incomplete public Boolean visit(OWLSubDataPropertyOfAxiom axiom) { return kernel.isDataSubPropertyOf(toDataPropertyPointer(axiom.getSubProperty()), toDataPropertyPointer(axiom.getSuperProperty())); } public Boolean visit(OWLInverseFunctionalObjectPropertyAxiom axiom) { return kernel.isObjectPropertyInverseFunctional(toObjectPropertyPointer(axiom.getProperty())); } public Boolean visit(OWLSameIndividualAxiom axiom) { for (OWLSameIndividualAxiom ax : axiom.asPairwiseAxioms()) { Iterator it = ax.getIndividuals().iterator(); OWLIndividual indA = it.next(); OWLIndividual indB = it.next(); if (!kernel.isSameAs(toIndividualPointer(indA), toIndividualPointer(indB))) { return false; } } return true; } public Boolean visit(OWLSubPropertyChainOfAxiom axiom) { kernel.initArgList(); for (OWLObjectPropertyExpression p : axiom.getPropertyChain()) { kernel.addArg(toObjectPropertyPointer(p)); } kernel.closeArgList(); return kernel.isSubPropertyChainOf(toObjectPropertyPointer(axiom.getSuperProperty())); } public Boolean visit(OWLInverseObjectPropertiesAxiom axiom) { for (OWLAxiom ax : axiom.asSubObjectPropertyOfAxioms()) { if (!ax.accept(this)) { return false; } } return true; } public Boolean visit(OWLHasKeyAxiom axiom) { // FIXME!! unsupported by FaCT++ ATM return null; } public Boolean visit(OWLDatatypeDefinitionAxiom axiom) { // FIXME!! unsupported by FaCT++ ATM return null; } public Boolean visit(SWRLRule rule) { // FIXME!! unsupported by FaCT++ ATM return null; } public Boolean visit(OWLSubAnnotationPropertyOfAxiom axiom) { return false; } public Boolean visit(OWLAnnotationPropertyDomainAxiom axiom) { return false; } public Boolean visit(OWLAnnotationPropertyRangeAxiom axiom) { return false; } } public synchronized void dispose() { manager.removeOntologyChangeListener(this); axiomTranslator = null; classExpressionTranslator = null; dataRangeTranslator = null; objectPropertyTranslator = null; dataPropertyTranslator = null; individualTranslator = null; entailmentChecker = null; axiom2PtrMap.clear(); ptr2AxiomMap.clear(); rawChanges.clear(); reasonerAxioms.clear(); kernel.dispose(); } private static class ProgressMonitorAdapter implements FaCTPlusPlusProgressMonitor { private int count = 0; private int total = 0; private final ReasonerProgressMonitor progressMonitor; private final AtomicBoolean interrupted; public ProgressMonitorAdapter(ReasonerProgressMonitor p, AtomicBoolean interr) { this.progressMonitor = p; this.interrupted = interr; } public void setClassificationStarted(int classCount) { count = 0; total = classCount; progressMonitor.reasonerTaskStarted(ReasonerProgressMonitor.CLASSIFYING); progressMonitor.reasonerTaskProgressChanged(count, classCount); } public void nextClass() { count++; progressMonitor.reasonerTaskProgressChanged(count, total); } public void setFinished() { progressMonitor.reasonerTaskStopped(); } public boolean isCancelled() { if (interrupted.get()) { throw new ReasonerInterruptedException(); } return false; } } public void dumpClassHierarchy(PrintStream pw, boolean includeBottomNode) { dumpSubClasses(getTopClassNode(), pw, 0, includeBottomNode); } private void dumpSubClasses(Node node, PrintStream pw, int depth, boolean includeBottomNode) { if (includeBottomNode || !node.isBottomNode()) { for (int i = 0; i < depth; i++) { pw.print(" "); } pw.println(node); for (Node sub : getSubClasses(node.getRepresentativeElement(), true)) { dumpSubClasses(sub, pw, depth + 1, includeBottomNode); } } } public NodePointer getRoot(OWLClassExpression expression) { return kernel.buildCompletionTree(toClassPointer(expression)); } public Node getObjectNeighbours(NodePointer object, boolean deterministicOnly) { return objectPropertyTranslator.getNodeFromPointers(kernel.getObjectNeighbours(object, deterministicOnly)); } public Node getDataNeighbours(NodePointer object, boolean deterministicOnly) { return dataPropertyTranslator.getNodeFromPointers(kernel.getDataNeighbours(object, deterministicOnly)); } public Collection getObjectNeighbours(NodePointer n, OWLObjectProperty property) { return Arrays.asList(kernel.getObjectNeighbours(n, toObjectPropertyPointer(property))); } public Collection getDataNeighbours(NodePointer n, OWLDataProperty property) { return Arrays.asList(kernel.getDataNeighbours(n, toDataPropertyPointer(property))); } public Node getObjectLabel(NodePointer object, boolean deterministicOnly) { return classExpressionTranslator.getNodeFromPointers(kernel.getObjectLabel(object, deterministicOnly)); } public Node getDataLabel(NodePointer object, boolean deterministicOnly) { return dataRangeTranslator.getNodeFromPointers(kernel.getDataLabel(object, deterministicOnly)); } /** * Build an atomic decomposition using syntactic/semantic locality checking * * @param useSemantic * if true, use semantic locality checking; if false, use * syntactic one * @param moduleType * if 0, use \bot modules; if 1, use \top modules; if 2, use STAR * modules * @return the size of the constructed atomic decomposition */ public int getAtomicDecompositionSize(boolean useSemantic, int moduleType) { return kernel.getAtomicDecompositionSize(useSemantic, moduleType); } public Set getAtomAxioms(int index) { AxiomPointer[] axioms = kernel.getAtomAxioms(index); return axiomsToSet(axioms); } private Set axiomsToSet(AxiomPointer[] axioms) { Set toReturn = new HashSet(); for (AxiomPointer p : axioms) { final OWLAxiom owlAxiom = ptr2AxiomMap.get(p); if (owlAxiom != null) { toReturn.add(owlAxiom); } } return toReturn; } public int[] getAtomDependents(int index) { return kernel.getAtomDependents(index); } private final class EntityVisitorEx implements OWLEntityVisitorEx { public Pointer visit(OWLClass cls) { return toClassPointer(cls); } public Pointer visit(OWLObjectProperty property) { return toObjectPropertyPointer(property); } public Pointer visit(OWLDataProperty property) { return toDataPropertyPointer(property); } public Pointer visit(OWLNamedIndividual individual) { return toIndividualPointer(individual); } public Pointer visit(OWLDatatype datatype) { return null; } public Pointer visit(OWLAnnotationProperty property) { return null; } } final EntityVisitorEx entityTranslator = new EntityVisitorEx(); /** * * @param signature * if true, use semantic locality checking; if false, use * syntactic one * @param moduleType * if 0, use \bot modules; if 1, use \top modules; if 2, use STAR * modules * @return */ public Set getModule(Set signature, boolean useSemantic, int moduleType) { kernel.initArgList(); for (OWLEntity entity : signature) kernel.addArg(entity.accept(entityTranslator)); AxiomPointer[] axioms = kernel.getModule(useSemantic, moduleType); return axiomsToSet(axioms); } public Set getNonLocal(Set signature, boolean useSemantic, int moduleType) { kernel.initArgList(); for (OWLEntity entity : signature) kernel.addArg(entity.accept(entityTranslator)); AxiomPointer[] axioms = kernel.getNonLocal(useSemantic, moduleType); return axiomsToSet(axioms); } } FaCTpp-src-v1.6.2~dfsg/src/FaCT++.JNI/0000755000000000000000000000000012112642473015463 5ustar rootrootFaCTpp-src-v1.6.2~dfsg/src/FaCT++.JNI/Queries.cpp0000644000000000000000000007366412112642405017617 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2006-2013 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ // this file contains implementation of DL query-related methods of FaCT++ JNI interface #include "uk_ac_manchester_cs_factplusplus_FaCTPlusPlus.h" #include "Kernel.h" #include "tJNICache.h" #include "JNIActor.h" #include "eFPPTimeout.h" #ifdef __cplusplus extern "C" { #endif //------------------------------------------------------------- // minimal query language (ASK languages) //------------------------------------------------------------- #define ASK_START do { try { #define ASK_END } \ catch ( const EFPPInconsistentKB& ) \ { ThrowICO(env); } \ catch ( const EFPPNonSimpleRole& nsr ) \ { ThrowNSR ( env, nsr.getRoleName() ); } \ catch ( const EFPPCycleInRIA& cir ) \ { ThrowRIC ( env, cir.getRoleName() ); } \ catch ( const EFPPTimeout& ) \ { ThrowTO(env); } \ catch ( const EFaCTPlusPlus& fpp ) \ { Throw ( env, fpp.what() ); } \ catch ( const std::exception& ex ) \ { Throw ( env, ex.what() ); } } while(0) #define PROCESS_QUERY(Action) ASK_START Action; ASK_END #define PROCESS_SIMPLE_QUERY(Action) ASK_START TJNICache* J = getJ(env,obj); Action; ASK_END /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: isKBConsistent * Signature: ()Z */ JNIEXPORT jboolean JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_isKBConsistent (JNIEnv * env, jobject obj) { TRACE_JNI("isKBConsistent"); bool ret = false; PROCESS_QUERY ( ret=getK(env,obj)->isKBConsistent() ); return ret; } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: classify * Signature: ()V */ JNIEXPORT void JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_classify (JNIEnv * env, jobject obj) { TRACE_JNI("classify"); PROCESS_QUERY ( getK(env,obj)->classifyKB() ); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: realise * Signature: ()V */ JNIEXPORT void JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_realise (JNIEnv * env, jobject obj) { TRACE_JNI("realise"); PROCESS_QUERY ( getK(env,obj)->realiseKB() ); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: isRealised * Signature: ()Z */ JNIEXPORT jboolean JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_isRealised (JNIEnv * env, jobject obj) { TRACE_JNI("isRealised"); return getK(env,obj)->isKBRealised(); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: isClassSatisfiable * Signature: (Luk/ac/manchester/cs/factplusplus/ClassPointer;)Z */ JNIEXPORT jboolean JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_isClassSatisfiable (JNIEnv * env, jobject obj, jobject arg) { TRACE_JNI("isClassSatisfiable"); TRACE_ARG(env,obj,arg); bool ret = false; PROCESS_SIMPLE_QUERY ( ret=J->K->isSatisfiable(getROConceptExpr(env,arg)) ); return ret; } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: isClassSubsumedBy * Signature: (Luk/ac/manchester/cs/factplusplus/ClassPointer;Luk/ac/manchester/cs/factplusplus/ClassPointer;)Z */ JNIEXPORT jboolean JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_isClassSubsumedBy (JNIEnv * env, jobject obj, jobject arg1, jobject arg2) { TRACE_JNI("isClassSubsumedBy"); TRACE_ARG(env,obj,arg1); TRACE_ARG(env,obj,arg2); bool ret = false; PROCESS_SIMPLE_QUERY ( ret=J->K->isSubsumedBy ( getROConceptExpr(env,arg1), getROConceptExpr(env,arg2) ) ); return ret; } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: isClassEquivalentTo * Signature: (Luk/ac/manchester/cs/factplusplus/ClassPointer;Luk/ac/manchester/cs/factplusplus/ClassPointer;)Z */ JNIEXPORT jboolean JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_isClassEquivalentTo (JNIEnv * env, jobject obj, jobject arg1, jobject arg2) { TRACE_JNI("isClassEquivalentTo"); TRACE_ARG(env,obj,arg1); TRACE_ARG(env,obj,arg2); bool ret = false; PROCESS_SIMPLE_QUERY ( ret=J->K->isEquivalent ( getROConceptExpr(env,arg1), getROConceptExpr(env,arg2) ) ); return ret; } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: isClassDisjointWith * Signature: (Luk/ac/manchester/cs/factplusplus/ClassPointer;Luk/ac/manchester/cs/factplusplus/ClassPointer;)Z */ JNIEXPORT jboolean JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_isClassDisjointWith (JNIEnv * env, jobject obj, jobject arg1, jobject arg2) { TRACE_JNI("isClassDisjointWith"); TRACE_ARG(env,obj,arg1); TRACE_ARG(env,obj,arg2); bool ret = false; PROCESS_SIMPLE_QUERY ( ret=J->K->isDisjoint ( getROConceptExpr(env,arg1), getROConceptExpr(env,arg2) ) ); return ret; } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: askSubClasses * Signature: (Luk/ac/manchester/cs/factplusplus/ClassPointer;Z)[[Luk/ac/manchester/cs/factplusplus/ClassPointer; */ JNIEXPORT jobjectArray JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_askSubClasses (JNIEnv * env, jobject obj, jobject arg, jboolean direct) { TRACE_JNI("askSubClasses"); TRACE_ARG(env,obj,arg); TJNICache* J = getJ(env,obj); JTaxonomyActor actor(J); const TConceptExpr* p = getROConceptExpr(env,arg); PROCESS_QUERY ( J->K->getSubConcepts(p,direct,actor) ); return actor.getElements(); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: askSuperClasses * Signature: (Luk/ac/manchester/cs/factplusplus/ClassPointer;Z)[[Luk/ac/manchester/cs/factplusplus/ClassPointer; */ JNIEXPORT jobjectArray JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_askSuperClasses (JNIEnv * env, jobject obj, jobject arg, jboolean direct) { TRACE_JNI("askSuperClasses"); TRACE_ARG(env,obj,arg); TJNICache* J = getJ(env,obj); JTaxonomyActor actor(J); const TConceptExpr* p = getROConceptExpr(env,arg); PROCESS_QUERY ( J->K->getSupConcepts(p,direct,actor) ); return actor.getElements(); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: askEquivalentClasses * Signature: (Luk/ac/manchester/cs/factplusplus/ClassPointer;)[Luk/ac/manchester/cs/factplusplus/ClassPointer; */ JNIEXPORT jobjectArray JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_askEquivalentClasses (JNIEnv * env, jobject obj, jobject arg) { TRACE_JNI("askEquivalentClasses"); TRACE_ARG(env,obj,arg); TJNICache* J = getJ(env,obj); JTaxonomyActor actor(J); PROCESS_QUERY ( J->K->getEquivalentConcepts ( getROConceptExpr(env,arg), actor ) ); return actor.getSynonyms(); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: askDisjointClasses * Signature: (Luk/ac/manchester/cs/factplusplus/ClassPointer;)[[Luk/ac/manchester/cs/factplusplus/ClassPointer; */ JNIEXPORT jobjectArray JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_askDisjointClasses (JNIEnv * env, jobject obj, jobject arg) { TRACE_JNI("askDisjointClasses"); TRACE_ARG(env,obj,arg); TJNICache* J = getJ(env,obj); JTaxonomyActor actor(J); const TConceptExpr* p = getROConceptExpr(env,arg); PROCESS_QUERY ( J->K->getDisjointConcepts(p,actor) ); return actor.getElements(); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: askSuperObjectProperties * Signature: (Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;Z)[[Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer; */ JNIEXPORT jobjectArray JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_askSuperObjectProperties (JNIEnv * env, jobject obj, jobject arg, jboolean direct) { TRACE_JNI("askSuperObjectProperties"); TRACE_ARG(env,obj,arg); TJNICache* J = getJ(env,obj); JTaxonomyActor actor(J); const TORoleExpr* p = getROORoleExpr(env,arg); PROCESS_QUERY ( J->K->getSupRoles(p,direct,actor) ); return actor.getElements(); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: askSubObjectProperties * Signature: (Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;Z)[[Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer; */ JNIEXPORT jobjectArray JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_askSubObjectProperties (JNIEnv * env, jobject obj, jobject arg, jboolean direct) { TRACE_JNI("askSubObjectProperties"); TRACE_ARG(env,obj,arg); TJNICache* J = getJ(env,obj); JTaxonomyActor actor(J); const TORoleExpr* p = getROORoleExpr(env,arg); PROCESS_QUERY ( J->K->getSubRoles(p,direct,actor) ); return actor.getElements(); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: askEquivalentObjectProperties * Signature: (Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;)[Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer; */ JNIEXPORT jobjectArray JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_askEquivalentObjectProperties (JNIEnv * env, jobject obj, jobject arg) { TRACE_JNI("askEquivalentObjectProperties"); TRACE_ARG(env,obj,arg); TJNICache* J = getJ(env,obj); JTaxonomyActor actor(J); PROCESS_QUERY ( J->K->getEquivalentRoles ( getROORoleExpr(env,arg), actor ) ); return actor.getSynonyms(); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: askObjectPropertyDomain * Signature: (Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;Z)[[Luk/ac/manchester/cs/factplusplus/ClassPointer; */ JNIEXPORT jobjectArray JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_askObjectPropertyDomain (JNIEnv * env, jobject obj, jobject arg, jboolean direct) { TRACE_JNI("askObjectPropertyDomain"); TRACE_ARG(env,obj,arg); TJNICache* J = getJ(env,obj); JTaxonomyActor actor(J); PROCESS_QUERY ( J->K->getORoleDomain ( getROORoleExpr(env,arg), direct, actor ) ); return actor.getElements(); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: askObjectPropertyRange * Signature: (Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;Z)[[Luk/ac/manchester/cs/factplusplus/ClassPointer; */ JNIEXPORT jobjectArray JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_askObjectPropertyRange (JNIEnv * env, jobject obj, jobject arg, jboolean direct) { TRACE_JNI("askObjectPropertyRange"); TRACE_ARG(env,obj,arg); TJNICache* J = getJ(env,obj); JTaxonomyActor actor(J); PROCESS_QUERY ( J->K->getRoleRange ( getROORoleExpr(env,arg), direct, actor ) ); return actor.getElements(); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: isObjectPropertyFunctional * Signature: (Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;)Z */ JNIEXPORT jboolean JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_isObjectPropertyFunctional (JNIEnv * env, jobject obj, jobject arg) { TRACE_JNI("isObjectPropertyFunctional"); TRACE_ARG(env,obj,arg); bool ret = false; PROCESS_SIMPLE_QUERY ( ret=J->K->isFunctional(getROORoleExpr(env,arg)) ); return ret; } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: isObjectPropertyInverseFunctional * Signature: (Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;)Z */ JNIEXPORT jboolean JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_isObjectPropertyInverseFunctional (JNIEnv * env, jobject obj, jobject arg) { TRACE_JNI("isObjectPropertyInverseFunctional"); TRACE_ARG(env,obj,arg); bool ret = false; PROCESS_SIMPLE_QUERY ( ret=J->K->isInverseFunctional(getROORoleExpr(env,arg)) ); return ret; } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: isObjectPropertySymmetric * Signature: (Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;)Z */ JNIEXPORT jboolean JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_isObjectPropertySymmetric (JNIEnv * env, jobject obj, jobject arg) { TRACE_JNI("isObjectPropertySymmetric"); TRACE_ARG(env,obj,arg); bool ret = false; PROCESS_SIMPLE_QUERY ( ret=J->K->isSymmetric(getROORoleExpr(env,arg)) ); return ret; } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: isObjectPropertyAsymmetric * Signature: (Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;)Z */ JNIEXPORT jboolean JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_isObjectPropertyAsymmetric (JNIEnv * env, jobject obj, jobject arg) { TRACE_JNI("isObjectPropertyAsymmetric"); TRACE_ARG(env,obj,arg); bool ret = false; PROCESS_SIMPLE_QUERY ( ret=J->K->isAsymmetric(getROORoleExpr(env,arg)) ); return ret; } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: isObjectPropertyTransitive * Signature: (Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;)Z */ JNIEXPORT jboolean JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_isObjectPropertyTransitive (JNIEnv * env, jobject obj, jobject arg) { TRACE_JNI("isObjectPropertyTransitive"); TRACE_ARG(env,obj,arg); bool ret = false; PROCESS_SIMPLE_QUERY ( ret=J->K->isTransitive(getROORoleExpr(env,arg)) ); return ret; } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: isObjectPropertyReflexive * Signature: (Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;)Z */ JNIEXPORT jboolean JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_isObjectPropertyReflexive (JNIEnv * env, jobject obj, jobject arg) { TRACE_JNI("isObjectPropertyReflexive"); TRACE_ARG(env,obj,arg); bool ret = false; PROCESS_SIMPLE_QUERY ( ret=J->K->isReflexive(getROORoleExpr(env,arg)) ); return ret; } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: isObjectPropertyIrreflexive * Signature: (Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;)Z */ JNIEXPORT jboolean JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_isObjectPropertyIrreflexive (JNIEnv * env, jobject obj, jobject arg) { TRACE_JNI("isObjectPropertyIrreflexive"); TRACE_ARG(env,obj,arg); bool ret = false; PROCESS_SIMPLE_QUERY ( ret=J->K->isIrreflexive(getROORoleExpr(env,arg)) ); return ret; } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: isObjectSubPropertyOf * Signature: (Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;)Z */ JNIEXPORT jboolean JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_isObjectSubPropertyOf (JNIEnv * env, jobject obj, jobject arg1, jobject arg2) { TRACE_JNI("isObjectSubPropertyOf"); TRACE_ARG(env,obj,arg1); TRACE_ARG(env,obj,arg2); bool ret = false; PROCESS_SIMPLE_QUERY ( ret=J->K->isSubRoles ( getROORoleExpr(env,arg1), getROORoleExpr(env,arg2) ) ); return ret; } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: isObjectPropertyDisjointWith * Signature: (Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;)Z */ JNIEXPORT jboolean JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_isObjectPropertyDisjointWith (JNIEnv * env, jobject obj, jobject arg1, jobject arg2) { TRACE_JNI("isObjectPropertyDisjointWith"); TRACE_ARG(env,obj,arg1); TRACE_ARG(env,obj,arg2); bool ret = false; PROCESS_SIMPLE_QUERY ( ret=J->K->isDisjointRoles ( getROORoleExpr(env,arg1), getROORoleExpr(env,arg2) ) ); return ret; } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: isSubPropertyChainOf * Signature: (Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;)Z */ JNIEXPORT jboolean JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_isSubPropertyChainOf (JNIEnv * env, jobject obj, jobject arg) { TRACE_JNI("isSubPropertyChainOf"); TRACE_ARG(env,obj,arg); bool ret = false; PROCESS_SIMPLE_QUERY ( ret=J->K->isSubChain(getROORoleExpr(env,arg)) ); return ret; } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: arePropertiesDisjoint * Signature: ()Z */ JNIEXPORT jboolean JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_arePropertiesDisjoint (JNIEnv * env, jobject obj) { TRACE_JNI("arePropertiesDisjoint"); bool ret = false; PROCESS_SIMPLE_QUERY ( ret=J->K->isDisjointRoles() ); return ret; } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: askSuperDataProperties * Signature: (Luk/ac/manchester/cs/factplusplus/DataPropertyPointer;Z)[[Luk/ac/manchester/cs/factplusplus/DataPropertyPointer; */ JNIEXPORT jobjectArray JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_askSuperDataProperties (JNIEnv * env, jobject obj, jobject arg, jboolean direct) { TRACE_JNI("askSuperDataProperties"); TRACE_ARG(env,obj,arg); TJNICache* J = getJ(env,obj); JTaxonomyActor actor(J); const TDRoleExpr* p = getRODRoleExpr(env,arg); PROCESS_QUERY ( J->K->getSupRoles(p,direct,actor) ); return actor.getElements(); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: askSubDataProperties * Signature: (Luk/ac/manchester/cs/factplusplus/DataPropertyPointer;Z)[[Luk/ac/manchester/cs/factplusplus/DataPropertyPointer; */ JNIEXPORT jobjectArray JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_askSubDataProperties (JNIEnv * env, jobject obj, jobject arg, jboolean direct) { TRACE_JNI("askSubDataProperties"); TRACE_ARG(env,obj,arg); TJNICache* J = getJ(env,obj); JTaxonomyActor actor(J); const TDRoleExpr* p = getRODRoleExpr(env,arg); PROCESS_QUERY ( J->K->getSubRoles(p,direct,actor) ); return actor.getElements(); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: askEquivalentDataProperties * Signature: (Luk/ac/manchester/cs/factplusplus/DataPropertyPointer;)[Luk/ac/manchester/cs/factplusplus/DataPropertyPointer; */ JNIEXPORT jobjectArray JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_askEquivalentDataProperties (JNIEnv * env, jobject obj, jobject arg) { TRACE_JNI("askEquivalentDataProperties"); TRACE_ARG(env,obj,arg); TJNICache* J = getJ(env,obj); JTaxonomyActor actor(J); PROCESS_QUERY ( J->K->getEquivalentRoles ( getRODRoleExpr(env,arg), actor ) ); return actor.getSynonyms(); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: askDataPropertyDomain * Signature: (Luk/ac/manchester/cs/factplusplus/DataPropertyPointer;Z)[[Luk/ac/manchester/cs/factplusplus/ClassPointer; */ JNIEXPORT jobjectArray JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_askDataPropertyDomain (JNIEnv * env, jobject obj, jobject arg, jboolean direct) { TRACE_JNI("askDataPropertyDomain"); TRACE_ARG(env,obj,arg); TJNICache* J = getJ(env,obj); JTaxonomyActor actor(J); PROCESS_QUERY ( J->K->getDRoleDomain ( getRODRoleExpr(env,arg), direct, actor ) ); return actor.getElements(); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: isDataPropertyFunctional * Signature: (Luk/ac/manchester/cs/factplusplus/DataPropertyPointer;)Z */ JNIEXPORT jboolean JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_isDataPropertyFunctional (JNIEnv * env, jobject obj, jobject arg) { TRACE_JNI("isDataPropertyFunctional"); TRACE_ARG(env,obj,arg); bool ret = false; PROCESS_SIMPLE_QUERY ( ret=J->K->isFunctional(getRODRoleExpr(env,arg)) ); return ret; } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: isDataSubPropertyOf * Signature: (Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;)Z */ JNIEXPORT jboolean JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_isDataSubPropertyOf (JNIEnv * env, jobject obj, jobject arg1, jobject arg2) { TRACE_JNI("isDataSubPropertyOf"); TRACE_ARG(env,obj,arg1); TRACE_ARG(env,obj,arg2); bool ret = false; PROCESS_SIMPLE_QUERY ( ret=J->K->isSubRoles ( getRODRoleExpr(env,arg1), getRODRoleExpr(env,arg2) ) ); return ret; } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: isObjectPropertyDisjointWith * Signature: (Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;)Z */ JNIEXPORT jboolean JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_isDataPropertyDisjointWith (JNIEnv * env, jobject obj, jobject arg1, jobject arg2) { TRACE_JNI("isDataPropertyDisjointWith"); TRACE_ARG(env,obj,arg1); TRACE_ARG(env,obj,arg2); bool ret = false; PROCESS_SIMPLE_QUERY ( ret=J->K->isDisjointRoles ( getRODRoleExpr(env,arg1), getRODRoleExpr(env,arg2) ) ); return ret; } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: askIndividualTypes * Signature: (Luk/ac/manchester/cs/factplusplus/IndividualPointer;Z)[[Luk/ac/manchester/cs/factplusplus/ClassPointer; */ JNIEXPORT jobjectArray JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_askIndividualTypes (JNIEnv * env, jobject obj, jobject arg, jboolean direct) { TRACE_JNI("askIndividualTypes"); TRACE_ARG(env,obj,arg); TJNICache* J = getJ(env,obj); JTaxonomyActor actor(J); const TIndividualExpr* p = getROIndividualExpr(env,arg); PROCESS_QUERY ( J->K->getTypes(p,direct,actor) ); return actor.getElements(); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: askObjectProperties * Signature: (Luk/ac/manchester/cs/factplusplus/IndividualPointer;)[Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer; */ JNIEXPORT jobjectArray JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_askObjectProperties (JNIEnv * env, jobject obj, jobject arg) { TRACE_JNI("askObjectProperties"); TRACE_ARG(env,obj,arg); TJNICache* J = getJ(env,obj); ReasoningKernel::NamesVector Rs; PROCESS_QUERY ( J->K->getRelatedRoles ( getROIndividualExpr(env,arg), Rs, /*data=*/false, /*needI=*/false ) ); std::vector acc; for ( ReasoningKernel::NamesVector::const_iterator p = Rs.begin(), p_end = Rs.end(); p < p_end; ++p ) acc.push_back(J->getOName((*p)->getName())); return J->buildArray ( acc, J->ObjectPropertyPointer ); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: askRelatedIndividuals * Signature: (Luk/ac/manchester/cs/factplusplus/IndividualPointer;Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;)[Luk/ac/manchester/cs/factplusplus/IndividualPointer; */ JNIEXPORT jobjectArray JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_askRelatedIndividuals (JNIEnv * env, jobject obj, jobject arg1, jobject arg2) { TRACE_JNI("askRelatedIndividuals"); TRACE_ARG(env,obj,arg1); TRACE_ARG(env,obj,arg2); TJNICache* J = getJ(env,obj); ReasoningKernel::NamesVector Js; PROCESS_QUERY ( J->K->getRoleFillers ( getROIndividualExpr(env,arg1), getROORoleExpr(env,arg2), Js ) ); std::vector acc; for ( ReasoningKernel::NamesVector::const_iterator p = Js.begin(), p_end = Js.end(); p < p_end; ++p ) acc.push_back(J->getIName((*p)->getName())); return J->buildArray ( acc, J->IndividualPointer ); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: askDataProperties * Signature: (Luk/ac/manchester/cs/factplusplus/IndividualPointer;)[Luk/ac/manchester/cs/factplusplus/DataPropertyPointer; */ JNIEXPORT jobjectArray JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_askDataProperties (JNIEnv * env, jobject obj, jobject arg) { TRACE_JNI("askDataProperties"); TRACE_ARG(env,obj,arg); TJNICache* J = getJ(env,obj); ReasoningKernel::NamesVector Rs; PROCESS_QUERY ( J->K->getRelatedRoles ( getROIndividualExpr(env,arg), Rs, /*data=*/true, /*needI=*/false ) ); std::vector acc; for ( ReasoningKernel::NamesVector::const_iterator p = Rs.begin(), p_end = Rs.end(); p < p_end; ++p ) acc.push_back(J->getDName((*p)->getName())); return J->buildArray ( acc, J->DataPropertyPointer ); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: askRelatedValues * Signature: (Luk/ac/manchester/cs/factplusplus/IndividualPointer;Luk/ac/manchester/cs/factplusplus/DataPropertyPointer;)[Luk/ac/manchester/cs/factplusplus/DataValuePointer; */ JNIEXPORT jobjectArray JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_askRelatedValues (JNIEnv * env, jobject obj ATTR_UNUSED, jobject arg1 ATTR_UNUSED, jobject arg2 ATTR_UNUSED) { TRACE_JNI("askRelatedValues"); TRACE_ARG(env,obj,arg1); TRACE_ARG(env,obj,arg2); Throw ( env, "FaCT++ Kernel: unsupported operation 'askRelatedValues'" ); return NULL; #if 0 ReasoningKernel::NamesVector Js; PROCESS_SIMPLE_QUERY ( J->K->getRoleFillers ( getROIndividualExpr(env,arg1), getRODRoleExpr(env,arg2), Js ) ); std::vector acc; for ( ReasoningKernel::NamesVector::const_iterator p = Js.begin(), p_end = Js.end(); p < p_end; ++p ) acc.push_back(new TExpr(TLexeme(DATAEXPR,const_cast(*p)))); return J->buildArray ( acc, J->DataValuePointer ); #endif } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: hasDataPropertyRelationship * Signature: (Luk/ac/manchester/cs/factplusplus/IndividualPointer;Luk/ac/manchester/cs/factplusplus/DataPropertyPointer;Luk/ac/manchester/cs/factplusplus/DataValuePointer;)Z */ JNIEXPORT jboolean JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_hasDataPropertyRelationship (JNIEnv * env, jobject obj ATTR_UNUSED, jobject arg1 ATTR_UNUSED, jobject arg2 ATTR_UNUSED, jobject arg3 ATTR_UNUSED) { TRACE_JNI("hasDataPropertyRelationship"); TRACE_ARG(env,obj,arg1); TRACE_ARG(env,obj,arg2); TRACE_ARG(env,obj,arg3); Throw ( env, "FaCT++ Kernel: unsupported operation 'hasDataPropertyRelationship'" ); return NULL; #if 0 bool ret = false; PROCESS_SIMPLE_QUERY ( ret=J->K->isRelated ( getROIndividualExpr(env,arg1), getRODRoleExpr(env,arg2), getROIndividualExpr(env,arg3) ) ); return ret; #endif } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: hasObjectPropertyRelationship * Signature: (Luk/ac/manchester/cs/factplusplus/IndividualPointer;Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;Luk/ac/manchester/cs/factplusplus/IndividualPointer;)Z */ JNIEXPORT jboolean JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_hasObjectPropertyRelationship (JNIEnv * env, jobject obj, jobject arg1, jobject arg2, jobject arg3) { TRACE_JNI("hasObjectPropertyRelationship"); TRACE_ARG(env,obj,arg1); TRACE_ARG(env,obj,arg2); TRACE_ARG(env,obj,arg3); bool ret = false; PROCESS_SIMPLE_QUERY ( ret=J->K->isRelated ( getROIndividualExpr(env,arg1), getROORoleExpr(env,arg2), getROIndividualExpr(env,arg3) ) ); return ret; } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: isInstanceOf * Signature: (Luk/ac/manchester/cs/factplusplus/IndividualPointer;Luk/ac/manchester/cs/factplusplus/ClassPointer;)Z */ JNIEXPORT jboolean JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_isInstanceOf (JNIEnv * env, jobject obj, jobject arg1, jobject arg2) { TRACE_JNI("isInstanceOf"); TRACE_ARG(env,obj,arg1); TRACE_ARG(env,obj,arg2); bool ret = false; PROCESS_SIMPLE_QUERY ( ret=J->K->isInstance ( getROIndividualExpr(env,arg1), getROConceptExpr(env,arg2) ) ); return ret; } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: askInstances * Signature: (Luk/ac/manchester/cs/factplusplus/ClassPointer;Z)[Luk/ac/manchester/cs/factplusplus/IndividualPointer; */ JNIEXPORT jobjectArray JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_askInstances (JNIEnv * env, jobject obj, jobject arg, jboolean direct) { TRACE_JNI("askInstances"); TRACE_ARG(env,obj,arg); TJNICache* J = getJ(env,obj); JTaxonomyActor > actor(J); const TConceptExpr* p = getROConceptExpr(env,arg); PROCESS_QUERY ( direct ? J->K->getDirectInstances(p,actor) : J->K->getInstances(p,actor) ); return actor.getElements(); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: askInstancesGrouped * Signature: (Luk/ac/manchester/cs/factplusplus/ClassPointer;Z)[[Luk/ac/manchester/cs/factplusplus/IndividualPointer; */ JNIEXPORT jobjectArray JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_askInstancesGrouped (JNIEnv * env, jobject obj, jobject arg, jboolean direct) { TRACE_JNI("askInstancesGrouped"); TRACE_ARG(env,obj,arg); TJNICache* J = getJ(env,obj); JTaxonomyActor > actor(J); const TConceptExpr* p = getROConceptExpr(env,arg); PROCESS_QUERY ( direct ? J->K->getDirectInstances(p,actor) : J->K->getInstances(p,actor) ); return actor.getElements(); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: askSameAs * Signature: (Luk/ac/manchester/cs/factplusplus/IndividualPointer;)[Luk/ac/manchester/cs/factplusplus/IndividualPointer; */ JNIEXPORT jobjectArray JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_askSameAs (JNIEnv * env, jobject obj, jobject arg) { TRACE_JNI("askSameAs"); TRACE_ARG(env,obj,arg); TJNICache* J = getJ(env,obj); JTaxonomyActor > actor(J); PROCESS_QUERY ( J->K->getSameAs ( getROIndividualExpr(env,arg), actor ) ); return actor.getSynonyms(); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: isSameAs * Signature: (Luk/ac/manchester/cs/factplusplus/IndividualPointer;Luk/ac/manchester/cs/factplusplus/IndividualPointer;)Z */ JNIEXPORT jboolean JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_isSameAs (JNIEnv * env, jobject obj, jobject arg1, jobject arg2) { TRACE_JNI("isSameAs"); TRACE_ARG(env,obj,arg1); TRACE_ARG(env,obj,arg2); bool ret = false; PROCESS_SIMPLE_QUERY ( ret=J->K->isSameIndividuals ( getROIndividualExpr(env,arg1), getROIndividualExpr(env,arg2) ) ); return ret; } #undef PROCESS_QUERY #undef PROCESS_SIMPLE_QUERY #ifdef __cplusplus } #endif FaCTpp-src-v1.6.2~dfsg/src/FaCT++.JNI/tJNICache.h0000644000000000000000000001660512112667451017377 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2006-2013 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef JNICACHE_H #define JNICACHE_H #include "JNISupport.h" //------------------------------------------------------ // Keeps class names and field IDs for different Java classes in FaCT++ interface //------------------------------------------------------ /// keep class, Node field and c'tor of an interface class class TClassFieldMethodIDs { protected: // members /// full qualifier for the array const char* ArrayClassName; public: // members /// class name jclass ClassID; /// array class type jclass ArrayClassID; /// c'tor type jmethodID CtorID; /// 'node' field jfieldID NodeFID; public: // interface /// c'tor: init class name TClassFieldMethodIDs ( const char* arrayClassName ) : ArrayClassName(arrayClassName) , ClassID(0) , ArrayClassID(0) , CtorID(0) , NodeFID(0) {} /// init values by class name void init ( JNIEnv* env ) { jclass id = env->FindClass(ArrayClassName+1); if ( id == 0 ) { Throw ( env, "Can't get class for Pointer" ); return; } ClassID = reinterpret_cast(env->NewGlobalRef(id)); id = env->FindClass(ArrayClassName); if ( id == 0 ) { Throw ( env, "Can't get class for [Pointer" ); return; } ArrayClassID = reinterpret_cast(env->NewGlobalRef(id)); CtorID = env->GetMethodID ( ClassID, "", "()V" ); if ( CtorID == 0 ) { Throw ( env, "Can't get c'tor for Pointer" ); return; } NodeFID = env->GetFieldID ( ClassID, "node", "J" ); if ( NodeFID == 0 ) { Throw ( env, "Can't get 'node' field" ); return; } } void fini ( JNIEnv* env ) { env->DeleteGlobalRef(ClassID); env->DeleteGlobalRef(ArrayClassID); } }; // TClassFieldMethodIDs /// Keep all the classes cache together with ENV class TJNICache { public: // members /// copy of an ENV to work with a given kernel JNIEnv* env; /// link to the owned kernel ReasoningKernel* K; /// attached Expression Manager TExpressionManager* EM; /// cached IDs for known classes TClassFieldMethodIDs ClassPointer, IndividualPointer, ObjectPropertyPointer, DataPropertyPointer, DataTypePointer, DataTypeExpressionPointer, DataValuePointer, DataTypeFacet, NodePointer, AxiomPointer; protected: // methods /// init all the IDs void init ( void ) { ClassPointer.init(env); IndividualPointer.init(env); ObjectPropertyPointer.init(env); DataPropertyPointer.init(env); DataTypePointer.init(env); DataTypeExpressionPointer.init(env); DataValuePointer.init(env); DataTypeFacet.init(env); NodePointer.init(env); AxiomPointer.init(env); } /// finilise all the IDs void fini ( void ) { ClassPointer.fini(env); IndividualPointer.fini(env); ObjectPropertyPointer.fini(env); DataPropertyPointer.fini(env); DataTypePointer.fini(env); DataTypeExpressionPointer.fini(env); DataValuePointer.fini(env); DataTypeFacet.fini(env); NodePointer.fini(env); AxiomPointer.fini(env); } /// get an object out of an arbitrary pointer jobject retObject ( const void* pointer, const TClassFieldMethodIDs& ID ) { if ( unlikely(pointer == NULL) ) { Throw ( env, "Incorrect operand by FaCT++ Kernel" ); return (jobject)0; } // create an object to return jobject obj = env->NewObject ( ID.ClassID, ID.CtorID ); if ( unlikely(obj == 0) ) Throw ( env, "Can't create Pointer object" ); else // set the return value env->SetLongField ( obj, ID.NodeFID, (jlong)pointer ); return obj; } public: // members /// ctor: init all the IDs TJNICache ( JNIEnv* e ) : env(e) , ClassPointer("[Luk/ac/manchester/cs/factplusplus/ClassPointer;") , IndividualPointer("[Luk/ac/manchester/cs/factplusplus/IndividualPointer;") , ObjectPropertyPointer("[Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;") , DataPropertyPointer("[Luk/ac/manchester/cs/factplusplus/DataPropertyPointer;") , DataTypePointer("[Luk/ac/manchester/cs/factplusplus/DataTypePointer;") , DataTypeExpressionPointer("[Luk/ac/manchester/cs/factplusplus/DataTypeExpressionPointer;") , DataValuePointer("[Luk/ac/manchester/cs/factplusplus/DataValuePointer;") , DataTypeFacet("[Luk/ac/manchester/cs/factplusplus/DataTypeFacet;") , NodePointer("[Luk/ac/manchester/cs/factplusplus/NodePointer;") , AxiomPointer("[Luk/ac/manchester/cs/factplusplus/AxiomPointer;") { init(); } /// d'tor: release all names ~TJNICache ( void ) { /*fini();*/ } /// switch the env to a new one E void reset ( JNIEnv* e ) { // fini(); env = e; init(); } /// object for class expression jobject Class ( TConceptExpr* expr ) { return retObject ( expr, ClassPointer ); } /// object for individual expression jobject Individual ( TIndividualExpr* expr ) { return retObject ( expr, IndividualPointer ); } jobject ObjectProperty ( TORoleExpr* expr ) { return retObject ( expr, ObjectPropertyPointer ); } jobject ObjectComplex ( TORoleComplexExpr* expr ) { return retObject ( expr, ObjectPropertyPointer ); } jobject DataProperty ( TDRoleExpr* expr ) { return retObject ( expr, DataPropertyPointer ); } jobject DataType ( TDataExpr* expr ) { return retObject ( expr, DataTypePointer ); } jobject DataTypeExpression ( TDataExpr* expr ) { return retObject ( expr, DataTypeExpressionPointer ); } jobject DataValue ( TDataValueExpr* expr ) { return retObject ( expr, DataValuePointer ); } jobject Facet ( TFacetExpr* expr ) { return retObject ( expr, DataTypeFacet ); } jobject Node ( TCGNode* node ) { return retObject ( node, NodePointer ); } jobject Axiom ( TDLAxiom* axiom ) { return retObject ( axiom, AxiomPointer ); } /// create vector of Java objects defined by ID from given VEC template jobjectArray buildArray ( const std::vector& vec, const TClassFieldMethodIDs& ID ) { jobjectArray ret = env->NewObjectArray ( vec.size(), ID.ClassID, NULL ); for ( unsigned int i = 0; i < vec.size(); ++i ) env->SetObjectArrayElement ( ret, i, retObject ( vec[i], ID ) ); return ret; } // get expressions for the names in the unified way /// get expression for the class name TConceptExpr* getCName ( const std::string& name ) { return EM->Concept(name); } /// get expression for the individual name TIndividualExpr* getIName ( const std::string& name ) { return EM->Individual(name); } /// get expression for the object property name TORoleExpr* getOName ( const std::string& name ) { return EM->ObjectRole(name); } /// get expression for the data property name TDRoleExpr* getDName ( const std::string& name ) { return EM->DataRole(name); } }; // TJNICache /// get JNI cache by the env and obj inline TJNICache* getJ ( JNIEnv* env, jobject obj ) { TJNICache* J = getK(env,obj)->getJNICache(); if ( unlikely(J->env != env) ) J->reset(env); return J; } #endif FaCTpp-src-v1.6.2~dfsg/src/FaCT++.JNI/KnowledgeExploration.cpp0000644000000000000000000001402612112642405022331 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2006-2013 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ // this file contains implementation of knowledge exploration methods of FaCT++ JNI interface #include "uk_ac_manchester_cs_factplusplus_FaCTPlusPlus.h" #include "Kernel.h" #include "tJNICache.h" #ifdef __cplusplus extern "C" { #endif /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: buildCompletionTree * Signature: (Luk/ac/manchester/cs/factplusplus/ClassPointer;)Luk/ac/manchester/cs/factplusplus/NodePointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_buildCompletionTree (JNIEnv * env, jobject obj, jobject arg) { TRACE_JNI("buildCompletionTree"); TRACE_ARG(env,obj,arg); TJNICache* J = getJ(env,obj); return J->Node(J->K->buildCompletionTree(getROConceptExpr(env,arg))); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getObjectNeighbours * Signature: (Luk/ac/manchester/cs/factplusplus/NodePointer;Z)[Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer; */ JNIEXPORT jobjectArray JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getObjectNeighbours__Luk_ac_manchester_cs_factplusplus_NodePointer_2Z (JNIEnv * env, jobject obj, jobject arg, jboolean flag) { TRACE_JNI("getObjectNeighbours"); TRACE_ARG(env,obj,arg); TJNICache* J = getJ(env,obj); ReasoningKernel::TCGRoleSet Set; J->K->getObjectRoles ( getRONode(env,arg), Set, /*onlyDet=*/flag, /*needIncoming=*/false ); std::vector ret; for ( ReasoningKernel::TCGRoleSet::const_iterator p = Set.begin(), p_end = Set.end(); p != p_end; ++p ) ret.push_back(dynamic_cast(*p)); return J->buildArray ( ret, J->ObjectPropertyPointer ); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getDataNeighbours * Signature: (Luk/ac/manchester/cs/factplusplus/NodePointer;Z)[Luk/ac/manchester/cs/factplusplus/DataPropertyPointer; */ JNIEXPORT jobjectArray JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getDataNeighbours__Luk_ac_manchester_cs_factplusplus_NodePointer_2Z (JNIEnv * env, jobject obj, jobject arg, jboolean flag) { TRACE_JNI("getDataNeighbours"); TRACE_ARG(env,obj,arg); TJNICache* J = getJ(env,obj); ReasoningKernel::TCGRoleSet Set; J->K->getDataRoles ( getRONode(env,arg), Set, /*onlyDet=*/flag ); std::vector ret; for ( ReasoningKernel::TCGRoleSet::const_iterator p = Set.begin(), p_end = Set.end(); p != p_end; ++p ) ret.push_back(dynamic_cast(*p)); return J->buildArray ( ret, J->DataPropertyPointer ); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getObjectNeighbours * Signature: (Luk/ac/manchester/cs/factplusplus/NodePointer;Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;)[Luk/ac/manchester/cs/factplusplus/NodePointer; */ JNIEXPORT jobjectArray JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getObjectNeighbours__Luk_ac_manchester_cs_factplusplus_NodePointer_2Luk_ac_manchester_cs_factplusplus_ObjectPropertyPointer_2 (JNIEnv * env, jobject obj, jobject arg1, jobject arg2 ) { TRACE_JNI("getObjectNeighbours"); TRACE_ARG(env,obj,arg1); TRACE_ARG(env,obj,arg2); TJNICache* J = getJ(env,obj); ReasoningKernel::TCGNodeVec Vec; J->K->getNeighbours ( getRONode(env,arg1), getROORoleExpr(env,arg2), Vec ); return J->buildArray ( Vec, J->NodePointer ); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getDataNeighbours * Signature: (Luk/ac/manchester/cs/factplusplus/NodePointer;Luk/ac/manchester/cs/factplusplus/DataPropertyPointer;)[Luk/ac/manchester/cs/factplusplus/NodePointer; */ JNIEXPORT jobjectArray JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getDataNeighbours__Luk_ac_manchester_cs_factplusplus_NodePointer_2Luk_ac_manchester_cs_factplusplus_DataPropertyPointer_2 (JNIEnv * env, jobject obj, jobject arg1, jobject arg2 ) { TRACE_JNI("getDataNeighbours"); TRACE_ARG(env,obj,arg1); TRACE_ARG(env,obj,arg2); TJNICache* J = getJ(env,obj); ReasoningKernel::TCGNodeVec Vec; J->K->getNeighbours ( getRONode(env,arg1), getRODRoleExpr(env,arg2), Vec ); return J->buildArray ( Vec, J->NodePointer ); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getObjectLabel * Signature: (Luk/ac/manchester/cs/factplusplus/NodePointer;Z)[Luk/ac/manchester/cs/factplusplus/ClassPointer; */ JNIEXPORT jobjectArray JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getObjectLabel (JNIEnv * env, jobject obj, jobject arg, jboolean flag) { TRACE_JNI("getObjectLabel"); TRACE_ARG(env,obj,arg); TJNICache* J = getJ(env,obj); ReasoningKernel::TCGItemVec Vec; J->K->getLabel ( getRONode(env,arg), Vec, /*onlyDet=*/flag ); return J->buildArray ( Vec, J->ClassPointer ); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getDataLabel * Signature: (Luk/ac/manchester/cs/factplusplus/NodePointer;Z)[Luk/ac/manchester/cs/factplusplus/DataTypePointer; */ JNIEXPORT jobjectArray JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getDataLabel (JNIEnv * env, jobject obj, jobject arg, jboolean flag) { TRACE_JNI("getDataLabel"); TRACE_ARG(env,obj,arg); TJNICache* J = getJ(env,obj); ReasoningKernel::TCGItemVec Vec; J->K->getLabel ( getRONode(env,arg), Vec, /*onlyDet=*/flag ); return J->buildArray ( Vec, J->DataTypeExpressionPointer ); } #ifdef __cplusplus } #endif FaCTpp-src-v1.6.2~dfsg/src/FaCT++.JNI/Expressions.cpp0000644000000000000000000007144712112642405020521 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2006-2013 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ // this file contains implementation of DL expression-related methods of FaCT++ JNI interface #include #include "uk_ac_manchester_cs_factplusplus_FaCTPlusPlus.h" #include "Kernel.h" #include "tJNICache.h" #ifdef __cplusplus extern "C" { #endif //------------------------------------------------------------- // Concept/role/datatype language //------------------------------------------------------------- /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getThing * Signature: ()Luk/ac/manchester/cs/factplusplus/ClassPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getThing (JNIEnv * env, jobject obj) { TRACE_JNI("getThing"); TJNICache* J = getJ(env,obj); return J->Class(J->EM->Top()); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getNothing * Signature: ()Luk/ac/manchester/cs/factplusplus/ClassPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getNothing (JNIEnv * env, jobject obj) { TRACE_JNI("getNothing"); TJNICache* J = getJ(env,obj); return J->Class(J->EM->Bottom()); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getNamedClass * Signature: (Ljava/lang/String;)Luk/ac/manchester/cs/factplusplus/ClassPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getNamedClass (JNIEnv * env, jobject obj, jstring str) { TRACE_JNI("getNamedClass"); TJNICache* J = getJ(env,obj); JString name(env,str); jobject ret = (jobject)0; try { ret = J->Class(J->getCName(name())); } catch (const EFPPCantRegName&) { Throw ( env, "FaCT++ Kernel: Can not register new class name" ); } return ret; } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getTopObjectProperty * Signature: ()Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getTopObjectProperty (JNIEnv * env, jobject obj) { TRACE_JNI("getTopObjectProperty"); TJNICache* J = getJ(env,obj); return J->ObjectProperty(J->getOName("http://www.w3.org/2002/07/owl#topObjectProperty")); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getBottomObjectProperty * Signature: ()Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getBottomObjectProperty (JNIEnv * env, jobject obj) { TRACE_JNI("getBottomObjectProperty"); TJNICache* J = getJ(env,obj); return J->ObjectProperty(J->getOName("http://www.w3.org/2002/07/owl#bottomObjectProperty")); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getObjectProperty * Signature: (Ljava/lang/String;)Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getObjectProperty (JNIEnv * env, jobject obj, jstring str) { TRACE_JNI("getObjectProperty"); TJNICache* J = getJ(env,obj); JString name(env,str); jobject ret = (jobject)0; try { ret = J->ObjectProperty(J->getOName(name())); } catch (const EFPPCantRegName&) { Throw ( env, "FaCT++ Kernel: Can not register new object property name" ); } return ret; } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getTopDataProperty * Signature: ()Luk/ac/manchester/cs/factplusplus/DataPropertyPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getTopDataProperty (JNIEnv * env, jobject obj) { TRACE_JNI("getTopDataProperty"); TJNICache* J = getJ(env,obj); return J->DataProperty(J->getDName("http://www.w3.org/2002/07/owl#topDataProperty")); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getBottomDataProperty * Signature: ()Luk/ac/manchester/cs/factplusplus/DataPropertyPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getBottomDataProperty (JNIEnv * env, jobject obj) { TRACE_JNI("getBottomDataProperty"); TJNICache* J = getJ(env,obj); return J->DataProperty(J->getDName("http://www.w3.org/2002/07/owl#bottomDataProperty")); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getDataProperty * Signature: (Ljava/lang/String;)Luk/ac/manchester/cs/factplusplus/DataPropertyPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getDataProperty (JNIEnv * env, jobject obj, jstring str) { TRACE_JNI("getDataProperty"); TJNICache* J = getJ(env,obj); JString name(env,str); jobject ret = (jobject)0; try { ret = J->DataProperty(J->getDName(name())); } catch (const EFPPCantRegName&) { Throw ( env, "FaCT++ Kernel: Can not register new data property name" ); } return ret; } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getIndividual * Signature: (Ljava/lang/String;)Luk/ac/manchester/cs/factplusplus/IndividualPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getIndividual (JNIEnv * env, jobject obj, jstring str) { TRACE_JNI("getIndividual"); TJNICache* J = getJ(env,obj); JString name(env,str); jobject ret = (jobject)0; try { ret = J->Individual(J->getIName(name())); } catch (const EFPPCantRegName&) { Throw ( env, "FaCT++ Kernel: Can not register new individual name" ); } return ret; } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getBuiltInDataType * Signature: (Ljava/lang/String;)Luk/ac/manchester/cs/factplusplus/DataTypePointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getBuiltInDataType (JNIEnv * env, jobject obj, jstring str) { TRACE_JNI("getBuiltInDataType"); TJNICache* J = getJ(env,obj); JString name(env,str); std::string DTName(name()); if ( DTName == "http://www.w3.org/2000/01/rdf-schema#Literal" || DTName == "http://www.w3.org/2000/01/rdf-schema#anySimpleType" || DTName == "http://www.w3.org/2001/XMLSchema#anyType" || DTName == "http://www.w3.org/2001/XMLSchema#anySimpleType" ) return J->DataType(J->EM->DataTop()); if ( DTName == "http://www.w3.org/1999/02/22-rdf-syntax-ns#PlainLiteral" || DTName == "http://www.w3.org/1999/02/22-rdf-syntax-ns#XMLLiteral" || DTName == "http://www.w3.org/2001/XMLSchema#string" || DTName == "http://www.w3.org/2001/XMLSchema#anyURI" || DTName == "http://www.w3.org/2001/XMLSchema#ID" ) return J->DataType(J->EM->getStrDataType()); if ( DTName == "http://www.w3.org/2001/XMLSchema#integer" || DTName == "http://www.w3.org/2001/XMLSchema#int" || DTName == "http://www.w3.org/2001/XMLSchema#long" || DTName == "http://www.w3.org/2001/XMLSchema#nonNegativeInteger" || DTName == "http://www.w3.org/2001/XMLSchema#positiveInteger" || DTName == "http://www.w3.org/2001/XMLSchema#negativeInteger" || DTName == "http://www.w3.org/2001/XMLSchema#short" || DTName == "http://www.w3.org/2001/XMLSchema#byte" ) return J->DataType(J->EM->getIntDataType()); if ( DTName == "http://www.w3.org/2001/XMLSchema#float" || DTName == "http://www.w3.org/2001/XMLSchema#double" || DTName == "http://www.w3.org/2001/XMLSchema#real" || DTName == "http://www.w3.org/2001/XMLSchema#decimal" ) return J->DataType(J->EM->getRealDataType()); if ( DTName == "http://www.w3.org/2001/XMLSchema#boolean" ) return J->DataType(J->EM->getBoolDataType()); if ( DTName == "http://www.w3.org/2001/XMLSchema#dateTimeAsLong" ) return J->DataType(J->EM->getTimeDataType()); std::stringstream err; err << "Unsupported datatype '" << DTName.c_str() << "'"; Throw ( env, err.str().c_str() ); return (jobject)0; } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getDataSubType * Signature: (Ljava/lang/String;Luk/ac/manchester/cs/factplusplus/DataTypeExpressionPointer;)Luk/ac/manchester/cs/factplusplus/DataTypeExpressionPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getDataSubType (JNIEnv * env, jobject obj ATTR_UNUSED, jstring str ATTR_UNUSED, jobject type ATTR_UNUSED) { TRACE_JNI("getDataSubType"); // TJNICache* J = getJ(env,obj); JString name(env,str); Throw ( env, "FaCT++ Kernel: unsupported operation 'getDataSubType'" ); jobject ret = (jobject)0; #if 0 try { ret = DataTypeExpression ( env, getK(env,obj)->getDataTypeCenter(). getDataType ( name(), getDataExpr(env,type) ) ); } catch (const EFPPCantRegName&) { Throw ( env, "FaCT++ Kernel: Can not register new data type" ); } #endif return ret; } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getDataTop * Signature: ()Luk/ac/manchester/cs/factplusplus/DataTypePointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getDataTop (JNIEnv * env, jobject obj) { TRACE_JNI("getDataTop"); TJNICache* J = getJ(env,obj); return J->DataType(J->EM->DataTop()); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getDataEnumeration * Signature: ()Luk/ac/manchester/cs/factplusplus/DataTypeExpressionPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getDataEnumeration (JNIEnv * env, jobject obj) { TRACE_JNI("getDataEnumeration"); TJNICache* J = getJ(env,obj); return J->DataTypeExpression(J->EM->DataOneOf()); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getRestrictedDataType * Signature: (Luk/ac/manchester/cs/factplusplus/DataTypeExpressionPointer;Luk/ac/manchester/cs/factplusplus/DataTypeFacet;)Luk/ac/manchester/cs/factplusplus/DataTypeExpressionPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getRestrictedDataType (JNIEnv * env, jobject obj, jobject arg1, jobject arg2) { TRACE_JNI("getRestrictedDataType"); TJNICache* J = getJ(env,obj); return J->DataTypeExpression ( J->EM->RestrictedType ( getDataTypeExpr(env,arg1), getFacetExpr(env,arg2) ) ); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getLength * Signature: (Luk/ac/manchester/cs/factplusplus/DataValuePointer;)Luk/ac/manchester/cs/factplusplus/DataTypeFacet; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getLength (JNIEnv * env, jobject, jobject) { Throw ( env, "FaCT++ Kernel: unsupported facet 'getLength'" ); return NULL; } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getMinLength * Signature: (Luk/ac/manchester/cs/factplusplus/DataValuePointer;)Luk/ac/manchester/cs/factplusplus/DataTypeFacet; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getMinLength (JNIEnv * env, jobject, jobject) { Throw ( env, "FaCT++ Kernel: unsupported facet 'getMinLength'" ); return NULL; } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getMaxLength * Signature: (Luk/ac/manchester/cs/factplusplus/DataValuePointer;)Luk/ac/manchester/cs/factplusplus/DataTypeFacet; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getMaxLength (JNIEnv * env, jobject, jobject) { Throw ( env, "FaCT++ Kernel: unsupported facet 'getMaxLength'" ); return NULL; } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getPattern * Signature: (Luk/ac/manchester/cs/factplusplus/DataValuePointer;)Luk/ac/manchester/cs/factplusplus/DataTypeFacet; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getPattern (JNIEnv * env, jobject, jobject) { Throw ( env, "FaCT++ Kernel: unsupported facet 'getPattern'" ); return NULL; } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getMinExclusiveFacet * Signature: (Luk/ac/manchester/cs/factplusplus/DataValuePointer;)Luk/ac/manchester/cs/factplusplus/DataTypeFacet; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getMinExclusiveFacet (JNIEnv * env, jobject obj, jobject arg) { TRACE_JNI("getMinExclusiveFacet"); TJNICache* J = getJ(env,obj); return J->Facet(J->EM->FacetMinExclusive(getDataValueExpr(env,arg))); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getMaxExclusiveFacet * Signature: (Luk/ac/manchester/cs/factplusplus/DataValuePointer;)Luk/ac/manchester/cs/factplusplus/DataTypeFacet; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getMaxExclusiveFacet (JNIEnv * env, jobject obj, jobject arg) { TRACE_JNI("getMaxExclusiveFacet"); TJNICache* J = getJ(env,obj); return J->Facet(J->EM->FacetMaxExclusive(getDataValueExpr(env,arg))); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getMinInclusiveFacet * Signature: (Luk/ac/manchester/cs/factplusplus/DataValuePointer;)Luk/ac/manchester/cs/factplusplus/DataTypeFacet; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getMinInclusiveFacet (JNIEnv * env, jobject obj, jobject arg) { TRACE_JNI("getMinInclusiveFacet"); TJNICache* J = getJ(env,obj); return J->Facet(J->EM->FacetMinInclusive(getDataValueExpr(env,arg))); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getMaxInclusiveFacet * Signature: (Luk/ac/manchester/cs/factplusplus/DataValuePointer;)Luk/ac/manchester/cs/factplusplus/DataTypeFacet; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getMaxInclusiveFacet (JNIEnv * env, jobject obj, jobject arg) { TRACE_JNI("getMaxInclusiveFacet"); TJNICache* J = getJ(env,obj); return J->Facet(J->EM->FacetMaxInclusive(getDataValueExpr(env,arg))); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getTotalDigitsFacet * Signature: (Luk/ac/manchester/cs/factplusplus/DataValuePointer;)Luk/ac/manchester/cs/factplusplus/DataTypeFacet; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getTotalDigitsFacet (JNIEnv * env, jobject, jobject) { Throw ( env, "FaCT++ Kernel: unsupported facet 'getTotalDigitsFacet'" ); return NULL; } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getFractionDigitsFacet * Signature: (Luk/ac/manchester/cs/factplusplus/DataValuePointer;)Luk/ac/manchester/cs/factplusplus/DataTypeFacet; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getFractionDigitsFacet (JNIEnv * env, jobject obj ATTR_UNUSED, jobject arg ATTR_UNUSED) { TRACE_JNI("getFractionDigitsFacet"); Throw ( env, "FaCT++ Kernel: unsupported facet 'getFractionDigitsFacet'" ); return NULL; } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getDataNot * Signature: (Luk/ac/manchester/cs/factplusplus/DataTypeExpressionPointer;)Luk/ac/manchester/cs/factplusplus/DataTypeExpressionPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getDataNot (JNIEnv * env, jobject obj, jobject arg) { TRACE_JNI("getDataNot"); TJNICache* J = getJ(env,obj); return J->DataTypeExpression(J->EM->DataNot(getDataExpr(env,arg))); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getDataIntersectionOf * Signature: ()Luk/ac/manchester/cs/factplusplus/DataTypeExpressionPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getDataIntersectionOf (JNIEnv * env, jobject obj) { TRACE_JNI("getDataIntersectionOf"); TJNICache* J = getJ(env,obj); return J->DataTypeExpression(J->EM->DataAnd()); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getDataUnionOf * Signature: ()Luk/ac/manchester/cs/factplusplus/DataTypeExpressionPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getDataUnionOf (JNIEnv * env, jobject obj) { TRACE_JNI("getDataUnionOf"); TJNICache* J = getJ(env,obj); return J->DataTypeExpression(J->EM->DataOr()); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getDataValue * Signature: (Ljava/lang/String;Luk/ac/manchester/cs/factplusplus/DataTypePointer;)Luk/ac/manchester/cs/factplusplus/DataValuePointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getDataValue__Ljava_lang_String_2Luk_ac_manchester_cs_factplusplus_DataTypePointer_2 (JNIEnv * env, jobject obj, jstring str, jobject type) { TRACE_JNI("getDataValue"); TJNICache* J = getJ(env,obj); JString name(env,str); jobject ret = (jobject)0; try { ret = J->DataValue ( J->EM->DataValue ( name(), getDataTypeExpr(env,type) ) ); } catch (const EFPPCantRegName&) { Throw ( env, "FaCT++ Kernel: Can not register new data value" ); } return ret; } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getConceptAnd * Signature: ()Luk/ac/manchester/cs/factplusplus/ClassPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getConceptAnd (JNIEnv * env, jobject obj) { TRACE_JNI("getConceptAnd"); TJNICache* J = getJ(env,obj); return J->Class(J->EM->And()); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getConceptOr * Signature: ()Luk/ac/manchester/cs/factplusplus/ClassPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getConceptOr (JNIEnv * env, jobject obj) { TRACE_JNI("getConceptOr"); TJNICache* J = getJ(env,obj); return J->Class(J->EM->Or()); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getConceptNot * Signature: (Luk/ac/manchester/cs/factplusplus/ClassPointer;)Luk/ac/manchester/cs/factplusplus/ClassPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getConceptNot (JNIEnv * env, jobject obj, jobject arg) { TRACE_JNI("getConceptNot"); TJNICache* J = getJ(env,obj); return J->Class(J->EM->Not(getConceptExpr(env,arg))); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getObjectSome * Signature: (Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;Luk/ac/manchester/cs/factplusplus/ClassPointer;)Luk/ac/manchester/cs/factplusplus/ClassPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getObjectSome (JNIEnv * env, jobject obj, jobject arg1, jobject arg2) { TRACE_JNI("getObjectSome"); TJNICache* J = getJ(env,obj); return J->Class ( J->EM->Exists ( getORoleExpr(env,arg1), getConceptExpr(env,arg2) ) ); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getObjectAll * Signature: (Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;Luk/ac/manchester/cs/factplusplus/ClassPointer;)Luk/ac/manchester/cs/factplusplus/ClassPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getObjectAll (JNIEnv * env, jobject obj, jobject arg1, jobject arg2) { TRACE_JNI("getObjectAll"); TJNICache* J = getJ(env,obj); return J->Class ( J->EM->Forall ( getORoleExpr(env,arg1), getConceptExpr(env,arg2) ) ); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getObjectValue * Signature: (Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;Luk/ac/manchester/cs/factplusplus/IndividualPointer;)Luk/ac/manchester/cs/factplusplus/ClassPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getObjectValue (JNIEnv * env, jobject obj, jobject arg1, jobject arg2) { TRACE_JNI("getObjectValue"); TJNICache* J = getJ(env,obj); return J->Class ( J->EM->Value ( getORoleExpr(env,arg1), getIndividualExpr(env,arg2) ) ); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getDataSome * Signature: (Luk/ac/manchester/cs/factplusplus/DataPropertyPointer;Luk/ac/manchester/cs/factplusplus/DataTypeExpressionPointer;)Luk/ac/manchester/cs/factplusplus/ClassPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getDataSome (JNIEnv * env, jobject obj, jobject arg1, jobject arg2) { TRACE_JNI("getDataSome"); TJNICache* J = getJ(env,obj); return J->Class ( J->EM->Exists ( getDRoleExpr(env,arg1), getDataExpr(env,arg2) ) ); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getDataAll * Signature: (Luk/ac/manchester/cs/factplusplus/DataPropertyPointer;Luk/ac/manchester/cs/factplusplus/DataTypeExpressionPointer;)Luk/ac/manchester/cs/factplusplus/ClassPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getDataAll (JNIEnv * env, jobject obj, jobject arg1, jobject arg2) { TRACE_JNI("getDataAll"); TJNICache* J = getJ(env,obj); return J->Class ( J->EM->Forall ( getDRoleExpr(env,arg1), getDataExpr(env,arg2) ) ); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getDataValue * Signature: (Luk/ac/manchester/cs/factplusplus/DataPropertyPointer;Luk/ac/manchester/cs/factplusplus/DataValuePointer;)Luk/ac/manchester/cs/factplusplus/ClassPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getDataValue__Luk_ac_manchester_cs_factplusplus_DataPropertyPointer_2Luk_ac_manchester_cs_factplusplus_DataValuePointer_2 (JNIEnv * env, jobject obj, jobject arg1, jobject arg2) { TRACE_JNI("getDataValue"); TJNICache* J = getJ(env,obj); return J->Class ( J->EM->Value ( getDRoleExpr(env,arg1), getDataValueExpr(env,arg2) ) ); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getObjectAtLeast * Signature: (ILuk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;Luk/ac/manchester/cs/factplusplus/ClassPointer;)Luk/ac/manchester/cs/factplusplus/ClassPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getObjectAtLeast (JNIEnv * env, jobject obj, jint n, jobject arg1, jobject arg2) { TRACE_JNI("getObjectAtLeast"); TJNICache* J = getJ(env,obj); return J->Class ( J->EM->MinCardinality ( n, getORoleExpr(env,arg1), getConceptExpr(env,arg2) ) ); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getObjectExact * Signature: (ILuk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;Luk/ac/manchester/cs/factplusplus/ClassPointer;)Luk/ac/manchester/cs/factplusplus/ClassPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getObjectExact (JNIEnv * env, jobject obj, jint n, jobject arg1, jobject arg2) { TRACE_JNI("getObjectExact"); TJNICache* J = getJ(env,obj); return J->Class ( J->EM->Cardinality ( n, getORoleExpr(env,arg1), getConceptExpr(env,arg2) ) ); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getObjectAtMost * Signature: (ILuk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;Luk/ac/manchester/cs/factplusplus/ClassPointer;)Luk/ac/manchester/cs/factplusplus/ClassPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getObjectAtMost (JNIEnv * env, jobject obj, jint n, jobject arg1, jobject arg2) { TRACE_JNI("getObjectAtMost"); TJNICache* J = getJ(env,obj); return J->Class ( J->EM->MaxCardinality ( n, getORoleExpr(env,arg1), getConceptExpr(env,arg2) ) ); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getDataAtLeast * Signature: (ILuk/ac/manchester/cs/factplusplus/DataPropertyPointer;Luk/ac/manchester/cs/factplusplus/DataTypePointer;)Luk/ac/manchester/cs/factplusplus/ClassPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getDataAtLeast (JNIEnv * env, jobject obj, jint n, jobject arg1, jobject arg2) { TRACE_JNI("getDataAtLeast"); TJNICache* J = getJ(env,obj); return J->Class ( J->EM->MinCardinality ( n, getDRoleExpr(env,arg1), getDataExpr(env,arg2) ) ); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getDataExact * Signature: (ILuk/ac/manchester/cs/factplusplus/DataPropertyPointer;Luk/ac/manchester/cs/factplusplus/DataTypePointer;)Luk/ac/manchester/cs/factplusplus/ClassPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getDataExact (JNIEnv * env, jobject obj, jint n, jobject arg1, jobject arg2) { TRACE_JNI("getDataExact"); TJNICache* J = getJ(env,obj); return J->Class ( J->EM->Cardinality ( n, getDRoleExpr(env,arg1), getDataExpr(env,arg2) ) ); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getDataAtMost * Signature: (ILuk/ac/manchester/cs/factplusplus/DataPropertyPointer;Luk/ac/manchester/cs/factplusplus/DataTypePointer;)Luk/ac/manchester/cs/factplusplus/ClassPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getDataAtMost (JNIEnv * env, jobject obj, jint n, jobject arg1, jobject arg2) { TRACE_JNI("getDataAtMost"); TJNICache* J = getJ(env,obj); return J->Class ( J->EM->MaxCardinality ( n, getDRoleExpr(env,arg1), getDataExpr(env,arg2) ) ); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getInverseProperty * Signature: (Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;)Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getInverseProperty (JNIEnv * env, jobject obj, jobject arg) { TRACE_JNI("getInverseProperty"); TJNICache* J = getJ(env,obj); return J->ObjectProperty(J->EM->Inverse(getORoleExpr(env,arg))); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getPropertyComposition * Signature: ()Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getPropertyComposition (JNIEnv * env, jobject obj) { TRACE_JNI("getPropertyComposition"); TJNICache* J = getJ(env,obj); return J->ObjectComplex(J->EM->Compose()); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getDataPropertyKey * Signature: ()Luk/ac/manchester/cs/factplusplus/DataPropertyPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getDataPropertyKey (JNIEnv * env, jobject obj ATTR_UNUSED) { TRACE_JNI("getDataPropertyKey"); Throw ( env, "FaCT++ Kernel: unsupported operation 'getDataPropertyKey'" ); return NULL; } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getObjectPropertyKey * Signature: ()Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getObjectPropertyKey (JNIEnv * env, jobject obj ATTR_UNUSED) { TRACE_JNI("getObjectPropertyKey"); Throw ( env, "FaCT++ Kernel: unsupported operation 'getObjectPropertyKey'" ); return NULL; } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getOneOf * Signature: ()Luk/ac/manchester/cs/factplusplus/ClassPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getOneOf (JNIEnv * env, jobject obj) { TRACE_JNI("getOneOf"); TJNICache* J = getJ(env,obj); return J->Class(J->EM->OneOf()); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getSelf * Signature: (Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;)Luk/ac/manchester/cs/factplusplus/ClassPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getSelf (JNIEnv * env, jobject obj, jobject arg) { TRACE_JNI("getSelf"); TJNICache* J = getJ(env,obj); return J->Class(J->EM->SelfReference(getORoleExpr(env,arg))); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: initArgList * Signature: ()V */ JNIEXPORT void JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_initArgList (JNIEnv * env, jobject obj) { TRACE_JNI("initArgList"); TJNICache* J = getJ(env,obj); J->EM->newArgList(); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: addArg * Signature: (Luk/ac/manchester/cs/factplusplus/Pointer;)V */ JNIEXPORT void JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_addArg (JNIEnv * env, jobject obj, jobject arg) { TRACE_JNI("addArg"); TRACE_ARG(env,obj,arg); TJNICache* J = getJ(env,obj); J->EM->addArg(getExpr(env,arg)); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: closeArgList * Signature: ()V */ JNIEXPORT void JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_closeArgList (JNIEnv *, jobject) { } #ifdef __cplusplus } #endif FaCTpp-src-v1.6.2~dfsg/src/FaCT++.JNI/Modularity.cpp0000644000000000000000000000726712112642405020327 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2006-2013 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ // this file contains implementation of modularity-related methods of FaCT++ JNI interface #include "uk_ac_manchester_cs_factplusplus_FaCTPlusPlus.h" #include "Kernel.h" #include "tJNICache.h" /// translate int values of Java interface into ModuleType enum inline enum ModuleType moduleTypeByInt ( jint moduleType ) { return moduleType == 0 ? M_BOT : moduleType == 1 ? M_TOP : M_STAR; } #ifdef __cplusplus extern "C" { #endif /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getAtomicDecompositionSize * Signature: (ZI)I */ JNIEXPORT jint JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getAtomicDecompositionSize (JNIEnv * env, jobject obj, jboolean useSemantic, jint moduleType) { TRACE_JNI("getAtomicDecompositionSize"); return getK(env,obj)->getAtomicDecompositionSize ( useSemantic, moduleTypeByInt(moduleType) ); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getAtomAxioms * Signature: (I)[Luk/ac/manchester/cs/factplusplus/AxiomPointer; */ JNIEXPORT jobjectArray JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getAtomAxioms (JNIEnv * env, jobject obj, jint index) { TRACE_JNI("getAtomAxioms"); TJNICache* J = getJ(env,obj); return J->buildArray ( J->K->getAtomAxioms(index), J->AxiomPointer ); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getAtomDependents * Signature: (I)[I */ JNIEXPORT jintArray JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getAtomDependents (JNIEnv * env, jobject obj, jint index) { TRACE_JNI("getAtomDependents"); const TOntologyAtom::AtomSet aSet = getK(env,obj)->getAtomDependents(index); size_t sz = aSet.size(); jint* buf = new jint[sz]; TOntologyAtom::AtomSet::const_iterator p = aSet.begin(); for ( size_t i = 0; i < sz; ++i, ++p ) buf[i] = (*p)->getId(); jintArray ret = env->NewIntArray(sz); env->SetIntArrayRegion ( ret, 0, sz, buf ); delete [] buf; return ret; } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getModule * Signature: (ZI)[Luk/ac/manchester/cs/factplusplus/AxiomPointer; */ JNIEXPORT jobjectArray JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getModule (JNIEnv * env, jobject obj, jboolean useSemantic, jint moduleType) { TRACE_JNI("getModule"); TJNICache* J = getJ(env,obj); return J->buildArray ( J->K->getModule(useSemantic,moduleTypeByInt(moduleType)), J->AxiomPointer ); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getNonLocal * Signature: (ZI)[Luk/ac/manchester/cs/factplusplus/AxiomPointer; */ JNIEXPORT jobjectArray JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getNonLocal (JNIEnv * env, jobject obj, jboolean useSemantic, jint moduleType) { TRACE_JNI("getNonLocal"); TJNICache* J = getJ(env,obj); return J->buildArray ( J->K->getNonLocal(useSemantic,moduleTypeByInt(moduleType)), J->AxiomPointer ); } #ifdef __cplusplus } #endif FaCTpp-src-v1.6.2~dfsg/src/FaCT++.JNI/Makefile0000644000000000000000000000067712112642405017130 0ustar rootroot# # Makefile for FaCT++ JNI interface library # # -- DO NOT CHANGE THE REST OF FILE -- LIBRARY = FaCTPlusPlusJNI LTYPE = shared INCLUDES = -I/Developer/SDKs/MacOSX10.6.sdk/System/Library/Frameworks/JavaVM.framework/Headers -I/System/Library/Frameworks/JavaVM.framework/Headers USE_IL = ../Kernel SOURCES = \ Axioms.cpp\ Expressions.cpp\ KnowledgeExploration.cpp\ Modularity.cpp\ Queries.cpp\ FaCTPlusPlus.cpp include ../Makefile.include FaCTpp-src-v1.6.2~dfsg/src/FaCT++.JNI/FaCTPlusPlus.cpp0000644000000000000000000001404712112642405020455 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2006-2013 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "uk_ac_manchester_cs_factplusplus_FaCTPlusPlus.h" #include "Kernel.h" #include "tJNICache.h" #include "JNIMonitor.h" #ifdef __cplusplus extern "C" { #endif //------------------------------------------------------------- // Different fields/method IDs and their setup //------------------------------------------------------------- /// field for Kernel's ID jfieldID KernelFID; /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: initMethodsFieldsIDs * Signature: ()V */ JNIEXPORT void JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_initMethodsFieldsIDs (JNIEnv * env, jclass cls) { KernelFID = env->GetFieldID ( cls, "KernelId", "J" ); if ( KernelFID == 0 ) { Throw ( env, "Can't get 'KernelId' field" ); return; } } //------------------------------------------------------------- // Kernel management (like newKB/curKB/releaseKB) //------------------------------------------------------------- /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: initKernel * Signature: ()V */ JNIEXPORT void JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_initKernel (JNIEnv * env, jobject obj) { // create new kernel and save it in an FaCTPlusPlus object ReasoningKernel* Kernel = new ReasoningKernel(); env->SetLongField ( obj, KernelFID, (jlong)Kernel ); // setup JNI cache TJNICache* J = new TJNICache(env); Kernel->setJNICache(J); J->K = Kernel; J->EM = Kernel->getExpressionManager(); TRACE_JNI("initKernel"); #ifdef _USE_LOGGING // initialize LeveLogger //LLM.initLogger ( 20, "reasoning.log" ); #endif } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: deleteKernel * Signature: ()V */ JNIEXPORT void JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_deleteKernel (JNIEnv * env, jobject obj) { TRACE_JNI("deleteKernel"); ReasoningKernel* Kernel = getK(env,obj); delete Kernel->getJNICache(); delete Kernel; // set to NULL env->SetLongField ( obj, KernelFID, 0 ); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: clearKernel * Signature: ()V */ JNIEXPORT void JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_clearKernel (JNIEnv * env, jobject obj) { TRACE_JNI("clearKernel"); getK(env,obj)->clearKB(); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: setTopBottomPropertyNames * Signature: (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V */ JNIEXPORT void JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_setTopBottomPropertyNames (JNIEnv * env, jobject obj, jstring ton, jstring bon, jstring tdn, jstring bdn) { TRACE_JNI("setTopBottomPropertyNames"); JString topObjectName(env,ton); JString botObjectName(env,bon); JString topDataName(env,tdn); JString botDataName(env,bdn); getK(env,obj)->setTopBottomRoleNames ( topObjectName(), botObjectName(), topDataName(), botDataName() ); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: setOperationTimeout * Signature: (J)V */ JNIEXPORT void JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_setOperationTimeout (JNIEnv * env, jobject obj, jlong delay) { TRACE_JNI("setOperationTimeout"); getK(env,obj)->setOperationTimeout(delay > 0 ? static_cast(delay) : 0); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: setFreshEntityPolicy * Signature: (Z)V */ JNIEXPORT void JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_setFreshEntityPolicy (JNIEnv * env, jobject obj, jboolean value) { TRACE_JNI("setFreshEntityPolicy"); getK(env,obj)->setUseUndefinedNames(value); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: setProgressMonitor * Signature: (Luk/ac/manchester/cs/factplusplus/FaCTPlusPlusProgressMonitor;)V */ JNIEXPORT void JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_setProgressMonitor (JNIEnv * env, jobject obj, jobject monitor) { TRACE_JNI("setProgressMonitor"); getK(env,obj)->setProgressMonitor ( new JNIProgressMonitor ( env, monitor ) ); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: startChanges * Signature: ()V */ JNIEXPORT void JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_startChanges (JNIEnv *, jobject) { } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: endChanges * Signature: ()V */ JNIEXPORT void JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_endChanges (JNIEnv * env ATTR_UNUSED, jobject obj ATTR_UNUSED) { TRACE_JNI("endChanges"); // do nothing for now } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: needTracing * Signature: ()V */ JNIEXPORT void JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_needTracing (JNIEnv * env, jobject obj) { TRACE_JNI("needTracing"); getK(env,obj)->needTracing(); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getTrace * Signature: ()[Luk/ac/manchester/cs/factplusplus/AxiomPointer; */ JNIEXPORT jobjectArray JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getTrace (JNIEnv * env, jobject obj) { TRACE_JNI("getTrace"); TJNICache* J = getJ(env,obj); return J->buildArray ( J->K->getTrace(), J->AxiomPointer ); } #ifdef __cplusplus } #endif FaCTpp-src-v1.6.2~dfsg/src/FaCT++.JNI/JNIActor.h0000644000000000000000000001215212112642405017241 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2006-2013 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef JNIACTOR_H #define JNIACTOR_H #include "tJNICache.h" /// class for acting with concept taxonomy template class JTaxonomyActor { protected: // types /// array of TNEs typedef std::vector SynVector; /// array for a set of taxonomy verteces typedef std::vector SetOfNodes; protected: // members /// JNI environment TJNICache* J; /// 2D array to return SetOfNodes acc; /// 1D array to return SynVector plain; /// temporary vector to keep synonyms SynVector syn; protected: // methods /// create vector of Java objects by given SynVector jobjectArray getArray ( const SynVector& vec ) const { return J->buildArray ( vec, AccessPolicy::getIDs(J) ); } /// try current entry void tryEntry ( const ClassifiableEntry* p ) { if ( p->isSystem() ) return; if ( AccessPolicy::applicable(p) ) syn.push_back(AccessPolicy::buildTree(J,p)); } public: // interface /// c'tor JTaxonomyActor ( TJNICache* cache ) : J(cache) {} /// d'tor ~JTaxonomyActor ( void ) {} // return values /// get single vector of synonyms (necessary for Equivalents, for example) jobjectArray getSynonyms ( void ) const { return getArray ( acc.empty() ? SynVector() : acc[0] ); } /// get 2D array of all required elements of the taxonomy jobjectArray getElements ( void ) const { if ( AccessPolicy::needPlain() ) return getArray(plain); jobjectArray ret = J->env->NewObjectArray ( acc.size(), AccessPolicy::getIDs(J).ArrayClassID, NULL ); for ( unsigned int i = 0; i < acc.size(); ++i ) J->env->SetObjectArrayElement ( ret, i, getArray(acc[i]) ); return ret; } /// taxonomy walking method. /// @return true if node was processed, and there is no need to go further /// @return false if node can not be processed in current settings bool apply ( const TaxonomyVertex& v ) { syn.clear(); tryEntry(v.getPrimer()); for ( TaxonomyVertex::syn_iterator p = v.begin_syn(), p_end=v.end_syn(); p != p_end; ++p ) tryEntry(*p); /// no applicable elements were found if ( syn.empty() ) return false; if ( AccessPolicy::needPlain() ) plain.insert ( plain.end(), syn.begin(), syn.end() ); else acc.push_back(syn); return true; } }; // JTaxonomyActor // policy elements /// policy for concepts class ClassPolicy { public: static const TClassFieldMethodIDs& getIDs ( const TJNICache* J ) { return J->ClassPointer; } static bool applicable ( const ClassifiableEntry* p ) { return !static_cast(p)->isSingleton(); } static bool needPlain ( void ) { return false; } static TExpr* buildTree ( TJNICache* J, const ClassifiableEntry* p ) { if ( p->getId() >= 0 ) return J->getCName(p->getName()); // top or bottom std::string name(p->getName()); if ( name == std::string("TOP") ) return J->EM->Top(); else if ( name == std::string("BOTTOM") ) return J->EM->Bottom(); else // error return NULL; } }; // ClassPolicy /// policy for individuals template class IndividualPolicy { public: static const TClassFieldMethodIDs& getIDs ( const TJNICache* J ) { return J->IndividualPointer; } static bool applicable ( const ClassifiableEntry* p ) { return static_cast(p)->isSingleton(); } static bool needPlain ( void ) { return plain; } static TExpr* buildTree ( TJNICache* J, const ClassifiableEntry* p ) { return J->getIName(p->getName()); } }; // IndividualPolicy /// policy for object properties class ObjectPropertyPolicy { public: static const TClassFieldMethodIDs& getIDs ( const TJNICache* J ) { return J->ObjectPropertyPointer; } static bool applicable ( const ClassifiableEntry* ) { return true; } static bool needPlain ( void ) { return false; } static TExpr* buildTree ( TJNICache* J, const ClassifiableEntry* p ) { return p->getId() >= 0 ? J->getOName(p->getName()) : J->EM->Inverse(J->getOName(static_cast(p)->realInverse()->getName())); } }; // ObjectPropertyPolicy /// policy for data properties class DataPropertyPolicy { public: static const TClassFieldMethodIDs& getIDs ( const TJNICache* J ) { return J->DataPropertyPointer; } static bool applicable ( const ClassifiableEntry* p ) { return p->getId() > 0; } static bool needPlain ( void ) { return false; } static TExpr* buildTree ( TJNICache* J, const ClassifiableEntry* p ) { return J->getDName(p->getName()); } }; // DataPropertyPolicy #endif FaCTpp-src-v1.6.2~dfsg/src/FaCT++.JNI/JNISupport.h0000644000000000000000000001742512112642405017655 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2006-2013 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef JNISUPPORT_H #define JNISUPPORT_H #include // switch tracing on //#define JNI_TRACING #ifdef ENABLE_CHECKING # define JNI_TRACING #endif #ifdef JNI_TRACING # define TRACE_JNI(func) std::cerr << "JNI " << env << " Kernel " << getK(env,obj) << " Call " << func << "\n" # define TRACE_ARG(env,obj,arg) do { \ std::cerr << " arg "; \ TExpr* expr=getROExpr(env,arg); \ const TNamedEntity* ne = dynamic_cast(expr); \ if ( ne != NULL ) std::cerr << ne->getName(); \ std::cerr << "\n"; } while(0) #else # define TRACE_JNI(func) (void)NULL # define TRACE_ARG(env,obj,arg) (void)NULL #endif //------------------------------------------------------------- // Expression typedefs //------------------------------------------------------------- /// general expression typedef ReasoningKernel::TExpr TExpr; /// concept expression typedef ReasoningKernel::TConceptExpr TConceptExpr; /// individual expression typedef ReasoningKernel::TIndividualExpr TIndividualExpr; /// role expression typedef ReasoningKernel::TRoleExpr TRoleExpr; /// object role complex expression (including role chains and projections) typedef ReasoningKernel::TORoleComplexExpr TORoleComplexExpr; /// object role expression typedef ReasoningKernel::TORoleExpr TORoleExpr; /// data role expression typedef ReasoningKernel::TDRoleExpr TDRoleExpr; /// data expression typedef ReasoningKernel::TDataExpr TDataExpr; /// data type expression typedef ReasoningKernel::TDataTypeExpr TDataTypeExpr; /// data value expression typedef ReasoningKernel::TDataValueExpr TDataValueExpr; /// data facet expression typedef const TDLFacetExpression TFacetExpr; /// completion tree node typedef const ReasoningKernel::TCGNode TCGNode; //------------------------------------------------------------- // Support functions //------------------------------------------------------------- // class for easy dealing with Java strings class JString { private: // prevent copy JString ( const JString& ); JString& operator = ( const JString& ); protected: JNIEnv* env; jstring str; const char* buf; public: JString ( JNIEnv* e, jstring s ) : env(e), str(s) { buf = env->GetStringUTFChars(str,0); } ~JString ( void ) { env->ReleaseStringUTFChars(str,buf); } const char* operator() ( void ) const { return buf; } }; // JString /// throw exception with a given signature inline void ThrowExc ( JNIEnv * env, const char* reason, const char* className ) { jclass cls = env->FindClass(className); env->ThrowNew ( cls, reason ); } /// throw exception with an empty c'tor and a given signature inline void ThrowExc ( JNIEnv * env, const char* className ) { jclass cls = env->FindClass(className); jmethodID CtorID = env->GetMethodID ( cls, "", "()V" ); jobject obj = env->NewObject ( cls, CtorID ); env->Throw((jthrowable)obj); } /// throw general Java exception inline void ThrowGen ( JNIEnv* env, const char* reason ) { ThrowExc ( env, reason, "Ljava/lang/Exception;" ); } /// throw general FaCT++ exception inline void Throw ( JNIEnv* env, const char* reason ) { ThrowExc ( env, reason, "Lorg/semanticweb/owlapi/reasoner/ReasonerInternalException;" ); } /// throw Inconsistent Ontology exception inline void ThrowICO ( JNIEnv* env ) { ThrowExc ( env, "Lorg/semanticweb/owlapi/reasoner/InconsistentOntologyException;" ); } /// throw CR for non-simple role exception inline void ThrowNSR ( JNIEnv* env, const char* reason ) { std::string msg ("Non-simple object property '"); msg += reason; msg += "' is used as a simple one"; ThrowExc ( env, msg.c_str(), "Lorg/semanticweb/owlapi/reasoner/OWLReasonerRuntimeException;"); // not correct because does not have enough information // jclass ceNotProfile = env->FindClass("Lorg/semanticweb/owlapi/reasoner/ClassExpressionNotInProfileException;"); // if ( ceNotProfile == 0 ) // { // Throw ( env, "Can't get class for Pointer" ); // return ; // } // // jmethodID CtorID = env->GetMethodID ( ceNotProfile, "", "(Lorg/semanticweb/owlapi/model/OWLClassExpression;Lorg/semanticweb/owlapi/profiles/OWLProfile;)V" ); // // // create an object to return // jobject obj = env->NewObject ( ceNotProfile, CtorID, NULL, NULL ); // env->Throw((jthrowable)obj); } /// throw Role Inclusion Cycle exception inline void ThrowRIC ( JNIEnv* env, const char* reason ) { ThrowExc ( env, reason, "Lorg/semanticweb/owlapi/reasoner/AxiomNotInProfileException;" ); } /// throw Role Inclusion Cycle exception inline void ThrowTO ( JNIEnv* env ) { ThrowExc ( env, "Lorg/semanticweb/owlapi/reasoner/TimeOutException;" ); } /// field for Kernel's ID extern "C" jfieldID KernelFID; /// get Kernel local to given object // as a side effect sets up curKernel inline ReasoningKernel* getK ( JNIEnv * env, jobject obj ) { jlong id = env->GetLongField ( obj, KernelFID ); // this is a pointer -- should not be NULL if ( unlikely(id == 0) ) Throw ( env, "Uninitialized FaCT++ kernel found" ); return (ReasoningKernel*)id; } // helper for getTree which extracts a JLONG from a given object inline jlong getPointer ( JNIEnv * env, jobject obj ) { jclass classThis = env->GetObjectClass(obj); if ( unlikely(classThis == 0) ) { Throw ( env, "Can't get class of 'this'" ); return 0; } jfieldID fid = env->GetFieldID ( classThis, "node", "J" ); if ( unlikely(fid == 0) ) { Throw ( env, "Can't get 'node' field" ); return 0; } return env->GetLongField ( obj, fid ); } // macro to expand into the accessor function that transforms pointer into appropriate type #define ACCESSOR(Name) \ inline T ## Name* get ## Name ( JNIEnv * env, jobject obj ) { \ return dynamic_cast((TExpr*)getPointer(env,obj)); } // accessors for different expression types ACCESSOR(Expr) ACCESSOR(ConceptExpr) ACCESSOR(IndividualExpr) ACCESSOR(RoleExpr) ACCESSOR(ORoleComplexExpr) ACCESSOR(ORoleExpr) ACCESSOR(DRoleExpr) ACCESSOR(DataExpr) ACCESSOR(DataValueExpr) ACCESSOR(FacetExpr) // ACCESSOR(DataTypeExpr) -- doesn't work as DTE is not a const typedef inline TDataTypeExpr* getDataTypeExpr ( JNIEnv * env, jobject obj ) { return const_cast(dynamic_cast((TExpr*)getPointer(env,obj))); } #undef ACCESSOR // macro to expand into the RO accessor function that transforms pointer into appropriate type #define ACCESSOR(Name) \ inline const T ## Name* getRO ## Name ( JNIEnv * env, jobject obj ) { \ return dynamic_cast((const TExpr*)getPointer(env,obj)); } // accessors for different expression types ACCESSOR(Expr) ACCESSOR(ConceptExpr) ACCESSOR(IndividualExpr) ACCESSOR(RoleExpr) ACCESSOR(ORoleComplexExpr) ACCESSOR(ORoleExpr) ACCESSOR(DRoleExpr) ACCESSOR(DataExpr) ACCESSOR(DataTypeExpr) ACCESSOR(DataValueExpr) ACCESSOR(FacetExpr) // ACCESSOR(NodeExpr) -- doesn't work as the type is not a TExpr's descendant inline TCGNode* getRONode ( JNIEnv * env, jobject obj ) { return (TCGNode*)getPointer(env,obj); } #undef ACCESSOR inline TDLAxiom* getAxiom ( JNIEnv * env, jobject obj ) { return (TDLAxiom*)getPointer(env,obj); } inline TCGNode* getNode ( JNIEnv * env, jobject obj ) { return (TCGNode*)getPointer(env,obj); } #endif FaCTpp-src-v1.6.2~dfsg/src/FaCT++.JNI/uk_ac_manchester_cs_factplusplus_FaCTPlusPlus.h0000644000000000000000000015434212112642405026772 0ustar rootroot/* DO NOT EDIT THIS FILE - it is machine generated */ #include /* Header for class uk_ac_manchester_cs_factplusplus_FaCTPlusPlus */ #ifndef _Included_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus #define _Included_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus #ifdef __cplusplus extern "C" { #endif /* Inaccessible static: initDone */ /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: initMethodsFieldsIDs * Signature: ()V */ JNIEXPORT void JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_initMethodsFieldsIDs (JNIEnv *, jclass); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: initKernel * Signature: ()V */ JNIEXPORT void JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_initKernel (JNIEnv *, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: deleteKernel * Signature: ()V */ JNIEXPORT void JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_deleteKernel (JNIEnv *, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: clearKernel * Signature: ()V */ JNIEXPORT void JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_clearKernel (JNIEnv *, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: setTopBottomPropertyNames * Signature: (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V */ JNIEXPORT void JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_setTopBottomPropertyNames (JNIEnv *, jobject, jstring, jstring, jstring, jstring); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: classify * Signature: ()V */ JNIEXPORT void JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_classify (JNIEnv *, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: realise * Signature: ()V */ JNIEXPORT void JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_realise (JNIEnv *, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: isRealised * Signature: ()Z */ JNIEXPORT jboolean JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_isRealised (JNIEnv *, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getThing * Signature: ()Luk/ac/manchester/cs/factplusplus/ClassPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getThing (JNIEnv *, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getNothing * Signature: ()Luk/ac/manchester/cs/factplusplus/ClassPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getNothing (JNIEnv *, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getNamedClass * Signature: (Ljava/lang/String;)Luk/ac/manchester/cs/factplusplus/ClassPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getNamedClass (JNIEnv *, jobject, jstring); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getTopObjectProperty * Signature: ()Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getTopObjectProperty (JNIEnv *, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getBottomObjectProperty * Signature: ()Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getBottomObjectProperty (JNIEnv *, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getObjectProperty * Signature: (Ljava/lang/String;)Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getObjectProperty (JNIEnv *, jobject, jstring); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getTopDataProperty * Signature: ()Luk/ac/manchester/cs/factplusplus/DataPropertyPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getTopDataProperty (JNIEnv *, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getBottomDataProperty * Signature: ()Luk/ac/manchester/cs/factplusplus/DataPropertyPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getBottomDataProperty (JNIEnv *, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getDataProperty * Signature: (Ljava/lang/String;)Luk/ac/manchester/cs/factplusplus/DataPropertyPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getDataProperty (JNIEnv *, jobject, jstring); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getIndividual * Signature: (Ljava/lang/String;)Luk/ac/manchester/cs/factplusplus/IndividualPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getIndividual (JNIEnv *, jobject, jstring); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getDataTop * Signature: ()Luk/ac/manchester/cs/factplusplus/DataTypePointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getDataTop (JNIEnv *, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getBuiltInDataType * Signature: (Ljava/lang/String;)Luk/ac/manchester/cs/factplusplus/DataTypePointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getBuiltInDataType (JNIEnv *, jobject, jstring); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getDataSubType * Signature: (Ljava/lang/String;Luk/ac/manchester/cs/factplusplus/DataTypeExpressionPointer;)Luk/ac/manchester/cs/factplusplus/DataTypeExpressionPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getDataSubType (JNIEnv *, jobject, jstring, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getDataEnumeration * Signature: ()Luk/ac/manchester/cs/factplusplus/DataTypeExpressionPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getDataEnumeration (JNIEnv *, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getRestrictedDataType * Signature: (Luk/ac/manchester/cs/factplusplus/DataTypeExpressionPointer;Luk/ac/manchester/cs/factplusplus/DataTypeFacet;)Luk/ac/manchester/cs/factplusplus/DataTypeExpressionPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getRestrictedDataType (JNIEnv *, jobject, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getLength * Signature: (Luk/ac/manchester/cs/factplusplus/DataValuePointer;)Luk/ac/manchester/cs/factplusplus/DataTypeFacet; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getLength (JNIEnv *, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getMinLength * Signature: (Luk/ac/manchester/cs/factplusplus/DataValuePointer;)Luk/ac/manchester/cs/factplusplus/DataTypeFacet; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getMinLength (JNIEnv *, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getMaxLength * Signature: (Luk/ac/manchester/cs/factplusplus/DataValuePointer;)Luk/ac/manchester/cs/factplusplus/DataTypeFacet; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getMaxLength (JNIEnv *, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getPattern * Signature: (Luk/ac/manchester/cs/factplusplus/DataValuePointer;)Luk/ac/manchester/cs/factplusplus/DataTypeFacet; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getPattern (JNIEnv *, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getMinExclusiveFacet * Signature: (Luk/ac/manchester/cs/factplusplus/DataValuePointer;)Luk/ac/manchester/cs/factplusplus/DataTypeFacet; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getMinExclusiveFacet (JNIEnv *, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getMaxExclusiveFacet * Signature: (Luk/ac/manchester/cs/factplusplus/DataValuePointer;)Luk/ac/manchester/cs/factplusplus/DataTypeFacet; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getMaxExclusiveFacet (JNIEnv *, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getMinInclusiveFacet * Signature: (Luk/ac/manchester/cs/factplusplus/DataValuePointer;)Luk/ac/manchester/cs/factplusplus/DataTypeFacet; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getMinInclusiveFacet (JNIEnv *, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getMaxInclusiveFacet * Signature: (Luk/ac/manchester/cs/factplusplus/DataValuePointer;)Luk/ac/manchester/cs/factplusplus/DataTypeFacet; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getMaxInclusiveFacet (JNIEnv *, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getTotalDigitsFacet * Signature: (Luk/ac/manchester/cs/factplusplus/DataValuePointer;)Luk/ac/manchester/cs/factplusplus/DataTypeFacet; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getTotalDigitsFacet (JNIEnv *, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getFractionDigitsFacet * Signature: (Luk/ac/manchester/cs/factplusplus/DataValuePointer;)Luk/ac/manchester/cs/factplusplus/DataTypeFacet; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getFractionDigitsFacet (JNIEnv *, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getDataNot * Signature: (Luk/ac/manchester/cs/factplusplus/DataTypeExpressionPointer;)Luk/ac/manchester/cs/factplusplus/DataTypeExpressionPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getDataNot (JNIEnv *, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getDataIntersectionOf * Signature: ()Luk/ac/manchester/cs/factplusplus/DataTypeExpressionPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getDataIntersectionOf (JNIEnv *, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getDataUnionOf * Signature: ()Luk/ac/manchester/cs/factplusplus/DataTypeExpressionPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getDataUnionOf (JNIEnv *, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getDataValue * Signature: (Ljava/lang/String;Luk/ac/manchester/cs/factplusplus/DataTypePointer;)Luk/ac/manchester/cs/factplusplus/DataValuePointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getDataValue__Ljava_lang_String_2Luk_ac_manchester_cs_factplusplus_DataTypePointer_2 (JNIEnv *, jobject, jstring, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getConceptAnd * Signature: ()Luk/ac/manchester/cs/factplusplus/ClassPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getConceptAnd (JNIEnv *, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getConceptOr * Signature: ()Luk/ac/manchester/cs/factplusplus/ClassPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getConceptOr (JNIEnv *, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getConceptNot * Signature: (Luk/ac/manchester/cs/factplusplus/ClassPointer;)Luk/ac/manchester/cs/factplusplus/ClassPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getConceptNot (JNIEnv *, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getObjectSome * Signature: (Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;Luk/ac/manchester/cs/factplusplus/ClassPointer;)Luk/ac/manchester/cs/factplusplus/ClassPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getObjectSome (JNIEnv *, jobject, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getObjectAll * Signature: (Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;Luk/ac/manchester/cs/factplusplus/ClassPointer;)Luk/ac/manchester/cs/factplusplus/ClassPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getObjectAll (JNIEnv *, jobject, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getObjectValue * Signature: (Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;Luk/ac/manchester/cs/factplusplus/IndividualPointer;)Luk/ac/manchester/cs/factplusplus/ClassPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getObjectValue (JNIEnv *, jobject, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getObjectAtLeast * Signature: (ILuk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;Luk/ac/manchester/cs/factplusplus/ClassPointer;)Luk/ac/manchester/cs/factplusplus/ClassPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getObjectAtLeast (JNIEnv *, jobject, jint, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getObjectExact * Signature: (ILuk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;Luk/ac/manchester/cs/factplusplus/ClassPointer;)Luk/ac/manchester/cs/factplusplus/ClassPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getObjectExact (JNIEnv *, jobject, jint, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getObjectAtMost * Signature: (ILuk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;Luk/ac/manchester/cs/factplusplus/ClassPointer;)Luk/ac/manchester/cs/factplusplus/ClassPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getObjectAtMost (JNIEnv *, jobject, jint, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getDataSome * Signature: (Luk/ac/manchester/cs/factplusplus/DataPropertyPointer;Luk/ac/manchester/cs/factplusplus/DataTypeExpressionPointer;)Luk/ac/manchester/cs/factplusplus/ClassPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getDataSome (JNIEnv *, jobject, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getDataAll * Signature: (Luk/ac/manchester/cs/factplusplus/DataPropertyPointer;Luk/ac/manchester/cs/factplusplus/DataTypeExpressionPointer;)Luk/ac/manchester/cs/factplusplus/ClassPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getDataAll (JNIEnv *, jobject, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getDataValue * Signature: (Luk/ac/manchester/cs/factplusplus/DataPropertyPointer;Luk/ac/manchester/cs/factplusplus/DataValuePointer;)Luk/ac/manchester/cs/factplusplus/ClassPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getDataValue__Luk_ac_manchester_cs_factplusplus_DataPropertyPointer_2Luk_ac_manchester_cs_factplusplus_DataValuePointer_2 (JNIEnv *, jobject, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getDataAtLeast * Signature: (ILuk/ac/manchester/cs/factplusplus/DataPropertyPointer;Luk/ac/manchester/cs/factplusplus/DataTypeExpressionPointer;)Luk/ac/manchester/cs/factplusplus/ClassPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getDataAtLeast (JNIEnv *, jobject, jint, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getDataExact * Signature: (ILuk/ac/manchester/cs/factplusplus/DataPropertyPointer;Luk/ac/manchester/cs/factplusplus/DataTypeExpressionPointer;)Luk/ac/manchester/cs/factplusplus/ClassPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getDataExact (JNIEnv *, jobject, jint, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getDataAtMost * Signature: (ILuk/ac/manchester/cs/factplusplus/DataPropertyPointer;Luk/ac/manchester/cs/factplusplus/DataTypeExpressionPointer;)Luk/ac/manchester/cs/factplusplus/ClassPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getDataAtMost (JNIEnv *, jobject, jint, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getInverseProperty * Signature: (Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;)Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getInverseProperty (JNIEnv *, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getPropertyComposition * Signature: ()Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getPropertyComposition (JNIEnv *, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getDataPropertyKey * Signature: ()Luk/ac/manchester/cs/factplusplus/DataPropertyPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getDataPropertyKey (JNIEnv *, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getObjectPropertyKey * Signature: ()Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getObjectPropertyKey (JNIEnv *, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getOneOf * Signature: ()Luk/ac/manchester/cs/factplusplus/ClassPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getOneOf (JNIEnv *, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getSelf * Signature: (Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;)Luk/ac/manchester/cs/factplusplus/ClassPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getSelf (JNIEnv *, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: tellClassDeclaration * Signature: (Luk/ac/manchester/cs/factplusplus/ClassPointer;)Luk/ac/manchester/cs/factplusplus/AxiomPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_tellClassDeclaration (JNIEnv *, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: tellObjectPropertyDeclaration * Signature: (Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;)Luk/ac/manchester/cs/factplusplus/AxiomPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_tellObjectPropertyDeclaration (JNIEnv *, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: tellDataPropertyDeclaration * Signature: (Luk/ac/manchester/cs/factplusplus/DataPropertyPointer;)Luk/ac/manchester/cs/factplusplus/AxiomPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_tellDataPropertyDeclaration (JNIEnv *, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: tellIndividualDeclaration * Signature: (Luk/ac/manchester/cs/factplusplus/IndividualPointer;)Luk/ac/manchester/cs/factplusplus/AxiomPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_tellIndividualDeclaration (JNIEnv *, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: tellDatatypeDeclaration * Signature: (Luk/ac/manchester/cs/factplusplus/DataTypePointer;)Luk/ac/manchester/cs/factplusplus/AxiomPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_tellDatatypeDeclaration (JNIEnv *, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: tellSubClassOf * Signature: (Luk/ac/manchester/cs/factplusplus/ClassPointer;Luk/ac/manchester/cs/factplusplus/ClassPointer;)Luk/ac/manchester/cs/factplusplus/AxiomPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_tellSubClassOf (JNIEnv *, jobject, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: tellEquivalentClass * Signature: ()Luk/ac/manchester/cs/factplusplus/AxiomPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_tellEquivalentClass (JNIEnv *, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: tellDisjointClasses * Signature: ()Luk/ac/manchester/cs/factplusplus/AxiomPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_tellDisjointClasses (JNIEnv *, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: tellDisjointUnion * Signature: (Luk/ac/manchester/cs/factplusplus/ClassPointer;)Luk/ac/manchester/cs/factplusplus/AxiomPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_tellDisjointUnion (JNIEnv *, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: tellHasKey * Signature: (Luk/ac/manchester/cs/factplusplus/ClassPointer;Luk/ac/manchester/cs/factplusplus/DataPropertyPointer;Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;)Luk/ac/manchester/cs/factplusplus/AxiomPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_tellHasKey (JNIEnv *, jobject, jobject, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: tellSubObjectProperties * Signature: (Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;)Luk/ac/manchester/cs/factplusplus/AxiomPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_tellSubObjectProperties (JNIEnv *, jobject, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: tellEquivalentObjectProperties * Signature: ()Luk/ac/manchester/cs/factplusplus/AxiomPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_tellEquivalentObjectProperties (JNIEnv *, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: tellInverseProperties * Signature: (Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;)Luk/ac/manchester/cs/factplusplus/AxiomPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_tellInverseProperties (JNIEnv *, jobject, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: tellObjectPropertyRange * Signature: (Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;Luk/ac/manchester/cs/factplusplus/ClassPointer;)Luk/ac/manchester/cs/factplusplus/AxiomPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_tellObjectPropertyRange (JNIEnv *, jobject, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: tellDataPropertyRange * Signature: (Luk/ac/manchester/cs/factplusplus/DataPropertyPointer;Luk/ac/manchester/cs/factplusplus/DataTypeExpressionPointer;)Luk/ac/manchester/cs/factplusplus/AxiomPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_tellDataPropertyRange (JNIEnv *, jobject, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: tellObjectPropertyDomain * Signature: (Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;Luk/ac/manchester/cs/factplusplus/ClassPointer;)Luk/ac/manchester/cs/factplusplus/AxiomPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_tellObjectPropertyDomain (JNIEnv *, jobject, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: tellDataPropertyDomain * Signature: (Luk/ac/manchester/cs/factplusplus/DataPropertyPointer;Luk/ac/manchester/cs/factplusplus/ClassPointer;)Luk/ac/manchester/cs/factplusplus/AxiomPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_tellDataPropertyDomain (JNIEnv *, jobject, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: tellDisjointObjectProperties * Signature: ()Luk/ac/manchester/cs/factplusplus/AxiomPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_tellDisjointObjectProperties (JNIEnv *, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: tellFunctionalObjectProperty * Signature: (Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;)Luk/ac/manchester/cs/factplusplus/AxiomPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_tellFunctionalObjectProperty (JNIEnv *, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: tellInverseFunctionalObjectProperty * Signature: (Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;)Luk/ac/manchester/cs/factplusplus/AxiomPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_tellInverseFunctionalObjectProperty (JNIEnv *, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: tellSymmetricObjectProperty * Signature: (Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;)Luk/ac/manchester/cs/factplusplus/AxiomPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_tellSymmetricObjectProperty (JNIEnv *, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: tellAsymmetricObjectProperty * Signature: (Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;)Luk/ac/manchester/cs/factplusplus/AxiomPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_tellAsymmetricObjectProperty (JNIEnv *, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: tellReflexiveObjectProperty * Signature: (Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;)Luk/ac/manchester/cs/factplusplus/AxiomPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_tellReflexiveObjectProperty (JNIEnv *, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: tellIrreflexiveObjectProperty * Signature: (Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;)Luk/ac/manchester/cs/factplusplus/AxiomPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_tellIrreflexiveObjectProperty (JNIEnv *, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: tellTransitiveObjectProperty * Signature: (Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;)Luk/ac/manchester/cs/factplusplus/AxiomPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_tellTransitiveObjectProperty (JNIEnv *, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: tellSubDataProperties * Signature: (Luk/ac/manchester/cs/factplusplus/DataPropertyPointer;Luk/ac/manchester/cs/factplusplus/DataPropertyPointer;)Luk/ac/manchester/cs/factplusplus/AxiomPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_tellSubDataProperties (JNIEnv *, jobject, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: tellEquivalentDataProperties * Signature: ()Luk/ac/manchester/cs/factplusplus/AxiomPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_tellEquivalentDataProperties (JNIEnv *, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: tellDisjointDataProperties * Signature: ()Luk/ac/manchester/cs/factplusplus/AxiomPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_tellDisjointDataProperties (JNIEnv *, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: tellFunctionalDataProperty * Signature: (Luk/ac/manchester/cs/factplusplus/DataPropertyPointer;)Luk/ac/manchester/cs/factplusplus/AxiomPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_tellFunctionalDataProperty (JNIEnv *, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: tellIndividualType * Signature: (Luk/ac/manchester/cs/factplusplus/IndividualPointer;Luk/ac/manchester/cs/factplusplus/ClassPointer;)Luk/ac/manchester/cs/factplusplus/AxiomPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_tellIndividualType (JNIEnv *, jobject, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: tellRelatedIndividuals * Signature: (Luk/ac/manchester/cs/factplusplus/IndividualPointer;Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;Luk/ac/manchester/cs/factplusplus/IndividualPointer;)Luk/ac/manchester/cs/factplusplus/AxiomPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_tellRelatedIndividuals (JNIEnv *, jobject, jobject, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: tellNotRelatedIndividuals * Signature: (Luk/ac/manchester/cs/factplusplus/IndividualPointer;Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;Luk/ac/manchester/cs/factplusplus/IndividualPointer;)Luk/ac/manchester/cs/factplusplus/AxiomPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_tellNotRelatedIndividuals (JNIEnv *, jobject, jobject, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: tellRelatedIndividualValue * Signature: (Luk/ac/manchester/cs/factplusplus/IndividualPointer;Luk/ac/manchester/cs/factplusplus/DataPropertyPointer;Luk/ac/manchester/cs/factplusplus/DataValuePointer;)Luk/ac/manchester/cs/factplusplus/AxiomPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_tellRelatedIndividualValue (JNIEnv *, jobject, jobject, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: tellNotRelatedIndividualValue * Signature: (Luk/ac/manchester/cs/factplusplus/IndividualPointer;Luk/ac/manchester/cs/factplusplus/DataPropertyPointer;Luk/ac/manchester/cs/factplusplus/DataValuePointer;)Luk/ac/manchester/cs/factplusplus/AxiomPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_tellNotRelatedIndividualValue (JNIEnv *, jobject, jobject, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: tellSameIndividuals * Signature: ()Luk/ac/manchester/cs/factplusplus/AxiomPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_tellSameIndividuals (JNIEnv *, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: tellDifferentIndividuals * Signature: ()Luk/ac/manchester/cs/factplusplus/AxiomPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_tellDifferentIndividuals (JNIEnv *, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: retract * Signature: (Luk/ac/manchester/cs/factplusplus/AxiomPointer;)V */ JNIEXPORT void JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_retract (JNIEnv *, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: isKBConsistent * Signature: ()Z */ JNIEXPORT jboolean JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_isKBConsistent (JNIEnv *, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: isClassSatisfiable * Signature: (Luk/ac/manchester/cs/factplusplus/ClassPointer;)Z */ JNIEXPORT jboolean JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_isClassSatisfiable (JNIEnv *, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: isClassSubsumedBy * Signature: (Luk/ac/manchester/cs/factplusplus/ClassPointer;Luk/ac/manchester/cs/factplusplus/ClassPointer;)Z */ JNIEXPORT jboolean JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_isClassSubsumedBy (JNIEnv *, jobject, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: isClassEquivalentTo * Signature: (Luk/ac/manchester/cs/factplusplus/ClassPointer;Luk/ac/manchester/cs/factplusplus/ClassPointer;)Z */ JNIEXPORT jboolean JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_isClassEquivalentTo (JNIEnv *, jobject, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: isClassDisjointWith * Signature: (Luk/ac/manchester/cs/factplusplus/ClassPointer;Luk/ac/manchester/cs/factplusplus/ClassPointer;)Z */ JNIEXPORT jboolean JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_isClassDisjointWith (JNIEnv *, jobject, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: askSubClasses * Signature: (Luk/ac/manchester/cs/factplusplus/ClassPointer;Z)[[Luk/ac/manchester/cs/factplusplus/ClassPointer; */ JNIEXPORT jobjectArray JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_askSubClasses (JNIEnv *, jobject, jobject, jboolean); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: askSuperClasses * Signature: (Luk/ac/manchester/cs/factplusplus/ClassPointer;Z)[[Luk/ac/manchester/cs/factplusplus/ClassPointer; */ JNIEXPORT jobjectArray JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_askSuperClasses (JNIEnv *, jobject, jobject, jboolean); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: askEquivalentClasses * Signature: (Luk/ac/manchester/cs/factplusplus/ClassPointer;)[Luk/ac/manchester/cs/factplusplus/ClassPointer; */ JNIEXPORT jobjectArray JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_askEquivalentClasses (JNIEnv *, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: askDisjointClasses * Signature: (Luk/ac/manchester/cs/factplusplus/ClassPointer;)[[Luk/ac/manchester/cs/factplusplus/ClassPointer; */ JNIEXPORT jobjectArray JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_askDisjointClasses (JNIEnv *, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: askSuperObjectProperties * Signature: (Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;Z)[[Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer; */ JNIEXPORT jobjectArray JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_askSuperObjectProperties (JNIEnv *, jobject, jobject, jboolean); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: askSubObjectProperties * Signature: (Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;Z)[[Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer; */ JNIEXPORT jobjectArray JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_askSubObjectProperties (JNIEnv *, jobject, jobject, jboolean); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: askEquivalentObjectProperties * Signature: (Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;)[Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer; */ JNIEXPORT jobjectArray JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_askEquivalentObjectProperties (JNIEnv *, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: askObjectPropertyDomain * Signature: (Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;Z)[[Luk/ac/manchester/cs/factplusplus/ClassPointer; */ JNIEXPORT jobjectArray JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_askObjectPropertyDomain (JNIEnv *, jobject, jobject, jboolean); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: askObjectPropertyRange * Signature: (Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;Z)[[Luk/ac/manchester/cs/factplusplus/ClassPointer; */ JNIEXPORT jobjectArray JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_askObjectPropertyRange (JNIEnv *, jobject, jobject, jboolean); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: isObjectPropertyFunctional * Signature: (Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;)Z */ JNIEXPORT jboolean JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_isObjectPropertyFunctional (JNIEnv *, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: isObjectPropertyInverseFunctional * Signature: (Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;)Z */ JNIEXPORT jboolean JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_isObjectPropertyInverseFunctional (JNIEnv *, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: isObjectPropertySymmetric * Signature: (Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;)Z */ JNIEXPORT jboolean JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_isObjectPropertySymmetric (JNIEnv *, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: isObjectPropertyAsymmetric * Signature: (Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;)Z */ JNIEXPORT jboolean JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_isObjectPropertyAsymmetric (JNIEnv *, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: isObjectPropertyTransitive * Signature: (Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;)Z */ JNIEXPORT jboolean JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_isObjectPropertyTransitive (JNIEnv *, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: isObjectPropertyReflexive * Signature: (Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;)Z */ JNIEXPORT jboolean JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_isObjectPropertyReflexive (JNIEnv *, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: isObjectPropertyIrreflexive * Signature: (Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;)Z */ JNIEXPORT jboolean JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_isObjectPropertyIrreflexive (JNIEnv *, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: isObjectSubPropertyOf * Signature: (Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;)Z */ JNIEXPORT jboolean JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_isObjectSubPropertyOf (JNIEnv *, jobject, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: isObjectPropertyDisjointWith * Signature: (Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;)Z */ JNIEXPORT jboolean JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_isObjectPropertyDisjointWith (JNIEnv *, jobject, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: isSubPropertyChainOf * Signature: (Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;)Z */ JNIEXPORT jboolean JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_isSubPropertyChainOf (JNIEnv *, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: arePropertiesDisjoint * Signature: ()Z */ JNIEXPORT jboolean JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_arePropertiesDisjoint (JNIEnv *, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: askSuperDataProperties * Signature: (Luk/ac/manchester/cs/factplusplus/DataPropertyPointer;Z)[[Luk/ac/manchester/cs/factplusplus/DataPropertyPointer; */ JNIEXPORT jobjectArray JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_askSuperDataProperties (JNIEnv *, jobject, jobject, jboolean); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: askSubDataProperties * Signature: (Luk/ac/manchester/cs/factplusplus/DataPropertyPointer;Z)[[Luk/ac/manchester/cs/factplusplus/DataPropertyPointer; */ JNIEXPORT jobjectArray JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_askSubDataProperties (JNIEnv *, jobject, jobject, jboolean); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: askEquivalentDataProperties * Signature: (Luk/ac/manchester/cs/factplusplus/DataPropertyPointer;)[Luk/ac/manchester/cs/factplusplus/DataPropertyPointer; */ JNIEXPORT jobjectArray JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_askEquivalentDataProperties (JNIEnv *, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: askDataPropertyDomain * Signature: (Luk/ac/manchester/cs/factplusplus/DataPropertyPointer;Z)[[Luk/ac/manchester/cs/factplusplus/ClassPointer; */ JNIEXPORT jobjectArray JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_askDataPropertyDomain (JNIEnv *, jobject, jobject, jboolean); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: isDataPropertyFunctional * Signature: (Luk/ac/manchester/cs/factplusplus/DataPropertyPointer;)Z */ JNIEXPORT jboolean JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_isDataPropertyFunctional (JNIEnv *, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: isDataSubPropertyOf * Signature: (Luk/ac/manchester/cs/factplusplus/DataPropertyPointer;Luk/ac/manchester/cs/factplusplus/DataPropertyPointer;)Z */ JNIEXPORT jboolean JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_isDataSubPropertyOf (JNIEnv *, jobject, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: isDataPropertyDisjointWith * Signature: (Luk/ac/manchester/cs/factplusplus/DataPropertyPointer;Luk/ac/manchester/cs/factplusplus/DataPropertyPointer;)Z */ JNIEXPORT jboolean JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_isDataPropertyDisjointWith (JNIEnv *, jobject, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: askIndividualTypes * Signature: (Luk/ac/manchester/cs/factplusplus/IndividualPointer;Z)[[Luk/ac/manchester/cs/factplusplus/ClassPointer; */ JNIEXPORT jobjectArray JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_askIndividualTypes (JNIEnv *, jobject, jobject, jboolean); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: askObjectProperties * Signature: (Luk/ac/manchester/cs/factplusplus/IndividualPointer;)[Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer; */ JNIEXPORT jobjectArray JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_askObjectProperties (JNIEnv *, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: askRelatedIndividuals * Signature: (Luk/ac/manchester/cs/factplusplus/IndividualPointer;Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;)[Luk/ac/manchester/cs/factplusplus/IndividualPointer; */ JNIEXPORT jobjectArray JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_askRelatedIndividuals (JNIEnv *, jobject, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: askDataProperties * Signature: (Luk/ac/manchester/cs/factplusplus/IndividualPointer;)[Luk/ac/manchester/cs/factplusplus/DataPropertyPointer; */ JNIEXPORT jobjectArray JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_askDataProperties (JNIEnv *, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: askRelatedValues * Signature: (Luk/ac/manchester/cs/factplusplus/IndividualPointer;Luk/ac/manchester/cs/factplusplus/DataPropertyPointer;)[Luk/ac/manchester/cs/factplusplus/DataValuePointer; */ JNIEXPORT jobjectArray JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_askRelatedValues (JNIEnv *, jobject, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: hasDataPropertyRelationship * Signature: (Luk/ac/manchester/cs/factplusplus/IndividualPointer;Luk/ac/manchester/cs/factplusplus/DataPropertyPointer;Luk/ac/manchester/cs/factplusplus/DataValuePointer;)Z */ JNIEXPORT jboolean JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_hasDataPropertyRelationship (JNIEnv *, jobject, jobject, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: hasObjectPropertyRelationship * Signature: (Luk/ac/manchester/cs/factplusplus/IndividualPointer;Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;Luk/ac/manchester/cs/factplusplus/IndividualPointer;)Z */ JNIEXPORT jboolean JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_hasObjectPropertyRelationship (JNIEnv *, jobject, jobject, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: isInstanceOf * Signature: (Luk/ac/manchester/cs/factplusplus/IndividualPointer;Luk/ac/manchester/cs/factplusplus/ClassPointer;)Z */ JNIEXPORT jboolean JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_isInstanceOf (JNIEnv *, jobject, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: askInstances * Signature: (Luk/ac/manchester/cs/factplusplus/ClassPointer;Z)[Luk/ac/manchester/cs/factplusplus/IndividualPointer; */ JNIEXPORT jobjectArray JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_askInstances (JNIEnv *, jobject, jobject, jboolean); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: askInstancesGrouped * Signature: (Luk/ac/manchester/cs/factplusplus/ClassPointer;Z)[[Luk/ac/manchester/cs/factplusplus/IndividualPointer; */ JNIEXPORT jobjectArray JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_askInstancesGrouped (JNIEnv *, jobject, jobject, jboolean); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: askSameAs * Signature: (Luk/ac/manchester/cs/factplusplus/IndividualPointer;)[Luk/ac/manchester/cs/factplusplus/IndividualPointer; */ JNIEXPORT jobjectArray JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_askSameAs (JNIEnv *, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: isSameAs * Signature: (Luk/ac/manchester/cs/factplusplus/IndividualPointer;Luk/ac/manchester/cs/factplusplus/IndividualPointer;)Z */ JNIEXPORT jboolean JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_isSameAs (JNIEnv *, jobject, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: setOperationTimeout * Signature: (J)V */ JNIEXPORT void JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_setOperationTimeout (JNIEnv *, jobject, jlong); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: setFreshEntityPolicy * Signature: (Z)V */ JNIEXPORT void JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_setFreshEntityPolicy (JNIEnv *, jobject, jboolean); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: setProgressMonitor * Signature: (Luk/ac/manchester/cs/factplusplus/FaCTPlusPlusProgressMonitor;)V */ JNIEXPORT void JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_setProgressMonitor (JNIEnv *, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: startChanges * Signature: ()V */ JNIEXPORT void JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_startChanges (JNIEnv *, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: endChanges * Signature: ()V */ JNIEXPORT void JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_endChanges (JNIEnv *, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: initArgList * Signature: ()V */ JNIEXPORT void JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_initArgList (JNIEnv *, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: addArg * Signature: (Luk/ac/manchester/cs/factplusplus/Pointer;)V */ JNIEXPORT void JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_addArg (JNIEnv *, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: closeArgList * Signature: ()V */ JNIEXPORT void JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_closeArgList (JNIEnv *, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: needTracing * Signature: ()V */ JNIEXPORT void JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_needTracing (JNIEnv *, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getTrace * Signature: ()[Luk/ac/manchester/cs/factplusplus/AxiomPointer; */ JNIEXPORT jobjectArray JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getTrace (JNIEnv *, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: buildCompletionTree * Signature: (Luk/ac/manchester/cs/factplusplus/ClassPointer;)Luk/ac/manchester/cs/factplusplus/NodePointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_buildCompletionTree (JNIEnv *, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getObjectNeighbours * Signature: (Luk/ac/manchester/cs/factplusplus/NodePointer;Z)[Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer; */ JNIEXPORT jobjectArray JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getObjectNeighbours__Luk_ac_manchester_cs_factplusplus_NodePointer_2Z (JNIEnv *, jobject, jobject, jboolean); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getDataNeighbours * Signature: (Luk/ac/manchester/cs/factplusplus/NodePointer;Z)[Luk/ac/manchester/cs/factplusplus/DataPropertyPointer; */ JNIEXPORT jobjectArray JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getDataNeighbours__Luk_ac_manchester_cs_factplusplus_NodePointer_2Z (JNIEnv *, jobject, jobject, jboolean); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getObjectNeighbours * Signature: (Luk/ac/manchester/cs/factplusplus/NodePointer;Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;)[Luk/ac/manchester/cs/factplusplus/NodePointer; */ JNIEXPORT jobjectArray JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getObjectNeighbours__Luk_ac_manchester_cs_factplusplus_NodePointer_2Luk_ac_manchester_cs_factplusplus_ObjectPropertyPointer_2 (JNIEnv *, jobject, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getDataNeighbours * Signature: (Luk/ac/manchester/cs/factplusplus/NodePointer;Luk/ac/manchester/cs/factplusplus/DataPropertyPointer;)[Luk/ac/manchester/cs/factplusplus/NodePointer; */ JNIEXPORT jobjectArray JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getDataNeighbours__Luk_ac_manchester_cs_factplusplus_NodePointer_2Luk_ac_manchester_cs_factplusplus_DataPropertyPointer_2 (JNIEnv *, jobject, jobject, jobject); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getObjectLabel * Signature: (Luk/ac/manchester/cs/factplusplus/NodePointer;Z)[Luk/ac/manchester/cs/factplusplus/ClassPointer; */ JNIEXPORT jobjectArray JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getObjectLabel (JNIEnv *, jobject, jobject, jboolean); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getDataLabel * Signature: (Luk/ac/manchester/cs/factplusplus/NodePointer;Z)[Luk/ac/manchester/cs/factplusplus/DataTypePointer; */ JNIEXPORT jobjectArray JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getDataLabel (JNIEnv *, jobject, jobject, jboolean); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getAtomicDecompositionSize * Signature: (ZI)I */ JNIEXPORT jint JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getAtomicDecompositionSize (JNIEnv *, jobject, jboolean, jint); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getAtomAxioms * Signature: (I)[Luk/ac/manchester/cs/factplusplus/AxiomPointer; */ JNIEXPORT jobjectArray JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getAtomAxioms (JNIEnv *, jobject, jint); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getAtomDependents * Signature: (I)[I */ JNIEXPORT jintArray JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getAtomDependents (JNIEnv *, jobject, jint); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getModule * Signature: (ZI)[Luk/ac/manchester/cs/factplusplus/AxiomPointer; */ JNIEXPORT jobjectArray JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getModule (JNIEnv *, jobject, jboolean, jint); /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: getNonLocal * Signature: (ZI)[Luk/ac/manchester/cs/factplusplus/AxiomPointer; */ JNIEXPORT jobjectArray JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_getNonLocal (JNIEnv *, jobject, jboolean, jint); #ifdef __cplusplus } #endif #endif FaCTpp-src-v1.6.2~dfsg/src/FaCT++.JNI/JNIMonitor.h0000644000000000000000000000510212112642405017615 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2006-2011 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef JNIMONITOR_H #define JNIMONITOR_H #include "tProgressMonitor.h" #include "JNISupport.h" class JNIProgressMonitor: public TProgressMonitor { protected: JNIEnv* env; jobject javaMonitor; jmethodID sCS, nC, sF, iC; public: /// c'tor: remember object and fill in methods to call JNIProgressMonitor ( JNIEnv* Env, jobject obj ) : TProgressMonitor() , env(Env) { javaMonitor = env->NewGlobalRef(obj); jclass cls = env->GetObjectClass(obj); if ( cls == 0 ) Throw ( env, "Can't get class of ProgressMonitor object" ); sCS = env->GetMethodID ( cls, "setClassificationStarted", "(I)V" ); if ( sCS == 0 ) Throw ( env, "Can't get method setClassificationStarted" ); nC = env->GetMethodID ( cls, "nextClass", "()V" ); if ( nC == 0 ) Throw ( env, "Can't get method nextClass" ); sF = env->GetMethodID ( cls, "setFinished", "()V" ); if ( sF == 0 ) Throw ( env, "Can't get method setFinished" ); iC = env->GetMethodID ( cls, "isCancelled", "()Z" ); if ( iC == 0 ) Throw ( env, "Can't get method isCancelled" ); } /// d'tor: allow JRE to delete object virtual ~JNIProgressMonitor ( void ) { env->DeleteGlobalRef(javaMonitor); } /// informs about beginning of classification with number of concepts to be classified virtual void setClassificationStarted ( unsigned int nConcepts ) { env->CallVoidMethod ( javaMonitor, sCS, nConcepts ); } /// informs about beginning of classification of a given CONCEPT virtual void nextClass ( void ) { env->CallVoidMethod ( javaMonitor, nC ); } /// informs that the reasoning is done virtual void setFinished ( void ) { env->CallVoidMethod ( javaMonitor, sF ); } /// @return true iff reasoner have to be stopped virtual bool isCancelled ( void ) { return env->CallBooleanMethod ( javaMonitor, iC ); } }; // JNIProgressMonitor #endif FaCTpp-src-v1.6.2~dfsg/src/FaCT++.JNI/Axioms.cpp0000644000000000000000000005011312112642405017422 0ustar rootroot/* This file is part of the FaCT++ DL reasoner Copyright (C) 2006-2013 by Dmitry Tsarkov This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ // this file contains implementation of DL axiom-related methods of FaCT++ JNI interface #include "uk_ac_manchester_cs_factplusplus_FaCTPlusPlus.h" #include "Kernel.h" #include "tJNICache.h" #ifdef __cplusplus extern "C" { #endif //------------------------------------------------------------- // Concept/role/individual axioms (TELL language) //------------------------------------------------------------- #define PROCESS_QUERY(Action,Name) \ do { TRACE_JNI(Name); \ TJNICache* J = getJ(env,obj); \ try { return J->Axiom(Action); } \ catch ( const EFPPInconsistentKB& ) \ { ThrowICO(J->env); } \ catch ( const EFPPNonSimpleRole& nsr ) \ { ThrowNSR ( J->env, nsr.getRoleName() ); } \ catch ( const EFPPCycleInRIA& cir ) \ { ThrowRIC ( J->env, cir.getRoleName() ); } \ catch ( const EFaCTPlusPlus& fpp ) \ { Throw ( J->env, fpp.what() ); } \ catch ( const std::exception& ex ) \ { Throw ( J->env, ex.what() ); } \ return NULL; } while(0) // Throw ( env, "FaCT++ Kernel: error during " Name " processing" ) /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: tellClassDeclaration * Signature: (Luk/ac/manchester/cs/factplusplus/ClassPointer;)Luk/ac/manchester/cs/factplusplus/AxiomPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_tellClassDeclaration (JNIEnv * env, jobject obj, jobject arg) { PROCESS_QUERY ( J->K->declare(getConceptExpr(env,arg)), "tellClassDeclaration" ); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: tellObjectPropertyDeclaration * Signature: (Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;)Luk/ac/manchester/cs/factplusplus/AxiomPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_tellObjectPropertyDeclaration (JNIEnv * env, jobject obj, jobject arg) { PROCESS_QUERY ( getK(env,obj)->declare(getORoleExpr(env,arg)), "tellObjectPropertyDeclaration" ); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: tellDataPropertyDeclaration * Signature: (Luk/ac/manchester/cs/factplusplus/DataPropertyPointer;)Luk/ac/manchester/cs/factplusplus/AxiomPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_tellDataPropertyDeclaration (JNIEnv * env, jobject obj, jobject arg) { PROCESS_QUERY ( getK(env,obj)->declare(getDRoleExpr(env,arg)), "tellDataPropertyDeclaration" ); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: tellIndividualDeclaration * Signature: (Luk/ac/manchester/cs/factplusplus/IndividualPointer;)Luk/ac/manchester/cs/factplusplus/AxiomPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_tellIndividualDeclaration (JNIEnv * env, jobject obj, jobject arg) { PROCESS_QUERY ( getK(env,obj)->declare(getIndividualExpr(env,arg)), "tellIndividualDeclaration" ); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: tellDatatypeDeclaration * Signature: (Luk/ac/manchester/cs/factplusplus/DataTypePointer;)Luk/ac/manchester/cs/factplusplus/AxiomPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_tellDatatypeDeclaration (JNIEnv * env, jobject obj ATTR_UNUSED, jobject arg ATTR_UNUSED) { PROCESS_QUERY ( getK(env,obj)->declare(getDataTypeExpr(env,arg)), "tellDatatypeDeclaration" ); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: tellSubClassOf * Signature: (Luk/ac/manchester/cs/factplusplus/ClassPointer;Luk/ac/manchester/cs/factplusplus/ClassPointer;)Luk/ac/manchester/cs/factplusplus/AxiomPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_tellSubClassOf (JNIEnv * env, jobject obj, jobject arg1, jobject arg2) { PROCESS_QUERY ( getK(env,obj)->impliesConcepts ( getConceptExpr(env,arg1), getConceptExpr(env,arg2) ), "tellSubClassOf" ); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: tellEquivalentClass * Signature: ()Luk/ac/manchester/cs/factplusplus/AxiomPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_tellEquivalentClass (JNIEnv * env, jobject obj) { PROCESS_QUERY ( getK(env,obj)->equalConcepts(), "tellEquivalentClasses" ); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: tellDisjointClasses * Signature: ()Luk/ac/manchester/cs/factplusplus/AxiomPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_tellDisjointClasses (JNIEnv * env, jobject obj) { PROCESS_QUERY ( getK(env,obj)->disjointConcepts(), "tellDisjointClasses" ); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: tellDisjointUnion * Signature: (Luk/ac/manchester/cs/factplusplus/ClassPointer;)Luk/ac/manchester/cs/factplusplus/AxiomPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_tellDisjointUnion (JNIEnv * env, jobject obj, jobject arg) { PROCESS_QUERY ( getK(env,obj)->disjointUnion(getConceptExpr(env,arg)), "tellDisjointUnion" ); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: tellHasKey * Signature: (Luk/ac/manchester/cs/factplusplus/ClassPointer;Luk/ac/manchester/cs/factplusplus/DataPropertyPointer;Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;)Luk/ac/manchester/cs/factplusplus/AxiomPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_tellHasKey (JNIEnv * env, jobject obj ATTR_UNUSED, jobject cls ATTR_UNUSED, jobject dataprops ATTR_UNUSED, jobject objectprops ATTR_UNUSED) { TRACE_JNI("tellHasKey"); Throw ( env, "FaCT++ Kernel: unsupported operation 'tellHasKey'" ); return NULL; } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: tellSubObjectProperties * Signature: (Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;)Luk/ac/manchester/cs/factplusplus/AxiomPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_tellSubObjectProperties (JNIEnv * env, jobject obj, jobject arg1, jobject arg2) { PROCESS_QUERY ( getK(env,obj)->impliesORoles ( getORoleComplexExpr(env,arg1), getORoleExpr(env,arg2) ), "tellSubObjectProperties" ); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: tellEquivalentObjectProperties * Signature: ()Luk/ac/manchester/cs/factplusplus/AxiomPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_tellEquivalentObjectProperties (JNIEnv * env, jobject obj) { PROCESS_QUERY ( getK(env,obj)->equalORoles(), "tellEquivalentObjectProperties" ); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: tellInverseProperties * Signature: (Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;)Luk/ac/manchester/cs/factplusplus/AxiomPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_tellInverseProperties (JNIEnv * env, jobject obj, jobject arg1, jobject arg2) { PROCESS_QUERY ( getK(env,obj)->setInverseRoles ( getORoleExpr(env,arg1), getORoleExpr(env,arg2) ), "tellInverseProperties" ); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: tellObjectPropertyRange * Signature: (Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;Luk/ac/manchester/cs/factplusplus/ClassPointer;)Luk/ac/manchester/cs/factplusplus/AxiomPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_tellObjectPropertyRange (JNIEnv * env, jobject obj, jobject arg1, jobject arg2) { PROCESS_QUERY ( getK(env,obj)->setORange ( getORoleExpr(env,arg1), getConceptExpr(env,arg2) ), "tellObjectPropertyRange" ); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: tellDataPropertyRange * Signature: (Luk/ac/manchester/cs/factplusplus/DataPropertyPointer;Luk/ac/manchester/cs/factplusplus/DataTypePointer;)Luk/ac/manchester/cs/factplusplus/AxiomPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_tellDataPropertyRange (JNIEnv * env, jobject obj, jobject arg1, jobject arg2) { PROCESS_QUERY ( getK(env,obj)->setDRange ( getDRoleExpr(env,arg1), getDataExpr(env,arg2) ), "tellDataPropertyRange" ); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: tellObjectPropertyDomain * Signature: (Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;Luk/ac/manchester/cs/factplusplus/ClassPointer;)Luk/ac/manchester/cs/factplusplus/AxiomPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_tellObjectPropertyDomain (JNIEnv * env, jobject obj, jobject arg1, jobject arg2) { PROCESS_QUERY ( getK(env,obj)->setODomain ( getORoleExpr(env,arg1), getConceptExpr(env,arg2) ), "tellObjectPropertyDomain" ); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: tellDataPropertyDomain * Signature: (Luk/ac/manchester/cs/factplusplus/DataPropertyPointer;Luk/ac/manchester/cs/factplusplus/ClassPointer;)Luk/ac/manchester/cs/factplusplus/AxiomPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_tellDataPropertyDomain (JNIEnv * env, jobject obj, jobject arg1, jobject arg2) { PROCESS_QUERY ( getK(env,obj)->setDDomain ( getDRoleExpr(env,arg1), getConceptExpr(env,arg2) ), "tellDataPropertyDomain" ); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: tellDisjointObjectProperties * Signature: ()Luk/ac/manchester/cs/factplusplus/AxiomPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_tellDisjointObjectProperties (JNIEnv * env, jobject obj) { PROCESS_QUERY ( getK(env,obj)->disjointORoles(), "tellDisjointObjectProperties" ); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: tellFunctionalObjectProperty * Signature: (Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;)Luk/ac/manchester/cs/factplusplus/AxiomPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_tellFunctionalObjectProperty (JNIEnv * env, jobject obj, jobject arg) { PROCESS_QUERY ( getK(env,obj)->setOFunctional(getORoleExpr(env,arg)), "tellFunctionalObjectProperty" ); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: tellInverseFunctionalObjectProperty * Signature: (Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;)Luk/ac/manchester/cs/factplusplus/AxiomPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_tellInverseFunctionalObjectProperty (JNIEnv * env, jobject obj, jobject arg) { PROCESS_QUERY ( getK(env,obj)->setInverseFunctional(getORoleExpr(env,arg)), "tellInverseFunctionalObjectProperty" ); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: tellSymmetricObjectProperty * Signature: (Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;)Luk/ac/manchester/cs/factplusplus/AxiomPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_tellSymmetricObjectProperty (JNIEnv * env, jobject obj, jobject arg) { PROCESS_QUERY ( getK(env,obj)->setSymmetric(getORoleExpr(env,arg)), "tellSymmetricObjectProperty" ); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: tellAsymmetricObjectProperty * Signature: (Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;)Luk/ac/manchester/cs/factplusplus/AxiomPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_tellAsymmetricObjectProperty (JNIEnv * env, jobject obj, jobject arg) { PROCESS_QUERY ( getK(env,obj)->setAsymmetric(getORoleExpr(env,arg)), "tellAsymmetricObjectProperty" ); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: tellReflexiveObjectProperty * Signature: (Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;)Luk/ac/manchester/cs/factplusplus/AxiomPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_tellReflexiveObjectProperty (JNIEnv * env, jobject obj, jobject arg) { PROCESS_QUERY ( getK(env,obj)->setReflexive(getORoleExpr(env,arg)), "tellReflexiveObjectProperty" ); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: tellIrreflexiveObjectProperty * Signature: (Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;)Luk/ac/manchester/cs/factplusplus/AxiomPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_tellIrreflexiveObjectProperty (JNIEnv * env, jobject obj, jobject arg) { PROCESS_QUERY ( getK(env,obj)->setIrreflexive(getORoleExpr(env,arg)), "tellIrreflexiveObjectProperty" ); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: tellTransitiveObjectProperty * Signature: (Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;)Luk/ac/manchester/cs/factplusplus/AxiomPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_tellTransitiveObjectProperty (JNIEnv * env, jobject obj, jobject arg) { PROCESS_QUERY ( getK(env,obj)->setTransitive(getORoleExpr(env,arg)), "tellTransitiveObjectProperty" ); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: tellSubDataProperties * Signature: (Luk/ac/manchester/cs/factplusplus/DataPropertyPointer;Luk/ac/manchester/cs/factplusplus/DataPropertyPointer;)Luk/ac/manchester/cs/factplusplus/AxiomPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_tellSubDataProperties (JNIEnv * env, jobject obj, jobject arg1, jobject arg2) { PROCESS_QUERY ( getK(env,obj)->impliesDRoles ( getDRoleExpr(env,arg1), getDRoleExpr(env,arg2) ), "tellSubDataProperties" ); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: tellEquivalentDataProperties * Signature: (Luk/ac/manchester/cs/factplusplus/DataPropertyPointer;Luk/ac/manchester/cs/factplusplus/DataPropertyPointer;)Luk/ac/manchester/cs/factplusplus/AxiomPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_tellEquivalentDataProperties (JNIEnv * env, jobject obj) { PROCESS_QUERY ( getK(env,obj)->equalDRoles(), "tellEquivalentDataProperties" ); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: tellDisjointDataProperties * Signature: ()Luk/ac/manchester/cs/factplusplus/AxiomPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_tellDisjointDataProperties (JNIEnv * env, jobject obj) { PROCESS_QUERY ( getK(env,obj)->disjointDRoles(), "tellDisjointDataProperties" ); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: tellFunctionalDataProperty * Signature: (Luk/ac/manchester/cs/factplusplus/DataPropertyPointer;)Luk/ac/manchester/cs/factplusplus/AxiomPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_tellFunctionalDataProperty (JNIEnv * env, jobject obj, jobject arg) { PROCESS_QUERY ( getK(env,obj)->setDFunctional(getDRoleExpr(env,arg)), "tellFunctionalDataProperty" ); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: tellIndividualType * Signature: (Luk/ac/manchester/cs/factplusplus/IndividualPointer;Luk/ac/manchester/cs/factplusplus/ClassPointer;)Luk/ac/manchester/cs/factplusplus/AxiomPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_tellIndividualType (JNIEnv * env, jobject obj, jobject arg1, jobject arg2) { PROCESS_QUERY ( getK(env,obj)->instanceOf ( getIndividualExpr(env,arg1), getConceptExpr(env,arg2) ), "tellIndividualType" ); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: tellRelatedIndividuals * Signature: (Luk/ac/manchester/cs/factplusplus/IndividualPointer;Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;Luk/ac/manchester/cs/factplusplus/IndividualPointer;)Luk/ac/manchester/cs/factplusplus/AxiomPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_tellRelatedIndividuals (JNIEnv * env, jobject obj, jobject arg1, jobject arg2, jobject arg3) { PROCESS_QUERY ( getK(env,obj)->relatedTo ( getIndividualExpr(env,arg1), getORoleExpr(env,arg2), getIndividualExpr(env,arg3) ), "tellRelatedIndividuals" ); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: tellNotRelatedIndividuals * Signature: (Luk/ac/manchester/cs/factplusplus/IndividualPointer;Luk/ac/manchester/cs/factplusplus/ObjectPropertyPointer;Luk/ac/manchester/cs/factplusplus/IndividualPointer;)Luk/ac/manchester/cs/factplusplus/AxiomPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_tellNotRelatedIndividuals (JNIEnv * env, jobject obj, jobject arg1, jobject arg2, jobject arg3) { PROCESS_QUERY ( getK(env,obj)->relatedToNot ( getIndividualExpr(env,arg1), getORoleExpr(env,arg2), getIndividualExpr(env,arg3) ), "tellNotRelatedIndividuals" ); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: tellRelatedIndividualValue * Signature: (Luk/ac/manchester/cs/factplusplus/IndividualPointer;Luk/ac/manchester/cs/factplusplus/DataPropertyPointer;Luk/ac/manchester/cs/factplusplus/DataValuePointer;)Luk/ac/manchester/cs/factplusplus/AxiomPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_tellRelatedIndividualValue (JNIEnv * env, jobject obj, jobject arg1, jobject arg2, jobject arg3) { PROCESS_QUERY ( getK(env,obj)->valueOf ( getIndividualExpr(env,arg1), getDRoleExpr(env,arg2), getDataValueExpr(env,arg3) ), "tellRelatedIndividualValue" ); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: tellNotRelatedIndividualValue * Signature: (Luk/ac/manchester/cs/factplusplus/IndividualPointer;Luk/ac/manchester/cs/factplusplus/DataPropertyPointer;Luk/ac/manchester/cs/factplusplus/DataValuePointer;)Luk/ac/manchester/cs/factplusplus/AxiomPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_tellNotRelatedIndividualValue (JNIEnv * env, jobject obj, jobject arg1, jobject arg2, jobject arg3) { PROCESS_QUERY ( getK(env,obj)->valueOfNot ( getIndividualExpr(env,arg1), getDRoleExpr(env,arg2), getDataValueExpr(env,arg3) ), "tellNotRelatedIndividualValue" ); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: tellSameIndividuals * Signature: ()Luk/ac/manchester/cs/factplusplus/AxiomPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_tellSameIndividuals (JNIEnv * env, jobject obj) { PROCESS_QUERY ( getK(env,obj)->processSame(), "tellSameIndividuals" ); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: tellDifferentIndividuals * Signature: ()Luk/ac/manchester/cs/factplusplus/AxiomPointer; */ JNIEXPORT jobject JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_tellDifferentIndividuals (JNIEnv * env, jobject obj) { PROCESS_QUERY ( getK(env,obj)->processDifferent(), "tellDifferentIndividuals" ); } /* * Class: uk_ac_manchester_cs_factplusplus_FaCTPlusPlus * Method: retract * Signature: (Luk/ac/manchester/cs/factplusplus/AxiomPointer;)V */ JNIEXPORT void JNICALL Java_uk_ac_manchester_cs_factplusplus_FaCTPlusPlus_retract (JNIEnv * env, jobject obj, jobject axiom) { TRACE_JNI("retract"); getK(env,obj)->retract(getAxiom(env,axiom)); } #undef PROCESS_QUERY #ifdef __cplusplus } #endif