diff --git a/.github/workflows/buildtest.yml b/.github/workflows/buildtest.yml index 59aba0cc3..9ff93558e 100644 --- a/.github/workflows/buildtest.yml +++ b/.github/workflows/buildtest.yml @@ -19,21 +19,50 @@ env: NR_JOBS: "2" # cmake arguments - CMAKE_DEBUG: "-DCMAKE_BUILD_TYPE=Debug -DSTORM_DEVELOPER=ON -DSTORM_PORTABLE=ON" - CMAKE_RELEASE: "-DCMAKE_BUILD_TYPE=Release -DSTORM_DEVELOPER=OFF -DSTORM_PORTABLE=ON" + CMAKE_DEBUG: "-DCMAKE_BUILD_TYPE=Debug -DSTORM_DEVELOPER=ON -DSTORM_PORTABLE=ON -DSTORM_USE_SPOT_SHIPPED=ON" + CMAKE_RELEASE: "-DCMAKE_BUILD_TYPE=Release -DSTORM_DEVELOPER=OFF -DSTORM_PORTABLE=ON -DSTORM_USE_SPOT_SHIPPED=ON" CARL_CMAKE_DEBUG: "-DCMAKE_BUILD_TYPE=Debug -DUSE_CLN_NUMBERS=ON -DUSE_GINAC=ON -DTHREAD_SAFE=ON -DBUILD_ADDONS=ON -DBUILD_ADDON_PARSER=ON" CARL_CMAKE_RELEASE: "-DCMAKE_BUILD_TYPE=Release -DUSE_CLN_NUMBERS=ON -DUSE_GINAC=ON -DTHREAD_SAFE=ON -DBUILD_ADDONS=ON -DBUILD_ADDON_PARSER=ON" jobs: + indepthTests: + name: Indepth Tests (${{ matrix.cmakeArgs.name }}) + runs-on: ubuntu-latest + env: + DISTRO: "ubuntu-20.10" + strategy: + matrix: + cmakeArgs: + - {name: "GMP exact; GMP rational functions; Spot", args: "-DCMAKE_BUILD_TYPE=Debug -DSTORM_DEVELOPER=ON -DSTORM_PORTABLE=ON -DSTORM_USE_CLN_EA=OFF -DSTORM_USE_CLN_RF=OFF -DSTORM_USE_SPOT_SHIPPED=ON"} + # This is the standard config + # - {name: "GMP exact; CLN rational functions; Spot", args: "-DCMAKE_BUILD_TYPE=Debug -DSTORM_DEVELOPER=ON -DSTORM_PORTABLE=ON -DSTORM_USE_CLN_EA=OFF -DSTORM_USE_CLN_RF=ON -DSTORM_USE_SPOT_SHIPPED=ON"} + - {name: "CLN exact; GMP rational functions; Spot", args: "-DCMAKE_BUILD_TYPE=Debug -DSTORM_DEVELOPER=ON -DSTORM_PORTABLE=ON -DSTORM_USE_CLN_EA=ON -DSTORM_USE_CLN_RF=OFF -DSTORM_USE_SPOT_SHIPPED=ON"} + - {name: "CLN exact; CLN rational functions; Spot", args: "-DCMAKE_BUILD_TYPE=Debug -DSTORM_DEVELOPER=ON -DSTORM_PORTABLE=ON -DSTORM_USE_CLN_EA=ON -DSTORM_USE_CLN_RF=ON -DSTORM_USE_SPOT_SHIPPED=ON"} + - {name: "GMP exact; CLN rational functions; No Spot", args: "-DCMAKE_BUILD_TYPE=Debug -DSTORM_DEVELOPER=ON -DSTORM_PORTABLE=ON -DSTORM_USE_CLN_EA=ON -DSTORM_USE_CLN_RF=ON -DSTORM_USE_SPOT_SHIPPED=OFF"} + steps: + - name: Init Docker + run: sudo docker run -d -it --name storm --privileged movesrwth/storm-basesystem:${DISTRO} + - name: Git clone + # git clone cannot clone individual commits based on a sha and some other refs + # this workaround fixes this and fetches only one commit + run: | + sudo docker exec storm bash -c "mkdir /opt/storm; cd /opt/storm; git init && git remote add origin ${STORM_GIT_URL} && git fetch --depth 1 origin ${STORM_BRANCH} && git checkout FETCH_HEAD" + - name: Run cmake + run: sudo docker exec storm bash -c "mkdir /opt/storm/build; cd /opt/storm/build; cmake .. ${{ matrix.cmakeArgs.args }}" + - name: Build storm + run: sudo docker exec storm bash -c "cd /opt/storm/build; make -j ${NR_JOBS}" + - name: Run unit tests + run: sudo docker exec storm bash -c "cd /opt/storm/build; ctest test --output-on-failure" + noDeploy: name: Build and Test runs-on: ubuntu-latest strategy: matrix: distro: ["ubuntu-18.04", "debian-10", "debian-9", "ubuntu-20.04"] - debugOrRelease: ["debug", "release"] + debugOrRelease: ["release"] steps: - name: Setup cmake arguments # this is strangely the best way to implement environment variables based on the value of another @@ -160,7 +189,7 @@ jobs: notify: name: Email notification runs-on: ubuntu-latest - needs: [noDeploy, deploy] + needs: [indepthTests, noDeploy, deploy] # Only run in main repo and even if previous step failed if: github.repository_owner == 'moves-rwth' && always() steps: diff --git a/CHANGELOG.md b/CHANGELOG.md index 955a43520..f7e13b53d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,10 +9,14 @@ The releases of major and minor versions contain an overview of changes since th Version 1.6.x ------------- ## Version 1.6.4 (20xx/xx) +- Added support for model checking LTL properties in the sparse (and dd-to-sparse) engine. Requires building with Spot or an external LTL to deterministic automaton converter (using option `--ltl2datool`). +- Added cmake options `STORM_USE_SPOT_SYSTEM` and `STORM_USE_SPOT_SHIPPED` to facilitate building Storm with [Spot](https://spot.lrde.epita.fr/). +- Improved parsing of formulas in PRISM-style syntax. +- Added export of schedulers that use memory (in particular optimizing schedulers for LTL properties) - Added support for PRISM models that use unbounded integer variables. - Added an export of check results to json. Use `--exportresult` in the command line interface. - Added computation of steady state probabilities for DTMC/CTMC in the sparse engine. Use `--steadystate` in the command line interface. -- Implemented parsing and model building of Stochastic multiplayer games (SMGs) in the PRISM language. No model checking implemented, for now. +- Implemented parsing and model building of Stochastic multiplayer games (SMGs) in the PRISM language. No model checking implemented (yet). - API: Simulation of prism-models - API: Model-builder takes a callback function to prevent extension of particular actions, prism-to-explicit mapping can be exported - API: Export of dice-formatted expressions diff --git a/CMakeLists.txt b/CMakeLists.txt index 85968256d..95d5cb822 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -23,6 +23,7 @@ include(RegisterSourceGroup) include(imported) include(CheckCXXSourceCompiles) include(CheckCSourceCompiles) +include(ProcessorCount) ############################################################# ## @@ -50,6 +51,8 @@ option(USE_SMTRAT "Sets whether SMT-RAT should be included." OFF) mark_as_advanced(USE_SMTRAT) option(USE_HYPRO "Sets whether HyPro should be included." OFF) mark_as_advanced(USE_HYPRO) +option(STORM_USE_SPOT_SYSTEM "Sets whether the system version of Spot should be included (if found)." ON) +option(STORM_USE_SPOT_SHIPPED "Sets whether Spot should be downloaded and installed (if system version is not available or not used)." OFF) option(XML_SUPPORT "Sets whether xml based format parsing should be included." ON) option(FORCE_COLOR "Force color output" OFF) mark_as_advanced(FORCE_COLOR) @@ -71,6 +74,8 @@ set(GUROBI_ROOT "" CACHE STRING "A hint to the root directory of Gurobi (optiona set(Z3_ROOT "" CACHE STRING "A hint to the root directory of Z3 (optional).") set(CUDA_ROOT "" CACHE STRING "The hint to the root directory of CUDA (optional).") set(MSAT_ROOT "" CACHE STRING "The hint to the root directory of MathSAT (optional).") +set(SPOT_ROOT "" CACHE STRING "The hint to the root directory of Spot (optional).") +MARK_AS_ADVANCED(SPOT_ROOT) option(STORM_LOAD_QVBS "Sets whether the Quantitative Verification Benchmark Set (QVBS) should be downloaded." OFF) set(STORM_QVBS_ROOT "" CACHE STRING "The root directory of the Quantitative Verification Benchmark Set (QVBS) in case it should not be downloaded (optional).") MARK_AS_ADVANCED(STORM_QVBS_ROOT) @@ -79,6 +84,17 @@ set(ADDITIONAL_LINK_DIRS "" CACHE STRING "Additional directories added to the li set(USE_XERCESC ${XML_SUPPORT}) mark_as_advanced(USE_XERCESC) +# Get an approximation of the number of available processors (used for parallel build of shipped resources) +ProcessorCount(STORM_RESOURCES_BUILD_JOBCOUNT_DEFAULT) +# To be safe, we only take a little more than half of the resources. +# This also correctly deals with the case where ProcessorCount is unable to find the correct number (and thus returns 0) +MATH(EXPR STORM_RESOURCES_BUILD_JOBCOUNT_DEFAULT "${STORM_RESOURCES_BUILD_JOBCOUNT_DEFAULT}/2 + 1") +set(STORM_RESOURCES_BUILD_JOBCOUNT "${STORM_RESOURCES_BUILD_JOBCOUNT_DEFAULT}" CACHE STRING "The number of jobs used when building external resources") +mark_as_advanced(STORM_RESOURCES_BUILD_JOBCOUNT) +if(NOT STORM_RESOURCES_BUILD_JOBCOUNT GREATER 0) + message(FATAL_ERROR "STORM_RESOURCES_BUILD_JOBCOUNT must be a positive number. Got '${STORM_RESOURCES_BUILD_JOBCOUNT}' instead." ) +endif() + # Set some CMAKE Variables as advanced mark_as_advanced(CMAKE_OSX_ARCHITECTURES) mark_as_advanced(CMAKE_OSX_SYSROOT) diff --git a/doc/update_resources.md b/doc/update_resources.md index 2c5f10dbe..5db30a8c2 100644 --- a/doc/update_resources.md +++ b/doc/update_resources.md @@ -26,3 +26,7 @@ grep GOOGLETEST_VERSION $STORM_DIR/resources/3rdparty/googletest/CMakeLists.txt ``` We add some extra code to gtest located in `$STORM_DIR/src/test/storm_gtest.h`. Note that our code might not be compatible with future versions of gtest. + +## Spot + +To update (shipped version of Spot), just change the url in `$STORM_DIR/resources/3rdparty/include_spot.cmake`. \ No newline at end of file diff --git a/resources/3rdparty/CMakeLists.txt b/resources/3rdparty/CMakeLists.txt index a9d9f9400..95a5cb67c 100644 --- a/resources/3rdparty/CMakeLists.txt +++ b/resources/3rdparty/CMakeLists.txt @@ -5,6 +5,7 @@ set(STORM_3RDPARTY_SOURCE_DIR ${PROJECT_SOURCE_DIR}/resources/3rdparty) set(STORM_3RDPARTY_BINARY_DIR ${PROJECT_BINARY_DIR}/resources/3rdparty) set(STORM_3RDPARTY_INCLUDE_DIR ${PROJECT_BINARY_DIR}/include/resources/3rdparty) +message(STATUS "Storm - Building external resources with ${STORM_RESOURCES_BUILD_JOBCOUNT} job(s) in parallel.") ############################################################# ## @@ -139,6 +140,16 @@ foreach(HEADER ${SPARSEPP_HEADERS}) list(APPEND SPARSEPP_BINDIR_HEADERS ${SPARSEPP_BINDIR_DIR}/sparsepp/${HEADER_FILENAME}) endforeach() +############################################################# +## +## cpphoafparser +## +############################################################# + +# Use the shipped version of cpphoafparser +message (STATUS "storm - Including cpphoafparser 0.99.2") +include_directories("${PROJECT_SOURCE_DIR}/resources/3rdparty/cpphoafparser-0.99.2/include") + ############################################################# ## ## ModernJSON @@ -328,7 +339,7 @@ if (STORM_SHIPPED_CARL) CONFIGURE_COMMAND "" BUILD_IN_SOURCE 1 BUILD_COMMAND make lib_carl - INSTALL_COMMAND make install + INSTALL_COMMAND make install -j${STORM_RESOURCES_BUILD_JOBCOUNT} LOG_BUILD ON LOG_INSTALL ON BUILD_BYPRODUCTS ${STORM_3RDPARTY_BINARY_DIR}/carl/lib/libcarl${DYNAMIC_EXT} @@ -428,7 +439,7 @@ get_filename_component(GMPXX_LIB_LOCATION ${GMPXX_LIB} DIRECTORY) ## ############################################################# -if(STORM_USE_CLN_RF OR STORM_USE_CLN_EA) +if(STORM_HAVE_CLN) get_target_property(CLN_INCLUDE_DIR CLN_SHARED INTERFACE_INCLUDE_DIRECTORIES) endif() @@ -504,6 +515,15 @@ endif() include(${STORM_3RDPARTY_SOURCE_DIR}/include_xerces.cmake) + +############################################################# +## +## Spot +## +############################################################# + +include(${STORM_3RDPARTY_SOURCE_DIR}/include_spot.cmake) + ############################################################# ## ## Sylvan diff --git a/resources/3rdparty/cpphoafparser-0.99.2/ChangeLog b/resources/3rdparty/cpphoafparser-0.99.2/ChangeLog new file mode 100644 index 000000000..bd36b7d72 --- /dev/null +++ b/resources/3rdparty/cpphoafparser-0.99.2/ChangeLog @@ -0,0 +1,24 @@ +2016-02-26 Joachim Klein <klein@tcs.inf.tu-dresden.de> + + * Release version 0.99.2: Bugfix release + + * Fix parsing of 't' and 'f' in the extra info of acc-name headers, e.g., + acc-name: undefined t + Previously, would lead to an infinite loop. + + * Fix dynamic_bitset::getHighestSetBit + Off-by-one error, tries to read potentially uninitialized + memory. This could lead to non-deterministic behavior for + getHighestSetBit, e.g., erroneous validation errors when + parsing when HOAIntermediateCheckValidity is active. + + * Add #include <stdexcept> to boolean_expression.hh to + have access to std::logical_error, even if not included by + the other standard library headers (fix compilation issue + with some older GCCs). + + +2015-07-20 Joachim Klein <klein@tcs.inf.tu-dresden.de> + + * Release version 0.99.1: Initial (preliminary) release + diff --git a/resources/3rdparty/cpphoafparser-0.99.2/Doxyfile b/resources/3rdparty/cpphoafparser-0.99.2/Doxyfile new file mode 100644 index 000000000..5967be7d3 --- /dev/null +++ b/resources/3rdparty/cpphoafparser-0.99.2/Doxyfile @@ -0,0 +1,2362 @@ +# Doxyfile 1.8.9.1 + +# This file describes the settings to be used by the documentation system +# doxygen (www.doxygen.org) for a project. +# +# All text after a double hash (##) is considered a comment and is placed in +# front of the TAG it is preceding. +# +# All text after a single hash (#) is considered a comment and will be ignored. +# The format is: +# TAG = value [value, ...] +# For lists, items can also be appended using: +# TAG += value [value, ...] +# Values that contain spaces should be placed between quotes (\" \"). + +#--------------------------------------------------------------------------- +# Project related configuration options +#--------------------------------------------------------------------------- + +# This tag specifies the encoding used for all characters in the config file +# that follow. The default is UTF-8 which is also the encoding used for all text +# before the first occurrence of this tag. Doxygen uses libiconv (or the iconv +# built into libc) for the transcoding. See http://www.gnu.org/software/libiconv +# for the list of possible encodings. +# The default value is: UTF-8. + +DOXYFILE_ENCODING = UTF-8 + +# The PROJECT_NAME tag is a single word (or a sequence of words surrounded by +# double-quotes, unless you are using Doxywizard) that should identify the +# project for which the documentation is generated. This name is used in the +# title of most generated pages and in a few other places. +# The default value is: My Project. + +PROJECT_NAME = "cpphoafparser library API" + +# The PROJECT_NUMBER tag can be used to enter a project or revision number. This +# could be handy for archiving the generated documentation or if some version +# control system is used. + +PROJECT_NUMBER = + +# Using the PROJECT_BRIEF tag one can provide an optional one line description +# for a project that appears at the top of each page and should give viewer a +# quick idea about the purpose of the project. Keep the description short. + +PROJECT_BRIEF = + +# With the PROJECT_LOGO tag one can specify a logo or an icon that is included +# in the documentation. The maximum height of the logo should not exceed 55 +# pixels and the maximum width should not exceed 200 pixels. Doxygen will copy +# the logo to the output directory. + +PROJECT_LOGO = + +# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) path +# into which the generated documentation will be written. If a relative path is +# entered, it will be relative to the location where doxygen was started. If +# left blank the current directory will be used. + +OUTPUT_DIRECTORY = docs + +# If the CREATE_SUBDIRS tag is set to YES then doxygen will create 4096 sub- +# directories (in 2 levels) under the output directory of each output format and +# will distribute the generated files over these directories. Enabling this +# option can be useful when feeding doxygen a huge amount of source files, where +# putting all generated files in the same directory would otherwise causes +# performance problems for the file system. +# The default value is: NO. + +CREATE_SUBDIRS = NO + +# If the ALLOW_UNICODE_NAMES tag is set to YES, doxygen will allow non-ASCII +# characters to appear in the names of generated files. If set to NO, non-ASCII +# characters will be escaped, for example _xE3_x81_x84 will be used for Unicode +# U+3044. +# The default value is: NO. + +ALLOW_UNICODE_NAMES = NO + +# The OUTPUT_LANGUAGE tag is used to specify the language in which all +# documentation generated by doxygen is written. Doxygen will use this +# information to generate all constant output in the proper language. +# Possible values are: Afrikaans, Arabic, Armenian, Brazilian, Catalan, Chinese, +# Chinese-Traditional, Croatian, Czech, Danish, Dutch, English (United States), +# Esperanto, Farsi (Persian), Finnish, French, German, Greek, Hungarian, +# Indonesian, Italian, Japanese, Japanese-en (Japanese with English messages), +# Korean, Korean-en (Korean with English messages), Latvian, Lithuanian, +# Macedonian, Norwegian, Persian (Farsi), Polish, Portuguese, Romanian, Russian, +# Serbian, Serbian-Cyrillic, Slovak, Slovene, Spanish, Swedish, Turkish, +# Ukrainian and Vietnamese. +# The default value is: English. + +OUTPUT_LANGUAGE = English + +# If the BRIEF_MEMBER_DESC tag is set to YES, doxygen will include brief member +# descriptions after the members that are listed in the file and class +# documentation (similar to Javadoc). Set to NO to disable this. +# The default value is: YES. + +BRIEF_MEMBER_DESC = YES + +# If the REPEAT_BRIEF tag is set to YES, doxygen will prepend the brief +# description of a member or function before the detailed description +# +# Note: If both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the +# brief descriptions will be completely suppressed. +# The default value is: YES. + +REPEAT_BRIEF = YES + +# This tag implements a quasi-intelligent brief description abbreviator that is +# used to form the text in various listings. Each string in this list, if found +# as the leading text of the brief description, will be stripped from the text +# and the result, after processing the whole list, is used as the annotated +# text. Otherwise, the brief description is used as-is. If left blank, the +# following values are used ($name is automatically replaced with the name of +# the entity):The $name class, The $name widget, The $name file, is, provides, +# specifies, contains, represents, a, an and the. + +ABBREVIATE_BRIEF = + +# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then +# doxygen will generate a detailed section even if there is only a brief +# description. +# The default value is: NO. + +ALWAYS_DETAILED_SEC = NO + +# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all +# inherited members of a class in the documentation of that class as if those +# members were ordinary class members. Constructors, destructors and assignment +# operators of the base classes will not be shown. +# The default value is: NO. + +INLINE_INHERITED_MEMB = NO + +# If the FULL_PATH_NAMES tag is set to YES, doxygen will prepend the full path +# before files name in the file list and in the header files. If set to NO the +# shortest path that makes the file name unique will be used +# The default value is: YES. + +FULL_PATH_NAMES = YES + +# The STRIP_FROM_PATH tag can be used to strip a user-defined part of the path. +# Stripping is only done if one of the specified strings matches the left-hand +# part of the path. The tag can be used to show relative paths in the file list. +# If left blank the directory from which doxygen is run is used as the path to +# strip. +# +# Note that you can specify absolute paths here, but also relative paths, which +# will be relative from the directory where doxygen is started. +# This tag requires that the tag FULL_PATH_NAMES is set to YES. + +STRIP_FROM_PATH = + +# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of the +# path mentioned in the documentation of a class, which tells the reader which +# header file to include in order to use a class. If left blank only the name of +# the header file containing the class definition is used. Otherwise one should +# specify the list of include paths that are normally passed to the compiler +# using the -I flag. + +STRIP_FROM_INC_PATH = + +# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter (but +# less readable) file names. This can be useful is your file systems doesn't +# support long names like on DOS, Mac, or CD-ROM. +# The default value is: NO. + +SHORT_NAMES = NO + +# If the JAVADOC_AUTOBRIEF tag is set to YES then doxygen will interpret the +# first line (until the first dot) of a Javadoc-style comment as the brief +# description. If set to NO, the Javadoc-style will behave just like regular Qt- +# style comments (thus requiring an explicit @brief command for a brief +# description.) +# The default value is: NO. + +JAVADOC_AUTOBRIEF = YES + +# If the QT_AUTOBRIEF tag is set to YES then doxygen will interpret the first +# line (until the first dot) of a Qt-style comment as the brief description. If +# set to NO, the Qt-style will behave just like regular Qt-style comments (thus +# requiring an explicit \brief command for a brief description.) +# The default value is: NO. + +QT_AUTOBRIEF = NO + +# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make doxygen treat a +# multi-line C++ special comment block (i.e. a block of //! or /// comments) as +# a brief description. This used to be the default behavior. The new default is +# to treat a multi-line C++ comment block as a detailed description. Set this +# tag to YES if you prefer the old behavior instead. +# +# Note that setting this tag to YES also means that rational rose comments are +# not recognized any more. +# The default value is: NO. + +MULTILINE_CPP_IS_BRIEF = NO + +# If the INHERIT_DOCS tag is set to YES then an undocumented member inherits the +# documentation from any documented member that it re-implements. +# The default value is: YES. + +INHERIT_DOCS = YES + +# If the SEPARATE_MEMBER_PAGES tag is set to YES then doxygen will produce a new +# page for each member. If set to NO, the documentation of a member will be part +# of the file/class/namespace that contains it. +# The default value is: NO. + +SEPARATE_MEMBER_PAGES = NO + +# The TAB_SIZE tag can be used to set the number of spaces in a tab. Doxygen +# uses this value to replace tabs by spaces in code fragments. +# Minimum value: 1, maximum value: 16, default value: 4. + +TAB_SIZE = 4 + +# This tag can be used to specify a number of aliases that act as commands in +# the documentation. An alias has the form: +# name=value +# For example adding +# "sideeffect=@par Side Effects:\n" +# will allow you to put the command \sideeffect (or @sideeffect) in the +# documentation, which will result in a user-defined paragraph with heading +# "Side Effects:". You can put \n's in the value part of an alias to insert +# newlines. + +ALIASES = + +# This tag can be used to specify a number of word-keyword mappings (TCL only). +# A mapping has the form "name=value". For example adding "class=itcl::class" +# will allow you to use the command class in the itcl::class meaning. + +TCL_SUBST = + +# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C sources +# only. Doxygen will then generate output that is more tailored for C. For +# instance, some of the names that are used will be different. The list of all +# members will be omitted, etc. +# The default value is: NO. + +OPTIMIZE_OUTPUT_FOR_C = NO + +# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java or +# Python sources only. Doxygen will then generate output that is more tailored +# for that language. For instance, namespaces will be presented as packages, +# qualified scopes will look different, etc. +# The default value is: NO. + +OPTIMIZE_OUTPUT_JAVA = NO + +# Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran +# sources. Doxygen will then generate output that is tailored for Fortran. +# The default value is: NO. + +OPTIMIZE_FOR_FORTRAN = NO + +# Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL +# sources. Doxygen will then generate output that is tailored for VHDL. +# The default value is: NO. + +OPTIMIZE_OUTPUT_VHDL = NO + +# Doxygen selects the parser to use depending on the extension of the files it +# parses. With this tag you can assign which parser to use for a given +# extension. Doxygen has a built-in mapping, but you can override or extend it +# using this tag. The format is ext=language, where ext is a file extension, and +# language is one of the parsers supported by doxygen: IDL, Java, Javascript, +# C#, C, C++, D, PHP, Objective-C, Python, Fortran (fixed format Fortran: +# FortranFixed, free formatted Fortran: FortranFree, unknown formatted Fortran: +# Fortran. In the later case the parser tries to guess whether the code is fixed +# or free formatted code, this is the default for Fortran type files), VHDL. For +# instance to make doxygen treat .inc files as Fortran files (default is PHP), +# and .f files as C (default is Fortran), use: inc=Fortran f=C. +# +# Note: For files without extension you can use no_extension as a placeholder. +# +# Note that for custom extensions you also need to set FILE_PATTERNS otherwise +# the files are not read by doxygen. + +EXTENSION_MAPPING = + +# If the MARKDOWN_SUPPORT tag is enabled then doxygen pre-processes all comments +# according to the Markdown format, which allows for more readable +# documentation. See http://daringfireball.net/projects/markdown/ for details. +# The output of markdown processing is further processed by doxygen, so you can +# mix doxygen, HTML, and XML commands with Markdown formatting. Disable only in +# case of backward compatibilities issues. +# The default value is: YES. + +MARKDOWN_SUPPORT = YES + +# When enabled doxygen tries to link words that correspond to documented +# classes, or namespaces to their corresponding documentation. Such a link can +# be prevented in individual cases by putting a % sign in front of the word or +# globally by setting AUTOLINK_SUPPORT to NO. +# The default value is: YES. + +AUTOLINK_SUPPORT = YES + +# If you use STL classes (i.e. std::string, std::vector, etc.) but do not want +# to include (a tag file for) the STL sources as input, then you should set this +# tag to YES in order to let doxygen match functions declarations and +# definitions whose arguments contain STL classes (e.g. func(std::string); +# versus func(std::string) {}). This also make the inheritance and collaboration +# diagrams that involve STL classes more complete and accurate. +# The default value is: NO. + +BUILTIN_STL_SUPPORT = YES + +# If you use Microsoft's C++/CLI language, you should set this option to YES to +# enable parsing support. +# The default value is: NO. + +CPP_CLI_SUPPORT = NO + +# Set the SIP_SUPPORT tag to YES if your project consists of sip (see: +# http://www.riverbankcomputing.co.uk/software/sip/intro) sources only. Doxygen +# will parse them like normal C++ but will assume all classes use public instead +# of private inheritance when no explicit protection keyword is present. +# The default value is: NO. + +SIP_SUPPORT = NO + +# For Microsoft's IDL there are propget and propput attributes to indicate +# getter and setter methods for a property. Setting this option to YES will make +# doxygen to replace the get and set methods by a property in the documentation. +# This will only work if the methods are indeed getting or setting a simple +# type. If this is not the case, or you want to show the methods anyway, you +# should set this option to NO. +# The default value is: YES. + +IDL_PROPERTY_SUPPORT = YES + +# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC +# tag is set to YES then doxygen will reuse the documentation of the first +# member in the group (if any) for the other members of the group. By default +# all members of a group must be documented explicitly. +# The default value is: NO. + +DISTRIBUTE_GROUP_DOC = NO + +# Set the SUBGROUPING tag to YES to allow class member groups of the same type +# (for instance a group of public functions) to be put as a subgroup of that +# type (e.g. under the Public Functions section). Set it to NO to prevent +# subgrouping. Alternatively, this can be done per class using the +# \nosubgrouping command. +# The default value is: YES. + +SUBGROUPING = YES + +# When the INLINE_GROUPED_CLASSES tag is set to YES, classes, structs and unions +# are shown inside the group in which they are included (e.g. using \ingroup) +# instead of on a separate page (for HTML and Man pages) or section (for LaTeX +# and RTF). +# +# Note that this feature does not work in combination with +# SEPARATE_MEMBER_PAGES. +# The default value is: NO. + +INLINE_GROUPED_CLASSES = NO + +# When the INLINE_SIMPLE_STRUCTS tag is set to YES, structs, classes, and unions +# with only public data fields or simple typedef fields will be shown inline in +# the documentation of the scope in which they are defined (i.e. file, +# namespace, or group documentation), provided this scope is documented. If set +# to NO, structs, classes, and unions are shown on a separate page (for HTML and +# Man pages) or section (for LaTeX and RTF). +# The default value is: NO. + +INLINE_SIMPLE_STRUCTS = NO + +# When TYPEDEF_HIDES_STRUCT tag is enabled, a typedef of a struct, union, or +# enum is documented as struct, union, or enum with the name of the typedef. So +# typedef struct TypeS {} TypeT, will appear in the documentation as a struct +# with name TypeT. When disabled the typedef will appear as a member of a file, +# namespace, or class. And the struct will be named TypeS. This can typically be +# useful for C code in case the coding convention dictates that all compound +# types are typedef'ed and only the typedef is referenced, never the tag name. +# The default value is: NO. + +TYPEDEF_HIDES_STRUCT = NO + +# The size of the symbol lookup cache can be set using LOOKUP_CACHE_SIZE. This +# cache is used to resolve symbols given their name and scope. Since this can be +# an expensive process and often the same symbol appears multiple times in the +# code, doxygen keeps a cache of pre-resolved symbols. If the cache is too small +# doxygen will become slower. If the cache is too large, memory is wasted. The +# cache size is given by this formula: 2^(16+LOOKUP_CACHE_SIZE). The valid range +# is 0..9, the default is 0, corresponding to a cache size of 2^16=65536 +# symbols. At the end of a run doxygen will report the cache usage and suggest +# the optimal cache size from a speed point of view. +# Minimum value: 0, maximum value: 9, default value: 0. + +LOOKUP_CACHE_SIZE = 0 + +#--------------------------------------------------------------------------- +# Build related configuration options +#--------------------------------------------------------------------------- + +# If the EXTRACT_ALL tag is set to YES, doxygen will assume all entities in +# documentation are documented, even if no documentation was available. Private +# class members and static file members will be hidden unless the +# EXTRACT_PRIVATE respectively EXTRACT_STATIC tags are set to YES. +# Note: This will also disable the warnings about undocumented members that are +# normally produced when WARNINGS is set to YES. +# The default value is: NO. + +EXTRACT_ALL = NO + +# If the EXTRACT_PRIVATE tag is set to YES, all private members of a class will +# be included in the documentation. +# The default value is: NO. + +EXTRACT_PRIVATE = NO + +# If the EXTRACT_PACKAGE tag is set to YES, all members with package or internal +# scope will be included in the documentation. +# The default value is: NO. + +EXTRACT_PACKAGE = NO + +# If the EXTRACT_STATIC tag is set to YES, all static members of a file will be +# included in the documentation. +# The default value is: NO. + +EXTRACT_STATIC = NO + +# If the EXTRACT_LOCAL_CLASSES tag is set to YES, classes (and structs) defined +# locally in source files will be included in the documentation. If set to NO, +# only classes defined in header files are included. Does not have any effect +# for Java sources. +# The default value is: YES. + +EXTRACT_LOCAL_CLASSES = YES + +# This flag is only useful for Objective-C code. If set to YES, local methods, +# which are defined in the implementation section but not in the interface are +# included in the documentation. If set to NO, only methods in the interface are +# included. +# The default value is: NO. + +EXTRACT_LOCAL_METHODS = NO + +# If this flag is set to YES, the members of anonymous namespaces will be +# extracted and appear in the documentation as a namespace called +# 'anonymous_namespace{file}', where file will be replaced with the base name of +# the file that contains the anonymous namespace. By default anonymous namespace +# are hidden. +# The default value is: NO. + +EXTRACT_ANON_NSPACES = NO + +# If the HIDE_UNDOC_MEMBERS tag is set to YES, doxygen will hide all +# undocumented members inside documented classes or files. If set to NO these +# members will be included in the various overviews, but no documentation +# section is generated. This option has no effect if EXTRACT_ALL is enabled. +# The default value is: NO. + +HIDE_UNDOC_MEMBERS = NO + +# If the HIDE_UNDOC_CLASSES tag is set to YES, doxygen will hide all +# undocumented classes that are normally visible in the class hierarchy. If set +# to NO, these classes will be included in the various overviews. This option +# has no effect if EXTRACT_ALL is enabled. +# The default value is: NO. + +HIDE_UNDOC_CLASSES = NO + +# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, doxygen will hide all friend +# (class|struct|union) declarations. If set to NO, these declarations will be +# included in the documentation. +# The default value is: NO. + +HIDE_FRIEND_COMPOUNDS = NO + +# If the HIDE_IN_BODY_DOCS tag is set to YES, doxygen will hide any +# documentation blocks found inside the body of a function. If set to NO, these +# blocks will be appended to the function's detailed documentation block. +# The default value is: NO. + +HIDE_IN_BODY_DOCS = NO + +# The INTERNAL_DOCS tag determines if documentation that is typed after a +# \internal command is included. If the tag is set to NO then the documentation +# will be excluded. Set it to YES to include the internal documentation. +# The default value is: NO. + +INTERNAL_DOCS = NO + +# If the CASE_SENSE_NAMES tag is set to NO then doxygen will only generate file +# names in lower-case letters. If set to YES, upper-case letters are also +# allowed. This is useful if you have classes or files whose names only differ +# in case and if your file system supports case sensitive file names. Windows +# and Mac users are advised to set this option to NO. +# The default value is: system dependent. + +CASE_SENSE_NAMES = NO + +# If the HIDE_SCOPE_NAMES tag is set to NO then doxygen will show members with +# their full class and namespace scopes in the documentation. If set to YES, the +# scope will be hidden. +# The default value is: NO. + +HIDE_SCOPE_NAMES = NO + +# If the HIDE_COMPOUND_REFERENCE tag is set to NO (default) then doxygen will +# append additional text to a page's title, such as Class Reference. If set to +# YES the compound reference will be hidden. +# The default value is: NO. + +HIDE_COMPOUND_REFERENCE= NO + +# If the SHOW_INCLUDE_FILES tag is set to YES then doxygen will put a list of +# the files that are included by a file in the documentation of that file. +# The default value is: YES. + +SHOW_INCLUDE_FILES = YES + +# If the SHOW_GROUPED_MEMB_INC tag is set to YES then Doxygen will add for each +# grouped member an include statement to the documentation, telling the reader +# which file to include in order to use the member. +# The default value is: NO. + +SHOW_GROUPED_MEMB_INC = NO + +# If the FORCE_LOCAL_INCLUDES tag is set to YES then doxygen will list include +# files with double quotes in the documentation rather than with sharp brackets. +# The default value is: NO. + +FORCE_LOCAL_INCLUDES = NO + +# If the INLINE_INFO tag is set to YES then a tag [inline] is inserted in the +# documentation for inline members. +# The default value is: YES. + +INLINE_INFO = YES + +# If the SORT_MEMBER_DOCS tag is set to YES then doxygen will sort the +# (detailed) documentation of file and class members alphabetically by member +# name. If set to NO, the members will appear in declaration order. +# The default value is: YES. + +SORT_MEMBER_DOCS = YES + +# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the brief +# descriptions of file, namespace and class members alphabetically by member +# name. If set to NO, the members will appear in declaration order. Note that +# this will also influence the order of the classes in the class list. +# The default value is: NO. + +SORT_BRIEF_DOCS = NO + +# If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen will sort the +# (brief and detailed) documentation of class members so that constructors and +# destructors are listed first. If set to NO the constructors will appear in the +# respective orders defined by SORT_BRIEF_DOCS and SORT_MEMBER_DOCS. +# Note: If SORT_BRIEF_DOCS is set to NO this option is ignored for sorting brief +# member documentation. +# Note: If SORT_MEMBER_DOCS is set to NO this option is ignored for sorting +# detailed member documentation. +# The default value is: NO. + +SORT_MEMBERS_CTORS_1ST = NO + +# If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the hierarchy +# of group names into alphabetical order. If set to NO the group names will +# appear in their defined order. +# The default value is: NO. + +SORT_GROUP_NAMES = NO + +# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be sorted by +# fully-qualified names, including namespaces. If set to NO, the class list will +# be sorted only by class name, not including the namespace part. +# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES. +# Note: This option applies only to the class list, not to the alphabetical +# list. +# The default value is: NO. + +SORT_BY_SCOPE_NAME = NO + +# If the STRICT_PROTO_MATCHING option is enabled and doxygen fails to do proper +# type resolution of all parameters of a function it will reject a match between +# the prototype and the implementation of a member function even if there is +# only one candidate or it is obvious which candidate to choose by doing a +# simple string match. By disabling STRICT_PROTO_MATCHING doxygen will still +# accept a match between prototype and implementation in such cases. +# The default value is: NO. + +STRICT_PROTO_MATCHING = NO + +# The GENERATE_TODOLIST tag can be used to enable (YES) or disable (NO) the todo +# list. This list is created by putting \todo commands in the documentation. +# The default value is: YES. + +GENERATE_TODOLIST = YES + +# The GENERATE_TESTLIST tag can be used to enable (YES) or disable (NO) the test +# list. This list is created by putting \test commands in the documentation. +# The default value is: YES. + +GENERATE_TESTLIST = YES + +# The GENERATE_BUGLIST tag can be used to enable (YES) or disable (NO) the bug +# list. This list is created by putting \bug commands in the documentation. +# The default value is: YES. + +GENERATE_BUGLIST = YES + +# The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or disable (NO) +# the deprecated list. This list is created by putting \deprecated commands in +# the documentation. +# The default value is: YES. + +GENERATE_DEPRECATEDLIST= YES + +# The ENABLED_SECTIONS tag can be used to enable conditional documentation +# sections, marked by \if <section_label> ... \endif and \cond <section_label> +# ... \endcond blocks. + +ENABLED_SECTIONS = + +# The MAX_INITIALIZER_LINES tag determines the maximum number of lines that the +# initial value of a variable or macro / define can have for it to appear in the +# documentation. If the initializer consists of more lines than specified here +# it will be hidden. Use a value of 0 to hide initializers completely. The +# appearance of the value of individual variables and macros / defines can be +# controlled using \showinitializer or \hideinitializer command in the +# documentation regardless of this setting. +# Minimum value: 0, maximum value: 10000, default value: 30. + +MAX_INITIALIZER_LINES = 30 + +# Set the SHOW_USED_FILES tag to NO to disable the list of files generated at +# the bottom of the documentation of classes and structs. If set to YES, the +# list will mention the files that were used to generate the documentation. +# The default value is: YES. + +SHOW_USED_FILES = YES + +# Set the SHOW_FILES tag to NO to disable the generation of the Files page. This +# will remove the Files entry from the Quick Index and from the Folder Tree View +# (if specified). +# The default value is: YES. + +SHOW_FILES = YES + +# Set the SHOW_NAMESPACES tag to NO to disable the generation of the Namespaces +# page. This will remove the Namespaces entry from the Quick Index and from the +# Folder Tree View (if specified). +# The default value is: YES. + +SHOW_NAMESPACES = YES + +# The FILE_VERSION_FILTER tag can be used to specify a program or script that +# doxygen should invoke to get the current version for each file (typically from +# the version control system). Doxygen will invoke the program by executing (via +# popen()) the command command input-file, where command is the value of the +# FILE_VERSION_FILTER tag, and input-file is the name of an input file provided +# by doxygen. Whatever the program writes to standard output is used as the file +# version. For an example see the documentation. + +FILE_VERSION_FILTER = + +# The LAYOUT_FILE tag can be used to specify a layout file which will be parsed +# by doxygen. The layout file controls the global structure of the generated +# output files in an output format independent way. To create the layout file +# that represents doxygen's defaults, run doxygen with the -l option. You can +# optionally specify a file name after the option, if omitted DoxygenLayout.xml +# will be used as the name of the layout file. +# +# Note that if you run doxygen from a directory containing a file called +# DoxygenLayout.xml, doxygen will parse it automatically even if the LAYOUT_FILE +# tag is left empty. + +LAYOUT_FILE = + +# The CITE_BIB_FILES tag can be used to specify one or more bib files containing +# the reference definitions. This must be a list of .bib files. The .bib +# extension is automatically appended if omitted. This requires the bibtex tool +# to be installed. See also http://en.wikipedia.org/wiki/BibTeX for more info. +# For LaTeX the style of the bibliography can be controlled using +# LATEX_BIB_STYLE. To use this feature you need bibtex and perl available in the +# search path. See also \cite for info how to create references. + +CITE_BIB_FILES = + +#--------------------------------------------------------------------------- +# Configuration options related to warning and progress messages +#--------------------------------------------------------------------------- + +# The QUIET tag can be used to turn on/off the messages that are generated to +# standard output by doxygen. If QUIET is set to YES this implies that the +# messages are off. +# The default value is: NO. + +QUIET = NO + +# The WARNINGS tag can be used to turn on/off the warning messages that are +# generated to standard error (stderr) by doxygen. If WARNINGS is set to YES +# this implies that the warnings are on. +# +# Tip: Turn warnings on while writing the documentation. +# The default value is: YES. + +WARNINGS = YES + +# If the WARN_IF_UNDOCUMENTED tag is set to YES then doxygen will generate +# warnings for undocumented members. If EXTRACT_ALL is set to YES then this flag +# will automatically be disabled. +# The default value is: YES. + +WARN_IF_UNDOCUMENTED = YES + +# If the WARN_IF_DOC_ERROR tag is set to YES, doxygen will generate warnings for +# potential errors in the documentation, such as not documenting some parameters +# in a documented function, or documenting parameters that don't exist or using +# markup commands wrongly. +# The default value is: YES. + +WARN_IF_DOC_ERROR = YES + +# This WARN_NO_PARAMDOC option can be enabled to get warnings for functions that +# are documented, but have no documentation for their parameters or return +# value. If set to NO, doxygen will only warn about wrong or incomplete +# parameter documentation, but not about the absence of documentation. +# The default value is: NO. + +WARN_NO_PARAMDOC = NO + +# The WARN_FORMAT tag determines the format of the warning messages that doxygen +# can produce. The string should contain the $file, $line, and $text tags, which +# will be replaced by the file and line number from which the warning originated +# and the warning text. Optionally the format may contain $version, which will +# be replaced by the version of the file (if it could be obtained via +# FILE_VERSION_FILTER) +# The default value is: $file:$line: $text. + +WARN_FORMAT = "$file:$line: $text" + +# The WARN_LOGFILE tag can be used to specify a file to which warning and error +# messages should be written. If left blank the output is written to standard +# error (stderr). + +WARN_LOGFILE = + +#--------------------------------------------------------------------------- +# Configuration options related to the input files +#--------------------------------------------------------------------------- + +# The INPUT tag is used to specify the files and/or directories that contain +# documented source files. You may enter file names like myfile.cpp or +# directories like /usr/src/myproject. Separate the files or directories with +# spaces. +# Note: If this tag is empty the current directory is searched. + +INPUT = include + +# This tag can be used to specify the character encoding of the source files +# that doxygen parses. Internally doxygen uses the UTF-8 encoding. Doxygen uses +# libiconv (or the iconv built into libc) for the transcoding. See the libiconv +# documentation (see: http://www.gnu.org/software/libiconv) for the list of +# possible encodings. +# The default value is: UTF-8. + +INPUT_ENCODING = UTF-8 + +# If the value of the INPUT tag contains directories, you can use the +# FILE_PATTERNS tag to specify one or more wildcard patterns (like *.cpp and +# *.h) to filter out the source-files in the directories. If left blank the +# following patterns are tested:*.c, *.cc, *.cxx, *.cpp, *.c++, *.java, *.ii, +# *.ixx, *.ipp, *.i++, *.inl, *.idl, *.ddl, *.odl, *.h, *.hh, *.hxx, *.hpp, +# *.h++, *.cs, *.d, *.php, *.php4, *.php5, *.phtml, *.inc, *.m, *.markdown, +# *.md, *.mm, *.dox, *.py, *.f90, *.f, *.for, *.tcl, *.vhd, *.vhdl, *.ucf, +# *.qsf, *.as and *.js. + +FILE_PATTERNS = + +# The RECURSIVE tag can be used to specify whether or not subdirectories should +# be searched for input files as well. +# The default value is: NO. + +RECURSIVE = YES + +# The EXCLUDE tag can be used to specify files and/or directories that should be +# excluded from the INPUT source files. This way you can easily exclude a +# subdirectory from a directory tree whose root is specified with the INPUT tag. +# +# Note that relative paths are relative to the directory from which doxygen is +# run. + +EXCLUDE = + +# The EXCLUDE_SYMLINKS tag can be used to select whether or not files or +# directories that are symbolic links (a Unix file system feature) are excluded +# from the input. +# The default value is: NO. + +EXCLUDE_SYMLINKS = NO + +# If the value of the INPUT tag contains directories, you can use the +# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude +# certain files from those directories. +# +# Note that the wildcards are matched against the file with absolute path, so to +# exclude all test directories for example use the pattern */test/* + +EXCLUDE_PATTERNS = + +# The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names +# (namespaces, classes, functions, etc.) that should be excluded from the +# output. The symbol name can be a fully qualified name, a word, or if the +# wildcard * is used, a substring. Examples: ANamespace, AClass, +# AClass::ANamespace, ANamespace::*Test +# +# Note that the wildcards are matched against the file with absolute path, so to +# exclude all test directories use the pattern */test/* + +EXCLUDE_SYMBOLS = + +# The EXAMPLE_PATH tag can be used to specify one or more files or directories +# that contain example code fragments that are included (see the \include +# command). + +EXAMPLE_PATH = + +# If the value of the EXAMPLE_PATH tag contains directories, you can use the +# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp and +# *.h) to filter out the source-files in the directories. If left blank all +# files are included. + +EXAMPLE_PATTERNS = + +# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be +# searched for input files to be used with the \include or \dontinclude commands +# irrespective of the value of the RECURSIVE tag. +# The default value is: NO. + +EXAMPLE_RECURSIVE = NO + +# The IMAGE_PATH tag can be used to specify one or more files or directories +# that contain images that are to be included in the documentation (see the +# \image command). + +IMAGE_PATH = + +# The INPUT_FILTER tag can be used to specify a program that doxygen should +# invoke to filter for each input file. Doxygen will invoke the filter program +# by executing (via popen()) the command: +# +# <filter> <input-file> +# +# where <filter> is the value of the INPUT_FILTER tag, and <input-file> is the +# name of an input file. Doxygen will then use the output that the filter +# program writes to standard output. If FILTER_PATTERNS is specified, this tag +# will be ignored. +# +# Note that the filter must not add or remove lines; it is applied before the +# code is scanned, but not when the output code is generated. If lines are added +# or removed, the anchors will not be placed correctly. + +INPUT_FILTER = + +# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern +# basis. Doxygen will compare the file name with each pattern and apply the +# filter if there is a match. The filters are a list of the form: pattern=filter +# (like *.cpp=my_cpp_filter). See INPUT_FILTER for further information on how +# filters are used. If the FILTER_PATTERNS tag is empty or if none of the +# patterns match the file name, INPUT_FILTER is applied. + +FILTER_PATTERNS = + +# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using +# INPUT_FILTER) will also be used to filter the input files that are used for +# producing the source files to browse (i.e. when SOURCE_BROWSER is set to YES). +# The default value is: NO. + +FILTER_SOURCE_FILES = NO + +# The FILTER_SOURCE_PATTERNS tag can be used to specify source filters per file +# pattern. A pattern will override the setting for FILTER_PATTERN (if any) and +# it is also possible to disable source filtering for a specific pattern using +# *.ext= (so without naming a filter). +# This tag requires that the tag FILTER_SOURCE_FILES is set to YES. + +FILTER_SOURCE_PATTERNS = + +# If the USE_MDFILE_AS_MAINPAGE tag refers to the name of a markdown file that +# is part of the input, its contents will be placed on the main page +# (index.html). This can be useful if you have a project on for instance GitHub +# and want to reuse the introduction page also for the doxygen output. + +USE_MDFILE_AS_MAINPAGE = + +#--------------------------------------------------------------------------- +# Configuration options related to source browsing +#--------------------------------------------------------------------------- + +# If the SOURCE_BROWSER tag is set to YES then a list of source files will be +# generated. Documented entities will be cross-referenced with these sources. +# +# Note: To get rid of all source code in the generated output, make sure that +# also VERBATIM_HEADERS is set to NO. +# The default value is: NO. + +SOURCE_BROWSER = NO + +# Setting the INLINE_SOURCES tag to YES will include the body of functions, +# classes and enums directly into the documentation. +# The default value is: NO. + +INLINE_SOURCES = NO + +# Setting the STRIP_CODE_COMMENTS tag to YES will instruct doxygen to hide any +# special comment blocks from generated source code fragments. Normal C, C++ and +# Fortran comments will always remain visible. +# The default value is: YES. + +STRIP_CODE_COMMENTS = YES + +# If the REFERENCED_BY_RELATION tag is set to YES then for each documented +# function all documented functions referencing it will be listed. +# The default value is: NO. + +REFERENCED_BY_RELATION = NO + +# If the REFERENCES_RELATION tag is set to YES then for each documented function +# all documented entities called/used by that function will be listed. +# The default value is: NO. + +REFERENCES_RELATION = NO + +# If the REFERENCES_LINK_SOURCE tag is set to YES and SOURCE_BROWSER tag is set +# to YES then the hyperlinks from functions in REFERENCES_RELATION and +# REFERENCED_BY_RELATION lists will link to the source code. Otherwise they will +# link to the documentation. +# The default value is: YES. + +REFERENCES_LINK_SOURCE = YES + +# If SOURCE_TOOLTIPS is enabled (the default) then hovering a hyperlink in the +# source code will show a tooltip with additional information such as prototype, +# brief description and links to the definition and documentation. Since this +# will make the HTML file larger and loading of large files a bit slower, you +# can opt to disable this feature. +# The default value is: YES. +# This tag requires that the tag SOURCE_BROWSER is set to YES. + +SOURCE_TOOLTIPS = YES + +# If the USE_HTAGS tag is set to YES then the references to source code will +# point to the HTML generated by the htags(1) tool instead of doxygen built-in +# source browser. The htags tool is part of GNU's global source tagging system +# (see http://www.gnu.org/software/global/global.html). You will need version +# 4.8.6 or higher. +# +# To use it do the following: +# - Install the latest version of global +# - Enable SOURCE_BROWSER and USE_HTAGS in the config file +# - Make sure the INPUT points to the root of the source tree +# - Run doxygen as normal +# +# Doxygen will invoke htags (and that will in turn invoke gtags), so these +# tools must be available from the command line (i.e. in the search path). +# +# The result: instead of the source browser generated by doxygen, the links to +# source code will now point to the output of htags. +# The default value is: NO. +# This tag requires that the tag SOURCE_BROWSER is set to YES. + +USE_HTAGS = NO + +# If the VERBATIM_HEADERS tag is set the YES then doxygen will generate a +# verbatim copy of the header file for each class for which an include is +# specified. Set to NO to disable this. +# See also: Section \class. +# The default value is: YES. + +VERBATIM_HEADERS = YES + +#--------------------------------------------------------------------------- +# Configuration options related to the alphabetical class index +#--------------------------------------------------------------------------- + +# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index of all +# compounds will be generated. Enable this if the project contains a lot of +# classes, structs, unions or interfaces. +# The default value is: YES. + +ALPHABETICAL_INDEX = YES + +# The COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns in +# which the alphabetical index list will be split. +# Minimum value: 1, maximum value: 20, default value: 5. +# This tag requires that the tag ALPHABETICAL_INDEX is set to YES. + +COLS_IN_ALPHA_INDEX = 5 + +# In case all classes in a project start with a common prefix, all classes will +# be put under the same header in the alphabetical index. The IGNORE_PREFIX tag +# can be used to specify a prefix (or a list of prefixes) that should be ignored +# while generating the index headers. +# This tag requires that the tag ALPHABETICAL_INDEX is set to YES. + +IGNORE_PREFIX = + +#--------------------------------------------------------------------------- +# Configuration options related to the HTML output +#--------------------------------------------------------------------------- + +# If the GENERATE_HTML tag is set to YES, doxygen will generate HTML output +# The default value is: YES. + +GENERATE_HTML = YES + +# The HTML_OUTPUT tag is used to specify where the HTML docs will be put. If a +# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of +# it. +# The default directory is: html. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_OUTPUT = api-html + +# The HTML_FILE_EXTENSION tag can be used to specify the file extension for each +# generated HTML page (for example: .htm, .php, .asp). +# The default value is: .html. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_FILE_EXTENSION = .html + +# The HTML_HEADER tag can be used to specify a user-defined HTML header file for +# each generated HTML page. If the tag is left blank doxygen will generate a +# standard header. +# +# To get valid HTML the header file that includes any scripts and style sheets +# that doxygen needs, which is dependent on the configuration options used (e.g. +# the setting GENERATE_TREEVIEW). It is highly recommended to start with a +# default header using +# doxygen -w html new_header.html new_footer.html new_stylesheet.css +# YourConfigFile +# and then modify the file new_header.html. See also section "Doxygen usage" +# for information on how to generate the default header that doxygen normally +# uses. +# Note: The header is subject to change so you typically have to regenerate the +# default header when upgrading to a newer version of doxygen. For a description +# of the possible markers and block names see the documentation. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_HEADER = + +# The HTML_FOOTER tag can be used to specify a user-defined HTML footer for each +# generated HTML page. If the tag is left blank doxygen will generate a standard +# footer. See HTML_HEADER for more information on how to generate a default +# footer and what special commands can be used inside the footer. See also +# section "Doxygen usage" for information on how to generate the default footer +# that doxygen normally uses. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_FOOTER = + +# The HTML_STYLESHEET tag can be used to specify a user-defined cascading style +# sheet that is used by each HTML page. It can be used to fine-tune the look of +# the HTML output. If left blank doxygen will generate a default style sheet. +# See also section "Doxygen usage" for information on how to generate the style +# sheet that doxygen normally uses. +# Note: It is recommended to use HTML_EXTRA_STYLESHEET instead of this tag, as +# it is more robust and this tag (HTML_STYLESHEET) will in the future become +# obsolete. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_STYLESHEET = + +# The HTML_EXTRA_STYLESHEET tag can be used to specify additional user-defined +# cascading style sheets that are included after the standard style sheets +# created by doxygen. Using this option one can overrule certain style aspects. +# This is preferred over using HTML_STYLESHEET since it does not replace the +# standard style sheet and is therefore more robust against future updates. +# Doxygen will copy the style sheet files to the output directory. +# Note: The order of the extra style sheet files is of importance (e.g. the last +# style sheet in the list overrules the setting of the previous ones in the +# list). For an example see the documentation. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_EXTRA_STYLESHEET = + +# The HTML_EXTRA_FILES tag can be used to specify one or more extra images or +# other source files which should be copied to the HTML output directory. Note +# that these files will be copied to the base HTML output directory. Use the +# $relpath^ marker in the HTML_HEADER and/or HTML_FOOTER files to load these +# files. In the HTML_STYLESHEET file, use the file name only. Also note that the +# files will be copied as-is; there are no commands or markers available. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_EXTRA_FILES = + +# The HTML_COLORSTYLE_HUE tag controls the color of the HTML output. Doxygen +# will adjust the colors in the style sheet and background images according to +# this color. Hue is specified as an angle on a colorwheel, see +# http://en.wikipedia.org/wiki/Hue for more information. For instance the value +# 0 represents red, 60 is yellow, 120 is green, 180 is cyan, 240 is blue, 300 +# purple, and 360 is red again. +# Minimum value: 0, maximum value: 359, default value: 220. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_COLORSTYLE_HUE = 203 + +# The HTML_COLORSTYLE_SAT tag controls the purity (or saturation) of the colors +# in the HTML output. For a value of 0 the output will use grayscales only. A +# value of 255 will produce the most vivid colors. +# Minimum value: 0, maximum value: 255, default value: 100. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_COLORSTYLE_SAT = 150 + +# The HTML_COLORSTYLE_GAMMA tag controls the gamma correction applied to the +# luminance component of the colors in the HTML output. Values below 100 +# gradually make the output lighter, whereas values above 100 make the output +# darker. The value divided by 100 is the actual gamma applied, so 80 represents +# a gamma of 0.8, The value 220 represents a gamma of 2.2, and 100 does not +# change the gamma. +# Minimum value: 40, maximum value: 240, default value: 80. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_COLORSTYLE_GAMMA = 80 + +# If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML +# page will contain the date and time when the page was generated. Setting this +# to NO can help when comparing the output of multiple runs. +# The default value is: YES. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_TIMESTAMP = NO + +# If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML +# documentation will contain sections that can be hidden and shown after the +# page has loaded. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_DYNAMIC_SECTIONS = YES + +# With HTML_INDEX_NUM_ENTRIES one can control the preferred number of entries +# shown in the various tree structured indices initially; the user can expand +# and collapse entries dynamically later on. Doxygen will expand the tree to +# such a level that at most the specified number of entries are visible (unless +# a fully collapsed tree already exceeds this amount). So setting the number of +# entries 1 will produce a full collapsed tree by default. 0 is a special value +# representing an infinite number of entries and will result in a full expanded +# tree by default. +# Minimum value: 0, maximum value: 9999, default value: 100. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_INDEX_NUM_ENTRIES = 100 + +# If the GENERATE_DOCSET tag is set to YES, additional index files will be +# generated that can be used as input for Apple's Xcode 3 integrated development +# environment (see: http://developer.apple.com/tools/xcode/), introduced with +# OSX 10.5 (Leopard). To create a documentation set, doxygen will generate a +# Makefile in the HTML output directory. Running make will produce the docset in +# that directory and running make install will install the docset in +# ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find it at +# startup. See http://developer.apple.com/tools/creatingdocsetswithdoxygen.html +# for more information. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +GENERATE_DOCSET = NO + +# This tag determines the name of the docset feed. A documentation feed provides +# an umbrella under which multiple documentation sets from a single provider +# (such as a company or product suite) can be grouped. +# The default value is: Doxygen generated docs. +# This tag requires that the tag GENERATE_DOCSET is set to YES. + +DOCSET_FEEDNAME = "Doxygen generated docs" + +# This tag specifies a string that should uniquely identify the documentation +# set bundle. This should be a reverse domain-name style string, e.g. +# com.mycompany.MyDocSet. Doxygen will append .docset to the name. +# The default value is: org.doxygen.Project. +# This tag requires that the tag GENERATE_DOCSET is set to YES. + +DOCSET_BUNDLE_ID = org.doxygen.Project + +# The DOCSET_PUBLISHER_ID tag specifies a string that should uniquely identify +# the documentation publisher. This should be a reverse domain-name style +# string, e.g. com.mycompany.MyDocSet.documentation. +# The default value is: org.doxygen.Publisher. +# This tag requires that the tag GENERATE_DOCSET is set to YES. + +DOCSET_PUBLISHER_ID = org.doxygen.Publisher + +# The DOCSET_PUBLISHER_NAME tag identifies the documentation publisher. +# The default value is: Publisher. +# This tag requires that the tag GENERATE_DOCSET is set to YES. + +DOCSET_PUBLISHER_NAME = Publisher + +# If the GENERATE_HTMLHELP tag is set to YES then doxygen generates three +# additional HTML index files: index.hhp, index.hhc, and index.hhk. The +# index.hhp is a project file that can be read by Microsoft's HTML Help Workshop +# (see: http://www.microsoft.com/en-us/download/details.aspx?id=21138) on +# Windows. +# +# The HTML Help Workshop contains a compiler that can convert all HTML output +# generated by doxygen into a single compiled HTML file (.chm). Compiled HTML +# files are now used as the Windows 98 help format, and will replace the old +# Windows help format (.hlp) on all Windows platforms in the future. Compressed +# HTML files also contain an index, a table of contents, and you can search for +# words in the documentation. The HTML workshop also contains a viewer for +# compressed HTML files. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +GENERATE_HTMLHELP = NO + +# The CHM_FILE tag can be used to specify the file name of the resulting .chm +# file. You can add a path in front of the file if the result should not be +# written to the html output directory. +# This tag requires that the tag GENERATE_HTMLHELP is set to YES. + +CHM_FILE = + +# The HHC_LOCATION tag can be used to specify the location (absolute path +# including file name) of the HTML help compiler (hhc.exe). If non-empty, +# doxygen will try to run the HTML help compiler on the generated index.hhp. +# The file has to be specified with full path. +# This tag requires that the tag GENERATE_HTMLHELP is set to YES. + +HHC_LOCATION = + +# The GENERATE_CHI flag controls if a separate .chi index file is generated +# (YES) or that it should be included in the master .chm file (NO). +# The default value is: NO. +# This tag requires that the tag GENERATE_HTMLHELP is set to YES. + +GENERATE_CHI = NO + +# The CHM_INDEX_ENCODING is used to encode HtmlHelp index (hhk), content (hhc) +# and project file content. +# This tag requires that the tag GENERATE_HTMLHELP is set to YES. + +CHM_INDEX_ENCODING = + +# The BINARY_TOC flag controls whether a binary table of contents is generated +# (YES) or a normal table of contents (NO) in the .chm file. Furthermore it +# enables the Previous and Next buttons. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTMLHELP is set to YES. + +BINARY_TOC = NO + +# The TOC_EXPAND flag can be set to YES to add extra items for group members to +# the table of contents of the HTML help documentation and to the tree view. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTMLHELP is set to YES. + +TOC_EXPAND = NO + +# If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and +# QHP_VIRTUAL_FOLDER are set, an additional index file will be generated that +# can be used as input for Qt's qhelpgenerator to generate a Qt Compressed Help +# (.qch) of the generated HTML documentation. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +GENERATE_QHP = NO + +# If the QHG_LOCATION tag is specified, the QCH_FILE tag can be used to specify +# the file name of the resulting .qch file. The path specified is relative to +# the HTML output folder. +# This tag requires that the tag GENERATE_QHP is set to YES. + +QCH_FILE = + +# The QHP_NAMESPACE tag specifies the namespace to use when generating Qt Help +# Project output. For more information please see Qt Help Project / Namespace +# (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#namespace). +# The default value is: org.doxygen.Project. +# This tag requires that the tag GENERATE_QHP is set to YES. + +QHP_NAMESPACE = org.doxygen.Project + +# The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating Qt +# Help Project output. For more information please see Qt Help Project / Virtual +# Folders (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#virtual- +# folders). +# The default value is: doc. +# This tag requires that the tag GENERATE_QHP is set to YES. + +QHP_VIRTUAL_FOLDER = doc + +# If the QHP_CUST_FILTER_NAME tag is set, it specifies the name of a custom +# filter to add. For more information please see Qt Help Project / Custom +# Filters (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#custom- +# filters). +# This tag requires that the tag GENERATE_QHP is set to YES. + +QHP_CUST_FILTER_NAME = + +# The QHP_CUST_FILTER_ATTRS tag specifies the list of the attributes of the +# custom filter to add. For more information please see Qt Help Project / Custom +# Filters (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#custom- +# filters). +# This tag requires that the tag GENERATE_QHP is set to YES. + +QHP_CUST_FILTER_ATTRS = + +# The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this +# project's filter section matches. Qt Help Project / Filter Attributes (see: +# http://qt-project.org/doc/qt-4.8/qthelpproject.html#filter-attributes). +# This tag requires that the tag GENERATE_QHP is set to YES. + +QHP_SECT_FILTER_ATTRS = + +# The QHG_LOCATION tag can be used to specify the location of Qt's +# qhelpgenerator. If non-empty doxygen will try to run qhelpgenerator on the +# generated .qhp file. +# This tag requires that the tag GENERATE_QHP is set to YES. + +QHG_LOCATION = + +# If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files will be +# generated, together with the HTML files, they form an Eclipse help plugin. To +# install this plugin and make it available under the help contents menu in +# Eclipse, the contents of the directory containing the HTML and XML files needs +# to be copied into the plugins directory of eclipse. The name of the directory +# within the plugins directory should be the same as the ECLIPSE_DOC_ID value. +# After copying Eclipse needs to be restarted before the help appears. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +GENERATE_ECLIPSEHELP = NO + +# A unique identifier for the Eclipse help plugin. When installing the plugin +# the directory name containing the HTML and XML files should also have this +# name. Each documentation set should have its own identifier. +# The default value is: org.doxygen.Project. +# This tag requires that the tag GENERATE_ECLIPSEHELP is set to YES. + +ECLIPSE_DOC_ID = org.doxygen.Project + +# If you want full control over the layout of the generated HTML pages it might +# be necessary to disable the index and replace it with your own. The +# DISABLE_INDEX tag can be used to turn on/off the condensed index (tabs) at top +# of each HTML page. A value of NO enables the index and the value YES disables +# it. Since the tabs in the index contain the same information as the navigation +# tree, you can set this option to YES if you also set GENERATE_TREEVIEW to YES. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +DISABLE_INDEX = NO + +# The GENERATE_TREEVIEW tag is used to specify whether a tree-like index +# structure should be generated to display hierarchical information. If the tag +# value is set to YES, a side panel will be generated containing a tree-like +# index structure (just like the one that is generated for HTML Help). For this +# to work a browser that supports JavaScript, DHTML, CSS and frames is required +# (i.e. any modern browser). Windows users are probably better off using the +# HTML help feature. Via custom style sheets (see HTML_EXTRA_STYLESHEET) one can +# further fine-tune the look of the index. As an example, the default style +# sheet generated by doxygen has an example that shows how to put an image at +# the root of the tree instead of the PROJECT_NAME. Since the tree basically has +# the same information as the tab index, you could consider setting +# DISABLE_INDEX to YES when enabling this option. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +GENERATE_TREEVIEW = NO + +# The ENUM_VALUES_PER_LINE tag can be used to set the number of enum values that +# doxygen will group on one line in the generated HTML documentation. +# +# Note that a value of 0 will completely suppress the enum values from appearing +# in the overview section. +# Minimum value: 0, maximum value: 20, default value: 4. +# This tag requires that the tag GENERATE_HTML is set to YES. + +ENUM_VALUES_PER_LINE = 4 + +# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be used +# to set the initial width (in pixels) of the frame in which the tree is shown. +# Minimum value: 0, maximum value: 1500, default value: 250. +# This tag requires that the tag GENERATE_HTML is set to YES. + +TREEVIEW_WIDTH = 250 + +# If the EXT_LINKS_IN_WINDOW option is set to YES, doxygen will open links to +# external symbols imported via tag files in a separate window. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +EXT_LINKS_IN_WINDOW = NO + +# Use this tag to change the font size of LaTeX formulas included as images in +# the HTML documentation. When you change the font size after a successful +# doxygen run you need to manually remove any form_*.png images from the HTML +# output directory to force them to be regenerated. +# Minimum value: 8, maximum value: 50, default value: 10. +# This tag requires that the tag GENERATE_HTML is set to YES. + +FORMULA_FONTSIZE = 10 + +# Use the FORMULA_TRANPARENT tag to determine whether or not the images +# generated for formulas are transparent PNGs. Transparent PNGs are not +# supported properly for IE 6.0, but are supported on all modern browsers. +# +# Note that when changing this option you need to delete any form_*.png files in +# the HTML output directory before the changes have effect. +# The default value is: YES. +# This tag requires that the tag GENERATE_HTML is set to YES. + +FORMULA_TRANSPARENT = YES + +# Enable the USE_MATHJAX option to render LaTeX formulas using MathJax (see +# http://www.mathjax.org) which uses client side Javascript for the rendering +# instead of using pre-rendered bitmaps. Use this if you do not have LaTeX +# installed or if you want to formulas look prettier in the HTML output. When +# enabled you may also need to install MathJax separately and configure the path +# to it using the MATHJAX_RELPATH option. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +USE_MATHJAX = NO + +# When MathJax is enabled you can set the default output format to be used for +# the MathJax output. See the MathJax site (see: +# http://docs.mathjax.org/en/latest/output.html) for more details. +# Possible values are: HTML-CSS (which is slower, but has the best +# compatibility), NativeMML (i.e. MathML) and SVG. +# The default value is: HTML-CSS. +# This tag requires that the tag USE_MATHJAX is set to YES. + +MATHJAX_FORMAT = HTML-CSS + +# When MathJax is enabled you need to specify the location relative to the HTML +# output directory using the MATHJAX_RELPATH option. The destination directory +# should contain the MathJax.js script. For instance, if the mathjax directory +# is located at the same level as the HTML output directory, then +# MATHJAX_RELPATH should be ../mathjax. The default value points to the MathJax +# Content Delivery Network so you can quickly see the result without installing +# MathJax. However, it is strongly recommended to install a local copy of +# MathJax from http://www.mathjax.org before deployment. +# The default value is: http://cdn.mathjax.org/mathjax/latest. +# This tag requires that the tag USE_MATHJAX is set to YES. + +MATHJAX_RELPATH = http://cdn.mathjax.org/mathjax/latest + +# The MATHJAX_EXTENSIONS tag can be used to specify one or more MathJax +# extension names that should be enabled during MathJax rendering. For example +# MATHJAX_EXTENSIONS = TeX/AMSmath TeX/AMSsymbols +# This tag requires that the tag USE_MATHJAX is set to YES. + +MATHJAX_EXTENSIONS = + +# The MATHJAX_CODEFILE tag can be used to specify a file with javascript pieces +# of code that will be used on startup of the MathJax code. See the MathJax site +# (see: http://docs.mathjax.org/en/latest/output.html) for more details. For an +# example see the documentation. +# This tag requires that the tag USE_MATHJAX is set to YES. + +MATHJAX_CODEFILE = + +# When the SEARCHENGINE tag is enabled doxygen will generate a search box for +# the HTML output. The underlying search engine uses javascript and DHTML and +# should work on any modern browser. Note that when using HTML help +# (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets (GENERATE_DOCSET) +# there is already a search function so this one should typically be disabled. +# For large projects the javascript based search engine can be slow, then +# enabling SERVER_BASED_SEARCH may provide a better solution. It is possible to +# search using the keyboard; to jump to the search box use <access key> + S +# (what the <access key> is depends on the OS and browser, but it is typically +# <CTRL>, <ALT>/<option>, or both). Inside the search box use the <cursor down +# key> to jump into the search results window, the results can be navigated +# using the <cursor keys>. Press <Enter> to select an item or <escape> to cancel +# the search. The filter options can be selected when the cursor is inside the +# search box by pressing <Shift>+<cursor down>. Also here use the <cursor keys> +# to select a filter and <Enter> or <escape> to activate or cancel the filter +# option. +# The default value is: YES. +# This tag requires that the tag GENERATE_HTML is set to YES. + +SEARCHENGINE = NO + +# When the SERVER_BASED_SEARCH tag is enabled the search engine will be +# implemented using a web server instead of a web client using Javascript. There +# are two flavors of web server based searching depending on the EXTERNAL_SEARCH +# setting. When disabled, doxygen will generate a PHP script for searching and +# an index file used by the script. When EXTERNAL_SEARCH is enabled the indexing +# and searching needs to be provided by external tools. See the section +# "External Indexing and Searching" for details. +# The default value is: NO. +# This tag requires that the tag SEARCHENGINE is set to YES. + +SERVER_BASED_SEARCH = NO + +# When EXTERNAL_SEARCH tag is enabled doxygen will no longer generate the PHP +# script for searching. Instead the search results are written to an XML file +# which needs to be processed by an external indexer. Doxygen will invoke an +# external search engine pointed to by the SEARCHENGINE_URL option to obtain the +# search results. +# +# Doxygen ships with an example indexer (doxyindexer) and search engine +# (doxysearch.cgi) which are based on the open source search engine library +# Xapian (see: http://xapian.org/). +# +# See the section "External Indexing and Searching" for details. +# The default value is: NO. +# This tag requires that the tag SEARCHENGINE is set to YES. + +EXTERNAL_SEARCH = NO + +# The SEARCHENGINE_URL should point to a search engine hosted by a web server +# which will return the search results when EXTERNAL_SEARCH is enabled. +# +# Doxygen ships with an example indexer (doxyindexer) and search engine +# (doxysearch.cgi) which are based on the open source search engine library +# Xapian (see: http://xapian.org/). See the section "External Indexing and +# Searching" for details. +# This tag requires that the tag SEARCHENGINE is set to YES. + +SEARCHENGINE_URL = + +# When SERVER_BASED_SEARCH and EXTERNAL_SEARCH are both enabled the unindexed +# search data is written to a file for indexing by an external tool. With the +# SEARCHDATA_FILE tag the name of this file can be specified. +# The default file is: searchdata.xml. +# This tag requires that the tag SEARCHENGINE is set to YES. + +SEARCHDATA_FILE = searchdata.xml + +# When SERVER_BASED_SEARCH and EXTERNAL_SEARCH are both enabled the +# EXTERNAL_SEARCH_ID tag can be used as an identifier for the project. This is +# useful in combination with EXTRA_SEARCH_MAPPINGS to search through multiple +# projects and redirect the results back to the right project. +# This tag requires that the tag SEARCHENGINE is set to YES. + +EXTERNAL_SEARCH_ID = + +# The EXTRA_SEARCH_MAPPINGS tag can be used to enable searching through doxygen +# projects other than the one defined by this configuration file, but that are +# all added to the same external search index. Each project needs to have a +# unique id set via EXTERNAL_SEARCH_ID. The search mapping then maps the id of +# to a relative location where the documentation can be found. The format is: +# EXTRA_SEARCH_MAPPINGS = tagname1=loc1 tagname2=loc2 ... +# This tag requires that the tag SEARCHENGINE is set to YES. + +EXTRA_SEARCH_MAPPINGS = + +#--------------------------------------------------------------------------- +# Configuration options related to the LaTeX output +#--------------------------------------------------------------------------- + +# If the GENERATE_LATEX tag is set to YES, doxygen will generate LaTeX output. +# The default value is: YES. + +GENERATE_LATEX = NO + +# The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. If a +# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of +# it. +# The default directory is: latex. +# This tag requires that the tag GENERATE_LATEX is set to YES. + +LATEX_OUTPUT = latex + +# The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be +# invoked. +# +# Note that when enabling USE_PDFLATEX this option is only used for generating +# bitmaps for formulas in the HTML output, but not in the Makefile that is +# written to the output directory. +# The default file is: latex. +# This tag requires that the tag GENERATE_LATEX is set to YES. + +LATEX_CMD_NAME = latex + +# The MAKEINDEX_CMD_NAME tag can be used to specify the command name to generate +# index for LaTeX. +# The default file is: makeindex. +# This tag requires that the tag GENERATE_LATEX is set to YES. + +MAKEINDEX_CMD_NAME = makeindex + +# If the COMPACT_LATEX tag is set to YES, doxygen generates more compact LaTeX +# documents. This may be useful for small projects and may help to save some +# trees in general. +# The default value is: NO. +# This tag requires that the tag GENERATE_LATEX is set to YES. + +COMPACT_LATEX = NO + +# The PAPER_TYPE tag can be used to set the paper type that is used by the +# printer. +# Possible values are: a4 (210 x 297 mm), letter (8.5 x 11 inches), legal (8.5 x +# 14 inches) and executive (7.25 x 10.5 inches). +# The default value is: a4. +# This tag requires that the tag GENERATE_LATEX is set to YES. + +PAPER_TYPE = a4 + +# The EXTRA_PACKAGES tag can be used to specify one or more LaTeX package names +# that should be included in the LaTeX output. To get the times font for +# instance you can specify +# EXTRA_PACKAGES=times +# If left blank no extra packages will be included. +# This tag requires that the tag GENERATE_LATEX is set to YES. + +EXTRA_PACKAGES = + +# The LATEX_HEADER tag can be used to specify a personal LaTeX header for the +# generated LaTeX document. The header should contain everything until the first +# chapter. If it is left blank doxygen will generate a standard header. See +# section "Doxygen usage" for information on how to let doxygen write the +# default header to a separate file. +# +# Note: Only use a user-defined header if you know what you are doing! The +# following commands have a special meaning inside the header: $title, +# $datetime, $date, $doxygenversion, $projectname, $projectnumber, +# $projectbrief, $projectlogo. Doxygen will replace $title with the empty +# string, for the replacement values of the other commands the user is referred +# to HTML_HEADER. +# This tag requires that the tag GENERATE_LATEX is set to YES. + +LATEX_HEADER = + +# The LATEX_FOOTER tag can be used to specify a personal LaTeX footer for the +# generated LaTeX document. The footer should contain everything after the last +# chapter. If it is left blank doxygen will generate a standard footer. See +# LATEX_HEADER for more information on how to generate a default footer and what +# special commands can be used inside the footer. +# +# Note: Only use a user-defined footer if you know what you are doing! +# This tag requires that the tag GENERATE_LATEX is set to YES. + +LATEX_FOOTER = + +# The LATEX_EXTRA_STYLESHEET tag can be used to specify additional user-defined +# LaTeX style sheets that are included after the standard style sheets created +# by doxygen. Using this option one can overrule certain style aspects. Doxygen +# will copy the style sheet files to the output directory. +# Note: The order of the extra style sheet files is of importance (e.g. the last +# style sheet in the list overrules the setting of the previous ones in the +# list). +# This tag requires that the tag GENERATE_LATEX is set to YES. + +LATEX_EXTRA_STYLESHEET = + +# The LATEX_EXTRA_FILES tag can be used to specify one or more extra images or +# other source files which should be copied to the LATEX_OUTPUT output +# directory. Note that the files will be copied as-is; there are no commands or +# markers available. +# This tag requires that the tag GENERATE_LATEX is set to YES. + +LATEX_EXTRA_FILES = + +# If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated is +# prepared for conversion to PDF (using ps2pdf or pdflatex). The PDF file will +# contain links (just like the HTML output) instead of page references. This +# makes the output suitable for online browsing using a PDF viewer. +# The default value is: YES. +# This tag requires that the tag GENERATE_LATEX is set to YES. + +PDF_HYPERLINKS = YES + +# If the USE_PDFLATEX tag is set to YES, doxygen will use pdflatex to generate +# the PDF file directly from the LaTeX files. Set this option to YES, to get a +# higher quality PDF documentation. +# The default value is: YES. +# This tag requires that the tag GENERATE_LATEX is set to YES. + +USE_PDFLATEX = YES + +# If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \batchmode +# command to the generated LaTeX files. This will instruct LaTeX to keep running +# if errors occur, instead of asking the user for help. This option is also used +# when generating formulas in HTML. +# The default value is: NO. +# This tag requires that the tag GENERATE_LATEX is set to YES. + +LATEX_BATCHMODE = NO + +# If the LATEX_HIDE_INDICES tag is set to YES then doxygen will not include the +# index chapters (such as File Index, Compound Index, etc.) in the output. +# The default value is: NO. +# This tag requires that the tag GENERATE_LATEX is set to YES. + +LATEX_HIDE_INDICES = NO + +# If the LATEX_SOURCE_CODE tag is set to YES then doxygen will include source +# code with syntax highlighting in the LaTeX output. +# +# Note that which sources are shown also depends on other settings such as +# SOURCE_BROWSER. +# The default value is: NO. +# This tag requires that the tag GENERATE_LATEX is set to YES. + +LATEX_SOURCE_CODE = NO + +# The LATEX_BIB_STYLE tag can be used to specify the style to use for the +# bibliography, e.g. plainnat, or ieeetr. See +# http://en.wikipedia.org/wiki/BibTeX and \cite for more info. +# The default value is: plain. +# This tag requires that the tag GENERATE_LATEX is set to YES. + +LATEX_BIB_STYLE = plain + +#--------------------------------------------------------------------------- +# Configuration options related to the RTF output +#--------------------------------------------------------------------------- + +# If the GENERATE_RTF tag is set to YES, doxygen will generate RTF output. The +# RTF output is optimized for Word 97 and may not look too pretty with other RTF +# readers/editors. +# The default value is: NO. + +GENERATE_RTF = NO + +# The RTF_OUTPUT tag is used to specify where the RTF docs will be put. If a +# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of +# it. +# The default directory is: rtf. +# This tag requires that the tag GENERATE_RTF is set to YES. + +RTF_OUTPUT = rtf + +# If the COMPACT_RTF tag is set to YES, doxygen generates more compact RTF +# documents. This may be useful for small projects and may help to save some +# trees in general. +# The default value is: NO. +# This tag requires that the tag GENERATE_RTF is set to YES. + +COMPACT_RTF = NO + +# If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated will +# contain hyperlink fields. The RTF file will contain links (just like the HTML +# output) instead of page references. This makes the output suitable for online +# browsing using Word or some other Word compatible readers that support those +# fields. +# +# Note: WordPad (write) and others do not support links. +# The default value is: NO. +# This tag requires that the tag GENERATE_RTF is set to YES. + +RTF_HYPERLINKS = NO + +# Load stylesheet definitions from file. Syntax is similar to doxygen's config +# file, i.e. a series of assignments. You only have to provide replacements, +# missing definitions are set to their default value. +# +# See also section "Doxygen usage" for information on how to generate the +# default style sheet that doxygen normally uses. +# This tag requires that the tag GENERATE_RTF is set to YES. + +RTF_STYLESHEET_FILE = + +# Set optional variables used in the generation of an RTF document. Syntax is +# similar to doxygen's config file. A template extensions file can be generated +# using doxygen -e rtf extensionFile. +# This tag requires that the tag GENERATE_RTF is set to YES. + +RTF_EXTENSIONS_FILE = + +# If the RTF_SOURCE_CODE tag is set to YES then doxygen will include source code +# with syntax highlighting in the RTF output. +# +# Note that which sources are shown also depends on other settings such as +# SOURCE_BROWSER. +# The default value is: NO. +# This tag requires that the tag GENERATE_RTF is set to YES. + +RTF_SOURCE_CODE = NO + +#--------------------------------------------------------------------------- +# Configuration options related to the man page output +#--------------------------------------------------------------------------- + +# If the GENERATE_MAN tag is set to YES, doxygen will generate man pages for +# classes and files. +# The default value is: NO. + +GENERATE_MAN = NO + +# The MAN_OUTPUT tag is used to specify where the man pages will be put. If a +# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of +# it. A directory man3 will be created inside the directory specified by +# MAN_OUTPUT. +# The default directory is: man. +# This tag requires that the tag GENERATE_MAN is set to YES. + +MAN_OUTPUT = man + +# The MAN_EXTENSION tag determines the extension that is added to the generated +# man pages. In case the manual section does not start with a number, the number +# 3 is prepended. The dot (.) at the beginning of the MAN_EXTENSION tag is +# optional. +# The default value is: .3. +# This tag requires that the tag GENERATE_MAN is set to YES. + +MAN_EXTENSION = .3 + +# The MAN_SUBDIR tag determines the name of the directory created within +# MAN_OUTPUT in which the man pages are placed. If defaults to man followed by +# MAN_EXTENSION with the initial . removed. +# This tag requires that the tag GENERATE_MAN is set to YES. + +MAN_SUBDIR = + +# If the MAN_LINKS tag is set to YES and doxygen generates man output, then it +# will generate one additional man file for each entity documented in the real +# man page(s). These additional files only source the real man page, but without +# them the man command would be unable to find the correct page. +# The default value is: NO. +# This tag requires that the tag GENERATE_MAN is set to YES. + +MAN_LINKS = NO + +#--------------------------------------------------------------------------- +# Configuration options related to the XML output +#--------------------------------------------------------------------------- + +# If the GENERATE_XML tag is set to YES, doxygen will generate an XML file that +# captures the structure of the code including all documentation. +# The default value is: NO. + +GENERATE_XML = NO + +# The XML_OUTPUT tag is used to specify where the XML pages will be put. If a +# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of +# it. +# The default directory is: xml. +# This tag requires that the tag GENERATE_XML is set to YES. + +XML_OUTPUT = xml + +# If the XML_PROGRAMLISTING tag is set to YES, doxygen will dump the program +# listings (including syntax highlighting and cross-referencing information) to +# the XML output. Note that enabling this will significantly increase the size +# of the XML output. +# The default value is: YES. +# This tag requires that the tag GENERATE_XML is set to YES. + +XML_PROGRAMLISTING = YES + +#--------------------------------------------------------------------------- +# Configuration options related to the DOCBOOK output +#--------------------------------------------------------------------------- + +# If the GENERATE_DOCBOOK tag is set to YES, doxygen will generate Docbook files +# that can be used to generate PDF. +# The default value is: NO. + +GENERATE_DOCBOOK = NO + +# The DOCBOOK_OUTPUT tag is used to specify where the Docbook pages will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be put in +# front of it. +# The default directory is: docbook. +# This tag requires that the tag GENERATE_DOCBOOK is set to YES. + +DOCBOOK_OUTPUT = docbook + +# If the DOCBOOK_PROGRAMLISTING tag is set to YES, doxygen will include the +# program listings (including syntax highlighting and cross-referencing +# information) to the DOCBOOK output. Note that enabling this will significantly +# increase the size of the DOCBOOK output. +# The default value is: NO. +# This tag requires that the tag GENERATE_DOCBOOK is set to YES. + +DOCBOOK_PROGRAMLISTING = NO + +#--------------------------------------------------------------------------- +# Configuration options for the AutoGen Definitions output +#--------------------------------------------------------------------------- + +# If the GENERATE_AUTOGEN_DEF tag is set to YES, doxygen will generate an +# AutoGen Definitions (see http://autogen.sf.net) file that captures the +# structure of the code including all documentation. Note that this feature is +# still experimental and incomplete at the moment. +# The default value is: NO. + +GENERATE_AUTOGEN_DEF = NO + +#--------------------------------------------------------------------------- +# Configuration options related to the Perl module output +#--------------------------------------------------------------------------- + +# If the GENERATE_PERLMOD tag is set to YES, doxygen will generate a Perl module +# file that captures the structure of the code including all documentation. +# +# Note that this feature is still experimental and incomplete at the moment. +# The default value is: NO. + +GENERATE_PERLMOD = NO + +# If the PERLMOD_LATEX tag is set to YES, doxygen will generate the necessary +# Makefile rules, Perl scripts and LaTeX code to be able to generate PDF and DVI +# output from the Perl module output. +# The default value is: NO. +# This tag requires that the tag GENERATE_PERLMOD is set to YES. + +PERLMOD_LATEX = NO + +# If the PERLMOD_PRETTY tag is set to YES, the Perl module output will be nicely +# formatted so it can be parsed by a human reader. This is useful if you want to +# understand what is going on. On the other hand, if this tag is set to NO, the +# size of the Perl module output will be much smaller and Perl will parse it +# just the same. +# The default value is: YES. +# This tag requires that the tag GENERATE_PERLMOD is set to YES. + +PERLMOD_PRETTY = YES + +# The names of the make variables in the generated doxyrules.make file are +# prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX. This is useful +# so different doxyrules.make files included by the same Makefile don't +# overwrite each other's variables. +# This tag requires that the tag GENERATE_PERLMOD is set to YES. + +PERLMOD_MAKEVAR_PREFIX = + +#--------------------------------------------------------------------------- +# Configuration options related to the preprocessor +#--------------------------------------------------------------------------- + +# If the ENABLE_PREPROCESSING tag is set to YES, doxygen will evaluate all +# C-preprocessor directives found in the sources and include files. +# The default value is: YES. + +ENABLE_PREPROCESSING = YES + +# If the MACRO_EXPANSION tag is set to YES, doxygen will expand all macro names +# in the source code. If set to NO, only conditional compilation will be +# performed. Macro expansion can be done in a controlled way by setting +# EXPAND_ONLY_PREDEF to YES. +# The default value is: NO. +# This tag requires that the tag ENABLE_PREPROCESSING is set to YES. + +MACRO_EXPANSION = NO + +# If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES then +# the macro expansion is limited to the macros specified with the PREDEFINED and +# EXPAND_AS_DEFINED tags. +# The default value is: NO. +# This tag requires that the tag ENABLE_PREPROCESSING is set to YES. + +EXPAND_ONLY_PREDEF = NO + +# If the SEARCH_INCLUDES tag is set to YES, the include files in the +# INCLUDE_PATH will be searched if a #include is found. +# The default value is: YES. +# This tag requires that the tag ENABLE_PREPROCESSING is set to YES. + +SEARCH_INCLUDES = YES + +# The INCLUDE_PATH tag can be used to specify one or more directories that +# contain include files that are not input files but should be processed by the +# preprocessor. +# This tag requires that the tag SEARCH_INCLUDES is set to YES. + +INCLUDE_PATH = + +# You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard +# patterns (like *.h and *.hpp) to filter out the header-files in the +# directories. If left blank, the patterns specified with FILE_PATTERNS will be +# used. +# This tag requires that the tag ENABLE_PREPROCESSING is set to YES. + +INCLUDE_FILE_PATTERNS = + +# The PREDEFINED tag can be used to specify one or more macro names that are +# defined before the preprocessor is started (similar to the -D option of e.g. +# gcc). The argument of the tag is a list of macros of the form: name or +# name=definition (no spaces). If the definition and the "=" are omitted, "=1" +# is assumed. To prevent a macro definition from being undefined via #undef or +# recursively expanded use the := operator instead of the = operator. +# This tag requires that the tag ENABLE_PREPROCESSING is set to YES. + +PREDEFINED = + +# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then this +# tag can be used to specify a list of macro names that should be expanded. The +# macro definition that is found in the sources will be used. Use the PREDEFINED +# tag if you want to use a different macro definition that overrules the +# definition found in the source code. +# This tag requires that the tag ENABLE_PREPROCESSING is set to YES. + +EXPAND_AS_DEFINED = + +# If the SKIP_FUNCTION_MACROS tag is set to YES then doxygen's preprocessor will +# remove all references to function-like macros that are alone on a line, have +# an all uppercase name, and do not end with a semicolon. Such function macros +# are typically used for boiler-plate code, and will confuse the parser if not +# removed. +# The default value is: YES. +# This tag requires that the tag ENABLE_PREPROCESSING is set to YES. + +SKIP_FUNCTION_MACROS = YES + +#--------------------------------------------------------------------------- +# Configuration options related to external references +#--------------------------------------------------------------------------- + +# The TAGFILES tag can be used to specify one or more tag files. For each tag +# file the location of the external documentation should be added. The format of +# a tag file without this location is as follows: +# TAGFILES = file1 file2 ... +# Adding location for the tag files is done as follows: +# TAGFILES = file1=loc1 "file2 = loc2" ... +# where loc1 and loc2 can be relative or absolute paths or URLs. See the +# section "Linking to external documentation" for more information about the use +# of tag files. +# Note: Each tag file must have a unique name (where the name does NOT include +# the path). If a tag file is not located in the directory in which doxygen is +# run, you must also specify the path to the tagfile here. + +TAGFILES = + +# When a file name is specified after GENERATE_TAGFILE, doxygen will create a +# tag file that is based on the input files it reads. See section "Linking to +# external documentation" for more information about the usage of tag files. + +GENERATE_TAGFILE = + +# If the ALLEXTERNALS tag is set to YES, all external class will be listed in +# the class index. If set to NO, only the inherited external classes will be +# listed. +# The default value is: NO. + +ALLEXTERNALS = NO + +# If the EXTERNAL_GROUPS tag is set to YES, all external groups will be listed +# in the modules index. If set to NO, only the current project's groups will be +# listed. +# The default value is: YES. + +EXTERNAL_GROUPS = YES + +# If the EXTERNAL_PAGES tag is set to YES, all external pages will be listed in +# the related pages index. If set to NO, only the current project's pages will +# be listed. +# The default value is: YES. + +EXTERNAL_PAGES = YES + +# The PERL_PATH should be the absolute path and name of the perl script +# interpreter (i.e. the result of 'which perl'). +# The default file (with absolute path) is: /usr/bin/perl. + +PERL_PATH = /usr/bin/perl + +#--------------------------------------------------------------------------- +# Configuration options related to the dot tool +#--------------------------------------------------------------------------- + +# If the CLASS_DIAGRAMS tag is set to YES, doxygen will generate a class diagram +# (in HTML and LaTeX) for classes with base or super classes. Setting the tag to +# NO turns the diagrams off. Note that this option also works with HAVE_DOT +# disabled, but it is recommended to install and use dot, since it yields more +# powerful graphs. +# The default value is: YES. + +CLASS_DIAGRAMS = YES + +# You can define message sequence charts within doxygen comments using the \msc +# command. Doxygen will then run the mscgen tool (see: +# http://www.mcternan.me.uk/mscgen/)) to produce the chart and insert it in the +# documentation. The MSCGEN_PATH tag allows you to specify the directory where +# the mscgen tool resides. If left empty the tool is assumed to be found in the +# default search path. + +MSCGEN_PATH = + +# You can include diagrams made with dia in doxygen documentation. Doxygen will +# then run dia to produce the diagram and insert it in the documentation. The +# DIA_PATH tag allows you to specify the directory where the dia binary resides. +# If left empty dia is assumed to be found in the default search path. + +DIA_PATH = + +# If set to YES the inheritance and collaboration graphs will hide inheritance +# and usage relations if the target is undocumented or is not a class. +# The default value is: YES. + +HIDE_UNDOC_RELATIONS = YES + +# If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is +# available from the path. This tool is part of Graphviz (see: +# http://www.graphviz.org/), a graph visualization toolkit from AT&T and Lucent +# Bell Labs. The other options in this section have no effect if this option is +# set to NO +# The default value is: NO. + +HAVE_DOT = YES + +# The DOT_NUM_THREADS specifies the number of dot invocations doxygen is allowed +# to run in parallel. When set to 0 doxygen will base this on the number of +# processors available in the system. You can set it explicitly to a value +# larger than 0 to get control over the balance between CPU load and processing +# speed. +# Minimum value: 0, maximum value: 32, default value: 0. +# This tag requires that the tag HAVE_DOT is set to YES. + +DOT_NUM_THREADS = 0 + +# When you want a differently looking font in the dot files that doxygen +# generates you can specify the font name using DOT_FONTNAME. You need to make +# sure dot is able to find the font, which can be done by putting it in a +# standard location or by setting the DOTFONTPATH environment variable or by +# setting DOT_FONTPATH to the directory containing the font. +# The default value is: Helvetica. +# This tag requires that the tag HAVE_DOT is set to YES. + +DOT_FONTNAME = Helvetica + +# The DOT_FONTSIZE tag can be used to set the size (in points) of the font of +# dot graphs. +# Minimum value: 4, maximum value: 24, default value: 10. +# This tag requires that the tag HAVE_DOT is set to YES. + +DOT_FONTSIZE = 10 + +# By default doxygen will tell dot to use the default font as specified with +# DOT_FONTNAME. If you specify a different font using DOT_FONTNAME you can set +# the path where dot can find it using this tag. +# This tag requires that the tag HAVE_DOT is set to YES. + +DOT_FONTPATH = + +# If the CLASS_GRAPH tag is set to YES then doxygen will generate a graph for +# each documented class showing the direct and indirect inheritance relations. +# Setting this tag to YES will force the CLASS_DIAGRAMS tag to NO. +# The default value is: YES. +# This tag requires that the tag HAVE_DOT is set to YES. + +CLASS_GRAPH = YES + +# If the COLLABORATION_GRAPH tag is set to YES then doxygen will generate a +# graph for each documented class showing the direct and indirect implementation +# dependencies (inheritance, containment, and class references variables) of the +# class with other documented classes. +# The default value is: YES. +# This tag requires that the tag HAVE_DOT is set to YES. + +COLLABORATION_GRAPH = YES + +# If the GROUP_GRAPHS tag is set to YES then doxygen will generate a graph for +# groups, showing the direct groups dependencies. +# The default value is: YES. +# This tag requires that the tag HAVE_DOT is set to YES. + +GROUP_GRAPHS = YES + +# If the UML_LOOK tag is set to YES, doxygen will generate inheritance and +# collaboration diagrams in a style similar to the OMG's Unified Modeling +# Language. +# The default value is: NO. +# This tag requires that the tag HAVE_DOT is set to YES. + +UML_LOOK = NO + +# If the UML_LOOK tag is enabled, the fields and methods are shown inside the +# class node. If there are many fields or methods and many nodes the graph may +# become too big to be useful. The UML_LIMIT_NUM_FIELDS threshold limits the +# number of items for each type to make the size more manageable. Set this to 0 +# for no limit. Note that the threshold may be exceeded by 50% before the limit +# is enforced. So when you set the threshold to 10, up to 15 fields may appear, +# but if the number exceeds 15, the total amount of fields shown is limited to +# 10. +# Minimum value: 0, maximum value: 100, default value: 10. +# This tag requires that the tag HAVE_DOT is set to YES. + +UML_LIMIT_NUM_FIELDS = 10 + +# If the TEMPLATE_RELATIONS tag is set to YES then the inheritance and +# collaboration graphs will show the relations between templates and their +# instances. +# The default value is: NO. +# This tag requires that the tag HAVE_DOT is set to YES. + +TEMPLATE_RELATIONS = NO + +# If the INCLUDE_GRAPH, ENABLE_PREPROCESSING and SEARCH_INCLUDES tags are set to +# YES then doxygen will generate a graph for each documented file showing the +# direct and indirect include dependencies of the file with other documented +# files. +# The default value is: YES. +# This tag requires that the tag HAVE_DOT is set to YES. + +INCLUDE_GRAPH = YES + +# If the INCLUDED_BY_GRAPH, ENABLE_PREPROCESSING and SEARCH_INCLUDES tags are +# set to YES then doxygen will generate a graph for each documented file showing +# the direct and indirect include dependencies of the file with other documented +# files. +# The default value is: YES. +# This tag requires that the tag HAVE_DOT is set to YES. + +INCLUDED_BY_GRAPH = YES + +# If the CALL_GRAPH tag is set to YES then doxygen will generate a call +# dependency graph for every global function or class method. +# +# Note that enabling this option will significantly increase the time of a run. +# So in most cases it will be better to enable call graphs for selected +# functions only using the \callgraph command. +# The default value is: NO. +# This tag requires that the tag HAVE_DOT is set to YES. + +CALL_GRAPH = NO + +# If the CALLER_GRAPH tag is set to YES then doxygen will generate a caller +# dependency graph for every global function or class method. +# +# Note that enabling this option will significantly increase the time of a run. +# So in most cases it will be better to enable caller graphs for selected +# functions only using the \callergraph command. +# The default value is: NO. +# This tag requires that the tag HAVE_DOT is set to YES. + +CALLER_GRAPH = NO + +# If the GRAPHICAL_HIERARCHY tag is set to YES then doxygen will graphical +# hierarchy of all classes instead of a textual one. +# The default value is: YES. +# This tag requires that the tag HAVE_DOT is set to YES. + +GRAPHICAL_HIERARCHY = YES + +# If the DIRECTORY_GRAPH tag is set to YES then doxygen will show the +# dependencies a directory has on other directories in a graphical way. The +# dependency relations are determined by the #include relations between the +# files in the directories. +# The default value is: YES. +# This tag requires that the tag HAVE_DOT is set to YES. + +DIRECTORY_GRAPH = YES + +# The DOT_IMAGE_FORMAT tag can be used to set the image format of the images +# generated by dot. +# Note: If you choose svg you need to set HTML_FILE_EXTENSION to xhtml in order +# to make the SVG files visible in IE 9+ (other browsers do not have this +# requirement). +# Possible values are: png, jpg, gif and svg. +# The default value is: png. +# This tag requires that the tag HAVE_DOT is set to YES. + +DOT_IMAGE_FORMAT = svg + +# If DOT_IMAGE_FORMAT is set to svg, then this option can be set to YES to +# enable generation of interactive SVG images that allow zooming and panning. +# +# Note that this requires a modern browser other than Internet Explorer. Tested +# and working are Firefox, Chrome, Safari, and Opera. +# Note: For IE 9+ you need to set HTML_FILE_EXTENSION to xhtml in order to make +# the SVG files visible. Older versions of IE do not have SVG support. +# The default value is: NO. +# This tag requires that the tag HAVE_DOT is set to YES. + +INTERACTIVE_SVG = NO + +# The DOT_PATH tag can be used to specify the path where the dot tool can be +# found. If left blank, it is assumed the dot tool can be found in the path. +# This tag requires that the tag HAVE_DOT is set to YES. + +DOT_PATH = + +# The DOTFILE_DIRS tag can be used to specify one or more directories that +# contain dot files that are included in the documentation (see the \dotfile +# command). +# This tag requires that the tag HAVE_DOT is set to YES. + +DOTFILE_DIRS = + +# The MSCFILE_DIRS tag can be used to specify one or more directories that +# contain msc files that are included in the documentation (see the \mscfile +# command). + +MSCFILE_DIRS = + +# The DIAFILE_DIRS tag can be used to specify one or more directories that +# contain dia files that are included in the documentation (see the \diafile +# command). + +DIAFILE_DIRS = + +# When using plantuml, the PLANTUML_JAR_PATH tag should be used to specify the +# path where java can find the plantuml.jar file. If left blank, it is assumed +# PlantUML is not used or called during a preprocessing step. Doxygen will +# generate a warning when it encounters a \startuml command in this case and +# will not generate output for the diagram. + +PLANTUML_JAR_PATH = + +# When using plantuml, the specified paths are searched for files specified by +# the !include statement in a plantuml block. + +PLANTUML_INCLUDE_PATH = + +# The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of nodes +# that will be shown in the graph. If the number of nodes in a graph becomes +# larger than this value, doxygen will truncate the graph, which is visualized +# by representing a node as a red box. Note that doxygen if the number of direct +# children of the root node in a graph is already larger than +# DOT_GRAPH_MAX_NODES then the graph will not be shown at all. Also note that +# the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH. +# Minimum value: 0, maximum value: 10000, default value: 50. +# This tag requires that the tag HAVE_DOT is set to YES. + +DOT_GRAPH_MAX_NODES = 50 + +# The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the graphs +# generated by dot. A depth value of 3 means that only nodes reachable from the +# root by following a path via at most 3 edges will be shown. Nodes that lay +# further from the root node will be omitted. Note that setting this option to 1 +# or 2 may greatly reduce the computation time needed for large code bases. Also +# note that the size of a graph can be further restricted by +# DOT_GRAPH_MAX_NODES. Using a depth of 0 means no depth restriction. +# Minimum value: 0, maximum value: 1000, default value: 0. +# This tag requires that the tag HAVE_DOT is set to YES. + +MAX_DOT_GRAPH_DEPTH = 0 + +# Set the DOT_TRANSPARENT tag to YES to generate images with a transparent +# background. This is disabled by default, because dot on Windows does not seem +# to support this out of the box. +# +# Warning: Depending on the platform used, enabling this option may lead to +# badly anti-aliased labels on the edges of a graph (i.e. they become hard to +# read). +# The default value is: NO. +# This tag requires that the tag HAVE_DOT is set to YES. + +DOT_TRANSPARENT = NO + +# Set the DOT_MULTI_TARGETS tag to YES to allow dot to generate multiple output +# files in one run (i.e. multiple -o and -T options on the command line). This +# makes dot run faster, but since only newer versions of dot (>1.8.10) support +# this, this feature is disabled by default. +# The default value is: NO. +# This tag requires that the tag HAVE_DOT is set to YES. + +DOT_MULTI_TARGETS = NO + +# If the GENERATE_LEGEND tag is set to YES doxygen will generate a legend page +# explaining the meaning of the various boxes and arrows in the dot generated +# graphs. +# The default value is: YES. +# This tag requires that the tag HAVE_DOT is set to YES. + +GENERATE_LEGEND = YES + +# If the DOT_CLEANUP tag is set to YES, doxygen will remove the intermediate dot +# files that are used to generate the various graphs. +# The default value is: YES. +# This tag requires that the tag HAVE_DOT is set to YES. + +DOT_CLEANUP = YES diff --git a/resources/3rdparty/cpphoafparser-0.99.2/Doxyfile.all b/resources/3rdparty/cpphoafparser-0.99.2/Doxyfile.all new file mode 100644 index 000000000..6ec5b1414 --- /dev/null +++ b/resources/3rdparty/cpphoafparser-0.99.2/Doxyfile.all @@ -0,0 +1,2362 @@ +# Doxyfile 1.8.9.1 + +# This file describes the settings to be used by the documentation system +# doxygen (www.doxygen.org) for a project. +# +# All text after a double hash (##) is considered a comment and is placed in +# front of the TAG it is preceding. +# +# All text after a single hash (#) is considered a comment and will be ignored. +# The format is: +# TAG = value [value, ...] +# For lists, items can also be appended using: +# TAG += value [value, ...] +# Values that contain spaces should be placed between quotes (\" \"). + +#--------------------------------------------------------------------------- +# Project related configuration options +#--------------------------------------------------------------------------- + +# This tag specifies the encoding used for all characters in the config file +# that follow. The default is UTF-8 which is also the encoding used for all text +# before the first occurrence of this tag. Doxygen uses libiconv (or the iconv +# built into libc) for the transcoding. See http://www.gnu.org/software/libiconv +# for the list of possible encodings. +# The default value is: UTF-8. + +DOXYFILE_ENCODING = UTF-8 + +# The PROJECT_NAME tag is a single word (or a sequence of words surrounded by +# double-quotes, unless you are using Doxywizard) that should identify the +# project for which the documentation is generated. This name is used in the +# title of most generated pages and in a few other places. +# The default value is: My Project. + +PROJECT_NAME = "cpphoafparser library API" + +# The PROJECT_NUMBER tag can be used to enter a project or revision number. This +# could be handy for archiving the generated documentation or if some version +# control system is used. + +PROJECT_NUMBER = + +# Using the PROJECT_BRIEF tag one can provide an optional one line description +# for a project that appears at the top of each page and should give viewer a +# quick idea about the purpose of the project. Keep the description short. + +PROJECT_BRIEF = + +# With the PROJECT_LOGO tag one can specify a logo or an icon that is included +# in the documentation. The maximum height of the logo should not exceed 55 +# pixels and the maximum width should not exceed 200 pixels. Doxygen will copy +# the logo to the output directory. + +PROJECT_LOGO = + +# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) path +# into which the generated documentation will be written. If a relative path is +# entered, it will be relative to the location where doxygen was started. If +# left blank the current directory will be used. + +OUTPUT_DIRECTORY = docs + +# If the CREATE_SUBDIRS tag is set to YES then doxygen will create 4096 sub- +# directories (in 2 levels) under the output directory of each output format and +# will distribute the generated files over these directories. Enabling this +# option can be useful when feeding doxygen a huge amount of source files, where +# putting all generated files in the same directory would otherwise causes +# performance problems for the file system. +# The default value is: NO. + +CREATE_SUBDIRS = NO + +# If the ALLOW_UNICODE_NAMES tag is set to YES, doxygen will allow non-ASCII +# characters to appear in the names of generated files. If set to NO, non-ASCII +# characters will be escaped, for example _xE3_x81_x84 will be used for Unicode +# U+3044. +# The default value is: NO. + +ALLOW_UNICODE_NAMES = NO + +# The OUTPUT_LANGUAGE tag is used to specify the language in which all +# documentation generated by doxygen is written. Doxygen will use this +# information to generate all constant output in the proper language. +# Possible values are: Afrikaans, Arabic, Armenian, Brazilian, Catalan, Chinese, +# Chinese-Traditional, Croatian, Czech, Danish, Dutch, English (United States), +# Esperanto, Farsi (Persian), Finnish, French, German, Greek, Hungarian, +# Indonesian, Italian, Japanese, Japanese-en (Japanese with English messages), +# Korean, Korean-en (Korean with English messages), Latvian, Lithuanian, +# Macedonian, Norwegian, Persian (Farsi), Polish, Portuguese, Romanian, Russian, +# Serbian, Serbian-Cyrillic, Slovak, Slovene, Spanish, Swedish, Turkish, +# Ukrainian and Vietnamese. +# The default value is: English. + +OUTPUT_LANGUAGE = English + +# If the BRIEF_MEMBER_DESC tag is set to YES, doxygen will include brief member +# descriptions after the members that are listed in the file and class +# documentation (similar to Javadoc). Set to NO to disable this. +# The default value is: YES. + +BRIEF_MEMBER_DESC = YES + +# If the REPEAT_BRIEF tag is set to YES, doxygen will prepend the brief +# description of a member or function before the detailed description +# +# Note: If both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the +# brief descriptions will be completely suppressed. +# The default value is: YES. + +REPEAT_BRIEF = YES + +# This tag implements a quasi-intelligent brief description abbreviator that is +# used to form the text in various listings. Each string in this list, if found +# as the leading text of the brief description, will be stripped from the text +# and the result, after processing the whole list, is used as the annotated +# text. Otherwise, the brief description is used as-is. If left blank, the +# following values are used ($name is automatically replaced with the name of +# the entity):The $name class, The $name widget, The $name file, is, provides, +# specifies, contains, represents, a, an and the. + +ABBREVIATE_BRIEF = + +# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then +# doxygen will generate a detailed section even if there is only a brief +# description. +# The default value is: NO. + +ALWAYS_DETAILED_SEC = NO + +# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all +# inherited members of a class in the documentation of that class as if those +# members were ordinary class members. Constructors, destructors and assignment +# operators of the base classes will not be shown. +# The default value is: NO. + +INLINE_INHERITED_MEMB = NO + +# If the FULL_PATH_NAMES tag is set to YES, doxygen will prepend the full path +# before files name in the file list and in the header files. If set to NO the +# shortest path that makes the file name unique will be used +# The default value is: YES. + +FULL_PATH_NAMES = YES + +# The STRIP_FROM_PATH tag can be used to strip a user-defined part of the path. +# Stripping is only done if one of the specified strings matches the left-hand +# part of the path. The tag can be used to show relative paths in the file list. +# If left blank the directory from which doxygen is run is used as the path to +# strip. +# +# Note that you can specify absolute paths here, but also relative paths, which +# will be relative from the directory where doxygen is started. +# This tag requires that the tag FULL_PATH_NAMES is set to YES. + +STRIP_FROM_PATH = + +# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of the +# path mentioned in the documentation of a class, which tells the reader which +# header file to include in order to use a class. If left blank only the name of +# the header file containing the class definition is used. Otherwise one should +# specify the list of include paths that are normally passed to the compiler +# using the -I flag. + +STRIP_FROM_INC_PATH = + +# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter (but +# less readable) file names. This can be useful is your file systems doesn't +# support long names like on DOS, Mac, or CD-ROM. +# The default value is: NO. + +SHORT_NAMES = NO + +# If the JAVADOC_AUTOBRIEF tag is set to YES then doxygen will interpret the +# first line (until the first dot) of a Javadoc-style comment as the brief +# description. If set to NO, the Javadoc-style will behave just like regular Qt- +# style comments (thus requiring an explicit @brief command for a brief +# description.) +# The default value is: NO. + +JAVADOC_AUTOBRIEF = YES + +# If the QT_AUTOBRIEF tag is set to YES then doxygen will interpret the first +# line (until the first dot) of a Qt-style comment as the brief description. If +# set to NO, the Qt-style will behave just like regular Qt-style comments (thus +# requiring an explicit \brief command for a brief description.) +# The default value is: NO. + +QT_AUTOBRIEF = NO + +# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make doxygen treat a +# multi-line C++ special comment block (i.e. a block of //! or /// comments) as +# a brief description. This used to be the default behavior. The new default is +# to treat a multi-line C++ comment block as a detailed description. Set this +# tag to YES if you prefer the old behavior instead. +# +# Note that setting this tag to YES also means that rational rose comments are +# not recognized any more. +# The default value is: NO. + +MULTILINE_CPP_IS_BRIEF = NO + +# If the INHERIT_DOCS tag is set to YES then an undocumented member inherits the +# documentation from any documented member that it re-implements. +# The default value is: YES. + +INHERIT_DOCS = YES + +# If the SEPARATE_MEMBER_PAGES tag is set to YES then doxygen will produce a new +# page for each member. If set to NO, the documentation of a member will be part +# of the file/class/namespace that contains it. +# The default value is: NO. + +SEPARATE_MEMBER_PAGES = NO + +# The TAB_SIZE tag can be used to set the number of spaces in a tab. Doxygen +# uses this value to replace tabs by spaces in code fragments. +# Minimum value: 1, maximum value: 16, default value: 4. + +TAB_SIZE = 4 + +# This tag can be used to specify a number of aliases that act as commands in +# the documentation. An alias has the form: +# name=value +# For example adding +# "sideeffect=@par Side Effects:\n" +# will allow you to put the command \sideeffect (or @sideeffect) in the +# documentation, which will result in a user-defined paragraph with heading +# "Side Effects:". You can put \n's in the value part of an alias to insert +# newlines. + +ALIASES = + +# This tag can be used to specify a number of word-keyword mappings (TCL only). +# A mapping has the form "name=value". For example adding "class=itcl::class" +# will allow you to use the command class in the itcl::class meaning. + +TCL_SUBST = + +# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C sources +# only. Doxygen will then generate output that is more tailored for C. For +# instance, some of the names that are used will be different. The list of all +# members will be omitted, etc. +# The default value is: NO. + +OPTIMIZE_OUTPUT_FOR_C = NO + +# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java or +# Python sources only. Doxygen will then generate output that is more tailored +# for that language. For instance, namespaces will be presented as packages, +# qualified scopes will look different, etc. +# The default value is: NO. + +OPTIMIZE_OUTPUT_JAVA = NO + +# Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran +# sources. Doxygen will then generate output that is tailored for Fortran. +# The default value is: NO. + +OPTIMIZE_FOR_FORTRAN = NO + +# Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL +# sources. Doxygen will then generate output that is tailored for VHDL. +# The default value is: NO. + +OPTIMIZE_OUTPUT_VHDL = NO + +# Doxygen selects the parser to use depending on the extension of the files it +# parses. With this tag you can assign which parser to use for a given +# extension. Doxygen has a built-in mapping, but you can override or extend it +# using this tag. The format is ext=language, where ext is a file extension, and +# language is one of the parsers supported by doxygen: IDL, Java, Javascript, +# C#, C, C++, D, PHP, Objective-C, Python, Fortran (fixed format Fortran: +# FortranFixed, free formatted Fortran: FortranFree, unknown formatted Fortran: +# Fortran. In the later case the parser tries to guess whether the code is fixed +# or free formatted code, this is the default for Fortran type files), VHDL. For +# instance to make doxygen treat .inc files as Fortran files (default is PHP), +# and .f files as C (default is Fortran), use: inc=Fortran f=C. +# +# Note: For files without extension you can use no_extension as a placeholder. +# +# Note that for custom extensions you also need to set FILE_PATTERNS otherwise +# the files are not read by doxygen. + +EXTENSION_MAPPING = + +# If the MARKDOWN_SUPPORT tag is enabled then doxygen pre-processes all comments +# according to the Markdown format, which allows for more readable +# documentation. See http://daringfireball.net/projects/markdown/ for details. +# The output of markdown processing is further processed by doxygen, so you can +# mix doxygen, HTML, and XML commands with Markdown formatting. Disable only in +# case of backward compatibilities issues. +# The default value is: YES. + +MARKDOWN_SUPPORT = YES + +# When enabled doxygen tries to link words that correspond to documented +# classes, or namespaces to their corresponding documentation. Such a link can +# be prevented in individual cases by putting a % sign in front of the word or +# globally by setting AUTOLINK_SUPPORT to NO. +# The default value is: YES. + +AUTOLINK_SUPPORT = YES + +# If you use STL classes (i.e. std::string, std::vector, etc.) but do not want +# to include (a tag file for) the STL sources as input, then you should set this +# tag to YES in order to let doxygen match functions declarations and +# definitions whose arguments contain STL classes (e.g. func(std::string); +# versus func(std::string) {}). This also make the inheritance and collaboration +# diagrams that involve STL classes more complete and accurate. +# The default value is: NO. + +BUILTIN_STL_SUPPORT = YES + +# If you use Microsoft's C++/CLI language, you should set this option to YES to +# enable parsing support. +# The default value is: NO. + +CPP_CLI_SUPPORT = NO + +# Set the SIP_SUPPORT tag to YES if your project consists of sip (see: +# http://www.riverbankcomputing.co.uk/software/sip/intro) sources only. Doxygen +# will parse them like normal C++ but will assume all classes use public instead +# of private inheritance when no explicit protection keyword is present. +# The default value is: NO. + +SIP_SUPPORT = NO + +# For Microsoft's IDL there are propget and propput attributes to indicate +# getter and setter methods for a property. Setting this option to YES will make +# doxygen to replace the get and set methods by a property in the documentation. +# This will only work if the methods are indeed getting or setting a simple +# type. If this is not the case, or you want to show the methods anyway, you +# should set this option to NO. +# The default value is: YES. + +IDL_PROPERTY_SUPPORT = YES + +# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC +# tag is set to YES then doxygen will reuse the documentation of the first +# member in the group (if any) for the other members of the group. By default +# all members of a group must be documented explicitly. +# The default value is: NO. + +DISTRIBUTE_GROUP_DOC = NO + +# Set the SUBGROUPING tag to YES to allow class member groups of the same type +# (for instance a group of public functions) to be put as a subgroup of that +# type (e.g. under the Public Functions section). Set it to NO to prevent +# subgrouping. Alternatively, this can be done per class using the +# \nosubgrouping command. +# The default value is: YES. + +SUBGROUPING = YES + +# When the INLINE_GROUPED_CLASSES tag is set to YES, classes, structs and unions +# are shown inside the group in which they are included (e.g. using \ingroup) +# instead of on a separate page (for HTML and Man pages) or section (for LaTeX +# and RTF). +# +# Note that this feature does not work in combination with +# SEPARATE_MEMBER_PAGES. +# The default value is: NO. + +INLINE_GROUPED_CLASSES = NO + +# When the INLINE_SIMPLE_STRUCTS tag is set to YES, structs, classes, and unions +# with only public data fields or simple typedef fields will be shown inline in +# the documentation of the scope in which they are defined (i.e. file, +# namespace, or group documentation), provided this scope is documented. If set +# to NO, structs, classes, and unions are shown on a separate page (for HTML and +# Man pages) or section (for LaTeX and RTF). +# The default value is: NO. + +INLINE_SIMPLE_STRUCTS = NO + +# When TYPEDEF_HIDES_STRUCT tag is enabled, a typedef of a struct, union, or +# enum is documented as struct, union, or enum with the name of the typedef. So +# typedef struct TypeS {} TypeT, will appear in the documentation as a struct +# with name TypeT. When disabled the typedef will appear as a member of a file, +# namespace, or class. And the struct will be named TypeS. This can typically be +# useful for C code in case the coding convention dictates that all compound +# types are typedef'ed and only the typedef is referenced, never the tag name. +# The default value is: NO. + +TYPEDEF_HIDES_STRUCT = NO + +# The size of the symbol lookup cache can be set using LOOKUP_CACHE_SIZE. This +# cache is used to resolve symbols given their name and scope. Since this can be +# an expensive process and often the same symbol appears multiple times in the +# code, doxygen keeps a cache of pre-resolved symbols. If the cache is too small +# doxygen will become slower. If the cache is too large, memory is wasted. The +# cache size is given by this formula: 2^(16+LOOKUP_CACHE_SIZE). The valid range +# is 0..9, the default is 0, corresponding to a cache size of 2^16=65536 +# symbols. At the end of a run doxygen will report the cache usage and suggest +# the optimal cache size from a speed point of view. +# Minimum value: 0, maximum value: 9, default value: 0. + +LOOKUP_CACHE_SIZE = 0 + +#--------------------------------------------------------------------------- +# Build related configuration options +#--------------------------------------------------------------------------- + +# If the EXTRACT_ALL tag is set to YES, doxygen will assume all entities in +# documentation are documented, even if no documentation was available. Private +# class members and static file members will be hidden unless the +# EXTRACT_PRIVATE respectively EXTRACT_STATIC tags are set to YES. +# Note: This will also disable the warnings about undocumented members that are +# normally produced when WARNINGS is set to YES. +# The default value is: NO. + +EXTRACT_ALL = NO + +# If the EXTRACT_PRIVATE tag is set to YES, all private members of a class will +# be included in the documentation. +# The default value is: NO. + +EXTRACT_PRIVATE = YES + +# If the EXTRACT_PACKAGE tag is set to YES, all members with package or internal +# scope will be included in the documentation. +# The default value is: NO. + +EXTRACT_PACKAGE = NO + +# If the EXTRACT_STATIC tag is set to YES, all static members of a file will be +# included in the documentation. +# The default value is: NO. + +EXTRACT_STATIC = NO + +# If the EXTRACT_LOCAL_CLASSES tag is set to YES, classes (and structs) defined +# locally in source files will be included in the documentation. If set to NO, +# only classes defined in header files are included. Does not have any effect +# for Java sources. +# The default value is: YES. + +EXTRACT_LOCAL_CLASSES = YES + +# This flag is only useful for Objective-C code. If set to YES, local methods, +# which are defined in the implementation section but not in the interface are +# included in the documentation. If set to NO, only methods in the interface are +# included. +# The default value is: NO. + +EXTRACT_LOCAL_METHODS = NO + +# If this flag is set to YES, the members of anonymous namespaces will be +# extracted and appear in the documentation as a namespace called +# 'anonymous_namespace{file}', where file will be replaced with the base name of +# the file that contains the anonymous namespace. By default anonymous namespace +# are hidden. +# The default value is: NO. + +EXTRACT_ANON_NSPACES = NO + +# If the HIDE_UNDOC_MEMBERS tag is set to YES, doxygen will hide all +# undocumented members inside documented classes or files. If set to NO these +# members will be included in the various overviews, but no documentation +# section is generated. This option has no effect if EXTRACT_ALL is enabled. +# The default value is: NO. + +HIDE_UNDOC_MEMBERS = NO + +# If the HIDE_UNDOC_CLASSES tag is set to YES, doxygen will hide all +# undocumented classes that are normally visible in the class hierarchy. If set +# to NO, these classes will be included in the various overviews. This option +# has no effect if EXTRACT_ALL is enabled. +# The default value is: NO. + +HIDE_UNDOC_CLASSES = NO + +# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, doxygen will hide all friend +# (class|struct|union) declarations. If set to NO, these declarations will be +# included in the documentation. +# The default value is: NO. + +HIDE_FRIEND_COMPOUNDS = NO + +# If the HIDE_IN_BODY_DOCS tag is set to YES, doxygen will hide any +# documentation blocks found inside the body of a function. If set to NO, these +# blocks will be appended to the function's detailed documentation block. +# The default value is: NO. + +HIDE_IN_BODY_DOCS = NO + +# The INTERNAL_DOCS tag determines if documentation that is typed after a +# \internal command is included. If the tag is set to NO then the documentation +# will be excluded. Set it to YES to include the internal documentation. +# The default value is: NO. + +INTERNAL_DOCS = NO + +# If the CASE_SENSE_NAMES tag is set to NO then doxygen will only generate file +# names in lower-case letters. If set to YES, upper-case letters are also +# allowed. This is useful if you have classes or files whose names only differ +# in case and if your file system supports case sensitive file names. Windows +# and Mac users are advised to set this option to NO. +# The default value is: system dependent. + +CASE_SENSE_NAMES = NO + +# If the HIDE_SCOPE_NAMES tag is set to NO then doxygen will show members with +# their full class and namespace scopes in the documentation. If set to YES, the +# scope will be hidden. +# The default value is: NO. + +HIDE_SCOPE_NAMES = NO + +# If the HIDE_COMPOUND_REFERENCE tag is set to NO (default) then doxygen will +# append additional text to a page's title, such as Class Reference. If set to +# YES the compound reference will be hidden. +# The default value is: NO. + +HIDE_COMPOUND_REFERENCE= NO + +# If the SHOW_INCLUDE_FILES tag is set to YES then doxygen will put a list of +# the files that are included by a file in the documentation of that file. +# The default value is: YES. + +SHOW_INCLUDE_FILES = YES + +# If the SHOW_GROUPED_MEMB_INC tag is set to YES then Doxygen will add for each +# grouped member an include statement to the documentation, telling the reader +# which file to include in order to use the member. +# The default value is: NO. + +SHOW_GROUPED_MEMB_INC = NO + +# If the FORCE_LOCAL_INCLUDES tag is set to YES then doxygen will list include +# files with double quotes in the documentation rather than with sharp brackets. +# The default value is: NO. + +FORCE_LOCAL_INCLUDES = NO + +# If the INLINE_INFO tag is set to YES then a tag [inline] is inserted in the +# documentation for inline members. +# The default value is: YES. + +INLINE_INFO = YES + +# If the SORT_MEMBER_DOCS tag is set to YES then doxygen will sort the +# (detailed) documentation of file and class members alphabetically by member +# name. If set to NO, the members will appear in declaration order. +# The default value is: YES. + +SORT_MEMBER_DOCS = YES + +# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the brief +# descriptions of file, namespace and class members alphabetically by member +# name. If set to NO, the members will appear in declaration order. Note that +# this will also influence the order of the classes in the class list. +# The default value is: NO. + +SORT_BRIEF_DOCS = NO + +# If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen will sort the +# (brief and detailed) documentation of class members so that constructors and +# destructors are listed first. If set to NO the constructors will appear in the +# respective orders defined by SORT_BRIEF_DOCS and SORT_MEMBER_DOCS. +# Note: If SORT_BRIEF_DOCS is set to NO this option is ignored for sorting brief +# member documentation. +# Note: If SORT_MEMBER_DOCS is set to NO this option is ignored for sorting +# detailed member documentation. +# The default value is: NO. + +SORT_MEMBERS_CTORS_1ST = NO + +# If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the hierarchy +# of group names into alphabetical order. If set to NO the group names will +# appear in their defined order. +# The default value is: NO. + +SORT_GROUP_NAMES = NO + +# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be sorted by +# fully-qualified names, including namespaces. If set to NO, the class list will +# be sorted only by class name, not including the namespace part. +# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES. +# Note: This option applies only to the class list, not to the alphabetical +# list. +# The default value is: NO. + +SORT_BY_SCOPE_NAME = NO + +# If the STRICT_PROTO_MATCHING option is enabled and doxygen fails to do proper +# type resolution of all parameters of a function it will reject a match between +# the prototype and the implementation of a member function even if there is +# only one candidate or it is obvious which candidate to choose by doing a +# simple string match. By disabling STRICT_PROTO_MATCHING doxygen will still +# accept a match between prototype and implementation in such cases. +# The default value is: NO. + +STRICT_PROTO_MATCHING = NO + +# The GENERATE_TODOLIST tag can be used to enable (YES) or disable (NO) the todo +# list. This list is created by putting \todo commands in the documentation. +# The default value is: YES. + +GENERATE_TODOLIST = YES + +# The GENERATE_TESTLIST tag can be used to enable (YES) or disable (NO) the test +# list. This list is created by putting \test commands in the documentation. +# The default value is: YES. + +GENERATE_TESTLIST = YES + +# The GENERATE_BUGLIST tag can be used to enable (YES) or disable (NO) the bug +# list. This list is created by putting \bug commands in the documentation. +# The default value is: YES. + +GENERATE_BUGLIST = YES + +# The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or disable (NO) +# the deprecated list. This list is created by putting \deprecated commands in +# the documentation. +# The default value is: YES. + +GENERATE_DEPRECATEDLIST= YES + +# The ENABLED_SECTIONS tag can be used to enable conditional documentation +# sections, marked by \if <section_label> ... \endif and \cond <section_label> +# ... \endcond blocks. + +ENABLED_SECTIONS = + +# The MAX_INITIALIZER_LINES tag determines the maximum number of lines that the +# initial value of a variable or macro / define can have for it to appear in the +# documentation. If the initializer consists of more lines than specified here +# it will be hidden. Use a value of 0 to hide initializers completely. The +# appearance of the value of individual variables and macros / defines can be +# controlled using \showinitializer or \hideinitializer command in the +# documentation regardless of this setting. +# Minimum value: 0, maximum value: 10000, default value: 30. + +MAX_INITIALIZER_LINES = 30 + +# Set the SHOW_USED_FILES tag to NO to disable the list of files generated at +# the bottom of the documentation of classes and structs. If set to YES, the +# list will mention the files that were used to generate the documentation. +# The default value is: YES. + +SHOW_USED_FILES = YES + +# Set the SHOW_FILES tag to NO to disable the generation of the Files page. This +# will remove the Files entry from the Quick Index and from the Folder Tree View +# (if specified). +# The default value is: YES. + +SHOW_FILES = YES + +# Set the SHOW_NAMESPACES tag to NO to disable the generation of the Namespaces +# page. This will remove the Namespaces entry from the Quick Index and from the +# Folder Tree View (if specified). +# The default value is: YES. + +SHOW_NAMESPACES = YES + +# The FILE_VERSION_FILTER tag can be used to specify a program or script that +# doxygen should invoke to get the current version for each file (typically from +# the version control system). Doxygen will invoke the program by executing (via +# popen()) the command command input-file, where command is the value of the +# FILE_VERSION_FILTER tag, and input-file is the name of an input file provided +# by doxygen. Whatever the program writes to standard output is used as the file +# version. For an example see the documentation. + +FILE_VERSION_FILTER = + +# The LAYOUT_FILE tag can be used to specify a layout file which will be parsed +# by doxygen. The layout file controls the global structure of the generated +# output files in an output format independent way. To create the layout file +# that represents doxygen's defaults, run doxygen with the -l option. You can +# optionally specify a file name after the option, if omitted DoxygenLayout.xml +# will be used as the name of the layout file. +# +# Note that if you run doxygen from a directory containing a file called +# DoxygenLayout.xml, doxygen will parse it automatically even if the LAYOUT_FILE +# tag is left empty. + +LAYOUT_FILE = + +# The CITE_BIB_FILES tag can be used to specify one or more bib files containing +# the reference definitions. This must be a list of .bib files. The .bib +# extension is automatically appended if omitted. This requires the bibtex tool +# to be installed. See also http://en.wikipedia.org/wiki/BibTeX for more info. +# For LaTeX the style of the bibliography can be controlled using +# LATEX_BIB_STYLE. To use this feature you need bibtex and perl available in the +# search path. See also \cite for info how to create references. + +CITE_BIB_FILES = + +#--------------------------------------------------------------------------- +# Configuration options related to warning and progress messages +#--------------------------------------------------------------------------- + +# The QUIET tag can be used to turn on/off the messages that are generated to +# standard output by doxygen. If QUIET is set to YES this implies that the +# messages are off. +# The default value is: NO. + +QUIET = NO + +# The WARNINGS tag can be used to turn on/off the warning messages that are +# generated to standard error (stderr) by doxygen. If WARNINGS is set to YES +# this implies that the warnings are on. +# +# Tip: Turn warnings on while writing the documentation. +# The default value is: YES. + +WARNINGS = YES + +# If the WARN_IF_UNDOCUMENTED tag is set to YES then doxygen will generate +# warnings for undocumented members. If EXTRACT_ALL is set to YES then this flag +# will automatically be disabled. +# The default value is: YES. + +WARN_IF_UNDOCUMENTED = YES + +# If the WARN_IF_DOC_ERROR tag is set to YES, doxygen will generate warnings for +# potential errors in the documentation, such as not documenting some parameters +# in a documented function, or documenting parameters that don't exist or using +# markup commands wrongly. +# The default value is: YES. + +WARN_IF_DOC_ERROR = YES + +# This WARN_NO_PARAMDOC option can be enabled to get warnings for functions that +# are documented, but have no documentation for their parameters or return +# value. If set to NO, doxygen will only warn about wrong or incomplete +# parameter documentation, but not about the absence of documentation. +# The default value is: NO. + +WARN_NO_PARAMDOC = NO + +# The WARN_FORMAT tag determines the format of the warning messages that doxygen +# can produce. The string should contain the $file, $line, and $text tags, which +# will be replaced by the file and line number from which the warning originated +# and the warning text. Optionally the format may contain $version, which will +# be replaced by the version of the file (if it could be obtained via +# FILE_VERSION_FILTER) +# The default value is: $file:$line: $text. + +WARN_FORMAT = "$file:$line: $text" + +# The WARN_LOGFILE tag can be used to specify a file to which warning and error +# messages should be written. If left blank the output is written to standard +# error (stderr). + +WARN_LOGFILE = + +#--------------------------------------------------------------------------- +# Configuration options related to the input files +#--------------------------------------------------------------------------- + +# The INPUT tag is used to specify the files and/or directories that contain +# documented source files. You may enter file names like myfile.cpp or +# directories like /usr/src/myproject. Separate the files or directories with +# spaces. +# Note: If this tag is empty the current directory is searched. + +INPUT = include + +# This tag can be used to specify the character encoding of the source files +# that doxygen parses. Internally doxygen uses the UTF-8 encoding. Doxygen uses +# libiconv (or the iconv built into libc) for the transcoding. See the libiconv +# documentation (see: http://www.gnu.org/software/libiconv) for the list of +# possible encodings. +# The default value is: UTF-8. + +INPUT_ENCODING = UTF-8 + +# If the value of the INPUT tag contains directories, you can use the +# FILE_PATTERNS tag to specify one or more wildcard patterns (like *.cpp and +# *.h) to filter out the source-files in the directories. If left blank the +# following patterns are tested:*.c, *.cc, *.cxx, *.cpp, *.c++, *.java, *.ii, +# *.ixx, *.ipp, *.i++, *.inl, *.idl, *.ddl, *.odl, *.h, *.hh, *.hxx, *.hpp, +# *.h++, *.cs, *.d, *.php, *.php4, *.php5, *.phtml, *.inc, *.m, *.markdown, +# *.md, *.mm, *.dox, *.py, *.f90, *.f, *.for, *.tcl, *.vhd, *.vhdl, *.ucf, +# *.qsf, *.as and *.js. + +FILE_PATTERNS = + +# The RECURSIVE tag can be used to specify whether or not subdirectories should +# be searched for input files as well. +# The default value is: NO. + +RECURSIVE = YES + +# The EXCLUDE tag can be used to specify files and/or directories that should be +# excluded from the INPUT source files. This way you can easily exclude a +# subdirectory from a directory tree whose root is specified with the INPUT tag. +# +# Note that relative paths are relative to the directory from which doxygen is +# run. + +EXCLUDE = + +# The EXCLUDE_SYMLINKS tag can be used to select whether or not files or +# directories that are symbolic links (a Unix file system feature) are excluded +# from the input. +# The default value is: NO. + +EXCLUDE_SYMLINKS = NO + +# If the value of the INPUT tag contains directories, you can use the +# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude +# certain files from those directories. +# +# Note that the wildcards are matched against the file with absolute path, so to +# exclude all test directories for example use the pattern */test/* + +EXCLUDE_PATTERNS = + +# The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names +# (namespaces, classes, functions, etc.) that should be excluded from the +# output. The symbol name can be a fully qualified name, a word, or if the +# wildcard * is used, a substring. Examples: ANamespace, AClass, +# AClass::ANamespace, ANamespace::*Test +# +# Note that the wildcards are matched against the file with absolute path, so to +# exclude all test directories use the pattern */test/* + +EXCLUDE_SYMBOLS = + +# The EXAMPLE_PATH tag can be used to specify one or more files or directories +# that contain example code fragments that are included (see the \include +# command). + +EXAMPLE_PATH = + +# If the value of the EXAMPLE_PATH tag contains directories, you can use the +# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp and +# *.h) to filter out the source-files in the directories. If left blank all +# files are included. + +EXAMPLE_PATTERNS = + +# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be +# searched for input files to be used with the \include or \dontinclude commands +# irrespective of the value of the RECURSIVE tag. +# The default value is: NO. + +EXAMPLE_RECURSIVE = NO + +# The IMAGE_PATH tag can be used to specify one or more files or directories +# that contain images that are to be included in the documentation (see the +# \image command). + +IMAGE_PATH = + +# The INPUT_FILTER tag can be used to specify a program that doxygen should +# invoke to filter for each input file. Doxygen will invoke the filter program +# by executing (via popen()) the command: +# +# <filter> <input-file> +# +# where <filter> is the value of the INPUT_FILTER tag, and <input-file> is the +# name of an input file. Doxygen will then use the output that the filter +# program writes to standard output. If FILTER_PATTERNS is specified, this tag +# will be ignored. +# +# Note that the filter must not add or remove lines; it is applied before the +# code is scanned, but not when the output code is generated. If lines are added +# or removed, the anchors will not be placed correctly. + +INPUT_FILTER = + +# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern +# basis. Doxygen will compare the file name with each pattern and apply the +# filter if there is a match. The filters are a list of the form: pattern=filter +# (like *.cpp=my_cpp_filter). See INPUT_FILTER for further information on how +# filters are used. If the FILTER_PATTERNS tag is empty or if none of the +# patterns match the file name, INPUT_FILTER is applied. + +FILTER_PATTERNS = + +# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using +# INPUT_FILTER) will also be used to filter the input files that are used for +# producing the source files to browse (i.e. when SOURCE_BROWSER is set to YES). +# The default value is: NO. + +FILTER_SOURCE_FILES = NO + +# The FILTER_SOURCE_PATTERNS tag can be used to specify source filters per file +# pattern. A pattern will override the setting for FILTER_PATTERN (if any) and +# it is also possible to disable source filtering for a specific pattern using +# *.ext= (so without naming a filter). +# This tag requires that the tag FILTER_SOURCE_FILES is set to YES. + +FILTER_SOURCE_PATTERNS = + +# If the USE_MDFILE_AS_MAINPAGE tag refers to the name of a markdown file that +# is part of the input, its contents will be placed on the main page +# (index.html). This can be useful if you have a project on for instance GitHub +# and want to reuse the introduction page also for the doxygen output. + +USE_MDFILE_AS_MAINPAGE = + +#--------------------------------------------------------------------------- +# Configuration options related to source browsing +#--------------------------------------------------------------------------- + +# If the SOURCE_BROWSER tag is set to YES then a list of source files will be +# generated. Documented entities will be cross-referenced with these sources. +# +# Note: To get rid of all source code in the generated output, make sure that +# also VERBATIM_HEADERS is set to NO. +# The default value is: NO. + +SOURCE_BROWSER = NO + +# Setting the INLINE_SOURCES tag to YES will include the body of functions, +# classes and enums directly into the documentation. +# The default value is: NO. + +INLINE_SOURCES = NO + +# Setting the STRIP_CODE_COMMENTS tag to YES will instruct doxygen to hide any +# special comment blocks from generated source code fragments. Normal C, C++ and +# Fortran comments will always remain visible. +# The default value is: YES. + +STRIP_CODE_COMMENTS = YES + +# If the REFERENCED_BY_RELATION tag is set to YES then for each documented +# function all documented functions referencing it will be listed. +# The default value is: NO. + +REFERENCED_BY_RELATION = NO + +# If the REFERENCES_RELATION tag is set to YES then for each documented function +# all documented entities called/used by that function will be listed. +# The default value is: NO. + +REFERENCES_RELATION = NO + +# If the REFERENCES_LINK_SOURCE tag is set to YES and SOURCE_BROWSER tag is set +# to YES then the hyperlinks from functions in REFERENCES_RELATION and +# REFERENCED_BY_RELATION lists will link to the source code. Otherwise they will +# link to the documentation. +# The default value is: YES. + +REFERENCES_LINK_SOURCE = YES + +# If SOURCE_TOOLTIPS is enabled (the default) then hovering a hyperlink in the +# source code will show a tooltip with additional information such as prototype, +# brief description and links to the definition and documentation. Since this +# will make the HTML file larger and loading of large files a bit slower, you +# can opt to disable this feature. +# The default value is: YES. +# This tag requires that the tag SOURCE_BROWSER is set to YES. + +SOURCE_TOOLTIPS = YES + +# If the USE_HTAGS tag is set to YES then the references to source code will +# point to the HTML generated by the htags(1) tool instead of doxygen built-in +# source browser. The htags tool is part of GNU's global source tagging system +# (see http://www.gnu.org/software/global/global.html). You will need version +# 4.8.6 or higher. +# +# To use it do the following: +# - Install the latest version of global +# - Enable SOURCE_BROWSER and USE_HTAGS in the config file +# - Make sure the INPUT points to the root of the source tree +# - Run doxygen as normal +# +# Doxygen will invoke htags (and that will in turn invoke gtags), so these +# tools must be available from the command line (i.e. in the search path). +# +# The result: instead of the source browser generated by doxygen, the links to +# source code will now point to the output of htags. +# The default value is: NO. +# This tag requires that the tag SOURCE_BROWSER is set to YES. + +USE_HTAGS = NO + +# If the VERBATIM_HEADERS tag is set the YES then doxygen will generate a +# verbatim copy of the header file for each class for which an include is +# specified. Set to NO to disable this. +# See also: Section \class. +# The default value is: YES. + +VERBATIM_HEADERS = YES + +#--------------------------------------------------------------------------- +# Configuration options related to the alphabetical class index +#--------------------------------------------------------------------------- + +# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index of all +# compounds will be generated. Enable this if the project contains a lot of +# classes, structs, unions or interfaces. +# The default value is: YES. + +ALPHABETICAL_INDEX = YES + +# The COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns in +# which the alphabetical index list will be split. +# Minimum value: 1, maximum value: 20, default value: 5. +# This tag requires that the tag ALPHABETICAL_INDEX is set to YES. + +COLS_IN_ALPHA_INDEX = 5 + +# In case all classes in a project start with a common prefix, all classes will +# be put under the same header in the alphabetical index. The IGNORE_PREFIX tag +# can be used to specify a prefix (or a list of prefixes) that should be ignored +# while generating the index headers. +# This tag requires that the tag ALPHABETICAL_INDEX is set to YES. + +IGNORE_PREFIX = + +#--------------------------------------------------------------------------- +# Configuration options related to the HTML output +#--------------------------------------------------------------------------- + +# If the GENERATE_HTML tag is set to YES, doxygen will generate HTML output +# The default value is: YES. + +GENERATE_HTML = YES + +# The HTML_OUTPUT tag is used to specify where the HTML docs will be put. If a +# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of +# it. +# The default directory is: html. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_OUTPUT = api-html + +# The HTML_FILE_EXTENSION tag can be used to specify the file extension for each +# generated HTML page (for example: .htm, .php, .asp). +# The default value is: .html. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_FILE_EXTENSION = .html + +# The HTML_HEADER tag can be used to specify a user-defined HTML header file for +# each generated HTML page. If the tag is left blank doxygen will generate a +# standard header. +# +# To get valid HTML the header file that includes any scripts and style sheets +# that doxygen needs, which is dependent on the configuration options used (e.g. +# the setting GENERATE_TREEVIEW). It is highly recommended to start with a +# default header using +# doxygen -w html new_header.html new_footer.html new_stylesheet.css +# YourConfigFile +# and then modify the file new_header.html. See also section "Doxygen usage" +# for information on how to generate the default header that doxygen normally +# uses. +# Note: The header is subject to change so you typically have to regenerate the +# default header when upgrading to a newer version of doxygen. For a description +# of the possible markers and block names see the documentation. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_HEADER = + +# The HTML_FOOTER tag can be used to specify a user-defined HTML footer for each +# generated HTML page. If the tag is left blank doxygen will generate a standard +# footer. See HTML_HEADER for more information on how to generate a default +# footer and what special commands can be used inside the footer. See also +# section "Doxygen usage" for information on how to generate the default footer +# that doxygen normally uses. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_FOOTER = + +# The HTML_STYLESHEET tag can be used to specify a user-defined cascading style +# sheet that is used by each HTML page. It can be used to fine-tune the look of +# the HTML output. If left blank doxygen will generate a default style sheet. +# See also section "Doxygen usage" for information on how to generate the style +# sheet that doxygen normally uses. +# Note: It is recommended to use HTML_EXTRA_STYLESHEET instead of this tag, as +# it is more robust and this tag (HTML_STYLESHEET) will in the future become +# obsolete. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_STYLESHEET = + +# The HTML_EXTRA_STYLESHEET tag can be used to specify additional user-defined +# cascading style sheets that are included after the standard style sheets +# created by doxygen. Using this option one can overrule certain style aspects. +# This is preferred over using HTML_STYLESHEET since it does not replace the +# standard style sheet and is therefore more robust against future updates. +# Doxygen will copy the style sheet files to the output directory. +# Note: The order of the extra style sheet files is of importance (e.g. the last +# style sheet in the list overrules the setting of the previous ones in the +# list). For an example see the documentation. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_EXTRA_STYLESHEET = + +# The HTML_EXTRA_FILES tag can be used to specify one or more extra images or +# other source files which should be copied to the HTML output directory. Note +# that these files will be copied to the base HTML output directory. Use the +# $relpath^ marker in the HTML_HEADER and/or HTML_FOOTER files to load these +# files. In the HTML_STYLESHEET file, use the file name only. Also note that the +# files will be copied as-is; there are no commands or markers available. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_EXTRA_FILES = + +# The HTML_COLORSTYLE_HUE tag controls the color of the HTML output. Doxygen +# will adjust the colors in the style sheet and background images according to +# this color. Hue is specified as an angle on a colorwheel, see +# http://en.wikipedia.org/wiki/Hue for more information. For instance the value +# 0 represents red, 60 is yellow, 120 is green, 180 is cyan, 240 is blue, 300 +# purple, and 360 is red again. +# Minimum value: 0, maximum value: 359, default value: 220. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_COLORSTYLE_HUE = 203 + +# The HTML_COLORSTYLE_SAT tag controls the purity (or saturation) of the colors +# in the HTML output. For a value of 0 the output will use grayscales only. A +# value of 255 will produce the most vivid colors. +# Minimum value: 0, maximum value: 255, default value: 100. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_COLORSTYLE_SAT = 150 + +# The HTML_COLORSTYLE_GAMMA tag controls the gamma correction applied to the +# luminance component of the colors in the HTML output. Values below 100 +# gradually make the output lighter, whereas values above 100 make the output +# darker. The value divided by 100 is the actual gamma applied, so 80 represents +# a gamma of 0.8, The value 220 represents a gamma of 2.2, and 100 does not +# change the gamma. +# Minimum value: 40, maximum value: 240, default value: 80. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_COLORSTYLE_GAMMA = 80 + +# If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML +# page will contain the date and time when the page was generated. Setting this +# to NO can help when comparing the output of multiple runs. +# The default value is: YES. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_TIMESTAMP = NO + +# If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML +# documentation will contain sections that can be hidden and shown after the +# page has loaded. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_DYNAMIC_SECTIONS = YES + +# With HTML_INDEX_NUM_ENTRIES one can control the preferred number of entries +# shown in the various tree structured indices initially; the user can expand +# and collapse entries dynamically later on. Doxygen will expand the tree to +# such a level that at most the specified number of entries are visible (unless +# a fully collapsed tree already exceeds this amount). So setting the number of +# entries 1 will produce a full collapsed tree by default. 0 is a special value +# representing an infinite number of entries and will result in a full expanded +# tree by default. +# Minimum value: 0, maximum value: 9999, default value: 100. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_INDEX_NUM_ENTRIES = 100 + +# If the GENERATE_DOCSET tag is set to YES, additional index files will be +# generated that can be used as input for Apple's Xcode 3 integrated development +# environment (see: http://developer.apple.com/tools/xcode/), introduced with +# OSX 10.5 (Leopard). To create a documentation set, doxygen will generate a +# Makefile in the HTML output directory. Running make will produce the docset in +# that directory and running make install will install the docset in +# ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find it at +# startup. See http://developer.apple.com/tools/creatingdocsetswithdoxygen.html +# for more information. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +GENERATE_DOCSET = NO + +# This tag determines the name of the docset feed. A documentation feed provides +# an umbrella under which multiple documentation sets from a single provider +# (such as a company or product suite) can be grouped. +# The default value is: Doxygen generated docs. +# This tag requires that the tag GENERATE_DOCSET is set to YES. + +DOCSET_FEEDNAME = "Doxygen generated docs" + +# This tag specifies a string that should uniquely identify the documentation +# set bundle. This should be a reverse domain-name style string, e.g. +# com.mycompany.MyDocSet. Doxygen will append .docset to the name. +# The default value is: org.doxygen.Project. +# This tag requires that the tag GENERATE_DOCSET is set to YES. + +DOCSET_BUNDLE_ID = org.doxygen.Project + +# The DOCSET_PUBLISHER_ID tag specifies a string that should uniquely identify +# the documentation publisher. This should be a reverse domain-name style +# string, e.g. com.mycompany.MyDocSet.documentation. +# The default value is: org.doxygen.Publisher. +# This tag requires that the tag GENERATE_DOCSET is set to YES. + +DOCSET_PUBLISHER_ID = org.doxygen.Publisher + +# The DOCSET_PUBLISHER_NAME tag identifies the documentation publisher. +# The default value is: Publisher. +# This tag requires that the tag GENERATE_DOCSET is set to YES. + +DOCSET_PUBLISHER_NAME = Publisher + +# If the GENERATE_HTMLHELP tag is set to YES then doxygen generates three +# additional HTML index files: index.hhp, index.hhc, and index.hhk. The +# index.hhp is a project file that can be read by Microsoft's HTML Help Workshop +# (see: http://www.microsoft.com/en-us/download/details.aspx?id=21138) on +# Windows. +# +# The HTML Help Workshop contains a compiler that can convert all HTML output +# generated by doxygen into a single compiled HTML file (.chm). Compiled HTML +# files are now used as the Windows 98 help format, and will replace the old +# Windows help format (.hlp) on all Windows platforms in the future. Compressed +# HTML files also contain an index, a table of contents, and you can search for +# words in the documentation. The HTML workshop also contains a viewer for +# compressed HTML files. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +GENERATE_HTMLHELP = NO + +# The CHM_FILE tag can be used to specify the file name of the resulting .chm +# file. You can add a path in front of the file if the result should not be +# written to the html output directory. +# This tag requires that the tag GENERATE_HTMLHELP is set to YES. + +CHM_FILE = + +# The HHC_LOCATION tag can be used to specify the location (absolute path +# including file name) of the HTML help compiler (hhc.exe). If non-empty, +# doxygen will try to run the HTML help compiler on the generated index.hhp. +# The file has to be specified with full path. +# This tag requires that the tag GENERATE_HTMLHELP is set to YES. + +HHC_LOCATION = + +# The GENERATE_CHI flag controls if a separate .chi index file is generated +# (YES) or that it should be included in the master .chm file (NO). +# The default value is: NO. +# This tag requires that the tag GENERATE_HTMLHELP is set to YES. + +GENERATE_CHI = NO + +# The CHM_INDEX_ENCODING is used to encode HtmlHelp index (hhk), content (hhc) +# and project file content. +# This tag requires that the tag GENERATE_HTMLHELP is set to YES. + +CHM_INDEX_ENCODING = + +# The BINARY_TOC flag controls whether a binary table of contents is generated +# (YES) or a normal table of contents (NO) in the .chm file. Furthermore it +# enables the Previous and Next buttons. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTMLHELP is set to YES. + +BINARY_TOC = NO + +# The TOC_EXPAND flag can be set to YES to add extra items for group members to +# the table of contents of the HTML help documentation and to the tree view. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTMLHELP is set to YES. + +TOC_EXPAND = NO + +# If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and +# QHP_VIRTUAL_FOLDER are set, an additional index file will be generated that +# can be used as input for Qt's qhelpgenerator to generate a Qt Compressed Help +# (.qch) of the generated HTML documentation. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +GENERATE_QHP = NO + +# If the QHG_LOCATION tag is specified, the QCH_FILE tag can be used to specify +# the file name of the resulting .qch file. The path specified is relative to +# the HTML output folder. +# This tag requires that the tag GENERATE_QHP is set to YES. + +QCH_FILE = + +# The QHP_NAMESPACE tag specifies the namespace to use when generating Qt Help +# Project output. For more information please see Qt Help Project / Namespace +# (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#namespace). +# The default value is: org.doxygen.Project. +# This tag requires that the tag GENERATE_QHP is set to YES. + +QHP_NAMESPACE = org.doxygen.Project + +# The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating Qt +# Help Project output. For more information please see Qt Help Project / Virtual +# Folders (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#virtual- +# folders). +# The default value is: doc. +# This tag requires that the tag GENERATE_QHP is set to YES. + +QHP_VIRTUAL_FOLDER = doc + +# If the QHP_CUST_FILTER_NAME tag is set, it specifies the name of a custom +# filter to add. For more information please see Qt Help Project / Custom +# Filters (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#custom- +# filters). +# This tag requires that the tag GENERATE_QHP is set to YES. + +QHP_CUST_FILTER_NAME = + +# The QHP_CUST_FILTER_ATTRS tag specifies the list of the attributes of the +# custom filter to add. For more information please see Qt Help Project / Custom +# Filters (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#custom- +# filters). +# This tag requires that the tag GENERATE_QHP is set to YES. + +QHP_CUST_FILTER_ATTRS = + +# The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this +# project's filter section matches. Qt Help Project / Filter Attributes (see: +# http://qt-project.org/doc/qt-4.8/qthelpproject.html#filter-attributes). +# This tag requires that the tag GENERATE_QHP is set to YES. + +QHP_SECT_FILTER_ATTRS = + +# The QHG_LOCATION tag can be used to specify the location of Qt's +# qhelpgenerator. If non-empty doxygen will try to run qhelpgenerator on the +# generated .qhp file. +# This tag requires that the tag GENERATE_QHP is set to YES. + +QHG_LOCATION = + +# If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files will be +# generated, together with the HTML files, they form an Eclipse help plugin. To +# install this plugin and make it available under the help contents menu in +# Eclipse, the contents of the directory containing the HTML and XML files needs +# to be copied into the plugins directory of eclipse. The name of the directory +# within the plugins directory should be the same as the ECLIPSE_DOC_ID value. +# After copying Eclipse needs to be restarted before the help appears. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +GENERATE_ECLIPSEHELP = NO + +# A unique identifier for the Eclipse help plugin. When installing the plugin +# the directory name containing the HTML and XML files should also have this +# name. Each documentation set should have its own identifier. +# The default value is: org.doxygen.Project. +# This tag requires that the tag GENERATE_ECLIPSEHELP is set to YES. + +ECLIPSE_DOC_ID = org.doxygen.Project + +# If you want full control over the layout of the generated HTML pages it might +# be necessary to disable the index and replace it with your own. The +# DISABLE_INDEX tag can be used to turn on/off the condensed index (tabs) at top +# of each HTML page. A value of NO enables the index and the value YES disables +# it. Since the tabs in the index contain the same information as the navigation +# tree, you can set this option to YES if you also set GENERATE_TREEVIEW to YES. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +DISABLE_INDEX = NO + +# The GENERATE_TREEVIEW tag is used to specify whether a tree-like index +# structure should be generated to display hierarchical information. If the tag +# value is set to YES, a side panel will be generated containing a tree-like +# index structure (just like the one that is generated for HTML Help). For this +# to work a browser that supports JavaScript, DHTML, CSS and frames is required +# (i.e. any modern browser). Windows users are probably better off using the +# HTML help feature. Via custom style sheets (see HTML_EXTRA_STYLESHEET) one can +# further fine-tune the look of the index. As an example, the default style +# sheet generated by doxygen has an example that shows how to put an image at +# the root of the tree instead of the PROJECT_NAME. Since the tree basically has +# the same information as the tab index, you could consider setting +# DISABLE_INDEX to YES when enabling this option. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +GENERATE_TREEVIEW = NO + +# The ENUM_VALUES_PER_LINE tag can be used to set the number of enum values that +# doxygen will group on one line in the generated HTML documentation. +# +# Note that a value of 0 will completely suppress the enum values from appearing +# in the overview section. +# Minimum value: 0, maximum value: 20, default value: 4. +# This tag requires that the tag GENERATE_HTML is set to YES. + +ENUM_VALUES_PER_LINE = 4 + +# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be used +# to set the initial width (in pixels) of the frame in which the tree is shown. +# Minimum value: 0, maximum value: 1500, default value: 250. +# This tag requires that the tag GENERATE_HTML is set to YES. + +TREEVIEW_WIDTH = 250 + +# If the EXT_LINKS_IN_WINDOW option is set to YES, doxygen will open links to +# external symbols imported via tag files in a separate window. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +EXT_LINKS_IN_WINDOW = NO + +# Use this tag to change the font size of LaTeX formulas included as images in +# the HTML documentation. When you change the font size after a successful +# doxygen run you need to manually remove any form_*.png images from the HTML +# output directory to force them to be regenerated. +# Minimum value: 8, maximum value: 50, default value: 10. +# This tag requires that the tag GENERATE_HTML is set to YES. + +FORMULA_FONTSIZE = 10 + +# Use the FORMULA_TRANPARENT tag to determine whether or not the images +# generated for formulas are transparent PNGs. Transparent PNGs are not +# supported properly for IE 6.0, but are supported on all modern browsers. +# +# Note that when changing this option you need to delete any form_*.png files in +# the HTML output directory before the changes have effect. +# The default value is: YES. +# This tag requires that the tag GENERATE_HTML is set to YES. + +FORMULA_TRANSPARENT = YES + +# Enable the USE_MATHJAX option to render LaTeX formulas using MathJax (see +# http://www.mathjax.org) which uses client side Javascript for the rendering +# instead of using pre-rendered bitmaps. Use this if you do not have LaTeX +# installed or if you want to formulas look prettier in the HTML output. When +# enabled you may also need to install MathJax separately and configure the path +# to it using the MATHJAX_RELPATH option. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +USE_MATHJAX = NO + +# When MathJax is enabled you can set the default output format to be used for +# the MathJax output. See the MathJax site (see: +# http://docs.mathjax.org/en/latest/output.html) for more details. +# Possible values are: HTML-CSS (which is slower, but has the best +# compatibility), NativeMML (i.e. MathML) and SVG. +# The default value is: HTML-CSS. +# This tag requires that the tag USE_MATHJAX is set to YES. + +MATHJAX_FORMAT = HTML-CSS + +# When MathJax is enabled you need to specify the location relative to the HTML +# output directory using the MATHJAX_RELPATH option. The destination directory +# should contain the MathJax.js script. For instance, if the mathjax directory +# is located at the same level as the HTML output directory, then +# MATHJAX_RELPATH should be ../mathjax. The default value points to the MathJax +# Content Delivery Network so you can quickly see the result without installing +# MathJax. However, it is strongly recommended to install a local copy of +# MathJax from http://www.mathjax.org before deployment. +# The default value is: http://cdn.mathjax.org/mathjax/latest. +# This tag requires that the tag USE_MATHJAX is set to YES. + +MATHJAX_RELPATH = http://cdn.mathjax.org/mathjax/latest + +# The MATHJAX_EXTENSIONS tag can be used to specify one or more MathJax +# extension names that should be enabled during MathJax rendering. For example +# MATHJAX_EXTENSIONS = TeX/AMSmath TeX/AMSsymbols +# This tag requires that the tag USE_MATHJAX is set to YES. + +MATHJAX_EXTENSIONS = + +# The MATHJAX_CODEFILE tag can be used to specify a file with javascript pieces +# of code that will be used on startup of the MathJax code. See the MathJax site +# (see: http://docs.mathjax.org/en/latest/output.html) for more details. For an +# example see the documentation. +# This tag requires that the tag USE_MATHJAX is set to YES. + +MATHJAX_CODEFILE = + +# When the SEARCHENGINE tag is enabled doxygen will generate a search box for +# the HTML output. The underlying search engine uses javascript and DHTML and +# should work on any modern browser. Note that when using HTML help +# (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets (GENERATE_DOCSET) +# there is already a search function so this one should typically be disabled. +# For large projects the javascript based search engine can be slow, then +# enabling SERVER_BASED_SEARCH may provide a better solution. It is possible to +# search using the keyboard; to jump to the search box use <access key> + S +# (what the <access key> is depends on the OS and browser, but it is typically +# <CTRL>, <ALT>/<option>, or both). Inside the search box use the <cursor down +# key> to jump into the search results window, the results can be navigated +# using the <cursor keys>. Press <Enter> to select an item or <escape> to cancel +# the search. The filter options can be selected when the cursor is inside the +# search box by pressing <Shift>+<cursor down>. Also here use the <cursor keys> +# to select a filter and <Enter> or <escape> to activate or cancel the filter +# option. +# The default value is: YES. +# This tag requires that the tag GENERATE_HTML is set to YES. + +SEARCHENGINE = NO + +# When the SERVER_BASED_SEARCH tag is enabled the search engine will be +# implemented using a web server instead of a web client using Javascript. There +# are two flavors of web server based searching depending on the EXTERNAL_SEARCH +# setting. When disabled, doxygen will generate a PHP script for searching and +# an index file used by the script. When EXTERNAL_SEARCH is enabled the indexing +# and searching needs to be provided by external tools. See the section +# "External Indexing and Searching" for details. +# The default value is: NO. +# This tag requires that the tag SEARCHENGINE is set to YES. + +SERVER_BASED_SEARCH = NO + +# When EXTERNAL_SEARCH tag is enabled doxygen will no longer generate the PHP +# script for searching. Instead the search results are written to an XML file +# which needs to be processed by an external indexer. Doxygen will invoke an +# external search engine pointed to by the SEARCHENGINE_URL option to obtain the +# search results. +# +# Doxygen ships with an example indexer (doxyindexer) and search engine +# (doxysearch.cgi) which are based on the open source search engine library +# Xapian (see: http://xapian.org/). +# +# See the section "External Indexing and Searching" for details. +# The default value is: NO. +# This tag requires that the tag SEARCHENGINE is set to YES. + +EXTERNAL_SEARCH = NO + +# The SEARCHENGINE_URL should point to a search engine hosted by a web server +# which will return the search results when EXTERNAL_SEARCH is enabled. +# +# Doxygen ships with an example indexer (doxyindexer) and search engine +# (doxysearch.cgi) which are based on the open source search engine library +# Xapian (see: http://xapian.org/). See the section "External Indexing and +# Searching" for details. +# This tag requires that the tag SEARCHENGINE is set to YES. + +SEARCHENGINE_URL = + +# When SERVER_BASED_SEARCH and EXTERNAL_SEARCH are both enabled the unindexed +# search data is written to a file for indexing by an external tool. With the +# SEARCHDATA_FILE tag the name of this file can be specified. +# The default file is: searchdata.xml. +# This tag requires that the tag SEARCHENGINE is set to YES. + +SEARCHDATA_FILE = searchdata.xml + +# When SERVER_BASED_SEARCH and EXTERNAL_SEARCH are both enabled the +# EXTERNAL_SEARCH_ID tag can be used as an identifier for the project. This is +# useful in combination with EXTRA_SEARCH_MAPPINGS to search through multiple +# projects and redirect the results back to the right project. +# This tag requires that the tag SEARCHENGINE is set to YES. + +EXTERNAL_SEARCH_ID = + +# The EXTRA_SEARCH_MAPPINGS tag can be used to enable searching through doxygen +# projects other than the one defined by this configuration file, but that are +# all added to the same external search index. Each project needs to have a +# unique id set via EXTERNAL_SEARCH_ID. The search mapping then maps the id of +# to a relative location where the documentation can be found. The format is: +# EXTRA_SEARCH_MAPPINGS = tagname1=loc1 tagname2=loc2 ... +# This tag requires that the tag SEARCHENGINE is set to YES. + +EXTRA_SEARCH_MAPPINGS = + +#--------------------------------------------------------------------------- +# Configuration options related to the LaTeX output +#--------------------------------------------------------------------------- + +# If the GENERATE_LATEX tag is set to YES, doxygen will generate LaTeX output. +# The default value is: YES. + +GENERATE_LATEX = NO + +# The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. If a +# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of +# it. +# The default directory is: latex. +# This tag requires that the tag GENERATE_LATEX is set to YES. + +LATEX_OUTPUT = latex + +# The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be +# invoked. +# +# Note that when enabling USE_PDFLATEX this option is only used for generating +# bitmaps for formulas in the HTML output, but not in the Makefile that is +# written to the output directory. +# The default file is: latex. +# This tag requires that the tag GENERATE_LATEX is set to YES. + +LATEX_CMD_NAME = latex + +# The MAKEINDEX_CMD_NAME tag can be used to specify the command name to generate +# index for LaTeX. +# The default file is: makeindex. +# This tag requires that the tag GENERATE_LATEX is set to YES. + +MAKEINDEX_CMD_NAME = makeindex + +# If the COMPACT_LATEX tag is set to YES, doxygen generates more compact LaTeX +# documents. This may be useful for small projects and may help to save some +# trees in general. +# The default value is: NO. +# This tag requires that the tag GENERATE_LATEX is set to YES. + +COMPACT_LATEX = NO + +# The PAPER_TYPE tag can be used to set the paper type that is used by the +# printer. +# Possible values are: a4 (210 x 297 mm), letter (8.5 x 11 inches), legal (8.5 x +# 14 inches) and executive (7.25 x 10.5 inches). +# The default value is: a4. +# This tag requires that the tag GENERATE_LATEX is set to YES. + +PAPER_TYPE = a4 + +# The EXTRA_PACKAGES tag can be used to specify one or more LaTeX package names +# that should be included in the LaTeX output. To get the times font for +# instance you can specify +# EXTRA_PACKAGES=times +# If left blank no extra packages will be included. +# This tag requires that the tag GENERATE_LATEX is set to YES. + +EXTRA_PACKAGES = + +# The LATEX_HEADER tag can be used to specify a personal LaTeX header for the +# generated LaTeX document. The header should contain everything until the first +# chapter. If it is left blank doxygen will generate a standard header. See +# section "Doxygen usage" for information on how to let doxygen write the +# default header to a separate file. +# +# Note: Only use a user-defined header if you know what you are doing! The +# following commands have a special meaning inside the header: $title, +# $datetime, $date, $doxygenversion, $projectname, $projectnumber, +# $projectbrief, $projectlogo. Doxygen will replace $title with the empty +# string, for the replacement values of the other commands the user is referred +# to HTML_HEADER. +# This tag requires that the tag GENERATE_LATEX is set to YES. + +LATEX_HEADER = + +# The LATEX_FOOTER tag can be used to specify a personal LaTeX footer for the +# generated LaTeX document. The footer should contain everything after the last +# chapter. If it is left blank doxygen will generate a standard footer. See +# LATEX_HEADER for more information on how to generate a default footer and what +# special commands can be used inside the footer. +# +# Note: Only use a user-defined footer if you know what you are doing! +# This tag requires that the tag GENERATE_LATEX is set to YES. + +LATEX_FOOTER = + +# The LATEX_EXTRA_STYLESHEET tag can be used to specify additional user-defined +# LaTeX style sheets that are included after the standard style sheets created +# by doxygen. Using this option one can overrule certain style aspects. Doxygen +# will copy the style sheet files to the output directory. +# Note: The order of the extra style sheet files is of importance (e.g. the last +# style sheet in the list overrules the setting of the previous ones in the +# list). +# This tag requires that the tag GENERATE_LATEX is set to YES. + +LATEX_EXTRA_STYLESHEET = + +# The LATEX_EXTRA_FILES tag can be used to specify one or more extra images or +# other source files which should be copied to the LATEX_OUTPUT output +# directory. Note that the files will be copied as-is; there are no commands or +# markers available. +# This tag requires that the tag GENERATE_LATEX is set to YES. + +LATEX_EXTRA_FILES = + +# If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated is +# prepared for conversion to PDF (using ps2pdf or pdflatex). The PDF file will +# contain links (just like the HTML output) instead of page references. This +# makes the output suitable for online browsing using a PDF viewer. +# The default value is: YES. +# This tag requires that the tag GENERATE_LATEX is set to YES. + +PDF_HYPERLINKS = YES + +# If the USE_PDFLATEX tag is set to YES, doxygen will use pdflatex to generate +# the PDF file directly from the LaTeX files. Set this option to YES, to get a +# higher quality PDF documentation. +# The default value is: YES. +# This tag requires that the tag GENERATE_LATEX is set to YES. + +USE_PDFLATEX = YES + +# If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \batchmode +# command to the generated LaTeX files. This will instruct LaTeX to keep running +# if errors occur, instead of asking the user for help. This option is also used +# when generating formulas in HTML. +# The default value is: NO. +# This tag requires that the tag GENERATE_LATEX is set to YES. + +LATEX_BATCHMODE = NO + +# If the LATEX_HIDE_INDICES tag is set to YES then doxygen will not include the +# index chapters (such as File Index, Compound Index, etc.) in the output. +# The default value is: NO. +# This tag requires that the tag GENERATE_LATEX is set to YES. + +LATEX_HIDE_INDICES = NO + +# If the LATEX_SOURCE_CODE tag is set to YES then doxygen will include source +# code with syntax highlighting in the LaTeX output. +# +# Note that which sources are shown also depends on other settings such as +# SOURCE_BROWSER. +# The default value is: NO. +# This tag requires that the tag GENERATE_LATEX is set to YES. + +LATEX_SOURCE_CODE = NO + +# The LATEX_BIB_STYLE tag can be used to specify the style to use for the +# bibliography, e.g. plainnat, or ieeetr. See +# http://en.wikipedia.org/wiki/BibTeX and \cite for more info. +# The default value is: plain. +# This tag requires that the tag GENERATE_LATEX is set to YES. + +LATEX_BIB_STYLE = plain + +#--------------------------------------------------------------------------- +# Configuration options related to the RTF output +#--------------------------------------------------------------------------- + +# If the GENERATE_RTF tag is set to YES, doxygen will generate RTF output. The +# RTF output is optimized for Word 97 and may not look too pretty with other RTF +# readers/editors. +# The default value is: NO. + +GENERATE_RTF = NO + +# The RTF_OUTPUT tag is used to specify where the RTF docs will be put. If a +# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of +# it. +# The default directory is: rtf. +# This tag requires that the tag GENERATE_RTF is set to YES. + +RTF_OUTPUT = rtf + +# If the COMPACT_RTF tag is set to YES, doxygen generates more compact RTF +# documents. This may be useful for small projects and may help to save some +# trees in general. +# The default value is: NO. +# This tag requires that the tag GENERATE_RTF is set to YES. + +COMPACT_RTF = NO + +# If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated will +# contain hyperlink fields. The RTF file will contain links (just like the HTML +# output) instead of page references. This makes the output suitable for online +# browsing using Word or some other Word compatible readers that support those +# fields. +# +# Note: WordPad (write) and others do not support links. +# The default value is: NO. +# This tag requires that the tag GENERATE_RTF is set to YES. + +RTF_HYPERLINKS = NO + +# Load stylesheet definitions from file. Syntax is similar to doxygen's config +# file, i.e. a series of assignments. You only have to provide replacements, +# missing definitions are set to their default value. +# +# See also section "Doxygen usage" for information on how to generate the +# default style sheet that doxygen normally uses. +# This tag requires that the tag GENERATE_RTF is set to YES. + +RTF_STYLESHEET_FILE = + +# Set optional variables used in the generation of an RTF document. Syntax is +# similar to doxygen's config file. A template extensions file can be generated +# using doxygen -e rtf extensionFile. +# This tag requires that the tag GENERATE_RTF is set to YES. + +RTF_EXTENSIONS_FILE = + +# If the RTF_SOURCE_CODE tag is set to YES then doxygen will include source code +# with syntax highlighting in the RTF output. +# +# Note that which sources are shown also depends on other settings such as +# SOURCE_BROWSER. +# The default value is: NO. +# This tag requires that the tag GENERATE_RTF is set to YES. + +RTF_SOURCE_CODE = NO + +#--------------------------------------------------------------------------- +# Configuration options related to the man page output +#--------------------------------------------------------------------------- + +# If the GENERATE_MAN tag is set to YES, doxygen will generate man pages for +# classes and files. +# The default value is: NO. + +GENERATE_MAN = NO + +# The MAN_OUTPUT tag is used to specify where the man pages will be put. If a +# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of +# it. A directory man3 will be created inside the directory specified by +# MAN_OUTPUT. +# The default directory is: man. +# This tag requires that the tag GENERATE_MAN is set to YES. + +MAN_OUTPUT = man + +# The MAN_EXTENSION tag determines the extension that is added to the generated +# man pages. In case the manual section does not start with a number, the number +# 3 is prepended. The dot (.) at the beginning of the MAN_EXTENSION tag is +# optional. +# The default value is: .3. +# This tag requires that the tag GENERATE_MAN is set to YES. + +MAN_EXTENSION = .3 + +# The MAN_SUBDIR tag determines the name of the directory created within +# MAN_OUTPUT in which the man pages are placed. If defaults to man followed by +# MAN_EXTENSION with the initial . removed. +# This tag requires that the tag GENERATE_MAN is set to YES. + +MAN_SUBDIR = + +# If the MAN_LINKS tag is set to YES and doxygen generates man output, then it +# will generate one additional man file for each entity documented in the real +# man page(s). These additional files only source the real man page, but without +# them the man command would be unable to find the correct page. +# The default value is: NO. +# This tag requires that the tag GENERATE_MAN is set to YES. + +MAN_LINKS = NO + +#--------------------------------------------------------------------------- +# Configuration options related to the XML output +#--------------------------------------------------------------------------- + +# If the GENERATE_XML tag is set to YES, doxygen will generate an XML file that +# captures the structure of the code including all documentation. +# The default value is: NO. + +GENERATE_XML = NO + +# The XML_OUTPUT tag is used to specify where the XML pages will be put. If a +# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of +# it. +# The default directory is: xml. +# This tag requires that the tag GENERATE_XML is set to YES. + +XML_OUTPUT = xml + +# If the XML_PROGRAMLISTING tag is set to YES, doxygen will dump the program +# listings (including syntax highlighting and cross-referencing information) to +# the XML output. Note that enabling this will significantly increase the size +# of the XML output. +# The default value is: YES. +# This tag requires that the tag GENERATE_XML is set to YES. + +XML_PROGRAMLISTING = YES + +#--------------------------------------------------------------------------- +# Configuration options related to the DOCBOOK output +#--------------------------------------------------------------------------- + +# If the GENERATE_DOCBOOK tag is set to YES, doxygen will generate Docbook files +# that can be used to generate PDF. +# The default value is: NO. + +GENERATE_DOCBOOK = NO + +# The DOCBOOK_OUTPUT tag is used to specify where the Docbook pages will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be put in +# front of it. +# The default directory is: docbook. +# This tag requires that the tag GENERATE_DOCBOOK is set to YES. + +DOCBOOK_OUTPUT = docbook + +# If the DOCBOOK_PROGRAMLISTING tag is set to YES, doxygen will include the +# program listings (including syntax highlighting and cross-referencing +# information) to the DOCBOOK output. Note that enabling this will significantly +# increase the size of the DOCBOOK output. +# The default value is: NO. +# This tag requires that the tag GENERATE_DOCBOOK is set to YES. + +DOCBOOK_PROGRAMLISTING = NO + +#--------------------------------------------------------------------------- +# Configuration options for the AutoGen Definitions output +#--------------------------------------------------------------------------- + +# If the GENERATE_AUTOGEN_DEF tag is set to YES, doxygen will generate an +# AutoGen Definitions (see http://autogen.sf.net) file that captures the +# structure of the code including all documentation. Note that this feature is +# still experimental and incomplete at the moment. +# The default value is: NO. + +GENERATE_AUTOGEN_DEF = NO + +#--------------------------------------------------------------------------- +# Configuration options related to the Perl module output +#--------------------------------------------------------------------------- + +# If the GENERATE_PERLMOD tag is set to YES, doxygen will generate a Perl module +# file that captures the structure of the code including all documentation. +# +# Note that this feature is still experimental and incomplete at the moment. +# The default value is: NO. + +GENERATE_PERLMOD = NO + +# If the PERLMOD_LATEX tag is set to YES, doxygen will generate the necessary +# Makefile rules, Perl scripts and LaTeX code to be able to generate PDF and DVI +# output from the Perl module output. +# The default value is: NO. +# This tag requires that the tag GENERATE_PERLMOD is set to YES. + +PERLMOD_LATEX = NO + +# If the PERLMOD_PRETTY tag is set to YES, the Perl module output will be nicely +# formatted so it can be parsed by a human reader. This is useful if you want to +# understand what is going on. On the other hand, if this tag is set to NO, the +# size of the Perl module output will be much smaller and Perl will parse it +# just the same. +# The default value is: YES. +# This tag requires that the tag GENERATE_PERLMOD is set to YES. + +PERLMOD_PRETTY = YES + +# The names of the make variables in the generated doxyrules.make file are +# prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX. This is useful +# so different doxyrules.make files included by the same Makefile don't +# overwrite each other's variables. +# This tag requires that the tag GENERATE_PERLMOD is set to YES. + +PERLMOD_MAKEVAR_PREFIX = + +#--------------------------------------------------------------------------- +# Configuration options related to the preprocessor +#--------------------------------------------------------------------------- + +# If the ENABLE_PREPROCESSING tag is set to YES, doxygen will evaluate all +# C-preprocessor directives found in the sources and include files. +# The default value is: YES. + +ENABLE_PREPROCESSING = YES + +# If the MACRO_EXPANSION tag is set to YES, doxygen will expand all macro names +# in the source code. If set to NO, only conditional compilation will be +# performed. Macro expansion can be done in a controlled way by setting +# EXPAND_ONLY_PREDEF to YES. +# The default value is: NO. +# This tag requires that the tag ENABLE_PREPROCESSING is set to YES. + +MACRO_EXPANSION = NO + +# If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES then +# the macro expansion is limited to the macros specified with the PREDEFINED and +# EXPAND_AS_DEFINED tags. +# The default value is: NO. +# This tag requires that the tag ENABLE_PREPROCESSING is set to YES. + +EXPAND_ONLY_PREDEF = NO + +# If the SEARCH_INCLUDES tag is set to YES, the include files in the +# INCLUDE_PATH will be searched if a #include is found. +# The default value is: YES. +# This tag requires that the tag ENABLE_PREPROCESSING is set to YES. + +SEARCH_INCLUDES = YES + +# The INCLUDE_PATH tag can be used to specify one or more directories that +# contain include files that are not input files but should be processed by the +# preprocessor. +# This tag requires that the tag SEARCH_INCLUDES is set to YES. + +INCLUDE_PATH = + +# You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard +# patterns (like *.h and *.hpp) to filter out the header-files in the +# directories. If left blank, the patterns specified with FILE_PATTERNS will be +# used. +# This tag requires that the tag ENABLE_PREPROCESSING is set to YES. + +INCLUDE_FILE_PATTERNS = + +# The PREDEFINED tag can be used to specify one or more macro names that are +# defined before the preprocessor is started (similar to the -D option of e.g. +# gcc). The argument of the tag is a list of macros of the form: name or +# name=definition (no spaces). If the definition and the "=" are omitted, "=1" +# is assumed. To prevent a macro definition from being undefined via #undef or +# recursively expanded use the := operator instead of the = operator. +# This tag requires that the tag ENABLE_PREPROCESSING is set to YES. + +PREDEFINED = + +# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then this +# tag can be used to specify a list of macro names that should be expanded. The +# macro definition that is found in the sources will be used. Use the PREDEFINED +# tag if you want to use a different macro definition that overrules the +# definition found in the source code. +# This tag requires that the tag ENABLE_PREPROCESSING is set to YES. + +EXPAND_AS_DEFINED = + +# If the SKIP_FUNCTION_MACROS tag is set to YES then doxygen's preprocessor will +# remove all references to function-like macros that are alone on a line, have +# an all uppercase name, and do not end with a semicolon. Such function macros +# are typically used for boiler-plate code, and will confuse the parser if not +# removed. +# The default value is: YES. +# This tag requires that the tag ENABLE_PREPROCESSING is set to YES. + +SKIP_FUNCTION_MACROS = YES + +#--------------------------------------------------------------------------- +# Configuration options related to external references +#--------------------------------------------------------------------------- + +# The TAGFILES tag can be used to specify one or more tag files. For each tag +# file the location of the external documentation should be added. The format of +# a tag file without this location is as follows: +# TAGFILES = file1 file2 ... +# Adding location for the tag files is done as follows: +# TAGFILES = file1=loc1 "file2 = loc2" ... +# where loc1 and loc2 can be relative or absolute paths or URLs. See the +# section "Linking to external documentation" for more information about the use +# of tag files. +# Note: Each tag file must have a unique name (where the name does NOT include +# the path). If a tag file is not located in the directory in which doxygen is +# run, you must also specify the path to the tagfile here. + +TAGFILES = + +# When a file name is specified after GENERATE_TAGFILE, doxygen will create a +# tag file that is based on the input files it reads. See section "Linking to +# external documentation" for more information about the usage of tag files. + +GENERATE_TAGFILE = + +# If the ALLEXTERNALS tag is set to YES, all external class will be listed in +# the class index. If set to NO, only the inherited external classes will be +# listed. +# The default value is: NO. + +ALLEXTERNALS = NO + +# If the EXTERNAL_GROUPS tag is set to YES, all external groups will be listed +# in the modules index. If set to NO, only the current project's groups will be +# listed. +# The default value is: YES. + +EXTERNAL_GROUPS = YES + +# If the EXTERNAL_PAGES tag is set to YES, all external pages will be listed in +# the related pages index. If set to NO, only the current project's pages will +# be listed. +# The default value is: YES. + +EXTERNAL_PAGES = YES + +# The PERL_PATH should be the absolute path and name of the perl script +# interpreter (i.e. the result of 'which perl'). +# The default file (with absolute path) is: /usr/bin/perl. + +PERL_PATH = /usr/bin/perl + +#--------------------------------------------------------------------------- +# Configuration options related to the dot tool +#--------------------------------------------------------------------------- + +# If the CLASS_DIAGRAMS tag is set to YES, doxygen will generate a class diagram +# (in HTML and LaTeX) for classes with base or super classes. Setting the tag to +# NO turns the diagrams off. Note that this option also works with HAVE_DOT +# disabled, but it is recommended to install and use dot, since it yields more +# powerful graphs. +# The default value is: YES. + +CLASS_DIAGRAMS = YES + +# You can define message sequence charts within doxygen comments using the \msc +# command. Doxygen will then run the mscgen tool (see: +# http://www.mcternan.me.uk/mscgen/)) to produce the chart and insert it in the +# documentation. The MSCGEN_PATH tag allows you to specify the directory where +# the mscgen tool resides. If left empty the tool is assumed to be found in the +# default search path. + +MSCGEN_PATH = + +# You can include diagrams made with dia in doxygen documentation. Doxygen will +# then run dia to produce the diagram and insert it in the documentation. The +# DIA_PATH tag allows you to specify the directory where the dia binary resides. +# If left empty dia is assumed to be found in the default search path. + +DIA_PATH = + +# If set to YES the inheritance and collaboration graphs will hide inheritance +# and usage relations if the target is undocumented or is not a class. +# The default value is: YES. + +HIDE_UNDOC_RELATIONS = YES + +# If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is +# available from the path. This tool is part of Graphviz (see: +# http://www.graphviz.org/), a graph visualization toolkit from AT&T and Lucent +# Bell Labs. The other options in this section have no effect if this option is +# set to NO +# The default value is: NO. + +HAVE_DOT = YES + +# The DOT_NUM_THREADS specifies the number of dot invocations doxygen is allowed +# to run in parallel. When set to 0 doxygen will base this on the number of +# processors available in the system. You can set it explicitly to a value +# larger than 0 to get control over the balance between CPU load and processing +# speed. +# Minimum value: 0, maximum value: 32, default value: 0. +# This tag requires that the tag HAVE_DOT is set to YES. + +DOT_NUM_THREADS = 0 + +# When you want a differently looking font in the dot files that doxygen +# generates you can specify the font name using DOT_FONTNAME. You need to make +# sure dot is able to find the font, which can be done by putting it in a +# standard location or by setting the DOTFONTPATH environment variable or by +# setting DOT_FONTPATH to the directory containing the font. +# The default value is: Helvetica. +# This tag requires that the tag HAVE_DOT is set to YES. + +DOT_FONTNAME = Helvetica + +# The DOT_FONTSIZE tag can be used to set the size (in points) of the font of +# dot graphs. +# Minimum value: 4, maximum value: 24, default value: 10. +# This tag requires that the tag HAVE_DOT is set to YES. + +DOT_FONTSIZE = 10 + +# By default doxygen will tell dot to use the default font as specified with +# DOT_FONTNAME. If you specify a different font using DOT_FONTNAME you can set +# the path where dot can find it using this tag. +# This tag requires that the tag HAVE_DOT is set to YES. + +DOT_FONTPATH = + +# If the CLASS_GRAPH tag is set to YES then doxygen will generate a graph for +# each documented class showing the direct and indirect inheritance relations. +# Setting this tag to YES will force the CLASS_DIAGRAMS tag to NO. +# The default value is: YES. +# This tag requires that the tag HAVE_DOT is set to YES. + +CLASS_GRAPH = YES + +# If the COLLABORATION_GRAPH tag is set to YES then doxygen will generate a +# graph for each documented class showing the direct and indirect implementation +# dependencies (inheritance, containment, and class references variables) of the +# class with other documented classes. +# The default value is: YES. +# This tag requires that the tag HAVE_DOT is set to YES. + +COLLABORATION_GRAPH = YES + +# If the GROUP_GRAPHS tag is set to YES then doxygen will generate a graph for +# groups, showing the direct groups dependencies. +# The default value is: YES. +# This tag requires that the tag HAVE_DOT is set to YES. + +GROUP_GRAPHS = YES + +# If the UML_LOOK tag is set to YES, doxygen will generate inheritance and +# collaboration diagrams in a style similar to the OMG's Unified Modeling +# Language. +# The default value is: NO. +# This tag requires that the tag HAVE_DOT is set to YES. + +UML_LOOK = NO + +# If the UML_LOOK tag is enabled, the fields and methods are shown inside the +# class node. If there are many fields or methods and many nodes the graph may +# become too big to be useful. The UML_LIMIT_NUM_FIELDS threshold limits the +# number of items for each type to make the size more manageable. Set this to 0 +# for no limit. Note that the threshold may be exceeded by 50% before the limit +# is enforced. So when you set the threshold to 10, up to 15 fields may appear, +# but if the number exceeds 15, the total amount of fields shown is limited to +# 10. +# Minimum value: 0, maximum value: 100, default value: 10. +# This tag requires that the tag HAVE_DOT is set to YES. + +UML_LIMIT_NUM_FIELDS = 10 + +# If the TEMPLATE_RELATIONS tag is set to YES then the inheritance and +# collaboration graphs will show the relations between templates and their +# instances. +# The default value is: NO. +# This tag requires that the tag HAVE_DOT is set to YES. + +TEMPLATE_RELATIONS = NO + +# If the INCLUDE_GRAPH, ENABLE_PREPROCESSING and SEARCH_INCLUDES tags are set to +# YES then doxygen will generate a graph for each documented file showing the +# direct and indirect include dependencies of the file with other documented +# files. +# The default value is: YES. +# This tag requires that the tag HAVE_DOT is set to YES. + +INCLUDE_GRAPH = YES + +# If the INCLUDED_BY_GRAPH, ENABLE_PREPROCESSING and SEARCH_INCLUDES tags are +# set to YES then doxygen will generate a graph for each documented file showing +# the direct and indirect include dependencies of the file with other documented +# files. +# The default value is: YES. +# This tag requires that the tag HAVE_DOT is set to YES. + +INCLUDED_BY_GRAPH = YES + +# If the CALL_GRAPH tag is set to YES then doxygen will generate a call +# dependency graph for every global function or class method. +# +# Note that enabling this option will significantly increase the time of a run. +# So in most cases it will be better to enable call graphs for selected +# functions only using the \callgraph command. +# The default value is: NO. +# This tag requires that the tag HAVE_DOT is set to YES. + +CALL_GRAPH = NO + +# If the CALLER_GRAPH tag is set to YES then doxygen will generate a caller +# dependency graph for every global function or class method. +# +# Note that enabling this option will significantly increase the time of a run. +# So in most cases it will be better to enable caller graphs for selected +# functions only using the \callergraph command. +# The default value is: NO. +# This tag requires that the tag HAVE_DOT is set to YES. + +CALLER_GRAPH = NO + +# If the GRAPHICAL_HIERARCHY tag is set to YES then doxygen will graphical +# hierarchy of all classes instead of a textual one. +# The default value is: YES. +# This tag requires that the tag HAVE_DOT is set to YES. + +GRAPHICAL_HIERARCHY = YES + +# If the DIRECTORY_GRAPH tag is set to YES then doxygen will show the +# dependencies a directory has on other directories in a graphical way. The +# dependency relations are determined by the #include relations between the +# files in the directories. +# The default value is: YES. +# This tag requires that the tag HAVE_DOT is set to YES. + +DIRECTORY_GRAPH = YES + +# The DOT_IMAGE_FORMAT tag can be used to set the image format of the images +# generated by dot. +# Note: If you choose svg you need to set HTML_FILE_EXTENSION to xhtml in order +# to make the SVG files visible in IE 9+ (other browsers do not have this +# requirement). +# Possible values are: png, jpg, gif and svg. +# The default value is: png. +# This tag requires that the tag HAVE_DOT is set to YES. + +DOT_IMAGE_FORMAT = svg + +# If DOT_IMAGE_FORMAT is set to svg, then this option can be set to YES to +# enable generation of interactive SVG images that allow zooming and panning. +# +# Note that this requires a modern browser other than Internet Explorer. Tested +# and working are Firefox, Chrome, Safari, and Opera. +# Note: For IE 9+ you need to set HTML_FILE_EXTENSION to xhtml in order to make +# the SVG files visible. Older versions of IE do not have SVG support. +# The default value is: NO. +# This tag requires that the tag HAVE_DOT is set to YES. + +INTERACTIVE_SVG = NO + +# The DOT_PATH tag can be used to specify the path where the dot tool can be +# found. If left blank, it is assumed the dot tool can be found in the path. +# This tag requires that the tag HAVE_DOT is set to YES. + +DOT_PATH = + +# The DOTFILE_DIRS tag can be used to specify one or more directories that +# contain dot files that are included in the documentation (see the \dotfile +# command). +# This tag requires that the tag HAVE_DOT is set to YES. + +DOTFILE_DIRS = + +# The MSCFILE_DIRS tag can be used to specify one or more directories that +# contain msc files that are included in the documentation (see the \mscfile +# command). + +MSCFILE_DIRS = + +# The DIAFILE_DIRS tag can be used to specify one or more directories that +# contain dia files that are included in the documentation (see the \diafile +# command). + +DIAFILE_DIRS = + +# When using plantuml, the PLANTUML_JAR_PATH tag should be used to specify the +# path where java can find the plantuml.jar file. If left blank, it is assumed +# PlantUML is not used or called during a preprocessing step. Doxygen will +# generate a warning when it encounters a \startuml command in this case and +# will not generate output for the diagram. + +PLANTUML_JAR_PATH = + +# When using plantuml, the specified paths are searched for files specified by +# the !include statement in a plantuml block. + +PLANTUML_INCLUDE_PATH = + +# The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of nodes +# that will be shown in the graph. If the number of nodes in a graph becomes +# larger than this value, doxygen will truncate the graph, which is visualized +# by representing a node as a red box. Note that doxygen if the number of direct +# children of the root node in a graph is already larger than +# DOT_GRAPH_MAX_NODES then the graph will not be shown at all. Also note that +# the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH. +# Minimum value: 0, maximum value: 10000, default value: 50. +# This tag requires that the tag HAVE_DOT is set to YES. + +DOT_GRAPH_MAX_NODES = 50 + +# The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the graphs +# generated by dot. A depth value of 3 means that only nodes reachable from the +# root by following a path via at most 3 edges will be shown. Nodes that lay +# further from the root node will be omitted. Note that setting this option to 1 +# or 2 may greatly reduce the computation time needed for large code bases. Also +# note that the size of a graph can be further restricted by +# DOT_GRAPH_MAX_NODES. Using a depth of 0 means no depth restriction. +# Minimum value: 0, maximum value: 1000, default value: 0. +# This tag requires that the tag HAVE_DOT is set to YES. + +MAX_DOT_GRAPH_DEPTH = 0 + +# Set the DOT_TRANSPARENT tag to YES to generate images with a transparent +# background. This is disabled by default, because dot on Windows does not seem +# to support this out of the box. +# +# Warning: Depending on the platform used, enabling this option may lead to +# badly anti-aliased labels on the edges of a graph (i.e. they become hard to +# read). +# The default value is: NO. +# This tag requires that the tag HAVE_DOT is set to YES. + +DOT_TRANSPARENT = NO + +# Set the DOT_MULTI_TARGETS tag to YES to allow dot to generate multiple output +# files in one run (i.e. multiple -o and -T options on the command line). This +# makes dot run faster, but since only newer versions of dot (>1.8.10) support +# this, this feature is disabled by default. +# The default value is: NO. +# This tag requires that the tag HAVE_DOT is set to YES. + +DOT_MULTI_TARGETS = NO + +# If the GENERATE_LEGEND tag is set to YES doxygen will generate a legend page +# explaining the meaning of the various boxes and arrows in the dot generated +# graphs. +# The default value is: YES. +# This tag requires that the tag HAVE_DOT is set to YES. + +GENERATE_LEGEND = YES + +# If the DOT_CLEANUP tag is set to YES, doxygen will remove the intermediate dot +# files that are used to generate the various graphs. +# The default value is: YES. +# This tag requires that the tag HAVE_DOT is set to YES. + +DOT_CLEANUP = YES diff --git a/resources/3rdparty/cpphoafparser-0.99.2/Makefile b/resources/3rdparty/cpphoafparser-0.99.2/Makefile new file mode 100644 index 000000000..5ae616efc --- /dev/null +++ b/resources/3rdparty/cpphoafparser-0.99.2/Makefile @@ -0,0 +1,20 @@ + +# CXXFLAGS for debugging: +# CXXFLAGS=-g -O1 -Wall + +# CXXFLAGS for production +CXXFLAGS=-O3 -Wall + +cpphoaf : src/cpphoaf.cc include/cpphoafparser/*/*.hh + $(CXX) $(CXXFLAGS) -I include --std=c++11 -o $@ $< + + +# The example parsers +basic_parser_1 : src/basic_parser_1.cc include/cpphoafparser/*/*.hh + $(CXX) $(CXXFLAGS) -I include --std=c++11 -o $@ $< + +basic_parser_2 : src/basic_parser_2.cc include/cpphoafparser/*/*.hh + $(CXX) $(CXXFLAGS) -I include --std=c++11 -o $@ $< + +.PHONY: all +all: cpphoaf basic_parser_1 basic_parser_2 diff --git a/resources/3rdparty/cpphoafparser-0.99.2/README b/resources/3rdparty/cpphoafparser-0.99.2/README new file mode 100644 index 000000000..61e85ce83 --- /dev/null +++ b/resources/3rdparty/cpphoafparser-0.99.2/README @@ -0,0 +1,63 @@ +============================================================================== +| +| cpphoafparser library (version 0.99.2) +| +| C++-based parser for the Hanoi Omega Automata Format +| +| http://automata.tools/hoa/cpphoafparser/ +============================================================================= + + Copyright (c) 2015- + Authors: + * Joachim Klein <klein@tcs.inf.tu-dresden.de> + * David Mueller <david.mueller@tcs.inf.tu-dresden.de> + + The cpphoafparser 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. + + The cpphoafparser 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 + + +----------------------------------------------------------------------------- + Quick start +----------------------------------------------------------------------------- + +(0) Have a look at the documentation in docs/index.html or at + http://automata.tools/hoa/cpphoafparser/ + +(1) Compile the library. In this directory, execute + make + +(2) Using the command-line tool: + + ./cpphoaf parse automaton.hoa + + Parse the automaton.hoa file and check for errors + + + ./cpphoaf print automaton.hoa + + Parse the automaton.hoa file and print back the parsed automaton + + + ./cpphoaf print --resolve-aliases automaton.hoa + + Parse the automaton.hoa file, resolve any aliases and + print back the parsed automaton + + ./cpphoaf help + + Print additional options + + Instead of a file, use - to read from standard input, i.e., + + tool-that-writes-hoa-to-stdout | ./cpphoaf parse - diff --git a/resources/3rdparty/cpphoafparser-0.99.2/docs/cpp2html.css b/resources/3rdparty/cpphoafparser-0.99.2/docs/cpp2html.css new file mode 100644 index 000000000..ff391a4a7 --- /dev/null +++ b/resources/3rdparty/cpphoafparser-0.99.2/docs/cpp2html.css @@ -0,0 +1,13 @@ + +.comment { color: #008000; font-style: italic; } +.pre { color: #000099; } +.string { color: #009900; } +.char { color: #009900; } +.float { color: #996600; } +.int { color: #000080; } +.bool { color: #000000; font-weight: bold; } +.type { color: #0000FF; } +.flow { color: #800000; } +.keyword { color: #000000; } +.operator { color: #000000; font-weight: bold; } +.operator { color: #000000; font-weight: bold; } \ No newline at end of file diff --git a/resources/3rdparty/cpphoafparser-0.99.2/docs/cpphoaf-tool.html b/resources/3rdparty/cpphoafparser-0.99.2/docs/cpphoaf-tool.html new file mode 100644 index 000000000..1b65c2917 --- /dev/null +++ b/resources/3rdparty/cpphoafparser-0.99.2/docs/cpphoaf-tool.html @@ -0,0 +1,243 @@ +<!DOCTYPE HTML> +<html> +<head> +<meta http-equiv="content-type" content="text/html; charset=utf-8"> +<link href="cpphoafparser.css" rel="stylesheet"> +<title>The cpphoaf command-line tool [cpphoafparser Library for the Hanoi Omega-Automata Format (HOAF), version 0.99.2]</title> +</head> + +<body> +<div class="nav"><a class="nav" href="index.html">^ Overview</a></div> + +<h1> +The <span class="blue1">cpp</span><span class="blue2">hoaf</span> Command-Line Tool<br/> +<span style="font-size:70%">The <span class="blue">cpphoafparser</span> +Library for the Hanoi Omega-Automata Format (HOAF), version 0.99.2</span> +</h1> + +<p> +The cpphoafparser library provides a command-line interface to some of +the functionality. This can be roughly divided into two broad areas: +</p> +<ul> + <li><em>Validating</em> an automaton (no syntax errors, declared properties are correct, ...)</li> + <li><em>Transforming</em> an automaton (translating from state- to transition-based acceptance, ...)</li> +</ul> + + +<p>We assume here that the reader is familiar with the basic concepts of +the <a href="http://adl.github.io/hoaf/">Hanoi Omega-Automata Format (HOAF)</a>. +</p> + +<h2><a name="general">General</a></h2> + +<h3>Obtaining and invoking the command-line tool</h3> +We assume here that you have downloaded the source code archive +from the <a href="http://automata.tools/hoa/cpphoafparser/">website</a>. +Unpack and build (Linux, OS X, ...): +<pre class="command"> +tar xzvf cpphoafparser-xx.yy.tgz +cd cpphoafparser-xx.yy +make +</pre> +<p> +where <i>xx.yy</i> is the version.</p> + +<p>Alternatively, for Windows, you can download a precompiled binary.</p> + +<p>There is also a <span class="classname">CMakeLists.txt</span> + configuration for <a href="http://www.cmake.org/">CMake</a> available. In the top-level directory, execute: +<pre class="command"> +mkdir build +cd build +cmake ../src +make +</pre> + +<p>CMake can alse be used to generate Visual Studio project files.</p> + +<h3>Getting Help</h3> +<p>With</p> +<pre class="command"> +./cpphoaf help +</pre> +<p>you'll obtain a brief description of the supported commands and +flags.</p> + +<h3>Input / Output</h3> +<p> +The command-line tool reads the file specified on the command-line, performs the required +processing and outputs the result to the standard output. +The hyphen character '-' can be used instead of the filename for reading from standard input. +Below, we provide some examples of invoking the command-line tool: +</p> + +<p> +In the simplest case, the following command parses the automaton +from automaton.hoa and prints the result +(the parsed automaton without comments, extra whitespace, etc) to the +console: +</p> + +<pre class="command"> +./cpphoaf print automaton.hoa +</pre> + +<p> +In the next example, we pipe the output of some other tool to the +input of cpphoaf: +</p> + +<pre class="command"> +./some-hoa-producer | ./cpphoaf print - +</pre> + +<p> +The output can be captured as usual to a file using redirection: +</p> + +<pre class="command"> +./some-hoa-producer | ./cpphoaf print - > result.hoa +</pre> + +<p> +Note: Take care that you do not simultaneously read and write from/to the same file! +</p> + +<h3>Commands and Flags</h3> +<p> +The general structure of invoking the command line-tool is +</p> +<pre class="command"> +./cpphoaf command flag(s) file(s) +</pre> + +<h3>Multiple automata</h3> +<p> +The HOA format supports the streaming of automata, i.e., the ability to represent a +sequence of automata in a single file. +</p> +<p> +Please note that, currently, the <span class="prog">cpphoaf</span> tool only supports parsing +a single automaton. +</p> + +<h3>Exit value</h3> +<p> +If you want to use the command-line tool in scripts, the value returned by the tool on exit +is useful for diagnosing errors. The tool will return 0 for success/no errors. If there are +errors during the processing of the automata, the value 1 will be returned. If there are problems +with the invocation (invalid command-line arguments, ...), the value 2 +will be returned. +</p> + +<h2><a name="validating">Validating Automata</a></h2> + +<p>To check that an automaton in HOA format can be successfully parsed, run +</p> +<pre class="commandWithOutput"> +./cpphoaf parse automaton-file.hoa +</pre> +<pre class="output"> +Parsing OK +</pre> + +<p>If everything went fine, the tool will output that parsing was OK, +otherwise there will be an error message indicating what went wrong.</p> + +<p>Upon success, the automaton</p> +<ul> + <li>has been successfully parsed (syntax conforms to the HOA + format),</li> + <li>properties specified in the header have been verified to be + correct (violations of <em>state-labels</em>, <em>trans-labels</em>, + <em>implicit-labels</em>, <em>explicit-labels</em>, <em>state-acc</em>, + <em>trans-acc</em>, <em>no-univ-branch</em>, <em>colored</em> are currently detected; + for the <em>deterministic</em> and <em>complete</em> properties, violations are + currently only detected when implicit transition labels are used), + </li> + <li>if an <em>acc-name</em> header has been provided and is one + of the standard acceptance conditions specified in the format, the + correspondence with the <em>Acceptance</em> header has been verified + </li> + <li>the number, ordering and names of the states are valid with regard to + the restrictions specified in the HOA format, + </li> + <li>if implicit transition labels are used, the required number is present, + </li> + <li>alias definitions are non-recursive and all aliases, atomic propositions and + acceptance sets that are used are defined. + </li> +</ul> + +<p> +The semantic validations can be disabled by the command-line +option <span class="cmdline">--no-validate</span>. The following command +will only check the syntactic correctness according to the HOA format: +</p> +<pre class="command"> +./cpphoaf parse --no-validate automaton.hoa +</pre> + +<h2>Transforming the Automaton</h2> + +<h3>Pretty-printing the Automaton</h3> + +<p>The simplest transformation is barely a transformation at all. Via</p> +<pre class="command"> +./cpphoaf print automaton-file.hoa +</pre> +<p>the automaton is simply parsed and printed back to the standard output.</p> +<p> +As comments and superfluous whitespace are ignored by the parser, this transforms the +automaton into some kind of canonical form, with the different elements of the HOA format +each placed on a single line. +</p> + +<h3>Resolving Aliases</h3> +<p> +The command-line option <span class="cmdline">--resolve-aliases</span> activates a transformation +that (1) removes the <em>Alias:</em> <a class="explanationref" href="http://adl.github.io/hoaf/#alias" target="_blank">?</a> +definitions and (2) resolves all <em>@alias</em> references in +transition labels.</p> +<p>The following command reads the automaton, resolves the aliases and prints the resulting automaton:</p> +<pre class="command"> +./cpphoaf print --resolve-aliases automaton-file.hoa +</pre> + +<p> +The option <span class="cmdline">--resolve-aliases</span> +can be used with all other commands and options. +</p> + +<h2>Tracing, Implementation Details</h2> +<p>If you wish to implement your own transformations or want to use the cpphoafparser library, +it might be interesting to play around with the <span class="cmdline">--trace</span> option:</p> + +<pre class="command"> +./cpphoaf parse --trace automaton-file.hoa +</pre> + +<p> +If activated, tracing will output the sequence of method calls into +the <em>HOAConsumer</em> by +the parser. This can be used to study the correspondence of syntactical elements in the +HOA format and the method calls. +</p> + +<p> +The command-line utility is implemented in the +<span class="classname">src/cpphoaf.cc</span>. It relies on the various +<em>HOAConsumers</em> for the functionality and is a good entry-point for further investigations. +</p> + +<hr> +<p>If you have further questions, find bugs or want to tell +us about your use of the cpphoafparser library, please feel free to contact us!</p> + +<p>(c) 2015-2016 +Joachim Klein <klein@tcs.inf.tu-dresden.de>, +David Müller <david.mueller@tcs.inf.tu-dresden.de> + +</body> +</html> diff --git a/resources/3rdparty/cpphoafparser-0.99.2/docs/cpphoafparser-library.html b/resources/3rdparty/cpphoafparser-0.99.2/docs/cpphoafparser-library.html new file mode 100644 index 000000000..7bebea5b4 --- /dev/null +++ b/resources/3rdparty/cpphoafparser-0.99.2/docs/cpphoafparser-library.html @@ -0,0 +1,183 @@ +<!DOCTYPE HTML> +<html> +<head> +<meta http-equiv="content-type" content="text/html; charset=utf-8"> +<link href="cpphoafparser.css" rel="stylesheet"> +<link href="cpp2html.css" rel="stylesheet"> +<title>Using the cpphoafparser Library [cpphoafparser Library for the Hanoi Omega-Automata Format (HOAF), version 0.99.2]</title> +</head> + +<body> +<div class="nav"><a class="nav" href="index.html">^ Overview</a></div> + +<h1> +Using the <span class="blue1">cpp</span><span class="blue2">hoaf</span><span class="blue3">parser</span> Library<br/> +<span style="font-size:70%">The <span class="blue">cpphoafparser</span> +Library for the Hanoi Omega-Automata Format (HOAF), version 0.99.2</span> +</h1> + +<p>The cpphoafparser library can be used to parse and process ω-automata +in the HOA format. We assume here that the reader is familiar with the basic concepts of +the <a href="http://adl.github.io/hoaf/">Hanoi Omega-Automata Format (HOAF)</a>. +</p> + +<h2><a name="general">General Structure</a></h2> + +<p> +The two main building blocks of the parser library are the <em>parser</em> and +classes implementing the <em>HOAConsumer</em> interface. A <em>HOAConsumer</em> has functions +corresponding to the various elements that can occur in a HOA automaton. While parsing, the parser +calls each of these functions to indicate that this particular element has just occurred. +</p> + +<p>cpphoafparser is a <emph>header-only</emph> C++ library, i.e., it suffices to +add the <span class="classname">include</span> directory to the include path of your compiler +and include the corresponding header files. All cpphoafparser elements are contained in the +<span class="classname">cpphoafparser</span> namespace. It uses C++11 features, so ensure that your +compiler is configured to support this standard version. +</p> + + +<h3>A Basic Parser</h3> +<p>The most basic use of the cpphoafparser library is shown in the following code snippet +(<span class="classname">src/basic_parser_1.cc</span></span>):</p> + +<div class="code"> +<pre><span class="pre">#include "cpphoafparser/consumer/hoa_consumer_print.hh" +#include "cpphoafparser/parser/hoa_parser.hh" +</span><span class="keyword"> +using namespace</span> cpphoafparser<span class="operator">;</span><span class="comment"> + +/** The most basic HOA parser: Read an automaton from input and print it to the output. */</span><span class="type"> +int</span><span class="keyword"> main</span><span class="operator">(</span><span class="type">int</span> argc<span class="operator">,</span><span class="keyword"> const</span><span class="type"> char</span><span class="operator">*</span> argv<span class="operator">[]) {</span> + HOAConsumer<span class="operator">::</span>ptr consumer<span class="operator">(</span><span class="keyword">new</span> HOAConsumerPrint<span class="operator">(</span>std<span class="operator">::</span>cout<span class="operator">));</span><span class="flow"> + + try</span><span class="operator"> {</span> + + HOAParser<span class="operator">::</span>parse<span class="operator">(</span>std<span class="operator">::</span>cin<span class="operator">,</span> consumer<span class="operator">); + + }</span><span class="flow"> catch</span><span class="operator"> (</span>std<span class="operator">::</span>exception<span class="operator">&</span> e<span class="operator">) {</span> + std<span class="operator">::</span>cerr<span class="operator"> <<</span> e<span class="operator">.</span>what<span class="operator">() <<</span> std<span class="operator">::</span>endl<span class="operator">;</span><span class="flow"> + return</span><span class="int"> 1</span><span class="operator">; + }</span><span class="flow"> + return</span><span class="int"> 0</span><span class="operator">; +}</span> +</pre> +</div> + +<p> +Here, the parser reads from <span class="classname">std::cin</span> +and calls into a <span class="classname">HOAConsumerPrint</span> +object that just outputs the elements to <span class="classname">std::cout</span>.</p> + +<h3>Chaining Multiple HOAConsumers: HOAIntermediate</h3> + +<p>The <span class="classname">HOAIntermediate</span> class, which itself +implements the <span class="classname">HOAConsumer</span> interface, provides the basis for chaining multiple +<span class="classname">HOAConsumers</span>, one after another, each reading the output of the previous one. +</p> + +<p> +Consider the following example +(<span class="classname">src/basic_parser_2.cc</span></span>):</p> + +<div class="code"> +<pre><span class="pre">#include "cpphoafparser/consumer/hoa_intermediate.hh" +#include "cpphoafparser/consumer/hoa_consumer_null.hh" +#include "cpphoafparser/parser/hoa_parser.hh" +</span><span class="keyword"> +using namespace</span> cpphoafparser<span class="operator">;</span><span class="comment"> + +/* An HOAIntermediate that counts invocations of addState */</span><span class="keyword"> +class</span> CountStates<span class="operator"> :</span><span class="keyword"> public</span> HOAIntermediate<span class="operator"> {</span><span class="keyword"> +public</span><span class="operator">:</span><span class="keyword"> + typedef</span> std<span class="operator">::</span>shared_ptr<span class="operator"><</span>CountStates<span class="operator">></span> ptr<span class="operator">;</span><span class="type"> + unsigned int</span> count<span class="operator"> =</span><span class="int"> 0</span><span class="operator">;</span> + + CountStates<span class="operator">(</span>HOAConsumer<span class="operator">::</span>ptr next<span class="operator">) :</span> HOAIntermediate<span class="operator">(</span>next<span class="operator">) { + }</span><span class="keyword"> + + virtual</span><span class="type"> void</span> addState<span class="operator">(</span><span class="type">unsigned int</span> id<span class="operator">,</span> + std<span class="operator">::</span>shared_ptr<span class="operator"><</span>std<span class="operator">::</span>string<span class="operator">></span> info<span class="operator">,</span> + label_expr<span class="operator">::</span>ptr labelExpr<span class="operator">,</span> + std<span class="operator">::</span>shared_ptr<span class="operator"><</span>int_list<span class="operator">></span> accSignature<span class="operator">)</span> override<span class="operator"> {</span> + count<span class="operator">++;</span> + next<span class="operator">-></span>addState<span class="operator">(</span>id<span class="operator">,</span> info<span class="operator">,</span> labelExpr<span class="operator">,</span> accSignature<span class="operator">); + } +};</span><span class="comment"> + +/** Demonstrating the use of HOAIntermediates */</span><span class="type"> +int</span><span class="keyword"> main</span><span class="operator">(</span><span class="type">int</span> argc<span class="operator">,</span><span class="keyword"> const</span><span class="type"> char</span><span class="operator">*</span> argv<span class="operator">[]) {</span> + HOAConsumer<span class="operator">::</span>ptr hoaNull<span class="operator">(</span><span class="keyword">new</span> HOAConsumerNull<span class="operator">());</span> + CountStates<span class="operator">::</span>ptr counter<span class="operator">(</span><span class="keyword">new</span> CountStates<span class="operator">(</span>hoaNull<span class="operator">));</span><span class="flow"> + + try</span><span class="operator"> {</span> + + HOAParser<span class="operator">::</span>parse<span class="operator">(</span>std<span class="operator">::</span>cin<span class="operator">,</span> counter<span class="operator">);</span> + std<span class="operator">::</span>cout<span class="operator"> <<</span><span class="string"> "Number of state definitions = "</span><span class="operator"> <<</span> counter<span class="operator">-></span>count<span class="operator"> <<</span> std<span class="operator">::</span>endl<span class="operator">; + + }</span><span class="flow"> catch</span><span class="operator"> (</span>std<span class="operator">::</span>exception<span class="operator">&</span> e<span class="operator">) {</span> + std<span class="operator">::</span>cerr<span class="operator"> <<</span> e<span class="operator">.</span>what<span class="operator">() <<</span> std<span class="operator">::</span>endl<span class="operator">;</span><span class="flow"> + return</span><span class="int"> 1</span><span class="operator">; + }</span><span class="flow"> + return</span><span class="int"> 0</span><span class="operator">; +}</span> +</pre> +</div> + +<p>We derive <span class="classname">CountStates</span> from <span class="classname">HOAIntermediate</span>. +Its constructor takes the next <span class="classname">HOAConsumer</span> in the chain, which can +again be a <span class="classname">HOAIntermediate</span>. Here, we are passing a +<span class="classname">HOAConsumerNull</span> object, which does nothing when called, acting as a "no-operation" +end of the consumer chain. Inside the <span class="classname">CountStates</span>, we override the +<span class="classname">addState</span> method, which is called for each <em>State:</em> +definition in the automaton. +We count the number of definitions and pass along the arguments to the next consumer. +In the end, we just output the count of the definitions. +</p> + + +<h2>The HOAConsumer API</h2> + +<p> +A good starting point for learning about the HOAConsumer API is the +<a +href="http://automata.tools/hoa/cpphoafparser/docs/api-html/classcpphoafparser_1_1_h_o_a_consumer.html">documentation of the HOAConsumer interface</a> +as well as the rest of the <a href="http://automata.tools/hoa/cpphoafparser/docs/api-html/index.html">API documentation</a>. + +<p>Another good introduction is the source code of the <span class="classname">HOAConsumerPrint</span> class, +as it translates back from the method calls in the <span class="classname">HOAConsumer</span> interface to the +textual representation of the HOA format. +</p> + +<p>Some further tidbits that might be useful:</p> +<ul> + <li>The boolean expressions for the explicit transition labels and the acceptance condition + are represented by + <a href="http://automata.tools/hoa/cpphoafparser/docs/api-html/classcpphoafparser_1_1_boolean_expression.html"><span class="classname">BooleanExpression</span></a>, + with appropriate <span class="classname">Atoms</span> for the leaf nodes in the abstract syntax tree. + The <span class="classname">BooleanExpressions</span> are designed to + be <em>immutable</em>. Therefore, subtrees can be safely shared between expressions. + </li> + <li> + If you encounter an error inside one of the <span class="classname">HOAConsumer</span> method calls, throw an + <a href="http://automata.tools/hoa/cpphoafparser/docs/api-html/classcpphoafparser_1_1_h_o_a_consumer_exception.html">HOAConsumerException</a>. + </li> + <li>Memory managment is generally handled via <span class="classname">shared_ptr</span> pointers.</li> + <li> + To trace the method calls into a <span class="classname">HOAConsumer</span> or <span class="classname">HOAIntermediate</span>, + wrap it into a <a href="http://automata.tools//hoa/cpphoafparser/docs/api-html/classcpphoafparser_1_1_h_o_a_intermediate_trace.html"><span class="classname">HOAIntermediateTrace</span></a> + object. This will print all the function invocations to the standard output, including the parameters. + </li> +</ul> + +<hr> +<p>If you have further questions, find bugs or want to tell +us about your use of the cpphoafparser library, please feel free to contact us!</p> + +<p>(c) 2015-2016 +Joachim Klein <klein@tcs.inf.tu-dresden.de>, +David Müller <david.mueller@tcs.inf.tu-dresden.de> + +</body> +</html> diff --git a/resources/3rdparty/cpphoafparser-0.99.2/docs/cpphoafparser.css b/resources/3rdparty/cpphoafparser-0.99.2/docs/cpphoafparser.css new file mode 100644 index 000000000..65f138dfc --- /dev/null +++ b/resources/3rdparty/cpphoafparser-0.99.2/docs/cpphoafparser.css @@ -0,0 +1,110 @@ +body {font-family:sans-serif; + margin: auto; + max-width: 60em; + text-align: justify; + line-height: 1.4; + font-size: 1em; +} + +div.nav { margin-top:1em; position: absolute; top:0em; left:0em} +a.nav {text-decoration: none; color:grey; margin:1em} + +.prog { + font-weight: bold; + font-family: monospace; + font-size: larger; +} + +.cmdline { + font-weight: normal; + font-family: monospace; + font-size: larger; +} + +.classname { + font-weight: normal; + font-family: monospace; + font-size: larger; +} + +.alert { + background-color: #ffd0d0; + border: 1px solid #c0d0d0; +} + +h1 { + padding-top: 1em; + border-bottom: 3px solid #4F8BAB; + text-align: center; +} + +h2 { + background-color: #6FC5EB; + padding: 0.3em; + margin-left: -.5em; + margin-right: -.5em; + margin-top: 2em; + border: 1px solid grey; + border-radius: 0.2em; +} + +h3 { + background-color: #E0F0FF; + padding: 0.3em; + margin-left: -0.5em; + margin-top: 2em; + border: 1px solid black; + border-radius: 0.2em; +} + +.blue1 { color: #4F8BAB; } +.blue2 { color: #4F9BC9; } +.blue3 { color: #64B3DF; } + +:link, :visited { color: #4f4fe0; text-decoration: none } + +a.explanationref {font-size:70%; vertical-align: super} +div.block { + margin-left: 2em; + margin-right: 2em; + padding: 0.5em; + border: 1px solid blue; + margin-bottom: 1em; +} + +li { + padding-bottom: 0.5em; +} + + +pre { + font-size: 120% +} + +pre.command { + background-color: #f0f0f0; + margin: 1em 2em; + padding: 0.5em 0em 0.5em 2em; + border-radius: 0.15em; +} + +pre.commandWithOutput { + background-color: #f0f0f0; + margin: 1em 2em 0em 2em; + padding: 0.5em 0em 0.5em 2em; + border-radius: 0.15em; +} + + +pre.output { + background-color: #e0e0e0; + margin: 0em 2em 1em 3em; + padding: 0.5em 0em 0.5em 2em; + border-radius: 0.15em; +} + + +div.code { + margin: 0.5em; padding: 0.5em; border: 1px solid #c0c0c0; +} + diff --git a/resources/3rdparty/cpphoafparser-0.99.2/docs/index.html b/resources/3rdparty/cpphoafparser-0.99.2/docs/index.html new file mode 100644 index 000000000..a94cc49fd --- /dev/null +++ b/resources/3rdparty/cpphoafparser-0.99.2/docs/index.html @@ -0,0 +1,145 @@ +<!DOCTYPE HTML> +<html> +<head> +<meta http-equiv="content-type" content="text/html; charset=utf-8"> +<link href="cpphoafparser.css" rel="stylesheet"> +<title>The cpphoafparser Library for the Hanoi Omega-Automata Format (HOAF): Documentation (version 0.99.2)</title> +</head> + +<body> +<div class="nav"></div> + +<h1> +The <span class="blue1">cpp</span><span class="blue2">hoaf</span><span class="blue3">parser</span> Library +for the <br>Hanoi Omega-Automata Format (HOAF):<br/> Documentation (version 0.99.2) +</h1> + +<h2><a name="overview">Overview</a></h2> + +<p>The <a href="http://adl.github.io/hoaf/">Hanoi Omega-Automata +Format (HOAF)</a> +provides a flexible and robust mechanism for exchanging +ω-automata between different tools. +With the <span class="prog">cpphoafparser</span> library, we provide (1) +a C++-based parser library for parsing HOA files that can be used +by applications and tools that want to read HOA files and (2) a +command-line tool for performing basic automata operations. +</p> + +<p>You can find the most current version of the library at +<a href="http://automata.tools/hoa/cpphoafparser/">http://automata.tools/hoa/cpphoafparser/</a>, +as well as links to example automata. +</p> + +<p>If you are interested in a Java-based variant of this library, +check out <a href="http://automata.tools/hoa/jhoafparser/">jhoafparser</a>. +<span class="prog">cpphoafparser</span> and <span class="prog">jhoafparser</span> +share the same design, but may differ in some of the features that are implemented. +</p> + +<p><span class="prog">cpphoafparser</span> is free software and +released under the terms of the GNU Lesser General Public License, version 2.1.</p> + +<h2>The Command-Line Tool</h2> + +<h3>The Command-Line Tool: First Steps</h3> +<p> +We assume here that you have downloaded the source code archive from the website and built the tool +using</p> +<pre class="command"> +make +</pre> +which allows you to invoke the tool via +</p> +<pre class="command"> +./cpphoaf +</pre> + +<p>Alternatively, you have downloaded a precompiled <span class="prog">cpphoaf</span> binary from the website.</p> + +<p> +Here are some examples for the command-line <span class="prog">cpphoaf</span> tool: +</p> + +<p><b>Parsing (validating) an automaton in HOA format</b></p> + +<pre class="command"> +./cpphoaf parse automaton-file.hoa +</pre> +<p> +Some of the semantic validations can be disabled by the command-line option +<span class="cmdline">--no-validate</span>. +</p> + +<p><b>Printing an automaton in HOA format</b> to standard output</p> +<pre class="command"> +./cpphoaf print automaton-file.hoa +</pre> + +<p><b>Resolving aliases</b></p> +<pre class="command"> +./cpphoaf print --resolve-aliases automaton-file.hoa +</pre> + +<h3>The Command-Line Tool: Further information</h3> +<p> +Further details on the command-line tool can be found <a href="cpphoaf-tool.html">here</a>.</p> + +<h2>The HOA Parser Library</h2> + +<p>The <span class="prog">cpphoafparser</span> library can also be used to parse HOA automata. +For example, you might want to read such automata in a tool or +you might want to implement your own automata transformations. +</p> + +<p> +As a first step, download the source code of the library from the +<a href="http://automata.tools/hoa/cpphoafparser/">website</a>. +Then, build a local copy of the API documentation with the <a href="http://www.doxygen.org">Doxygen</a> tool: +</p> +<pre class="command"> +doxygen Doxyfile +</pre> +<p>This produces the API documentation in the <span class="cmdline">docs/api-html</span> subdirectory. +The alternative <span class="classname">Doxyfile.all</span> configuration file produces documentation for all +the private/implementation details as well. If you do not have the <a href="http://www.graphviz.org/">dot</a> utility +installed, set <span class="classname">HAVE_DOT = NO</span> in <span class="classname">Doxyfile</span>. +</p> +<p> +The API documentation of the current version of the library is available as well on the website at +<a href="http://automata.tools/hoa/cpphoafparser/docs/api-html/">http://automata.tools/hoa/cpphoafparser/docs/api-html/</a>. +</p> + +<p> +A good starting point is the API documentation of the <span class="classname">HOAConsumer</span> +interface and the source code of <span class="classname">src/cpphoaf.cc</span>, +where you can see how the parser is invoked. +To parse automata using the cpphoafparser library, +an application provides the parser with a class which implements the <span class="cmdline">HOAConsumer</span> interface. +The parser then invokes the functions corresponding to the element in the HOA file format while parsing the automaton. +</p> + +<h3>The Parser Library: Further information</h3> + +<p>More details and an overview over the cpphoafparser architecture can be found <a href="cpphoafparser-library.html">here</a>. + +<h2><a name="links">Additional links</a></h2> + +<ul> + <li>The <a href="http://adl.github.io/hoaf/">specification</a> of the Hanoi Omega-Automata Format (HOAF). + </li> + <li>A <a href="http://adl.github.io/hoaf/support.html">page listing tools</a> that support HOAF.</li> + <li>A <a href="https://github.com/adl/hoaf-tests">GitHub repository with HOA automata for testing</a>.</li> +</ul> + + +<hr> +<p>If you have further questions, find bugs or want to tell +us about your use of the cpphoafparser library, please feel free to contact us!</p> + +<p>(c) 2015-2016 +Joachim Klein <klein@tcs.inf.tu-dresden.de>, +David Müller <david.mueller@tcs.inf.tu-dresden.de> + +</body> +</html> diff --git a/resources/3rdparty/cpphoafparser-0.99.2/include/cpphoafparser/ast/atom_acceptance.hh b/resources/3rdparty/cpphoafparser-0.99.2/include/cpphoafparser/ast/atom_acceptance.hh new file mode 100644 index 000000000..f5022020c --- /dev/null +++ b/resources/3rdparty/cpphoafparser-0.99.2/include/cpphoafparser/ast/atom_acceptance.hh @@ -0,0 +1,115 @@ +//============================================================================== +// +// Copyright (c) 2015- +// Authors: +// * Joachim Klein <klein@tcs.inf.tu-dresden.de> +// * David Mueller <david.mueller@tcs.inf.tu-dresden.de> +// +//------------------------------------------------------------------------------ +// +// This file is part of the cpphoafparser library, +// http://automata.tools/hoa/cpphoafparser/ +// +// The cpphoafparser 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. +// +// The cpphoafparser 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 CPPHOAFPARSER_ATOMACCEPTANCE_H +#define CPPHOAFPARSER_ATOMACCEPTANCE_H + +#include <memory> +#include <iostream> + +namespace cpphoafparser { + +/** + * Atom of an acceptance condition, either Fin(accSet), Fin(!accSet), Inf(accSet) or Inf(!accSet) + */ +class AtomAcceptance { +public: + /** A shared_ptr wrapping an AtomAcceptance */ + typedef std::shared_ptr<AtomAcceptance> ptr; + + /** The type of the temporal operator (Fin / Inf) */ + enum AtomType {TEMPORAL_FIN, TEMPORAL_INF}; + + /** + * Constructor. + * @param kind the type of the temporal operator (Fin / Inf) + * @param accSet the acceptance set index + * @param negated is the acceptance set negated? + **/ + AtomAcceptance(AtomType kind, unsigned int accSet, bool negated) + : kind(kind), accSet(accSet), negated(negated) { + } + + /** Static constructor for a Fin(accSet) atom. */ + static ptr Fin(unsigned int accSet) { + return ptr(new AtomAcceptance(TEMPORAL_FIN, accSet, false)); + } + + /** Static constructor for a Fin(!accSet) atom. */ + static ptr FinNot(unsigned int accSet) { + return ptr(new AtomAcceptance(TEMPORAL_FIN, accSet, true)); + } + + /** Static constructor for an Inf(accSet) atom. */ + static ptr Inf(unsigned int accSet) { + return ptr(new AtomAcceptance(TEMPORAL_INF, accSet, false)); + } + + /** Static constructor for a Inf(!accSet) atom. */ + static ptr InfNot(unsigned int accSet) { + return ptr(new AtomAcceptance(TEMPORAL_INF, accSet, true)); + } + + /** Get the temporal operator type of this atom. */ + AtomType getType() const {return kind;} + /** Get the acceptance set index of this atom. */ + unsigned int getAcceptanceSet() const {return accSet;} + /** Is the acceptance set negated? */ + bool isNegated() const {return negated;} + + /** Output operator, renders atom in HOA syntax */ + friend std::ostream& operator<<(std::ostream& out, const AtomAcceptance& atom) { + out << (atom.kind == TEMPORAL_FIN ? "Fin" : "Inf"); + out << "("; + if (atom.negated) out << "!"; + out << atom.accSet; + out << ")"; + return out; + } + + /** Equality operator */ + bool operator==(const AtomAcceptance& other) const { + return + this->kind == other.kind && + this->accSet == other.accSet && + this->negated == other.negated; + } + +private: + /** The temporal operator of this atom */ + AtomType kind; + /** The acceptance set index of this atom */ + unsigned int accSet; + /** Is the acceptance set negated? */ + bool negated; +}; + +} + +#endif diff --git a/resources/3rdparty/cpphoafparser-0.99.2/include/cpphoafparser/ast/atom_label.hh b/resources/3rdparty/cpphoafparser-0.99.2/include/cpphoafparser/ast/atom_label.hh new file mode 100644 index 000000000..dcc852c79 --- /dev/null +++ b/resources/3rdparty/cpphoafparser-0.99.2/include/cpphoafparser/ast/atom_label.hh @@ -0,0 +1,120 @@ +//============================================================================== +// +// Copyright (c) 2015- +// Authors: +// * Joachim Klein <klein@tcs.inf.tu-dresden.de> +// * David Mueller <david.mueller@tcs.inf.tu-dresden.de> +// +//------------------------------------------------------------------------------ +// +// This file is part of the cpphoafparser library, +// http://automata.tools/hoa/cpphoafparser/ +// +// The cpphoafparser 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. +// +// The cpphoafparser 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 CPPHOAFPARSER_ATOMLABEL_HH +#define CPPHOAFPARSER_ATOMLABEL_HH + +#include <memory> +#include <string> +#include <iostream> + +namespace cpphoafparser { + +/** + * Atom of a label expression (either an atomic proposition index or an alias reference) + */ +class AtomLabel { +public: + /** A shared_ptr wrapping an AtomLabel */ + typedef std::shared_ptr<AtomLabel> ptr; + + /** Static constructor for an atomic proposition atom */ + static AtomLabel::ptr createAPIndex(unsigned int apIndex) { + return AtomLabel::ptr(new AtomLabel(apIndex)); + } + + /** Static constructor for an alias reference (name has to be without leading @) */ + static AtomLabel::ptr createAlias(const std::string name) { + return AtomLabel::ptr(new AtomLabel(name)); + } + + /** Copy constructor. */ + AtomLabel(const AtomLabel& other) : apIndex(0), aliasName(nullptr) { + if (other.isAlias()) { + aliasName = std::shared_ptr<std::string>(new std::string(*other.aliasName)); + } else { + apIndex = other.apIndex; + } + } + + /** Returns true if this atom is an alias reference */ + bool isAlias() const {return (bool)aliasName;} + + /** + * Returns the alias name (for an alias reference atom). + * May only be called if `isAlias() == true`. + */ + const std::string& getAliasName() const { + if (!isAlias()) {throw std::logic_error("Illegal access");} + return *aliasName; + } + + /** + * Returns the atomic proposition index (for an AP atom). + * May only be called if `isAlias() == false`. + */ + unsigned int getAPIndex() const { + if (isAlias()) {throw std::logic_error("Illegal access");} + return apIndex; + } + + /** Output operator, renders in HOA syntax */ + friend std::ostream& operator<<(std::ostream& out, const AtomLabel& atom) { + if (atom.isAlias()) { + out << "@" << *atom.aliasName; + } else { + out << atom.apIndex; + } + return out; + } + + /** Equality operator. */ + bool operator==(const AtomLabel& other) const { + if (isAlias()) { + return other.isAlias() && getAliasName() == other.getAliasName(); + } else { + return !other.isAlias() && getAPIndex() == other.getAPIndex(); + } + } + + +private: + /** The AP index (if applicable) */ + unsigned int apIndex; + /** The aliasName (empty pointer if AP atom) */ + std::shared_ptr<std::string> aliasName; + + /** Private constructor (AP atom) */ + AtomLabel(unsigned int apIndex) : apIndex(apIndex), aliasName(nullptr) {} + /** Private constructor (alias reference atom) */ + AtomLabel(const std::string& name) : apIndex(0), aliasName(new std::string(name)) {} +}; + +} + +#endif diff --git a/resources/3rdparty/cpphoafparser-0.99.2/include/cpphoafparser/ast/boolean_expression.hh b/resources/3rdparty/cpphoafparser-0.99.2/include/cpphoafparser/ast/boolean_expression.hh new file mode 100644 index 000000000..b173d6013 --- /dev/null +++ b/resources/3rdparty/cpphoafparser-0.99.2/include/cpphoafparser/ast/boolean_expression.hh @@ -0,0 +1,302 @@ +//============================================================================== +// +// Copyright (c) 2015- +// Authors: +// * Joachim Klein <klein@tcs.inf.tu-dresden.de> +// * David Mueller <david.mueller@tcs.inf.tu-dresden.de> +// +//------------------------------------------------------------------------------ +// +// This file is part of the cpphoafparser library, +// http://automata.tools/hoa/cpphoafparser/ +// +// The cpphoafparser 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. +// +// The cpphoafparser 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 CPPHOAFPARSER_BOOLEANEXPRESSION_H +#define CPPHOAFPARSER_BOOLEANEXPRESSION_H + +#include <memory> +#include <iostream> +#include <sstream> +#include <stdexcept> + +namespace cpphoafparser { + +/** + * This represents (a node of) an abstract syntax tree + * of a boolean expression, parametrized with the type + * of leaf nodes (atoms). + * + * The nodes are designed to be immutable, which allows + * sharing of subexpression in a safe way between multiple + * trees. + * + * For unary operator (NOT), the child is stored as the + * left child of the not. + * + * With AtomLabel, this represents a label expression + * over atomic propositions, with AtomAcceptance an + * expression of Fin/Inf acceptance conditions. + * + * @tparam <Atoms> The atoms (leaf nodes) in the abstract syntax tree. + */ +template <typename Atoms> +class BooleanExpression { +public: + /** A shared_ptr to a node in this AST */ + typedef std::shared_ptr< BooleanExpression<Atoms> > ptr; + /** A shared_ptr to an atom (leaf node) in this AST */ + typedef std::shared_ptr< Atoms> atom_ptr; + + /** The node types of this AST */ + enum OperatorType { + EXP_AND, + EXP_OR, + EXP_NOT, + EXP_TRUE, + EXP_FALSE, + EXP_ATOM + }; + + /** Get the node type for this node */ + OperatorType getType() { + return kind; + } + + /** Static constructor for a node representing a TRUE leaf */ + static ptr True() {return ptr(new BooleanExpression(true));} + /** Static constructor for a node representing a FALSE leaf */ + static ptr False() {return ptr(new BooleanExpression(false));} + /** Static constructor for a node representing an atom leaf */ + static ptr Atom(atom_ptr atom) {return ptr(new BooleanExpression(atom));} + + /** + * Constructor for a node, providing the type and left and right child nodes. + * + * For unary operators, the `right` node should be an empty pointer. + **/ + BooleanExpression(OperatorType kind, ptr left, ptr right) : + kind(kind), left(left), right(right), atom(nullptr) { + } + + /** + * Constructor for a TRUE/FALSE leaf node. + */ + BooleanExpression(bool value) : + left(nullptr), right(nullptr), atom(nullptr) { + if (value) { + kind = EXP_TRUE; + } else { + kind = EXP_FALSE; + } + } + + /** Constructor for an atom node */ + BooleanExpression(atom_ptr atom) : + kind(EXP_ATOM), left(nullptr), right(nullptr), atom(atom) { + } + + /** Constructor for an atom node (copies atom) */ + BooleanExpression(const Atoms& atom) : + kind(EXP_ATOM), left(nullptr), right(nullptr), atom(new Atoms(atom)) { + } + + /** Perform a deep copy (recursive) of this AST and return the result */ + ptr deepCopy() { + switch (kind) { + case EXP_AND: + return ptr(new BooleanExpression(EXP_AND, left->deepCopy(), right->deepCopy())); + case EXP_OR: + return ptr(new BooleanExpression(EXP_OR, left->deepCopy(), right->deepCopy())); + case EXP_NOT: + return ptr(new BooleanExpression(EXP_NOT, left->deepCopy(), nullptr)); + case EXP_TRUE: + return True(); + case EXP_FALSE: + return False(); + case EXP_ATOM: + return ptr(new BooleanExpression(*atom)); + } + throw std::logic_error("Unsupported operator"); + } + + /** Get the left child node (might be an empty pointer) */ + ptr getLeft() const {return left;} + /** Get the right child node (might be an empty pointer) */ + ptr getRight() const {return right;} + /** Get the atom for an EXP_ATOM node. May only be called if `isAtom() == true` */ + const Atoms& getAtom() const { + if (!isAtom()) throw std::logic_error("Illegal access"); + return *atom; + } + + /** Returns true if this node is an EXP_AND node */ + bool isAND() const {return kind==EXP_AND;} + /** Returns true if this node is an EXP_OR node */ + bool isOR() const {return kind==EXP_OR;} + /** Returns true if this node is an EXP_NOT node */ + bool isNOT() const {return kind==EXP_NOT;} + /** Returns true if this node is an EXP_TRUE node */ + bool isTRUE() const {return kind==EXP_TRUE;} + /** Returns true if this node is an EXP_FALSE node */ + bool isFALSE() const {return kind==EXP_FALSE;} + /** Returns true if this node is an EXP_ATOM node */ + bool isAtom() const {return kind==EXP_ATOM;} + + /** Conjunction operator */ + friend ptr operator&(ptr left, ptr right) { + return ptr(new BooleanExpression<Atoms>(EXP_AND, left, right)); + } + + /** Disjunction operator */ + friend ptr operator|(ptr left, ptr right) { + return ptr(new BooleanExpression<Atoms>(EXP_OR, left, right)); + } + + /** Negation operator */ + friend ptr operator!(ptr other) { + return ptr(new BooleanExpression<Atoms>(EXP_NOT, other, nullptr)); + } + + /** Output operator, renders in HOA syntax */ + friend std::ostream& operator<<(std::ostream& out, const BooleanExpression<Atoms>& expr) { + switch (expr.kind) { + case EXP_AND: { + bool paren = expr.left->needsParentheses(EXP_AND); + if (paren) out << "("; + out << *expr.left; + if (paren) out << ")"; + + out << " & "; + + paren = expr.right->needsParentheses(EXP_AND); + if (paren) out << "("; + out << *expr.right; + if (paren) out << ")"; + return out; + } + case EXP_OR: { + bool paren = expr.left->needsParentheses(EXP_OR); + if (paren) out << "("; + out << *expr.left; + if (paren) out << ")"; + + out << " | "; + + paren = expr.right->needsParentheses(EXP_OR); + if (paren) out << "("; + out << *expr.right; + if (paren) out << ")"; + return out; + } + case EXP_NOT: { + bool paren = expr.left->needsParentheses(EXP_NOT); + out << "!"; + if (paren) out << "("; + out << *expr.left; + if (paren) out << ")"; + return out; + } + case EXP_TRUE: + out << "t"; + return out; + case EXP_FALSE: + out << "f"; + return out; + case EXP_ATOM: + out << *(expr.atom); + return out; + } + throw std::logic_error("Unhandled operator"); + } + + /** Return a string representation of this AST (HOA syntax) */ + std::string toString() const { + std::stringstream ss; + ss << *this; + return ss.str(); + } + + /** + * Returns `true` if `expr1` and `expr2` are syntactically equal. + * Two AST are syntactically equal if the trees match and the + * atoms are equal. + */ + static bool areSyntacticallyEqual(ptr expr1, ptr expr2) + { + if (!expr1.get() || !expr2.get()) return false; + if (expr1->getType() != expr2->getType()) return false; + + switch (expr1->getType()) { + case EXP_TRUE: + case EXP_FALSE: + return true; + case EXP_AND: + case EXP_OR: + if (!areSyntacticallyEqual(expr1->getLeft(), expr2->getLeft())) return false; + if (!areSyntacticallyEqual(expr1->getRight(), expr2->getRight())) return false; + return true; + case EXP_NOT: + if (!areSyntacticallyEqual(expr1->getLeft(), expr2->getLeft())) return false; + return true; + case EXP_ATOM: + return expr1->getAtom() == expr2->getAtom(); + } + throw std::logic_error("Unknown operator in expression: "+expr1->toString()); +} + +private: + /** The node type */ + OperatorType kind; + /** The left child (if applicable) */ + ptr left; + /** The right child (if applicable) */ + ptr right; + /** The atom (if applicable) */ + atom_ptr atom; + + /** + * Returns true if outputing this node in infix syntax needs parentheses, + * if the operator above is of `enclosingType` + */ + bool needsParentheses(OperatorType enclosingType) const { + switch (kind) { + case EXP_ATOM: + case EXP_TRUE: + case EXP_FALSE: + return false; + case EXP_AND: + if (enclosingType==EXP_NOT) return true; + if (enclosingType==EXP_AND) return false; + if (enclosingType==EXP_OR) return false; + break; + case EXP_OR: + if (enclosingType==EXP_NOT) return true; + if (enclosingType==EXP_AND) return true; + if (enclosingType==EXP_OR) return false; + break; + case EXP_NOT: + return false; + } + throw std::logic_error("Unhandled operator"); + } + +}; + +} + +#endif diff --git a/resources/3rdparty/cpphoafparser-0.99.2/include/cpphoafparser/consumer/hoa_consumer.hh b/resources/3rdparty/cpphoafparser-0.99.2/include/cpphoafparser/consumer/hoa_consumer.hh new file mode 100644 index 000000000..52800e351 --- /dev/null +++ b/resources/3rdparty/cpphoafparser-0.99.2/include/cpphoafparser/consumer/hoa_consumer.hh @@ -0,0 +1,218 @@ +//============================================================================== +// +// Copyright (c) 2015- +// Authors: +// * Joachim Klein <klein@tcs.inf.tu-dresden.de> +// * David Mueller <david.mueller@tcs.inf.tu-dresden.de> +// +//------------------------------------------------------------------------------ +// +// This file is part of the cpphoafparser library, +// http://automata.tools/hoa/cpphoafparser/ +// +// The cpphoafparser 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. +// +// The cpphoafparser 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 CPPHOAFPARSER_HOACONSUMER_H +#define CPPHOAFPARSER_HOACONSUMER_H + +#include <vector> +#include <memory> + +#include "cpphoafparser/ast/boolean_expression.hh" +#include "cpphoafparser/ast/atom_label.hh" +#include "cpphoafparser/ast/atom_acceptance.hh" +#include "cpphoafparser/util/int_or_string.hh" + +#include "cpphoafparser/consumer/hoa_consumer_exception.hh" + +namespace cpphoafparser { + +/** + * Abstract class defining the interface for consuming parse events generated by HOAParser. + * + * The HOAConsumer abstract class is the basic means of interacting with the parser and + * the other infrastructure provided by cpphoafparser. + * + * Most of the functions in this class correspond to the various events that happen + * during parsing of a HOA input, e.g., marking the occurrence of the various header + * elements, the start of the automaton body, the states and edges, etc. + * In the documentation for each function, additional information is provided whether + * the corresponding element in a HOA input is considered optional or mandatory and + * whether it can occur once or multiple times. For error handling, a consumer is + * supposed to throw HOAConsumerException. + * + * Additionally, the consumer can indicate to the parser that aliases + * have to be resolved before invoking any of the event methods in the consumer. + * + * To chain HOAConsumers, see the HOAIntermediate interface. + */ +class HOAConsumer { +public: + /** A shared_ptr wrapping a HOAConsumer */ + typedef std::shared_ptr<HOAConsumer> ptr; + /** A label expression */ + typedef BooleanExpression<AtomLabel> label_expr; + /** An acceptance expression */ + typedef BooleanExpression<AtomAcceptance> acceptance_expr; + /** A list of integers */ + typedef std::vector<unsigned int> int_list; + + /** Destructor */ + virtual ~HOAConsumer() {} + + /** + * This function is called by the parser to query the consumer whether aliases should be + * resolved by the parser (return `true` or whether the consumer would like to + * see the aliases unresolved (return `false`). This function should always return + * a constant value. + **/ + virtual bool parserResolvesAliases() = 0; + + /** Called by the parser for the "HOA: version" item [mandatory, once]. */ + virtual void notifyHeaderStart(const std::string& version) = 0; + + /** Called by the parser for the "States: int(numberOfStates)" item [optional, once]. */ + virtual void setNumberOfStates(unsigned int numberOfStates) = 0; + + /** + * Called by the parser for each "Start: state-conj" item [optional, multiple]. + * @param stateConjunction a list of state indizes, interpreted as a conjunction + **/ + virtual void addStartStates(const int_list& stateConjunction) = 0; + + /** + * Called by the parser for each "Alias: alias-def" item [optional, multiple]. + * Will be called no matter the return value of `parserResolvesAliases()`. + * + * @param name the alias name (without @) + * @param labelExpr a boolean expression over labels + **/ + virtual void addAlias(const std::string& name, label_expr::ptr labelExpr) = 0; + + /** + * Called by the parser for the "AP: ap-def" item [optional, once]. + * @param aps the list of atomic propositions + */ + virtual void setAPs(const std::vector<std::string>& aps) = 0; + + /** + * Called by the parser for the "Acceptance: acceptance-def" item [mandatory, once]. + * @param numberOfSets the number of acceptance sets used to tag state / transition acceptance + * @param accExpr a boolean expression over acceptance atoms + **/ + virtual void setAcceptanceCondition(unsigned int numberOfSets, acceptance_expr::ptr accExpr) = 0; + + /** + * Called by the parser for each "acc-name: ..." item [optional, multiple]. + * @param name the provided name + * @param extraInfo the additional information for this item + * */ + virtual void provideAcceptanceName(const std::string& name, const std::vector<IntOrString>& extraInfo) = 0; + + /** + * Called by the parser for the "name: ..." item [optional, once]. + **/ + virtual void setName(const std::string& name) = 0; + + /** + * Called by the parser for the "tool: ..." item [optional, once]. + * @param name the tool name + * @param version the tool version (option, empty pointer if not provided) + **/ + virtual void setTool(const std::string& name, std::shared_ptr<std::string> version) = 0; + + /** + * Called by the parser for the "properties: ..." item [optional, multiple]. + * @param properties a list of properties + */ + virtual void addProperties(const std::vector<std::string>& properties) = 0; + + /** + * Called by the parser for each unknown header item [optional, multiple]. + * @param name the name of the header (without ':') + * @param content a list of extra information provided by the header + */ + virtual void addMiscHeader(const std::string& name, const std::vector<IntOrString>& content) = 0; + + /** + * Called by the parser to notify that the BODY of the automaton has started [mandatory, once]. + */ + virtual void notifyBodyStart() = 0; + + /** + * Called by the parser for each "State: ..." item [multiple]. + * @param id the identifier for this state + * @param info an optional string providing additional information about the state (empty pointer if not provided) + * @param labelExpr an optional boolean expression over labels (state-labeled) (empty pointer if not provided) + * @param accSignature an optional list of acceptance set indizes (state-labeled acceptance) (empty pointer if not provided) + */ + virtual void addState(unsigned int id, std::shared_ptr<std::string> info, label_expr::ptr labelExpr, std::shared_ptr<int_list> accSignature) = 0; + + /** + * Called by the parser for each implicit edge definition [multiple], i.e., + * where the edge label is deduced from the index of the edge. + * + * If the edges are provided in implicit form, after every `addState()` there should be 2^|AP| calls to + * `addEdgeImplicit`. The corresponding boolean expression over labels / BitSet + * can be obtained by calling BooleanExpression.fromImplicit(i-1) for the i-th call of this function per state. + * + * @param stateId the index of the 'from' state + * @param conjSuccessors a list of successor state indizes, interpreted as a conjunction + * @param accSignature an optional list of acceptance set indizes (transition-labeled acceptance) (empty pointer if not provided) + */ + virtual void addEdgeImplicit(unsigned int stateId, const int_list& conjSuccessors, std::shared_ptr<int_list> accSignature) = 0; + + /** + * Called by the parser for each explicit edge definition [optional, multiple], i.e., + * where the label is either specified for the edge or as a state-label. + * <br/> + * @param stateId the index of the 'from' state + * @param labelExpr a boolean expression over labels (empty pointer if none provided, only in case of state-labeled states) + * @param conjSuccessors a list of successors state indizes, interpreted as a conjunction + * @param accSignature an optional list of acceptance set indizes (transition-labeled acceptance) (empty pointer if none provided) + */ + virtual void addEdgeWithLabel(unsigned int stateId, label_expr::ptr labelExpr, const int_list& conjSuccessors, std::shared_ptr<int_list> accSignature) = 0; + + /** + * Called by the parser to notify the consumer that the definition for state `stateId` + * has ended [multiple]. + */ + virtual void notifyEndOfState(unsigned int stateId) = 0; + + /** + * Called by the parser to notify the consumer that the automata definition has ended [mandatory, once]. + */ + virtual void notifyEnd() = 0; + + /** + * Called by the parser to notify the consumer that an "ABORT" message has been encountered + * (at any time, indicating error, the automaton should be discarded). + */ + virtual void notifyAbort() = 0; + + + /** + * Is called whenever a condition is encountered that merits a (non-fatal) warning. + * The consumer is free to handle this situation as it wishes. + */ + virtual void notifyWarning(const std::string& warning) = 0; + +}; + +} + +#endif diff --git a/resources/3rdparty/cpphoafparser-0.99.2/include/cpphoafparser/consumer/hoa_consumer_exception.hh b/resources/3rdparty/cpphoafparser-0.99.2/include/cpphoafparser/consumer/hoa_consumer_exception.hh new file mode 100644 index 000000000..2fcc8bff0 --- /dev/null +++ b/resources/3rdparty/cpphoafparser-0.99.2/include/cpphoafparser/consumer/hoa_consumer_exception.hh @@ -0,0 +1,48 @@ +//============================================================================== +// +// Copyright (c) 2015- +// Authors: +// * Joachim Klein <klein@tcs.inf.tu-dresden.de> +// * David Mueller <david.mueller@tcs.inf.tu-dresden.de> +// +//------------------------------------------------------------------------------ +// +// This file is part of the cpphoafparser library, +// http://automata.tools/hoa/cpphoafparser/ +// +// The cpphoafparser 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. +// +// The cpphoafparser 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 CPPHOAFPARSER_HOACONSUMEREXCEPTION_H +#define CPPHOAFPARSER_HOACONSUMEREXCEPTION_H + +#include <stdexcept> + +namespace cpphoafparser { + +/** + * An exception that allows a HOAConsumer or HOAIntermediate + * to signal that an error has occurred. + */ +class HOAConsumerException : public std::runtime_error { +public: + /** Constructor */ + HOAConsumerException(const std::string& what) : std::runtime_error(what) {} +}; + +} + +#endif diff --git a/resources/3rdparty/cpphoafparser-0.99.2/include/cpphoafparser/consumer/hoa_consumer_null.hh b/resources/3rdparty/cpphoafparser-0.99.2/include/cpphoafparser/consumer/hoa_consumer_null.hh new file mode 100644 index 000000000..de9101c98 --- /dev/null +++ b/resources/3rdparty/cpphoafparser-0.99.2/include/cpphoafparser/consumer/hoa_consumer_null.hh @@ -0,0 +1,109 @@ +//============================================================================== +// +// Copyright (c) 2015- +// Authors: +// * Joachim Klein <klein@tcs.inf.tu-dresden.de> +// * David Mueller <david.mueller@tcs.inf.tu-dresden.de> +// +//------------------------------------------------------------------------------ +// +// This file is part of the cpphoafparser library, +// http://automata.tools/hoa/cpphoafparser/ +// +// The cpphoafparser 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. +// +// The cpphoafparser 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 CPPHOAFPARSER_HOACONSUMERNULL_H +#define CPPHOAFPARSER_HOACONSUMERNULL_H + +#include "cpphoafparser/consumer/hoa_consumer.hh" + + +namespace cpphoafparser { + +/** + * A no-operation HOAConsumer. + * Provides no-op implementations for all the functions required by the + * HOAConsumer interface. + */ +class HOAConsumerNull : public HOAConsumer { +public: + + virtual bool parserResolvesAliases() override { + return false; + } + + virtual void notifyHeaderStart(const std::string& version) override { + } + + virtual void setNumberOfStates(unsigned int numberOfStates) override { + } + + virtual void addStartStates(const int_list& stateConjunction) override { + } + + virtual void addAlias(const std::string& name, label_expr::ptr labelExpr) override { + } + + virtual void setAPs(const std::vector<std::string>& aps) override { + } + + virtual void setAcceptanceCondition(unsigned int numberOfSets, acceptance_expr::ptr accExpr) override { + } + + virtual void provideAcceptanceName(const std::string& name, const std::vector<IntOrString>& extraInfo) override { + } + + virtual void setName(const std::string& name) override { + } + + virtual void setTool(const std::string& name, std::shared_ptr<std::string> version) override { + } + + virtual void addProperties(const std::vector<std::string>& properties) override { + } + + virtual void addMiscHeader(const std::string& name, const std::vector<IntOrString>& content) override { + } + + virtual void notifyBodyStart() override { + } + + virtual void addState(unsigned int id, std::shared_ptr<std::string> info, label_expr::ptr labelExpr, std::shared_ptr<int_list> accSignature) override { + } + + virtual void addEdgeImplicit(unsigned int stateId, const int_list& conjSuccessors, std::shared_ptr<int_list> accSignature) override { + } + + virtual void addEdgeWithLabel(unsigned int stateId, label_expr::ptr labelExpr, const int_list& conjSuccessors, std::shared_ptr<int_list> accSignature) override { + } + + virtual void notifyEndOfState(unsigned int stateId) override { + } + + virtual void notifyEnd() override { + } + + virtual void notifyAbort() { + } + + virtual void notifyWarning(const std::string& warning) { + } +}; + +} + +#endif diff --git a/resources/3rdparty/cpphoafparser-0.99.2/include/cpphoafparser/consumer/hoa_consumer_print.hh b/resources/3rdparty/cpphoafparser-0.99.2/include/cpphoafparser/consumer/hoa_consumer_print.hh new file mode 100644 index 000000000..cf775c395 --- /dev/null +++ b/resources/3rdparty/cpphoafparser-0.99.2/include/cpphoafparser/consumer/hoa_consumer_print.hh @@ -0,0 +1,238 @@ +//============================================================================== +// +// Copyright (c) 2015- +// Authors: +// * Joachim Klein <klein@tcs.inf.tu-dresden.de> +// * David Mueller <david.mueller@tcs.inf.tu-dresden.de> +// +//------------------------------------------------------------------------------ +// +// This file is part of the cpphoafparser library, +// http://automata.tools/hoa/cpphoafparser/ +// +// The cpphoafparser 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. +// +// The cpphoafparser 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 CPPHOAFPARSER_HOACONSUMERPRINT_H +#define CPPHOAFPARSER_HOACONSUMERPRINT_H + +#include <iostream> + +#include "cpphoafparser/consumer/hoa_consumer.hh" +#include "cpphoafparser/parser/hoa_parser_helper.hh" + +namespace cpphoafparser { + +/** + * A HOAConsumer implementation that provides printing functionality. + * + * Outputs the HOA automaton corresponding to the function calls on the given output stream. + * Can be used as a "pretty-printer", as it will output the various syntax elements with + * a consistent layout of white-space and line breaks. + */ + +class HOAConsumerPrint : public HOAConsumer { +public: + + /** Constructor, providing a reference to the output stream */ + HOAConsumerPrint(std::ostream& out) : out(out) {} + + virtual bool parserResolvesAliases() override { + return false; + } + + virtual void notifyHeaderStart(const std::string& version) override { + out << "HOA: " << version << std::endl; + } + + virtual void setNumberOfStates(unsigned int numberOfStates) override { + out << "States: " << numberOfStates << std::endl; + } + + virtual void addStartStates(const int_list& stateConjunction) override { + out << "Start: "; + bool first = true; + for (unsigned int state : stateConjunction) { + if (!first) out << " & "; + first=false; + out << state; + } + out << std::endl; + } + + virtual void addAlias(const std::string& name, label_expr::ptr labelExpr) override { + out << "Alias: @" << name << " " << *labelExpr << std::endl; + } + + virtual void setAPs(const std::vector<std::string>& aps) override { + out << "AP: " << aps.size(); + for (const std::string& ap : aps) { + out << " "; + HOAParserHelper::print_quoted(out, ap); + } + out << std::endl; + } + + virtual void setAcceptanceCondition(unsigned int numberOfSets, acceptance_expr::ptr accExpr) override { + out << "Acceptance: " << numberOfSets << " " << *accExpr << std::endl; + } + + virtual void provideAcceptanceName(const std::string& name, const std::vector<IntOrString>& extraInfo) override { + out << "acc-name: " << name; + for (const IntOrString& extra : extraInfo) { + out << " " << extra; + } + out << std::endl; + } + + virtual void setName(const std::string& name) override { + out << "name: "; + HOAParserHelper::print_quoted(out, name); + out << std::endl; + } + + virtual void setTool(const std::string& name, std::shared_ptr<std::string> version) override { + out << "tool: "; + HOAParserHelper::print_quoted(out, name); + if (version) { + out << " "; + HOAParserHelper::print_quoted(out, *version); + } + out << std::endl; + } + + virtual void addProperties(const std::vector<std::string>& properties) override { + out << "properties:"; + for (const std::string& property : properties) { + out << " " << property; + } + out << std::endl; + } + + virtual void addMiscHeader(const std::string& name, const std::vector<IntOrString>& content) override { + out << name << ":"; + for (const IntOrString& extra : content) { + out << " " << extra; + } + out << std::endl; + } + + virtual void notifyBodyStart() override { + out << "--BODY--" << std::endl; + } + + virtual void addState(unsigned int id, + std::shared_ptr<std::string> info, + label_expr::ptr labelExpr, + std::shared_ptr<int_list> accSignature) override { + out << "State: "; + if (labelExpr) { + out << "[" << *labelExpr << "] "; + } + out << id; + if (info) { + out << " "; + HOAParserHelper::print_quoted(out, *info); + } + if (accSignature) { + out << " {"; + bool first = true; + for (unsigned int acc : *accSignature) { + if (!first) out << " "; + first = false; + out << acc; + } + out << "}"; + } + out << std::endl; + } + + virtual void addEdgeImplicit(unsigned int stateId, + const int_list& conjSuccessors, + std::shared_ptr<int_list> accSignature) override { + bool first = true; + for (unsigned int succ : conjSuccessors) { + if (!first) out << "&"; + first = false; + out << succ; + } + if (accSignature) { + out << " {"; + first = true; + for (unsigned int acc : *accSignature) { + if (!first) out << " "; + first = false; + out << acc; + } + out << "}"; + } + out << std::endl; + } + + virtual void addEdgeWithLabel(unsigned int stateId, + label_expr::ptr labelExpr, + const int_list& conjSuccessors, + std::shared_ptr<int_list> accSignature) override { + if (labelExpr) { + out << "[" << *labelExpr << "] "; + } + + bool first = true; + for (unsigned int succ : conjSuccessors) { + if (!first) out << "&"; + first = false; + out << succ; + } + + if (accSignature) { + out << " {"; + first = true; + for (unsigned int acc : *accSignature) { + if (!first) out << " "; + first = false; + out << acc; + } + out << "}"; + } + out << std::endl; + } + + virtual void notifyEndOfState(unsigned int stateId) override { + // nothing to do + } + + virtual void notifyEnd() override { + out << "--END--" << std::endl; + out.flush(); + } + + virtual void notifyAbort() override { + out << "--ABORT--" << std::endl; + out.flush(); + } + + virtual void notifyWarning(const std::string& warning) override { + std::cerr << "Warning: " << warning << std::endl; + } + +private: + /** Reference to the output stream */ + std::ostream& out; +}; + +} + +#endif diff --git a/resources/3rdparty/cpphoafparser-0.99.2/include/cpphoafparser/consumer/hoa_intermediate.hh b/resources/3rdparty/cpphoafparser-0.99.2/include/cpphoafparser/consumer/hoa_intermediate.hh new file mode 100644 index 000000000..f0b2dd84a --- /dev/null +++ b/resources/3rdparty/cpphoafparser-0.99.2/include/cpphoafparser/consumer/hoa_intermediate.hh @@ -0,0 +1,148 @@ +//============================================================================== +// +// Copyright (c) 2015- +// Authors: +// * Joachim Klein <klein@tcs.inf.tu-dresden.de> +// * David Mueller <david.mueller@tcs.inf.tu-dresden.de> +// +//------------------------------------------------------------------------------ +// +// This file is part of the cpphoafparser library, +// http://automata.tools/hoa/cpphoafparser/ +// +// The cpphoafparser 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. +// +// The cpphoafparser 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 CPPHOAFPARSER_HOAINTERMEDIATE_H +#define CPPHOAFPARSER_HOAINTERMEDIATE_H + +#include "cpphoafparser/consumer/hoa_consumer.hh" + +namespace cpphoafparser { + +/** + * The HOAIntermediate class provides a mechanism to chain + * multiple HOAConsumer together. + * Implementing the HOAConsumer interface, the default behavior + * is to simply propagate method calls to the `next` consumer. + * + * By overriding functions, this behavior can be customized, e.g., + * validating constraints on the input (HOAIntermediateCheckValidity) or + * performing on-the-fly transformations (HOAIntermediateResolveAliases). + */ + +class HOAIntermediate : public HOAConsumer { +public: + + /** Constructor, providing the `next` HOAConsumer */ + HOAIntermediate(HOAConsumer::ptr next) : next(next) {} + + virtual bool parserResolvesAliases() override { + return next->parserResolvesAliases(); + } + + virtual void notifyHeaderStart(const std::string& version) override { + next->notifyHeaderStart(version); + } + + virtual void setNumberOfStates(unsigned int numberOfStates) override { + next->setNumberOfStates(numberOfStates); + } + + virtual void addStartStates(const int_list& stateConjunction) override { + next->addStartStates(stateConjunction); + } + + virtual void addAlias(const std::string& name, label_expr::ptr labelExpr) override { + next->addAlias(name, labelExpr); + } + + virtual void setAPs(const std::vector<std::string>& aps) override { + next->setAPs(aps); + } + + virtual void setAcceptanceCondition(unsigned int numberOfSets, acceptance_expr::ptr accExpr) override { + next->setAcceptanceCondition(numberOfSets, accExpr); + } + + virtual void provideAcceptanceName(const std::string& name, const std::vector<IntOrString>& extraInfo) override { + next->provideAcceptanceName(name, extraInfo); + } + + virtual void setName(const std::string& name) override { + next->setName(name); + } + + virtual void setTool(const std::string& name, std::shared_ptr<std::string> version) override { + next->setTool(name, version); + } + + virtual void addProperties(const std::vector<std::string>& properties) override { + next->addProperties(properties); + } + + virtual void addMiscHeader(const std::string& name, const std::vector<IntOrString>& content) override { + next->addMiscHeader(name, content); + } + + virtual void notifyBodyStart() override { + next->notifyBodyStart(); + } + + virtual void addState(unsigned int id, + std::shared_ptr<std::string> info, + label_expr::ptr labelExpr, + std::shared_ptr<int_list> accSignature) override { + next->addState(id, info, labelExpr, accSignature); + } + + virtual void addEdgeImplicit(unsigned int stateId, + const int_list& conjSuccessors, + std::shared_ptr<int_list> accSignature) override { + next->addEdgeImplicit(stateId, conjSuccessors, accSignature); + } + + virtual void addEdgeWithLabel(unsigned int stateId, + label_expr::ptr labelExpr, + const int_list& conjSuccessors, + std::shared_ptr<int_list> accSignature) override { + next->addEdgeWithLabel(stateId, labelExpr, conjSuccessors, accSignature); + } + + virtual void notifyEndOfState(unsigned int stateId) override { + next->notifyEndOfState(stateId); + } + + virtual void notifyEnd() override { + next->notifyEnd(); + } + + virtual void notifyAbort() override { + next->notifyAbort(); + } + + virtual void notifyWarning(const std::string& warning) override { + next->notifyWarning(warning); + } + +protected: + /** The next consumer */ + HOAConsumer::ptr next; +}; + +} + +#endif diff --git a/resources/3rdparty/cpphoafparser-0.99.2/include/cpphoafparser/consumer/hoa_intermediate_check_validity.hh b/resources/3rdparty/cpphoafparser-0.99.2/include/cpphoafparser/consumer/hoa_intermediate_check_validity.hh new file mode 100644 index 000000000..9cbffefbb --- /dev/null +++ b/resources/3rdparty/cpphoafparser-0.99.2/include/cpphoafparser/consumer/hoa_intermediate_check_validity.hh @@ -0,0 +1,828 @@ +//============================================================================== +// +// Copyright (c) 2015- +// Authors: +// * Joachim Klein <klein@tcs.inf.tu-dresden.de> +// * David Mueller <david.mueller@tcs.inf.tu-dresden.de> +// +//------------------------------------------------------------------------------ +// +// This file is part of the cpphoafparser library, +// http://automata.tools/hoa/cpphoafparser/ +// +// The cpphoafparser 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. +// +// The cpphoafparser 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 CPPHOAFPARSER_HOAINTERMEDIATECHECKVALIDITY_H +#define CPPHOAFPARSER_HOAINTERMEDIATECHECKVALIDITY_H + +#include "cpphoafparser/consumer/hoa_intermediate.hh" +#include "cpphoafparser/util/dynamic_bitset.hh" +#include "cpphoafparser/util/implicit_edge_helper.hh" +#include "cpphoafparser/util/acceptance_repository_standard.hh" + +#include <unordered_set> +#include <cassert> + +namespace cpphoafparser { + +// TODO Accurately reflect status in the doc! +/** + * HOAIntermediate that checks that the parsed HOA automaton is well-formed. + * + * Among others, checks for + * <ul> + * <li>Conformance of stated properties with the automaton structure. + * <li>Conformance of Acceptance and acc-name headers. + * <li>Definedness of aliases. + * <li>Well-formedness of label expressions (only using atomic proposition indizes that are defined). + * <li>Well-formedness of acceptance (only using acceptance set indizes that are defined). + * </ul> + */ +class HOAIntermediateCheckValidity : public HOAIntermediate +{ +public: + + /** Constructor, providing the `next` HOAConsumer */ + HOAIntermediateCheckValidity(HOAConsumer::ptr next) + : HOAIntermediate(next), + implicitEdgeHelper(0) {} + + /** + * Add (semantically-relevant) headers not defined in the format specification that + * can be handled. + */ + template <class InputIterator> + void setSupportedMiscHeaders(InputIterator first, InputIterator last) { + supportedMiscHeaders.insert(first, last); + } + /** + * Add (semantically-relevant) header not defined in the format specification that + * can be handled. + */ + void addSupportedMiscHeader(const std::string& supportedMiscHeader) { + supportedMiscHeaders.insert(supportedMiscHeader); + } + + virtual bool parserResolvesAliases() override { + return next->parserResolvesAliases(); + } + + virtual void notifyHeaderStart(const std::string& version) override { + if (version != "v1") { + throw HOAConsumerException("Can only parse HOA format v1"); + } + next->notifyHeaderStart(version); + } + + virtual void setNumberOfStates(unsigned int numberOfStates) override { + headerAtMostOnce("States"); + this->numberOfStates.reset(new unsigned int(numberOfStates)); + next->setNumberOfStates(numberOfStates); + } + + virtual void addStartStates(const int_list& stateConjunction) override { + numberOfStartHeaders++; + if (stateConjunction.size()>1) { + hasUniversalBranching = true; + } + + for (unsigned int state : stateConjunction) { + checkStateIndex(state); + startStates.set(state); + } + next->addStartStates(stateConjunction); + } + + virtual void addAlias(const std::string& name, label_expr::ptr labelExpr) override { + usedHeaders.insert("Alias"); + + checkAliasesAreDefined(labelExpr); + aliases.insert(name); + + gatherLabels(labelExpr, apsInAliases); + + next->addAlias(name, labelExpr); + } + + virtual void setAPs(const std::vector<std::string>& aps) override { + headerAtMostOnce("AP"); + + numberOfAPs.reset(new unsigned int(aps.size())); + + std::unordered_set<std::string> apSet; + for (const std::string& ap : aps) { + if (apSet.insert(ap).second == false) { + throw HOAConsumerException("Atomic proposition "+ap+" appears more than once in AP-header"); + } + } + + next->setAPs(aps); + } + + virtual void setAcceptanceCondition(unsigned int numberOfSets, acceptance_expr::ptr accExpr) override { + headerAtMostOnce("Acceptance"); + numberOfAcceptanceSets.reset(new unsigned int(numberOfSets)); + + checkAcceptanceCondition(accExpr); + acceptance = accExpr->deepCopy(); + + next->setAcceptanceCondition(numberOfSets, accExpr); + } + + virtual void provideAcceptanceName(const std::string& name, const std::vector<IntOrString>& extraInfo) override { + headerAtMostOnce("acc-name"); + accName.reset(new std::string(name)); + + accExtraInfo = extraInfo; + next->provideAcceptanceName(name, extraInfo); + } + + + virtual void setName(const std::string& name) override { + headerAtMostOnce("name"); + next->setName(name); + } + + virtual void setTool(const std::string& name, std::shared_ptr<std::string> version) override { + headerAtMostOnce("tool"); + next->setTool(name, version); + } + + virtual void addProperties(const std::vector<std::string>& properties) override { + usedHeaders.insert("properties"); + + for (const std::string& property : properties) { + if (property == "state_labels") { + property_state_labels = true; + } else if (property == "trans_labels") { + property_trans_labels = true; + } else if (property == "implicit_labels") { + property_implicit_labels = true; + } else if (property == "explicit_labels") { + property_explicit_labels = true; + } else if (property == "state_acc") { + property_state_acc = true; + } else if (property == "trans_acc") { + property_trans_acc = true; + } else if (property == "univ_branch") { + property_univ_branch = true; + } else if (property == "no_univ_branch") { + property_no_univ_branch = true; + } else if (property == "deterministic") { + property_deterministic = true; + } else if (property == "complete") { + property_complete = true; + } else if (property == "colored") { + property_colored = true; + } else { + // do nothing + } + } + + next->addProperties(properties); + } + + virtual void addMiscHeader(const std::string& name, const std::vector<IntOrString>& content) override { + usedHeaders.insert(name); + if (name.at(0) >= 'A' && name.at(0) <= 'Z') { + // first character is upper case -> if we don't know what to do with this header, + // raise exception as this may change the semantics of the automaton + if (supportedMiscHeaders.find(name) != supportedMiscHeaders.end()) + throw HOAConsumerException("Header "+name+" potentially has semantic relevance, but is not supported"); + } + next->addMiscHeader(name, content); + } + + virtual void notifyBodyStart() override { + // check for existence of mandatory headers + headerIsMandatory("Acceptance"); + + // check that all AP indizes in aliases are valid + if (!numberOfAPs) { + // there was no AP-header, equivalent to AP: 0 + numberOfAPs.reset(new unsigned int(0)); + } + std::pair<std::size_t, bool> highestAPIndex = apsInAliases.getHighestSetBit(); + if (highestAPIndex.second && highestAPIndex.first >= *numberOfAPs) { + throw HOAConsumerException("AP index " + + std::to_string(highestAPIndex.first) + + " in some alias definition is out of range (0 - " + + std::to_string(*numberOfAPs-1) + +")"); + } + + if (accName) { + checkAccName(); + } + + // check whether the start states violate properties + if (property_no_univ_branch && hasUniversalBranching) { + throw HOAConsumerException("Property 'no_univ_branching' is violated by the start states"); + } + if (property_deterministic && numberOfStartHeaders != 1) { + throw HOAConsumerException("Property 'deterministic' is violated by having "+std::to_string(numberOfStartHeaders)+" Start-headers"); + } + + implicitEdgeHelper = ImplicitEdgeHelper(*numberOfAPs); + + next->notifyBodyStart(); + } + + virtual void addState(unsigned int id, std::shared_ptr<std::string> info, label_expr::ptr labelExpr, std::shared_ptr<int_list> accSignature) override { + checkStateIndex(id); + if (statesWithDefinition.get(id)) { + throw HOAConsumerException("State "+std::to_string(id)+" is defined multiple times"); + } + statesWithDefinition.set(id); + currentState = id; + + if (accSignature) { + checkAcceptanceSignature(*accSignature, false); + currentStateIsColored = (accSignature->size() == 1); + } else { + currentStateIsColored = false; + } + + if (property_colored && *numberOfAcceptanceSets>0 && !currentStateIsColored) { + if (property_state_acc) { + // we already know that the automaton is in violation... + throw HOAConsumerException("State "+std::to_string(id)+" is not colored"); + } + } + + if (labelExpr) { + checkLabelExpression(labelExpr); + } + + // reset flags + currentStateHasStateLabel = (bool)labelExpr; + currentStateHasTransitionLabel = false; + currentStateHasImplicitEdge = false; + currentStateHasExplicitEdge = false; + currentStateHasStateAcceptance = (bool)accSignature; + currentStateHasTransitionAcceptance = false; + + implicitEdgeHelper.startOfState(id); + + next->addState(id, info, labelExpr, accSignature); + } + + virtual void addEdgeImplicit(unsigned int stateId, + const int_list& conjSuccessors, + std::shared_ptr<int_list> accSignature) override { + assert(stateId == currentState); + + for (unsigned int succ : conjSuccessors) { + checkStateIndexTarget(succ); + } + + if (conjSuccessors.size() > 1) { + hasUniversalBranching = true; + } + + bool edgeIsColored = false; + if (accSignature) { + checkAcceptanceSignature(*accSignature, true); + edgeIsColored = (accSignature->size() == 1); + } + + if (property_colored && *numberOfAcceptanceSets > 0) { + if (!currentStateIsColored && !edgeIsColored) { + throw HOAConsumerException("In state "+std::to_string(stateId)+", there is a transition that is not colored..."); + } else if (currentStateIsColored && edgeIsColored) { + throw HOAConsumerException("In state "+std::to_string(stateId)+", there is a transition that is colored even though the state is colored already..."); + } + } + + if (currentStateHasExplicitEdge) { + throw HOAConsumerException("Can not mix explicit and implicit edge definitions (state "+std::to_string(stateId)+")"); + } + currentStateHasImplicitEdge = true; + + currentStateHasTransitionLabel = true; + if (currentStateHasStateLabel) { + throw new HOAConsumerException("Can not mix state labels and implicit edge definitions (state "+std::to_string(stateId)+")"); + } + + implicitEdgeHelper.nextImplicitEdge(); + next->addEdgeImplicit(stateId, conjSuccessors, accSignature); + } + + virtual void addEdgeWithLabel(unsigned int stateId, + label_expr::ptr labelExpr, + const int_list& conjSuccessors, + std::shared_ptr<int_list> accSignature) override { + assert(stateId == currentState); + + for (unsigned int succ : conjSuccessors) { + checkStateIndexTarget(succ); + } + + if (conjSuccessors.size() > 1) { + hasUniversalBranching = true; + } + + bool edgeIsColored = false; + if (accSignature) { + checkAcceptanceSignature(*accSignature, true); + edgeIsColored = (accSignature->size() == 1); + } + + if (property_colored && *numberOfAcceptanceSets > 0) { + if (!currentStateIsColored && !edgeIsColored) { + throw HOAConsumerException("In state "+std::to_string(stateId)+", there is a transition that is not colored..."); + } else if (currentStateIsColored && edgeIsColored) { + throw HOAConsumerException("In state "+std::to_string(stateId)+", there is a transition that is colored even though the state is colored already..."); + } + } + + if (labelExpr) { + checkLabelExpression(labelExpr); + } + + if (labelExpr) { + currentStateHasTransitionLabel = true; + if (currentStateHasStateLabel) { + throw HOAConsumerException("Can not mix state and transition labeling (state "+std::to_string(stateId)+")"); + } + } + + if (currentStateHasImplicitEdge) { + throw HOAConsumerException("Can not mix explicit and implicit edge definitions (state "+std::to_string(stateId)+")"); + } + currentStateHasExplicitEdge = true; + + next->addEdgeWithLabel(stateId, labelExpr, conjSuccessors, accSignature); + } + + virtual void notifyEndOfState(unsigned int stateId) override { + implicitEdgeHelper.endOfState(); + + // check for property violations + if (property_state_labels && currentStateHasTransitionLabel) { + throw HOAConsumerException("Property 'state-labels' is violated by having transition labels in state "+std::to_string(stateId)); + } + if (property_trans_labels && currentStateHasStateLabel) { + throw HOAConsumerException("Property 'trans-labels' is violated by having a state label in state "+std::to_string(stateId)); + + } + if (property_implicit_labels && currentStateHasExplicitEdge) { + throw HOAConsumerException("Property 'implicit-label' is violated by having a label expression on a transition in state "+std::to_string(stateId)); + } + if (property_explicit_labels && currentStateHasImplicitEdge) { + throw HOAConsumerException("Property 'explicit-label' is violated by having implicit transition(s) in state "+std::to_string(stateId)); + } + if (property_state_acc && currentStateHasTransitionAcceptance) { + throw HOAConsumerException("Property 'state-acc' is violated by having transition acceptance in state "+std::to_string(stateId)); + } + if (property_trans_acc && currentStateHasStateAcceptance) { + throw HOAConsumerException("Property 'trans-acc' is violated by having state acceptance in state "+std::to_string(stateId)); + } + if (property_no_univ_branch && hasUniversalBranching) { + throw HOAConsumerException("Property 'no-univ-branch' is violated by having universal branching in state "+std::to_string(stateId)); + } + + // TODO: deterministic + // for implicit edges, this is done via the ImplicitEdgeHelper + // for explicit edges, check would need to keep track of overlapping label expressions + + // TODO: complete + // for implicit edges, this is done via the ImplicitEdgeHelper + // for explicit edges, check would need to keep track of overlapping label expressions + + next->notifyEndOfState(stateId); + } + + virtual void notifyEnd() override { + // check sanity of state definitions and target states + checkStates(); + + if (property_univ_branch && !hasUniversalBranching) { + throw HOAConsumerException("Property 'univ-branch' is violated by not having universal branching in the automaton"); + } + + next->notifyEnd(); + } + + virtual void notifyAbort() override { + next->notifyAbort(); + } + +protected: + + // ---------------------------------------------------------------------------- + + /** Send a warning */ + void doWarning(const std::string& warning) + { + next->notifyWarning(warning); + } + + // ---------------------------------------------------------------------------- + + /** Check that a mandatory header has been seen */ + void headerIsMandatory(const std::string& name) + { + if (usedHeaders.find(name) == usedHeaders.end()) { + throw HOAConsumerException("Mandatory header "+name+" is missing"); + } + } + + /** Check that a 'once' header has not been seen multiple times */ + void headerAtMostOnce(const std::string& headerName) + { + if (usedHeaders.insert(headerName).second == false) { + throw HOAConsumerException("Header "+headerName+" occurs multiple times, but is allowed only once."); + } + } + + /** Check that a states index is in range */ + void checkStateIndex(unsigned int index) + { + if (numberOfStates) { + if (index >= *numberOfStates) { + throw HOAConsumerException("State index " + + std::to_string(index) + + " is out of range (0 - " + + std::to_string(*numberOfStates-1) + + ")"); + } + } + } + + /** Checks that the target state index of a transition is valid */ + void checkStateIndexTarget(unsigned int index) + { + if (numberOfStates) { + if (index >= *numberOfStates) { + throw HOAConsumerException("State index " + + std::to_string(index) + + " is out of range (0 - " + + std::to_string(*numberOfStates-1) + + ")"); + } + } + targetStatesOfTransitions.set(index); + } + + /** Check that the states have been properly defined */ + void checkStates() + { + bool haveComplainedAboutMissingStates = false; + + // if numberOfStates is set, check that all states are in range + if (numberOfStates) { + // the states with a definition + std::pair<std::size_t, bool> highestStateIndex = statesWithDefinition.getHighestSetBit(); + if (highestStateIndex.second && highestStateIndex.first >= *numberOfStates) { + throw HOAConsumerException("State index " + + std::to_string(highestStateIndex.first) + + " is out of range (0 - " + + std::to_string(*numberOfStates-1) + + ")"); + } + + // the states occurring as targets + highestStateIndex = targetStatesOfTransitions.getHighestSetBit(); + if (highestStateIndex.second && highestStateIndex.first >= *numberOfStates) { + throw HOAConsumerException("State index " + + std::to_string(highestStateIndex.first) + + " (target in a transition) is out of range (0 - " + + std::to_string(*numberOfStates-1) + +")"); + } + + // the start states + highestStateIndex = startStates.getHighestSetBit(); + if (highestStateIndex.second && highestStateIndex.first >= *numberOfStates) { + throw HOAConsumerException("State index " + + std::to_string(highestStateIndex.first) + + " (start state) is out of range (0 - " + + std::to_string(*numberOfStates-1) + +")"); + } + + if (statesWithDefinition.cardinality() != *numberOfStates) { + std::size_t missing = *numberOfStates - statesWithDefinition.cardinality(); + doWarning("There are "+std::to_string(missing)+" states without definition"); + haveComplainedAboutMissingStates = true; + } + } + + dynamic_bitset targetsButNoDefinition(targetStatesOfTransitions); + targetsButNoDefinition.andNot(statesWithDefinition); + if (!targetsButNoDefinition.isEmpty() && !haveComplainedAboutMissingStates) { + doWarning("There are " + + std::to_string(targetsButNoDefinition.cardinality()) + + " states that are targets of transitions but that have no definition"); + haveComplainedAboutMissingStates = true; + } + + dynamic_bitset startStatesButNoDefinition(startStates); + startStatesButNoDefinition.andNot(statesWithDefinition); + if (!startStatesButNoDefinition.isEmpty() && !haveComplainedAboutMissingStates) { + doWarning("There are " + + std::to_string(startStatesButNoDefinition.cardinality()) + + " states that are start states but that have no definition"); + haveComplainedAboutMissingStates = true; + } + + + if (haveComplainedAboutMissingStates && property_colored && *numberOfAcceptanceSets > 0) { + // states without definition are not colored + throw HOAConsumerException("An automaton with property 'colored' can not have states missing a definition"); + } + } + + /** + * Check that the acceptance condition is well-formed. + * In particular, that no boolean negation occurs and + * that the referenced acceptance sets are defined. + */ + void checkAcceptanceCondition(acceptance_expr::ptr accExpr) + { + assert (numberOfAcceptanceSets); + + switch (accExpr->getType()) { + case acceptance_expr::EXP_TRUE: + case acceptance_expr::EXP_FALSE: + return; + case acceptance_expr::EXP_AND: + case acceptance_expr::EXP_OR: + checkAcceptanceCondition(accExpr->getLeft()); + checkAcceptanceCondition(accExpr->getRight()); + return; + case acceptance_expr::EXP_NOT: + throw HOAConsumerException("Acceptance condition contains boolean negation, not allowed"); + case acceptance_expr::EXP_ATOM: + unsigned int acceptanceSet = accExpr->getAtom().getAcceptanceSet(); + if (acceptanceSet >= *numberOfAcceptanceSets) { + throw HOAConsumerException("Acceptance condition contains acceptance set with index " + + std::to_string(acceptanceSet) + + ", valid range is 0 - " + + std::to_string(*numberOfAcceptanceSets-1)); + } + return; + } + throw std::logic_error("Unknown operator in acceptance condition: "+accExpr->toString()); + } + + /** + * Check that an acceptance signature is well-formed. + * In particular, that the referenced acceptance sets are defined. + */ + void checkAcceptanceSignature(const int_list& accSignature, bool inTransition) + { + for (unsigned int acceptanceSet : accSignature) { + if (acceptanceSet >= *numberOfAcceptanceSets) { + throw HOAConsumerException("Acceptance signature " + + (inTransition ? std::string("(in transition) ") : std::string("")) + + "for state index " + + std::to_string(currentState) + + " contains acceptance set with index " + + std::to_string(acceptanceSet) + + ", valid range is 0 - " + + std::to_string(*numberOfAcceptanceSets-1)); + } + } + } + + /** + * Check that all alias references in a label expression are + * properly defined + */ + void checkAliasesAreDefined(label_expr::ptr expr) + { + switch (expr->getType()) { + case label_expr::EXP_TRUE: + case label_expr::EXP_FALSE: + return; + case label_expr::EXP_AND: + case label_expr::EXP_OR: + checkAliasesAreDefined(expr->getLeft()); + checkAliasesAreDefined(expr->getRight()); + return; + case label_expr::EXP_NOT: + checkAliasesAreDefined(expr->getLeft()); + return; + case label_expr::EXP_ATOM: + if (expr->getAtom().isAlias()) { + if (aliases.find(expr->getAtom().getAliasName()) != aliases.end()) { + throw HOAConsumerException("Alias @"+expr->getAtom().getAliasName()+" is not defined"); + } + } + return; + } + throw std::logic_error("Unknown operator in label expression: "+expr->toString()); + } + + /** + * Traverse the expression and, for every label encountered, set the corresponding bit in the + * `result` bitset. + * @param expr the expression + * @param[out] result a bitset where the additional bits corresponding to APs are set + */ + void gatherLabels(label_expr::ptr expr, dynamic_bitset& result) { + switch (expr->getType()) { + case label_expr::EXP_TRUE: + case label_expr::EXP_FALSE: + return; + case label_expr::EXP_AND: + case label_expr::EXP_OR: + gatherLabels(expr->getLeft(), result); + gatherLabels(expr->getRight(), result); + return; + case label_expr::EXP_NOT: + gatherLabels(expr->getLeft(), result); + return; + case label_expr::EXP_ATOM: + if (!expr->getAtom().isAlias()) { + result.set(expr->getAtom().getAPIndex()); + } + return; + } + throw std::logic_error("Unknown operator in label expression: "+expr->toString()); + } + + /** Check a label expression for well-formedness */ + void checkLabelExpression(label_expr::ptr expr) + { + switch (expr->getType()) { + case label_expr::EXP_TRUE: + case label_expr::EXP_FALSE: + return; + case label_expr::EXP_AND: + case label_expr::EXP_OR: + checkLabelExpression(expr->getLeft()); + checkLabelExpression(expr->getRight()); + return; + case label_expr::EXP_NOT: + checkLabelExpression(expr->getLeft()); + return; + case label_expr::EXP_ATOM: + if (expr->getAtom().isAlias()) { + if (aliases.find(expr->getAtom().getAliasName()) == aliases.end()) { + throw HOAConsumerException("Alias @"+expr->getAtom().getAliasName()+" is not defined"); + } + } else { + assert(numberOfAPs); + unsigned int apIndex = expr->getAtom().getAPIndex(); + if (apIndex >= *numberOfAPs) { + if (*numberOfAPs == 0) { + throw HOAConsumerException("AP index "+std::to_string(apIndex)+" in expression is out of range (no APs): "+expr->toString()); + } else { + throw HOAConsumerException("AP index " + + std::to_string(apIndex) + + " in expression is out of range (from 0 to " + + std::to_string(*numberOfAPs-1) + + "): " + + expr->toString()); + } + } + } + return; + } + throw std::logic_error("Unknown operator in label expression: "+expr->toString()); + } + + // ---------------------------------------------------------------------------- + + /** + * Check that the canonical expression for an acc-name (if known) matches that + * given by the Acceptance header. + */ + void checkAccName(){ + AcceptanceRepository::ptr repository(new AcceptanceRepositoryStandard()); + + + acceptance_expr::ptr canonical; + try { + canonical = repository->getCanonicalAcceptanceExpression(*accName, accExtraInfo); + if (!(bool)canonical) { + // acceptance name is not known + return; + } + } catch (AcceptanceRepository::IllegalArgumentException& e) { + throw HOAConsumerException(e.what()); + } + + assert((bool)acceptance); + + //std::cerr << "Canonical: " << *canonical << std::endl; + //std::cerr << "Acceptance: " << *acceptance << std::endl; + + if (!acceptance_expr::areSyntacticallyEqual(acceptance, canonical)) { + throw HOAConsumerException(std::string("The acceptance given by the Acceptance and by the acc-name headers do not match syntactically:") + + "\nFrom Acceptance-header: "+acceptance->toString() + + "\nCanonical expression for acc-name-header: "+canonical->toString()); + } +} + +// ----------------- member variables + +protected: + /** A set of headers that are supported beyond the standard headers of the format */ + std::unordered_set<std::string> supportedMiscHeaders; + + /** The header names that have occurred so far in the automaton definition */ + std::unordered_set<std::string> usedHeaders; + + /** The number of states that have been specified in the header (optional) */ + std::shared_ptr<unsigned int > numberOfStates; + + /** The number of acceptance sets (mandatory) */ + std::shared_ptr<unsigned int> numberOfAcceptanceSets; + + /** The set of states for which addState has been called */ + dynamic_bitset statesWithDefinition; + + /** The set of states that occur as target states of some transition */ + dynamic_bitset targetStatesOfTransitions; + + /** The set of states that are start states */ + dynamic_bitset startStates; + + /** The set of alias names that have been defined (Alias-header) */ + std::unordered_set<std::string> aliases; + /** Atomic propositions that are referenced in some alias definition */ + dynamic_bitset apsInAliases; + + /** The number of atomic propositions */ + std::shared_ptr<unsigned int> numberOfAPs; + + /** The acc-name (optional) */ + std::shared_ptr<std::string> accName; + /** extraInfo parameters for acc-name */ + std::vector<IntOrString> accExtraInfo; + + /** The acceptance condition */ + acceptance_expr::ptr acceptance; + + /** The current state */ + std::size_t currentState = 0; + /** Does the current state have a state label? */ + bool currentStateHasStateLabel = false; + /** Does the current state have transitions with transition label? */ + bool currentStateHasTransitionLabel = false; + /** Does the current state have implicit edges? */ + bool currentStateHasImplicitEdge = false; + /** Does the current state have edges with explicit labels? */ + bool currentStateHasExplicitEdge = false; + /** Does the current state have state acceptance? */ + bool currentStateHasStateAcceptance = false; + /** Does the current state have transition acceptance? */ + bool currentStateHasTransitionAcceptance = false; + /** Is the current state colored ? */ + bool currentStateIsColored = false; + + + /** The implicit edge helper */ + ImplicitEdgeHelper implicitEdgeHelper; + + // properties: set to true if the given property is asserted by the HOA automaton + /** hints that the automaton uses only state labels */ + bool property_state_labels = false; + /** hints that the automaton uses only transition labels */ + bool property_trans_labels = false; + /** hints that the automaton uses only implicit transitions labels */ + bool property_implicit_labels = false; + /** hints that the automaton uses only explicit transitions labels */ + bool property_explicit_labels = false; + /** hints that the automaton uses only state-based acceptance specifications */ + bool property_state_acc = false; + /** hints that the automaton uses only transition-based acceptance specifications */ + bool property_trans_acc = false; + /** hints that the automaton uses universal branching for at least one transition or for the initial state */ + bool property_univ_branch = false; + /** hints that the automaton does not use universal branching */ + bool property_no_univ_branch = false; + /** hints that the automaton is deterministic, i.e., it has at most one initial state, and the outgoing transitions of each state have disjoint labels (note that this also applies in the presence of universal branching) */ + bool property_deterministic = false; + /** hints that the automaton is complete, i.e., it has at least one state, and the transition function is total */ + bool property_complete = false; + /** hints that each transition (or each state, for state-based acceptance) of the automaton belongs to exactly one acceptance set; this is typically the case in parity automata */ + bool property_colored = false; + + /** The number of Start-definitions (more than 1 = non-deterministic start states) */ + int numberOfStartHeaders = 0; + /** Has this automaton universal branching? */ + bool hasUniversalBranching = false; +}; + +} + +#endif diff --git a/resources/3rdparty/cpphoafparser-0.99.2/include/cpphoafparser/consumer/hoa_intermediate_resolve_aliases.hh b/resources/3rdparty/cpphoafparser-0.99.2/include/cpphoafparser/consumer/hoa_intermediate_resolve_aliases.hh new file mode 100644 index 000000000..ff53e0364 --- /dev/null +++ b/resources/3rdparty/cpphoafparser-0.99.2/include/cpphoafparser/consumer/hoa_intermediate_resolve_aliases.hh @@ -0,0 +1,185 @@ +//============================================================================== +// +// Copyright (c) 2015- +// Authors: +// * Joachim Klein <klein@tcs.inf.tu-dresden.de> +// * David Mueller <david.mueller@tcs.inf.tu-dresden.de> +// +//------------------------------------------------------------------------------ +// +// This file is part of the cpphoafparser library, +// http://automata.tools/hoa/cpphoafparser/ +// +// The cpphoafparser 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. +// +// The cpphoafparser 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 CPPHOAFPARSER_HOAINTERMEDIATERESOLVEALIASES_H +#define CPPHOAFPARSER_HOAINTERMEDIATERESOLVEALIASES_H + +#include <unordered_map> + +#include "cpphoafparser/consumer/hoa_intermediate.hh" + +namespace cpphoafparser { + +/** + * A HOAIntermediate that resolves aliases on-the-fly. + * + * Stores the definition of aliases from the header and resolves + * any aliases in label expressions before passing the events to + * the next consumer. + */ +class HOAIntermediateResolveAliases : public HOAIntermediate +{ +public: + /** Constructor, providing the `next` HOAConsumer */ + HOAIntermediateResolveAliases(HOAConsumer::ptr next) : HOAIntermediate(next) {} + + /** Store alias definition */ + virtual void addAlias(const std::string& name, label_expr::ptr labelExpr) override { + if (aliases.find(name) != aliases.end()) { + throw new HOAConsumerException("Alias "+name+" is defined multiple times!"); + } + + if (containsAliases(labelExpr)) { + // check that all the aliases in the expression are already defined + checkAliasDefinedness(labelExpr); + + // resolve aliases in the expression + labelExpr = resolveAliases(labelExpr); + } + + aliases[name]=labelExpr; + } + + /** Resolve alias references in state label, pass on to next HOAConsumer */ + virtual void addState(unsigned int id, + std::shared_ptr<std::string> info, + label_expr::ptr labelExpr, + std::shared_ptr<int_list> accSignature) override { + if (labelExpr && containsAliases(labelExpr)) { + labelExpr = resolveAliases(labelExpr); + } + next->addState(id, info, labelExpr, accSignature); + } + + /** Resolve alias references in edge label, pass on to next HOAConsumer */ + virtual void addEdgeWithLabel(unsigned int stateId, + label_expr::ptr labelExpr, + const int_list& conjSuccessors, + std::shared_ptr<int_list> accSignature) override { + if (labelExpr && containsAliases(labelExpr)) { + labelExpr = resolveAliases(labelExpr); + } + + next->addEdgeWithLabel(stateId, labelExpr, conjSuccessors, accSignature); + } + +private: + /** Map for mapping alias names to alias definitions */ + std::unordered_map<std::string, label_expr::ptr> aliases; + + /** Returns `true` if the label expression contains an alias reference */ + bool containsAliases(label_expr::ptr labelExpr) { + switch (labelExpr->getType()) { + case label_expr::EXP_FALSE: + case label_expr::EXP_TRUE: + return false; + case label_expr::EXP_AND: + case label_expr::EXP_OR: + if (containsAliases(labelExpr->getLeft())) return true; + if (containsAliases(labelExpr->getRight())) return true; + return false; + case label_expr::EXP_NOT: + if (containsAliases(labelExpr->getLeft())) return true; + return false; + case label_expr::EXP_ATOM: + return labelExpr->getAtom().isAlias(); + } + throw HOAConsumerException("Unhandled boolean expression type"); + } + + /** + * Checks that all alias references occuring in the label expression are defined. + * If that is not the case, a HOAConsumerExeption is thrown. + */ + void checkAliasDefinedness(label_expr::ptr labelExpr) { + switch (labelExpr->getType()) { + case label_expr::EXP_FALSE: + case label_expr::EXP_TRUE: + return; + case label_expr::EXP_AND: + case label_expr::EXP_OR: + checkAliasDefinedness(labelExpr->getLeft()); + checkAliasDefinedness(labelExpr->getRight()); + return; + case label_expr::EXP_NOT: + checkAliasDefinedness(labelExpr->getLeft()); + return; + case label_expr::EXP_ATOM: + if (labelExpr->getAtom().isAlias()) { + const std::string& aliasName = labelExpr->getAtom().getAliasName(); + if (aliases.find(aliasName) == aliases.end()) { + throw HOAConsumerException("Expression "+labelExpr->toString()+" uses undefined alias @"+aliasName); + } + } + return; + } + throw HOAConsumerException("Unhandled boolean expression type"); + + } + + /** + * Returns a label expression, with all alias references resolved. + */ + label_expr::ptr resolveAliases(label_expr::ptr labelExpr) { + switch (labelExpr->getType()) { + case label_expr::EXP_TRUE: + case label_expr::EXP_FALSE: + return labelExpr; + case label_expr::EXP_AND: + case label_expr::EXP_OR: + return label_expr::ptr(new label_expr(labelExpr->getType(), + resolveAliases(labelExpr->getLeft()), + resolveAliases(labelExpr->getRight()))); + case label_expr::EXP_NOT: + return label_expr::ptr(new label_expr(labelExpr->getType(), + resolveAliases(labelExpr->getLeft()), + nullptr)); + case label_expr::EXP_ATOM: + if (!labelExpr->getAtom().isAlias()) { + return labelExpr; + } else { + auto it = aliases.find(labelExpr->getAtom().getAliasName()); + if (it == aliases.end()) { + throw HOAConsumerException("Can not resolve alias @"+labelExpr->getAtom().getAliasName()); + } + + label_expr::ptr resolved = it->second; + if (containsAliases(resolved)) { + resolved = resolveAliases(resolved); + } + + return resolved; + } + } + throw HOAConsumerException("Unhandled boolean expression type"); + } + +}; + +} +#endif diff --git a/resources/3rdparty/cpphoafparser-0.99.2/include/cpphoafparser/consumer/hoa_intermediate_trace.hh b/resources/3rdparty/cpphoafparser-0.99.2/include/cpphoafparser/consumer/hoa_intermediate_trace.hh new file mode 100644 index 000000000..a235c4502 --- /dev/null +++ b/resources/3rdparty/cpphoafparser-0.99.2/include/cpphoafparser/consumer/hoa_intermediate_trace.hh @@ -0,0 +1,255 @@ +//============================================================================== +// +// Copyright (c) 2015- +// Authors: +// * Joachim Klein <klein@tcs.inf.tu-dresden.de> +// * David Mueller <david.mueller@tcs.inf.tu-dresden.de> +// +//------------------------------------------------------------------------------ +// +// This file is part of the cpphoafparser library, +// http://automata.tools/hoa/cpphoafparser/ +// +// The cpphoafparser 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. +// +// The cpphoafparser 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 CPPHOAFPARSER_HOAINTERMEDIATE_TRACE_H +#define CPPHOAFPARSER_HOAINTERMEDIATE_TRACE_H + +#include <iostream> + +#include "cpphoafparser/consumer/hoa_intermediate.hh" + +namespace cpphoafparser { + +/** + * Traces the function calls to HOAConsumer, prints function name and arguments to stream. + */ +class HOAIntermediateTrace : public HOAIntermediate { +public: + + /** Constructor, providing the `next` HOAConsumer */ + HOAIntermediateTrace(HOAConsumer::ptr next) : HOAIntermediate(next), out(std::cout) {} + + /** Constructor, providing the `next` HOAConsumer */ + HOAIntermediateTrace(HOAConsumer::ptr next, std::ostream& out) : HOAIntermediate(next), out(out) {} + + virtual bool parserResolvesAliases() override { + return next->parserResolvesAliases(); + } + + virtual void notifyHeaderStart(const std::string& version) override { + traceFunction("notifyHeaderStart"); + traceArgument("version", version); + + next->notifyHeaderStart(version); + } + + virtual void setNumberOfStates(unsigned int numberOfStates) override { + traceFunction("setNumberOfStates"); + traceArgument("numberOfStates", numberOfStates); + + next->setNumberOfStates(numberOfStates); + } + + virtual void addStartStates(const int_list& stateConjunction) override { + traceFunction("addStartStates"); + traceArgument("stateConjunction", stateConjunction); + + next->addStartStates(stateConjunction); + } + + virtual void addAlias(const std::string& name, label_expr::ptr labelExpr) override { + traceFunction("addAlias"); + traceArgument("labelExpr", labelExpr); + + next->addAlias(name, labelExpr); + } + + virtual void setAPs(const std::vector<std::string>& aps) override { + traceFunction("setAPs"); + traceArgument("aps", aps); + + next->setAPs(aps); + } + + virtual void setAcceptanceCondition(unsigned int numberOfSets, acceptance_expr::ptr accExpr) override { + traceFunction("setAcceptanceCondition"); + traceArgument("numberOfSets", numberOfSets); + traceArgument("accExpr", accExpr); + + next->setAcceptanceCondition(numberOfSets, accExpr); + } + + virtual void provideAcceptanceName(const std::string& name, const std::vector<IntOrString>& extraInfo) override { + traceFunction("setAcceptanceCondition"); + traceArgument("name", name); + traceArgument("extraInfo", extraInfo); + + next->provideAcceptanceName(name, extraInfo); + } + + virtual void setName(const std::string& name) override { + traceFunction("setName"); + traceArgument("name", name); + + next->setName(name); + } + + virtual void setTool(const std::string& name, std::shared_ptr<std::string> version) override { + traceFunction("setTool"); + traceArgument("name", name); + traceArgument("version", version); + + next->setTool(name, version); + } + + virtual void addProperties(const std::vector<std::string>& properties) override { + traceFunction("addProperties"); + traceArgument("properties", properties); + + next->addProperties(properties); + } + + virtual void addMiscHeader(const std::string& name, const std::vector<IntOrString>& content) override { + traceFunction("addMiscHeader"); + traceArgument("content", content); + + next->addMiscHeader(name, content); + } + + virtual void notifyBodyStart() override { + traceFunction("notifyBodyStart"); + + next->notifyBodyStart(); + } + + virtual void addState(unsigned int id, + std::shared_ptr<std::string> info, + label_expr::ptr labelExpr, + std::shared_ptr<int_list> accSignature) override { + traceFunction("addState"); + traceArgument("id", id); + traceArgument("info", info); + traceArgument("labelExpr", labelExpr); + traceArgument("accSignature", accSignature); + + next->addState(id, info, labelExpr, accSignature); + } + + virtual void addEdgeImplicit(unsigned int stateId, + const int_list& conjSuccessors, + std::shared_ptr<int_list> accSignature) override { + traceFunction("addEdgeImplicit"); + traceArgument("stateId", stateId); + traceArgument("conjSuccessors", conjSuccessors); + traceArgument("accSignature", accSignature); + + next->addEdgeImplicit(stateId, conjSuccessors, accSignature); + } + + virtual void addEdgeWithLabel(unsigned int stateId, + label_expr::ptr labelExpr, + const int_list& conjSuccessors, + std::shared_ptr<int_list> accSignature) override { + traceFunction("addEdgeWithLabel"); + traceArgument("stateId", stateId); + traceArgument("labelExpr", labelExpr); + traceArgument("conjSuccessors", conjSuccessors); + traceArgument("accSignature", accSignature); + + next->addEdgeWithLabel(stateId, labelExpr, conjSuccessors, accSignature); + } + + virtual void notifyEndOfState(unsigned int stateId) override { + traceFunction("notifyEndOfState"); + traceArgument("stateId", stateId); + + next->notifyEndOfState(stateId); + } + + virtual void notifyEnd() override { + traceFunction("notifyEnd"); + + next->notifyEnd(); + } + + virtual void notifyAbort() override { + traceFunction("notifyAbort"); + + next->notifyAbort(); + } + + virtual void notifyWarning(const std::string& warning) override { + traceFunction("notifyWarning"); + traceArgument("warning", warning); + + next->notifyWarning(warning); + } + +protected: + /** The output stream */ + std::ostream& out; + + /** Trace function call */ + void traceFunction(const std::string& function) { + out << "=> " << function << std::endl; + } + + /** Trace argument (string) */ + void traceArgument(const std::string& name, const std::string& value) { + out << " " << name << " = " << value << std::endl; + } + + /** Trace argument (int) */ + void traceArgument(const std::string& name, unsigned int value) { + out << " " << name << " = " << value << std::endl; + } + + /** Trace argument (BooleanExpression) */ + template <typename Atom> + void traceArgument(const std::string& name, const BooleanExpression<Atom>& expr) { + out << " " << name << " = " << expr << std::endl; + } + + /** Trace argument (vector) */ + template <typename T> + void traceArgument(const std::string& name, const std::vector<T>& list) { + out << " " << name << " = "; + out << "["; + bool first= true; + for (const T& element : list) { + if (!first) out << ","; else first = false; + out << element; + } + out << "]" << std::endl; + } + + /** Trace argument (shared_ptr) */ + template <typename O> + void traceArgument(const std::string& name, typename std::shared_ptr<O> o) { + if ((bool)o) { + traceArgument(name, *o); + } else { + traceArgument(name, "null"); + } + } + +}; + +} + +#endif diff --git a/resources/3rdparty/cpphoafparser-0.99.2/include/cpphoafparser/parser/hoa_lexer.hh b/resources/3rdparty/cpphoafparser-0.99.2/include/cpphoafparser/parser/hoa_lexer.hh new file mode 100644 index 000000000..25a2893bd --- /dev/null +++ b/resources/3rdparty/cpphoafparser-0.99.2/include/cpphoafparser/parser/hoa_lexer.hh @@ -0,0 +1,534 @@ +//============================================================================== +// +// Copyright (c) 2015- +// Authors: +// * Joachim Klein <klein@tcs.inf.tu-dresden.de> +// * David Mueller <david.mueller@tcs.inf.tu-dresden.de> +// +//------------------------------------------------------------------------------ +// +// This file is part of the cpphoafparser library, +// http://automata.tools/hoa/cpphoafparser/ +// +// The cpphoafparser 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. +// +// The cpphoafparser 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 CPPHOAFPARSER_HOALEXER_H +#define CPPHOAFPARSER_HOALEXER_H + +#include <map> +#include <string> +#include <stdexcept> + +#include "cpphoafparser/parser/hoa_parser_exception.hh" + +namespace cpphoafparser { + +/** Lexer for tokenizing a HOA stream (used internally by HOAParser). */ +class HOALexer { +public: + /** The type of the tokens in a HOA stream. */ + enum TokenType { + TOKEN_INT, + TOKEN_IDENT, + TOKEN_STRING, + TOKEN_HEADER_NAME, + TOKEN_ALIAS_NAME, + + TOKEN_EOF, + + TOKEN_BODY, + TOKEN_END, + TOKEN_ABORT, + TOKEN_HOA, + TOKEN_STATE, + TOKEN_STATES, + TOKEN_START, + TOKEN_AP, + TOKEN_ALIAS, + TOKEN_ACCEPTANCE, + TOKEN_ACCNAME, + TOKEN_TOOL, + TOKEN_NAME, + TOKEN_PROPERTIES, + + // Punctuation, etc. + TOKEN_NOT, + TOKEN_AND, + TOKEN_OR, + TOKEN_LPARENTH, + TOKEN_RPARENTH, + TOKEN_LBRACKET, + TOKEN_RBRACKET, + TOKEN_LCURLY, + TOKEN_RCURLY, + TOKEN_TRUE, + TOKEN_FALSE + }; + + /** A token in the HOA stream. */ + struct Token { + /** The kind of the token. */ + TokenType kind; + /** The string representation of this token (if applicable) */ + std::string vString; + /** The integer representation of this token (if applicable) */ + unsigned int vInteger; + + /** The line where this token started */ + unsigned int line; + /** The column where this token started */ + unsigned int col; + + /** EOF (end-of-file) constructor. */ + Token() : kind(TOKEN_EOF), vString(""), vInteger(0), line(0), col(0) {} + /** Constructor for syntactic element */ + Token(TokenType kind, unsigned int line, unsigned int col) : kind(kind), vString(""), vInteger(0), line(line), col(col) {} + /** Constructor for a token having variable string content (e.g., TOKEN_IDENTIFIER, TOKEN_ALIAS, TOKEN_STRING, ...) */ + Token(TokenType kind, const std::string vString, unsigned int line, unsigned int col) : kind(kind), vString(vString), vInteger(0), line(line), col(col) {} + /** Constructor for an unsigned integer token */ + Token(unsigned int vInteger, unsigned int line, unsigned int col) : kind(TOKEN_INT), vString(""), vInteger(vInteger), line(line), col(col) {} + + /** Returns true if this token represents the end-of-file. */ + bool isEOF() const {return kind == TOKEN_EOF;} + + /** Returns a string name for the given token type. */ + static std::string typeAsString(TokenType kind) { + switch (kind) { + case TOKEN_INT: return std::string("INT"); + case TOKEN_IDENT: return std::string("IDENT"); + case TOKEN_STRING: return std::string("STRING"); + case TOKEN_HEADER_NAME: return std::string("HEADER_NAME"); + case TOKEN_ALIAS_NAME: return std::string("ALIAS_NAME"); + + case TOKEN_EOF: return std::string("EOF"); + + case TOKEN_BODY: return std::string("BODY"); + case TOKEN_END: return std::string("END"); + case TOKEN_ABORT: return std::string("ABORT"); + case TOKEN_HOA: return std::string("HOA"); + case TOKEN_STATE: return std::string("STATE"); + case TOKEN_STATES: return std::string("STATES"); + case TOKEN_START: return std::string("START"); + case TOKEN_AP: return std::string("AP"); + case TOKEN_ALIAS: return std::string("ALIAS"); + case TOKEN_ACCEPTANCE: return std::string("ACCEPTANCE"); + case TOKEN_ACCNAME: return std::string("ACCNAME"); + case TOKEN_TOOL: return std::string("TOOL"); + case TOKEN_NAME: return std::string("NAME"); + case TOKEN_PROPERTIES: return std::string("PROPERTIES"); + + // Punctuation: etc. + case TOKEN_NOT: return std::string("NOT"); + case TOKEN_AND: return std::string("AND"); + case TOKEN_OR: return std::string("OR"); + case TOKEN_LPARENTH: return std::string("LPARENTH"); + case TOKEN_RPARENTH: return std::string("RPARENTH"); + case TOKEN_LBRACKET: return std::string("LBRACKET"); + case TOKEN_RBRACKET: return std::string("RBRACKET"); + case TOKEN_LCURLY: return std::string("LCURLY"); + case TOKEN_RCURLY: return std::string("RCURLY"); + case TOKEN_TRUE: return std::string("TRUE"); + case TOKEN_FALSE: return std::string("FALSE"); + } + throw std::logic_error("Unhandled token type"); + } + + /** Returns a string name for the given token type (for use in error messages). */ + static std::string forErrorMessage(TokenType kind) { + switch (kind) { + case TOKEN_INT: return std::string("INTEGER"); + case TOKEN_IDENT: return std::string("IDENTIFIER"); + case TOKEN_STRING: return std::string("STRING"); + case TOKEN_HEADER_NAME: return std::string("HEADER_NAME"); + case TOKEN_ALIAS_NAME: return std::string("ALIAS_NAME"); + + case TOKEN_EOF: return std::string("END-OF_FILE"); + + case TOKEN_BODY: return std::string("--BODY--"); + case TOKEN_END: return std::string("--END--"); + case TOKEN_ABORT: return std::string("--ABORT--"); + case TOKEN_HOA: return std::string("HOA:"); + case TOKEN_STATE: return std::string("State:"); + case TOKEN_STATES: return std::string("States:"); + case TOKEN_START: return std::string("Start:"); + case TOKEN_AP: return std::string("AP:"); + case TOKEN_ALIAS: return std::string("Alias:"); + case TOKEN_ACCEPTANCE: return std::string("Acceptance:"); + case TOKEN_ACCNAME: return std::string("acc-name:"); + case TOKEN_TOOL: return std::string("tool:"); + case TOKEN_NAME: return std::string("name:"); + case TOKEN_PROPERTIES: return std::string("properties:"); + + // Punctuation: etc. + case TOKEN_NOT: return std::string("!"); + case TOKEN_AND: return std::string("&"); + case TOKEN_OR: return std::string("|"); + case TOKEN_LPARENTH: return std::string("("); + case TOKEN_RPARENTH: return std::string(")"); + case TOKEN_LBRACKET: return std::string("["); + case TOKEN_RBRACKET: return std::string("]"); + case TOKEN_LCURLY: return std::string("{"); + case TOKEN_RCURLY: return std::string("}"); + case TOKEN_TRUE: return std::string("t"); + case TOKEN_FALSE: return std::string("f"); + } + throw std::logic_error("Unhandled token type"); + } + + /** Returns a string representation of a given token (for error messages). */ + static std::string forErrorMessage(Token token) { + switch (token.kind) { + case TOKEN_INT: return std::string("INTEGER ")+std::to_string(token.vInteger); + case TOKEN_IDENT: return std::string("IDENTIFIER ")+token.vString; + case TOKEN_STRING: return std::string("STRING ")+token.vString; + case TOKEN_HEADER_NAME: return std::string("HEADER ")+token.vString; + case TOKEN_ALIAS_NAME: return std::string("ALIAS ")+token.vString; + + case TOKEN_EOF: return std::string("END-OF-FILE"); + + case TOKEN_BODY: return std::string("--BODY--"); + case TOKEN_END: return std::string("--END--"); + case TOKEN_ABORT: return std::string("--ABORT--"); + case TOKEN_HOA: return std::string("HEADER HOA"); + case TOKEN_STATES: return std::string("HEADER States"); + case TOKEN_START: return std::string("HEADERr Start"); + case TOKEN_AP: return std::string("HEADER AP"); + case TOKEN_ALIAS: return std::string("HEADER Alias"); + case TOKEN_ACCEPTANCE: return std::string("HEADER Acceptance"); + case TOKEN_ACCNAME: return std::string("HEADER acc-name"); + case TOKEN_TOOL: return std::string("HEADER tool"); + case TOKEN_NAME: return std::string("HEADER name"); + case TOKEN_PROPERTIES: return std::string("HEADER properties"); + + case TOKEN_STATE: return std::string("DEFINITION State"); + + // Punctuation: etc. + case TOKEN_NOT: return std::string("!"); + case TOKEN_AND: return std::string("&"); + case TOKEN_OR: return std::string("|"); + case TOKEN_LPARENTH: return std::string("("); + case TOKEN_RPARENTH: return std::string(")"); + case TOKEN_LBRACKET: return std::string("["); + case TOKEN_RBRACKET: return std::string("]"); + case TOKEN_LCURLY: return std::string("{"); + case TOKEN_RCURLY: return std::string("}"); + case TOKEN_TRUE: return std::string("TRUE t"); + case TOKEN_FALSE: return std::string("FALSE f"); + } + throw std::logic_error("Unhandled token type"); + } + + /** Output function for a given token. */ + friend std::ostream& operator<<(std::ostream& out, const Token& token) { + out << "<" << token.typeAsString(token.kind) << "> "; + if (token.kind == TOKEN_INT) { + out << token.vInteger; + } else { + out << token.vString; + } + out << " (" << token.line << "," << token.col << ")"; + return out; + } + }; + + /** Constructor for a lexer, reading from the given input stream. */ + HOALexer(std::istream& in) + : in(in), line(1), col(0), ch(0) { + // The headers we know + knownHeaders["HOA:"] = TOKEN_HOA; + knownHeaders["State:"] = TOKEN_STATE; + knownHeaders["States:"] = TOKEN_STATES; + knownHeaders["Start:"] = TOKEN_START; + knownHeaders["AP:"] = TOKEN_AP; + knownHeaders["Alias:"] = TOKEN_ALIAS; + knownHeaders["Acceptance:"] = TOKEN_ACCEPTANCE; + knownHeaders["acc-name:"] = TOKEN_ACCNAME; + knownHeaders["tool:"] = TOKEN_TOOL; + knownHeaders["name:"] = TOKEN_NAME; + knownHeaders["properties:"] = TOKEN_PROPERTIES; + } + + /** Get the next token from the input stream. */ + Token nextToken() { + // first, skip any whitespace + skip(); + if (ch == EOF) return Token(TOKEN_EOF, line, col); + + // handle the simple syntactic elements + switch (ch) { + case '!': return Token(TOKEN_NOT, line, col); + case '&': return Token(TOKEN_AND, line, col); + case '|': return Token(TOKEN_OR, line, col); + case '(': return Token(TOKEN_LPARENTH, line, col); + case ')': return Token(TOKEN_RPARENTH, line, col); + case '[': return Token(TOKEN_LBRACKET, line, col); + case ']': return Token(TOKEN_RBRACKET, line, col); + case '{': return Token(TOKEN_LCURLY, line, col); + case '}': return Token(TOKEN_RCURLY, line, col); + } + + // remember where the token began + unsigned int lineStart = line; + unsigned int colStart = col; + + // handle --XYZ-- style markers + if (ch == '-') { + unsigned int index=0; + bool canBeAbort = true; + bool canBeBody = true; + bool canBeEnd = true; + std::string abort("-ABORT--"); + std::string body("-BODY--"); + std::string end("-END--"); + + while (canBeAbort || canBeBody || canBeEnd) { + nextChar(); + if (ch == EOF) {throw error("Premature end-of-file inside token", lineStart, colStart);} + if (canBeAbort && ch == abort.at(index)) { + if (index == abort.length()-1) { + return Token(TOKEN_ABORT, lineStart, colStart); + } + } else { + canBeAbort=false; + } + if (canBeBody && ch == body.at(index)) { + if (index == body.length()-1) { + return Token(TOKEN_BODY, lineStart, colStart); + } + } else { + canBeBody=false; + } + if (canBeEnd && ch == end.at(index)) { + if (index == end.length()-1) { + return Token(TOKEN_END, lineStart, colStart); + } + } else { + canBeEnd=false; + } + + index++; + if (index >= abort.length()) canBeAbort = false; + if (index >= body.length()) canBeBody = false; + if (index >= end.length()) canBeEnd = false; + } + throw error("Lexical error: For token starting with '-', expected either '--BODY--', '--END--' or '--ABORT--'", lineStart, colStart); + } + + // handle quoted strings + if (ch == '"') { + std::string text(1, (char)ch); + bool last_was_quote = false; + while (true) { + nextChar(); + if (ch == EOF) {throw error("Premature end-of-file in quoted string", lineStart, colStart);} + text+=(char)ch; + if (ch == '"' && !last_was_quote) break; + if (ch == '\\' && !last_was_quote) { + last_was_quote = true; + } else { + last_was_quote = false; + } + } + + return Token(TOKEN_STRING, text, lineStart, colStart); + } + + // handle integers + if (ch >= '0' && ch <= '9') { + std::string text(1, (char)ch); + while (true) { + int next = peekChar(); + if (next >= '0' && next <= '9') { + nextChar(); + text+=(char)ch; + } else { + break; + } + } + + if (text.at(0)=='0' && text.length() > 1) { + throw error("Syntax error parsing integer, starts with 0: "+text, lineStart, colStart); + } + + try { + unsigned int vInteger = std::stoi(text); + return Token(vInteger, lineStart, colStart); + } catch (std::invalid_argument& e) { + throw error("Syntax error: "+text+" is not an integer", lineStart, colStart); + } catch (std::out_of_range& e) { + throw error("Syntax error: integer "+text+" is too big to represent as an unsigned int", lineStart, colStart); + } + + } else if (ch == '@' || ch == '_' || (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) { + // handle identifiers, @alias-names, headers, t and f + std::string text(1, (char)ch); + + bool alias = (ch == '@'); + while (true) { + int next = peekChar(); + if (next == EOF) break; + if (next == ':') { + if (alias) break; + // consume ':' + nextChar(); + text+=':'; + break; + } + if (next == '_' || + next == '-' || + (next >= 'a' && next <= 'z') || + (next >= 'A' && next <= 'Z') || + (next >= '0' && next <= '9')) { + nextChar(); + text+=(char)ch; + continue; + } else { + break; + } + } + + if (alias) { + return Token(TOKEN_ALIAS_NAME, text, lineStart, colStart); + } + + if (text.back() == ':') { + auto it = knownHeaders.find(text); + if (it != knownHeaders.end()) { + return Token((*it).second, text, lineStart, colStart); + } + return Token(TOKEN_HEADER_NAME, text, lineStart, colStart); + } + if (text == "t") { + return Token(TOKEN_TRUE, text, lineStart, colStart); + } else if (text == "f") { + return Token(TOKEN_FALSE, text, lineStart, colStart); + } + return Token(TOKEN_IDENT, text, lineStart, colStart); + } + + throw error("Syntax error, illegal character '"+std::string(1, (char)ch)+"'", lineStart, colStart); + } + +private: + + /** Skip whitespace. */ + void skip() { + while (true) { + nextChar(); + if (ch == EOF) { // EOF + return; + } + if (ch == '/') { + skipComment(); + continue; + } + if (ch == ' ' || ch == '\t') { + continue; + } + if (ch == '\n' || ch == '\r') { + line++; + col=0; + continue; + } + break; + } + } + + /** Skip a comment */ + void skipComment() { + nextChar(); + if (ch != '*') { + throw error("Malformed start of comment", line, col); + } + bool last_was_slash = false; + bool last_was_star = false; + unsigned int nesting = 0; + while (true) { + nextChar(); + if (ch == EOF) {throw error("End-of-file inside comment", line, col);} + if (ch == '\n' || ch == '\r') { + line++; + col=0; + last_was_slash = false; + last_was_star = false; + continue; + } + if (ch == '/') { + if (last_was_star) { + if (nesting == 0) { + return; + } else { + nesting--; + } + } else { + last_was_slash = true; + } + continue; + } + if (ch == '*') { + if (last_was_slash) { + nesting++; + } else { + last_was_star = true; + continue; + } + } + last_was_slash = false; + last_was_star = false; + } + } + + /** Read the next char in the input stream, store in `ch` */ + void nextChar() { + ch = in.get(); + if (ch != EOF) { + col++; + } + } + + /** Peek at the next char in the input stream without consuming */ + int peekChar() { + return in.peek(); + } + + /** + * Construct a HOAParserExeption for a lexer error. + * @param msg the error message + * @param errLine the line number where the error occured + * @param errCol column number where the error occured + */ + HOAParserException error(const std::string& msg, unsigned int errLine, unsigned int errCol) { + return HOAParserException(msg+" (at line "+std::to_string(errLine)+", col "+std::to_string(errCol)+")", errLine, errCol); + } + +private: + /** The input stream */ + std::istream& in; + /** The current line number */ + unsigned int line; + /** The current column number */ + unsigned int col; + /** The current character (or EOF) */ + int ch; + + /** A map for mapping the known header names to the corresponding token types */ + std::map<std::string, TokenType> knownHeaders; +}; + +} + +#endif diff --git a/resources/3rdparty/cpphoafparser-0.99.2/include/cpphoafparser/parser/hoa_parser.hh b/resources/3rdparty/cpphoafparser-0.99.2/include/cpphoafparser/parser/hoa_parser.hh new file mode 100644 index 000000000..7e6b8afc0 --- /dev/null +++ b/resources/3rdparty/cpphoafparser-0.99.2/include/cpphoafparser/parser/hoa_parser.hh @@ -0,0 +1,692 @@ +//============================================================================== +// +// Copyright (c) 2015- +// Authors: +// * Joachim Klein <klein@tcs.inf.tu-dresden.de> +// * David Mueller <david.mueller@tcs.inf.tu-dresden.de> +// +//------------------------------------------------------------------------------ +// +// This file is part of the cpphoafparser library, +// http://automata.tools/hoa/cpphoafparser/ +// +// The cpphoafparser 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. +// +// The cpphoafparser 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 CPPHOAFPARSER_HOAPARSER_H +#define CPPHOAFPARSER_HOAPARSER_H + +#include <set> +#include <string> +#include <sstream> + +#include "cpphoafparser/parser/hoa_lexer.hh" +#include "cpphoafparser/consumer/hoa_consumer.hh" +#include "cpphoafparser/consumer/hoa_intermediate_check_validity.hh" +#include "cpphoafparser/consumer/hoa_intermediate_resolve_aliases.hh" +#include "cpphoafparser/parser/hoa_parser_exception.hh" + + +/** @mainpage cpphoafparser API documentation + * + * API documentation for the <a href="http://automata.tools/hoa/cpphoafparser/">cpphoafparser</a> library. + */ + +/** @namespace cpphoafparser + * The `cpphoafparser` namespace contains all the classes of the + * cpphoafparser library. + */ +namespace cpphoafparser { + +/** + * Parser class for parsing HOA files. + * + * Provides a static function for parsing a HOA automaton from an input stream, + * calling into a HOAConsumer for every syntax element encountered during the parse. + * + * The parser is implemented as a simple, hand-written recursive-descent parser, + * with functions corresponding to grammar rules. + **/ +class HOAParser { +public: + + /** + * Function for parsing a single HOA automaton. + * + * On error, will throw HOAParserException, the consumers will generally throw + * HOAConsumerException. + * + * @param in std::istream from which the automaton will be read + * @param consumer a shared_ptr to the HOAConsumer whose functions will + * be called for each element of the HOA automaton + * @param check_validity Should the validity of the HOA be checked? + * These are checks beyond the basic syntactic well-formedness guaranteed by the grammar. + **/ + static void parse(std::istream& in, HOAConsumer::ptr consumer, bool check_validity=true) { + if (consumer->parserResolvesAliases()) { + consumer.reset(new HOAIntermediateResolveAliases(consumer)); + } + + if (check_validity) { + consumer.reset(new HOAIntermediateCheckValidity(consumer)); + } + + HOAParser parser(in, consumer); + parser.nextToken(); + parser.Automaton(); + } + +private: + /** The registered consumer */ + HOAConsumer::ptr consumer; + /** The lexer for tokenizing the input stream */ + HOALexer lexer; + + /** The current token */ + HOALexer::Token token; + /** true if we are currently in a State: definition */ + bool inState; + /** the index of the current state*/ + unsigned int currentState; + /** true if the current state has state labeling */ + bool currentStateHasStateLabel; + + + /** Private constructor. */ + HOAParser(std::istream& in, HOAConsumer::ptr consumer) : + consumer(consumer), lexer(in), inState(false), currentState(0), currentStateHasStateLabel(false) { + } + + /** Advance to the next token. Handles TOKEN_ABORT */ + void nextToken() { + token = lexer.nextToken(); + if (token.kind == HOALexer::TOKEN_ABORT) { + consumer->notifyAbort(); + throw "aborted"; + } + } + + /** Advances to the next token if it is of the expected kind, otherwise throw an error. */ + void expect(HOALexer::TokenType kind, const std::string& context="") { + if (token.kind != kind) { + throw error(HOALexer::Token::forErrorMessage(kind), context); + } + + // eat token + nextToken(); + } + + /** + * Constructs a HOAParserExeption for a syntax error. + * @param expectedTokenTypes a string detailing which token types were expected + * @param context optionally, some context for the error message */ + HOAParserException error(const std::string& expectedTokenTypes, const std::string& context="") { + std::stringstream ss; + ss << "Syntax error"; + if (context != "") { + ss << " (while reading " << context << ")"; + } + ss << ": Expected " << expectedTokenTypes; + ss << ", got " << HOALexer::Token::forErrorMessage(token); + ss << " (line " << std::to_string(token.line) << ", col " << std::to_string(token.col) << ")"; + + return HOAParserException(ss.str(), token.line, token.col); + } + + /** Grammar rule for the whole Automaton */ + void Automaton() { + Header(); + expect(HOALexer::TOKEN_BODY); + consumer->notifyBodyStart(); + Body(); + expect(HOALexer::TOKEN_END); + if (inState) { + consumer->notifyEndOfState(currentState); + } + consumer->notifyEnd(); + } + + /** Grammar rule for the HOA header */ + void Header() { + Format(); + HeaderItems(); + } + + /** Grammar rule for the HOA: header */ + void Format() { + expect(HOALexer::TOKEN_HOA); + std::string version = Identifier("version"); + // TODO: check format version + consumer->notifyHeaderStart(version); + } + + /** Grammar rule for the remaining header items, returns if there are not more headers */ + void HeaderItems() { + while (true) { + switch (token.kind) { + case HOALexer::TOKEN_STATES: HeaderItemStates(); break; + case HOALexer::TOKEN_START: HeaderItemStart(); break; + case HOALexer::TOKEN_AP: HeaderItemAP(); break; + case HOALexer::TOKEN_ALIAS: HeaderItemAlias(); break; + case HOALexer::TOKEN_ACCEPTANCE: HeaderItemAcceptance(); break; + case HOALexer::TOKEN_ACCNAME: HeaderItemAccName(); break; + case HOALexer::TOKEN_TOOL: HeaderItemTool(); break; + case HOALexer::TOKEN_NAME: HeaderItemName(); break; + case HOALexer::TOKEN_PROPERTIES: HeaderItemProperties(); break; + case HOALexer::TOKEN_HEADER_NAME: HeaderMiscItem(); break; + default: + // not a header, return + return; + } + } + } + + /** Grammar rule for the States-header */ + void HeaderItemStates() { + expect(HOALexer::TOKEN_STATES); + + unsigned int states = Integer("number of states in States-header"); + consumer->setNumberOfStates(states); + } + + /** Grammar rule for the Start-header */ + void HeaderItemStart() { + expect(HOALexer::TOKEN_START); + + std::vector<unsigned int> stateConjunction; + unsigned int state = Integer("Start: index of start state"); + stateConjunction.push_back(state); + while (token.kind == HOALexer::TOKEN_AND) { + expect(HOALexer::TOKEN_AND); + state = Integer("Start: index of start state in conjunction"); + stateConjunction.push_back(state); + } + + consumer->addStartStates(stateConjunction); + } + + /** Grammar rule for the AP-header */ + void HeaderItemAP() { + expect(HOALexer::TOKEN_AP); + + unsigned int apCount = Integer("AP: number of atomic propositions"); + + std::vector<std::string> apList; + std::set<std::string> aps; + + while (token.kind == HOALexer::TOKEN_STRING) { + std::string ap = QuotedString(); + if (aps.find(ap) != aps.end()) { + throw HOAConsumerException("Atomic proposition \""+ap+"\" is a duplicate!"); + } + aps.insert(ap); + apList.push_back(ap); + } + + if (apList.size() != apCount) { + throw HOAConsumerException("Number of provided APs (" + std::to_string(apList.size()) + ") does not match number of APs that was specified (" + std::to_string(apCount) + ")"); + } + + consumer->setAPs(apList); + } + + /** Grammar rule for the Alias-header */ + void HeaderItemAlias() { + expect(HOALexer::TOKEN_ALIAS); + std::string aliasName = AliasName(); + + HOAConsumer::label_expr::ptr labelExpr = LabelExpr(); + + consumer->addAlias(aliasName, labelExpr); + } + + /** Grammar rule for the Acceptance-header */ + void HeaderItemAcceptance() { + expect(HOALexer::TOKEN_ACCEPTANCE); + unsigned int numberOfSets = Integer("Acceptance: number of acceptance sets"); + + HOAConsumer::acceptance_expr::ptr accExpr = AcceptanceCondition(); + + consumer->setAcceptanceCondition(numberOfSets, accExpr); + } + + /** Grammar rule for the acc-name-header */ + void HeaderItemAccName() { + expect(HOALexer::TOKEN_ACCNAME); + + std::string accName = Identifier("acceptance name"); + std::vector<IntOrString> extraInfo; + + while (true) { + if (token.kind == HOALexer::TOKEN_IDENT) { + extraInfo.push_back(IntOrString(Identifier())); + } else if (token.kind == HOALexer::TOKEN_INT) { + extraInfo.push_back(IntOrString(Integer())); + } else if (token.kind == HOALexer::TOKEN_TRUE) { + extraInfo.push_back(IntOrString("t")); + expect(HOALexer::TOKEN_TRUE); // munch + } else if (token.kind == HOALexer::TOKEN_FALSE) { + extraInfo.push_back(IntOrString("f")); + expect(HOALexer::TOKEN_FALSE); // munch + } else { + break; + } + + // TODO + // if (settings == null || !settings.getFlagIgnoreAccName()) { + // consumer.provideAcceptanceName(accName, extraInfo); + //} + } + + consumer->provideAcceptanceName(accName, extraInfo); + } + + /** Grammar rule for the tool-header */ + void HeaderItemTool() { + expect(HOALexer::TOKEN_TOOL); + + std::string tool = QuotedString(); + std::shared_ptr<std::string> version; + + if (token.kind == HOALexer::TOKEN_STRING) { + version.reset(new std::string(QuotedString())); + } + + consumer->setTool(tool, version); + } + + /** Grammar rule for the name-header */ + void HeaderItemName() { + expect(HOALexer::TOKEN_NAME); + + std::string name = QuotedString(); + + consumer->setName(name); + } + + /** Grammar rule for the properties-header */ + void HeaderItemProperties() { + expect(HOALexer::TOKEN_PROPERTIES); + + std::vector<std::string> properties; + while (true) { + if (token.kind == HOALexer::TOKEN_IDENT) { + std::string property = Identifier(); + properties.push_back(property); + } else if (token.kind == HOALexer::TOKEN_TRUE) { + // t does not have the special boolean meaning here, back to string + properties.push_back("t"); + expect(HOALexer::TOKEN_TRUE); // eat + } else if (token.kind == HOALexer::TOKEN_FALSE) { + // f does not have the special boolean meaning here, back to string + properties.push_back("f"); + expect(HOALexer::TOKEN_FALSE); // eat + } else { + // no more properties... + break; + } + } + + consumer->addProperties(properties); + } + + /** Grammar rule for a misc header (not known from the format specification) */ + void HeaderMiscItem() { + std::string headerName = token.vString; + headerName = headerName.substr(0, headerName.length()-1); + expect(HOALexer::TOKEN_HEADER_NAME); + + std::vector<IntOrString> content; + + while (true) { + if (token.kind == HOALexer::TOKEN_INT) { + content.push_back(Integer()); + } else if (token.kind == HOALexer::TOKEN_IDENT) { + content.push_back(Identifier()); + } else if (token.kind == HOALexer::TOKEN_STRING) { + content.push_back(IntOrString(QuotedString(), true)); + } else if (token.kind == HOALexer::TOKEN_TRUE) { + // t does not have the special boolean meaning here, back to string + content.push_back(IntOrString("t", false)); + expect(HOALexer::TOKEN_TRUE); // eat + } else if (token.kind == HOALexer::TOKEN_FALSE) { + // f does not have the special boolean meaning here, back to string + content.push_back(IntOrString("f", false)); + expect(HOALexer::TOKEN_FALSE); // eat + } else { + break; + } + } + + consumer->addMiscHeader(headerName, content); + } + + /** Grammar rule for the automaton body */ + void Body() { + while (true) { + switch (token.kind) { + case HOALexer::TOKEN_STATE: + StateName(); + break; + case HOALexer::TOKEN_END: + return; + case HOALexer::TOKEN_EOF: + return; + default: + if (inState) { + Edge(); + } else { + throw error("either State: or --END--"); + } + } + } + } + + /** Grammar rule for the State definition */ + void StateName() { + expect(HOALexer::TOKEN_STATE); + + HOAConsumer::label_expr::ptr labelExpr; + std::shared_ptr<std::string> stateComment; + std::shared_ptr<HOAConsumer::int_list> accSignature; + + if (token.kind == HOALexer::TOKEN_LBRACKET) { + labelExpr = Label(); + } + + unsigned int state = Integer(); // name of the state + if (token.kind == HOALexer::TOKEN_STRING) { + stateComment.reset(new std::string(QuotedString())); // state comment + } + + if (token.kind == HOALexer::TOKEN_LCURLY) { + accSignature = AcceptanceSignature(); + } + + if (inState) { + consumer->notifyEndOfState(currentState); + } + + consumer->addState(state, stateComment, labelExpr, accSignature); + + // store global information: + inState = true; + currentState = state; + currentStateHasStateLabel = (bool)(labelExpr); + } + + /** Grammar rule for an automaton edge */ + void Edge() { + HOAConsumer::label_expr::ptr labelExpr; + std::shared_ptr<HOAConsumer::int_list> conjStates; + std::shared_ptr<HOAConsumer::int_list> accSignature; + + if (token.kind == HOALexer::TOKEN_LBRACKET) { + labelExpr = Label(); + } + + conjStates = StateConjunction("edge"); + + if (token.kind == HOALexer::TOKEN_LCURLY) { + accSignature = AcceptanceSignature(); + } + + if (labelExpr || currentStateHasStateLabel) { + consumer->addEdgeWithLabel(currentState, labelExpr, *conjStates, accSignature); + } else { + consumer->addEdgeImplicit(currentState, *conjStates, accSignature); + } + } + + /** + * Grammar rule for a state conjunction + * @param context contextual information for error messages + */ + std::shared_ptr<HOAConsumer::int_list> StateConjunction(const std::string& context) { + std::shared_ptr<HOAConsumer::int_list> stateConjunction (new HOAConsumer::int_list()); + + unsigned int state = Integer(context); + stateConjunction->push_back(state); + while (token.kind == HOALexer::TOKEN_AND) { + expect(HOALexer::TOKEN_AND); + state = Integer(context); + stateConjunction->push_back(state); + } + return stateConjunction; + } + + /** Grammar rule for a [label-expr] */ + HOAConsumer::label_expr::ptr Label() { + HOAConsumer::label_expr::ptr result; + expect(HOALexer::TOKEN_LBRACKET); + result = LabelExpr(); + expect(HOALexer::TOKEN_RBRACKET); + return result; + } + + /** Grammar rule for an acceptance signature */ + std::shared_ptr<HOAConsumer::int_list> AcceptanceSignature() { + std::shared_ptr<HOAConsumer::int_list> result(new HOAConsumer::int_list()); + + expect(HOALexer::TOKEN_LCURLY); + while (token.kind == HOALexer::TOKEN_INT) { + unsigned int accSet = Integer(); + result->push_back(accSet); + } + expect(HOALexer::TOKEN_RCURLY); + + return result; + } + + /** Grammar rule for an acceptance condition expression (handle disjunction)*/ + HOAConsumer::acceptance_expr::ptr AcceptanceCondition() { + HOAConsumer::acceptance_expr::ptr left = AcceptanceConditionAnd(); + while (token.kind == HOALexer::TOKEN_OR) { + expect(HOALexer::TOKEN_OR); + + HOAConsumer::acceptance_expr::ptr right = AcceptanceConditionAnd(); + left = left | right; + } + return left; + } + + /** Grammar rule for conjunction in an acceptance condition */ + HOAConsumer::acceptance_expr::ptr AcceptanceConditionAnd() { + HOAConsumer::acceptance_expr::ptr left = AcceptanceConditionAtom(); + while (token.kind == HOALexer::TOKEN_AND) { + expect(HOALexer::TOKEN_AND); + + HOAConsumer::acceptance_expr::ptr right = AcceptanceConditionAtom(); + left = left & right; + } + return left; + } + + /** Grammar rule for the atoms in an acceptance condition */ + HOAConsumer::acceptance_expr::ptr AcceptanceConditionAtom() { + HOAConsumer::acceptance_expr::ptr result; + + switch (token.kind) { + case HOALexer::TOKEN_LPARENTH: + expect(HOALexer::TOKEN_LPARENTH); + result = AcceptanceCondition(); + expect(HOALexer::TOKEN_RPARENTH); + return result; + case HOALexer::TOKEN_TRUE: + expect(HOALexer::TOKEN_TRUE); + result.reset(new HOAConsumer::acceptance_expr(true)); + return result; + case HOALexer::TOKEN_FALSE: + expect(HOALexer::TOKEN_FALSE); + result.reset(new HOAConsumer::acceptance_expr(false)); + return result; + case HOALexer::TOKEN_IDENT: + result.reset(new HOAConsumer::acceptance_expr(AcceptanceConditionTemporalOperator())); + return result; + default: + throw error("acceptance condition"); + } + } + + /** Grammar rule for a temporal operator (Fin/Inf) in an acceptance condition */ + AtomAcceptance::ptr AcceptanceConditionTemporalOperator() { + AtomAcceptance::AtomType atomType = AtomAcceptance::TEMPORAL_FIN; + bool negated = false; + unsigned int accSetIndex; + + std::string temporalOperator = Identifier(); + + if (temporalOperator == "Fin") { + atomType = AtomAcceptance::TEMPORAL_FIN; + } else if (temporalOperator == "Inf") { + atomType = AtomAcceptance::TEMPORAL_INF; + } else { + throw error("either 'Fin' or 'Inf'", "acceptance condition"); + } + + expect(HOALexer::TOKEN_LPARENTH, "acceptance condition"); + if (token.kind == HOALexer::TOKEN_NOT) { + expect(HOALexer::TOKEN_NOT); + negated = true; + } + accSetIndex = Integer("acceptance set index"); + expect(HOALexer::TOKEN_RPARENTH, "acceptance condition"); + + return AtomAcceptance::ptr(new AtomAcceptance(atomType, accSetIndex, negated)); + } + + /** Grammar rule for a label expression (handle disjunction) */ + HOAConsumer::label_expr::ptr LabelExpr() { + HOAConsumer::label_expr::ptr left = LabelExprAnd(); + while (token.kind == HOALexer::TOKEN_OR) { + expect(HOALexer::TOKEN_OR); + + HOAConsumer::label_expr::ptr right = LabelExprAnd(); + left = left | right; + } + return left; + } + + /** Grammar rule for a label expression (handle conjunction) */ + HOAConsumer::label_expr::ptr LabelExprAnd() { + HOAConsumer::label_expr::ptr left = LabelExprAtom(); + while (token.kind == HOALexer::TOKEN_AND) { + expect(HOALexer::TOKEN_AND); + + HOAConsumer::label_expr::ptr right = LabelExprAtom(); + left = left & right; + } + return left; + } + + /** Grammar rule for a label expression (handle atoms) */ + HOAConsumer::label_expr::ptr LabelExprAtom() { + HOAConsumer::label_expr::ptr result; + + switch (token.kind) { + case HOALexer::TOKEN_LPARENTH: + expect(HOALexer::TOKEN_LPARENTH); + result = LabelExpr(); + expect(HOALexer::TOKEN_RPARENTH); + return result; + case HOALexer::TOKEN_TRUE: + expect(HOALexer::TOKEN_TRUE); + result.reset(new HOAConsumer::label_expr(true)); + return result; + case HOALexer::TOKEN_FALSE: + expect(HOALexer::TOKEN_FALSE); + result.reset(new HOAConsumer::label_expr(false)); + return result; + case HOALexer::TOKEN_NOT: + expect(HOALexer::TOKEN_NOT); + result = LabelExprAtom(); + return !result; + case HOALexer::TOKEN_INT: { + unsigned int apIndex = Integer(); + result.reset(new HOAConsumer::label_expr(AtomLabel::createAPIndex(apIndex))); + return result; + } + case HOALexer::TOKEN_ALIAS_NAME: { + std::string aliasName = AliasName(); + result.reset(new HOAConsumer::label_expr(AtomLabel::createAlias(aliasName))); + return result; + } + default: + throw error("label expression"); + } + } + + /** Grammar rule for a quoted string */ + std::string QuotedString(const std::string& context="") { + if (token.kind != HOALexer::TOKEN_STRING) { + expect(HOALexer::TOKEN_STRING, context); + } + + std::string result = token.vString; + // eat token + nextToken(); + + result = HOAParserHelper::unquote(result); + + return result; + } + + /** Grammar rule for a HOA identifier */ + std::string Identifier(const std::string& context="") { + if (token.kind != HOALexer::TOKEN_IDENT) { + expect(HOALexer::TOKEN_IDENT, context); + } + + std::string result = token.vString; + // eat token + nextToken(); + + return result; + } + + /** Grammar rule for an @@alias-name. Returns the name without the leading @@. */ + std::string AliasName() { + if (token.kind != HOALexer::TOKEN_ALIAS_NAME) { + expect(HOALexer::TOKEN_ALIAS_NAME); + } + + std::string result = token.vString; + // eat token + nextToken(); + + // eat @ + result = result.substr(1); + + return result; + } + + /** Grammar rule for an unsigned integer */ + unsigned int Integer(const std::string& context="") { + if (token.kind != HOALexer::TOKEN_INT) { + expect(HOALexer::TOKEN_INT, context); + } + + unsigned int result = token.vInteger; + // eat token + nextToken(); + + return result; + } +}; + +} + +#endif diff --git a/resources/3rdparty/cpphoafparser-0.99.2/include/cpphoafparser/parser/hoa_parser_exception.hh b/resources/3rdparty/cpphoafparser-0.99.2/include/cpphoafparser/parser/hoa_parser_exception.hh new file mode 100644 index 000000000..c68b05a44 --- /dev/null +++ b/resources/3rdparty/cpphoafparser-0.99.2/include/cpphoafparser/parser/hoa_parser_exception.hh @@ -0,0 +1,75 @@ +//============================================================================== +// +// Copyright (c) 2015- +// Authors: +// * Joachim Klein <klein@tcs.inf.tu-dresden.de> +// * David Mueller <david.mueller@tcs.inf.tu-dresden.de> +// +//------------------------------------------------------------------------------ +// +// This file is part of the cpphoafparser library, +// http://automata.tools/hoa/cpphoafparser/ +// +// The cpphoafparser 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. +// +// The cpphoafparser 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 CPPHOAFPARSER_HOAPARSEREXCEPTION_H +#define CPPHOAFPARSER_HOAPARSEREXCEPTION_H + +#include <stdexcept> +#include <cassert> + +namespace cpphoafparser { + +/** Exception thrown to indicate an error during parsing, mostly for syntax errors. */ +class HOAParserException : public std::runtime_error { +public: + /** Constructor for simple error message. */ + HOAParserException(const std::string& what) : + std::runtime_error(what), hasLocation(false), line(0), col(0) {} + + /** Constructor for error message with location (line/column) information. */ + HOAParserException(const std::string& what, int line, int col) : + std::runtime_error(what), hasLocation(true), line(line), col(col) {} + + bool getHasLocation() const { + return hasLocation; + } + + /** @pre getHasLocation returns true */ + bool getLine() const { + assert(getHasLocation()); + return line; + } + + /** @pre getHasLocation returns true */ + bool getCol() const { + assert(getHasLocation()); + return col; + } + +private: + /** True if we have location information */ + bool hasLocation; + /** The line number */ + unsigned int line; + /** The column number */ + unsigned int col; +}; + +} + +#endif diff --git a/resources/3rdparty/cpphoafparser-0.99.2/include/cpphoafparser/parser/hoa_parser_helper.hh b/resources/3rdparty/cpphoafparser-0.99.2/include/cpphoafparser/parser/hoa_parser_helper.hh new file mode 100644 index 000000000..c61642c93 --- /dev/null +++ b/resources/3rdparty/cpphoafparser-0.99.2/include/cpphoafparser/parser/hoa_parser_helper.hh @@ -0,0 +1,122 @@ +//============================================================================== +// +// Copyright (c) 2015- +// Authors: +// * Joachim Klein <klein@tcs.inf.tu-dresden.de> +// * David Mueller <david.mueller@tcs.inf.tu-dresden.de> +// +//------------------------------------------------------------------------------ +// +// This file is part of the cpphoafparser library, +// http://automata.tools/hoa/cpphoafparser/ +// +// The cpphoafparser 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. +// +// The cpphoafparser 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 CPPHOAFPARSER_HOAPARSERHELPER_H +#define CPPHOAFPARSER_HOAPARSERHELPER_H + +#include <iostream> +#include <string> +#include <sstream> + +#include "cpphoafparser/parser/hoa_parser_exception.hh" + +namespace cpphoafparser { + +/** Helper function for dealing with quoted strings */ +class HOAParserHelper { +public: + /** + * Outputs a quoted version of the string to the ostream. + * The string is quoted to conform the to double-quoted + * string syntax of the HOA format. + */ + static void print_quoted(std::ostream& out, const std::string& s) { + std::string::size_type pos = s.find_first_of("\\\""); // find next \ or " + + if (pos == std::string::npos) { + // nothing to quote + out << "\"" << s << "\""; + return; + } + + out << "\""; + std::string::size_type last_pos = 0; + do { + out << s.substr(last_pos, pos); // characters that don't need to be quoted + out << "\\"; // add quote + out << s.substr(pos,1); // add character + + last_pos = pos+1; + pos = s.find_first_of("\\\"", last_pos); // find next \ or " + } while (pos != std::string::npos); + if (last_pos < s.length()) { + out << s.substr(last_pos); // remaining + } + out << "\""; + } + + /** Returns a double-quoted version of the string (HOA syntax and quoting rules). */ + static std::string quote(const std::string& s) { + std::stringstream ss; + print_quoted(ss, s); + return ss.str(); + } + + /** + * Performs unquoting of a double-quoted string (HOA syntax and quoting rules). + * If the string is not a validly quoted string, a HOAParserException is thrown. + * @returns the unquoted string + **/ + static std::string unquote(const std::string& s) { + if (s.length() == 0 || s.at(0) != '"') { + throw HOAParserException("String not quoted : " + s); + } + if (s.back() != '"') { + throw HOAParserException("String does not end with quote: " + s); + } + std::string::size_type pos = s.find_first_of("\\", 1); // find first '\' + + if (pos == std::string::npos) { + // nothing to unquote, just remove outer quotes + return s.substr(1, s.length()-2); + } + + std::stringstream ss; + std::string::size_type last_pos = 1; + do { + ss << s.substr(last_pos, pos); // characters that don't need to be quoted + if (pos+1 >= s.length()) { + throw HOAParserException("String ends with \\ character: s"); + } + ss << s.substr(pos+1,1); // the quoted character + last_pos = pos+2; // skip quote character + pos = s.find_first_of("\\\"", last_pos); // find next '\' + } while (pos != std::string::npos); + + if (last_pos < s.length()-1) { + ss << s.substr(last_pos, s.length()-1-last_pos); // remaining + } + + return ss.str(); + } + +}; + +} + +#endif diff --git a/resources/3rdparty/cpphoafparser-0.99.2/include/cpphoafparser/util/acceptance_repository.hh b/resources/3rdparty/cpphoafparser-0.99.2/include/cpphoafparser/util/acceptance_repository.hh new file mode 100644 index 000000000..c4e1b5adb --- /dev/null +++ b/resources/3rdparty/cpphoafparser-0.99.2/include/cpphoafparser/util/acceptance_repository.hh @@ -0,0 +1,77 @@ +//============================================================================== +// +// Copyright (c) 2015- +// Authors: +// * Joachim Klein <klein@tcs.inf.tu-dresden.de> +// * David Mueller <david.mueller@tcs.inf.tu-dresden.de> +// +//------------------------------------------------------------------------------ +// +// This file is part of the cpphoafparser library, +// http://automata.tools/hoa/cpphoafparser/ +// +// The cpphoafparser 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. +// +// The cpphoafparser 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 CPPHOAFPARSER_ACCEPTANCEREPOSITORY_H +#define CPPHOAFPARSER_ACCEPTANCEREPOSITORY_H + +#include <stdexcept> +#include <memory> +#include "cpphoafparser/consumer/hoa_consumer.hh" + +namespace cpphoafparser { + +/** + * Virtual base class defining the interface to a repository of known acceptance names. + * This can be used to construct the canonical acceptance expression for a given acc-name header, + * i.e., the acceptance name (with the extra parameters) for known acceptance names. + */ +class AcceptanceRepository +{ +public: + /** A shared_ptr wrapping an AcceptanceRepository */ + typedef std::shared_ptr<AcceptanceRepository> ptr; + /** An acceptance condition expression */ + typedef HOAConsumer::acceptance_expr acceptance_expr; + + /** This exception is thrown if the extra arguments of an acc-name are malformed */ + class IllegalArgumentException : public std::runtime_error { + public: + /** Constructor */ + IllegalArgumentException(const std::string& s) : std::runtime_error(s) {} + }; + + /** Destructor */ + virtual ~AcceptanceRepository() {} + + /** + * For a given acc-name header, construct the corresponding canonical acceptance expression. + * If the acc-name is not known, returns an empty pointer. + * + * @param accName the acceptance name, as passed in an acc-name header + * @param extraInfo extra info, as passed in an acc-name header + * @return the canonical acceptance expression for this name, empty pointer if not known + * @throws IllegalParameterException if the acceptance name is known, but there is an error with the extraInfo + */ + virtual acceptance_expr::ptr getCanonicalAcceptanceExpression(const std::string& accName, const std::vector<IntOrString>& extraInfo) = 0; + +}; + +} + +#endif diff --git a/resources/3rdparty/cpphoafparser-0.99.2/include/cpphoafparser/util/acceptance_repository_standard.hh b/resources/3rdparty/cpphoafparser-0.99.2/include/cpphoafparser/util/acceptance_repository_standard.hh new file mode 100644 index 000000000..4080d6e71 --- /dev/null +++ b/resources/3rdparty/cpphoafparser-0.99.2/include/cpphoafparser/util/acceptance_repository_standard.hh @@ -0,0 +1,388 @@ +//============================================================================== +// +// Copyright (c) 2015- +// Authors: +// * Joachim Klein <klein@tcs.inf.tu-dresden.de> +// * David Mueller <david.mueller@tcs.inf.tu-dresden.de> +// +//------------------------------------------------------------------------------ +// +// This file is part of the cpphoafparser library, +// http://automata.tools/hoa/cpphoafparser/ +// +// The cpphoafparser 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. +// +// The cpphoafparser 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 CPPHOAFPARSER_ACCEPTANCEREPOSITORYSTANDARD_H +#define CPPHOAFPARSER_ACCEPTANCEREPOSITORYSTANDARD_H + +#include "cpphoafparser/util/acceptance_repository.hh" + +namespace cpphoafparser { + +/** + * An acceptance repository with all the acceptance conditions specified + * in the format specification. + */ +class AcceptanceRepositoryStandard : public AcceptanceRepository +{ +public: + + /** + * @name acc-name constants + * String constants for the various acceptance condition names */ + /**@{*/ + const char* ACC_ALL = "all"; + const char* ACC_NONE = "none"; + + const char* ACC_BUCHI = "Buchi"; + const char* ACC_COBUCHI = "coBuchi"; + + const char* ACC_GENERALIZED_BUCHI = "generalized-Buchi"; + const char* ACC_GENERALIZED_COBUCHI = "generalized-coBuchi"; + + const char* ACC_RABIN = "Rabin"; + const char* ACC_STREETT = "Streett"; + + const char* ACC_GENERALIZED_RABIN = "generalized-Rabin"; + + const char* ACC_PARITY = "parity"; + /**@}*/ + + virtual acceptance_expr::ptr getCanonicalAcceptanceExpression(const std::string& accName, + const std::vector<IntOrString>& extraInfo) override { + if (accName == ACC_ALL) + return forAll(extraInfo); + if (accName == ACC_NONE) + return forNone(extraInfo); + + if (accName == ACC_BUCHI) + return forBuchi(extraInfo); + if (accName == ACC_COBUCHI) + return forCoBuchi(extraInfo); + + if (accName == ACC_GENERALIZED_BUCHI) + return forGenBuchi(extraInfo); + if (accName == ACC_GENERALIZED_COBUCHI) + return forGenCoBuchi(extraInfo); + + if (accName == ACC_RABIN) + return forRabin(extraInfo); + if (accName == ACC_STREETT) + return forStreett(extraInfo); + if (accName == ACC_GENERALIZED_RABIN) + return forGeneralizedRabin(extraInfo); + + if (accName == ACC_PARITY) + return forParity(extraInfo); + + return acceptance_expr::ptr(); + } + + /** Construct canonical acceptance condition for 'all' */ + acceptance_expr::ptr forAll(const std::vector<IntOrString>& extraInfo) { + checkNumberOfArguments(ACC_ALL, extraInfo, 0); + + return acceptance_expr::True(); + } + + /** Construct canonical acceptance condition for 'none' */ + acceptance_expr::ptr forNone(const std::vector<IntOrString>& extraInfo) { + checkNumberOfArguments(ACC_ALL, extraInfo, 0); + + return acceptance_expr::False(); + } + + /** Construct canonical acceptance condition for 'Buchi' */ + acceptance_expr::ptr forBuchi(const std::vector<IntOrString>& extraInfo) { + checkNumberOfArguments(ACC_BUCHI, extraInfo, 0); + + return acceptance_expr::Atom(AtomAcceptance::Inf(0)); + } + + /** Construct canonical acceptance condition for 'coBuchi' */ + acceptance_expr::ptr forCoBuchi(const std::vector<IntOrString>& extraInfo) { + checkNumberOfArguments(ACC_COBUCHI, extraInfo, 0); + + return acceptance_expr::Atom(AtomAcceptance::Fin(0)); + } + + /** Construct canonical acceptance condition for 'generalized-Buchi' */ + acceptance_expr::ptr forGenBuchi(const std::vector<IntOrString>& extraInfo) { + checkNumberOfArguments(ACC_GENERALIZED_BUCHI, extraInfo, 1); + unsigned int numberOfInf = extraInfoToIntegerList(ACC_GENERALIZED_BUCHI, extraInfo).at(0); + + if (numberOfInf == 0) { + return acceptance_expr::True(); + } + + acceptance_expr::ptr result; + for (unsigned int i = 0; i < numberOfInf; i++) { + acceptance_expr::ptr inf = acceptance_expr::Atom(AtomAcceptance::Inf(i)); + + if (i == 0) { + result = inf; + } else { + result = result & inf; + } + } + + return result; + } + + /** Construct canonical acceptance condition for 'generalized-co-Buchi' */ + acceptance_expr::ptr forGenCoBuchi(const std::vector<IntOrString>& extraInfo) { + checkNumberOfArguments(ACC_GENERALIZED_COBUCHI, extraInfo, 1); + unsigned int numberOfFin = extraInfoToIntegerList(ACC_GENERALIZED_COBUCHI, extraInfo).at(0); + + if (numberOfFin == 0) { + return acceptance_expr::False(); + } + + acceptance_expr::ptr result; + for (unsigned int i = 0; i < numberOfFin; i++) { + acceptance_expr::ptr fin = acceptance_expr::Atom(AtomAcceptance::Fin(i)); + + if (i == 0) { + result = fin; + } else { + result = result & fin; + } + } + + return result; + } + + /** Construct canonical acceptance condition for 'Rabin' */ + acceptance_expr::ptr forRabin(const std::vector<IntOrString>& extraInfo) { + checkNumberOfArguments(ACC_RABIN, extraInfo, 1); + unsigned int numberOfPairs = extraInfoToIntegerList(ACC_RABIN, extraInfo).at(0); + + if (numberOfPairs == 0) { + return acceptance_expr::False(); + } + + acceptance_expr::ptr result; + for (unsigned int i = 0; i < numberOfPairs; i++) { + acceptance_expr::ptr fin = acceptance_expr::Atom(AtomAcceptance::Fin(2*i)); + acceptance_expr::ptr inf = acceptance_expr::Atom(AtomAcceptance::Inf(2*i+1)); + + acceptance_expr::ptr pair = fin & inf; + + if (i == 0) { + result = pair; + } else { + result = result | pair; + } + } + + return result; + } + + /** Construct canonical acceptance condition for 'Streett' */ + acceptance_expr::ptr forStreett(const std::vector<IntOrString>& extraInfo) { + checkNumberOfArguments(ACC_STREETT, extraInfo, 1); + unsigned int numberOfPairs = extraInfoToIntegerList(ACC_STREETT, extraInfo).at(0); + + if (numberOfPairs == 0) { + return acceptance_expr::True(); + } + + acceptance_expr::ptr result; + for (unsigned int i = 0; i < numberOfPairs; i++) { + acceptance_expr::ptr fin = acceptance_expr::Atom(AtomAcceptance::Fin(2*i)); + acceptance_expr::ptr inf = acceptance_expr::Atom(AtomAcceptance::Inf(2*i+1)); + + acceptance_expr::ptr pair = fin | inf; + + if (i == 0) { + result = pair; + } else { + result = result & pair; + } + } + + return result; + } + + /** Construct canonical acceptance condition for 'generalized-Rabin' */ + acceptance_expr::ptr forGeneralizedRabin(const std::vector<IntOrString>& extraInfo) { + std::vector<unsigned int> parameters = extraInfoToIntegerList(ACC_GENERALIZED_RABIN, extraInfo); + + if (parameters.size() == 0) { + throw IllegalArgumentException(std::string("Acceptance ")+ACC_GENERALIZED_RABIN+" needs at least one argument"); + } + + unsigned int numberOfPairs = parameters.at(0); + if (parameters.size() != numberOfPairs + 1) { + throw IllegalArgumentException(std::string("Acceptance ")+ACC_GENERALIZED_RABIN+" with " + std::to_string(numberOfPairs) +" generalized pairs: There is not exactly one argument per pair"); + } + + acceptance_expr::ptr result; + int currentIndex = 0; + for (unsigned int i = 0; i < numberOfPairs; i++) { + unsigned int numberOfInf = parameters.at(i+1); + + acceptance_expr::ptr fin = acceptance_expr::Atom(AtomAcceptance::Fin(currentIndex++)); + acceptance_expr::ptr pair = fin; + for (unsigned int j = 0; j< numberOfInf; j++) { + acceptance_expr::ptr inf = acceptance_expr::Atom(AtomAcceptance::Inf(currentIndex++)); + pair = pair & inf; + } + + if (i == 0) { + result = pair; + } else { + result = result | pair; + } + } + + return result; + } + + /** Construct canonical acceptance condition for 'parity' */ + acceptance_expr::ptr forParity(const std::vector<IntOrString>& extraInfo) { + checkNumberOfArguments(ACC_PARITY, extraInfo, 3); + + bool min = false; + bool even = false; + + const std::string& minMax = extraInfoToString(ACC_PARITY, extraInfo, 0); + if (minMax == "min") { + min = true; + } else if (minMax == "max") { + min = false; + } else { + throw IllegalArgumentException(std::string("For acceptance ") + ACC_PARITY +", the first argument has to be either 'min' or 'max'"); + } + const std::string& evenOdd = extraInfoToString(ACC_PARITY, extraInfo, 1); + if (evenOdd == "even") { + even = true; + } else if (evenOdd == "odd") { + even = false; + } else { + throw IllegalArgumentException(std::string("For acceptance ") + ACC_PARITY +", the second argument has to be either 'even' or 'odd'"); + } + + unsigned int colors; + if (!(extraInfo.at(2).isInteger())) { + throw IllegalArgumentException(std::string("For acceptance ") + ACC_PARITY + ", the third argument has to be the number of colors"); + } + colors = extraInfo.at(2).getInteger(); + + if (colors == 0) { + if ( min && even) return BooleanExpression<AtomAcceptance>::True(); + if (!min && even) return BooleanExpression<AtomAcceptance>::False(); + if ( min && !even) return BooleanExpression<AtomAcceptance>::False(); + if (!min && !even) return BooleanExpression<AtomAcceptance>::True(); + } + + acceptance_expr::ptr result; + + bool reversed = min; + bool infOnOdd = !even; + + for (unsigned int i = 0; i < colors; i++) { + unsigned int color = (reversed ? colors-i-1 : i); + + bool produceInf; + if (color % 2 == 0) { + produceInf = !infOnOdd; + } else { + produceInf = infOnOdd; + } + + acceptance_expr::ptr node; + if (produceInf) { + node.reset(new BooleanExpression<AtomAcceptance>(AtomAcceptance::Inf(color))); + } else { + node.reset(new BooleanExpression<AtomAcceptance>(AtomAcceptance::Fin(color))); + } + + if (result) { + if (produceInf) { + // Inf always with | + result = node | result; + } else { + // Fin always with & + result = node & result; + } + } else { + result = node; + } + } + + return result; + } + + private: + + /** + * Convert an extra info vector to an integer list. + * @param accName the name of the acceptance condition (for error messages) + * @param extraInfo the vector + */ + std::vector<unsigned int> extraInfoToIntegerList(const std::string& accName, const std::vector<IntOrString>& extraInfo) + { + std::vector<unsigned int> result; + for (IntOrString i : extraInfo) { + if (!(i.isInteger())) { + throw IllegalArgumentException("For acceptance " + accName + ", all arguments have to be integers"); + } + + result.push_back(i.getInteger()); + } + + return result; + } + + /** Extract a string from extraInfo at a given index, throw exception otherwise. + * @param accName the name of the acceptance condition (for error messages) + * @param extraInfo the vector + * @param index the index into the extraInfo vector + */ + const std::string& extraInfoToString(const std::string& accName, const std::vector<IntOrString>& extraInfo, unsigned int index) { + if (!extraInfo.at(index).isString()) { + throw IllegalArgumentException(std::string("Argument ")+std::to_string(index-1)+" for acceptance " + accName +" has to be a string!"); + } + return extraInfo.at(index).getString(); + } + + /** + * Check that the number of arguments in the extraInfo vector is as expected. + * If that's not the case, throw an IllegalArgumentException. + * @param accName the acceptance condition name (for error message) + * @param extraInfo the extraInfo vector + * @param expectedNumberOfArguments the expected number of elements in the extraInfo vector + */ + void checkNumberOfArguments(const std::string& accName, const std::vector<IntOrString>& extraInfo, unsigned int expectedNumberOfArguments) + { + if (expectedNumberOfArguments != extraInfo.size()) { + throw IllegalArgumentException("For acceptance " + + accName + + ", expected " + + std::to_string(expectedNumberOfArguments) + + " arguments, got " + + std::to_string(extraInfo.size())); + } + } + +}; + +} + +#endif diff --git a/resources/3rdparty/cpphoafparser-0.99.2/include/cpphoafparser/util/dynamic_bitset.hh b/resources/3rdparty/cpphoafparser-0.99.2/include/cpphoafparser/util/dynamic_bitset.hh new file mode 100644 index 000000000..b2ad5490d --- /dev/null +++ b/resources/3rdparty/cpphoafparser-0.99.2/include/cpphoafparser/util/dynamic_bitset.hh @@ -0,0 +1,124 @@ +//============================================================================== +// +// Copyright (c) 2015- +// Authors: +// * Joachim Klein <klein@tcs.inf.tu-dresden.de> +// * David Mueller <david.mueller@tcs.inf.tu-dresden.de> +// +//------------------------------------------------------------------------------ +// +// This file is part of the cpphoafparser library, +// http://automata.tools/hoa/cpphoafparser/ +// +// The cpphoafparser 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. +// +// The cpphoafparser 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 CPPHOAFPARSER_DYNAMICBITSET_H +#define CPPHOAFPARSER_DYNAMICBITSET_H + +#include <vector> + +namespace cpphoafparser { + +/** + * A dynamic bitset that grows automatically. + * Inherits the functionality of std::vector<bool>, adding + * convenience functions. + **/ +class dynamic_bitset : public std::vector<bool> { +public: + + /** + * Set the bit at the given `index` to `value`. + * It `index` is larger than the highest set bit, + * the intermediate bits are set to `false`. + */ + void set(std::size_t index, bool value=true) { + if (index >= size()) { + resize(index+1, false); + } + + at(index) = value; + } + + /** + * Get the bit at the given `index`. + * If `index` is beyond the highest set bit + * then return false. + */ + bool get(std::size_t index) const { + if (index >= size()) { + return false; + } + + return at(index); + } + + /** + * Returns the index of the highest set bit. + * The actual return value is a pair, where the first + * element is the index of the highest set bit (if there + * are any) and the second element being false + * if there is no set bit at all. + */ + std::pair<std::size_t,bool> getHighestSetBit() const { + if (size() == 0) { + return std::make_pair(0, false); + } + for (std::size_t index = size(); index > 0; index--) { + if ((*this)[index-1]) { + return std::make_pair(index-1, true); + } + } + return std::make_pair(0, false); + } + + /** + * Returns the cardinality (the number of set bits) of this + * bitset. + */ + std::size_t cardinality() const { + std::size_t result = 0; + for (bool b : *this) { + if (b) result++; + } + return result; + } + + /** + * Perform andNot operator on this bitset. + * After calling this function a bit is set in this bitset + * if it was set before and if the corresponding bit in + * `other` is not set. + */ + void andNot(const dynamic_bitset& other) { + for (std::size_t index = 0; index < size() && index < other.size(); index++) { + at(index) = at(index) & !other.at(index); + } + } + + /** Returns `true` if there are not set bits */ + bool isEmpty() const { + for (bool b : *this) { + if (b) return false; + } + return true; + } + +}; + +} +#endif diff --git a/resources/3rdparty/cpphoafparser-0.99.2/include/cpphoafparser/util/implicit_edge_helper.hh b/resources/3rdparty/cpphoafparser-0.99.2/include/cpphoafparser/util/implicit_edge_helper.hh new file mode 100644 index 000000000..34c96c4b4 --- /dev/null +++ b/resources/3rdparty/cpphoafparser-0.99.2/include/cpphoafparser/util/implicit_edge_helper.hh @@ -0,0 +1,156 @@ +//============================================================================== +// +// Copyright (c) 2015- +// Authors: +// * Joachim Klein <klein@tcs.inf.tu-dresden.de> +// * David Mueller <david.mueller@tcs.inf.tu-dresden.de> +// +//------------------------------------------------------------------------------ +// +// This file is part of the cpphoafparser library, +// http://automata.tools/hoa/cpphoafparser/ +// +// The cpphoafparser 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. +// +// The cpphoafparser 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 CPPHOAFPARSER_IMPLICITEDGEHELPER_H +#define CPPHOAFPARSER_IMPLICITEDGEHELPER_H + +#include "cpphoafparser/consumer/hoa_consumer_exception.hh" + +#include <exception> +#include <string> + +namespace cpphoafparser { + +/** + * Helper for keeping track of implicit edges. + * + * In `notifyBodyStart()`, call:<br> + * `helper = new ImplicitEdgeHelper(numberOfAPs);` + * + * In `addState()`, call:<br> + * `helper.startOfState(stateId);` + * + * In `addEdgeImplicit()`, call:<br> + * edgeIndex = helper.nextImplicitEdge();` + * + * In `notifyEndOfState()`, call:<br> + * `helper.endOfState();` + */ +class ImplicitEdgeHelper +{ +public: + + /** Constructor, pass number of atomic propositions */ + ImplicitEdgeHelper(unsigned int numberOfAPs) : + numberOfAPs(numberOfAPs), stateId(0) + { + edgesPerState = ((std::size_t)1) << numberOfAPs; + } + + /** Return the expected number of edges per state, i.e., 2^|AP|. */ + std::size_t getEdgesPerState() + { + return edgesPerState; + } + + /** Notify the ImplicitEdgeHelper that a new state definition has been encountered. + * @param newStateId the state index (for error message) + * @throws std::logic_error if `startOfState()` is called before another state is finished with a call to `endOfState() + */ + void startOfState(unsigned int newStateId) + { + if (inState) { + throw std::logic_error("ImplicitEdgeHelper: startOfState(" + + std::to_string(newStateId) + + ") without previous call to endOfState()"); + } + + edgeIndex = 0; + stateId = newStateId; + inState = true; + } + + /** Notify the ImplicitEdgeHelper that the next implicit edge for the current state has been encountered. + * Return the edge index. + * @return the index of the current edge + * @throws HOAConsumerException if the number of edges is more than 2^numberOfAPs + * @throws std::logic_error if this function is called without a previous call to `startOfState() + * */ + std::size_t nextImplicitEdge() + { + if (!inState) { + throw std::logic_error("ImplicitEdgeHelper: nextImplicitEdge() without previous call to startOfState()"); + } + + unsigned long currentEdgeIndex = edgeIndex; + edgeIndex++; + + if (currentEdgeIndex >= edgesPerState) { + throw HOAConsumerException("For state " + +std::to_string(stateId) + +", more edges than allowed for " + +std::to_string(numberOfAPs) + +" atomic propositions"); + } + + return currentEdgeIndex; + } + + /** Notify the ImplicitEdgeHelper that the current state definition is finished. + * Checks the number of encountered implicit edges against the expected number. + * If there are no implicit edges for the current state, that's fine as well. + * @throws HOAConsumerException if there are more then zero and less then 2^numberOfAPs edges + * @throws std::logic_error if `endOfState()` is called without previous call to `startOfState()` + */ + void endOfState() + { + if (!inState) { + throw std::logic_error("ImplicitEdgeHelper: endOfState() without previous call to startOfState()"); + } + + inState = false; + + if (edgeIndex >0 && edgeIndex != edgesPerState) { + throw HOAConsumerException("For state " + + std::to_string(stateId) + + ", less edges than required for " + + std::to_string(numberOfAPs) + + " atomic propositions"); + } + } + +private: + /** The number of atomic propositions */ + unsigned int numberOfAPs; + + /** The index of the current edge */ + std::size_t edgeIndex = 0; + + /** The required number of edges per state */ + std::size_t edgesPerState; + + /** Are we currently in a state definition? */ + bool inState = false; + + /** The current state index (for error message) */ + std::size_t stateId = 0; + +}; + +} +#endif diff --git a/resources/3rdparty/cpphoafparser-0.99.2/include/cpphoafparser/util/int_or_string.hh b/resources/3rdparty/cpphoafparser-0.99.2/include/cpphoafparser/util/int_or_string.hh new file mode 100644 index 000000000..74b1201d8 --- /dev/null +++ b/resources/3rdparty/cpphoafparser-0.99.2/include/cpphoafparser/util/int_or_string.hh @@ -0,0 +1,116 @@ +//============================================================================== +// +// Copyright (c) 2015- +// Authors: +// * Joachim Klein <klein@tcs.inf.tu-dresden.de> +// * David Mueller <david.mueller@tcs.inf.tu-dresden.de> +// +//------------------------------------------------------------------------------ +// +// This file is part of the cpphoafparser library, +// http://automata.tools/hoa/cpphoafparser/ +// +// The cpphoafparser 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. +// +// The cpphoafparser 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 CPPHOAFPARSER_INTORSTRING_H +#define CPPHOAFPARSER_INTORSTRING_H + +#include <string> +#include <stdexcept> + +#include "cpphoafparser/parser/hoa_parser_helper.hh" + +namespace cpphoafparser { + +/** + * Utility class for storing either an integer or a string value. + * The stored value is immutable. + */ +class IntOrString { +public: + /** Constructor for storing an integer. */ + IntOrString(unsigned int vInteger) : vInteger(vInteger), vString(nullptr), wasQuoted(false) {} + /** + * Constructor for storing a string. + * @param vString the string to store + * @param wasQuoted remember that the string was originally quoted + */ + IntOrString(const std::string& vString, bool wasQuoted = false) : vInteger(0), vString(new std::string(vString)), wasQuoted(wasQuoted) {} + + /** Returns true if the stored value is a string */ + bool isString() const {return (bool)vString;} + + /** Returns true if the stored value is an integer */ + bool isInteger() const {return !isString();} + + /** + * Returns whether this string was originally quoted. + * May only be called if `isString() == true`. + **/ + bool wasStringQuoted() const { + if (!isString()) {throw std::logic_error("Illegal access");} + return wasQuoted; + } + + /** + * Returns (a const reference to) the stored string. + * May only be called if `isString() == true`. + **/ + const std::string& getString() const { + if (!isString()) {throw std::logic_error("Illegal access");} + return *vString; + } + + /** + * Returns the stored integer. + * May only be called if `isInteger() == true`. + **/ + unsigned int getInteger() const { + if (!isInteger()) {throw std::logic_error("Illegal access");} + return vInteger; + } + + /** + * Stream output operator for IntOrString. + * If the stored value is a string that is marked as having been quoted, + * will quote the string before output. + */ + friend std::ostream& operator<<(std::ostream& out, const IntOrString& intOrString) { + if (intOrString.isInteger()) { + out << intOrString.getInteger(); + } else { + if (intOrString.wasQuoted) { + HOAParserHelper::print_quoted(out, intOrString.getString()); + } else { + out << intOrString.getString(); + } + } + return out; + } + +private: + /** The stored integer value */ + unsigned int vInteger; + /** The stored string value */ + std::shared_ptr<std::string> vString; + /** Was this string originally quoted? */ + bool wasQuoted; +}; + +} +#endif diff --git a/resources/3rdparty/cpphoafparser-0.99.2/src/CMakeLists.txt b/resources/3rdparty/cpphoafparser-0.99.2/src/CMakeLists.txt new file mode 100644 index 000000000..e471884e3 --- /dev/null +++ b/resources/3rdparty/cpphoafparser-0.99.2/src/CMakeLists.txt @@ -0,0 +1,15 @@ +cmake_minimum_required(VERSION 2.6) +cmake_policy(SET CMP0054 OLD) +PROJECT( cpphoaf ) + +INCLUDE_DIRECTORIES("../include") + +IF ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang" OR + "${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU") + IF ("${CMAKE_CXX_FLAGS}" STREQUAL "") + # Only set flags if there has been no flag set + SET (CMAKE_CXX_FLAGS "-std=c++11 -Wall" CACHE STRING "Flags used by the compiler during all build types." FORCE) + ENDIF() +ENDIF() + +ADD_EXECUTABLE ( cpphoaf cpphoaf.cc ) diff --git a/resources/3rdparty/cpphoafparser-0.99.2/src/basic_parser_1.cc b/resources/3rdparty/cpphoafparser-0.99.2/src/basic_parser_1.cc new file mode 100644 index 000000000..7f6db98fd --- /dev/null +++ b/resources/3rdparty/cpphoafparser-0.99.2/src/basic_parser_1.cc @@ -0,0 +1,19 @@ +#include "cpphoafparser/consumer/hoa_consumer_print.hh" +#include "cpphoafparser/parser/hoa_parser.hh" + +using namespace cpphoafparser; + +/** The most basic HOA parser: Read an automaton from input and print it to the output. */ +int main(int argc, const char* argv[]) { + HOAConsumer::ptr consumer(new HOAConsumerPrint(std::cout)); + + try { + + HOAParser::parse(std::cin, consumer); + + } catch (std::exception& e) { + std::cerr << e.what() << std::endl; + return 1; + } + return 0; +} diff --git a/resources/3rdparty/cpphoafparser-0.99.2/src/basic_parser_2.cc b/resources/3rdparty/cpphoafparser-0.99.2/src/basic_parser_2.cc new file mode 100644 index 000000000..074524228 --- /dev/null +++ b/resources/3rdparty/cpphoafparser-0.99.2/src/basic_parser_2.cc @@ -0,0 +1,40 @@ +#include "cpphoafparser/consumer/hoa_intermediate.hh" +#include "cpphoafparser/consumer/hoa_consumer_null.hh" +#include "cpphoafparser/parser/hoa_parser.hh" + +using namespace cpphoafparser; + +/* An HOAIntermediate that counts invocations of addState */ +class CountStates : public HOAIntermediate { +public: + typedef std::shared_ptr<CountStates> ptr; + unsigned int count = 0; + + CountStates(HOAConsumer::ptr next) : HOAIntermediate(next) { + } + + virtual void addState(unsigned int id, + std::shared_ptr<std::string> info, + label_expr::ptr labelExpr, + std::shared_ptr<int_list> accSignature) override { + count++; + next->addState(id, info, labelExpr, accSignature); + } +}; + +/** Demonstrating the use of HOAIntermediates */ +int main(int argc, const char* argv[]) { + HOAConsumer::ptr hoaNull(new HOAConsumerNull()); + CountStates::ptr counter(new CountStates(hoaNull)); + + try { + + HOAParser::parse(std::cin, counter); + std::cout << "Number of state definitions = " << counter->count << std::endl; + + } catch (std::exception& e) { + std::cerr << e.what() << std::endl; + return 1; + } + return 0; +} diff --git a/resources/3rdparty/cpphoafparser-0.99.2/src/cpphoaf.cc b/resources/3rdparty/cpphoafparser-0.99.2/src/cpphoaf.cc new file mode 100644 index 000000000..ae653fbf6 --- /dev/null +++ b/resources/3rdparty/cpphoafparser-0.99.2/src/cpphoaf.cc @@ -0,0 +1,203 @@ +//============================================================================== +// +// Copyright (c) 2015- +// Authors: +// * Joachim Klein <klein@tcs.inf.tu-dresden.de> +// * David Mueller <david.mueller@tcs.inf.tu-dresden.de> +// +//------------------------------------------------------------------------------ +// +// This file is part of the cpphoafparser library, +// http://automata.tools/hoa/cpphoafparser/ +// +// The cpphoafparser 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. +// +// The cpphoafparser 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 <queue> +#include <iostream> +#include <fstream> + +#include "cpphoafparser/consumer/hoa_consumer_print.hh" +#include "cpphoafparser/consumer/hoa_consumer_null.hh" +#include "cpphoafparser/consumer/hoa_intermediate_trace.hh" +#include "cpphoafparser/consumer/hoa_intermediate_resolve_aliases.hh" +#include "cpphoafparser/parser/hoa_parser.hh" + +using namespace cpphoafparser; + +/** The version */ +static const char* version = "0.99.2"; + +/** Print version to out, verbose? */ +static void printVersion(std::ostream& out, bool verbose) { + out << "cpphoafparser library - command line tool (version " << version << ")" << std::endl; + out << " (C) Copyright 2015- Joachim Klein, David Mueller" << std::endl; + out << " http://automata.tools/hoa/cpphoafparser/" << std::endl; + out << std::endl; + + if (verbose) { + out << "The cpphoafparser library is free software; you can redistribute it and/or" << std::endl; + out << "modify it under the terms of the GNU Lesser General Public" << std::endl; + out << "License as published by the Free Software Foundation; either" << std::endl; + out << "version 2.1 of the License, or (at your option) any later version." << std::endl; + out << std::endl; + out << "The cpphoafparser library is distributed in the hope that it will be useful," << std::endl; + out << "but WITHOUT ANY WARRANTY; without even the implied warranty of" << std::endl; + out << "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU" << std::endl; + out << "Lesser General Public License for more details." << std::endl; + } +} + +/** Print usage information, and optionally error message */ +static unsigned int usage(const std::string& error = "") { + + printVersion(std::cerr, false); + + if (error != "") { + std::cerr << "Command-line arguments error: " << error << std::endl; + std::cerr << "Use argument 'help' to get usage information." << std::endl; + return 2; + } + + std::cerr << "Arguments:" << std::endl; + std::cerr << " command [flags]* file" << std::endl << std::endl; + + std::cerr << " Valid commands:" << std::endl; + std::cerr << " parse Parse the HOAF file and check for errors" << std::endl; + std::cerr << " print Parse the HOAF file, perform any specified transformations" << std::endl; + std::cerr << " and print the parsed automata to standard out" << std::endl; + std::cerr << " version Print the version and exit" << std::endl; + std::cerr << " help Print this help screen and exit" << std::endl; + std::cerr << std::endl; + std::cerr << " file can be a filename or - to request reading from standard input" << std::endl; + std::cerr << std::endl; + std::cerr << " Valid flags:" << std::endl; + std::cerr << " --resolve-aliases Resolve aliases" << std::endl; + std::cerr << " --no-validate Do not perform semantic validation" << std::endl; + std::cerr << " --trace Debugging: Trace the function calls to HOAConsumer" << std::endl; +// std::cerr << " --verbose Increase verbosity" << std::endl; + + return (error != "" ? 2 : 0); +} + + + +int main(int argc, char* argv[]) { + bool verbose = false; + bool resolve_aliases = false; + bool trace = false; + bool validate = true; + + std::queue<std::string> arguments; + for (int i=1; i<argc; i++) { + arguments.push(argv[i]); + } + + if (arguments.size() == 0) { + return usage(); + } + + std::string command = arguments.front(); + arguments.pop(); + if (command == "help" || command == "--help") { + return usage(); + } + if (command == "version") { + printVersion(std::cout, true); + return 0; + } + + while (!arguments.empty()) { + const std::string& arg = arguments.front(); + if (arg.compare(0, 2, "--") == 0) { + // is an argument + arguments.pop(); + if (arg == "--resolve-aliases") { + resolve_aliases = true; + } else if (arg == "--trace") { + trace = true; + } else if (arg == "--no-validate") { + validate = false; + } else if (arg == "--") { + // end of arguments + break; + } else { + return usage("Unknown argument "+arg); + } + } + // not an argument + break; + } + + + if (arguments.empty()) { + return usage("Missing filename (or - for standard input)"); + } + + if (arguments.size() > 1) { + return usage("More than one filename, currently only supports single file"); + } + + std::string filename = arguments.front(); + arguments.pop(); + std::shared_ptr<std::ifstream> f_in; + if (filename != "-") { + f_in.reset(new std::ifstream(filename.c_str())); + if (!*f_in) { + std::cerr << "Error opening file " + filename << std::endl; + return 1; + } + } + std::istream& in = (filename == "-" ? std::cin : *f_in); + + if (verbose) { + std::cerr << "Reading from " + (filename != "-" ? "file "+filename : "standard input") << std::endl; + } + + HOAConsumer::ptr consumer; + if (command == "print") { + consumer.reset(new HOAConsumerPrint(std::cout)); + } else if (command == "parse") { + consumer.reset(new HOAConsumerNull()); + } else { + return usage("Unknown command: "+command); + } + + if (resolve_aliases) { + consumer.reset(new HOAIntermediateResolveAliases(consumer)); + } + + if (trace) { + consumer.reset(new HOAIntermediateTrace(consumer)); + } + + try { + HOAParser::parse(in, consumer, validate); + + if (command == "parse") { + std::cout << "Parsing OK" << std::endl; + } + + return 0; + } catch (HOAParserException& e) { + std::cerr << e.what() << std::endl; + } catch (HOAConsumerException& e) { + std::cerr << "Exception: " << e.what() << std::endl; + } + return 1; +} + + diff --git a/resources/3rdparty/include_cudd.cmake b/resources/3rdparty/include_cudd.cmake index 6ed57d456..16b045306 100644 --- a/resources/3rdparty/include_cudd.cmake +++ b/resources/3rdparty/include_cudd.cmake @@ -54,7 +54,7 @@ ExternalProject_Add( PATCH_COMMAND ${AUTORECONF} CONFIGURE_COMMAND ${STORM_3RDPARTY_SOURCE_DIR}/cudd-3.0.0/configure --enable-shared --enable-obj --with-pic=yes --prefix=${STORM_3RDPARTY_BINARY_DIR}/cudd-3.0.0 --libdir=${CUDD_LIB_DIR} CC=${CMAKE_C_COMPILER} CXX=${CUDD_CXX_COMPILER} ${CUDD_INCLUDE_FLAGS} BUILD_COMMAND make ${STORM_CUDD_FLAGS} - INSTALL_COMMAND make install + INSTALL_COMMAND make install -j${STORM_RESOURCES_BUILD_JOBCOUNT} BUILD_IN_SOURCE 0 LOG_CONFIGURE ON LOG_BUILD ON diff --git a/resources/3rdparty/include_glpk.cmake b/resources/3rdparty/include_glpk.cmake index 87c3ebcfa..b2aef3dad 100644 --- a/resources/3rdparty/include_glpk.cmake +++ b/resources/3rdparty/include_glpk.cmake @@ -17,7 +17,7 @@ else() SOURCE_DIR ${STORM_3RDPARTY_SOURCE_DIR}/glpk-4.65 CONFIGURE_COMMAND ${STORM_3RDPARTY_SOURCE_DIR}/glpk-4.65/configure --prefix=${STORM_3RDPARTY_BINARY_DIR}/glpk-4.65 --libdir=${GLPK_LIB_DIR} CC=${CMAKE_C_COMPILER} CXX=${CMAKE_CXX_COMPILER} ${GLPK_INCLUDE_FLAGS} BUILD_COMMAND make "CFLAGS=-O3 -w" - INSTALL_COMMAND make install + INSTALL_COMMAND make install -j${STORM_RESOURCES_BUILD_JOBCOUNT} BUILD_IN_SOURCE 0 LOG_CONFIGURE ON LOG_BUILD ON diff --git a/resources/3rdparty/include_spot.cmake b/resources/3rdparty/include_spot.cmake new file mode 100644 index 000000000..e7c138b2c --- /dev/null +++ b/resources/3rdparty/include_spot.cmake @@ -0,0 +1,54 @@ +set(STORM_HAVE_SPOT OFF) + +if(STORM_USE_SPOT_SYSTEM) + # try to find Spot on the system + if (NOT "${SPOT_ROOT}" STREQUAL "") + message(STATUS "Storm - searching for Spot in ${SPOT_ROOT}") + find_package(SPOT QUIET PATHS ${SPOT_ROOT} NO_DEFAULT_PATH) + endif() + if (NOT SPOT_FOUND) + find_package(SPOT QUIET) + endif() + + if (SPOT_FOUND) + message(STATUS "Storm - Using system version of Spot ${SPOT_VERSION} (include: ${SPOT_INCLUDE_DIR}, library: ${SPOT_LIBRARIES}).") + set(STORM_HAVE_SPOT ON) + elseif(NOT STORM_USE_SPOT_SHIPPED) + message (WARNING "Storm - Could not find Spot. Model checking of LTL formulas (beyond PCTL) will not be supported. You may want to set cmake option STORM_USE_SPOT_SHIPPED to install Spot automatically. If you already installed Spot, consider setting cmake option SPOT_ROOT. Unset STORM_USE_SPOT_SYSTEM to silence this warning.") + endif() +elseif() +endif() + +set(STORM_SHIPPED_SPOT OFF) +if(STORM_USE_SPOT_SHIPPED AND NOT STORM_HAVE_SPOT) + + # download and install shipped Spot + ExternalProject_Add(spot + URL http://www.lrde.epita.fr/dload/spot/spot-2.9.6.tar.gz # When updating, also change version output below + DOWNLOAD_NO_PROGRESS TRUE + DOWNLOAD_DIR ${STORM_3RDPARTY_BINARY_DIR}/spot_src + SOURCE_DIR ${STORM_3RDPARTY_BINARY_DIR}/spot_src + PREFIX ${STORM_3RDPARTY_BINARY_DIR}/spot + CONFIGURE_COMMAND ${STORM_3RDPARTY_BINARY_DIR}/spot_src/configure --prefix=${STORM_3RDPARTY_BINARY_DIR}/spot --disable-python + BUILD_COMMAND make -j${STORM_RESOURCES_BUILD_JOBCOUNT} + INSTALL_COMMAND make install + LOG_CONFIGURE ON + LOG_BUILD ON + LOG_INSTALL ON + BUILD_BYPRODUCTS ${STORM_3RDPARTY_BINARY_DIR}/spot/lib/libspot${DYNAMIC_EXT} + ) + add_dependencies(resources spot) + set(SPOT_INCLUDE_DIR "${STORM_3RDPARTY_BINARY_DIR}/spot/include/") + set(SPOT_DIR "${STORM_3RDPARTY_BINARY_DIR}/spot/") + set(SPOT_LIBRARIES ${STORM_3RDPARTY_BINARY_DIR}/spot/lib/libspot${DYNAMIC_EXT}) + set(STORM_HAVE_SPOT ON) + set(STORM_SHIPPED_SPOT ON) + + message(STATUS "Storm - Using shipped version of Spot 2.9.6 (include: ${SPOT_INCLUDE_DIR}, library ${SPOT_LIBRARIES}).") + +endif() + +if (STORM_HAVE_SPOT) + include_directories("${SPOT_INCLUDE_DIR}") + list(APPEND STORM_LINK_LIBRARIES ${SPOT_LIBRARIES}) +endif() diff --git a/resources/3rdparty/sylvan/src/storm_wrapper.cpp b/resources/3rdparty/sylvan/src/storm_wrapper.cpp index b0a10c1b8..82c67f8f0 100644 --- a/resources/3rdparty/sylvan/src/storm_wrapper.cpp +++ b/resources/3rdparty/sylvan/src/storm_wrapper.cpp @@ -42,8 +42,8 @@ void storm_rational_number_init(storm_rational_number_ptr* a) { #ifndef RATIONAL_NUMBER_THREAD_SAFE std::lock_guard<std::mutex> lock(rationalNumberMutex); #endif - - storm_rational_number_ptr srn_ptr = new storm::RationalNumber(*((storm::RationalNumber*)(*a))); + + storm_rational_number_ptr srn_ptr = new storm::RationalNumber(*(static_cast<storm::RationalNumber*>(*a))); *a = srn_ptr; } @@ -51,8 +51,8 @@ void storm_rational_number_destroy(storm_rational_number_ptr a) { #ifndef RATIONAL_NUMBER_THREAD_SAFE std::lock_guard<std::mutex> lock(rationalNumberMutex); #endif - - storm::RationalNumber* srn_ptr = (storm::RationalNumber*)a; + + storm::RationalNumber* srn_ptr = static_cast<storm::RationalNumber*>(a); delete srn_ptr; } @@ -60,10 +60,10 @@ int storm_rational_number_equals(storm_rational_number_ptr a, storm_rational_num #ifndef RATIONAL_NUMBER_THREAD_SAFE std::lock_guard<std::mutex> lock(rationalNumberMutex); #endif - - storm::RationalNumber const& srn_a = *(storm::RationalNumber*)a; - storm::RationalNumber const& srn_b = *(storm::RationalNumber*)b; - + + storm::RationalNumber const& srn_a = *static_cast<storm::RationalNumber*>(a); + storm::RationalNumber const& srn_b = *static_cast<storm::RationalNumber*>(b); + return (srn_a == srn_b) ? 1 : 0; } @@ -71,16 +71,16 @@ char* storm_rational_number_to_str(storm_rational_number_ptr val, char *buf, siz #ifndef RATIONAL_NUMBER_THREAD_SAFE std::lock_guard<std::mutex> lock(rationalNumberMutex); #endif - + std::stringstream ss; - storm::RationalNumber const& srn_a = *(storm::RationalNumber*)val; + storm::RationalNumber const& srn_a = *static_cast<storm::RationalNumber*>(val); ss << srn_a; std::string s = ss.str(); if (s.size() + 1 < buflen) { std::memcpy(buf, s.c_str(), s.size() + 1); return buf; } else { - char* result = (char*)malloc(s.size() + 1); + char* result = static_cast<char*>(malloc(s.size() + 1)); std::memcpy(result, s.c_str(), s.size() + 1); return result; } @@ -90,53 +90,53 @@ storm_rational_number_ptr storm_rational_number_clone(storm_rational_number_ptr #ifndef RATIONAL_NUMBER_THREAD_SAFE std::lock_guard<std::mutex> lock(rationalNumberMutex); #endif - - storm::RationalNumber* result_srn = new storm::RationalNumber(*((storm::RationalNumber const*)a)); - return (storm_rational_number_ptr)result_srn; + + storm::RationalNumber* result_srn = new storm::RationalNumber(*static_cast<storm::RationalNumber const*>(a)); + return static_cast<storm_rational_number_ptr>(result_srn); } storm_rational_number_ptr storm_rational_number_get_zero() { #ifndef RATIONAL_NUMBER_THREAD_SAFE std::lock_guard<std::mutex> lock(rationalNumberMutex); #endif - + storm::RationalNumber* result_srn = new storm::RationalNumber(storm::utility::zero<storm::RationalNumber>()); - return (storm_rational_number_ptr)result_srn; + return static_cast<storm_rational_number_ptr>(result_srn); } storm_rational_number_ptr storm_rational_number_get_one() { #ifndef RATIONAL_NUMBER_THREAD_SAFE std::lock_guard<std::mutex> lock(rationalNumberMutex); #endif - + storm::RationalNumber* result_srn = new storm::RationalNumber(storm::utility::one<storm::RationalNumber>()); - return (storm_rational_number_ptr)result_srn; + return static_cast<storm_rational_number_ptr>(result_srn); } storm_rational_number_ptr storm_rational_number_get_infinity() { #ifndef RATIONAL_NUMBER_THREAD_SAFE std::lock_guard<std::mutex> lock(rationalNumberMutex); #endif - + storm::RationalNumber* result_srn = new storm::RationalNumber(storm::utility::infinity<storm::RationalNumber>()); - return (storm_rational_number_ptr)result_srn; + return static_cast<storm_rational_number_ptr>(result_srn); } int storm_rational_number_is_zero(storm_rational_number_ptr a) { #ifndef RATIONAL_NUMBER_THREAD_SAFE std::lock_guard<std::mutex> lock(rationalNumberMutex); #endif - - return storm::utility::isZero(*(storm::RationalNumber const*)a) ? 1 : 0; + + return storm::utility::isZero(*static_cast<storm::RationalNumber const*>(a)) ? 1 : 0; } uint64_t storm_rational_number_hash(storm_rational_number_ptr const a, uint64_t const seed) { #ifndef RATIONAL_NUMBER_THREAD_SAFE std::lock_guard<std::mutex> lock(rationalNumberMutex); #endif - - storm::RationalNumber const& srn_a = *(storm::RationalNumber const*)a; - + + storm::RationalNumber const& srn_a = *static_cast<storm::RationalNumber const*>(a); + // Taken from boost::hash_combine that we do not call here for the lack of boost headers. return seed ^ (std::hash<storm::RationalNumber>()(srn_a) + 0x9e3779b9 + (seed<<6) + (seed>>2)); } @@ -145,8 +145,8 @@ double storm_rational_number_get_value_double(storm_rational_number_ptr a) { #ifndef RATIONAL_NUMBER_THREAD_SAFE std::lock_guard<std::mutex> lock(rationalNumberMutex); #endif - - storm::RationalNumber const& srn_a = *(storm::RationalNumber const*)a; + + storm::RationalNumber const& srn_a = *static_cast<storm::RationalNumber const*>(a); return storm::utility::convertNumber<double>(srn_a); } @@ -154,7 +154,7 @@ storm_rational_number_ptr storm_rational_number_from_double(double value) { #ifndef RATIONAL_NUMBER_THREAD_SAFE std::lock_guard<std::mutex> lock(rationalNumberMutex); #endif - + storm::RationalNumber* number = new storm::RationalNumber(storm::utility::convertNumber<storm::RationalNumber>(value)); return number; } @@ -163,90 +163,82 @@ storm_rational_number_ptr storm_rational_number_plus(storm_rational_number_ptr a #ifndef RATIONAL_NUMBER_THREAD_SAFE std::lock_guard<std::mutex> lock(rationalNumberMutex); #endif - - storm::RationalNumber const& srn_a = *(storm::RationalNumber const*)a; - storm::RationalNumber const& srn_b = *(storm::RationalNumber const*)b; - + + storm::RationalNumber const& srn_a = *static_cast<storm::RationalNumber const*>(a); + storm::RationalNumber const& srn_b = *static_cast<storm::RationalNumber const*>(b); + storm::RationalNumber* result_srn = new storm::RationalNumber(srn_a + srn_b); - return (storm_rational_number_ptr)result_srn; + return static_cast<storm_rational_number_ptr>(result_srn); } storm_rational_number_ptr storm_rational_number_minus(storm_rational_number_ptr a, storm_rational_number_ptr b) { #ifndef RATIONAL_NUMBER_THREAD_SAFE std::lock_guard<std::mutex> lock(rationalNumberMutex); #endif - - storm::RationalNumber const& srn_a = *(storm::RationalNumber const*)a; - storm::RationalNumber const& srn_b = *(storm::RationalNumber const*)b; - + + storm::RationalNumber const& srn_a = *static_cast<storm::RationalNumber const*>(a); + storm::RationalNumber const& srn_b = *static_cast<storm::RationalNumber const*>(b); + storm::RationalNumber* result_srn = new storm::RationalNumber(srn_a - srn_b); - return (storm_rational_number_ptr)result_srn; + return static_cast<storm_rational_number_ptr>(result_srn); } storm_rational_number_ptr storm_rational_number_times(storm_rational_number_ptr a, storm_rational_number_ptr b) { #ifndef RATIONAL_NUMBER_THREAD_SAFE std::lock_guard<std::mutex> lock(rationalNumberMutex); #endif - - storm::RationalNumber const& srn_a = *(storm::RationalNumber const*)a; - storm::RationalNumber const& srn_b = *(storm::RationalNumber const*)b; - + + storm::RationalNumber const& srn_a = *static_cast<storm::RationalNumber const*>(a); + storm::RationalNumber const& srn_b = *static_cast<storm::RationalNumber const*>(b); + storm::RationalNumber* result_srn = new storm::RationalNumber(srn_a * srn_b); - return (storm_rational_number_ptr)result_srn; + return static_cast<storm_rational_number_ptr>(result_srn); } storm_rational_number_ptr storm_rational_number_divide(storm_rational_number_ptr a, storm_rational_number_ptr b) { #ifndef RATIONAL_NUMBER_THREAD_SAFE std::lock_guard<std::mutex> lock(rationalNumberMutex); #endif - - storm::RationalNumber const& srn_a = *(storm::RationalNumber const*)a; - storm::RationalNumber const& srn_b = *(storm::RationalNumber const*)b; - + + storm::RationalNumber const& srn_a = *static_cast<storm::RationalNumber const*>(a); + storm::RationalNumber const& srn_b = *static_cast<storm::RationalNumber const*>(b); + storm::RationalNumber* result_srn = new storm::RationalNumber(srn_a / srn_b); - return (storm_rational_number_ptr)result_srn; + return static_cast<storm_rational_number_ptr>(result_srn); } storm_rational_number_ptr storm_rational_number_pow(storm_rational_number_ptr a, storm_rational_number_ptr b) { #ifndef RATIONAL_NUMBER_THREAD_SAFE std::lock_guard<std::mutex> lock(rationalNumberMutex); #endif - - storm::RationalNumber const& srn_a = *(storm::RationalNumber const*)a; - storm::RationalNumber const& srn_b = *(storm::RationalNumber const*)b; + + storm::RationalNumber const& srn_a = *static_cast<storm::RationalNumber const*>(a); + storm::RationalNumber const& srn_b = *static_cast<storm::RationalNumber const*>(b); carl::sint exponentAsInteger = carl::toInt<carl::sint>(srn_b); storm::RationalNumber* result_srn = new storm::RationalNumber(storm::utility::pow(srn_a, exponentAsInteger)); - return (storm_rational_number_ptr)result_srn; + return static_cast<storm_rational_number_ptr>(result_srn); } storm_rational_number_ptr storm_rational_number_mod(storm_rational_number_ptr a, storm_rational_number_ptr b) { #ifndef RATIONAL_NUMBER_THREAD_SAFE std::lock_guard<std::mutex> lock(rationalNumberMutex); #endif - - storm::RationalNumber const& srn_a = *(storm::RationalNumber const*)a; - storm::RationalNumber const& srn_b = *(storm::RationalNumber const*)b; + + storm::RationalNumber const& srn_a = *static_cast<storm::RationalNumber const*>(a); + storm::RationalNumber const& srn_b = *static_cast<storm::RationalNumber const*>(b); if (carl::isInteger(srn_a) && carl::isInteger(srn_b)) { storm::RationalNumber* result_srn = new storm::RationalNumber(carl::mod(carl::getNum(srn_a), carl::getNum(srn_b))); - return (storm_rational_number_ptr)result_srn; + return static_cast<storm_rational_number_ptr>(result_srn); } throw storm::exceptions::InvalidOperationException() << "Modulo not supported for rational, non-integer numbers."; } storm_rational_number_ptr storm_rational_number_min(storm_rational_number_ptr a, storm_rational_number_ptr b) { -#ifndef RATIONAL_NUMBER_THREAD_SAFE - std::lock_guard<std::mutex> lock(rationalNumberMutex); -#endif - return storm_rational_number_less_or_equal(a, b) ? storm_rational_number_clone(a) : storm_rational_number_clone(b); } storm_rational_number_ptr storm_rational_number_max(storm_rational_number_ptr a, storm_rational_number_ptr b) { -#ifndef RATIONAL_NUMBER_THREAD_SAFE - std::lock_guard<std::mutex> lock(rationalNumberMutex); -#endif - return storm_rational_number_less(a, b) ? storm_rational_number_clone(b) : storm_rational_number_clone(a); } @@ -254,16 +246,16 @@ int storm_rational_number_less(storm_rational_number_ptr a, storm_rational_numbe #ifndef RATIONAL_NUMBER_THREAD_SAFE std::lock_guard<std::mutex> lock(rationalNumberMutex); #endif - - storm::RationalNumber const& srn_a = *(storm::RationalNumber const*)a; - storm::RationalNumber const& srn_b = *(storm::RationalNumber const*)b; - + + storm::RationalNumber const& srn_a = *static_cast<storm::RationalNumber const*>(a); + storm::RationalNumber const& srn_b = *static_cast<storm::RationalNumber const*>(b); + if (storm::utility::isInfinity<storm::RationalNumber>(srn_b)) { return storm::utility::isInfinity<storm::RationalNumber>(srn_a) ? 0 : 1; } else if (storm::utility::isInfinity<storm::RationalNumber>(srn_a)) { return 0; } - + return srn_a < srn_b ? 1 : 0; } @@ -271,16 +263,16 @@ int storm_rational_number_less_or_equal(storm_rational_number_ptr a, storm_ratio #ifndef RATIONAL_NUMBER_THREAD_SAFE std::lock_guard<std::mutex> lock(rationalNumberMutex); #endif - - storm::RationalNumber const& srn_a = *(storm::RationalNumber const*)a; - storm::RationalNumber const& srn_b = *(storm::RationalNumber const*)b; - + + storm::RationalNumber const& srn_a = *static_cast<storm::RationalNumber const*>(a); + storm::RationalNumber const& srn_b = *static_cast<storm::RationalNumber const*>(b); + if (storm::utility::isInfinity<storm::RationalNumber>(srn_b)) { return 1; } else if (storm::utility::isInfinity<storm::RationalNumber>(srn_a)) { return 0; } - + return srn_a <= srn_b ? 1 : 0; } @@ -288,30 +280,30 @@ storm_rational_number_ptr storm_rational_number_negate(storm_rational_number_ptr #ifndef RATIONAL_NUMBER_THREAD_SAFE std::lock_guard<std::mutex> lock(rationalNumberMutex); #endif - - storm::RationalNumber const& srn_a = *(storm::RationalNumber const*)a; + + storm::RationalNumber const& srn_a = *static_cast<storm::RationalNumber const*>(a); storm::RationalNumber* result_srn = new storm::RationalNumber(-srn_a); - return (storm_rational_number_ptr)result_srn; + return static_cast<storm_rational_number_ptr>(result_srn); } storm_rational_number_ptr storm_rational_number_floor(storm_rational_number_ptr a) { #ifndef RATIONAL_NUMBER_THREAD_SAFE std::lock_guard<std::mutex> lock(rationalNumberMutex); #endif - - storm::RationalNumber const& srn_a = *(storm::RationalNumber const*)a; + + storm::RationalNumber const& srn_a = *static_cast<storm::RationalNumber const*>(a); storm::RationalNumber* result_srn = new storm::RationalNumber(carl::floor(srn_a)); - return (storm_rational_number_ptr)result_srn; + return static_cast<storm_rational_number_ptr>(result_srn); } storm_rational_number_ptr storm_rational_number_ceil(storm_rational_number_ptr a) { #ifndef RATIONAL_NUMBER_THREAD_SAFE std::lock_guard<std::mutex> lock(rationalNumberMutex); #endif - - storm::RationalNumber const& srn_a = *(storm::RationalNumber const*)a; + + storm::RationalNumber const& srn_a = *static_cast<storm::RationalNumber const*>(a); storm::RationalNumber* result_srn = new storm::RationalNumber(carl::ceil(srn_a)); - return (storm_rational_number_ptr)result_srn; + return static_cast<storm_rational_number_ptr>(result_srn); } storm_rational_number_ptr storm_double_sharpen(double value, size_t precision) { @@ -322,9 +314,9 @@ storm_rational_number_ptr storm_double_sharpen(double value, size_t precision) { try { storm::RationalNumber tmp = storm::utility::kwek_mehlhorn::sharpen<storm::RationalNumber, double>(precision, value); storm::RationalNumber* result_srn = new storm::RationalNumber(tmp); - return (storm_rational_number_ptr)result_srn; + return static_cast<storm_rational_number_ptr>(result_srn); } catch (storm::exceptions::PrecisionExceededException const& e) { - return (storm_rational_number_ptr)0; + return nullptr; } } @@ -333,10 +325,10 @@ storm_rational_number_ptr storm_rational_number_sharpen(storm_rational_number_pt std::lock_guard<std::mutex> lock(rationalNumberMutex); #endif - storm::RationalNumber const& srn_a = *(storm::RationalNumber const*)a; + storm::RationalNumber const& srn_a = *static_cast<storm::RationalNumber const*>(a); storm::RationalNumber tmp = storm::utility::kwek_mehlhorn::sharpen<storm::RationalNumber, storm::RationalNumber>(precision, srn_a); storm::RationalNumber* result_srn = new storm::RationalNumber(tmp); - return (storm_rational_number_ptr)result_srn; + return static_cast<storm_rational_number_ptr>(result_srn); } int storm_rational_number_equal_modulo_precision(int relative, storm_rational_number_ptr a, storm_rational_number_ptr b, storm_rational_number_ptr precision) { @@ -344,9 +336,9 @@ int storm_rational_number_equal_modulo_precision(int relative, storm_rational_nu std::lock_guard<std::mutex> lock(rationalNumberMutex); #endif - storm::RationalNumber const& srn_a = *(storm::RationalNumber const*)a; - storm::RationalNumber const& srn_b = *(storm::RationalNumber const*)b; - storm::RationalNumber const& srn_p = *(storm::RationalNumber const*)precision; + storm::RationalNumber const& srn_a = *static_cast<storm::RationalNumber const*>(a); + storm::RationalNumber const& srn_b = *static_cast<storm::RationalNumber const*>(b); + storm::RationalNumber const& srn_p = *static_cast<storm::RationalNumber const*>(precision); if (relative) { if (storm::utility::isZero<storm::RationalNumber>(srn_a)) { @@ -363,17 +355,18 @@ void print_storm_rational_number(storm_rational_number_ptr a) { #ifndef RATIONAL_NUMBER_THREAD_SAFE std::lock_guard<std::mutex> lock(rationalNumberMutex); #endif - - storm::RationalNumber const& srn_a = *(storm::RationalNumber const*)a; + + storm::RationalNumber const& srn_a = *static_cast<storm::RationalNumber const*>(a); + std::cout << srn_a << std::flush; } void print_storm_rational_number_to_file(storm_rational_number_ptr a, FILE* out) { #ifndef RATIONAL_NUMBER_THREAD_SAFE std::lock_guard<std::mutex> lock(rationalNumberMutex); #endif - + std::stringstream ss; - storm::RationalNumber const& srn_a = *(storm::RationalNumber const*)a; + storm::RationalNumber const& srn_a = *static_cast<storm::RationalNumber const*>(a); ss << srn_a; std::string s = ss.str(); fprintf(out, "%s", s.c_str()); @@ -387,8 +380,8 @@ void storm_rational_function_init(storm_rational_function_ptr* a) { #ifndef RATIONAL_FUNCTION_THREAD_SAFE std::lock_guard<std::mutex> lock(rationalFunctionMutex); #endif - - storm_rational_function_ptr srf_ptr = new storm::RationalFunction(*((storm::RationalFunction*)(*a))); + + storm_rational_function_ptr srf_ptr = new storm::RationalFunction(*static_cast<storm::RationalFunction*>(*a)); *a = srf_ptr; } @@ -396,8 +389,8 @@ void storm_rational_function_destroy(storm_rational_function_ptr a) { #ifndef RATIONAL_FUNCTION_THREAD_SAFE std::lock_guard<std::mutex> lock(rationalFunctionMutex); #endif - - storm::RationalFunction* srf = (storm::RationalFunction*)a; + + storm::RationalFunction* srf = static_cast<storm::RationalFunction*>(a); delete srf; } @@ -405,10 +398,10 @@ int storm_rational_function_equals(storm_rational_function_ptr a, storm_rational #ifndef RATIONAL_FUNCTION_THREAD_SAFE std::lock_guard<std::mutex> lock(rationalFunctionMutex); #endif - - storm::RationalFunction const& srf_a = *(storm::RationalFunction*)a; - storm::RationalFunction const& srf_b = *(storm::RationalFunction*)b; - + + storm::RationalFunction const& srf_a = *static_cast<storm::RationalFunction*>(a); + storm::RationalFunction const& srf_b = *static_cast<storm::RationalFunction*>(b); + return (srf_a == srf_b) ? 1 : 0; } @@ -416,17 +409,17 @@ char* storm_rational_function_to_str(storm_rational_function_ptr val, char* buf, #ifndef RATIONAL_FUNCTION_THREAD_SAFE std::lock_guard<std::mutex> lock(rationalFunctionMutex); #endif - + std::stringstream ss; - storm::RationalFunction const& srf_a = *(storm::RationalFunction*)val; + storm::RationalFunction const& srf_a = *static_cast<storm::RationalFunction*>(val); ss << srf_a; std::string s = ss.str(); if (s.size() + 1 < buflen) { - std::strcpy(buf, s.c_str()); + std::memcpy(buf, s.c_str(), s.size() + 1); return buf; } else { - char* result = (char*)malloc(s.size() + 1); - std::strcpy(result, s.c_str()); + char* result = static_cast<char*>(malloc(s.size() + 1)); + std::memcpy(result, s.c_str(), s.size() + 1); return result; } } @@ -435,36 +428,36 @@ storm_rational_function_ptr storm_rational_function_clone(storm_rational_functio #ifndef RATIONAL_FUNCTION_THREAD_SAFE std::lock_guard<std::mutex> lock(rationalFunctionMutex); #endif - - storm::RationalFunction* result_srf = new storm::RationalFunction(*((storm::RationalFunction const*)a)); - return (storm_rational_function_ptr)result_srf; + + storm::RationalFunction* result_srf = new storm::RationalFunction(*static_cast<storm::RationalFunction const*>(a)); + return static_cast<storm_rational_function_ptr>(result_srf); } storm_rational_function_ptr storm_rational_function_get_zero() { #ifndef RATIONAL_FUNCTION_THREAD_SAFE std::lock_guard<std::mutex> lock(rationalFunctionMutex); #endif - + storm::RationalFunction* result_srf = new storm::RationalFunction(storm::utility::zero<storm::RationalFunction>()); - return (storm_rational_function_ptr)result_srf; + return static_cast<storm_rational_function_ptr>(result_srf); } storm_rational_function_ptr storm_rational_function_get_one() { #ifndef RATIONAL_FUNCTION_THREAD_SAFE std::lock_guard<std::mutex> lock(rationalFunctionMutex); #endif - + storm::RationalFunction* result_srf = new storm::RationalFunction(storm::utility::one<storm::RationalFunction>()); - return (storm_rational_function_ptr)result_srf; + return static_cast<storm_rational_function_ptr>(result_srf); } storm_rational_function_ptr storm_rational_function_get_infinity() { #ifndef RATIONAL_FUNCTION_THREAD_SAFE std::lock_guard<std::mutex> lock(rationalFunctionMutex); #endif - + storm::RationalFunction* result_srf = new storm::RationalFunction(storm::utility::infinity<storm::RationalFunction>()); - return (storm_rational_function_ptr)result_srf; + return static_cast<storm_rational_function_ptr>(result_srf); } @@ -472,17 +465,17 @@ int storm_rational_function_is_zero(storm_rational_function_ptr a) { #ifndef RATIONAL_FUNCTION_THREAD_SAFE std::lock_guard<std::mutex> lock(rationalFunctionMutex); #endif - - return storm::utility::isZero(*(storm::RationalFunction const*)a) ? 1 : 0; + + return storm::utility::isZero(*static_cast<storm::RationalFunction const*>(a)) ? 1 : 0; } uint64_t storm_rational_function_hash(storm_rational_function_ptr const a, uint64_t const seed) { #ifndef RATIONAL_FUNCTION_THREAD_SAFE std::lock_guard<std::mutex> lock(rationalFunctionMutex); #endif - - storm::RationalFunction const& srf_a = *(storm::RationalFunction const*)a; - + + storm::RationalFunction const& srf_a = *static_cast<storm::RationalFunction const*>(a); + // Taken from boost::hash_combine that we do not call here for the lack of boost headers. return seed ^ (std::hash<storm::RationalFunction>()(srf_a) + 0x9e3779b9 + (seed<<6) + (seed>>2)); } @@ -491,8 +484,8 @@ double storm_rational_function_get_value_double(storm_rational_function_ptr a) { #ifndef RATIONAL_FUNCTION_THREAD_SAFE std::lock_guard<std::mutex> lock(rationalFunctionMutex); #endif - - storm::RationalFunction const& srf_a = *(storm::RationalFunction const*)a; + + storm::RationalFunction const& srf_a = *static_cast<storm::RationalFunction const*>(a); if (srf_a.isConstant()) { return storm::utility::convertNumber<double>(srf_a); } else { @@ -504,75 +497,75 @@ storm_rational_function_ptr storm_rational_function_plus(storm_rational_function #ifndef RATIONAL_FUNCTION_THREAD_SAFE std::lock_guard<std::mutex> lock(rationalFunctionMutex); #endif - - storm::RationalFunction const& srf_a = *(storm::RationalFunction const*)a; - storm::RationalFunction const& srf_b = *(storm::RationalFunction const*)b; - + + storm::RationalFunction const& srf_a = *static_cast<storm::RationalFunction const*>(a); + storm::RationalFunction const& srf_b = *static_cast<storm::RationalFunction const*>(b); + storm::RationalFunction* result_srf = new storm::RationalFunction(srf_a); *result_srf += srf_b; - return (storm_rational_function_ptr)result_srf; + return static_cast<storm_rational_function_ptr>(result_srf); } storm_rational_function_ptr storm_rational_function_minus(storm_rational_function_ptr a, storm_rational_function_ptr b) { #ifndef RATIONAL_FUNCTION_THREAD_SAFE std::lock_guard<std::mutex> lock(rationalFunctionMutex); #endif - - storm::RationalFunction const& srf_a = *(storm::RationalFunction const*)a; - storm::RationalFunction const& srf_b = *(storm::RationalFunction const*)b; - + + storm::RationalFunction const& srf_a = *static_cast<storm::RationalFunction const*>(a); + storm::RationalFunction const& srf_b = *static_cast<storm::RationalFunction const*>(b); + storm::RationalFunction* result_srf = new storm::RationalFunction(srf_a); *result_srf -= srf_b; - return (storm_rational_function_ptr)result_srf; + return static_cast<storm_rational_function_ptr>(result_srf); } storm_rational_function_ptr storm_rational_function_times(storm_rational_function_ptr a, storm_rational_function_ptr b) { #ifndef RATIONAL_FUNCTION_THREAD_SAFE std::lock_guard<std::mutex> lock(rationalFunctionMutex); #endif - - storm::RationalFunction const& srf_a = *(storm::RationalFunction const*)a; - storm::RationalFunction const& srf_b = *(storm::RationalFunction const*)b; - + + storm::RationalFunction const& srf_a = *static_cast<storm::RationalFunction const*>(a); + storm::RationalFunction const& srf_b = *static_cast<storm::RationalFunction const*>(b); + storm::RationalFunction* result_srf = new storm::RationalFunction(srf_a); *result_srf *= srf_b; - return (storm_rational_function_ptr)result_srf; + return static_cast<storm_rational_function_ptr>(result_srf); } storm_rational_function_ptr storm_rational_function_divide(storm_rational_function_ptr a, storm_rational_function_ptr b) { #ifndef RATIONAL_FUNCTION_THREAD_SAFE std::lock_guard<std::mutex> lock(rationalFunctionMutex); #endif - - storm::RationalFunction const& srf_a = *(storm::RationalFunction const*)a; - storm::RationalFunction const& srf_b = *(storm::RationalFunction const*)b; - + + storm::RationalFunction const& srf_a = *static_cast<storm::RationalFunction const*>(a); + storm::RationalFunction const& srf_b = *static_cast<storm::RationalFunction const*>(b); + storm::RationalFunction* result_srf = new storm::RationalFunction(srf_a); *result_srf /= srf_b; - return (storm_rational_function_ptr)result_srf; + return static_cast<storm_rational_function_ptr>(result_srf); } storm_rational_function_ptr storm_rational_function_pow(storm_rational_function_ptr a, storm_rational_function_ptr b) { #ifndef RATIONAL_FUNCTION_THREAD_SAFE std::lock_guard<std::mutex> lock(rationalFunctionMutex); #endif - - storm::RationalFunction const& srf_a = *(storm::RationalFunction const*)a; - storm::RationalFunction const& srf_b = *(storm::RationalFunction const*)b; - + + storm::RationalFunction const& srf_a = *static_cast<storm::RationalFunction const*>(a); + storm::RationalFunction const& srf_b = *static_cast<storm::RationalFunction const*>(b); + carl::uint exponentAsInteger = carl::toInt<carl::uint>(srf_b.nominatorAsNumber()); storm::RationalFunction* result_srf = new storm::RationalFunction(carl::pow(srf_a, exponentAsInteger)); - return (storm_rational_function_ptr)result_srf; + return static_cast<storm_rational_function_ptr>(result_srf); } storm_rational_function_ptr storm_rational_function_mod(storm_rational_function_ptr a, storm_rational_function_ptr b) { #ifndef RATIONAL_FUNCTION_THREAD_SAFE std::lock_guard<std::mutex> lock(rationalFunctionMutex); #endif - - storm::RationalFunction const& srf_a = *(storm::RationalFunction const*)a; - storm::RationalFunction const& srf_b = *(storm::RationalFunction const*)b; - + + storm::RationalFunction const& srf_a = *static_cast<storm::RationalFunction const*>(a); + storm::RationalFunction const& srf_b = *static_cast<storm::RationalFunction const*>(b); + if (!storm::utility::isConstant(srf_a) || !storm::utility::isConstant(srf_b)) { throw storm::exceptions::InvalidOperationException() << "Operands of mod must not be non-constant rational functions."; } @@ -580,43 +573,27 @@ storm_rational_function_ptr storm_rational_function_mod(storm_rational_function_ } storm_rational_function_ptr storm_rational_function_min(storm_rational_function_ptr a, storm_rational_function_ptr b) { -#ifndef RATIONAL_FUNCTION_THREAD_SAFE - std::lock_guard<std::mutex> lock(rationalFunctionMutex); -#endif - - if (storm_rational_function_less_or_equal(a, b)) { - return storm_rational_function_clone(a); - } else { - return storm_rational_function_clone(b); - } + return storm_rational_function_less_or_equal(a, b) ? storm_rational_function_clone(a) : storm_rational_function_clone(b); } storm_rational_function_ptr storm_rational_function_max(storm_rational_function_ptr a, storm_rational_function_ptr b) { -#ifndef RATIONAL_FUNCTION_THREAD_SAFE - std::lock_guard<std::mutex> lock(rationalFunctionMutex); -#endif - - if (storm_rational_function_less(a, b)) { - return storm_rational_function_clone(b); - } else { - return storm_rational_function_clone(a); - } + return storm_rational_function_less(a, b) ? storm_rational_function_clone(b) : storm_rational_function_clone(a); } int storm_rational_function_less(storm_rational_function_ptr a, storm_rational_function_ptr b) { #ifndef RATIONAL_FUNCTION_THREAD_SAFE std::lock_guard<std::mutex> lock(rationalFunctionMutex); #endif - - storm::RationalFunction const& srf_a = *(storm::RationalFunction const*)a; - storm::RationalFunction const& srf_b = *(storm::RationalFunction const*)b; + + storm::RationalFunction const& srf_a = *static_cast<storm::RationalFunction const*>(a); + storm::RationalFunction const& srf_b = *static_cast<storm::RationalFunction const*>(b); if (!storm::utility::isConstant(srf_a) || !storm::utility::isConstant(srf_b)) { throw storm::exceptions::InvalidOperationException() << "Operands of less must not be non-constant rational functions."; } - + storm::RationalFunctionCoefficient srn_a = storm::utility::convertNumber<storm::RationalFunctionCoefficient>(srf_a); storm::RationalFunctionCoefficient srn_b = storm::utility::convertNumber<storm::RationalFunctionCoefficient>(srf_b); - + if (storm::utility::isInfinity<storm::RationalFunctionCoefficient>(srn_b)) { return storm::utility::isInfinity<storm::RationalFunctionCoefficient>(srn_a) ? 0 : 1; } else if (storm::utility::isInfinity<storm::RationalFunctionCoefficient>(srn_a)) { @@ -630,22 +607,22 @@ int storm_rational_function_less_or_equal(storm_rational_function_ptr a, storm_r #ifndef RATIONAL_FUNCTION_THREAD_SAFE std::lock_guard<std::mutex> lock(rationalFunctionMutex); #endif - - storm::RationalFunction const& srf_a = *(storm::RationalFunction const*)a; - storm::RationalFunction const& srf_b = *(storm::RationalFunction const*)b; + + storm::RationalFunction const& srf_a = *static_cast<storm::RationalFunction const*>(a); + storm::RationalFunction const& srf_b = *static_cast<storm::RationalFunction const*>(b); if (!storm::utility::isConstant(srf_a) || !storm::utility::isConstant(srf_b)) { throw storm::exceptions::InvalidOperationException() << "Operands of less-or-equal must not be non-constant rational functions."; } - + storm::RationalFunctionCoefficient srn_a = storm::utility::convertNumber<storm::RationalFunctionCoefficient>(srf_a); storm::RationalFunctionCoefficient srn_b = storm::utility::convertNumber<storm::RationalFunctionCoefficient>(srf_b); - + if (storm::utility::isInfinity<storm::RationalFunctionCoefficient>(srn_b)) { return 1; } else if (storm::utility::isInfinity<storm::RationalFunctionCoefficient>(srn_a)) { return 0; } - + return (srn_a <= srn_b) ? 1 : 0; } @@ -653,51 +630,51 @@ storm_rational_function_ptr storm_rational_function_negate(storm_rational_functi #ifndef RATIONAL_FUNCTION_THREAD_SAFE std::lock_guard<std::mutex> lock(rationalFunctionMutex); #endif - - storm::RationalFunction const& srf_a = *(storm::RationalFunction const*)a; + + storm::RationalFunction const& srf_a = *static_cast<storm::RationalFunction const*>(a); storm::RationalFunction* result_srf = new storm::RationalFunction(-srf_a); - return (storm_rational_function_ptr)result_srf; + return static_cast<storm_rational_function_ptr>(result_srf); } storm_rational_function_ptr storm_rational_function_floor(storm_rational_function_ptr a) { #ifndef RATIONAL_FUNCTION_THREAD_SAFE std::lock_guard<std::mutex> lock(rationalFunctionMutex); #endif - - storm::RationalFunction const& srf_a = *(storm::RationalFunction const*)a; + + storm::RationalFunction const& srf_a = *static_cast<storm::RationalFunction const*>(a); if (!storm::utility::isConstant(srf_a)) { throw storm::exceptions::InvalidOperationException() << "Operand of floor must not be non-constant rational function."; } storm::RationalFunction* result_srf = new storm::RationalFunction(carl::floor(storm::utility::convertNumber<storm::RationalFunctionCoefficient>(srf_a))); - return (storm_rational_function_ptr)result_srf; + return static_cast<storm_rational_function_ptr>(result_srf); } storm_rational_function_ptr storm_rational_function_ceil(storm_rational_function_ptr a) { #ifndef RATIONAL_FUNCTION_THREAD_SAFE std::lock_guard<std::mutex> lock(rationalFunctionMutex); #endif - - storm::RationalFunction const& srf_a = *(storm::RationalFunction const*)a; + + storm::RationalFunction const& srf_a = *static_cast<storm::RationalFunction const*>(a); if (!storm::utility::isConstant(srf_a)) { throw storm::exceptions::InvalidOperationException() << "Operand of ceil must not be non-constant rational function."; } storm::RationalFunction* result_srf = new storm::RationalFunction(carl::ceil(storm::utility::convertNumber<storm::RationalFunctionCoefficient>(srf_a))); - return (storm_rational_function_ptr)result_srf; + return static_cast<storm_rational_function_ptr>(result_srf); } int storm_rational_function_equal_modulo_precision(int relative, storm_rational_function_ptr a, storm_rational_function_ptr b, storm_rational_function_ptr precision) { #ifndef RATIONAL_FUNCTION_THREAD_SAFE std::lock_guard<std::mutex> lock(rationalFunctionMutex); #endif - - storm::RationalFunction const& srf_a = *(storm::RationalFunction const*)a; - storm::RationalFunction const& srf_b = *(storm::RationalFunction const*)b; - storm::RationalFunction const& srf_p = *(storm::RationalFunction const*)precision; - + + storm::RationalFunction const& srf_a = *static_cast<storm::RationalFunction const*>(a); + storm::RationalFunction const& srf_b = *static_cast<storm::RationalFunction const*>(b); + storm::RationalFunction const& srf_p = *static_cast<storm::RationalFunction const*>(precision); + if (!storm::utility::isConstant(srf_a) || !storm::utility::isConstant(srf_b) || !storm::utility::isConstant(srf_p)) { throw storm::exceptions::InvalidOperationException() << "Operands of equal-modulo-precision must not be non-constant rational functions."; } - + storm::RationalFunctionCoefficient srn_a = storm::utility::convertNumber<storm::RationalFunctionCoefficient>(srf_a); storm::RationalFunctionCoefficient srn_b = storm::utility::convertNumber<storm::RationalFunctionCoefficient>(srf_b); storm::RationalFunctionCoefficient srn_p = storm::utility::convertNumber<storm::RationalFunctionCoefficient>(srf_p); @@ -713,8 +690,8 @@ void print_storm_rational_function(storm_rational_function_ptr a) { #ifndef RATIONAL_FUNCTION_THREAD_SAFE std::lock_guard<std::mutex> lock(rationalFunctionMutex); #endif - - storm::RationalFunction const& srf_a = *(storm::RationalFunction const*)a; + + storm::RationalFunction const& srf_a = *static_cast<storm::RationalFunction const*>(a); std::cout << srf_a << std::flush; } @@ -722,9 +699,9 @@ void print_storm_rational_function_to_file(storm_rational_function_ptr a, FILE* #ifndef RATIONAL_FUNCTION_THREAD_SAFE std::lock_guard<std::mutex> lock(rationalFunctionMutex); #endif - + std::stringstream ss; - storm::RationalFunction const& srf_a = *(storm::RationalFunction const*)a; + storm::RationalFunction const& srf_a = *static_cast<storm::RationalFunction const*>(a); ss << srf_a; std::string s = ss.str(); fprintf(out, "%s", s.c_str()); diff --git a/resources/cmake/find_modules/FindSPOT.cmake b/resources/cmake/find_modules/FindSPOT.cmake new file mode 100644 index 000000000..f0ba32917 --- /dev/null +++ b/resources/cmake/find_modules/FindSPOT.cmake @@ -0,0 +1,41 @@ +# - Try to find libspot +# Once done this will define +# SPOT_FOUND - System has glpk +# SPOT_INCLUDE_DIR - The glpk include directory +# SPOT_LIBRARIES - The libraries needed to use glpk +# SPOT_VERSION - The version of spot + +# use pkg-config to get the directories and then use these values + +# in the find_path() and find_library() calls +find_package(PkgConfig QUIET) +PKG_CHECK_MODULES(PC_SPOT QUIET spot) + +find_path(SPOT_INCLUDE_DIR NAMES spot/misc/_config.h + HINTS + ${PC_SPOT_INCLUDEDIR} + ${PC_SPOT_INCLUDE_DIRS} + ) + +find_library(SPOT_LIBRARIES NAMES spot + HINTS + ${PC_SPOT_LIBDIR} + ${PC_SPOT_LIBRARY_DIRS} + ) + +if(PC_SPOT_VERSION) + set(SPOT_VERSION ${PC_SPOT_VERSION}) +elseif(SPOT_INCLUDE_DIR AND EXISTS "${SPOT_INCLUDE_DIR}/spot/misc/_config.h") + file(STRINGS "${SPOT_INCLUDE_DIR}/spot/misc/_config.h" SPOT_VERSION + REGEX "^#define[\t ]+SPOT_VERSION[\t ]+\".+\"") + string(REGEX REPLACE "^#define[\t ]+SPOT_VERSION[\t ]+\"(.+)\"" "\\1" SPOT_VERSION "${SPOT_VERSION}") +endif() + +# handle the QUIETLY and REQUIRED arguments and set SPOT_FOUND to TRUE if +# all listed variables are TRUE +include(FindPackageHandleStandardArgs) +FIND_PACKAGE_HANDLE_STANDARD_ARGS(SPOT + REQUIRED_VARS SPOT_LIBRARIES SPOT_INCLUDE_DIR + VERSION_VAR SPOT_VERSION) + +mark_as_advanced(SPOT_INCLUDE_DIR SPOT_LIBRARIES) diff --git a/resources/examples/testfiles/hoa/automaton_Fandp0Xp1.hoa b/resources/examples/testfiles/hoa/automaton_Fandp0Xp1.hoa new file mode 100644 index 000000000..1998df31e --- /dev/null +++ b/resources/examples/testfiles/hoa/automaton_Fandp0Xp1.hoa @@ -0,0 +1,27 @@ +HOA: v1 +States: 3 +properties: implicit-labels trans-labels no-univ-branch deterministic complete +tool: "ltl2dstar" "0.5.4" +name: "F & p0 X p1" +comment: "DBA2DRA[NBA=3]" +acc-name: Rabin 1 +Acceptance: 2 (Fin(0)&Inf(1)) +Start: 2 +AP: 2 "p0" "p1" +--BODY-- +State: 0 {1} +0 +0 +0 +0 +State: 1 {} +2 +1 +0 +0 +State: 2 {} +2 +1 +2 +1 +--END-- diff --git a/resources/examples/testfiles/hoa/automaton_UXp0p1.hoa b/resources/examples/testfiles/hoa/automaton_UXp0p1.hoa new file mode 100644 index 000000000..2927e0b91 --- /dev/null +++ b/resources/examples/testfiles/hoa/automaton_UXp0p1.hoa @@ -0,0 +1,32 @@ +HOA: v1 +States: 4 +properties: implicit-labels trans-labels no-univ-branch deterministic complete +tool: "ltl2dstar" "0.5.4" +name: "U X p0 p1" +comment: "DBA2DRA[NBA=3]" +acc-name: Rabin 1 +Acceptance: 2 (Fin(0)&Inf(1)) +Start: 1 +AP: 2 "p0" "p1" +--BODY-- +State: 0 {1} +0 +0 +0 +0 +State: 1 {} +2 +2 +0 +0 +State: 2 {} +3 +2 +3 +0 +State: 3 {} +3 +3 +3 +3 +--END-- diff --git a/src/storm-pars/analysis/AssumptionChecker.cpp b/src/storm-pars/analysis/AssumptionChecker.cpp index 0d8d87cf9..a6ad9bbaf 100644 --- a/src/storm-pars/analysis/AssumptionChecker.cpp +++ b/src/storm-pars/analysis/AssumptionChecker.cpp @@ -11,6 +11,7 @@ #include "storm/storage/expressions/ExpressionManager.h" #include "storm/storage/expressions/VariableExpression.h" #include "storm/storage/expressions/RationalFunctionToExpression.h" +#include "storm/utility/solver.h" namespace storm { namespace analysis { @@ -33,7 +34,7 @@ namespace storm { auto lb = region.getLowerBoundary(var.name()); auto ub = region.getUpperBoundary(var.name()); // Creates samples between lb and ub, that is: lb, lb + (ub-lb)/(#samples -1), lb + 2* (ub-lb)/(#samples -1), ..., ub - auto val = std::pair<VariableType, CoefficientType>(var, utility::convertNumber<CoefficientType>(lb + i * (ub - lb) / (numberOfSamples - 1))); + auto val = std::pair<VariableType, CoefficientType>(var, (lb + i * (ub - lb) / (numberOfSamples - 1))); valuation.insert(val); } models::sparse::Dtmc<ConstantType> sampleModel = instantiator.instantiate(valuation); diff --git a/src/storm-pars/analysis/MonotonicityHelper.cpp b/src/storm-pars/analysis/MonotonicityHelper.cpp index 34406067d..9a652345c 100644 --- a/src/storm-pars/analysis/MonotonicityHelper.cpp +++ b/src/storm-pars/analysis/MonotonicityHelper.cpp @@ -266,7 +266,7 @@ namespace storm { auto lb = region.getLowerBoundary(itr->name()); auto ub = region.getUpperBoundary(itr->name()); // Creates samples between lb and ub, that is: lb, lb + (ub-lb)/(#samples -1), lb + 2* (ub-lb)/(#samples -1), ..., ub - valuation[*itr2] = utility::convertNumber<typename utility::parametric::CoefficientType<ValueType>::type>(lb + i*(ub-lb)/(numberOfSamples-1)); + valuation[*itr2] = (lb + i*(ub-lb)/(numberOfSamples-1)); } else { auto lb = region.getLowerBoundary(itr2->name()); valuation[*itr2] = utility::convertNumber<typename utility::parametric::CoefficientType<ValueType>::type>(lb); diff --git a/src/storm-pars/modelchecker/region/SparseDtmcParameterLiftingModelChecker.cpp b/src/storm-pars/modelchecker/region/SparseDtmcParameterLiftingModelChecker.cpp index 9fec51ff5..6af642da4 100644 --- a/src/storm-pars/modelchecker/region/SparseDtmcParameterLiftingModelChecker.cpp +++ b/src/storm-pars/modelchecker/region/SparseDtmcParameterLiftingModelChecker.cpp @@ -647,7 +647,7 @@ namespace storm { STORM_LOG_INFO("Splitting based on region split estimates"); ConstantType diff = this->lastValue - (this->currentCheckTask->getFormula().asOperatorFormula().template getThresholdAs<ConstantType>()); for (auto &entry : regionSplitEstimates) { - if ((!this->isUseMonotonicitySet() || !monRes.isMonotone(entry.first)) && entry.second > diff) { + if ((!this->isUseMonotonicitySet() || !monRes.isMonotone(entry.first)) && storm::utility::convertNumber<ConstantType>(entry.second) > diff) { sortedOnValues.insert({-(entry.second * storm::utility::convertNumber<double>(region.getDifference(entry.first)) * storm::utility::convertNumber<double>(region.getDifference(entry.first))), entry.first}); } } diff --git a/src/storm-parsers/parser/FormulaParserGrammar.cpp b/src/storm-parsers/parser/FormulaParserGrammar.cpp index 3aba843be..aa07a7961 100644 --- a/src/storm-parsers/parser/FormulaParserGrammar.cpp +++ b/src/storm-parsers/parser/FormulaParserGrammar.cpp @@ -1,6 +1,8 @@ #include "FormulaParserGrammar.h" #include "storm/storage/expressions/ExpressionManager.h" +#include <memory> + namespace storm { namespace parser { @@ -15,73 +17,98 @@ namespace storm { void FormulaParserGrammar::initialize() { // Register all variables so we can parse them in the expressions. for (auto variableTypePair : *constManager) { - identifiers_.add(variableTypePair.first.getName(), variableTypePair.first); + addIdentifierExpression(variableTypePair.first.getName(), variableTypePair.first); } // Set the identifier mapping to actually generate expressions. expressionParser.setIdentifierMapping(&identifiers_); - longRunAverageRewardFormula = (qi::lit("LRA") | qi::lit("S") | qi::lit("MP"))[qi::_val = phoenix::bind(&FormulaParserGrammar::createLongRunAverageRewardFormula, phoenix::ref(*this))]; - longRunAverageRewardFormula.name("long run average reward formula"); - - instantaneousRewardFormula = (qi::lit("I=") > expressionParser)[qi::_val = phoenix::bind(&FormulaParserGrammar::createInstantaneousRewardFormula, phoenix::ref(*this), qi::_1)]; - instantaneousRewardFormula.name("instantaneous reward formula"); - - cumulativeRewardFormula = (qi::lit("C") >> timeBounds)[qi::_val = phoenix::bind(&FormulaParserGrammar::createCumulativeRewardFormula, phoenix::ref(*this), qi::_1)]; - cumulativeRewardFormula.name("cumulative reward formula"); - - totalRewardFormula = (qi::lit("C"))[qi::_val = phoenix::bind(&FormulaParserGrammar::createTotalRewardFormula, phoenix::ref(*this))]; - totalRewardFormula.name("total reward formula"); - - rewardPathFormula = longRunAverageRewardFormula | conditionalFormula(storm::logic::FormulaContext::Reward) | eventuallyFormula(storm::logic::FormulaContext::Reward) | cumulativeRewardFormula | instantaneousRewardFormula | totalRewardFormula; - rewardPathFormula.name("reward path formula"); - - expressionFormula = expressionParser[qi::_val = phoenix::bind(&FormulaParserGrammar::createAtomicExpressionFormula, phoenix::ref(*this), qi::_1)]; - expressionFormula.name("expression formula"); - - label = qi::as_string[qi::raw[qi::lexeme[((qi::alpha | qi::char_('_')) >> *(qi::alnum | qi::char_('_')))]]]; + keywords_.name("keyword"); + nonStandardKeywords_.name("non-standard Storm-specific keyword"); + relationalOperator_.name("relational operator"); + optimalityOperator_.name("optimality operator"); + rewardMeasureType_.name("reward measure"); + operatorKeyword_.name("Operator keyword"); + filterType_.name("filter type"); + + // Auxiliary helpers + isPathFormula = qi::eps(qi::_r1 == FormulaKind::Path); + noAmbiguousNonAssociativeOperator = !(qi::lit(qi::_r2)[qi::_pass = phoenix::bind(&FormulaParserGrammar::raiseAmbiguousNonAssociativeOperatorError, phoenix::ref(*this), qi::_r1, qi::_r2)]); + noAmbiguousNonAssociativeOperator.name("no ambiguous non-associative operator"); + identifier %= qi::as_string[qi::raw[qi::lexeme[((qi::alpha | qi::char_('_') | qi::char_('.')) >> *(qi::alnum | qi::char_('_')))]]]; + identifier.name("identifier"); + label %= qi::as_string[qi::raw[qi::lexeme[((qi::alpha | qi::char_('_')) >> *(qi::alnum | qi::char_('_')))]]]; label.name("label"); + quotedString %= qi::as_string[qi::lexeme[qi::omit[qi::char_('"')] > qi::raw[*(!qi::char_('"') >> qi::char_)] > qi::omit[qi::lit('"')]]]; + quotedString.name("quoted string"); + + // PCTL-like Operator Formulas + operatorInformation = (-optimalityOperator_)[qi::_a = qi::_1] >> + ((qi::lit("=") > qi::lit("?"))[qi::_val = phoenix::bind(&FormulaParserGrammar::createOperatorInformation, phoenix::ref(*this), qi::_a, boost::none, boost::none)] + | (relationalOperator_ > expressionParser)[qi::_val = phoenix::bind(&FormulaParserGrammar::createOperatorInformation, phoenix::ref(*this), qi::_a, qi::_1, qi::_2)] + ); + operatorInformation.name("operator information"); + operatorSubFormula = (( (qi::eps(qi::_r1 == storm::logic::FormulaContext::Probability) > formula(FormulaKind::Path, qi::_r1)) + | (qi::eps(qi::_r1 == storm::logic::FormulaContext::Reward) > (longRunAverageRewardFormula | eventuallyFormula( qi::_r1) | cumulativeRewardFormula | instantaneousRewardFormula | totalRewardFormula)) + | (qi::eps(qi::_r1 == storm::logic::FormulaContext::Time) > eventuallyFormula(qi::_r1)) + | (qi::eps(qi::_r1 == storm::logic::FormulaContext::LongRunAverage) > formula(FormulaKind::State, storm::logic::FormulaContext::LongRunAverage)) + ) >> -(qi::lit("||") > formula(FormulaKind::Path, storm::logic::FormulaContext::Probability)) + )[qi::_val = phoenix::bind(&FormulaParserGrammar::createConditionalFormula, phoenix::ref(*this), qi::_1, qi::_2, qi::_r1)]; + operatorSubFormula.name("operator subformula"); + rewardModelName = qi::eps(qi::_r1 == storm::logic::FormulaContext::Reward) >> (qi::lit("{\"") > label > qi::lit("\"}")); + rewardModelName.name("reward model name"); + rewardMeasureType = qi::eps(qi::_r1 == storm::logic::FormulaContext::Reward || qi::_r1 == storm::logic::FormulaContext::Time) >> qi::lit("[") >> rewardMeasureType_ >> qi::lit("]"); + rewardMeasureType.name("reward measure type"); + operatorFormula = (operatorKeyword_[qi::_a = qi::_1] > -rewardMeasureType(qi::_a) > -rewardModelName(qi::_a) > operatorInformation > qi::lit("[") > operatorSubFormula(qi::_a) > qi::lit("]")) + [qi::_val = phoenix::bind(&FormulaParserGrammar::createOperatorFormula, phoenix::ref(*this), qi::_a, qi::_2, qi::_3, qi::_4, qi::_5)]; + operatorFormula.name("operator formula"); + + // Atomic propositions labelFormula = (qi::lit("\"") >> label >> qi::lit("\""))[qi::_val = phoenix::bind(&FormulaParserGrammar::createAtomicLabelFormula, phoenix::ref(*this), qi::_1)]; labelFormula.name("label formula"); - booleanLiteralFormula = (qi::lit("true")[qi::_a = true] | qi::lit("false")[qi::_a = false])[qi::_val = phoenix::bind(&FormulaParserGrammar::createBooleanLiteralFormula, phoenix::ref(*this), qi::_a)]; booleanLiteralFormula.name("boolean literal formula"); - - operatorFormula = probabilityOperator | rewardOperator | longRunAverageOperator | timeOperator; - operatorFormula.name("operator formulas"); - - atomicStateFormula = booleanLiteralFormula | labelFormula | expressionFormula | (qi::lit("(") > stateFormula > qi::lit(")")) | operatorFormula; - atomicStateFormula.name("atomic state formula"); - - atomicStateFormulaWithoutExpression = booleanLiteralFormula | labelFormula | (qi::lit("(") > stateFormula > qi::lit(")")) | operatorFormula; - atomicStateFormula.name("atomic state formula without expression"); - - notStateFormula = (unaryBooleanOperator_ >> atomicStateFormulaWithoutExpression)[qi::_val = phoenix::bind(&FormulaParserGrammar::createUnaryBooleanStateFormula, phoenix::ref(*this), qi::_2, qi::_1)] | atomicStateFormula[qi::_val = qi::_1]; - notStateFormula.name("negation formula"); - - eventuallyFormula = (qi::lit("F") >> (-timeBounds) >> pathFormulaWithoutUntil(qi::_r1))[qi::_val = phoenix::bind(&FormulaParserGrammar::createEventuallyFormula, phoenix::ref(*this), qi::_1, qi::_r1, qi::_2)]; - eventuallyFormula.name("eventually formula"); - - globallyFormula = (qi::lit("G") >> (-timeBounds) >> pathFormulaWithoutUntil(qi::_r1))[qi::_val = phoenix::bind(&FormulaParserGrammar::createGloballyFormula, phoenix::ref(*this), qi::_1, qi::_2)]; - globallyFormula.name("globally formula"); - - nextFormula = (qi::lit("X") >> pathFormulaWithoutUntil(qi::_r1))[qi::_val = phoenix::bind(&FormulaParserGrammar::createNextFormula, phoenix::ref(*this), qi::_1)]; - nextFormula.name("next formula"); - - pathFormulaWithoutUntil = eventuallyFormula(qi::_r1) | globallyFormula(qi::_r1) | nextFormula(qi::_r1) | stateFormula; - pathFormulaWithoutUntil.name("path formula"); - - untilFormula = pathFormulaWithoutUntil(qi::_r1)[qi::_val = qi::_1] >> *(qi::lit("U") >> (-timeBounds) >> pathFormulaWithoutUntil(qi::_r1))[qi::_val = phoenix::bind(&FormulaParserGrammar::createUntilFormula, phoenix::ref(*this), qi::_val, qi::_1, qi::_2)]; - untilFormula.name("until formula"); - - conditionalFormula = untilFormula(qi::_r1)[qi::_val = qi::_1] >> *(qi::lit("||") >> untilFormula(storm::logic::FormulaContext::Probability))[qi::_val = phoenix::bind(&FormulaParserGrammar::createConditionalFormula, phoenix::ref(*this), qi::_val, qi::_1, qi::_r1)]; - conditionalFormula.name("conditional formula"); - - timeBoundReference = (-qi::lit("rew") >> rewardModelName)[qi::_val = phoenix::bind(&FormulaParserGrammar::createTimeBoundReference, phoenix::ref(*this), storm::logic::TimeBoundType::Reward, qi::_1)] + expressionFormula = expressionParser[qi::_val = phoenix::bind(&FormulaParserGrammar::createAtomicExpressionFormula, phoenix::ref(*this), qi::_1)]; + expressionFormula.name("expression formula"); + atomicPropositionFormula = (booleanLiteralFormula | labelFormula | expressionFormula); + atomicPropositionFormula.name("atomic proposition"); + + // Propositional Logic operators + // To correctly parse the operator precedences (! binds stronger than & binds stronger than |), we run through different "precedence levels" starting with the weakest binding operator. + basicPropositionalFormula = (qi::lit("(") >> (formula(qi::_r1, qi::_r2) > qi::lit(")"))) + | atomicPropositionFormula // Should be checked before operator formulas and others. Otherwise, e.g. variable "Random" would be parsed as reward operator 'R' (followed by andom) + | negationPropositionalFormula(qi::_r1, qi::_r2) + | operatorFormula + | (isPathFormula(qi::_r1) >> prefixOperatorPathFormula(qi::_r2)) // Needed for e.g. F "a" & X "a" = F ("a" & (X "a")) + | multiOperatorFormula // Has to come after prefixOperatorPathFormula to avoid confusion with multiBoundedPathFormula + | quantileFormula + | gameFormula; + negationPropositionalFormula = (qi::lit("!") > basicPropositionalFormula(qi::_r1, qi::_r2))[qi::_val = phoenix::bind(&FormulaParserGrammar::createUnaryBooleanStateOrPathFormula, phoenix::ref(*this), qi::_1, storm::logic::UnaryBooleanOperatorType::Not)]; + basicPropositionalFormula.name("basic propositional formula"); + andLevelPropositionalFormula = basicPropositionalFormula(qi::_r1, qi::_r2)[qi::_val = qi::_1] + >> *( qi::lit("&") + > basicPropositionalFormula(qi::_r1, qi::_r2)[qi::_val = phoenix::bind(&FormulaParserGrammar::createBinaryBooleanStateOrPathFormula, phoenix::ref(*this), qi::_val, qi::_1, storm::logic::BinaryBooleanStateFormula::OperatorType::And)]); + andLevelPropositionalFormula.name("and precedence level propositional formula"); + orLevelPropositionalFormula = andLevelPropositionalFormula(qi::_r1, qi::_r2)[qi::_val = qi::_1] + >> *( (!qi::lit("||") >> qi::lit("|")) // Make sure to not confuse with conditional operator "||" + > andLevelPropositionalFormula(qi::_r1, qi::_r2)[qi::_val = phoenix::bind(&FormulaParserGrammar::createBinaryBooleanStateOrPathFormula, phoenix::ref(*this), qi::_val, qi::_1, storm::logic::BinaryBooleanStateFormula::OperatorType::Or)]); + orLevelPropositionalFormula.name("or precedence level propositional formula"); + propositionalFormula = orLevelPropositionalFormula(qi::_r1, qi::_r2); + + // Path operators + // Again need to parse precedences correctly. Propositional formulae bind stronger than temporal operators. + basicPathFormula = propositionalFormula(FormulaKind::Path, qi::_r1) // Bracketed case is handled here as well + | prefixOperatorPathFormula(qi::_r1); // Needs to be checked *after* atomic expression formulas. Otherwise e.g. variable Fail would be parsed as "F (ail)" + prefixOperatorPathFormula = eventuallyFormula(qi::_r1) + | nextFormula(qi::_r1) + | globallyFormula(qi::_r1) + | hoaPathFormula(qi::_r1) + | multiBoundedPathFormula(qi::_r1); + basicPathFormula.name("basic path formula"); + timeBoundReference = (-qi::lit("rew") >> rewardModelName(storm::logic::FormulaContext::Reward))[qi::_val = phoenix::bind(&FormulaParserGrammar::createTimeBoundReference, phoenix::ref(*this), storm::logic::TimeBoundType::Reward, qi::_1)] | (qi::lit("steps"))[qi::_val = phoenix::bind(&FormulaParserGrammar::createTimeBoundReference, phoenix::ref(*this), storm::logic::TimeBoundType::Steps, boost::none)] | (-qi::lit("time"))[qi::_val = phoenix::bind(&FormulaParserGrammar::createTimeBoundReference, phoenix::ref(*this), storm::logic::TimeBoundType::Time, boost::none)]; timeBoundReference.name("time bound reference"); - timeBound = ((timeBoundReference >> qi::lit("[")) > expressionParser > qi::lit(",") > expressionParser > qi::lit("]")) [qi::_val = phoenix::bind(&FormulaParserGrammar::createTimeBoundFromInterval, phoenix::ref(*this), qi::_2, qi::_3, qi::_1)] | ( timeBoundReference >> (qi::lit("<=")[qi::_a = true, qi::_b = false] | qi::lit("<")[qi::_a = true, qi::_b = true] | qi::lit(">=")[qi::_a = false, qi::_b = false] | qi::lit(">")[qi::_a = false, qi::_b = true]) >> expressionParser) @@ -89,88 +116,74 @@ namespace storm { | ( timeBoundReference >> qi::lit("=") >> expressionParser) [qi::_val = phoenix::bind(&FormulaParserGrammar::createTimeBoundFromInterval, phoenix::ref(*this), qi::_2, qi::_2, qi::_1)]; timeBound.name("time bound"); - timeBounds = (timeBound % qi::lit(",")) | (((-qi::lit("^") >> qi::lit("{")) >> (timeBound % qi::lit(","))) >> qi::lit("}")); timeBounds.name("time bounds"); - - pathFormula = conditionalFormula(qi::_r1); + eventuallyFormula = (qi::lit("F") > (-timeBounds) > basicPathFormula(qi::_r1))[qi::_val = phoenix::bind(&FormulaParserGrammar::createEventuallyFormula, phoenix::ref(*this), qi::_1, qi::_r1, qi::_2)]; + eventuallyFormula.name("eventually formula"); + nextFormula = (qi::lit("X") > basicPathFormula(qi::_r1))[qi::_val = phoenix::bind(&FormulaParserGrammar::createNextFormula, phoenix::ref(*this), qi::_1)]; + nextFormula.name("next formula"); + globallyFormula = (qi::lit("G") > basicPathFormula(qi::_r1))[qi::_val = phoenix::bind(&FormulaParserGrammar::createGloballyFormula, phoenix::ref(*this), qi::_1)]; + globallyFormula.name("globally formula"); + hoaPathFormula = qi::lit("HOA:") > qi::lit("{") + > quotedString[qi::_val = phoenix::bind(&FormulaParserGrammar::createHOAPathFormula, phoenix::ref(*this), qi::_1)] + >> *(qi::lit(",") > quotedString > qi::lit("->") > formula(FormulaKind::State, qi::_r1) )[phoenix::bind(&FormulaParserGrammar::addHoaAPMapping, phoenix::ref(*this), *qi::_val, qi::_1, qi::_2)] + > qi::lit("}"); + multiBoundedPathFormulaOperand = pathFormula(qi::_r1)[qi::_pass = phoenix::bind(&FormulaParserGrammar::isValidMultiBoundedPathFormulaOperand, phoenix::ref(*this), qi::_1)][qi::_val = qi::_1]; + multiBoundedPathFormulaOperand.name("multi bounded path formula operand"); + multiBoundedPathFormula = ((qi::lit("multi") > qi::lit("(")) >> (multiBoundedPathFormulaOperand(qi::_r1) % qi::lit(",")) >> qi::lit(")"))[qi::_val = phoenix::bind(&FormulaParserGrammar::createMultiBoundedPathFormula, phoenix::ref(*this), qi::_1)]; + multiBoundedPathFormula.name("multi bounded path formula"); + untilLevelPathFormula = basicPathFormula(qi::_r1)[qi::_val = qi::_1] + >> -( (qi::lit("U") + > (-timeBounds) > basicPathFormula(qi::_r1))[qi::_val = phoenix::bind(&FormulaParserGrammar::createUntilFormula, phoenix::ref(*this), qi::_val, qi::_1, qi::_2)]) + >> (qi::eps > noAmbiguousNonAssociativeOperator(qi::_val,std::string("U"))); // Do not parse a U b U c + untilLevelPathFormula.name("until precedence level path formula"); + pathFormula = untilLevelPathFormula(qi::_r1); pathFormula.name("path formula"); - rewardMeasureType = qi::lit("[") >> rewardMeasureType_ >> qi::lit("]"); - rewardMeasureType.name("reward measure type"); - - operatorInformation = (-optimalityOperator_[qi::_a = qi::_1] >> ((relationalOperator_[qi::_b = qi::_1] > expressionParser[qi::_c = qi::_1]) | (qi::lit("=") > qi::lit("?"))))[qi::_val = phoenix::bind(&FormulaParserGrammar::createOperatorInformation, phoenix::ref(*this), qi::_a, qi::_b, qi::_c)]; - operatorInformation.name("operator information"); - - longRunAverageOperator = ((qi::lit("LRA") | qi::lit("S")) > operatorInformation > qi::lit("[") > stateFormula > qi::lit("]"))[qi::_val = phoenix::bind(&FormulaParserGrammar::createLongRunAverageOperatorFormula, phoenix::ref(*this), qi::_1, qi::_2)]; - longRunAverageOperator.name("long-run average operator"); - - rewardModelName = qi::lit("{\"") > label > qi::lit("\"}"); - rewardModelName.name("reward model name"); - - rewardOperator = (qi::lit("R") > -rewardMeasureType > -rewardModelName > operatorInformation > qi::lit("[") > rewardPathFormula > qi::lit("]"))[qi::_val = phoenix::bind(&FormulaParserGrammar::createRewardOperatorFormula, phoenix::ref(*this), qi::_1, qi::_2, qi::_3, qi::_4)]; - rewardOperator.name("reward operator"); - - timeOperator = (qi::lit("T") > -rewardMeasureType > operatorInformation > qi::lit("[") > eventuallyFormula(storm::logic::FormulaContext::Time) > qi::lit("]"))[qi::_val = phoenix::bind(&FormulaParserGrammar::createTimeOperatorFormula, phoenix::ref(*this), qi::_1, qi::_2, qi::_3)]; - timeOperator.name("time operator"); - - probabilityOperator = (qi::lit("P") > operatorInformation > qi::lit("[") > pathFormula(storm::logic::FormulaContext::Probability) > qi::lit("]"))[qi::_val = phoenix::bind(&FormulaParserGrammar::createProbabilityOperatorFormula, phoenix::ref(*this), qi::_1, qi::_2)]; - probabilityOperator.name("probability operator"); - - andStateFormula = notStateFormula[qi::_val = qi::_1] >> *(qi::lit("&") >> notStateFormula)[qi::_val = phoenix::bind(&FormulaParserGrammar::createBinaryBooleanStateFormula, phoenix::ref(*this), qi::_val, qi::_1, storm::logic::BinaryBooleanStateFormula::OperatorType::And)]; - andStateFormula.name("and state formula"); - - orStateFormula = andStateFormula[qi::_val = qi::_1] >> *(qi::lit("|") >> andStateFormula)[qi::_val = phoenix::bind(&FormulaParserGrammar::createBinaryBooleanStateFormula, phoenix::ref(*this), qi::_val, qi::_1, storm::logic::BinaryBooleanStateFormula::OperatorType::Or)]; - orStateFormula.name("or state formula"); - - multiFormula = (qi::lit("multi") > qi::lit("(") >> ((pathFormula(storm::logic::FormulaContext::Probability) | stateFormula) % qi::lit(",")) >> qi::lit(")"))[qi::_val = phoenix::bind(&FormulaParserGrammar::createMultiFormula, phoenix::ref(*this), qi::_1)]; - multiFormula.name("Multi formula"); - - identifier %= qi::as_string[qi::raw[qi::lexeme[((qi::alpha | qi::char_('_') | qi::char_('.')) >> *(qi::alnum | qi::char_('_')))]]]; - identifier.name("identifier"); - - quantileBoundVariable = (-(qi::lit("min")[qi::_a = storm::solver::OptimizationDirection::Minimize] | qi::lit("max")[qi::_a = storm::solver::OptimizationDirection::Maximize]) >> identifier >> qi::lit(","))[qi::_val = phoenix::bind(&FormulaParserGrammar::createQuantileBoundVariables, phoenix::ref(*this), qi::_a, qi::_1)]; - quantileBoundVariable.name("quantile bound variable"); - quantileFormula = (qi::lit("quantile") > qi::lit("(") >> *(quantileBoundVariable) >> stateFormula > qi::lit(")"))[qi::_val = phoenix::bind(&FormulaParserGrammar::createQuantileFormula, phoenix::ref(*this), qi::_1, qi::_2)]; - quantileFormula.name("Quantile formula"); + // Quantitative path formulae (reward) + longRunAverageRewardFormula = (qi::lit("LRA") | qi::lit("S") | qi::lit("MP"))[qi::_val = phoenix::bind(&FormulaParserGrammar::createLongRunAverageRewardFormula, phoenix::ref(*this))]; + longRunAverageRewardFormula.name("long run average reward formula"); + instantaneousRewardFormula = (qi::lit("I=") > expressionParser)[qi::_val = phoenix::bind(&FormulaParserGrammar::createInstantaneousRewardFormula, phoenix::ref(*this), qi::_1)]; + instantaneousRewardFormula.name("instantaneous reward formula"); + cumulativeRewardFormula = (qi::lit("C") >> timeBounds)[qi::_val = phoenix::bind(&FormulaParserGrammar::createCumulativeRewardFormula, phoenix::ref(*this), qi::_1)]; + cumulativeRewardFormula.name("cumulative reward formula"); + totalRewardFormula = (qi::lit("C"))[qi::_val = phoenix::bind(&FormulaParserGrammar::createTotalRewardFormula, phoenix::ref(*this))]; + totalRewardFormula.name("total reward formula"); + // Game Formulae playerCoalition = (-((identifier[phoenix::push_back(qi::_a, qi::_1)] | qi::uint_[phoenix::push_back(qi::_a, qi::_1)]) % ','))[qi::_val = phoenix::bind(&FormulaParserGrammar::createPlayerCoalition, phoenix::ref(*this), qi::_a)]; playerCoalition.name("player coalition"); - gameFormula = (qi::lit("<<") > playerCoalition > qi::lit(">>") > operatorFormula)[qi::_val = phoenix::bind(&FormulaParserGrammar::createGameFormula, phoenix::ref(*this), qi::_1, qi::_2)]; gameFormula.name("game formula"); - shieldExpression = (qi::lit("<") > label > qi::lit(",") > shieldingType > -(qi::lit(",") > shieldComparison) > qi::lit(">"))[qi::_val = phoenix::bind(&FormulaParserGrammar::createShieldExpression, phoenix::ref(*this), qi::_2, qi::_1, qi::_3)]; - - shieldExpression.name("shield expression"); - - shieldingType = (qi::lit("PreSafety")[qi::_val = storm::logic::ShieldingType::PreSafety] | - qi::lit("PostSafety")[qi::_val = storm::logic::ShieldingType::PostSafety] | - qi::lit("Optimal")[qi::_val = storm::logic::ShieldingType::Optimal]) > -qi::lit("Shield"); - shieldingType.name("shielding type"); - - probability = qi::double_[qi::_pass = (qi::_1 >= 0) & (qi::_1 <= 1.0), qi::_val = qi::_1 ]; - probability.name("double between 0 and 1"); + // Multi-objective, quantiles + multiOperatorFormula = (qi::lit("multi") > qi::lit("(") + > (operatorFormula % qi::lit(",")) + > qi::lit(")"))[qi::_val = phoenix::bind(&FormulaParserGrammar::createMultiOperatorFormula, phoenix::ref(*this), qi::_1)]; + multiOperatorFormula.name("multi-objective operator formula"); + quantileBoundVariable = (-optimalityOperator_ >> identifier >> qi::lit(","))[qi::_val = phoenix::bind(&FormulaParserGrammar::createQuantileBoundVariables, phoenix::ref(*this), qi::_1, qi::_2)]; + quantileBoundVariable.name("quantile bound variable"); + quantileFormula = (qi::lit("quantile") > qi::lit("(") > *(quantileBoundVariable) > operatorFormula[qi::_pass = phoenix::bind(&FormulaParserGrammar::isBooleanReturnType, phoenix::ref(*this), qi::_1, true)] > qi::lit(")"))[qi::_val = phoenix::bind(&FormulaParserGrammar::createQuantileFormula, phoenix::ref(*this), qi::_1, qi::_2)]; + quantileFormula.name("Quantile formula"); - shieldComparison = ((qi::lit("lambda")[qi::_a = storm::logic::ShieldComparison::Relative] | - qi::lit("gamma")[qi::_a = storm::logic::ShieldComparison::Absolute]) > qi::lit("=") > probability)[qi::_val = phoenix::bind(&FormulaParserGrammar::createShieldComparisonStruct, phoenix::ref(*this), qi::_a, qi::_1)]; - shieldComparison.name("shield comparison type"); + // General formulae + formula = (isPathFormula(qi::_r1) >> pathFormula(qi::_r2) | propositionalFormula(qi::_r1, qi::_r2)); + formula.name("formula"); - stateFormula = (orStateFormula | multiFormula | quantileFormula | gameFormula); - stateFormula.name("state formula"); + topLevelFormula = formula(FormulaKind::State, storm::logic::FormulaContext::Undefined); + topLevelFormula.name("top-level formula"); formulaName = qi::lit("\"") >> identifier >> qi::lit("\"") >> qi::lit(":"); formulaName.name("formula name"); - - constantDefinition = (qi::lit("const") > -(qi::lit("int")[qi::_a = ConstantDataType::Integer] | qi::lit("bool")[qi::_a = ConstantDataType::Bool] | qi::lit("double")[qi::_a = ConstantDataType::Rational]) >> identifier >> -(qi::lit("=") > expressionParser))[phoenix::bind(&FormulaParserGrammar::addConstant, phoenix::ref(*this), qi::_1, qi::_a, qi::_2)]; constantDefinition.name("constant definition"); #pragma clang diagnostic push #pragma clang diagnostic ignored "-Woverloaded-shift-op-parentheses" - filterProperty = (-formulaName >> qi::lit("filter") > qi::lit("(") > filterType_ > qi::lit(",") > stateFormula > qi::lit(",") > stateFormula > qi::lit(")"))[qi::_val = phoenix::bind(&FormulaParserGrammar::createProperty, phoenix::ref(*this), qi::_1, qi::_2, qi::_3, qi::_4)] | (-formulaName >> stateFormula)[qi::_val = phoenix::bind(&FormulaParserGrammar::createPropertyWithDefaultFilterTypeAndStates, phoenix::ref(*this), qi::_1, qi::_2)] | (-formulaName >> shieldExpression >> stateFormula)[qi::_val = phoenix::bind(&FormulaParserGrammar::createShieldingProperty, phoenix::ref(*this), qi::_1, qi::_3, qi::_2)]; + filterProperty = (-formulaName >> qi::lit("filter") > qi::lit("(") > filterType_ > qi::lit(",") > topLevelFormula > qi::lit(",") > formula(FormulaKind::State, storm::logic::FormulaContext::Undefined)> qi::lit(")"))[qi::_val = phoenix::bind(&FormulaParserGrammar::createProperty, phoenix::ref(*this), qi::_1, qi::_2, qi::_3, qi::_4)] | + (-formulaName >> topLevelFormula)[qi::_val = phoenix::bind(&FormulaParserGrammar::createPropertyWithDefaultFilterTypeAndStates, phoenix::ref(*this), qi::_1, qi::_2)]; filterProperty.name("filter property"); #pragma clang diagnostic pop @@ -182,60 +195,91 @@ namespace storm { start.name("start"); // Enable the following lines to print debug output for most the rules. - //debug(start); - //debug(constantDefinition); - //debug(stateFormula); - //debug(orStateFormula); - //debug(andStateFormula); - //debug(probabilityOperator); - //debug(rewardOperator); - //debug(longRunAverageOperator); - //debug(timeOperator); - //debug(pathFormulaWithoutUntil); - //debug(pathFormula); - //debug(conditionalFormula); - //debug(nextFormula); - //debug(globallyFormula); - //debug(eventuallyFormula); - //debug(atomicStateFormula); - //debug(booleanLiteralFormula); - //debug(labelFormula); - //debug(expressionFormula); - //debug(rewardPathFormula); - //debug(cumulativeRewardFormula); - //debug(totalRewardFormula); - //debug(instantaneousRewardFormula); - //debug(multiFormula); +// debug(rewardModelName) +// debug(rewardMeasureType) +// debug(operatorFormula) +// debug(labelFormula) +// debug(expressionFormula) +// debug(booleanLiteralFormula) +// debug(atomicPropositionFormula) +// debug(basicPropositionalFormula) +// debug(negationPropositionalFormula) +// debug(andLevelPropositionalFormula) +// debug(orLevelPropositionalFormula) +// debug(propositionalFormula) +// debug(timeBoundReference) +// debug(timeBound) +// debug(timeBounds) +// debug(eventuallyFormula) +// debug(nextFormula) +// debug(globallyFormula) +// debug(hoaPathFormula) +// debug(multiBoundedPathFormula) +// debug(prefixOperatorPathFormula) +// debug(basicPathFormula) +// debug(untilLevelPathFormula) +// debug(pathFormula) +// debug(longRunAverageRewardFormula) +// debug(instantaneousRewardFormula) +// debug(cumulativeRewardFormula) +// debug(totalRewardFormula) +// debug(playerCoalition) +// debug(gameFormula) +// debug(multiOperatorFormula) +// debug(quantileBoundVariable) +// debug(quantileFormula) +// debug(formula) +// debug(topLevelFormula) +// debug(formulaName) +// debug(filterProperty) +// debug(constantDefinition ) +// debug(start) // Enable error reporting. - qi::on_error<qi::fail>(start, handler(qi::_1, qi::_2, qi::_3, qi::_4)); - qi::on_error<qi::fail>(stateFormula, handler(qi::_1, qi::_2, qi::_3, qi::_4)); - qi::on_error<qi::fail>(orStateFormula, handler(qi::_1, qi::_2, qi::_3, qi::_4)); - qi::on_error<qi::fail>(andStateFormula, handler(qi::_1, qi::_2, qi::_3, qi::_4)); - qi::on_error<qi::fail>(probabilityOperator, handler(qi::_1, qi::_2, qi::_3, qi::_4)); - qi::on_error<qi::fail>(rewardOperator, handler(qi::_1, qi::_2, qi::_3, qi::_4)); - qi::on_error<qi::fail>(longRunAverageOperator, handler(qi::_1, qi::_2, qi::_3, qi::_4)); - qi::on_error<qi::fail>(timeOperator, handler(qi::_1, qi::_2, qi::_3, qi::_4)); - qi::on_error<qi::fail>(operatorInformation, handler(qi::_1, qi::_2, qi::_3, qi::_4)); - qi::on_error<qi::fail>(pathFormulaWithoutUntil, handler(qi::_1, qi::_2, qi::_3, qi::_4)); - qi::on_error<qi::fail>(pathFormula, handler(qi::_1, qi::_2, qi::_3, qi::_4)); - qi::on_error<qi::fail>(conditionalFormula, handler(qi::_1, qi::_2, qi::_3, qi::_4)); - qi::on_error<qi::fail>(untilFormula, handler(qi::_1, qi::_2, qi::_3, qi::_4)); - qi::on_error<qi::fail>(nextFormula, handler(qi::_1, qi::_2, qi::_3, qi::_4)); - qi::on_error<qi::fail>(globallyFormula, handler(qi::_1, qi::_2, qi::_3, qi::_4)); - qi::on_error<qi::fail>(eventuallyFormula, handler(qi::_1, qi::_2, qi::_3, qi::_4)); - qi::on_error<qi::fail>(atomicStateFormula, handler(qi::_1, qi::_2, qi::_3, qi::_4)); - qi::on_error<qi::fail>(booleanLiteralFormula, handler(qi::_1, qi::_2, qi::_3, qi::_4)); + qi::on_error<qi::fail>(rewardModelName, handler(qi::_1, qi::_2, qi::_3, qi::_4)); + qi::on_error<qi::fail>(rewardMeasureType, handler(qi::_1, qi::_2, qi::_3, qi::_4)); + qi::on_error<qi::fail>(operatorFormula, handler(qi::_1, qi::_2, qi::_3, qi::_4)); qi::on_error<qi::fail>(labelFormula, handler(qi::_1, qi::_2, qi::_3, qi::_4)); qi::on_error<qi::fail>(expressionFormula, handler(qi::_1, qi::_2, qi::_3, qi::_4)); - qi::on_error<qi::fail>(rewardPathFormula, handler(qi::_1, qi::_2, qi::_3, qi::_4)); + qi::on_error<qi::fail>(booleanLiteralFormula, handler(qi::_1, qi::_2, qi::_3, qi::_4)); + qi::on_error<qi::fail>(atomicPropositionFormula, handler(qi::_1, qi::_2, qi::_3, qi::_4)); + qi::on_error<qi::fail>(basicPropositionalFormula, handler(qi::_1, qi::_2, qi::_3, qi::_4)); + qi::on_error<qi::fail>(negationPropositionalFormula, handler(qi::_1, qi::_2, qi::_3, qi::_4)); + qi::on_error<qi::fail>(andLevelPropositionalFormula, handler(qi::_1, qi::_2, qi::_3, qi::_4)); + qi::on_error<qi::fail>(orLevelPropositionalFormula, handler(qi::_1, qi::_2, qi::_3, qi::_4)); + qi::on_error<qi::fail>(propositionalFormula, handler(qi::_1, qi::_2, qi::_3, qi::_4)); + qi::on_error<qi::fail>(timeBoundReference, handler(qi::_1, qi::_2, qi::_3, qi::_4)); + qi::on_error<qi::fail>(timeBound, handler(qi::_1, qi::_2, qi::_3, qi::_4)); + qi::on_error<qi::fail>(timeBounds, handler(qi::_1, qi::_2, qi::_3, qi::_4)); + qi::on_error<qi::fail>(eventuallyFormula, handler(qi::_1, qi::_2, qi::_3, qi::_4)); + qi::on_error<qi::fail>(nextFormula, handler(qi::_1, qi::_2, qi::_3, qi::_4)); + qi::on_error<qi::fail>(globallyFormula, handler(qi::_1, qi::_2, qi::_3, qi::_4)); + qi::on_error<qi::fail>(hoaPathFormula, handler(qi::_1, qi::_2, qi::_3, qi::_4)); + qi::on_error<qi::fail>(multiBoundedPathFormula, handler(qi::_1, qi::_2, qi::_3, qi::_4)); + qi::on_error<qi::fail>(prefixOperatorPathFormula, handler(qi::_1, qi::_2, qi::_3, qi::_4)); + qi::on_error<qi::fail>(basicPathFormula, handler(qi::_1, qi::_2, qi::_3, qi::_4)); + qi::on_error<qi::fail>(untilLevelPathFormula, handler(qi::_1, qi::_2, qi::_3, qi::_4)); + qi::on_error<qi::fail>(pathFormula, handler(qi::_1, qi::_2, qi::_3, qi::_4)); + qi::on_error<qi::fail>(longRunAverageRewardFormula, handler(qi::_1, qi::_2, qi::_3, qi::_4)); + qi::on_error<qi::fail>(instantaneousRewardFormula, handler(qi::_1, qi::_2, qi::_3, qi::_4)); qi::on_error<qi::fail>(cumulativeRewardFormula, handler(qi::_1, qi::_2, qi::_3, qi::_4)); qi::on_error<qi::fail>(totalRewardFormula, handler(qi::_1, qi::_2, qi::_3, qi::_4)); - qi::on_error<qi::fail>(instantaneousRewardFormula, handler(qi::_1, qi::_2, qi::_3, qi::_4)); - qi::on_error<qi::fail>(multiFormula, handler(qi::_1, qi::_2, qi::_3, qi::_4)); + qi::on_error<qi::fail>(playerCoalition, handler(qi::_1, qi::_2, qi::_3, qi::_4)); + qi::on_error<qi::fail>(gameFormula, handler(qi::_1, qi::_2, qi::_3, qi::_4)); + qi::on_error<qi::fail>(multiOperatorFormula, handler(qi::_1, qi::_2, qi::_3, qi::_4)); + qi::on_error<qi::fail>(quantileBoundVariable, handler(qi::_1, qi::_2, qi::_3, qi::_4)); + qi::on_error<qi::fail>(quantileFormula, handler(qi::_1, qi::_2, qi::_3, qi::_4)); + qi::on_error<qi::fail>(formula, handler(qi::_1, qi::_2, qi::_3, qi::_4)); + qi::on_error<qi::fail>(topLevelFormula, handler(qi::_1, qi::_2, qi::_3, qi::_4)); + qi::on_error<qi::fail>(formulaName, handler(qi::_1, qi::_2, qi::_3, qi::_4)); + qi::on_error<qi::fail>(filterProperty, handler(qi::_1, qi::_2, qi::_3, qi::_4)); + qi::on_error<qi::fail>(constantDefinition , handler(qi::_1, qi::_2, qi::_3, qi::_4)); + qi::on_error<qi::fail>(start, handler(qi::_1, qi::_2, qi::_3, qi::_4)); } void FormulaParserGrammar::addIdentifierExpression(std::string const& identifier, storm::expressions::Expression const& expression) { + STORM_LOG_WARN_COND(keywords_.find(identifier) == nullptr, "Identifier `" << identifier << "' coincides with a reserved keyword or operator. Property expressions using the variable or constant '" << identifier << "' will not be parsed correctly."); + STORM_LOG_WARN_COND(nonStandardKeywords_.find(identifier) == nullptr, "Identifier `" << identifier << "' coincides with a reserved keyword or operator. Property expressions using the variable or constant '" << identifier << "' might not be parsed correctly."); this->identifiers_.add(identifier, expression); } @@ -342,20 +386,8 @@ namespace storm { } } - std::shared_ptr<storm::logic::Formula const> FormulaParserGrammar::createGloballyFormula(boost::optional<std::vector<std::tuple<boost::optional<storm::logic::TimeBound>, boost::optional<storm::logic::TimeBound>, std::shared_ptr<storm::logic::TimeBoundReference>>>> const& timeBounds, std::shared_ptr<storm::logic::Formula const> const& subformula) const { - if (timeBounds && !timeBounds.get().empty()) { - std::vector<boost::optional<storm::logic::TimeBound>> lowerBounds, upperBounds; - std::vector<storm::logic::TimeBoundReference> timeBoundReferences; - for (auto const& timeBound : timeBounds.get()) { - STORM_LOG_ASSERT(!std::get<0>(timeBound), "Cannot use lower time bounds (or intervals) in globally formulas."); - lowerBounds.push_back(std::get<0>(timeBound)); - upperBounds.push_back(std::get<1>(timeBound)); - timeBoundReferences.emplace_back(*std::get<2>(timeBound)); - } - return std::shared_ptr<storm::logic::Formula const>(new storm::logic::BoundedGloballyFormula(subformula, lowerBounds, upperBounds, timeBoundReferences)); - } else { - return std::shared_ptr<storm::logic::Formula const>(new storm::logic::GloballyFormula(subformula)); - } + std::shared_ptr<storm::logic::Formula const> FormulaParserGrammar::createGloballyFormula(std::shared_ptr<storm::logic::Formula const> const& subformula) const { + return std::shared_ptr<storm::logic::Formula const>(new storm::logic::GloballyFormula(subformula)); } std::shared_ptr<storm::logic::Formula const> FormulaParserGrammar::createNextFormula(std::shared_ptr<storm::logic::Formula const> const& subformula) const { @@ -377,8 +409,24 @@ namespace storm { } } - std::shared_ptr<storm::logic::Formula const> FormulaParserGrammar::createConditionalFormula(std::shared_ptr<storm::logic::Formula const> const& leftSubformula, std::shared_ptr<storm::logic::Formula const> const& rightSubformula, storm::logic::FormulaContext context) const { - return std::shared_ptr<storm::logic::Formula const>(new storm::logic::ConditionalFormula(leftSubformula, rightSubformula, context)); + std::shared_ptr<storm::logic::Formula const> FormulaParserGrammar::createHOAPathFormula(std::string const& automatonFile) const { + return std::shared_ptr<storm::logic::Formula const>(new storm::logic::HOAPathFormula(automatonFile)); + } + + void FormulaParserGrammar::addHoaAPMapping(storm::logic::Formula const& hoaFormula, const std::string& ap, std::shared_ptr<storm::logic::Formula const>& expression) const { + // taking a const Formula reference and doing static_ and const_cast from Formula to allow non-const access to + // qi::_val of the hoaPathFormula rule + storm::logic::HOAPathFormula& hoaFormula_ = static_cast<storm::logic::HOAPathFormula&>(const_cast<storm::logic::Formula&>(hoaFormula)); + hoaFormula_.addAPMapping(ap, expression); + } + + std::shared_ptr<storm::logic::Formula const> FormulaParserGrammar::createConditionalFormula(std::shared_ptr<storm::logic::Formula const> const& leftSubformula, boost::optional<std::shared_ptr<storm::logic::Formula const>> const& rightSubformula, storm::logic::FormulaContext context) const { + if (rightSubformula) { + return std::shared_ptr<storm::logic::Formula const>(new storm::logic::ConditionalFormula(leftSubformula, rightSubformula.get(), context)); + } else { + // If there is no rhs, just return the lhs + return leftSubformula; + } } storm::logic::OperatorInformation FormulaParserGrammar::createOperatorInformation(boost::optional<storm::OptimizationDirection> const& optimizationDirection, boost::optional<storm::logic::ComparisonType> const& comparisonType, boost::optional<storm::expressions::Expression> const& threshold) const { @@ -390,6 +438,24 @@ namespace storm { } } + std::shared_ptr<storm::logic::Formula const> FormulaParserGrammar::createOperatorFormula(storm::logic::FormulaContext const& context, boost::optional<storm::logic::RewardMeasureType> const& rewardMeasureType, boost::optional<std::string> const& rewardModelName, storm::logic::OperatorInformation const& operatorInformation, std::shared_ptr<storm::logic::Formula const> const& subformula) { + switch(context) { + case storm::logic::FormulaContext::Probability: + STORM_LOG_ASSERT(!rewardMeasureType && !rewardModelName, "Probability operator with reward information parsed"); + return createProbabilityOperatorFormula(operatorInformation, subformula); + case storm::logic::FormulaContext::Reward: + return createRewardOperatorFormula(rewardMeasureType, rewardModelName, operatorInformation, subformula); + case storm::logic::FormulaContext::LongRunAverage: + STORM_LOG_ASSERT(!rewardMeasureType && !rewardModelName, "LRA operator with reward information parsed"); + return createLongRunAverageOperatorFormula(operatorInformation, subformula); + case storm::logic::FormulaContext::Time: + STORM_LOG_ASSERT(!rewardModelName, "Time operator with reward model name parsed"); + return createTimeOperatorFormula(rewardMeasureType, operatorInformation, subformula); + default: + STORM_LOG_THROW(false, storm::exceptions::WrongFormatException, "Unexpected formula context."); + } + } + std::shared_ptr<storm::logic::Formula const> FormulaParserGrammar::createLongRunAverageOperatorFormula(storm::logic::OperatorInformation const& operatorInformation, std::shared_ptr<storm::logic::Formula const> const& subformula) const { return std::shared_ptr<storm::logic::Formula const>(new storm::logic::LongRunAverageOperatorFormula(subformula, operatorInformation)); } @@ -426,40 +492,73 @@ namespace storm { } } - std::shared_ptr<storm::logic::Formula const> FormulaParserGrammar::createMultiFormula(std::vector<std::shared_ptr<storm::logic::Formula const>> const& subformulas) { - bool isMultiDimensionalBoundedUntilFormula = !subformulas.empty(); - for (auto const& subformula : subformulas) { - if (!subformula->isBoundedUntilFormula()) { - isMultiDimensionalBoundedUntilFormula = false; - break; + std::shared_ptr<storm::logic::Formula const> FormulaParserGrammar::createBinaryBooleanPathFormula(std::shared_ptr<storm::logic::Formula const> const& leftSubformula, std::shared_ptr<storm::logic::Formula const> const& rightSubformula, storm::logic::BinaryBooleanPathFormula::OperatorType operatorType) { + return std::shared_ptr<storm::logic::Formula const>(new storm::logic::BinaryBooleanPathFormula(operatorType, leftSubformula, rightSubformula)); + } + + std::shared_ptr<storm::logic::Formula const> FormulaParserGrammar::createUnaryBooleanPathFormula(std::shared_ptr<storm::logic::Formula const> const& subformula, boost::optional<storm::logic::UnaryBooleanPathFormula::OperatorType> const& operatorType) { + if (operatorType) { + return std::shared_ptr<storm::logic::Formula const>(new storm::logic::UnaryBooleanPathFormula(operatorType.get(), subformula)); + } else { + return subformula; + } + } + + std::shared_ptr<storm::logic::Formula const> FormulaParserGrammar::createBinaryBooleanStateOrPathFormula(std::shared_ptr<storm::logic::Formula const> const& leftSubformula, std::shared_ptr<storm::logic::Formula const> const& rightSubformula, storm::logic::BinaryBooleanOperatorType operatorType) { + if (leftSubformula->isStateFormula() && rightSubformula->isStateFormula()) { + return createBinaryBooleanStateFormula(leftSubformula, rightSubformula, operatorType); + } else if (leftSubformula->isPathFormula() || rightSubformula->isPathFormula()) { + return createBinaryBooleanPathFormula(leftSubformula, rightSubformula, operatorType); + } + STORM_LOG_THROW(false, storm::exceptions::WrongFormatException, "Subformulas have unexpected type."); + } + + std::shared_ptr<storm::logic::Formula const> FormulaParserGrammar::createUnaryBooleanStateOrPathFormula(std::shared_ptr<storm::logic::Formula const> const& subformula, boost::optional<storm::logic::UnaryBooleanOperatorType> const& operatorType) { + if (subformula->isStateFormula()) { + return createUnaryBooleanStateFormula(subformula, operatorType); + } else if (subformula->isPathFormula()) { + return createUnaryBooleanPathFormula(subformula, operatorType); + } + STORM_LOG_THROW(false, storm::exceptions::WrongFormatException, "Subformulas have unexpected type."); + } + + bool FormulaParserGrammar::isValidMultiBoundedPathFormulaOperand(std::shared_ptr<storm::logic::Formula const> const& operand) { + if (operand->isBoundedUntilFormula()) { + if (!operand->asBoundedUntilFormula().isMultiDimensional()) { + return true; } + STORM_LOG_ERROR("Composition of multidimensional bounded until formula must consist of single dimension subformulas. Got '" << *operand << "' instead."); } + return false; + } - if (isMultiDimensionalBoundedUntilFormula) { - std::vector<std::shared_ptr<storm::logic::Formula const>> leftSubformulas, rightSubformulas; - std::vector<boost::optional<storm::logic::TimeBound>> lowerBounds, upperBounds; - std::vector<storm::logic::TimeBoundReference> timeBoundReferences; - for (auto const& subformula : subformulas) { - auto const& f = subformula->asBoundedUntilFormula(); - STORM_LOG_THROW(!f.isMultiDimensional(), storm::exceptions::WrongFormatException, "Composition of multidimensional bounded until formula must consist of single dimension subformulas. Got '" << f << "' instead."); - leftSubformulas.push_back(f.getLeftSubformula().asSharedPointer()); - rightSubformulas.push_back(f.getRightSubformula().asSharedPointer()); - if (f.hasLowerBound()) { - lowerBounds.emplace_back(storm::logic::TimeBound(f.isLowerBoundStrict(), f.getLowerBound())); - } else { - lowerBounds.emplace_back(); - } - if (f.hasUpperBound()) { - upperBounds.emplace_back(storm::logic::TimeBound(f.isUpperBoundStrict(), f.getUpperBound())); - } else { - upperBounds.emplace_back(); - } - timeBoundReferences.push_back(f.getTimeBoundReference()); + std::shared_ptr<storm::logic::Formula const> FormulaParserGrammar::createMultiBoundedPathFormula(std::vector<std::shared_ptr<storm::logic::Formula const>> const& subformulas) { + std::vector<std::shared_ptr<storm::logic::Formula const>> leftSubformulas, rightSubformulas; + std::vector<boost::optional<storm::logic::TimeBound>> lowerBounds, upperBounds; + std::vector<storm::logic::TimeBoundReference> timeBoundReferences; + for (auto const& subformula : subformulas) { + STORM_LOG_THROW(subformula->isBoundedUntilFormula(), storm::exceptions::WrongFormatException, "multi-path formulas require bounded until (or eventually) subformulae. Got '" << *subformula << "' instead."); + auto const& f = subformula->asBoundedUntilFormula(); + STORM_LOG_THROW(!f.isMultiDimensional(), storm::exceptions::WrongFormatException, "Composition of multidimensional bounded until formula must consist of single dimension subformulas. Got '" << f << "' instead."); + leftSubformulas.push_back(f.getLeftSubformula().asSharedPointer()); + rightSubformulas.push_back(f.getRightSubformula().asSharedPointer()); + if (f.hasLowerBound()) { + lowerBounds.emplace_back(storm::logic::TimeBound(f.isLowerBoundStrict(), f.getLowerBound())); + } else { + lowerBounds.emplace_back(); } - return std::shared_ptr<storm::logic::Formula const>(new storm::logic::BoundedUntilFormula(leftSubformulas, rightSubformulas, lowerBounds, upperBounds, timeBoundReferences)); - } else { - return std::shared_ptr<storm::logic::Formula const>(new storm::logic::MultiObjectiveFormula(subformulas)); + if (f.hasUpperBound()) { + upperBounds.emplace_back(storm::logic::TimeBound(f.isUpperBoundStrict(), f.getUpperBound())); + } else { + upperBounds.emplace_back(); + } + timeBoundReferences.push_back(f.getTimeBoundReference()); } + return std::shared_ptr<storm::logic::Formula const>(new storm::logic::BoundedUntilFormula(leftSubformulas, rightSubformulas, lowerBounds, upperBounds, timeBoundReferences)); + } + + std::shared_ptr<storm::logic::Formula const> FormulaParserGrammar::createMultiOperatorFormula(std::vector<std::shared_ptr<storm::logic::Formula const>> const& subformulas) { + return std::shared_ptr<storm::logic::Formula const>(new storm::logic::MultiObjectiveFormula(subformulas)); } storm::expressions::Variable FormulaParserGrammar::createQuantileBoundVariables(boost::optional<storm::solver::OptimizationDirection> const& dir, std::string const& variableName) { @@ -508,35 +607,26 @@ namespace storm { } } - std::pair<storm::logic::ShieldComparison, double> FormulaParserGrammar::createShieldComparisonStruct(storm::logic::ShieldComparison comparisonType, double value) { - return std::make_pair(comparisonType, value); + storm::logic::PlayerCoalition FormulaParserGrammar::createPlayerCoalition(std::vector<boost::variant<std::string, storm::storage::PlayerIndex>> const& playerIds) const { + return storm::logic::PlayerCoalition(playerIds); } - std::shared_ptr<storm::logic::ShieldExpression const> FormulaParserGrammar::createShieldExpression(storm::logic::ShieldingType type, std::string name, boost::optional<std::pair<storm::logic::ShieldComparison, double>> comparisonStruct) { - if(comparisonStruct.is_initialized()) { - STORM_LOG_WARN_COND(type != storm::logic::ShieldingType::Optimal , "Comparison for optimal shield will be ignored."); - return std::shared_ptr<storm::logic::ShieldExpression>(new storm::logic::ShieldExpression(type, name, comparisonStruct.get().first, comparisonStruct.get().second)); - } else { - STORM_LOG_THROW(type == storm::logic::ShieldingType::Optimal , storm::exceptions::WrongFormatException, "Construction of safety shield needs a comparison parameter (lambda or gamma)"); - return std::shared_ptr<storm::logic::ShieldExpression>(new storm::logic::ShieldExpression(type, name)); - } + std::shared_ptr<storm::logic::Formula const> FormulaParserGrammar::createGameFormula(storm::logic::PlayerCoalition const& coalition, std::shared_ptr<storm::logic::Formula const> const& subformula) const { + return std::shared_ptr<storm::logic::Formula const>(new storm::logic::GameFormula(coalition, subformula)); } - storm::jani::Property FormulaParserGrammar::createShieldingProperty(boost::optional<std::string> const& propertyName, std::shared_ptr<storm::logic::Formula const> const& formula, std::shared_ptr<storm::logic::ShieldExpression const> const& shieldExpression) { - ++propertyCount; - if (propertyName) { - return storm::jani::Property(propertyName.get(), formula, this->getUndefinedConstants(formula), shieldExpression); - } else { - return storm::jani::Property(std::to_string(propertyCount), formula, this->getUndefinedConstants(formula), shieldExpression); + bool FormulaParserGrammar::isBooleanReturnType(std::shared_ptr<storm::logic::Formula const> const& formula, bool raiseErrorMessage) { + if (formula->hasQualitativeResult()) { + return true; } + STORM_LOG_ERROR_COND(!raiseErrorMessage, "Formula " << *formula << " does not have a Boolean return type."); + return false; } - storm::logic::PlayerCoalition FormulaParserGrammar::createPlayerCoalition(std::vector<boost::variant<std::string, storm::storage::PlayerIndex>> const& playerIds) const { - return storm::logic::PlayerCoalition(playerIds); + bool FormulaParserGrammar::raiseAmbiguousNonAssociativeOperatorError(std::shared_ptr<storm::logic::Formula const> const& formula, std::string const& op) { + STORM_LOG_ERROR( "Ambiguous use of non-associative operator '" << op << "' in formula '" << *formula << " U ... '"); + return true; } - std::shared_ptr<storm::logic::Formula const> FormulaParserGrammar::createGameFormula(storm::logic::PlayerCoalition const& coalition, std::shared_ptr<storm::logic::Formula const> const& subformula) const { - return std::shared_ptr<storm::logic::Formula const>(new storm::logic::GameFormula(coalition, subformula)); - } } } diff --git a/src/storm-parsers/parser/FormulaParserGrammar.h b/src/storm-parsers/parser/FormulaParserGrammar.h index 35ac56b6b..fca3b3a1c 100644 --- a/src/storm-parsers/parser/FormulaParserGrammar.h +++ b/src/storm-parsers/parser/FormulaParserGrammar.h @@ -10,7 +10,6 @@ #include "storm/storage/jani/Property.h" #include "storm/logic/Formulas.h" #include "storm-parsers/parser/ExpressionParser.h" -#include "storm-parsers/parser/ConstantDataType.h" #include "storm/modelchecker/results/FilterType.h" @@ -53,14 +52,32 @@ namespace storm { ("F", 5) ("G", 6) ("X", 7) - ("multi", 8) - ("quantile", 9); + ("U", 8) + ("C", 9) + ("I", 10) + ("P", 11) + ("R", 12) + ("S", 13); } }; - - // A parser used for recognizing the keywords. + // A parser used for recognizing the standard keywords (that also apply to e.g. PRISM). These shall not coincide with expression variables keywordsStruct keywords_; + struct nonStandardKeywordsStruct : qi::symbols<char, uint_fast64_t> { + nonStandardKeywordsStruct() { + add + ("T", 1) + ("LRA", 2) + ("MP", 3) + ("multi", 4) + ("quantile", 5) + ("HOA", 6); + } + }; + // A parser used for recognizing non-standard Storm-specific keywords. + // For compatibility, we still try to parse expression variables whose identifier is such a keyword and just issue a warning. + nonStandardKeywordsStruct nonStandardKeywords_; + struct relationalOperatorStruct : qi::symbols<char, storm::logic::ComparisonType> { relationalOperatorStruct() { add @@ -74,27 +91,6 @@ namespace storm { // A parser used for recognizing the operators at the "relational" precedence level. relationalOperatorStruct relationalOperator_; - struct binaryBooleanOperatorStruct : qi::symbols<char, storm::logic::BinaryBooleanStateFormula::OperatorType> { - binaryBooleanOperatorStruct() { - add - ("&", storm::logic::BinaryBooleanStateFormula::OperatorType::And) - ("|", storm::logic::BinaryBooleanStateFormula::OperatorType::Or); - } - }; - - // A parser used for recognizing the operators at the "binary" precedence level. - binaryBooleanOperatorStruct binaryBooleanOperator_; - - struct unaryBooleanOperatorStruct : qi::symbols<char, storm::logic::UnaryBooleanStateFormula::OperatorType> { - unaryBooleanOperatorStruct() { - add - ("!", storm::logic::UnaryBooleanStateFormula::OperatorType::Not); - } - }; - - // A parser used for recognizing the operators at the "unary" precedence level. - unaryBooleanOperatorStruct unaryBooleanOperator_; - struct optimalityOperatorStruct : qi::symbols<char, storm::OptimizationDirection> { optimalityOperatorStruct() { add @@ -136,6 +132,24 @@ namespace storm { // A parser used for recognizing the filter type. filterTypeStruct filterType_; + struct operatorKeyword : qi::symbols<char, storm::logic::FormulaContext> { + operatorKeyword() { + add + ("P", storm::logic::FormulaContext::Probability) + ("R", storm::logic::FormulaContext::Reward) + ("T", storm::logic::FormulaContext::Time) + ("LRA", storm::logic::FormulaContext::LongRunAverage) + ("S", storm::logic::FormulaContext::LongRunAverage); + } + }; + operatorKeyword operatorKeyword_; + + enum class FormulaKind { + State, /// PCTL*-like (boolean) state formula + Path, /// PCTL*-like (boolean) path formula (include state formulae) + }; + qi::rule<Iterator, qi::unused_type(FormulaKind), Skipper> isPathFormula; + // The manager used to parse expressions. std::shared_ptr<storm::expressions::ExpressionManager const> constManager; std::shared_ptr<storm::expressions::ExpressionManager> manager; @@ -147,75 +161,87 @@ namespace storm { // they are to be replaced with. qi::symbols<char, storm::expressions::Expression> identifiers_; - qi::rule<Iterator, std::vector<storm::jani::Property>(), Skipper> start; - - qi::rule<Iterator, qi::unused_type(), qi::locals<ConstantDataType>, Skipper> constantDefinition; - qi::rule<Iterator, std::string(), Skipper> identifier; - qi::rule<Iterator, std::string(), Skipper> formulaName; - qi::rule<Iterator, storm::logic::OperatorInformation(), qi::locals<boost::optional<storm::OptimizationDirection>, boost::optional<storm::logic::ComparisonType>, boost::optional<storm::expressions::Expression>>, Skipper> operatorInformation; - qi::rule<Iterator, storm::logic::RewardMeasureType(), Skipper> rewardMeasureType; - qi::rule<Iterator, std::shared_ptr<storm::logic::Formula const>(), Skipper> probabilityOperator; - qi::rule<Iterator, std::shared_ptr<storm::logic::Formula const>(), Skipper> rewardOperator; - qi::rule<Iterator, std::shared_ptr<storm::logic::Formula const>(), Skipper> timeOperator; - qi::rule<Iterator, std::shared_ptr<storm::logic::Formula const>(), Skipper> longRunAverageOperator; + // Rules - qi::rule<Iterator, storm::logic::PlayerCoalition(), qi::locals<std::vector<boost::variant<std::string, storm::storage::PlayerIndex>>>, Skipper> playerCoalition; - - qi::rule<Iterator, storm::jani::Property(), Skipper> filterProperty; - qi::rule<Iterator, std::shared_ptr<storm::logic::Formula const>(), Skipper> simpleFormula; - qi::rule<Iterator, std::shared_ptr<storm::logic::Formula const>(), Skipper> stateFormula; - qi::rule<Iterator, std::shared_ptr<storm::logic::Formula const>(storm::logic::FormulaContext), Skipper> pathFormula; - qi::rule<Iterator, std::shared_ptr<storm::logic::Formula const>(storm::logic::FormulaContext), Skipper> pathFormulaWithoutUntil; - qi::rule<Iterator, std::shared_ptr<storm::logic::Formula const>(), Skipper> simplePathFormula; - qi::rule<Iterator, std::shared_ptr<storm::logic::Formula const>(), Skipper> atomicStateFormula; - qi::rule<Iterator, std::shared_ptr<storm::logic::Formula const>(), Skipper> atomicStateFormulaWithoutExpression; - qi::rule<Iterator, std::shared_ptr<storm::logic::Formula const>(), Skipper> operatorFormula; + // Auxiliary helpers + qi::rule<Iterator, qi::unused_type(std::shared_ptr<storm::logic::Formula const>, std::string), Skipper> noAmbiguousNonAssociativeOperator; + qi::rule<Iterator, std::string(), Skipper> identifier; qi::rule<Iterator, std::string(), Skipper> label; - qi::rule<Iterator, std::string(), Skipper> rewardModelName; + qi::rule<Iterator, std::string(), Skipper> quotedString; - qi::rule<Iterator, std::shared_ptr<storm::logic::Formula const>(), Skipper> andStateFormula; - qi::rule<Iterator, std::shared_ptr<storm::logic::Formula const>(), Skipper> orStateFormula; - qi::rule<Iterator, std::shared_ptr<storm::logic::Formula const>(), Skipper> notStateFormula; + // PCTL-like Operator Formulas + qi::rule<Iterator, storm::logic::OperatorInformation(), qi::locals<boost::optional<storm::OptimizationDirection>>, Skipper> operatorInformation; + qi::rule<Iterator, std::shared_ptr<storm::logic::Formula const>(storm::logic::FormulaContext), Skipper> operatorSubFormula; + qi::rule<Iterator, std::string(storm::logic::FormulaContext), Skipper> rewardModelName; + qi::rule<Iterator, storm::logic::RewardMeasureType(storm::logic::FormulaContext), Skipper> rewardMeasureType; + qi::rule<Iterator, std::shared_ptr<storm::logic::Formula const>(), qi::locals<storm::logic::FormulaContext>, Skipper> operatorFormula; + + // Atomic propositions qi::rule<Iterator, std::shared_ptr<storm::logic::Formula const>(), Skipper> labelFormula; qi::rule<Iterator, std::shared_ptr<storm::logic::Formula const>(), Skipper> expressionFormula; qi::rule<Iterator, std::shared_ptr<storm::logic::Formula const>(), qi::locals<bool>, Skipper> booleanLiteralFormula; + qi::rule<Iterator, std::shared_ptr<storm::logic::Formula const>(), Skipper> atomicPropositionFormula; - qi::rule<Iterator, std::shared_ptr<storm::logic::Formula const>(storm::logic::FormulaContext), Skipper> conditionalFormula; - qi::rule<Iterator, std::shared_ptr<storm::logic::Formula const>(storm::logic::FormulaContext), Skipper> eventuallyFormula; - qi::rule<Iterator, std::shared_ptr<storm::logic::Formula const>(storm::logic::FormulaContext), Skipper> nextFormula; - qi::rule<Iterator, std::shared_ptr<storm::logic::Formula const>(storm::logic::FormulaContext), Skipper> globallyFormula; - qi::rule<Iterator, std::shared_ptr<storm::logic::Formula const>(storm::logic::FormulaContext), Skipper> untilFormula; + // Propositional logic operators + qi::rule<Iterator, std::shared_ptr<storm::logic::Formula const>(FormulaKind, storm::logic::FormulaContext), Skipper> basicPropositionalFormula; + qi::rule<Iterator, std::shared_ptr<storm::logic::Formula const>(FormulaKind, storm::logic::FormulaContext), Skipper> negationPropositionalFormula; + qi::rule<Iterator, std::shared_ptr<storm::logic::Formula const>(FormulaKind, storm::logic::FormulaContext), Skipper> andLevelPropositionalFormula; + qi::rule<Iterator, std::shared_ptr<storm::logic::Formula const>(FormulaKind, storm::logic::FormulaContext), Skipper> orLevelPropositionalFormula; + qi::rule<Iterator, std::shared_ptr<storm::logic::Formula const>(FormulaKind, storm::logic::FormulaContext), Skipper> propositionalFormula; + // Path operators qi::rule<Iterator, std::shared_ptr<storm::logic::TimeBoundReference>, Skipper> timeBoundReference; qi::rule<Iterator, std::tuple<boost::optional<storm::logic::TimeBound>, boost::optional<storm::logic::TimeBound>, std::shared_ptr<storm::logic::TimeBoundReference>>(), qi::locals<bool, bool>, Skipper> timeBound; qi::rule<Iterator, std::vector<std::tuple<boost::optional<storm::logic::TimeBound>, boost::optional<storm::logic::TimeBound>, std::shared_ptr<storm::logic::TimeBoundReference>>>(), qi::locals<bool, bool>, Skipper> timeBounds; + qi::rule<Iterator, std::shared_ptr<storm::logic::Formula const>(storm::logic::FormulaContext), Skipper> eventuallyFormula; + qi::rule<Iterator, std::shared_ptr<storm::logic::Formula const>(storm::logic::FormulaContext), Skipper> nextFormula; + qi::rule<Iterator, std::shared_ptr<storm::logic::Formula const>(storm::logic::FormulaContext), Skipper> globallyFormula; + qi::rule<Iterator, std::shared_ptr<storm::logic::Formula const>(storm::logic::FormulaContext), Skipper> hoaPathFormula; + qi::rule<Iterator, std::shared_ptr<storm::logic::Formula const>(storm::logic::FormulaContext), Skipper> multiBoundedPathFormulaOperand; + qi::rule<Iterator, std::shared_ptr<storm::logic::Formula const>(storm::logic::FormulaContext), Skipper> multiBoundedPathFormula; + qi::rule<Iterator, std::shared_ptr<storm::logic::Formula const>(storm::logic::FormulaContext), Skipper> prefixOperatorPathFormula; + qi::rule<Iterator, std::shared_ptr<storm::logic::Formula const>(storm::logic::FormulaContext), Skipper> basicPathFormula; + qi::rule<Iterator, std::shared_ptr<storm::logic::Formula const>(storm::logic::FormulaContext), Skipper> untilLevelPathFormula; + qi::rule<Iterator, std::shared_ptr<storm::logic::Formula const>(storm::logic::FormulaContext), Skipper> pathFormula; - qi::rule<Iterator, std::shared_ptr<storm::logic::Formula const>(), Skipper> rewardPathFormula; - qi::rule<Iterator, std::shared_ptr<storm::logic::Formula const>(), qi::locals<bool>, Skipper> cumulativeRewardFormula; - qi::rule<Iterator, std::shared_ptr<storm::logic::Formula const>(), Skipper> totalRewardFormula; - qi::rule<Iterator, std::shared_ptr<storm::logic::Formula const>(), Skipper> instantaneousRewardFormula; + // Quantitative path operators (reward) qi::rule<Iterator, std::shared_ptr<storm::logic::Formula const>(), Skipper> longRunAverageRewardFormula; + qi::rule<Iterator, std::shared_ptr<storm::logic::Formula const>(), Skipper> instantaneousRewardFormula; + qi::rule<Iterator, std::shared_ptr<storm::logic::Formula const>(), Skipper> cumulativeRewardFormula; + qi::rule<Iterator, std::shared_ptr<storm::logic::Formula const>(), Skipper> totalRewardFormula; - qi::rule<Iterator, std::shared_ptr<storm::logic::Formula const>(), Skipper> multiFormula; - qi::rule<Iterator, storm::expressions::Variable(), qi::locals<boost::optional<storm::solver::OptimizationDirection>>, Skipper> quantileBoundVariable; - qi::rule<Iterator, std::shared_ptr<storm::logic::Formula const>(), Skipper> quantileFormula; + // Game Formulae + qi::rule<Iterator, storm::logic::PlayerCoalition(), qi::locals<std::vector<boost::variant<std::string, storm::storage::PlayerIndex>>>, Skipper> playerCoalition; qi::rule<Iterator, std::shared_ptr<storm::logic::Formula const>(), Skipper> gameFormula; - qi::rule<Iterator, std::shared_ptr<storm::logic::ShieldExpression const>(), Skipper> shieldExpression; - qi::rule<Iterator, storm::logic::ShieldingType, Skipper> shieldingType; - qi::rule<Iterator, double, Skipper> probability; - qi::rule<Iterator, std::pair<storm::logic::ShieldComparison, double>, qi::locals<storm::logic::ShieldComparison>, Skipper> shieldComparison; + // Multi-objective, quantiles + qi::rule<Iterator, std::shared_ptr<storm::logic::Formula const>(), Skipper> multiOperatorFormula; + qi::rule<Iterator, storm::expressions::Variable(), Skipper> quantileBoundVariable; + qi::rule<Iterator, std::shared_ptr<storm::logic::Formula const>(), Skipper> quantileFormula; + + // General formulae + qi::rule<Iterator, std::shared_ptr<storm::logic::Formula const>(FormulaKind, storm::logic::FormulaContext), Skipper> formula; + qi::rule<Iterator, std::shared_ptr<storm::logic::Formula const>(), Skipper> topLevelFormula; + + // Properties + qi::rule<Iterator, std::string(), Skipper> formulaName; + qi::rule<Iterator, storm::jani::Property(), Skipper> filterProperty; + + // Constant declarations + enum class ConstantDataType { + Bool, Integer, Rational + }; + qi::rule<Iterator, qi::unused_type(), qi::locals<ConstantDataType>, Skipper> constantDefinition; - // Parser that is used to recognize doubles only (as opposed to Spirit's double_ parser). - boost::spirit::qi::real_parser<double, boost::spirit::qi::strict_real_policies<double>> strict_double; + // Start symbol + qi::rule<Iterator, std::vector<storm::jani::Property>(), Skipper> start; + + void addHoaAPMapping(storm::logic::Formula const& hoaFormula, const std::string& ap, std::shared_ptr<storm::logic::Formula const>& expression) const; storm::logic::PlayerCoalition createPlayerCoalition(std::vector<boost::variant<std::string, storm::storage::PlayerIndex>> const& playerIds) const; std::shared_ptr<storm::logic::Formula const> createGameFormula(storm::logic::PlayerCoalition const& coalition, std::shared_ptr<storm::logic::Formula const> const& subformula) const; - std::pair<storm::logic::ShieldComparison, double> createShieldComparisonStruct(storm::logic::ShieldComparison comparisonType, double value); - std::shared_ptr<storm::logic::ShieldExpression const> createShieldExpression(storm::logic::ShieldingType type, std::string name, boost::optional<std::pair<storm::logic::ShieldComparison, double>> comparisonStruct); - bool areConstantDefinitionsAllowed() const; void addConstant(std::string const& name, ConstantDataType type, boost::optional<storm::expressions::Expression> const& expression); void addProperty(std::vector<storm::jani::Property>& properties, boost::optional<std::string> const& name, std::shared_ptr<storm::logic::Formula const> const& formula); @@ -233,25 +259,35 @@ namespace storm { std::shared_ptr<storm::logic::Formula const> createBooleanLiteralFormula(bool literal) const; std::shared_ptr<storm::logic::Formula const> createAtomicLabelFormula(std::string const& label) const; std::shared_ptr<storm::logic::Formula const> createEventuallyFormula(boost::optional<std::vector<std::tuple<boost::optional<storm::logic::TimeBound>, boost::optional<storm::logic::TimeBound>, std::shared_ptr<storm::logic::TimeBoundReference>>>> const& timeBounds, storm::logic::FormulaContext context, std::shared_ptr<storm::logic::Formula const> const& subformula) const; - std::shared_ptr<storm::logic::Formula const> createGloballyFormula(boost::optional<std::vector<std::tuple<boost::optional<storm::logic::TimeBound>, boost::optional<storm::logic::TimeBound>, std::shared_ptr<storm::logic::TimeBoundReference>>>> const& timeBounds, std::shared_ptr<storm::logic::Formula const> const& subformula) const; + std::shared_ptr<storm::logic::Formula const> createGloballyFormula(std::shared_ptr<storm::logic::Formula const> const& subformula) const; std::shared_ptr<storm::logic::Formula const> createNextFormula(std::shared_ptr<storm::logic::Formula const> const& subformula) const; std::shared_ptr<storm::logic::Formula const> createUntilFormula(std::shared_ptr<storm::logic::Formula const> const& leftSubformula, boost::optional<std::vector<std::tuple<boost::optional<storm::logic::TimeBound>, boost::optional<storm::logic::TimeBound>, std::shared_ptr<storm::logic::TimeBoundReference>>>> const& timeBounds, std::shared_ptr<storm::logic::Formula const> const& rightSubformula); - std::shared_ptr<storm::logic::Formula const> createConditionalFormula(std::shared_ptr<storm::logic::Formula const> const& leftSubformula, std::shared_ptr<storm::logic::Formula const> const& rightSubformula, storm::logic::FormulaContext context) const; + std::shared_ptr<storm::logic::Formula const> createHOAPathFormula(const std::string& automataFile) const; + std::shared_ptr<storm::logic::Formula const> createConditionalFormula(std::shared_ptr<storm::logic::Formula const> const& leftSubformula, boost::optional<std::shared_ptr<storm::logic::Formula const>> const& rightSubformula, storm::logic::FormulaContext context) const; storm::logic::OperatorInformation createOperatorInformation(boost::optional<storm::OptimizationDirection> const& optimizationDirection, boost::optional<storm::logic::ComparisonType> const& comparisonType, boost::optional<storm::expressions::Expression> const& threshold) const; + std::shared_ptr<storm::logic::Formula const> createOperatorFormula(storm::logic::FormulaContext const& context, boost::optional<storm::logic::RewardMeasureType> const& rewardMeasureType, boost::optional<std::string> const& rewardModelName, storm::logic::OperatorInformation const& operatorInformation, std::shared_ptr<storm::logic::Formula const> const& subformula); std::shared_ptr<storm::logic::Formula const> createLongRunAverageOperatorFormula(storm::logic::OperatorInformation const& operatorInformation, std::shared_ptr<storm::logic::Formula const> const& subformula) const; std::shared_ptr<storm::logic::Formula const> createRewardOperatorFormula(boost::optional<storm::logic::RewardMeasureType> const& rewardMeasureType, boost::optional<std::string> const& rewardModelName, storm::logic::OperatorInformation const& operatorInformation, std::shared_ptr<storm::logic::Formula const> const& subformula) const; std::shared_ptr<storm::logic::Formula const> createTimeOperatorFormula(boost::optional<storm::logic::RewardMeasureType> const& rewardMeasureType, storm::logic::OperatorInformation const& operatorInformation, std::shared_ptr<storm::logic::Formula const> const& subformula) const; std::shared_ptr<storm::logic::Formula const> createProbabilityOperatorFormula(storm::logic::OperatorInformation const& operatorInformation, std::shared_ptr<storm::logic::Formula const> const& subformula); std::shared_ptr<storm::logic::Formula const> createBinaryBooleanStateFormula(std::shared_ptr<storm::logic::Formula const> const& leftSubformula, std::shared_ptr<storm::logic::Formula const> const& rightSubformula, storm::logic::BinaryBooleanStateFormula::OperatorType operatorType); + std::shared_ptr<storm::logic::Formula const> createBinaryBooleanPathFormula(std::shared_ptr<storm::logic::Formula const> const& leftSubformula, std::shared_ptr<storm::logic::Formula const> const& rightSubformula, storm::logic::BinaryBooleanPathFormula::OperatorType operatorType); + std::shared_ptr<storm::logic::Formula const> createBinaryBooleanStateOrPathFormula(std::shared_ptr<storm::logic::Formula const> const& leftSubformula, std::shared_ptr<storm::logic::Formula const> const& rightSubformula, storm::logic::BinaryBooleanOperatorType operatorType); std::shared_ptr<storm::logic::Formula const> createUnaryBooleanStateFormula(std::shared_ptr<storm::logic::Formula const> const& subformula, boost::optional<storm::logic::UnaryBooleanStateFormula::OperatorType> const& operatorType); - std::shared_ptr<storm::logic::Formula const> createMultiFormula(std::vector<std::shared_ptr<storm::logic::Formula const>> const& subformulas); + std::shared_ptr<storm::logic::Formula const> createUnaryBooleanPathFormula(std::shared_ptr<storm::logic::Formula const> const& subformula, boost::optional<storm::logic::UnaryBooleanPathFormula::OperatorType> const& operatorType); + std::shared_ptr<storm::logic::Formula const> createUnaryBooleanStateOrPathFormula(std::shared_ptr<storm::logic::Formula const> const& subformula, boost::optional<storm::logic::UnaryBooleanOperatorType> const& operatorType); + bool isValidMultiBoundedPathFormulaOperand(std::shared_ptr<storm::logic::Formula const> const& operand); + std::shared_ptr<storm::logic::Formula const> createMultiBoundedPathFormula(std::vector<std::shared_ptr<storm::logic::Formula const>> const& subformulas); + std::shared_ptr<storm::logic::Formula const> createMultiOperatorFormula(std::vector<std::shared_ptr<storm::logic::Formula const>> const& subformulas); storm::expressions::Variable createQuantileBoundVariables(boost::optional<storm::solver::OptimizationDirection> const& dir, std::string const& variableName); std::shared_ptr<storm::logic::Formula const> createQuantileFormula(std::vector<storm::expressions::Variable> const& boundVariables, std::shared_ptr<storm::logic::Formula const> const& subformula); std::set<storm::expressions::Variable> getUndefinedConstants(std::shared_ptr<storm::logic::Formula const> const& formula) const; storm::jani::Property createProperty(boost::optional<std::string> const& propertyName, storm::modelchecker::FilterType const& filterType, std::shared_ptr<storm::logic::Formula const> const& formula, std::shared_ptr<storm::logic::Formula const> const& states); storm::jani::Property createPropertyWithDefaultFilterTypeAndStates(boost::optional<std::string> const& propertyName, std::shared_ptr<storm::logic::Formula const> const& formula); - storm::jani::Property createShieldingProperty(boost::optional<std::string> const& propertyName, std::shared_ptr<storm::logic::Formula const> const& formula, std::shared_ptr<storm::logic::ShieldExpression const> const& shieldingExpression); + + bool isBooleanReturnType(std::shared_ptr<storm::logic::Formula const> const& formula, bool raiseErrorMessage = false); + bool raiseAmbiguousNonAssociativeOperatorError(std::shared_ptr<storm::logic::Formula const> const& formula, std::string const& op); // An error handler function. phoenix::function<SpiritErrorHandler> handler; diff --git a/src/storm-pomdp/analysis/WinningRegion.cpp b/src/storm-pomdp/analysis/WinningRegion.cpp index 7b872a20a..39d89c095 100644 --- a/src/storm-pomdp/analysis/WinningRegion.cpp +++ b/src/storm-pomdp/analysis/WinningRegion.cpp @@ -210,7 +210,7 @@ namespace pomdp { storm::RationalNumber n = 1; while (n < max) { oom += 1; - n *= 2; + n = n * 2; } STORM_LOG_DEBUG("Order of magnitude = " << oom); @@ -390,4 +390,4 @@ namespace pomdp { } } -} \ No newline at end of file +} diff --git a/src/storm-pomdp/generator/NondeterministicBeliefTracker.cpp b/src/storm-pomdp/generator/NondeterministicBeliefTracker.cpp index d3b82647d..1389a59da 100644 --- a/src/storm-pomdp/generator/NondeterministicBeliefTracker.cpp +++ b/src/storm-pomdp/generator/NondeterministicBeliefTracker.cpp @@ -139,7 +139,7 @@ namespace storm { if (lhs.belief.size() != rhs.belief.size()) { return false; } - storm::utility::ConstantsComparator<ValueType> cmp(0.00001, true); + storm::utility::ConstantsComparator<ValueType> cmp(storm::utility::convertNumber<ValueType>(0.00001), true); auto lhsIt = lhs.belief.begin(); auto rhsIt = rhs.belief.begin(); while(lhsIt != lhs.belief.end()) { diff --git a/src/storm-pomdp/storage/BeliefManager.cpp b/src/storm-pomdp/storage/BeliefManager.cpp index 82ddabaaa..e998e4c70 100644 --- a/src/storm-pomdp/storage/BeliefManager.cpp +++ b/src/storm-pomdp/storage/BeliefManager.cpp @@ -14,7 +14,7 @@ namespace storm { } template<typename PomdpType, typename BeliefValueType, typename StateType> - BeliefManager<PomdpType, BeliefValueType, StateType>::FreudenthalDiff::FreudenthalDiff(StateType const &dimension, BeliefValueType &&diff) : dimension(dimension), + BeliefManager<PomdpType, BeliefValueType, StateType>::FreudenthalDiff::FreudenthalDiff(StateType const &dimension, BeliefValueType diff) : dimension(dimension), diff(std::move(diff)) { // Intentionally left empty } @@ -514,4 +514,4 @@ namespace storm { template class BeliefManager<storm::models::sparse::Pomdp<storm::RationalNumber>>; } -} \ No newline at end of file +} diff --git a/src/storm-pomdp/storage/BeliefManager.h b/src/storm-pomdp/storage/BeliefManager.h index 087114a55..2e7d29ff7 100644 --- a/src/storm-pomdp/storage/BeliefManager.h +++ b/src/storm-pomdp/storage/BeliefManager.h @@ -76,7 +76,7 @@ namespace storm { }; struct FreudenthalDiff { - FreudenthalDiff(StateType const &dimension, BeliefValueType &&diff); + FreudenthalDiff(StateType const &dimension, BeliefValueType diff); StateType dimension; // i BeliefValueType diff; // d[i] @@ -123,4 +123,4 @@ namespace storm { }; } -} \ No newline at end of file +} diff --git a/src/storm/api/export.h b/src/storm/api/export.h index b1dbb6d21..6f4b82f77 100644 --- a/src/storm/api/export.h +++ b/src/storm/api/export.h @@ -56,9 +56,9 @@ namespace storm { storm::utility::openFile(filename, stream); std::string jsonFileExtension = ".json"; if (filename.size() > 4 && std::equal(jsonFileExtension.rbegin(), jsonFileExtension.rend(), filename.rbegin())) { - scheduler.printJsonToStream(stream, model); + scheduler.printJsonToStream(stream, model, false, true); } else { - scheduler.printToStream(stream, model); + scheduler.printToStream(stream, model, false, true); } storm::utility::closeFile(stream); } diff --git a/src/storm/automata/APSet.cpp b/src/storm/automata/APSet.cpp new file mode 100644 index 000000000..6c136effd --- /dev/null +++ b/src/storm/automata/APSet.cpp @@ -0,0 +1,64 @@ + +#include "storm/automata/APSet.h" +#include "storm/exceptions/UnexpectedException.h" +#include "storm/utility/macros.h" + +#include <string> +#include <exception> + +namespace storm { + namespace automata { + + APSet::APSet() { + // intentionally left blank + } + + unsigned int APSet::size() const { + return index_to_ap.size(); + } + + std::size_t APSet::alphabetSize() const { + return 1L << size(); + } + + void APSet::add(const std::string& ap) { + STORM_LOG_THROW(size() < MAX_APS, storm::exceptions::UnexpectedException, "Set of atomic proposition size is limited to " << std::to_string(MAX_APS)); + + unsigned int index = size(); + bool fresh = ap_to_index.insert(std::make_pair(ap, index)).second; + STORM_LOG_THROW(fresh, storm::exceptions::UnexpectedException,"Duplicate atomic proposition '" << ap << "' in APSet"); + + index_to_ap.push_back(ap); + } + + unsigned int APSet::getIndex(const std::string& ap) const { + // throws out_of_range if ap is not in the set + return ap_to_index.at(ap); + } + + const std::string& APSet::getAP(unsigned int index) const { + // throws out_of_range if index is out of range + return index_to_ap.at(index); + } + + const std::vector<std::string>& APSet::getAPs() const { + return index_to_ap; + } + + + bool APSet::contains(const std::string& ap) const { + return ap_to_index.find(ap) != ap_to_index.end(); + } + + APSet::alphabet_element APSet::elementAllFalse() const { + return 0; + } + + APSet::alphabet_element APSet::elementAddAP(alphabet_element element, unsigned int ap) const { + STORM_LOG_THROW(ap < size(), storm::exceptions::UnexpectedException, "AP out of range"); + + return element | (1ul << ap); + } + + } +} diff --git a/src/storm/automata/APSet.h b/src/storm/automata/APSet.h new file mode 100644 index 000000000..b56733685 --- /dev/null +++ b/src/storm/automata/APSet.h @@ -0,0 +1,33 @@ +#pragma once + +#include <vector> +#include <map> +#include <string> + +namespace storm { + namespace automata { + class APSet { + public: + // TODO: uint32 + typedef std::size_t alphabet_element; + + APSet(); + + unsigned int size() const; + std::size_t alphabetSize() const; + void add(const std::string& ap); + unsigned int getIndex(const std::string& ap) const; + bool contains(const std::string& ap) const; + const std::string& getAP(unsigned int index) const; + const std::vector<std::string>& getAPs() const; + + alphabet_element elementAllFalse() const; + alphabet_element elementAddAP(alphabet_element element, unsigned int ap) const; + + const unsigned int MAX_APS = 32; + private: + std::map<std::string, unsigned int> ap_to_index; + std::vector<std::string> index_to_ap; + }; + } +} diff --git a/src/storm/automata/AcceptanceCondition.cpp b/src/storm/automata/AcceptanceCondition.cpp new file mode 100644 index 000000000..8360ec24a --- /dev/null +++ b/src/storm/automata/AcceptanceCondition.cpp @@ -0,0 +1,145 @@ +#include "AcceptanceCondition.h" + +#include "storm/utility/macros.h" +#include "storm/exceptions/InvalidOperationException.h" + +namespace storm { +namespace automata { + +AcceptanceCondition::AcceptanceCondition(std::size_t numberOfStates, unsigned int numberOfAcceptanceSets, acceptance_expr::ptr acceptance) + : numberOfAcceptanceSets(numberOfAcceptanceSets), acceptance(acceptance) { + + // initialize acceptance sets + for (unsigned int i = 0; i < numberOfAcceptanceSets; i++) { + acceptanceSets.push_back(storm::storage::BitVector(numberOfStates)); + } +} + +unsigned int AcceptanceCondition::getNumberOfAcceptanceSets() const { + return numberOfAcceptanceSets; +} + + +storm::storage::BitVector& AcceptanceCondition::getAcceptanceSet(unsigned int index) { + return acceptanceSets.at(index); +} + +const storm::storage::BitVector& AcceptanceCondition::getAcceptanceSet(unsigned int index) const { + return acceptanceSets.at(index); +} + +AcceptanceCondition::acceptance_expr::ptr AcceptanceCondition::getAcceptanceExpression() const { + return acceptance; +} + + +bool AcceptanceCondition::isAccepting(const storm::storage::StateBlock& scc) const { + return isAccepting(scc, acceptance); +} + +bool AcceptanceCondition::isAccepting(const storm::storage::StateBlock& scc, acceptance_expr::ptr expr) const { + switch (expr->getType()) { + case acceptance_expr::EXP_AND: + return isAccepting(scc, expr->getLeft()) && isAccepting(scc, expr->getRight()); + case acceptance_expr::EXP_OR: + return isAccepting(scc, expr->getLeft()) || isAccepting(scc, expr->getRight()); + case acceptance_expr::EXP_NOT: + return !isAccepting(scc, expr->getLeft()); + case acceptance_expr::EXP_TRUE: + return true; + case acceptance_expr::EXP_FALSE: + return false; + case acceptance_expr::EXP_ATOM: { + const cpphoafparser::AtomAcceptance& atom = expr->getAtom(); + const storm::storage::BitVector& acceptanceSet = acceptanceSets.at(atom.getAcceptanceSet()); + bool negated = atom.isNegated(); + bool rv; + switch (atom.getType()) { + case cpphoafparser::AtomAcceptance::TEMPORAL_INF: + rv = false; + for (auto& state : scc) { + if (acceptanceSet.get(state)) { + rv = true; + break; + } + } + break; + case cpphoafparser::AtomAcceptance::TEMPORAL_FIN: + rv = true; + for (auto& state : scc) { + if (acceptanceSet.get(state)) { + rv = false; + break; + } + } + break; + } + + return (negated ? !rv : rv); + } + } + + throw std::runtime_error("Missing case statement"); +} + +std::vector<std::vector<AcceptanceCondition::acceptance_expr::ptr>> AcceptanceCondition::extractFromDNF() const { + std::vector<std::vector<AcceptanceCondition::acceptance_expr::ptr>> dnf; + + extractFromDNFRecursion(getAcceptanceExpression(), dnf, true); + + return dnf; +} + + +void AcceptanceCondition::extractFromDNFRecursion(AcceptanceCondition::acceptance_expr::ptr e, std::vector<std::vector<acceptance_expr::ptr>>& dnf, bool topLevel) const { + if (topLevel) { + if (e->isOR()) { + if (e->getLeft()->isOR()) { + extractFromDNFRecursion(e->getLeft(), dnf, true); + } else { + dnf.emplace_back(); + extractFromDNFRecursion(e->getLeft(), dnf, false); + } + + if (e->getRight()->isOR()) { + extractFromDNFRecursion(e->getRight(), dnf, true); + } else { + dnf.emplace_back(); + extractFromDNFRecursion(e->getRight(), dnf, false); + } + } else { + dnf.emplace_back(); + extractFromDNFRecursion(e, dnf, false); + } + } else { + if (e->isOR() || e->isNOT()) { + STORM_LOG_THROW(false, storm::exceptions::InvalidOperationException, "Acceptance condition is not in DNF"); + } else if (e->isAND()) { + extractFromDNFRecursion(e->getLeft(), dnf, false); + extractFromDNFRecursion(e->getRight(), dnf, false); + } else { + dnf.back().push_back(e); + } + } +} + + +AcceptanceCondition::ptr AcceptanceCondition::lift(std::size_t productNumberOfStates, std::function<std::size_t (std::size_t)> mapping) const { + AcceptanceCondition::ptr lifted(new AcceptanceCondition(productNumberOfStates, numberOfAcceptanceSets, acceptance)); + for (unsigned int i = 0; i < numberOfAcceptanceSets; i++) { + const storm::storage::BitVector& set = getAcceptanceSet(i); + storm::storage::BitVector& liftedSet = lifted->getAcceptanceSet(i); + + for (std::size_t prodState = 0; prodState < productNumberOfStates; prodState++) { + if (set.get(mapping(prodState))) { + liftedSet.set(prodState); + } + } + } + + return lifted; +} + + +} +} diff --git a/src/storm/automata/AcceptanceCondition.h b/src/storm/automata/AcceptanceCondition.h new file mode 100644 index 000000000..a70a96e10 --- /dev/null +++ b/src/storm/automata/AcceptanceCondition.h @@ -0,0 +1,38 @@ +#pragma once + +#include <functional> +#include <vector> +#include <memory> +#include "storm/storage/BitVector.h" +#include "storm/storage/StateBlock.h" +#include "cpphoafparser/consumer/hoa_consumer.hh" + +namespace storm { + namespace automata { + class AcceptanceCondition { + public: + typedef std::shared_ptr<AcceptanceCondition> ptr; + typedef cpphoafparser::HOAConsumer::acceptance_expr acceptance_expr; + + AcceptanceCondition(std::size_t numberOfStates, unsigned int numberOfAcceptanceSets, acceptance_expr::ptr acceptance); + bool isAccepting(const storm::storage::StateBlock& scc) const ; + + unsigned int getNumberOfAcceptanceSets() const; + storm::storage::BitVector& getAcceptanceSet(unsigned int index); + const storm::storage::BitVector& getAcceptanceSet(unsigned int index) const; + + acceptance_expr::ptr getAcceptanceExpression() const; + + AcceptanceCondition::ptr lift(std::size_t productNumberOfStates, std::function<std::size_t (std::size_t)> mapping) const; + + std::vector<std::vector<acceptance_expr::ptr>> extractFromDNF() const; + private: + bool isAccepting(const storm::storage::StateBlock& scc, acceptance_expr::ptr expr) const; + void extractFromDNFRecursion(acceptance_expr::ptr e, std::vector<std::vector<acceptance_expr::ptr>>& dnf, bool topLevel) const; + + unsigned int numberOfAcceptanceSets; + acceptance_expr::ptr acceptance; + std::vector<storm::storage::BitVector> acceptanceSets; + }; + } +} diff --git a/src/storm/automata/DeterministicAutomaton.cpp b/src/storm/automata/DeterministicAutomaton.cpp new file mode 100644 index 000000000..c19f55dbe --- /dev/null +++ b/src/storm/automata/DeterministicAutomaton.cpp @@ -0,0 +1,115 @@ +#include "storm/automata/DeterministicAutomaton.h" + +#include "cpphoafparser/parser/hoa_parser.hh" +#include "cpphoafparser/parser/hoa_parser_helper.hh" +#include "cpphoafparser/consumer/hoa_intermediate_check_validity.hh" + +#include "storm/automata/AcceptanceCondition.h" +#include "storm/automata/HOAConsumerDA.h" +#include "storm/utility/macros.h" + +#include "storm/exceptions/FileIoException.h" + +namespace storm { + namespace automata { + DeterministicAutomaton::DeterministicAutomaton(APSet apSet, std::size_t numberOfStates, std::size_t initialState, AcceptanceCondition::ptr acceptance) + : apSet(apSet), numberOfStates(numberOfStates), initialState(initialState), acceptance(acceptance) { + // TODO: this could overflow, add check? + edgesPerState = apSet.alphabetSize(); + numberOfEdges = numberOfStates * edgesPerState; + successors.resize(numberOfEdges); + } + + std::size_t DeterministicAutomaton::getInitialState() const { + return initialState; + } + + const APSet& DeterministicAutomaton::getAPSet() const { + return apSet; + } + + std::size_t DeterministicAutomaton::getSuccessor(std::size_t from, APSet::alphabet_element label) const { + std::size_t index = from * edgesPerState + label; + return successors.at(index); + } + + void DeterministicAutomaton::setSuccessor(std::size_t from, APSet::alphabet_element label, std::size_t successor) { + std::size_t index = from * edgesPerState + label; + successors.at(index) = successor; + } + + std::size_t DeterministicAutomaton::getNumberOfStates() const { + return numberOfStates; + } + + std::size_t DeterministicAutomaton::getNumberOfEdgesPerState() const { + return edgesPerState; + } + + AcceptanceCondition::ptr DeterministicAutomaton::getAcceptance() const { + return acceptance; + } + + + void DeterministicAutomaton::printHOA(std::ostream& out) const { + out << "HOA: v1\n"; + + out << "States: " << numberOfStates << "\n"; + + out << "Start: " << initialState << "\n"; + + out << "AP: " << apSet.size(); + for (unsigned int i = 0; i < apSet.size(); i++) { + out << " " << cpphoafparser::HOAParserHelper::quote(apSet.getAP(i)); + } + out << "\n"; + + out << "Acceptance: " << acceptance->getNumberOfAcceptanceSets() << " " << *acceptance->getAcceptanceExpression() << "\n"; + + out << "--BODY--" << "\n"; + + for (std::size_t s = 0; s < getNumberOfStates(); s++) { + out << "State: " << s; + out << " {"; + bool first = true; + for (unsigned int i = 0; i < acceptance->getNumberOfAcceptanceSets(); i++) { + if (acceptance->getAcceptanceSet(i).get(s)) { + if (!first) + out << " "; + first = false; + out << i; + } + } + out << "}\n"; + for (std::size_t label = 0; label < getNumberOfEdgesPerState(); label++) { + out << getSuccessor(s, label) << "\n"; + } + } + } + + + DeterministicAutomaton::ptr DeterministicAutomaton::parse(std::istream& in) { + HOAConsumerDA::ptr consumer(new HOAConsumerDA()); + cpphoafparser::HOAIntermediateCheckValidity::ptr validator(new cpphoafparser::HOAIntermediateCheckValidity(consumer)); + cpphoafparser::HOAParser::parse(in, validator); + + return consumer->getDA(); + } + + DeterministicAutomaton::ptr DeterministicAutomaton::parseFromFile(const std::string& filename) { + std::ifstream in(filename); + STORM_LOG_THROW(in.good(), storm::exceptions::FileIoException, "Can not open '" << filename << "' for reading."); + auto da = parse(in); + + STORM_LOG_INFO("Deterministic automaton from HOA file '" << filename << "' has " + << da->getNumberOfStates() << " states, " + << da->getAPSet().size() << " atomic propositions and " + << *da->getAcceptance()->getAcceptanceExpression() << " as acceptance condition."); + return da; + } + + } +} + + + diff --git a/src/storm/automata/DeterministicAutomaton.h b/src/storm/automata/DeterministicAutomaton.h new file mode 100644 index 000000000..940ae77de --- /dev/null +++ b/src/storm/automata/DeterministicAutomaton.h @@ -0,0 +1,46 @@ +#pragma once + +#include <iostream> +#include <memory> +#include "storm/automata/APSet.h" + + +namespace storm { + namespace automata { + // fwd + class AcceptanceCondition; + + class DeterministicAutomaton { + public: + typedef std::shared_ptr<DeterministicAutomaton> ptr; + + DeterministicAutomaton(APSet apSet, std::size_t numberOfStates, std::size_t initialState, std::shared_ptr<AcceptanceCondition> acceptance); + + const APSet& getAPSet() const; + + std::size_t getInitialState() const; + + std::size_t getSuccessor(std::size_t from, APSet::alphabet_element label) const; + void setSuccessor(std::size_t from, APSet::alphabet_element label, std::size_t successor); + + std::size_t getNumberOfStates() const; + std::size_t getNumberOfEdgesPerState() const; + + std::shared_ptr<AcceptanceCondition> getAcceptance() const; + + void printHOA(std::ostream& out) const; + + static DeterministicAutomaton::ptr parse(std::istream& in); + static DeterministicAutomaton::ptr parseFromFile(const std::string& filename); + + private: + APSet apSet; + std::size_t numberOfStates; + std::size_t initialState; + std::size_t numberOfEdges; + std::size_t edgesPerState; + std::shared_ptr<AcceptanceCondition> acceptance; + std::vector<std::size_t> successors; + }; + } +} diff --git a/src/storm/automata/HOAConsumerDA.h b/src/storm/automata/HOAConsumerDA.h new file mode 100644 index 000000000..4a2215a8c --- /dev/null +++ b/src/storm/automata/HOAConsumerDA.h @@ -0,0 +1,237 @@ +#pragma once + +#include "storm/automata/APSet.h" +#include "storm/automata/DeterministicAutomaton.h" +#include "storm/automata/HOAConsumerDAHeader.h" +#include "storm/exceptions/OutOfRangeException.h" +#include "storm/exceptions/InvalidOperationException.h" +#include "storm/storage/BitVector.h" +#include "storm/storage/SparseMatrix.h" +#include "storm/storage/expressions/ExpressionManager.h" +#include "storm/solver/SmtSolver.h" +#include "storm/utility/solver.h" + +#include "cpphoafparser/consumer/hoa_consumer.hh" +#include "cpphoafparser/util/implicit_edge_helper.hh" + +#include <boost/optional.hpp> +#include <exception> + +namespace storm { +namespace automata { + +class HOAConsumerDA : public HOAConsumerDAHeader { +private: + AcceptanceCondition::ptr acceptance; + + DeterministicAutomaton::ptr da; + cpphoafparser::ImplicitEdgeHelper *helper = nullptr; + + std::shared_ptr<storm::expressions::ExpressionManager> expressionManager; + std::vector<storm::expressions::Variable> apVariables; + std::unique_ptr<storm::solver::SmtSolver> solver; + + storm::storage::BitVector seenEdges; + +public: + typedef std::shared_ptr<HOAConsumerDA> ptr; + + HOAConsumerDA() : seenEdges(0) { + expressionManager.reset(new storm::expressions::ExpressionManager()); + storm::utility::solver::SmtSolverFactory factory; + solver = factory.create(*expressionManager); + } + + ~HOAConsumerDA() { + delete helper; + } + + DeterministicAutomaton::ptr getDA() { + return da; + } + + /** + * Called by the parser to notify that the BODY of the automaton has started [mandatory, once]. + */ + virtual void notifyBodyStart() { + if (!header.numberOfStates) { + throw std::runtime_error("Parsing deterministic HOA automaton: Missing number-of-states header"); + } + + acceptance = header.getAcceptanceCondition(); + da.reset(new DeterministicAutomaton(header.apSet, *header.numberOfStates, *header.startState, acceptance)); + + helper = new cpphoafparser::ImplicitEdgeHelper(header.apSet.size()); + + seenEdges.resize(*header.numberOfStates * helper->getEdgesPerState()); + + for (const std::string& ap : header.apSet.getAPs()) { + apVariables.push_back(expressionManager->declareBooleanVariable(ap)); + } + } + + /** + * Called by the parser for each "State: ..." item [multiple]. + * @param id the identifier for this state + * @param info an optional string providing additional information about the state (empty pointer if not provided) + * @param labelExpr an optional boolean expression over labels (state-labeled) (empty pointer if not provided) + * @param accSignature an optional list of acceptance set indizes (state-labeled acceptance) (empty pointer if not provided) + */ + virtual void addState(unsigned int id, std::shared_ptr<std::string> info, label_expr::ptr labelExpr, std::shared_ptr<int_list> accSignature) { + if (accSignature) { + for (unsigned int accSet : *accSignature) { + acceptance->getAcceptanceSet(accSet).set(id); + } + } + + if (labelExpr) { + throw std::runtime_error("Parsing deterministic HOA automaton: State-labeled automata not supported"); + } + + helper->startOfState(id); + } + + /** + * Called by the parser for each implicit edge definition [multiple], i.e., + * where the edge label is deduced from the index of the edge. + * + * If the edges are provided in implicit form, after every `addState()` there should be 2^|AP| calls to + * `addEdgeImplicit`. The corresponding boolean expression over labels / BitSet + * can be obtained by calling BooleanExpression.fromImplicit(i-1) for the i-th call of this function per state. + * + * @param stateId the index of the 'from' state + * @param conjSuccessors a list of successor state indizes, interpreted as a conjunction + * @param accSignature an optional list of acceptance set indizes (transition-labeled acceptance) (empty pointer if not provided) + */ + virtual void addEdgeImplicit(unsigned int stateId, const int_list& conjSuccessors, std::shared_ptr<int_list> accSignature) { + std::size_t edgeIndex = helper->nextImplicitEdge(); + + if (conjSuccessors.size() != 1) { + throw std::runtime_error("Parsing deterministic HOA automaton: Does not support alternation (conjunction of successor states)"); + } + + if (accSignature) { + throw std::runtime_error("Parsing deterministic HOA automaton: Does not support transition-based acceptance"); + } + + da->setSuccessor(stateId, edgeIndex, conjSuccessors.at(0)); + markEdgeAsSeen(stateId, edgeIndex); + } + + /** + * Called by the parser for each explicit edge definition [optional, multiple], i.e., + * where the label is either specified for the edge or as a state-label. + * <br/> + * @param stateId the index of the 'from' state + * @param labelExpr a boolean expression over labels (empty pointer if none provided, only in case of state-labeled states) + * @param conjSuccessors a list of successors state indizes, interpreted as a conjunction + * @param accSignature an optional list of acceptance set indizes (transition-labeled acceptance) (empty pointer if none provided) + */ + virtual void addEdgeWithLabel(unsigned int stateId, label_expr::ptr labelExpr, const int_list& conjSuccessors, std::shared_ptr<int_list> accSignature) { + if (conjSuccessors.size() != 1) { + throw std::runtime_error("Parsing deterministic HOA automaton: Does not support alternation (conjunction of successor states)"); + } + + if (accSignature) { + throw std::runtime_error("Parsing deterministic HOA automaton: Does not support transition-based acceptance"); + } + + std::size_t successor = conjSuccessors.at(0); + + solver->reset(); + solver->add(labelToStormExpression(labelExpr)); + + solver->allSat(apVariables, + [this, stateId, successor] (storm::expressions::SimpleValuation& valuation) { + // construct edge index from valuation + APSet::alphabet_element edgeIndex = header.apSet.elementAllFalse(); + for (std::size_t i = 0; i < apVariables.size(); i++) { + if (valuation.getBooleanValue(apVariables[i])) { + edgeIndex = header.apSet.elementAddAP(edgeIndex, i); + } + } + + // require: edge already exists -> same successor + STORM_LOG_THROW(!alreadyHaveEdge(stateId, edgeIndex) || da->getSuccessor(stateId, edgeIndex) == successor, + storm::exceptions::InvalidOperationException, "HOA automaton: multiple definitions of successor for state " << stateId << " and edge " << edgeIndex); + + // std::cout << stateId << " -(" << edgeIndex << ")-> " << successor << std::endl; + da->setSuccessor(stateId, edgeIndex, successor); + markEdgeAsSeen(stateId, edgeIndex); + + // continue with next valuation + return true; + }); + } + + /** + * Called by the parser to notify the consumer that the definition for state `stateId` + * has ended [multiple]. + */ + virtual void notifyEndOfState(unsigned int stateId) { + helper->endOfState(); + } + + /** + * Called by the parser to notify the consumer that the automata definition has ended [mandatory, once]. + */ + virtual void notifyEnd() { + // require that we have seen all edges, i.e., that the automaton is complete + STORM_LOG_THROW(seenEdges.full(), + storm::exceptions::InvalidOperationException, "HOA automaton has mismatch in number of edges, not complete?"); + } + + /** + * Called by the parser to notify the consumer that an "ABORT" message has been encountered + * (at any time, indicating error, the automaton should be discarded). + */ + virtual void notifyAbort() { + throw std::runtime_error("Parsing deterministic automaton: Automaton is incomplete (abort)"); + } + + + /** + * Is called whenever a condition is encountered that merits a (non-fatal) warning. + * The consumer is free to handle this situation as it wishes. + */ + virtual void notifyWarning(const std::string& warning) { + // IGNORE + (void)warning; + } + +private: + storm::expressions::Expression labelToStormExpression(label_expr::ptr labelExpr) { + switch (labelExpr->getType()) { + case label_expr::EXP_AND: + return labelToStormExpression(labelExpr->getLeft()) && labelToStormExpression(labelExpr->getRight()); + case label_expr::EXP_OR: + return labelToStormExpression(labelExpr->getLeft()) || labelToStormExpression(labelExpr->getRight()); + case label_expr::EXP_NOT: + return !labelToStormExpression(labelExpr->getLeft()); + case label_expr::EXP_TRUE: + return expressionManager->boolean(true); + case label_expr::EXP_FALSE: + return expressionManager->boolean(false); + case label_expr::EXP_ATOM: { + unsigned int apIndex = labelExpr->getAtom().getAPIndex(); + STORM_LOG_THROW(apIndex < apVariables.size(), + storm::exceptions::OutOfRangeException, "HOA automaton refers to non-existing atomic proposition"); + return apVariables.at(apIndex).getExpression(); + } + } + throw std::runtime_error("Unknown label expression operator"); + } + + bool alreadyHaveEdge(std::size_t stateId, std::size_t edgeIndex) { + return seenEdges.get(stateId * helper->getEdgesPerState() + edgeIndex); + } + + void markEdgeAsSeen(std::size_t stateId, std::size_t edgeIndex) { + seenEdges.set(stateId * helper->getEdgesPerState() + edgeIndex); + } + +}; + +} +} + diff --git a/src/storm/automata/HOAConsumerDAHeader.h b/src/storm/automata/HOAConsumerDAHeader.h new file mode 100644 index 000000000..c206ef8e3 --- /dev/null +++ b/src/storm/automata/HOAConsumerDAHeader.h @@ -0,0 +1,217 @@ +#pragma once + +#include "storm/automata/APSet.h" +#include "storm/automata/DeterministicAutomaton.h" +#include "storm/automata/HOAHeader.h" +#include "storm/storage/BitVector.h" +#include "storm/storage/SparseMatrix.h" +#include "cpphoafparser/consumer/hoa_consumer.hh" +#include "cpphoafparser/util/implicit_edge_helper.hh" + +#include <boost/optional.hpp> +#include <exception> + +namespace storm { +namespace automata { + +class HOAConsumerDAHeader : public cpphoafparser::HOAConsumer { +protected: + HOAHeader header; + +public: + typedef std::shared_ptr<HOAConsumerDAHeader> ptr; + + struct header_parsing_done : public std::exception {}; + + HOAHeader& getHeader() { + return header; + } + + virtual bool parserResolvesAliases() { + return true; + } + + /** Called by the parser for the "HOA: version" item [mandatory, once]. */ + virtual void notifyHeaderStart(const std::string& /*version*/) { + // TODO: Check version + } + + /** Called by the parser for the "States: int(numberOfStates)" item [optional, once]. */ + virtual void setNumberOfStates(unsigned int numberOfStates) { + header.numberOfStates = numberOfStates; + } + + /** + * Called by the parser for each "Start: state-conj" item [optional, multiple]. + * @param stateConjunction a list of state indizes, interpreted as a conjunction + **/ + virtual void addStartStates(const int_list& stateConjunction) { + if (header.startState) { + throw std::runtime_error("Parsing deterministic HOA automaton: Nondeterministic choice of start states not supported"); + } + if (stateConjunction.size() != 1) { + throw std::runtime_error("Parsing deterministic HOA automaton: Conjunctive choice of start states not supported"); + } + header.startState = stateConjunction.at(0); + } + + /** + * Called by the parser for the "AP: ap-def" item [optional, once]. + * @param aps the list of atomic propositions + */ + virtual void setAPs(const std::vector<std::string>& aps) { + for (const std::string& ap : aps) { + header.apSet.add(ap); + } + } + + /** + * Called by the parser for the "Acceptance: acceptance-def" item [mandatory, once]. + * @param numberOfSets the number of acceptance sets used to tag state / transition acceptance + * @param accExpr a boolean expression over acceptance atoms + **/ + virtual void setAcceptanceCondition(unsigned int numberOfSets, acceptance_expr::ptr accExpr) { + header.numberOfAcceptanceSets = numberOfSets; + header.acceptance_expression = accExpr; + } + + /** + * Called by the parser for each "acc-name: ..." item [optional, multiple]. + * @param name the provided name + * @param extraInfo the additional information for this item + * */ + virtual void provideAcceptanceName(const std::string& name, const std::vector<cpphoafparser::IntOrString>& extraInfo) { + header.accName = name; + header.accNameExtraInfo = extraInfo; + } + + /** + * Called by the parser for each "Alias: alias-def" item [optional, multiple]. + * Will be called no matter the return value of `parserResolvesAliases()`. + * + * @param name the alias name (without @) + * @param labelExpr a boolean expression over labels + **/ + virtual void addAlias(const std::string& name, label_expr::ptr labelExpr) { + // IGNORE + (void)name; + (void)labelExpr; + } + + /** + * Called by the parser for the "name: ..." item [optional, once]. + **/ + virtual void setName(const std::string& /*name*/) { + // IGNORE + } + + /** + * Called by the parser for the "tool: ..." item [optional, once]. + * @param name the tool name + * @param version the tool version (option, empty pointer if not provided) + **/ + virtual void setTool(const std::string& /*name*/, std::shared_ptr<std::string> /*version*/) { + // IGNORE + } + + /** + * Called by the parser for the "properties: ..." item [optional, multiple]. + * @param properties a list of properties + */ + virtual void addProperties(const std::vector<std::string>& /*properties*/) { + // TODO: check supported + } + + /** + * Called by the parser for each unknown header item [optional, multiple]. + * @param name the name of the header (without ':') + * @param content a list of extra information provided by the header + */ + virtual void addMiscHeader(const std::string& /*name*/, const std::vector<cpphoafparser::IntOrString>& /*content*/) { + // TODO: Check semantic headers + } + + /** + * Called by the parser to notify that the BODY of the automaton has started [mandatory, once]. + */ + virtual void notifyBodyStart() { + throw header_parsing_done(); + } + + /** + * Called by the parser for each "State: ..." item [multiple]. + * @param id the identifier for this state + * @param info an optional string providing additional information about the state (empty pointer if not provided) + * @param labelExpr an optional boolean expression over labels (state-labeled) (empty pointer if not provided) + * @param accSignature an optional list of acceptance set indizes (state-labeled acceptance) (empty pointer if not provided) + */ + virtual void addState(unsigned int /*id*/, std::shared_ptr<std::string> /*info*/, label_expr::ptr /*labelExpr*/, std::shared_ptr<int_list> /*accSignature*/) { + // IGNORE + } + + /** + * Called by the parser for each implicit edge definition [multiple], i.e., + * where the edge label is deduced from the index of the edge. + * + * If the edges are provided in implicit form, after every `addState()` there should be 2^|AP| calls to + * `addEdgeImplicit`. The corresponding boolean expression over labels / BitSet + * can be obtained by calling BooleanExpression.fromImplicit(i-1) for the i-th call of this function per state. + * + * @param stateId the index of the 'from' state + * @param conjSuccessors a list of successor state indizes, interpreted as a conjunction + * @param accSignature an optional list of acceptance set indizes (transition-labeled acceptance) (empty pointer if not provided) + */ + virtual void addEdgeImplicit(unsigned int /*stateId*/, const int_list& /*conjSuccessors*/, std::shared_ptr<int_list> /*accSignature*/) { + // IGNORE + } + + /** + * Called by the parser for each explicit edge definition [optional, multiple], i.e., + * where the label is either specified for the edge or as a state-label. + * <br/> + * @param stateId the index of the 'from' state + * @param labelExpr a boolean expression over labels (empty pointer if none provided, only in case of state-labeled states) + * @param conjSuccessors a list of successors state indizes, interpreted as a conjunction + * @param accSignature an optional list of acceptance set indizes (transition-labeled acceptance) (empty pointer if none provided) + */ + virtual void addEdgeWithLabel(unsigned int /*stateId*/, label_expr::ptr /*labelExpr*/, const int_list& /*conjSuccessors*/, std::shared_ptr<int_list> /*accSignature*/) { + // IGNORE + } + + /** + * Called by the parser to notify the consumer that the definition for state `stateId` + * has ended [multiple]. + */ + virtual void notifyEndOfState(unsigned int /*stateId*/) { + // IGNORE + } + + /** + * Called by the parser to notify the consumer that the automata definition has ended [mandatory, once]. + */ + virtual void notifyEnd() { + } + + /** + * Called by the parser to notify the consumer that an "ABORT" message has been encountered + * (at any time, indicating error, the automaton should be discarded). + */ + virtual void notifyAbort() { + throw std::runtime_error("Parsing deterministic automaton: Automaton is incomplete (abort)"); + } + + + /** + * Is called whenever a condition is encountered that merits a (non-fatal) warning. + * The consumer is free to handle this situation as it wishes. + */ + virtual void notifyWarning(const std::string& warning) { + // IGNORE + (void)warning; + } + +}; + +} +} + diff --git a/src/storm/automata/HOAHeader.h b/src/storm/automata/HOAHeader.h new file mode 100644 index 000000000..1eb7e33af --- /dev/null +++ b/src/storm/automata/HOAHeader.h @@ -0,0 +1,26 @@ +#pragma once + +#include "storm/automata/APSet.h" +#include "cpphoafparser/consumer/hoa_consumer.hh" +#include <boost/optional.hpp> + +namespace storm { + namespace automata { + class HOAHeader { + public: + boost::optional<unsigned int> startState; + boost::optional<unsigned int> numberOfStates; + APSet apSet; + + boost::optional<unsigned int> numberOfAcceptanceSets; + cpphoafparser::HOAConsumer::acceptance_expr::ptr acceptance_expression; + boost::optional<std::string> accName; + boost::optional<std::vector<cpphoafparser::IntOrString>> accNameExtraInfo; + + AcceptanceCondition::ptr getAcceptanceCondition() { + return AcceptanceCondition::ptr(new AcceptanceCondition(*numberOfStates, *numberOfAcceptanceSets, acceptance_expression)); + } + + }; + } +} diff --git a/src/storm/automata/LTL2DeterministicAutomaton.cpp b/src/storm/automata/LTL2DeterministicAutomaton.cpp new file mode 100644 index 000000000..6e1636961 --- /dev/null +++ b/src/storm/automata/LTL2DeterministicAutomaton.cpp @@ -0,0 +1,107 @@ +#include "storm/automata/LTL2DeterministicAutomaton.h" +#include "storm/automata/DeterministicAutomaton.h" + +#include "storm/logic/Formula.h" +#include "storm/utility/macros.h" +#include "storm/exceptions/ExpressionEvaluationException.h" +#include "storm/exceptions/NotSupportedException.h" +#include "storm/exceptions/FileIoException.h" + +#include <sys/wait.h> + +#ifdef STORM_HAVE_SPOT +#include "spot/tl/formula.hh" +#include "spot/tl/parse.hh" +#include "spot/twaalgos/translate.hh" +#include "spot/twaalgos/hoa.hh" +#include "spot/twaalgos/totgba.hh" +#endif + +namespace storm { + namespace automata { + + + std::shared_ptr<DeterministicAutomaton> LTL2DeterministicAutomaton::ltl2daSpot(storm::logic::Formula const& f, bool dnf) { +#ifdef STORM_HAVE_SPOT + std::string prefixLtl = f.toPrefixString(); + + spot::parsed_formula spotPrefixLtl = spot::parse_prefix_ltl(prefixLtl); + if(!spotPrefixLtl.errors.empty()){ + std::ostringstream errorMsg; + spotPrefixLtl.format_errors(errorMsg); + STORM_LOG_THROW(false, storm::exceptions::ExpressionEvaluationException, "Spot could not parse formula: " << prefixLtl << ": " << errorMsg.str()); + } + spot::formula spotFormula = spotPrefixLtl.f; + + + // Request a deterministic, complete automaton with state-based acceptance + spot::translator trans = spot::translator(); + trans.set_type(spot::postprocessor::Generic); + trans.set_pref(spot::postprocessor::Deterministic | spot::postprocessor::SBAcc | spot::postprocessor::Complete); + STORM_LOG_INFO("Construct deterministic automaton for "<< spotFormula); + auto aut = trans.run(spotFormula); + + if(!(aut->get_acceptance().is_dnf()) && dnf){ + STORM_LOG_INFO("Convert acceptance condition "<< aut->get_acceptance() << " into DNF..."); + // Transform the acceptance condition in disjunctive normal form and merge all the Fin-sets of each clause + aut = to_generalized_rabin(aut,true); + } + + STORM_LOG_INFO("The deterministic automaton has acceptance condition: "<< aut->get_acceptance()); + + STORM_LOG_INFO(aut->get_acceptance()); + + std::stringstream autStream; + // Print reachable states in HOA format, implicit edges (i), state-based acceptance (s) + spot::print_hoa(autStream, aut, "is"); + + storm::automata::DeterministicAutomaton::ptr da = DeterministicAutomaton::parse(autStream); + + return da; + +#else + STORM_LOG_THROW(false, storm::exceptions::NotSupportedException, "Storm is compiled without Spot support."); +#endif + } + + std::shared_ptr<DeterministicAutomaton> LTL2DeterministicAutomaton::ltl2daExternalTool(storm::logic::Formula const& f, std::string ltl2daTool) { + std::string prefixLtl = f.toPrefixString(); + + STORM_LOG_INFO("Calling external LTL->DA tool: " << ltl2daTool << " '" << prefixLtl << "' da.hoa"); + + pid_t pid; + + pid = fork(); + STORM_LOG_THROW(pid >= 0, storm::exceptions::FileIoException, "Could not construct deterministic automaton, fork failed"); + + if (pid == 0) { + // we are in the child process + if (execlp(ltl2daTool.c_str(), ltl2daTool.c_str(), prefixLtl.c_str(), "da.hoa", NULL) < 0) { + std::cerr << "ERROR: exec failed: " << strerror(errno) << std::endl; + std::exit(1); + } + // never reached + return std::shared_ptr<DeterministicAutomaton>(); + } else { // in the parent + int status; + + // wait for completion + while (wait(&status) != pid); + + int rv; + if (WIFEXITED(status)) { + rv = WEXITSTATUS(status); + } else { + STORM_LOG_THROW(false, storm::exceptions::FileIoException, "Could not construct deterministic automaton: process aborted"); + } + STORM_LOG_THROW(rv == 0, storm::exceptions::FileIoException, "Could not construct deterministic automaton for " << prefixLtl << ", return code = " << rv); + + STORM_LOG_INFO("Reading automaton for " << prefixLtl << " from da.hoa"); + + return DeterministicAutomaton::parseFromFile("da.hoa"); + } + } + + } + +} diff --git a/src/storm/automata/LTL2DeterministicAutomaton.h b/src/storm/automata/LTL2DeterministicAutomaton.h new file mode 100644 index 000000000..94669138f --- /dev/null +++ b/src/storm/automata/LTL2DeterministicAutomaton.h @@ -0,0 +1,43 @@ +#pragma + +#include <memory> + +namespace storm { + + namespace logic { + // fwd + class Formula; + } + + namespace automata { + // fwd + class DeterministicAutomaton; + + class LTL2DeterministicAutomaton { + public: + + /*! + * Converts an LTL formula into a deterministic omega-automaton using the internal LTL2DA tool "Spot". + * The resulting DA uses transition-based acceptance and if specified the acceptance condition is converted to DNF. + * + * @param f The LTL formula. + * @param dnf A Flag indicating whether the acceptance condition is transformed into DNF. + * @return An automaton equivalent to the formula. + */ + static std::shared_ptr<DeterministicAutomaton> ltl2daSpot(storm::logic::Formula const& f, bool dnf); + + /*! + * Converts an LTL formula into a deterministic omega-automaton using an external LTL2DA tool. + * The external tool must guarantee transition-based acceptance. + * Additionally, for MDP model checking, the acceptance condition of the resulting automaton must be in DNF. + * + * @param f The LTL formula. + * @param ltl2daTool The external tool. + * @return An automaton equivalent to the formula. + */ + static std::shared_ptr<DeterministicAutomaton> ltl2daExternalTool(storm::logic::Formula const& f, std::string ltl2daTool); + + }; + + } +} diff --git a/src/storm/environment/modelchecker/ModelCheckerEnvironment.cpp b/src/storm/environment/modelchecker/ModelCheckerEnvironment.cpp index f0d917a28..6dbb25890 100644 --- a/src/storm/environment/modelchecker/ModelCheckerEnvironment.cpp +++ b/src/storm/environment/modelchecker/ModelCheckerEnvironment.cpp @@ -3,6 +3,7 @@ #include "storm/environment/modelchecker/MultiObjectiveModelCheckerEnvironment.h" #include "storm/settings/SettingsManager.h" +#include "storm/settings/modules/ModelCheckerSettings.h" #include "storm/utility/macros.h" #include "storm/exceptions/InvalidEnvironmentException.h" @@ -12,7 +13,10 @@ namespace storm { ModelCheckerEnvironment::ModelCheckerEnvironment() { - // Intentionally left empty + auto const& mcSettings = storm::settings::getModule<storm::settings::modules::ModelCheckerSettings>(); + if (mcSettings.isLtl2daToolSet()) { + ltl2daTool = mcSettings.getLtl2daTool(); + } } ModelCheckerEnvironment::~ModelCheckerEnvironment() { @@ -26,6 +30,25 @@ namespace storm { MultiObjectiveModelCheckerEnvironment const& ModelCheckerEnvironment::multi() const { return multiObjectiveModelCheckerEnvironment.get(); } + + bool ModelCheckerEnvironment::isLtl2daToolSet() const { + return ltl2daTool.is_initialized(); + } + + std::string const& ModelCheckerEnvironment::getLtl2daTool() const { + return ltl2daTool.get(); + } + + void ModelCheckerEnvironment::setLtl2daTool(std::string const& value) { + ltl2daTool = value; + } + + void ModelCheckerEnvironment::unsetLtl2daTool() { + ltl2daTool = boost::none; + } + + + } diff --git a/src/storm/environment/modelchecker/ModelCheckerEnvironment.h b/src/storm/environment/modelchecker/ModelCheckerEnvironment.h index 2ec1eebd8..6867a487c 100644 --- a/src/storm/environment/modelchecker/ModelCheckerEnvironment.h +++ b/src/storm/environment/modelchecker/ModelCheckerEnvironment.h @@ -1,6 +1,7 @@ #pragma once #include <memory> +#include <string> #include <boost/optional.hpp> #include "storm/environment/Environment.h" @@ -20,9 +21,16 @@ namespace storm { MultiObjectiveModelCheckerEnvironment& multi(); MultiObjectiveModelCheckerEnvironment const& multi() const; - + + bool isLtl2daToolSet() const; + std::string const& getLtl2daTool() const; + void setLtl2daTool(std::string const& value); + void unsetLtl2daTool(); + + private: SubEnvironment<MultiObjectiveModelCheckerEnvironment> multiObjectiveModelCheckerEnvironment; + boost::optional<std::string> ltl2daTool; }; } diff --git a/src/storm/logic/AtomicExpressionFormula.cpp b/src/storm/logic/AtomicExpressionFormula.cpp index 6fe7b6fdb..1a8d4caa8 100644 --- a/src/storm/logic/AtomicExpressionFormula.cpp +++ b/src/storm/logic/AtomicExpressionFormula.cpp @@ -28,8 +28,15 @@ namespace storm { expression.gatherVariables(usedVariables); } - std::ostream& AtomicExpressionFormula::writeToStream(std::ostream& out) const { + std::ostream& AtomicExpressionFormula::writeToStream(std::ostream& out, bool allowParentheses) const { + bool parentheses = allowParentheses & (this->expression.isLiteral() || this->expression.isVariable()); + if (parentheses) { + out << "("; + } out << expression; + if (parentheses) { + out << ")"; + } return out; } } diff --git a/src/storm/logic/AtomicExpressionFormula.h b/src/storm/logic/AtomicExpressionFormula.h index 21168493b..8bb0b3018 100644 --- a/src/storm/logic/AtomicExpressionFormula.h +++ b/src/storm/logic/AtomicExpressionFormula.h @@ -19,7 +19,7 @@ namespace storm { storm::expressions::Expression const& getExpression() const; - virtual std::ostream& writeToStream(std::ostream& out) const override; + virtual std::ostream& writeToStream(std::ostream& out, bool allowParentheses = false) const override; virtual void gatherAtomicExpressionFormulas(std::vector<std::shared_ptr<AtomicExpressionFormula const>>& atomicExpressionFormulas) const override; virtual void gatherUsedVariables(std::set<storm::expressions::Variable>& usedVariables) const override; diff --git a/src/storm/logic/AtomicLabelFormula.cpp b/src/storm/logic/AtomicLabelFormula.cpp index 15790609a..413617c68 100644 --- a/src/storm/logic/AtomicLabelFormula.cpp +++ b/src/storm/logic/AtomicLabelFormula.cpp @@ -25,7 +25,8 @@ namespace storm { atomicExpressionFormulas.push_back(std::dynamic_pointer_cast<AtomicLabelFormula const>(this->shared_from_this())); } - std::ostream& AtomicLabelFormula::writeToStream(std::ostream& out) const { + std::ostream& AtomicLabelFormula::writeToStream(std::ostream& out, bool /*allowParentheses*/) const { + // No parentheses necessary out << "\"" << label << "\""; return out; } diff --git a/src/storm/logic/AtomicLabelFormula.h b/src/storm/logic/AtomicLabelFormula.h index 1173701a0..8314cdb92 100644 --- a/src/storm/logic/AtomicLabelFormula.h +++ b/src/storm/logic/AtomicLabelFormula.h @@ -23,7 +23,7 @@ namespace storm { virtual void gatherAtomicLabelFormulas(std::vector<std::shared_ptr<AtomicLabelFormula const>>& atomicLabelFormulas) const override; - virtual std::ostream& writeToStream(std::ostream& out) const override; + virtual std::ostream& writeToStream(std::ostream& out, bool allowParentheses = false) const override; private: std::string label; diff --git a/src/storm/logic/BinaryBooleanOperatorType.h b/src/storm/logic/BinaryBooleanOperatorType.h new file mode 100644 index 000000000..8c4c141a4 --- /dev/null +++ b/src/storm/logic/BinaryBooleanOperatorType.h @@ -0,0 +1,7 @@ +#pragma once + +namespace storm { + namespace logic { + enum class BinaryBooleanOperatorType {And, Or}; + } +} diff --git a/src/storm/logic/BinaryBooleanPathFormula.cpp b/src/storm/logic/BinaryBooleanPathFormula.cpp new file mode 100644 index 000000000..1b1b45bf0 --- /dev/null +++ b/src/storm/logic/BinaryBooleanPathFormula.cpp @@ -0,0 +1,60 @@ +#include "storm/logic/BinaryBooleanPathFormula.h" + +#include "storm/logic/FormulaVisitor.h" + +#include "storm/utility/macros.h" +#include "storm/exceptions/InvalidPropertyException.h" + +namespace storm { + namespace logic { + BinaryBooleanPathFormula::BinaryBooleanPathFormula(OperatorType operatorType, std::shared_ptr<Formula const> const& leftSubformula, std::shared_ptr<Formula const> const& rightSubformula, FormulaContext context) : BinaryPathFormula(leftSubformula, rightSubformula), operatorType(operatorType), context(context) { + STORM_LOG_THROW(this->getLeftSubformula().isStateFormula() || this->getLeftSubformula().isPathFormula(), storm::exceptions::InvalidPropertyException, "Boolean path formula must have either path or state subformulas"); + STORM_LOG_THROW(this->getRightSubformula().isStateFormula() || this->getRightSubformula().isPathFormula(), storm::exceptions::InvalidPropertyException, "Boolean path formula must have either path or state subformulas"); + STORM_LOG_THROW(context == FormulaContext::Probability, storm::exceptions::InvalidPropertyException, "Invalid context for formula."); + } + + FormulaContext const& BinaryBooleanPathFormula::getContext() const { + return context; + } + + bool BinaryBooleanPathFormula::isBinaryBooleanPathFormula() const { + return true; + } + + bool BinaryBooleanPathFormula::isProbabilityPathFormula() const { + return true; + } + + boost::any BinaryBooleanPathFormula::accept(FormulaVisitor const& visitor, boost::any const& data) const { + return visitor.visit(*this, data); + } + + BinaryBooleanPathFormula::OperatorType BinaryBooleanPathFormula::getOperator() const { + return operatorType; + } + + bool BinaryBooleanPathFormula::isAnd() const { + return this->getOperator() == OperatorType::And; + } + + bool BinaryBooleanPathFormula::isOr() const { + return this->getOperator() == OperatorType::Or; + } + + std::ostream& BinaryBooleanPathFormula::writeToStream(std::ostream& out, bool allowParentheses) const { + if (allowParentheses) { + out << "("; + } + this->getLeftSubformula().writeToStream(out, true); + switch (operatorType) { + case OperatorType::And: out << " & "; break; + case OperatorType::Or: out << " | "; break; + } + this->getRightSubformula().writeToStream(out, true); + if (allowParentheses) { + out << ")"; + } + return out; + } + } +} diff --git a/src/storm/logic/BinaryBooleanPathFormula.h b/src/storm/logic/BinaryBooleanPathFormula.h new file mode 100644 index 000000000..344aed715 --- /dev/null +++ b/src/storm/logic/BinaryBooleanPathFormula.h @@ -0,0 +1,43 @@ +#ifndef STORM_LOGIC_BINARYBOOLEANPATHFORMULA_H_ +#define STORM_LOGIC_BINARYBOOLEANPATHFORMULA_H_ + +#include <map> + +#include "storm/logic/BinaryPathFormula.h" +#include "storm/logic/BinaryBooleanOperatorType.h" +#include "storm/logic/FormulaContext.h" + +namespace storm { + namespace logic { + class BinaryBooleanPathFormula : public BinaryPathFormula { + public: + typedef storm::logic::BinaryBooleanOperatorType OperatorType; + + BinaryBooleanPathFormula(OperatorType operatorType, std::shared_ptr<Formula const> const& leftSubformula, std::shared_ptr<Formula const> const& rightSubformula, FormulaContext context = FormulaContext::Probability); + + virtual ~BinaryBooleanPathFormula() { + // Intentionally left empty. + }; + + FormulaContext const& getContext() const; + + virtual bool isBinaryBooleanPathFormula() const override; + virtual bool isProbabilityPathFormula() const override; + + virtual boost::any accept(FormulaVisitor const& visitor, boost::any const& data) const override; + + OperatorType getOperator() const; + + virtual bool isAnd() const; + virtual bool isOr() const; + + virtual std::ostream& writeToStream(std::ostream& out, bool allowParentheses = false) const override; + + private: + OperatorType operatorType; + FormulaContext context; + }; + } +} + +#endif /* STORM_LOGIC_BINARYBOOLEANPATHFORMULA_H_ */ diff --git a/src/storm/logic/BinaryBooleanStateFormula.cpp b/src/storm/logic/BinaryBooleanStateFormula.cpp index ec630eb59..925a155bf 100644 --- a/src/storm/logic/BinaryBooleanStateFormula.cpp +++ b/src/storm/logic/BinaryBooleanStateFormula.cpp @@ -31,15 +31,19 @@ namespace storm { return this->getOperator() == OperatorType::Or; } - std::ostream& BinaryBooleanStateFormula::writeToStream(std::ostream& out) const { - out << "("; - this->getLeftSubformula().writeToStream(out); + std::ostream& BinaryBooleanStateFormula::writeToStream(std::ostream& out, bool allowParentheses) const { + if (allowParentheses) { + out << "("; + } + this->getLeftSubformula().writeToStream(out, true); switch (operatorType) { case OperatorType::And: out << " & "; break; case OperatorType::Or: out << " | "; break; } - this->getRightSubformula().writeToStream(out); - out << ")"; + this->getRightSubformula().writeToStream(out, true); + if (allowParentheses) { + out << ")"; + } return out; } } diff --git a/src/storm/logic/BinaryBooleanStateFormula.h b/src/storm/logic/BinaryBooleanStateFormula.h index 9a884e60a..26bb3b717 100644 --- a/src/storm/logic/BinaryBooleanStateFormula.h +++ b/src/storm/logic/BinaryBooleanStateFormula.h @@ -4,12 +4,13 @@ #include <map> #include "storm/logic/BinaryStateFormula.h" +#include "storm/logic/BinaryBooleanOperatorType.h" namespace storm { namespace logic { class BinaryBooleanStateFormula : public BinaryStateFormula { public: - enum class OperatorType {And, Or}; + typedef storm::logic::BinaryBooleanOperatorType OperatorType; BinaryBooleanStateFormula(OperatorType operatorType, std::shared_ptr<Formula const> const& leftSubformula, std::shared_ptr<Formula const> const& rightSubformula); @@ -26,7 +27,7 @@ namespace storm { virtual bool isAnd() const; virtual bool isOr() const; - virtual std::ostream& writeToStream(std::ostream& out) const override; + virtual std::ostream& writeToStream(std::ostream& out, bool allowParentheses = false) const override; private: OperatorType operatorType; diff --git a/src/storm/logic/BooleanLiteralFormula.cpp b/src/storm/logic/BooleanLiteralFormula.cpp index 15f961509..552c048b4 100644 --- a/src/storm/logic/BooleanLiteralFormula.cpp +++ b/src/storm/logic/BooleanLiteralFormula.cpp @@ -24,7 +24,8 @@ namespace storm { return visitor.visit(*this, data); } - std::ostream& BooleanLiteralFormula::writeToStream(std::ostream& out) const { + std::ostream& BooleanLiteralFormula::writeToStream(std::ostream& out, bool /*allowParentheses */) const { + // No parentheses necessary if (value) { out << "true"; } else { diff --git a/src/storm/logic/BooleanLiteralFormula.h b/src/storm/logic/BooleanLiteralFormula.h index 2cc59ea15..ef83b6349 100644 --- a/src/storm/logic/BooleanLiteralFormula.h +++ b/src/storm/logic/BooleanLiteralFormula.h @@ -19,7 +19,7 @@ namespace storm { virtual boost::any accept(FormulaVisitor const& visitor, boost::any const& data) const override; - virtual std::ostream& writeToStream(std::ostream& out) const override; + virtual std::ostream& writeToStream(std::ostream& out, bool allowParentheses = false) const override; private: bool value; diff --git a/src/storm/logic/BoundedGloballyFormula.cpp b/src/storm/logic/BoundedGloballyFormula.cpp index 736625d4e..92cfa80a4 100644 --- a/src/storm/logic/BoundedGloballyFormula.cpp +++ b/src/storm/logic/BoundedGloballyFormula.cpp @@ -218,7 +218,7 @@ namespace storm { STORM_LOG_THROW(!bound.containsVariables(), storm::exceptions::InvalidOperationException, "Cannot evaluate time-bound '" << bound << "' as it contains undefined constants."); } - std::ostream& BoundedGloballyFormula::writeToStream(std::ostream& out) const { + std::ostream& BoundedGloballyFormula::writeToStream(std::ostream& out, bool allowParentheses) const { out << "G" ; if (this->isMultiDimensional()) { out << "^{"; @@ -277,4 +277,4 @@ namespace storm { return out; } } -} \ No newline at end of file +} diff --git a/src/storm/logic/BoundedGloballyFormula.h b/src/storm/logic/BoundedGloballyFormula.h index 644bd950c..c4b7e8004 100644 --- a/src/storm/logic/BoundedGloballyFormula.h +++ b/src/storm/logic/BoundedGloballyFormula.h @@ -60,10 +60,7 @@ namespace storm { template<typename ValueType> ValueType getNonStrictLowerBound(unsigned i = 0) const; - - - virtual std::ostream &writeToStream(std::ostream &out) const override; - + virtual std::ostream &writeToStream(std::ostream &out, bool allowParentheses = false) const override; private: static void checkNoVariablesInBound(storm::expressions::Expression const& bound); @@ -73,4 +70,4 @@ namespace storm { std::vector<boost::optional<TimeBound>> upperBound; }; } -} \ No newline at end of file +} diff --git a/src/storm/logic/BoundedUntilFormula.cpp b/src/storm/logic/BoundedUntilFormula.cpp index 572712257..e22b626a0 100644 --- a/src/storm/logic/BoundedUntilFormula.cpp +++ b/src/storm/logic/BoundedUntilFormula.cpp @@ -309,7 +309,7 @@ namespace storm { return std::make_shared<BoundedUntilFormula const>(getLeftSubformula(i).asSharedPointer(), getRightSubformula(i).asSharedPointer(), lowerBound.at(i), upperBound.at(i), getTimeBoundReference(i)); } - std::ostream& BoundedUntilFormula::writeToStream(std::ostream& out) const { + std::ostream& BoundedUntilFormula::writeToStream(std::ostream& out, bool allowParentheses) const { if (hasMultiDimensionalSubformulas()) { out << "multi("; restrictToDimension(0)->writeToStream(out); @@ -319,8 +319,10 @@ namespace storm { } out << ")"; } else { - - this->getLeftSubformula().writeToStream(out); + if (allowParentheses) { + out << "("; + } + this->getLeftSubformula().writeToStream(out, true); out << " U"; if (this->isMultiDimensional()) { @@ -379,7 +381,10 @@ namespace storm { out << "}"; } - this->getRightSubformula().writeToStream(out); + this->getRightSubformula().writeToStream(out, true); + if (allowParentheses) { + out << ")"; + } } return out; diff --git a/src/storm/logic/BoundedUntilFormula.h b/src/storm/logic/BoundedUntilFormula.h index df1ff92b5..65da690da 100644 --- a/src/storm/logic/BoundedUntilFormula.h +++ b/src/storm/logic/BoundedUntilFormula.h @@ -67,7 +67,7 @@ namespace storm { std::shared_ptr<BoundedUntilFormula const> restrictToDimension(unsigned i) const; - virtual std::ostream& writeToStream(std::ostream& out) const override; + virtual std::ostream& writeToStream(std::ostream& out, bool allowParentheses = false) const override; private: static void checkNoVariablesInBound(storm::expressions::Expression const& bound); diff --git a/src/storm/logic/CloneVisitor.cpp b/src/storm/logic/CloneVisitor.cpp index 57c8ce377..ca1af66d9 100644 --- a/src/storm/logic/CloneVisitor.cpp +++ b/src/storm/logic/CloneVisitor.cpp @@ -24,6 +24,12 @@ namespace storm { return std::static_pointer_cast<Formula>(std::make_shared<BinaryBooleanStateFormula>(f.getOperator(), left, right)); } + boost::any CloneVisitor::visit(BinaryBooleanPathFormula const& f, boost::any const& data) const { + std::shared_ptr<Formula> left = boost::any_cast<std::shared_ptr<Formula>>(f.getLeftSubformula().accept(*this, data)); + std::shared_ptr<Formula> right = boost::any_cast<std::shared_ptr<Formula>>(f.getRightSubformula().accept(*this, data)); + return std::static_pointer_cast<Formula>(std::make_shared<BinaryBooleanPathFormula>(f.getOperator(), left, right)); + } + boost::any CloneVisitor::visit(BooleanLiteralFormula const& f, boost::any const&) const { return std::static_pointer_cast<Formula>(std::make_shared<BooleanLiteralFormula>(f)); } @@ -170,11 +176,24 @@ namespace storm { return std::static_pointer_cast<Formula>(std::make_shared<UnaryBooleanStateFormula>(f.getOperator(), subformula)); } + boost::any CloneVisitor::visit(UnaryBooleanPathFormula const& f, boost::any const& data) const { + std::shared_ptr<Formula> subformula = boost::any_cast<std::shared_ptr<Formula>>(f.getSubformula().accept(*this, data)); + return std::static_pointer_cast<Formula>(std::make_shared<UnaryBooleanPathFormula>(f.getOperator(), subformula)); + } + boost::any CloneVisitor::visit(UntilFormula const& f, boost::any const& data) const { std::shared_ptr<Formula> left = boost::any_cast<std::shared_ptr<Formula>>(f.getLeftSubformula().accept(*this, data)); std::shared_ptr<Formula> right = boost::any_cast<std::shared_ptr<Formula>>(f.getRightSubformula().accept(*this, data)); return std::static_pointer_cast<Formula>(std::make_shared<UntilFormula>(left, right)); } + boost::any CloneVisitor::visit(HOAPathFormula const& f, boost::any const& data) const { + std::shared_ptr<HOAPathFormula> result = std::make_shared<HOAPathFormula>(f.getAutomatonFile()); + for (auto& mapped : f.getAPMapping()) { + std::shared_ptr<Formula> clonedExpression = boost::any_cast<std::shared_ptr<Formula>>(mapped.second->accept(*this, data)); + result->addAPMapping(mapped.first, clonedExpression); + } + return std::static_pointer_cast<Formula>(result); + } } } diff --git a/src/storm/logic/CloneVisitor.h b/src/storm/logic/CloneVisitor.h index 61578bdca..3b5bc1054 100644 --- a/src/storm/logic/CloneVisitor.h +++ b/src/storm/logic/CloneVisitor.h @@ -15,6 +15,7 @@ namespace storm { virtual boost::any visit(AtomicExpressionFormula const& f, boost::any const& data) const override; virtual boost::any visit(AtomicLabelFormula const& f, boost::any const& data) const override; virtual boost::any visit(BinaryBooleanStateFormula const& f, boost::any const& data) const override; + virtual boost::any visit(BinaryBooleanPathFormula const& f, boost::any const& data) const override; virtual boost::any visit(BooleanLiteralFormula const& f, boost::any const& data) const override; virtual boost::any visit(BoundedGloballyFormula const& f, boost::any const& data) const override; virtual boost::any visit(BoundedUntilFormula const& f, boost::any const& data) const override; @@ -34,7 +35,9 @@ namespace storm { virtual boost::any visit(RewardOperatorFormula const& f, boost::any const& data) const override; virtual boost::any visit(TotalRewardFormula const& f, boost::any const& data) const override; virtual boost::any visit(UnaryBooleanStateFormula const& f, boost::any const& data) const override; + virtual boost::any visit(UnaryBooleanPathFormula const& f, boost::any const& data) const override; virtual boost::any visit(UntilFormula const& f, boost::any const& data) const override; + virtual boost::any visit(HOAPathFormula const& f, boost::any const& data) const override; }; } diff --git a/src/storm/logic/ConditionalFormula.cpp b/src/storm/logic/ConditionalFormula.cpp index a02af1877..70f82eaec 100644 --- a/src/storm/logic/ConditionalFormula.cpp +++ b/src/storm/logic/ConditionalFormula.cpp @@ -62,10 +62,16 @@ namespace storm { return true; } - std::ostream& ConditionalFormula::writeToStream(std::ostream& out) const { - this->getSubformula().writeToStream(out); + std::ostream& ConditionalFormula::writeToStream(std::ostream& out, bool allowParentheses) const { + if (allowParentheses) { + out << "("; + } + this->getSubformula().writeToStream(out, true); out << " || "; - this->getConditionFormula().writeToStream(out); + this->getConditionFormula().writeToStream(out, true); + if (allowParentheses) { + out << ")"; + } return out; } } diff --git a/src/storm/logic/ConditionalFormula.h b/src/storm/logic/ConditionalFormula.h index 3a32b3463..1c973085a 100644 --- a/src/storm/logic/ConditionalFormula.h +++ b/src/storm/logic/ConditionalFormula.h @@ -23,7 +23,7 @@ namespace storm { virtual boost::any accept(FormulaVisitor const& visitor, boost::any const& data) const override; - virtual std::ostream& writeToStream(std::ostream& out) const override; + virtual std::ostream& writeToStream(std::ostream& out, bool allowParentheses = false) const override; virtual void gatherAtomicExpressionFormulas(std::vector<std::shared_ptr<AtomicExpressionFormula const>>& atomicExpressionFormulas) const override; virtual void gatherAtomicLabelFormulas(std::vector<std::shared_ptr<AtomicLabelFormula const>>& atomicLabelFormulas) const override; diff --git a/src/storm/logic/CumulativeRewardFormula.cpp b/src/storm/logic/CumulativeRewardFormula.cpp index ccafab82c..482731108 100644 --- a/src/storm/logic/CumulativeRewardFormula.cpp +++ b/src/storm/logic/CumulativeRewardFormula.cpp @@ -161,7 +161,8 @@ namespace storm { return std::make_shared<CumulativeRewardFormula const>(bounds.at(i), getTimeBoundReference(i), rewardAccumulation); } - std::ostream& CumulativeRewardFormula::writeToStream(std::ostream& out) const { + std::ostream& CumulativeRewardFormula::writeToStream(std::ostream& out, bool /*allowParentheses*/ ) const { + // No parentheses necessary out << "C"; if (hasRewardAccumulation()) { out << "[" << getRewardAccumulation() << "]"; diff --git a/src/storm/logic/CumulativeRewardFormula.h b/src/storm/logic/CumulativeRewardFormula.h index 80924865a..b15b17de8 100644 --- a/src/storm/logic/CumulativeRewardFormula.h +++ b/src/storm/logic/CumulativeRewardFormula.h @@ -26,7 +26,7 @@ namespace storm { virtual void gatherReferencedRewardModels(std::set<std::string>& referencedRewardModels) const override; virtual void gatherUsedVariables(std::set<storm::expressions::Variable>& usedVariables) const override; - virtual std::ostream& writeToStream(std::ostream& out) const override; + virtual std::ostream& writeToStream(std::ostream& out, bool allowParentheses = false) const override; TimeBoundReference const& getTimeBoundReference() const; TimeBoundReference const& getTimeBoundReference(unsigned i) const; diff --git a/src/storm/logic/EventuallyFormula.cpp b/src/storm/logic/EventuallyFormula.cpp index 12a77d49b..dcea3d9e2 100644 --- a/src/storm/logic/EventuallyFormula.cpp +++ b/src/storm/logic/EventuallyFormula.cpp @@ -55,12 +55,18 @@ namespace storm { return visitor.visit(*this, data); } - std::ostream& EventuallyFormula::writeToStream(std::ostream& out) const { + std::ostream& EventuallyFormula::writeToStream(std::ostream& out, bool allowParentheses) const { + if (allowParentheses) { + out << "("; + } out << "F "; if (hasRewardAccumulation()) { out << "[" << getRewardAccumulation() << "]"; } - this->getSubformula().writeToStream(out); + this->getSubformula().writeToStream(out, !this->getSubformula().isUnaryFormula()); + if (allowParentheses) { + out << ")"; + } return out; } } diff --git a/src/storm/logic/EventuallyFormula.h b/src/storm/logic/EventuallyFormula.h index 5fa30da6d..fdce64eb5 100644 --- a/src/storm/logic/EventuallyFormula.h +++ b/src/storm/logic/EventuallyFormula.h @@ -29,7 +29,7 @@ namespace storm { virtual boost::any accept(FormulaVisitor const& visitor, boost::any const& data) const override; - virtual std::ostream& writeToStream(std::ostream& out) const override; + virtual std::ostream& writeToStream(std::ostream& out, bool allowParentheses = false) const override; bool hasRewardAccumulation() const; RewardAccumulation const& getRewardAccumulation() const; diff --git a/src/storm/logic/ExtractMaximalStateFormulasVisitor.cpp b/src/storm/logic/ExtractMaximalStateFormulasVisitor.cpp new file mode 100644 index 000000000..f0c434ab2 --- /dev/null +++ b/src/storm/logic/ExtractMaximalStateFormulasVisitor.cpp @@ -0,0 +1,184 @@ +#include "storm/logic/ExtractMaximalStateFormulasVisitor.h" + +#include "storm/logic/Formulas.h" + +#include "storm/exceptions/InvalidOperationException.h" + +namespace storm { + namespace logic { + + ExtractMaximalStateFormulasVisitor::ExtractMaximalStateFormulasVisitor(ApToFormulaMap& extractedFormulas) : extractedFormulas(extractedFormulas), nestingLevel(0) { + } + + std::shared_ptr<Formula> ExtractMaximalStateFormulasVisitor::extract(PathFormula const& f, ApToFormulaMap& extractedFormulas) { + ExtractMaximalStateFormulasVisitor visitor(extractedFormulas); + boost::any result = f.accept(visitor, boost::any()); + return boost::any_cast<std::shared_ptr<Formula>>(result); + } + + boost::any ExtractMaximalStateFormulasVisitor::visit(BinaryBooleanPathFormula const& f, boost::any const& data) const { + if (nestingLevel > 0) { + return CloneVisitor::visit(f, data); + } + + std::shared_ptr<Formula> left = boost::any_cast<std::shared_ptr<Formula>>(f.getLeftSubformula().accept(*this, data)); + if (left->hasQualitativeResult()) { + left = extract(left); + } + + std::shared_ptr<Formula> right = boost::any_cast<std::shared_ptr<Formula>>(f.getRightSubformula().accept(*this, data)); + if (right->hasQualitativeResult()) { + right = extract(right); + } + + return std::static_pointer_cast<Formula>(std::make_shared<BinaryBooleanPathFormula>(f.getOperator(), left, right)); + } + + boost::any ExtractMaximalStateFormulasVisitor::visit(BoundedUntilFormula const& f, boost::any const& data) const { + if (nestingLevel > 0) { + return CloneVisitor::visit(f, data); + } + + STORM_LOG_THROW(true, storm::exceptions::InvalidOperationException, "Can not extract maximal state formulas for bounded until"); + // never reached + return boost::any(); + } + + boost::any ExtractMaximalStateFormulasVisitor::visit(EventuallyFormula const& f, boost::any const& data) const { + if (nestingLevel > 0) { + return CloneVisitor::visit(f, data); + } + + std::shared_ptr<Formula> sub = boost::any_cast<std::shared_ptr<Formula>>(f.getSubformula().accept(*this, data)); + if (sub->hasQualitativeResult()) { + sub = extract(sub); + } + + return std::static_pointer_cast<Formula>(std::make_shared<EventuallyFormula>(sub)); + } + + boost::any ExtractMaximalStateFormulasVisitor::visit(GloballyFormula const& f, boost::any const& data) const { + if (nestingLevel > 0) { + return CloneVisitor::visit(f, data); + } + + std::shared_ptr<Formula> sub = boost::any_cast<std::shared_ptr<Formula>>(f.getSubformula().accept(*this, data)); + if (sub->hasQualitativeResult()) { + sub = extract(sub); + } + + return std::static_pointer_cast<Formula>(std::make_shared<GloballyFormula>(sub)); + } + + boost::any ExtractMaximalStateFormulasVisitor::visit(NextFormula const& f, boost::any const& data) const { + if (nestingLevel > 0) { + return CloneVisitor::visit(f, data); + } + + std::shared_ptr<Formula> sub = boost::any_cast<std::shared_ptr<Formula>>(f.getSubformula().accept(*this, data)); + if (sub->hasQualitativeResult()) { + sub = extract(sub); + } + + return std::static_pointer_cast<Formula>(std::make_shared<NextFormula>(sub)); + } + + boost::any ExtractMaximalStateFormulasVisitor::visit(UnaryBooleanPathFormula const& f, boost::any const& data) const { + if (nestingLevel > 0) { + return CloneVisitor::visit(f, data); + } + + std::shared_ptr<Formula> sub = boost::any_cast<std::shared_ptr<Formula>>(f.getSubformula().accept(*this, data)); + if (sub->hasQualitativeResult()) { + sub = extract(sub); + } + + return std::static_pointer_cast<Formula>(std::make_shared<UnaryBooleanPathFormula>(f.getOperator(), sub)); + } + + boost::any ExtractMaximalStateFormulasVisitor::visit(UntilFormula const& f, boost::any const& data) const { + if (nestingLevel > 0) { + return CloneVisitor::visit(f, data); + } + + std::shared_ptr<Formula> left = boost::any_cast<std::shared_ptr<Formula>>(f.getLeftSubformula().accept(*this, data)); + if (left->hasQualitativeResult()) { + left = extract(left); + } + + std::shared_ptr<Formula> right = boost::any_cast<std::shared_ptr<Formula>>(f.getRightSubformula().accept(*this, data)); + if (right->hasQualitativeResult()) { + right = extract(right); + } + + return std::static_pointer_cast<Formula>(std::make_shared<UntilFormula>(left, right)); + } + + boost::any ExtractMaximalStateFormulasVisitor::visit(TimeOperatorFormula const& f, boost::any const& data) const { + incrementNestingLevel(); + boost::any result = CloneVisitor::visit(f, data); + decrementNestingLevel(); + return result; + } + + boost::any ExtractMaximalStateFormulasVisitor::visit(LongRunAverageOperatorFormula const& f, boost::any const& data) const { + incrementNestingLevel(); + boost::any result = CloneVisitor::visit(f, data); + decrementNestingLevel(); + return result; + } + + boost::any ExtractMaximalStateFormulasVisitor::visit(MultiObjectiveFormula const& f, boost::any const& data) const { + incrementNestingLevel(); + boost::any result = CloneVisitor::visit(f, data); + decrementNestingLevel(); + return result; + } + + boost::any ExtractMaximalStateFormulasVisitor::visit(ProbabilityOperatorFormula const& f, boost::any const& data) const { + incrementNestingLevel(); + boost::any result = CloneVisitor::visit(f, data); + decrementNestingLevel(); + return result; + } + + boost::any ExtractMaximalStateFormulasVisitor::visit(RewardOperatorFormula const& f, boost::any const& data) const { + incrementNestingLevel(); + boost::any result = CloneVisitor::visit(f, data); + decrementNestingLevel(); + return result; + } + + std::shared_ptr<Formula> ExtractMaximalStateFormulasVisitor::extract(std::shared_ptr<Formula> f) const { + // We use the string representation of formulae to check if they are equivalent. + // Of course, this could be made more elegant if there were an actual operator< and/or operator== for formulae + + std::string label; + + // Find equivalent formula in cache + auto it = cachedFormulas.find(f->toString()); + if (it != cachedFormulas.end()){ + // Reuse label of equivalent formula + label = it->second; + } else { + // Create new label + label = "p" + std::to_string(extractedFormulas.size()); + extractedFormulas[label] = f; + // Update cache + cachedFormulas[f->toString()] = label; + } + + return std::make_shared<storm::logic::AtomicLabelFormula>(label); + } + + void ExtractMaximalStateFormulasVisitor::incrementNestingLevel() const { + const_cast<std::size_t&>(nestingLevel)++; + } + void ExtractMaximalStateFormulasVisitor::decrementNestingLevel() const { + STORM_LOG_ASSERT(nestingLevel > 0, "Illegal nesting level decrement"); + const_cast<std::size_t&>(nestingLevel)--; + } + + + } +} diff --git a/src/storm/logic/ExtractMaximalStateFormulasVisitor.h b/src/storm/logic/ExtractMaximalStateFormulasVisitor.h new file mode 100644 index 000000000..13c829dea --- /dev/null +++ b/src/storm/logic/ExtractMaximalStateFormulasVisitor.h @@ -0,0 +1,51 @@ +#pragma once + +#include <vector> +#include <map> +#include "storm/logic/CloneVisitor.h" + +namespace storm { + namespace logic { + + class ExtractMaximalStateFormulasVisitor : public CloneVisitor { + public: + typedef std::map<std::string, std::shared_ptr<Formula const>> ApToFormulaMap; + + /*! + * Finds state subformulae in f and replaces them by atomic propositions. + * @param extractedFormulas will be the mapping of atomic propositions to the subformulae they replace + * @return the formula with replaced state subformulae + * @note identical subformulae will be replaced by the same atomic proposition + */ + static std::shared_ptr<Formula> extract(PathFormula const& f, ApToFormulaMap& extractedFormulas); + + virtual boost::any visit(BinaryBooleanPathFormula const& f, boost::any const& data) const override; + virtual boost::any visit(BoundedUntilFormula const& f, boost::any const& data) const override; + virtual boost::any visit(EventuallyFormula const& f, boost::any const& data) const override; + virtual boost::any visit(GloballyFormula const& f, boost::any const& data) const override; + virtual boost::any visit(NextFormula const& f, boost::any const& data) const override; + virtual boost::any visit(UnaryBooleanPathFormula const& f, boost::any const& data) const override; + virtual boost::any visit(UntilFormula const& f, boost::any const& data) const override; + + virtual boost::any visit(TimeOperatorFormula const& f, boost::any const& data) const override; + virtual boost::any visit(LongRunAverageOperatorFormula const& f, boost::any const& data) const override; + virtual boost::any visit(MultiObjectiveFormula const& f, boost::any const& data) const override; + virtual boost::any visit(ProbabilityOperatorFormula const& f, boost::any const& data) const override; + virtual boost::any visit(RewardOperatorFormula const& f, boost::any const& data) const override; + + private: + ExtractMaximalStateFormulasVisitor(ApToFormulaMap& extractedFormulas); + + std::shared_ptr<Formula> extract(std::shared_ptr<Formula> f) const; + void incrementNestingLevel() const; + void decrementNestingLevel() const; + + ApToFormulaMap& extractedFormulas; + // A mapping from formula-strings to labels in order to use the same label for the equivalent formulas (as strings) + mutable std::map<std::string, std::string> cachedFormulas; + std::size_t nestingLevel; + }; + + } +} + diff --git a/src/storm/logic/Formula.cpp b/src/storm/logic/Formula.cpp index b4e6c13bc..b71316097 100644 --- a/src/storm/logic/Formula.cpp +++ b/src/storm/logic/Formula.cpp @@ -8,6 +8,7 @@ #include "storm/logic/LabelSubstitutionVisitor.h" #include "storm/logic/RewardModelNameSubstitutionVisitor.h" #include "storm/logic/ToExpressionVisitor.h" +#include "storm/logic/ToPrefixStringVisitor.h" namespace storm { namespace logic { @@ -43,6 +44,14 @@ namespace storm { return false; } + bool Formula::isBinaryBooleanPathFormula() const { + return false; + } + + bool Formula::isUnaryBooleanPathFormula() const { + return false; + } + bool Formula::isBooleanLiteralFormula() const { return false; } @@ -83,6 +92,10 @@ namespace storm { return false; } + bool Formula::isHOAPathFormula() const { + return false; + } + bool Formula::isBinaryPathFormula() const { return false; } @@ -166,6 +179,10 @@ namespace storm { bool Formula::isOperatorFormula() const { return false; } + + bool Formula::isUnaryFormula() const { + return isUnaryPathFormula() || isUnaryStateFormula(); + } bool Formula::hasQualitativeResult() const { return true; @@ -180,9 +197,8 @@ namespace storm { return checker.conformsToSpecification(*this, fragment); } - FormulaInformation Formula::info() const { - FormulaInformationVisitor visitor; - return visitor.getInformation(*this); + FormulaInformation Formula::info(bool recurseIntoOperators) const { + return FormulaInformationVisitor::getInformation(*this, recurseIntoOperators); } std::shared_ptr<Formula const> Formula::getTrueFormula() { @@ -289,6 +305,14 @@ namespace storm { return dynamic_cast<AtomicLabelFormula const&>(*this); } + HOAPathFormula& Formula::asHOAPathFormula() { + return dynamic_cast<HOAPathFormula&>(*this); + } + + HOAPathFormula const& Formula::asHOAPathFormula() const { + return dynamic_cast<HOAPathFormula const&>(*this); + } + UntilFormula& Formula::asUntilFormula() { return dynamic_cast<UntilFormula&>(*this); } @@ -548,5 +572,11 @@ namespace storm { std::ostream& operator<<(std::ostream& out, Formula const& formula) { return formula.writeToStream(out); } + + std::string Formula::toPrefixString() const { + ToPrefixStringVisitor visitor; + return visitor.toPrefixString(*this); + } + } } diff --git a/src/storm/logic/Formula.h b/src/storm/logic/Formula.h index 62aab0dde..0c83e718c 100644 --- a/src/storm/logic/Formula.h +++ b/src/storm/logic/Formula.h @@ -21,17 +21,17 @@ namespace storm { // Forward-declare fragment specification for isInFragment() method. class FragmentSpecification; - + // Forward-declare formula information class for info() method. class FormulaInformation; - + class Formula : public std::enable_shared_from_this<Formula> { public: // Make the destructor virtual to allow deletion of objects of subclasses via a pointer to this class. virtual ~Formula() { // Intentionally left empty. }; - + friend std::ostream& operator<<(std::ostream& out, Formula const& formula); // Basic formula types. @@ -39,14 +39,17 @@ namespace storm { virtual bool isStateFormula() const; virtual bool isConditionalProbabilityFormula() const; virtual bool isConditionalRewardFormula() const; - + virtual bool isProbabilityPathFormula() const; virtual bool isRewardPathFormula() const; virtual bool isTimePathFormula() const; virtual bool isBinaryBooleanStateFormula() const; virtual bool isUnaryBooleanStateFormula() const; - + + virtual bool isBinaryBooleanPathFormula() const; + virtual bool isUnaryBooleanPathFormula() const; + virtual bool isMultiObjectiveFormula() const; virtual bool isQuantileFormula() const; @@ -71,6 +74,7 @@ namespace storm { virtual bool isGloballyFormula() const; virtual bool isEventuallyFormula() const; virtual bool isReachabilityProbabilityFormula() const; + virtual bool isHOAPathFormula() const; virtual bool isBoundedGloballyFormula() const; // Reward formulas. @@ -91,38 +95,39 @@ namespace storm { virtual bool isBinaryStateFormula() const; virtual bool isUnaryPathFormula() const; virtual bool isUnaryStateFormula() const; + bool isUnaryFormula() const; // Accessors for the return type of a formula. virtual bool hasQualitativeResult() const; virtual bool hasQuantitativeResult() const; - + bool isInFragment(FragmentSpecification const& fragment) const; - FormulaInformation info() const; + FormulaInformation info(bool recurseIntoOperators = true) const; virtual boost::any accept(FormulaVisitor const& visitor, boost::any const& data = boost::any()) const = 0; - + static std::shared_ptr<Formula const> getTrueFormula(); bool isInitialFormula() const; - + PathFormula& asPathFormula(); PathFormula const& asPathFormula() const; - + StateFormula& asStateFormula(); StateFormula const& asStateFormula() const; - + MultiObjectiveFormula& asMultiObjectiveFormula(); MultiObjectiveFormula const& asMultiObjectiveFormula() const; - + QuantileFormula& asQuantileFormula(); QuantileFormula const& asQuantileFormula() const; - + BinaryStateFormula& asBinaryStateFormula(); BinaryStateFormula const& asBinaryStateFormula() const; - + UnaryStateFormula& asUnaryStateFormula(); UnaryStateFormula const& asUnaryStateFormula() const; - + BinaryBooleanStateFormula& asBinaryBooleanStateFormula(); BinaryBooleanStateFormula const& asBinaryBooleanStateFormula() const; @@ -131,25 +136,31 @@ namespace storm { BooleanLiteralFormula& asBooleanLiteralFormula(); BooleanLiteralFormula const& asBooleanLiteralFormula() const; - + AtomicExpressionFormula& asAtomicExpressionFormula(); AtomicExpressionFormula const& asAtomicExpressionFormula() const; - + AtomicLabelFormula& asAtomicLabelFormula(); AtomicLabelFormula const& asAtomicLabelFormula() const; - + UntilFormula& asUntilFormula(); UntilFormula const& asUntilFormula() const; - + + HOAPathFormula& asHOAPathFormula(); + HOAPathFormula const& asHOAPathFormula() const; + + HOAPathFormula& asHOAPathFormula(); + HOAPathFormula const& asHOAPathFormula() const; + BoundedUntilFormula& asBoundedUntilFormula(); BoundedUntilFormula const& asBoundedUntilFormula() const; - + EventuallyFormula& asEventuallyFormula(); EventuallyFormula const& asEventuallyFormula() const; - + EventuallyFormula& asReachabilityProbabilityFormula(); EventuallyFormula const& asReachabilityProbabilityFormula() const; - + EventuallyFormula& asReachabilityRewardFormula(); EventuallyFormula const& asReachabilityRewardFormula() const; @@ -161,16 +172,16 @@ namespace storm { GloballyFormula& asGloballyFormula(); GloballyFormula const& asGloballyFormula() const; - + BinaryPathFormula& asBinaryPathFormula(); BinaryPathFormula const& asBinaryPathFormula() const; - + UnaryPathFormula& asUnaryPathFormula(); UnaryPathFormula const& asUnaryPathFormula() const; - + ConditionalFormula& asConditionalFormula(); ConditionalFormula const& asConditionalFormula() const; - + NextFormula& asNextFormula(); NextFormula const& asNextFormula() const; @@ -182,36 +193,36 @@ namespace storm { TimeOperatorFormula& asTimeOperatorFormula(); TimeOperatorFormula const& asTimeOperatorFormula() const; - + CumulativeRewardFormula& asCumulativeRewardFormula(); CumulativeRewardFormula const& asCumulativeRewardFormula() const; - + TotalRewardFormula& asTotalRewardFormula(); TotalRewardFormula const& asTotalRewardFormula() const; - + InstantaneousRewardFormula& asInstantaneousRewardFormula(); InstantaneousRewardFormula const& asInstantaneousRewardFormula() const; - + LongRunAverageRewardFormula& asLongRunAverageRewardFormula(); LongRunAverageRewardFormula const& asLongRunAverageRewardFormula() const; - + ProbabilityOperatorFormula& asProbabilityOperatorFormula(); ProbabilityOperatorFormula const& asProbabilityOperatorFormula() const; - + RewardOperatorFormula& asRewardOperatorFormula(); RewardOperatorFormula const& asRewardOperatorFormula() const; - + OperatorFormula& asOperatorFormula(); OperatorFormula const& asOperatorFormula() const; - + std::vector<std::shared_ptr<AtomicExpressionFormula const>> getAtomicExpressionFormulas() const; std::vector<std::shared_ptr<AtomicLabelFormula const>> getAtomicLabelFormulas() const; std::set<storm::expressions::Variable> getUsedVariables() const; std::set<std::string> getReferencedRewardModels() const; - + std::shared_ptr<Formula const> asSharedPointer(); std::shared_ptr<Formula const> asSharedPointer() const; - + std::shared_ptr<Formula> substitute(std::map<storm::expressions::Variable, storm::expressions::Expression> const& substitution) const; std::shared_ptr<Formula> substitute(std::function<storm::expressions::Expression(storm::expressions::Expression const&)> const& expressionSubstitution) const; std::shared_ptr<Formula> substitute(std::map<std::string, storm::expressions::Expression> const& labelSubstitution) const; @@ -228,10 +239,18 @@ namespace storm { * @return An equivalent expression. */ storm::expressions::Expression toExpression(storm::expressions::ExpressionManager const& manager, std::map<std::string, storm::expressions::Expression> const& labelToExpressionMapping = {}) const; - + std::string toString() const; - virtual std::ostream& writeToStream(std::ostream& out) const = 0; - + + /*! + * Writes the forumla to the given output stream + * @param allowParenthesis if true, the output is *potentially* surrounded by parentheses depending on whether parentheses are needed to avoid ambiguity when this formula appears as a subformula of some larger formula. + * @return + */ + virtual std::ostream& writeToStream(std::ostream& out, bool allowParentheses = false) const = 0; + + std::string toPrefixString() const; + virtual void gatherAtomicExpressionFormulas(std::vector<std::shared_ptr<AtomicExpressionFormula const>>& atomicExpressionFormulas) const; virtual void gatherAtomicLabelFormulas(std::vector<std::shared_ptr<AtomicLabelFormula const>>& atomicLabelFormulas) const; virtual void gatherReferencedRewardModels(std::set<std::string>& referencedRewardModels) const; @@ -240,7 +259,7 @@ namespace storm { private: // Currently empty. }; - + std::ostream& operator<<(std::ostream& out, Formula const& formula); } } diff --git a/src/storm/logic/FormulaInformation.cpp b/src/storm/logic/FormulaInformation.cpp index 4adae5a3c..23d826fe1 100644 --- a/src/storm/logic/FormulaInformation.cpp +++ b/src/storm/logic/FormulaInformation.cpp @@ -2,7 +2,7 @@ namespace storm { namespace logic { - FormulaInformation::FormulaInformation() : mContainsRewardOperator(false), mContainsNextFormula(false), mContainsBoundedUntilFormula(false), mContainsCumulativeRewardFormula(false), mContainsRewardBoundedFormula(false), mContainsLongRunFormula(false) { + FormulaInformation::FormulaInformation() : mContainsRewardOperator(false), mContainsNextFormula(false), mContainsBoundedUntilFormula(false), mContainsCumulativeRewardFormula(false), mContainsRewardBoundedFormula(false), mContainsLongRunFormula(false), mContainsComplexPathFormula(false) { // Intentionally left empty } @@ -30,6 +30,10 @@ namespace storm { return this->mContainsLongRunFormula; } + bool FormulaInformation::containsComplexPathFormula() const { + return this->mContainsComplexPathFormula; + } + FormulaInformation FormulaInformation::join(FormulaInformation const& other) { FormulaInformation result; result.mContainsRewardOperator = this->containsRewardOperator() || other.containsRewardOperator(); @@ -38,6 +42,7 @@ namespace storm { result.mContainsCumulativeRewardFormula = this->containsCumulativeRewardFormula() || other.containsCumulativeRewardFormula(); result.mContainsRewardBoundedFormula = this->containsRewardBoundedFormula() || other.containsRewardBoundedFormula(); result.mContainsLongRunFormula = this->containsLongRunFormula() || other.containsLongRunFormula(); + result.mContainsComplexPathFormula = this->containsComplexPathFormula() || other.containsComplexPathFormula(); return result; } @@ -70,5 +75,11 @@ namespace storm { this->mContainsLongRunFormula = newValue; return *this; } + + FormulaInformation& FormulaInformation::setContainsComplexPathFormula(bool newValue) { + this->mContainsComplexPathFormula = newValue; + return *this; + } + } } diff --git a/src/storm/logic/FormulaInformation.h b/src/storm/logic/FormulaInformation.h index 6c2c320b2..6d86ba3fd 100644 --- a/src/storm/logic/FormulaInformation.h +++ b/src/storm/logic/FormulaInformation.h @@ -19,6 +19,11 @@ namespace storm { bool containsRewardBoundedFormula() const; bool containsLongRunFormula() const; + /*! + * @return true iff the formula contains nested temporal operators and/or boolean combinations of path formulas (e.g. '"safe" & F "goal"') + */ + bool containsComplexPathFormula() const; + FormulaInformation join(FormulaInformation const& other); FormulaInformation& setContainsRewardOperator(bool newValue = true); @@ -27,6 +32,7 @@ namespace storm { FormulaInformation& setContainsCumulativeRewardFormula(bool newValue = true); FormulaInformation& setContainsRewardBoundedFormula(bool newValue = true); FormulaInformation& setContainsLongRunFormula(bool newValue = true); + FormulaInformation& setContainsComplexPathFormula(bool newValue = true); private: bool mContainsRewardOperator; @@ -35,6 +41,7 @@ namespace storm { bool mContainsCumulativeRewardFormula; bool mContainsRewardBoundedFormula; bool mContainsLongRunFormula; + bool mContainsComplexPathFormula; }; } diff --git a/src/storm/logic/FormulaInformationVisitor.cpp b/src/storm/logic/FormulaInformationVisitor.cpp index 41417eeed..0f174430b 100644 --- a/src/storm/logic/FormulaInformationVisitor.cpp +++ b/src/storm/logic/FormulaInformationVisitor.cpp @@ -4,11 +4,15 @@ namespace storm { namespace logic { - FormulaInformation FormulaInformationVisitor::getInformation(Formula const& f) const { - boost::any result = f.accept(*this, boost::any()); + FormulaInformation FormulaInformationVisitor::getInformation(Formula const& f, bool recurseIntoOperators) { + FormulaInformationVisitor visitor(recurseIntoOperators); + boost::any result = f.accept(visitor, boost::any()); return boost::any_cast<FormulaInformation>(result); } + FormulaInformationVisitor::FormulaInformationVisitor(bool recurseIntoOperators) : recurseIntoOperators(recurseIntoOperators) { + } + boost::any FormulaInformationVisitor::visit(AtomicExpressionFormula const&, boost::any const&) const { return FormulaInformation(); } @@ -17,10 +21,15 @@ namespace storm { return FormulaInformation(); } - boost::any FormulaInformationVisitor::visit(BinaryBooleanStateFormula const&, boost::any const&) const { - return FormulaInformation(); + boost::any FormulaInformationVisitor::visit(BinaryBooleanStateFormula const& f, boost::any const& data) const { + return boost::any_cast<FormulaInformation>(f.getLeftSubformula().accept(*this, data)).join(boost::any_cast<FormulaInformation>(f.getRightSubformula().accept(*this))); } + boost::any FormulaInformationVisitor::visit(BinaryBooleanPathFormula const& f, boost::any const& data) const { + FormulaInformation result = boost::any_cast<FormulaInformation>(f.getLeftSubformula().accept(*this, data)).join(boost::any_cast<FormulaInformation>(f.getRightSubformula().accept(*this))); + return result.setContainsComplexPathFormula(); + } + boost::any FormulaInformationVisitor::visit(BooleanLiteralFormula const&, boost::any const&) const { return FormulaInformation(); } @@ -42,10 +51,16 @@ namespace storm { for (unsigned i = 0; i < f.getDimension(); ++i) { result.join(boost::any_cast<FormulaInformation>(f.getLeftSubformula(i).accept(*this, data))); result.join(boost::any_cast<FormulaInformation>(f.getRightSubformula(i).accept(*this, data))); + if (f.getLeftSubformula(i).isPathFormula() || f.getRightSubformula(i).isPathFormula()) { + result.setContainsComplexPathFormula(); + } } } else { result.join(boost::any_cast<FormulaInformation>(f.getLeftSubformula().accept(*this, data))); result.join(boost::any_cast<FormulaInformation>(f.getRightSubformula().accept(*this, data))); + if (f.getLeftSubformula().isPathFormula() || f.getRightSubformula().isPathFormula()) { + result.setContainsComplexPathFormula(); + } } return result; } @@ -66,7 +81,11 @@ namespace storm { } boost::any FormulaInformationVisitor::visit(EventuallyFormula const& f, boost::any const& data) const { - return f.getSubformula().accept(*this, data); + FormulaInformation result = boost::any_cast<FormulaInformation>(f.getSubformula().accept(*this, data)); + if (f.getSubformula().isPathFormula()) { + result.setContainsComplexPathFormula(); + } + return result; } boost::any FormulaInformationVisitor::visit(TimeOperatorFormula const& f, boost::any const& data) const { @@ -74,7 +93,11 @@ namespace storm { } boost::any FormulaInformationVisitor::visit(GloballyFormula const& f, boost::any const& data) const { - return f.getSubformula().accept(*this, data); + FormulaInformation result = boost::any_cast<FormulaInformation>(f.getSubformula().accept(*this, data)); + if (f.getSubformula().isPathFormula()) { + result.setContainsComplexPathFormula(); + } + return result; } boost::any FormulaInformationVisitor::visit(GameFormula const& f, boost::any const& data) const { @@ -88,7 +111,9 @@ namespace storm { boost::any FormulaInformationVisitor::visit(LongRunAverageOperatorFormula const& f, boost::any const& data) const { FormulaInformation result; result.setContainsLongRunFormula(true); - result.join(boost::any_cast<FormulaInformation>(f.getSubformula().accept(*this, data))); + if (recurseIntoOperators) { + result.join(boost::any_cast<FormulaInformation>(f.getSubformula().accept(*this, data))); + } return result; } @@ -100,26 +125,44 @@ namespace storm { boost::any FormulaInformationVisitor::visit(MultiObjectiveFormula const& f, boost::any const& data) const { FormulaInformation result; - for(auto const& subF : f.getSubformulas()){ - result.join(boost::any_cast<FormulaInformation>(subF->accept(*this, data))); + if (recurseIntoOperators) { + for(auto const& subF : f.getSubformulas()){ + result.join(boost::any_cast<FormulaInformation>(subF->accept(*this, data))); + } } return result; } boost::any FormulaInformationVisitor::visit(QuantileFormula const& f, boost::any const& data) const { - return f.getSubformula().accept(*this, data); + if (recurseIntoOperators) { + return f.getSubformula().accept(*this, data); + } else { + return FormulaInformation(); + } } boost::any FormulaInformationVisitor::visit(NextFormula const& f, boost::any const& data) const { - return boost::any_cast<FormulaInformation>(f.getSubformula().accept(*this, data)).setContainsNextFormula(); + FormulaInformation result = boost::any_cast<FormulaInformation>(f.getSubformula().accept(*this, data)).setContainsNextFormula(); + if (f.getSubformula().isPathFormula()) { + result.setContainsComplexPathFormula(); + } + return result; } boost::any FormulaInformationVisitor::visit(ProbabilityOperatorFormula const& f, boost::any const& data) const { - return f.getSubformula().accept(*this, data); + if (recurseIntoOperators) { + return f.getSubformula().accept(*this, data); + } else { + return FormulaInformation(); + } } boost::any FormulaInformationVisitor::visit(RewardOperatorFormula const& f, boost::any const& data) const { - return boost::any_cast<FormulaInformation>(f.getSubformula().accept(*this, data)).setContainsRewardOperator(); + if (recurseIntoOperators) { + return boost::any_cast<FormulaInformation>(f.getSubformula().accept(*this, data)).setContainsRewardOperator(); + } else { + return FormulaInformation(); + } } boost::any FormulaInformationVisitor::visit(TotalRewardFormula const&, boost::any const&) const { @@ -130,8 +173,28 @@ namespace storm { return f.getSubformula().accept(*this, data); } + boost::any FormulaInformationVisitor::visit(UnaryBooleanPathFormula const& f, boost::any const& data) const { + FormulaInformation result = boost::any_cast<FormulaInformation>(f.getSubformula().accept(*this, data)); + result.setContainsComplexPathFormula(); + return result; + } + boost::any FormulaInformationVisitor::visit(UntilFormula const& f, boost::any const& data) const { - return boost::any_cast<FormulaInformation>(f.getLeftSubformula().accept(*this, data)).join(boost::any_cast<FormulaInformation>(f.getRightSubformula().accept(*this))); + FormulaInformation result = boost::any_cast<FormulaInformation>(f.getLeftSubformula().accept(*this, data)).join(boost::any_cast<FormulaInformation>(f.getRightSubformula().accept(*this))); + if (f.getLeftSubformula().isPathFormula() || f.getRightSubformula().isPathFormula()) { + result.setContainsComplexPathFormula(); + } + return result; + } + + boost::any FormulaInformationVisitor::visit(HOAPathFormula const& f, boost::any const& data) const { + FormulaInformation info; + if (recurseIntoOperators) { + for (auto& mapped : f.getAPMapping()) { + info = info.join(boost::any_cast<FormulaInformation>(mapped.second->accept(*this, data))); + } + } + return info; } } diff --git a/src/storm/logic/FormulaInformationVisitor.h b/src/storm/logic/FormulaInformationVisitor.h index ecf5a1ab7..8bf7a25a9 100644 --- a/src/storm/logic/FormulaInformationVisitor.h +++ b/src/storm/logic/FormulaInformationVisitor.h @@ -9,11 +9,18 @@ namespace storm { class FormulaInformationVisitor : public FormulaVisitor { public: - FormulaInformation getInformation(Formula const& f) const; - + static FormulaInformation getInformation(Formula const& f, bool recurseIntoOperators = true); + + explicit FormulaInformationVisitor(bool recurseIntoOperators); + FormulaInformationVisitor(FormulaInformationVisitor const& other) = default; + FormulaInformationVisitor(FormulaInformationVisitor&& other) = default; + FormulaInformationVisitor& operator=(FormulaInformationVisitor const& other) = default; + FormulaInformationVisitor& operator=(FormulaInformationVisitor&& other) = default; + virtual boost::any visit(AtomicExpressionFormula const& f, boost::any const& data) const override; virtual boost::any visit(AtomicLabelFormula const& f, boost::any const& data) const override; virtual boost::any visit(BinaryBooleanStateFormula const& f, boost::any const& data) const override; + virtual boost::any visit(BinaryBooleanPathFormula const& f, boost::any const& data) const override; virtual boost::any visit(BooleanLiteralFormula const& f, boost::any const& data) const override; virtual boost::any visit(BoundedGloballyFormula const& f, boost::any const& data) const override; virtual boost::any visit(BoundedUntilFormula const& f, boost::any const& data) const override; @@ -33,7 +40,12 @@ namespace storm { virtual boost::any visit(RewardOperatorFormula const& f, boost::any const& data) const override; virtual boost::any visit(TotalRewardFormula const& f, boost::any const& data) const override; virtual boost::any visit(UnaryBooleanStateFormula const& f, boost::any const& data) const override; + virtual boost::any visit(UnaryBooleanPathFormula const& f, boost::any const& data) const override; virtual boost::any visit(UntilFormula const& f, boost::any const& data) const override; + virtual boost::any visit(HOAPathFormula const& f, boost::any const& data) const override; + + private: + bool recurseIntoOperators; }; } diff --git a/src/storm/logic/FormulaVisitor.h b/src/storm/logic/FormulaVisitor.h index 23673ff50..def8cf722 100644 --- a/src/storm/logic/FormulaVisitor.h +++ b/src/storm/logic/FormulaVisitor.h @@ -15,6 +15,7 @@ namespace storm { virtual boost::any visit(AtomicExpressionFormula const& f, boost::any const& data) const = 0; virtual boost::any visit(AtomicLabelFormula const& f, boost::any const& data) const = 0; virtual boost::any visit(BinaryBooleanStateFormula const& f, boost::any const& data) const = 0; + virtual boost::any visit(BinaryBooleanPathFormula const& f, boost::any const& data) const = 0; virtual boost::any visit(BooleanLiteralFormula const& f, boost::any const& data) const = 0; virtual boost::any visit(BoundedGloballyFormula const& f, boost::any const& data) const = 0; virtual boost::any visit(BoundedUntilFormula const& f, boost::any const& data) const = 0; @@ -34,7 +35,9 @@ namespace storm { virtual boost::any visit(RewardOperatorFormula const& f, boost::any const& data) const = 0; virtual boost::any visit(TotalRewardFormula const& f, boost::any const& data) const = 0; virtual boost::any visit(UnaryBooleanStateFormula const& f, boost::any const& data) const = 0; + virtual boost::any visit(UnaryBooleanPathFormula const& f, boost::any const& data) const = 0; virtual boost::any visit(UntilFormula const& f, boost::any const& data) const = 0; + virtual boost::any visit(HOAPathFormula const& f, boost::any const& data) const = 0; }; } diff --git a/src/storm/logic/Formulas.h b/src/storm/logic/Formulas.h index cc59b93b6..82c44604e 100644 --- a/src/storm/logic/Formulas.h +++ b/src/storm/logic/Formulas.h @@ -2,6 +2,7 @@ #include "storm/logic/AtomicExpressionFormula.h" #include "storm/logic/AtomicLabelFormula.h" #include "storm/logic/BinaryBooleanStateFormula.h" +#include "storm/logic/BinaryBooleanPathFormula.h" #include "storm/logic/BinaryPathFormula.h" #include "storm/logic/BinaryStateFormula.h" #include "storm/logic/BooleanLiteralFormula.h" @@ -25,9 +26,11 @@ #include "storm/logic/TimeOperatorFormula.h" #include "storm/logic/TotalRewardFormula.h" #include "storm/logic/UnaryBooleanStateFormula.h" +#include "storm/logic/UnaryBooleanPathFormula.h" #include "storm/logic/UnaryPathFormula.h" #include "storm/logic/UnaryStateFormula.h" #include "storm/logic/UntilFormula.h" +#include "storm/logic/HOAPathFormula.h" #include "storm/logic/ConditionalFormula.h" #include "storm/logic/ProbabilityOperatorFormula.h" #include "storm/logic/RewardOperatorFormula.h" diff --git a/src/storm/logic/FormulasForwardDeclarations.h b/src/storm/logic/FormulasForwardDeclarations.h index 1a6611f13..0dc68db03 100644 --- a/src/storm/logic/FormulasForwardDeclarations.h +++ b/src/storm/logic/FormulasForwardDeclarations.h @@ -8,6 +8,7 @@ namespace storm { class AtomicExpressionFormula; class AtomicLabelFormula; class BinaryBooleanStateFormula; + class BinaryBooleanPathFormula; class BinaryPathFormula; class BinaryStateFormula; class BooleanLiteralFormula; @@ -33,9 +34,11 @@ namespace storm { class StateFormula; class TotalRewardFormula; class UnaryBooleanStateFormula; + class UnaryBooleanPathFormula; class UnaryPathFormula; class UnaryStateFormula; class UntilFormula; + class HOAPathFormula; } } diff --git a/src/storm/logic/FragmentChecker.cpp b/src/storm/logic/FragmentChecker.cpp index df79d22a5..6ee707ef5 100644 --- a/src/storm/logic/FragmentChecker.cpp +++ b/src/storm/logic/FragmentChecker.cpp @@ -52,6 +52,14 @@ namespace storm { return result; } + boost::any FragmentChecker::visit(BinaryBooleanPathFormula const& f, boost::any const& data) const { + InheritedInformation const& inherited = boost::any_cast<InheritedInformation const&>(data); + bool result = inherited.getSpecification().areBinaryBooleanPathFormulasAllowed(); + result = result && boost::any_cast<bool>(f.getLeftSubformula().accept(*this, data)); + result = result && boost::any_cast<bool>(f.getRightSubformula().accept(*this, data)); + return result; + } + boost::any FragmentChecker::visit(BooleanLiteralFormula const&, boost::any const& data) const { InheritedInformation const& inherited = boost::any_cast<InheritedInformation const&>(data); return inherited.getSpecification().areBooleanLiteralFormulasAllowed(); @@ -311,6 +319,13 @@ namespace storm { return result; } + boost::any FragmentChecker::visit(UnaryBooleanPathFormula const& f, boost::any const& data) const { + InheritedInformation const& inherited = boost::any_cast<InheritedInformation const&>(data); + bool result = inherited.getSpecification().areUnaryBooleanPathFormulasAllowed(); + result = result && boost::any_cast<bool>(f.getSubformula().accept(*this, data)); + return result; + } + boost::any FragmentChecker::visit(UntilFormula const& f, boost::any const& data) const { InheritedInformation const& inherited = boost::any_cast<InheritedInformation const&>(data); bool result = inherited.getSpecification().areUntilFormulasAllowed(); @@ -322,5 +337,14 @@ namespace storm { result = result && boost::any_cast<bool>(f.getRightSubformula().accept(*this, data)); return result; } + + boost::any FragmentChecker::visit(HOAPathFormula const& f, boost::any const& data) const { + InheritedInformation const& inherited = boost::any_cast<InheritedInformation const&>(data); + bool result = inherited.getSpecification().areHOAPathFormulasAllowed(); + for (auto& mapped : f.getAPMapping()) { + result = result && boost::any_cast<bool>(mapped.second->accept(*this, data)); + } + return result; + } } } diff --git a/src/storm/logic/FragmentChecker.h b/src/storm/logic/FragmentChecker.h index 0b0d179aa..3d9f50a2b 100644 --- a/src/storm/logic/FragmentChecker.h +++ b/src/storm/logic/FragmentChecker.h @@ -15,6 +15,7 @@ namespace storm { virtual boost::any visit(AtomicExpressionFormula const& f, boost::any const& data) const override; virtual boost::any visit(AtomicLabelFormula const& f, boost::any const& data) const override; virtual boost::any visit(BinaryBooleanStateFormula const& f, boost::any const& data) const override; + virtual boost::any visit(BinaryBooleanPathFormula const& f, boost::any const& data) const override; virtual boost::any visit(BooleanLiteralFormula const& f, boost::any const& data) const override; virtual boost::any visit(BoundedGloballyFormula const& f, boost::any const& data) const override; virtual boost::any visit(BoundedUntilFormula const& f, boost::any const& data) const override; @@ -34,7 +35,9 @@ namespace storm { virtual boost::any visit(RewardOperatorFormula const& f, boost::any const& data) const override; virtual boost::any visit(TotalRewardFormula const& f, boost::any const& data) const override; virtual boost::any visit(UnaryBooleanStateFormula const& f, boost::any const& data) const override; + virtual boost::any visit(UnaryBooleanPathFormula const& f, boost::any const& data) const override; virtual boost::any visit(UntilFormula const& f, boost::any const& data) const override; + virtual boost::any visit(HOAPathFormula const& f, boost::any const& data) const override; }; } diff --git a/src/storm/logic/FragmentSpecification.cpp b/src/storm/logic/FragmentSpecification.cpp index dc93f7f9c..b75dca240 100644 --- a/src/storm/logic/FragmentSpecification.cpp +++ b/src/storm/logic/FragmentSpecification.cpp @@ -45,6 +45,18 @@ namespace storm { return pctl; } + FragmentSpecification pctlstar() { + FragmentSpecification pctlstar = pctl(); + + pctlstar.setBinaryBooleanPathFormulasAllowed(true); + pctlstar.setUnaryBooleanPathFormulasAllowed(true); + pctlstar.setNestedOperatorsAllowed(true); + pctlstar.setNestedPathFormulasAllowed(true); + pctlstar.setHOAPathFormulasAllowed(true); + + return pctlstar; + } + FragmentSpecification flatPctl() { FragmentSpecification flatPctl = pctl(); @@ -53,6 +65,35 @@ namespace storm { return flatPctl; } + FragmentSpecification prctl() { + FragmentSpecification prctl = pctl(); + + prctl.setRewardOperatorsAllowed(true); + prctl.setCumulativeRewardFormulasAllowed(true); + prctl.setInstantaneousFormulasAllowed(true); + prctl.setReachabilityRewardFormulasAllowed(true); + prctl.setLongRunAverageOperatorsAllowed(true); + prctl.setStepBoundedCumulativeRewardFormulasAllowed(true); + prctl.setTimeBoundedCumulativeRewardFormulasAllowed(true); + + return prctl; + } + + FragmentSpecification prctlstar() { + FragmentSpecification prctlstar = pctlstar(); + + prctlstar.setRewardOperatorsAllowed(true); + prctlstar.setCumulativeRewardFormulasAllowed(true); + prctlstar.setInstantaneousFormulasAllowed(true); + prctlstar.setReachabilityRewardFormulasAllowed(true); + prctlstar.setLongRunAverageOperatorsAllowed(true); + prctlstar.setStepBoundedCumulativeRewardFormulasAllowed(true); + prctlstar.setTimeBoundedCumulativeRewardFormulasAllowed(true); + + return prctlstar; + + } + FragmentSpecification rpatl() { FragmentSpecification rpatl = propositional(); @@ -87,6 +128,21 @@ namespace storm { return prctl; } + FragmentSpecification prctlstar() { + FragmentSpecification prctlstar = pctlstar(); + + prctlstar.setRewardOperatorsAllowed(true); + prctlstar.setCumulativeRewardFormulasAllowed(true); + prctlstar.setInstantaneousFormulasAllowed(true); + prctlstar.setReachabilityRewardFormulasAllowed(true); + prctlstar.setLongRunAverageOperatorsAllowed(true); + prctlstar.setStepBoundedCumulativeRewardFormulasAllowed(true); + prctlstar.setTimeBoundedCumulativeRewardFormulasAllowed(true); + + return prctlstar; + + } + FragmentSpecification csl() { FragmentSpecification csl = pctl(); @@ -95,6 +151,18 @@ namespace storm { return csl; } + FragmentSpecification cslstar() { + FragmentSpecification cslstar = csl(); + + cslstar.setBinaryBooleanPathFormulasAllowed(true); + cslstar.setUnaryBooleanPathFormulasAllowed(true); + cslstar.setNestedOperatorsAllowed(true); + cslstar.setNestedPathFormulasAllowed(true); + cslstar.setHOAPathFormulasAllowed(true); + + return cslstar; + } + FragmentSpecification csrl() { FragmentSpecification csrl = csl(); @@ -108,6 +176,19 @@ namespace storm { return csrl; } + FragmentSpecification csrlstar() { + FragmentSpecification csrlstar = cslstar(); + + csrlstar.setRewardOperatorsAllowed(true); + csrlstar.setCumulativeRewardFormulasAllowed(true); + csrlstar.setInstantaneousFormulasAllowed(true); + csrlstar.setReachabilityRewardFormulasAllowed(true); + csrlstar.setLongRunAverageOperatorsAllowed(true); + csrlstar.setTimeBoundedCumulativeRewardFormulasAllowed(true); + + return csrlstar; + } + FragmentSpecification multiObjective() { FragmentSpecification multiObjective = propositional(); @@ -168,12 +249,15 @@ namespace storm { nextFormula = false; untilFormula = false; boundedUntilFormula = false; + hoaPathFormula = false; atomicExpressionFormula = false; atomicLabelFormula = false; booleanLiteralFormula = false; unaryBooleanStateFormula = false; binaryBooleanStateFormula = false; + unaryBooleanPathFormula = false; + binaryBooleanPathFormula = false; cumulativeRewardFormula = false; instantaneousRewardFormula = false; @@ -326,6 +410,15 @@ namespace storm { return *this; } + bool FragmentSpecification::areHOAPathFormulasAllowed() const { + return hoaPathFormula; + } + + FragmentSpecification& FragmentSpecification::setHOAPathFormulasAllowed(bool newValue) { + this->hoaPathFormula = newValue; + return *this; + } + bool FragmentSpecification::areAtomicExpressionFormulasAllowed() const { return atomicExpressionFormula; } @@ -362,6 +455,15 @@ namespace storm { return *this; } + bool FragmentSpecification::areUnaryBooleanPathFormulasAllowed() const { + return unaryBooleanPathFormula; + } + + FragmentSpecification& FragmentSpecification::setUnaryBooleanPathFormulasAllowed(bool newValue) { + this->unaryBooleanPathFormula = newValue; + return *this; + } + bool FragmentSpecification::areBinaryBooleanStateFormulasAllowed() const { return binaryBooleanStateFormula; } @@ -371,6 +473,15 @@ namespace storm { return *this; } + bool FragmentSpecification::areBinaryBooleanPathFormulasAllowed() const { + return binaryBooleanPathFormula; + } + + FragmentSpecification& FragmentSpecification::setBinaryBooleanPathFormulasAllowed(bool newValue) { + this->binaryBooleanPathFormula = newValue; + return *this; + } + bool FragmentSpecification::areCumulativeRewardFormulasAllowed() const { return cumulativeRewardFormula; } diff --git a/src/storm/logic/FragmentSpecification.h b/src/storm/logic/FragmentSpecification.h index f097e940f..0bbe0fb17 100644 --- a/src/storm/logic/FragmentSpecification.h +++ b/src/storm/logic/FragmentSpecification.h @@ -55,6 +55,9 @@ namespace storm { bool areBoundedGloballyFormulasAllowed() const; FragmentSpecification& setBoundedGloballyFormulasAllowed(bool newValue); + bool areHOAPathFormulasAllowed() const; + FragmentSpecification& setHOAPathFormulasAllowed(bool newValue); + bool areAtomicExpressionFormulasAllowed() const; FragmentSpecification& setAtomicExpressionFormulasAllowed(bool newValue); @@ -67,9 +70,15 @@ namespace storm { bool areUnaryBooleanStateFormulasAllowed() const; FragmentSpecification& setUnaryBooleanStateFormulasAllowed(bool newValue); + bool areUnaryBooleanPathFormulasAllowed() const; + FragmentSpecification& setUnaryBooleanPathFormulasAllowed(bool newValue); + bool areBinaryBooleanStateFormulasAllowed() const; FragmentSpecification& setBinaryBooleanStateFormulasAllowed(bool newValue); + bool areBinaryBooleanPathFormulasAllowed() const; + FragmentSpecification& setBinaryBooleanPathFormulasAllowed(bool newValue); + bool areCumulativeRewardFormulasAllowed() const; FragmentSpecification& setCumulativeRewardFormulasAllowed(bool newValue); @@ -180,12 +189,15 @@ namespace storm { bool untilFormula; bool boundedUntilFormula; bool boundedGloballyFormula; + bool hoaPathFormula; bool atomicExpressionFormula; bool atomicLabelFormula; bool booleanLiteralFormula; bool unaryBooleanStateFormula; bool binaryBooleanStateFormula; + bool unaryBooleanPathFormula; + bool binaryBooleanPathFormula; bool cumulativeRewardFormula; bool instantaneousRewardFormula; @@ -239,16 +251,27 @@ namespace storm { // rPATL for SMGs FragmentSpecification rpatl(); + // PCTL* + FragmentSpecification pctlstar(); // PCTL + cumulative, instantaneous, reachability and long-run rewards. FragmentSpecification prctl(); + // PCTL* + cumulative, instantaneous, reachability and long-run rewards. + FragmentSpecification prctlstar(); + // Regular CSL. FragmentSpecification csl(); + // CSL*, i.e., CSL with LTL path formulas. + FragmentSpecification cslstar(); + // CSL + cumulative, instantaneous, reachability and long-run rewards. FragmentSpecification csrl(); + // CSL* + cumulative, instantaneous, reachability and long-run rewards. + FragmentSpecification csrlstar(); + // Multi-Objective formulas. FragmentSpecification multiObjective(); diff --git a/src/storm/logic/GameFormula.cpp b/src/storm/logic/GameFormula.cpp index 8387e38fd..462631c62 100644 --- a/src/storm/logic/GameFormula.cpp +++ b/src/storm/logic/GameFormula.cpp @@ -32,9 +32,10 @@ namespace storm { return visitor.visit(*this, data); } - std::ostream& GameFormula::writeToStream(std::ostream& out) const { + std::ostream& GameFormula::writeToStream(std::ostream& out, bool /* allowParentheses */) const { + // No parenthesis necessary out << "<<" << coalition << ">> "; - this->getSubformula().writeToStream(out); + this->getSubformula().writeToStream(out, true); return out; } } diff --git a/src/storm/logic/GameFormula.h b/src/storm/logic/GameFormula.h index a14825cc5..1cadc5f62 100644 --- a/src/storm/logic/GameFormula.h +++ b/src/storm/logic/GameFormula.h @@ -24,7 +24,7 @@ namespace storm { virtual boost::any accept(FormulaVisitor const& visitor, boost::any const& data) const override; - virtual std::ostream& writeToStream(std::ostream& out) const override; + virtual std::ostream& writeToStream(std::ostream& out, bool allowParentheses = false) const override; private: PlayerCoalition coalition; diff --git a/src/storm/logic/GloballyFormula.cpp b/src/storm/logic/GloballyFormula.cpp index af429be92..cb9bac874 100644 --- a/src/storm/logic/GloballyFormula.cpp +++ b/src/storm/logic/GloballyFormula.cpp @@ -20,9 +20,15 @@ namespace storm { return visitor.visit(*this, data); } - std::ostream& GloballyFormula::writeToStream(std::ostream& out) const { + std::ostream& GloballyFormula::writeToStream(std::ostream& out, bool allowParentheses) const { + if (allowParentheses) { + out << "("; + } out << "G "; - this->getSubformula().writeToStream(out); + this->getSubformula().writeToStream(out, !this->getSubformula().isUnaryFormula()); + if (allowParentheses) { + out << ")"; + } return out; } } diff --git a/src/storm/logic/GloballyFormula.h b/src/storm/logic/GloballyFormula.h index 6c44ba2a1..3eaa834c3 100644 --- a/src/storm/logic/GloballyFormula.h +++ b/src/storm/logic/GloballyFormula.h @@ -18,7 +18,7 @@ namespace storm { virtual boost::any accept(FormulaVisitor const& visitor, boost::any const& data) const override; - virtual std::ostream& writeToStream(std::ostream& out) const override; + virtual std::ostream& writeToStream(std::ostream& out, bool allowParentheses = false) const override; }; } } diff --git a/src/storm/logic/HOAPathFormula.cpp b/src/storm/logic/HOAPathFormula.cpp new file mode 100644 index 000000000..39a0f60c9 --- /dev/null +++ b/src/storm/logic/HOAPathFormula.cpp @@ -0,0 +1,93 @@ +#include "storm/logic/HOAPathFormula.h" +#include "storm/logic/FormulaVisitor.h" + +#include "storm/utility/macros.h" +#include "storm/automata/DeterministicAutomaton.h" +#include "storm/exceptions/ExpressionEvaluationException.h" +#include "storm/exceptions/IllegalArgumentException.h" +#include "storm/exceptions/InvalidPropertyException.h" + +namespace storm { + namespace logic { + HOAPathFormula::HOAPathFormula(const std::string& automatonFile, FormulaContext context) : automatonFile(automatonFile), context(context) { + STORM_LOG_THROW(context == FormulaContext::Probability, storm::exceptions::InvalidPropertyException, "Invalid context for formula."); + } + + FormulaContext const& HOAPathFormula::getContext() const { + return context; + } + + const std::string& HOAPathFormula::getAutomatonFile() const { + return automatonFile; + } + + const HOAPathFormula::ap_to_formula_map &HOAPathFormula::getAPMapping() const { + return apToFormulaMap; + } + + void HOAPathFormula::addAPMapping(const std::string& ap, const std::shared_ptr<Formula const>& formula) { + STORM_LOG_THROW(apToFormulaMap.find(ap) == apToFormulaMap.end(), storm::exceptions::IllegalArgumentException, "HOA path formula: Mapping for atomic proposition \"" + ap + "\" already exists."); + apToFormulaMap[ap] = formula; + } + + bool HOAPathFormula::isProbabilityPathFormula() const { + return true; + } + + bool HOAPathFormula::isHOAPathFormula() const { + return true; + } + + bool HOAPathFormula::hasQuantitativeResult() const { + return true; + } + + bool HOAPathFormula::hasQualitativeResult() const { + return false; + } + + boost::any HOAPathFormula::accept(FormulaVisitor const& visitor, boost::any const& data) const { + return visitor.visit(*this, data); + } + + void HOAPathFormula::gatherAtomicExpressionFormulas(std::vector<std::shared_ptr<AtomicExpressionFormula const>>& atomicExpressionFormulas) const { + for (auto& mapped : getAPMapping()) { + mapped.second->gatherAtomicExpressionFormulas(atomicExpressionFormulas); + } + } + + void HOAPathFormula::gatherAtomicLabelFormulas(std::vector<std::shared_ptr<AtomicLabelFormula const>>& atomicLabelFormulas) const { + for (auto& mapped : getAPMapping()) { + mapped.second->gatherAtomicLabelFormulas(atomicLabelFormulas); + } + } + + void HOAPathFormula::gatherReferencedRewardModels(std::set<std::string>& referencedRewardModels) const { + for (auto& mapped : getAPMapping()) { + mapped.second->gatherReferencedRewardModels(referencedRewardModels); + } + } + + storm::automata::DeterministicAutomaton::ptr HOAPathFormula::readAutomaton() const { + std::ifstream in(automatonFile); + storm::automata::DeterministicAutomaton::ptr automaton = storm::automata::DeterministicAutomaton::parse(in); + for (auto& ap : automaton->getAPSet().getAPs()) { + STORM_LOG_THROW(apToFormulaMap.find(ap) != apToFormulaMap.end(), storm::exceptions::ExpressionEvaluationException, "For '" << automatonFile << "' HOA automaton, expression for atomic proposition '" << ap << "' is missing."); + } + return automaton; + } + + + std::ostream& HOAPathFormula::writeToStream(std::ostream& out, bool /* allowParentheses */ ) const { + // No parentheses necessary + out << "HOA: { "; + out << "\"" << automatonFile << "\""; + for (auto& mapping : apToFormulaMap) { + out << ", \"" << mapping.first << "\" -> "; + mapping.second->writeToStream(out); + } + out << " }"; + return out; + } + } +} diff --git a/src/storm/logic/HOAPathFormula.h b/src/storm/logic/HOAPathFormula.h new file mode 100644 index 000000000..53fcc1120 --- /dev/null +++ b/src/storm/logic/HOAPathFormula.h @@ -0,0 +1,55 @@ +#pragma once + +#include "storm/logic/PathFormula.h" +#include "storm/logic/FormulaContext.h" + +#include <map> +#include <memory> + +namespace storm { + namespace automata { + // fwd + class DeterministicAutomaton; + } + + namespace logic { + class HOAPathFormula : public PathFormula { + public: + typedef std::map<std::string, std::shared_ptr<Formula const>> ap_to_formula_map; + + HOAPathFormula(const std::string& automatonFile, FormulaContext context = FormulaContext::Probability); + + virtual ~HOAPathFormula() { + // Intentionally left empty. + } + + FormulaContext const& getContext() const; + const std::string& getAutomatonFile() const; + const ap_to_formula_map &getAPMapping() const; + + void addAPMapping(const std::string& ap, const std::shared_ptr<Formula const>& formula); + + virtual bool isHOAPathFormula() const override; + virtual bool isProbabilityPathFormula() const override; + virtual bool hasQuantitativeResult() const override; + virtual bool hasQualitativeResult() const override; + + virtual boost::any accept(FormulaVisitor const& visitor, boost::any const& data) const override; + + virtual void gatherAtomicExpressionFormulas(std::vector<std::shared_ptr<AtomicExpressionFormula const>>& atomicExpressionFormulas) const override; + virtual void gatherAtomicLabelFormulas(std::vector<std::shared_ptr<AtomicLabelFormula const>>& atomicLabelFormulas) const override; + virtual void gatherReferencedRewardModels(std::set<std::string>& referencedRewardModels) const override; + + virtual std::ostream& writeToStream(std::ostream& out, bool allowParentheses = false) const override; + + std::shared_ptr<storm::automata::DeterministicAutomaton> readAutomaton() const; + + private: + std::string automatonFile; + ap_to_formula_map apToFormulaMap; + + FormulaContext context; + }; + } +} + diff --git a/src/storm/logic/InstantaneousRewardFormula.cpp b/src/storm/logic/InstantaneousRewardFormula.cpp index 1ed2c1f66..c5e615515 100644 --- a/src/storm/logic/InstantaneousRewardFormula.cpp +++ b/src/storm/logic/InstantaneousRewardFormula.cpp @@ -68,7 +68,8 @@ namespace storm { STORM_LOG_THROW(!bound.containsVariables(), storm::exceptions::InvalidOperationException, "Cannot evaluate time-instant '" << bound << "' as it contains undefined constants."); } - std::ostream& InstantaneousRewardFormula::writeToStream(std::ostream& out) const { + std::ostream& InstantaneousRewardFormula::writeToStream(std::ostream& out, bool /* allowParentheses */) const { + // No parentheses necessary. out << "I=" << this->getBound(); return out; } diff --git a/src/storm/logic/InstantaneousRewardFormula.h b/src/storm/logic/InstantaneousRewardFormula.h index 69e5dd38f..6d6b440f6 100644 --- a/src/storm/logic/InstantaneousRewardFormula.h +++ b/src/storm/logic/InstantaneousRewardFormula.h @@ -22,7 +22,7 @@ namespace storm { virtual boost::any accept(FormulaVisitor const& visitor, boost::any const& data) const override; - virtual std::ostream& writeToStream(std::ostream& out) const override; + virtual std::ostream& writeToStream(std::ostream& out, bool allowParentheses = false) const override; TimeBoundType const& getTimeBoundType() const; bool isStepBounded() const; diff --git a/src/storm/logic/LiftableTransitionRewardsVisitor.cpp b/src/storm/logic/LiftableTransitionRewardsVisitor.cpp index a61dccf7c..2ead1325b 100644 --- a/src/storm/logic/LiftableTransitionRewardsVisitor.cpp +++ b/src/storm/logic/LiftableTransitionRewardsVisitor.cpp @@ -22,8 +22,12 @@ namespace storm { return true; } - boost::any LiftableTransitionRewardsVisitor::visit(BinaryBooleanStateFormula const&, boost::any const&) const { - return true; + boost::any LiftableTransitionRewardsVisitor::visit(BinaryBooleanStateFormula const& f, boost::any const& data) const { + return boost::any_cast<bool>(f.getLeftSubformula().accept(*this, data)) && boost::any_cast<bool>(f.getRightSubformula().accept(*this, data)); + } + + boost::any LiftableTransitionRewardsVisitor::visit(BinaryBooleanPathFormula const& f, boost::any const& data) const { + return boost::any_cast<bool>(f.getLeftSubformula().accept(*this, data)) && boost::any_cast<bool>(f.getRightSubformula().accept(*this, data)); } boost::any LiftableTransitionRewardsVisitor::visit(BooleanLiteralFormula const&, boost::any const&) const { @@ -143,10 +147,23 @@ namespace storm { return f.getSubformula().accept(*this, data); } + boost::any LiftableTransitionRewardsVisitor::visit(UnaryBooleanPathFormula const& f, boost::any const& data) const { + return f.getSubformula().accept(*this, data); + } + boost::any LiftableTransitionRewardsVisitor::visit(UntilFormula const& f, boost::any const& data) const { return boost::any_cast<bool>(f.getLeftSubformula().accept(*this, data)) && boost::any_cast<bool>(f.getRightSubformula().accept(*this)); } + boost::any LiftableTransitionRewardsVisitor::visit(HOAPathFormula const& f, boost::any const& data) const { + for (auto const& ap : f.getAPMapping()) { + if (!boost::any_cast<bool>(ap.second->accept(*this, data))) { + return false; + } + } + return true; + } + bool LiftableTransitionRewardsVisitor::rewardModelHasTransitionRewards(std::string const& rewardModelName) const { if (symbolicModelDescription.hasModel()) { if (symbolicModelDescription.isJaniModel()) { diff --git a/src/storm/logic/LiftableTransitionRewardsVisitor.h b/src/storm/logic/LiftableTransitionRewardsVisitor.h index 52a791237..bf2b6a4f5 100644 --- a/src/storm/logic/LiftableTransitionRewardsVisitor.h +++ b/src/storm/logic/LiftableTransitionRewardsVisitor.h @@ -21,6 +21,7 @@ namespace storm { virtual boost::any visit(AtomicExpressionFormula const& f, boost::any const& data) const override; virtual boost::any visit(AtomicLabelFormula const& f, boost::any const& data) const override; virtual boost::any visit(BinaryBooleanStateFormula const& f, boost::any const& data) const override; + virtual boost::any visit(BinaryBooleanPathFormula const& f, boost::any const& data) const override; virtual boost::any visit(BooleanLiteralFormula const& f, boost::any const& data) const override; virtual boost::any visit(BoundedGloballyFormula const& f, boost::any const& data) const override; virtual boost::any visit(BoundedUntilFormula const& f, boost::any const& data) const override; @@ -40,7 +41,9 @@ namespace storm { virtual boost::any visit(RewardOperatorFormula const& f, boost::any const& data) const override; virtual boost::any visit(TotalRewardFormula const& f, boost::any const& data) const override; virtual boost::any visit(UnaryBooleanStateFormula const& f, boost::any const& data) const override; + virtual boost::any visit(UnaryBooleanPathFormula const& f, boost::any const& data) const override; virtual boost::any visit(UntilFormula const& f, boost::any const& data) const override; + virtual boost::any visit(HOAPathFormula const& f, boost::any const& data) const override; private: storm::storage::SymbolicModelDescription const& symbolicModelDescription; diff --git a/src/storm/logic/LongRunAverageOperatorFormula.cpp b/src/storm/logic/LongRunAverageOperatorFormula.cpp index 6f4c061cb..24997ed73 100644 --- a/src/storm/logic/LongRunAverageOperatorFormula.cpp +++ b/src/storm/logic/LongRunAverageOperatorFormula.cpp @@ -18,10 +18,11 @@ namespace storm { boost::any LongRunAverageOperatorFormula::accept(FormulaVisitor const& visitor, boost::any const& data) const { return visitor.visit(*this, data); } - - std::ostream& LongRunAverageOperatorFormula::writeToStream(std::ostream& out) const { + + std::ostream& LongRunAverageOperatorFormula::writeToStream(std::ostream& out, bool /* allowParentheses */) const { + // No parentheses necessary out << "LRA"; - OperatorFormula::writeToStream(out); + OperatorFormula::writeToStream(out, false); return out; } } diff --git a/src/storm/logic/LongRunAverageOperatorFormula.h b/src/storm/logic/LongRunAverageOperatorFormula.h index 9cc156408..4774537b9 100644 --- a/src/storm/logic/LongRunAverageOperatorFormula.h +++ b/src/storm/logic/LongRunAverageOperatorFormula.h @@ -17,7 +17,7 @@ namespace storm { virtual boost::any accept(FormulaVisitor const& visitor, boost::any const& data) const override; - virtual std::ostream& writeToStream(std::ostream& out) const override; + virtual std::ostream& writeToStream(std::ostream& out, bool allowParentheses = false) const override; }; } } diff --git a/src/storm/logic/LongRunAverageRewardFormula.cpp b/src/storm/logic/LongRunAverageRewardFormula.cpp index 294c8de95..4dd7a2a33 100644 --- a/src/storm/logic/LongRunAverageRewardFormula.cpp +++ b/src/storm/logic/LongRunAverageRewardFormula.cpp @@ -32,7 +32,8 @@ namespace storm { return visitor.visit(*this, data); } - std::ostream& LongRunAverageRewardFormula::writeToStream(std::ostream& out) const { + std::ostream& LongRunAverageRewardFormula::writeToStream(std::ostream& out, bool /* allowParentheses */) const { + // No parentheses necessary out << "LRA"; if (hasRewardAccumulation()) { out << "[" << getRewardAccumulation() << "]"; diff --git a/src/storm/logic/LongRunAverageRewardFormula.h b/src/storm/logic/LongRunAverageRewardFormula.h index 45bbe3de5..03b21b761 100644 --- a/src/storm/logic/LongRunAverageRewardFormula.h +++ b/src/storm/logic/LongRunAverageRewardFormula.h @@ -23,7 +23,7 @@ namespace storm { virtual boost::any accept(FormulaVisitor const& visitor, boost::any const& data) const override; - virtual std::ostream& writeToStream(std::ostream& out) const override; + virtual std::ostream& writeToStream(std::ostream& out, bool allowParentheses = false) const override; private: boost::optional<RewardAccumulation> rewardAccumulation; diff --git a/src/storm/logic/MultiObjectiveFormula.cpp b/src/storm/logic/MultiObjectiveFormula.cpp index 0ecf795b0..edae6a1ea 100644 --- a/src/storm/logic/MultiObjectiveFormula.cpp +++ b/src/storm/logic/MultiObjectiveFormula.cpp @@ -84,7 +84,8 @@ namespace storm { } } - std::ostream& MultiObjectiveFormula::writeToStream(std::ostream &out) const { + std::ostream& MultiObjectiveFormula::writeToStream(std::ostream &out, bool /* allowParentheses */) const { + // No parentheses necessary out << "multi("; for(uint_fast64_t index = 0; index < this->getNumberOfSubformulas(); ++index){ if(index>0){ diff --git a/src/storm/logic/MultiObjectiveFormula.h b/src/storm/logic/MultiObjectiveFormula.h index 9ec5204d9..82e34807e 100644 --- a/src/storm/logic/MultiObjectiveFormula.h +++ b/src/storm/logic/MultiObjectiveFormula.h @@ -1,11 +1,11 @@ #ifndef STORM_LOGIC_MULTIOBJECTIVEFORMULA_H_ #define STORM_LOGIC_MULTIOBJECTIVEFORMULA_H_ -#include "storm/logic/Formula.h" +#include "storm/logic/StateFormula.h" namespace storm { namespace logic { - class MultiObjectiveFormula : public Formula { + class MultiObjectiveFormula : public StateFormula { public: MultiObjectiveFormula(std::vector<std::shared_ptr<Formula const>> const& subformulas); @@ -27,7 +27,7 @@ namespace storm { virtual void gatherAtomicLabelFormulas(std::vector<std::shared_ptr<AtomicLabelFormula const>>& atomicLabelFormulas) const override; virtual void gatherReferencedRewardModels(std::set<std::string>& referencedRewardModels) const override; - virtual std::ostream& writeToStream(std::ostream& out) const override; + virtual std::ostream& writeToStream(std::ostream& out, bool allowParentheses = false) const override; private: std::vector<std::shared_ptr<Formula const>> subformulas; }; diff --git a/src/storm/logic/NextFormula.cpp b/src/storm/logic/NextFormula.cpp index f38df2ac0..c99d4d35c 100644 --- a/src/storm/logic/NextFormula.cpp +++ b/src/storm/logic/NextFormula.cpp @@ -20,9 +20,15 @@ namespace storm { return visitor.visit(*this, data); } - std::ostream& NextFormula::writeToStream(std::ostream& out) const { + std::ostream& NextFormula::writeToStream(std::ostream& out, bool allowParentheses) const { + if (allowParentheses) { + out << "("; + } out << "X "; - this->getSubformula().writeToStream(out); + this->getSubformula().writeToStream(out, !this->getSubformula().isUnaryFormula()); + if (allowParentheses) { + out << ")"; + } return out; } } diff --git a/src/storm/logic/NextFormula.h b/src/storm/logic/NextFormula.h index 2083fee98..e67010de0 100644 --- a/src/storm/logic/NextFormula.h +++ b/src/storm/logic/NextFormula.h @@ -18,7 +18,7 @@ namespace storm { virtual boost::any accept(FormulaVisitor const& visitor, boost::any const& data) const override; - virtual std::ostream& writeToStream(std::ostream& out) const override; + virtual std::ostream& writeToStream(std::ostream& out, bool allowParentheses = false) const override; }; } } diff --git a/src/storm/logic/OperatorFormula.cpp b/src/storm/logic/OperatorFormula.cpp index 890d5476c..7bf7bd55f 100644 --- a/src/storm/logic/OperatorFormula.cpp +++ b/src/storm/logic/OperatorFormula.cpp @@ -104,7 +104,8 @@ namespace storm { } } - std::ostream& OperatorFormula::writeToStream(std::ostream& out) const { + std::ostream& OperatorFormula::writeToStream(std::ostream& out, bool /* allowParentheses */) const { + // No parentheses necessary if (hasOptimalityType()) { out << (getOptimalityType() == OptimizationDirection::Minimize ? "min" : "max"); } diff --git a/src/storm/logic/OperatorFormula.h b/src/storm/logic/OperatorFormula.h index c4d3067fb..807661aa2 100644 --- a/src/storm/logic/OperatorFormula.h +++ b/src/storm/logic/OperatorFormula.h @@ -56,7 +56,7 @@ namespace storm { virtual void gatherUsedVariables(std::set<storm::expressions::Variable>& usedVariables) const override; - virtual std::ostream& writeToStream(std::ostream& out) const override; + virtual std::ostream& writeToStream(std::ostream& out, bool allowParentheses = false) const override; protected: OperatorInformation operatorInformation; diff --git a/src/storm/logic/ProbabilityOperatorFormula.cpp b/src/storm/logic/ProbabilityOperatorFormula.cpp index 0c36a07a5..25af22871 100644 --- a/src/storm/logic/ProbabilityOperatorFormula.cpp +++ b/src/storm/logic/ProbabilityOperatorFormula.cpp @@ -19,9 +19,10 @@ namespace storm { return visitor.visit(*this, data); } - std::ostream& ProbabilityOperatorFormula::writeToStream(std::ostream& out) const { + std::ostream& ProbabilityOperatorFormula::writeToStream(std::ostream& out, bool /* allowParentheses */) const { + // No parentheses necessary out << "P"; - OperatorFormula::writeToStream(out); + OperatorFormula::writeToStream(out, false); return out; } } diff --git a/src/storm/logic/ProbabilityOperatorFormula.h b/src/storm/logic/ProbabilityOperatorFormula.h index 37950b3cb..92c8a3e87 100644 --- a/src/storm/logic/ProbabilityOperatorFormula.h +++ b/src/storm/logic/ProbabilityOperatorFormula.h @@ -17,7 +17,7 @@ namespace storm { virtual boost::any accept(FormulaVisitor const& visitor, boost::any const& data) const override; - virtual std::ostream& writeToStream(std::ostream& out) const override; + virtual std::ostream& writeToStream(std::ostream& out, bool allowParentheses = false) const override; }; } } diff --git a/src/storm/logic/QuantileFormula.cpp b/src/storm/logic/QuantileFormula.cpp index 4e1e21aef..679d14d99 100644 --- a/src/storm/logic/QuantileFormula.cpp +++ b/src/storm/logic/QuantileFormula.cpp @@ -73,7 +73,8 @@ namespace storm { subformula->gatherReferencedRewardModels(referencedRewardModels); } - std::ostream& QuantileFormula::writeToStream(std::ostream& out) const { + std::ostream& QuantileFormula::writeToStream(std::ostream& out, bool /* allowParentheses */) const { + // No parentheses necessary out << "quantile("; for (auto const& bv : boundVariables) { out << bv.getName() << ", "; diff --git a/src/storm/logic/QuantileFormula.h b/src/storm/logic/QuantileFormula.h index 8765013a7..16fbaf408 100644 --- a/src/storm/logic/QuantileFormula.h +++ b/src/storm/logic/QuantileFormula.h @@ -1,10 +1,10 @@ #pragma once -#include "storm/logic/Formula.h" +#include "storm/logic/StateFormula.h" namespace storm { namespace logic { - class QuantileFormula : public Formula { + class QuantileFormula : public StateFormula { public: QuantileFormula(std::vector<storm::expressions::Variable> const& boundVariables, std::shared_ptr<Formula const> subformula); @@ -29,7 +29,7 @@ namespace storm { virtual void gatherAtomicLabelFormulas(std::vector<std::shared_ptr<AtomicLabelFormula const>>& atomicLabelFormulas) const override; virtual void gatherReferencedRewardModels(std::set<std::string>& referencedRewardModels) const override; - virtual std::ostream& writeToStream(std::ostream& out) const override; + virtual std::ostream& writeToStream(std::ostream& out, bool allowParentheses = false) const override; private: std::vector<storm::expressions::Variable> boundVariables; std::shared_ptr<Formula const> subformula; diff --git a/src/storm/logic/RewardOperatorFormula.cpp b/src/storm/logic/RewardOperatorFormula.cpp index 28d1678e5..bdceca897 100644 --- a/src/storm/logic/RewardOperatorFormula.cpp +++ b/src/storm/logic/RewardOperatorFormula.cpp @@ -44,7 +44,8 @@ namespace storm { return rewardMeasureType; } - std::ostream& RewardOperatorFormula::writeToStream(std::ostream& out) const { + std::ostream& RewardOperatorFormula::writeToStream(std::ostream& out, bool /* allowParentheses */) const { + // No parentheses necessary out << "R"; out << "[" << rewardMeasureType << "]"; if (this->hasRewardModelName()) { diff --git a/src/storm/logic/RewardOperatorFormula.h b/src/storm/logic/RewardOperatorFormula.h index af9a09056..77564714b 100644 --- a/src/storm/logic/RewardOperatorFormula.h +++ b/src/storm/logic/RewardOperatorFormula.h @@ -20,7 +20,7 @@ namespace storm { virtual void gatherReferencedRewardModels(std::set<std::string>& referencedRewardModels) const override; - virtual std::ostream& writeToStream(std::ostream& out) const override; + virtual std::ostream& writeToStream(std::ostream& out, bool allowParentheses = false) const override; /*! * Retrieves whether the reward model refers to a specific reward model. diff --git a/src/storm/logic/StateFormula.cpp b/src/storm/logic/StateFormula.cpp index 688d9f8a9..d6b9b6ca5 100644 --- a/src/storm/logic/StateFormula.cpp +++ b/src/storm/logic/StateFormula.cpp @@ -5,5 +5,12 @@ namespace storm { bool StateFormula::isStateFormula() const { return true; } + + + bool StateFormula::isProbabilityPathFormula() const { + // a single state formula can be seen as a path formula as well + return true; + } + } } diff --git a/src/storm/logic/StateFormula.h b/src/storm/logic/StateFormula.h index 18f745a8b..b7e82d3ae 100644 --- a/src/storm/logic/StateFormula.h +++ b/src/storm/logic/StateFormula.h @@ -12,6 +12,9 @@ namespace storm { }; virtual bool isStateFormula() const override; + + virtual bool isProbabilityPathFormula() const override; + }; } } diff --git a/src/storm/logic/TimeOperatorFormula.cpp b/src/storm/logic/TimeOperatorFormula.cpp index f32568cdc..5fe746a12 100644 --- a/src/storm/logic/TimeOperatorFormula.cpp +++ b/src/storm/logic/TimeOperatorFormula.cpp @@ -24,7 +24,8 @@ namespace storm { return rewardMeasureType; } - std::ostream& TimeOperatorFormula::writeToStream(std::ostream& out) const { + std::ostream& TimeOperatorFormula::writeToStream(std::ostream& out, bool /* allowParentheses */) const { + // No parentheses necessary out << "T"; out << "[" << rewardMeasureType << "]"; OperatorFormula::writeToStream(out); diff --git a/src/storm/logic/TimeOperatorFormula.h b/src/storm/logic/TimeOperatorFormula.h index 080cec30d..0a52cb879 100644 --- a/src/storm/logic/TimeOperatorFormula.h +++ b/src/storm/logic/TimeOperatorFormula.h @@ -19,7 +19,7 @@ namespace storm { virtual boost::any accept(FormulaVisitor const& visitor, boost::any const& data) const override; - virtual std::ostream& writeToStream(std::ostream& out) const override; + virtual std::ostream& writeToStream(std::ostream& out, bool allowParentheses = false) const override; /*! * Retrieves the measure type of the operator. diff --git a/src/storm/logic/ToExpressionVisitor.cpp b/src/storm/logic/ToExpressionVisitor.cpp index 1e6852d84..ff1025fca 100644 --- a/src/storm/logic/ToExpressionVisitor.cpp +++ b/src/storm/logic/ToExpressionVisitor.cpp @@ -37,6 +37,10 @@ namespace storm { return boost::any(); } + boost::any ToExpressionVisitor::visit(BinaryBooleanPathFormula const& f, boost::any const& data) const { + STORM_LOG_THROW(false, storm::exceptions::InvalidOperationException, "Cannot assemble expression from formula that contains illegal elements."); + } + boost::any ToExpressionVisitor::visit(BooleanLiteralFormula const& f, boost::any const& data) const { storm::expressions::Expression result; if (f.isTrueFormula()) { @@ -124,10 +128,17 @@ namespace storm { } return boost::any(); } - + + boost::any ToExpressionVisitor::visit(UnaryBooleanPathFormula const& f, boost::any const& data) const { + STORM_LOG_THROW(false, storm::exceptions::InvalidOperationException, "Cannot assemble expression from formula that contains illegal elements."); + } + boost::any ToExpressionVisitor::visit(UntilFormula const&, boost::any const&) const { STORM_LOG_THROW(false, storm::exceptions::InvalidOperationException, "Cannot assemble expression from formula that contains illegal elements."); } + boost::any ToExpressionVisitor::visit(HOAPathFormula const&, boost::any const&) const { + STORM_LOG_THROW(false, storm::exceptions::InvalidOperationException, "Cannot assemble expression from formula that contains illegal elements."); + } } } diff --git a/src/storm/logic/ToExpressionVisitor.h b/src/storm/logic/ToExpressionVisitor.h index b68b5c438..a97a9a4b0 100644 --- a/src/storm/logic/ToExpressionVisitor.h +++ b/src/storm/logic/ToExpressionVisitor.h @@ -15,6 +15,7 @@ namespace storm { virtual boost::any visit(AtomicExpressionFormula const& f, boost::any const& data) const override; virtual boost::any visit(AtomicLabelFormula const& f, boost::any const& data) const override; virtual boost::any visit(BinaryBooleanStateFormula const& f, boost::any const& data) const override; + virtual boost::any visit(BinaryBooleanPathFormula const& f, boost::any const& data) const override; virtual boost::any visit(BooleanLiteralFormula const& f, boost::any const& data) const override; virtual boost::any visit(BoundedGloballyFormula const& f, boost::any const& data) const override; virtual boost::any visit(BoundedUntilFormula const& f, boost::any const& data) const override; @@ -34,7 +35,9 @@ namespace storm { virtual boost::any visit(RewardOperatorFormula const& f, boost::any const& data) const override; virtual boost::any visit(TotalRewardFormula const& f, boost::any const& data) const override; virtual boost::any visit(UnaryBooleanStateFormula const& f, boost::any const& data) const override; + virtual boost::any visit(UnaryBooleanPathFormula const& f, boost::any const& data) const override; virtual boost::any visit(UntilFormula const& f, boost::any const& data) const override; + virtual boost::any visit(HOAPathFormula const& f, boost::any const& data) const override; }; } diff --git a/src/storm/logic/ToPrefixStringVisitor.cpp b/src/storm/logic/ToPrefixStringVisitor.cpp new file mode 100644 index 000000000..300a53d97 --- /dev/null +++ b/src/storm/logic/ToPrefixStringVisitor.cpp @@ -0,0 +1,159 @@ +#include "storm/logic/ToPrefixStringVisitor.h" + +#include "storm/logic/Formulas.h" + +#include "storm/utility/macros.h" +#include "storm/exceptions/InvalidOperationException.h" + +namespace storm { + namespace logic { + + std::string ToPrefixStringVisitor::toPrefixString(Formula const& f) const { + boost::any result = f.accept(*this, boost::any()); + return boost::any_cast<std::string>(result); + } + + boost::any ToPrefixStringVisitor::visit(AtomicExpressionFormula const&, boost::any const&) const { + STORM_LOG_THROW(false, storm::exceptions::InvalidOperationException, "Can not convert to prefix string"); + } + + boost::any ToPrefixStringVisitor::visit(AtomicLabelFormula const& f, boost::any const&) const { + return std::string("\"" + f.getLabel() + "\""); + } + + boost::any ToPrefixStringVisitor::visit(BinaryBooleanStateFormula const& f, boost::any const& data) const { + std::string left = boost::any_cast<std::string>(f.getLeftSubformula().accept(*this, data)); + std::string right = boost::any_cast<std::string>(f.getRightSubformula().accept(*this, data)); + switch (f.getOperator()) { + case BinaryBooleanStateFormula::OperatorType::And: + return std::string("& ") + left + " " + right; + break; + case BinaryBooleanStateFormula::OperatorType::Or: + return std::string("| ") + left + " " + right; + break; + } + return boost::any(); + } + + boost::any ToPrefixStringVisitor::visit(BinaryBooleanPathFormula const& f, boost::any const& data) const { + std::string left = boost::any_cast<std::string>(f.getLeftSubformula().accept(*this, data)); + std::string right = boost::any_cast<std::string>(f.getRightSubformula().accept(*this, data)); + switch (f.getOperator()) { + case BinaryBooleanPathFormula::OperatorType::And: + return std::string("& ") + left + " " + right; + break; + case BinaryBooleanPathFormula::OperatorType::Or: + return std::string("| ") + left + " " + right; + break; + } + return boost::any(); + } + + boost::any ToPrefixStringVisitor::visit(BooleanLiteralFormula const& f, boost::any const&) const { + storm::expressions::Expression result; + if (f.isTrueFormula()) { + return std::string("t"); + } else { + return std::string("f"); + } + return result; + } + + boost::any ToPrefixStringVisitor::visit(BoundedUntilFormula const&, boost::any const&) const { + STORM_LOG_THROW(false, storm::exceptions::InvalidOperationException, "Can not convert to prefix string"); + } + + boost::any ToPrefixStringVisitor::visit(ConditionalFormula const&, boost::any const&) const { + STORM_LOG_THROW(false, storm::exceptions::InvalidOperationException, "Can not convert to prefix string"); + } + + boost::any ToPrefixStringVisitor::visit(CumulativeRewardFormula const&, boost::any const&) const { + STORM_LOG_THROW(false, storm::exceptions::InvalidOperationException, "Can not convert to prefix string"); + } + + boost::any ToPrefixStringVisitor::visit(EventuallyFormula const& f, boost::any const& data) const { + std::string subexpression = boost::any_cast<std::string>(f.getSubformula().accept(*this, data)); + return std::string("F ") + subexpression; + } + + boost::any ToPrefixStringVisitor::visit(TimeOperatorFormula const&, boost::any const&) const { + STORM_LOG_THROW(false, storm::exceptions::InvalidOperationException, "Can not convert to prefix string"); + } + + boost::any ToPrefixStringVisitor::visit(GloballyFormula const& f, boost::any const& data) const { + std::string subexpression = boost::any_cast<std::string>(f.getSubformula().accept(*this, data)); + return std::string("G ") + subexpression; + } + + boost::any ToPrefixStringVisitor::visit(GameFormula const&, boost::any const&) const { + STORM_LOG_THROW(false, storm::exceptions::InvalidOperationException, "Can not convert to prefix string"); + } + + boost::any ToPrefixStringVisitor::visit(InstantaneousRewardFormula const&, boost::any const&) const { + STORM_LOG_THROW(false, storm::exceptions::InvalidOperationException, "Can not convert to prefix string"); + } + + boost::any ToPrefixStringVisitor::visit(LongRunAverageOperatorFormula const&, boost::any const&) const { + STORM_LOG_THROW(false, storm::exceptions::InvalidOperationException, "Can not convert to prefix string"); + } + + boost::any ToPrefixStringVisitor::visit(LongRunAverageRewardFormula const&, boost::any const&) const { + STORM_LOG_THROW(false, storm::exceptions::InvalidOperationException, "Can not convert to prefix string"); + } + + boost::any ToPrefixStringVisitor::visit(MultiObjectiveFormula const&, boost::any const&) const { + STORM_LOG_THROW(false, storm::exceptions::InvalidOperationException, "Can not convert to prefix string"); + } + + boost::any ToPrefixStringVisitor::visit(QuantileFormula const&, boost::any const&) const { + STORM_LOG_THROW(false, storm::exceptions::InvalidOperationException, "Can not convert to prefix string"); + } + + boost::any ToPrefixStringVisitor::visit(NextFormula const& f, boost::any const& data) const { + std::string subexpression = boost::any_cast<std::string>(f.getSubformula().accept(*this, data)); + return std::string("X ") + subexpression; + } + + boost::any ToPrefixStringVisitor::visit(ProbabilityOperatorFormula const&, boost::any const&) const { + STORM_LOG_THROW(false, storm::exceptions::InvalidOperationException, "Can not convert to prefix string"); + } + + boost::any ToPrefixStringVisitor::visit(RewardOperatorFormula const&, boost::any const&) const { + STORM_LOG_THROW(false, storm::exceptions::InvalidOperationException, "Can not convert to prefix string"); + } + + boost::any ToPrefixStringVisitor::visit(TotalRewardFormula const&, boost::any const&) const { + STORM_LOG_THROW(false, storm::exceptions::InvalidOperationException, "Can not convert to prefix string"); + } + + boost::any ToPrefixStringVisitor::visit(UnaryBooleanStateFormula const& f, boost::any const& data) const { + std::string subexpression = boost::any_cast<std::string>(f.getSubformula().accept(*this, data)); + switch (f.getOperator()) { + case UnaryBooleanStateFormula::OperatorType::Not: + return std::string("! ") + subexpression; + break; + } + return boost::any(); + } + + boost::any ToPrefixStringVisitor::visit(UnaryBooleanPathFormula const& f, boost::any const& data) const { + std::string subexpression = boost::any_cast<std::string>(f.getSubformula().accept(*this, data)); + switch (f.getOperator()) { + case UnaryBooleanPathFormula::OperatorType::Not: + return std::string("! ") + subexpression; + break; + } + return boost::any(); + } + + boost::any ToPrefixStringVisitor::visit(UntilFormula const& f, boost::any const& data) const { + std::string left = boost::any_cast<std::string>(f.getLeftSubformula().accept(*this, data)); + std::string right = boost::any_cast<std::string>(f.getRightSubformula().accept(*this, data)); + return std::string("U ") + left + " " + right; + } + + boost::any ToPrefixStringVisitor::visit(HOAPathFormula const&, boost::any const&) const { + STORM_LOG_THROW(false, storm::exceptions::InvalidOperationException, "Can not convert to prefix string"); + } + } +} diff --git a/src/storm/logic/ToPrefixStringVisitor.h b/src/storm/logic/ToPrefixStringVisitor.h new file mode 100644 index 000000000..38a786458 --- /dev/null +++ b/src/storm/logic/ToPrefixStringVisitor.h @@ -0,0 +1,43 @@ +#pragma once + +#include "storm/logic/FormulaVisitor.h" + +#include <string> + +namespace storm { + namespace logic { + + class ToPrefixStringVisitor : public FormulaVisitor { + public: + std::string toPrefixString(Formula const& f) const; + + virtual boost::any visit(AtomicExpressionFormula const& f, boost::any const& data) const override; + virtual boost::any visit(AtomicLabelFormula const& f, boost::any const& data) const override; + virtual boost::any visit(BinaryBooleanStateFormula const& f, boost::any const& data) const override; + virtual boost::any visit(BinaryBooleanPathFormula const& f, boost::any const& data) const override; + virtual boost::any visit(BooleanLiteralFormula const& f, boost::any const& data) const override; + virtual boost::any visit(BoundedGloballyFormula const& f, boost::any const& data) const override; + virtual boost::any visit(BoundedUntilFormula const& f, boost::any const& data) const override; + virtual boost::any visit(ConditionalFormula const& f, boost::any const& data) const override; + virtual boost::any visit(CumulativeRewardFormula const& f, boost::any const& data) const override; + virtual boost::any visit(EventuallyFormula const& f, boost::any const& data) const override; + virtual boost::any visit(TimeOperatorFormula const& f, boost::any const& data) const override; + virtual boost::any visit(GloballyFormula const& f, boost::any const& data) const override; + virtual boost::any visit(GameFormula const& f, boost::any const& data) const override; + virtual boost::any visit(InstantaneousRewardFormula const& f, boost::any const& data) const override; + virtual boost::any visit(LongRunAverageOperatorFormula const& f, boost::any const& data) const override; + virtual boost::any visit(LongRunAverageRewardFormula const& f, boost::any const& data) const override; + virtual boost::any visit(MultiObjectiveFormula const& f, boost::any const& data) const override; + virtual boost::any visit(QuantileFormula const& f, boost::any const& data) const override; + virtual boost::any visit(NextFormula const& f, boost::any const& data) const override; + virtual boost::any visit(ProbabilityOperatorFormula const& f, boost::any const& data) const override; + virtual boost::any visit(RewardOperatorFormula const& f, boost::any const& data) const override; + virtual boost::any visit(TotalRewardFormula const& f, boost::any const& data) const override; + virtual boost::any visit(UnaryBooleanStateFormula const& f, boost::any const& data) const override; + virtual boost::any visit(UnaryBooleanPathFormula const& f, boost::any const& data) const override; + virtual boost::any visit(UntilFormula const& f, boost::any const& data) const override; + virtual boost::any visit(HOAPathFormula const& f, boost::any const& data) const override; + }; + + } +} diff --git a/src/storm/logic/TotalRewardFormula.cpp b/src/storm/logic/TotalRewardFormula.cpp index fb6f60873..8bd8e26eb 100644 --- a/src/storm/logic/TotalRewardFormula.cpp +++ b/src/storm/logic/TotalRewardFormula.cpp @@ -32,7 +32,8 @@ namespace storm { return visitor.visit(*this, data); } - std::ostream& TotalRewardFormula::writeToStream(std::ostream& out) const { + std::ostream& TotalRewardFormula::writeToStream(std::ostream& out, bool /* allowParentheses */) const { + // No parentheses necessary out << "C"; if (hasRewardAccumulation()) { out << "[" << getRewardAccumulation() << "]"; diff --git a/src/storm/logic/TotalRewardFormula.h b/src/storm/logic/TotalRewardFormula.h index 1fa366723..42bce45c8 100644 --- a/src/storm/logic/TotalRewardFormula.h +++ b/src/storm/logic/TotalRewardFormula.h @@ -24,7 +24,7 @@ namespace storm { virtual boost::any accept(FormulaVisitor const& visitor, boost::any const& data) const override; - virtual std::ostream& writeToStream(std::ostream& out) const override; + virtual std::ostream& writeToStream(std::ostream& out, bool allowParentheses = false) const override; private: boost::optional<RewardAccumulation> rewardAccumulation; diff --git a/src/storm/logic/UnaryBooleanOperatorType.h b/src/storm/logic/UnaryBooleanOperatorType.h new file mode 100644 index 000000000..915a11f8a --- /dev/null +++ b/src/storm/logic/UnaryBooleanOperatorType.h @@ -0,0 +1,7 @@ +#pragma once + +namespace storm { + namespace logic { + enum class UnaryBooleanOperatorType {Not}; + } +} diff --git a/src/storm/logic/UnaryBooleanPathFormula.cpp b/src/storm/logic/UnaryBooleanPathFormula.cpp new file mode 100644 index 000000000..707599e0b --- /dev/null +++ b/src/storm/logic/UnaryBooleanPathFormula.cpp @@ -0,0 +1,53 @@ +#include "storm/logic/UnaryBooleanPathFormula.h" + +#include "storm/logic/FormulaVisitor.h" + +#include "storm/utility/macros.h" +#include "storm/exceptions/InvalidPropertyException.h" + +namespace storm { + namespace logic { + UnaryBooleanPathFormula::UnaryBooleanPathFormula(OperatorType operatorType, std::shared_ptr<Formula const> const& subformula, FormulaContext context) : UnaryPathFormula(subformula), operatorType(operatorType), context(context) { + STORM_LOG_THROW(this->getSubformula().isStateFormula() || this->getSubformula().isPathFormula(), storm::exceptions::InvalidPropertyException, "Boolean path formula must have either path or state subformulas"); + STORM_LOG_THROW(context == FormulaContext::Probability, storm::exceptions::InvalidPropertyException, "Invalid context for formula."); + } + + FormulaContext const& UnaryBooleanPathFormula::getContext() const { + return context; + } + + bool UnaryBooleanPathFormula::isUnaryBooleanPathFormula() const { + return true; + } + + bool UnaryBooleanPathFormula::isProbabilityPathFormula() const { + return true; + } + + boost::any UnaryBooleanPathFormula::accept(FormulaVisitor const& visitor, boost::any const& data) const { + return visitor.visit(*this, data); + } + + UnaryBooleanPathFormula::OperatorType UnaryBooleanPathFormula::getOperator() const { + return operatorType; + } + + bool UnaryBooleanPathFormula::isNot() const { + return this->getOperator() == OperatorType::Not; + } + + std::ostream& UnaryBooleanPathFormula::writeToStream(std::ostream& out, bool allowParentheses) const { + if (allowParentheses) { + out << "("; + } + switch (operatorType) { + case OperatorType::Not: out << "!"; break; + } + this->getSubformula().writeToStream(out, !this->getSubformula().isUnaryFormula()); + if (allowParentheses) { + out << ")"; + } + return out; + } + } +} diff --git a/src/storm/logic/UnaryBooleanPathFormula.h b/src/storm/logic/UnaryBooleanPathFormula.h new file mode 100644 index 000000000..f8a78aed5 --- /dev/null +++ b/src/storm/logic/UnaryBooleanPathFormula.h @@ -0,0 +1,40 @@ +#ifndef STORM_LOGIC_UNARYBOOLEANPATHFORMULA_H_ +#define STORM_LOGIC_UNARYBOOLEANPATHFORMULA_H_ + +#include "storm/logic/UnaryPathFormula.h" +#include "storm/logic/UnaryBooleanOperatorType.h" +#include "storm/logic/FormulaContext.h" + +namespace storm { + namespace logic { + class UnaryBooleanPathFormula : public UnaryPathFormula { + public: + typedef storm::logic::UnaryBooleanOperatorType OperatorType; + + UnaryBooleanPathFormula(OperatorType operatorType, std::shared_ptr<Formula const> const& subformula, FormulaContext context = FormulaContext::Probability); + + virtual ~UnaryBooleanPathFormula() { + // Intentionally left empty. + }; + + FormulaContext const& getContext() const; + + virtual bool isUnaryBooleanPathFormula() const override; + virtual bool isProbabilityPathFormula() const override; + + virtual boost::any accept(FormulaVisitor const& visitor, boost::any const& data) const override; + + OperatorType getOperator() const; + + virtual bool isNot() const; + + virtual std::ostream& writeToStream(std::ostream& out, bool allowParentheses = false) const override; + + private: + OperatorType operatorType; + FormulaContext context; + }; + } +} + +#endif /* STORM_LOGIC_UNARYBOOLEANPATHFORMULA_H_ */ diff --git a/src/storm/logic/UnaryBooleanStateFormula.cpp b/src/storm/logic/UnaryBooleanStateFormula.cpp index ef75a0f9b..5592d4589 100644 --- a/src/storm/logic/UnaryBooleanStateFormula.cpp +++ b/src/storm/logic/UnaryBooleanStateFormula.cpp @@ -27,12 +27,17 @@ namespace storm { return this->getOperator() == OperatorType::Not; } - std::ostream& UnaryBooleanStateFormula::writeToStream(std::ostream& out) const { + std::ostream& UnaryBooleanStateFormula::writeToStream(std::ostream& out, bool allowParentheses) const { + if (allowParentheses) { + out << "("; + } switch (operatorType) { - case OperatorType::Not: out << "!("; break; + case OperatorType::Not: out << "!"; break; + } + this->getSubformula().writeToStream(out, !this->getSubformula().isUnaryFormula()); + if (allowParentheses) { + out << ")"; } - this->getSubformula().writeToStream(out); - out << ")"; return out; } } diff --git a/src/storm/logic/UnaryBooleanStateFormula.h b/src/storm/logic/UnaryBooleanStateFormula.h index 19420ec16..14aef7eb1 100644 --- a/src/storm/logic/UnaryBooleanStateFormula.h +++ b/src/storm/logic/UnaryBooleanStateFormula.h @@ -2,12 +2,13 @@ #define STORM_LOGIC_UNARYBOOLEANSTATEFORMULA_H_ #include "storm/logic/UnaryStateFormula.h" +#include "storm/logic/UnaryBooleanOperatorType.h" namespace storm { namespace logic { class UnaryBooleanStateFormula : public UnaryStateFormula { public: - enum class OperatorType { Not }; + typedef storm::logic::UnaryBooleanOperatorType OperatorType; UnaryBooleanStateFormula(OperatorType operatorType, std::shared_ptr<Formula const> const& subformula); @@ -23,7 +24,7 @@ namespace storm { virtual bool isNot() const; - virtual std::ostream& writeToStream(std::ostream& out) const override; + virtual std::ostream& writeToStream(std::ostream& out, bool allowParentheses = false) const override; private: OperatorType operatorType; diff --git a/src/storm/logic/UntilFormula.cpp b/src/storm/logic/UntilFormula.cpp index d4b09bd4d..945bb9283 100644 --- a/src/storm/logic/UntilFormula.cpp +++ b/src/storm/logic/UntilFormula.cpp @@ -20,10 +20,16 @@ namespace storm { return visitor.visit(*this, data); } - std::ostream& UntilFormula::writeToStream(std::ostream& out) const { - this->getLeftSubformula().writeToStream(out); + std::ostream& UntilFormula::writeToStream(std::ostream& out, bool allowParentheses) const { + if (allowParentheses) { + out << "("; + } + this->getLeftSubformula().writeToStream(out, true); out << " U "; - this->getRightSubformula().writeToStream(out); + this->getRightSubformula().writeToStream(out, true); + if (allowParentheses) { + out << ")"; + } return out; } } diff --git a/src/storm/logic/UntilFormula.h b/src/storm/logic/UntilFormula.h index a26542a38..db8804504 100644 --- a/src/storm/logic/UntilFormula.h +++ b/src/storm/logic/UntilFormula.h @@ -18,7 +18,7 @@ namespace storm { virtual boost::any accept(FormulaVisitor const& visitor, boost::any const& data) const override; - virtual std::ostream& writeToStream(std::ostream& out) const override; + virtual std::ostream& writeToStream(std::ostream& out, bool allowParentheses = false) const override; }; } } diff --git a/src/storm/modelchecker/AbstractModelChecker.cpp b/src/storm/modelchecker/AbstractModelChecker.cpp index 803ddc711..5fb9fa6e0 100644 --- a/src/storm/modelchecker/AbstractModelChecker.cpp +++ b/src/storm/modelchecker/AbstractModelChecker.cpp @@ -2,6 +2,9 @@ #include "storm/modelchecker/results/QualitativeCheckResult.h" #include "storm/modelchecker/results/QuantitativeCheckResult.h" +#include "storm/modelchecker/results/ExplicitQuantitativeCheckResult.h" +#include "storm/modelchecker/results/SymbolicQuantitativeCheckResult.h" + #include "storm/utility/constants.h" #include "storm/utility/macros.h" #include "storm/exceptions/NotImplementedException.h" @@ -11,6 +14,7 @@ #include "storm/environment/Environment.h" +#include "storm/models/ModelRepresentation.h" #include "storm/models/sparse/Dtmc.h" #include "storm/models/sparse/Ctmc.h" #include "storm/models/sparse/Mdp.h" @@ -24,6 +28,7 @@ #include "storm/models/sparse/MarkovAutomaton.h" #include "storm/models/sparse/StandardRewardModel.h" #include "storm/models/symbolic/StandardRewardModel.h" +#include "storm/logic/FormulaInformation.h" #include "storm/storage/dd/Add.h" #include "storm/storage/dd/Bdd.h" @@ -43,7 +48,7 @@ namespace storm { Environment env; return this->check(env, checkTask); } - + template<typename ModelType> std::unique_ptr<CheckResult> AbstractModelChecker<ModelType>::check(Environment const& env, CheckTask<storm::logic::Formula, ValueType> const& checkTask) { storm::logic::Formula const& formula = checkTask.getFormula(); @@ -63,6 +68,15 @@ namespace storm { template<typename ModelType> std::unique_ptr<CheckResult> AbstractModelChecker<ModelType>::computeProbabilities(Environment const& env, CheckTask<storm::logic::Formula, ValueType> const& checkTask) { storm::logic::Formula const& formula = checkTask.getFormula(); + + if (formula.isStateFormula() || formula.hasQualitativeResult()) { + return this->computeStateFormulaProbabilities(env, checkTask.substituteFormula(formula)); + } + + if (formula.info(false).containsComplexPathFormula()) { + // we need to do LTL model checking + return this->computeLTLProbabilities(env, checkTask.substituteFormula(formula.asPathFormula())); + } if (formula.isBoundedGloballyFormula()) { return this->computeBoundedGloballyProbabilities(env, checkTask.substituteFormula(formula.asBoundedGloballyFormula())); } else if (formula.isBoundedUntilFormula()) { @@ -73,6 +87,8 @@ namespace storm { return this->computeGloballyProbabilities(env, checkTask.substituteFormula(formula.asGloballyFormula())); } else if (formula.isUntilFormula()) { return this->computeUntilProbabilities(env, checkTask.substituteFormula(formula.asUntilFormula())); + } else if (formula.isHOAPathFormula()) { + return this->computeHOAPathProbabilities(env, checkTask.substituteFormula(formula.asHOAPathFormula())); } else if (formula.isNextFormula()) { return this->computeNextProbabilities(env, checkTask.substituteFormula(formula.asNextFormula())); } else if (formula.isConditionalProbabilityFormula()) { @@ -118,6 +134,31 @@ namespace storm { STORM_LOG_THROW(false, storm::exceptions::NotImplementedException, "This model checker (" << getClassName() << ") does not support the formula: " << checkTask.getFormula() << "."); } + template<typename ModelType> + std::unique_ptr<CheckResult> AbstractModelChecker<ModelType>::computeHOAPathProbabilities(Environment const& env, CheckTask<storm::logic::HOAPathFormula, ValueType> const& checkTask) { + STORM_LOG_THROW(false, storm::exceptions::NotImplementedException, "This model checker does not support the formula: " << checkTask.getFormula() << "."); + } + + template<typename ModelType> + std::unique_ptr<CheckResult> AbstractModelChecker<ModelType>::computeLTLProbabilities(Environment const& env, CheckTask<storm::logic::PathFormula, ValueType> const& checkTask) { + STORM_LOG_THROW(false, storm::exceptions::NotImplementedException, "This model checker does not support the formula: " << checkTask.getFormula() << "."); + } + + template<typename ModelType> + std::unique_ptr<CheckResult> AbstractModelChecker<ModelType>::computeStateFormulaProbabilities(Environment const& env, CheckTask<storm::logic::Formula, ValueType> const& checkTask) { + // recurse + std::unique_ptr<CheckResult> resultPointer = this->check(env, checkTask.getFormula()); + if (resultPointer->isExplicitQualitativeCheckResult()) { + STORM_LOG_ASSERT(ModelType::Representation == storm::models::ModelRepresentation::Sparse, "Unexpected model type."); + return std::make_unique<ExplicitQuantitativeCheckResult<ValueType>>(resultPointer->asExplicitQualitativeCheckResult()); + } else { + STORM_LOG_ASSERT(resultPointer->isSymbolicQualitativeCheckResult(), "Unexpected result type."); + STORM_LOG_ASSERT(ModelType::Representation != storm::models::ModelRepresentation::Sparse, "Unexpected model type."); + auto const& qualRes = resultPointer->asSymbolicQualitativeCheckResult<storm::models::GetDdType<ModelType::Representation>::ddType>(); + return std::make_unique<SymbolicQuantitativeCheckResult<storm::models::GetDdType<ModelType::Representation>::ddType, ValueType>>(qualRes); + } + } + template<typename ModelType> std::unique_ptr<CheckResult> AbstractModelChecker<ModelType>::computeRewards(Environment const& env, storm::logic::RewardMeasureType rewardMeasureType, CheckTask<storm::logic::Formula, ValueType> const& checkTask) { storm::logic::Formula const& rewardFormula = checkTask.getFormula(); @@ -156,7 +197,7 @@ namespace storm { std::unique_ptr<CheckResult> AbstractModelChecker<ModelType>::computeReachabilityRewards(Environment const& env, storm::logic::RewardMeasureType, CheckTask<storm::logic::EventuallyFormula, ValueType> const& checkTask) { STORM_LOG_THROW(false, storm::exceptions::NotImplementedException, "This model checker (" << getClassName() << ") does not support the formula: " << checkTask.getFormula() << "."); } - + template<typename ModelType> std::unique_ptr<CheckResult> AbstractModelChecker<ModelType>::computeTotalRewards(Environment const& env, storm::logic::RewardMeasureType, CheckTask<storm::logic::TotalRewardFormula, ValueType> const& checkTask) { STORM_LOG_THROW(false, storm::exceptions::NotImplementedException, "This model checker (" << getClassName() << ") does not support the formula: " << checkTask.getFormula() << "."); @@ -211,6 +252,10 @@ namespace storm { return this->checkBooleanLiteralFormula(env, checkTask.substituteFormula(stateFormula.asBooleanLiteralFormula())); } else if (stateFormula.isGameFormula()) { return this->checkGameFormula(env, checkTask.substituteFormula(stateFormula.asGameFormula())); + } else if (stateFormula.isMultiObjectiveFormula()){ + return this->checkMultiObjectiveFormula(env, checkTask.substituteFormula(stateFormula.asMultiObjectiveFormula())); + } else if (stateFormula.isQuantileFormula()){ + return this->checkQuantileFormula(env, checkTask.substituteFormula(stateFormula.asQuantileFormula())); } STORM_LOG_THROW(false, storm::exceptions::InvalidArgumentException, "The given formula '" << stateFormula << "' is invalid."); } @@ -232,12 +277,12 @@ namespace storm { std::unique_ptr<CheckResult> AbstractModelChecker<ModelType>::checkBinaryBooleanStateFormula(Environment const& env, CheckTask<storm::logic::BinaryBooleanStateFormula, ValueType> const& checkTask) { storm::logic::BinaryBooleanStateFormula const& stateFormula = checkTask.getFormula(); STORM_LOG_THROW(stateFormula.getLeftSubformula().isStateFormula() && stateFormula.getRightSubformula().isStateFormula(), storm::exceptions::InvalidArgumentException, "The given formula is invalid."); - + std::unique_ptr<CheckResult> leftResult = this->check(env, checkTask.template substituteFormula<storm::logic::Formula>(stateFormula.getLeftSubformula().asStateFormula())); std::unique_ptr<CheckResult> rightResult = this->check(env, checkTask.template substituteFormula<storm::logic::Formula>(stateFormula.getRightSubformula().asStateFormula())); - + STORM_LOG_THROW(leftResult->isQualitative() && rightResult->isQualitative(), storm::exceptions::InternalTypeErrorException, "Expected qualitative results."); - + if (stateFormula.isAnd()) { leftResult->asQualitativeCheckResult() &= rightResult->asQualitativeCheckResult(); } else if (stateFormula.isOr()) { @@ -245,7 +290,7 @@ namespace storm { } else { STORM_LOG_THROW(false, storm::exceptions::InvalidArgumentException, "The given formula '" << stateFormula << "' is invalid."); } - + return leftResult; } @@ -258,7 +303,7 @@ namespace storm { std::unique_ptr<CheckResult> AbstractModelChecker<ModelType>::checkProbabilityOperatorFormula(Environment const& env, CheckTask<storm::logic::ProbabilityOperatorFormula, ValueType> const& checkTask) { storm::logic::ProbabilityOperatorFormula const& stateFormula = checkTask.getFormula(); std::unique_ptr<CheckResult> result = this->computeProbabilities(env, checkTask.substituteFormula(stateFormula.getSubformula())); - + if (checkTask.isBoundSet()) { STORM_LOG_THROW(result->isQuantitative(), storm::exceptions::InvalidOperationException, "Unable to perform comparison operation on non-quantitative result."); return result->asQuantitativeCheckResult<ValueType>().compareAgainstBound(checkTask.getBoundComparisonType(), checkTask.getBoundThreshold()); @@ -271,7 +316,7 @@ namespace storm { std::unique_ptr<CheckResult> AbstractModelChecker<ModelType>::checkRewardOperatorFormula(Environment const& env, CheckTask<storm::logic::RewardOperatorFormula, ValueType> const& checkTask) { storm::logic::RewardOperatorFormula const& stateFormula = checkTask.getFormula(); std::unique_ptr<CheckResult> result = this->computeRewards(env, stateFormula.getMeasureType(), checkTask.substituteFormula(stateFormula.getSubformula())); - + if (checkTask.isBoundSet()) { STORM_LOG_THROW(result->isQuantitative(), storm::exceptions::InvalidOperationException, "Unable to perform comparison operation on non-quantitative result."); return result->asQuantitativeCheckResult<ValueType>().compareAgainstBound(checkTask.getBoundComparisonType(), checkTask.getBoundThreshold()); @@ -284,9 +329,9 @@ namespace storm { std::unique_ptr<CheckResult> AbstractModelChecker<ModelType>::checkTimeOperatorFormula(Environment const& env, CheckTask<storm::logic::TimeOperatorFormula, ValueType> const& checkTask) { storm::logic::TimeOperatorFormula const& stateFormula = checkTask.getFormula(); STORM_LOG_THROW(stateFormula.getSubformula().isReachabilityTimeFormula(), storm::exceptions::InvalidArgumentException, "The given formula is invalid."); - + std::unique_ptr<CheckResult> result = this->computeTimes(env, stateFormula.getMeasureType(), checkTask.substituteFormula(stateFormula.getSubformula())); - + if (checkTask.isBoundSet()) { STORM_LOG_THROW(result->isQuantitative(), storm::exceptions::InvalidOperationException, "Unable to perform comparison operation on non-quantitative result."); return result->asQuantitativeCheckResult<ValueType>().compareAgainstBound(checkTask.getBoundComparisonType(), checkTask.getBoundThreshold()); @@ -299,9 +344,9 @@ namespace storm { std::unique_ptr<CheckResult> AbstractModelChecker<ModelType>::checkLongRunAverageOperatorFormula(Environment const& env, CheckTask<storm::logic::LongRunAverageOperatorFormula, ValueType> const& checkTask) { storm::logic::LongRunAverageOperatorFormula const& stateFormula = checkTask.getFormula(); STORM_LOG_THROW(stateFormula.getSubformula().isStateFormula(), storm::exceptions::InvalidArgumentException, "The given formula is invalid."); - + std::unique_ptr<CheckResult> result = this->computeLongRunAverageProbabilities(env, checkTask.substituteFormula(stateFormula.getSubformula().asStateFormula())); - + if (checkTask.isBoundSet()) { STORM_LOG_THROW(result->isQuantitative(), storm::exceptions::InvalidOperationException, "Unable to perform comparison operation on non-quantitative result."); return result->asQuantitativeCheckResult<ValueType>().compareAgainstBound(checkTask.getBoundComparisonType(), checkTask.getBoundThreshold()); @@ -309,7 +354,7 @@ namespace storm { return result; } } - + template<typename ModelType> std::unique_ptr<CheckResult> AbstractModelChecker<ModelType>::checkUnaryBooleanStateFormula(Environment const& env, CheckTask<storm::logic::UnaryBooleanStateFormula, ValueType> const& checkTask) { storm::logic::UnaryBooleanStateFormula const& stateFormula = checkTask.getFormula(); diff --git a/src/storm/modelchecker/AbstractModelChecker.h b/src/storm/modelchecker/AbstractModelChecker.h index 578b83f15..2038e6361 100644 --- a/src/storm/modelchecker/AbstractModelChecker.h +++ b/src/storm/modelchecker/AbstractModelChecker.h @@ -9,12 +9,12 @@ #include "storm/solver/OptimizationDirection.h" namespace storm { - + class Environment; - + namespace modelchecker { class CheckResult; - + enum class RewardType { Expectation, Variance }; template<typename ModelType> @@ -39,7 +39,7 @@ namespace storm { * @return True iff the model checker can check the given task. */ virtual bool canHandle(CheckTask<storm::logic::Formula, ValueType> const& checkTask) const = 0; - + /*! * Checks the provided formula. * @@ -47,13 +47,13 @@ namespace storm { * @return The verification result. */ virtual std::unique_ptr<CheckResult> check(Environment const& env, CheckTask<storm::logic::Formula, ValueType> const& checkTask); - + /*! * Checks the provided formula with the default environment. * TODO This function is obsolete as soon as the Environment is fully integrated. */ std::unique_ptr<CheckResult> check(CheckTask<storm::logic::Formula, ValueType> const& checkTask); - + // The methods to compute probabilities for path formulas. virtual std::unique_ptr<CheckResult> computeProbabilities(Environment const& env, CheckTask<storm::logic::Formula, ValueType> const& checkTask); virtual std::unique_ptr<CheckResult> computeConditionalProbabilities(Environment const& env, CheckTask<storm::logic::ConditionalFormula, ValueType> const& checkTask); @@ -63,6 +63,9 @@ namespace storm { virtual std::unique_ptr<CheckResult> computeGloballyProbabilities(Environment const& env, CheckTask<storm::logic::GloballyFormula, ValueType> const& checkTask); virtual std::unique_ptr<CheckResult> computeNextProbabilities(Environment const& env, CheckTask<storm::logic::NextFormula, ValueType> const& checkTask); virtual std::unique_ptr<CheckResult> computeUntilProbabilities(Environment const& env, CheckTask<storm::logic::UntilFormula, ValueType> const& checkTask); + virtual std::unique_ptr<CheckResult> computeHOAPathProbabilities(Environment const& env, CheckTask<storm::logic::HOAPathFormula, ValueType> const& checkTask); + virtual std::unique_ptr<CheckResult> computeLTLProbabilities(Environment const& env, CheckTask<storm::logic::PathFormula, ValueType> const& checkTask); + std::unique_ptr<CheckResult> computeStateFormulaProbabilities(Environment const& env, CheckTask<storm::logic::Formula, ValueType> const& checkTask); // The methods to compute the rewards for path formulas. virtual std::unique_ptr<CheckResult> computeRewards(Environment const& env, storm::logic::RewardMeasureType rewardMeasureType, CheckTask<storm::logic::Formula, ValueType> const& checkTask); @@ -72,12 +75,12 @@ namespace storm { virtual std::unique_ptr<CheckResult> computeReachabilityRewards(Environment const& env, storm::logic::RewardMeasureType rewardMeasureType, CheckTask<storm::logic::EventuallyFormula, ValueType> const& checkTask); virtual std::unique_ptr<CheckResult> computeTotalRewards(Environment const& env, storm::logic::RewardMeasureType rewardMeasureType, CheckTask<storm::logic::TotalRewardFormula, ValueType> const& checkTask); virtual std::unique_ptr<CheckResult> computeLongRunAverageRewards(Environment const& env, storm::logic::RewardMeasureType rewardMeasureType, CheckTask<storm::logic::LongRunAverageRewardFormula, ValueType> const& checkTask); - + // The methods to compute the long-run average probabilities and timing measures. virtual std::unique_ptr<CheckResult> computeLongRunAverageProbabilities(Environment const& env, CheckTask<storm::logic::StateFormula, ValueType> const& checkTask); virtual std::unique_ptr<CheckResult> computeTimes(Environment const& env, storm::logic::RewardMeasureType rewardMeasureType, CheckTask<storm::logic::Formula, ValueType> const& checkTask); virtual std::unique_ptr<CheckResult> computeReachabilityTimes(Environment const& env, storm::logic::RewardMeasureType rewardMeasureType, CheckTask<storm::logic::EventuallyFormula, ValueType> const& checkTask); - + // The methods to check state formulas. virtual std::unique_ptr<CheckResult> checkStateFormula(Environment const& env, CheckTask<storm::logic::StateFormula, ValueType> const& checkTask); virtual std::unique_ptr<CheckResult> checkAtomicExpressionFormula(Environment const& env, CheckTask<storm::logic::AtomicExpressionFormula, ValueType> const& checkTask); diff --git a/src/storm/modelchecker/CheckTask.h b/src/storm/modelchecker/CheckTask.h index b42e8c3f8..2143e1f30 100644 --- a/src/storm/modelchecker/CheckTask.h +++ b/src/storm/modelchecker/CheckTask.h @@ -101,6 +101,27 @@ namespace storm { } } + /*! + * Negate the optimization direction and the bound threshold, if those exist. + * Suitable for switching from Pmin[phi] to 1-Pmax[!psi] computations. + */ + CheckTask negate() const { + CheckTask result(*this); + if (isOptimizationDirectionSet()) { + // switch from min to max and vice-versa + result.setOptimizationDirection(invert(getOptimizationDirection())); + } + + if (isBoundSet()) { + // invert bound comparison type (retain strictness), + // convert threshold to 1- threshold + result.bound = storm::logic::Bound(storm::logic::invertPreserveStrictness(getBound().comparisonType), + 1 - getBound().threshold); + } + + return result; + } + /*! * Copies the check task from the source while replacing the considered ValueType the new one. In particular, this * changes the formula type of the check task object. diff --git a/src/storm/modelchecker/csl/SparseCtmcCslModelChecker.cpp b/src/storm/modelchecker/csl/SparseCtmcCslModelChecker.cpp index 513f9d8cb..f3c107c8b 100644 --- a/src/storm/modelchecker/csl/SparseCtmcCslModelChecker.cpp +++ b/src/storm/modelchecker/csl/SparseCtmcCslModelChecker.cpp @@ -16,6 +16,8 @@ #include "storm/modelchecker/results/ExplicitQualitativeCheckResult.h" #include "storm/modelchecker/results/ExplicitQuantitativeCheckResult.h" +#include "storm/modelchecker/helper/ltl/SparseLTLHelper.h" + #include "storm/logic/FragmentSpecification.h" #include "storm/adapters/RationalFunctionAdapter.h" @@ -30,21 +32,21 @@ namespace storm { SparseCtmcCslModelChecker<SparseCtmcModelType>::SparseCtmcCslModelChecker(SparseCtmcModelType const& model) : SparsePropositionalModelChecker<SparseCtmcModelType>(model) { // Intentionally left empty. } - + template <typename ModelType> bool SparseCtmcCslModelChecker<ModelType>::canHandleStatic(CheckTask<storm::logic::Formula, ValueType> const& checkTask) { - auto fragment = storm::logic::csrl().setGloballyFormulasAllowed(false).setLongRunAverageRewardFormulasAllowed(true).setLongRunAverageProbabilitiesAllowed(true).setTimeAllowed(true).setTimeOperatorsAllowed(true).setTotalRewardFormulasAllowed(true).setRewardAccumulationAllowed(true); + auto fragment = storm::logic::csrlstar().setLongRunAverageRewardFormulasAllowed(true).setLongRunAverageProbabilitiesAllowed(true).setTimeAllowed(true).setTimeOperatorsAllowed(true).setTotalRewardFormulasAllowed(true).setRewardAccumulationAllowed(true); if (!storm::NumberTraits<ValueType>::SupportsExponential) { fragment.setBoundedUntilFormulasAllowed(false).setCumulativeRewardFormulasAllowed(false).setInstantaneousFormulasAllowed(false); } return checkTask.getFormula().isInFragment(fragment); } - + template <typename SparseCtmcModelType> bool SparseCtmcCslModelChecker<SparseCtmcModelType>::canHandle(CheckTask<storm::logic::Formula, ValueType> const& checkTask) const { return canHandleStatic(checkTask); } - + template <typename SparseCtmcModelType> std::unique_ptr<CheckResult> SparseCtmcCslModelChecker<SparseCtmcModelType>::computeBoundedUntilProbabilities(Environment const& env, CheckTask<storm::logic::BoundedUntilFormula, ValueType> const& checkTask) { storm::logic::BoundedUntilFormula const& pathFormula = checkTask.getFormula(); @@ -68,7 +70,7 @@ namespace storm { std::vector<ValueType> numericResult = storm::modelchecker::helper::SparseCtmcCslHelper::computeBoundedUntilProbabilities(env, storm::solver::SolveGoal<ValueType>(this->getModel(), checkTask), this->getModel().getTransitionMatrix(), this->getModel().getBackwardTransitions(), leftResult.getTruthValuesVector(), rightResult.getTruthValuesVector(), this->getModel().getExitRateVector(), checkTask.isQualitativeSet(), lowerBound, upperBound); return std::unique_ptr<CheckResult>(new ExplicitQuantitativeCheckResult<ValueType>(std::move(numericResult))); } - + template <typename SparseCtmcModelType> std::unique_ptr<CheckResult> SparseCtmcCslModelChecker<SparseCtmcModelType>::computeNextProbabilities(Environment const& env, CheckTask<storm::logic::NextFormula, ValueType> const& checkTask) { storm::logic::NextFormula const& pathFormula = checkTask.getFormula(); @@ -77,7 +79,17 @@ namespace storm { std::vector<ValueType> numericResult = storm::modelchecker::helper::SparseCtmcCslHelper::computeNextProbabilities(env, this->getModel().getTransitionMatrix(), this->getModel().getExitRateVector(), subResult.getTruthValuesVector()); return std::unique_ptr<CheckResult>(new ExplicitQuantitativeCheckResult<ValueType>(std::move(numericResult))); } - + + template<typename SparseCtmcModelType> + std::unique_ptr<CheckResult> SparseCtmcCslModelChecker<SparseCtmcModelType>::computeGloballyProbabilities(Environment const& env, CheckTask<storm::logic::GloballyFormula, ValueType> const& checkTask) { + storm::logic::GloballyFormula const& pathFormula = checkTask.getFormula(); + std::unique_ptr<CheckResult> subResultPointer = this->check(env, pathFormula.getSubformula()); + ExplicitQualitativeCheckResult const& subResult = subResultPointer->asExplicitQualitativeCheckResult(); + auto probabilisticTransitions = this->getModel().computeProbabilityMatrix(); + std::vector<ValueType> numericResult = storm::modelchecker::helper::SparseDtmcPrctlHelper<ValueType>::computeGloballyProbabilities(env, storm::solver::SolveGoal<ValueType>(this->getModel(), checkTask), probabilisticTransitions, probabilisticTransitions.transpose(), subResult.getTruthValuesVector(), checkTask.isQualitativeSet()); + return std::unique_ptr<CheckResult>(new ExplicitQuantitativeCheckResult<ValueType>(std::move(numericResult))); + } + template <typename SparseCtmcModelType> std::unique_ptr<CheckResult> SparseCtmcCslModelChecker<SparseCtmcModelType>::computeUntilProbabilities(Environment const& env, CheckTask<storm::logic::UntilFormula, ValueType> const& checkTask) { storm::logic::UntilFormula const& pathFormula = checkTask.getFormula(); @@ -88,7 +100,36 @@ namespace storm { std::vector<ValueType> numericResult = storm::modelchecker::helper::SparseCtmcCslHelper::computeUntilProbabilities(env, storm::solver::SolveGoal<ValueType>(this->getModel(), checkTask), this->getModel().getTransitionMatrix(), this->getModel().getBackwardTransitions(), this->getModel().getExitRateVector(), leftResult.getTruthValuesVector(), rightResult.getTruthValuesVector(), checkTask.isQualitativeSet()); return std::unique_ptr<CheckResult>(new ExplicitQuantitativeCheckResult<ValueType>(std::move(numericResult))); } - + + template<typename SparseCtmcModelType> + std::unique_ptr<CheckResult> SparseCtmcCslModelChecker<SparseCtmcModelType>::computeHOAPathProbabilities(Environment const& env, CheckTask<storm::logic::HOAPathFormula, ValueType> const& checkTask) { + storm::logic::HOAPathFormula const& pathFormula = checkTask.getFormula(); + + auto probabilisticTransitions = this->getModel().computeProbabilityMatrix(); + storm::modelchecker::helper::SparseLTLHelper<ValueType, false> helper(probabilisticTransitions); + storm::modelchecker::helper::setInformationFromCheckTaskDeterministic(helper, checkTask, this->getModel()); + + auto formulaChecker = [&] (storm::logic::Formula const& formula) { return this->check(env, formula)->asExplicitQualitativeCheckResult().getTruthValuesVector(); }; + auto apSets = helper.computeApSets(pathFormula.getAPMapping(), formulaChecker); + std::vector<ValueType> numericResult = helper.computeDAProductProbabilities(env, *pathFormula.readAutomaton(), apSets); + + return std::unique_ptr<CheckResult>(new ExplicitQuantitativeCheckResult<ValueType>(std::move(numericResult))); + } + + template<typename SparseCtmcModelType> + std::unique_ptr<CheckResult> SparseCtmcCslModelChecker<SparseCtmcModelType>::computeLTLProbabilities(Environment const& env, CheckTask<storm::logic::PathFormula, ValueType> const& checkTask) { + storm::logic::PathFormula const& pathFormula = checkTask.getFormula(); + + auto probabilisticTransitions = this->getModel().computeProbabilityMatrix(); + storm::modelchecker::helper::SparseLTLHelper<ValueType, false> helper(probabilisticTransitions); + storm::modelchecker::helper::setInformationFromCheckTaskDeterministic(helper, checkTask, this->getModel()); + + auto formulaChecker = [&] (storm::logic::Formula const& formula) { return this->check(env, formula)->asExplicitQualitativeCheckResult().getTruthValuesVector(); }; + std::vector<ValueType> numericResult = helper.computeLTLProbabilities(env, pathFormula, formulaChecker); + + return std::unique_ptr<CheckResult>(new ExplicitQuantitativeCheckResult<ValueType>(std::move(numericResult))); + } + template <typename SparseCtmcModelType> std::unique_ptr<CheckResult> SparseCtmcCslModelChecker<SparseCtmcModelType>::computeInstantaneousRewards(Environment const& env, storm::logic::RewardMeasureType, CheckTask<storm::logic::InstantaneousRewardFormula, ValueType> const& checkTask) { storm::logic::InstantaneousRewardFormula const& rewardPathFormula = checkTask.getFormula(); @@ -96,7 +137,7 @@ namespace storm { std::vector<ValueType> numericResult = storm::modelchecker::helper::SparseCtmcCslHelper::computeInstantaneousRewards(env, storm::solver::SolveGoal<ValueType>(this->getModel(), checkTask), this->getModel().getTransitionMatrix(), this->getModel().getExitRateVector(), checkTask.isRewardModelSet() ? this->getModel().getRewardModel(checkTask.getRewardModel()) : this->getModel().getRewardModel(""), rewardPathFormula.getBound<double>()); return std::unique_ptr<CheckResult>(new ExplicitQuantitativeCheckResult<ValueType>(std::move(numericResult))); } - + template <typename SparseCtmcModelType> std::unique_ptr<CheckResult> SparseCtmcCslModelChecker<SparseCtmcModelType>::computeCumulativeRewards(Environment const& env, storm::logic::RewardMeasureType, CheckTask<storm::logic::CumulativeRewardFormula, ValueType> const& checkTask) { storm::logic::CumulativeRewardFormula const& rewardPathFormula = checkTask.getFormula(); @@ -105,7 +146,7 @@ namespace storm { std::vector<ValueType> numericResult = storm::modelchecker::helper::SparseCtmcCslHelper::computeCumulativeRewards(env, storm::solver::SolveGoal<ValueType>(this->getModel(), checkTask), this->getModel().getTransitionMatrix(), this->getModel().getExitRateVector(), rewardModel.get(), rewardPathFormula.getNonStrictBound<double>()); return std::unique_ptr<CheckResult>(new ExplicitQuantitativeCheckResult<ValueType>(std::move(numericResult))); } - + template <typename SparseCtmcModelType> std::unique_ptr<CheckResult> SparseCtmcCslModelChecker<SparseCtmcModelType>::computeReachabilityRewards(Environment const& env, storm::logic::RewardMeasureType, CheckTask<storm::logic::EventuallyFormula, ValueType> const& checkTask) { storm::logic::EventuallyFormula const& eventuallyFormula = checkTask.getFormula(); @@ -115,25 +156,25 @@ namespace storm { std::vector<ValueType> numericResult = storm::modelchecker::helper::SparseCtmcCslHelper::computeReachabilityRewards(env, storm::solver::SolveGoal<ValueType>(this->getModel(), checkTask), this->getModel().getTransitionMatrix(), this->getModel().getBackwardTransitions(), this->getModel().getExitRateVector(), rewardModel.get(), subResult.getTruthValuesVector(), checkTask.isQualitativeSet()); return std::unique_ptr<CheckResult>(new ExplicitQuantitativeCheckResult<ValueType>(std::move(numericResult))); } - + template<typename SparseCtmcModelType> std::unique_ptr<CheckResult> SparseCtmcCslModelChecker<SparseCtmcModelType>::computeTotalRewards(Environment const& env, storm::logic::RewardMeasureType, CheckTask<storm::logic::TotalRewardFormula, ValueType> const& checkTask) { auto rewardModel = storm::utility::createFilteredRewardModel(this->getModel(), checkTask); std::vector<ValueType> numericResult = storm::modelchecker::helper::SparseCtmcCslHelper::computeTotalRewards(env, storm::solver::SolveGoal<ValueType>(this->getModel(), checkTask), this->getModel().getTransitionMatrix(), this->getModel().getBackwardTransitions(), this->getModel().getExitRateVector(), rewardModel.get(), checkTask.isQualitativeSet()); return std::unique_ptr<CheckResult>(new ExplicitQuantitativeCheckResult<ValueType>(std::move(numericResult))); } - + template <typename SparseCtmcModelType> std::unique_ptr<CheckResult> SparseCtmcCslModelChecker<SparseCtmcModelType>::computeLongRunAverageProbabilities(Environment const& env, CheckTask<storm::logic::StateFormula, ValueType> const& checkTask) { storm::logic::StateFormula const& stateFormula = checkTask.getFormula(); std::unique_ptr<CheckResult> subResultPointer = this->check(env, stateFormula); ExplicitQualitativeCheckResult const& subResult = subResultPointer->asExplicitQualitativeCheckResult(); - + auto probabilisticTransitions = this->getModel().computeProbabilityMatrix(); storm::modelchecker::helper::SparseDeterministicInfiniteHorizonHelper<ValueType> helper(probabilisticTransitions, this->getModel().getExitRateVector()); storm::modelchecker::helper::setInformationFromCheckTaskDeterministic(helper, checkTask, this->getModel()); auto values = helper.computeLongRunAverageProbabilities(env, subResult.getTruthValuesVector()); - + return std::unique_ptr<CheckResult>(new ExplicitQuantitativeCheckResult<ValueType>(std::move(values))); } @@ -146,7 +187,7 @@ namespace storm { auto values = helper.computeLongRunAverageRewards(env, rewardModel.get()); return std::unique_ptr<CheckResult>(new ExplicitQuantitativeCheckResult<ValueType>(std::move(values))); } - + template <typename SparseCtmcModelType> std::unique_ptr<CheckResult> SparseCtmcCslModelChecker<SparseCtmcModelType>::computeReachabilityTimes(Environment const& env, storm::logic::RewardMeasureType, CheckTask<storm::logic::EventuallyFormula, ValueType> const& checkTask) { storm::logic::EventuallyFormula const& eventuallyFormula = checkTask.getFormula(); @@ -172,13 +213,13 @@ namespace storm { std::vector<ValueType> result = storm::modelchecker::helper::SparseCtmcCslHelper::computeAllTransientProbabilities(env, this->getModel().getTransitionMatrix(), this->getModel().getInitialStates(), leftResult.getTruthValuesVector(), rightResult.getTruthValuesVector(), this->getModel().getExitRateVector(), upperBound); return result; } - + template <typename SparseCtmcModelType> std::unique_ptr<CheckResult> SparseCtmcCslModelChecker<SparseCtmcModelType>::computeSteadyStateDistribution(Environment const& env) { // Initialize helper auto probabilisticTransitions = this->getModel().computeProbabilityMatrix(); storm::modelchecker::helper::SparseDeterministicInfiniteHorizonHelper<ValueType> helper(probabilisticTransitions, this->getModel().getExitRateVector()); - + // Compute result std::vector<ValueType> result; auto const& initialStates = this->getModel().getInitialStates(); diff --git a/src/storm/modelchecker/csl/SparseCtmcCslModelChecker.h b/src/storm/modelchecker/csl/SparseCtmcCslModelChecker.h index fa43b6f9e..1730aa327 100644 --- a/src/storm/modelchecker/csl/SparseCtmcCslModelChecker.h +++ b/src/storm/modelchecker/csl/SparseCtmcCslModelChecker.h @@ -10,25 +10,29 @@ #include "storm/utility/NumberTraits.h" namespace storm { - + namespace modelchecker { - + template<class SparseCtmcModelType> class SparseCtmcCslModelChecker : public SparsePropositionalModelChecker<SparseCtmcModelType> { public: typedef typename SparseCtmcModelType::ValueType ValueType; typedef typename SparseCtmcModelType::RewardModelType RewardModelType; - + explicit SparseCtmcCslModelChecker(SparseCtmcModelType const& model); - + // Returns false, if this task can certainly not be handled by this model checker (independent of the concrete model). static bool canHandleStatic(CheckTask<storm::logic::Formula, ValueType> const& checkTask); - + // The implemented methods of the AbstractModelChecker interface. virtual bool canHandle(CheckTask<storm::logic::Formula, ValueType> const& checkTask) const override; virtual std::unique_ptr<CheckResult> computeBoundedUntilProbabilities(Environment const& env, CheckTask<storm::logic::BoundedUntilFormula, ValueType> const& checkTask) override; virtual std::unique_ptr<CheckResult> computeNextProbabilities(Environment const& env, CheckTask<storm::logic::NextFormula, ValueType> const& checkTask) override; + virtual std::unique_ptr<CheckResult> computeGloballyProbabilities(Environment const& env, CheckTask<storm::logic::GloballyFormula, ValueType> const& checkTask) override; virtual std::unique_ptr<CheckResult> computeUntilProbabilities(Environment const& env, CheckTask<storm::logic::UntilFormula, ValueType> const& checkTask) override; + virtual std::unique_ptr<CheckResult> computeLTLProbabilities(Environment const& env, CheckTask<storm::logic::PathFormula, ValueType> const& checkTask) override; + virtual std::unique_ptr<CheckResult> computeHOAPathProbabilities(Environment const& env, CheckTask<storm::logic::HOAPathFormula, ValueType> const& checkTask) override; + virtual std::unique_ptr<CheckResult> computeLongRunAverageProbabilities(Environment const& env, CheckTask<storm::logic::StateFormula, ValueType> const& checkTask) override; virtual std::unique_ptr<CheckResult> computeReachabilityTimes(Environment const& env, storm::logic::RewardMeasureType rewardMeasureType, CheckTask<storm::logic::EventuallyFormula, ValueType> const& checkTask) override; @@ -50,7 +54,7 @@ namespace storm { std::unique_ptr<CheckResult> computeSteadyStateDistribution(Environment const& env); }; - + } // namespace modelchecker } // namespace storm diff --git a/src/storm/modelchecker/csl/SparseMarkovAutomatonCslModelChecker.cpp b/src/storm/modelchecker/csl/SparseMarkovAutomatonCslModelChecker.cpp index e0844fbb8..7afb03f38 100644 --- a/src/storm/modelchecker/csl/SparseMarkovAutomatonCslModelChecker.cpp +++ b/src/storm/modelchecker/csl/SparseMarkovAutomatonCslModelChecker.cpp @@ -1,8 +1,10 @@ #include "storm/modelchecker/csl/SparseMarkovAutomatonCslModelChecker.h" - #include "storm/modelchecker/csl/helper/SparseMarkovAutomatonCslHelper.h" +#include "storm/modelchecker/prctl/helper/SparseMdpPrctlHelper.h" + #include "storm/modelchecker/helper/infinitehorizon/SparseNondeterministicInfiniteHorizonHelper.h" #include "storm/modelchecker/helper/utility/SetInformationFromCheckTask.h" +#include "storm/modelchecker/helper/ltl/SparseLTLHelper.h" #include "storm/modelchecker/multiobjective/multiObjectiveModelChecking.h" @@ -11,8 +13,6 @@ #include "storm/utility/FilteredRewardModel.h" #include "storm/utility/macros.h" -#include "storm/settings/SettingsManager.h" -#include "storm/settings/modules/GeneralSettings.h" #include "storm/solver/SolveGoal.h" #include "storm/modelchecker/results/ExplicitQualitativeCheckResult.h" @@ -32,7 +32,7 @@ namespace storm { template <typename ModelType> bool SparseMarkovAutomatonCslModelChecker<ModelType>::canHandleStatic(CheckTask<storm::logic::Formula, ValueType> const& checkTask, bool* requiresSingleInitialState) { - auto singleObjectiveFragment = storm::logic::csl().setGloballyFormulasAllowed(false).setNextFormulasAllowed(false).setRewardOperatorsAllowed(true).setReachabilityRewardFormulasAllowed(true).setTotalRewardFormulasAllowed(true).setTimeAllowed(true).setLongRunAverageProbabilitiesAllowed(true).setLongRunAverageRewardFormulasAllowed(true).setRewardAccumulationAllowed(true).setInstantaneousFormulasAllowed(false); + auto singleObjectiveFragment = storm::logic::csrlstar().setRewardOperatorsAllowed(true).setReachabilityRewardFormulasAllowed(true).setTotalRewardFormulasAllowed(true).setTimeAllowed(true).setLongRunAverageProbabilitiesAllowed(true).setLongRunAverageRewardFormulasAllowed(true).setRewardAccumulationAllowed(true).setInstantaneousFormulasAllowed(false); auto multiObjectiveFragment = storm::logic::multiObjective().setTimeAllowed(true).setTimeBoundedUntilFormulasAllowed(true).setRewardAccumulationAllowed(true); if (!storm::NumberTraits<ValueType>::SupportsExponential) { singleObjectiveFragment.setBoundedUntilFormulasAllowed(false).setCumulativeRewardFormulasAllowed(false); @@ -85,6 +85,31 @@ namespace storm { std::vector<ValueType> result = storm::modelchecker::helper::SparseMarkovAutomatonCslHelper::computeBoundedUntilProbabilities(env, storm::solver::SolveGoal<ValueType>(this->getModel(), checkTask), this->getModel().getTransitionMatrix(), this->getModel().getExitRates(), this->getModel().getMarkovianStates(), leftResult.getTruthValuesVector(), rightResult.getTruthValuesVector(), std::make_pair(lowerBound, upperBound)); return std::unique_ptr<CheckResult>(new ExplicitQuantitativeCheckResult<ValueType>(std::move(result))); } + + + template<typename SparseMarkovAutomatonModelType> + std::unique_ptr<CheckResult> SparseMarkovAutomatonCslModelChecker<SparseMarkovAutomatonModelType>::computeNextProbabilities(Environment const& env, CheckTask<storm::logic::NextFormula, ValueType> const& checkTask) { + storm::logic::NextFormula const& pathFormula = checkTask.getFormula(); + STORM_LOG_THROW(checkTask.isOptimizationDirectionSet(), storm::exceptions::InvalidPropertyException, "Formula needs to specify whether minimal or maximal values are to be computed on nondeterministic model."); + std::unique_ptr<CheckResult> subResultPointer = this->check(env, pathFormula.getSubformula()); + ExplicitQualitativeCheckResult const& subResult = subResultPointer->asExplicitQualitativeCheckResult(); + std::vector<ValueType> numericResult = storm::modelchecker::helper::SparseMdpPrctlHelper<ValueType>::computeNextProbabilities(env, checkTask.getOptimizationDirection(), this->getModel().getTransitionMatrix(), subResult.getTruthValuesVector()); + return std::unique_ptr<CheckResult>(new ExplicitQuantitativeCheckResult<ValueType>(std::move(numericResult))); + } + + template<typename SparseMarkovAutomatonModelType> + std::unique_ptr<CheckResult> SparseMarkovAutomatonCslModelChecker<SparseMarkovAutomatonModelType>::computeGloballyProbabilities(Environment const& env, CheckTask<storm::logic::GloballyFormula, ValueType> const& checkTask) { + storm::logic::GloballyFormula const& pathFormula = checkTask.getFormula(); + STORM_LOG_THROW(checkTask.isOptimizationDirectionSet(), storm::exceptions::InvalidPropertyException, "Formula needs to specify whether minimal or maximal values are to be computed on nondeterministic model."); + std::unique_ptr<CheckResult> subResultPointer = this->check(env, pathFormula.getSubformula()); + ExplicitQualitativeCheckResult const& subResult = subResultPointer->asExplicitQualitativeCheckResult(); + auto ret = storm::modelchecker::helper::SparseMdpPrctlHelper<ValueType>::computeGloballyProbabilities(env, storm::solver::SolveGoal<ValueType>(this->getModel(), checkTask), this->getModel().getTransitionMatrix(), this->getModel().getBackwardTransitions(), subResult.getTruthValuesVector(), checkTask.isQualitativeSet(), checkTask.isProduceSchedulersSet()); + std::unique_ptr<CheckResult> result(new ExplicitQuantitativeCheckResult<ValueType>(std::move(ret.values))); + if (checkTask.isProduceSchedulersSet() && ret.scheduler) { + result->asExplicitQuantitativeCheckResult<ValueType>().setScheduler(std::move(ret.scheduler)); + } + return result; + } template<typename SparseMarkovAutomatonModelType> std::unique_ptr<CheckResult> SparseMarkovAutomatonCslModelChecker<SparseMarkovAutomatonModelType>::computeUntilProbabilities(Environment const& env, CheckTask<storm::logic::UntilFormula, ValueType> const& checkTask) { @@ -102,7 +127,46 @@ namespace storm { } return result; } - + + template<typename SparseMarkovAutomatonModelType> + std::unique_ptr<CheckResult> SparseMarkovAutomatonCslModelChecker<SparseMarkovAutomatonModelType>::computeHOAPathProbabilities(Environment const& env, CheckTask<storm::logic::HOAPathFormula, ValueType> const& checkTask) { + storm::logic::HOAPathFormula const& pathFormula = checkTask.getFormula(); + + storm::modelchecker::helper::SparseLTLHelper<ValueType, true> helper(this->getModel().getTransitionMatrix()); + storm::modelchecker::helper::setInformationFromCheckTaskNondeterministic(helper, checkTask, this->getModel()); + + auto formulaChecker = [&] (storm::logic::Formula const& formula) { return this->check(env, formula)->asExplicitQualitativeCheckResult().getTruthValuesVector(); }; + auto apSets = helper.computeApSets(pathFormula.getAPMapping(), formulaChecker); + std::vector<ValueType> numericResult = helper.computeDAProductProbabilities(env, *pathFormula.readAutomaton(), apSets); + + std::unique_ptr<CheckResult> result(new ExplicitQuantitativeCheckResult<ValueType>(std::move(numericResult))); + if (checkTask.isProduceSchedulersSet()) { + result->asExplicitQuantitativeCheckResult<ValueType>().setScheduler(std::make_unique<storm::storage::Scheduler<ValueType>>(helper.extractScheduler(this->getModel()))); + } + + return result; + } + + template<typename SparseMarkovAutomatonModelType> + std::unique_ptr<CheckResult> SparseMarkovAutomatonCslModelChecker<SparseMarkovAutomatonModelType>::computeLTLProbabilities(Environment const& env, CheckTask<storm::logic::PathFormula, ValueType> const& checkTask) { + storm::logic::PathFormula const& pathFormula = checkTask.getFormula(); + + STORM_LOG_THROW(checkTask.isOptimizationDirectionSet(), storm::exceptions::InvalidPropertyException, "Formula needs to specify whether minimal or maximal values are to be computed on nondeterministic model."); + + storm::modelchecker::helper::SparseLTLHelper<ValueType, true> helper(this->getModel().getTransitionMatrix()); + storm::modelchecker::helper::setInformationFromCheckTaskNondeterministic(helper, checkTask, this->getModel()); + + auto formulaChecker = [&] (storm::logic::Formula const& formula) { return this->check(env, formula)->asExplicitQualitativeCheckResult().getTruthValuesVector(); }; + std::vector<ValueType> numericResult = helper.computeLTLProbabilities(env, pathFormula, formulaChecker); + + std::unique_ptr<CheckResult> result(new ExplicitQuantitativeCheckResult<ValueType>(std::move(numericResult))); + if (checkTask.isProduceSchedulersSet()) { + result->asExplicitQuantitativeCheckResult<ValueType>().setScheduler(std::make_unique<storm::storage::Scheduler<ValueType>>(helper.extractScheduler(this->getModel()))); + } + + return result; + } + template<typename SparseMarkovAutomatonModelType> std::unique_ptr<CheckResult> SparseMarkovAutomatonCslModelChecker<SparseMarkovAutomatonModelType>::computeReachabilityRewards(Environment const& env, storm::logic::RewardMeasureType, CheckTask<storm::logic::EventuallyFormula, ValueType> const& checkTask) { storm::logic::EventuallyFormula const& eventuallyFormula = checkTask.getFormula(); diff --git a/src/storm/modelchecker/csl/SparseMarkovAutomatonCslModelChecker.h b/src/storm/modelchecker/csl/SparseMarkovAutomatonCslModelChecker.h index f18f4a374..093df17aa 100644 --- a/src/storm/modelchecker/csl/SparseMarkovAutomatonCslModelChecker.h +++ b/src/storm/modelchecker/csl/SparseMarkovAutomatonCslModelChecker.h @@ -28,7 +28,11 @@ namespace storm { // The implemented methods of the AbstractModelChecker interface. virtual bool canHandle(CheckTask<storm::logic::Formula, ValueType> const& checkTask) const override; virtual std::unique_ptr<CheckResult> computeBoundedUntilProbabilities(Environment const& env, CheckTask<storm::logic::BoundedUntilFormula, ValueType> const& checkTask) override; + virtual std::unique_ptr<CheckResult> computeNextProbabilities(Environment const& env, CheckTask<storm::logic::NextFormula, ValueType> const& checkTask) override; virtual std::unique_ptr<CheckResult> computeUntilProbabilities(Environment const& env, CheckTask<storm::logic::UntilFormula, ValueType> const& checkTask) override; + virtual std::unique_ptr<CheckResult> computeGloballyProbabilities(Environment const& env, CheckTask<storm::logic::GloballyFormula, ValueType> const& checkTask) override; + virtual std::unique_ptr<CheckResult> computeLTLProbabilities(Environment const& env, CheckTask<storm::logic::PathFormula, ValueType> const& checkTask) override; + virtual std::unique_ptr<CheckResult> computeHOAPathProbabilities(Environment const& env, CheckTask<storm::logic::HOAPathFormula, ValueType> const& checkTask) override; virtual std::unique_ptr<CheckResult> computeReachabilityRewards(Environment const& env, storm::logic::RewardMeasureType rewardMeasureType, CheckTask<storm::logic::EventuallyFormula, ValueType> const& checkTask) override; virtual std::unique_ptr<CheckResult> computeTotalRewards(Environment const& env, storm::logic::RewardMeasureType rewardMeasureType, CheckTask<storm::logic::TotalRewardFormula, ValueType> const& checkTask) override; virtual std::unique_ptr<CheckResult> computeLongRunAverageProbabilities(Environment const& env, CheckTask<storm::logic::StateFormula, ValueType> const& checkTask) override; diff --git a/src/storm/modelchecker/helper/SingleValueModelCheckerHelper.cpp b/src/storm/modelchecker/helper/SingleValueModelCheckerHelper.cpp index 796b696f8..885411b01 100644 --- a/src/storm/modelchecker/helper/SingleValueModelCheckerHelper.cpp +++ b/src/storm/modelchecker/helper/SingleValueModelCheckerHelper.cpp @@ -82,6 +82,16 @@ namespace storm { bool SingleValueModelCheckerHelper<ValueType, ModelRepresentation>::isProduceSchedulerSet() const { return _produceScheduler; } + + template <typename ValueType, storm::models::ModelRepresentation ModelRepresentation> + void SingleValueModelCheckerHelper<ValueType, ModelRepresentation>::setQualitative(bool value) { + _isQualitativeSet = value; + } + + template <typename ValueType, storm::models::ModelRepresentation ModelRepresentation> + bool SingleValueModelCheckerHelper<ValueType, ModelRepresentation>::isQualitativeSet() const { + return _isQualitativeSet; + } template class SingleValueModelCheckerHelper<double, storm::models::ModelRepresentation::Sparse>; template class SingleValueModelCheckerHelper<storm::RationalNumber, storm::models::ModelRepresentation::Sparse>; diff --git a/src/storm/modelchecker/helper/SingleValueModelCheckerHelper.h b/src/storm/modelchecker/helper/SingleValueModelCheckerHelper.h index 2246ef793..f328d5a7f 100644 --- a/src/storm/modelchecker/helper/SingleValueModelCheckerHelper.h +++ b/src/storm/modelchecker/helper/SingleValueModelCheckerHelper.h @@ -100,11 +100,22 @@ namespace storm { * @return whether an optimal scheduler shall be constructed during the computation */ bool isProduceSchedulerSet() const; + + /*! + * Sets whether the property needs to be checked qualitatively + */ + void setQualitative(bool value); + + /*! + * @return whether the property needs to be checked qualitatively + */ + bool isQualitativeSet() const; private: boost::optional<storm::solver::OptimizationDirection> _optimizationDirection; boost::optional<std::pair<storm::logic::ComparisonType, ValueType>> _valueThreshold; bool _produceScheduler; + bool _isQualitativeSet; }; } } diff --git a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp new file mode 100644 index 000000000..677695e6a --- /dev/null +++ b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp @@ -0,0 +1,364 @@ +#include "SparseLTLHelper.h" + +#include "storm/automata/LTL2DeterministicAutomaton.h" +#include "storm/automata/DeterministicAutomaton.h" + +#include "storm/environment/modelchecker/ModelCheckerEnvironment.h" + +#include "storm/logic/ExtractMaximalStateFormulasVisitor.h" + +#include "storm/modelchecker/prctl/helper/SparseDtmcPrctlHelper.h" +#include "storm/modelchecker/prctl/helper/SparseMdpPrctlHelper.h" + +#include "storm/storage/StronglyConnectedComponentDecomposition.h" +#include "storm/storage/MaximalEndComponentDecomposition.h" +#include "storm/solver/SolveGoal.h" + + +#include "storm/exceptions/InvalidPropertyException.h" + + +namespace storm { + namespace modelchecker { + namespace helper { + + template <typename ValueType, bool Nondeterministic> + SparseLTLHelper<ValueType, Nondeterministic>::SparseLTLHelper(storm::storage::SparseMatrix<ValueType> const& transitionMatrix) : _transitionMatrix(transitionMatrix) { + // Intentionally left empty. + } + + template <typename ValueType, bool Nondeterministic> + storm::storage::Scheduler<ValueType> SparseLTLHelper<ValueType, Nondeterministic>::SparseLTLHelper::extractScheduler(storm::models::sparse::Model<ValueType> const& model) { + STORM_LOG_ASSERT(this->isProduceSchedulerSet(), "Trying to get the produced optimal choices although no scheduler was requested."); + STORM_LOG_ASSERT(this->_schedulerHelper.is_initialized(), "Trying to get the produced optimal choices but none were available. Was there a computation call before?"); + + return this->_schedulerHelper.get().extractScheduler(model, this->hasRelevantStates()); + } + + + template<typename ValueType, bool Nondeterministic> + std::vector<ValueType> SparseLTLHelper<ValueType, Nondeterministic>::computeLTLProbabilities(Environment const &env, storm::logic::PathFormula const& formula, CheckFormulaCallback const& formulaChecker) { + // Replace state-subformulae by atomic propositions (APs) + storm::logic::ExtractMaximalStateFormulasVisitor::ApToFormulaMap extracted; + std::shared_ptr<storm::logic::Formula> ltlFormula = storm::logic::ExtractMaximalStateFormulasVisitor::extract(formula, extracted); + STORM_LOG_ASSERT(ltlFormula->isPathFormula(), "Unexpected formula type."); + + + // Compute Satisfaction sets for the APs (which represent the state-subformulae + auto apSets = computeApSets(extracted, formulaChecker); + + STORM_LOG_INFO("Computing LTL probabilities for formula with " << apSets.size() << " atomic proposition(s)."); + + // Compute the resulting LTL probabilities + return computeLTLProbabilities(env, ltlFormula->asPathFormula(), apSets); + + } + + template<typename ValueType, bool Nondeterministic> + std::map<std::string, storm::storage::BitVector> SparseLTLHelper<ValueType, Nondeterministic>::computeApSets(std::map<std::string, std::shared_ptr<storm::logic::Formula const>> const& extracted, CheckFormulaCallback const& formulaChecker) { + std::map<std::string, storm::storage::BitVector> apSets; + for (auto& p: extracted) { + STORM_LOG_DEBUG(" Computing satisfaction set for atomic proposition \"" << p.first << "\" <=> " << *p.second << "..."); + apSets[p.first] = formulaChecker(*p.second); + } + return apSets; + } + + + template <typename ValueType, bool Nondeterministic> + storm::storage::BitVector SparseLTLHelper<ValueType, Nondeterministic>::computeAcceptingECs(automata::AcceptanceCondition const& acceptance, storm::storage::SparseMatrix<ValueType> const& transitionMatrix, storm::storage::SparseMatrix<ValueType> const& backwardTransitions, typename transformer::DAProduct<productModelType>::ptr product) { + STORM_LOG_INFO("Computing accepting states for acceptance condition " << *acceptance.getAcceptanceExpression()); + if (acceptance.getAcceptanceExpression()->isTRUE()) { + STORM_LOG_INFO(" TRUE -> all states accepting (assumes no deadlock in the model)"); + return storm::storage::BitVector(transitionMatrix.getRowGroupCount(), true); + } else if (acceptance.getAcceptanceExpression()->isFALSE()) { + STORM_LOG_INFO(" FALSE -> all states rejecting"); + return storm::storage::BitVector(transitionMatrix.getRowGroupCount(), false); + } + + std::vector<std::vector<automata::AcceptanceCondition::acceptance_expr::ptr>> dnf = acceptance.extractFromDNF(); + + storm::storage::BitVector acceptingStates(transitionMatrix.getRowGroupCount(), false); + + std::size_t accMECs = 0; + std::size_t allMECs = 0; + + + for (auto const& conjunction : dnf) { + // Determine the set of states of the subMDP that can satisfy the condition, remove all states that would violate Fins in the conjunction. + storm::storage::BitVector allowed(transitionMatrix.getRowGroupCount(), true); + + for (auto const& literal : conjunction) { + if (literal->isTRUE()) { + // skip + } else if (literal->isFALSE()) { + allowed.clear(); + break; + } else if (literal->isAtom()) { + const cpphoafparser::AtomAcceptance& atom = literal->getAtom(); + if (atom.getType() == cpphoafparser::AtomAcceptance::TEMPORAL_FIN) { + // only deal with FIN, ignore INF here + const storm::storage::BitVector& accSet = acceptance.getAcceptanceSet(atom.getAcceptanceSet()); + if (atom.isNegated()) { + // allowed = allowed \ ~accSet = allowed & accSet + allowed &= accSet; + } else { + // allowed = allowed \ accSet = allowed & ~accSet + allowed &= ~accSet; + } + } + } + } + + if (allowed.empty()) { + // skip + continue; + } + + // Compute MECs in the allowed fragment + storm::storage::MaximalEndComponentDecomposition<ValueType> mecs(transitionMatrix, backwardTransitions, allowed); + allMECs += mecs.size(); + for (const auto& mec : mecs) { + + bool accepting = true; + for (auto const& literal : conjunction) { + if (literal->isTRUE()) { + // skip + + } else if (literal->isFALSE()) { + accepting = false; + break; + } else if (literal->isAtom()) { + const cpphoafparser::AtomAcceptance& atom = literal->getAtom(); + const storm::storage::BitVector& accSet = acceptance.getAcceptanceSet(atom.getAcceptanceSet()); + if (atom.getType() == cpphoafparser::AtomAcceptance::TEMPORAL_INF) { + if (atom.isNegated()) { + if (!mec.containsAnyState(~accSet)) { + accepting = false; + break; + } + } else { + if (!mec.containsAnyState(accSet)) { + accepting = false; + break; + } + + } + + } else if (atom.getType() == cpphoafparser::AtomAcceptance::TEMPORAL_FIN) { + // Do only sanity checks here. + STORM_LOG_ASSERT(atom.isNegated() ? !mec.containsAnyState(~accSet) : !mec.containsAnyState(accSet), "MEC contains Fin-states, which should have been removed"); + } + } + } + + if (accepting) { + accMECs++; + + for (auto const &stateChoicePair : mec) { + acceptingStates.set(stateChoicePair.first); + } + + if (this->isProduceSchedulerSet()) { + // save choices for states that weren't assigned to any other MEC yet. + this->_schedulerHelper.get().saveProductEcChoices(acceptance, mec, conjunction, product); + + } + } + + } + } + + STORM_LOG_INFO("Found " << acceptingStates.getNumberOfSetBits() << " states in " << accMECs << " accepting MECs (considered " << allMECs << " MECs)."); + + return acceptingStates; + } + + template <typename ValueType, bool Nondeterministic> + storm::storage::BitVector SparseLTLHelper<ValueType, Nondeterministic>::computeAcceptingBCCs(automata::AcceptanceCondition const& acceptance, storm::storage::SparseMatrix<ValueType> const& transitionMatrix) { + storm::storage::StronglyConnectedComponentDecomposition<ValueType> bottomSccs(transitionMatrix, storage::StronglyConnectedComponentDecompositionOptions().onlyBottomSccs().dropNaiveSccs()); + storm::storage::BitVector acceptingStates(transitionMatrix.getRowGroupCount(), false); + + std::size_t checkedBSCCs = 0, acceptingBSCCs = 0, acceptingBSCCStates = 0; + for (auto& scc : bottomSccs) { + checkedBSCCs++; + if (acceptance.isAccepting(scc)) { + acceptingBSCCs++; + for (auto& state : scc) { + acceptingStates.set(state); + acceptingBSCCStates++; + } + } + } + STORM_LOG_INFO("BSCC analysis: " << acceptingBSCCs << " of " << checkedBSCCs << " BSCCs were acceptingStates (" << acceptingBSCCStates << " states in acceptingStates BSCCs)."); + return acceptingStates; + } + + + template<typename ValueType, bool Nondeterministic> + std::vector<ValueType> SparseLTLHelper<ValueType, Nondeterministic>::computeDAProductProbabilities(Environment const& env, storm::automata::DeterministicAutomaton const& da, std::map<std::string, storm::storage::BitVector>& apSatSets) { + const storm::automata::APSet& apSet = da.getAPSet(); + + + std::vector<storm::storage::BitVector> statesForAP; + for (const std::string& ap : apSet.getAPs()) { + auto it = apSatSets.find(ap); + STORM_LOG_THROW(it != apSatSets.end(), storm::exceptions::InvalidOperationException, "Deterministic automaton has AP " << ap << ", does not appear in formula"); + + statesForAP.push_back(std::move(it->second)); + } + + storm::storage::BitVector statesOfInterest; + + if (this->hasRelevantStates()) { + statesOfInterest = this->getRelevantStates(); + } else { + // Product from all model states + statesOfInterest = storm::storage::BitVector(this->_transitionMatrix.getRowGroupCount(), true); + } + + + STORM_LOG_INFO("Building "+ (Nondeterministic ? std::string("MDP-DA") : std::string("DTMC-DA")) +" product with deterministic automaton, starting from " << statesOfInterest.getNumberOfSetBits() << " model states..."); + transformer::DAProductBuilder productBuilder(da, statesForAP); + + auto product = productBuilder.build<productModelType>(this->_transitionMatrix, statesOfInterest); + + + STORM_LOG_INFO("Product "+ (Nondeterministic ? std::string("MDP-DA") : std::string("DTMC-DA")) +" has " << product->getProductModel().getNumberOfStates() << " states and " + << product->getProductModel().getNumberOfTransitions() << " transitions."); + + // Prepare scheduler + if (this->isProduceSchedulerSet()) { + STORM_LOG_THROW(Nondeterministic, storm::exceptions::InvalidOperationException, "Scheduler export only supported for nondeterministic models."); + this->_schedulerHelper.emplace(product->getProductModel().getNumberOfStates()); + } + + // Compute accepting states + storm::storage::BitVector acceptingStates; + if (Nondeterministic) { + STORM_LOG_INFO("Computing MECs and checking for acceptance..."); + acceptingStates = computeAcceptingECs(*product->getAcceptance(), product->getProductModel().getTransitionMatrix(), product->getProductModel().getBackwardTransitions(), product); + + } else { + STORM_LOG_INFO("Computing BSCCs and checking for acceptance..."); + acceptingStates = computeAcceptingBCCs(*product->getAcceptance(), product->getProductModel().getTransitionMatrix()); + + } + + if (acceptingStates.empty()) { + STORM_LOG_INFO("No accepting states, skipping probability computation."); + if (this->isProduceSchedulerSet()) { + this->_schedulerHelper.get().setRandom(); + } + std::vector<ValueType> numericResult(this->_transitionMatrix.getRowGroupCount(), storm::utility::zero<ValueType>()); + return numericResult; + } + + STORM_LOG_INFO("Computing probabilities for reaching accepting components..."); + + storm::storage::BitVector bvTrue(product->getProductModel().getNumberOfStates(), true); + storm::storage::BitVector soiProduct(product->getStatesOfInterest()); + + // Create goal for computeUntilProbabilities, always compute maximizing probabilities + storm::solver::SolveGoal<ValueType> solveGoalProduct; + if (this->isValueThresholdSet()) { + solveGoalProduct = storm::solver::SolveGoal<ValueType>(OptimizationDirection::Maximize, this->getValueThresholdComparisonType(), this->getValueThresholdValue(), std::move(soiProduct)); + } else { + solveGoalProduct = storm::solver::SolveGoal<ValueType>(OptimizationDirection::Maximize); + solveGoalProduct.setRelevantValues(std::move(soiProduct)); + } + + std::vector<ValueType> prodNumericResult; + + + if (Nondeterministic) { + MDPSparseModelCheckingHelperReturnType<ValueType> prodCheckResult = storm::modelchecker::helper::SparseMdpPrctlHelper<ValueType>::computeUntilProbabilities(env, + std::move(solveGoalProduct), + product->getProductModel().getTransitionMatrix(), + product->getProductModel().getBackwardTransitions(), + bvTrue, + acceptingStates, + this->isQualitativeSet(), + this->isProduceSchedulerSet() // Whether to create memoryless scheduler for the Model-DA Product. + ); + prodNumericResult = std::move(prodCheckResult.values); + + if (this->isProduceSchedulerSet()) { + this->_schedulerHelper.get().prepareScheduler(da.getNumberOfStates(), acceptingStates, std::move(prodCheckResult.scheduler), productBuilder, product, statesOfInterest, this->_transitionMatrix); + } + + } else { + prodNumericResult = storm::modelchecker::helper::SparseDtmcPrctlHelper<ValueType>::computeUntilProbabilities(env, + std::move(solveGoalProduct), + product->getProductModel().getTransitionMatrix(), + product->getProductModel().getBackwardTransitions(), + bvTrue, + acceptingStates, + this->isQualitativeSet()); + } + + std::vector<ValueType> numericResult = product->projectToOriginalModel(this->_transitionMatrix.getRowGroupCount(), prodNumericResult); + + return numericResult; + } + + + template<typename ValueType, bool Nondeterministic> + std::vector <ValueType> SparseLTLHelper<ValueType, Nondeterministic>::computeLTLProbabilities(Environment const& env, storm::logic::PathFormula const& formula, std::map<std::string, storm::storage::BitVector>& apSatSets) { + std::shared_ptr<storm::logic::Formula const> ltlFormula; + STORM_LOG_THROW((!Nondeterministic) || this->isOptimizationDirectionSet(), storm::exceptions::InvalidPropertyException, "Formula needs to specify whether minimal or maximal values are to be computed on nondeterministic model."); + if (Nondeterministic && this->getOptimizationDirection() == OptimizationDirection::Minimize) { + // negate formula in order to compute 1-Pmax[!formula] + ltlFormula = std::make_shared<storm::logic::UnaryBooleanPathFormula>(storm::logic::UnaryBooleanOperatorType::Not, formula.asSharedPointer()); + STORM_LOG_INFO("Computing Pmin, proceeding with negated LTL formula."); + } else { + ltlFormula = formula.asSharedPointer(); + } + + STORM_LOG_INFO("Resulting LTL path formula: " << ltlFormula->toString()); + STORM_LOG_INFO(" in prefix format: " << ltlFormula->toPrefixString()); + + // Convert LTL formula to a deterministic automaton + std::shared_ptr<storm::automata::DeterministicAutomaton> da; + if (env.modelchecker().isLtl2daToolSet()) { + // Use the external tool given via ltl2da + da = storm::automata::LTL2DeterministicAutomaton::ltl2daExternalTool(*ltlFormula, env.modelchecker().getLtl2daTool()); + } + else { + // Use the internal tool (Spot) + // For nondeterministic models the acceptance condition is transformed into DNF + da = storm::automata::LTL2DeterministicAutomaton::ltl2daSpot(*ltlFormula, Nondeterministic); + } + + STORM_LOG_INFO("Deterministic automaton for LTL formula has " + << da->getNumberOfStates() << " states, " + << da->getAPSet().size() << " atomic propositions and " + << *da->getAcceptance()->getAcceptanceExpression() << " as acceptance condition." << std::endl); + + + std::vector<ValueType> numericResult = computeDAProductProbabilities(env, *da, apSatSets); + + if(Nondeterministic && this->getOptimizationDirection()==OptimizationDirection::Minimize) { + // compute 1-Pmax[!fomula] + for (auto& value : numericResult) { + value = storm::utility::one<ValueType>() - value; + } + } + + return numericResult; + } + + + template class SparseLTLHelper<double, false>; + template class SparseLTLHelper<double, true>; + +#ifdef STORM_HAVE_CARL + template class SparseLTLHelper<storm::RationalNumber, false>; + template class SparseLTLHelper<storm::RationalNumber, true>; + template class SparseLTLHelper<storm::RationalFunction, false>; + +#endif + + } + } +} \ No newline at end of file diff --git a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h new file mode 100644 index 000000000..ff19e475c --- /dev/null +++ b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h @@ -0,0 +1,119 @@ +#include "storm/modelchecker/helper/SingleValueModelCheckerHelper.h" + +#include "storm/modelchecker/helper/ltl/internal/SparseLTLSchedulerHelper.h" + +#include "storm/storage/SparseMatrix.h" +#include "storm/models/sparse/Dtmc.h" +#include "storm/models/sparse/Mdp.h" +#include "storm/transformer/DAProductBuilder.h" + + +namespace storm { + + class Environment; + + namespace logic { + class Formula; + class PathFormula; + } + namespace automata { + class DeterministicAutomaton; + } + + namespace modelchecker { + namespace helper { + + /*! + * Helper class for LTL model checking + * @tparam ValueType the type a value can have + * @tparam Nondeterministic A flag indicating if there is nondeterminism in the Model (MDP) + */ + template<typename ValueType, bool Nondeterministic> + class SparseLTLHelper: public SingleValueModelCheckerHelper<ValueType, storm::models::ModelRepresentation::Sparse> { + + public: + + typedef std::function<storm::storage::BitVector(storm::logic::Formula const&)> CheckFormulaCallback; + + /*! + * The type of the product model (DTMC or MDP) that is used during the computation. + */ + using productModelType = typename std::conditional<Nondeterministic, storm::models::sparse::Mdp<ValueType>, storm::models::sparse::Dtmc<ValueType>>::type; + + /*! + * Initializes the helper for a discrete time model (i.e. DTMC, MDP) + * @param transitionMatrix the transition matrix of the model + */ + SparseLTLHelper(storm::storage::SparseMatrix<ValueType> const& transitionMatrix); + + + /*! + * @pre before calling this, a computation call should have been performed during which scheduler production was enabled. + * @param model the model + * @return a new scheduler containing optimal choices for each state that yield the long run average values of the most recent call. + */ + storm::storage::Scheduler<ValueType> extractScheduler(storm::models::sparse::Model<ValueType> const& model); + + /*! + * Computes the LTL probabilities + * @param formula the LTL formula (allowing PCTL* like nesting) + * @param formulaChecker lambda that evaluates sub-formulas checks the provided formula and returns the set of states in which the formula holds< + * @return a value for each state + */ + std::vector<ValueType> computeLTLProbabilities(Environment const &env, storm::logic::PathFormula const& formula, CheckFormulaCallback const& formulaChecker); + + /*! + * Computes the states that are satisfying the AP. + * @param extracted mapping from Ap to formula + * @param formulaChecker lambda that checks the provided formula and returns the set of states in which the formula holds + * @return mapping from AP to satisfaction sets + */ + static std::map<std::string, storm::storage::BitVector> computeApSets(std::map<std::string, std::shared_ptr<storm::logic::Formula const>> const& extracted, CheckFormulaCallback const& formulaChecker); + + /*! + * Computes the (maximizing) probabilities for the constructed DA product + * @param da the DA to build the product with + * @param apSatSets the atomic propositions and satisfaction sets + * @return a value for each state + */ + std::vector<ValueType> computeDAProductProbabilities(Environment const& env, storm::automata::DeterministicAutomaton const& da, std::map<std::string, storm::storage::BitVector>& apSatSets); + + /*! + * Computes the LTL probabilities + * @param formula the LTL formula (without PCTL*-like nesting) + * @param apSatSets a mapping from all atomic propositions occuring in the formula to the corresponding satisfaction set + * @return a value for each state + */ + std::vector<ValueType> computeLTLProbabilities(Environment const &env, storm::logic::PathFormula const& formula, std::map<std::string, storm::storage::BitVector>& apSatSets); + + private: + /*! + * Computes a set S of states that admit a probability 1 strategy of satisfying the given acceptance condition (in DNF). + * More precisely, let + * accEC be the set of states that are contained in end components that satisfy the acceptance condition + * and let + * P1acc be the set of states that satisfy Pmax=1[ F accEC ]. + * This function then computes a set that contains accEC and is contained by P1acc. + * However, if the acceptance condition consists of 'true', the whole state space can be returned. + * @param acceptance the acceptance condition (in DNF) + * @param transitionMatrix the transition matrix of the model + * @param backwardTransitions the reversed transition relation + */ + storm::storage::BitVector computeAcceptingECs(automata::AcceptanceCondition const& acceptance, storm::storage::SparseMatrix<ValueType> const& transitionMatrix, storm::storage::SparseMatrix<ValueType> const& backwardTransitions, typename transformer::DAProduct<productModelType>::ptr product); + + /*! + * Computes a set S of states that are contained in BSCCs that satisfy the given acceptance conditon. + * @param acceptance the acceptance condition + * @param transitionMatrix the transition matrix of the model + */ + storm::storage::BitVector computeAcceptingBCCs(automata::AcceptanceCondition const& acceptance, storm::storage::SparseMatrix<ValueType> const& transitionMatrix); + + + storm::storage::SparseMatrix<ValueType> const& _transitionMatrix; + + boost::optional<storm::modelchecker::helper::internal::SparseLTLSchedulerHelper<ValueType, Nondeterministic>> _schedulerHelper; + + }; + } + } +} \ No newline at end of file diff --git a/src/storm/modelchecker/helper/ltl/internal/SparseLTLSchedulerHelper.cpp b/src/storm/modelchecker/helper/ltl/internal/SparseLTLSchedulerHelper.cpp new file mode 100644 index 000000000..b4a599634 --- /dev/null +++ b/src/storm/modelchecker/helper/ltl/internal/SparseLTLSchedulerHelper.cpp @@ -0,0 +1,335 @@ +#include "SparseLTLSchedulerHelper.h" +#include "storm/storage/memorystructure/MemoryStructure.h" +#include "storm/storage/memorystructure/MemoryStructureBuilder.h" +#include "storm/transformer/DAProductBuilder.h" + +#include "storm/utility/graph.h" + + +namespace storm { + namespace modelchecker { + namespace helper { + namespace internal { + + template<typename ValueType, bool Nondeterministic> + const uint_fast64_t SparseLTLSchedulerHelper<ValueType, Nondeterministic>::DEFAULT_INFSET = 0; + + template<typename ValueType, bool Nondeterministic> + uint_fast64_t SparseLTLSchedulerHelper<ValueType, Nondeterministic>::InfSetPool::getOrCreateIndex(storm::storage::BitVector&& infSet) { + auto it = std::find(_storage.begin(), _storage.end(), infSet); + if (it == _storage.end()) { + _storage.push_back(std::move(infSet)); + return _storage.size() - 1; + } else { + return distance(_storage.begin(), it); + } + } + + template<typename ValueType, bool Nondeterministic> + storm::storage::BitVector const& SparseLTLSchedulerHelper<ValueType, Nondeterministic>::InfSetPool::get(uint_fast64_t index) const { + STORM_LOG_ASSERT(index < size(), "inf set index " << index << " is invalid."); + return _storage[index]; + } + + template<typename ValueType, bool Nondeterministic> + uint_fast64_t SparseLTLSchedulerHelper<ValueType, Nondeterministic>::InfSetPool::size() const { + return _storage.size(); + } + + template<typename ValueType, bool Nondeterministic> + SparseLTLSchedulerHelper<ValueType, Nondeterministic>::SparseLTLSchedulerHelper(uint_fast64_t numProductStates) : _randomScheduler(false), _accInfSets(numProductStates, boost::none) { + // Intentionally left empty. + } + + template<typename ValueType, bool Nondeterministic> + uint_fast64_t SparseLTLSchedulerHelper<ValueType, Nondeterministic>::SparseLTLSchedulerHelper::getMemoryState(uint_fast64_t daState, uint_fast64_t infSet) { + return (daState * _infSets.size())+ infSet; + } + + template<typename ValueType, bool Nondeterministic> + void SparseLTLSchedulerHelper<ValueType, Nondeterministic>::SparseLTLSchedulerHelper::setRandom() { + this->_randomScheduler = true; + } + + template<typename ValueType, bool Nondeterministic> + void SparseLTLSchedulerHelper<ValueType, Nondeterministic>::saveProductEcChoices(automata::AcceptanceCondition const& acceptance, storm::storage::MaximalEndComponent const& mec, std::vector<automata::AcceptanceCondition::acceptance_expr::ptr> const& conjunction, typename transformer::DAProduct<productModelType>::ptr product) { + // Save all states contained in this MEC and find out whether there is some overlap with another, already processed accepting mec + storm::storage::BitVector mecStates(product->getProductModel().getNumberOfStates(), false); + storm::storage::BitVector overlapStates; + + for (auto const &stateChoicePair : mec) { + if (_accInfSets[stateChoicePair.first].is_initialized()) { + overlapStates.resize(product->getProductModel().getNumberOfStates(), false); + overlapStates.set(stateChoicePair.first); + } else { + mecStates.set(stateChoicePair.first); + } + } + + if (!overlapStates.empty()) { + // If all the states in mec are overlapping, we are done already. + if (!mecStates.empty()) { + // Simply Reach the overlapStates almost surely + // set inf sets + for (auto mecState : mecStates) { + STORM_LOG_ASSERT(!_accInfSets[mecState].is_initialized(), "accepting inf sets were already defined for a MEC state which is not expected."); + _accInfSets[mecState] = std::set<uint_fast64_t>({DEFAULT_INFSET}); + } + + // Define scheduler choices for the states in this MEC (that are not in any other MEC) + // Compute a scheduler that, with prob=1 reaches the overlap states + storm::storage::Scheduler<ValueType> mecScheduler(product->getProductModel().getNumberOfStates()); + storm::utility::graph::computeSchedulerProb1E<ValueType>(mecStates, product->getProductModel().getTransitionMatrix(), product->getProductModel().getBackwardTransitions(), mecStates, overlapStates, mecScheduler); + + // Extract scheduler choices + for (auto pState : mecStates) { + this->_producedChoices.insert({std::make_tuple(product->getModelState(pState), product->getAutomatonState(pState), DEFAULT_INFSET), mecScheduler.getChoice(pState)}); + } + } + } else { + // No overlap! Let's do actual work. + + // We know the MEC satisfied the conjunction: Save InfSets. + std::set<uint_fast64_t> infSetIds; + for (auto const& literal : conjunction) { + if (literal->isAtom()) { + const cpphoafparser::AtomAcceptance &atom = literal->getAtom(); + if (atom.getType() == cpphoafparser::AtomAcceptance::TEMPORAL_INF) { + storm::storage::BitVector infSet; + if (atom.isNegated()) { + infSet = ~acceptance.getAcceptanceSet(atom.getAcceptanceSet()); + } else { + infSet = acceptance.getAcceptanceSet(atom.getAcceptanceSet()); + } + // Save new InfSet + infSetIds.insert(_infSets.getOrCreateIndex(std::move(infSet))); + } + // A TEMPORAL_FIN atom can be ignored at this point since the mec is already known to only contain "allowed" states + } + // TRUE literals can be ignored since those will be satisfied anyway + // FALSE literals are not possible here since the MEC is known to be accepting. + } + if (infSetIds.empty()) { + // There might not be any infSet at this point (e.g. because all literals are TEMPORAL_FIN atoms). We need at least one infset, though + infSetIds.insert(_infSets.getOrCreateIndex(storm::storage::BitVector(product->getProductModel().getNumberOfStates(), true))); + } + + // Save the InfSets into the _accInfSets for states in this MEC + for (auto const &mecState : mecStates) { + STORM_LOG_ASSERT(!_accInfSets[mecState].is_initialized(), "accepting inf sets were already defined for a MEC state which is not expected."); + _accInfSets[mecState].emplace(infSetIds); + } + + // Define scheduler choices for the states in this MEC (that are not in any other MEC) + // The resulting scheduler will visit each InfSet inf often + for (uint_fast64_t id : infSetIds) { + // Scheduler that satisfies the MEC acceptance condition + storm::storage::Scheduler<ValueType> mecScheduler(product->getProductModel().getNumberOfStates()); + + storm::storage::BitVector infStatesWithinMec = _infSets.get(id) & mecStates; + // States not in InfSet: Compute a scheduler that, with prob=1, reaches the infSet via mecStates + storm::utility::graph::computeSchedulerProb1E<ValueType>(mecStates, product->getProductModel().getTransitionMatrix(), product->getProductModel().getBackwardTransitions(), mecStates, infStatesWithinMec, mecScheduler); + + // States that already reached the InfSet + for (auto pState : infStatesWithinMec) { + // Prob1E sets an arbitrary choice for the psi states, but we want to stay in this accepting MEC. + mecScheduler.setChoice(*mec.getChoicesForState(pState).begin() - product->getProductModel().getTransitionMatrix().getRowGroupIndices()[pState], pState); + } + + // Extract scheduler choices + for (auto pState : mecStates) { + // We want to reach the InfSet, save choice: <s, q, InfSetID> ---> choice + this->_producedChoices.insert({std::make_tuple(product->getModelState(pState), product->getAutomatonState(pState), id), mecScheduler.getChoice(pState)}); + } + } + } + } + + + template<typename ValueType, bool Nondeterministic> + void SparseLTLSchedulerHelper<ValueType, Nondeterministic>::prepareScheduler(uint_fast64_t numDaStates, storm::storage::BitVector const& acceptingProductStates, std::unique_ptr<storm::storage::Scheduler<ValueType>> reachScheduler, transformer::DAProductBuilder const& productBuilder, typename transformer::DAProduct<productModelType>::ptr product, storm::storage::BitVector const& modelStatesOfInterest, storm::storage::SparseMatrix<ValueType> const& transitionMatrix) { + STORM_LOG_ASSERT(_infSets.size() > 0, "There is no inf set. Were the accepting ECs processed before?"); + + // Compute size of the resulting memory structure: A state <q, infSet> is encoded as (q* (|infSets|))+ |infSet| + uint64 numMemoryStates = (numDaStates) * (_infSets.size()); + _dontCareStates = std::vector<storm::storage::BitVector>(numMemoryStates, storm::storage::BitVector(transitionMatrix.getRowGroupCount(), false)); + + // Set choices for states or consider them "dontCare" + for (storm::storage::sparse::state_type automatonState= 0; automatonState < numDaStates; ++automatonState) { + for (storm::storage::sparse::state_type modelState = 0; modelState < transitionMatrix.getRowGroupCount(); ++modelState) { + + if (!product->isValidProductState(modelState, automatonState)) { + // If the state <s,q> does not occur in the product model, all the infSet combinations are irrelevant for the scheduler. + for (uint_fast64_t infSet = 0; infSet < _infSets.size(); ++infSet) { + _dontCareStates[getMemoryState(automatonState, infSet)].set(modelState, true); + } + } else { + auto pState = product->getProductStateIndex(modelState, automatonState); + if (acceptingProductStates.get(pState)) { + // For states in accepting ECs set the MEC-scheduler. Missing combinations are "dontCare", they are not reachable using the scheduler choices. + for (uint_fast64_t infSet = 0; infSet < _infSets.size(); ++infSet) { + if (_producedChoices.count(std::make_tuple(product->getModelState(pState), product->getAutomatonState(pState), infSet)) == 0 ) { + _dontCareStates[getMemoryState(product->getAutomatonState(pState), infSet)].set(product->getModelState(pState), true); + } + } + + } else { + // Extract the choices of the REACH-scheduler (choices to reach an acc. MEC) for the MDP-DA product: <s,q> -> choice. The memory structure corresponds to the "0th" copy of the DA (DEFAULT_INFSET). + this->_accInfSets[pState] = std::set<uint_fast64_t>({DEFAULT_INFSET}); + if (reachScheduler->isDontCare(pState)) { + // Mark the maybe States of the untilProbability scheduler as "dontCare" + _dontCareStates[getMemoryState(product->getAutomatonState(pState), DEFAULT_INFSET)].set(product->getModelState(pState), true); + } else { + // Set choice For non-accepting states that are not in any accepting EC + this->_producedChoices.insert({std::make_tuple(product->getModelState(pState), product->getAutomatonState(pState), DEFAULT_INFSET), reachScheduler->getChoice(pState)}); + }; + // All other InfSet combinations are unreachable (dontCare) + static_assert(DEFAULT_INFSET == 0, "This code assumes that the default infset is 0"); + for (uint_fast64_t infSet = 1; infSet < _infSets.size(); ++infSet) { + _dontCareStates[getMemoryState(product->getAutomatonState(pState), infSet)].set(product->getModelState(pState), true); + } + } + } + } + } + + // Prepare the memory structure. For that, we need: transitions, initialMemoryStates (and memoryStateLabeling) + + // The next move function of the memory, will be build based on the transitions of the DA and jumps between InfSets. + _memoryTransitions = std::vector<std::vector<storm::storage::BitVector>>(numMemoryStates, std::vector<storm::storage::BitVector>(numMemoryStates, storm::storage::BitVector(transitionMatrix.getRowGroupCount(), false))); + for (storm::storage::sparse::state_type automatonFrom = 0; automatonFrom < numDaStates; ++automatonFrom) { + for (storm::storage::sparse::state_type modelState = 0; modelState < transitionMatrix.getRowGroupCount(); ++modelState) { + uint_fast64_t automatonTo = productBuilder.getSuccessor(automatonFrom, modelState); + + if (product->isValidProductState(modelState, automatonTo)) { + uint_fast64_t daProductState = product->getProductStateIndex(modelState, automatonTo); + STORM_LOG_ASSERT(_accInfSets[daProductState] != boost::none, "The list of InfSets for the product state <" <<modelState<< ", " << automatonTo<<"> is undefined."); + std::set<uint_fast64_t> const& daProductStateInfSets = _accInfSets[daProductState].get(); + // Add the modelState to one outgoing transition of all states of the form <automatonFrom, InfSet> + // For non-accepting states that are not in any accepting EC and for overlapping accepting ECs we always use the '0th' copy of the DA. + // For the states in accepting ECs that do not overlap we cycle through copies 0,1,2, ... k of the DA (skipping copies whose inf-sets are not needed for the accepting EC). + for (uint_fast64_t currentInfSet = 0; currentInfSet < _infSets.size(); ++currentInfSet) { + uint_fast64_t newInfSet; + // Check if we need to switch the inf set (i.e. the DA copy) + if (daProductStateInfSets.count(currentInfSet) == 0) { + // This infSet is not relevant for the daProductState. We need to switch to a copy representing a relevant infset. + newInfSet = *daProductStateInfSets.begin(); + } else if (daProductStateInfSets.size() > 1 && (_infSets.get(currentInfSet).get(daProductState))) { + // We have reached a state from the current infSet and thus need to move on to the next infSet in the list. + // Note that if the list contains just a single item, the switch would have no effect. + // In particular, this is the case for states that are not in an accepting MEC as those only have DEFAULT_INFSET in their list + auto nextInfSetIt = daProductStateInfSets.find(currentInfSet); + STORM_LOG_ASSERT(nextInfSetIt != daProductStateInfSets.end(), "The list of InfSets for the product state <" <<modelState<< ", " << automatonTo<<"> does not contain the infSet " << currentInfSet); + nextInfSetIt++; + if (nextInfSetIt == daProductStateInfSets.end()) { + // Start again. + nextInfSetIt = daProductStateInfSets.begin(); + } + newInfSet = *nextInfSetIt; + } else { + // In all other cases we can keep the current inf set (i.e. the DA copy) + newInfSet = currentInfSet; + } + _memoryTransitions[getMemoryState(automatonFrom, currentInfSet)][getMemoryState(automatonTo, newInfSet)].set(modelState); + } + } + } + } + // Finished creation of transitions. + + // Find initial memory states + this->_memoryInitialStates = std::vector<uint_fast64_t>(transitionMatrix.getRowGroupCount()); + // Save for each relevant model state its initial memory state (get the s-successor q of q0) + for (storm::storage::sparse::state_type modelState : modelStatesOfInterest) { + storm::storage::sparse::state_type automatonState = productBuilder.getInitialState(modelState); + STORM_LOG_ASSERT(product->isValidProductState(modelState, automatonState), "The memory successor state for the model state "<< modelState << "does not exist in the DA-Model Product."); + STORM_LOG_ASSERT(_accInfSets[product->getProductStateIndex(modelState, automatonState)] != boost::none, "The list of InfSets for the product state <" <<modelState<< ", " << automatonState<<"> is undefined."); + // Start in the first InfSet of <s, q> + auto infSet = _accInfSets[product->getProductStateIndex(modelState, automatonState)].get().begin(); + _memoryInitialStates[modelState] = getMemoryState(automatonState, *infSet); + } + } + + template<typename ValueType, bool Nondeterministic> + storm::storage::Scheduler<ValueType> SparseLTLSchedulerHelper<ValueType, Nondeterministic>::SparseLTLSchedulerHelper::extractScheduler(storm::models::sparse::Model<ValueType> const& model, bool onlyInitialStatesRelevant) { + + if (_randomScheduler) { + storm::storage::Scheduler<ValueType> scheduler(model.getNumberOfStates()); + for (storm::storage::sparse::state_type state = 0; state < model.getNumberOfStates(); ++state) { + scheduler.setChoice(0, state); + + } + return scheduler; + } + + // Otherwise, we compute a scheduler with memory. + + // Create a memory structure for the MDP scheduler with memory. If hasRelevantStates is set, we only consider initial model states relevant. + auto memoryBuilder = storm::storage::MemoryStructureBuilder<ValueType>(this->_memoryTransitions.size(), model, onlyInitialStatesRelevant); + + // Build the transitions between the memory states: startState to goalState using modelStates (transitionVector). + for (storm::storage::sparse::state_type startState = 0; startState < this->_memoryTransitions.size(); ++startState) { + for (storm::storage::sparse::state_type goalState = 0; goalState < this->_memoryTransitions.size(); ++goalState) { + // Bitvector that represents modelStates the model states that trigger this transition. + memoryBuilder.setTransition(startState, goalState, this->_memoryTransitions[startState][goalState]); + } + } + + // InitialMemoryStates: Assign an initial memory state model states + if (onlyInitialStatesRelevant) { + // Only consider initial model states + for (uint_fast64_t modelState : model.getInitialStates()) { + memoryBuilder.setInitialMemoryState(modelState, this->_memoryInitialStates[modelState]); + } + } else { + // All model states are relevant + for (uint_fast64_t modelState = 0; modelState < model.getNumberOfStates(); ++modelState) { + memoryBuilder.setInitialMemoryState(modelState, this->_memoryInitialStates[modelState]); + } + } + + // Build the memoryStructure. + storm::storage::MemoryStructure memoryStructure = memoryBuilder.build(); + + // Create a scheduler (with memory) for the model from the REACH and MEC scheduler of the MDP-DA-product model. + storm::storage::Scheduler<ValueType> scheduler(model.getNumberOfStates(), memoryStructure); + + // Use choices in the product model to create a choice based on model state and memory state + for (const auto &choice : this->_producedChoices) { + // <s, q, InfSet> -> choice + storm::storage::sparse::state_type modelState = std::get<0>(choice.first); + storm::storage::sparse::state_type daState = std::get<1>(choice.first); + uint_fast64_t infSet = std::get<2>(choice.first); + STORM_LOG_ASSERT(!this->_dontCareStates[getMemoryState(daState, infSet)].get(modelState), "Tried to set choice for dontCare state."); + scheduler.setChoice(choice.second, modelState, getMemoryState(daState, infSet)); + } + + // Set "dontCare" states + for (uint_fast64_t memoryState = 0; memoryState < this->_dontCareStates.size(); ++memoryState) { + for (auto state : this->_dontCareStates[memoryState]) { + scheduler.setDontCare(state, memoryState); + } + } + + // Sanity check for created scheduler. + STORM_LOG_ASSERT(scheduler.isDeterministicScheduler(), "Expected a deterministic scheduler"); + STORM_LOG_ASSERT(!scheduler.isPartialScheduler(), "Expected a fully defined scheduler"); + + return scheduler; + + } + + template class SparseLTLSchedulerHelper<double, false>; + template class SparseLTLSchedulerHelper<double, true>; + +#ifdef STORM_HAVE_CARL + template class SparseLTLSchedulerHelper<storm::RationalNumber, false>; + template class SparseLTLSchedulerHelper<storm::RationalNumber, true>; + template class SparseLTLSchedulerHelper<storm::RationalFunction, false>; + +#endif + + } + } + } +} \ No newline at end of file diff --git a/src/storm/modelchecker/helper/ltl/internal/SparseLTLSchedulerHelper.h b/src/storm/modelchecker/helper/ltl/internal/SparseLTLSchedulerHelper.h new file mode 100644 index 000000000..5f22a698a --- /dev/null +++ b/src/storm/modelchecker/helper/ltl/internal/SparseLTLSchedulerHelper.h @@ -0,0 +1,138 @@ +#include "storm/storage/Scheduler.h" +#include "storm/models/sparse/Dtmc.h" +#include "storm/models/sparse/Mdp.h" +#include "storm/storage/MaximalEndComponent.h" +#include "storm/transformer/DAProductBuilder.h" + +namespace storm { + + + namespace modelchecker { + namespace helper { + namespace internal { + + /*! + * Helper class for scheduler construction in LTL model checking + * @tparam ValueType the type a value can have + * @tparam Nondeterministic A flag indicating if there is nondeterminism in the Model (MDP) + */ + template<typename ValueType, bool Nondeterministic> + class SparseLTLSchedulerHelper { + + public: + /*! + * The type of the product model (DTMC or MDP) that is used during the computation. + */ + using productModelType = typename std::conditional<Nondeterministic, storm::models::sparse::Mdp<ValueType>, storm::models::sparse::Dtmc<ValueType>>::type; + + /*! + * Initializes the helper. + * @param numProductStates number of product states + */ + SparseLTLSchedulerHelper(uint_fast64_t numProductStates); + + + /*! + * Set the scheduler choices to random. + */ + void setRandom(); + + /*! + * Save choices for states in the accepting end component of the DA-Model product. + * We know the EC satisfies the given conjunction of the acceptance condition. Therefore, we want to reach each infinity set in the conjunction infinitely often. + * Choices are of the Form <s, q, InfSetID> -> choice. + * + * @note The given end component might overlap with another accepting EC (that potentially satisfies another conjunction of the DNF-acceptance condition). + * If this is the case, this method will set a scheduler under which the states of the overlapping EC are reached almost surely. + * This method only sets new choices for states that are not in any other accepting EC (yet). + * + * @param acceptance the acceptance condition (in DNF) + * @param mec the accepting end component which shall only contain states that can be visited infinitely often (without violating the acc cond.) + * @param conjunction the conjunction satisfied by the end component + * @param product the product model + */ + void saveProductEcChoices(automata::AcceptanceCondition const& acceptance, storm::storage::MaximalEndComponent const& mec, std::vector<automata::AcceptanceCondition::acceptance_expr::ptr> const& conjunction, typename transformer::DAProduct<productModelType>::ptr product); + + /*! + * Extracts scheduler choices and creates the memory structure for the LTL-Scheduler. + * + * @pre saveProductEcChoices has been called on some mec before, in particular there must be at least one accepting product state. + * + * @param numDaStates number of DA-states + * @param acceptingProductStates states in accepting end components of the model-DA product + * @param reachScheduler the scheduler ensuring to reach some acceptingState, defined on the model-DA product + * @param productBuilder the product builder + * @param product the model-DA product + * @param modelStatesOfInterest relevant states of the model + * @param transitionMatrix the transition matrix of the model + */ + void prepareScheduler(uint_fast64_t numDaStates, storm::storage::BitVector const& acceptingProductStates, std::unique_ptr<storm::storage::Scheduler<ValueType>> reachScheduler, transformer::DAProductBuilder const& productBuilder, typename transformer::DAProduct<productModelType>::ptr product, storm::storage::BitVector const& modelStatesOfInterest, storm::storage::SparseMatrix<ValueType> const& transitionMatrix); + + /*! + * Returns a deterministic fully defined scheduler (except for dontCareStates) for the given model. + * The choices are random if isRandom was set to true. + * + * @param model the model to construct the scheduler for + * @param onlyInitialStatesRelevant flag indicating whether we only consider the fragment reachable from initial model states. + * @return the scheduler + */ + storm::storage::Scheduler<ValueType> extractScheduler(storm::models::sparse::Model<ValueType> const& model, bool onlyInitialStatesRelevant); + + private: + + /** + * Computes the memory state for a given DA-state and infSet ID. + * Encoded as (DA-state * (numberOfInfSets+1)) + infSet. (+1 because an additional "copy" of the DA is used for states outside accepting ECs) + * @param daState DA-state + * @param infSet infSet ID + */ + uint_fast64_t getMemoryState(uint_fast64_t daState, uint_fast64_t infSet); + + + /*! + * Manages the InfSets of the acceptance condition by maintaining an assignment from infSets to unique indices + * An infSet is a BitVector that encodes the product model states that are contained in the infSet + */ + class InfSetPool { + public: + InfSetPool() = default; + + /*! + * If the given infSet has been seen before, the corresponding index is returned. Otherwise, a new index is assigned to the infset. + * Indices are assigned in a consecutive way starting from 0 + */ + uint_fast64_t getOrCreateIndex(storm::storage::BitVector&& infSet); + /*! + * Gets the inf set from the given index. + * @param index + * @return + */ + storm::storage::BitVector const& get(uint_fast64_t index) const; + + /*! + * @return The current number of stored infSets (which coincides with the index of the most recently added infSet (or 0 if there is none) + */ + uint_fast64_t size() const; + + private: + std::vector<storm::storage::BitVector> _storage; + } _infSets; + + static const uint_fast64_t DEFAULT_INFSET; /// Some arbitrary fixed infset index that will be used e.g. for states that are not in any accepting EC + + bool _randomScheduler; + std::vector<storm::storage::BitVector> _dontCareStates; // memorySate-modelState combinations that are never visited + + std::map <std::tuple<uint_fast64_t, uint_fast64_t, uint_fast64_t>, storm::storage::SchedulerChoice<ValueType>> _producedChoices; // <s, q, DEFAULT_INFSET)> -> ReachChoice and <s, q, InfSetIndex> -> MecChoice + + std::vector<boost::optional<std::set<uint_fast64_t>>> _accInfSets; // Save for each product state (which is assigned to an acceptingMEC), the infSets that need to be visited inf often to satisfy the acceptance condition. Remaining states belonging to no accepting EC, are assigned len(_infSets) (REACH scheduler) + + // Memory structure + std::vector<std::vector<storm::storage::BitVector>> _memoryTransitions; // The BitVector contains the model states that lead from startState <q, mec, infSet> to <q', mec', infSet'>. This is deterministic, because each state <s, q> is assigned to a unique MEC (scheduler). + std::vector<uint_fast64_t> _memoryInitialStates; // Save for each relevant state (initial or all) s its unique initial memory state (which memory state is reached from the initial state after reading s) + + }; + } + } + } +} \ No newline at end of file diff --git a/src/storm/modelchecker/helper/utility/SetInformationFromCheckTask.h b/src/storm/modelchecker/helper/utility/SetInformationFromCheckTask.h index 49b46db26..df1df7362 100644 --- a/src/storm/modelchecker/helper/utility/SetInformationFromCheckTask.h +++ b/src/storm/modelchecker/helper/utility/SetInformationFromCheckTask.h @@ -25,6 +25,9 @@ namespace storm { } // Scheduler Production helper.setProduceScheduler(checkTask.isProduceSchedulersSet()); + + // Qualitative flag + helper.setQualitative(checkTask.isQualitativeSet()); } /*! @@ -40,6 +43,10 @@ namespace storm { if (checkTask.isBoundSet()) { helper.setValueThreshold(checkTask.getBoundComparisonType(), checkTask.getBoundThreshold()); } + + // Qualitative flag + helper.setQualitative(checkTask.isQualitativeSet()); + } } } diff --git a/src/storm/modelchecker/prctl/HybridDtmcPrctlModelChecker.cpp b/src/storm/modelchecker/prctl/HybridDtmcPrctlModelChecker.cpp index 176bba662..7bd2474de 100644 --- a/src/storm/modelchecker/prctl/HybridDtmcPrctlModelChecker.cpp +++ b/src/storm/modelchecker/prctl/HybridDtmcPrctlModelChecker.cpp @@ -81,7 +81,7 @@ namespace storm { SymbolicQualitativeCheckResult<DdType> const& rightResult = rightResultPointer->asSymbolicQualitativeCheckResult<DdType>(); return storm::modelchecker::helper::HybridDtmcPrctlHelper<DdType, ValueType>::computeBoundedUntilProbabilities(env, this->getModel(), this->getModel().getTransitionMatrix(), leftResult.getTruthValuesVector(), rightResult.getTruthValuesVector(), pathFormula.getNonStrictUpperBound<uint64_t>()); } - + template<typename ModelType> std::unique_ptr<CheckResult> HybridDtmcPrctlModelChecker<ModelType>::computeCumulativeRewards(Environment const& env, storm::logic::RewardMeasureType, CheckTask<storm::logic::CumulativeRewardFormula, ValueType> const& checkTask) { storm::logic::CumulativeRewardFormula const& rewardPathFormula = checkTask.getFormula(); diff --git a/src/storm/modelchecker/prctl/HybridMdpPrctlModelChecker.cpp b/src/storm/modelchecker/prctl/HybridMdpPrctlModelChecker.cpp index 15725a415..e74c921a8 100644 --- a/src/storm/modelchecker/prctl/HybridMdpPrctlModelChecker.cpp +++ b/src/storm/modelchecker/prctl/HybridMdpPrctlModelChecker.cpp @@ -102,7 +102,7 @@ namespace storm { SymbolicQualitativeCheckResult<DdType> const& rightResult = rightResultPointer->asSymbolicQualitativeCheckResult<DdType>(); return storm::modelchecker::helper::HybridMdpPrctlHelper<DdType, ValueType>::computeBoundedUntilProbabilities(env, checkTask.getOptimizationDirection(), this->getModel(), this->getModel().getTransitionMatrix(), leftResult.getTruthValuesVector(), rightResult.getTruthValuesVector(), pathFormula.getNonStrictUpperBound<uint64_t>()); } - + template<typename ModelType> std::unique_ptr<CheckResult> HybridMdpPrctlModelChecker<ModelType>::computeCumulativeRewards(Environment const& env, storm::logic::RewardMeasureType, CheckTask<storm::logic::CumulativeRewardFormula, ValueType> const& checkTask) { storm::logic::CumulativeRewardFormula const& rewardPathFormula = checkTask.getFormula(); diff --git a/src/storm/modelchecker/prctl/HybridMdpPrctlModelChecker.h b/src/storm/modelchecker/prctl/HybridMdpPrctlModelChecker.h index cc253e753..d3b87f3a2 100644 --- a/src/storm/modelchecker/prctl/HybridMdpPrctlModelChecker.h +++ b/src/storm/modelchecker/prctl/HybridMdpPrctlModelChecker.h @@ -38,6 +38,7 @@ namespace storm { virtual std::unique_ptr<CheckResult> computeNextProbabilities(Environment const& env, CheckTask<storm::logic::NextFormula, ValueType> const& checkTask) override; virtual std::unique_ptr<CheckResult> computeUntilProbabilities(Environment const& env, CheckTask<storm::logic::UntilFormula, ValueType> const& checkTask) override; virtual std::unique_ptr<CheckResult> computeGloballyProbabilities(Environment const& env, CheckTask<storm::logic::GloballyFormula, ValueType> const& checkTask) override; + virtual std::unique_ptr<CheckResult> computeCumulativeRewards(Environment const& env, storm::logic::RewardMeasureType rewardMeasureType, CheckTask<storm::logic::CumulativeRewardFormula, ValueType> const& checkTask) override; virtual std::unique_ptr<CheckResult> computeInstantaneousRewards(Environment const& env, storm::logic::RewardMeasureType rewardMeasureType, CheckTask<storm::logic::InstantaneousRewardFormula, ValueType> const& checkTask) override; virtual std::unique_ptr<CheckResult> computeReachabilityRewards(Environment const& env, storm::logic::RewardMeasureType rewardMeasureType, CheckTask<storm::logic::EventuallyFormula, ValueType> const& checkTask) override; diff --git a/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.cpp b/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.cpp index 30858ae3a..645564aa6 100644 --- a/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.cpp +++ b/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.cpp @@ -15,15 +15,15 @@ #include "storm/modelchecker/csl/helper/SparseCtmcCslHelper.h" #include "storm/modelchecker/prctl/helper/rewardbounded/QuantileHelper.h" #include "storm/modelchecker/helper/infinitehorizon/SparseDeterministicInfiniteHorizonHelper.h" +#include "storm/modelchecker/helper/ltl/SparseLTLHelper.h" #include "storm/modelchecker/helper/utility/SetInformationFromCheckTask.h" #include "storm/logic/FragmentSpecification.h" -#include "storm/models/sparse/StandardRewardModel.h" - -#include "storm/settings/modules/GeneralSettings.h" + #include "storm/solver/SolveGoal.h" -#include "storm/exceptions/InvalidStateException.h" +#include "storm/models/sparse/Dtmc.h" +#include "storm/models/sparse/StandardRewardModel.h" #include "storm/exceptions/InvalidPropertyException.h" @@ -33,11 +33,11 @@ namespace storm { SparseDtmcPrctlModelChecker<SparseDtmcModelType>::SparseDtmcPrctlModelChecker(SparseDtmcModelType const& model) : SparsePropositionalModelChecker<SparseDtmcModelType>(model) { // Intentionally left empty. } - + template<typename SparseDtmcModelType> bool SparseDtmcPrctlModelChecker<SparseDtmcModelType>::canHandleStatic(CheckTask<storm::logic::Formula, ValueType> const& checkTask, bool* requiresSingleInitialState) { storm::logic::Formula const& formula = checkTask.getFormula(); - if (formula.isInFragment(storm::logic::prctl().setLongRunAverageRewardFormulasAllowed(true).setLongRunAverageProbabilitiesAllowed(true).setConditionalProbabilityFormulasAllowed(true).setConditionalRewardFormulasAllowed(true).setTotalRewardFormulasAllowed(true).setOnlyEventuallyFormuluasInConditionalFormulasAllowed(true).setRewardBoundedUntilFormulasAllowed(true).setRewardBoundedCumulativeRewardFormulasAllowed(true).setMultiDimensionalBoundedUntilFormulasAllowed(true).setMultiDimensionalCumulativeRewardFormulasAllowed(true).setTimeOperatorsAllowed(true).setReachbilityTimeFormulasAllowed(true).setRewardAccumulationAllowed(true))) { + if (formula.isInFragment(storm::logic::prctlstar().setLongRunAverageRewardFormulasAllowed(true).setLongRunAverageProbabilitiesAllowed(true).setConditionalProbabilityFormulasAllowed(true).setConditionalRewardFormulasAllowed(true).setTotalRewardFormulasAllowed(true).setOnlyEventuallyFormuluasInConditionalFormulasAllowed(true).setRewardBoundedUntilFormulasAllowed(true).setRewardBoundedCumulativeRewardFormulasAllowed(true).setMultiDimensionalBoundedUntilFormulasAllowed(true).setMultiDimensionalCumulativeRewardFormulasAllowed(true).setTimeOperatorsAllowed(true).setReachbilityTimeFormulasAllowed(true).setRewardAccumulationAllowed(true).setHOAPathFormulasAllowed(true))) { return true; } else if (checkTask.isOnlyInitialStatesRelevantSet() && formula.isInFragment(storm::logic::quantiles())) { if (requiresSingleInitialState) { @@ -47,7 +47,7 @@ namespace storm { } return false; } - + template<typename SparseDtmcModelType> bool SparseDtmcPrctlModelChecker<SparseDtmcModelType>::canHandle(CheckTask<storm::logic::Formula, ValueType> const& checkTask) const { bool requiresSingleInitialState = false; @@ -57,7 +57,7 @@ namespace storm { return false; } } - + template<typename SparseDtmcModelType> std::unique_ptr<CheckResult> SparseDtmcPrctlModelChecker<SparseDtmcModelType>::computeBoundedUntilProbabilities(Environment const& env, CheckTask<storm::logic::BoundedUntilFormula, ValueType> const& checkTask) { storm::logic::BoundedUntilFormula const& pathFormula = checkTask.getFormula(); @@ -84,7 +84,7 @@ namespace storm { return result; } } - + template<typename SparseDtmcModelType> std::unique_ptr<CheckResult> SparseDtmcPrctlModelChecker<SparseDtmcModelType>::computeNextProbabilities(Environment const& env, CheckTask<storm::logic::NextFormula, ValueType> const& checkTask) { storm::logic::NextFormula const& pathFormula = checkTask.getFormula(); @@ -93,7 +93,7 @@ namespace storm { std::vector<ValueType> numericResult = storm::modelchecker::helper::SparseDtmcPrctlHelper<ValueType>::computeNextProbabilities(env, this->getModel().getTransitionMatrix(), subResult.getTruthValuesVector()); return std::unique_ptr<CheckResult>(new ExplicitQuantitativeCheckResult<ValueType>(std::move(numericResult))); } - + template<typename SparseDtmcModelType> std::unique_ptr<CheckResult> SparseDtmcPrctlModelChecker<SparseDtmcModelType>::computeUntilProbabilities(Environment const& env, CheckTask<storm::logic::UntilFormula, ValueType> const& checkTask) { storm::logic::UntilFormula const& pathFormula = checkTask.getFormula(); @@ -104,7 +104,7 @@ namespace storm { std::vector<ValueType> numericResult = storm::modelchecker::helper::SparseDtmcPrctlHelper<ValueType>::computeUntilProbabilities(env, storm::solver::SolveGoal<ValueType>(this->getModel(), checkTask), this->getModel().getTransitionMatrix(), this->getModel().getBackwardTransitions(), leftResult.getTruthValuesVector(), rightResult.getTruthValuesVector(), checkTask.isQualitativeSet(), checkTask.getHint()); return std::unique_ptr<CheckResult>(new ExplicitQuantitativeCheckResult<ValueType>(std::move(numericResult))); } - + template<typename SparseDtmcModelType> std::unique_ptr<CheckResult> SparseDtmcPrctlModelChecker<SparseDtmcModelType>::computeGloballyProbabilities(Environment const& env, CheckTask<storm::logic::GloballyFormula, ValueType> const& checkTask) { storm::logic::GloballyFormula const& pathFormula = checkTask.getFormula(); @@ -113,9 +113,64 @@ namespace storm { std::vector<ValueType> numericResult = storm::modelchecker::helper::SparseDtmcPrctlHelper<ValueType>::computeGloballyProbabilities(env, storm::solver::SolveGoal<ValueType>(this->getModel(), checkTask), this->getModel().getTransitionMatrix(), this->getModel().getBackwardTransitions(), subResult.getTruthValuesVector(), checkTask.isQualitativeSet()); return std::unique_ptr<CheckResult>(new ExplicitQuantitativeCheckResult<ValueType>(std::move(numericResult))); } - + + template<typename SparseDtmcModelType> + std::unique_ptr<CheckResult> SparseDtmcPrctlModelChecker<SparseDtmcModelType>::computeHOAPathProbabilities(Environment const& env, CheckTask<storm::logic::HOAPathFormula, ValueType> const& checkTask) { + storm::logic::HOAPathFormula const& pathFormula = checkTask.getFormula(); + + storm::modelchecker::helper::SparseLTLHelper<ValueType, false> helper(this->getModel().getTransitionMatrix()); + storm::modelchecker::helper::setInformationFromCheckTaskDeterministic(helper, checkTask, this->getModel()); + + auto formulaChecker = [&] (storm::logic::Formula const& formula) { return this->check(env, formula)->asExplicitQualitativeCheckResult().getTruthValuesVector(); }; + auto apSets = helper.computeApSets(pathFormula.getAPMapping(), formulaChecker); + std::vector<ValueType> numericResult = helper.computeDAProductProbabilities(env, *pathFormula.readAutomaton(), apSets); + + return std::unique_ptr<CheckResult>(new ExplicitQuantitativeCheckResult<ValueType>(std::move(numericResult))); + } + + template<typename SparseDtmcModelType> + std::unique_ptr<CheckResult> SparseDtmcPrctlModelChecker<SparseDtmcModelType>::computeLTLProbabilities(Environment const& env, CheckTask<storm::logic::PathFormula, ValueType> const& checkTask) { + storm::logic::PathFormula const& pathFormula = checkTask.getFormula(); + + storm::modelchecker::helper::SparseLTLHelper<ValueType, false> helper(this->getModel().getTransitionMatrix()); + storm::modelchecker::helper::setInformationFromCheckTaskDeterministic(helper, checkTask, this->getModel()); + + auto formulaChecker = [&] (storm::logic::Formula const& formula) { return this->check(env, formula)->asExplicitQualitativeCheckResult().getTruthValuesVector(); }; + std::vector<ValueType> numericResult = helper.computeLTLProbabilities(env, pathFormula, formulaChecker); + + return std::unique_ptr<CheckResult>(new ExplicitQuantitativeCheckResult<ValueType>(std::move(numericResult))); + } + + template<typename SparseDtmcModelType> + std::unique_ptr<CheckResult> SparseDtmcPrctlModelChecker<SparseDtmcModelType>::computeHOAPathProbabilities(Environment const& env, CheckTask<storm::logic::HOAPathFormula, ValueType> const& checkTask) { + storm::logic::HOAPathFormula const& pathFormula = checkTask.getFormula(); + + storm::modelchecker::helper::SparseLTLHelper<ValueType, false> helper(this->getModel().getTransitionMatrix()); + storm::modelchecker::helper::setInformationFromCheckTaskDeterministic(helper, checkTask, this->getModel()); + + auto formulaChecker = [&] (storm::logic::Formula const& formula) { return this->check(env, formula)->asExplicitQualitativeCheckResult().getTruthValuesVector(); }; + auto apSets = helper.computeApSets(pathFormula.getAPMapping(), formulaChecker); + std::vector<ValueType> numericResult = helper.computeDAProductProbabilities(env, *pathFormula.readAutomaton(), apSets); + + return std::unique_ptr<CheckResult>(new ExplicitQuantitativeCheckResult<ValueType>(std::move(numericResult))); + } + + template<typename SparseDtmcModelType> + std::unique_ptr<CheckResult> SparseDtmcPrctlModelChecker<SparseDtmcModelType>::computeLTLProbabilities(Environment const& env, CheckTask<storm::logic::PathFormula, ValueType> const& checkTask) { + storm::logic::PathFormula const& pathFormula = checkTask.getFormula(); + + storm::modelchecker::helper::SparseLTLHelper<ValueType, false> helper(this->getModel().getTransitionMatrix()); + storm::modelchecker::helper::setInformationFromCheckTaskDeterministic(helper, checkTask, this->getModel()); + + auto formulaChecker = [&] (storm::logic::Formula const& formula) { return this->check(env, formula)->asExplicitQualitativeCheckResult().getTruthValuesVector(); }; + std::vector<ValueType> numericResult = helper.computeLTLProbabilities(env, pathFormula, formulaChecker); + + return std::unique_ptr<CheckResult>(new ExplicitQuantitativeCheckResult<ValueType>(std::move(numericResult))); + } + template<typename SparseDtmcModelType> std::unique_ptr<CheckResult> SparseDtmcPrctlModelChecker<SparseDtmcModelType>::computeCumulativeRewards(Environment const& env, storm::logic::RewardMeasureType, CheckTask<storm::logic::CumulativeRewardFormula, ValueType> const& checkTask) { + storm::logic::CumulativeRewardFormula const& rewardPathFormula = checkTask.getFormula(); if (rewardPathFormula.isMultiDimensional() || rewardPathFormula.getTimeBoundReference().isRewardBound()) { STORM_LOG_THROW(checkTask.isOnlyInitialStatesRelevantSet(), storm::exceptions::InvalidOperationException, "Checking non-trivial bounded until probabilities can only be computed for the initial states of the model."); @@ -134,7 +189,7 @@ namespace storm { return std::unique_ptr<CheckResult>(new ExplicitQuantitativeCheckResult<ValueType>(std::move(numericResult))); } } - + template<typename SparseDtmcModelType> std::unique_ptr<CheckResult> SparseDtmcPrctlModelChecker<SparseDtmcModelType>::computeInstantaneousRewards(Environment const& env, storm::logic::RewardMeasureType, CheckTask<storm::logic::InstantaneousRewardFormula, ValueType> const& checkTask) { storm::logic::InstantaneousRewardFormula const& rewardPathFormula = checkTask.getFormula(); @@ -142,7 +197,7 @@ namespace storm { std::vector<ValueType> numericResult = storm::modelchecker::helper::SparseDtmcPrctlHelper<ValueType>::computeInstantaneousRewards(env, storm::solver::SolveGoal<ValueType>(this->getModel(), checkTask), this->getModel().getTransitionMatrix(), checkTask.isRewardModelSet() ? this->getModel().getRewardModel(checkTask.getRewardModel()) : this->getModel().getRewardModel(""), rewardPathFormula.getBound<uint64_t>()); return std::unique_ptr<CheckResult>(new ExplicitQuantitativeCheckResult<ValueType>(std::move(numericResult))); } - + template<typename SparseDtmcModelType> std::unique_ptr<CheckResult> SparseDtmcPrctlModelChecker<SparseDtmcModelType>::computeReachabilityRewards(Environment const& env, storm::logic::RewardMeasureType, CheckTask<storm::logic::EventuallyFormula, ValueType> const& checkTask) { storm::logic::EventuallyFormula const& eventuallyFormula = checkTask.getFormula(); @@ -152,7 +207,7 @@ namespace storm { std::vector<ValueType> numericResult = storm::modelchecker::helper::SparseDtmcPrctlHelper<ValueType>::computeReachabilityRewards(env, storm::solver::SolveGoal<ValueType>(this->getModel(), checkTask), this->getModel().getTransitionMatrix(), this->getModel().getBackwardTransitions(), rewardModel.get(), subResult.getTruthValuesVector(), checkTask.isQualitativeSet(), checkTask.getHint()); return std::unique_ptr<CheckResult>(new ExplicitQuantitativeCheckResult<ValueType>(std::move(numericResult))); } - + template<typename SparseDtmcModelType> std::unique_ptr<CheckResult> SparseDtmcPrctlModelChecker<SparseDtmcModelType>::computeReachabilityTimes(Environment const& env, storm::logic::RewardMeasureType, CheckTask<storm::logic::EventuallyFormula, ValueType> const& checkTask) { storm::logic::EventuallyFormula const& eventuallyFormula = checkTask.getFormula(); @@ -161,7 +216,7 @@ namespace storm { std::vector<ValueType> numericResult = storm::modelchecker::helper::SparseDtmcPrctlHelper<ValueType>::computeReachabilityTimes(env, storm::solver::SolveGoal<ValueType>(this->getModel(), checkTask), this->getModel().getTransitionMatrix(), this->getModel().getBackwardTransitions(), subResult.getTruthValuesVector(), checkTask.isQualitativeSet(), checkTask.getHint()); return std::unique_ptr<CheckResult>(new ExplicitQuantitativeCheckResult<ValueType>(std::move(numericResult))); } - + template<typename SparseDtmcModelType> std::unique_ptr<CheckResult> SparseDtmcPrctlModelChecker<SparseDtmcModelType>::computeTotalRewards(Environment const& env, storm::logic::RewardMeasureType, CheckTask<storm::logic::TotalRewardFormula, ValueType> const& checkTask) { auto rewardModel = storm::utility::createFilteredRewardModel(this->getModel(), checkTask); @@ -171,18 +226,17 @@ namespace storm { template<typename SparseDtmcModelType> std::unique_ptr<CheckResult> SparseDtmcPrctlModelChecker<SparseDtmcModelType>::computeLongRunAverageProbabilities(Environment const& env, CheckTask<storm::logic::StateFormula, ValueType> const& checkTask) { - storm::logic::StateFormula const& stateFormula = checkTask.getFormula(); - std::unique_ptr<CheckResult> subResultPointer = this->check(env, stateFormula); - ExplicitQualitativeCheckResult const& subResult = subResultPointer->asExplicitQualitativeCheckResult(); - - storm::modelchecker::helper::SparseDeterministicInfiniteHorizonHelper<ValueType> helper(this->getModel().getTransitionMatrix()); + std::unique_ptr<CheckResult> subResultPointer = this->check(env, stateFormula); + ExplicitQualitativeCheckResult const& subResult = subResultPointer->asExplicitQualitativeCheckResult(); + + storm::modelchecker::helper::SparseDeterministicInfiniteHorizonHelper<ValueType> helper(this->getModel().getTransitionMatrix()); storm::modelchecker::helper::setInformationFromCheckTaskDeterministic(helper, checkTask, this->getModel()); - auto values = helper.computeLongRunAverageProbabilities(env, subResult.getTruthValuesVector()); - + auto values = helper.computeLongRunAverageProbabilities(env, subResult.getTruthValuesVector()); + return std::unique_ptr<CheckResult>(new ExplicitQuantitativeCheckResult<ValueType>(std::move(values))); } - + template<typename SparseDtmcModelType> std::unique_ptr<CheckResult> SparseDtmcPrctlModelChecker<SparseDtmcModelType>::computeLongRunAverageRewards(Environment const& env, storm::logic::RewardMeasureType rewardMeasureType, CheckTask<storm::logic::LongRunAverageRewardFormula, ValueType> const& checkTask) { auto rewardModel = storm::utility::createFilteredRewardModel(this->getModel(), checkTask); @@ -191,7 +245,7 @@ namespace storm { auto values = helper.computeLongRunAverageRewards(env, rewardModel.get()); return std::unique_ptr<CheckResult>(new ExplicitQuantitativeCheckResult<ValueType>(std::move(values))); } - + template<typename SparseDtmcModelType> std::unique_ptr<CheckResult> SparseDtmcPrctlModelChecker<SparseDtmcModelType>::computeConditionalProbabilities(Environment const& env, CheckTask<storm::logic::ConditionalFormula, ValueType> const& checkTask) { storm::logic::ConditionalFormula const& conditionalFormula = checkTask.getFormula(); @@ -206,28 +260,28 @@ namespace storm { std::vector<ValueType> numericResult = storm::modelchecker::helper::SparseDtmcPrctlHelper<ValueType>::computeConditionalProbabilities(env, storm::solver::SolveGoal<ValueType>(this->getModel(), checkTask), this->getModel().getTransitionMatrix(), this->getModel().getBackwardTransitions(), leftResult.getTruthValuesVector(), rightResult.getTruthValuesVector(), checkTask.isQualitativeSet()); return std::unique_ptr<CheckResult>(new ExplicitQuantitativeCheckResult<ValueType>(std::move(numericResult))); } - + template<typename SparseDtmcModelType> std::unique_ptr<CheckResult> SparseDtmcPrctlModelChecker<SparseDtmcModelType>::computeConditionalRewards(Environment const& env, storm::logic::RewardMeasureType, CheckTask<storm::logic::ConditionalFormula, ValueType> const& checkTask) { storm::logic::ConditionalFormula const& conditionalFormula = checkTask.getFormula(); STORM_LOG_THROW(conditionalFormula.getSubformula().isReachabilityRewardFormula(), storm::exceptions::InvalidPropertyException, "Illegal conditional probability formula."); STORM_LOG_THROW(conditionalFormula.getConditionFormula().isEventuallyFormula(), storm::exceptions::InvalidPropertyException, "Illegal conditional probability formula."); - + std::unique_ptr<CheckResult> leftResultPointer = this->check(env, conditionalFormula.getSubformula().asReachabilityRewardFormula().getSubformula()); std::unique_ptr<CheckResult> rightResultPointer = this->check(env, conditionalFormula.getConditionFormula().asEventuallyFormula().getSubformula()); ExplicitQualitativeCheckResult const& leftResult = leftResultPointer->asExplicitQualitativeCheckResult(); ExplicitQualitativeCheckResult const& rightResult = rightResultPointer->asExplicitQualitativeCheckResult(); - + std::vector<ValueType> numericResult = storm::modelchecker::helper::SparseDtmcPrctlHelper<ValueType>::computeConditionalRewards(env, storm::solver::SolveGoal<ValueType>(this->getModel(), checkTask), this->getModel().getTransitionMatrix(), this->getModel().getBackwardTransitions(), checkTask.isRewardModelSet() ? this->getModel().getRewardModel(checkTask.getRewardModel()) : this->getModel().getRewardModel(""), leftResult.getTruthValuesVector(), rightResult.getTruthValuesVector(), checkTask.isQualitativeSet()); return std::unique_ptr<CheckResult>(new ExplicitQuantitativeCheckResult<ValueType>(std::move(numericResult))); } - - + + template<> std::unique_ptr<CheckResult> SparseDtmcPrctlModelChecker<storm::models::sparse::Dtmc<storm::RationalFunction>>::checkQuantileFormula(Environment const& env, CheckTask<storm::logic::QuantileFormula, ValueType> const& checkTask) { STORM_LOG_THROW(false, storm::exceptions::NotImplementedException, "Quantiles for parametric models are not implemented."); } - + template<typename SparseDtmcModelType> std::unique_ptr<CheckResult> SparseDtmcPrctlModelChecker<SparseDtmcModelType>::checkQuantileFormula(Environment const& env, CheckTask<storm::logic::QuantileFormula, ValueType> const& checkTask) { STORM_LOG_THROW(checkTask.isOnlyInitialStatesRelevantSet(), storm::exceptions::InvalidOperationException, "Computing quantiles is only supported for the initial states of a model."); @@ -236,19 +290,19 @@ namespace storm { helper::rewardbounded::QuantileHelper<SparseDtmcModelType> qHelper(this->getModel(), checkTask.getFormula()); auto res = qHelper.computeQuantile(env); - + if (res.size() == 1 && res.front().size() == 1) { return std::unique_ptr<CheckResult>(new ExplicitQuantitativeCheckResult<ValueType>(initialState, std::move(res.front().front()))); } else { return std::unique_ptr<CheckResult>(new ExplicitParetoCurveCheckResult<ValueType>(initialState, std::move(res))); } } - + template <typename SparseCtmcModelType> std::unique_ptr<CheckResult> SparseDtmcPrctlModelChecker<SparseCtmcModelType>::computeSteadyStateDistribution(Environment const& env) { // Initialize helper storm::modelchecker::helper::SparseDeterministicInfiniteHorizonHelper<ValueType> helper(this->getModel().getTransitionMatrix()); - + // Compute result std::vector<ValueType> result; auto const& initialStates = this->getModel().getInitialStates(); @@ -265,7 +319,7 @@ namespace storm { return std::unique_ptr<CheckResult>(new ExplicitQuantitativeCheckResult<ValueType>(std::move(result))); } - + template class SparseDtmcPrctlModelChecker<storm::models::sparse::Dtmc<double>>; #ifdef STORM_HAVE_CARL diff --git a/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.h b/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.h index 93ae8dbfb..7ab10210f 100644 --- a/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.h +++ b/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.h @@ -3,35 +3,34 @@ #include "storm/modelchecker/propositional/SparsePropositionalModelChecker.h" #include "storm/models/sparse/Dtmc.h" -#include "storm/utility/solver.h" -#include "storm/solver/LinearEquationSolver.h" -#include "storm/storage/StronglyConnectedComponent.h" namespace storm { namespace modelchecker { - + template<class SparseDtmcModelType> class SparseDtmcPrctlModelChecker : public SparsePropositionalModelChecker<SparseDtmcModelType> { public: typedef typename SparseDtmcModelType::ValueType ValueType; typedef typename SparseDtmcModelType::RewardModelType RewardModelType; - + explicit SparseDtmcPrctlModelChecker(SparseDtmcModelType const& model); - + /*! * Returns false, if this task can certainly not be handled by this model checker (independent of the concrete model). * @param requiresSingleInitialState if not nullptr, this flag is set to true iff checking this formula requires a model with a single initial state */ static bool canHandleStatic(CheckTask<storm::logic::Formula, ValueType> const& checkTask, bool* requiresSingleInitialState = nullptr); - + // The implemented methods of the AbstractModelChecker interface. virtual bool canHandle(CheckTask<storm::logic::Formula, ValueType> const& checkTask) const override; virtual std::unique_ptr<CheckResult> computeBoundedUntilProbabilities(Environment const& env, CheckTask<storm::logic::BoundedUntilFormula, ValueType> const& checkTask) override; virtual std::unique_ptr<CheckResult> computeNextProbabilities(Environment const& env, CheckTask<storm::logic::NextFormula, ValueType> const& checkTask) override; virtual std::unique_ptr<CheckResult> computeUntilProbabilities(Environment const& env, CheckTask<storm::logic::UntilFormula, ValueType> const& checkTask) override; virtual std::unique_ptr<CheckResult> computeGloballyProbabilities(Environment const& env, CheckTask<storm::logic::GloballyFormula, ValueType> const& checkTask) override; + virtual std::unique_ptr<CheckResult> computeHOAPathProbabilities(Environment const& env, CheckTask<storm::logic::HOAPathFormula, ValueType> const& checkTask) override; virtual std::unique_ptr<CheckResult> computeConditionalProbabilities(Environment const& env, CheckTask<storm::logic::ConditionalFormula, ValueType> const& checkTask) override; virtual std::unique_ptr<CheckResult> computeLongRunAverageProbabilities(Environment const& env, CheckTask<storm::logic::StateFormula, ValueType> const& checkTask) override; + virtual std::unique_ptr<CheckResult> computeLTLProbabilities(Environment const& env, CheckTask<storm::logic::PathFormula, ValueType> const& checkTask) override; virtual std::unique_ptr<CheckResult> computeCumulativeRewards(Environment const& env, storm::logic::RewardMeasureType rewardMeasureType, CheckTask<storm::logic::CumulativeRewardFormula, ValueType> const& checkTask) override; virtual std::unique_ptr<CheckResult> computeInstantaneousRewards(Environment const& env, storm::logic::RewardMeasureType rewardMeasureType, CheckTask<storm::logic::InstantaneousRewardFormula, ValueType> const& checkTask) override; @@ -41,15 +40,15 @@ namespace storm { virtual std::unique_ptr<CheckResult> computeLongRunAverageRewards(Environment const& env, storm::logic::RewardMeasureType rewardMeasureType, CheckTask<storm::logic::LongRunAverageRewardFormula, ValueType> const& checkTask) override; virtual std::unique_ptr<CheckResult> computeReachabilityTimes(Environment const& env, storm::logic::RewardMeasureType rewardMeasureType, CheckTask<storm::logic::EventuallyFormula, ValueType> const& checkTask) override; virtual std::unique_ptr<CheckResult> checkQuantileFormula(Environment const& env, CheckTask<storm::logic::QuantileFormula, ValueType> const& checkTask) override; - + /*! * Computes the long run average (or: steady state) distribution over all states * Assumes a uniform distribution over initial states. */ std::unique_ptr<CheckResult> computeSteadyStateDistribution(Environment const& env); - + }; - + } // namespace modelchecker } // namespace storm diff --git a/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.cpp b/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.cpp index ffefa0e78..a48995526 100644 --- a/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.cpp +++ b/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.cpp @@ -17,25 +17,22 @@ #include "storm/modelchecker/prctl/helper/SparseMdpPrctlHelper.h" #include "storm/modelchecker/helper/infinitehorizon/SparseNondeterministicInfiniteHorizonHelper.h" #include "storm/modelchecker/helper/finitehorizon/SparseNondeterministicStepBoundedHorizonHelper.h" +#include "storm/modelchecker/helper/ltl/SparseLTLHelper.h" #include "storm/modelchecker/helper/utility/SetInformationFromCheckTask.h" #include "storm/modelchecker/prctl/helper/rewardbounded/QuantileHelper.h" #include "storm/modelchecker/multiobjective/multiObjectiveModelChecking.h" #include "storm/solver/SolveGoal.h" - #include "storm/storage/BitVector.h" #include "storm/shields/ShieldHandling.h" #include "storm/settings/modules/GeneralSettings.h" - #include "storm/exceptions/InvalidStateException.h" #include "storm/exceptions/InvalidPropertyException.h" #include "storm/storage/expressions/Expressions.h" -#include "storm/storage/MaximalEndComponentDecomposition.h" - #include "storm/exceptions/InvalidPropertyException.h" namespace storm { @@ -48,7 +45,7 @@ namespace storm { template<typename SparseMdpModelType> bool SparseMdpPrctlModelChecker<SparseMdpModelType>::canHandleStatic(CheckTask<storm::logic::Formula, ValueType> const& checkTask, bool* requiresSingleInitialState) { storm::logic::Formula const& formula = checkTask.getFormula(); - if (formula.isInFragment(storm::logic::prctl().setLongRunAverageRewardFormulasAllowed(true).setLongRunAverageProbabilitiesAllowed(true).setConditionalProbabilityFormulasAllowed(true).setOnlyEventuallyFormuluasInConditionalFormulasAllowed(true).setTotalRewardFormulasAllowed(true).setRewardBoundedUntilFormulasAllowed(true).setRewardBoundedCumulativeRewardFormulasAllowed(true).setMultiDimensionalBoundedUntilFormulasAllowed(true).setMultiDimensionalCumulativeRewardFormulasAllowed(true).setTimeOperatorsAllowed(true).setReachbilityTimeFormulasAllowed(true).setRewardAccumulationAllowed(true))) { + if (formula.isInFragment(storm::logic::prctlstar().setLongRunAverageRewardFormulasAllowed(true).setLongRunAverageProbabilitiesAllowed(true).setConditionalProbabilityFormulasAllowed(true).setOnlyEventuallyFormuluasInConditionalFormulasAllowed(true).setTotalRewardFormulasAllowed(true).setRewardBoundedUntilFormulasAllowed(true).setRewardBoundedCumulativeRewardFormulasAllowed(true).setMultiDimensionalBoundedUntilFormulasAllowed(true).setMultiDimensionalCumulativeRewardFormulasAllowed(true).setTimeOperatorsAllowed(true).setReachbilityTimeFormulasAllowed(true).setRewardAccumulationAllowed(true))) { return true; } else if (checkTask.isOnlyInitialStatesRelevantSet()) { auto multiObjectiveFragment = storm::logic::multiObjective().setCumulativeRewardFormulasAllowed(true).setTimeBoundedCumulativeRewardFormulasAllowed(true).setStepBoundedCumulativeRewardFormulasAllowed(true).setRewardBoundedCumulativeRewardFormulasAllowed(true).setTimeBoundedUntilFormulasAllowed(true).setStepBoundedUntilFormulasAllowed(true).setRewardBoundedUntilFormulasAllowed(true).setMultiDimensionalBoundedUntilFormulasAllowed(true).setMultiDimensionalCumulativeRewardFormulasAllowed(true).setRewardAccumulationAllowed(true); @@ -160,6 +157,45 @@ namespace storm { return result; } + template<typename SparseMdpModelType> + std::unique_ptr<CheckResult> SparseMdpPrctlModelChecker<SparseMdpModelType>::computeHOAPathProbabilities(Environment const& env, CheckTask<storm::logic::HOAPathFormula, ValueType> const& checkTask) { + storm::logic::HOAPathFormula const& pathFormula = checkTask.getFormula(); + + storm::modelchecker::helper::SparseLTLHelper<ValueType, true> helper(this->getModel().getTransitionMatrix()); + storm::modelchecker::helper::setInformationFromCheckTaskNondeterministic(helper, checkTask, this->getModel()); + + auto formulaChecker = [&] (storm::logic::Formula const& formula) { return this->check(env, formula)->asExplicitQualitativeCheckResult().getTruthValuesVector(); }; + auto apSets = helper.computeApSets(pathFormula.getAPMapping(), formulaChecker); + std::vector<ValueType> numericResult = helper.computeDAProductProbabilities(env, *pathFormula.readAutomaton(), apSets); + + std::unique_ptr<CheckResult> result(new ExplicitQuantitativeCheckResult<ValueType>(std::move(numericResult))); + if (checkTask.isProduceSchedulersSet()) { + result->asExplicitQuantitativeCheckResult<ValueType>().setScheduler(std::make_unique<storm::storage::Scheduler<ValueType>>(helper.extractScheduler(this->getModel()))); + } + + return result; + } + + template<typename SparseMdpModelType> + std::unique_ptr<CheckResult> SparseMdpPrctlModelChecker<SparseMdpModelType>::computeLTLProbabilities(Environment const& env, CheckTask<storm::logic::PathFormula, ValueType> const& checkTask) { + storm::logic::PathFormula const& pathFormula = checkTask.getFormula(); + + STORM_LOG_THROW(checkTask.isOptimizationDirectionSet(), storm::exceptions::InvalidPropertyException, "Formula needs to specify whether minimal or maximal values are to be computed on nondeterministic model."); + + storm::modelchecker::helper::SparseLTLHelper<ValueType, true> helper(this->getModel().getTransitionMatrix()); + storm::modelchecker::helper::setInformationFromCheckTaskNondeterministic(helper, checkTask, this->getModel()); + + auto formulaChecker = [&] (storm::logic::Formula const& formula) { return this->check(env, formula)->asExplicitQualitativeCheckResult().getTruthValuesVector(); }; + std::vector<ValueType> numericResult = helper.computeLTLProbabilities(env, pathFormula, formulaChecker); + + std::unique_ptr<CheckResult> result(new ExplicitQuantitativeCheckResult<ValueType>(std::move(numericResult))); + if (checkTask.isProduceSchedulersSet()) { + result->asExplicitQuantitativeCheckResult<ValueType>().setScheduler(std::make_unique<storm::storage::Scheduler<ValueType>>(helper.extractScheduler(this->getModel()))); + } + + return result; + } + template<typename SparseMdpModelType> std::unique_ptr<CheckResult> SparseMdpPrctlModelChecker<SparseMdpModelType>::computeConditionalProbabilities(Environment const& env, CheckTask<storm::logic::ConditionalFormula, ValueType> const& checkTask) { storm::logic::ConditionalFormula const& conditionalFormula = checkTask.getFormula(); diff --git a/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.h b/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.h index 44916728b..3feb0802d 100644 --- a/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.h +++ b/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.h @@ -5,6 +5,7 @@ #include "storm/models/sparse/Mdp.h" #include "storm/solver/MinMaxLinearEquationSolver.h" + namespace storm { class Environment; @@ -38,6 +39,8 @@ namespace storm { virtual std::unique_ptr<CheckResult> computeReachabilityTimes(Environment const& env, storm::logic::RewardMeasureType rewardMeasureType, CheckTask<storm::logic::EventuallyFormula, ValueType> const& checkTask) override; virtual std::unique_ptr<CheckResult> computeLongRunAverageProbabilities(Environment const& env, CheckTask<storm::logic::StateFormula, ValueType> const& checkTask) override; virtual std::unique_ptr<CheckResult> computeLongRunAverageRewards(Environment const& env, storm::logic::RewardMeasureType rewardMeasureType, CheckTask<storm::logic::LongRunAverageRewardFormula, ValueType> const& checkTask) override; + virtual std::unique_ptr<CheckResult> computeLTLProbabilities(Environment const& env, CheckTask<storm::logic::PathFormula, ValueType> const& checkTask) override; + virtual std::unique_ptr<CheckResult> computeHOAPathProbabilities(Environment const& env, CheckTask<storm::logic::HOAPathFormula, ValueType> const& checkTask) override; virtual std::unique_ptr<CheckResult> checkMultiObjectiveFormula(Environment const& env, CheckTask<storm::logic::MultiObjectiveFormula, ValueType> const& checkTask) override; virtual std::unique_ptr<CheckResult> checkQuantileFormula(Environment const& env, CheckTask<storm::logic::QuantileFormula, ValueType> const& checkTask) override; diff --git a/src/storm/modelchecker/prctl/SymbolicDtmcPrctlModelChecker.cpp b/src/storm/modelchecker/prctl/SymbolicDtmcPrctlModelChecker.cpp index 340a48aff..473a39cab 100644 --- a/src/storm/modelchecker/prctl/SymbolicDtmcPrctlModelChecker.cpp +++ b/src/storm/modelchecker/prctl/SymbolicDtmcPrctlModelChecker.cpp @@ -58,7 +58,7 @@ namespace storm { storm::dd::Add<DdType, ValueType> numericResult = storm::modelchecker::helper::SymbolicDtmcPrctlHelper<DdType, ValueType>::computeGloballyProbabilities(env, this->getModel(), this->getModel().getTransitionMatrix(), subResult.getTruthValuesVector(), checkTask.isQualitativeSet()); return std::make_unique<SymbolicQuantitativeCheckResult<DdType, ValueType>>(this->getModel().getReachableStates(), numericResult); } - + template<typename ModelType> std::unique_ptr<CheckResult> SymbolicDtmcPrctlModelChecker<ModelType>::computeNextProbabilities(Environment const& env, CheckTask<storm::logic::NextFormula, ValueType> const& checkTask) { storm::logic::NextFormula const& pathFormula = checkTask.getFormula(); diff --git a/src/storm/modelchecker/prctl/SymbolicMdpPrctlModelChecker.cpp b/src/storm/modelchecker/prctl/SymbolicMdpPrctlModelChecker.cpp index 5479e4720..d9937001d 100644 --- a/src/storm/modelchecker/prctl/SymbolicMdpPrctlModelChecker.cpp +++ b/src/storm/modelchecker/prctl/SymbolicMdpPrctlModelChecker.cpp @@ -58,7 +58,7 @@ namespace storm { SymbolicQualitativeCheckResult<DdType> const& subResult = subResultPointer->asSymbolicQualitativeCheckResult<DdType>(); return storm::modelchecker::helper::SymbolicMdpPrctlHelper<DdType, ValueType>::computeGloballyProbabilities(env, checkTask.getOptimizationDirection(), this->getModel(), this->getModel().getTransitionMatrix(), subResult.getTruthValuesVector(), checkTask.isQualitativeSet()); } - + template<typename ModelType> std::unique_ptr<CheckResult> SymbolicMdpPrctlModelChecker<ModelType>::computeNextProbabilities(Environment const& env, CheckTask<storm::logic::NextFormula, ValueType> const& checkTask) { storm::logic::NextFormula const& pathFormula = checkTask.getFormula(); diff --git a/src/storm/modelchecker/prctl/helper/SparseDtmcPrctlHelper.cpp b/src/storm/modelchecker/prctl/helper/SparseDtmcPrctlHelper.cpp index 7139684a2..4ebfb4821 100644 --- a/src/storm/modelchecker/prctl/helper/SparseDtmcPrctlHelper.cpp +++ b/src/storm/modelchecker/prctl/helper/SparseDtmcPrctlHelper.cpp @@ -307,7 +307,7 @@ namespace storm { multiplier->multiply(env, result, nullptr, result); return result; } - + template<typename ValueType, typename RewardModelType> std::vector<ValueType> SparseDtmcPrctlHelper<ValueType, RewardModelType>::computeCumulativeRewards(Environment const& env, storm::solver::SolveGoal<ValueType>&& goal, storm::storage::SparseMatrix<ValueType> const& transitionMatrix, RewardModelType const& rewardModel, uint_fast64_t stepBound) { // Initialize result to the null vector. diff --git a/src/storm/modelchecker/prctl/helper/SparseDtmcPrctlHelper.h b/src/storm/modelchecker/prctl/helper/SparseDtmcPrctlHelper.h index 17fb161de..79f03e80c 100644 --- a/src/storm/modelchecker/prctl/helper/SparseDtmcPrctlHelper.h +++ b/src/storm/modelchecker/prctl/helper/SparseDtmcPrctlHelper.h @@ -16,9 +16,8 @@ #include "storm/solver/SolveGoal.h" namespace storm { - class Environment; - + namespace modelchecker { class CheckResult; @@ -37,7 +36,7 @@ namespace storm { static std::vector<ValueType> computeAllUntilProbabilities(Environment const& env, storm::solver::SolveGoal<ValueType>&& goal, storm::storage::SparseMatrix<ValueType> const& transitionMatrix, storm::storage::BitVector const& initialStates, storm::storage::BitVector const& phiStates, storm::storage::BitVector const& psiStates); static std::vector<ValueType> computeGloballyProbabilities(Environment const& env, storm::solver::SolveGoal<ValueType>&& goal, storm::storage::SparseMatrix<ValueType> const& transitionMatrix, storm::storage::SparseMatrix<ValueType> const& backwardTransitions, storm::storage::BitVector const& psiStates, bool qualitative); - + static std::vector<ValueType> computeCumulativeRewards(Environment const& env, storm::solver::SolveGoal<ValueType>&& goal, storm::storage::SparseMatrix<ValueType> const& transitionMatrix, RewardModelType const& rewardModel, uint_fast64_t stepBound); static std::vector<ValueType> computeInstantaneousRewards(Environment const& env, storm::solver::SolveGoal<ValueType>&& goal, storm::storage::SparseMatrix<ValueType> const& transitionMatrix, RewardModelType const& rewardModel, uint_fast64_t stepCount); diff --git a/src/storm/modelchecker/prctl/helper/SparseMdpPrctlHelper.cpp b/src/storm/modelchecker/prctl/helper/SparseMdpPrctlHelper.cpp index 17bef0ff8..461435816 100644 --- a/src/storm/modelchecker/prctl/helper/SparseMdpPrctlHelper.cpp +++ b/src/storm/modelchecker/prctl/helper/SparseMdpPrctlHelper.cpp @@ -52,19 +52,19 @@ namespace storm { namespace modelchecker { namespace helper { - + template<typename ValueType> std::map<storm::storage::sparse::state_type, ValueType> SparseMdpPrctlHelper<ValueType>::computeRewardBoundedValues(Environment const& env, OptimizationDirection dir, rewardbounded::MultiDimensionalRewardUnfolding<ValueType, true>& rewardUnfolding, storm::storage::BitVector const& initialStates) { storm::utility::Stopwatch swAll(true), swBuild, swCheck; - + // Get lower and upper bounds for the solution. auto lowerBound = rewardUnfolding.getLowerObjectiveBound(); auto upperBound = rewardUnfolding.getUpperObjectiveBound(); - + // Initialize epoch models auto initEpoch = rewardUnfolding.getStartEpoch(); auto epochOrder = rewardUnfolding.getEpochComputationOrder(initEpoch); - + // initialize data that will be needed for each epoch std::vector<ValueType> x, b; std::unique_ptr<storm::solver::MinMaxLinearEquationSolver<ValueType>> minMaxSolver; @@ -72,7 +72,7 @@ namespace storm { ValueType precision = rewardUnfolding.getRequiredEpochModelPrecision(initEpoch, storm::utility::convertNumber<ValueType>(storm::settings::getModule<storm::settings::modules::GeneralSettings>().getPrecision())); Environment preciseEnv = env; preciseEnv.solver().minMax().setPrecision(storm::utility::convertNumber<storm::RationalNumber>(precision)); - + // In case of cdf export we store the necessary data. std::vector<std::vector<ValueType>> cdfData; @@ -101,14 +101,14 @@ namespace storm { break; } } - + std::map<storm::storage::sparse::state_type, ValueType> result; for (auto initState : initialStates) { result[initState] = rewardUnfolding.getInitialStateResult(initEpoch, initState); } - + swAll.stop(); - + if (storm::settings::getModule<storm::settings::modules::IOSettings>().isExportCdfSet()) { std::vector<std::string> headers; for (uint64_t i = 0; i < rewardUnfolding.getEpochManager().getDimensionCount(); ++i) { @@ -118,7 +118,7 @@ namespace storm { storm::utility::exportDataToCSVFile<ValueType, std::string, std::string>(storm::settings::getModule<storm::settings::modules::IOSettings>().getExportCdfDirectory() + "cdf.csv", cdfData, headers); } - + if (storm::settings::getModule<storm::settings::modules::CoreSettings>().isShowStatisticsSet()) { STORM_PRINT_AND_LOG("---------------------------------" << std::endl); STORM_PRINT_AND_LOG("Statistics:" << std::endl); @@ -129,7 +129,7 @@ namespace storm { STORM_PRINT_AND_LOG("Epoch Model checking Time: " << swCheck << "." << std::endl); STORM_PRINT_AND_LOG("---------------------------------" << std::endl); } - + return result; } @@ -154,7 +154,7 @@ namespace storm { return MDPSparseModelCheckingHelperReturnType<ValueType>(std::move(result), std::move(allStates), nullptr, std::move(choiceValues)); } - + template<typename ValueType> std::vector<uint_fast64_t> computeValidSchedulerHint(Environment const& env, SolutionType const& type, storm::storage::SparseMatrix<ValueType> const& transitionMatrix, storm::storage::SparseMatrix<ValueType> const& backwardTransitions, storm::storage::BitVector const& maybeStates, storm::storage::BitVector const& filterStates, storm::storage::BitVector const& targetStates) { storm::storage::Scheduler<ValueType> validScheduler(maybeStates.size()); @@ -166,7 +166,7 @@ namespace storm { } else { STORM_LOG_ASSERT(false, "Unexpected equation system type."); } - + // Extract the relevant parts of the scheduler for the solver. std::vector<uint_fast64_t> schedulerHint(maybeStates.getNumberOfSetBits()); auto maybeIt = maybeStates.begin(); @@ -176,13 +176,13 @@ namespace storm { } return schedulerHint; } - + template<typename ValueType> struct SparseMdpHintType { SparseMdpHintType() : eliminateEndComponents(false), computeUpperBounds(false), uniqueSolution(false), noEndComponents(false) { // Intentionally left empty. } - + bool hasSchedulerHint() const { return static_cast<bool>(schedulerHint); } @@ -198,11 +198,11 @@ namespace storm { ValueType const& getLowerResultBound() const { return lowerResultBound.get(); } - + bool hasUpperResultBound() const { return static_cast<bool>(upperResultBound); } - + bool hasUpperResultBounds() const { return static_cast<bool>(upperResultBounds); } @@ -214,19 +214,19 @@ namespace storm { std::vector<ValueType>& getUpperResultBounds() { return upperResultBounds.get(); } - + std::vector<ValueType> const& getUpperResultBounds() const { return upperResultBounds.get(); } - + std::vector<uint64_t>& getSchedulerHint() { return schedulerHint.get(); } - + std::vector<ValueType>& getValueHint() { return valueHint.get(); } - + bool getEliminateEndComponents() const { return eliminateEndComponents; } @@ -238,11 +238,11 @@ namespace storm { bool hasUniqueSolution() const { return uniqueSolution; } - + bool hasNoEndComponents() const { return noEndComponents; } - + boost::optional<std::vector<uint64_t>> schedulerHint; boost::optional<std::vector<ValueType>> valueHint; boost::optional<ValueType> lowerResultBound; @@ -253,10 +253,10 @@ namespace storm { bool uniqueSolution; bool noEndComponents; }; - + template<typename ValueType> void extractValueAndSchedulerHint(SparseMdpHintType<ValueType>& hintStorage, storm::storage::SparseMatrix<ValueType> const& transitionMatrix, storm::storage::SparseMatrix<ValueType> const& backwardTransitions, storm::storage::BitVector const& maybeStates, boost::optional<storm::storage::BitVector> const& selectedChoices, ModelCheckerHint const& hint, bool skipECWithinMaybeStatesCheck) { - + // Deal with scheduler hint. if (hint.isExplicitModelCheckerHint() && hint.template asExplicitModelCheckerHint<ValueType>().hasSchedulerHint()) { if (hintStorage.hasSchedulerHint()) { @@ -276,7 +276,7 @@ namespace storm { } else { hintApplicable = true; } - + if (hintApplicable) { // Compute the hint w.r.t. the given subsystem. hintChoices.clear(); @@ -297,13 +297,13 @@ namespace storm { } } } - + // Deal with solution value hint. Only applicable if there are no End Components consisting of maybe states. if (hint.isExplicitModelCheckerHint() && hint.template asExplicitModelCheckerHint<ValueType>().hasResultHint() && (skipECWithinMaybeStatesCheck || hintStorage.hasSchedulerHint() || storm::utility::graph::performProb1A(transitionMatrix, transitionMatrix.getRowGroupIndices(), backwardTransitions, maybeStates, ~maybeStates).full())) { hintStorage.valueHint = storm::utility::vector::filterVector(hint.template asExplicitModelCheckerHint<ValueType>().getResultHint(), maybeStates); } } - + template<typename ValueType> SparseMdpHintType<ValueType> computeHints(Environment const& env, SolutionType const& type, ModelCheckerHint const& hint, storm::OptimizationDirection const& dir, storm::storage::SparseMatrix<ValueType> const& transitionMatrix, storm::storage::SparseMatrix<ValueType> const& backwardTransitions, storm::storage::BitVector const& maybeStates, storm::storage::BitVector const& phiStates, storm::storage::BitVector const& targetStates, bool produceScheduler, boost::optional<storm::storage::BitVector> const& selectedChoices = boost::none) { SparseMdpHintType<ValueType> result; @@ -313,11 +313,11 @@ namespace storm { result.noEndComponents = (dir == storm::solver::OptimizationDirection::Minimize && type == SolutionType::UntilProbabilities) || (dir == storm::solver::OptimizationDirection::Maximize && type == SolutionType::ExpectedRewards) || (hint.isExplicitModelCheckerHint() && hint.asExplicitModelCheckerHint<ValueType>().getNoEndComponentsInMaybeStates()); - + // If there are no end components, the solution is unique. (Note that the other direction does not hold, // e.g., end components in which infinite reward is collected. result.uniqueSolution = result.hasNoEndComponents(); - + // Check for requirements of the solver. bool hasSchedulerHint = hint.isExplicitModelCheckerHint() && hint.template asExplicitModelCheckerHint<ValueType>().hasSchedulerHint(); storm::solver::GeneralMinMaxLinearEquationSolverFactory<ValueType> minMaxLinearEquationSolverFactory; @@ -335,14 +335,14 @@ namespace storm { // Note that in the case of minimizing expected rewards there might still be end components in which reward is collected. result.noEndComponents = (type == SolutionType::UntilProbabilities); } - + // If the solver requires an initial scheduler, compute one now. Note that any scheduler is valid if there are no end components. if (requirements.validInitialScheduler() && !result.noEndComponents) { STORM_LOG_DEBUG("Computing valid scheduler, because the solver requires it."); result.schedulerHint = computeValidSchedulerHint(env, type, transitionMatrix, backwardTransitions, maybeStates, phiStates, targetStates); requirements.clearValidInitialScheduler(); } - + // Finally, we have information on the bounds depending on the problem type. if (type == SolutionType::UntilProbabilities) { requirements.clearBounds(); @@ -373,7 +373,7 @@ namespace storm { if (!result.hasUpperResultBound() && type == SolutionType::UntilProbabilities) { result.upperResultBound = storm::utility::one<ValueType>(); } - + // If we received an upper bound, we can drop the requirement to compute one. if (result.hasUpperResultBound()) { result.computeUpperBounds = false; @@ -381,35 +381,35 @@ namespace storm { return result; } - + template<typename ValueType> struct MaybeStateResult { MaybeStateResult(std::vector<ValueType>&& values) : values(std::move(values)) { // Intentionally left empty. } - + bool hasScheduler() const { return static_cast<bool>(scheduler); } - + std::vector<uint64_t> const& getScheduler() const { return scheduler.get(); } - + std::vector<ValueType> const& getValues() const { return values; } - + std::vector<ValueType> values; boost::optional<std::vector<uint64_t>> scheduler; }; - + template<typename ValueType> MaybeStateResult<ValueType> computeValuesForMaybeStates(Environment const& env, storm::solver::SolveGoal<ValueType>&& goal, storm::storage::SparseMatrix<ValueType>&& submatrix, std::vector<ValueType> const& b, bool produceScheduler, SparseMdpHintType<ValueType>& hint) { - + // Initialize the solution vector. std::vector<ValueType> x = hint.hasValueHint() ? std::move(hint.getValueHint()) : std::vector<ValueType>(submatrix.getRowGroupCount(), hint.hasLowerResultBound() ? hint.getLowerResultBound() : storm::utility::zero<ValueType>()); - + // Set up the solver. storm::solver::GeneralMinMaxLinearEquationSolverFactory<ValueType> minMaxLinearEquationSolverFactory; std::unique_ptr<storm::solver::MinMaxLinearEquationSolver<ValueType>> solver = storm::solver::configureMinMaxLinearEquationSolver(env, std::move(goal), minMaxLinearEquationSolverFactory, std::move(submatrix)); @@ -429,21 +429,21 @@ namespace storm { solver->setInitialScheduler(std::move(hint.getSchedulerHint())); } solver->setTrackScheduler(produceScheduler); - + // Solve the corresponding system of equations. solver->solveEquations(env, x, b); - + #ifndef NDEBUG // As a sanity check, make sure our local upper bounds were in fact correct. if (solver->hasUpperBound(storm::solver::AbstractEquationSolver<ValueType>::BoundType::Local)) { auto resultIt = x.begin(); for (auto const& entry : solver->getUpperBounds()) { - STORM_LOG_ASSERT(*resultIt <= entry + env.solver().minMax().getPrecision(), "Expecting result value for state " << std::distance(x.begin(), resultIt) << " to be <= " << entry << ", but got " << *resultIt << "."); + STORM_LOG_ASSERT(*resultIt <= entry + storm::utility::convertNumber<ValueType>(env.solver().minMax().getPrecision()), "Expecting result value for state " << std::distance(x.begin(), resultIt) << " to be <= " << entry << ", but got " << *resultIt << "."); ++resultIt; } } #endif - + // Create result. MaybeStateResult<ValueType> result(std::move(x)); @@ -453,18 +453,18 @@ namespace storm { } return result; } - + struct QualitativeStateSetsUntilProbabilities { storm::storage::BitVector maybeStates; storm::storage::BitVector statesWithProbability0; storm::storage::BitVector statesWithProbability1; }; - + template<typename ValueType> QualitativeStateSetsUntilProbabilities getQualitativeStateSetsUntilProbabilitiesFromHint(ModelCheckerHint const& hint) { QualitativeStateSetsUntilProbabilities result; result.maybeStates = hint.template asExplicitModelCheckerHint<ValueType>().getMaybeStates(); - + // Treat the states with probability zero/one. std::vector<ValueType> const& resultsForNonMaybeStates = hint.template asExplicitModelCheckerHint<ValueType>().getResultHint(); result.statesWithProbability1 = storm::storage::BitVector(result.maybeStates.size()); @@ -478,10 +478,10 @@ namespace storm { result.statesWithProbability0.set(state, true); } } - + return result; } - + template<typename ValueType> QualitativeStateSetsUntilProbabilities computeQualitativeStateSetsUntilProbabilities(storm::solver::SolveGoal<ValueType> const& goal, storm::storage::SparseMatrix<ValueType> const& transitionMatrix, storm::storage::SparseMatrix<ValueType> const& backwardTransitions, storm::storage::BitVector const& phiStates, storm::storage::BitVector const& psiStates) { QualitativeStateSetsUntilProbabilities result; @@ -496,10 +496,10 @@ namespace storm { result.statesWithProbability0 = std::move(statesWithProbability01.first); result.statesWithProbability1 = std::move(statesWithProbability01.second); result.maybeStates = ~(result.statesWithProbability0 | result.statesWithProbability1); - + return result; } - + template<typename ValueType> QualitativeStateSetsUntilProbabilities getQualitativeStateSetsUntilProbabilities(storm::solver::SolveGoal<ValueType> const& goal, storm::storage::SparseMatrix<ValueType> const& transitionMatrix, storm::storage::SparseMatrix<ValueType> const& backwardTransitions, storm::storage::BitVector const& phiStates, storm::storage::BitVector const& psiStates, ModelCheckerHint const& hint) { if (hint.isExplicitModelCheckerHint() && hint.template asExplicitModelCheckerHint<ValueType>().getComputeOnlyMaybeStates()) { @@ -508,7 +508,7 @@ namespace storm { return computeQualitativeStateSetsUntilProbabilities(goal, transitionMatrix, backwardTransitions, phiStates, psiStates); } } - + template<typename ValueType> void extractSchedulerChoices(storm::storage::Scheduler<ValueType>& scheduler, std::vector<uint_fast64_t> const& subChoices, storm::storage::BitVector const& maybeStates) { auto subChoiceIt = subChoices.begin(); @@ -518,10 +518,10 @@ namespace storm { } assert(subChoiceIt == subChoices.end()); } - + template<typename ValueType> void extendScheduler(storm::storage::Scheduler<ValueType>& scheduler, storm::solver::SolveGoal<ValueType> const& goal, QualitativeStateSetsUntilProbabilities const& qualitativeStateSets, storm::storage::SparseMatrix<ValueType> const& transitionMatrix, storm::storage::SparseMatrix<ValueType> const& backwardTransitions, storm::storage::BitVector const& phiStates, storm::storage::BitVector const& psiStates) { - + // Finally, if we need to produce a scheduler, we also need to figure out the parts of the scheduler for // the states with probability 1 or 0 (depending on whether we maximize or minimize). // We also need to define some arbitrary choice for the remaining states to obtain a fully defined scheduler. @@ -537,40 +537,40 @@ namespace storm { } } } - + template<typename ValueType> void computeFixedPointSystemUntilProbabilities(storm::solver::SolveGoal<ValueType>& goal, storm::storage::SparseMatrix<ValueType> const& transitionMatrix, QualitativeStateSetsUntilProbabilities const& qualitativeStateSets, storm::storage::SparseMatrix<ValueType>& submatrix, std::vector<ValueType>& b) { // First, we can eliminate the rows and columns from the original transition probability matrix for states // whose probabilities are already known. submatrix = transitionMatrix.getSubmatrix(true, qualitativeStateSets.maybeStates, qualitativeStateSets.maybeStates, false); - + // Prepare the right-hand side of the equation system. For entry i this corresponds to // the accumulated probability of going from state i to some state that has probability 1. b = transitionMatrix.getConstrainedRowGroupSumVector(qualitativeStateSets.maybeStates, qualitativeStateSets.statesWithProbability1); - + // If the solve goal has relevant values, we need to adjust them. goal.restrictRelevantValues(qualitativeStateSets.maybeStates); } - + template<typename ValueType> boost::optional<SparseMdpEndComponentInformation<ValueType>> computeFixedPointSystemUntilProbabilitiesEliminateEndComponents(storm::solver::SolveGoal<ValueType>& goal, storm::storage::SparseMatrix<ValueType> const& transitionMatrix, storm::storage::SparseMatrix<ValueType> const& backwardTransitions, QualitativeStateSetsUntilProbabilities const& qualitativeStateSets, storm::storage::SparseMatrix<ValueType>& submatrix, std::vector<ValueType>& b, bool produceScheduler) { - + // Get the set of states that (under some scheduler) can stay in the set of maybestates forever storm::storage::BitVector candidateStates = storm::utility::graph::performProb0E(transitionMatrix, transitionMatrix.getRowGroupIndices(), backwardTransitions, qualitativeStateSets.maybeStates, ~qualitativeStateSets.maybeStates); - + bool doDecomposition = !candidateStates.empty(); - + storm::storage::MaximalEndComponentDecomposition<ValueType> endComponentDecomposition; if (doDecomposition) { // Compute the states that are in MECs. endComponentDecomposition = storm::storage::MaximalEndComponentDecomposition<ValueType>(transitionMatrix, backwardTransitions, candidateStates); } - + // Only do more work if there are actually end-components. if (doDecomposition && !endComponentDecomposition.empty()) { STORM_LOG_DEBUG("Eliminating " << endComponentDecomposition.size() << " EC(s)."); SparseMdpEndComponentInformation<ValueType> result = SparseMdpEndComponentInformation<ValueType>::eliminateEndComponents(endComponentDecomposition, transitionMatrix, qualitativeStateSets.maybeStates, &qualitativeStateSets.statesWithProbability1, nullptr, nullptr, submatrix, &b, nullptr, produceScheduler); - + // If the solve goal has relevant values, we need to adjust them. if (goal.hasRelevantValues()) { storm::storage::BitVector newRelevantValues(submatrix.getRowGroupCount()); @@ -583,40 +583,46 @@ namespace storm { goal.setRelevantValues(std::move(newRelevantValues)); } } - + return result; } else { STORM_LOG_DEBUG("Not eliminating ECs as there are none."); computeFixedPointSystemUntilProbabilities(goal, transitionMatrix, qualitativeStateSets, submatrix, b); - + return boost::none; } } - + template<typename ValueType> MDPSparseModelCheckingHelperReturnType<ValueType> SparseMdpPrctlHelper<ValueType>::computeUntilProbabilities(Environment const& env, storm::solver::SolveGoal<ValueType>&& goal, storm::storage::SparseMatrix<ValueType> const& transitionMatrix, storm::storage::SparseMatrix<ValueType> const& backwardTransitions, storm::storage::BitVector const& phiStates, storm::storage::BitVector const& psiStates, bool qualitative, bool produceScheduler, ModelCheckerHint const& hint) { STORM_LOG_THROW(!qualitative || !produceScheduler, storm::exceptions::InvalidSettingsException, "Cannot produce scheduler when performing qualitative model checking only."); - + // Prepare resulting vector. std::vector<ValueType> result(transitionMatrix.getRowGroupCount(), storm::utility::zero<ValueType>()); - + // We need to identify the maybe states (states which have a probability for satisfying the until formula // that is strictly between 0 and 1) and the states that satisfy the formula with probablity 1 and 0, respectively. QualitativeStateSetsUntilProbabilities qualitativeStateSets = getQualitativeStateSetsUntilProbabilities(goal, transitionMatrix, backwardTransitions, phiStates, psiStates, hint); STORM_LOG_INFO("Preprocessing: " << qualitativeStateSets.statesWithProbability1.getNumberOfSetBits() << " states with probability 1, " << qualitativeStateSets.statesWithProbability0.getNumberOfSetBits() << " with probability 0 (" << qualitativeStateSets.maybeStates.getNumberOfSetBits() << " states remaining)."); - + // Set values of resulting vector that are known exactly. storm::utility::vector::setVectorValues<ValueType>(result, qualitativeStateSets.statesWithProbability1, storm::utility::one<ValueType>()); - + + // Check if the values of the maybe states are relevant for the SolveGoal + bool maybeStatesNotRelevant = goal.hasRelevantValues() && goal.relevantValues().isDisjointFrom(qualitativeStateSets.maybeStates); + // If requested, we will produce a scheduler. std::unique_ptr<storm::storage::Scheduler<ValueType>> scheduler; if (produceScheduler) { scheduler = std::make_unique<storm::storage::Scheduler<ValueType>>(transitionMatrix.getRowGroupCount()); + // If maybeStatesNotRelevant is true, we have to set the scheduler for maybe states as "dontCare" + if (maybeStatesNotRelevant) { + for (auto state : qualitativeStateSets.maybeStates) { + scheduler->setDontCare(state); + } + } } - - // Check if the values of the maybe states are relevant for the SolveGoal - bool maybeStatesNotRelevant = goal.hasRelevantValues() && goal.relevantValues().isDisjointFrom(qualitativeStateSets.maybeStates); // create multiplier and execute the calculation for 1 additional step auto multiplier = storm::solver::MultiplierFactory<ValueType>().create(env, transitionMatrix); @@ -629,7 +635,7 @@ namespace storm { } std::vector<ValueType> maybeStateChoiceValues = std::vector<ValueType>(sizeMaybeStateChoiceValues, storm::utility::zero<ValueType>()); - + // Check whether we need to compute exact probabilities for some states. if ((qualitative || maybeStatesNotRelevant) && !goal.isShieldingTask()) { // Set the values for all maybe-states to 0.5 to indicate that their probability values are neither 0 nor 1. @@ -640,7 +646,7 @@ namespace storm { // Obtain proper hint information either from the provided hint or from requirements of the solver. SparseMdpHintType<ValueType> hintInformation = computeHints(env, SolutionType::UntilProbabilities, hint, goal.direction(), transitionMatrix, backwardTransitions, qualitativeStateSets.maybeStates, phiStates, qualitativeStateSets.statesWithProbability1, produceScheduler); - + // Declare the components of the equation system we will solve. storm::storage::SparseMatrix<ValueType> submatrix; std::vector<ValueType> b; @@ -710,7 +716,7 @@ namespace storm { if (produceScheduler) { extendScheduler(*scheduler, goal, qualitativeStateSets, transitionMatrix, backwardTransitions, phiStates, psiStates); } - + // Sanity check for created scheduler. STORM_LOG_ASSERT(!produceScheduler || scheduler, "Expected that a scheduler was obtained."); STORM_LOG_ASSERT((!produceScheduler && !scheduler) || !scheduler->isPartialScheduler(), "Expected a fully defined scheduler"); @@ -745,42 +751,42 @@ namespace storm { return result; } } - + template<typename ValueType> template<typename RewardModelType> std::vector<ValueType> SparseMdpPrctlHelper<ValueType>::computeInstantaneousRewards(Environment const& env, storm::solver::SolveGoal<ValueType>&& goal, storm::storage::SparseMatrix<ValueType> const& transitionMatrix, RewardModelType const& rewardModel, uint_fast64_t stepCount) { // Only compute the result if the model has a state-based reward this->getModel(). STORM_LOG_THROW(rewardModel.hasStateRewards(), storm::exceptions::InvalidPropertyException, "Missing reward model for formula. Skipping formula."); - + // Initialize result to state rewards of the this->getModel(). std::vector<ValueType> result(rewardModel.getStateRewardVector()); - + auto multiplier = storm::solver::MultiplierFactory<ValueType>().create(env, transitionMatrix); multiplier->repeatedMultiplyAndReduce(env, goal.direction(), result, nullptr, stepCount); return result; } - + template<typename ValueType> template<typename RewardModelType> std::vector<ValueType> SparseMdpPrctlHelper<ValueType>::computeCumulativeRewards(Environment const& env, storm::solver::SolveGoal<ValueType>&& goal, storm::storage::SparseMatrix<ValueType> const& transitionMatrix, RewardModelType const& rewardModel, uint_fast64_t stepBound) { // Only compute the result if the model has at least one reward this->getModel(). STORM_LOG_THROW(!rewardModel.empty(), storm::exceptions::InvalidPropertyException, "Missing reward model for formula. Skipping formula."); - + // Compute the reward vector to add in each step based on the available reward models. std::vector<ValueType> totalRewardVector = rewardModel.getTotalRewardVector(transitionMatrix); - + // Initialize result to the zero vector. std::vector<ValueType> result(transitionMatrix.getRowGroupCount(), storm::utility::zero<ValueType>()); - + auto multiplier = storm::solver::MultiplierFactory<ValueType>().create(env, transitionMatrix); multiplier->repeatedMultiplyAndReduce(env, goal.direction(), result, &totalRewardVector, stepBound); - + return result; } - + template<typename ValueType> template<typename RewardModelType> MDPSparseModelCheckingHelperReturnType<ValueType> SparseMdpPrctlHelper<ValueType>::computeTotalRewards(Environment const& env, storm::solver::SolveGoal<ValueType>&& goal, storm::storage::SparseMatrix<ValueType> const& transitionMatrix, storm::storage::SparseMatrix<ValueType> const& backwardTransitions, RewardModelType const& rewardModel, bool qualitative, bool produceScheduler, ModelCheckerHint const& hint) { @@ -804,7 +810,7 @@ namespace storm { storm::storage::BitVector statesWithoutReward = rewardModel.getStatesWithZeroReward(transitionMatrix); storm::storage::BitVector rew0AStates = storm::utility::graph::performProbGreater0E(backwardTransitions, statesWithoutReward, ~statesWithoutReward); rew0AStates.complement(); - + // There might be end components that consists only of states/choices with zero rewards. The reachability reward semantics would assign such // end components reward infinity. To avoid this, we potentially need to eliminate such end components storm::storage::BitVector trueStates(transitionMatrix.getRowGroupCount(), true); @@ -819,7 +825,7 @@ namespace storm { for (auto oldRew0AState : rew0AStates) { newRew0AStates.set(ecElimResult.oldToNewStateMapping[oldRew0AState]); } - + MDPSparseModelCheckingHelperReturnType<ValueType> result = computeReachabilityRewardsHelper(env, std::move(goal), ecElimResult.matrix, ecElimResult.matrix.transpose(true), [&] (uint_fast64_t rowCount, storm::storage::SparseMatrix<ValueType> const& transitionMatrix, storm::storage::BitVector const& maybeStates) { std::vector<ValueType> result; @@ -850,7 +856,7 @@ namespace storm { } return newChoicesWithoutReward; }); - + std::vector<ValueType> resultInEcQuotient = std::move(result.values); result.values.resize(ecElimResult.oldToNewStateMapping.size()); storm::utility::vector::selectVectorValues(result.values, ecElimResult.oldToNewStateMapping, resultInEcQuotient); @@ -858,7 +864,7 @@ namespace storm { } } } - + template<typename ValueType> template<typename RewardModelType> MDPSparseModelCheckingHelperReturnType<ValueType> SparseMdpPrctlHelper<ValueType>::computeReachabilityRewards(Environment const& env, storm::solver::SolveGoal<ValueType>&& goal, storm::storage::SparseMatrix<ValueType> const& transitionMatrix, storm::storage::SparseMatrix<ValueType> const& backwardTransitions, RewardModelType const& rewardModel, storm::storage::BitVector const& targetStates, bool qualitative, bool produceScheduler, ModelCheckerHint const& hint) { @@ -877,7 +883,7 @@ namespace storm { }, hint); } - + template<typename ValueType> MDPSparseModelCheckingHelperReturnType<ValueType> SparseMdpPrctlHelper<ValueType>::computeReachabilityTimes(Environment const& env, storm::solver::SolveGoal<ValueType>&& goal, storm::storage::SparseMatrix<ValueType> const& transitionMatrix, storm::storage::SparseMatrix<ValueType> const& backwardTransitions, storm::storage::BitVector const& targetStates, bool qualitative, bool produceScheduler, ModelCheckerHint const& hint) { return computeReachabilityRewardsHelper(env, std::move(goal), transitionMatrix, backwardTransitions, @@ -893,7 +899,7 @@ namespace storm { }, hint); } - + #ifdef STORM_HAVE_CARL template<typename ValueType> std::vector<ValueType> SparseMdpPrctlHelper<ValueType>::computeReachabilityRewards(Environment const& env, storm::solver::SolveGoal<ValueType>&& goal, storm::storage::SparseMatrix<ValueType> const& transitionMatrix, storm::storage::SparseMatrix<ValueType> const& backwardTransitions, storm::models::sparse::StandardRewardModel<storm::Interval> const& intervalRewardModel, bool lowerBoundOfIntervals, storm::storage::BitVector const& targetStates, bool qualitative) { @@ -917,13 +923,13 @@ namespace storm { return intervalRewardModel.getChoicesWithFilter(transitionMatrix, [&](storm::Interval const& i) {return storm::utility::isZero(lowerBoundOfIntervals ? i.lower() : i.upper());}); }).values; } - + template<> std::vector<storm::RationalNumber> SparseMdpPrctlHelper<storm::RationalNumber>::computeReachabilityRewards(Environment const& env, storm::solver::SolveGoal<storm::RationalNumber>&&, storm::storage::SparseMatrix<storm::RationalNumber> const&, storm::storage::SparseMatrix<storm::RationalNumber> const&, storm::models::sparse::StandardRewardModel<storm::Interval> const&, bool, storm::storage::BitVector const&, bool) { STORM_LOG_THROW(false, storm::exceptions::IllegalFunctionCallException, "Computing reachability rewards is unsupported for this data type."); } #endif - + struct QualitativeStateSetsReachabilityRewards { storm::storage::BitVector maybeStates; storm::storage::BitVector infinityStates; @@ -934,7 +940,7 @@ namespace storm { QualitativeStateSetsReachabilityRewards getQualitativeStateSetsReachabilityRewardsFromHint(ModelCheckerHint const& hint, storm::storage::BitVector const& targetStates) { QualitativeStateSetsReachabilityRewards result; result.maybeStates = hint.template asExplicitModelCheckerHint<ValueType>().getMaybeStates(); - + // Treat the states with reward zero/infinity. std::vector<ValueType> const& resultsForNonMaybeStates = hint.template asExplicitModelCheckerHint<ValueType>().getResultHint(); result.infinityStates = storm::storage::BitVector(result.maybeStates.size()); @@ -950,7 +956,7 @@ namespace storm { } return result; } - + template<typename ValueType> QualitativeStateSetsReachabilityRewards computeQualitativeStateSetsReachabilityRewards(storm::solver::SolveGoal<ValueType> const& goal, storm::storage::SparseMatrix<ValueType> const& transitionMatrix, storm::storage::SparseMatrix<ValueType> const& backwardTransitions, storm::storage::BitVector const& targetStates, std::function<storm::storage::BitVector()> const& zeroRewardStatesGetter, std::function<storm::storage::BitVector()> const& zeroRewardChoicesGetter) { QualitativeStateSetsReachabilityRewards result; @@ -961,7 +967,7 @@ namespace storm { result.infinityStates = storm::utility::graph::performProb1A(transitionMatrix, transitionMatrix.getRowGroupIndices(), backwardTransitions, trueStates, targetStates); } result.infinityStates.complement(); - + if (storm::settings::getModule<storm::settings::modules::ModelCheckerSettings>().isFilterRewZeroSet()) { if (goal.minimize()) { result.rewardZeroStates = storm::utility::graph::performProb1E(transitionMatrix, transitionMatrix.getRowGroupIndices(), backwardTransitions, trueStates, targetStates, zeroRewardChoicesGetter()); @@ -974,7 +980,7 @@ namespace storm { result.maybeStates = ~(result.rewardZeroStates | result.infinityStates); return result; } - + template<typename ValueType> QualitativeStateSetsReachabilityRewards getQualitativeStateSetsReachabilityRewards(storm::solver::SolveGoal<ValueType> const& goal, storm::storage::SparseMatrix<ValueType> const& transitionMatrix, storm::storage::SparseMatrix<ValueType> const& backwardTransitions, storm::storage::BitVector const& targetStates, ModelCheckerHint const& hint, std::function<storm::storage::BitVector()> const& zeroRewardStatesGetter, std::function<storm::storage::BitVector()> const& zeroRewardChoicesGetter) { if (hint.isExplicitModelCheckerHint() && hint.template asExplicitModelCheckerHint<ValueType>().getComputeOnlyMaybeStates()) { @@ -983,7 +989,7 @@ namespace storm { return computeQualitativeStateSetsReachabilityRewards(goal, transitionMatrix, backwardTransitions, targetStates, zeroRewardStatesGetter, zeroRewardChoicesGetter); } } - + template<typename ValueType> void extendScheduler(storm::storage::Scheduler<ValueType>& scheduler, storm::solver::SolveGoal<ValueType> const& goal, QualitativeStateSetsReachabilityRewards const& qualitativeStateSets, storm::storage::SparseMatrix<ValueType> const& transitionMatrix, storm::storage::SparseMatrix<ValueType> const& backwardTransitions, storm::storage::BitVector const& targetStates, std::function<storm::storage::BitVector()> const& zeroRewardChoicesGetter) { // Finally, if we need to produce a scheduler, we also need to figure out the parts of the scheduler for @@ -1000,7 +1006,7 @@ namespace storm { } } } - + template<typename ValueType> void extractSchedulerChoices(storm::storage::Scheduler<ValueType>& scheduler, storm::storage::SparseMatrix<ValueType> const& transitionMatrix, std::vector<uint_fast64_t> const& subChoices, storm::storage::BitVector const& maybeStates, boost::optional<storm::storage::BitVector> const& selectedChoices) { auto subChoiceIt = subChoices.begin(); @@ -1023,7 +1029,7 @@ namespace storm { } assert(subChoiceIt == subChoices.end()); } - + template<typename ValueType> void computeFixedPointSystemReachabilityRewards(storm::solver::SolveGoal<ValueType>& goal, storm::storage::SparseMatrix<ValueType> const& transitionMatrix, QualitativeStateSetsReachabilityRewards const& qualitativeStateSets, boost::optional<storm::storage::BitVector> const& selectedChoices, std::function<std::vector<ValueType>(uint_fast64_t, storm::storage::SparseMatrix<ValueType> const&, storm::storage::BitVector const&)> const& totalStateRewardVectorGetter, storm::storage::SparseMatrix<ValueType>& submatrix, std::vector<ValueType>& b, std::vector<ValueType>* oneStepTargetProbabilities = nullptr) { // Remove rows and columns from the original transition probability matrix for states whose reward values are already known. @@ -1042,20 +1048,20 @@ namespace storm { (*oneStepTargetProbabilities) = transitionMatrix.getConstrainedRowSumVector(*selectedChoices, qualitativeStateSets.rewardZeroStates); } } - + // If the solve goal has relevant values, we need to adjust them. goal.restrictRelevantValues(qualitativeStateSets.maybeStates); } - + template<typename ValueType> boost::optional<SparseMdpEndComponentInformation<ValueType>> computeFixedPointSystemReachabilityRewardsEliminateEndComponents(storm::solver::SolveGoal<ValueType>& goal, storm::storage::SparseMatrix<ValueType> const& transitionMatrix, storm::storage::SparseMatrix<ValueType> const& backwardTransitions, QualitativeStateSetsReachabilityRewards const& qualitativeStateSets, boost::optional<storm::storage::BitVector> const& selectedChoices, std::function<std::vector<ValueType>(uint_fast64_t, storm::storage::SparseMatrix<ValueType> const&, storm::storage::BitVector const&)> const& totalStateRewardVectorGetter, storm::storage::SparseMatrix<ValueType>& submatrix, std::vector<ValueType>& b, boost::optional<std::vector<ValueType>>& oneStepTargetProbabilities, bool produceScheduler) { - + // Start by computing the choices with reward 0, as we only want ECs within this fragment. storm::storage::BitVector zeroRewardChoices(transitionMatrix.getRowCount()); // Get the rewards of all choices. std::vector<ValueType> rewardVector = totalStateRewardVectorGetter(transitionMatrix.getRowCount(), transitionMatrix, storm::storage::BitVector(transitionMatrix.getRowGroupCount(), true)); - + uint64_t index = 0; for (auto const& e : rewardVector) { if (storm::utility::isZero(e)) { @@ -1063,40 +1069,40 @@ namespace storm { } ++index; } - + // Compute the states that have some zero reward choice. storm::storage::BitVector candidateStates(qualitativeStateSets.maybeStates); for (auto state : qualitativeStateSets.maybeStates) { bool keepState = false; - + for (auto row = transitionMatrix.getRowGroupIndices()[state], rowEnd = transitionMatrix.getRowGroupIndices()[state + 1]; row < rowEnd; ++row) { if (zeroRewardChoices.get(row)) { keepState = true; break; } } - + if (!keepState) { candidateStates.set(state, false); } } - + // Only keep the candidate states that (under some scheduler) can stay in the set of candidates forever candidateStates = storm::utility::graph::performProb0E(transitionMatrix, transitionMatrix.getRowGroupIndices(), backwardTransitions, candidateStates, ~candidateStates); - + bool doDecomposition = !candidateStates.empty(); - + storm::storage::MaximalEndComponentDecomposition<ValueType> endComponentDecomposition; if (doDecomposition) { // Then compute the states that are in MECs with zero reward. endComponentDecomposition = storm::storage::MaximalEndComponentDecomposition<ValueType>(transitionMatrix, backwardTransitions, candidateStates, zeroRewardChoices); } - + // Only do more work if there are actually end-components. if (doDecomposition && !endComponentDecomposition.empty()) { STORM_LOG_DEBUG("Eliminating " << endComponentDecomposition.size() << " ECs."); SparseMdpEndComponentInformation<ValueType> result = SparseMdpEndComponentInformation<ValueType>::eliminateEndComponents(endComponentDecomposition, transitionMatrix, qualitativeStateSets.maybeStates, oneStepTargetProbabilities ? &qualitativeStateSets.rewardZeroStates : nullptr, selectedChoices ? &selectedChoices.get() : nullptr, &rewardVector, submatrix, oneStepTargetProbabilities ? &oneStepTargetProbabilities.get() : nullptr, &b, produceScheduler); - + // If the solve goal has relevant values, we need to adjust them. if (goal.hasRelevantValues()) { storm::storage::BitVector newRelevantValues(submatrix.getRowGroupCount()); @@ -1109,7 +1115,7 @@ namespace storm { goal.setRelevantValues(std::move(newRelevantValues)); } } - + return result; } else { STORM_LOG_DEBUG("Not eliminating ECs as there are none."); @@ -1117,10 +1123,10 @@ namespace storm { return boost::none; } } - + template<typename ValueType> void computeUpperRewardBounds(SparseMdpHintType<ValueType>& hintInformation, storm::OptimizationDirection const& direction, storm::storage::SparseMatrix<ValueType> const& submatrix, std::vector<ValueType> const& choiceRewards, std::vector<ValueType> const& oneStepTargetProbabilities) { - + // For the min-case, we use DS-MPI, for the max-case variant 2 of the Baier et al. paper (CAV'17). if (direction == storm::OptimizationDirection::Minimize) { DsMpiMdpUpperRewardBoundsComputer<ValueType> dsmpi(submatrix, choiceRewards, oneStepTargetProbabilities); @@ -1130,29 +1136,29 @@ namespace storm { hintInformation.upperResultBound = baier.computeUpperBound(); } } - + template<typename ValueType> MDPSparseModelCheckingHelperReturnType<ValueType> SparseMdpPrctlHelper<ValueType>::computeReachabilityRewardsHelper(Environment const& env, storm::solver::SolveGoal<ValueType>&& goal, storm::storage::SparseMatrix<ValueType> const& transitionMatrix, storm::storage::SparseMatrix<ValueType> const& backwardTransitions, std::function<std::vector<ValueType>(uint_fast64_t, storm::storage::SparseMatrix<ValueType> const&, storm::storage::BitVector const&)> const& totalStateRewardVectorGetter, storm::storage::BitVector const& targetStates, bool qualitative, bool produceScheduler, std::function<storm::storage::BitVector()> const& zeroRewardStatesGetter, std::function<storm::storage::BitVector()> const& zeroRewardChoicesGetter, ModelCheckerHint const& hint) { - + // Prepare resulting vector. std::vector<ValueType> result(transitionMatrix.getRowGroupCount(), storm::utility::zero<ValueType>()); // Determine which states have a reward that is infinity or less than infinity. QualitativeStateSetsReachabilityRewards qualitativeStateSets = getQualitativeStateSetsReachabilityRewards(goal, transitionMatrix, backwardTransitions, targetStates, hint, zeroRewardStatesGetter, zeroRewardChoicesGetter); - + STORM_LOG_INFO("Preprocessing: " << qualitativeStateSets.infinityStates.getNumberOfSetBits() << " states with reward infinity, " << qualitativeStateSets.rewardZeroStates.getNumberOfSetBits() << " states with reward zero (" << qualitativeStateSets.maybeStates.getNumberOfSetBits() << " states remaining)."); storm::utility::vector::setVectorValues(result, qualitativeStateSets.infinityStates, storm::utility::infinity<ValueType>()); - + // If requested, we will produce a scheduler. std::unique_ptr<storm::storage::Scheduler<ValueType>> scheduler; if (produceScheduler) { scheduler = std::make_unique<storm::storage::Scheduler<ValueType>>(transitionMatrix.getRowGroupCount()); } - + // Check if the values of the maybe states are relevant for the SolveGoal bool maybeStatesNotRelevant = goal.hasRelevantValues() && goal.relevantValues().isDisjointFrom(qualitativeStateSets.maybeStates); - + // Check whether we need to compute exact rewards for some states. if (qualitative || maybeStatesNotRelevant) { STORM_LOG_INFO("The rewards for the initial states were determined in a preprocessing step. No exact rewards were computed."); @@ -1168,10 +1174,10 @@ namespace storm { if (!qualitativeStateSets.infinityStates.empty()) { selectedChoices = transitionMatrix.getRowFilter(qualitativeStateSets.maybeStates, ~qualitativeStateSets.infinityStates); } - + // Obtain proper hint information either from the provided hint or from requirements of the solver. SparseMdpHintType<ValueType> hintInformation = computeHints(env, SolutionType::ExpectedRewards, hint, goal.direction(), transitionMatrix, backwardTransitions, qualitativeStateSets.maybeStates, ~qualitativeStateSets.rewardZeroStates, qualitativeStateSets.rewardZeroStates, produceScheduler, selectedChoices); - + // Declare the components of the equation system we will solve. storm::storage::SparseMatrix<ValueType> submatrix; std::vector<ValueType> b; @@ -1182,7 +1188,7 @@ namespace storm { if (hintInformation.getComputeUpperBounds()) { oneStepTargetProbabilities = std::vector<ValueType>(); } - + // If the hint information tells us that we have to eliminate MECs, we do so now. boost::optional<SparseMdpEndComponentInformation<ValueType>> ecInformation; if (hintInformation.getEliminateEndComponents()) { @@ -1191,13 +1197,13 @@ namespace storm { // Otherwise, we compute the standard equations. computeFixedPointSystemReachabilityRewards(goal, transitionMatrix, qualitativeStateSets, selectedChoices, totalStateRewardVectorGetter, submatrix, b, oneStepTargetProbabilities ? &oneStepTargetProbabilities.get() : nullptr); } - + // If we need to compute upper bounds, do so now. if (hintInformation.getComputeUpperBounds()) { STORM_LOG_ASSERT(oneStepTargetProbabilities, "Expecting one step target probability vector to be available."); computeUpperRewardBounds(hintInformation, goal.direction(), submatrix, b, oneStepTargetProbabilities.get()); } - + // Now compute the results for the maybe states. MaybeStateResult<ValueType> resultForMaybeStates = computeValuesForMaybeStates(env, std::move(goal), std::move(submatrix), b, produceScheduler, hintInformation); @@ -1216,12 +1222,12 @@ namespace storm { } } } - + // Extend scheduler with choices for the states in the qualitative state sets. if (produceScheduler) { extendScheduler(*scheduler, goal, qualitativeStateSets, transitionMatrix, backwardTransitions, targetStates, zeroRewardChoicesGetter); } - + // Sanity check for created scheduler. STORM_LOG_ASSERT(!produceScheduler || scheduler, "Expected that a scheduler was obtained."); STORM_LOG_ASSERT((!produceScheduler && !scheduler) || !scheduler->isPartialScheduler(), "Expected a fully defined scheduler"); @@ -1232,12 +1238,12 @@ namespace storm { return MDPSparseModelCheckingHelperReturnType<ValueType>(std::move(result), std::move(qualitativeStateSets.maybeStates), std::move(scheduler), std::move(choiceValues)); } - + template<typename ValueType> std::unique_ptr<CheckResult> SparseMdpPrctlHelper<ValueType>::computeConditionalProbabilities(Environment const& env, storm::solver::SolveGoal<ValueType>&& goal, storm::storage::SparseMatrix<ValueType> const& transitionMatrix, storm::storage::SparseMatrix<ValueType> const& backwardTransitions, storm::storage::BitVector const& targetStates, storm::storage::BitVector const& conditionStates) { - + std::chrono::high_resolution_clock::time_point start = std::chrono::high_resolution_clock::now(); - + // For the max-case, we can simply take the given target states. For the min-case, however, we need to // find the MECs of non-target states and make them the new target states. storm::storage::BitVector fixedTargetStates; @@ -1252,18 +1258,18 @@ namespace storm { } } } - + storm::storage::BitVector allStates(fixedTargetStates.size(), true); - + // Extend the target states by computing all states that have probability 1 to go to a target state // under *all* schedulers. fixedTargetStates = storm::utility::graph::performProb1A(transitionMatrix, transitionMatrix.getRowGroupIndices(), backwardTransitions, allStates, fixedTargetStates); - + // We solve the max-case and later adjust the result if the optimization direction was to minimize. storm::storage::BitVector initialStatesBitVector = goal.relevantValues(); STORM_LOG_THROW(initialStatesBitVector.getNumberOfSetBits() == 1, storm::exceptions::NotSupportedException, "Computing conditional probabilities in MDPs is only supported for models with exactly one initial state."); storm::storage::sparse::state_type initialState = *initialStatesBitVector.begin(); - + // Extend the condition states by computing all states that have probability 1 to go to a condition state // under *all* schedulers. storm::storage::BitVector extendedConditionStates = storm::utility::graph::performProb1A(transitionMatrix, transitionMatrix.getRowGroupIndices(), backwardTransitions, allStates, conditionStates); @@ -1273,12 +1279,12 @@ namespace storm { std::vector<ValueType> conditionProbabilities = std::move(computeUntilProbabilities(env, OptimizationDirection::Maximize, transitionMatrix, backwardTransitions, allStates, extendedConditionStates, false, false).values); std::chrono::high_resolution_clock::time_point conditionEnd = std::chrono::high_resolution_clock::now(); STORM_LOG_DEBUG("Computed probabilities to satisfy for condition in " << std::chrono::duration_cast<std::chrono::milliseconds>(conditionEnd - conditionStart).count() << "ms."); - + // If the conditional probability is undefined for the initial state, we return directly. if (storm::utility::isZero(conditionProbabilities[initialState])) { return std::unique_ptr<CheckResult>(new ExplicitQuantitativeCheckResult<ValueType>(initialState, storm::utility::infinity<ValueType>())); } - + STORM_LOG_DEBUG("Computing probabilities to reach target."); std::chrono::high_resolution_clock::time_point targetStart = std::chrono::high_resolution_clock::now(); std::vector<ValueType> targetProbabilities = std::move(computeUntilProbabilities(env, OptimizationDirection::Maximize, transitionMatrix, backwardTransitions, allStates, fixedTargetStates, false, false).values); @@ -1306,7 +1312,7 @@ namespace storm { storm::storage::sparse::state_type newGoalState = relevantStates.getNumberOfSetBits(); storm::storage::sparse::state_type newStopState = newGoalState + 1; storm::storage::sparse::state_type newFailState = newStopState + 1; - + // Build the transitions of the (relevant) states of the original model. storm::storage::SparseMatrixBuilder<ValueType> builder(0, newFailState + 1, 0, true, true); uint_fast64_t currentRow = 0; @@ -1344,7 +1350,7 @@ namespace storm { } } } - + // Now build the transitions of the newly introduced states. builder.newRowGroup(currentRow); builder.addNextValue(currentRow, newGoalState, storm::utility::one<ValueType>()); @@ -1355,10 +1361,10 @@ namespace storm { builder.newRowGroup(currentRow); builder.addNextValue(currentRow, numberOfStatesBeforeRelevantStates[initialState], storm::utility::one<ValueType>()); ++currentRow; - + std::chrono::high_resolution_clock::time_point end = std::chrono::high_resolution_clock::now(); STORM_LOG_DEBUG("Computed transformed model in " << std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count() << "ms."); - + // Finally, build the matrix and dispatch the query as a reachability query. STORM_LOG_DEBUG("Computing conditional probabilties."); storm::storage::BitVector newGoalStates(newFailState + 1); @@ -1366,20 +1372,20 @@ namespace storm { storm::storage::SparseMatrix<ValueType> newTransitionMatrix = builder.build(); STORM_LOG_DEBUG("Transformed model has " << newTransitionMatrix.getRowGroupCount() << " states and " << newTransitionMatrix.getNonzeroEntryCount() << " transitions."); storm::storage::SparseMatrix<ValueType> newBackwardTransitions = newTransitionMatrix.transpose(true); - + storm::solver::OptimizationDirection dir = goal.direction(); if (goal.minimize()) { goal.oneMinus(); } - + std::chrono::high_resolution_clock::time_point conditionalStart = std::chrono::high_resolution_clock::now(); std::vector<ValueType> goalProbabilities = std::move(computeUntilProbabilities(env, std::move(goal), newTransitionMatrix, newBackwardTransitions, storm::storage::BitVector(newFailState + 1, true), newGoalStates, false, false).values); std::chrono::high_resolution_clock::time_point conditionalEnd = std::chrono::high_resolution_clock::now(); STORM_LOG_DEBUG("Computed conditional probabilities in transformed model in " << std::chrono::duration_cast<std::chrono::milliseconds>(conditionalEnd - conditionalStart).count() << "ms."); - + return std::unique_ptr<CheckResult>(new ExplicitQuantitativeCheckResult<ValueType>(initialState, dir == OptimizationDirection::Maximize ? goalProbabilities[numberOfStatesBeforeRelevantStates[initialState]] : storm::utility::one<ValueType>() - goalProbabilities[numberOfStatesBeforeRelevantStates[initialState]])); } - + template class SparseMdpPrctlHelper<double>; template std::vector<double> SparseMdpPrctlHelper<double>::computeInstantaneousRewards(Environment const& env, storm::solver::SolveGoal<double>&& goal, storm::storage::SparseMatrix<double> const& transitionMatrix, storm::models::sparse::StandardRewardModel<double> const& rewardModel, uint_fast64_t stepCount); template std::vector<double> SparseMdpPrctlHelper<double>::computeCumulativeRewards(Environment const& env, storm::solver::SolveGoal<double>&& goal, storm::storage::SparseMatrix<double> const& transitionMatrix, storm::models::sparse::StandardRewardModel<double> const& rewardModel, uint_fast64_t stepBound); diff --git a/src/storm/modelchecker/prctl/helper/SparseMdpPrctlHelper.h b/src/storm/modelchecker/prctl/helper/SparseMdpPrctlHelper.h index 099533dab..6515b9d83 100644 --- a/src/storm/modelchecker/prctl/helper/SparseMdpPrctlHelper.h +++ b/src/storm/modelchecker/prctl/helper/SparseMdpPrctlHelper.h @@ -46,7 +46,7 @@ namespace storm { static MDPSparseModelCheckingHelperReturnType<ValueType> computeUntilProbabilities(Environment const& env, storm::solver::SolveGoal<ValueType>&& goal, storm::storage::SparseMatrix<ValueType> const& transitionMatrix, storm::storage::SparseMatrix<ValueType> const& backwardTransitions, storm::storage::BitVector const& phiStates, storm::storage::BitVector const& psiStates, bool qualitative, bool produceScheduler, ModelCheckerHint const& hint = ModelCheckerHint()); static MDPSparseModelCheckingHelperReturnType<ValueType> computeGloballyProbabilities(Environment const& env, storm::solver::SolveGoal<ValueType>&& goal, storm::storage::SparseMatrix<ValueType> const& transitionMatrix, storm::storage::SparseMatrix<ValueType> const& backwardTransitions, storm::storage::BitVector const& psiStates, bool qualitative, bool produceScheduler, bool useMecBasedTechnique = false); - + template<typename RewardModelType> static std::vector<ValueType> computeInstantaneousRewards(Environment const& env, storm::solver::SolveGoal<ValueType>&& goal, storm::storage::SparseMatrix<ValueType> const& transitionMatrix, RewardModelType const& rewardModel, uint_fast64_t stepCount); diff --git a/src/storm/modelchecker/results/ExplicitQuantitativeCheckResult.cpp b/src/storm/modelchecker/results/ExplicitQuantitativeCheckResult.cpp index e05c83344..19b1f627e 100644 --- a/src/storm/modelchecker/results/ExplicitQuantitativeCheckResult.cpp +++ b/src/storm/modelchecker/results/ExplicitQuantitativeCheckResult.cpp @@ -51,6 +51,31 @@ namespace storm { ExplicitQuantitativeCheckResult<ValueType>::ExplicitQuantitativeCheckResult(boost::variant<vector_type, map_type>&& values, boost::optional<std::shared_ptr<storm::storage::Scheduler<ValueType>>> scheduler) : values(std::move(values)), scheduler(scheduler) { // Intentionally left empty. } + + template<typename ValueType> + ExplicitQuantitativeCheckResult<ValueType>::ExplicitQuantitativeCheckResult(ExplicitQualitativeCheckResult const& other) { + if (other.isResultForAllStates()) { + storm::storage::BitVector const& bvValues = other.getTruthValuesVector(); + + vector_type newVector; + newVector.reserve(bvValues.size()); + for (std::size_t i = 0, n = bvValues.size(); i < n; i++) { + newVector.push_back(bvValues.get(i) ? storm::utility::one<ValueType>() : storm::utility::zero<ValueType>()); + } + + values = newVector; + } else { + ExplicitQualitativeCheckResult::map_type const& bitMap = other.getTruthValuesMap(); + + map_type newMap; + for (auto const& e : bitMap) { + newMap[e.first] = e.second ? storm::utility::one<ValueType>() : storm::utility::zero<ValueType>(); + } + + values = newMap; + } + } + template<typename ValueType> std::unique_ptr<CheckResult> ExplicitQuantitativeCheckResult<ValueType>::clone() const { diff --git a/src/storm/modelchecker/results/ExplicitQuantitativeCheckResult.h b/src/storm/modelchecker/results/ExplicitQuantitativeCheckResult.h index e6fe5a178..4fe38b0f0 100644 --- a/src/storm/modelchecker/results/ExplicitQuantitativeCheckResult.h +++ b/src/storm/modelchecker/results/ExplicitQuantitativeCheckResult.h @@ -16,6 +16,9 @@ namespace storm { namespace modelchecker { + // fwd + class ExplicitQualitativeCheckResult; + template<typename ValueType> class ExplicitQuantitativeCheckResult : public QuantitativeCheckResult<ValueType> { public: @@ -37,6 +40,8 @@ namespace storm { ExplicitQuantitativeCheckResult(ExplicitQuantitativeCheckResult&& other) = default; ExplicitQuantitativeCheckResult& operator=(ExplicitQuantitativeCheckResult&& other) = default; #endif + explicit ExplicitQuantitativeCheckResult(ExplicitQualitativeCheckResult const& other); + virtual ~ExplicitQuantitativeCheckResult() = default; virtual std::unique_ptr<CheckResult> clone() const override; diff --git a/src/storm/modelchecker/results/SymbolicQualitativeCheckResult.cpp b/src/storm/modelchecker/results/SymbolicQualitativeCheckResult.cpp index 1fea0544c..d11d0afe4 100644 --- a/src/storm/modelchecker/results/SymbolicQualitativeCheckResult.cpp +++ b/src/storm/modelchecker/results/SymbolicQualitativeCheckResult.cpp @@ -61,6 +61,16 @@ namespace storm { return this->truthValues; } + template<storm::dd::DdType Type> + storm::dd::Bdd<Type> const& SymbolicQualitativeCheckResult<Type>::getStates() const { + return states; + } + + template<storm::dd::DdType Type> + storm::dd::Bdd<Type> const& SymbolicQualitativeCheckResult<Type>::getReachableStates() const { + return reachableStates; + } + template <storm::dd::DdType Type> bool SymbolicQualitativeCheckResult<Type>::existsTrue() const { return !this->truthValues.isZero(); diff --git a/src/storm/modelchecker/results/SymbolicQualitativeCheckResult.h b/src/storm/modelchecker/results/SymbolicQualitativeCheckResult.h index 9afa4cd0f..2c2c022f1 100644 --- a/src/storm/modelchecker/results/SymbolicQualitativeCheckResult.h +++ b/src/storm/modelchecker/results/SymbolicQualitativeCheckResult.h @@ -40,6 +40,8 @@ namespace storm { storm::dd::Bdd<Type> const& getTruthValuesVector() const; + storm::dd::Bdd<Type> const& getStates() const; + storm::dd::Bdd<Type> const& getReachableStates() const; virtual std::ostream& writeToStream(std::ostream& out) const override; diff --git a/src/storm/modelchecker/results/SymbolicQuantitativeCheckResult.cpp b/src/storm/modelchecker/results/SymbolicQuantitativeCheckResult.cpp index ef778a7f7..37d79ffea 100644 --- a/src/storm/modelchecker/results/SymbolicQuantitativeCheckResult.cpp +++ b/src/storm/modelchecker/results/SymbolicQuantitativeCheckResult.cpp @@ -22,6 +22,12 @@ namespace storm { // Intentionally left empty. } + + template<storm::dd::DdType Type, typename ValueType> + SymbolicQuantitativeCheckResult<Type, ValueType>::SymbolicQuantitativeCheckResult(SymbolicQualitativeCheckResult<Type> const& other) : reachableStates(other.getReachableStates()), states(other.getStates()), values(other.getTruthValuesVector().template toAdd<ValueType>()) { + // Intentionally left empty. + } + template<storm::dd::DdType Type, typename ValueType> std::unique_ptr<CheckResult> SymbolicQuantitativeCheckResult<Type, ValueType>::clone() const { return std::make_unique<SymbolicQuantitativeCheckResult<Type, ValueType>>(this->reachableStates, this->states, this->values); diff --git a/src/storm/modelchecker/results/SymbolicQuantitativeCheckResult.h b/src/storm/modelchecker/results/SymbolicQuantitativeCheckResult.h index d1d5fa3ba..61c041d5f 100644 --- a/src/storm/modelchecker/results/SymbolicQuantitativeCheckResult.h +++ b/src/storm/modelchecker/results/SymbolicQuantitativeCheckResult.h @@ -8,6 +8,10 @@ namespace storm { namespace modelchecker { + // fwd + template<storm::dd::DdType Type> + class SymbolicQualitativeCheckResult; + template<storm::dd::DdType Type, typename ValueType = double> class SymbolicQuantitativeCheckResult : public QuantitativeCheckResult<ValueType> { public: @@ -21,6 +25,8 @@ namespace storm { SymbolicQuantitativeCheckResult(SymbolicQuantitativeCheckResult&& other) = default; SymbolicQuantitativeCheckResult& operator=(SymbolicQuantitativeCheckResult&& other) = default; #endif + + SymbolicQuantitativeCheckResult(SymbolicQualitativeCheckResult<Type> const& other); virtual std::unique_ptr<CheckResult> clone() const override; diff --git a/src/storm/models/sparse/ItemLabeling.cpp b/src/storm/models/sparse/ItemLabeling.cpp index 329c961c8..47db00e3c 100644 --- a/src/storm/models/sparse/ItemLabeling.cpp +++ b/src/storm/models/sparse/ItemLabeling.cpp @@ -137,6 +137,18 @@ namespace storm { labelings.emplace_back(std::move(labeling)); } + std::string ItemLabeling::addUniqueLabel(std::string const& prefix, storage::BitVector const& labeling) { + std::string label = generateUniqueLabel(prefix); + addLabel(label, labeling); + return label; + } + + std::string ItemLabeling::addUniqueLabel(std::string const& prefix, storage::BitVector const&& labeling) { + std::string label = generateUniqueLabel(prefix); + addLabel(label, labeling); + return label; + } + bool ItemLabeling::containsLabel(std::string const& label) const { return nameToLabelingIndexMap.find(label) != nameToLabelingIndexMap.end(); } @@ -210,6 +222,18 @@ namespace storm { return out; } + std::string ItemLabeling::generateUniqueLabel(const std::string& prefix) const { + if (!containsLabel(prefix)) { + return prefix; + } + unsigned int i = 0; + std::string label; + do { + label = prefix + "_" + std::to_string(i); + } while (containsLabel(label)); + return label; + } + } } } diff --git a/src/storm/models/sparse/ItemLabeling.h b/src/storm/models/sparse/ItemLabeling.h index 43a5b9f21..9c386de85 100644 --- a/src/storm/models/sparse/ItemLabeling.h +++ b/src/storm/models/sparse/ItemLabeling.h @@ -3,6 +3,7 @@ #include <unordered_map> #include <set> +#include <string> #include <ostream> @@ -90,6 +91,28 @@ namespace storm { */ void addLabel(std::string const& label, storage::BitVector&& labeling); + /*! + * Creates a new label with a unique name, derived from the prefix, + * and attaches it to the given items. Note that the dimension of given labeling must + * match the number of items for which this item labeling is valid. + * + * @param prefix A prefix to use for the new label. + * @param labeling A bit vector that indicates whether or not the new label is attached to a item. + * @return the new label + */ + std::string addUniqueLabel(std::string const& prefix, storage::BitVector const& labeling); + + /*! + * Creates a new label with a unique name, derived from the prefix, + * and attaches it to the given items. Note that the dimension of given labeling must + * match the number of items for which this item labeling is valid. + * + * @param prefix A prefix to use for the new label. + * @param labeling A bit vector that indicates whether or not the new label is attached to a item. + * @return the new label + */ + std::string addUniqueLabel(std::string const& prefix, storage::BitVector const&& labeling); + /*! * Adds all labels from the other labeling to this labeling. * It is assumed that both labelings have the same itemcount. @@ -217,6 +240,12 @@ namespace storm { // A vector that holds the labeling for all known labels. std::vector<storm::storage::BitVector> labelings; + + /*! + * Generate a unique, previously unused label from the given prefix string. + */ + std::string generateUniqueLabel(const std::string& prefix) const; + }; } // namespace sparse diff --git a/src/storm/models/sparse/Model.h b/src/storm/models/sparse/Model.h index 962e17dbf..d89a4d772 100644 --- a/src/storm/models/sparse/Model.h +++ b/src/storm/models/sparse/Model.h @@ -6,6 +6,7 @@ #include <boost/optional.hpp> #include "storm/models/Model.h" +#include "storm/models/ModelRepresentation.h" #include "storm/models/sparse/StateLabeling.h" #include "storm/models/sparse/ChoiceLabeling.h" #include "storm/storage/sparse/ModelComponents.h" @@ -34,6 +35,7 @@ namespace storm { public: typedef CValueType ValueType; typedef CRewardModelType RewardModelType; + static const storm::models::ModelRepresentation Representation = ModelRepresentation::Sparse; Model(Model<ValueType, RewardModelType> const& other) = default; Model& operator=(Model<ValueType, RewardModelType> const& other) = default; diff --git a/src/storm/models/symbolic/Model.h b/src/storm/models/symbolic/Model.h index 0146b33b8..7cb738489 100644 --- a/src/storm/models/symbolic/Model.h +++ b/src/storm/models/symbolic/Model.h @@ -12,6 +12,7 @@ #include "storm/storage/dd/Add.h" #include "storm/storage/dd/Bdd.h" #include "storm/models/Model.h" +#include "storm/models/ModelRepresentation.h" #include "storm/utility/OsDetection.h" #include "storm-config.h" @@ -50,6 +51,8 @@ namespace storm { static const storm::dd::DdType DdType = Type; typedef StandardRewardModel<Type, ValueType> RewardModelType; + static const storm::models::ModelRepresentation Representation = GetModelRepresentation<DdType>::representation; + Model(Model<Type, ValueType> const& other) = default; Model& operator=(Model<Type, ValueType> const& other) = default; diff --git a/src/storm/settings/modules/ModelCheckerSettings.cpp b/src/storm/settings/modules/ModelCheckerSettings.cpp index da0b64d8e..d54e8a92e 100644 --- a/src/storm/settings/modules/ModelCheckerSettings.cpp +++ b/src/storm/settings/modules/ModelCheckerSettings.cpp @@ -14,14 +14,24 @@ namespace storm { const std::string ModelCheckerSettings::moduleName = "modelchecker"; const std::string ModelCheckerSettings::filterRewZeroOptionName = "filterrewzero"; + const std::string ModelCheckerSettings::ltl2daToolOptionName = "ltl2datool"; ModelCheckerSettings::ModelCheckerSettings() : ModuleSettings(moduleName) { this->addOption(storm::settings::OptionBuilder(moduleName, filterRewZeroOptionName, false, "If set, states with reward zero are filtered out, potentially reducing the size of the equation system").setIsAdvanced().build()); + this->addOption(storm::settings::OptionBuilder(moduleName, ltl2daToolOptionName, false, "If set, use an external tool to convert LTL formulas to state-based deterministic automata in HOA format").setIsAdvanced().addArgument(storm::settings::ArgumentBuilder::createStringArgument("filename", "A script that can be called with a prefix formula and a name for the output automaton.").build()).build()); } bool ModelCheckerSettings::isFilterRewZeroSet() const { return this->getOption(filterRewZeroOptionName).getHasOptionBeenSet(); } + + bool ModelCheckerSettings::isLtl2daToolSet() const { + return this->getOption(ltl2daToolOptionName).getHasOptionBeenSet(); + } + + std::string ModelCheckerSettings::getLtl2daTool() const { + return this->getOption(ltl2daToolOptionName).getArgumentByName("filename").getValueAsString(); + } } // namespace modules } // namespace settings diff --git a/src/storm/settings/modules/ModelCheckerSettings.h b/src/storm/settings/modules/ModelCheckerSettings.h index 4c6a1dfd6..6d5511863 100644 --- a/src/storm/settings/modules/ModelCheckerSettings.h +++ b/src/storm/settings/modules/ModelCheckerSettings.h @@ -19,15 +19,30 @@ namespace storm { * Creates a new set of general settings. */ ModelCheckerSettings(); - + bool isFilterRewZeroSet() const; + /*! + * Retrieves whether the external ltl2da tool has been set. + * + * @return True iff the external ltl2da has been set. + */ + bool isLtl2daToolSet() const; + + /*! + * Retrieves the external ltl2da tool that is used for converting LTL formulas to deterministic automata. + * + * @return The executable to use for converting LTL formulas to deterministic automata. + */ + std::string getLtl2daTool() const; + // The name of the module. static const std::string moduleName; private: // Define the string names of the options as constants. static const std::string filterRewZeroOptionName; + static const std::string ltl2daToolOptionName; }; } // namespace modules diff --git a/src/storm/storage/MaximalEndComponent.cpp b/src/storm/storage/MaximalEndComponent.cpp index 58683a3df..aa7453277 100644 --- a/src/storm/storage/MaximalEndComponent.cpp +++ b/src/storm/storage/MaximalEndComponent.cpp @@ -1,4 +1,5 @@ #include "storm/storage/MaximalEndComponent.h" +#include "storm/storage/BitVector.h" #include "storm/exceptions/InvalidStateException.h" namespace storm { @@ -69,6 +70,16 @@ namespace storm { return true; } + bool MaximalEndComponent::containsAnyState(storm::storage::BitVector stateSet) const { + // TODO: iteration over unordered_map is potentially inefficient? + for (auto const& stateChoicesPair : stateToChoicesMapping) { + if (stateSet.get(stateChoicesPair.first)) { + return true; + } + } + return false; + } + void MaximalEndComponent::removeState(uint_fast64_t state) { auto stateChoicePair = stateToChoicesMapping.find(state); diff --git a/src/storm/storage/MaximalEndComponent.h b/src/storm/storage/MaximalEndComponent.h index b40da6455..a1d5b37c2 100644 --- a/src/storm/storage/MaximalEndComponent.h +++ b/src/storm/storage/MaximalEndComponent.h @@ -8,6 +8,8 @@ namespace storm { namespace storage { + // fwd + class BitVector; /*! * This class represents a maximal end-component of a nondeterministic model. @@ -106,6 +108,14 @@ namespace storm { */ bool containsState(uint_fast64_t state) const; + /*! + * Retrieves whether at least one of the given states is contained in this MEC. + * + * @param stateSet The states for which to query membership in the MEC. + * @return True if any of the given states is contained in the MEC. + */ + bool containsAnyState(storm::storage::BitVector stateSet) const; + /*! * Retrieves whether the given choice for the given state is contained in the MEC. * diff --git a/src/storm/storage/Scheduler.cpp b/src/storm/storage/Scheduler.cpp index 0582fdd76..6405528a0 100644 --- a/src/storm/storage/Scheduler.cpp +++ b/src/storm/storage/Scheduler.cpp @@ -13,30 +13,36 @@ namespace storm { Scheduler<ValueType>::Scheduler(uint_fast64_t numberOfModelStates, boost::optional<storm::storage::MemoryStructure> const& memoryStructure) : memoryStructure(memoryStructure) { uint_fast64_t numOfMemoryStates = memoryStructure ? memoryStructure->getNumberOfStates() : 1; schedulerChoices = std::vector<std::vector<SchedulerChoice<ValueType>>>(numOfMemoryStates, std::vector<SchedulerChoice<ValueType>>(numberOfModelStates)); + dontCareStates = std::vector<storm::storage::BitVector>(numOfMemoryStates, storm::storage::BitVector(numberOfModelStates, false)); numOfUndefinedChoices = numOfMemoryStates * numberOfModelStates; numOfDeterministicChoices = 0; + numOfDontCareStates = 0; } template <typename ValueType> Scheduler<ValueType>::Scheduler(uint_fast64_t numberOfModelStates, boost::optional<storm::storage::MemoryStructure>&& memoryStructure) : memoryStructure(std::move(memoryStructure)) { uint_fast64_t numOfMemoryStates = this->memoryStructure ? this->memoryStructure->getNumberOfStates() : 1; schedulerChoices = std::vector<std::vector<SchedulerChoice<ValueType>>>(numOfMemoryStates, std::vector<SchedulerChoice<ValueType>>(numberOfModelStates)); + dontCareStates = std::vector<storm::storage::BitVector>(numOfMemoryStates, storm::storage::BitVector(numberOfModelStates, false)); numOfUndefinedChoices = numOfMemoryStates * numberOfModelStates; numOfDeterministicChoices = 0; + numOfDontCareStates = 0; } template <typename ValueType> void Scheduler<ValueType>::setChoice(SchedulerChoice<ValueType> const& choice, uint_fast64_t modelState, uint_fast64_t memoryState) { STORM_LOG_ASSERT(memoryState < getNumberOfMemoryStates(), "Illegal memory state index"); STORM_LOG_ASSERT(modelState < schedulerChoices[memoryState].size(), "Illegal model state index"); + auto& schedulerChoice = schedulerChoices[memoryState][modelState]; + if (schedulerChoice.isDefined()) { if (!choice.isDefined()) { ++numOfUndefinedChoices; } } else { if (choice.isDefined()) { - assert(numOfUndefinedChoices > 0); + assert(numOfUndefinedChoices > 0); --numOfUndefinedChoices; } } @@ -79,6 +85,39 @@ namespace storm { return schedulerChoices[memoryState][modelState]; } + template <typename ValueType> + void Scheduler<ValueType>::setDontCare(uint_fast64_t modelState, uint_fast64_t memoryState, bool setArbitraryChoice) { + STORM_LOG_ASSERT(memoryState < getNumberOfMemoryStates(), "Illegal memory state index"); + STORM_LOG_ASSERT(modelState < schedulerChoices[memoryState].size(), "Illegal model state index"); + + if (!dontCareStates[memoryState].get(modelState)) { + auto& schedulerChoice = schedulerChoices[memoryState][modelState]; + if (!schedulerChoice.isDefined() && setArbitraryChoice) { + // Set an arbitrary choice + this->setChoice(0, modelState, memoryState); + } + dontCareStates[memoryState].set(modelState, true); + ++numOfDontCareStates; + } + } + + template <typename ValueType> + void Scheduler<ValueType>::unSetDontCare(uint_fast64_t modelState, uint_fast64_t memoryState) { + STORM_LOG_ASSERT(memoryState < getNumberOfMemoryStates(), "Illegal memory state index"); + STORM_LOG_ASSERT(modelState < schedulerChoices[memoryState].size(), "Illegal model state index"); + + if (dontCareStates[memoryState].get(modelState)) { + dontCareStates[memoryState].set(modelState, false); + --numOfDontCareStates; + } + } + + + template <typename ValueType> + bool Scheduler<ValueType>::isDontCare(uint_fast64_t modelState, uint64_t memoryState) const { + return dontCareStates[memoryState].get(modelState); + } + template<typename ValueType> storm::storage::BitVector Scheduler<ValueType>::computeActionSupport(std::vector<uint_fast64_t> const& nondeterministicChoiceIndices) const { auto nrActions = nondeterministicChoiceIndices.back(); @@ -123,7 +162,7 @@ namespace storm { } template <typename ValueType> - void Scheduler<ValueType>::printToStream(std::ostream& out, std::shared_ptr<storm::models::sparse::Model<ValueType>> model, bool skipUniqueChoices) const { + void Scheduler<ValueType>::printToStream(std::ostream& out, std::shared_ptr<storm::models::sparse::Model<ValueType>> model, bool skipUniqueChoices, bool skipDontCareStates) const { STORM_LOG_THROW(model == nullptr || model->getNumberOfStates() == schedulerChoices.front().size(), storm::exceptions::InvalidOperationException, "The given model is not compatible with this scheduler."); bool const stateValuationsGiven = model != nullptr && model->hasStateValuations(); @@ -145,7 +184,7 @@ namespace storm { } out << ":" << std::endl; STORM_LOG_WARN_COND(!(skipUniqueChoices && model == nullptr), "Can not skip unique choices if the model is not given."); - out << std::setw(widthOfStates) << "model state:" << " " << (isMemorylessScheduler() ? "" : " memory: ") << "choice(s)" << std::endl; + out << std::setw(widthOfStates) << "model state:" << " " << (isMemorylessScheduler() ? "" : " memory: ") << "choice(s)" << (isMemorylessScheduler() ? "" : " memory updates: ") << std::endl; for (uint_fast64_t state = 0; state < schedulerChoices.front().size(); ++state) { std::stringstream stateString; // Check whether the state is skipped @@ -175,6 +214,27 @@ namespace storm { if (!isMemorylessScheduler()) { stateString << "m" << std::setw(8) << memoryState; } + stateString << " "; + + bool firstMemoryState = true; + for (uint_fast64_t memoryState = 0; memoryState < getNumberOfMemoryStates(); ++memoryState) { + + // Ignore dontCare states + if(skipDontCareStates && isDontCare(state, memoryState)) { + continue; + } + + // Indent if this is not the first memory state + if (firstMemoryState) { + firstMemoryState = false; + } else { + out << std::setw(widthOfStates) << ""; + out << " "; + } + // Print the memory state info + if (!isMemorylessScheduler()) { + out << "m="<< memoryState << std::setw(8) << ""; + } // Print choice info SchedulerChoice<ValueType> const& choice = schedulerChoices[memoryState][state]; @@ -215,61 +275,139 @@ namespace storm { stateString << "undefined."; } - // Todo: print memory updates - out << stateString.str(); - out << std::endl; + // Print memory updates + if(!isMemorylessScheduler()) { + stateString << std::setw(widthOfStates) << ""; + // The memory updates do not depend on the actual choice, they only depend on the current model- and memory state as well as the successor model state. + for (auto const& choiceProbPair : choice.getChoiceAsDistribution()) { + uint64_t row = model->getTransitionMatrix().getRowGroupIndices()[state] + choiceProbPair.first; + bool firstUpdate = true; + for (auto entryIt = model->getTransitionMatrix().getRow(row).begin(); entryIt < model->getTransitionMatrix().getRow(row).end(); ++entryIt) { + if (firstUpdate) { + firstUpdate = false; + } else { + stateString << ", "; + } + stateString << "model state' = " << entryIt->getColumn() << ": -> " << "(m' = "<<this->memoryStructure->getSuccessorMemoryState(memoryState, entryIt - model->getTransitionMatrix().begin()) <<")"; + // out << "model state' = " << entryIt->getColumn() << ": (transition = " << entryIt - model->getTransitionMatrix().begin() << ") -> " << "(m' = "<<this->memoryStructure->getSuccessorMemoryState(memoryState, entryIt - model->getTransitionMatrix().begin()) <<")"; + } + } + } + + // Print memory updates + if(!isMemorylessScheduler()) { + out << std::setw(widthOfStates) << ""; + // The memory updates do not depend on the actual choice, they only depend on the current model- and memory state as well as the successor model state. + for (auto const& choiceProbPair : choice.getChoiceAsDistribution()) { + uint64_t row = model->getTransitionMatrix().getRowGroupIndices()[state] + choiceProbPair.first; + bool firstUpdate = true; + for (auto entryIt = model->getTransitionMatrix().getRow(row).begin(); entryIt < model->getTransitionMatrix().getRow(row).end(); ++entryIt) { + if (firstUpdate) { + firstUpdate = false; + } else { + out << ", "; + } + out << "model state' = " << entryIt->getColumn() << ": -> " << "(m' = "<<this->memoryStructure->getSuccessorMemoryState(memoryState, entryIt - model->getTransitionMatrix().begin()) <<")"; + // out << "model state' = " << entryIt->getColumn() << ": (transition = " << entryIt - model->getTransitionMatrix().begin() << ") -> " << "(m' = "<<this->memoryStructure->getSuccessorMemoryState(memoryState, entryIt - model->getTransitionMatrix().begin()) <<")"; + } + + } + + } + + out << std::endl; + } + + stateString << stateString.str(); + stateString << std::endl; } } if (numOfSkippedStatesWithUniqueChoice > 0) { - out << "Skipped " << numOfSkippedStatesWithUniqueChoice << " deterministic states with unique choice." << std::endl; + stateString << "Skipped " << numOfSkippedStatesWithUniqueChoice << " deterministic states with unique choice." << std::endl; } - out << "___________________________________________________________________" << std::endl; + stateString << "___________________________________________________________________" << std::endl; + } template <> - void Scheduler<float>::printJsonToStream(std::ostream& out, std::shared_ptr<storm::models::sparse::Model<float>> model, bool skipUniqueChoices) const { + void Scheduler<float>::printJsonToStream(std::ostream& out, std::shared_ptr<storm::models::sparse::Model<float>> model, bool skipUniqueChoices, bool skipDontCareStates) const { STORM_LOG_THROW(isMemorylessScheduler(), storm::exceptions::NotImplementedException, "Json export of schedulers not implemented for this value type."); } template <typename ValueType> - void Scheduler<ValueType>::printJsonToStream(std::ostream& out, std::shared_ptr<storm::models::sparse::Model<ValueType>> model, bool skipUniqueChoices) const { + void Scheduler<ValueType>::printJsonToStream(std::ostream& out, std::shared_ptr<storm::models::sparse::Model<ValueType>> model, bool skipUniqueChoices, bool skipDontCareStates) const { STORM_LOG_THROW(model == nullptr || model->getNumberOfStates() == schedulerChoices.front().size(), storm::exceptions::InvalidOperationException, "The given model is not compatible with this scheduler."); STORM_LOG_WARN_COND(!(skipUniqueChoices && model == nullptr), "Can not skip unique choices if the model is not given."); - STORM_LOG_THROW(isMemorylessScheduler(), storm::exceptions::NotImplementedException, "Json export of schedulers with memory not implemented."); storm::json<storm::RationalNumber> output; for (uint64_t state = 0; state < schedulerChoices.front().size(); ++state) { // Check whether the state is skipped if (skipUniqueChoices && model != nullptr && model->getTransitionMatrix().getRowGroupSize(state) == 1) { continue; } - storm::json<storm::RationalNumber> stateChoicesJson; - if (model && model->hasStateValuations()) { - stateChoicesJson["s"] = model->getStateValuations().template toJson<storm::RationalNumber>(state); - } else { - stateChoicesJson["s"] = state; - } - auto const& choice = schedulerChoices.front()[state]; - storm::json<storm::RationalNumber> choicesJson; - if (choice.isDefined()) { - for (auto const& choiceProbPair : choice.getChoiceAsDistribution()) { - uint64_t globalChoiceIndex = model->getTransitionMatrix().getRowGroupIndices()[state] + choiceProbPair.first; - storm::json<storm::RationalNumber> choiceJson; - if (model && model->hasChoiceOrigins() && model->getChoiceOrigins()->getIdentifier(globalChoiceIndex) != model->getChoiceOrigins()->getIdentifierForChoicesWithNoOrigin()) { - choiceJson["origin"] = model->getChoiceOrigins()->getChoiceAsJson(globalChoiceIndex); - } - if (model && model->hasChoiceLabeling()) { - auto choiceLabels = model->getChoiceLabeling().getLabelsOfChoice(globalChoiceIndex); - choiceJson["labels"] = std::vector<std::string>(choiceLabels.begin(), choiceLabels.end()); + + for (uint_fast64_t memoryState = 0; memoryState < getNumberOfMemoryStates(); ++memoryState) { + // Ignore dontCare states + if (skipDontCareStates && isDontCare(state, memoryState)) { + continue; + } + + storm::json<storm::RationalNumber> stateChoicesJson; + if (model && model->hasStateValuations()) { + stateChoicesJson["s"] = model->getStateValuations().template toJson<storm::RationalNumber>(state); + } else { + stateChoicesJson["s"] = state; + } + + if (!isMemorylessScheduler()) { + stateChoicesJson["m"] = memoryState; + } + + auto const &choice = schedulerChoices[memoryState][state]; + storm::json<storm::RationalNumber> choicesJson; + if (choice.isDefined()) { + for (auto const &choiceProbPair : choice.getChoiceAsDistribution()) { + uint64_t globalChoiceIndex = model->getTransitionMatrix().getRowGroupIndices()[state] + choiceProbPair.first; + storm::json<storm::RationalNumber> choiceJson; + if (model && model->hasChoiceOrigins() && + model->getChoiceOrigins()->getIdentifier(globalChoiceIndex) != + model->getChoiceOrigins()->getIdentifierForChoicesWithNoOrigin()) { + choiceJson["origin"] = model->getChoiceOrigins()->getChoiceAsJson(globalChoiceIndex); + } + if (model && model->hasChoiceLabeling()) { + auto choiceLabels = model->getChoiceLabeling().getLabelsOfChoice(globalChoiceIndex); + choiceJson["labels"] = std::vector<std::string>(choiceLabels.begin(), + choiceLabels.end()); + } + choiceJson["index"] = globalChoiceIndex; + choiceJson["prob"] = storm::utility::convertNumber<storm::RationalNumber>( + choiceProbPair.second); + + // Memory updates + if(!isMemorylessScheduler()) { + choiceJson["memory-updates"] = std::vector<storm::json<storm::RationalNumber>>(); + uint64_t row = model->getTransitionMatrix().getRowGroupIndices()[state] + choiceProbPair.first; + for (auto entryIt = model->getTransitionMatrix().getRow(row).begin(); entryIt < model->getTransitionMatrix().getRow(row).end(); ++entryIt) { + storm::json<storm::RationalNumber> updateJson; + // next model state + if (model && model->hasStateValuations()) { + updateJson["s'"] = model->getStateValuations().template toJson<storm::RationalNumber>(entryIt->getColumn()); + } else { + updateJson["s'"] = entryIt->getColumn(); + } + // next memory state + updateJson["m'"] = this->memoryStructure->getSuccessorMemoryState(memoryState, entryIt - model->getTransitionMatrix().begin()); + choiceJson["memory-updates"].push_back(std::move(updateJson)); + } + } + + choicesJson.push_back(std::move(choiceJson)); } - choiceJson["index"] = globalChoiceIndex; - choiceJson["prob"] = storm::utility::convertNumber<storm::RationalNumber>(choiceProbPair.second); - choicesJson.push_back(std::move(choiceJson)); + } else { + choicesJson = "undefined"; } - } else { - choicesJson = "undefined"; + stateChoicesJson["c"] = std::move(choicesJson); + output.push_back(std::move(stateChoicesJson)); } - stateChoicesJson["c"] = std::move(choicesJson); - output.push_back(std::move(stateChoicesJson)); } out << output.dump(4); } diff --git a/src/storm/storage/Scheduler.h b/src/storm/storage/Scheduler.h index 43c7bb1cb..96819be58 100644 --- a/src/storm/storage/Scheduler.h +++ b/src/storm/storage/Scheduler.h @@ -5,6 +5,7 @@ #include "storm/storage/memorystructure/MemoryStructure.h" #include "storm/storage/SchedulerChoice.h" +#include "storm/storage/BitVector.h" namespace storm { namespace storage { @@ -59,13 +60,37 @@ namespace storm { */ SchedulerChoice<ValueType> const& getChoice(uint_fast64_t modelState, uint_fast64_t memoryState = 0) const; + /*! + * Set the combination of model state and memoryStructure state to dontCare. + * These states are considered unreachable and are ignored when printing the scheduler. + * If not specified otherwise, an arbitrary choice is set if no choice exists. + * + * @param modelState The state of the model. + * @param memoryState The state of the memoryStructure. + * @param memoryState A flag indicating whether to set an arbitrary choice. + */ + void setDontCare(uint_fast64_t modelState, uint_fast64_t memoryState = 0, bool setArbitraryChoice = true); + + /*! + * Unset the combination of model state and memoryStructure state to dontCare. + * + * @param modelState The state of the model. + * @param memoryState The state of the memoryStructure. + */ + void unSetDontCare(uint_fast64_t modelState, uint_fast64_t memoryState = 0); + + /*! + * Is the combination of model state and memoryStructure state to reachable? + */ + bool isDontCare(uint_fast64_t modelState, uint64_t memoryState = 0) const; + /*! * Compute the Action Support: A bit vector that indicates all actions that are selected with positive probability in some memory state */ storm::storage::BitVector computeActionSupport(std::vector<uint64_t> const& nondeterministicChoiceIndicies) const; /*! - * Retrieves whether there is a pair of model and memory state for which the choice is undefined. + * Retrieves whether there is a *reachable* pair of model and memory state for which the choice is undefined. */ bool isPartialScheduler() const; @@ -110,25 +135,26 @@ namespace storm { * @param model If given, provides additional information for printing (e.g., displaying the state valuations instead of state indices) * @param skipUniqueChoices If true, the (unique) choice for deterministic states (i.e., states with only one enabled choice) is not printed explicitly. * Requires a model to be given. + * @param skipDontCareStates If true, the choice for dontCareStates states is not printed explicitly. */ - void printToStream(std::ostream& out, std::shared_ptr<storm::models::sparse::Model<ValueType>> model = nullptr, bool skipUniqueChoices = false) const; - + void printToStream(std::ostream& out, std::shared_ptr<storm::models::sparse::Model<ValueType>> model = nullptr, bool skipUniqueChoices = false, bool skipDontCareStates = false) const; /*! * Prints the scheduler in json format to the given output stream. */ - void printJsonToStream(std::ostream& out, std::shared_ptr<storm::models::sparse::Model<ValueType>> model = nullptr, bool skipUniqueChoices = false) const; - - void setPrintUndefinedChoices(bool value = true); - - protected: + void printJsonToStream(std::ostream& out, std::shared_ptr<storm::models::sparse::Model<ValueType>> model = nullptr, bool skipUniqueChoices = false, bool skipDontCareStates = false) const; + private: boost::optional<storm::storage::MemoryStructure> memoryStructure; std::vector<std::vector<SchedulerChoice<ValueType>>> schedulerChoices; bool printUndefinedChoices = false; + + std::vector<storm::storage::BitVector> reachableStates; + std::vector<storm::storage::BitVector> dontCareStates; uint_fast64_t numOfUndefinedChoices; uint_fast64_t numOfDeterministicChoices; + uint_fast64_t numOfDontCareStates; }; } } diff --git a/src/storm/storage/geometry/ReduceVertexCloud.cpp b/src/storm/storage/geometry/ReduceVertexCloud.cpp index 71e725d78..844f1f12d 100644 --- a/src/storm/storage/geometry/ReduceVertexCloud.cpp +++ b/src/storm/storage/geometry/ReduceVertexCloud.cpp @@ -53,7 +53,7 @@ namespace storm { expressionManager->rational(1)); } else { smtSolver->add(storm::expressions::sum(weightVariableExpressions) <= - expressionManager->rational(1.0 + wiggle)); + expressionManager->rational(1 + wiggle)); smtSolver->add(storm::expressions::sum(weightVariableExpressions) >= expressionManager->rational(1 - wiggle)); } @@ -135,4 +135,4 @@ namespace storm { template class ReduceVertexCloud<storm::RationalNumber>; } } -} \ No newline at end of file +} diff --git a/src/storm/storage/jani/JSONExporter.cpp b/src/storm/storage/jani/JSONExporter.cpp index 2e900bb92..bf5895d5e 100644 --- a/src/storm/storage/jani/JSONExporter.cpp +++ b/src/storm/storage/jani/JSONExporter.cpp @@ -208,6 +208,14 @@ namespace storm { opDecl["right"] = anyToJson(f.getRightSubformula().accept(*this, data)); return opDecl; } + boost::any FormulaToJaniJson::visit(storm::logic::BinaryBooleanPathFormula const& f, boost::any const& data) const{ + ExportJsonType opDecl; + storm::logic::BinaryBooleanPathFormula::OperatorType op = f.getOperator(); + opDecl["op"] = op == storm::logic::BinaryBooleanPathFormula::OperatorType::And ? "∧" : "∨"; + opDecl["left"] = boost::any_cast<ExportJsonType>(f.getLeftSubformula().accept(*this, data)); + opDecl["right"] = boost::any_cast<ExportJsonType>(f.getRightSubformula().accept(*this, data)); + return opDecl; + } boost::any FormulaToJaniJson::visit(storm::logic::BooleanLiteralFormula const& f, boost::any const&) const { ExportJsonType opDecl(f.isTrueFormula() ? true : false); return opDecl; @@ -588,6 +596,15 @@ namespace storm { return opDecl; } + boost::any FormulaToJaniJson::visit(storm::logic::UnaryBooleanPathFormula const& f, boost::any const& data) const { + ExportJsonType opDecl; + storm::logic::UnaryBooleanPathFormula::OperatorType op = f.getOperator(); + assert(op == storm::logic::UnaryBooleanPathFormula::OperatorType::Not); + opDecl["op"] = "¬"; + opDecl["exp"] = boost::any_cast<ExportJsonType>(f.getSubformula().accept(*this, data)); + return opDecl; + } + boost::any FormulaToJaniJson::visit(storm::logic::UntilFormula const& f, boost::any const& data) const { ExportJsonType opDecl; opDecl["op"] = "U"; @@ -596,6 +613,10 @@ namespace storm { return opDecl; } + boost::any FormulaToJaniJson::visit(storm::logic::HOAPathFormula const&, boost::any const&) const { + STORM_LOG_THROW(false, storm::exceptions::NotSupportedException, "Jani currently does not support HOA path formulae"); + } + std::string operatorTypeToJaniString(storm::expressions::OperatorType optype) { using OpType = storm::expressions::OperatorType; @@ -690,7 +711,7 @@ namespace storm { return opDecl; } } - + boost::any ExpressionToJson::visit(storm::expressions::BinaryRelationExpression const& expression, boost::any const& data) { ExportJsonType opDecl; opDecl["op"] = operatorTypeToJaniString(expression.getOperator()); diff --git a/src/storm/storage/jani/JSONExporter.h b/src/storm/storage/jani/JSONExporter.h index cee374f02..a00088cb1 100644 --- a/src/storm/storage/jani/JSONExporter.h +++ b/src/storm/storage/jani/JSONExporter.h @@ -52,6 +52,7 @@ namespace storm { virtual boost::any visit(storm::logic::AtomicExpressionFormula const& f, boost::any const& data) const; virtual boost::any visit(storm::logic::AtomicLabelFormula const& f, boost::any const& data) const; virtual boost::any visit(storm::logic::BinaryBooleanStateFormula const& f, boost::any const& data) const; + virtual boost::any visit(storm::logic::BinaryBooleanPathFormula const& f, boost::any const& data) const; virtual boost::any visit(storm::logic::BooleanLiteralFormula const& f, boost::any const& data) const; virtual boost::any visit(storm::logic::BoundedGloballyFormula const& f, boost::any const& data) const; virtual boost::any visit(storm::logic::BoundedUntilFormula const& f, boost::any const& data) const; @@ -71,7 +72,9 @@ namespace storm { virtual boost::any visit(storm::logic::RewardOperatorFormula const& f, boost::any const& data) const; virtual boost::any visit(storm::logic::TotalRewardFormula const& f, boost::any const& data) const; virtual boost::any visit(storm::logic::UnaryBooleanStateFormula const& f, boost::any const& data) const; + virtual boost::any visit(storm::logic::UnaryBooleanPathFormula const& f, boost::any const& data) const; virtual boost::any visit(storm::logic::UntilFormula const& f, boost::any const& data) const; + virtual boost::any visit(storm::logic::HOAPathFormula const& f, boost::any const& data) const; private: FormulaToJaniJson(storm::jani::Model const& model) : model(model), stateExitRewards(false) { } diff --git a/src/storm/storage/memorystructure/MemoryStructure.cpp b/src/storm/storage/memorystructure/MemoryStructure.cpp index 83bc7ad81..1bcded410 100644 --- a/src/storm/storage/memorystructure/MemoryStructure.cpp +++ b/src/storm/storage/memorystructure/MemoryStructure.cpp @@ -11,14 +11,18 @@ namespace storm { namespace storage { - MemoryStructure::MemoryStructure(TransitionMatrix const& transitionMatrix, storm::models::sparse::StateLabeling const& memoryStateLabeling, std::vector<uint_fast64_t> const& initialMemoryStates) : transitions(transitionMatrix), stateLabeling(memoryStateLabeling), initialMemoryStates(initialMemoryStates) { + MemoryStructure::MemoryStructure(TransitionMatrix const& transitionMatrix, storm::models::sparse::StateLabeling const& memoryStateLabeling, std::vector<uint_fast64_t> const& initialMemoryStates, bool onlyInitialStatesRelevant) : transitions(transitionMatrix), stateLabeling(memoryStateLabeling), initialMemoryStates(initialMemoryStates), onlyInitialStatesRelevant(onlyInitialStatesRelevant) { // intentionally left empty } - - MemoryStructure::MemoryStructure(TransitionMatrix&& transitionMatrix, storm::models::sparse::StateLabeling&& memoryStateLabeling, std::vector<uint_fast64_t>&& initialMemoryStates) : transitions(std::move(transitionMatrix)), stateLabeling(std::move(memoryStateLabeling)), initialMemoryStates(std::move(initialMemoryStates)) { + + MemoryStructure::MemoryStructure(TransitionMatrix&& transitionMatrix, storm::models::sparse::StateLabeling&& memoryStateLabeling, std::vector<uint_fast64_t>&& initialMemoryStates, bool onlyInitialStatesRelevant) : transitions(std::move(transitionMatrix)), stateLabeling(std::move(memoryStateLabeling)), initialMemoryStates(std::move(initialMemoryStates)), onlyInitialStatesRelevant(onlyInitialStatesRelevant) { // intentionally left empty } - + + bool MemoryStructure::isOnlyInitialStatesRelevantSet() const { + return onlyInitialStatesRelevant; + } + MemoryStructure::TransitionMatrix const& MemoryStructure::getTransitionMatrix() const { return transitions; } diff --git a/src/storm/storage/memorystructure/MemoryStructure.h b/src/storm/storage/memorystructure/MemoryStructure.h index c1a255f29..e831b58cf 100644 --- a/src/storm/storage/memorystructure/MemoryStructure.h +++ b/src/storm/storage/memorystructure/MemoryStructure.h @@ -33,11 +33,13 @@ namespace storm { * * @param transitionMatrix The transition matrix * @param memoryStateLabeling A labeling of the memory states to specify, e.g., accepting states - * @param initialMemoryStates assigns an initial memory state to each initial state of the model. + * @param initialMemoryStates assigns an initial memory state to each (initial?) state of the model. + * @param onlyInitialStatesRelevant if true, initial memory states are only provided for each initial model state. Otherwise, an initial memory state is provided for *every* model state. */ - MemoryStructure(TransitionMatrix const& transitionMatrix, storm::models::sparse::StateLabeling const& memoryStateLabeling, std::vector<uint_fast64_t> const& initialMemoryStates); - MemoryStructure(TransitionMatrix&& transitionMatrix, storm::models::sparse::StateLabeling&& memoryStateLabeling, std::vector<uint_fast64_t>&& initialMemoryStates); - + MemoryStructure(TransitionMatrix const& transitionMatrix, storm::models::sparse::StateLabeling const& memoryStateLabeling, std::vector<uint_fast64_t> const& initialMemoryStates, bool onlyInitialStatesRelevant = true); + MemoryStructure(TransitionMatrix&& transitionMatrix, storm::models::sparse::StateLabeling&& memoryStateLabeling, std::vector<uint_fast64_t>&& initialMemoryStates, bool onlyInitialStatesRelevant = true); + + bool isOnlyInitialStatesRelevantSet () const; TransitionMatrix const& getTransitionMatrix() const; storm::models::sparse::StateLabeling const& getStateLabeling() const; std::vector<uint_fast64_t> const& getInitialMemoryStates() const; @@ -65,6 +67,7 @@ namespace storm { TransitionMatrix transitions; storm::models::sparse::StateLabeling stateLabeling; std::vector<uint_fast64_t> initialMemoryStates; + bool onlyInitialStatesRelevant; // Whether initial memory states are only defined for initial model states or for all model states }; } diff --git a/src/storm/storage/memorystructure/MemoryStructureBuilder.cpp b/src/storm/storage/memorystructure/MemoryStructureBuilder.cpp index f3a3818cc..54accf38a 100644 --- a/src/storm/storage/memorystructure/MemoryStructureBuilder.cpp +++ b/src/storm/storage/memorystructure/MemoryStructureBuilder.cpp @@ -10,28 +10,42 @@ namespace storm { namespace storage { template <typename ValueType, typename RewardModelType> - MemoryStructureBuilder<ValueType, RewardModelType>::MemoryStructureBuilder(uint_fast64_t numberOfMemoryStates, storm::models::sparse::Model<ValueType, RewardModelType> const& model) : model(model), transitions(numberOfMemoryStates, std::vector<boost::optional<storm::storage::BitVector>>(numberOfMemoryStates)), stateLabeling(numberOfMemoryStates), initialMemoryStates(model.getInitialStates().getNumberOfSetBits(), 0) { + MemoryStructureBuilder<ValueType, RewardModelType>::MemoryStructureBuilder(uint_fast64_t numberOfMemoryStates, storm::models::sparse::Model<ValueType, RewardModelType> const& model, bool onlyInitialStatesRelevant) : model(model), transitions(numberOfMemoryStates, std::vector<boost::optional<storm::storage::BitVector>>(numberOfMemoryStates)), stateLabeling(numberOfMemoryStates), initialMemoryStates(onlyInitialStatesRelevant ? model.getInitialStates().getNumberOfSetBits() : model.getNumberOfStates(), 0), onlyInitialStatesRelevant(onlyInitialStatesRelevant) { // Intentionally left empty } template <typename ValueType, typename RewardModelType> - MemoryStructureBuilder<ValueType, RewardModelType>::MemoryStructureBuilder(MemoryStructure const& memoryStructure, storm::models::sparse::Model<ValueType, RewardModelType> const& model) : model(model), transitions(memoryStructure.getTransitionMatrix()), stateLabeling(memoryStructure.getStateLabeling()), initialMemoryStates(memoryStructure.getInitialMemoryStates()) { + MemoryStructureBuilder<ValueType, RewardModelType>::MemoryStructureBuilder(MemoryStructure const& memoryStructure, storm::models::sparse::Model<ValueType, RewardModelType> const& model) : model(model), transitions(memoryStructure.getTransitionMatrix()), stateLabeling(memoryStructure.getStateLabeling()), initialMemoryStates(memoryStructure.getInitialMemoryStates()), onlyInitialStatesRelevant(memoryStructure.isOnlyInitialStatesRelevantSet()) { // Intentionally left empty } + template <typename ValueType, typename RewardModelType> void MemoryStructureBuilder<ValueType, RewardModelType>::setInitialMemoryState(uint_fast64_t initialModelState, uint_fast64_t initialMemoryState) { - STORM_LOG_THROW(model.getInitialStates().get(initialModelState), storm::exceptions::InvalidOperationException, "Invalid index of initial model state: " << initialMemoryState << ". This is not an initial state of the model."); + STORM_LOG_THROW(!onlyInitialStatesRelevant || model.getInitialStates().get(initialModelState), storm::exceptions::InvalidOperationException, "Invalid index of initial model state: " << initialMemoryState << ". This is not an initial state of the model."); STORM_LOG_THROW(initialMemoryState < transitions.size(), storm::exceptions::InvalidOperationException, "Invalid index of initial memory state: " << initialMemoryState << ". There are only " << transitions.size() << " states in this memory structure."); auto initMemStateIt = initialMemoryStates.begin(); - for (auto initState : model.getInitialStates()) { - if (initState == initialModelState) { - *initMemStateIt = initialMemoryState; - break; + + if (onlyInitialStatesRelevant) { + for (auto initState : model.getInitialStates()) { + if (initState == initialModelState) { + *initMemStateIt = initialMemoryState; + break; + } + ++initMemStateIt; + } + } else { + // Consider non-initial model states + for (uint_fast64_t state = 0; state < model.getNumberOfStates(); ++state) { + if (state == initialModelState) { + *initMemStateIt = initialMemoryState; + break; + } + ++initMemStateIt; } - ++initMemStateIt; } + assert(initMemStateIt != initialMemoryStates.end()); } @@ -85,7 +99,7 @@ namespace storm { template <typename ValueType, typename RewardModelType> MemoryStructure MemoryStructureBuilder<ValueType, RewardModelType>::build() { - return MemoryStructure(std::move(transitions), std::move(stateLabeling), std::move(initialMemoryStates)); + return MemoryStructure(std::move(transitions), std::move(stateLabeling), std::move(initialMemoryStates), onlyInitialStatesRelevant); } template <typename ValueType, typename RewardModelType> diff --git a/src/storm/storage/memorystructure/MemoryStructureBuilder.h b/src/storm/storage/memorystructure/MemoryStructureBuilder.h index bb310ccf3..b038fb98f 100644 --- a/src/storm/storage/memorystructure/MemoryStructureBuilder.h +++ b/src/storm/storage/memorystructure/MemoryStructureBuilder.h @@ -14,23 +14,24 @@ namespace storm { class MemoryStructureBuilder { public: - /*! - * Initializes a new builder for a memory structure + /*! + * Initializes a new builder with the data from the provided memory structure * @param numberOfMemoryStates The number of states the resulting memory structure should have + * @param onlyInitialStatesRelevant If true, assume that we only consider the fragment reachable from initial model states. If false, initial memory states need to be provided for *all* model states. */ - MemoryStructureBuilder(uint_fast64_t numberOfMemoryStates, storm::models::sparse::Model<ValueType, RewardModelType> const& model); - + MemoryStructureBuilder(uint_fast64_t numberOfMemoryStates, storm::models::sparse::Model<ValueType, RewardModelType> const& model, bool onlyInitialStatesRelevant = true); + /*! * Initializes a new builder with the data from the provided memory structure */ MemoryStructureBuilder(MemoryStructure const& memoryStructure, storm::models::sparse::Model<ValueType, RewardModelType> const& model); /*! - * Specifies for the given initial state of the model the corresponding initial memory state. + * Specifies for the given state of the model the corresponding initial memory state. * * @note The default initial memory state is 0. * - * @param initialModelState the index of an initial state of the model. + * @param initialModelState the index of a state of the model. Has to be an initial state iff `onlyInitialStatesRelevant` is true. * @param initialMemoryState the initial memory state associated to the corresponding model state. */ void setInitialMemoryState(uint_fast64_t initialModelState, uint_fast64_t initialMemoryState); @@ -73,6 +74,7 @@ namespace storm { MemoryStructure::TransitionMatrix transitions; storm::models::sparse::StateLabeling stateLabeling; std::vector<uint_fast64_t> initialMemoryStates; + bool onlyInitialStatesRelevant; }; } diff --git a/src/storm/storage/memorystructure/SparseModelMemoryProduct.cpp b/src/storm/storage/memorystructure/SparseModelMemoryProduct.cpp index 029387288..76fa593ba 100644 --- a/src/storm/storage/memorystructure/SparseModelMemoryProduct.cpp +++ b/src/storm/storage/memorystructure/SparseModelMemoryProduct.cpp @@ -38,9 +38,17 @@ namespace storm { // Get the initial states and reachable states. A stateIndex s corresponds to the model state (s / memoryStateCount) and memory state (s % memoryStateCount) storm::storage::BitVector initialStates(modelStateCount * memoryStateCount, false); auto memoryInitIt = memory.getInitialMemoryStates().begin(); - for (auto modelInit : model.getInitialStates()) { - initialStates.set(modelInit * memoryStateCount + *memoryInitIt, true); - ++memoryInitIt; + if (memory.isOnlyInitialStatesRelevantSet()) { + for (auto modelInit : model.getInitialStates()) { + initialStates.set(modelInit * memoryStateCount + *memoryInitIt, true); + ++memoryInitIt; + } + } else { + // Build Product from all model states + for (uint_fast64_t modelState = 0; modelState < model.getNumberOfStates(); ++modelState) { + initialStates.set(modelState * memoryStateCount + *memoryInitIt, true); + ++memoryInitIt; + } } STORM_LOG_ASSERT(memoryInitIt == memory.getInitialMemoryStates().end(), "Unexpected number of initial states."); @@ -508,15 +516,7 @@ namespace storm { components.exitRates = std::move(resultExitRates); } - storm::models::ModelType resultType = model.getType(); - if (scheduler && !scheduler->isPartialScheduler()) { - if (model.isOfType(storm::models::ModelType::Mdp)) { - resultType = storm::models::ModelType::Dtmc; - } - // Note that converting deterministic MAs to CTMCs via state elimination does not preserve all properties (e.g. step bounded) - } - - return storm::utility::builder::buildModelFromComponents(resultType, std::move(components)); + return storm::utility::builder::buildModelFromComponents(model.getType(), std::move(components)); } template <typename ValueType, typename RewardModelType> diff --git a/src/storm/transformer/DAProduct.h b/src/storm/transformer/DAProduct.h new file mode 100644 index 000000000..ac3e46926 --- /dev/null +++ b/src/storm/transformer/DAProduct.h @@ -0,0 +1,27 @@ +#pragma + +#include "storm/automata/AcceptanceCondition.h" +#include "storm/transformer/Product.h" +#include <memory> + +namespace storm { + namespace transformer { + + template <typename Model> + class DAProduct : public Product<Model> { + public: + typedef std::shared_ptr<DAProduct<Model>> ptr; + + DAProduct(Product<Model>&& product, storm::automata::AcceptanceCondition::ptr acceptance) + : Product<Model>(std::move(product)), acceptance(acceptance) { + // Intentionally left blank + } + + storm::automata::AcceptanceCondition::ptr getAcceptance() { + return acceptance; + } + private: + storm::automata::AcceptanceCondition::ptr acceptance; + }; + } +} diff --git a/src/storm/transformer/DAProductBuilder.h b/src/storm/transformer/DAProductBuilder.h new file mode 100644 index 000000000..c9e72331a --- /dev/null +++ b/src/storm/transformer/DAProductBuilder.h @@ -0,0 +1,59 @@ +#pragma once + +#include "storm/storage/BitVector.h" +#include "storm/automata/DeterministicAutomaton.h" +#include "storm/transformer/DAProduct.h" +#include "storm/transformer/Product.h" +#include "storm/transformer/ProductBuilder.h" + +#include <vector> + +namespace storm { + namespace transformer { + class DAProductBuilder { + public: + DAProductBuilder(const storm::automata::DeterministicAutomaton& da, const std::vector<storm::storage::BitVector>& statesForAP) + : da(da), statesForAP(statesForAP) { + } + + template <typename Model> + typename DAProduct<Model>::ptr build(const Model& originalModel, const storm::storage::BitVector& statesOfInterest) const { + return build<Model>(originalModel.getTransitionMatrix(), statesOfInterest); + } + + template <typename Model> + typename DAProduct<Model>::ptr build(const storm::storage::SparseMatrix<typename Model::ValueType>& originalMatrix, const storm::storage::BitVector& statesOfInterest) const { + typename Product<Model>::ptr product = ProductBuilder<Model>::buildProduct(originalMatrix, *this, statesOfInterest); + storm::automata::AcceptanceCondition::ptr prodAcceptance + = da.getAcceptance()->lift(product->getProductModel().getNumberOfStates(), + [&product](std::size_t prodState) {return product->getAutomatonState(prodState);}); + + return typename DAProduct<Model>::ptr(new DAProduct<Model>(std::move(*product), prodAcceptance)); + } + + storm::storage::sparse::state_type getInitialState(storm::storage::sparse::state_type modelState) const { + return da.getSuccessor(da.getInitialState(), getLabelForState(modelState)); + } + + storm::storage::sparse::state_type getSuccessor(storm::storage::sparse::state_type automatonFrom, + storm::storage::sparse::state_type modelTo) const { + return da.getSuccessor(automatonFrom, getLabelForState(modelTo)); + } + + + private: + const storm::automata::DeterministicAutomaton& da; + const std::vector<storm::storage::BitVector>& statesForAP; + + storm::automata::APSet::alphabet_element getLabelForState(storm::storage::sparse::state_type s) const { + storm::automata::APSet::alphabet_element label = da.getAPSet().elementAllFalse(); + for (unsigned int ap = 0; ap < da.getAPSet().size(); ap++) { + if (statesForAP.at(ap).get(s)) { + label = da.getAPSet().elementAddAP(label, ap); + } + } + return label; + } + }; + } +} diff --git a/src/storm/transformer/Product.h b/src/storm/transformer/Product.h new file mode 100644 index 000000000..7d69bce57 --- /dev/null +++ b/src/storm/transformer/Product.h @@ -0,0 +1,102 @@ +#pragma once + +#include <memory> + +namespace storm { + namespace transformer { + template <typename Model> + class Product { + public: + typedef std::shared_ptr<Product<Model>> ptr; + + typedef storm::storage::sparse::state_type state_type; + typedef std::pair<state_type, state_type> product_state_type; + typedef std::map<product_state_type, state_type> product_state_to_product_index_map; + typedef std::vector<product_state_type> product_index_to_product_state_vector; + + Product(Model&& productModel, + std::string&& productStateOfInterestLabel, + product_state_to_product_index_map&& productStateToProductIndex, + product_index_to_product_state_vector&& productIndexToProductState) + : productModel(productModel), + productStateOfInterestLabel(productStateOfInterestLabel), + productStateToProductIndex(productStateToProductIndex), + productIndexToProductState(productIndexToProductState) {} + + Product(Product<Model>&& product) = default; + Product& operator=(Product<Model>&& product) = default; + + Model& getProductModel() {return productModel;} + + state_type getModelState(state_type productStateIndex) const { + return productIndexToProductState.at(productStateIndex).first; + } + + state_type getAutomatonState(state_type productStateIndex) const { + return productIndexToProductState.at(productStateIndex).second; + } + + state_type getProductStateIndex(state_type modelState, state_type automatonState) const { + return productStateToProductIndex.at(product_state_type(modelState, automatonState)); + } + + bool isValidProductState(state_type modelState, state_type automatonState) const { + return (productStateToProductIndex.count(product_state_type(modelState, automatonState)) >0); + } + + storm::storage::BitVector liftFromAutomaton(const storm::storage::BitVector& vector) const { + state_type n = productModel.getNumberOfStates(); + storm::storage::BitVector lifted(n, false); + for (state_type s = 0; s < n; s++) { + if (vector.get(getAutomatonState(s))) { + lifted.set(s); + } + } + return lifted; + } + + storm::storage::BitVector liftFromModel(const storm::storage::BitVector& vector) const { + state_type n = productModel.getNumberOfStates(); + storm::storage::BitVector lifted(n, false); + for (state_type s = 0; s < n; s++) { + if (vector.get(getModelState(s))) { + lifted.set(s); + } + } + return lifted; + } + + template <typename ValueType> + std::vector<ValueType> projectToOriginalModel(const Model& originalModel, const std::vector<ValueType>& prodValues) { + return projectToOriginalModel(originalModel.getNumberOfStates(), prodValues); + } + + template <typename ValueType> + std::vector<ValueType> projectToOriginalModel(std::size_t numberOfStates, const std::vector<ValueType>& prodValues) { + std::vector<ValueType> origValues(numberOfStates); + for (state_type productState : productModel.getStateLabeling().getStates(productStateOfInterestLabel)) { + state_type originalState = getModelState(productState); + origValues.at(originalState) = prodValues.at(productState); + } + return origValues; + } + + const storm::storage::BitVector& getStatesOfInterest() const { + return productModel.getStates(productStateOfInterestLabel); + } + + void printMapping(std::ostream& out) const { + out << "Mapping index -> product state\n"; + for (std::size_t i = 0; i < productIndexToProductState.size(); i++) { + out << " " << i << ": " << productIndexToProductState.at(i).first << "," << productIndexToProductState.at(i).second << "\n"; + } + } + + private: + Model productModel; + std::string productStateOfInterestLabel; + product_state_to_product_index_map productStateToProductIndex; + product_index_to_product_state_vector productIndexToProductState; + }; + } +} diff --git a/src/storm/transformer/ProductBuilder.h b/src/storm/transformer/ProductBuilder.h new file mode 100644 index 000000000..4be4bf045 --- /dev/null +++ b/src/storm/transformer/ProductBuilder.h @@ -0,0 +1,130 @@ +#pragma once + +#include "storm/models/sparse/StateLabeling.h" +#include "storm/storage/SparseMatrix.h" +#include "storm/storage/BitVector.h" + +#include <vector> +#include <deque> +#include <map> + +namespace storm { + namespace transformer { + + template <typename Model> + class ProductBuilder { + public: + typedef storm::storage::SparseMatrix<typename Model::ValueType> matrix_type; + + template <typename ProductOperator> + static typename Product<Model>::ptr buildProduct(const matrix_type& originalMatrix , ProductOperator& prodOp, const storm::storage::BitVector& statesOfInterest) { + bool deterministic = originalMatrix.hasTrivialRowGrouping(); + + typedef storm::storage::sparse::state_type state_type; + typedef std::pair<state_type, state_type> product_state_type; + + state_type nextState = 0; + std::map<product_state_type, state_type> productStateToProductIndex; + std::vector<product_state_type> productIndexToProductState; + std::vector<state_type> prodInitial; + + // use deque for todo so that the states are handled in the order + // of their index in the product model, which is required due to the + // use of the SparseMatrixBuilder that can only handle linear addNextValue + // calls + std::deque<state_type> todo; + for (state_type s_0 : statesOfInterest) { + state_type q_0 = prodOp.getInitialState(s_0); + + // std::cout << "Initial: " << s_0 << ", " << q_0 << " = " << nextState << "\n"; + + product_state_type s_q(s_0, q_0); + state_type index = nextState++; + productStateToProductIndex[s_q] = index; + productIndexToProductState.push_back(s_q); + prodInitial.push_back(index); + todo.push_back(index); + } + + storm::storage::SparseMatrixBuilder<typename Model::ValueType> builder(0, 0, 0, false, deterministic ? false : true, 0); + std::size_t curRow = 0; + while (!todo.empty()) { + state_type prodIndexFrom = todo.front(); + todo.pop_front(); + + product_state_type from = productIndexToProductState.at(prodIndexFrom); + // std::cout << "Handle " << from.first << "," << from.second << " (prodIndexFrom = " << prodIndexFrom << "):\n"; + if (deterministic) { + typename matrix_type::const_rows row = originalMatrix.getRow(from.first); + for (auto const& entry : row) { + state_type t = entry.getColumn(); + state_type p = prodOp.getSuccessor(from.second, t); + // std::cout << " p = " << p << "\n"; + product_state_type t_p(t, p); + state_type prodIndexTo; + auto it = productStateToProductIndex.find(t_p); + if (it == productStateToProductIndex.end()) { + prodIndexTo = nextState++; + todo.push_back(prodIndexTo); + productIndexToProductState.push_back(t_p); + productStateToProductIndex[t_p] = prodIndexTo; + // std::cout << " Adding " << t_p.first << "," << t_p.second << " as " << prodIndexTo << "\n"; + } else { + prodIndexTo = it->second; + } + // std::cout << " " << t_p.first << "," << t_p.second << ": to = " << prodIndexTo << "\n"; + + // std::cout << " addNextValue(" << prodIndexFrom << "," << prodIndexTo << "," << entry.getValue() << ")\n"; + builder.addNextValue(prodIndexFrom, prodIndexTo, entry.getValue()); + } + } else { + std::size_t numRows = originalMatrix.getRowGroupSize(from.first); + builder.newRowGroup(curRow); + for (std::size_t i = 0; i < numRows; i++) { + auto const& row = originalMatrix.getRow(from.first, i); + for (auto const& entry : row) { + state_type t = entry.getColumn(); + state_type p = prodOp.getSuccessor(from.second, t); + // std::cout << " p = " << p << "\n"; + product_state_type t_p(t, p); + state_type prodIndexTo; + auto it = productStateToProductIndex.find(t_p); + if (it == productStateToProductIndex.end()) { + prodIndexTo = nextState++; + todo.push_back(prodIndexTo); + productIndexToProductState.push_back(t_p); + productStateToProductIndex[t_p] = prodIndexTo; + // std::cout << " Adding " << t_p.first << "," << t_p.second << " as " << prodIndexTo << "\n"; + } else { + prodIndexTo = it->second; + } + // std::cout << " " << t_p.first << "," << t_p.second << ": to = " << prodIndexTo << "\n"; + + // std::cout << " addNextValue(" << prodIndexFrom << "," << prodIndexTo << "," << entry.getValue() << ")\n"; + builder.addNextValue(curRow, prodIndexTo, entry.getValue()); + } + curRow++; + } + } + } + + state_type numberOfProductStates = nextState; + + Model product(builder.build(), storm::models::sparse::StateLabeling(numberOfProductStates)); + storm::storage::BitVector productStatesOfInterest(product.getNumberOfStates()); + for (auto& s : prodInitial) { + productStatesOfInterest.set(s); + } + std::string prodSoiLabel = product.getStateLabeling().addUniqueLabel("soi", productStatesOfInterest); + + // const storm::models::sparse::StateLabeling& orignalLabels = dtmc->getStateLabeling(); + // for (originalLabels.) + + return typename Product<Model>::ptr(new Product<Model>(std::move(product), + std::move(prodSoiLabel), + std::move(productStateToProductIndex), + std::move(productIndexToProductState))); + } + }; + } +} diff --git a/src/storm/utility/graph.cpp b/src/storm/utility/graph.cpp index 5df06c585..76203dbe9 100644 --- a/src/storm/utility/graph.cpp +++ b/src/storm/utility/graph.cpp @@ -1764,7 +1764,7 @@ namespace storm { template void computeSchedulerProb1E(storm::storage::BitVector const& prob1EStates, storm::storage::SparseMatrix<double> const& transitionMatrix, storm::storage::SparseMatrix<double> const& backwardTransitions, storm::storage::BitVector const& phiStates, storm::storage::BitVector const& psiStates, storm::storage::Scheduler<double>& scheduler, boost::optional<storm::storage::BitVector> const& rowFilter = boost::none); - + template storm::storage::BitVector performProbGreater0E(storm::storage::SparseMatrix<double> const& backwardTransitions, storm::storage::BitVector const& phiStates, storm::storage::BitVector const& psiStates, bool useStepBound = false, uint_fast64_t maximalSteps = 0) ; template storm::storage::BitVector performProb0A(storm::storage::SparseMatrix<double> const& backwardTransitions, storm::storage::BitVector const& phiStates, storm::storage::BitVector const& psiStates); @@ -1892,9 +1892,9 @@ namespace storm { template std::pair<storm::storage::BitVector, storm::storage::BitVector> performProb01(storm::storage::SparseMatrix<storm::RationalFunction> const& backwardTransitions, storm::storage::BitVector const& phiStates, storm::storage::BitVector const& psiStates); - - - + + template void computeSchedulerProb1E(storm::storage::BitVector const& prob1EStates, storm::storage::SparseMatrix<storm::RationalFunction> const& transitionMatrix, storm::storage::SparseMatrix<storm::RationalFunction> const& backwardTransitions, storm::storage::BitVector const& phiStates, storm::storage::BitVector const& psiStates, storm::storage::Scheduler<storm::RationalFunction>& scheduler, boost::optional<storm::storage::BitVector> const& rowFilter = boost::none); + template storm::storage::BitVector performProbGreater0E(storm::storage::SparseMatrix<storm::RationalFunction> const& backwardTransitions, storm::storage::BitVector const& phiStates, storm::storage::BitVector const& psiStates, bool useStepBound = false, uint_fast64_t maximalSteps = 0) ; template storm::storage::BitVector performProb0A(storm::storage::SparseMatrix<storm::RationalFunction> const& backwardTransitions, storm::storage::BitVector const& phiStates, storm::storage::BitVector const& psiStates); diff --git a/src/test/storm/CMakeLists.txt b/src/test/storm/CMakeLists.txt index d99806231..4fc60ab16 100755 --- a/src/test/storm/CMakeLists.txt +++ b/src/test/storm/CMakeLists.txt @@ -10,7 +10,7 @@ register_source_groups_from_filestructure("${ALL_FILES}" test) include_directories(${GTEST_INCLUDE_DIR}) # Set split and non-split test directories -set(NON_SPLIT_TESTS abstraction adapter builder logic model parser permissiveschedulers simulator solver storage transformer utility) +set(NON_SPLIT_TESTS abstraction adapter automata builder logic model parser permissiveschedulers simulator solver storage transformer utility) set(MODELCHECKER_TEST_SPLITS abstraction csl exploration multiobjective reachability) set(MODELCHECKER_PRCTL_TEST_SPLITS dtmc mdp) diff --git a/src/test/storm/automata/HOAParsingTest.cpp b/src/test/storm/automata/HOAParsingTest.cpp new file mode 100644 index 000000000..1e733ee74 --- /dev/null +++ b/src/test/storm/automata/HOAParsingTest.cpp @@ -0,0 +1,31 @@ +#include "gtest/gtest.h" +#include "storm/automata/DeterministicAutomaton.h" + +#include <string> +#include <sstream> + +TEST(DeterministicAutomaton, ParseAutomaton) { + std::string aUb = + "HOA: v1\n" + "States: 3\n" + "Start: 0\n" + "acc-name: Rabin 1\n" + "Acceptance: 2 (Fin(0) & Inf(1))\n" + "AP: 2 \"a\" \"b\"" + "--BODY--\n" + "State: 0 \"a U b\" { 0 }\n" + " 2 /* !a & !b */\n" + " 0 /* a & !b */\n" + " 1 /* !a & b */\n" + " 1 /* a & b */\n" + "State: 1 { 1 }\n" + " 1 1 1 1 /* four transitions on one line */\n" + "State: 2 \"sink state\" { 0 }\n" + " 2 2 2 2\n" + "--END--\n"; + + std::istringstream in = std::istringstream(aUb); + storm::automata::DeterministicAutomaton::ptr da; + ASSERT_NO_THROW(da = storm::automata::DeterministicAutomaton::parse(in)); + // da->printHOA(std::cout); +} diff --git a/src/test/storm/logic/FragmentCheckerTest.cpp b/src/test/storm/logic/FragmentCheckerTest.cpp index 179e8d099..c0f10a5ed 100644 --- a/src/test/storm/logic/FragmentCheckerTest.cpp +++ b/src/test/storm/logic/FragmentCheckerTest.cpp @@ -150,13 +150,10 @@ TEST(FragmentCheckerTest, MultiObjective) { ASSERT_NO_THROW(formula = formulaParser.parseSingleFormulaFromString("P=? [F \"label\"]")); EXPECT_FALSE(checker.conformsToSpecification(*formula, multiobjective)); - ASSERT_NO_THROW(formula = formulaParser.parseSingleFormulaFromString("multi(R<0.3 [ C ], P<0.6 [F \"label\"] & \"label\" & R<=4[F \"label\"])")); + ASSERT_NO_THROW(formula = formulaParser.parseSingleFormulaFromString("multi(R<0.3 [ C ], P<0.6 [(F \"label1\") & G \"label2\"])")); EXPECT_FALSE(checker.conformsToSpecification(*formula, multiobjective)); - ASSERT_NO_THROW(formula = formulaParser.parseSingleFormulaFromString("Pmax=? [ F multi(R<0.3 [ C ], P<0.6 [F \"label\"] & \"label\" & R<=4[F \"label\"])]")); - EXPECT_FALSE(checker.conformsToSpecification(*formula, multiobjective)); - - ASSERT_NO_THROW(formula = formulaParser.parseSingleFormulaFromString("multi(R<0.3 [ C ], P<0.6 [F \"label\"], \"label\", R<=4[F \"label\"])")); + ASSERT_NO_THROW(formula = formulaParser.parseSingleFormulaFromString("Pmax=? [ F multi(R<0.3 [ C ], P<0.6 [F \"label\" & \"label\" & R<=4[F \"label\"]])]")); EXPECT_FALSE(checker.conformsToSpecification(*formula, multiobjective)); ASSERT_NO_THROW(formula = formulaParser.parseSingleFormulaFromString("multi(R<0.3 [ C ], P<0.6 [F \"label\"], R<=4[F \"label\"])")); @@ -165,9 +162,6 @@ TEST(FragmentCheckerTest, MultiObjective) { ASSERT_NO_THROW(formula = formulaParser.parseSingleFormulaFromString("multi(R<0.3 [ C<=3 ], P<0.6 [F \"label\"], R<=4[F \"label\"])")); EXPECT_FALSE(checker.conformsToSpecification(*formula, multiobjective)); - ASSERT_NO_THROW(formula = formulaParser.parseSingleFormulaFromString("multi(R<0.3 [ C ], multi(P<0.6 [F \"label\"], R<=4[F \"label\"]))")); - EXPECT_FALSE(checker.conformsToSpecification(*formula, multiobjective)); - ASSERT_NO_THROW(formula = formulaParser.parseSingleFormulaFromString("multi(R<0.3 [ C ], P<0.6 [F \"label\" & \"otherlabel\"], P<=4[\"label\" U<=42 \"otherlabel\"])")); EXPECT_TRUE(checker.conformsToSpecification(*formula, multiobjective)); diff --git a/src/test/storm/modelchecker/csl/CtmcCslModelCheckerTest.cpp b/src/test/storm/modelchecker/csl/CtmcCslModelCheckerTest.cpp index 83414e72f..e13d0ebb1 100755 --- a/src/test/storm/modelchecker/csl/CtmcCslModelCheckerTest.cpp +++ b/src/test/storm/modelchecker/csl/CtmcCslModelCheckerTest.cpp @@ -446,4 +446,111 @@ namespace { EXPECT_NEAR(0.404043, result[0], 1e-6); EXPECT_NEAR(0.595957, result[1], 1e-6); } + + + TYPED_TEST(CtmcCslModelCheckerTest, LtlProbabilitiesEmbedded) { +#ifdef STORM_HAVE_LTL_MODELCHECKING_SUPPORT + std::string formulasString = "P=? [ X F (!\"down\" U \"fail_sensors\") ]"; + formulasString += "; P=? [ (! \"down\" U ( F \"fail_actuators\" U \"fail_io\")) ]"; + formulasString += "; P=? [ F \"down\" & X G \"fail_sensors\" ]"; // F ("down" & (X (G "fail_sensors")) ) + formulasString += "; P<1 [ F \"down\" & X G \"fail_sensors\" ]"; // F ("down" & (X (G "fail_sensors")) ) + formulasString += "; P>0.9 [ F \"down\" & X G \"fail_sensors\" ]"; // F ("down" & (X (G "fail_sensors")) ) + formulasString += "; P=? [ ( X X X X X X !\"down\") ]"; + + auto modelFormulas = this->buildModelFormulas(STORM_TEST_RESOURCES_DIR "/ctmc/embedded2.sm", formulasString); + auto model = std::move(modelFormulas.first); + auto tasks = this->getTasks(modelFormulas.second); + EXPECT_EQ(3478ul, model->getNumberOfStates()); + EXPECT_EQ(14639ul, model->getNumberOfTransitions()); + ASSERT_EQ(model->getType(), storm::models::ModelType::Ctmc); + + auto checker = this->createModelChecker(model); + std::unique_ptr<storm::modelchecker::CheckResult> result; + if (TypeParam::engine == CtmcEngine::PrismSparse || TypeParam::engine == CtmcEngine::JaniSparse || TypeParam::engine == CtmcEngine::JitSparse) { + result = checker->check(this->env(), tasks[0]); + + EXPECT_NEAR(this->parseNumber("6201111489217/6635130141055"),this->getQuantitativeResultAtInitialState(model, result), this->precision()); + + result = checker->check(this->env(), tasks[1]); + EXPECT_NEAR(this->parseNumber("182020967567825809324525759316263872210321582568114089975442470616306546970576799368889148054286400140039235238542379833694042687710639406937776190886135408090165698233430649593680647981952463347746024873495777857814386773710331804169990674529100754583695367774161875507044994661278270139591275881461260070117701448841596602041739425021618556458197240253807881255308059191194657575523127649292873946401600705744976789328068766287472574570803652848157332500632820598013756095085890607757713651215707639162546865863133892334758775858116620357147078085971884542677483086820336410289852315689173054718889915988181632722920483222289764504589120520736097022590652379/207288566091424649028720059396722579180935939731896317482437400340085729948319838320744587962528995351116735632610062501984165964160824743820968502984043393631527162621940700372437967239869902745684470791247218025011629936383683180819173695481357872127414459383695458034829702750095798077157671737142972112983783526417917830063407814131534204102733837172200651731758231462705370319722286895248244604663525334713443271108863630608264048954674658939565927125123713502020902415642152134952750797223075762309310186151383660810569853113110736677679624520398243456708277522978182665363672039087497825748539279661186260492946647251487454498033763681938956076478285935"),this->getQuantitativeResultAtInitialState(model, result), this->precision()); + + result = checker->check(this->env(), tasks[2]); + EXPECT_NEAR(this->parseNumber("6201111489217/6635130141055"),this->getQuantitativeResultAtInitialState(model, result), this->precision()); + + result = checker->check(this->env(), tasks[3]); + EXPECT_TRUE(this->getQualitativeResultAtInitialState(model, result)); + + result = checker->check(this->env(), tasks[4]); + EXPECT_TRUE(this->getQualitativeResultAtInitialState(model, result)); + + result = checker->check(this->env(), tasks[5]); + EXPECT_NEAR(this->parseNumber("1202946881424160483813283754811216158529681407876794488562578158132042553611617599206276810240300260522066002609216899556806782592159369214025808794108439870476812421358247413140536419394633974952856222783873484713998841710951907938016323396243234904692402529616778550274612832580948290476037585840335145980480834541017213112991298412961159070334858462971422527038014973671594536802662479216742910965815165548764799425931464388642414276679044295398781842946801210199279858811082435065176154734735687314482662005774077569191240855183945543277103593833128730289929192543135438680962528094118605758445585995100073617/1202972050928710483231931881297292393407746913324566889646682839175998467151639078036566607429531813783366080734929392920005624456488274509559191073647430577878963431232759904608946782891839010213213206349818700590576273106941528872428420715245020013732520855670532992537989370310710476972890517512421272587449374385206819958406508377778081897385805121026698602418585526601660738490866798063415281360790178552717524631472037313126822801359812861351759990595156696407982588022635797417464794849389306521644962338915119549986021747121828809226061546105390273235103310319147341214480736689719855550298904337697187500"),this->getQuantitativeResultAtInitialState(model, result), this->precision()); + + } else { + EXPECT_FALSE(checker->canHandle(tasks[0])); + } +#else + GTEST_SKIP(); +#endif + + } + + TYPED_TEST(CtmcCslModelCheckerTest, LtlProbabilitiesPolling) { +#ifdef STORM_HAVE_LTL_MODELCHECKING_SUPPORT + std::string formulasString = "P=? [ X X !(s=1 & a=1) U (s=2 & a=1) ]"; // (X X a) U b + formulasString += "; P=? [ X (( !(s=1) U (a=1)) U (s=1)) ]"; + + auto modelFormulas = this->buildModelFormulas(STORM_TEST_RESOURCES_DIR "/ctmc/polling2.sm", formulasString); + auto model = std::move(modelFormulas.first); + auto tasks = this->getTasks(modelFormulas.second); + EXPECT_EQ(12ul, model->getNumberOfStates()); + EXPECT_EQ(22ul, model->getNumberOfTransitions()); + ASSERT_EQ(model->getType(), storm::models::ModelType::Ctmc); + + auto checker = this->createModelChecker(model); + std::unique_ptr<storm::modelchecker::CheckResult> result; + // LTL not supported in all engines (Hybrid, PrismDd, JaniDd) + if (TypeParam::engine == CtmcEngine::PrismSparse || TypeParam::engine == CtmcEngine::JaniSparse || TypeParam::engine == CtmcEngine::JitSparse) { + result = checker->check(this->env(), tasks[0]); + EXPECT_NEAR(this->parseNumber("80400/160801"),this->getQuantitativeResultAtInitialState(model, result), this->precision()); + + result = checker->check(this->env(), tasks[1]); + EXPECT_NEAR(this->parseNumber("601/80601"),this->getQuantitativeResultAtInitialState(model, result), this->precision()); + + } else { + EXPECT_FALSE(checker->canHandle(tasks[0])); + } +#else + GTEST_SKIP(); +#endif + + } + + TYPED_TEST(CtmcCslModelCheckerTest, HOAProbabilitiesPolling) { + // "P=? [ F "target" & (X s=1)]" + std::string formulasString = "; P=?[HOA: {\"" STORM_TEST_RESOURCES_DIR "/hoa/automaton_Fandp0Xp1.hoa\", \"p0\" -> \"target\", \"p1\" -> (s=1) }]"; + // "P=? [!(s=1) U (s=1)]" + formulasString += "; P=?[HOA: {\"" STORM_TEST_RESOURCES_DIR "/hoa/automaton_UXp0p1.hoa\", \"p0\" -> !(s=1) , \"p1\" -> \"target\" }]"; + + auto modelFormulas = this->buildModelFormulas(STORM_TEST_RESOURCES_DIR "/ctmc/polling2.sm", formulasString); + auto model = std::move(modelFormulas.first); + auto tasks = this->getTasks(modelFormulas.second); + EXPECT_EQ(12ul, model->getNumberOfStates()); + EXPECT_EQ(22ul, model->getNumberOfTransitions()); + ASSERT_EQ(model->getType(), storm::models::ModelType::Ctmc); + auto checker = this->createModelChecker(model); + std::unique_ptr<storm::modelchecker::CheckResult> result; + + // Not supported in all engines (Hybrid, PrismDd, JaniDd) + if (TypeParam::engine == CtmcEngine::PrismSparse || TypeParam::engine == CtmcEngine::JaniSparse || TypeParam::engine == CtmcEngine::JitSparse) { + result = checker->check(tasks[0]); + EXPECT_NEAR(this->parseNumber("1"), this->getQuantitativeResultAtInitialState(model, result), this->precision()); + + result = checker->check(tasks[1]); + EXPECT_NEAR(this->parseNumber("1"), this->getQuantitativeResultAtInitialState(model, result), this->precision()); + } else { + EXPECT_FALSE(checker->canHandle(tasks[0])); + } + + } } diff --git a/src/test/storm/modelchecker/csl/MarkovAutomatonCslModelCheckerTest.cpp b/src/test/storm/modelchecker/csl/MarkovAutomatonCslModelCheckerTest.cpp index 745c32f55..3d02af1c2 100755 --- a/src/test/storm/modelchecker/csl/MarkovAutomatonCslModelCheckerTest.cpp +++ b/src/test/storm/modelchecker/csl/MarkovAutomatonCslModelCheckerTest.cpp @@ -349,4 +349,70 @@ namespace { } #endif } + + TYPED_TEST(MarkovAutomatonCslModelCheckerTest, LtlSimple) { +#ifdef STORM_HAVE_LTL_MODELCHECKING_SUPPORT + std::string formulasString = "Pmax=? [X X s=3]"; + formulasString += "; Pmax=? [X X G s>2]"; + formulasString += "; Pmin=? [X X G s>2]"; + formulasString += "; Pmax=? [F ((s=0) U X(s=0) & X(s=2))]"; + + auto modelFormulas = this->buildModelFormulas(STORM_TEST_RESOURCES_DIR "/ma/simple.ma", formulasString); + auto model = std::move(modelFormulas.first); + auto tasks = this->getTasks(modelFormulas.second); + EXPECT_EQ(5ul, model->getNumberOfStates()); + EXPECT_EQ(8ul, model->getNumberOfTransitions()); + ASSERT_EQ(model->getType(), storm::models::ModelType::MarkovAutomaton); + auto checker = this->createModelChecker(model); + std::unique_ptr<storm::modelchecker::CheckResult> result; + + // LTL not supported in all engines (Hybrid, PrismDd, JaniDd) + if (TypeParam::engine == MaEngine::PrismSparse || TypeParam::engine == MaEngine::JaniSparse || TypeParam::engine == MaEngine::JitSparse) { + result = checker->check(this->env(), tasks[0]); + EXPECT_NEAR(this->parseNumber("1/10"), this->getQuantitativeResultAtInitialState(model, result), this->precision()); + + result = checker->check(this->env(), tasks[1]); + EXPECT_NEAR(this->parseNumber("1/5"), this->getQuantitativeResultAtInitialState(model, result), this->precision()); + + result = checker->check(this->env(), tasks[2]); + EXPECT_NEAR(this->parseNumber("1/10"), this->getQuantitativeResultAtInitialState(model, result), this->precision()); + + result = checker->check(this->env(), tasks[3]); + EXPECT_NEAR(this->parseNumber("9/10"), this->getQuantitativeResultAtInitialState(model, result), this->precision()); + + } else { + EXPECT_FALSE(checker->canHandle(tasks[0])); + } +#else + GTEST_SKIP(); +#endif + } + + TYPED_TEST(MarkovAutomatonCslModelCheckerTest, HOASimple) { + // "P=? [ F (s=3) & (X s=1)]" + std::string formulasString = "; P=?[HOA: {\"" STORM_TEST_RESOURCES_DIR "/hoa/automaton_Fandp0Xp1.hoa\", \"p0\" -> (s>1), \"p1\" -> !(s=1) }]"; + // "P=? [ (s=2) U (s=1)]" + formulasString += "; P=?[HOA: {\"" STORM_TEST_RESOURCES_DIR "/hoa/automaton_UXp0p1.hoa\", \"p0\" -> (s=2), \"p1\" -> (s=1) }]"; + + auto modelFormulas = this->buildModelFormulas(STORM_TEST_RESOURCES_DIR "/ma/simple.ma", formulasString); + auto model = std::move(modelFormulas.first); + auto tasks = this->getTasks(modelFormulas.second); + EXPECT_EQ(5ul, model->getNumberOfStates()); + EXPECT_EQ(8ul, model->getNumberOfTransitions()); + ASSERT_EQ(model->getType(), storm::models::ModelType::MarkovAutomaton); + auto checker = this->createModelChecker(model); + std::unique_ptr<storm::modelchecker::CheckResult> result; + + // Not supported in all engines (Hybrid, PrismDd, JaniDd) + if (TypeParam::engine == MaEngine::PrismSparse || TypeParam::engine == MaEngine::JaniSparse || TypeParam::engine == MaEngine::JitSparse) { + result = checker->check(tasks[0]); + EXPECT_NEAR(this->parseNumber("1"), this->getQuantitativeResultAtInitialState(model, result), this->precision()); + + result = checker->check(tasks[1]); + EXPECT_NEAR(this->parseNumber("0"), this->getQuantitativeResultAtInitialState(model, result), this->precision()); + } else { + EXPECT_FALSE(checker->canHandle(tasks[0])); + } + + } } diff --git a/src/test/storm/modelchecker/prctl/dtmc/DtmcPrctlModelCheckerTest.cpp b/src/test/storm/modelchecker/prctl/dtmc/DtmcPrctlModelCheckerTest.cpp index 7d7e4812b..1fa6f4159 100755 --- a/src/test/storm/modelchecker/prctl/dtmc/DtmcPrctlModelCheckerTest.cpp +++ b/src/test/storm/modelchecker/prctl/dtmc/DtmcPrctlModelCheckerTest.cpp @@ -30,6 +30,7 @@ #include "storm/environment/solver/EigenSolverEnvironment.h" #include "storm/environment/solver/TopologicalSolverEnvironment.h" + namespace { enum class DtmcEngine {PrismSparse, JaniSparse, JitSparse, Hybrid, PrismDd, JaniDd}; @@ -630,13 +631,13 @@ namespace { result = checker->check(this->env(), tasks[0]); EXPECT_NEAR(this->parseNumber("78686542099694893/1268858272000000000"), this->getQuantitativeResultAtInitialState(model, result), this->precision()); - + result = checker->check(this->env(), tasks[1]); EXPECT_NEAR(this->parseNumber("40300855878315123/1268858272000000000"), this->getQuantitativeResultAtInitialState(model, result), this->precision()); result = checker->check(this->env(), tasks[2]); EXPECT_NEAR(this->parseNumber("13433618626105041/1268858272000000000"), this->getQuantitativeResultAtInitialState(model, result), this->precision()); - + } TYPED_TEST(DtmcPrctlModelCheckerTest, SynchronousLeader) { @@ -716,4 +717,148 @@ namespace { EXPECT_NEAR(0, result[12], 1e-6); } + TYPED_TEST(DtmcPrctlModelCheckerTest, LtlProbabilitiesDie) { +#ifdef STORM_HAVE_LTL_MODELCHECKING_SUPPORT + std::string formulasString = "P=? [(X s>0) U (s=7 & d=2)]"; + formulasString += "; P=? [ X (((s=1) U (s=3)) U (s=7))]"; + formulasString += "; P=? [ (F (X (s=6 & (XX s=5)))) & (F G (d!=5))]"; + formulasString += "; P=? [ F (s=3 U (\"three\"))]"; + formulasString += "; P=? [ F s=3 U (\"three\")]"; + formulasString += "; P=? [ F (s=6) & X \"done\"]"; + formulasString += "; P=? [ (F s=6) & (X \"done\")]"; + + auto modelFormulas = this->buildModelFormulas(STORM_TEST_RESOURCES_DIR "/dtmc/die.pm", formulasString); + auto model = std::move(modelFormulas.first); + auto tasks = this->getTasks(modelFormulas.second); + EXPECT_EQ(13ul, model->getNumberOfStates()); + EXPECT_EQ(20ul, model->getNumberOfTransitions()); + ASSERT_EQ(model->getType(), storm::models::ModelType::Dtmc); + auto checker = this->createModelChecker(model); + std::unique_ptr<storm::modelchecker::CheckResult> result; + + // LTL not supported in all engines (Hybrid, PrismDd, JaniDd) + if (TypeParam::engine == DtmcEngine::PrismSparse || TypeParam::engine == DtmcEngine::JaniSparse || TypeParam::engine == DtmcEngine::JitSparse) { + result = checker->check(tasks[0]); + EXPECT_NEAR(this->parseNumber("1/6"), this->getQuantitativeResultAtInitialState(model, result), this->precision()); + + result = checker->check(tasks[1]); + EXPECT_NEAR(this->parseNumber("1/6"), this->getQuantitativeResultAtInitialState(model, result), this->precision()); + + result = checker->check(tasks[2]); + EXPECT_NEAR(this->parseNumber("1/24"), this->getQuantitativeResultAtInitialState(model, result), this->precision()); + + result = checker->check(tasks[3]); + EXPECT_NEAR(this->parseNumber("1/6"), this->getQuantitativeResultAtInitialState(model, result), this->precision()); + + result = checker->check(tasks[4]); + EXPECT_NEAR(this->parseNumber("0"), this->getQuantitativeResultAtInitialState(model, result), this->precision()); + + result = checker->check(tasks[5]); + EXPECT_NEAR(this->parseNumber("1/6"), this->getQuantitativeResultAtInitialState(model, result), this->precision()); + + result = checker->check(tasks[6]); + EXPECT_NEAR(this->parseNumber("0"), this->getQuantitativeResultAtInitialState(model, result), this->precision()); + } else { + EXPECT_FALSE(checker->canHandle(tasks[0])); + } +#else + GTEST_SKIP(); +#endif + } + + TYPED_TEST(DtmcPrctlModelCheckerTest, LtlProbabilitiesSynchronousLeader) { +#ifdef STORM_HAVE_LTL_MODELCHECKING_SUPPORT + std::string formulasString = "P=? [X (u1=true U \"elected\")]"; + formulasString += "; P=? [X !(u1=true U \"elected\")]"; + formulasString += "; P=? [X v1=2 & X v1=1]"; + formulasString += "; P=? [(X v1=2) & (X v1=1)]"; + formulasString += "; P=? [(!X v1=2) & (X v1=1)]"; + + auto modelFormulas = this->buildModelFormulas(STORM_TEST_RESOURCES_DIR "/dtmc/leader-3-5.pm", formulasString); + auto model = std::move(modelFormulas.first); + auto tasks = this->getTasks(modelFormulas.second); + EXPECT_EQ(273ul, model->getNumberOfStates()); + EXPECT_EQ(397ul, model->getNumberOfTransitions()); + ASSERT_EQ(model->getType(), storm::models::ModelType::Dtmc); + auto checker = this->createModelChecker(model); + std::unique_ptr<storm::modelchecker::CheckResult> result; + + // LTL not supported in all engines (Hybrid, PrismDd, JaniDd) + if (TypeParam::engine == DtmcEngine::PrismSparse || TypeParam::engine == DtmcEngine::JaniSparse || TypeParam::engine == DtmcEngine::JitSparse) { + result = checker->check(tasks[0]); + EXPECT_NEAR(this->parseNumber("16/25"), this->getQuantitativeResultAtInitialState(model, result), this->precision()); + + result = checker->check(tasks[1]); + EXPECT_NEAR(this->parseNumber("9/25"), this->getQuantitativeResultAtInitialState(model, result), this->precision()); + + result = checker->check(tasks[2]); + EXPECT_NEAR(this->parseNumber("1/25"), this->getQuantitativeResultAtInitialState(model, result), this->precision()); + + result = checker->check(tasks[3]); + EXPECT_NEAR(this->parseNumber("0"), this->getQuantitativeResultAtInitialState(model, result), this->precision()); + + result = checker->check(tasks[4]); + EXPECT_NEAR(this->parseNumber("1/5"), this->getQuantitativeResultAtInitialState(model, result), this->precision()); + + } else { + EXPECT_FALSE(checker->canHandle(tasks[0])); + } +#else + GTEST_SKIP(); +#endif + } + + TYPED_TEST(DtmcPrctlModelCheckerTest, HOAProbabilitiesDie) { + // "P=? [(X s>0) U (s=7 & d=2)]" + std::string formulasString = "P=?[HOA: {\"" STORM_TEST_RESOURCES_DIR "/hoa/automaton_UXp0p1.hoa\", \"p0\" -> (s>0), \"p1\" -> (s=7 & d=2) }]"; + // "P=? [(X s>0) U (d=4 | d=2)]" + formulasString += "; P=?[HOA: {\"" STORM_TEST_RESOURCES_DIR "/hoa/automaton_UXp0p1.hoa\", \"p0\" -> (s>0), \"p1\" -> (d=4 | d=2) }]"; + // "P=? [ (F s=4) & (X \"three\")]" + formulasString += "; P=?[HOA: {\"" STORM_TEST_RESOURCES_DIR "/hoa/automaton_Fandp0Xp1.hoa\", \"p0\" -> (s=4), \"p1\" -> \"three\" }]"; + // "P=? [ (F s=6) & (X \"done\")]" + formulasString += "; P=?[HOA: {\"" STORM_TEST_RESOURCES_DIR "/hoa/automaton_Fandp0Xp1.hoa\", \"p0\" -> (s=6), \"p1\" -> \"done\" }]"; + // "P=? [ (F s=6) & (X !\"done\")]" + formulasString += "; P=?[HOA: {\"" STORM_TEST_RESOURCES_DIR "/hoa/automaton_Fandp0Xp1.hoa\", \"p0\" -> (s=6), \"p1\" -> !\"done\" }]"; + // "P=? [ (F (s=4 | s=5)) & (X (\"three\" | \"five\"))]" + formulasString += "; P=?[HOA: {\"" STORM_TEST_RESOURCES_DIR "/hoa/automaton_Fandp0Xp1.hoa\", \"p0\" -> (s=4 | s=5), \"p1\" -> s=7 & (d=3 | d=5) }]"; + // "P=? [ (F (s=4 | s=5)) & (X (\"three\" | \"five\"))]" + formulasString += "; P>0.3[HOA: {\"" STORM_TEST_RESOURCES_DIR "/hoa/automaton_Fandp0Xp1.hoa\", \"p0\" -> (s=4 | s=5), \"p1\" -> s=7 & (d=3 | d=5) }]"; + + auto modelFormulas = this->buildModelFormulas(STORM_TEST_RESOURCES_DIR "/dtmc/die.pm", formulasString); + auto model = std::move(modelFormulas.first); + auto tasks = this->getTasks(modelFormulas.second); + EXPECT_EQ(13ul, model->getNumberOfStates()); + EXPECT_EQ(20ul, model->getNumberOfTransitions()); + ASSERT_EQ(model->getType(), storm::models::ModelType::Dtmc); + auto checker = this->createModelChecker(model); + std::unique_ptr<storm::modelchecker::CheckResult> result; + + // Not supported in all engines (Hybrid, PrismDd, JaniDd) + if (TypeParam::engine == DtmcEngine::PrismSparse || TypeParam::engine == DtmcEngine::JaniSparse || TypeParam::engine == DtmcEngine::JitSparse) { + result = checker->check(tasks[0]); + EXPECT_NEAR(this->parseNumber("1/6"), this->getQuantitativeResultAtInitialState(model, result), this->precision()); + + result = checker->check(tasks[1]); + EXPECT_NEAR(this->parseNumber("1/3"), this->getQuantitativeResultAtInitialState(model, result), this->precision()); + + result = checker->check(tasks[2]); + EXPECT_NEAR(this->parseNumber("1/6"), this->getQuantitativeResultAtInitialState(model, result), this->precision()); + + result = checker->check(tasks[3]); + EXPECT_NEAR(this->parseNumber("1/6"), this->getQuantitativeResultAtInitialState(model, result), this->precision()); + + result = checker->check(tasks[4]); + EXPECT_NEAR(this->parseNumber("1/8"), this->getQuantitativeResultAtInitialState(model, result), this->precision()); + + result = checker->check(tasks[5]); + EXPECT_NEAR(this->parseNumber("1/3"), this->getQuantitativeResultAtInitialState(model, result), this->precision()); + + result = checker->check(tasks[6]); + EXPECT_TRUE(this->getQualitativeResultAtInitialState(model, result)); + } else { + EXPECT_FALSE(checker->canHandle(tasks[0])); + } + + } + } diff --git a/src/test/storm/modelchecker/prctl/mdp/MdpPrctlModelCheckerTest.cpp b/src/test/storm/modelchecker/prctl/mdp/MdpPrctlModelCheckerTest.cpp index 87e670104..82f25b7c0 100755 --- a/src/test/storm/modelchecker/prctl/mdp/MdpPrctlModelCheckerTest.cpp +++ b/src/test/storm/modelchecker/prctl/mdp/MdpPrctlModelCheckerTest.cpp @@ -695,4 +695,125 @@ namespace { EXPECT_FALSE(checker->canHandle(tasks[0])); } } + + TYPED_TEST(MdpPrctlModelCheckerTest, LtlProbabilitiesCoin) { +#ifdef STORM_HAVE_LTL_MODELCHECKING_SUPPORT + std::string formulasString = "Pmin=? [!(GF \"all_coins_equal_1\")]"; + formulasString += "; Pmax=? [F \"all_coins_equal_1\" U \"finished\"]"; + formulasString += "; P>0.4 [!(GF \"all_coins_equal_1\")]"; + formulasString += "; P<0.6 [F \"all_coins_equal_1\" U \"finished\"]"; + // The following example results in an automaton with acceptance condition not in DNF (Streett, using Spot) + formulasString += "; Pmax=?[ (GF \"all_coins_equal_1\") & ((GF \"all_coins_equal_0\") | (FG \"finished\"))]"; + + auto modelFormulas = this->buildModelFormulas(STORM_TEST_RESOURCES_DIR "/mdp/coin2-2.nm", formulasString); + auto model = std::move(modelFormulas.first); + auto tasks = this->getTasks(modelFormulas.second); + EXPECT_EQ(272ul, model->getNumberOfStates()); + EXPECT_EQ(492ul, model->getNumberOfTransitions()); + ASSERT_EQ(model->getType(), storm::models::ModelType::Mdp); + auto checker = this->createModelChecker(model); + std::unique_ptr<storm::modelchecker::CheckResult> result; + + // LTL not supported in all engines (Hybrid, PrismDd, JaniDd) + if (TypeParam::engine == MdpEngine::PrismSparse || TypeParam::engine == MdpEngine::JaniSparse || TypeParam::engine == MdpEngine::JitSparse) { + result = checker->check(this->env(), tasks[0]); + EXPECT_NEAR(this->parseNumber("4/9"), this->getQuantitativeResultAtInitialState(model, result), this->precision()); + + result = checker->check(this->env(), tasks[1]); + EXPECT_NEAR(this->parseNumber("5/9"), this->getQuantitativeResultAtInitialState(model, result), this->precision()); + + result = checker->check(this->env(), tasks[2]); + EXPECT_TRUE(this->getQualitativeResultAtInitialState(model, result)); + + result = checker->check(this->env(), tasks[3]); + EXPECT_TRUE(this->getQualitativeResultAtInitialState(model, result)); + + result = checker->check(this->env(), tasks[4]); + EXPECT_NEAR(this->parseNumber("5/9"), this->getQuantitativeResultAtInitialState(model, result), this->precision()); + + + } else { + EXPECT_FALSE(checker->canHandle(tasks[0])); + } +#else + GTEST_SKIP(); +#endif + } + + TYPED_TEST(MdpPrctlModelCheckerTest, LtlDice) { +#ifdef STORM_HAVE_LTL_MODELCHECKING_SUPPORT + std::string formulasString = "Pmax=? [ X (((s1=1) U (s1=3)) U (s1=7))]"; + formulasString += "; Pmax=? [ (F (X (s1=6 & (XX s1=5)))) & (F G (d1!=5))]"; + formulasString += "; Pmax=? [ F s1=3 U (\"three\")]"; + formulasString += "; Pmin=? [! F (s2=6) & X \"done\"]"; + // Acceptance condition not in DNF (Streett, using Spot) + formulasString += "; Pmax=? [ ( (G F !(\"two\")) | F G (\"three\") ) & ( (G F !(\"five\") ) | F G (\"seven\") )]"; + + + auto modelFormulas = this->buildModelFormulas(STORM_TEST_RESOURCES_DIR "/mdp/two_dice.nm", formulasString); + auto model = std::move(modelFormulas.first); + auto tasks = this->getTasks(modelFormulas.second); + EXPECT_EQ(169ul, model->getNumberOfStates()); + EXPECT_EQ(436ul, model->getNumberOfTransitions()); + ASSERT_EQ(model->getType(), storm::models::ModelType::Mdp); + auto checker = this->createModelChecker(model); + std::unique_ptr<storm::modelchecker::CheckResult> result; + + // LTL not supported in all engines (Hybrid, PrismDd, JaniDd) + if (TypeParam::engine == MdpEngine::PrismSparse || TypeParam::engine == MdpEngine::JaniSparse || TypeParam::engine == MdpEngine::JitSparse) { + + result = checker->check(this->env(), tasks[0]); + EXPECT_NEAR(this->parseNumber("1/6"), this->getQuantitativeResultAtInitialState(model, result), this->precision()); + + result = checker->check(this->env(), tasks[1]); + EXPECT_NEAR(this->parseNumber("1/24"), this->getQuantitativeResultAtInitialState(model, result), this->precision()); + + result = checker->check(this->env(), tasks[2]); + EXPECT_NEAR(this->parseNumber("1/36"), this->getQuantitativeResultAtInitialState(model, result), this->precision()); + + result = checker->check(this->env(), tasks[3]); + EXPECT_NEAR(this->parseNumber("5/6"), this->getQuantitativeResultAtInitialState(model, result), this->precision()); + + result = checker->check(this->env(), tasks[4]); + EXPECT_NEAR(this->parseNumber("31/36"), this->getQuantitativeResultAtInitialState(model, result), this->precision()); + + } else { + EXPECT_FALSE(checker->canHandle(tasks[0])); + } + +#else + GTEST_SKIP(); +#endif + + } + + TYPED_TEST(MdpPrctlModelCheckerTest, HOADice) { + // "P=? [ F "three" & (X s=1)]" + std::string formulasString = "; P=?[HOA: {\"" STORM_TEST_RESOURCES_DIR "/hoa/automaton_Fandp0Xp1.hoa\", \"p0\" -> \"three\", \"p1\" -> s2=1 }]"; + // "P=? [!(s2=6) U "done"]" + formulasString += "; P=?[HOA: {\"" STORM_TEST_RESOURCES_DIR "/hoa/automaton_UXp0p1.hoa\", \"p0\" -> !(s2=6), \"p1\" -> \"done\" }]"; + + auto modelFormulas = this->buildModelFormulas(STORM_TEST_RESOURCES_DIR "/mdp/two_dice.nm", formulasString); + auto model = std::move(modelFormulas.first); + auto tasks = this->getTasks(modelFormulas.second); + EXPECT_EQ(169ul, model->getNumberOfStates()); + EXPECT_EQ(436ul, model->getNumberOfTransitions()); + ASSERT_EQ(model->getType(), storm::models::ModelType::Mdp); + auto checker = this->createModelChecker(model); + std::unique_ptr<storm::modelchecker::CheckResult> result; + + // Not supported in all engines (Hybrid, PrismDd, JaniDd) + if (TypeParam::engine == MdpEngine::PrismSparse || TypeParam::engine == MdpEngine::JaniSparse || TypeParam::engine == MdpEngine::JitSparse) { + result = checker->check(tasks[0]); + EXPECT_NEAR(this->parseNumber("0"), this->getQuantitativeResultAtInitialState(model, result), this->precision()); + + result = checker->check(tasks[1]); + EXPECT_NEAR(this->parseNumber("3/4"), this->getQuantitativeResultAtInitialState(model, result), this->precision()); + } else { + EXPECT_FALSE(checker->canHandle(tasks[0])); + } + + } + + } diff --git a/src/test/storm/modelchecker/prctl/mdp/QuantileQueryTest.cpp b/src/test/storm/modelchecker/prctl/mdp/QuantileQueryTest.cpp index 9fbf3bffb..65983ef6a 100755 --- a/src/test/storm/modelchecker/prctl/mdp/QuantileQueryTest.cpp +++ b/src/test/storm/modelchecker/prctl/mdp/QuantileQueryTest.cpp @@ -98,6 +98,7 @@ namespace { std::pair<bool, std::string> compareResult(std::shared_ptr<storm::models::sparse::Model<ValueType>> const& model, std::unique_ptr<storm::modelchecker::CheckResult>& result, std::vector<std::string> const& expected) { bool equal = true; std::string errorMessage = ""; + ValueType comparePrecision = std::is_same<ValueType, double>::value ? storm::utility::convertNumber<ValueType>(1e-10) : storm::utility::zero<ValueType>(); auto filter = getInitialStateFilter(model); result->filter(*filter); std::vector<std::vector<ValueType>> resultPoints; @@ -120,7 +121,7 @@ namespace { for (auto const& resPoint : resultPoints) { bool contained = false; for (auto const& expPoint : expectedPoints) { - if (resPoint == expPoint) { + if (storm::utility::vector::equalModuloPrecision(resPoint, expPoint, comparePrecision, true)) { contained = true; break; } @@ -133,7 +134,7 @@ namespace { for (auto const& expPoint : expectedPoints) { bool contained = false; for (auto const& resPoint : resultPoints) { - if (resPoint == expPoint) { + if (storm::utility::vector::equalModuloPrecision(resPoint, expPoint, comparePrecision, true)) { contained = true; break; } diff --git a/src/test/storm/modelchecker/prctl/mdp/SchedulerGenerationMdpPrctlModelCheckerTest.cpp b/src/test/storm/modelchecker/prctl/mdp/SchedulerGenerationMdpPrctlModelCheckerTest.cpp index dbea6504d..02e37ab58 100755 --- a/src/test/storm/modelchecker/prctl/mdp/SchedulerGenerationMdpPrctlModelCheckerTest.cpp +++ b/src/test/storm/modelchecker/prctl/mdp/SchedulerGenerationMdpPrctlModelCheckerTest.cpp @@ -11,6 +11,7 @@ #include "storm/logic/Formulas.h" #include "storm/models/sparse/StandardRewardModel.h" #include "storm/modelchecker/prctl/SparseMdpPrctlModelChecker.h" +#include "storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.h" #include "storm/modelchecker/results/ExplicitQuantitativeCheckResult.h" #include "storm/settings/SettingsManager.h" #include "storm/settings/modules/GeneralSettings.h" @@ -71,14 +72,14 @@ namespace { // return env; // } // }; - + template<typename TestType> class SchedulerGenerationMdpPrctlModelCheckerTest : public ::testing::Test { public: typedef typename TestType::ValueType ValueType; SchedulerGenerationMdpPrctlModelCheckerTest() : _environment(TestType::createEnvironment()) {} storm::Environment const& env() const { return _environment; } - + std::pair<std::shared_ptr<storm::models::sparse::Mdp<ValueType>>, std::vector<std::shared_ptr<storm::logic::Formula const>>> buildModelFormulas(std::string const& pathToPrismFile, std::string const& formulasAsString, std::string const& constantDefinitionString = "") const { std::pair<std::shared_ptr<storm::models::sparse::Mdp<ValueType>>, std::vector<std::shared_ptr<storm::logic::Formula const>>> result; storm::prism::Program program = storm::api::parseProgram(pathToPrismFile); @@ -87,7 +88,7 @@ namespace { result.first = storm::api::buildSparseModel<ValueType>(program, result.second)->template as<storm::models::sparse::Mdp<ValueType>>(); return result; } - + std::vector<storm::modelchecker::CheckTask<storm::logic::Formula, ValueType>> getTasks(std::vector<std::shared_ptr<storm::logic::Formula const>> const& formulas) const { std::vector<storm::modelchecker::CheckTask<storm::logic::Formula, ValueType>> result; for (auto const& f : formulas) { @@ -96,13 +97,13 @@ namespace { } return result; } - + ValueType parseNumber(std::string const& input) const { return storm::utility::convertNumber<ValueType>(input);} - + private: storm::Environment _environment; }; - + typedef ::testing::Types< DoubleViEnvironment, DoubleSoundViEnvironment, @@ -110,10 +111,10 @@ namespace { RationalPIEnvironment //RationalRationalSearchEnvironment > TestingTypes; - + TYPED_TEST_SUITE(SchedulerGenerationMdpPrctlModelCheckerTest, TestingTypes,); - + TYPED_TEST(SchedulerGenerationMdpPrctlModelCheckerTest, reachability) { typedef typename TestFixture::ValueType ValueType; @@ -125,9 +126,9 @@ namespace { EXPECT_EQ(11ull, mdp->getNumberOfTransitions()); ASSERT_EQ(mdp->getType(), storm::models::ModelType::Mdp); EXPECT_EQ(7ull, mdp->getNumberOfChoices()); - + storm::modelchecker::SparseMdpPrctlModelChecker<storm::models::sparse::Mdp<ValueType>> checker(*mdp); - + auto result = checker.check(this->env(), tasks[0]); ASSERT_TRUE(result->isExplicitQuantitativeCheckResult()); ASSERT_TRUE(result->template asExplicitQuantitativeCheckResult<ValueType>().hasScheduler()); @@ -136,7 +137,7 @@ namespace { EXPECT_EQ(1ull, scheduler.getChoice(1).getDeterministicChoice()); EXPECT_EQ(0ull, scheduler.getChoice(2).getDeterministicChoice()); EXPECT_EQ(0ull, scheduler.getChoice(3).getDeterministicChoice()); - + result = checker.check(tasks[1]); ASSERT_TRUE(result->isExplicitQuantitativeCheckResult()); ASSERT_TRUE(result->template asExplicitQuantitativeCheckResult<ValueType>().hasScheduler()); @@ -146,12 +147,12 @@ namespace { EXPECT_EQ(0ull, scheduler2.getChoice(2).getDeterministicChoice()); EXPECT_EQ(0ull, scheduler2.getChoice(3).getDeterministicChoice()); } - + TYPED_TEST(SchedulerGenerationMdpPrctlModelCheckerTest, lra) { typedef typename TestFixture::ValueType ValueType; std::string formulasString = "R{\"grants\"}max=? [ MP ]; R{\"grants\"}min=? [ MP ];"; - + auto modelFormulas = this->buildModelFormulas(STORM_TEST_RESOURCES_DIR "/mdp/cs_nfail3.nm", formulasString); auto mdp = std::move(modelFormulas.first); auto tasks = this->getTasks(modelFormulas.second); @@ -160,19 +161,20 @@ namespace { EXPECT_EQ(439ul, mdp->getNumberOfChoices()); ASSERT_EQ(mdp->getType(), storm::models::ModelType::Mdp); storm::modelchecker::SparseMdpPrctlModelChecker<storm::models::sparse::Mdp<ValueType>> checker(*mdp); - + if (!std::is_same<ValueType, double>::value) { GTEST_SKIP() << "Lra scheduler extraction not supported for LP based method"; } { auto result = checker.check(this->env(), tasks[0]); ASSERT_TRUE(result->isExplicitQuantitativeCheckResult()); - EXPECT_NEAR(this->parseNumber("333/1000"), result->template asExplicitQuantitativeCheckResult<ValueType>()[*mdp->getInitialStates().begin()], this->env().solver().lra().getPrecision()); + EXPECT_NEAR(this->parseNumber("333/1000"), result->template asExplicitQuantitativeCheckResult<ValueType>()[*mdp->getInitialStates().begin()], storm::utility::convertNumber<ValueType>(this->env().solver().lra().getPrecision())); ASSERT_TRUE(result->template asExplicitQuantitativeCheckResult<ValueType>().hasScheduler()); storm::storage::Scheduler<ValueType> const& scheduler = result->template asExplicitQuantitativeCheckResult<ValueType>().getScheduler(); EXPECT_TRUE(scheduler.isDeterministicScheduler()); EXPECT_TRUE(scheduler.isMemorylessScheduler()); EXPECT_TRUE(!scheduler.isPartialScheduler()); + auto inducedModel = mdp->applyScheduler(scheduler); ASSERT_EQ(inducedModel->getType(), storm::models::ModelType::Mdp); auto const& inducedMdp = inducedModel->template as<storm::models::sparse::Mdp<ValueType>>(); @@ -180,12 +182,12 @@ namespace { storm::modelchecker::SparseMdpPrctlModelChecker<storm::models::sparse::Mdp<ValueType>> inducedChecker(*inducedMdp); auto inducedResult = inducedChecker.check(this->env(), tasks[0]); ASSERT_TRUE(inducedResult->isExplicitQuantitativeCheckResult()); - EXPECT_NEAR(this->parseNumber("333/1000"), inducedResult->template asExplicitQuantitativeCheckResult<ValueType>()[*mdp->getInitialStates().begin()], this->env().solver().lra().getPrecision()); + EXPECT_NEAR(this->parseNumber("333/1000"), inducedResult->template asExplicitQuantitativeCheckResult<ValueType>()[*mdp->getInitialStates().begin()], storm::utility::convertNumber<ValueType>(this->env().solver().lra().getPrecision())); } { auto result = checker.check(this->env(), tasks[1]); ASSERT_TRUE(result->isExplicitQuantitativeCheckResult()); - EXPECT_NEAR(this->parseNumber("0"), result->template asExplicitQuantitativeCheckResult<ValueType>()[*mdp->getInitialStates().begin()], this->env().solver().lra().getPrecision()); + EXPECT_NEAR(this->parseNumber("0"), result->template asExplicitQuantitativeCheckResult<ValueType>()[*mdp->getInitialStates().begin()], storm::utility::convertNumber<ValueType>(this->env().solver().lra().getPrecision())); ASSERT_TRUE(result->template asExplicitQuantitativeCheckResult<ValueType>().hasScheduler()); storm::storage::Scheduler<ValueType> const& scheduler = result->template asExplicitQuantitativeCheckResult<ValueType>().getScheduler(); EXPECT_TRUE(scheduler.isDeterministicScheduler()); @@ -198,8 +200,217 @@ namespace { storm::modelchecker::SparseMdpPrctlModelChecker<storm::models::sparse::Mdp<ValueType>> inducedChecker(*inducedMdp); auto inducedResult = inducedChecker.check(this->env(), tasks[1]); ASSERT_TRUE(inducedResult->isExplicitQuantitativeCheckResult()); - EXPECT_NEAR(this->parseNumber("0"), inducedResult->template asExplicitQuantitativeCheckResult<ValueType>()[*mdp->getInitialStates().begin()], this->env().solver().lra().getPrecision()); + EXPECT_NEAR(this->parseNumber("0"), inducedResult->template asExplicitQuantitativeCheckResult<ValueType>()[*mdp->getInitialStates().begin()], storm::utility::convertNumber<ValueType>(this->env().solver().lra().getPrecision())); } } - -} \ No newline at end of file + + + TYPED_TEST(SchedulerGenerationMdpPrctlModelCheckerTest, ltl) { + typedef typename TestFixture::ValueType ValueType; + +#ifdef STORM_HAVE_LTL_MODELCHECKING_SUPPORT + std::string formulasString = "Pmax=? [X X s=0]; Pmin=? [G F \"target\"]; Pmax=? [(G F s>2) & (F G !(s=3))];"; + auto modelFormulas = this->buildModelFormulas(STORM_TEST_RESOURCES_DIR "/mdp/scheduler_generation.nm", + formulasString); + auto mdp = std::move(modelFormulas.first); + auto tasks = this->getTasks(modelFormulas.second); + EXPECT_EQ(4ull, mdp->getNumberOfStates()); + EXPECT_EQ(11ull, mdp->getNumberOfTransitions()); + ASSERT_EQ(mdp->getType(), storm::models::ModelType::Mdp); + EXPECT_EQ(7ull, mdp->getNumberOfChoices()); + + storm::modelchecker::SparseMdpPrctlModelChecker<storm::models::sparse::Mdp<ValueType>> checker(*mdp); + + { + tasks[0].setOnlyInitialStatesRelevant(true); + auto result = checker.check(this->env(), tasks[0]); + ASSERT_TRUE(result->isExplicitQuantitativeCheckResult()); + EXPECT_NEAR(this->parseNumber("81/100"), result->template asExplicitQuantitativeCheckResult<ValueType>()[*mdp->getInitialStates().begin()], storm::utility::convertNumber<ValueType>(this->env().solver().minMax().getPrecision())); + ASSERT_TRUE(result->template asExplicitQuantitativeCheckResult<ValueType>().hasScheduler()); + storm::storage::Scheduler<ValueType> const &scheduler = result->template asExplicitQuantitativeCheckResult<ValueType>().getScheduler(); + + + EXPECT_TRUE(scheduler.isDeterministicScheduler()); + EXPECT_TRUE(!scheduler.isMemorylessScheduler()); + EXPECT_TRUE(!scheduler.isPartialScheduler()); + auto inducedModel = mdp->applyScheduler(scheduler); + + ASSERT_EQ(inducedModel->getType(), storm::models::ModelType::Mdp); + auto const &inducedMdp = inducedModel->template as<storm::models::sparse::Mdp<ValueType>>(); + EXPECT_EQ(inducedMdp->getNumberOfChoices(), inducedMdp->getNumberOfStates()); + + storm::modelchecker::SparseMdpPrctlModelChecker<storm::models::sparse::Mdp<ValueType>> inducedChecker(*inducedMdp); + auto inducedResult = inducedChecker.check(this->env(), tasks[0]); + ASSERT_TRUE(inducedResult->isExplicitQuantitativeCheckResult()); + EXPECT_NEAR(this->parseNumber("81/100"), inducedResult->template asExplicitQuantitativeCheckResult<ValueType>()[*inducedMdp->getInitialStates().begin()], storm::utility::convertNumber<ValueType>(this->env().solver().minMax().getPrecision())); + } + { + tasks[1].setOnlyInitialStatesRelevant(true); + auto result = checker.check(this->env(), tasks[1]); + ASSERT_TRUE(result->isExplicitQuantitativeCheckResult()); + EXPECT_NEAR(this->parseNumber("1/2"), result->template asExplicitQuantitativeCheckResult<ValueType>()[*mdp->getInitialStates().begin()], storm::utility::convertNumber<ValueType>(this->env().solver().minMax().getPrecision())); + ASSERT_TRUE(result->template asExplicitQuantitativeCheckResult<ValueType>().hasScheduler()); + storm::storage::Scheduler<ValueType> const &scheduler = result->template asExplicitQuantitativeCheckResult<ValueType>().getScheduler(); + + EXPECT_TRUE(scheduler.isDeterministicScheduler()); + EXPECT_TRUE(!scheduler.isMemorylessScheduler()); + EXPECT_TRUE(!scheduler.isPartialScheduler()); + auto inducedModel = mdp->applyScheduler(scheduler); + + ASSERT_EQ(inducedModel->getType(), storm::models::ModelType::Mdp); + auto const &inducedMdp = inducedModel->template as<storm::models::sparse::Mdp<ValueType>>(); + EXPECT_EQ(inducedMdp->getNumberOfChoices(), inducedMdp->getNumberOfStates()); + + storm::modelchecker::SparseMdpPrctlModelChecker<storm::models::sparse::Mdp<ValueType>> inducedChecker(*inducedMdp); + auto inducedResult = inducedChecker.check(this->env(), tasks[1]); + ASSERT_TRUE(inducedResult->isExplicitQuantitativeCheckResult()); + + EXPECT_NEAR(this->parseNumber("1/2"),inducedResult->template asExplicitQuantitativeCheckResult<ValueType>()[*inducedMdp->getInitialStates().begin()], storm::utility::convertNumber<ValueType>(this->env().solver().minMax().getPrecision())); + } + { + tasks[2].setOnlyInitialStatesRelevant(false); + auto result = checker.check(this->env(), tasks[2]); + ASSERT_TRUE(result->isExplicitQuantitativeCheckResult()); + EXPECT_NEAR(this->parseNumber("1/2"), result->template asExplicitQuantitativeCheckResult<ValueType>()[*mdp->getInitialStates().begin()], storm::utility::convertNumber<ValueType>(this->env().solver().minMax().getPrecision())); + ASSERT_TRUE(result->template asExplicitQuantitativeCheckResult<ValueType>().hasScheduler()); + storm::storage::Scheduler<ValueType> const &scheduler = result->template asExplicitQuantitativeCheckResult<ValueType>().getScheduler(); + + EXPECT_TRUE(scheduler.isDeterministicScheduler()); + EXPECT_TRUE(!scheduler.isMemorylessScheduler()); + EXPECT_TRUE(!scheduler.isPartialScheduler()); + auto inducedModel = mdp->applyScheduler(scheduler); + + ASSERT_EQ(inducedModel->getType(), storm::models::ModelType::Mdp); + auto const &inducedMdp = inducedModel->template as<storm::models::sparse::Mdp<ValueType>>(); + EXPECT_EQ(inducedMdp->getNumberOfChoices(), inducedMdp->getNumberOfStates()); + + storm::modelchecker::SparseMdpPrctlModelChecker<storm::models::sparse::Mdp<ValueType>> inducedChecker(*inducedMdp); + auto inducedResult = inducedChecker.check(this->env(), tasks[2]); + ASSERT_TRUE(inducedResult->isExplicitQuantitativeCheckResult()); + + auto test = inducedResult->template asExplicitQuantitativeCheckResult<ValueType>().getValueVector(); + EXPECT_NEAR(this->parseNumber("1/2"), inducedResult->template asExplicitQuantitativeCheckResult<ValueType>()[0], storm::utility::convertNumber<ValueType>(this->env().solver().minMax().getPrecision())); + EXPECT_NEAR(this->parseNumber("1"), inducedResult->template asExplicitQuantitativeCheckResult<ValueType>()[1], storm::utility::convertNumber<ValueType>(this->env().solver().minMax().getPrecision())); + EXPECT_NEAR(this->parseNumber("0"), inducedResult->template asExplicitQuantitativeCheckResult<ValueType>()[2], storm::utility::convertNumber<ValueType>(this->env().solver().minMax().getPrecision())); + } +#else + GTEST_SKIP(); +#endif + } + + TYPED_TEST(SchedulerGenerationMdpPrctlModelCheckerTest, ltlNondetChoice) { + typedef typename TestFixture::ValueType ValueType; +#ifdef STORM_HAVE_LTL_MODELCHECKING_SUPPORT + // Nondeterministic choice in an accepting EC. + std::string formulasString = "Pmax=? [X X !(x=0)];"; + auto modelFormulas = this->buildModelFormulas(STORM_TEST_RESOURCES_DIR "/mdp/prism-mec-example1.nm", formulasString); + + auto mdp = std::move(modelFormulas.first); + auto tasks = this->getTasks(modelFormulas.second); + EXPECT_EQ(3ull, mdp->getNumberOfStates()); + EXPECT_EQ(5ull, mdp->getNumberOfTransitions()); + ASSERT_EQ(mdp->getType(), storm::models::ModelType::Mdp); + EXPECT_EQ(4ull, mdp->getNumberOfChoices()); + + storm::modelchecker::SparseMdpPrctlModelChecker<storm::models::sparse::Mdp<ValueType>> checker(*mdp); + + { + tasks[0].setOnlyInitialStatesRelevant(true); + auto result = checker.check(this->env(), tasks[0]); + ASSERT_TRUE(result->isExplicitQuantitativeCheckResult()); + EXPECT_NEAR(this->parseNumber("1"),result->template asExplicitQuantitativeCheckResult<ValueType>()[*mdp->getInitialStates().begin()], + storm::utility::convertNumber<ValueType>(this->env().solver().minMax().getPrecision())); + ASSERT_TRUE(result->template asExplicitQuantitativeCheckResult<ValueType>().hasScheduler()); + storm::storage::Scheduler<ValueType> const &scheduler = result->template asExplicitQuantitativeCheckResult<ValueType>().getScheduler(); + + EXPECT_TRUE(scheduler.isDeterministicScheduler()); + EXPECT_TRUE(!scheduler.isMemorylessScheduler()); + EXPECT_TRUE(!scheduler.isPartialScheduler()); + auto inducedModel = mdp->applyScheduler(scheduler); + + ASSERT_EQ(inducedModel->getType(), storm::models::ModelType::Mdp); + auto const &inducedMdp = inducedModel->template as<storm::models::sparse::Mdp<ValueType>>(); + EXPECT_EQ(inducedMdp->getNumberOfChoices(), inducedMdp->getNumberOfStates()); + + storm::modelchecker::SparseMdpPrctlModelChecker<storm::models::sparse::Mdp<ValueType>> inducedChecker(*inducedMdp); + auto inducedResult = inducedChecker.check(this->env(), tasks[0]); + ASSERT_TRUE(inducedResult->isExplicitQuantitativeCheckResult()); + EXPECT_NEAR(this->parseNumber("1"), inducedResult->template asExplicitQuantitativeCheckResult<ValueType>()[*inducedMdp->getInitialStates().begin()], storm::utility::convertNumber<ValueType>(this->env().solver().minMax().getPrecision())); + } +#else + GTEST_SKIP(); +#endif + + } + + + TYPED_TEST(SchedulerGenerationMdpPrctlModelCheckerTest, ltlUnsat) { + typedef typename TestFixture::ValueType ValueType; +#ifdef STORM_HAVE_LTL_MODELCHECKING_SUPPORT + // Nondeterministic choice in an accepting EC, Pmax unsatisfiable, Pmin tautology (compute 1-Pmax(!phi)) + std::string formulasString = "Pmax=? [(X X !(s=0)) & (X X (s=0))]; Pmin=? [(X X !(s=0)) | (X X (s=0))];"; + auto modelFormulas = this->buildModelFormulas(STORM_TEST_RESOURCES_DIR "/mdp/scheduler_generation.nm", formulasString); + + auto mdp = std::move(modelFormulas.first); + auto tasks = this->getTasks(modelFormulas.second); + EXPECT_EQ(4ull, mdp->getNumberOfStates()); + EXPECT_EQ(11ull, mdp->getNumberOfTransitions()); + ASSERT_EQ(mdp->getType(), storm::models::ModelType::Mdp); + EXPECT_EQ(7ull, mdp->getNumberOfChoices()); + + storm::modelchecker::SparseMdpPrctlModelChecker<storm::models::sparse::Mdp<ValueType>> checker(*mdp); + + { + tasks[0].setOnlyInitialStatesRelevant(true); + auto result = checker.check(this->env(), tasks[0]); + ASSERT_TRUE(result->isExplicitQuantitativeCheckResult()); + EXPECT_NEAR(this->parseNumber("0"),result->template asExplicitQuantitativeCheckResult<ValueType>()[*mdp->getInitialStates().begin()], + storm::utility::convertNumber<ValueType>(this->env().solver().minMax().getPrecision())); + ASSERT_TRUE(result->template asExplicitQuantitativeCheckResult<ValueType>().hasScheduler()); + storm::storage::Scheduler<ValueType> const &scheduler = result->template asExplicitQuantitativeCheckResult<ValueType>().getScheduler(); + + EXPECT_TRUE(scheduler.isDeterministicScheduler()); + EXPECT_TRUE(scheduler.isMemorylessScheduler()); + EXPECT_TRUE(!scheduler.isPartialScheduler()); + auto inducedModel = mdp->applyScheduler(scheduler); + + ASSERT_EQ(inducedModel->getType(), storm::models::ModelType::Mdp); + auto const &inducedMdp = inducedModel->template as<storm::models::sparse::Mdp<ValueType>>(); + EXPECT_EQ(inducedMdp->getNumberOfChoices(), inducedMdp->getNumberOfStates()); + + storm::modelchecker::SparseMdpPrctlModelChecker<storm::models::sparse::Mdp<ValueType>> inducedChecker(*inducedMdp); + auto inducedResult = inducedChecker.check(this->env(), tasks[0]); + ASSERT_TRUE(inducedResult->isExplicitQuantitativeCheckResult()); + EXPECT_NEAR(this->parseNumber("0"), inducedResult->template asExplicitQuantitativeCheckResult<ValueType>()[*inducedMdp->getInitialStates().begin()], storm::utility::convertNumber<ValueType>(this->env().solver().minMax().getPrecision())); + } + + { + tasks[1].setOnlyInitialStatesRelevant(true); + auto result = checker.check(this->env(), tasks[1]); + ASSERT_TRUE(result->isExplicitQuantitativeCheckResult()); + ASSERT_TRUE(result->template asExplicitQuantitativeCheckResult<ValueType>().hasScheduler()); + EXPECT_NEAR(this->parseNumber("1"),result->template asExplicitQuantitativeCheckResult<ValueType>()[*mdp->getInitialStates().begin()], + storm::utility::convertNumber<ValueType>(this->env().solver().minMax().getPrecision())); + storm::storage::Scheduler<ValueType> const &scheduler = result->template asExplicitQuantitativeCheckResult<ValueType>().getScheduler(); + + EXPECT_TRUE(scheduler.isDeterministicScheduler()); + EXPECT_TRUE(scheduler.isMemorylessScheduler()); + EXPECT_TRUE(!scheduler.isPartialScheduler()); + auto inducedModel = mdp->applyScheduler(scheduler); + + + ASSERT_EQ(inducedModel->getType(), storm::models::ModelType::Mdp); + auto const &inducedMdp = inducedModel->template as<storm::models::sparse::Mdp<ValueType>>(); + EXPECT_EQ(inducedMdp->getNumberOfChoices(), inducedMdp->getNumberOfStates()); + + storm::modelchecker::SparseMdpPrctlModelChecker<storm::models::sparse::Mdp<ValueType>> inducedChecker(*inducedMdp); + auto inducedResult = inducedChecker.check(this->env(), tasks[1]); + ASSERT_TRUE(inducedResult->isExplicitQuantitativeCheckResult()); + EXPECT_NEAR(this->parseNumber("1"), inducedResult->template asExplicitQuantitativeCheckResult<ValueType>()[*inducedMdp->getInitialStates().begin()], storm::utility::convertNumber<ValueType>(this->env().solver().minMax().getPrecision())); + } +#else + GTEST_SKIP(); +#endif + + } +} diff --git a/src/test/storm/parser/FormulaParserTest.cpp b/src/test/storm/parser/FormulaParserTest.cpp index 52e1d2dbf..8602f5398 100644 --- a/src/test/storm/parser/FormulaParserTest.cpp +++ b/src/test/storm/parser/FormulaParserTest.cpp @@ -2,7 +2,9 @@ #include "storm-config.h" #include "storm-parsers/parser/FormulaParser.h" #include "storm/logic/FragmentSpecification.h" +#include "storm/automata/DeterministicAutomaton.h" #include "storm/exceptions/WrongFormatException.h" +#include "storm/exceptions/ExpressionEvaluationException.h" #include "storm/storage/expressions/ExpressionManager.h" TEST(FormulaParserTest, LabelTest) { @@ -30,7 +32,7 @@ TEST(FormulaParserTest, ExpressionTest) { std::shared_ptr<storm::expressions::ExpressionManager> manager(new storm::expressions::ExpressionManager()); manager->declareBooleanVariable("x"); manager->declareIntegerVariable("y"); - + storm::parser::FormulaParser formulaParser(manager); std::string input = "!(x | y > 3)"; @@ -38,7 +40,7 @@ TEST(FormulaParserTest, ExpressionTest) { ASSERT_NO_THROW(formula = formulaParser.parseSingleFormulaFromString(input)); EXPECT_TRUE(formula->isInFragment(storm::logic::propositional())); - EXPECT_TRUE(formula->isUnaryBooleanStateFormula()); + EXPECT_TRUE(formula->isAtomicExpressionFormula()); } TEST(FormulaParserTest, LabelAndExpressionTest) { @@ -155,7 +157,6 @@ TEST(FormulaParserTest, CommentTest) { ASSERT_TRUE(formula->asProbabilityOperatorFormula().getSubformula().asNextFormula().getSubformula().isAtomicLabelFormula()); } - TEST(FormulaParserTest, WrongFormatTest) { std::shared_ptr<storm::expressions::ExpressionManager> manager(new storm::expressions::ExpressionManager()); manager->declareBooleanVariable("x"); @@ -177,6 +178,16 @@ TEST(FormulaParserTest, WrongFormatTest) { input = "P>0.5 [F y!=0)]"; STORM_SILENT_EXPECT_THROW(formula = formulaParser.parseSingleFormulaFromString(input), storm::exceptions::WrongFormatException); + + input = "P<0.9 [G F]"; + STORM_SILENT_EXPECT_THROW(formula = formulaParser.parseSingleFormulaFromString(input), storm::exceptions::WrongFormatException); + + input = "P<0.9 [\"a\" U \"b\" U \"c\"]"; + STORM_SILENT_EXPECT_THROW(formula = formulaParser.parseSingleFormulaFromString(input), storm::exceptions::WrongFormatException); + + input = "P<0.9 [X \"a\" U G \"b\" U X \"c\"]"; + STORM_SILENT_EXPECT_THROW(formula = formulaParser.parseSingleFormulaFromString(input), storm::exceptions::WrongFormatException); + } TEST(FormulaParserTest, MultiObjectiveFormulaTest) { @@ -206,3 +217,198 @@ TEST(FormulaParserTest, MultiObjectiveFormulaTest) { ASSERT_TRUE(storm::solver::minimize(mof.getSubformula(2).asProbabilityOperatorFormula().getOptimalityType())); } + +TEST(FormulaParserTest, LogicalPrecedenceTest) { + // Test precedence of logical operators over temporal operators, etc. + storm::parser::FormulaParser formulaParser; + std::shared_ptr<storm::logic::Formula const> formula(nullptr); + + std::string input = "P=? [ !\"a\" & \"b\" U ! \"c\" | \"b\" ]"; + ASSERT_NO_THROW(formula = formulaParser.parseSingleFormulaFromString(input)); + EXPECT_TRUE(formula->isProbabilityOperatorFormula()); + + auto const &nested1 = formula->asProbabilityOperatorFormula().getSubformula(); + EXPECT_TRUE(nested1.isUntilFormula()); + ASSERT_TRUE(nested1.asUntilFormula().getLeftSubformula().isBinaryBooleanStateFormula()); + ASSERT_TRUE(nested1.asUntilFormula().getLeftSubformula().asBinaryBooleanStateFormula().getLeftSubformula().isUnaryBooleanStateFormula()); + ASSERT_TRUE(nested1.asUntilFormula().getRightSubformula().isBinaryBooleanStateFormula()); + ASSERT_TRUE(nested1.asUntilFormula().getRightSubformula().asBinaryBooleanStateFormula().getLeftSubformula().isUnaryBooleanStateFormula()); + + input = "P<0.9 [ F G !\"a\" | \"b\" ] "; + ASSERT_NO_THROW(formula = formulaParser.parseSingleFormulaFromString(input)); + auto const &nested2 = formula->asProbabilityOperatorFormula().getSubformula(); + EXPECT_TRUE(nested2.asEventuallyFormula().getSubformula().isGloballyFormula()); + auto const &nested2Subformula = nested2.asEventuallyFormula().getSubformula().asGloballyFormula(); + EXPECT_TRUE(nested2Subformula.getSubformula().isBinaryBooleanStateFormula()); + ASSERT_TRUE(nested2Subformula.getSubformula().asBinaryBooleanStateFormula().getLeftSubformula().isUnaryBooleanStateFormula()); + + input = "P<0.9 [ X G \"a\" | !\"b\" | \"c\"] "; // from left to right + ASSERT_NO_THROW(formula = formulaParser.parseSingleFormulaFromString(input)); + auto const &nested3 = formula->asProbabilityOperatorFormula().getSubformula(); + EXPECT_TRUE(nested3.asNextFormula().getSubformula().isGloballyFormula()); + EXPECT_TRUE(nested3.asNextFormula().getSubformula().asGloballyFormula().getSubformula().isBinaryBooleanStateFormula()); + auto const &nested3Subformula = nested3.asNextFormula().getSubformula().asGloballyFormula().getSubformula().asBinaryBooleanStateFormula(); + ASSERT_TRUE(nested3Subformula.getLeftSubformula().isBinaryBooleanStateFormula()); + ASSERT_TRUE(nested3Subformula.asBinaryBooleanStateFormula().getRightSubformula().isAtomicLabelFormula()); + + input = "P<0.9 [ X F \"a\" | ! \"b\" & \"c\"] "; // & has precedence over | and ! over & + ASSERT_NO_THROW(formula = formulaParser.parseSingleFormulaFromString(input)); + auto const &nested4 = formula->asProbabilityOperatorFormula().getSubformula(); + EXPECT_TRUE(nested4.asNextFormula().getSubformula().isEventuallyFormula()); + EXPECT_TRUE(nested4.asNextFormula().getSubformula().asEventuallyFormula().getSubformula().isBinaryBooleanStateFormula()); + auto const &nested4Subformula = nested4.asNextFormula().getSubformula().asEventuallyFormula().getSubformula().asBinaryBooleanStateFormula(); + ASSERT_TRUE(nested4Subformula.getLeftSubformula().isAtomicLabelFormula()); + ASSERT_TRUE(nested4Subformula.getRightSubformula().isBinaryBooleanStateFormula()); + + input = "P<0.9 [X \"a\" | F \"b\"]"; // X (a | F b) + ASSERT_NO_THROW(formula = formulaParser.parseSingleFormulaFromString(input)); + auto const &nested5 = formula->asProbabilityOperatorFormula().getSubformula(); + EXPECT_TRUE(nested5.isNextFormula()); + EXPECT_TRUE(nested5.asNextFormula().getSubformula().isBinaryBooleanPathFormula()); + EXPECT_TRUE(nested5.asNextFormula().getSubformula().asBinaryPathFormula().getLeftSubformula().isAtomicLabelFormula()); + EXPECT_TRUE(nested5.asNextFormula().getSubformula().asBinaryPathFormula().getRightSubformula().isEventuallyFormula()); + + input = "P<0.9 [F \"a\" | G \"b\" | X \"c\" ]"; // F (a | G (b | X c)) + ASSERT_NO_THROW(formula = formulaParser.parseSingleFormulaFromString(input)); + auto const &nested6 = formula->asProbabilityOperatorFormula().getSubformula(); + EXPECT_TRUE(nested6.isEventuallyFormula()); + EXPECT_TRUE(nested6.asEventuallyFormula().getSubformula().isBinaryBooleanPathFormula()); + EXPECT_TRUE(nested6.asEventuallyFormula().getSubformula().asBinaryPathFormula().getLeftSubformula().isAtomicLabelFormula()); + EXPECT_TRUE(nested6.asEventuallyFormula().getSubformula().asBinaryPathFormula().getRightSubformula().isGloballyFormula()); + auto const &nested6Subformula = nested6.asEventuallyFormula().getSubformula().asBinaryPathFormula().getRightSubformula().asGloballyFormula(); +} + +TEST(FormulaParserTest, TemporalPrecedenceTest) { + // Unary operators (F, G and X) have precedence over binary operators (U). + storm::parser::FormulaParser formulaParser; + std::shared_ptr<storm::logic::Formula const> formula(nullptr); + + std::string input = "P=? [ F \"a\" U G \"b\" ]"; // (F a) U (G b) + ASSERT_NO_THROW(formula = formulaParser.parseSingleFormulaFromString(input)); + auto const &nested1 = formula->asProbabilityOperatorFormula().getSubformula(); + EXPECT_TRUE(nested1.isUntilFormula()); + ASSERT_TRUE(nested1.asUntilFormula().getLeftSubformula().isEventuallyFormula()); + ASSERT_TRUE(nested1.asUntilFormula().getRightSubformula().isGloballyFormula()); + + input = "P=? [ X ( F \"a\" U G \"b\") U G \"c\"]"; // X((F a) U (G b)) U (G c) + ASSERT_NO_THROW(formula = formulaParser.parseSingleFormulaFromString(input)); + auto const &nested2 = formula->asProbabilityOperatorFormula().getSubformula(); + EXPECT_TRUE(nested2.isUntilFormula()); + EXPECT_TRUE(nested2.asUntilFormula().getLeftSubformula().isNextFormula()); + EXPECT_TRUE(nested2.asUntilFormula().getLeftSubformula().asNextFormula().getSubformula().isUntilFormula()); + EXPECT_TRUE(nested2.asUntilFormula().getRightSubformula().isGloballyFormula()); + + input = "P=? [ X F \"a\" U (G \"b\" U G \"c\")]"; // (XF a) U ((G b) U (G c)) + ASSERT_NO_THROW(formula = formulaParser.parseSingleFormulaFromString(input)); + auto const &nested3 = formula->asProbabilityOperatorFormula().getSubformula(); + EXPECT_TRUE(nested3.isUntilFormula()); + EXPECT_TRUE(nested3.asUntilFormula().getLeftSubformula().isNextFormula()); + EXPECT_TRUE(nested3.asUntilFormula().getLeftSubformula().asNextFormula().getSubformula().isEventuallyFormula()); + EXPECT_TRUE(nested3.asUntilFormula().getRightSubformula().isUntilFormula()); + EXPECT_TRUE(nested3.asUntilFormula().getRightSubformula().asUntilFormula().getLeftSubformula().isGloballyFormula()); + EXPECT_TRUE(nested3.asUntilFormula().getRightSubformula().asUntilFormula().getRightSubformula().isGloballyFormula()); +} + +TEST(FormulaParserTest, TemporalNegationTest) { + storm::parser::FormulaParser formulaParser; + std::shared_ptr<storm::logic::Formula const> formula(nullptr); + + std::string input = "P<0.9 [ ! X \"a\" | \"b\"]"; + ASSERT_NO_THROW(formula = formulaParser.parseSingleFormulaFromString(input)); + auto const &nested1 = formula->asProbabilityOperatorFormula().getSubformula(); + EXPECT_TRUE(nested1.isUnaryBooleanPathFormula()); + EXPECT_TRUE(nested1.asUnaryPathFormula().getSubformula().isNextFormula()); + EXPECT_TRUE(nested1.asUnaryPathFormula().getSubformula().asNextFormula().getSubformula().isBinaryBooleanStateFormula()); + + input ="P<0.9 [! F ! G \"b\"]"; + ASSERT_NO_THROW(formula = formulaParser.parseSingleFormulaFromString(input)); + auto const &nested2 = formula->asProbabilityOperatorFormula().getSubformula(); + EXPECT_TRUE(nested2.isUnaryBooleanPathFormula()); + EXPECT_TRUE(nested2.asUnaryPathFormula().getSubformula().isEventuallyFormula()); + EXPECT_TRUE(nested2.asUnaryPathFormula().getSubformula().asEventuallyFormula().getSubformula().isUnaryBooleanPathFormula()); + EXPECT_TRUE(nested2.asUnaryPathFormula().getSubformula().asEventuallyFormula().getSubformula().asUnaryPathFormula().getSubformula().isGloballyFormula()); + + input ="P<0.9 [! (\"a\" U \"b\")]"; + ASSERT_NO_THROW(formula = formulaParser.parseSingleFormulaFromString(input)); + auto const &nested3 = formula->asProbabilityOperatorFormula().getSubformula(); + EXPECT_TRUE(nested3.isUnaryBooleanPathFormula()); + EXPECT_TRUE(nested3.asUnaryPathFormula().getSubformula().isUntilFormula()); + +} + +TEST(FormulaParserTest, ComplexPathFormulaTest) { + storm::parser::FormulaParser formulaParser; + std::shared_ptr<storm::logic::Formula const> formula(nullptr); + + std::string input = "P<0.9 [(X !\"a\") & (F ( X \"b\" U G \"c\" & \"d\"))]"; // ((X ! a) & (F ( (X b) U (G (c & d))))) + ASSERT_NO_THROW(formula = formulaParser.parseSingleFormulaFromString(input)); + auto const &nested1 = formula->asProbabilityOperatorFormula().getSubformula(); + EXPECT_TRUE(nested1.asBinaryPathFormula().getRightSubformula().asEventuallyFormula().getSubformula().isUntilFormula()); + auto const nested1Subformula = nested1.asBinaryPathFormula().getRightSubformula().asEventuallyFormula().getSubformula().asUntilFormula(); + EXPECT_TRUE(nested1Subformula.getLeftSubformula().isNextFormula()); + EXPECT_TRUE(nested1Subformula.getRightSubformula().asGloballyFormula().getSubformula().isBinaryBooleanStateFormula()); + + input = "P<0.9 [(F \"a\") & (G \"b\") | (! \"a\" U (F X ! \"b\"))]"; + ASSERT_NO_THROW(formula = formulaParser.parseSingleFormulaFromString(input)); + auto const &nested2 = formula->asProbabilityOperatorFormula().getSubformula(); + ASSERT_TRUE(nested2.asBinaryPathFormula().getLeftSubformula().isBinaryPathFormula()); + ASSERT_TRUE(nested2.asBinaryPathFormula().getRightSubformula().isUntilFormula()); + + input = "P=? [(X \"a\") U ( \"b\"& \"c\")]"; + formula = formulaParser.parseSingleFormulaFromString(input); + ASSERT_NO_THROW(formula = formulaParser.parseSingleFormulaFromString(input)); + auto const &nested3 = formula->asProbabilityOperatorFormula().getSubformula(); + EXPECT_TRUE(nested3.asBinaryPathFormula().isUntilFormula()); + EXPECT_TRUE(nested3.asBinaryPathFormula().getLeftSubformula().isNextFormula()); +} + +TEST(FormulaParserTest, HOAPathFormulaTest) { + std::shared_ptr<storm::expressions::ExpressionManager> manager(new storm::expressions::ExpressionManager()); + manager->declareIntegerVariable("x"); + manager->declareIntegerVariable("y"); + storm::parser::FormulaParser formulaParser(manager); + std::shared_ptr<storm::logic::Formula const> formula(nullptr); + + std::string input = "P=?[HOA: {\"" STORM_TEST_RESOURCES_DIR "/hoa/automaton_Fandp0Xp1.hoa\", \"p0\" -> !\"a\", \"p1\" -> \"b\" | \"c\" }]"; + ASSERT_NO_THROW(formula = formulaParser.parseSingleFormulaFromString(input)); + auto const &nested1 = formula->asProbabilityOperatorFormula().getSubformula(); + EXPECT_TRUE(nested1.isHOAPathFormula()); + EXPECT_TRUE(nested1.isPathFormula()); + + ASSERT_NO_THROW(std::string af = nested1.asHOAPathFormula().getAutomatonFile()); + storm::automata::DeterministicAutomaton::ptr da1; + ASSERT_NO_THROW(da1 = nested1.asHOAPathFormula().readAutomaton()); + EXPECT_EQ(3, da1->getNumberOfStates()); + EXPECT_EQ(4, da1->getNumberOfEdgesPerState()); + + std::map<std::string, std::shared_ptr<storm::logic::Formula const>> apFormulaMap1 = nested1.asHOAPathFormula().getAPMapping(); + EXPECT_TRUE(apFormulaMap1["p0"]->isUnaryBooleanStateFormula()); + EXPECT_TRUE(apFormulaMap1["p1"]->isBinaryBooleanStateFormula()); + + input = "P=?[HOA: {\"" STORM_TEST_RESOURCES_DIR "/hoa/automaton_UXp0p1.hoa\", \"p0\" -> (x < 7) & !(y = 2), \"p1\" -> (x > 0) }]"; + ASSERT_NO_THROW(formula = formulaParser.parseSingleFormulaFromString(input)); + auto const &nested2 = formula->asProbabilityOperatorFormula().getSubformula(); + EXPECT_TRUE(nested2.isHOAPathFormula()); + EXPECT_TRUE(nested2.isPathFormula()); + + ASSERT_NO_THROW(std::string af = nested2.asHOAPathFormula().getAutomatonFile()); + storm::automata::DeterministicAutomaton::ptr da2; + ASSERT_NO_THROW(da2 = nested2.asHOAPathFormula().readAutomaton()); + EXPECT_EQ(4, da2->getNumberOfStates()); + EXPECT_EQ(4, da2->getNumberOfEdgesPerState()); + + std::map<std::string, std::shared_ptr<storm::logic::Formula const>> apFormulaMap2 = nested2.asHOAPathFormula().getAPMapping(); + EXPECT_TRUE(apFormulaMap2["p0"]->isBinaryBooleanStateFormula()); + EXPECT_TRUE(apFormulaMap2["p1"]->isAtomicExpressionFormula()); + + // Wrong format: p1 -> path formula + input = "P=?[HOA: {\"" STORM_TEST_RESOURCES_DIR "/hoa/automaton_UXp0p1.hoa\", \"p0\" -> (x > 0), \"p1\" -> (x < 7) & (X y = 2) }]"; + STORM_SILENT_EXPECT_THROW(formula = formulaParser.parseSingleFormulaFromString(input), storm::exceptions::WrongFormatException); + + // Exception: p1 not assigned + input = "P=?[HOA: {\"" STORM_TEST_RESOURCES_DIR "/hoa/automaton_UXp0p1.hoa\", \"p0\" -> (x > 0)}]"; + ASSERT_NO_THROW(formula = formulaParser.parseSingleFormulaFromString(input)); + auto const &nested3 = formula->asProbabilityOperatorFormula().getSubformula(); + storm::automata::DeterministicAutomaton::ptr da3; + STORM_SILENT_EXPECT_THROW(da3 = nested3.asHOAPathFormula().readAutomaton(), storm::exceptions::ExpressionEvaluationException); +} diff --git a/src/test/storm/transformer/DAProductBuilderTest.cpp b/src/test/storm/transformer/DAProductBuilderTest.cpp new file mode 100644 index 000000000..d5a6e4c63 --- /dev/null +++ b/src/test/storm/transformer/DAProductBuilderTest.cpp @@ -0,0 +1,137 @@ +#include "gtest/gtest.h" +#include "storm-config.h" +#include "storm/models/sparse/Dtmc.h" +#include "storm/models/sparse/StandardRewardModel.h" +#include "storm/models/sparse/MarkovAutomaton.h" +#include "storm/settings/SettingMemento.h" +#include "storm-parsers/parser/PrismParser.h" +#include "storm/builder/ExplicitModelBuilder.h" +#include "storm/automata/DeterministicAutomaton.h" +#include "storm/settings/modules/IOSettings.h" + +#include "storm/storage/BitVector.h" +#include "storm/transformer/DAProductBuilder.h" + +#include <memory> +#include <string> +#include <sstream> + +TEST(DAProductBuilderTest_aUb, Dtmc) { + storm::prism::Program program = storm::parser::PrismParser::parse(STORM_TEST_RESOURCES_DIR "/dtmc/die.pm"); + + std::shared_ptr<storm::models::sparse::Model<double>> model = storm::builder::ExplicitModelBuilder<double>(program).build(); + auto dtmc = std::dynamic_pointer_cast<storm::models::sparse::Dtmc<double>>(model); + + std::string aUb = + "HOA: v1\n" + "States: 3\n" + "Start: 0\n" + "acc-name: Rabin 1\n" + "Acceptance: 2 (Fin(0) & Inf(1))\n" + "AP: 2 \"a\" \"b\"" + "--BODY--\n" + "State: 0 \"a U b\" \n { 0 }\n" + " 2 /* !a & !b */\n" + " 0 /* a & !b */\n" + " 1 /* !a & b */\n" + " 1 /* a & b */\n" + "State: 1 { 1 }\n" + " 1 1 1 1 /* four transitions on one line */\n" + "State: 2 \"sink state\" { 0 }\n" + " 2 2 2 2\n" + "--END--\n"; + + std::istringstream in = std::istringstream(aUb); + storm::automata::DeterministicAutomaton::ptr da; + ASSERT_NO_THROW(da = storm::automata::DeterministicAutomaton::parse(in)); + + std::vector<storm::storage::BitVector> apLabels; + storm::storage::BitVector apA(dtmc->getNumberOfStates(), true); + apA.set(2, false); + storm::storage::BitVector apB(dtmc->getNumberOfStates(), false); + apB.set(7); + + // std::cout << "apA: " << apA << "\n"; + // std::cout << "apB: " << apB << "\n"; + apLabels.push_back(apA); + apLabels.push_back(apB); + + storm::transformer::DAProductBuilder productBuilder(*da, apLabels); + auto product = productBuilder.build(*dtmc, dtmc->getInitialStates()); + + // std::ofstream modelDot("model.dot"); + // dtmc->writeDotToStream(modelDot); + // modelDot.close(); + + // std::ofstream productDot("product.dot"); + // product->getProductModel().writeDotToStream(productDot); + // productDot.close(); + + // product->printMapping(std::cout); + + // for (unsigned int i = 0; i < product->getAcceptance()->getNumberOfAcceptanceSets(); i++) { + // std::cout << i << ": " << product->getAcceptance()->getAcceptanceSet(i) << "\n"; + // } + + storm::storage::StateBlock scc; + scc.insert(7); + ASSERT_EQ(product->getAcceptance()->isAccepting(scc), 1); + scc.insert(8); + ASSERT_EQ(product->getAcceptance()->isAccepting(scc), false); + scc.insert(12); + ASSERT_EQ(product->getAcceptance()->isAccepting(scc), false); +} + +TEST(DAProductBuilderTest_aWb, Dtmc) { + storm::prism::Program program = storm::parser::PrismParser::parse(STORM_TEST_RESOURCES_DIR "/dtmc/die.pm"); + + std::shared_ptr<storm::models::sparse::Model<double>> model = storm::builder::ExplicitModelBuilder<double>(program).build(); + auto dtmc = std::dynamic_pointer_cast<storm::models::sparse::Dtmc<double>>(model); + + std::string aUb = + "HOA: v1\n" + "States: 3\n" + "Start: 0\n" + "acc-name: Rabin 1\n" + "Acceptance: 2 (Fin(0) & Inf(1))\n" + "AP: 2 \"a\" \"b\"" + "--BODY--\n" + "State: 0 \"a U b\" \n" + " 2 /* !a & !b */\n" + " 0 /* a & !b */\n" + " 1 /* !a & b */\n" + " 1 /* a & b */\n" + "State: 1 { 1 }\n" + " 1 1 1 1 /* four transitions on one line */\n" + "State: 2 \"sink state\" { 0 }\n" + " 2 2 2 2\n" + "--END--\n"; + + std::istringstream in = std::istringstream(aUb); + storm::automata::DeterministicAutomaton::ptr da; + ASSERT_NO_THROW(da = storm::automata::DeterministicAutomaton::parse(in)); + + // NOTE: the following relies on the fact that the exploration order of the + // states in the transformation from PRISM program to explicit model is fixed... + // Would be better to add labels and get the corresponding states from those labels + + std::vector<storm::storage::BitVector> apLabels; + storm::storage::BitVector apA(dtmc->getNumberOfStates(), true); + apA.set(2, false); + storm::storage::BitVector apB(dtmc->getNumberOfStates(), false); + apB.set(7); + + apLabels.push_back(apA); + apLabels.push_back(apB); + + storm::transformer::DAProductBuilder productBuilder(*da, apLabels); + auto product = productBuilder.build(*dtmc, dtmc->getInitialStates()); + + storm::storage::StateBlock scc; + scc.insert(7); + ASSERT_EQ(product->getAcceptance()->isAccepting(scc), true); + scc.insert(8); + ASSERT_EQ(product->getAcceptance()->isAccepting(scc), true); + scc.insert(12); + ASSERT_EQ(product->getAcceptance()->isAccepting(scc), false); +} diff --git a/storm-config.h.in b/storm-config.h.in index 78164aa05..d1da99a22 100644 --- a/storm-config.h.in +++ b/storm-config.h.in @@ -85,6 +85,14 @@ #cmakedefine STORM_HAVE_XERCES +// Whether Spot is available and to be used +#cmakedefine STORM_HAVE_SPOT + +// Whether LTL model checking shall be enabled +#ifdef STORM_HAVE_SPOT + #define STORM_HAVE_LTL_MODELCHECKING_SUPPORT +#endif // STORM_HAVE_SPOT + // Whether smtrat is available and to be used. #cmakedefine STORM_HAVE_SMTRAT