From 8d680749cd0b1692c5301d71ba7c71ea7073ade8 Mon Sep 17 00:00:00 2001 From: Joachim Klein <joachim.klein@automata.tools> Date: Mon, 24 Aug 2020 22:24:51 +0200 Subject: [PATCH 001/172] (DA) Add cpphoafparser 0.99.2 Add cpphoafparser 0.99.2 as 3rdparty library (for HOA automata parsing). --- resources/3rdparty/CMakeLists.txt | 10 + .../3rdparty/cpphoafparser-0.99.2/ChangeLog | 24 + .../3rdparty/cpphoafparser-0.99.2/Doxyfile | 2362 +++++++++++++++++ .../cpphoafparser-0.99.2/Doxyfile.all | 2362 +++++++++++++++++ .../3rdparty/cpphoafparser-0.99.2/Makefile | 20 + .../3rdparty/cpphoafparser-0.99.2/README | 63 + .../cpphoafparser-0.99.2/docs/cpp2html.css | 13 + .../docs/cpphoaf-tool.html | 243 ++ .../docs/cpphoafparser-library.html | 183 ++ .../docs/cpphoafparser.css | 110 + .../cpphoafparser-0.99.2/docs/index.html | 145 + .../cpphoafparser/ast/atom_acceptance.hh | 115 + .../include/cpphoafparser/ast/atom_label.hh | 120 + .../cpphoafparser/ast/boolean_expression.hh | 302 +++ .../cpphoafparser/consumer/hoa_consumer.hh | 218 ++ .../consumer/hoa_consumer_exception.hh | 48 + .../consumer/hoa_consumer_null.hh | 109 + .../consumer/hoa_consumer_print.hh | 238 ++ .../consumer/hoa_intermediate.hh | 148 ++ .../hoa_intermediate_check_validity.hh | 828 ++++++ .../hoa_intermediate_resolve_aliases.hh | 185 ++ .../consumer/hoa_intermediate_trace.hh | 255 ++ .../include/cpphoafparser/parser/hoa_lexer.hh | 534 ++++ .../cpphoafparser/parser/hoa_parser.hh | 692 +++++ .../parser/hoa_parser_exception.hh | 58 + .../cpphoafparser/parser/hoa_parser_helper.hh | 122 + .../util/acceptance_repository.hh | 77 + .../util/acceptance_repository_standard.hh | 388 +++ .../cpphoafparser/util/dynamic_bitset.hh | 124 + .../util/implicit_edge_helper.hh | 156 ++ .../cpphoafparser/util/int_or_string.hh | 116 + .../cpphoafparser-0.99.2/src/CMakeLists.txt | 15 + .../src/basic_parser_1.cc | 19 + .../src/basic_parser_2.cc | 40 + .../cpphoafparser-0.99.2/src/cpphoaf.cc | 203 ++ 35 files changed, 10645 insertions(+) create mode 100644 resources/3rdparty/cpphoafparser-0.99.2/ChangeLog create mode 100644 resources/3rdparty/cpphoafparser-0.99.2/Doxyfile create mode 100644 resources/3rdparty/cpphoafparser-0.99.2/Doxyfile.all create mode 100644 resources/3rdparty/cpphoafparser-0.99.2/Makefile create mode 100644 resources/3rdparty/cpphoafparser-0.99.2/README create mode 100644 resources/3rdparty/cpphoafparser-0.99.2/docs/cpp2html.css create mode 100644 resources/3rdparty/cpphoafparser-0.99.2/docs/cpphoaf-tool.html create mode 100644 resources/3rdparty/cpphoafparser-0.99.2/docs/cpphoafparser-library.html create mode 100644 resources/3rdparty/cpphoafparser-0.99.2/docs/cpphoafparser.css create mode 100644 resources/3rdparty/cpphoafparser-0.99.2/docs/index.html create mode 100644 resources/3rdparty/cpphoafparser-0.99.2/include/cpphoafparser/ast/atom_acceptance.hh create mode 100644 resources/3rdparty/cpphoafparser-0.99.2/include/cpphoafparser/ast/atom_label.hh create mode 100644 resources/3rdparty/cpphoafparser-0.99.2/include/cpphoafparser/ast/boolean_expression.hh create mode 100644 resources/3rdparty/cpphoafparser-0.99.2/include/cpphoafparser/consumer/hoa_consumer.hh create mode 100644 resources/3rdparty/cpphoafparser-0.99.2/include/cpphoafparser/consumer/hoa_consumer_exception.hh create mode 100644 resources/3rdparty/cpphoafparser-0.99.2/include/cpphoafparser/consumer/hoa_consumer_null.hh create mode 100644 resources/3rdparty/cpphoafparser-0.99.2/include/cpphoafparser/consumer/hoa_consumer_print.hh create mode 100644 resources/3rdparty/cpphoafparser-0.99.2/include/cpphoafparser/consumer/hoa_intermediate.hh create mode 100644 resources/3rdparty/cpphoafparser-0.99.2/include/cpphoafparser/consumer/hoa_intermediate_check_validity.hh create mode 100644 resources/3rdparty/cpphoafparser-0.99.2/include/cpphoafparser/consumer/hoa_intermediate_resolve_aliases.hh create mode 100644 resources/3rdparty/cpphoafparser-0.99.2/include/cpphoafparser/consumer/hoa_intermediate_trace.hh create mode 100644 resources/3rdparty/cpphoafparser-0.99.2/include/cpphoafparser/parser/hoa_lexer.hh create mode 100644 resources/3rdparty/cpphoafparser-0.99.2/include/cpphoafparser/parser/hoa_parser.hh create mode 100644 resources/3rdparty/cpphoafparser-0.99.2/include/cpphoafparser/parser/hoa_parser_exception.hh create mode 100644 resources/3rdparty/cpphoafparser-0.99.2/include/cpphoafparser/parser/hoa_parser_helper.hh create mode 100644 resources/3rdparty/cpphoafparser-0.99.2/include/cpphoafparser/util/acceptance_repository.hh create mode 100644 resources/3rdparty/cpphoafparser-0.99.2/include/cpphoafparser/util/acceptance_repository_standard.hh create mode 100644 resources/3rdparty/cpphoafparser-0.99.2/include/cpphoafparser/util/dynamic_bitset.hh create mode 100644 resources/3rdparty/cpphoafparser-0.99.2/include/cpphoafparser/util/implicit_edge_helper.hh create mode 100644 resources/3rdparty/cpphoafparser-0.99.2/include/cpphoafparser/util/int_or_string.hh create mode 100644 resources/3rdparty/cpphoafparser-0.99.2/src/CMakeLists.txt create mode 100644 resources/3rdparty/cpphoafparser-0.99.2/src/basic_parser_1.cc create mode 100644 resources/3rdparty/cpphoafparser-0.99.2/src/basic_parser_2.cc create mode 100644 resources/3rdparty/cpphoafparser-0.99.2/src/cpphoaf.cc diff --git a/resources/3rdparty/CMakeLists.txt b/resources/3rdparty/CMakeLists.txt index a9d9f9400..50a220135 100644 --- a/resources/3rdparty/CMakeLists.txt +++ b/resources/3rdparty/CMakeLists.txt @@ -139,6 +139,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 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..554404c95 --- /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) { + 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) { + 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() { + // 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() { + 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..1d0a4ebdf --- /dev/null +++ b/resources/3rdparty/cpphoafparser-0.99.2/include/cpphoafparser/parser/hoa_parser_exception.hh @@ -0,0 +1,58 @@ +//============================================================================== +// +// 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> + +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) {} + +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..3bf37f23e --- /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(false) {} + + /** 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; +} + + From de0dd71679ccfff4027595773225b565d49a8245 Mon Sep 17 00:00:00 2001 From: Joachim Klein <joachim.klein@automata.tools> Date: Mon, 24 Aug 2020 22:24:54 +0200 Subject: [PATCH 002/172] (DA) Automata classes: DeterministicAutomaton, APSet, HOAConsumer, AcceptanceCondition Adapted from ltl2dstar. --- src/storm/automata/APSet.cpp | 65 +++++ src/storm/automata/APSet.h | 33 +++ src/storm/automata/AcceptanceCondition.cpp | 100 ++++++++ src/storm/automata/AcceptanceCondition.h | 36 +++ src/storm/automata/DeterministicAutomaton.cpp | 103 ++++++++ src/storm/automata/DeterministicAutomaton.h | 46 ++++ src/storm/automata/HOAConsumerDA.h | 237 ++++++++++++++++++ src/storm/automata/HOAConsumerDAHeader.h | 217 ++++++++++++++++ src/storm/automata/HOAHeader.h | 26 ++ 9 files changed, 863 insertions(+) create mode 100644 src/storm/automata/APSet.cpp create mode 100644 src/storm/automata/APSet.h create mode 100644 src/storm/automata/AcceptanceCondition.cpp create mode 100644 src/storm/automata/AcceptanceCondition.h create mode 100644 src/storm/automata/DeterministicAutomaton.cpp create mode 100644 src/storm/automata/DeterministicAutomaton.h create mode 100644 src/storm/automata/HOAConsumerDA.h create mode 100644 src/storm/automata/HOAConsumerDAHeader.h create mode 100644 src/storm/automata/HOAHeader.h diff --git a/src/storm/automata/APSet.cpp b/src/storm/automata/APSet.cpp new file mode 100644 index 000000000..937207215 --- /dev/null +++ b/src/storm/automata/APSet.cpp @@ -0,0 +1,65 @@ + +#include "storm/automata/APSet.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) { + if (size() >= MAX_APS) + throw std::runtime_error("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; + if (!fresh) + throw std::runtime_error("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 { + if (ap >= size()) { + throw std::runtime_error("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..4f0a7a02a --- /dev/null +++ b/src/storm/automata/AcceptanceCondition.cpp @@ -0,0 +1,100 @@ +#include "AcceptanceCondition.h" + +namespace storm { +namespace automata { + +AcceptanceCondition::AcceptanceCondition(std::size_t numberOfStates, unsigned int numberOfAcceptanceSets, acceptance_expr::ptr acceptance) + : numberOfStates(numberOfStates), 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"); +} + +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..7f1b993c8 --- /dev/null +++ b/src/storm/automata/AcceptanceCondition.h @@ -0,0 +1,36 @@ +#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; + private: + bool isAccepting(const storm::storage::StateBlock& scc, acceptance_expr::ptr expr) const; + + std::size_t numberOfStates; + 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..62ae6c043 --- /dev/null +++ b/src/storm/automata/DeterministicAutomaton.cpp @@ -0,0 +1,103 @@ +#include "storm/automata/DeterministicAutomaton.h" +#include "storm/automata/AcceptanceCondition.h" +#include "storm/automata/HOAConsumerDA.h" +#include "cpphoafparser/parser/hoa_parser.hh" +#include "cpphoafparser/parser/hoa_parser_helper.hh" +#include "cpphoafparser/consumer/hoa_intermediate_check_validity.hh" + +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); + return parse(in); + } + + } +} + + + 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..4d12c0082 --- /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)); + } + + }; + } +} From 3696e1373688e1bac9b7cc3488d4f8773dd158f2 Mon Sep 17 00:00:00 2001 From: Joachim Klein <joachim.klein@automata.tools> Date: Mon, 24 Aug 2020 22:24:57 +0200 Subject: [PATCH 003/172] (DA) ItemLabeling: addUniqueLabel, generateUniqueLabel For model-automaton product constructions, we would like to add automatically generated labels to the result, so we need a way to ensure that we can get those without clashing with existing labels. --- src/storm/models/sparse/ItemLabeling.cpp | 24 ++++++++++++++++++++ src/storm/models/sparse/ItemLabeling.h | 29 ++++++++++++++++++++++++ 2 files changed, 53 insertions(+) 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 From e5282708dd01cc89131c8b5b446e44c44d265247 Mon Sep 17 00:00:00 2001 From: Joachim Klein <joachim.klein@automata.tools> Date: Mon, 24 Aug 2020 22:24:57 +0200 Subject: [PATCH 004/172] (DA-product) transformer: Product, DAProduct + builders --- src/storm/transformer/DAProduct.h | 27 ++++++ src/storm/transformer/DAProductBuilder.h | 55 ++++++++++++ src/storm/transformer/Product.h | 89 +++++++++++++++++++ src/storm/transformer/ProductBuilder.h | 105 +++++++++++++++++++++++ 4 files changed, 276 insertions(+) create mode 100644 src/storm/transformer/DAProduct.h create mode 100644 src/storm/transformer/DAProductBuilder.h create mode 100644 src/storm/transformer/Product.h create mode 100644 src/storm/transformer/ProductBuilder.h 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..9e903e058 --- /dev/null +++ b/src/storm/transformer/DAProductBuilder.h @@ -0,0 +1,55 @@ +#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 { + typename Product<Model>::ptr product = ProductBuilder<Model>::buildProduct(originalModel, *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 modelFrom, + 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..d0d826d0f --- /dev/null +++ b/src/storm/transformer/Product.h @@ -0,0 +1,89 @@ +#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; + } + + 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) { + std::vector<ValueType> origValues(originalModel.getNumberOfStates()); + 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..bf047db14 --- /dev/null +++ b/src/storm/transformer/ProductBuilder.h @@ -0,0 +1,105 @@ +#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 Model& originalModel, ProductOperator& prodOp, const storm::storage::BitVector& statesOfInterest) { + const matrix_type& originalMatrix = originalModel.getTransitionMatrix(); + 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); + 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.first, 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 { + throw std::runtime_error("nondeterministic product not yet supported"); + } + } + + 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))); + } + }; + } +} From 044074a4b1ce7e92e44d476c413a8c0ef60123c6 Mon Sep 17 00:00:00 2001 From: Stefan Pranger <stefan.pranger@student.tugraz.at> Date: Sat, 7 Aug 2021 19:10:58 +0200 Subject: [PATCH 005/172] (DA) tests: HOAParsingTest --- src/test/storm/CMakeLists.txt | 2 +- src/test/storm/automata/HOAParsingTest.cpp | 31 ++++++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) create mode 100644 src/test/storm/automata/HOAParsingTest.cpp diff --git a/src/test/storm/CMakeLists.txt b/src/test/storm/CMakeLists.txt index d99806231..ccf090674 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 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); +} From 85a408dd7210e5b8418b630c4f6def9f60394b95 Mon Sep 17 00:00:00 2001 From: Joachim Klein <joachim.klein@automata.tools> Date: Mon, 24 Aug 2020 22:24:59 +0200 Subject: [PATCH 006/172] (DA-product) tests: DAProductBuilderTest --- .../transformer/DAProductBuilderTest.cpp | 137 ++++++++++++++++++ 1 file changed, 137 insertions(+) create mode 100644 src/test/storm/transformer/DAProductBuilderTest.cpp 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); +} From 21b9d7381648401aefe3dd9adf562575076fb413 Mon Sep 17 00:00:00 2001 From: Joachim Klein <joachim.klein@automata.tools> Date: Mon, 24 Aug 2020 22:24:55 +0200 Subject: [PATCH 007/172] WIP (HOA-path) logic: HOAPathFormula Note: syntax of the HOA path formula will change! We have added checks for boundedGloballyFormulae hence the conflicts Conflicts: src/storm/logic/CloneVisitor.cpp src/storm/logic/Formula.cpp src/storm/logic/Formula.h src/storm/logic/FragmentSpecification.cpp src/storm/logic/FragmentSpecification.h src/storm/logic/LiftableTransitionRewardsVisitor.cpp src/storm/storage/jani/JSONExporter.cpp --- src/storm/logic/CloneVisitor.cpp | 8 ++ src/storm/logic/CloneVisitor.h | 1 + src/storm/logic/Formula.cpp | 12 +++ src/storm/logic/Formula.h | 79 ++++++++-------- src/storm/logic/FormulaInformationVisitor.cpp | 8 ++ src/storm/logic/FormulaInformationVisitor.h | 1 + src/storm/logic/FormulaVisitor.h | 1 + src/storm/logic/Formulas.h | 1 + src/storm/logic/FormulasForwardDeclarations.h | 1 + src/storm/logic/FragmentChecker.cpp | 10 +++ src/storm/logic/FragmentChecker.h | 1 + src/storm/logic/FragmentSpecification.cpp | 10 +++ src/storm/logic/FragmentSpecification.h | 4 + src/storm/logic/HOAPathFormula.cpp | 90 +++++++++++++++++++ src/storm/logic/HOAPathFormula.h | 54 +++++++++++ .../LiftableTransitionRewardsVisitor.cpp | 9 ++ .../logic/LiftableTransitionRewardsVisitor.h | 1 + src/storm/logic/ToExpressionVisitor.cpp | 3 + src/storm/logic/ToExpressionVisitor.h | 1 + src/storm/storage/jani/JSONExporter.cpp | 4 + src/storm/storage/jani/JSONExporter.h | 1 + 21 files changed, 262 insertions(+), 38 deletions(-) create mode 100644 src/storm/logic/HOAPathFormula.cpp create mode 100644 src/storm/logic/HOAPathFormula.h diff --git a/src/storm/logic/CloneVisitor.cpp b/src/storm/logic/CloneVisitor.cpp index 57c8ce377..15499c9d9 100644 --- a/src/storm/logic/CloneVisitor.cpp +++ b/src/storm/logic/CloneVisitor.cpp @@ -176,5 +176,13 @@ namespace storm { 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..954d46db4 100644 --- a/src/storm/logic/CloneVisitor.h +++ b/src/storm/logic/CloneVisitor.h @@ -35,6 +35,7 @@ namespace storm { 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(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/Formula.cpp b/src/storm/logic/Formula.cpp index b4e6c13bc..553e15b89 100644 --- a/src/storm/logic/Formula.cpp +++ b/src/storm/logic/Formula.cpp @@ -83,6 +83,10 @@ namespace storm { return false; } + bool Formula::isHOAPathFormula() const { + return false; + } + bool Formula::isBinaryPathFormula() const { return false; } @@ -289,6 +293,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); } diff --git a/src/storm/logic/Formula.h b/src/storm/logic/Formula.h index 62aab0dde..0014baef4 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,14 @@ 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 isMultiObjectiveFormula() const; virtual bool isQuantileFormula() const; @@ -95,34 +95,34 @@ namespace storm { // 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; 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 +131,28 @@ 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; + 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 +164,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 +185,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 +231,10 @@ 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; - + 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 +243,7 @@ namespace storm { private: // Currently empty. }; - + std::ostream& operator<<(std::ostream& out, Formula const& formula); } } diff --git a/src/storm/logic/FormulaInformationVisitor.cpp b/src/storm/logic/FormulaInformationVisitor.cpp index 41417eeed..471503e2a 100644 --- a/src/storm/logic/FormulaInformationVisitor.cpp +++ b/src/storm/logic/FormulaInformationVisitor.cpp @@ -134,5 +134,13 @@ namespace storm { return boost::any_cast<FormulaInformation>(f.getLeftSubformula().accept(*this, data)).join(boost::any_cast<FormulaInformation>(f.getRightSubformula().accept(*this))); } + boost::any FormulaInformationVisitor::visit(HOAPathFormula const& f, boost::any const& data) const { + FormulaInformation info; + 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..a1f3a3fb0 100644 --- a/src/storm/logic/FormulaInformationVisitor.h +++ b/src/storm/logic/FormulaInformationVisitor.h @@ -34,6 +34,7 @@ namespace storm { 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(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/FormulaVisitor.h b/src/storm/logic/FormulaVisitor.h index 23673ff50..b1c6db105 100644 --- a/src/storm/logic/FormulaVisitor.h +++ b/src/storm/logic/FormulaVisitor.h @@ -35,6 +35,7 @@ namespace storm { 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(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..47ceae22a 100644 --- a/src/storm/logic/Formulas.h +++ b/src/storm/logic/Formulas.h @@ -28,6 +28,7 @@ #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..41aca3c3b 100644 --- a/src/storm/logic/FormulasForwardDeclarations.h +++ b/src/storm/logic/FormulasForwardDeclarations.h @@ -36,6 +36,7 @@ namespace storm { class UnaryPathFormula; class UnaryStateFormula; class UntilFormula; + class HOAPathFormula; } } diff --git a/src/storm/logic/FragmentChecker.cpp b/src/storm/logic/FragmentChecker.cpp index df79d22a5..0c76dec44 100644 --- a/src/storm/logic/FragmentChecker.cpp +++ b/src/storm/logic/FragmentChecker.cpp @@ -322,5 +322,15 @@ 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(); + // TODO: check + 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..e027f7c46 100644 --- a/src/storm/logic/FragmentChecker.h +++ b/src/storm/logic/FragmentChecker.h @@ -35,6 +35,7 @@ namespace storm { 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(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..445ae0b8c 100644 --- a/src/storm/logic/FragmentSpecification.cpp +++ b/src/storm/logic/FragmentSpecification.cpp @@ -168,6 +168,7 @@ namespace storm { nextFormula = false; untilFormula = false; boundedUntilFormula = false; + hoaPathFormula = false; atomicExpressionFormula = false; atomicLabelFormula = false; @@ -326,6 +327,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; } diff --git a/src/storm/logic/FragmentSpecification.h b/src/storm/logic/FragmentSpecification.h index f097e940f..5f656695e 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); @@ -180,6 +183,7 @@ namespace storm { bool untilFormula; bool boundedUntilFormula; bool boundedGloballyFormula; + bool hoaPathFormula; bool atomicExpressionFormula; bool atomicLabelFormula; diff --git a/src/storm/logic/HOAPathFormula.cpp b/src/storm/logic/HOAPathFormula.cpp new file mode 100644 index 000000000..915f4f13d --- /dev/null +++ b/src/storm/logic/HOAPathFormula.cpp @@ -0,0 +1,90 @@ +#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" +#include "storm/exceptions/FileIoException.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; + } + + 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_LOG_THROW(in.good(), storm::exceptions::FileIoException, "Can not open '" << automatonFile << "' for reading."); + 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) const { + 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..81352243e --- /dev/null +++ b/src/storm/logic/HOAPathFormula.h @@ -0,0 +1,54 @@ +#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 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) 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/LiftableTransitionRewardsVisitor.cpp b/src/storm/logic/LiftableTransitionRewardsVisitor.cpp index a61dccf7c..5a0219242 100644 --- a/src/storm/logic/LiftableTransitionRewardsVisitor.cpp +++ b/src/storm/logic/LiftableTransitionRewardsVisitor.cpp @@ -147,6 +147,15 @@ namespace storm { 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..db5530cad 100644 --- a/src/storm/logic/LiftableTransitionRewardsVisitor.h +++ b/src/storm/logic/LiftableTransitionRewardsVisitor.h @@ -41,6 +41,7 @@ namespace storm { 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(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/ToExpressionVisitor.cpp b/src/storm/logic/ToExpressionVisitor.cpp index 1e6852d84..41688ad8e 100644 --- a/src/storm/logic/ToExpressionVisitor.cpp +++ b/src/storm/logic/ToExpressionVisitor.cpp @@ -129,5 +129,8 @@ namespace storm { 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..eb7e261f2 100644 --- a/src/storm/logic/ToExpressionVisitor.h +++ b/src/storm/logic/ToExpressionVisitor.h @@ -35,6 +35,7 @@ namespace storm { 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(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/storage/jani/JSONExporter.cpp b/src/storm/storage/jani/JSONExporter.cpp index 2e900bb92..f89e1cab5 100644 --- a/src/storm/storage/jani/JSONExporter.cpp +++ b/src/storm/storage/jani/JSONExporter.cpp @@ -596,6 +596,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; diff --git a/src/storm/storage/jani/JSONExporter.h b/src/storm/storage/jani/JSONExporter.h index cee374f02..c14524f69 100644 --- a/src/storm/storage/jani/JSONExporter.h +++ b/src/storm/storage/jani/JSONExporter.h @@ -72,6 +72,7 @@ namespace storm { 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::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) { } From aed8e53a29d7294a87ccfcadee3e889e0fd822c8 Mon Sep 17 00:00:00 2001 From: Joachim Klein <joachim.klein@automata.tools> Date: Mon, 24 Aug 2020 22:24:56 +0200 Subject: [PATCH 008/172] (HOA-path) AbstractModelChecker: default handling for HOAPathFormulas (= reject) Conflicts: src/storm/modelchecker/AbstractModelChecker.h --- src/storm/modelchecker/AbstractModelChecker.cpp | 7 +++++++ src/storm/modelchecker/AbstractModelChecker.h | 17 +++++++++-------- 2 files changed, 16 insertions(+), 8 deletions(-) diff --git a/src/storm/modelchecker/AbstractModelChecker.cpp b/src/storm/modelchecker/AbstractModelChecker.cpp index 803ddc711..c4e485d89 100644 --- a/src/storm/modelchecker/AbstractModelChecker.cpp +++ b/src/storm/modelchecker/AbstractModelChecker.cpp @@ -73,6 +73,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 +120,11 @@ 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>::computeRewards(Environment const& env, storm::logic::RewardMeasureType rewardMeasureType, CheckTask<storm::logic::Formula, ValueType> const& checkTask) { storm::logic::Formula const& rewardFormula = checkTask.getFormula(); diff --git a/src/storm/modelchecker/AbstractModelChecker.h b/src/storm/modelchecker/AbstractModelChecker.h index 578b83f15..29a5735f5 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,7 @@ 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); // 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 +73,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); From ba907a1d757fb8390da266b3d5a7a8e3662dd45a Mon Sep 17 00:00:00 2001 From: Joachim Klein <joachim.klein@automata.tools> Date: Mon, 24 Aug 2020 22:24:56 +0200 Subject: [PATCH 009/172] WIP (HOA-path) FormulaParser: parse HOAPathFormula Note: Syntax of HOA path formulas will change! Conflicts: src/storm-parsers/parser/FormulaParserGrammar.cpp src/storm-parsers/parser/FormulaParserGrammar.h --- .../parser/FormulaParserGrammar.cpp | 29 ++++++++++++++++++- .../parser/FormulaParserGrammar.h | 7 +++++ 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/src/storm-parsers/parser/FormulaParserGrammar.cpp b/src/storm-parsers/parser/FormulaParserGrammar.cpp index 3aba843be..57e18295e 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 { @@ -73,8 +75,17 @@ namespace storm { 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)]; + + hoaPathFormula = qi::lit("HOA:") > qi::lit("{") + > quotedString[qi::_val = phoenix::bind(&FormulaParserGrammar::createHOAPathFormula, phoenix::ref(*this), qi::_1)] + >> *(qi::lit(",") > quotedString > qi::lit("->") > stateFormula )[phoenix::bind(&FormulaParserGrammar::addHoaAPMapping, phoenix::ref(*this), *qi::_val, qi::_1, qi::_2)] + > qi::lit("}"); + + basicPathFormula = (hoaPathFormula(qi::_r1)[qi::_val = qi::_1]) | untilFormula(qi::_r1)[qi::_val = qi::_1]; + basicPathFormula.name("basic path formula"); + + conditionalFormula = basicPathFormula(qi::_r1)[qi::_val = qi::_1] >> *(qi::lit("||") >> basicPathFormula(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)] @@ -159,6 +170,9 @@ namespace storm { stateFormula = (orStateFormula | multiFormula | quantileFormula | gameFormula); stateFormula.name("state formula"); + quotedString %= qi::as_string[qi::lexeme[qi::omit[qi::char_('"')] > qi::raw[*(!qi::char_('"') >> qi::char_)] > qi::omit[qi::lit('"')]]]; + quotedString.name("quoted string"); + formulaName = qi::lit("\"") >> identifier >> qi::lit("\"") >> qi::lit(":"); formulaName.name("formula name"); @@ -221,6 +235,8 @@ namespace storm { 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>(hoaPathFormula, 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>(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)); @@ -377,6 +393,17 @@ namespace storm { } } + 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, 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)); } diff --git a/src/storm-parsers/parser/FormulaParserGrammar.h b/src/storm-parsers/parser/FormulaParserGrammar.h index 35ac56b6b..c40842532 100644 --- a/src/storm-parsers/parser/FormulaParserGrammar.h +++ b/src/storm-parsers/parser/FormulaParserGrammar.h @@ -152,6 +152,7 @@ namespace storm { 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, std::string(), Skipper> quotedString; 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; @@ -187,6 +188,11 @@ namespace storm { 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; + 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> hoaPathFormula; + + void addHoaAPMapping(storm::logic::Formula const& hoaFormula, const std::string& ap, std::shared_ptr<storm::logic::Formula const>& expression) const; + 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; @@ -236,6 +242,7 @@ namespace storm { 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> 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> createHOAPathFormula(const std::string& automataFile) const; 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; 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> createLongRunAverageOperatorFormula(storm::logic::OperatorInformation const& operatorInformation, std::shared_ptr<storm::logic::Formula const> const& subformula) const; From ad774e5138594bc67c3cd64ff454f500ee2fa3ee Mon Sep 17 00:00:00 2001 From: Joachim Klein <joachim.klein@automata.tools> Date: Mon, 24 Aug 2020 22:24:56 +0200 Subject: [PATCH 010/172] WIP (HOA-path) FormulaParser: parse HOAPathFormula Note: Syntax of HOA path formulas will change! Conflicts: src/storm-parsers/parser/FormulaParserGrammar.cpp src/storm-parsers/parser/FormulaParserGrammar.h --- src/storm-parsers/parser/FormulaParserGrammar.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/src/storm-parsers/parser/FormulaParserGrammar.cpp b/src/storm-parsers/parser/FormulaParserGrammar.cpp index 57e18295e..95a27d70c 100644 --- a/src/storm-parsers/parser/FormulaParserGrammar.cpp +++ b/src/storm-parsers/parser/FormulaParserGrammar.cpp @@ -75,7 +75,6 @@ namespace storm { 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)]; hoaPathFormula = qi::lit("HOA:") > qi::lit("{") > quotedString[qi::_val = phoenix::bind(&FormulaParserGrammar::createHOAPathFormula, phoenix::ref(*this), qi::_1)] From 256f9839da6fdc88be3f9c3b3eaf737a5cd96ccf Mon Sep 17 00:00:00 2001 From: Joachim Klein <joachim.klein@automata.tools> Date: Thu, 27 Aug 2020 06:35:10 +0200 Subject: [PATCH 011/172] SparseDtmcPrctlModelChecker: computeDAProductProbabilities() --- .../prctl/helper/SparseDtmcPrctlHelper.cpp | 98 +++++++++++++++++++ .../prctl/helper/SparseDtmcPrctlHelper.h | 18 +++- 2 files changed, 113 insertions(+), 3 deletions(-) diff --git a/src/storm/modelchecker/prctl/helper/SparseDtmcPrctlHelper.cpp b/src/storm/modelchecker/prctl/helper/SparseDtmcPrctlHelper.cpp index 7139684a2..2bcc9478a 100644 --- a/src/storm/modelchecker/prctl/helper/SparseDtmcPrctlHelper.cpp +++ b/src/storm/modelchecker/prctl/helper/SparseDtmcPrctlHelper.cpp @@ -6,6 +6,8 @@ #include "storm/utility/vector.h" #include "storm/utility/graph.h" +#include "storm/models/sparse/Dtmc.h" + #include "storm/storage/StronglyConnectedComponentDecomposition.h" #include "storm/storage/DynamicPriorityQueue.h" #include "storm/storage/ConsecutiveUint64DynamicPriorityQueue.h" @@ -20,9 +22,12 @@ #include "storm/environment/solver/SolverEnvironment.h" +#include "storm/transformer/DAProductBuilder.h" + #include "storm/settings/SettingsManager.h" #include "storm/settings/modules/GeneralSettings.h" #include "storm/settings/modules/CoreSettings.h" +#include "storm/settings/modules/DebugSettings.h" #include "storm/settings/modules/IOSettings.h" #include "storm/settings/modules/ModelCheckerSettings.h" @@ -40,6 +45,7 @@ #include "storm/exceptions/UncheckedRequirementException.h" #include "storm/exceptions/NotSupportedException.h" + namespace storm { namespace modelchecker { namespace helper { @@ -308,6 +314,98 @@ namespace storm { return result; } + template<typename ValueType, typename RewardModelType> + std::vector<ValueType> SparseDtmcPrctlHelper<ValueType, RewardModelType>::computeDAProductProbabilities(Environment const& env, typename storm::models::sparse::Dtmc<ValueType,RewardModelType> const& dtmc, storm::solver::SolveGoal<ValueType>&& goal, storm::automata::DeterministicAutomaton const& da, std::map<std::string, storm::storage::BitVector>& apSatSets, bool qualitative) { + const storm::automata::APSet& apSet = da.getAPSet(); + + std::vector<storm::storage::BitVector> apLabels; + 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"); + + apLabels.push_back(std::move(it->second)); + } + + storm::storage::BitVector statesOfInterest; + if (goal.hasRelevantValues()) { + statesOfInterest = goal.relevantValues(); + } else { + // product from all model states + statesOfInterest = storm::storage::BitVector(dtmc.getNumberOfStates(), true); + } + + STORM_LOG_INFO("Building DTMC-DA product with deterministic automaton, starting from " << statesOfInterest.getNumberOfSetBits() << " model states..."); + storm::transformer::DAProductBuilder productBuilder(da, apLabels); + auto product = productBuilder.build(dtmc, statesOfInterest); + STORM_LOG_INFO("Product DTMC has " << product->getProductModel().getNumberOfStates() << " states and " + << product->getProductModel().getNumberOfTransitions() << " transitions."); + + if (storm::settings::getModule<storm::settings::modules::DebugSettings>().isTraceSet()) { + STORM_LOG_TRACE("Writing model to model.dot"); + std::ofstream modelDot("model.dot"); + dtmc.writeDotToStream(modelDot); + modelDot.close(); + + STORM_LOG_TRACE("Writing product model to product.dot"); + std::ofstream productDot("product.dot"); + product->getProductModel().writeDotToStream(productDot); + productDot.close(); + + STORM_LOG_TRACE("Product model mapping:"); + std::stringstream str; + product->printMapping(str); + STORM_LOG_TRACE(str.str()); + } + + STORM_LOG_INFO("Computing BSCCs and checking for acceptance..."); + + storm::storage::StronglyConnectedComponentDecomposition<ValueType> bottomSccs(product->getProductModel().getTransitionMatrix(), + storage::StronglyConnectedComponentDecompositionOptions().onlyBottomSccs().dropNaiveSccs()); + storm::storage::BitVector acceptingBSCC(product->getProductModel().getNumberOfStates()); + std::size_t checkedBSCCs = 0, acceptingBSCCs = 0, acceptingBSCCStates = 0; + for (auto& scc : bottomSccs) { + checkedBSCCs++; + if (product->getAcceptance()->isAccepting(scc)) { + acceptingBSCCs++; + for (auto& state : scc) { + acceptingBSCC.set(state); + acceptingBSCCStates++; + } + } + } + + STORM_LOG_INFO("BSCC analysis: " << acceptingBSCCs << " of " << checkedBSCCs << " BSCCs were accepting (" << acceptingBSCCStates << " states in accepting BSCCs)."); + + if (acceptingBSCCs == 0) { + STORM_LOG_INFO("No accepting BSCCs, skipping probability computation."); + std::vector<ValueType> numericResult(dtmc.getNumberOfStates(), storm::utility::zero<ValueType>()); + return numericResult; + } + + STORM_LOG_INFO("Computing probabilities for reaching accepting BSCCs..."); + + storm::storage::BitVector bvTrue(product->getProductModel().getNumberOfStates(), true); + + storm::solver::SolveGoal<ValueType> solveGoalProduct(goal); + storm::storage::BitVector soiProduct(product->getStatesOfInterest()); + solveGoalProduct.setRelevantValues(std::move(soiProduct)); + + std::vector<ValueType> prodNumericResult + = storm::modelchecker::helper::SparseDtmcPrctlHelper<ValueType>::computeUntilProbabilities(env, + std::move(solveGoalProduct), + product->getProductModel().getTransitionMatrix(), + product->getProductModel().getBackwardTransitions(), + bvTrue, + acceptingBSCC, + qualitative); + + std::vector<ValueType> numericResult = product->projectToOriginalModel(dtmc, prodNumericResult); + return numericResult; + } + + + + 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..4af089f9b 100644 --- a/src/storm/modelchecker/prctl/helper/SparseDtmcPrctlHelper.h +++ b/src/storm/modelchecker/prctl/helper/SparseDtmcPrctlHelper.h @@ -16,9 +16,19 @@ #include "storm/solver/SolveGoal.h" namespace storm { - + // fwd class Environment; - + + namespace automata { + class DeterministicAutomaton; + } + + namespace models { + namespace sparse { + template <typename ValueType, typename RewardModelType> class Dtmc; + } + } + namespace modelchecker { class CheckResult; @@ -37,7 +47,9 @@ 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> computeDAProductProbabilities(Environment const& env, typename storm::models::sparse::Dtmc<ValueType,RewardModelType> const& dtmc, storm::solver::SolveGoal<ValueType>&& goal, storm::automata::DeterministicAutomaton const& da, std::map<std::string, storm::storage::BitVector>& apSatSets, 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); From 5482a32b8a177e444d1bcca00908a8f0247053e0 Mon Sep 17 00:00:00 2001 From: Joachim Klein <joachim.klein@automata.tools> Date: Mon, 24 Aug 2020 22:25:00 +0200 Subject: [PATCH 012/172] (LTL) Refactor unary/boolean state formulas to allow path formulas as well Previously, the formula parser only supported AND, OR and NOT over state formulas. For LTL, we need those over path formulas. We tweak the grammar, the AST types and visitors, to also handle UnaryBooleanPathFormula and BinaryBooleanPathformula. During parsing, we determine on-demand whether to generate the path or state formula variant by looking at the subformulas - if they are state formulas, the boolean operator will be a state formula as well. Conflicts: src/storm-parsers/parser/FormulaParserGrammar.cpp src/storm-parsers/parser/FormulaParserGrammar.h src/storm/logic/CloneVisitor.cpp src/storm/logic/Formula.cpp src/storm/logic/Formula.h src/storm/logic/FragmentChecker.cpp src/storm/logic/FragmentSpecification.cpp src/storm/logic/FragmentSpecification.h src/storm/logic/LiftableTransitionRewardsVisitor.cpp src/storm/storage/jani/JSONExporter.cpp --- .../parser/FormulaParserGrammar.cpp | 52 ++++++++++++++----- .../parser/FormulaParserGrammar.h | 16 +++--- src/storm/logic/BinaryBooleanOperatorType.h | 7 +++ src/storm/logic/BinaryBooleanPathFormula.cpp | 47 +++++++++++++++++ src/storm/logic/BinaryBooleanPathFormula.h | 38 ++++++++++++++ src/storm/logic/BinaryBooleanStateFormula.h | 3 +- src/storm/logic/CloneVisitor.cpp | 11 ++++ src/storm/logic/CloneVisitor.h | 2 + src/storm/logic/Formula.cpp | 8 +++ src/storm/logic/Formula.h | 3 ++ src/storm/logic/FormulaInformationVisitor.cpp | 12 ++++- src/storm/logic/FormulaInformationVisitor.h | 2 + src/storm/logic/FormulaVisitor.h | 2 + src/storm/logic/Formulas.h | 2 + src/storm/logic/FormulasForwardDeclarations.h | 2 + src/storm/logic/FragmentChecker.cpp | 15 ++++++ src/storm/logic/FragmentChecker.h | 2 + src/storm/logic/FragmentSpecification.cpp | 19 +++++-- src/storm/logic/FragmentSpecification.h | 8 +++ .../LiftableTransitionRewardsVisitor.cpp | 10 ++++ .../logic/LiftableTransitionRewardsVisitor.h | 2 + src/storm/logic/ToExpressionVisitor.cpp | 10 +++- src/storm/logic/ToExpressionVisitor.h | 2 + src/storm/logic/UnaryBooleanOperatorType.h | 7 +++ src/storm/logic/UnaryBooleanPathFormula.cpp | 39 ++++++++++++++ src/storm/logic/UnaryBooleanPathFormula.h | 35 +++++++++++++ src/storm/logic/UnaryBooleanStateFormula.h | 3 +- src/storm/storage/jani/JSONExporter.cpp | 17 ++++++ src/storm/storage/jani/JSONExporter.h | 2 + 29 files changed, 351 insertions(+), 27 deletions(-) create mode 100644 src/storm/logic/BinaryBooleanOperatorType.h create mode 100644 src/storm/logic/BinaryBooleanPathFormula.cpp create mode 100644 src/storm/logic/BinaryBooleanPathFormula.h create mode 100644 src/storm/logic/UnaryBooleanOperatorType.h create mode 100644 src/storm/logic/UnaryBooleanPathFormula.cpp create mode 100644 src/storm/logic/UnaryBooleanPathFormula.h diff --git a/src/storm-parsers/parser/FormulaParserGrammar.cpp b/src/storm-parsers/parser/FormulaParserGrammar.cpp index 95a27d70c..d768fab9b 100644 --- a/src/storm-parsers/parser/FormulaParserGrammar.cpp +++ b/src/storm-parsers/parser/FormulaParserGrammar.cpp @@ -52,13 +52,13 @@ namespace storm { operatorFormula = probabilityOperator | rewardOperator | longRunAverageOperator | timeOperator; operatorFormula.name("operator formulas"); - atomicStateFormula = booleanLiteralFormula | labelFormula | expressionFormula | (qi::lit("(") > stateFormula > qi::lit(")")) | operatorFormula; + atomicStateFormula = booleanLiteralFormula | labelFormula | expressionFormula | (qi::lit("(") > untilFormula(qi::_r1) > qi::lit(")")) | operatorFormula; atomicStateFormula.name("atomic state formula"); - atomicStateFormulaWithoutExpression = booleanLiteralFormula | labelFormula | (qi::lit("(") > stateFormula > qi::lit(")")) | operatorFormula; + atomicStateFormulaWithoutExpression = booleanLiteralFormula | labelFormula | (qi::lit("(") > untilFormula(qi::_r1) > 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 = (unaryBooleanOperator_ >> atomicStateFormulaWithoutExpression(qi::_r1))[qi::_val = phoenix::bind(&FormulaParserGrammar::createUnaryBooleanStateOrPathFormula, phoenix::ref(*this), qi::_2, qi::_1)] | atomicStateFormula(qi::_r1)[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)]; @@ -70,7 +70,7 @@ namespace storm { 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 = eventuallyFormula(qi::_r1) | globallyFormula(qi::_r1) | nextFormula(qi::_r1) | stateFormula(qi::_r1); 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)]; @@ -78,7 +78,7 @@ namespace storm { hoaPathFormula = qi::lit("HOA:") > qi::lit("{") > quotedString[qi::_val = phoenix::bind(&FormulaParserGrammar::createHOAPathFormula, phoenix::ref(*this), qi::_1)] - >> *(qi::lit(",") > quotedString > qi::lit("->") > stateFormula )[phoenix::bind(&FormulaParserGrammar::addHoaAPMapping, phoenix::ref(*this), *qi::_val, qi::_1, qi::_2)] + >> *(qi::lit(",") > quotedString > qi::lit("->") > stateFormula(qi::_r1) )[phoenix::bind(&FormulaParserGrammar::addHoaAPMapping, phoenix::ref(*this), *qi::_val, qi::_1, qi::_2)] > qi::lit("}"); basicPathFormula = (hoaPathFormula(qi::_r1)[qi::_val = qi::_1]) | untilFormula(qi::_r1)[qi::_val = qi::_1]; @@ -112,7 +112,7 @@ namespace storm { 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 = ((qi::lit("LRA") | qi::lit("S")) > operatorInformation > qi::lit("[") > stateFormula(storm::logic::FormulaContext::LongRunAverage) > 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("\"}"); @@ -127,13 +127,13 @@ namespace storm { 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 = notStateFormula(qi::_r1)[qi::_val = qi::_1] >> *(qi::lit("&") >> notStateFormula(qi::_r1))[qi::_val = phoenix::bind(&FormulaParserGrammar::createBinaryBooleanStateOrPathFormula, 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 = andStateFormula(qi::_r1)[qi::_val = qi::_1] >> *(qi::lit("|") >> andStateFormula(qi::_r1))[qi::_val = phoenix::bind(&FormulaParserGrammar::createBinaryBooleanStateOrPathFormula, 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 = (qi::lit("multi") > qi::lit("(") >> ((pathFormula(storm::logic::FormulaContext::Probability) | stateFormula(storm::logic::FormulaContext::Probability)) % 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_('_')))]]]; @@ -141,7 +141,7 @@ namespace storm { 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 = (qi::lit("quantile") > qi::lit("(") >> *(quantileBoundVariable) >> stateFormula(storm::logic::FormulaContext::Undefined) > qi::lit(")"))[qi::_val = phoenix::bind(&FormulaParserGrammar::createQuantileFormula, phoenix::ref(*this), qi::_1, qi::_2)]; quantileFormula.name("Quantile formula"); 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)]; @@ -166,7 +166,7 @@ namespace storm { 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"); - stateFormula = (orStateFormula | multiFormula | quantileFormula | gameFormula); + stateFormula = (orStateFormula(qi::_r1) | multiFormula | quantileFormula); stateFormula.name("state formula"); quotedString %= qi::as_string[qi::lexeme[qi::omit[qi::char_('"')] > qi::raw[*(!qi::char_('"') >> qi::char_)] > qi::omit[qi::lit('"')]]]; @@ -183,7 +183,7 @@ namespace storm { #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(",") > stateFormula(storm::logic::FormulaContext::Undefined) > qi::lit(",") > stateFormula(storm::logic::FormulaContext::Undefined) > qi::lit(")"))[qi::_val = phoenix::bind(&FormulaParserGrammar::createProperty, phoenix::ref(*this), qi::_1, qi::_2, qi::_3, qi::_4)] | (-formulaName >> stateFormula(storm::logic::FormulaContext::Undefined))[qi::_val = phoenix::bind(&FormulaParserGrammar::createPropertyWithDefaultFilterTypeAndStates, phoenix::ref(*this), qi::_1, qi::_2)] | (-formulaName >> shieldExpression >> stateFormula(storm::logic::FormulaContext::Undefined))[qi::_val = phoenix::bind(&FormulaParserGrammar::createShieldingProperty, phoenix::ref(*this), qi::_1, qi::_3, qi::_2)]; filterProperty.name("filter property"); #pragma clang diagnostic pop @@ -452,6 +452,34 @@ namespace storm { } } + 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 { + return createBinaryBooleanPathFormula(leftSubformula, rightSubformula, operatorType); + } + } + + 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 { + return createUnaryBooleanPathFormula(subformula, operatorType); + } + } + 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) { diff --git a/src/storm-parsers/parser/FormulaParserGrammar.h b/src/storm-parsers/parser/FormulaParserGrammar.h index c40842532..2bba99c73 100644 --- a/src/storm-parsers/parser/FormulaParserGrammar.h +++ b/src/storm-parsers/parser/FormulaParserGrammar.h @@ -165,19 +165,19 @@ namespace storm { 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> 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>(storm::logic::FormulaContext), Skipper> atomicStateFormula; + qi::rule<Iterator, std::shared_ptr<storm::logic::Formula const>(storm::logic::FormulaContext), Skipper> atomicStateFormulaWithoutExpression; qi::rule<Iterator, std::shared_ptr<storm::logic::Formula const>(), Skipper> operatorFormula; qi::rule<Iterator, std::string(), Skipper> label; qi::rule<Iterator, std::string(), Skipper> rewardModelName; - 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; + qi::rule<Iterator, std::shared_ptr<storm::logic::Formula const>(storm::logic::FormulaContext), Skipper> andStateFormula; + qi::rule<Iterator, std::shared_ptr<storm::logic::Formula const>(storm::logic::FormulaContext), Skipper> orStateFormula; + qi::rule<Iterator, std::shared_ptr<storm::logic::Formula const>(storm::logic::FormulaContext), Skipper> notStateFormula; 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; @@ -250,7 +250,11 @@ namespace storm { 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> 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); std::shared_ptr<storm::logic::Formula const> createMultiFormula(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); 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..aa84f23f7 --- /dev/null +++ b/src/storm/logic/BinaryBooleanPathFormula.cpp @@ -0,0 +1,47 @@ +#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) : BinaryPathFormula(leftSubformula, rightSubformula), operatorType(operatorType) { + 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"); + } + + bool BinaryBooleanPathFormula::isBinaryBooleanPathFormula() 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) const { + out << "("; + this->getLeftSubformula().writeToStream(out); + switch (operatorType) { + case OperatorType::And: out << " & "; break; + case OperatorType::Or: out << " | "; break; + } + this->getRightSubformula().writeToStream(out); + out << ")"; + return out; + } + } +} diff --git a/src/storm/logic/BinaryBooleanPathFormula.h b/src/storm/logic/BinaryBooleanPathFormula.h new file mode 100644 index 000000000..6f60f06f4 --- /dev/null +++ b/src/storm/logic/BinaryBooleanPathFormula.h @@ -0,0 +1,38 @@ +#ifndef STORM_LOGIC_BINARYBOOLEANPATHFORMULA_H_ +#define STORM_LOGIC_BINARYBOOLEANPATHFORMULA_H_ + +#include <map> + +#include "storm/logic/BinaryPathFormula.h" +#include "storm/logic/BinaryBooleanOperatorType.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); + + virtual ~BinaryBooleanPathFormula() { + // Intentionally left empty. + }; + + virtual bool isBinaryBooleanPathFormula() 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) const override; + + private: + OperatorType operatorType; + }; + } +} + +#endif /* STORM_LOGIC_BINARYBOOLEANPATHFORMULA_H_ */ diff --git a/src/storm/logic/BinaryBooleanStateFormula.h b/src/storm/logic/BinaryBooleanStateFormula.h index 9a884e60a..085b4fb24 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); diff --git a/src/storm/logic/CloneVisitor.cpp b/src/storm/logic/CloneVisitor.cpp index 15499c9d9..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,6 +176,11 @@ 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)); diff --git a/src/storm/logic/CloneVisitor.h b/src/storm/logic/CloneVisitor.h index 954d46db4..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,6 +35,7 @@ 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/Formula.cpp b/src/storm/logic/Formula.cpp index 553e15b89..202116dff 100644 --- a/src/storm/logic/Formula.cpp +++ b/src/storm/logic/Formula.cpp @@ -43,6 +43,14 @@ namespace storm { return false; } + bool Formula::isBinaryBooleanPathFormula() const { + return false; + } + + bool Formula::isUnaryBooleanPathFormula() const { + return false; + } + bool Formula::isBooleanLiteralFormula() const { return false; } diff --git a/src/storm/logic/Formula.h b/src/storm/logic/Formula.h index 0014baef4..e4fec35c6 100644 --- a/src/storm/logic/Formula.h +++ b/src/storm/logic/Formula.h @@ -47,6 +47,9 @@ namespace storm { virtual bool isBinaryBooleanStateFormula() const; virtual bool isUnaryBooleanStateFormula() const; + virtual bool isBinaryBooleanPathFormula() const; + virtual bool isUnaryBooleanPathFormula() const; + virtual bool isMultiObjectiveFormula() const; virtual bool isQuantileFormula() const; diff --git a/src/storm/logic/FormulaInformationVisitor.cpp b/src/storm/logic/FormulaInformationVisitor.cpp index 471503e2a..e42bb2cbb 100644 --- a/src/storm/logic/FormulaInformationVisitor.cpp +++ b/src/storm/logic/FormulaInformationVisitor.cpp @@ -17,10 +17,14 @@ 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 { + return boost::any_cast<FormulaInformation>(f.getLeftSubformula().accept(*this, data)).join(boost::any_cast<FormulaInformation>(f.getRightSubformula().accept(*this))); + } + boost::any FormulaInformationVisitor::visit(BooleanLiteralFormula const&, boost::any const&) const { return FormulaInformation(); } @@ -130,6 +134,10 @@ namespace storm { return f.getSubformula().accept(*this, data); } + boost::any FormulaInformationVisitor::visit(UnaryBooleanPathFormula const& f, boost::any const& data) const { + return f.getSubformula().accept(*this, data); + } + 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))); } diff --git a/src/storm/logic/FormulaInformationVisitor.h b/src/storm/logic/FormulaInformationVisitor.h index a1f3a3fb0..11ba3e80b 100644 --- a/src/storm/logic/FormulaInformationVisitor.h +++ b/src/storm/logic/FormulaInformationVisitor.h @@ -14,6 +14,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; @@ -33,6 +34,7 @@ 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/FormulaVisitor.h b/src/storm/logic/FormulaVisitor.h index b1c6db105..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,6 +35,7 @@ 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 47ceae22a..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,6 +26,7 @@ #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" diff --git a/src/storm/logic/FormulasForwardDeclarations.h b/src/storm/logic/FormulasForwardDeclarations.h index 41aca3c3b..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,6 +34,7 @@ namespace storm { class StateFormula; class TotalRewardFormula; class UnaryBooleanStateFormula; + class UnaryBooleanPathFormula; class UnaryPathFormula; class UnaryStateFormula; class UntilFormula; diff --git a/src/storm/logic/FragmentChecker.cpp b/src/storm/logic/FragmentChecker.cpp index 0c76dec44..c40d703c9 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(); diff --git a/src/storm/logic/FragmentChecker.h b/src/storm/logic/FragmentChecker.h index e027f7c46..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,6 +35,7 @@ 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 445ae0b8c..c00d53cf7 100644 --- a/src/storm/logic/FragmentSpecification.cpp +++ b/src/storm/logic/FragmentSpecification.cpp @@ -175,6 +175,8 @@ namespace storm { booleanLiteralFormula = false; unaryBooleanStateFormula = false; binaryBooleanStateFormula = false; + unaryBooleanPathFormula = false; + binaryBooleanPathFormula = false; cumulativeRewardFormula = false; instantaneousRewardFormula = false; @@ -372,12 +374,21 @@ namespace storm { return *this; } - bool FragmentSpecification::areBinaryBooleanStateFormulasAllowed() const { - return binaryBooleanStateFormula; + bool FragmentSpecification::areUnaryBooleanPathFormulasAllowed() const { + return unaryBooleanPathFormula; } - FragmentSpecification& FragmentSpecification::setBinaryBooleanStateFormulasAllowed(bool newValue) { - this->binaryBooleanStateFormula = newValue; + FragmentSpecification& FragmentSpecification::setUnaryBooleanPathFormulasAllowed(bool newValue) { + this->unaryBooleanPathFormula = newValue; + return *this; + } + + bool FragmentSpecification::areBinaryBooleanPathFormulasAllowed() const { + return binaryBooleanPathFormula; + } + + FragmentSpecification& FragmentSpecification::setBinaryBooleanPathFormulasAllowed(bool newValue) { + this->binaryBooleanPathFormula = newValue; return *this; } diff --git a/src/storm/logic/FragmentSpecification.h b/src/storm/logic/FragmentSpecification.h index 5f656695e..07dd5c3da 100644 --- a/src/storm/logic/FragmentSpecification.h +++ b/src/storm/logic/FragmentSpecification.h @@ -70,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); @@ -190,6 +196,8 @@ namespace storm { bool booleanLiteralFormula; bool unaryBooleanStateFormula; bool binaryBooleanStateFormula; + bool unaryBooleanPathFormula; + bool binaryBooleanPathFormula; bool cumulativeRewardFormula; bool instantaneousRewardFormula; diff --git a/src/storm/logic/LiftableTransitionRewardsVisitor.cpp b/src/storm/logic/LiftableTransitionRewardsVisitor.cpp index 5a0219242..fbb215440 100644 --- a/src/storm/logic/LiftableTransitionRewardsVisitor.cpp +++ b/src/storm/logic/LiftableTransitionRewardsVisitor.cpp @@ -23,9 +23,15 @@ namespace storm { } boost::any LiftableTransitionRewardsVisitor::visit(BinaryBooleanStateFormula const&, boost::any const&) const { + // TODO joachim: is this correct? return true; } + 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)); + } + + boost::any LiftableTransitionRewardsVisitor::visit(BooleanLiteralFormula const&, boost::any const&) const { return true; } @@ -143,6 +149,10 @@ 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)); } diff --git a/src/storm/logic/LiftableTransitionRewardsVisitor.h b/src/storm/logic/LiftableTransitionRewardsVisitor.h index db5530cad..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,6 +41,7 @@ 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/ToExpressionVisitor.cpp b/src/storm/logic/ToExpressionVisitor.cpp index 41688ad8e..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,7 +128,11 @@ 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."); } diff --git a/src/storm/logic/ToExpressionVisitor.h b/src/storm/logic/ToExpressionVisitor.h index eb7e261f2..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,6 +35,7 @@ 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/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..61b699d55 --- /dev/null +++ b/src/storm/logic/UnaryBooleanPathFormula.cpp @@ -0,0 +1,39 @@ +#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) : UnaryPathFormula(subformula), operatorType(operatorType) { + STORM_LOG_THROW(this->getSubformula().isStateFormula() || this->getSubformula().isPathFormula(), storm::exceptions::InvalidPropertyException, "Boolean path formula must have either path or state subformulas"); + } + + bool UnaryBooleanPathFormula::isUnaryBooleanPathFormula() 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) const { + switch (operatorType) { + case OperatorType::Not: out << "!("; break; + } + this->getSubformula().writeToStream(out); + out << ")"; + return out; + } + } +} diff --git a/src/storm/logic/UnaryBooleanPathFormula.h b/src/storm/logic/UnaryBooleanPathFormula.h new file mode 100644 index 000000000..bbef7aeac --- /dev/null +++ b/src/storm/logic/UnaryBooleanPathFormula.h @@ -0,0 +1,35 @@ +#ifndef STORM_LOGIC_UNARYBOOLEANPATHFORMULA_H_ +#define STORM_LOGIC_UNARYBOOLEANPATHFORMULA_H_ + +#include "storm/logic/UnaryPathFormula.h" +#include "storm/logic/UnaryBooleanOperatorType.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); + + virtual ~UnaryBooleanPathFormula() { + // Intentionally left empty. + }; + + virtual bool isUnaryBooleanPathFormula() 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) const override; + + private: + OperatorType operatorType; + }; + } +} + +#endif /* STORM_LOGIC_UNARYBOOLEANPATHFORMULA_H_ */ diff --git a/src/storm/logic/UnaryBooleanStateFormula.h b/src/storm/logic/UnaryBooleanStateFormula.h index 19420ec16..4c3cd3c17 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); diff --git a/src/storm/storage/jani/JSONExporter.cpp b/src/storm/storage/jani/JSONExporter.cpp index f89e1cab5..5706618c6 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"; diff --git a/src/storm/storage/jani/JSONExporter.h b/src/storm/storage/jani/JSONExporter.h index c14524f69..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,6 +72,7 @@ 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; From bd0a882cd5b664262fc3e3f4a80d2f65c94b0272 Mon Sep 17 00:00:00 2001 From: Joachim Klein <joachim.klein@automata.tools> Date: Mon, 24 Aug 2020 22:25:01 +0200 Subject: [PATCH 013/172] (LTL) FormulaInformation: add containsComplexPathFormula() We want to differentiate between a simple path formula (single G, F, U, X, with negation over state formulas) and complex path formulas (nested temporal operators, conjunction/disjunction, etc). Adapt FormulaInformation and FormulaInformationVisitor accordingly. Additionally, we tweak the FormulaInformationVisitor so that we can optionally prohibit recursing into operator subformulas (e.g., P>0[...]). For PRCTL*, such subformulas are treated just as state subformulas, and we would like to have the ability to get FormulaInformation just for the structure of the "surface-level" formula, without looking into the probability, long-run, reward, ... sub-formulas. refactor FormulaInformationVisitor to support stopping recursion into nested operators and for detecting complex path formulas Conflicts: src/storm/logic/Formula.cpp --- src/storm/logic/Formula.cpp | 5 +- src/storm/logic/Formula.h | 2 +- src/storm/logic/FormulaInformation.cpp | 13 ++- src/storm/logic/FormulaInformation.h | 3 + src/storm/logic/FormulaInformationVisitor.cpp | 80 +++++++++++++++---- src/storm/logic/FormulaInformationVisitor.h | 13 ++- 6 files changed, 93 insertions(+), 23 deletions(-) diff --git a/src/storm/logic/Formula.cpp b/src/storm/logic/Formula.cpp index 202116dff..7cefa26d1 100644 --- a/src/storm/logic/Formula.cpp +++ b/src/storm/logic/Formula.cpp @@ -192,9 +192,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() { diff --git a/src/storm/logic/Formula.h b/src/storm/logic/Formula.h index e4fec35c6..452ef0f73 100644 --- a/src/storm/logic/Formula.h +++ b/src/storm/logic/Formula.h @@ -100,7 +100,7 @@ namespace storm { 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; 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..280fa5e59 100644 --- a/src/storm/logic/FormulaInformation.h +++ b/src/storm/logic/FormulaInformation.h @@ -18,6 +18,7 @@ namespace storm { bool containsCumulativeRewardFormula() const; bool containsRewardBoundedFormula() const; bool containsLongRunFormula() const; + bool containsComplexPathFormula() const; FormulaInformation join(FormulaInformation const& other); @@ -27,6 +28,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 +37,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 e42bb2cbb..7a0b95f0c 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(); } @@ -22,7 +26,8 @@ namespace storm { } boost::any FormulaInformationVisitor::visit(BinaryBooleanPathFormula 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))); + return result.setContainsComplexPathFormula(); } boost::any FormulaInformationVisitor::visit(BooleanLiteralFormula const&, boost::any const&) const { @@ -46,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; } @@ -70,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 { @@ -78,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 { @@ -92,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; } @@ -104,26 +125,45 @@ 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); + // TODO (joachim): check is this correct? + 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 { @@ -135,17 +175,25 @@ namespace storm { } boost::any FormulaInformationVisitor::visit(UnaryBooleanPathFormula const& f, boost::any const& data) const { - return f.getSubformula().accept(*this, data); + 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; - for (auto& mapped : f.getAPMapping()) { - info = info.join(boost::any_cast<FormulaInformation>(mapped.second->accept(*this, data))); + 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 11ba3e80b..8bf7a25a9 100644 --- a/src/storm/logic/FormulaInformationVisitor.h +++ b/src/storm/logic/FormulaInformationVisitor.h @@ -9,8 +9,14 @@ 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; @@ -37,6 +43,9 @@ namespace storm { 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; }; } From b04d2723c2e580212463f0c0c3b89353fed4450f Mon Sep 17 00:00:00 2001 From: Joachim Klein <joachim.klein@automata.tools> Date: Mon, 24 Aug 2020 22:25:03 +0200 Subject: [PATCH 014/172] (LTL) Add Formula::toPrefixString() Convert a formula into prefix format (LBTT/ltl2dstar-style LTL syntax). Conflicts: src/storm/logic/Formula.h --- src/storm/logic/Formula.cpp | 7 + src/storm/logic/Formula.h | 1 + src/storm/logic/ToPrefixStringVisitor.cpp | 155 ++++++++++++++++++++++ src/storm/logic/ToPrefixStringVisitor.h | 42 ++++++ 4 files changed, 205 insertions(+) create mode 100644 src/storm/logic/ToPrefixStringVisitor.cpp create mode 100644 src/storm/logic/ToPrefixStringVisitor.h diff --git a/src/storm/logic/Formula.cpp b/src/storm/logic/Formula.cpp index 7cefa26d1..752389b36 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 { @@ -567,5 +568,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 452ef0f73..72631e2fe 100644 --- a/src/storm/logic/Formula.h +++ b/src/storm/logic/Formula.h @@ -237,6 +237,7 @@ namespace storm { std::string toString() const; virtual std::ostream& writeToStream(std::ostream& out) 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; diff --git a/src/storm/logic/ToPrefixStringVisitor.cpp b/src/storm/logic/ToPrefixStringVisitor.cpp new file mode 100644 index 000000000..a3d55b994 --- /dev/null +++ b/src/storm/logic/ToPrefixStringVisitor.cpp @@ -0,0 +1,155 @@ +#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(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..95d1bc585 --- /dev/null +++ b/src/storm/logic/ToPrefixStringVisitor.h @@ -0,0 +1,42 @@ +#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(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(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; + }; + + } +} + From 393dd2af87b893fff7dc1344911edf269fc66bf0 Mon Sep 17 00:00:00 2001 From: Joachim Klein <joachim.klein@automata.tools> Date: Mon, 24 Aug 2020 22:25:03 +0200 Subject: [PATCH 015/172] (LTL) ExtractMaximalStateFormulasVisitor For PRCTL*-model checking, we need to extract the maximal state subformulas in a path formula and substitute those with new labels, e.g., for (F P>0.5[...]) & G (s=0 & d=1) we would get (F a_1) & G a_2 as the resulting formula, with a_1 => P>0.5[...] a_2 => s=0 & d=1 This then allows the recursive computation of the satisfaction sets of the maximal state subformulas and using those in the computation for the (simplified) path formula. --- .../ExtractMaximalStateFormulasVisitor.cpp | 170 ++++++++++++++++++ .../ExtractMaximalStateFormulasVisitor.h | 43 +++++ 2 files changed, 213 insertions(+) create mode 100644 src/storm/logic/ExtractMaximalStateFormulasVisitor.cpp create mode 100644 src/storm/logic/ExtractMaximalStateFormulasVisitor.h diff --git a/src/storm/logic/ExtractMaximalStateFormulasVisitor.cpp b/src/storm/logic/ExtractMaximalStateFormulasVisitor.cpp new file mode 100644 index 000000000..d6f465027 --- /dev/null +++ b/src/storm/logic/ExtractMaximalStateFormulasVisitor.cpp @@ -0,0 +1,170 @@ +#include "storm/logic/ExtractMaximalStateFormulasVisitor.h" + +#include "storm/logic/Formulas.h" + +#include "storm/exceptions/InvalidOperationException.h" + +namespace storm { + namespace logic { + + ExtractMaximalStateFormulasVisitor::ExtractMaximalStateFormulasVisitor(std::vector<LabelFormulaPair>& extractedFormulas) : extractedFormulas(extractedFormulas), nestingLevel(0) { + } + + std::shared_ptr<Formula> ExtractMaximalStateFormulasVisitor::extract(PathFormula const& f, std::vector<LabelFormulaPair>& 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 { + std::string label = "p" + std::to_string(extractedFormulas.size()); + + const_cast<std::vector<LabelFormulaPair>&>(extractedFormulas).emplace_back(label, f); + + 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..e3bd1cea5 --- /dev/null +++ b/src/storm/logic/ExtractMaximalStateFormulasVisitor.h @@ -0,0 +1,43 @@ +#pragma once + +#include <vector> + +#include "storm/logic/CloneVisitor.h" + +namespace storm { + namespace logic { + + class ExtractMaximalStateFormulasVisitor : public CloneVisitor { + public: + typedef std::pair<std::string, std::shared_ptr<Formula const>> LabelFormulaPair; + + static std::shared_ptr<Formula> extract(PathFormula const& f, std::vector<LabelFormulaPair>& 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(std::vector<LabelFormulaPair>& extractedFormulas); + + std::shared_ptr<Formula> extract(std::shared_ptr<Formula> f) const; + void incrementNestingLevel() const; + void decrementNestingLevel() const; + + std::vector<LabelFormulaPair>& extractedFormulas; + std::size_t nestingLevel; + }; + + } +} + From 6404c526e2221bba6cd0e3094dd891094a653144 Mon Sep 17 00:00:00 2001 From: Joachim Klein <joachim.klein@automata.tools> Date: Mon, 24 Aug 2020 22:25:01 +0200 Subject: [PATCH 016/172] WIP (LTL) LTL2DeterministicAutomaton (first hacky attempt) Requires a script ltl2da on the PATH that takes two arguments, first an LTL formula in prefix format, second the DA automaton output filename. E.g., it could be called via ltl2da "& p1 F G p0" out.hoa and should produce a complete deterministic automaton (with arbitrary acceptance) for the LTL formula 'p1 & F (G p0)' and write it to the out.hoa file. Optionally, you can set the LTL2DA environment variable to provide the path to the script, e.g., invoking storm via LTL2DA=../ltl2da-script bin/storm ... --- .../automata/LTL2DeterministicAutomaton.cpp | 61 +++++++++++++++++++ .../automata/LTL2DeterministicAutomaton.h | 24 ++++++++ 2 files changed, 85 insertions(+) create mode 100644 src/storm/automata/LTL2DeterministicAutomaton.cpp create mode 100644 src/storm/automata/LTL2DeterministicAutomaton.h diff --git a/src/storm/automata/LTL2DeterministicAutomaton.cpp b/src/storm/automata/LTL2DeterministicAutomaton.cpp new file mode 100644 index 000000000..8a4275c60 --- /dev/null +++ b/src/storm/automata/LTL2DeterministicAutomaton.cpp @@ -0,0 +1,61 @@ +#include "storm/automata/LTL2DeterministicAutomaton.h" +#include "storm/automata/DeterministicAutomaton.h" + +#include "storm/logic/Formula.h" +#include "storm/utility/macros.h" +#include "storm/exceptions/FileIoException.h" + +#include <cstring> +#include <cerrno> +#include <cstdlib> +#include <unistd.h> // for execlp +#include <sys/wait.h> + +namespace storm { + namespace automata { + + // TODO: this is quite hacky, improve robustness + std::shared_ptr<DeterministicAutomaton> LTL2DeterministicAutomaton::ltl2da(storm::logic::Formula const& f) { + std::string prefixLtl = f.toPrefixString(); + + std::string ltl2da_tool = "ltl2da"; + if (const char* ltl2da_env = std::getenv("LTL2DA")) { + ltl2da_tool = ltl2da_env; + } + + STORM_LOG_INFO("Calling external LTL->DA tool: " << ltl2da_tool << " '" << 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(ltl2da_tool.c_str(), ltl2da_tool.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..c39f1b235 --- /dev/null +++ b/src/storm/automata/LTL2DeterministicAutomaton.h @@ -0,0 +1,24 @@ +#pragma + +#include <memory> + +namespace storm { + + namespace logic { + // fwd + class Formula; + } + + namespace automata { + + // fwd + class DeterministicAutomaton; + + + class LTL2DeterministicAutomaton { + public: + static std::shared_ptr<DeterministicAutomaton> ltl2da(storm::logic::Formula const& f); + }; + + } +} From fbe5236c4df87113b7eb371c50aff708dec9dd17 Mon Sep 17 00:00:00 2001 From: Joachim Klein <joachim.klein@automata.tools> Date: Mon, 24 Aug 2020 22:25:04 +0200 Subject: [PATCH 017/172] (LTL) FragmentSpecification: add pctlstar() and prctlstar() fragments We add the star variants (allow complex path formulas). Conflicts: src/storm/logic/FragmentSpecification.cpp src/storm/logic/FragmentSpecification.h --- src/storm/logic/FragmentSpecification.cpp | 54 +++++++++++++++++------ src/storm/logic/FragmentSpecification.h | 10 ++++- 2 files changed, 48 insertions(+), 16 deletions(-) diff --git a/src/storm/logic/FragmentSpecification.cpp b/src/storm/logic/FragmentSpecification.cpp index c00d53cf7..314bca97f 100644 --- a/src/storm/logic/FragmentSpecification.cpp +++ b/src/storm/logic/FragmentSpecification.cpp @@ -45,6 +45,17 @@ namespace storm { return pctl; } + FragmentSpecification pctlstar() { + FragmentSpecification pctlstar = pctl(); + + pctlstar.setBinaryBooleanPathFormulasAllowed(true); + pctlstar.setUnaryBooleanPathFormulasAllowed(true); + pctlstar.setNestedOperatorsAllowed(true); + pctlstar.setNestedPathFormulasAllowed(true); + + return pctlstar; + } + FragmentSpecification flatPctl() { FragmentSpecification flatPctl = pctl(); @@ -53,6 +64,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(); @@ -73,20 +113,6 @@ namespace storm { return rpatl; } - 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 csl() { FragmentSpecification csl = pctl(); diff --git a/src/storm/logic/FragmentSpecification.h b/src/storm/logic/FragmentSpecification.h index 07dd5c3da..8c50c635a 100644 --- a/src/storm/logic/FragmentSpecification.h +++ b/src/storm/logic/FragmentSpecification.h @@ -249,12 +249,18 @@ namespace storm { // Flat PCTL. FragmentSpecification flatPctl(); - // 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(); + + // rPATL for SMGs + FragmentSpecification rpatl(); + // Regular CSL. FragmentSpecification csl(); From 5427702376dfab4c8d46e133f5bb4c4c193aa7bb Mon Sep 17 00:00:00 2001 From: Joachim Klein <joachim.klein@automata.tools> Date: Mon, 24 Aug 2020 22:25:05 +0200 Subject: [PATCH 018/172] WIP:needed? Boolean path formulas: allow storing context --- src/storm/logic/BinaryBooleanPathFormula.cpp | 11 ++++++++++- src/storm/logic/BinaryBooleanPathFormula.h | 7 ++++++- src/storm/logic/UnaryBooleanPathFormula.cpp | 11 ++++++++++- src/storm/logic/UnaryBooleanPathFormula.h | 7 ++++++- 4 files changed, 32 insertions(+), 4 deletions(-) diff --git a/src/storm/logic/BinaryBooleanPathFormula.cpp b/src/storm/logic/BinaryBooleanPathFormula.cpp index aa84f23f7..b759db23b 100644 --- a/src/storm/logic/BinaryBooleanPathFormula.cpp +++ b/src/storm/logic/BinaryBooleanPathFormula.cpp @@ -7,15 +7,24 @@ namespace storm { namespace logic { - BinaryBooleanPathFormula::BinaryBooleanPathFormula(OperatorType operatorType, std::shared_ptr<Formula const> const& leftSubformula, std::shared_ptr<Formula const> const& rightSubformula) : BinaryPathFormula(leftSubformula, rightSubformula), operatorType(operatorType) { + 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); } diff --git a/src/storm/logic/BinaryBooleanPathFormula.h b/src/storm/logic/BinaryBooleanPathFormula.h index 6f60f06f4..10286f23f 100644 --- a/src/storm/logic/BinaryBooleanPathFormula.h +++ b/src/storm/logic/BinaryBooleanPathFormula.h @@ -5,6 +5,7 @@ #include "storm/logic/BinaryPathFormula.h" #include "storm/logic/BinaryBooleanOperatorType.h" +#include "storm/logic/FormulaContext.h" namespace storm { namespace logic { @@ -12,13 +13,16 @@ namespace storm { public: typedef storm::logic::BinaryBooleanOperatorType OperatorType; - BinaryBooleanPathFormula(OperatorType operatorType, std::shared_ptr<Formula const> const& leftSubformula, std::shared_ptr<Formula const> const& rightSubformula); + 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; @@ -31,6 +35,7 @@ namespace storm { private: OperatorType operatorType; + FormulaContext context; }; } } diff --git a/src/storm/logic/UnaryBooleanPathFormula.cpp b/src/storm/logic/UnaryBooleanPathFormula.cpp index 61b699d55..7613032b6 100644 --- a/src/storm/logic/UnaryBooleanPathFormula.cpp +++ b/src/storm/logic/UnaryBooleanPathFormula.cpp @@ -7,14 +7,23 @@ namespace storm { namespace logic { - UnaryBooleanPathFormula::UnaryBooleanPathFormula(OperatorType operatorType, std::shared_ptr<Formula const> const& subformula) : UnaryPathFormula(subformula), operatorType(operatorType) { + 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); } diff --git a/src/storm/logic/UnaryBooleanPathFormula.h b/src/storm/logic/UnaryBooleanPathFormula.h index bbef7aeac..3323f6949 100644 --- a/src/storm/logic/UnaryBooleanPathFormula.h +++ b/src/storm/logic/UnaryBooleanPathFormula.h @@ -3,6 +3,7 @@ #include "storm/logic/UnaryPathFormula.h" #include "storm/logic/UnaryBooleanOperatorType.h" +#include "storm/logic/FormulaContext.h" namespace storm { namespace logic { @@ -10,13 +11,16 @@ namespace storm { public: typedef storm::logic::UnaryBooleanOperatorType OperatorType; - UnaryBooleanPathFormula(OperatorType operatorType, std::shared_ptr<Formula const> const& subformula); + 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; @@ -28,6 +32,7 @@ namespace storm { private: OperatorType operatorType; + FormulaContext context; }; } } From ab32af463bc107292b46bb0f9b8bb241a019882a Mon Sep 17 00:00:00 2001 From: Joachim Klein <joachim.klein@automata.tools> Date: Mon, 24 Aug 2020 22:25:05 +0200 Subject: [PATCH 019/172] (LTL) AbstractModelChecker: detect need for LTL PMC, call (unimplemented) computeLTLProbabilities Conflicts: src/storm/modelchecker/AbstractModelChecker.cpp src/storm/modelchecker/AbstractModelChecker.h --- .../modelchecker/AbstractModelChecker.cpp | 36 ++++++++++++------- src/storm/modelchecker/AbstractModelChecker.h | 1 + 2 files changed, 24 insertions(+), 13 deletions(-) diff --git a/src/storm/modelchecker/AbstractModelChecker.cpp b/src/storm/modelchecker/AbstractModelChecker.cpp index c4e485d89..4ad79b8ed 100644 --- a/src/storm/modelchecker/AbstractModelChecker.cpp +++ b/src/storm/modelchecker/AbstractModelChecker.cpp @@ -24,6 +24,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 +44,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 +64,10 @@ 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.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()) { @@ -125,6 +130,11 @@ namespace storm { 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>::computeRewards(Environment const& env, storm::logic::RewardMeasureType rewardMeasureType, CheckTask<storm::logic::Formula, ValueType> const& checkTask) { storm::logic::Formula const& rewardFormula = checkTask.getFormula(); @@ -163,7 +173,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() << "."); @@ -239,12 +249,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()) { @@ -252,7 +262,7 @@ namespace storm { } else { STORM_LOG_THROW(false, storm::exceptions::InvalidArgumentException, "The given formula '" << stateFormula << "' is invalid."); } - + return leftResult; } @@ -265,7 +275,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()); @@ -278,7 +288,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()); @@ -291,9 +301,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()); @@ -306,9 +316,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()); @@ -316,7 +326,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 29a5735f5..11d781319 100644 --- a/src/storm/modelchecker/AbstractModelChecker.h +++ b/src/storm/modelchecker/AbstractModelChecker.h @@ -64,6 +64,7 @@ namespace storm { 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); // 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); From 1243b9300c6c2b20905c95a89954d1e555160bc5 Mon Sep 17 00:00:00 2001 From: Joachim Klein <joachim.klein@automata.tools> Date: Thu, 27 Aug 2020 06:25:25 +0200 Subject: [PATCH 020/172] (LTL) SparseDtmcModelChecker: Implement LTL model checking Conflicts: src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.cpp src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.h --- .../prctl/SparseDtmcPrctlModelChecker.cpp | 131 ++++++++++++++---- .../prctl/SparseDtmcPrctlModelChecker.h | 15 +- 2 files changed, 112 insertions(+), 34 deletions(-) diff --git a/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.cpp b/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.cpp index 30858ae3a..859de2fb2 100644 --- a/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.cpp +++ b/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.cpp @@ -18,10 +18,17 @@ #include "storm/modelchecker/helper/utility/SetInformationFromCheckTask.h" #include "storm/logic/FragmentSpecification.h" +#include "storm/logic/ExtractMaximalStateFormulasVisitor.h" + +#include "storm/automata/AcceptanceCondition.h" +#include "storm/automata/DeterministicAutomaton.h" +#include "storm/automata/LTL2DeterministicAutomaton.h" #include "storm/models/sparse/StandardRewardModel.h" +#include "storm/settings/SettingsManager.h" #include "storm/settings/modules/GeneralSettings.h" +#include "storm/settings/modules/DebugSettings.h" #include "storm/exceptions/InvalidStateException.h" @@ -33,11 +40,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 +54,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 +64,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 +91,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 +100,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 +111,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,7 +120,77 @@ 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_LOG_INFO("Obtaining HOA automaton..."); + storm::automata::DeterministicAutomaton::ptr da = pathFormula.readAutomaton(); + const storm::automata::APSet& apSet = da->getAPSet(); + + STORM_LOG_INFO("Deterministic automaton from HOA file has " + << da->getNumberOfStates() << " states, " + << da->getAPSet().size() << " atomic propositions and " + << *da->getAcceptance()->getAcceptanceExpression() << " as acceptance condition."); + + std::map<std::string, storm::storage::BitVector> apSets; + for (std::string const& ap : apSet.getAPs()) { + std::shared_ptr<storm::logic::Formula const> expression = pathFormula.getAPMapping().at(ap); + STORM_LOG_INFO("Computing satisfaction set for atomic proposition \"" << ap << "\" <=> " << *expression << "..."); + std::unique_ptr<CheckResult> resultPointer = this->check(*expression); + ExplicitQualitativeCheckResult const& result = resultPointer->asExplicitQualitativeCheckResult(); + storm::storage::BitVector bitVector = result.getTruthValuesVector(); + STORM_LOG_INFO("Atomic proposition \"" << ap << "\" is satisfied by " << bitVector.getNumberOfSetBits() << " states."); + apSets[ap] = std::move(bitVector); + } + + const SparseDtmcModelType& dtmc = this->getModel(); + storm::solver::SolveGoal<ValueType> goal(dtmc, checkTask); + + std::vector<ValueType> numericResult = storm::modelchecker::helper::SparseDtmcPrctlHelper<ValueType>::computeDAProductProbabilities(env, dtmc, std::move(goal), *da, apSets, checkTask.isQualitativeSet()); + 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(); + + std::vector<storm::logic::ExtractMaximalStateFormulasVisitor::LabelFormulaPair> extracted; + std::shared_ptr<storm::logic::Formula> ltlFormula = storm::logic::ExtractMaximalStateFormulasVisitor::extract(pathFormula, extracted); + + STORM_LOG_INFO("Extracting maximal state formulas and computing satisfaction sets for path formula: " << pathFormula); + + std::map<std::string, storm::storage::BitVector> apSets; + + for (auto& p : extracted) { + STORM_LOG_INFO(" Computing satisfaction set for atomic proposition \"" << p.first << "\" <=> " << *p.second << "..."); + + std::unique_ptr<CheckResult> subResultPointer = this->check(env, *p.second); + ExplicitQualitativeCheckResult const& subResult = subResultPointer->asExplicitQualitativeCheckResult(); + auto sat = subResult.getTruthValuesVector(); + + STORM_LOG_INFO(" Atomic proposition \"" << p.first << "\" is satisfied by " << sat.getNumberOfSetBits() << " states."); + + apSets[p.first] = std::move(sat); + } + + STORM_LOG_INFO("Resulting LTL path formula: " << *ltlFormula); + STORM_LOG_INFO(" in prefix format: " << ltlFormula->toPrefixString()); + + std::shared_ptr<storm::automata::DeterministicAutomaton> da = storm::automata::LTL2DeterministicAutomaton::ltl2da(*ltlFormula); + + STORM_LOG_INFO("Deterministic automaton for LTL formula has " + << da->getNumberOfStates() << " states, " + << da->getAPSet().size() << " atomic propositions and " + << *da->getAcceptance()->getAcceptanceExpression() << " as acceptance condition."); + + const SparseDtmcModelType& dtmc = this->getModel(); + storm::solver::SolveGoal<ValueType> goal(dtmc, checkTask); + + std::vector<ValueType> numericResult = storm::modelchecker::helper::SparseDtmcPrctlHelper<ValueType>::computeDAProductProbabilities(env, dtmc, std::move(goal), *da, apSets, checkTask.isQualitativeSet()); + 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(); @@ -134,7 +211,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 +219,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 +229,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 +238,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 +248,18 @@ 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()); 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))); } - + 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 +268,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 +283,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 +313,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 +342,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..572ecc57e 100644 --- a/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.h +++ b/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.h @@ -9,21 +9,21 @@ 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; @@ -32,6 +32,7 @@ namespace storm { virtual std::unique_ptr<CheckResult> computeGloballyProbabilities(Environment const& env, CheckTask<storm::logic::GloballyFormula, 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 +42,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 From 27ca10a668907212fe4185a0e5de05d15ecc2531 Mon Sep 17 00:00:00 2001 From: Joachim Klein <joachim.klein@automata.tools> Date: Mon, 24 Aug 2020 22:25:08 +0200 Subject: [PATCH 021/172] (stateformula) SymbolicQualitativeCheckResult: add getReachableStates() and getStates() accessors, like SymbolicQuantitativeCheckResult --- .../results/SymbolicQualitativeCheckResult.cpp | 10 ++++++++++ .../results/SymbolicQualitativeCheckResult.h | 2 ++ 2 files changed, 12 insertions(+) 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; From a639836f6fb800b61c64a96acbc38b4a5d835382 Mon Sep 17 00:00:00 2001 From: Joachim Klein <joachim.klein@automata.tools> Date: Mon, 24 Aug 2020 22:25:09 +0200 Subject: [PATCH 022/172] (stateformula) CheckResults: provide constructor for quantitative from qualitative result --- .../ExplicitQuantitativeCheckResult.cpp | 25 +++++++++++++++++++ .../results/ExplicitQuantitativeCheckResult.h | 5 ++++ .../SymbolicQuantitativeCheckResult.cpp | 6 +++++ .../results/SymbolicQuantitativeCheckResult.h | 6 +++++ 4 files changed, 42 insertions(+) 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/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; From af10aa8b4b2bbd33326ee9e8e26e98dc7d6d5b8b Mon Sep 17 00:00:00 2001 From: Joachim Klein <joachim.klein@automata.tools> Date: Mon, 24 Aug 2020 22:25:09 +0200 Subject: [PATCH 023/172] (stateformula) StateFormula: a StateFormula is a probabilistic path formula --- src/storm/logic/StateFormula.cpp | 7 +++++++ src/storm/logic/StateFormula.h | 3 +++ 2 files changed, 10 insertions(+) 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; + }; } } From cf6af6c456e819ceca103ee3ce73f4a386ddb40f Mon Sep 17 00:00:00 2001 From: Joachim Klein <joachim.klein@automata.tools> Date: Mon, 24 Aug 2020 22:25:10 +0200 Subject: [PATCH 024/172] (stateformula) Modelcheckers: support P[phi], Pmax/min[phi] where phi is a state formula This a bit of a weird corner-case. Consider P>0[ s=0 ] or P=?[ s=0 ]. Those are not PCTL-formula (the P-operator requires a temporal operator) and they are not particularly useful, as we just need to evaluate the state formula and the threshold (or turn the satisfaction set into a quantitative result). They can be dealt with by the LTL machinery (DA-construction, product, ...), but this is quite expensive (and not implemented yet for all engines). So, we just deal with it by special treatment. Conflicts: src/storm/modelchecker/AbstractModelChecker.cpp src/storm/modelchecker/AbstractModelChecker.h It looks like you may be committing a cherry-pick. If this is not correct, please run git update-ref -d CHERRY_PICK_HEAD and try again. --- src/storm/modelchecker/AbstractModelChecker.cpp | 9 +++++++++ src/storm/modelchecker/AbstractModelChecker.h | 1 + .../modelchecker/prctl/HybridDtmcPrctlModelChecker.cpp | 10 +++++++++- .../modelchecker/prctl/HybridDtmcPrctlModelChecker.h | 1 + .../modelchecker/prctl/HybridMdpPrctlModelChecker.cpp | 9 +++++++++ .../modelchecker/prctl/HybridMdpPrctlModelChecker.h | 2 ++ .../modelchecker/prctl/SparseDtmcPrctlModelChecker.cpp | 8 ++++++++ .../modelchecker/prctl/SparseDtmcPrctlModelChecker.h | 1 + .../modelchecker/prctl/SparseMdpPrctlModelChecker.cpp | 9 +++++++++ .../modelchecker/prctl/SparseMdpPrctlModelChecker.h | 1 + .../prctl/SymbolicDtmcPrctlModelChecker.cpp | 8 ++++++++ .../modelchecker/prctl/SymbolicDtmcPrctlModelChecker.h | 1 + .../prctl/SymbolicMdpPrctlModelChecker.cpp | 10 ++++++++++ .../modelchecker/prctl/SymbolicMdpPrctlModelChecker.h | 1 + 14 files changed, 70 insertions(+), 1 deletion(-) diff --git a/src/storm/modelchecker/AbstractModelChecker.cpp b/src/storm/modelchecker/AbstractModelChecker.cpp index 4ad79b8ed..31b34cd72 100644 --- a/src/storm/modelchecker/AbstractModelChecker.cpp +++ b/src/storm/modelchecker/AbstractModelChecker.cpp @@ -64,6 +64,10 @@ 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())); @@ -135,6 +139,11 @@ namespace storm { 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) { + 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>::computeRewards(Environment const& env, storm::logic::RewardMeasureType rewardMeasureType, CheckTask<storm::logic::Formula, ValueType> const& checkTask) { storm::logic::Formula const& rewardFormula = checkTask.getFormula(); diff --git a/src/storm/modelchecker/AbstractModelChecker.h b/src/storm/modelchecker/AbstractModelChecker.h index 11d781319..6eb3b0de8 100644 --- a/src/storm/modelchecker/AbstractModelChecker.h +++ b/src/storm/modelchecker/AbstractModelChecker.h @@ -65,6 +65,7 @@ namespace storm { 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); + virtual 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); diff --git a/src/storm/modelchecker/prctl/HybridDtmcPrctlModelChecker.cpp b/src/storm/modelchecker/prctl/HybridDtmcPrctlModelChecker.cpp index 176bba662..44bd4ab3c 100644 --- a/src/storm/modelchecker/prctl/HybridDtmcPrctlModelChecker.cpp +++ b/src/storm/modelchecker/prctl/HybridDtmcPrctlModelChecker.cpp @@ -81,7 +81,15 @@ 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>::computeStateFormulaProbabilities(Environment const& env, CheckTask<storm::logic::Formula, ValueType> const& checkTask) { + storm::logic::Formula const& formula = checkTask.getFormula(); + std::unique_ptr<CheckResult> resultPointer = this->check(env, formula); + SymbolicQualitativeCheckResult<DdType> const& result = resultPointer->asSymbolicQualitativeCheckResult<DdType>(); + return std::make_unique<SymbolicQuantitativeCheckResult<DdType, ValueType>>(result); + } + 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/HybridDtmcPrctlModelChecker.h b/src/storm/modelchecker/prctl/HybridDtmcPrctlModelChecker.h index f779e1920..761d0168f 100644 --- a/src/storm/modelchecker/prctl/HybridDtmcPrctlModelChecker.h +++ b/src/storm/modelchecker/prctl/HybridDtmcPrctlModelChecker.h @@ -31,6 +31,7 @@ namespace storm { 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> computeLongRunAverageProbabilities(Environment const& env, CheckTask<storm::logic::StateFormula, ValueType> const& checkTask) override; + virtual std::unique_ptr<CheckResult> computeStateFormulaProbabilities(Environment const& env, CheckTask<storm::logic::Formula, 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> computeCumulativeRewards(Environment const& env, storm::logic::RewardMeasureType rewardMeasureType, CheckTask<storm::logic::CumulativeRewardFormula, ValueType> const& checkTask) override; diff --git a/src/storm/modelchecker/prctl/HybridMdpPrctlModelChecker.cpp b/src/storm/modelchecker/prctl/HybridMdpPrctlModelChecker.cpp index 15725a415..275527797 100644 --- a/src/storm/modelchecker/prctl/HybridMdpPrctlModelChecker.cpp +++ b/src/storm/modelchecker/prctl/HybridMdpPrctlModelChecker.cpp @@ -103,6 +103,15 @@ namespace storm { 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>::computeStateFormulaProbabilities(Environment const& env, CheckTask<storm::logic::Formula, ValueType> const& checkTask) { + storm::logic::Formula const& formula = checkTask.getFormula(); + std::unique_ptr<CheckResult> resultPointer = this->check(env, formula); + SymbolicQualitativeCheckResult<DdType> const& result = resultPointer->asSymbolicQualitativeCheckResult<DdType>(); + // min/max does not matters + return std::make_unique<SymbolicQuantitativeCheckResult<DdType, ValueType>>(result); + } + 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..3fa76a65a 100644 --- a/src/storm/modelchecker/prctl/HybridMdpPrctlModelChecker.h +++ b/src/storm/modelchecker/prctl/HybridMdpPrctlModelChecker.h @@ -38,6 +38,8 @@ 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> computeStateFormulaProbabilities(Environment const& env, CheckTask<storm::logic::Formula, 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 859de2fb2..ccb5d1a83 100644 --- a/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.cpp +++ b/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.cpp @@ -191,6 +191,14 @@ namespace storm { return std::unique_ptr<CheckResult>(new ExplicitQuantitativeCheckResult<ValueType>(std::move(numericResult))); } + template<typename SparseDtmcModelType> + std::unique_ptr<CheckResult> SparseDtmcPrctlModelChecker<SparseDtmcModelType>::computeStateFormulaProbabilities(Environment const& env, CheckTask<storm::logic::Formula, ValueType> const& checkTask) { + // recurse + std::unique_ptr<CheckResult> resultPointer = this->check(env, checkTask.getFormula()); + ExplicitQualitativeCheckResult const& result = resultPointer->asExplicitQualitativeCheckResult(); + return std::make_unique<ExplicitQuantitativeCheckResult<ValueType>>(result); + } + 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(); diff --git a/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.h b/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.h index 572ecc57e..e03ba42b8 100644 --- a/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.h +++ b/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.h @@ -33,6 +33,7 @@ namespace storm { 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> computeStateFormulaProbabilities(Environment const& env, CheckTask<storm::logic::Formula, 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; diff --git a/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.cpp b/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.cpp index ffefa0e78..a56a8b3ef 100644 --- a/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.cpp +++ b/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.cpp @@ -160,6 +160,15 @@ namespace storm { return result; } + template<typename SparseMdpModelType> + std::unique_ptr<CheckResult> SparseMdpPrctlModelChecker<SparseMdpModelType>::computeStateFormulaProbabilities(Environment const& env, CheckTask<storm::logic::Formula, ValueType> const& checkTask) { + storm::logic::Formula const& formula = 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> resultPointer = this->check(env, formula); + ExplicitQualitativeCheckResult const& result = resultPointer->asExplicitQualitativeCheckResult(); + return std::make_unique<ExplicitQuantitativeCheckResult<ValueType>>(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..ad164df32 100644 --- a/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.h +++ b/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.h @@ -38,6 +38,7 @@ 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> computeStateFormulaProbabilities(Environment const& env, CheckTask<storm::logic::Formula, 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..6b68c945f 100644 --- a/src/storm/modelchecker/prctl/SymbolicDtmcPrctlModelChecker.cpp +++ b/src/storm/modelchecker/prctl/SymbolicDtmcPrctlModelChecker.cpp @@ -59,6 +59,14 @@ namespace storm { return std::make_unique<SymbolicQuantitativeCheckResult<DdType, ValueType>>(this->getModel().getReachableStates(), numericResult); } + template<typename ModelType> + std::unique_ptr<CheckResult> SymbolicDtmcPrctlModelChecker<ModelType>::computeStateFormulaProbabilities(Environment const& env, CheckTask<storm::logic::Formula, ValueType> const& checkTask) { + storm::logic::Formula const& formula = checkTask.getFormula(); + std::unique_ptr<CheckResult> resultPointer = this->check(env, formula); + SymbolicQualitativeCheckResult<DdType> const& result = resultPointer->asSymbolicQualitativeCheckResult<DdType>(); + return std::make_unique<SymbolicQuantitativeCheckResult<DdType, ValueType>>(result); + } + 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/SymbolicDtmcPrctlModelChecker.h b/src/storm/modelchecker/prctl/SymbolicDtmcPrctlModelChecker.h index 1a115468f..17c96e927 100644 --- a/src/storm/modelchecker/prctl/SymbolicDtmcPrctlModelChecker.h +++ b/src/storm/modelchecker/prctl/SymbolicDtmcPrctlModelChecker.h @@ -26,6 +26,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> computeStateFormulaProbabilities(Environment const& env, CheckTask<storm::logic::Formula, 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/SymbolicMdpPrctlModelChecker.cpp b/src/storm/modelchecker/prctl/SymbolicMdpPrctlModelChecker.cpp index 5479e4720..8f366034a 100644 --- a/src/storm/modelchecker/prctl/SymbolicMdpPrctlModelChecker.cpp +++ b/src/storm/modelchecker/prctl/SymbolicMdpPrctlModelChecker.cpp @@ -59,6 +59,16 @@ namespace storm { 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>::computeStateFormulaProbabilities(Environment const& env, CheckTask<storm::logic::Formula, ValueType> const& checkTask) { + storm::logic::Formula const& formula = checkTask.getFormula(); + STORM_LOG_THROW(checkTask.isOptimizationDirectionSet(), storm::exceptions::InvalidArgumentException, "Formula needs to specify whether minimal or maximal values are to be computed on nondeterministic model."); + std::unique_ptr<CheckResult> resultPointer = this->check(env, formula); + SymbolicQualitativeCheckResult<DdType> const& result = resultPointer->asSymbolicQualitativeCheckResult<DdType>(); + // min/max does not matters + return std::make_unique<SymbolicQuantitativeCheckResult<DdType, ValueType>>(result); + } + 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/SymbolicMdpPrctlModelChecker.h b/src/storm/modelchecker/prctl/SymbolicMdpPrctlModelChecker.h index 4fda40be3..e54f3579d 100644 --- a/src/storm/modelchecker/prctl/SymbolicMdpPrctlModelChecker.h +++ b/src/storm/modelchecker/prctl/SymbolicMdpPrctlModelChecker.h @@ -27,6 +27,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> computeStateFormulaProbabilities(Environment const& env, CheckTask<storm::logic::Formula, 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; From b6b31f20afa969f342376205ab40e0e2c6a110d8 Mon Sep 17 00:00:00 2001 From: Joachim Klein <joachim.klein@automata.tools> Date: Mon, 24 Aug 2020 22:25:13 +0200 Subject: [PATCH 025/172] (MDP-LTL) AcceptanceCondition: extractFromDNF Convert a generic acceptance condition to DNF. --- src/storm/automata/AcceptanceCondition.cpp | 45 ++++++++++++++++++++++ src/storm/automata/AcceptanceCondition.h | 3 ++ 2 files changed, 48 insertions(+) diff --git a/src/storm/automata/AcceptanceCondition.cpp b/src/storm/automata/AcceptanceCondition.cpp index 4f0a7a02a..59e4f6775 100644 --- a/src/storm/automata/AcceptanceCondition.cpp +++ b/src/storm/automata/AcceptanceCondition.cpp @@ -1,5 +1,8 @@ #include "AcceptanceCondition.h" +#include "storm/utility/macros.h" +#include "storm/exceptions/InvalidOperationException.h" + namespace storm { namespace automata { @@ -79,6 +82,48 @@ bool AcceptanceCondition::isAccepting(const storm::storage::StateBlock& scc, acc 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++) { diff --git a/src/storm/automata/AcceptanceCondition.h b/src/storm/automata/AcceptanceCondition.h index 7f1b993c8..7434cac4a 100644 --- a/src/storm/automata/AcceptanceCondition.h +++ b/src/storm/automata/AcceptanceCondition.h @@ -24,8 +24,11 @@ namespace storm { 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; std::size_t numberOfStates; unsigned int numberOfAcceptanceSets; From 5855a82e800051a092a0ef46d65479c725fc1b6d Mon Sep 17 00:00:00 2001 From: Joachim Klein <joachim.klein@automata.tools> Date: Mon, 24 Aug 2020 22:25:13 +0200 Subject: [PATCH 026/172] (MDP-LTL) CheckTask: negate() Allow a CheckTask to be negated (e.g., useful for converting from Pmin to 1-Pmax). --- src/storm/modelchecker/CheckTask.h | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) 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. From c099183063d14a38f727aa9e44b554c8f3f988cc Mon Sep 17 00:00:00 2001 From: Joachim Klein <joachim.klein@automata.tools> Date: Mon, 24 Aug 2020 22:25:14 +0200 Subject: [PATCH 027/172] (MDP-LTL) MaximalEndComponent: containsAnyState Conflicts: src/storm/storage/MaximalEndComponent.cpp --- src/storm/storage/MaximalEndComponent.cpp | 11 +++++++++++ src/storm/storage/MaximalEndComponent.h | 10 ++++++++++ 2 files changed, 21 insertions(+) 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. * From 4c70f1a160849b39d5e21844edf0e3ae8fde22e9 Mon Sep 17 00:00:00 2001 From: Joachim Klein <joachim.klein@automata.tools> Date: Mon, 24 Aug 2020 22:25:15 +0200 Subject: [PATCH 028/172] (MDP-LTL) ProductBuilder: DA product with MDP --- src/storm/transformer/ProductBuilder.h | 29 +++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/src/storm/transformer/ProductBuilder.h b/src/storm/transformer/ProductBuilder.h index bf047db14..32f3a0cea 100644 --- a/src/storm/transformer/ProductBuilder.h +++ b/src/storm/transformer/ProductBuilder.h @@ -49,6 +49,7 @@ namespace storm { } 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(); @@ -79,7 +80,33 @@ namespace storm { builder.addNextValue(prodIndexFrom, prodIndexTo, entry.getValue()); } } else { - throw std::runtime_error("nondeterministic product not yet supported"); + 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.first, 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++; + } } } From 615b2b53993ad59b9b541d7c0e1fae5fd596450f Mon Sep 17 00:00:00 2001 From: Joachim Klein <joachim.klein@automata.tools> Date: Mon, 24 Aug 2020 22:25:15 +0200 Subject: [PATCH 029/172] (MDP-LTL) SparseMdpPrctlHelper: computeSurelyAcceptingPmaxStates --- .../prctl/helper/SparseMdpPrctlHelper.cpp | 106 ++++++++++++++++++ .../prctl/helper/SparseMdpPrctlHelper.h | 13 +++ 2 files changed, 119 insertions(+) diff --git a/src/storm/modelchecker/prctl/helper/SparseMdpPrctlHelper.cpp b/src/storm/modelchecker/prctl/helper/SparseMdpPrctlHelper.cpp index 17bef0ff8..c79f6c9ae 100644 --- a/src/storm/modelchecker/prctl/helper/SparseMdpPrctlHelper.cpp +++ b/src/storm/modelchecker/prctl/helper/SparseMdpPrctlHelper.cpp @@ -745,6 +745,112 @@ namespace storm { return result; } } + + template<typename ValueType> + storm::storage::BitVector SparseMdpPrctlHelper<ValueType>::computeSurelyAcceptingPmaxStates(automata::AcceptanceCondition const& acceptance, storm::storage::SparseMatrix<ValueType> const& transitionMatrix, storm::storage::SparseMatrix<ValueType> const& backwardTransitions) { + STORM_LOG_INFO("Computing accepting states for acceptance condition " << *acceptance.getAcceptanceExpression()); + std::cout << transitionMatrix.getRowGroupCount() << std::endl; + 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 i = 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); + + STORM_LOG_INFO("Handle conjunction " << i); + + for (auto const& literal : conjunction) { + STORM_LOG_INFO(" " << *literal); + 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; + } + + STORM_LOG_INFO(" Allowed states: " << allowed); + + // compute MECs in the allowed fragment + storm::storage::MaximalEndComponentDecomposition<ValueType> mecs(transitionMatrix, backwardTransitions, allowed); + for (const auto& mec : mecs) { + STORM_LOG_INFO("Inspect MEC: " << mec); + + 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()) { + STORM_LOG_INFO("Checking against " << ~accSet); + if (!mec.containsAnyState(~accSet)) { + STORM_LOG_INFO(" -> not satisfied"); + accepting = false; + break; + } + } else { + STORM_LOG_INFO("Checking against " << accSet); + if (!mec.containsAnyState(accSet)) { + STORM_LOG_INFO(" -> not satisfied"); + 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) { + STORM_LOG_INFO("MEC is accepting"); + for (auto const& stateChoicePair : mec) { + acceptingStates.set(stateChoicePair.first); + } + } + + } + } + + STORM_LOG_INFO("Accepting states: " << acceptingStates); + return acceptingStates; + } template<typename ValueType> template<typename RewardModelType> diff --git a/src/storm/modelchecker/prctl/helper/SparseMdpPrctlHelper.h b/src/storm/modelchecker/prctl/helper/SparseMdpPrctlHelper.h index 099533dab..e70648186 100644 --- a/src/storm/modelchecker/prctl/helper/SparseMdpPrctlHelper.h +++ b/src/storm/modelchecker/prctl/helper/SparseMdpPrctlHelper.h @@ -10,6 +10,8 @@ #include "storm/modelchecker/prctl/helper/rewardbounded/MultiDimensionalRewardUnfolding.h" #include "MDPModelCheckingHelperReturnType.h" +#include "storm/automata/AcceptanceCondition.h" + #include "storm/utility/solver.h" #include "storm/solver/SolveGoal.h" @@ -47,6 +49,17 @@ namespace storm { 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); + /*! + * Compute a set S of states that admit a probability 1 strategy of satisfying the given acceptance conditon. + * 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. + */ + static storm::storage::BitVector computeSurelyAcceptingPmaxStates(automata::AcceptanceCondition const& acceptance, storm::storage::SparseMatrix<ValueType> const& transitionMatrix, storm::storage::SparseMatrix<ValueType> const& backwardTransitions); + 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); From 04a8bec83f51bd8a370343baec3b7b4a0a2a298f Mon Sep 17 00:00:00 2001 From: Joachim Klein <joachim.klein@automata.tools> Date: Mon, 24 Aug 2020 22:25:16 +0200 Subject: [PATCH 030/172] (MDP-LTL) SparseMdpPrctlModelChecker: handle LTL Conflicts: src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.cpp --- .../prctl/SparseMdpPrctlModelChecker.cpp | 155 +++++++++++++++++- .../prctl/SparseMdpPrctlModelChecker.h | 5 + .../prctl/helper/SparseMdpPrctlHelper.cpp | 27 +-- 3 files changed, 174 insertions(+), 13 deletions(-) diff --git a/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.cpp b/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.cpp index a56a8b3ef..31b3a5c1d 100644 --- a/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.cpp +++ b/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.cpp @@ -1,5 +1,7 @@ #include "storm/modelchecker/prctl/SparseMdpPrctlModelChecker.h" +#include <sstream> + #include "storm/utility/constants.h" #include "storm/utility/macros.h" #include "storm/utility/vector.h" @@ -12,6 +14,10 @@ #include "storm/logic/FragmentSpecification.h" +#include "storm/transformer/DAProductBuilder.h" +#include "storm/logic/ExtractMaximalStateFormulasVisitor.h" +#include "storm/automata/LTL2DeterministicAutomaton.h" + #include "storm/models/sparse/StandardRewardModel.h" #include "storm/modelchecker/prctl/helper/SparseMdpPrctlHelper.h" @@ -23,12 +29,14 @@ #include "storm/modelchecker/multiobjective/multiObjectiveModelChecking.h" #include "storm/solver/SolveGoal.h" - #include "storm/storage/BitVector.h" #include "storm/shields/ShieldHandling.h" +#include "storm/settings/SettingsManager.h" + #include "storm/settings/modules/GeneralSettings.h" +#include "storm/settings/modules/DebugSettings.h" #include "storm/exceptions/InvalidStateException.h" #include "storm/exceptions/InvalidPropertyException.h" @@ -48,7 +56,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); @@ -169,6 +177,149 @@ namespace storm { return std::make_unique<ExplicitQuantitativeCheckResult<ValueType>>(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."); + + std::vector<storm::logic::ExtractMaximalStateFormulasVisitor::LabelFormulaPair> extracted; + std::shared_ptr<storm::logic::Formula> ltlFormula = storm::logic::ExtractMaximalStateFormulasVisitor::extract(pathFormula, extracted); + + STORM_LOG_INFO("Extracting maximal state formulas and computing satisfaction sets for path formula: " << pathFormula); + + std::map<std::string, storm::storage::BitVector> apSets; + + for (auto& p : extracted) { + STORM_LOG_INFO(" Computing satisfaction set for atomic proposition \"" << p.first << "\" <=> " << *p.second << "..."); + + std::unique_ptr<CheckResult> subResultPointer = this->check(env, *p.second); + ExplicitQualitativeCheckResult const& subResult = subResultPointer->asExplicitQualitativeCheckResult(); + auto sat = subResult.getTruthValuesVector(); + + STORM_LOG_INFO(" Atomic proposition \"" << p.first << "\" is satisfied by " << sat.getNumberOfSetBits() << " states."); + + apSets[p.first] = std::move(sat); + } + + bool minimize = false; + CheckTask<storm::logic::Formula, ValueType> subTask(checkTask); + + if (checkTask.getOptimizationDirection() == OptimizationDirection::Minimize) { + minimize = true; + // negate + ltlFormula = std::make_shared<storm::logic::UnaryBooleanPathFormula>(storm::logic::UnaryBooleanOperatorType::Not, ltlFormula); + STORM_LOG_INFO("Computing Pmin, proceeding with negated LTL formula."); + + subTask = checkTask.negate().substituteFormula(*ltlFormula); + } else { + subTask = checkTask.substituteFormula(*ltlFormula); + } + + STORM_LOG_INFO("Resulting LTL path formula: " << *ltlFormula); + STORM_LOG_INFO(" in prefix format: " << ltlFormula->toPrefixString()); + + std::shared_ptr<storm::automata::DeterministicAutomaton> da = storm::automata::LTL2DeterministicAutomaton::ltl2da(*ltlFormula); + + STORM_LOG_INFO("Deterministic automaton for LTL formula has " + << da->getNumberOfStates() << " states, " + << da->getAPSet().size() << " atomic propositions and " + << *da->getAcceptance()->getAcceptanceExpression() << " as acceptance condition."); + + const SparseMdpModelType& mdp = this->getModel(); + storm::solver::SolveGoal<ValueType> goal(mdp, subTask); + + std::vector<ValueType> numericResult = computeDAProductProbabilities(env, std::move(goal), *da, apSets, checkTask.isQualitativeSet()); + + if (minimize) { + // compute 1-Pmax[!ltl] + for (auto& value : numericResult) { + value = storm::utility::one<ValueType>() - value; + } + } + return std::unique_ptr<CheckResult>(new ExplicitQuantitativeCheckResult<ValueType>(std::move(numericResult))); + } + + + template<typename SparseMdpModelType> + std::vector<typename SparseMdpPrctlModelChecker<SparseMdpModelType>::ValueType> SparseMdpPrctlModelChecker<SparseMdpModelType>::computeDAProductProbabilities(Environment const& env, storm::solver::SolveGoal<typename SparseMdpPrctlModelChecker<SparseMdpModelType>::ValueType>&& goal, storm::automata::DeterministicAutomaton const& da, std::map<std::string, storm::storage::BitVector>& apSatSets, bool qualitative) const { + STORM_LOG_THROW(goal.hasDirection() && goal.direction() == OptimizationDirection::Maximize, storm::exceptions::InvalidPropertyException, "Can only compute maximizing probabilties for DA product with MDP"); + + const storm::automata::APSet& apSet = da.getAPSet(); + + std::vector<storm::storage::BitVector> apLabels; + 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"); + + apLabels.push_back(std::move(it->second)); + } + + const SparseMdpModelType& mdp = this->getModel(); + + storm::storage::BitVector statesOfInterest; + if (goal.hasRelevantValues()) { + statesOfInterest = goal.relevantValues(); + } else { + // product from all model states + statesOfInterest = storm::storage::BitVector(mdp.getNumberOfStates(), true); + } + + STORM_LOG_INFO("Building MDP-DA product with deterministic automaton, starting from " << statesOfInterest.getNumberOfSetBits() << " model states..."); + storm::transformer::DAProductBuilder productBuilder(da, apLabels); + auto product = productBuilder.build(mdp, statesOfInterest); + STORM_LOG_INFO("Product MDP has " << product->getProductModel().getNumberOfStates() << " states and " + << product->getProductModel().getNumberOfTransitions() << " transitions."); + + if (storm::settings::getModule<storm::settings::modules::DebugSettings>().isTraceSet()) { + STORM_LOG_TRACE("Writing model to model.dot"); + std::ofstream modelDot("model.dot"); + mdp.writeDotToStream(modelDot); + modelDot.close(); + + STORM_LOG_TRACE("Writing product model to product.dot"); + std::ofstream productDot("product.dot"); + product->getProductModel().writeDotToStream(productDot); + productDot.close(); + + STORM_LOG_TRACE("Product model mapping:"); + std::stringstream str; + product->printMapping(str); + STORM_LOG_TRACE(str.str()); + } + + STORM_LOG_INFO("Computing accepting end components..."); + storm::storage::BitVector accepting = storm::modelchecker::helper::SparseMdpPrctlHelper<ValueType>::computeSurelyAcceptingPmaxStates(*product->getAcceptance(), product->getProductModel().getTransitionMatrix(), product->getProductModel().getBackwardTransitions()); + if (accepting.empty()) { + STORM_LOG_INFO("No accepting states, skipping probability computation."); + std::vector<ValueType> numericResult(this->getModel().getNumberOfStates(), storm::utility::zero<ValueType>()); + return numericResult; + } + + STORM_LOG_INFO("Computing probabilities for reaching accepting BSCCs..."); + + storm::storage::BitVector bvTrue(product->getProductModel().getNumberOfStates(), true); + + storm::solver::SolveGoal<ValueType> solveGoalProduct(goal); + storm::storage::BitVector soiProduct(product->getStatesOfInterest()); + solveGoalProduct.setRelevantValues(std::move(soiProduct)); + + std::vector<ValueType> prodNumericResult + = std::move(storm::modelchecker::helper::SparseMdpPrctlHelper<ValueType>::computeUntilProbabilities(env, + std::move(solveGoalProduct), + product->getProductModel().getTransitionMatrix(), + product->getProductModel().getBackwardTransitions(), + bvTrue, + accepting, + qualitative, + false // no schedulers (at the moment) + ).values); + + std::vector<ValueType> numericResult = product->projectToOriginalModel(this->getModel(), prodNumericResult); + return numericResult; + } + + 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 ad164df32..73e706596 100644 --- a/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.h +++ b/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.h @@ -4,6 +4,8 @@ #include "storm/modelchecker/propositional/SparsePropositionalModelChecker.h" #include "storm/models/sparse/Mdp.h" #include "storm/solver/MinMaxLinearEquationSolver.h" +#include "storm/solver/SolveGoal.h" + namespace storm { @@ -39,9 +41,12 @@ namespace storm { 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> computeStateFormulaProbabilities(Environment const& env, CheckTask<storm::logic::Formula, 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> 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; + private: + std::vector<ValueType> computeDAProductProbabilities(Environment const& env, storm::solver::SolveGoal<ValueType>&& goal, storm::automata::DeterministicAutomaton const& da, std::map<std::string, storm::storage::BitVector>& apSatSets, bool qualitative) const; }; } // namespace modelchecker } // namespace storm diff --git a/src/storm/modelchecker/prctl/helper/SparseMdpPrctlHelper.cpp b/src/storm/modelchecker/prctl/helper/SparseMdpPrctlHelper.cpp index c79f6c9ae..2e4cb8894 100644 --- a/src/storm/modelchecker/prctl/helper/SparseMdpPrctlHelper.cpp +++ b/src/storm/modelchecker/prctl/helper/SparseMdpPrctlHelper.cpp @@ -749,7 +749,6 @@ namespace storm { template<typename ValueType> storm::storage::BitVector SparseMdpPrctlHelper<ValueType>::computeSurelyAcceptingPmaxStates(automata::AcceptanceCondition const& acceptance, storm::storage::SparseMatrix<ValueType> const& transitionMatrix, storm::storage::SparseMatrix<ValueType> const& backwardTransitions) { STORM_LOG_INFO("Computing accepting states for acceptance condition " << *acceptance.getAcceptanceExpression()); - std::cout << transitionMatrix.getRowGroupCount() << std::endl; if (acceptance.getAcceptanceExpression()->isTRUE()) { STORM_LOG_INFO(" TRUE -> all states accepting (assumes no deadlock in the model)"); return storm::storage::BitVector(transitionMatrix.getRowGroupCount(), true); @@ -762,16 +761,18 @@ namespace storm { storm::storage::BitVector acceptingStates(transitionMatrix.getRowGroupCount(), false); + std::size_t accMECs = 0; + std::size_t allMECs = 0; std::size_t i = 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); - STORM_LOG_INFO("Handle conjunction " << i); + STORM_LOG_DEBUG("Handle conjunction " << i); for (auto const& literal : conjunction) { - STORM_LOG_INFO(" " << *literal); + STORM_LOG_DEBUG(" " << *literal); if (literal->isTRUE()) { // skip } else if (literal->isFALSE()) { @@ -798,12 +799,13 @@ namespace storm { continue; } - STORM_LOG_INFO(" Allowed states: " << allowed); + STORM_LOG_DEBUG(" Allowed states: " << allowed); // compute MECs in the allowed fragment storm::storage::MaximalEndComponentDecomposition<ValueType> mecs(transitionMatrix, backwardTransitions, allowed); + allMECs += mecs.size(); for (const auto& mec : mecs) { - STORM_LOG_INFO("Inspect MEC: " << mec); + STORM_LOG_DEBUG("Inspect MEC: " << mec); bool accepting = true; for (auto const& literal : conjunction) { @@ -817,16 +819,16 @@ namespace storm { const storm::storage::BitVector& accSet = acceptance.getAcceptanceSet(atom.getAcceptanceSet()); if (atom.getType() == cpphoafparser::AtomAcceptance::TEMPORAL_INF) { if (atom.isNegated()) { - STORM_LOG_INFO("Checking against " << ~accSet); + STORM_LOG_DEBUG("Checking against " << ~accSet); if (!mec.containsAnyState(~accSet)) { - STORM_LOG_INFO(" -> not satisfied"); + STORM_LOG_DEBUG(" -> not satisfied"); accepting = false; break; } } else { - STORM_LOG_INFO("Checking against " << accSet); + STORM_LOG_DEBUG("Checking against " << accSet); if (!mec.containsAnyState(accSet)) { - STORM_LOG_INFO(" -> not satisfied"); + STORM_LOG_DEBUG(" -> not satisfied"); accepting = false; break; } @@ -839,7 +841,8 @@ namespace storm { } if (accepting) { - STORM_LOG_INFO("MEC is accepting"); + accMECs++; + STORM_LOG_DEBUG("MEC is accepting"); for (auto const& stateChoicePair : mec) { acceptingStates.set(stateChoicePair.first); } @@ -848,7 +851,9 @@ namespace storm { } } - STORM_LOG_INFO("Accepting states: " << acceptingStates); + STORM_LOG_DEBUG("Accepting states: " << acceptingStates); + STORM_LOG_INFO("Found " << acceptingStates.getNumberOfSetBits() << " states in " << accMECs << " accepting MECs (considered " << allMECs << " MECs)."); + return acceptingStates; } From 819d97b712f51a271d19c9bee4c2a7a680ff5f83 Mon Sep 17 00:00:00 2001 From: Joachim Klein <joachim.klein@automata.tools> Date: Mon, 24 Aug 2020 22:25:19 +0200 Subject: [PATCH 031/172] (CTMC-LTL) FragmentSpecification: cslstar and csrlstar Conflicts: src/storm/logic/FragmentSpecification.cpp src/storm/logic/FragmentSpecification.h --- src/storm/logic/FragmentSpecification.cpp | 24 +++++++++++++++++++++++ src/storm/logic/FragmentSpecification.h | 6 ++++++ 2 files changed, 30 insertions(+) diff --git a/src/storm/logic/FragmentSpecification.cpp b/src/storm/logic/FragmentSpecification.cpp index 314bca97f..3bd34e629 100644 --- a/src/storm/logic/FragmentSpecification.cpp +++ b/src/storm/logic/FragmentSpecification.cpp @@ -121,6 +121,17 @@ namespace storm { return csl; } + FragmentSpecification cslstar() { + FragmentSpecification cslstar = csl(); + + cslstar.setBinaryBooleanPathFormulasAllowed(true); + cslstar.setUnaryBooleanPathFormulasAllowed(true); + cslstar.setNestedOperatorsAllowed(true); + cslstar.setNestedPathFormulasAllowed(true); + + return cslstar; + } + FragmentSpecification csrl() { FragmentSpecification csrl = csl(); @@ -134,6 +145,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(); diff --git a/src/storm/logic/FragmentSpecification.h b/src/storm/logic/FragmentSpecification.h index 8c50c635a..18b8a8686 100644 --- a/src/storm/logic/FragmentSpecification.h +++ b/src/storm/logic/FragmentSpecification.h @@ -264,9 +264,15 @@ namespace storm { // 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(); From 3a769b3149d86fc62409357049b4879c38f56169 Mon Sep 17 00:00:00 2001 From: Tim Quatmann <tim.quatmann@cs.rwth-aachen.de> Date: Thu, 11 Mar 2021 07:58:49 +0100 Subject: [PATCH 032/172] ToPrefixStringVisitor: Added missing case for GameFormula --- src/storm/logic/ToPrefixStringVisitor.cpp | 4 ++++ src/storm/logic/ToPrefixStringVisitor.h | 1 + 2 files changed, 5 insertions(+) diff --git a/src/storm/logic/ToPrefixStringVisitor.cpp b/src/storm/logic/ToPrefixStringVisitor.cpp index a3d55b994..6fc7640e4 100644 --- a/src/storm/logic/ToPrefixStringVisitor.cpp +++ b/src/storm/logic/ToPrefixStringVisitor.cpp @@ -85,6 +85,10 @@ namespace storm { 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"); } diff --git a/src/storm/logic/ToPrefixStringVisitor.h b/src/storm/logic/ToPrefixStringVisitor.h index 95d1bc585..16b8fad4a 100644 --- a/src/storm/logic/ToPrefixStringVisitor.h +++ b/src/storm/logic/ToPrefixStringVisitor.h @@ -22,6 +22,7 @@ namespace storm { 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; From 9ce60766892ad52615587ade9c04fe1d0dae7e35 Mon Sep 17 00:00:00 2001 From: Tim Quatmann <tim.quatmann@cs.rwth-aachen.de> Date: Thu, 11 Mar 2021 08:02:27 +0100 Subject: [PATCH 033/172] Silenced a warning --- src/storm/automata/AcceptanceCondition.cpp | 2 +- src/storm/automata/AcceptanceCondition.h | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/src/storm/automata/AcceptanceCondition.cpp b/src/storm/automata/AcceptanceCondition.cpp index 59e4f6775..14eb9c818 100644 --- a/src/storm/automata/AcceptanceCondition.cpp +++ b/src/storm/automata/AcceptanceCondition.cpp @@ -7,7 +7,7 @@ namespace storm { namespace automata { AcceptanceCondition::AcceptanceCondition(std::size_t numberOfStates, unsigned int numberOfAcceptanceSets, acceptance_expr::ptr acceptance) - : numberOfStates(numberOfStates), numberOfAcceptanceSets(numberOfAcceptanceSets), acceptance(acceptance) { + : numberOfAcceptanceSets(numberOfAcceptanceSets), acceptance(acceptance) { // initialize acceptance sets for (unsigned int i = 0; i < numberOfAcceptanceSets; i++) { diff --git a/src/storm/automata/AcceptanceCondition.h b/src/storm/automata/AcceptanceCondition.h index 7434cac4a..a70a96e10 100644 --- a/src/storm/automata/AcceptanceCondition.h +++ b/src/storm/automata/AcceptanceCondition.h @@ -30,7 +30,6 @@ namespace storm { 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; - std::size_t numberOfStates; unsigned int numberOfAcceptanceSets; acceptance_expr::ptr acceptance; std::vector<storm::storage::BitVector> acceptanceSets; From 4fe4704f60009acaa083e1c6be225d07c0571cb2 Mon Sep 17 00:00:00 2001 From: Tim Quatmann <tim.quatmann@cs.rwth-aachen.de> Date: Thu, 11 Mar 2021 10:27:04 +0100 Subject: [PATCH 034/172] Silenced a couple of warnings triggered by cpphoafparser. --- .../hoa_intermediate_check_validity.hh | 8 ++++---- .../parser/hoa_parser_exception.hh | 18 +++++++++++++++++- .../cpphoafparser/util/int_or_string.hh | 2 +- 3 files changed, 22 insertions(+), 6 deletions(-) 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 index 554404c95..9cbffefbb 100644 --- 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 @@ -118,7 +118,7 @@ public: next->addAlias(name, labelExpr); } - virtual void setAPs(const std::vector<std::string>& aps) { + virtual void setAPs(const std::vector<std::string>& aps) override { headerAtMostOnce("AP"); numberOfAPs.reset(new unsigned int(aps.size())); @@ -162,7 +162,7 @@ public: next->setTool(name, version); } - virtual void addProperties(const std::vector<std::string>& properties) { + virtual void addProperties(const std::vector<std::string>& properties) override { usedHeaders.insert("properties"); for (const std::string& property : properties) { @@ -207,7 +207,7 @@ public: next->addMiscHeader(name, content); } - virtual void notifyBodyStart() { + virtual void notifyBodyStart() override { // check for existence of mandatory headers headerIsMandatory("Acceptance"); @@ -418,7 +418,7 @@ public: next->notifyEnd(); } - virtual void notifyAbort() { + virtual void notifyAbort() override { next->notifyAbort(); } 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 index 1d0a4ebdf..46834d644 100644 --- 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 @@ -43,7 +43,23 @@ public: /** 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; 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 index 3bf37f23e..74b1201d8 100644 --- 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 @@ -50,7 +50,7 @@ public: * @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(false) {} + 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;} From b6800361ce4e00b3046afe231ca39958fd23fb98 Mon Sep 17 00:00:00 2001 From: hannah <hannah.mertens@rwth-aachen.de> Date: Wed, 7 Apr 2021 00:45:00 +0200 Subject: [PATCH 035/172] ltl formula parser tests --- src/test/storm/parser/FormulaParserTest.cpp | 143 +++++++++++++++++++- 1 file changed, 142 insertions(+), 1 deletion(-) diff --git a/src/test/storm/parser/FormulaParserTest.cpp b/src/test/storm/parser/FormulaParserTest.cpp index 52e1d2dbf..3831976e2 100644 --- a/src/test/storm/parser/FormulaParserTest.cpp +++ b/src/test/storm/parser/FormulaParserTest.cpp @@ -155,7 +155,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"); @@ -206,3 +205,145 @@ 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\" | (X \"b\")]"; // X(a|Xb) todo why is this allowed, but not [X \"a\" | X \"b\"] + ASSERT_NO_THROW(formula = formulaParser.parseSingleFormulaFromString(input)); + auto const &nested5 = formula->asProbabilityOperatorFormula().getSubformula(); + EXPECT_TRUE(nested5.isNextFormula()); + EXPECT_TRUE(nested5.asNextFormula().getSubformula().isBinaryBooleanPathFormula()); + auto const &nested5Subformula = nested5.asNextFormula().getSubformula().asBinaryPathFormula(); + EXPECT_TRUE(nested5.asNextFormula().getSubformula().asBinaryPathFormula().getLeftSubformula().isAtomicLabelFormula()); + EXPECT_TRUE(nested5.asNextFormula().getSubformula().asBinaryPathFormula().getRightSubformula().isNextFormula()); +} + +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\"]"; // (X F 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().isUntilFormula()); + EXPECT_TRUE(nested3.asUntilFormula().getLeftSubformula().asUntilFormula().getLeftSubformula().isNextFormula()); + EXPECT_TRUE(nested3.asUntilFormula().getRightSubformula().isGloballyFormula()); +} + +TEST(FormulaParserTest, NestedUntilTest) { + storm::parser::FormulaParser formulaParser; + std::string input = "P<0.9 [\"a\" U (\"b\" U \"c\")]"; + std::shared_ptr<storm::logic::Formula const> formula(nullptr); + + ASSERT_NO_THROW(formula = formulaParser.parseSingleFormulaFromString(input)); + auto const &nested1 = formula->asProbabilityOperatorFormula().getSubformula(); + EXPECT_TRUE(nested1.isUntilFormula()); + EXPECT_FALSE(nested1.isBoundedUntilFormula()); + ASSERT_TRUE( nested1.asUntilFormula().getLeftSubformula().isAtomicLabelFormula()); + ASSERT_TRUE(nested1.asUntilFormula().getRightSubformula().isUntilFormula()); + + input = "P<0.9 [\"a\" U \"b\" U \"c\"]"; // Nested Until without parentheses: (a U b) U c + ASSERT_NO_THROW(formula = formulaParser.parseSingleFormulaFromString(input)); + auto const &nested2 = formula->asProbabilityOperatorFormula().getSubformula(); + EXPECT_TRUE(nested2.isUntilFormula()); + EXPECT_FALSE(nested2.isBoundedUntilFormula()); + ASSERT_TRUE(nested2.asUntilFormula().getLeftSubformula().isUntilFormula()); + ASSERT_TRUE(nested2.asUntilFormula().getRightSubformula().isAtomicLabelFormula()); +} + +TEST(FormulaParserTest, ComplexPathFormulaTest) { + storm::parser::FormulaParser formulaParser; + std::shared_ptr<storm::logic::Formula const> formula(nullptr); + formula = formulaParser.parseSingleFormulaFromString( "P=? [(X \"a\") U ( \"b\"& \"c\")]"); + + 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()); +} + +TEST(FormulaParserTest, LtlWrongFormatTest) { + storm::parser::FormulaParser formulaParser; + std::shared_ptr<storm::logic::Formula const> formula(nullptr); + + std::string input = "P<0.9 [F \"a\" & X \"b\"]"; + STORM_SILENT_EXPECT_THROW(formula = formulaParser.parseSingleFormulaFromString(input), storm::exceptions::WrongFormatException); + + input = "P<0.9 [X \"a\" & G \"b\"]"; + STORM_SILENT_EXPECT_THROW(formula = formulaParser.parseSingleFormulaFromString(input), storm::exceptions::WrongFormatException); + + input = "P<0.9 [G \"a\" & G \"b\"]"; + STORM_SILENT_EXPECT_THROW(formula = formulaParser.parseSingleFormulaFromString(input), storm::exceptions::WrongFormatException); + + input = "P<0.9 [(G \"a\") & G \"b\"]"; //todo why? + STORM_SILENT_EXPECT_THROW(formula = formulaParser.parseSingleFormulaFromString(input), storm::exceptions::WrongFormatException); + + input = "P<0.9 [! X \"b\"]"; + STORM_SILENT_EXPECT_THROW(formula = formulaParser.parseSingleFormulaFromString(input), storm::exceptions::WrongFormatException); +} From 02b77707d482a9983ec1cbe4c07222d591d2c705 Mon Sep 17 00:00:00 2001 From: hannah <hannah.mertens@rwth-aachen.de> Date: Wed, 7 Apr 2021 00:46:03 +0200 Subject: [PATCH 036/172] ltl dtmc modelchecker tests --- .../prctl/dtmc/DtmcPrctlModelCheckerTest.cpp | 67 ++++++++++++++++++- 1 file changed, 65 insertions(+), 2 deletions(-) diff --git a/src/test/storm/modelchecker/prctl/dtmc/DtmcPrctlModelCheckerTest.cpp b/src/test/storm/modelchecker/prctl/dtmc/DtmcPrctlModelCheckerTest.cpp index 7d7e4812b..fd1c70a52 100755 --- a/src/test/storm/modelchecker/prctl/dtmc/DtmcPrctlModelCheckerTest.cpp +++ b/src/test/storm/modelchecker/prctl/dtmc/DtmcPrctlModelCheckerTest.cpp @@ -30,6 +30,8 @@ #include "storm/environment/solver/EigenSolverEnvironment.h" #include "storm/environment/solver/TopologicalSolverEnvironment.h" +#include <cstdlib> //todo + namespace { enum class DtmcEngine {PrismSparse, JaniSparse, JitSparse, Hybrid, PrismDd, JaniDd}; @@ -630,13 +632,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 +718,65 @@ namespace { EXPECT_NEAR(0, result[12], 1e-6); } + TEST(DtmcPrctlModelCheckerTest, LtlProbabilitiesDie) { + setenv("LTL2DA", "ltl2da-ltl2tgba", true); //todo set PATH variable + + std::string formulasString = "P=? [(X s>0) U (s=7 & d=2)]"; + formulasString += "; P=? [ X (s=1) U (s=3) U (s=7)]"; // a U b U c is Treated as: ( a U b ) U c + formulasString += "; P=? [ G s!=3 U (\"three\") ]"; + formulasString += "; P=? [ (F (X (s=6 & (XX s=5) ))) & (F G (d!=5))]"; + formulasString += "; P=? [ F ((s=6) & (X \"done\"))]"; + + storm::prism::Program program = storm::api::parseProgram(STORM_TEST_RESOURCES_DIR "/dtmc/die.pm"); + auto formulas = storm::api::extractFormulasFromProperties(storm::api::parsePropertiesForPrismProgram(formulasString, program)); + std::vector<storm::modelchecker::CheckTask<storm::logic::Formula, double>> tasks; + for (auto const& f : formulas) { + tasks.emplace_back(*f); + } + auto model = storm::api::buildSparseModel<double>(program, formulas)->as<storm::models::sparse::Dtmc<double>>(); + auto checker = storm::modelchecker::SparseDtmcPrctlModelChecker<storm::models::sparse::Dtmc<double>>(*model); + std::unique_ptr<storm::modelchecker::CheckResult> result; + + result = checker.check(tasks[0]); + EXPECT_NEAR(1/6, result->asQuantitativeCheckResult<double>().getMin(), 1e-6); + + result = checker.check(tasks[1]); + EXPECT_NEAR(1/6, result->asQuantitativeCheckResult<double>().getMin(), 1e-6); + + result = checker.check(tasks[2]); + EXPECT_NEAR(1/8, result->asQuantitativeCheckResult<double>().getMin(), 1e-6); + + result = checker.check(tasks[3]); + EXPECT_NEAR(1/24, result->asQuantitativeCheckResult<double>().getMin(), 1e-6); + + result = checker.check(tasks[4]); + EXPECT_NEAR(1/2, result->asQuantitativeCheckResult<double>().getMin(), 1e-6); + } + + TEST(DtmcPrctlModelCheckerTest, LtlProbabilitiesSynchronousLeader) { + setenv("LTL2DA", "ltl2da-ltl2tgba", true); + std::string formulasString = "P=? [X (u1=true U \"elected\")]"; + formulasString += "; P=? [X v1=2 & (X v1=1)]"; // (X v1=2 & (XX v1=1) + formulasString += "; P=? [(X v1=2) & (X v1=1)]"; + + storm::prism::Program program = storm::api::parseProgram(STORM_TEST_RESOURCES_DIR "/dtmc/leader-3-5.pm"); + auto formulas = storm::api::extractFormulasFromProperties(storm::api::parsePropertiesForPrismProgram(formulasString, program)); + std::vector<storm::modelchecker::CheckTask<storm::logic::Formula, double>> tasks; + for (auto const& f : formulas) { + tasks.emplace_back(*f); + } + auto model = storm::api::buildSparseModel<double>(program, formulas)->as<storm::models::sparse::Dtmc<double>>(); + auto checker = storm::modelchecker::SparseDtmcPrctlModelChecker<storm::models::sparse::Dtmc<double>>(*model); + std::unique_ptr<storm::modelchecker::CheckResult> result; + + result= checker.check(tasks[0]); + EXPECT_NEAR(16/25, result->asQuantitativeCheckResult<double>().getMin(), 1e-6); + + result = checker.check(tasks[1]); + EXPECT_NEAR(1/25, result->asQuantitativeCheckResult<double>().getMin(), 1e-6); + + result = checker.check(tasks[2]); + EXPECT_NEAR(0, result->asQuantitativeCheckResult<double>().getMin(), 1e-6); + } + } From affee2bc5b6a4e20b3d2b10eaa0800fc2dd03da0 Mon Sep 17 00:00:00 2001 From: hannah <hannah.mertens@rwth-aachen.de> Date: Wed, 7 Apr 2021 01:18:33 +0200 Subject: [PATCH 037/172] ltl dtmc modelchecker tests --- .../storm/modelchecker/prctl/dtmc/DtmcPrctlModelCheckerTest.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/storm/modelchecker/prctl/dtmc/DtmcPrctlModelCheckerTest.cpp b/src/test/storm/modelchecker/prctl/dtmc/DtmcPrctlModelCheckerTest.cpp index fd1c70a52..dc3eb96ac 100755 --- a/src/test/storm/modelchecker/prctl/dtmc/DtmcPrctlModelCheckerTest.cpp +++ b/src/test/storm/modelchecker/prctl/dtmc/DtmcPrctlModelCheckerTest.cpp @@ -722,7 +722,7 @@ namespace { setenv("LTL2DA", "ltl2da-ltl2tgba", true); //todo set PATH variable std::string formulasString = "P=? [(X s>0) U (s=7 & d=2)]"; - formulasString += "; P=? [ X (s=1) U (s=3) U (s=7)]"; // a U b U c is Treated as: ( a U b ) U c + formulasString += "; P=? [ X (s=1) U (s=3) U (s=7)]"; // a U b U c is Treated as: (a U b ) U c formulasString += "; P=? [ G s!=3 U (\"three\") ]"; formulasString += "; P=? [ (F (X (s=6 & (XX s=5) ))) & (F G (d!=5))]"; formulasString += "; P=? [ F ((s=6) & (X \"done\"))]"; From bcf45f68df5d714ea08aaec1b58758288d345fa1 Mon Sep 17 00:00:00 2001 From: hannah <hannah.mertens@rwth-aachen.de> Date: Thu, 8 Apr 2021 11:07:13 +0200 Subject: [PATCH 038/172] modelchecker test update --- .../prctl/dtmc/DtmcPrctlModelCheckerTest.cpp | 27 ++++++++++++++----- 1 file changed, 20 insertions(+), 7 deletions(-) diff --git a/src/test/storm/modelchecker/prctl/dtmc/DtmcPrctlModelCheckerTest.cpp b/src/test/storm/modelchecker/prctl/dtmc/DtmcPrctlModelCheckerTest.cpp index dc3eb96ac..4367cee7d 100755 --- a/src/test/storm/modelchecker/prctl/dtmc/DtmcPrctlModelCheckerTest.cpp +++ b/src/test/storm/modelchecker/prctl/dtmc/DtmcPrctlModelCheckerTest.cpp @@ -722,10 +722,12 @@ namespace { setenv("LTL2DA", "ltl2da-ltl2tgba", true); //todo set PATH variable std::string formulasString = "P=? [(X s>0) U (s=7 & d=2)]"; - formulasString += "; P=? [ X (s=1) U (s=3) U (s=7)]"; // a U b U c is Treated as: (a U b ) U c - formulasString += "; P=? [ G s!=3 U (\"three\") ]"; - formulasString += "; P=? [ (F (X (s=6 & (XX s=5) ))) & (F G (d!=5))]"; - formulasString += "; P=? [ F ((s=6) & (X \"done\"))]"; + 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\")]"; //todo without () + formulasString += "; P=? [ (F s=6) & (X \"done\")]"; storm::prism::Program program = storm::api::parseProgram(STORM_TEST_RESOURCES_DIR "/dtmc/die.pm"); auto formulas = storm::api::extractFormulasFromProperties(storm::api::parsePropertiesForPrismProgram(formulasString, program)); @@ -744,20 +746,27 @@ namespace { EXPECT_NEAR(1/6, result->asQuantitativeCheckResult<double>().getMin(), 1e-6); result = checker.check(tasks[2]); - EXPECT_NEAR(1/8, result->asQuantitativeCheckResult<double>().getMin(), 1e-6); + EXPECT_NEAR(1/24, result->asQuantitativeCheckResult<double>().getMin(), 1e-6); result = checker.check(tasks[3]); - EXPECT_NEAR(1/24, result->asQuantitativeCheckResult<double>().getMin(), 1e-6); + EXPECT_NEAR(1/6, result->asQuantitativeCheckResult<double>().getMin(), 1e-6); result = checker.check(tasks[4]); + EXPECT_NEAR(0, result->asQuantitativeCheckResult<double>().getMin(), 1e-6); + + result = checker.check(tasks[5]); EXPECT_NEAR(1/2, result->asQuantitativeCheckResult<double>().getMin(), 1e-6); + + result = checker.check(tasks[6]); + EXPECT_NEAR(0, result->asQuantitativeCheckResult<double>().getMin(), 1e-6); } TEST(DtmcPrctlModelCheckerTest, LtlProbabilitiesSynchronousLeader) { setenv("LTL2DA", "ltl2da-ltl2tgba", true); std::string formulasString = "P=? [X (u1=true U \"elected\")]"; - formulasString += "; P=? [X v1=2 & (X v1=1)]"; // (X v1=2 & (XX v1=1) + formulasString += "; P=? [X v1=2 & (X v1=1)]"; // (X v1=2 & (XX v1=1)) formulasString += "; P=? [(X v1=2) & (X v1=1)]"; + //todo (X v1=2 & XX v1=1) storm::prism::Program program = storm::api::parseProgram(STORM_TEST_RESOURCES_DIR "/dtmc/leader-3-5.pm"); auto formulas = storm::api::extractFormulasFromProperties(storm::api::parsePropertiesForPrismProgram(formulasString, program)); @@ -777,6 +786,10 @@ namespace { result = checker.check(tasks[2]); EXPECT_NEAR(0, result->asQuantitativeCheckResult<double>().getMin(), 1e-6); + + // (X v1=2 & XX v1=1) + //result = checker.check(tasks[3]); + //EXPECT_NEAR(1/25, result->asQuantitativeCheckResult<double>().getMin(), 1e-6); } } From 10e2d85cc4e9db8ab82139b1317acec59b43f396 Mon Sep 17 00:00:00 2001 From: Tim Quatmann <tim.quatmann@cs.rwth-aachen.de> Date: Thu, 8 Apr 2021 16:50:12 +0200 Subject: [PATCH 039/172] Formulas: Added parentheses to formula output to avoid ambiguity --- src/storm/logic/AtomicExpressionFormula.cpp | 9 ++++++++- src/storm/logic/AtomicExpressionFormula.h | 2 +- src/storm/logic/AtomicLabelFormula.cpp | 3 ++- src/storm/logic/AtomicLabelFormula.h | 2 +- src/storm/logic/BinaryBooleanPathFormula.cpp | 14 +++++++++----- src/storm/logic/BinaryBooleanPathFormula.h | 2 +- src/storm/logic/BinaryBooleanStateFormula.cpp | 14 +++++++++----- src/storm/logic/BinaryBooleanStateFormula.h | 2 +- src/storm/logic/BooleanLiteralFormula.cpp | 3 ++- src/storm/logic/BooleanLiteralFormula.h | 2 +- src/storm/logic/BoundedUntilFormula.cpp | 13 +++++++++---- src/storm/logic/BoundedUntilFormula.h | 2 +- src/storm/logic/ConditionalFormula.cpp | 12 +++++++++--- src/storm/logic/ConditionalFormula.h | 2 +- src/storm/logic/CumulativeRewardFormula.cpp | 3 ++- src/storm/logic/CumulativeRewardFormula.h | 2 +- src/storm/logic/EventuallyFormula.cpp | 10 ++++++++-- src/storm/logic/EventuallyFormula.h | 2 +- src/storm/logic/Formula.cpp | 4 ++++ src/storm/logic/Formula.h | 10 +++++++++- src/storm/logic/GameFormula.cpp | 5 +++-- src/storm/logic/GameFormula.h | 2 +- src/storm/logic/GloballyFormula.cpp | 10 ++++++++-- src/storm/logic/GloballyFormula.h | 2 +- src/storm/logic/HOAPathFormula.cpp | 3 ++- src/storm/logic/HOAPathFormula.h | 2 +- src/storm/logic/InstantaneousRewardFormula.cpp | 3 ++- src/storm/logic/InstantaneousRewardFormula.h | 2 +- src/storm/logic/LongRunAverageOperatorFormula.cpp | 7 ++++--- src/storm/logic/LongRunAverageOperatorFormula.h | 2 +- src/storm/logic/LongRunAverageRewardFormula.cpp | 3 ++- src/storm/logic/LongRunAverageRewardFormula.h | 2 +- src/storm/logic/MultiObjectiveFormula.cpp | 3 ++- src/storm/logic/MultiObjectiveFormula.h | 2 +- src/storm/logic/NextFormula.cpp | 10 ++++++++-- src/storm/logic/NextFormula.h | 2 +- src/storm/logic/OperatorFormula.cpp | 3 ++- src/storm/logic/OperatorFormula.h | 2 +- src/storm/logic/ProbabilityOperatorFormula.cpp | 5 +++-- src/storm/logic/ProbabilityOperatorFormula.h | 2 +- src/storm/logic/QuantileFormula.cpp | 3 ++- src/storm/logic/QuantileFormula.h | 2 +- src/storm/logic/RewardOperatorFormula.cpp | 3 ++- src/storm/logic/RewardOperatorFormula.h | 2 +- src/storm/logic/TimeOperatorFormula.cpp | 3 ++- src/storm/logic/TimeOperatorFormula.h | 2 +- src/storm/logic/TotalRewardFormula.cpp | 3 ++- src/storm/logic/TotalRewardFormula.h | 2 +- src/storm/logic/UnaryBooleanPathFormula.cpp | 13 +++++++++---- src/storm/logic/UnaryBooleanPathFormula.h | 2 +- src/storm/logic/UnaryBooleanStateFormula.cpp | 13 +++++++++---- src/storm/logic/UnaryBooleanStateFormula.h | 2 +- src/storm/logic/UntilFormula.cpp | 12 +++++++++--- src/storm/logic/UntilFormula.h | 2 +- 54 files changed, 168 insertions(+), 81 deletions(-) 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/BinaryBooleanPathFormula.cpp b/src/storm/logic/BinaryBooleanPathFormula.cpp index b759db23b..1b1b45bf0 100644 --- a/src/storm/logic/BinaryBooleanPathFormula.cpp +++ b/src/storm/logic/BinaryBooleanPathFormula.cpp @@ -41,15 +41,19 @@ namespace storm { return this->getOperator() == OperatorType::Or; } - std::ostream& BinaryBooleanPathFormula::writeToStream(std::ostream& out) const { - out << "("; - this->getLeftSubformula().writeToStream(out); + 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); - out << ")"; + this->getRightSubformula().writeToStream(out, true); + if (allowParentheses) { + out << ")"; + } return out; } } diff --git a/src/storm/logic/BinaryBooleanPathFormula.h b/src/storm/logic/BinaryBooleanPathFormula.h index 10286f23f..344aed715 100644 --- a/src/storm/logic/BinaryBooleanPathFormula.h +++ b/src/storm/logic/BinaryBooleanPathFormula.h @@ -31,7 +31,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/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 085b4fb24..26bb3b717 100644 --- a/src/storm/logic/BinaryBooleanStateFormula.h +++ b/src/storm/logic/BinaryBooleanStateFormula.h @@ -27,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/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/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/Formula.cpp b/src/storm/logic/Formula.cpp index 752389b36..b71316097 100644 --- a/src/storm/logic/Formula.cpp +++ b/src/storm/logic/Formula.cpp @@ -179,6 +179,10 @@ namespace storm { bool Formula::isOperatorFormula() const { return false; } + + bool Formula::isUnaryFormula() const { + return isUnaryPathFormula() || isUnaryStateFormula(); + } bool Formula::hasQualitativeResult() const { return true; diff --git a/src/storm/logic/Formula.h b/src/storm/logic/Formula.h index 72631e2fe..92100326a 100644 --- a/src/storm/logic/Formula.h +++ b/src/storm/logic/Formula.h @@ -94,6 +94,7 @@ 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; @@ -236,7 +237,14 @@ namespace storm { 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; 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 index 915f4f13d..cd17a6a46 100644 --- a/src/storm/logic/HOAPathFormula.cpp +++ b/src/storm/logic/HOAPathFormula.cpp @@ -76,7 +76,8 @@ namespace storm { } - std::ostream& HOAPathFormula::writeToStream(std::ostream& out) const { + std::ostream& HOAPathFormula::writeToStream(std::ostream& out, bool /* allowParentheses */ ) const { + // No parentheses necessary out << "HOA: { "; out << "\"" << automatonFile << "\""; for (auto& mapping : apToFormulaMap) { diff --git a/src/storm/logic/HOAPathFormula.h b/src/storm/logic/HOAPathFormula.h index 81352243e..fd9ba1a93 100644 --- a/src/storm/logic/HOAPathFormula.h +++ b/src/storm/logic/HOAPathFormula.h @@ -39,7 +39,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; std::shared_ptr<storm::automata::DeterministicAutomaton> readAutomaton() const; 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/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..faf774958 100644 --- a/src/storm/logic/MultiObjectiveFormula.h +++ b/src/storm/logic/MultiObjectiveFormula.h @@ -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..4bfe0a5a1 100644 --- a/src/storm/logic/QuantileFormula.h +++ b/src/storm/logic/QuantileFormula.h @@ -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/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/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/UnaryBooleanPathFormula.cpp b/src/storm/logic/UnaryBooleanPathFormula.cpp index 7613032b6..707599e0b 100644 --- a/src/storm/logic/UnaryBooleanPathFormula.cpp +++ b/src/storm/logic/UnaryBooleanPathFormula.cpp @@ -36,12 +36,17 @@ namespace storm { return this->getOperator() == OperatorType::Not; } - std::ostream& UnaryBooleanPathFormula::writeToStream(std::ostream& out) const { + std::ostream& UnaryBooleanPathFormula::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/UnaryBooleanPathFormula.h b/src/storm/logic/UnaryBooleanPathFormula.h index 3323f6949..f8a78aed5 100644 --- a/src/storm/logic/UnaryBooleanPathFormula.h +++ b/src/storm/logic/UnaryBooleanPathFormula.h @@ -28,7 +28,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/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 4c3cd3c17..14aef7eb1 100644 --- a/src/storm/logic/UnaryBooleanStateFormula.h +++ b/src/storm/logic/UnaryBooleanStateFormula.h @@ -24,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; }; } } From 7d74efd5919b13c3e54a63b97f80ad39f73dd2ff Mon Sep 17 00:00:00 2001 From: hannah <hannah.mertens@rwth-aachen.de> Date: Thu, 8 Apr 2021 22:26:37 +0200 Subject: [PATCH 040/172] TYPED_TESTS for LTL modelchecker --- .../prctl/dtmc/DtmcPrctlModelCheckerTest.cpp | 100 ++++++++++-------- 1 file changed, 56 insertions(+), 44 deletions(-) diff --git a/src/test/storm/modelchecker/prctl/dtmc/DtmcPrctlModelCheckerTest.cpp b/src/test/storm/modelchecker/prctl/dtmc/DtmcPrctlModelCheckerTest.cpp index 4367cee7d..af1882e5a 100755 --- a/src/test/storm/modelchecker/prctl/dtmc/DtmcPrctlModelCheckerTest.cpp +++ b/src/test/storm/modelchecker/prctl/dtmc/DtmcPrctlModelCheckerTest.cpp @@ -718,78 +718,90 @@ namespace { EXPECT_NEAR(0, result[12], 1e-6); } - TEST(DtmcPrctlModelCheckerTest, LtlProbabilitiesDie) { - setenv("LTL2DA", "ltl2da-ltl2tgba", true); //todo set PATH variable + TYPED_TEST(DtmcPrctlModelCheckerTest, LtlProbabilitiesDie) { + setenv("LTL2DA", "ltl2da-ltl2tgba", true); 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\")]"; //todo without () + formulasString += "; P=? [ F (s=6) & (X \"done\")]"; // TODO without () formulasString += "; P=? [ (F s=6) & (X \"done\")]"; - storm::prism::Program program = storm::api::parseProgram(STORM_TEST_RESOURCES_DIR "/dtmc/die.pm"); - auto formulas = storm::api::extractFormulasFromProperties(storm::api::parsePropertiesForPrismProgram(formulasString, program)); - std::vector<storm::modelchecker::CheckTask<storm::logic::Formula, double>> tasks; - for (auto const& f : formulas) { - tasks.emplace_back(*f); - } - auto model = storm::api::buildSparseModel<double>(program, formulas)->as<storm::models::sparse::Dtmc<double>>(); - auto checker = storm::modelchecker::SparseDtmcPrctlModelChecker<storm::models::sparse::Dtmc<double>>(*model); + 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; - result = checker.check(tasks[0]); - EXPECT_NEAR(1/6, result->asQuantitativeCheckResult<double>().getMin(), 1e-6); + // LTL not supported in all engines (Hybrid, PrismDd, JaniDd) + if (TypeParam::engine == DtmcEngine::PrismSparse || TypeParam::engine == DtmcEngine::JaniSparse || TypeParam::engine == DtmcEngine::JitSparse) { + EXPECT_TRUE(checker->canHandle(tasks[0])); + result = checker->check(tasks[0]); + EXPECT_NEAR(this->parseNumber("1/6"), this->getQuantitativeResultAtInitialState(model, result), this->precision()); - result = checker.check(tasks[1]); - EXPECT_NEAR(1/6, result->asQuantitativeCheckResult<double>().getMin(), 1e-6); + result = checker->check(tasks[1]); + EXPECT_NEAR(this->parseNumber("1/6"), this->getQuantitativeResultAtInitialState(model, result), this->precision()); - result = checker.check(tasks[2]); - EXPECT_NEAR(1/24, result->asQuantitativeCheckResult<double>().getMin(), 1e-6); + result = checker->check(tasks[2]); + EXPECT_NEAR(this->parseNumber("1/24"), this->getQuantitativeResultAtInitialState(model, result), this->precision()); - result = checker.check(tasks[3]); - EXPECT_NEAR(1/6, result->asQuantitativeCheckResult<double>().getMin(), 1e-6); + result = checker->check(tasks[3]); + EXPECT_NEAR(this->parseNumber("1/6"), this->getQuantitativeResultAtInitialState(model, result), this->precision()); - result = checker.check(tasks[4]); - EXPECT_NEAR(0, result->asQuantitativeCheckResult<double>().getMin(), 1e-6); + result = checker->check(tasks[4]); + EXPECT_NEAR(this->parseNumber("0"), this->getQuantitativeResultAtInitialState(model, result), this->precision()); - result = checker.check(tasks[5]); - EXPECT_NEAR(1/2, result->asQuantitativeCheckResult<double>().getMin(), 1e-6); + result = checker->check(tasks[5]); + EXPECT_NEAR(this->parseNumber("1/6"), this->getQuantitativeResultAtInitialState(model, result), this->precision()); - result = checker.check(tasks[6]); - EXPECT_NEAR(0, result->asQuantitativeCheckResult<double>().getMin(), 1e-6); + result = checker->check(tasks[4]); + EXPECT_NEAR(this->parseNumber("0"), this->getQuantitativeResultAtInitialState(model, result), this->precision()); + } else { + EXPECT_FALSE(checker->canHandle(tasks[0])); + } } - TEST(DtmcPrctlModelCheckerTest, LtlProbabilitiesSynchronousLeader) { + TYPED_TEST(DtmcPrctlModelCheckerTest, LtlProbabilitiesSynchronousLeader) { setenv("LTL2DA", "ltl2da-ltl2tgba", true); + std::string formulasString = "P=? [X (u1=true U \"elected\")]"; formulasString += "; P=? [X v1=2 & (X v1=1)]"; // (X v1=2 & (XX v1=1)) formulasString += "; P=? [(X v1=2) & (X v1=1)]"; - //todo (X v1=2 & XX v1=1) + // TODO (X v1=2 & XX v1=1) - storm::prism::Program program = storm::api::parseProgram(STORM_TEST_RESOURCES_DIR "/dtmc/leader-3-5.pm"); - auto formulas = storm::api::extractFormulasFromProperties(storm::api::parsePropertiesForPrismProgram(formulasString, program)); - std::vector<storm::modelchecker::CheckTask<storm::logic::Formula, double>> tasks; - for (auto const& f : formulas) { - tasks.emplace_back(*f); - } - auto model = storm::api::buildSparseModel<double>(program, formulas)->as<storm::models::sparse::Dtmc<double>>(); - auto checker = storm::modelchecker::SparseDtmcPrctlModelChecker<storm::models::sparse::Dtmc<double>>(*model); + 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; - result= checker.check(tasks[0]); - EXPECT_NEAR(16/25, result->asQuantitativeCheckResult<double>().getMin(), 1e-6); + // LTL not supported in all engines (Hybrid, PrismDd, JaniDd) + if (TypeParam::engine == DtmcEngine::PrismSparse || TypeParam::engine == DtmcEngine::JaniSparse || TypeParam::engine == DtmcEngine::JitSparse) { + EXPECT_TRUE(checker->canHandle(tasks[0])); + 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("1/25"), this->getQuantitativeResultAtInitialState(model, result), this->precision()); - result = checker.check(tasks[1]); - EXPECT_NEAR(1/25, result->asQuantitativeCheckResult<double>().getMin(), 1e-6); + result = checker->check(tasks[2]); + EXPECT_NEAR(this->parseNumber("0"), this->getQuantitativeResultAtInitialState(model, result), this->precision()); - result = checker.check(tasks[2]); - EXPECT_NEAR(0, result->asQuantitativeCheckResult<double>().getMin(), 1e-6); + // TODO + // result = checker->check(tasks[3]); + // EXPECT_NEAR(this->parseNumber("1/25"), this->getQuantitativeResultAtInitialState(model, result), this->precision()); - // (X v1=2 & XX v1=1) - //result = checker.check(tasks[3]); - //EXPECT_NEAR(1/25, result->asQuantitativeCheckResult<double>().getMin(), 1e-6); + } else { + EXPECT_FALSE(checker->canHandle(tasks[0])); + } } } From 132c29310552cde2469f996d7b7c230d86b2f877 Mon Sep 17 00:00:00 2001 From: hannah <hannah.mertens@rwth-aachen.de> Date: Thu, 8 Apr 2021 22:29:10 +0200 Subject: [PATCH 041/172] TYPED_TESTS for LTL modelchecker --- .../storm/modelchecker/prctl/dtmc/DtmcPrctlModelCheckerTest.cpp | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/test/storm/modelchecker/prctl/dtmc/DtmcPrctlModelCheckerTest.cpp b/src/test/storm/modelchecker/prctl/dtmc/DtmcPrctlModelCheckerTest.cpp index af1882e5a..dad2c4c6b 100755 --- a/src/test/storm/modelchecker/prctl/dtmc/DtmcPrctlModelCheckerTest.cpp +++ b/src/test/storm/modelchecker/prctl/dtmc/DtmcPrctlModelCheckerTest.cpp @@ -740,7 +740,6 @@ namespace { // LTL not supported in all engines (Hybrid, PrismDd, JaniDd) if (TypeParam::engine == DtmcEngine::PrismSparse || TypeParam::engine == DtmcEngine::JaniSparse || TypeParam::engine == DtmcEngine::JitSparse) { - EXPECT_TRUE(checker->canHandle(tasks[0])); result = checker->check(tasks[0]); EXPECT_NEAR(this->parseNumber("1/6"), this->getQuantitativeResultAtInitialState(model, result), this->precision()); @@ -785,7 +784,6 @@ namespace { // LTL not supported in all engines (Hybrid, PrismDd, JaniDd) if (TypeParam::engine == DtmcEngine::PrismSparse || TypeParam::engine == DtmcEngine::JaniSparse || TypeParam::engine == DtmcEngine::JitSparse) { - EXPECT_TRUE(checker->canHandle(tasks[0])); result = checker->check(tasks[0]); EXPECT_NEAR(this->parseNumber("16/25"), this->getQuantitativeResultAtInitialState(model, result), this->precision()); From 4cf2fd7d61521fbc7101bcff54445341f0878fa7 Mon Sep 17 00:00:00 2001 From: Tim Quatmann <tim.quatmann@cs.rwth-aachen.de> Date: Tue, 13 Apr 2021 15:56:32 +0200 Subject: [PATCH 042/172] Heavily refactored FormulaParser as it had become quite messy. LTL-Operator precedence should now correctly mimic the behavior of PRISM. --- .../parser/FormulaParserGrammar.cpp | 520 ++++++++++-------- .../parser/FormulaParserGrammar.h | 201 ++++--- 2 files changed, 400 insertions(+), 321 deletions(-) diff --git a/src/storm-parsers/parser/FormulaParserGrammar.cpp b/src/storm-parsers/parser/FormulaParserGrammar.cpp index d768fab9b..0b1ce85ab 100644 --- a/src/storm-parsers/parser/FormulaParserGrammar.cpp +++ b/src/storm-parsers/parser/FormulaParserGrammar.cpp @@ -17,81 +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("(") > untilFormula(qi::_r1) > qi::lit(")")) | operatorFormula; - atomicStateFormula.name("atomic state formula"); - - atomicStateFormulaWithoutExpression = booleanLiteralFormula | labelFormula | (qi::lit("(") > untilFormula(qi::_r1) > qi::lit(")")) | operatorFormula; - atomicStateFormula.name("atomic state formula without expression"); - - notStateFormula = (unaryBooleanOperator_ >> atomicStateFormulaWithoutExpression(qi::_r1))[qi::_val = phoenix::bind(&FormulaParserGrammar::createUnaryBooleanStateOrPathFormula, phoenix::ref(*this), qi::_2, qi::_1)] | atomicStateFormula(qi::_r1)[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(qi::_r1); - 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"); - - hoaPathFormula = qi::lit("HOA:") > qi::lit("{") - > quotedString[qi::_val = phoenix::bind(&FormulaParserGrammar::createHOAPathFormula, phoenix::ref(*this), qi::_1)] - >> *(qi::lit(",") > quotedString > qi::lit("->") > stateFormula(qi::_r1) )[phoenix::bind(&FormulaParserGrammar::addHoaAPMapping, phoenix::ref(*this), *qi::_val, qi::_1, qi::_2)] - > qi::lit("}"); - - basicPathFormula = (hoaPathFormula(qi::_r1)[qi::_val = qi::_1]) | untilFormula(qi::_r1)[qi::_val = 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 + | multiOperatorFormula + | quantileFormula + | gameFormula + | (isPathFormula(qi::_r1) >> prefixOperatorPathFormula(qi::_r2)); // Needed for e.g. F "a" & X "a" = F ("a" & (X "a")) + 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"); - - conditionalFormula = basicPathFormula(qi::_r1)[qi::_val = qi::_1] >> *(qi::lit("||") >> basicPathFormula(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)] + 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) @@ -99,79 +116,63 @@ 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::Path, 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::_val)]; + 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(storm::logic::FormulaContext::LongRunAverage) > 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::_r1)[qi::_val = qi::_1] >> *(qi::lit("&") >> notStateFormula(qi::_r1))[qi::_val = phoenix::bind(&FormulaParserGrammar::createBinaryBooleanStateOrPathFormula, phoenix::ref(*this), qi::_val, qi::_1, storm::logic::BinaryBooleanStateFormula::OperatorType::And)]; - andStateFormula.name("and state formula"); - - orStateFormula = andStateFormula(qi::_r1)[qi::_val = qi::_1] >> *(qi::lit("|") >> andStateFormula(qi::_r1))[qi::_val = phoenix::bind(&FormulaParserGrammar::createBinaryBooleanStateOrPathFormula, 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(storm::logic::FormulaContext::Probability)) % 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(storm::logic::FormulaContext::Undefined) > 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"); - - 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"); - - stateFormula = (orStateFormula(qi::_r1) | multiFormula | quantileFormula); - stateFormula.name("state formula"); - - quotedString %= qi::as_string[qi::lexeme[qi::omit[qi::char_('"')] > qi::raw[*(!qi::char_('"') >> qi::char_)] > qi::omit[qi::lit('"')]]]; - quotedString.name("quoted string"); - + + // 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"); + + // General formulae + formula = (isPathFormula(qi::_r1) >> pathFormula(qi::_r2) | propositionalFormula(qi::_r1, qi::_r2)); + formula.name("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"); @@ -182,8 +183,9 @@ namespace storm { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Woverloaded-shift-op-parentheses" - - filterProperty = (-formulaName >> qi::lit("filter") > qi::lit("(") > filterType_ > qi::lit(",") > stateFormula(storm::logic::FormulaContext::Undefined) > qi::lit(",") > stateFormula(storm::logic::FormulaContext::Undefined) > qi::lit(")"))[qi::_val = phoenix::bind(&FormulaParserGrammar::createProperty, phoenix::ref(*this), qi::_1, qi::_2, qi::_3, qi::_4)] | (-formulaName >> stateFormula(storm::logic::FormulaContext::Undefined))[qi::_val = phoenix::bind(&FormulaParserGrammar::createPropertyWithDefaultFilterTypeAndStates, phoenix::ref(*this), qi::_1, qi::_2)] | (-formulaName >> shieldExpression >> stateFormula(storm::logic::FormulaContext::Undefined))[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 @@ -195,62 +197,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>(hoaPathFormula, 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>(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); } @@ -403,8 +434,13 @@ namespace storm { hoaFormula_.addAPMapping(ap, expression); } - 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::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 { @@ -415,7 +451,25 @@ namespace storm { return storm::logic::OperatorInformation(optimizationDirection, boost::none); } } - + + 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)); } @@ -467,53 +521,58 @@ namespace storm { 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 { + } 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 { + } else if (subformula->isPathFormula()) { return createUnaryBooleanPathFormula(subformula, operatorType); } + STORM_LOG_THROW(false, storm::exceptions::WrongFormatException, "Subformulas have unexpected type."); } - 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; + 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) { @@ -561,30 +620,7 @@ namespace storm { return storm::jani::Property(std::to_string(propertyCount), formula, this->getUndefinedConstants(formula)); } } - - std::pair<storm::logic::ShieldComparison, double> FormulaParserGrammar::createShieldComparisonStruct(storm::logic::ShieldComparison comparisonType, double value) { - return std::make_pair(comparisonType, value); - } - - 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)); - } - } - - 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); - } - } - + storm::logic::PlayerCoalition FormulaParserGrammar::createPlayerCoalition(std::vector<boost::variant<std::string, storm::storage::PlayerIndex>> const& playerIds) const { return storm::logic::PlayerCoalition(playerIds); } @@ -592,5 +628,19 @@ namespace storm { 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)); } + + 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; + } + + 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; + } + } } diff --git a/src/storm-parsers/parser/FormulaParserGrammar.h b/src/storm-parsers/parser/FormulaParserGrammar.h index 2bba99c73..33d9e7935 100644 --- a/src/storm-parsers/parser/FormulaParserGrammar.h +++ b/src/storm-parsers/parser/FormulaParserGrammar.h @@ -53,14 +53,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 @@ -73,28 +91,7 @@ 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 @@ -135,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; @@ -146,75 +161,84 @@ namespace storm { // A symbol table that is a mapping from identifiers that can be used in expressions to the expressions // 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; + + + // Rules + + // 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> formulaName; - qi::rule<Iterator, std::string(), Skipper> quotedString; - - 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; - - 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>(storm::logic::FormulaContext), 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>(storm::logic::FormulaContext), Skipper> atomicStateFormula; - qi::rule<Iterator, std::shared_ptr<storm::logic::Formula const>(storm::logic::FormulaContext), Skipper> atomicStateFormulaWithoutExpression; - qi::rule<Iterator, std::shared_ptr<storm::logic::Formula const>(), Skipper> operatorFormula; qi::rule<Iterator, std::string(), Skipper> label; - qi::rule<Iterator, std::string(), Skipper> rewardModelName; - - qi::rule<Iterator, std::shared_ptr<storm::logic::Formula const>(storm::logic::FormulaContext), Skipper> andStateFormula; - qi::rule<Iterator, std::shared_ptr<storm::logic::Formula const>(storm::logic::FormulaContext), Skipper> orStateFormula; - qi::rule<Iterator, std::shared_ptr<storm::logic::Formula const>(storm::logic::FormulaContext), Skipper> notStateFormula; + qi::rule<Iterator, std::string(), Skipper> quotedString; + + // 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>(storm::logic::FormulaContext), Skipper> conditionalFormula; + qi::rule<Iterator, std::shared_ptr<storm::logic::Formula const>(), Skipper> atomicPropositionFormula; + + // 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> untilFormula; - - 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> hoaPathFormula; - - void addHoaAPMapping(storm::logic::Formula const& hoaFormula, const std::string& ap, std::shared_ptr<storm::logic::Formula const>& expression) const; - - 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>(), 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; + 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; + + // 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; + + // 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::Formula const>(), Skipper> multiFormula; - qi::rule<Iterator, storm::expressions::Variable(), qi::locals<boost::optional<storm::solver::OptimizationDirection>>, Skipper> quantileBoundVariable; + // 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; - qi::rule<Iterator, std::shared_ptr<storm::logic::Formula const>(), Skipper> gameFormula; + + // 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; - 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; + // 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; @@ -243,8 +267,9 @@ namespace storm { 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> createHOAPathFormula(const std::string& automataFile) const; - 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> 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; @@ -255,15 +280,19 @@ namespace storm { 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> 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); - std::shared_ptr<storm::logic::Formula const> createMultiFormula(std::vector<std::shared_ptr<storm::logic::Formula const>> const& subformulas); + 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; From 76c689a0017a232617fbb9607c7c1819b437d092 Mon Sep 17 00:00:00 2001 From: Tim Quatmann <tim.quatmann@cs.rwth-aachen.de> Date: Wed, 14 Apr 2021 12:19:56 +0200 Subject: [PATCH 043/172] flagging multi-objective formulae as State formulae --- src/storm/logic/MultiObjectiveFormula.cpp | 4 ++++ src/storm/logic/MultiObjectiveFormula.h | 1 + 2 files changed, 5 insertions(+) diff --git a/src/storm/logic/MultiObjectiveFormula.cpp b/src/storm/logic/MultiObjectiveFormula.cpp index edae6a1ea..dec0fc6cd 100644 --- a/src/storm/logic/MultiObjectiveFormula.cpp +++ b/src/storm/logic/MultiObjectiveFormula.cpp @@ -19,6 +19,10 @@ namespace storm { return true; } + bool MultiObjectiveFormula::isStateFormula() const { + return true; + } + bool MultiObjectiveFormula::hasQualitativeResult() const { for(auto const& subformula : this->subformulas){ if(subformula->hasQuantitativeResult()){ diff --git a/src/storm/logic/MultiObjectiveFormula.h b/src/storm/logic/MultiObjectiveFormula.h index faf774958..bee816a61 100644 --- a/src/storm/logic/MultiObjectiveFormula.h +++ b/src/storm/logic/MultiObjectiveFormula.h @@ -12,6 +12,7 @@ namespace storm { virtual ~MultiObjectiveFormula(); virtual bool isMultiObjectiveFormula() const override; + virtual bool isStateFormula() const override; virtual bool hasQualitativeResult() const override; // Result is true or false virtual bool hasQuantitativeResult() const override; // Result is numerical or a pareto curve From cc9a4b8cb33da402824b6bb6e1812ac7f27f92df Mon Sep 17 00:00:00 2001 From: Tim Quatmann <tim.quatmann@cs.rwth-aachen.de> Date: Wed, 14 Apr 2021 12:20:15 +0200 Subject: [PATCH 044/172] Adapting a parser test-case to the new parser --- src/test/storm/parser/FormulaParserTest.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/storm/parser/FormulaParserTest.cpp b/src/test/storm/parser/FormulaParserTest.cpp index 3831976e2..8a36622fa 100644 --- a/src/test/storm/parser/FormulaParserTest.cpp +++ b/src/test/storm/parser/FormulaParserTest.cpp @@ -38,7 +38,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) { From aa29ad1196dff7cfc8ab389a3f4484f34a27863e Mon Sep 17 00:00:00 2001 From: Tim Quatmann <tim.quatmann@cs.rwth-aachen.de> Date: Wed, 14 Apr 2021 15:29:49 +0200 Subject: [PATCH 045/172] flagging multi-objective and quantile formulae as StateFormulae (fixing the previous commit) Conflicts: src/storm/modelchecker/AbstractModelChecker.cpp --- src/storm/logic/MultiObjectiveFormula.cpp | 4 ---- src/storm/logic/MultiObjectiveFormula.h | 5 ++--- src/storm/logic/QuantileFormula.h | 4 ++-- src/storm/modelchecker/AbstractModelChecker.cpp | 4 ++++ 4 files changed, 8 insertions(+), 9 deletions(-) diff --git a/src/storm/logic/MultiObjectiveFormula.cpp b/src/storm/logic/MultiObjectiveFormula.cpp index dec0fc6cd..edae6a1ea 100644 --- a/src/storm/logic/MultiObjectiveFormula.cpp +++ b/src/storm/logic/MultiObjectiveFormula.cpp @@ -19,10 +19,6 @@ namespace storm { return true; } - bool MultiObjectiveFormula::isStateFormula() const { - return true; - } - bool MultiObjectiveFormula::hasQualitativeResult() const { for(auto const& subformula : this->subformulas){ if(subformula->hasQuantitativeResult()){ diff --git a/src/storm/logic/MultiObjectiveFormula.h b/src/storm/logic/MultiObjectiveFormula.h index bee816a61..82e34807e 100644 --- a/src/storm/logic/MultiObjectiveFormula.h +++ b/src/storm/logic/MultiObjectiveFormula.h @@ -1,18 +1,17 @@ #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); virtual ~MultiObjectiveFormula(); virtual bool isMultiObjectiveFormula() const override; - virtual bool isStateFormula() const override; virtual bool hasQualitativeResult() const override; // Result is true or false virtual bool hasQuantitativeResult() const override; // Result is numerical or a pareto curve diff --git a/src/storm/logic/QuantileFormula.h b/src/storm/logic/QuantileFormula.h index 4bfe0a5a1..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); diff --git a/src/storm/modelchecker/AbstractModelChecker.cpp b/src/storm/modelchecker/AbstractModelChecker.cpp index 31b34cd72..8e40891f4 100644 --- a/src/storm/modelchecker/AbstractModelChecker.cpp +++ b/src/storm/modelchecker/AbstractModelChecker.cpp @@ -237,6 +237,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."); } From 8c669b9e8ba489ca6f669906121f7cddf3b4f950 Mon Sep 17 00:00:00 2001 From: Tim Quatmann <tim.quatmann@cs.rwth-aachen.de> Date: Wed, 14 Apr 2021 15:30:30 +0200 Subject: [PATCH 046/172] Fixed a FragmentCheckerTest case which considered a formula that is now considered invalid. --- src/test/storm/logic/FragmentCheckerTest.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/storm/logic/FragmentCheckerTest.cpp b/src/test/storm/logic/FragmentCheckerTest.cpp index 179e8d099..2fccdb1e8 100644 --- a/src/test/storm/logic/FragmentCheckerTest.cpp +++ b/src/test/storm/logic/FragmentCheckerTest.cpp @@ -150,7 +150,7 @@ 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\"])]")); From b71cb813df8e746aa5eef88c65da01c629582ae6 Mon Sep 17 00:00:00 2001 From: Tim Quatmann <tim.quatmann@cs.rwth-aachen.de> Date: Wed, 14 Apr 2021 15:31:57 +0200 Subject: [PATCH 047/172] FormulaParser: Fixed parsing of multi-bounded path operator and quantile operator --- src/storm-parsers/parser/FormulaParserGrammar.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/storm-parsers/parser/FormulaParserGrammar.cpp b/src/storm-parsers/parser/FormulaParserGrammar.cpp index 0b1ce85ab..6a522051a 100644 --- a/src/storm-parsers/parser/FormulaParserGrammar.cpp +++ b/src/storm-parsers/parser/FormulaParserGrammar.cpp @@ -79,10 +79,10 @@ namespace storm { | 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 - | multiOperatorFormula + | (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 - | (isPathFormula(qi::_r1) >> prefixOperatorPathFormula(qi::_r2)); // Needed for e.g. F "a" & X "a" = F ("a" & (X "a")) + | 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] @@ -128,9 +128,9 @@ namespace storm { > quotedString[qi::_val = phoenix::bind(&FormulaParserGrammar::createHOAPathFormula, phoenix::ref(*this), qi::_1)] >> *(qi::lit(",") > quotedString > qi::lit("->") > formula(FormulaKind::Path, 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::_val)]; + 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 = ((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") @@ -161,7 +161,7 @@ namespace storm { > (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 = (-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"); From 1c16c17a57dda221ae3ee4e5aef65e129779076e Mon Sep 17 00:00:00 2001 From: Tim Quatmann <tim.quatmann@cs.rwth-aachen.de> Date: Wed, 14 Apr 2021 16:26:55 +0200 Subject: [PATCH 048/172] FragmentCheckerTest: Fixed a few more testcaes that now correspond to invalid formulae. --- src/test/storm/logic/FragmentCheckerTest.cpp | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/src/test/storm/logic/FragmentCheckerTest.cpp b/src/test/storm/logic/FragmentCheckerTest.cpp index 2fccdb1e8..c0f10a5ed 100644 --- a/src/test/storm/logic/FragmentCheckerTest.cpp +++ b/src/test/storm/logic/FragmentCheckerTest.cpp @@ -153,10 +153,7 @@ TEST(FragmentCheckerTest, MultiObjective) { 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)); From d5edde05a7bb12744f465a996ffa63b0f19916a4 Mon Sep 17 00:00:00 2001 From: hannah <hannah.mertens@rwth-aachen.de> Date: Thu, 15 Apr 2021 10:10:31 +0200 Subject: [PATCH 049/172] Adapted ModelChecker test-cases and FormulaParser test-cases --- .../prctl/dtmc/DtmcPrctlModelCheckerTest.cpp | 20 +++-- src/test/storm/parser/FormulaParserTest.cpp | 86 ++++++++++--------- 2 files changed, 57 insertions(+), 49 deletions(-) diff --git a/src/test/storm/modelchecker/prctl/dtmc/DtmcPrctlModelCheckerTest.cpp b/src/test/storm/modelchecker/prctl/dtmc/DtmcPrctlModelCheckerTest.cpp index dad2c4c6b..191dd3509 100755 --- a/src/test/storm/modelchecker/prctl/dtmc/DtmcPrctlModelCheckerTest.cpp +++ b/src/test/storm/modelchecker/prctl/dtmc/DtmcPrctlModelCheckerTest.cpp @@ -30,7 +30,6 @@ #include "storm/environment/solver/EigenSolverEnvironment.h" #include "storm/environment/solver/TopologicalSolverEnvironment.h" -#include <cstdlib> //todo namespace { @@ -726,7 +725,7 @@ namespace { 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\")]"; // TODO without () + 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); @@ -758,7 +757,7 @@ namespace { result = checker->check(tasks[5]); EXPECT_NEAR(this->parseNumber("1/6"), this->getQuantitativeResultAtInitialState(model, result), this->precision()); - result = checker->check(tasks[4]); + result = checker->check(tasks[6]); EXPECT_NEAR(this->parseNumber("0"), this->getQuantitativeResultAtInitialState(model, result), this->precision()); } else { EXPECT_FALSE(checker->canHandle(tasks[0])); @@ -769,9 +768,10 @@ namespace { setenv("LTL2DA", "ltl2da-ltl2tgba", true); std::string formulasString = "P=? [X (u1=true U \"elected\")]"; - formulasString += "; P=? [X v1=2 & (X v1=1)]"; // (X v1=2 & (XX v1=1)) + formulasString += "; P=? [X !(u1=true U \"elected\")]"; + formulasString += "; P=? [X v1=2 & X v1=1]"; formulasString += "; P=? [(X v1=2) & (X v1=1)]"; - // TODO (X v1=2 & XX 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); @@ -788,14 +788,16 @@ namespace { EXPECT_NEAR(this->parseNumber("16/25"), this->getQuantitativeResultAtInitialState(model, result), this->precision()); result = checker->check(tasks[1]); - EXPECT_NEAR(this->parseNumber("1/25"), this->getQuantitativeResultAtInitialState(model, result), this->precision()); + 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()); - // TODO - // result = checker->check(tasks[3]); - // EXPECT_NEAR(this->parseNumber("1/25"), 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])); diff --git a/src/test/storm/parser/FormulaParserTest.cpp b/src/test/storm/parser/FormulaParserTest.cpp index 8a36622fa..22e7e6fd9 100644 --- a/src/test/storm/parser/FormulaParserTest.cpp +++ b/src/test/storm/parser/FormulaParserTest.cpp @@ -176,6 +176,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) { @@ -230,7 +240,7 @@ TEST(FormulaParserTest, LogicalPrecedenceTest) { 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 + 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()); @@ -248,14 +258,22 @@ TEST(FormulaParserTest, LogicalPrecedenceTest) { ASSERT_TRUE(nested4Subformula.getLeftSubformula().isAtomicLabelFormula()); ASSERT_TRUE(nested4Subformula.getRightSubformula().isBinaryBooleanStateFormula()); - input = "P<0.9 [X \"a\" | (X \"b\")]"; // X(a|Xb) todo why is this allowed, but not [X \"a\" | X \"b\"] + 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()); - auto const &nested5Subformula = nested5.asNextFormula().getSubformula().asBinaryPathFormula(); EXPECT_TRUE(nested5.asNextFormula().getSubformula().asBinaryPathFormula().getLeftSubformula().isAtomicLabelFormula()); - EXPECT_TRUE(nested5.asNextFormula().getSubformula().asBinaryPathFormula().getRightSubformula().isNextFormula()); + 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) { @@ -278,34 +296,42 @@ TEST(FormulaParserTest, TemporalPrecedenceTest) { 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\"]"; // (X F a) U (G b) U (G c) + 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().isUntilFormula()); - EXPECT_TRUE(nested3.asUntilFormula().getLeftSubformula().asUntilFormula().getLeftSubformula().isNextFormula()); - EXPECT_TRUE(nested3.asUntilFormula().getRightSubformula().isGloballyFormula()); + 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, NestedUntilTest) { +TEST(FormulaParserTest, TemporalNegationTest) { storm::parser::FormulaParser formulaParser; - std::string input = "P<0.9 [\"a\" U (\"b\" U \"c\")]"; 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.isUntilFormula()); - EXPECT_FALSE(nested1.isBoundedUntilFormula()); - ASSERT_TRUE( nested1.asUntilFormula().getLeftSubformula().isAtomicLabelFormula()); - ASSERT_TRUE(nested1.asUntilFormula().getRightSubformula().isUntilFormula()); + EXPECT_TRUE(nested1.isUnaryBooleanPathFormula()); + EXPECT_TRUE(nested1.asUnaryPathFormula().getSubformula().isNextFormula()); + EXPECT_TRUE(nested1.asUnaryPathFormula().getSubformula().asNextFormula().getSubformula().isBinaryBooleanStateFormula()); - input = "P<0.9 [\"a\" U \"b\" U \"c\"]"; // Nested Until without parentheses: (a U b) U c + input ="P<0.9 [! F ! G \"b\"]"; ASSERT_NO_THROW(formula = formulaParser.parseSingleFormulaFromString(input)); auto const &nested2 = formula->asProbabilityOperatorFormula().getSubformula(); - EXPECT_TRUE(nested2.isUntilFormula()); - EXPECT_FALSE(nested2.isBoundedUntilFormula()); - ASSERT_TRUE(nested2.asUntilFormula().getLeftSubformula().isUntilFormula()); - ASSERT_TRUE(nested2.asUntilFormula().getRightSubformula().isAtomicLabelFormula()); + 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) { @@ -321,29 +347,9 @@ TEST(FormulaParserTest, ComplexPathFormulaTest) { 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\"))]"; + 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()); } - -TEST(FormulaParserTest, LtlWrongFormatTest) { - storm::parser::FormulaParser formulaParser; - std::shared_ptr<storm::logic::Formula const> formula(nullptr); - - std::string input = "P<0.9 [F \"a\" & X \"b\"]"; - STORM_SILENT_EXPECT_THROW(formula = formulaParser.parseSingleFormulaFromString(input), storm::exceptions::WrongFormatException); - - input = "P<0.9 [X \"a\" & G \"b\"]"; - STORM_SILENT_EXPECT_THROW(formula = formulaParser.parseSingleFormulaFromString(input), storm::exceptions::WrongFormatException); - - input = "P<0.9 [G \"a\" & G \"b\"]"; - STORM_SILENT_EXPECT_THROW(formula = formulaParser.parseSingleFormulaFromString(input), storm::exceptions::WrongFormatException); - - input = "P<0.9 [(G \"a\") & G \"b\"]"; //todo why? - STORM_SILENT_EXPECT_THROW(formula = formulaParser.parseSingleFormulaFromString(input), storm::exceptions::WrongFormatException); - - input = "P<0.9 [! X \"b\"]"; - STORM_SILENT_EXPECT_THROW(formula = formulaParser.parseSingleFormulaFromString(input), storm::exceptions::WrongFormatException); -} From d44bc3c6c25a6e572343405656a3553f7b2c1f4f Mon Sep 17 00:00:00 2001 From: Tim Quatmann <tim.quatmann@cs.rwth-aachen.de> Date: Fri, 16 Apr 2021 15:37:38 +0200 Subject: [PATCH 050/172] CMAKE: Added option to include and link against Spot Conflicts: CMakeLists.txt --- CMakeLists.txt | 8 ++- resources/3rdparty/CMakeLists.txt | 9 +++ resources/3rdparty/include_SPOT.cmake | 64 +++++++++++++++++++++ resources/cmake/find_modules/FindSPOT.cmake | 42 ++++++++++++++ storm-config.h.in | 8 +++ 5 files changed, 130 insertions(+), 1 deletion(-) create mode 100644 resources/3rdparty/include_SPOT.cmake create mode 100644 resources/cmake/find_modules/FindSPOT.cmake diff --git a/CMakeLists.txt b/CMakeLists.txt index 85968256d..fd37f01f5 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -49,7 +49,11 @@ MARK_AS_ADVANCED(STORM_FORCE_SHIPPED_CARL) 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_FORCE_LTL_SUPPORT "Sets whether support for LTL model checking needs to be included." OFF) +option(STORM_USE_SPOT "Sets whether Spot should be included." ON) +MARK_AS_ADVANCED(STORM_USE_SPOT) +option(STORM_FORCE_SHIPPED_SPOT "Sets whether the Spot sources should be downloaded and installed." OFF) +MARK_AS_ADVANCED(STORM_FORCE_SHIPPED_SPOT) 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 +75,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) diff --git a/resources/3rdparty/CMakeLists.txt b/resources/3rdparty/CMakeLists.txt index 50a220135..cdc18db60 100644 --- a/resources/3rdparty/CMakeLists.txt +++ b/resources/3rdparty/CMakeLists.txt @@ -514,6 +514,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/include_SPOT.cmake b/resources/3rdparty/include_SPOT.cmake new file mode 100644 index 000000000..0332bdd4e --- /dev/null +++ b/resources/3rdparty/include_SPOT.cmake @@ -0,0 +1,64 @@ +set(STORM_HAVE_SPOT OFF) + + +if (STORM_FORCE_SHIPPED_SPOT AND NOT STORM_USE_SPOT) + message(FATAL_ERROR "Storm - Incompatible cmake options: STORM_FORCE_SHIPPED_SPOT=ON and STORM_USE_SPOT=OFF.") +endif() + +if (STORM_FORCE_LTL_SUPPORT AND NOT STORM_USE_SPOT) + message(FATAL_ERROR "Storm - Incompatible cmake options: STORM_FORCE_LTL_SUPPORT=ON and STORM_USE_SPOT=OFF. LTL support requires Spot.") +endif() + +if(STORM_USE_SPOT AND NOT STORM_SHIPPED_SPOT AND NOT STORM_FORCE_SHIPPED_SPOT) + + # 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 - Linking with shipped Spot ${SPOT_VERSION} (include: ${SPOT_INCLUDE_DIR}, library: ${SPOT_LIBRARIES}).") + set(STORM_HAVE_SPOT ON) + elseif(NOT STORM_FORCE_LTL_SUPPORT) + 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_FORCE_LTL_SUPPORT to install Spot automatically. If you already installed Spot, consider setting cmake option SPOT_ROOT") + endif() +elseif() +endif() + +set(STORM_SHIPPED_SPOT OFF) +if(STORM_FORCE_SHIPPED_SPOT OR (STORM_FORCE_LTL_SUPPORT 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 + 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 - Linking with shipped 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/cmake/find_modules/FindSPOT.cmake b/resources/cmake/find_modules/FindSPOT.cmake new file mode 100644 index 000000000..383793a09 --- /dev/null +++ b/resources/cmake/find_modules/FindSPOT.cmake @@ -0,0 +1,42 @@ +# - 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 +message(STATUS "FIND SPOT") + +# 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/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 From 6110d33bcccf507e15f1fd112a9b60007def3783 Mon Sep 17 00:00:00 2001 From: Tim Quatmann <tim.quatmann@cs.rwth-aachen.de> Date: Mon, 19 Apr 2021 07:49:47 +0200 Subject: [PATCH 051/172] Removed debug output --- resources/cmake/find_modules/FindSPOT.cmake | 2 -- 1 file changed, 2 deletions(-) diff --git a/resources/cmake/find_modules/FindSPOT.cmake b/resources/cmake/find_modules/FindSPOT.cmake index 383793a09..f4a0be599 100644 --- a/resources/cmake/find_modules/FindSPOT.cmake +++ b/resources/cmake/find_modules/FindSPOT.cmake @@ -6,8 +6,6 @@ # SPOT_VERSION - The version of spot # use pkg-config to get the directories and then use these values -message(STATUS "FIND SPOT") - # in the find_path() and find_library() calls find_package(PkgConfig QUIET) PKG_CHECK_MODULES(PC_SPOT QUIET spot) From d861c377a95b9abab5c8b88f232531ce09618348 Mon Sep 17 00:00:00 2001 From: hannah <hannah.mertens@rwth-aachen.de> Date: Tue, 20 Apr 2021 10:21:44 +0200 Subject: [PATCH 052/172] fixed typo --- resources/3rdparty/{include_SPOT.cmake => include_spot.cmake} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename resources/3rdparty/{include_SPOT.cmake => include_spot.cmake} (100%) diff --git a/resources/3rdparty/include_SPOT.cmake b/resources/3rdparty/include_spot.cmake similarity index 100% rename from resources/3rdparty/include_SPOT.cmake rename to resources/3rdparty/include_spot.cmake From c290e16260b870f7c3691b4b4d2430d27fe01f51 Mon Sep 17 00:00:00 2001 From: hannah <hannah.mertens@rwth-aachen.de> Date: Wed, 21 Apr 2021 21:29:59 +0200 Subject: [PATCH 053/172] Simplified LTL2DeterministicAutomaton --- .../automata/LTL2DeterministicAutomaton.cpp | 75 +++++++------------ 1 file changed, 28 insertions(+), 47 deletions(-) diff --git a/src/storm/automata/LTL2DeterministicAutomaton.cpp b/src/storm/automata/LTL2DeterministicAutomaton.cpp index 8a4275c60..ca4d0b5db 100644 --- a/src/storm/automata/LTL2DeterministicAutomaton.cpp +++ b/src/storm/automata/LTL2DeterministicAutomaton.cpp @@ -3,59 +3,40 @@ #include "storm/logic/Formula.h" #include "storm/utility/macros.h" -#include "storm/exceptions/FileIoException.h" -#include <cstring> -#include <cerrno> -#include <cstdlib> -#include <unistd.h> // for execlp -#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" +#endif namespace storm { namespace automata { - // TODO: this is quite hacky, improve robustness std::shared_ptr<DeterministicAutomaton> LTL2DeterministicAutomaton::ltl2da(storm::logic::Formula const& f) { - std::string prefixLtl = f.toPrefixString(); - - std::string ltl2da_tool = "ltl2da"; - if (const char* ltl2da_env = std::getenv("LTL2DA")) { - ltl2da_tool = ltl2da_env; - } - - STORM_LOG_INFO("Calling external LTL->DA tool: " << ltl2da_tool << " '" << 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(ltl2da_tool.c_str(), ltl2da_tool.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"); - } +#ifdef STORM_HAVE_SPOT + spot::formula parsed_formula = spot::parse_formula(f.toPrefixString()); + + STORM_LOG_INFO("Construct deterministic automaton for "<< parsed_formula); + + // 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); + auto aut = trans.run(parsed_formula); + + 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 } } } From 466339059f917473c936b98b5677d30354ae9747 Mon Sep 17 00:00:00 2001 From: hannah <hannah.mertens@rwth-aachen.de> Date: Wed, 21 Apr 2021 22:42:55 +0200 Subject: [PATCH 054/172] Call parse_prefix_ltl instead of parse_formula --- src/storm/automata/LTL2DeterministicAutomaton.cpp | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/src/storm/automata/LTL2DeterministicAutomaton.cpp b/src/storm/automata/LTL2DeterministicAutomaton.cpp index ca4d0b5db..7f951135e 100644 --- a/src/storm/automata/LTL2DeterministicAutomaton.cpp +++ b/src/storm/automata/LTL2DeterministicAutomaton.cpp @@ -3,6 +3,7 @@ #include "storm/logic/Formula.h" #include "storm/utility/macros.h" +#include "storm/exceptions/ExpressionEvaluationException.h" #ifdef STORM_HAVE_SPOT #include "spot/tl/formula.hh" @@ -16,15 +17,19 @@ namespace storm { std::shared_ptr<DeterministicAutomaton> LTL2DeterministicAutomaton::ltl2da(storm::logic::Formula const& f) { #ifdef STORM_HAVE_SPOT - spot::formula parsed_formula = spot::parse_formula(f.toPrefixString()); - STORM_LOG_INFO("Construct deterministic automaton for "<< parsed_formula); + std::string prefixLtl = f.toPrefixString(); + spot::parsed_formula spotPrefixLtl = spot::parse_prefix_ltl(prefixLtl); + STORM_LOG_THROW(!spotPrefixLtl.format_errors(std::cerr), storm::exceptions::ExpressionEvaluationException, "Spot could not parse formula: " << prefixLtl); + 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); - auto aut = trans.run(parsed_formula); + STORM_LOG_INFO("Construct deterministic automaton for "<< spotFormula); + auto aut = trans.run(spotFormula); std::stringstream autStream; // Print reachable states in HOA format, implicit edges (i), state-based acceptance (s) From 884b284ab53f2bdc76d025ec207bb97e8e6a853d Mon Sep 17 00:00:00 2001 From: hannah <hannah.mertens@rwth-aachen.de> Date: Mon, 26 Apr 2021 23:45:41 +0200 Subject: [PATCH 055/172] corrected exception --- src/storm/automata/LTL2DeterministicAutomaton.cpp | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/storm/automata/LTL2DeterministicAutomaton.cpp b/src/storm/automata/LTL2DeterministicAutomaton.cpp index 7f951135e..8e18d8328 100644 --- a/src/storm/automata/LTL2DeterministicAutomaton.cpp +++ b/src/storm/automata/LTL2DeterministicAutomaton.cpp @@ -4,6 +4,7 @@ #include "storm/logic/Formula.h" #include "storm/utility/macros.h" #include "storm/exceptions/ExpressionEvaluationException.h" +#include "storm/exceptions/WrongFormatException.h" #ifdef STORM_HAVE_SPOT #include "spot/tl/formula.hh" @@ -19,8 +20,12 @@ namespace storm { #ifdef STORM_HAVE_SPOT std::string prefixLtl = f.toPrefixString(); - spot::parsed_formula spotPrefixLtl = spot::parse_prefix_ltl(prefixLtl); - STORM_LOG_THROW(!spotPrefixLtl.format_errors(std::cerr), storm::exceptions::ExpressionEvaluationException, "Spot could not parse formula: " << prefixLtl); + spot::parsed_formula spotPrefixLtl = spot::parse_prefix_ltl("())"); + 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; From 0f5c4708ca733617b7f1ca5b470ce025d2cd7884 Mon Sep 17 00:00:00 2001 From: hannah <hannah.mertens@rwth-aachen.de> Date: Mon, 26 Apr 2021 23:46:20 +0200 Subject: [PATCH 056/172] corrected exception --- src/storm/automata/LTL2DeterministicAutomaton.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/storm/automata/LTL2DeterministicAutomaton.cpp b/src/storm/automata/LTL2DeterministicAutomaton.cpp index 8e18d8328..3833db73e 100644 --- a/src/storm/automata/LTL2DeterministicAutomaton.cpp +++ b/src/storm/automata/LTL2DeterministicAutomaton.cpp @@ -20,7 +20,7 @@ namespace storm { #ifdef STORM_HAVE_SPOT std::string prefixLtl = f.toPrefixString(); - spot::parsed_formula spotPrefixLtl = spot::parse_prefix_ltl("())"); + spot::parsed_formula spotPrefixLtl = spot::parse_prefix_ltl(prefixLtl); if(!spotPrefixLtl.errors.empty()){ std::ostringstream errorMsg; spotPrefixLtl.format_errors(errorMsg); From 4fc3c792218a0e2c09b372d802a9a661813335e2 Mon Sep 17 00:00:00 2001 From: hannah <hannah.mertens@rwth-aachen.de> Date: Tue, 27 Apr 2021 10:10:39 +0200 Subject: [PATCH 057/172] LTL tests for MDPs --- .../prctl/mdp/MdpPrctlModelCheckerTest.cpp | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/src/test/storm/modelchecker/prctl/mdp/MdpPrctlModelCheckerTest.cpp b/src/test/storm/modelchecker/prctl/mdp/MdpPrctlModelCheckerTest.cpp index 87e670104..1f8018abb 100755 --- a/src/test/storm/modelchecker/prctl/mdp/MdpPrctlModelCheckerTest.cpp +++ b/src/test/storm/modelchecker/prctl/mdp/MdpPrctlModelCheckerTest.cpp @@ -695,4 +695,36 @@ 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\"]"; + + 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()); + + } else { + EXPECT_FALSE(checker->canHandle(tasks[0])); + } + } +#else + GTEST_SKIP(); +#endif + + } From b30713c23d82fdf5bba2a9fe3fa7c83156b9f5fe Mon Sep 17 00:00:00 2001 From: hannah <hannah.mertens@rwth-aachen.de> Date: Sat, 15 May 2021 22:42:31 +0200 Subject: [PATCH 058/172] Started to restructure LTL model checking algorithms Conflicts: src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.cpp --- .../helper/SingleValueModelCheckerHelper.cpp | 10 + .../helper/SingleValueModelCheckerHelper.h | 11 + .../helper/ltl/SparseLTLHelper.cpp | 192 ++++++++++++++++++ .../modelchecker/helper/ltl/SparseLTLHelper.h | 52 +++++ .../utility/SetInformationFromCheckTask.h | 7 + .../prctl/SparseDtmcPrctlModelChecker.cpp | 28 +-- .../prctl/SparseMdpPrctlModelChecker.cpp | 21 +- .../prctl/SparseMdpPrctlModelChecker.h | 2 +- 8 files changed, 291 insertions(+), 32 deletions(-) create mode 100644 src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp create mode 100644 src/storm/modelchecker/helper/ltl/SparseLTLHelper.h 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..7dd5e1367 --- /dev/null +++ b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp @@ -0,0 +1,192 @@ +#include "SparseLTLHelper.h" + +#include "storm/transformer/DAProductBuilder.h" +#include "storm/automata/LTL2DeterministicAutomaton.h" + +#include "storm/models/sparse/Dtmc.h" +#include "storm/models/sparse/Mdp.h" + +#include "storm/modelchecker/prctl/helper/SparseDtmcPrctlHelper.h" +#include "storm/modelchecker/prctl/helper/SparseMdpPrctlHelper.h" + +#include "storm/storage/StronglyConnectedComponentDecomposition.h" + +#include "storm/settings/SettingsManager.h" +#include "storm/settings/modules/DebugSettings.h" +#include "storm/exceptions/InvalidPropertyException.h" + +namespace storm { + namespace modelchecker { + namespace helper { + + template <typename ValueType, typename Model, bool Nondeterministic> + SparseLTLHelper<ValueType, Model, Nondeterministic>::SparseLTLHelper(Model const& model, storm::storage::SparseMatrix<ValueType> const& transitionMatrix) : _model(model), _transitionMatrix(transitionMatrix) { + // Intentionally left empty. + } + + template<typename ValueType, typename Model, bool Nondeterministic> + std::vector<ValueType> SparseLTLHelper<ValueType, Model, Nondeterministic>::computeDAProductProbabilities(Environment const& env, storm::solver::SolveGoal<ValueType>&& goal, storm::automata::DeterministicAutomaton const& da, std::map<std::string, storm::storage::BitVector>& apSatSets, bool qualitative) { + STORM_LOG_THROW((!Nondeterministic) || goal.hasDirection() && goal.direction() == OptimizationDirection::Maximize, storm::exceptions::InvalidPropertyException, "Can only compute maximizing probabilties for DA product with MDP"); + + + const storm::automata::APSet& apSet = da.getAPSet(); + + std::vector<storm::storage::BitVector> apLabels; + 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"); + + apLabels.push_back(std::move(it->second)); + } + + storm::storage::BitVector statesOfInterest; + if (goal.hasRelevantValues()) { + statesOfInterest = goal.relevantValues(); + } else { + // product from all model states + statesOfInterest = storm::storage::BitVector(this->_model.getNumberOfStates(), true); + } + + + STORM_LOG_INFO("Building "+ (Nondeterministic ? std::string("MDP-DA") : std::string("DTMC-DA")) +"product with deterministic automaton, starting from " << statesOfInterest.getNumberOfSetBits() << " model states..."); + storm::transformer::DAProductBuilder productBuilder(da, apLabels); + + auto product = productBuilder.build(this->_model, statesOfInterest); + + STORM_LOG_INFO("Product "+ (Nondeterministic ? std::string("MDP-DA") : std::string("DTMC")) +" has " << product->getProductModel().getNumberOfStates() << " states and " + << product->getProductModel().getNumberOfTransitions() << " transitions."); + + if (storm::settings::getModule<storm::settings::modules::DebugSettings>().isTraceSet()) { + STORM_LOG_TRACE("Writing model to model.dot"); + std::ofstream modelDot("model.dot"); + this->_model.writeDotToStream(modelDot); + modelDot.close(); + + STORM_LOG_TRACE("Writing product model to product.dot"); + std::ofstream productDot("product.dot"); + product->getProductModel().writeDotToStream(productDot); + productDot.close(); + + STORM_LOG_TRACE("Product model mapping:"); + std::stringstream str; + product->printMapping(str); + STORM_LOG_TRACE(str.str()); + } + + + // DTMC: BCC + // MDP: computeSurelyAcceptingPmaxStates + storm::storage::BitVector accepting; + if (Nondeterministic) { + STORM_LOG_INFO("Computing accepting end components..."); + accepting = storm::modelchecker::helper::SparseMdpPrctlHelper<ValueType>::computeSurelyAcceptingPmaxStates(*product->getAcceptance(), product->getProductModel().getTransitionMatrix(), product->getProductModel().getBackwardTransitions()); + if (accepting.empty()) { + STORM_LOG_INFO("No accepting states, skipping probability computation."); + std::vector<ValueType> numericResult(this->_model.getNumberOfStates(), storm::utility::zero<ValueType>()); + return numericResult; + } + + } else { + STORM_LOG_INFO("Computing BSCCs and checking for acceptance..."); + + storm::storage::StronglyConnectedComponentDecomposition<ValueType> bottomSccs(product->getProductModel().getTransitionMatrix(), + storage::StronglyConnectedComponentDecompositionOptions().onlyBottomSccs().dropNaiveSccs()); + accepting = storm::storage::BitVector(product->getProductModel().getNumberOfStates()); + std::size_t checkedBSCCs = 0, acceptingBSCCs = 0, acceptingBSCCStates = 0; + for (auto& scc : bottomSccs) { + checkedBSCCs++; + if (product->getAcceptance()->isAccepting(scc)) { + acceptingBSCCs++; + for (auto& state : scc) { + accepting.set(state); + acceptingBSCCStates++; + } + } + } + + STORM_LOG_INFO("BSCC analysis: " << acceptingBSCCs << " of " << checkedBSCCs << " BSCCs were accepting (" << acceptingBSCCStates << " states in accepting BSCCs)."); + + if (acceptingBSCCs == 0) { + STORM_LOG_INFO("No accepting BSCCs, skipping probability computation."); + std::vector<ValueType> numericResult(this->_model.getNumberOfStates(), storm::utility::zero<ValueType>()); + return numericResult; + } + } + + STORM_LOG_INFO("Computing probabilities for reaching accepting BSCCs..."); + + storm::storage::BitVector bvTrue(product->getProductModel().getNumberOfStates(), true); + + storm::solver::SolveGoal<ValueType> solveGoalProduct(goal); + storm::storage::BitVector soiProduct(product->getStatesOfInterest()); + solveGoalProduct.setRelevantValues(std::move(soiProduct)); + + std::vector<ValueType> prodNumericResult; + + if (Nondeterministic) { + prodNumericResult + = std::move(storm::modelchecker::helper::SparseMdpPrctlHelper<ValueType>::computeUntilProbabilities(env, + std::move(solveGoalProduct), + product->getProductModel().getTransitionMatrix(), + product->getProductModel().getBackwardTransitions(), + bvTrue, + accepting, + qualitative, + false // no schedulers (at the moment) + ).values); + + } else { + prodNumericResult = storm::modelchecker::helper::SparseDtmcPrctlHelper<ValueType>::computeUntilProbabilities(env, + std::move(solveGoalProduct), + product->getProductModel().getTransitionMatrix(), + product->getProductModel().getBackwardTransitions(), + bvTrue, + accepting, + qualitative); + } + + std::vector<ValueType> numericResult = product->projectToOriginalModel(this->_model, prodNumericResult); + return numericResult; + } + + + template<typename ValueType, typename RewardModelType, bool Nondeterministic> + std::vector <ValueType> SparseLTLHelper<ValueType, RewardModelType, Nondeterministic>::computeLTLProbabilities(Environment const &env, storm::solver::SolveGoal<ValueType>&& goal, storm::logic::Formula const& ltlFormula, std::map<std::string, storm::storage::BitVector>& apSatSets) { + STORM_LOG_INFO("Resulting LTL path formula: " << ltlFormula); + STORM_LOG_INFO(" in prefix format: " << ltlFormula.toPrefixString()); + + std::shared_ptr<storm::automata::DeterministicAutomaton> da = storm::automata::LTL2DeterministicAutomaton::ltl2da(ltlFormula); + + 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::vector<ValueType> numericResult = computeDAProductProbabilities(env, std::move(goal), *da, apSatSets, this->isQualitativeSet()); + + /* + if(Nondeterministic && this->getOptimizationDirection()==OptimizationDirection::Minimize) { + // compute 1-Pmax[!ltl] + for (auto& value : numericResult) { + value = storm::utility::one<ValueType>() - value; + } + } + */ + + return numericResult; + } + + template class SparseLTLHelper<double, storm::models::sparse::Dtmc<double>, false>; + template class SparseLTLHelper<double, storm::models::sparse::Mdp<double>, true>; + +#ifdef STORM_HAVE_CARL + template class SparseLTLHelper<storm::RationalNumber, storm::models::sparse::Dtmc<storm::RationalNumber>, false>; + template class SparseLTLHelper<storm::RationalNumber, storm::models::sparse::Mdp<storm::RationalNumber>, true>; + template class SparseLTLHelper<storm::RationalFunction, storm::models::sparse::Dtmc<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..6240fe1b0 --- /dev/null +++ b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h @@ -0,0 +1,52 @@ +#include "storm/modelchecker/helper/SingleValueModelCheckerHelper.h" +#include "storm/storage/SparseMatrix.h" +#include "storm/solver/SolveGoal.h" + + +namespace storm { + + namespace automata { + // fwd + class DeterministicAutomaton; + } + + namespace modelchecker { + namespace helper { + + /*! + * Helper class for todo... + * @tparam ValueType the type a value can have + * @tparam Nondeterministic true if there is nondeterminism in the Model (MDP) + */ + template<typename ValueType, typename Model, bool Nondeterministic> // todo remove Model + class SparseLTLHelper: public SingleValueModelCheckerHelper<ValueType, storm::models::ModelRepresentation::Sparse> { + + public: + /*! + * Initializes the helper for a discrete time (i.e. DTMC, MDP) + */ + SparseLTLHelper(Model const& model, storm::storage::SparseMatrix<ValueType> const& transitionMatrix); + + + /*! + * todo + * @return + */ + std::vector<ValueType> computeDAProductProbabilities(Environment const& env, storm::solver::SolveGoal<ValueType>&& goal, storm::automata::DeterministicAutomaton const& da, std::map<std::string, storm::storage::BitVector>& apSatSets, bool qualitative); + + + /*! + * Computes the ltl probabilities ...todo + * @return a value for each state + */ + std::vector<ValueType> computeLTLProbabilities(Environment const &env, storm::solver::SolveGoal<ValueType>&& goal, storm::logic::Formula const& f, std::map<std::string, storm::storage::BitVector>& apSatSets); //todo was brauchen wir hier aps und ..? + + + private: + storm::storage::SparseMatrix<ValueType> const& _transitionMatrix; + Model const& _model; // todo remove ? + + }; + } + } +} \ 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/SparseDtmcPrctlModelChecker.cpp b/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.cpp index ccb5d1a83..64c2eaa05 100644 --- a/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.cpp +++ b/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.cpp @@ -15,6 +15,7 @@ #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" @@ -161,7 +162,7 @@ namespace storm { STORM_LOG_INFO("Extracting maximal state formulas and computing satisfaction sets for path formula: " << pathFormula); std::map<std::string, storm::storage::BitVector> apSets; - + // todo instead: std::map<std::string, storm::storage::BitVector> apSets = storm::modelchecker::helper::computeApSets(env, checkTask); for (auto& p : extracted) { STORM_LOG_INFO(" Computing satisfaction set for atomic proposition \"" << p.first << "\" <=> " << *p.second << "..."); @@ -174,20 +175,12 @@ namespace storm { apSets[p.first] = std::move(sat); } - STORM_LOG_INFO("Resulting LTL path formula: " << *ltlFormula); - STORM_LOG_INFO(" in prefix format: " << ltlFormula->toPrefixString()); - - std::shared_ptr<storm::automata::DeterministicAutomaton> da = storm::automata::LTL2DeterministicAutomaton::ltl2da(*ltlFormula); - - STORM_LOG_INFO("Deterministic automaton for LTL formula has " - << da->getNumberOfStates() << " states, " - << da->getAPSet().size() << " atomic propositions and " - << *da->getAcceptance()->getAcceptanceExpression() << " as acceptance condition."); - const SparseDtmcModelType& dtmc = this->getModel(); - storm::solver::SolveGoal<ValueType> goal(dtmc, checkTask); - std::vector<ValueType> numericResult = storm::modelchecker::helper::SparseDtmcPrctlHelper<ValueType>::computeDAProductProbabilities(env, dtmc, std::move(goal), *da, apSets, checkTask.isQualitativeSet()); + storm::modelchecker::helper::SparseLTLHelper<ValueType, SparseDtmcModelType, false> helper(dtmc, dtmc.getTransitionMatrix()); + storm::modelchecker::helper::setInformationFromCheckTaskDeterministic(helper, checkTask, dtmc); + std::vector<ValueType> numericResult = helper.computeLTLProbabilities(env, storm::solver::SolveGoal<ValueType>(this->getModel(), checkTask), *ltlFormula, apSets); + return std::unique_ptr<CheckResult>(new ExplicitQuantitativeCheckResult<ValueType>(std::move(numericResult))); } @@ -256,14 +249,13 @@ 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(); + 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::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))); } diff --git a/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.cpp b/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.cpp index 31b3a5c1d..dbf044910 100644 --- a/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.cpp +++ b/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.cpp @@ -23,6 +23,7 @@ #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" @@ -189,7 +190,6 @@ namespace storm { STORM_LOG_INFO("Extracting maximal state formulas and computing satisfaction sets for path formula: " << pathFormula); std::map<std::string, storm::storage::BitVector> apSets; - for (auto& p : extracted) { STORM_LOG_INFO(" Computing satisfaction set for atomic proposition \"" << p.first << "\" <=> " << *p.second << "..."); @@ -216,31 +216,25 @@ namespace storm { subTask = checkTask.substituteFormula(*ltlFormula); } - STORM_LOG_INFO("Resulting LTL path formula: " << *ltlFormula); - STORM_LOG_INFO(" in prefix format: " << ltlFormula->toPrefixString()); - - std::shared_ptr<storm::automata::DeterministicAutomaton> da = storm::automata::LTL2DeterministicAutomaton::ltl2da(*ltlFormula); - - STORM_LOG_INFO("Deterministic automaton for LTL formula has " - << da->getNumberOfStates() << " states, " - << da->getAPSet().size() << " atomic propositions and " - << *da->getAcceptance()->getAcceptanceExpression() << " as acceptance condition."); - const SparseMdpModelType& mdp = this->getModel(); storm::solver::SolveGoal<ValueType> goal(mdp, subTask); - std::vector<ValueType> numericResult = computeDAProductProbabilities(env, std::move(goal), *da, apSets, checkTask.isQualitativeSet()); + storm::modelchecker::helper::SparseLTLHelper<ValueType, SparseMdpModelType, true> helper(mdp, mdp.getTransitionMatrix()); + storm::modelchecker::helper::setInformationFromCheckTaskNondeterministic(helper, subTask, mdp); + std::vector<ValueType> numericResult = helper.computeLTLProbabilities(env, storm::solver::SolveGoal<ValueType>(this->getModel(), subTask), *ltlFormula, apSets); - if (minimize) { + if(minimize) { // compute 1-Pmax[!ltl] for (auto& value : numericResult) { value = storm::utility::one<ValueType>() - value; } } + return std::unique_ptr<CheckResult>(new ExplicitQuantitativeCheckResult<ValueType>(std::move(numericResult))); } + /* template<typename SparseMdpModelType> std::vector<typename SparseMdpPrctlModelChecker<SparseMdpModelType>::ValueType> SparseMdpPrctlModelChecker<SparseMdpModelType>::computeDAProductProbabilities(Environment const& env, storm::solver::SolveGoal<typename SparseMdpPrctlModelChecker<SparseMdpModelType>::ValueType>&& goal, storm::automata::DeterministicAutomaton const& da, std::map<std::string, storm::storage::BitVector>& apSatSets, bool qualitative) const { STORM_LOG_THROW(goal.hasDirection() && goal.direction() == OptimizationDirection::Maximize, storm::exceptions::InvalidPropertyException, "Can only compute maximizing probabilties for DA product with MDP"); @@ -318,6 +312,7 @@ namespace storm { std::vector<ValueType> numericResult = product->projectToOriginalModel(this->getModel(), prodNumericResult); return numericResult; } + */ template<typename SparseMdpModelType> diff --git a/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.h b/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.h index 73e706596..2a09694c5 100644 --- a/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.h +++ b/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.h @@ -46,7 +46,7 @@ namespace storm { virtual std::unique_ptr<CheckResult> checkQuantileFormula(Environment const& env, CheckTask<storm::logic::QuantileFormula, ValueType> const& checkTask) override; private: - std::vector<ValueType> computeDAProductProbabilities(Environment const& env, storm::solver::SolveGoal<ValueType>&& goal, storm::automata::DeterministicAutomaton const& da, std::map<std::string, storm::storage::BitVector>& apSatSets, bool qualitative) const; + //std::vector<ValueType> computeDAProductProbabilities(Environment const& env, storm::solver::SolveGoal<ValueType>&& goal, storm::automata::DeterministicAutomaton const& da, std::map<std::string, storm::storage::BitVector>& apSatSets, bool qualitative) const; }; } // namespace modelchecker } // namespace storm From f8d97731315c3fdac1414077a26d0dd38a79b474 Mon Sep 17 00:00:00 2001 From: hannah <hannah.mertens@rwth-aachen.de> Date: Tue, 18 May 2021 21:52:02 +0200 Subject: [PATCH 059/172] test update --- .../modelchecker/prctl/dtmc/DtmcPrctlModelCheckerTest.cpp | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/test/storm/modelchecker/prctl/dtmc/DtmcPrctlModelCheckerTest.cpp b/src/test/storm/modelchecker/prctl/dtmc/DtmcPrctlModelCheckerTest.cpp index 191dd3509..8664fce18 100755 --- a/src/test/storm/modelchecker/prctl/dtmc/DtmcPrctlModelCheckerTest.cpp +++ b/src/test/storm/modelchecker/prctl/dtmc/DtmcPrctlModelCheckerTest.cpp @@ -718,8 +718,6 @@ namespace { } TYPED_TEST(DtmcPrctlModelCheckerTest, LtlProbabilitiesDie) { - setenv("LTL2DA", "ltl2da-ltl2tgba", true); - 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))]"; @@ -765,8 +763,6 @@ namespace { } TYPED_TEST(DtmcPrctlModelCheckerTest, LtlProbabilitiesSynchronousLeader) { - setenv("LTL2DA", "ltl2da-ltl2tgba", true); - std::string formulasString = "P=? [X (u1=true U \"elected\")]"; formulasString += "; P=? [X !(u1=true U \"elected\")]"; formulasString += "; P=? [X v1=2 & X v1=1]"; From ffe70ea056c50654e502fcf1d721959873ae01cc Mon Sep 17 00:00:00 2001 From: hannah <hannah.mertens@rwth-aachen.de> Date: Tue, 18 May 2021 21:53:41 +0200 Subject: [PATCH 060/172] removed model from SparseLTLHelper --- .../helper/ltl/SparseLTLHelper.cpp | 43 +++++----- .../modelchecker/helper/ltl/SparseLTLHelper.h | 21 +++-- .../prctl/SparseDtmcPrctlModelChecker.cpp | 4 +- .../prctl/SparseMdpPrctlModelChecker.cpp | 84 +------------------ src/storm/transformer/DAProductBuilder.h | 11 ++- src/storm/transformer/Product.h | 7 +- src/storm/transformer/ProductBuilder.h | 3 +- 7 files changed, 51 insertions(+), 122 deletions(-) diff --git a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp index 7dd5e1367..8182289ce 100644 --- a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp +++ b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp @@ -3,9 +3,6 @@ #include "storm/transformer/DAProductBuilder.h" #include "storm/automata/LTL2DeterministicAutomaton.h" -#include "storm/models/sparse/Dtmc.h" -#include "storm/models/sparse/Mdp.h" - #include "storm/modelchecker/prctl/helper/SparseDtmcPrctlHelper.h" #include "storm/modelchecker/prctl/helper/SparseMdpPrctlHelper.h" @@ -19,13 +16,13 @@ namespace storm { namespace modelchecker { namespace helper { - template <typename ValueType, typename Model, bool Nondeterministic> - SparseLTLHelper<ValueType, Model, Nondeterministic>::SparseLTLHelper(Model const& model, storm::storage::SparseMatrix<ValueType> const& transitionMatrix) : _model(model), _transitionMatrix(transitionMatrix) { + template <typename ValueType, bool Nondeterministic> + SparseLTLHelper<ValueType, Nondeterministic>::SparseLTLHelper(storm::storage::SparseMatrix<ValueType> const& transitionMatrix, std::size_t numberOfStates) : _transitionMatrix(transitionMatrix), _numberOfStates(numberOfStates) { // Intentionally left empty. } - template<typename ValueType, typename Model, bool Nondeterministic> - std::vector<ValueType> SparseLTLHelper<ValueType, Model, Nondeterministic>::computeDAProductProbabilities(Environment const& env, storm::solver::SolveGoal<ValueType>&& goal, storm::automata::DeterministicAutomaton const& da, std::map<std::string, storm::storage::BitVector>& apSatSets, bool qualitative) { + template<typename ValueType, bool Nondeterministic> + std::vector<ValueType> SparseLTLHelper<ValueType, Nondeterministic>::computeDAProductProbabilities(Environment const& env, storm::solver::SolveGoal<ValueType>&& goal, storm::automata::DeterministicAutomaton const& da, std::map<std::string, storm::storage::BitVector>& apSatSets, bool qualitative) { STORM_LOG_THROW((!Nondeterministic) || goal.hasDirection() && goal.direction() == OptimizationDirection::Maximize, storm::exceptions::InvalidPropertyException, "Can only compute maximizing probabilties for DA product with MDP"); @@ -44,14 +41,14 @@ namespace storm { statesOfInterest = goal.relevantValues(); } else { // product from all model states - statesOfInterest = storm::storage::BitVector(this->_model.getNumberOfStates(), true); + statesOfInterest = storm::storage::BitVector(this->_numberOfStates, true); } STORM_LOG_INFO("Building "+ (Nondeterministic ? std::string("MDP-DA") : std::string("DTMC-DA")) +"product with deterministic automaton, starting from " << statesOfInterest.getNumberOfSetBits() << " model states..."); storm::transformer::DAProductBuilder productBuilder(da, apLabels); - auto product = productBuilder.build(this->_model, statesOfInterest); + auto product = productBuilder.build<productModelType>(this->_transitionMatrix, statesOfInterest); STORM_LOG_INFO("Product "+ (Nondeterministic ? std::string("MDP-DA") : std::string("DTMC")) +" has " << product->getProductModel().getNumberOfStates() << " states and " << product->getProductModel().getNumberOfTransitions() << " transitions."); @@ -59,7 +56,7 @@ namespace storm { if (storm::settings::getModule<storm::settings::modules::DebugSettings>().isTraceSet()) { STORM_LOG_TRACE("Writing model to model.dot"); std::ofstream modelDot("model.dot"); - this->_model.writeDotToStream(modelDot); + // this->_model.writeDotToStream(modelDot); // TODO modelDot.close(); STORM_LOG_TRACE("Writing product model to product.dot"); @@ -82,7 +79,7 @@ namespace storm { accepting = storm::modelchecker::helper::SparseMdpPrctlHelper<ValueType>::computeSurelyAcceptingPmaxStates(*product->getAcceptance(), product->getProductModel().getTransitionMatrix(), product->getProductModel().getBackwardTransitions()); if (accepting.empty()) { STORM_LOG_INFO("No accepting states, skipping probability computation."); - std::vector<ValueType> numericResult(this->_model.getNumberOfStates(), storm::utility::zero<ValueType>()); + std::vector<ValueType> numericResult(this->_numberOfStates, storm::utility::zero<ValueType>()); return numericResult; } @@ -108,12 +105,12 @@ namespace storm { if (acceptingBSCCs == 0) { STORM_LOG_INFO("No accepting BSCCs, skipping probability computation."); - std::vector<ValueType> numericResult(this->_model.getNumberOfStates(), storm::utility::zero<ValueType>()); + std::vector<ValueType> numericResult(this->_numberOfStates, storm::utility::zero<ValueType>()); return numericResult; } } - STORM_LOG_INFO("Computing probabilities for reaching accepting BSCCs..."); + STORM_LOG_INFO("Computing probabilities for reaching accepting components..."); storm::storage::BitVector bvTrue(product->getProductModel().getNumberOfStates(), true); @@ -124,8 +121,7 @@ namespace storm { std::vector<ValueType> prodNumericResult; if (Nondeterministic) { - prodNumericResult - = std::move(storm::modelchecker::helper::SparseMdpPrctlHelper<ValueType>::computeUntilProbabilities(env, + prodNumericResult = std::move(storm::modelchecker::helper::SparseMdpPrctlHelper<ValueType>::computeUntilProbabilities(env, std::move(solveGoalProduct), product->getProductModel().getTransitionMatrix(), product->getProductModel().getBackwardTransitions(), @@ -145,13 +141,13 @@ namespace storm { qualitative); } - std::vector<ValueType> numericResult = product->projectToOriginalModel(this->_model, prodNumericResult); + std::vector<ValueType> numericResult = product->projectToOriginalModel(this->_numberOfStates, prodNumericResult); return numericResult; } - template<typename ValueType, typename RewardModelType, bool Nondeterministic> - std::vector <ValueType> SparseLTLHelper<ValueType, RewardModelType, Nondeterministic>::computeLTLProbabilities(Environment const &env, storm::solver::SolveGoal<ValueType>&& goal, storm::logic::Formula const& ltlFormula, std::map<std::string, storm::storage::BitVector>& apSatSets) { + template<typename ValueType, bool Nondeterministic> + std::vector <ValueType> SparseLTLHelper<ValueType, Nondeterministic>::computeLTLProbabilities(Environment const &env, storm::solver::SolveGoal<ValueType>&& goal, storm::logic::Formula const& ltlFormula, std::map<std::string, storm::storage::BitVector>& apSatSets) { STORM_LOG_INFO("Resulting LTL path formula: " << ltlFormula); STORM_LOG_INFO(" in prefix format: " << ltlFormula.toPrefixString()); @@ -165,6 +161,7 @@ namespace storm { std::vector<ValueType> numericResult = computeDAProductProbabilities(env, std::move(goal), *da, apSatSets, this->isQualitativeSet()); + // TODO /* if(Nondeterministic && this->getOptimizationDirection()==OptimizationDirection::Minimize) { // compute 1-Pmax[!ltl] @@ -177,13 +174,13 @@ namespace storm { return numericResult; } - template class SparseLTLHelper<double, storm::models::sparse::Dtmc<double>, false>; - template class SparseLTLHelper<double, storm::models::sparse::Mdp<double>, true>; + template class SparseLTLHelper<double, false>; + template class SparseLTLHelper<double, true>; #ifdef STORM_HAVE_CARL - template class SparseLTLHelper<storm::RationalNumber, storm::models::sparse::Dtmc<storm::RationalNumber>, false>; - template class SparseLTLHelper<storm::RationalNumber, storm::models::sparse::Mdp<storm::RationalNumber>, true>; - template class SparseLTLHelper<storm::RationalFunction, storm::models::sparse::Dtmc<storm::RationalFunction>, false>; + template class SparseLTLHelper<storm::RationalNumber, false>; + template class SparseLTLHelper<storm::RationalNumber, true>; + template class SparseLTLHelper<storm::RationalFunction, false>; #endif diff --git a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h index 6240fe1b0..42bf322cc 100644 --- a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h +++ b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h @@ -1,15 +1,13 @@ #include "storm/modelchecker/helper/SingleValueModelCheckerHelper.h" +#include "storm/automata/DeterministicAutomaton.h" #include "storm/storage/SparseMatrix.h" #include "storm/solver/SolveGoal.h" +#include "storm/models/sparse/Dtmc.h" +#include "storm/models/sparse/Mdp.h" namespace storm { - namespace automata { - // fwd - class DeterministicAutomaton; - } - namespace modelchecker { namespace helper { @@ -18,14 +16,21 @@ namespace storm { * @tparam ValueType the type a value can have * @tparam Nondeterministic true if there is nondeterminism in the Model (MDP) */ - template<typename ValueType, typename Model, bool Nondeterministic> // todo remove Model + template<typename ValueType, bool Nondeterministic> class SparseLTLHelper: public SingleValueModelCheckerHelper<ValueType, storm::models::ModelRepresentation::Sparse> { public: + + /*! + * The type of the product automaton model // todo + */ + using productModelType = typename std::conditional<Nondeterministic, storm::models::sparse::Mdp<ValueType>, storm::models::sparse::Dtmc<ValueType>>::type; + + /*! * Initializes the helper for a discrete time (i.e. DTMC, MDP) */ - SparseLTLHelper(Model const& model, storm::storage::SparseMatrix<ValueType> const& transitionMatrix); + SparseLTLHelper(storm::storage::SparseMatrix<ValueType> const& transitionMatrix, std::size_t numberOfSates); /*! @@ -44,7 +49,7 @@ namespace storm { private: storm::storage::SparseMatrix<ValueType> const& _transitionMatrix; - Model const& _model; // todo remove ? + std::size_t _numberOfStates; }; } diff --git a/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.cpp b/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.cpp index 64c2eaa05..66b726bce 100644 --- a/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.cpp +++ b/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.cpp @@ -162,7 +162,7 @@ namespace storm { STORM_LOG_INFO("Extracting maximal state formulas and computing satisfaction sets for path formula: " << pathFormula); std::map<std::string, storm::storage::BitVector> apSets; - // todo instead: std::map<std::string, storm::storage::BitVector> apSets = storm::modelchecker::helper::computeApSets(env, checkTask); + // todo apSets = computeApSets(env, checkTask); for (auto& p : extracted) { STORM_LOG_INFO(" Computing satisfaction set for atomic proposition \"" << p.first << "\" <=> " << *p.second << "..."); @@ -177,7 +177,7 @@ namespace storm { const SparseDtmcModelType& dtmc = this->getModel(); - storm::modelchecker::helper::SparseLTLHelper<ValueType, SparseDtmcModelType, false> helper(dtmc, dtmc.getTransitionMatrix()); + storm::modelchecker::helper::SparseLTLHelper<ValueType, false> helper(dtmc.getTransitionMatrix(), this->getModel().getNumberOfStates()); storm::modelchecker::helper::setInformationFromCheckTaskDeterministic(helper, checkTask, dtmc); std::vector<ValueType> numericResult = helper.computeLTLProbabilities(env, storm::solver::SolveGoal<ValueType>(this->getModel(), checkTask), *ltlFormula, apSets); diff --git a/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.cpp b/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.cpp index dbf044910..6f0bc270a 100644 --- a/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.cpp +++ b/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.cpp @@ -219,7 +219,7 @@ namespace storm { const SparseMdpModelType& mdp = this->getModel(); storm::solver::SolveGoal<ValueType> goal(mdp, subTask); - storm::modelchecker::helper::SparseLTLHelper<ValueType, SparseMdpModelType, true> helper(mdp, mdp.getTransitionMatrix()); + storm::modelchecker::helper::SparseLTLHelper<ValueType, true> helper(mdp.getTransitionMatrix(), this->getModel().getNumberOfStates()); storm::modelchecker::helper::setInformationFromCheckTaskNondeterministic(helper, subTask, mdp); std::vector<ValueType> numericResult = helper.computeLTLProbabilities(env, storm::solver::SolveGoal<ValueType>(this->getModel(), subTask), *ltlFormula, apSets); @@ -233,88 +233,6 @@ namespace storm { return std::unique_ptr<CheckResult>(new ExplicitQuantitativeCheckResult<ValueType>(std::move(numericResult))); } - - /* - template<typename SparseMdpModelType> - std::vector<typename SparseMdpPrctlModelChecker<SparseMdpModelType>::ValueType> SparseMdpPrctlModelChecker<SparseMdpModelType>::computeDAProductProbabilities(Environment const& env, storm::solver::SolveGoal<typename SparseMdpPrctlModelChecker<SparseMdpModelType>::ValueType>&& goal, storm::automata::DeterministicAutomaton const& da, std::map<std::string, storm::storage::BitVector>& apSatSets, bool qualitative) const { - STORM_LOG_THROW(goal.hasDirection() && goal.direction() == OptimizationDirection::Maximize, storm::exceptions::InvalidPropertyException, "Can only compute maximizing probabilties for DA product with MDP"); - - const storm::automata::APSet& apSet = da.getAPSet(); - - std::vector<storm::storage::BitVector> apLabels; - 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"); - - apLabels.push_back(std::move(it->second)); - } - - const SparseMdpModelType& mdp = this->getModel(); - - storm::storage::BitVector statesOfInterest; - if (goal.hasRelevantValues()) { - statesOfInterest = goal.relevantValues(); - } else { - // product from all model states - statesOfInterest = storm::storage::BitVector(mdp.getNumberOfStates(), true); - } - - STORM_LOG_INFO("Building MDP-DA product with deterministic automaton, starting from " << statesOfInterest.getNumberOfSetBits() << " model states..."); - storm::transformer::DAProductBuilder productBuilder(da, apLabels); - auto product = productBuilder.build(mdp, statesOfInterest); - STORM_LOG_INFO("Product MDP has " << product->getProductModel().getNumberOfStates() << " states and " - << product->getProductModel().getNumberOfTransitions() << " transitions."); - - if (storm::settings::getModule<storm::settings::modules::DebugSettings>().isTraceSet()) { - STORM_LOG_TRACE("Writing model to model.dot"); - std::ofstream modelDot("model.dot"); - mdp.writeDotToStream(modelDot); - modelDot.close(); - - STORM_LOG_TRACE("Writing product model to product.dot"); - std::ofstream productDot("product.dot"); - product->getProductModel().writeDotToStream(productDot); - productDot.close(); - - STORM_LOG_TRACE("Product model mapping:"); - std::stringstream str; - product->printMapping(str); - STORM_LOG_TRACE(str.str()); - } - - STORM_LOG_INFO("Computing accepting end components..."); - storm::storage::BitVector accepting = storm::modelchecker::helper::SparseMdpPrctlHelper<ValueType>::computeSurelyAcceptingPmaxStates(*product->getAcceptance(), product->getProductModel().getTransitionMatrix(), product->getProductModel().getBackwardTransitions()); - if (accepting.empty()) { - STORM_LOG_INFO("No accepting states, skipping probability computation."); - std::vector<ValueType> numericResult(this->getModel().getNumberOfStates(), storm::utility::zero<ValueType>()); - return numericResult; - } - - STORM_LOG_INFO("Computing probabilities for reaching accepting BSCCs..."); - - storm::storage::BitVector bvTrue(product->getProductModel().getNumberOfStates(), true); - - storm::solver::SolveGoal<ValueType> solveGoalProduct(goal); - storm::storage::BitVector soiProduct(product->getStatesOfInterest()); - solveGoalProduct.setRelevantValues(std::move(soiProduct)); - - std::vector<ValueType> prodNumericResult - = std::move(storm::modelchecker::helper::SparseMdpPrctlHelper<ValueType>::computeUntilProbabilities(env, - std::move(solveGoalProduct), - product->getProductModel().getTransitionMatrix(), - product->getProductModel().getBackwardTransitions(), - bvTrue, - accepting, - qualitative, - false // no schedulers (at the moment) - ).values); - - std::vector<ValueType> numericResult = product->projectToOriginalModel(this->getModel(), prodNumericResult); - return numericResult; - } - */ - - 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/transformer/DAProductBuilder.h b/src/storm/transformer/DAProductBuilder.h index 9e903e058..d90d4b6dc 100644 --- a/src/storm/transformer/DAProductBuilder.h +++ b/src/storm/transformer/DAProductBuilder.h @@ -18,10 +18,15 @@ namespace storm { template <typename Model> typename DAProduct<Model>::ptr build(const Model& originalModel, const storm::storage::BitVector& statesOfInterest) const { - typename Product<Model>::ptr product = ProductBuilder<Model>::buildProduct(originalModel, *this, statesOfInterest); + 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 { //todo transition matrix + 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);}); + = 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)); } diff --git a/src/storm/transformer/Product.h b/src/storm/transformer/Product.h index d0d826d0f..ee037784b 100644 --- a/src/storm/transformer/Product.h +++ b/src/storm/transformer/Product.h @@ -60,7 +60,12 @@ namespace storm { template <typename ValueType> std::vector<ValueType> projectToOriginalModel(const Model& originalModel, const std::vector<ValueType>& prodValues) { - std::vector<ValueType> origValues(originalModel.getNumberOfStates()); + 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); diff --git a/src/storm/transformer/ProductBuilder.h b/src/storm/transformer/ProductBuilder.h index 32f3a0cea..a82bd2839 100644 --- a/src/storm/transformer/ProductBuilder.h +++ b/src/storm/transformer/ProductBuilder.h @@ -17,8 +17,7 @@ namespace storm { typedef storm::storage::SparseMatrix<typename Model::ValueType> matrix_type; template <typename ProductOperator> - static typename Product<Model>::ptr buildProduct(const Model& originalModel, ProductOperator& prodOp, const storm::storage::BitVector& statesOfInterest) { - const matrix_type& originalMatrix = originalModel.getTransitionMatrix(); + 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; From 1fe30f7d785ac449624a120813ad86c64cd08766 Mon Sep 17 00:00:00 2001 From: hannah <hannah.mertens@rwth-aachen.de> Date: Wed, 19 May 2021 02:03:11 +0200 Subject: [PATCH 061/172] Convert acceptance formula into disjunctive normal form --- src/storm/automata/LTL2DeterministicAutomaton.cpp | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/storm/automata/LTL2DeterministicAutomaton.cpp b/src/storm/automata/LTL2DeterministicAutomaton.cpp index 3833db73e..5383745ed 100644 --- a/src/storm/automata/LTL2DeterministicAutomaton.cpp +++ b/src/storm/automata/LTL2DeterministicAutomaton.cpp @@ -11,6 +11,9 @@ #include "spot/tl/parse.hh" #include "spot/twaalgos/translate.hh" #include "spot/twaalgos/hoa.hh" +#include "spot/twaalgos/totgba.hh" +#include "spot/twaalgos/toparity.hh" +#include "spot/twa/acc.hh" #endif namespace storm { @@ -36,6 +39,11 @@ namespace storm { STORM_LOG_INFO("Construct deterministic automaton for "<< spotFormula); auto aut = trans.run(spotFormula); + // TODO necessary for MDP LTL-MC + if(!(aut->get_acceptance().is_dnf())){ + aut->set_acceptance(aut->get_acceptance().to_dnf()); + } + std::stringstream autStream; // Print reachable states in HOA format, implicit edges (i), state-based acceptance (s) spot::print_hoa(autStream, aut, "is"); From fc0ae2ea4bf09be74ec542f8aafc995d89a2bfef Mon Sep 17 00:00:00 2001 From: hannah <hannah.mertens@rwth-aachen.de> Date: Thu, 20 May 2021 23:41:11 +0200 Subject: [PATCH 062/172] removed SolveGoal in function computeLTLproabilities of SparseLTLHelper --- .../helper/ltl/SparseLTLHelper.cpp | 245 +++++++++++++----- .../modelchecker/helper/ltl/SparseLTLHelper.h | 21 +- .../prctl/SparseDtmcPrctlModelChecker.cpp | 11 +- .../prctl/SparseMdpPrctlModelChecker.cpp | 12 +- .../prctl/helper/SparseMdpPrctlHelper.cpp | 111 -------- .../prctl/helper/SparseMdpPrctlHelper.h | 11 - 6 files changed, 222 insertions(+), 189 deletions(-) diff --git a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp index 8182289ce..86841f63f 100644 --- a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp +++ b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp @@ -7,6 +7,7 @@ #include "storm/modelchecker/prctl/helper/SparseMdpPrctlHelper.h" #include "storm/storage/StronglyConnectedComponentDecomposition.h" +#include "storm/storage/MaximalEndComponentDecomposition.h" #include "storm/settings/SettingsManager.h" #include "storm/settings/modules/DebugSettings.h" @@ -21,11 +22,143 @@ namespace storm { // Intentionally left empty. } - template<typename ValueType, bool Nondeterministic> - std::vector<ValueType> SparseLTLHelper<ValueType, Nondeterministic>::computeDAProductProbabilities(Environment const& env, storm::solver::SolveGoal<ValueType>&& goal, storm::automata::DeterministicAutomaton const& da, std::map<std::string, storm::storage::BitVector>& apSatSets, bool qualitative) { - STORM_LOG_THROW((!Nondeterministic) || goal.hasDirection() && goal.direction() == OptimizationDirection::Maximize, storm::exceptions::InvalidPropertyException, "Can only compute maximizing probabilties for DA product with MDP"); + // todo only for MDP and change name! + template <typename ValueType, bool Nondeterministic> + storm::storage::BitVector SparseLTLHelper<ValueType, Nondeterministic>::computeSurelyAcceptingPmaxStates(automata::AcceptanceCondition const& acceptance, storm::storage::SparseMatrix<ValueType> const& transitionMatrix, storm::storage::SparseMatrix<ValueType> const& backwardTransitions) { + 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; + std::size_t i = 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); + + STORM_LOG_INFO("Handle conjunction " << i); + + for (auto const& literal : conjunction) { + STORM_LOG_INFO(" " << *literal); + 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; + } + + STORM_LOG_DEBUG(" Allowed states: " << allowed); + + // compute MECs in the allowed fragment + storm::storage::MaximalEndComponentDecomposition<ValueType> mecs(transitionMatrix, backwardTransitions, allowed); + allMECs += mecs.size(); + for (const auto& mec : mecs) { + STORM_LOG_DEBUG("Inspect MEC: " << mec); + + 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()) { + STORM_LOG_DEBUG("Checking against " << ~accSet); + if (!mec.containsAnyState(~accSet)) { + STORM_LOG_DEBUG(" -> not satisfied"); + accepting = false; + break; + } + } else { + STORM_LOG_DEBUG("Checking against " << accSet); + if (!mec.containsAnyState(accSet)) { + STORM_LOG_DEBUG(" -> not satisfied"); + 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++; + STORM_LOG_DEBUG("MEC is accepting"); + for (auto const& stateChoicePair : mec) { + acceptingStates.set(stateChoicePair.first); + } + } + + } + } + + STORM_LOG_DEBUG("Accepting states: " << acceptingStates); + STORM_LOG_INFO("Found " << acceptingStates.getNumberOfSetBits() << " states in " << accMECs << " accepting MECs (considered " << allMECs << " MECs)."); + + return acceptingStates; + } + + // todo only for dtmc and change name! + template <typename ValueType, bool Nondeterministic> + storm::storage::BitVector SparseLTLHelper<ValueType, Nondeterministic>::computeAcceptingComponentStates(automata::AcceptanceCondition const& acceptance, storm::storage::SparseMatrix<ValueType> const& transitionMatrix) { + storm::storage::StronglyConnectedComponentDecomposition<ValueType> bottomSccs(transitionMatrix, storage::StronglyConnectedComponentDecompositionOptions().onlyBottomSccs().dropNaiveSccs()); + //storm::storage::BitVector acceptingStates = storm::storage::BitVector(product->getProductModel().getNumberOfStates()); + 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, bool qualitative) { const storm::automata::APSet& apSet = da.getAPSet(); std::vector<storm::storage::BitVector> apLabels; @@ -37,28 +170,25 @@ namespace storm { } storm::storage::BitVector statesOfInterest; - if (goal.hasRelevantValues()) { - statesOfInterest = goal.relevantValues(); + + if (this->hasRelevantStates()) { + statesOfInterest = this->getRelevantStates(); } else { // product from all model states statesOfInterest = storm::storage::BitVector(this->_numberOfStates, true); } + // todo change text STORM_LOG_INFO("Building "+ (Nondeterministic ? std::string("MDP-DA") : std::string("DTMC-DA")) +"product with deterministic automaton, starting from " << statesOfInterest.getNumberOfSetBits() << " model states..."); storm::transformer::DAProductBuilder productBuilder(da, apLabels); auto product = productBuilder.build<productModelType>(this->_transitionMatrix, statesOfInterest); - STORM_LOG_INFO("Product "+ (Nondeterministic ? std::string("MDP-DA") : std::string("DTMC")) +" has " << product->getProductModel().getNumberOfStates() << " states and " + STORM_LOG_INFO("Product "+ (Nondeterministic ? std::string("MDP-DA") : std::string("DTMC-DA")) +" has " << product->getProductModel().getNumberOfStates() << " states and " << product->getProductModel().getNumberOfTransitions() << " transitions."); if (storm::settings::getModule<storm::settings::modules::DebugSettings>().isTraceSet()) { - STORM_LOG_TRACE("Writing model to model.dot"); - std::ofstream modelDot("model.dot"); - // this->_model.writeDotToStream(modelDot); // TODO - modelDot.close(); - STORM_LOG_TRACE("Writing product model to product.dot"); std::ofstream productDot("product.dot"); product->getProductModel().writeDotToStream(productDot); @@ -70,75 +200,63 @@ namespace storm { STORM_LOG_TRACE(str.str()); } - // DTMC: BCC // MDP: computeSurelyAcceptingPmaxStates - storm::storage::BitVector accepting; + storm::storage::BitVector acceptingStates; if (Nondeterministic) { STORM_LOG_INFO("Computing accepting end components..."); - accepting = storm::modelchecker::helper::SparseMdpPrctlHelper<ValueType>::computeSurelyAcceptingPmaxStates(*product->getAcceptance(), product->getProductModel().getTransitionMatrix(), product->getProductModel().getBackwardTransitions()); - if (accepting.empty()) { - STORM_LOG_INFO("No accepting states, skipping probability computation."); - std::vector<ValueType> numericResult(this->_numberOfStates, storm::utility::zero<ValueType>()); - return numericResult; - } + // todo compute accepting states, same as below + acceptingStates = computeSurelyAcceptingPmaxStates(*product->getAcceptance(), product->getProductModel().getTransitionMatrix(), product->getProductModel().getBackwardTransitions()); + } else { STORM_LOG_INFO("Computing BSCCs and checking for acceptance..."); + // todo compute accepting states, (no btm) + acceptingStates = computeAcceptingComponentStates(*product->getAcceptance(), product->getProductModel().getTransitionMatrix()); - storm::storage::StronglyConnectedComponentDecomposition<ValueType> bottomSccs(product->getProductModel().getTransitionMatrix(), - storage::StronglyConnectedComponentDecompositionOptions().onlyBottomSccs().dropNaiveSccs()); - accepting = storm::storage::BitVector(product->getProductModel().getNumberOfStates()); - std::size_t checkedBSCCs = 0, acceptingBSCCs = 0, acceptingBSCCStates = 0; - for (auto& scc : bottomSccs) { - checkedBSCCs++; - if (product->getAcceptance()->isAccepting(scc)) { - acceptingBSCCs++; - for (auto& state : scc) { - accepting.set(state); - acceptingBSCCStates++; - } - } - } - - STORM_LOG_INFO("BSCC analysis: " << acceptingBSCCs << " of " << checkedBSCCs << " BSCCs were accepting (" << acceptingBSCCStates << " states in accepting BSCCs)."); + } - if (acceptingBSCCs == 0) { - STORM_LOG_INFO("No accepting BSCCs, skipping probability computation."); - std::vector<ValueType> numericResult(this->_numberOfStates, storm::utility::zero<ValueType>()); - return numericResult; - } + if (acceptingStates.empty()) { + STORM_LOG_INFO("No acceptingStates states, skipping probability computation."); + std::vector<ValueType> numericResult(this->_numberOfStates, storm::utility::zero<ValueType>()); + return numericResult; } - STORM_LOG_INFO("Computing probabilities for reaching accepting components..."); + STORM_LOG_INFO("Computing probabilities for reaching acceptingStates components..."); storm::storage::BitVector bvTrue(product->getProductModel().getNumberOfStates(), true); - - storm::solver::SolveGoal<ValueType> solveGoalProduct(goal); storm::storage::BitVector soiProduct(product->getStatesOfInterest()); - solveGoalProduct.setRelevantValues(std::move(soiProduct)); + + // Create goal for computeUntilProbabilities, compute maximizing probabilties for DA product with MDP + 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) { prodNumericResult = std::move(storm::modelchecker::helper::SparseMdpPrctlHelper<ValueType>::computeUntilProbabilities(env, - std::move(solveGoalProduct), - product->getProductModel().getTransitionMatrix(), - product->getProductModel().getBackwardTransitions(), - bvTrue, - accepting, - qualitative, - false // no schedulers (at the moment) + std::move(solveGoalProduct), + product->getProductModel().getTransitionMatrix(), + product->getProductModel().getBackwardTransitions(), + bvTrue, + acceptingStates, + qualitative, + false // no schedulers (at the moment) ).values); } else { prodNumericResult = storm::modelchecker::helper::SparseDtmcPrctlHelper<ValueType>::computeUntilProbabilities(env, - std::move(solveGoalProduct), - product->getProductModel().getTransitionMatrix(), - product->getProductModel().getBackwardTransitions(), - bvTrue, - accepting, - qualitative); + std::move(solveGoalProduct), + product->getProductModel().getTransitionMatrix(), + product->getProductModel().getBackwardTransitions(), + bvTrue, + acceptingStates, + qualitative); } std::vector<ValueType> numericResult = product->projectToOriginalModel(this->_numberOfStates, prodNumericResult); @@ -146,8 +264,12 @@ namespace storm { } + //todo remove goal? template<typename ValueType, bool Nondeterministic> - std::vector <ValueType> SparseLTLHelper<ValueType, Nondeterministic>::computeLTLProbabilities(Environment const &env, storm::solver::SolveGoal<ValueType>&& goal, storm::logic::Formula const& ltlFormula, std::map<std::string, storm::storage::BitVector>& apSatSets) { + std::vector <ValueType> SparseLTLHelper<ValueType, Nondeterministic>::computeLTLProbabilities(Environment const &env, storm::logic::Formula const& ltlFormula, std::map<std::string, storm::storage::BitVector>& apSatSets) { + // TODO optDir: helper.getOptimizationDirection for MDP + // negate formula etc ~ap? + STORM_LOG_INFO("Resulting LTL path formula: " << ltlFormula); STORM_LOG_INFO(" in prefix format: " << ltlFormula.toPrefixString()); @@ -159,10 +281,11 @@ namespace storm { << *da->getAcceptance()->getAcceptanceExpression() << " as acceptance condition."); - std::vector<ValueType> numericResult = computeDAProductProbabilities(env, std::move(goal), *da, apSatSets, this->isQualitativeSet()); + //todo remove goal here? send dir instead? + std::vector<ValueType> numericResult = computeDAProductProbabilities(env, *da, apSatSets, this->isQualitativeSet()); - // TODO - /* + // TODO optDir: helper.getOptimizationDirection for MDP + /* //for any path formula ψ: pmin(s, ψ) = 1- pmax(s, ¬ψ) if(Nondeterministic && this->getOptimizationDirection()==OptimizationDirection::Minimize) { // compute 1-Pmax[!ltl] for (auto& value : numericResult) { diff --git a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h index 42bf322cc..3e69b6f8d 100644 --- a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h +++ b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h @@ -35,19 +35,36 @@ namespace storm { /*! * todo + * Computes maximizing(!) probabilties for DA product with MDP * @return */ - std::vector<ValueType> computeDAProductProbabilities(Environment const& env, storm::solver::SolveGoal<ValueType>&& goal, storm::automata::DeterministicAutomaton const& da, std::map<std::string, storm::storage::BitVector>& apSatSets, bool qualitative); + std::vector<ValueType> computeDAProductProbabilities(Environment const& env, storm::automata::DeterministicAutomaton const& da, std::map<std::string, storm::storage::BitVector>& apSatSets, bool qualitative); /*! * Computes the ltl probabilities ...todo * @return a value for each state */ - std::vector<ValueType> computeLTLProbabilities(Environment const &env, storm::solver::SolveGoal<ValueType>&& goal, storm::logic::Formula const& f, std::map<std::string, storm::storage::BitVector>& apSatSets); //todo was brauchen wir hier aps und ..? + std::vector<ValueType> computeLTLProbabilities(Environment const &env, storm::logic::Formula const& f, std::map<std::string, storm::storage::BitVector>& apSatSets); //todo was brauchen wir hier aps und ..? private: + + /*! todo only relevant for MDP - enable_if_t ? + * Compute a set S of states that admit a probability 1 strategy of satisfying the given acceptance conditon. + * 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. + */ + static storm::storage::BitVector computeSurelyAcceptingPmaxStates(automata::AcceptanceCondition const& acceptance, storm::storage::SparseMatrix<ValueType> const& transitionMatrix, storm::storage::SparseMatrix<ValueType> const& backwardTransitions); + + //todo only for dtmc, different to mdp: no backward tm + static storm::storage::BitVector computeAcceptingComponentStates(automata::AcceptanceCondition const& acceptance, storm::storage::SparseMatrix<ValueType> const& transitionMatrix); + + storm::storage::SparseMatrix<ValueType> const& _transitionMatrix; std::size_t _numberOfStates; diff --git a/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.cpp b/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.cpp index 66b726bce..28009225c 100644 --- a/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.cpp +++ b/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.cpp @@ -162,7 +162,6 @@ namespace storm { STORM_LOG_INFO("Extracting maximal state formulas and computing satisfaction sets for path formula: " << pathFormula); std::map<std::string, storm::storage::BitVector> apSets; - // todo apSets = computeApSets(env, checkTask); for (auto& p : extracted) { STORM_LOG_INFO(" Computing satisfaction set for atomic proposition \"" << p.first << "\" <=> " << *p.second << "..."); @@ -177,9 +176,17 @@ namespace storm { const SparseDtmcModelType& dtmc = this->getModel(); + // TODO + if (storm::settings::getModule<storm::settings::modules::DebugSettings>().isTraceSet()) { + STORM_LOG_TRACE("Writing model to model.dot"); + std::ofstream modelDot("model.dot"); + this->getModel().writeDotToStream(modelDot); + modelDot.close(); + } + storm::modelchecker::helper::SparseLTLHelper<ValueType, false> helper(dtmc.getTransitionMatrix(), this->getModel().getNumberOfStates()); storm::modelchecker::helper::setInformationFromCheckTaskDeterministic(helper, checkTask, dtmc); - std::vector<ValueType> numericResult = helper.computeLTLProbabilities(env, storm::solver::SolveGoal<ValueType>(this->getModel(), checkTask), *ltlFormula, apSets); + std::vector<ValueType> numericResult = helper.computeLTLProbabilities(env, *ltlFormula, apSets); return std::unique_ptr<CheckResult>(new ExplicitQuantitativeCheckResult<ValueType>(std::move(numericResult))); } diff --git a/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.cpp b/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.cpp index 6f0bc270a..85f89bf18 100644 --- a/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.cpp +++ b/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.cpp @@ -217,11 +217,19 @@ namespace storm { } const SparseMdpModelType& mdp = this->getModel(); - storm::solver::SolveGoal<ValueType> goal(mdp, subTask); + storm::solver::SolveGoal<ValueType> goal(mdp, subTask); //todo remove, infos now in helper, see below + + // TODO + if (storm::settings::getModule<storm::settings::modules::DebugSettings>().isTraceSet()) { + STORM_LOG_TRACE("Writing model to model.dot"); + std::ofstream modelDot("model.dot"); + this->getModel().writeDotToStream(modelDot); + modelDot.close(); + } storm::modelchecker::helper::SparseLTLHelper<ValueType, true> helper(mdp.getTransitionMatrix(), this->getModel().getNumberOfStates()); storm::modelchecker::helper::setInformationFromCheckTaskNondeterministic(helper, subTask, mdp); - std::vector<ValueType> numericResult = helper.computeLTLProbabilities(env, storm::solver::SolveGoal<ValueType>(this->getModel(), subTask), *ltlFormula, apSets); + std::vector<ValueType> numericResult = helper.computeLTLProbabilities(env, *ltlFormula, apSets); if(minimize) { // compute 1-Pmax[!ltl] diff --git a/src/storm/modelchecker/prctl/helper/SparseMdpPrctlHelper.cpp b/src/storm/modelchecker/prctl/helper/SparseMdpPrctlHelper.cpp index 2e4cb8894..17bef0ff8 100644 --- a/src/storm/modelchecker/prctl/helper/SparseMdpPrctlHelper.cpp +++ b/src/storm/modelchecker/prctl/helper/SparseMdpPrctlHelper.cpp @@ -745,117 +745,6 @@ namespace storm { return result; } } - - template<typename ValueType> - storm::storage::BitVector SparseMdpPrctlHelper<ValueType>::computeSurelyAcceptingPmaxStates(automata::AcceptanceCondition const& acceptance, storm::storage::SparseMatrix<ValueType> const& transitionMatrix, storm::storage::SparseMatrix<ValueType> const& backwardTransitions) { - 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; - std::size_t i = 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); - - STORM_LOG_DEBUG("Handle conjunction " << i); - - for (auto const& literal : conjunction) { - STORM_LOG_DEBUG(" " << *literal); - 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; - } - - STORM_LOG_DEBUG(" Allowed states: " << allowed); - - // compute MECs in the allowed fragment - storm::storage::MaximalEndComponentDecomposition<ValueType> mecs(transitionMatrix, backwardTransitions, allowed); - allMECs += mecs.size(); - for (const auto& mec : mecs) { - STORM_LOG_DEBUG("Inspect MEC: " << mec); - - 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()) { - STORM_LOG_DEBUG("Checking against " << ~accSet); - if (!mec.containsAnyState(~accSet)) { - STORM_LOG_DEBUG(" -> not satisfied"); - accepting = false; - break; - } - } else { - STORM_LOG_DEBUG("Checking against " << accSet); - if (!mec.containsAnyState(accSet)) { - STORM_LOG_DEBUG(" -> not satisfied"); - 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++; - STORM_LOG_DEBUG("MEC is accepting"); - for (auto const& stateChoicePair : mec) { - acceptingStates.set(stateChoicePair.first); - } - } - - } - } - - STORM_LOG_DEBUG("Accepting states: " << acceptingStates); - STORM_LOG_INFO("Found " << acceptingStates.getNumberOfSetBits() << " states in " << accMECs << " accepting MECs (considered " << allMECs << " MECs)."); - - return acceptingStates; - } template<typename ValueType> template<typename RewardModelType> diff --git a/src/storm/modelchecker/prctl/helper/SparseMdpPrctlHelper.h b/src/storm/modelchecker/prctl/helper/SparseMdpPrctlHelper.h index e70648186..ea38383f0 100644 --- a/src/storm/modelchecker/prctl/helper/SparseMdpPrctlHelper.h +++ b/src/storm/modelchecker/prctl/helper/SparseMdpPrctlHelper.h @@ -48,17 +48,6 @@ 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); - - /*! - * Compute a set S of states that admit a probability 1 strategy of satisfying the given acceptance conditon. - * 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. - */ - static storm::storage::BitVector computeSurelyAcceptingPmaxStates(automata::AcceptanceCondition const& acceptance, storm::storage::SparseMatrix<ValueType> const& transitionMatrix, storm::storage::SparseMatrix<ValueType> const& backwardTransitions); 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); From 93d9b586edad847285c37f9fc4add123030345ab Mon Sep 17 00:00:00 2001 From: hannah <hannah.mertens@rwth-aachen.de> Date: Fri, 21 May 2021 01:34:23 +0200 Subject: [PATCH 063/172] compute 1-Pmax[in order to compute Pmin for MDPs --- .../helper/ltl/SparseLTLHelper.cpp | 32 +++++++++++-------- .../modelchecker/helper/ltl/SparseLTLHelper.h | 2 +- .../prctl/SparseMdpPrctlModelChecker.cpp | 24 +------------- 3 files changed, 20 insertions(+), 38 deletions(-) diff --git a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp index 86841f63f..12b51dcf4 100644 --- a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp +++ b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp @@ -227,7 +227,7 @@ namespace storm { storm::storage::BitVector bvTrue(product->getProductModel().getNumberOfStates(), true); storm::storage::BitVector soiProduct(product->getStatesOfInterest()); - // Create goal for computeUntilProbabilities, compute maximizing probabilties for DA product with MDP + // Create goal for computeUntilProbabilities, compute maximizing probabilities for DA product with MDP storm::solver::SolveGoal<ValueType> solveGoalProduct; if (this->isValueThresholdSet()) { solveGoalProduct = storm::solver::SolveGoal<ValueType>(OptimizationDirection::Maximize, this->getValueThresholdComparisonType(), this->getValueThresholdValue(), std::move(soiProduct)); @@ -263,17 +263,23 @@ namespace storm { return numericResult; } - - //todo remove goal? template<typename ValueType, bool Nondeterministic> - std::vector <ValueType> SparseLTLHelper<ValueType, Nondeterministic>::computeLTLProbabilities(Environment const &env, storm::logic::Formula const& ltlFormula, std::map<std::string, storm::storage::BitVector>& apSatSets) { - // TODO optDir: helper.getOptimizationDirection for MDP - // negate formula etc ~ap? + std::vector <ValueType> SparseLTLHelper<ValueType, Nondeterministic>::computeLTLProbabilities(Environment const &env, storm::logic::Formula 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); - STORM_LOG_INFO(" in prefix format: " << ltlFormula.toPrefixString()); - std::shared_ptr<storm::automata::DeterministicAutomaton> da = storm::automata::LTL2DeterministicAutomaton::ltl2da(ltlFormula); + STORM_LOG_INFO("Resulting LTL path formula: " << ltlFormula->toString()); + STORM_LOG_INFO(" in prefix format: " << ltlFormula->toPrefixString()); + + std::shared_ptr<storm::automata::DeterministicAutomaton> da = storm::automata::LTL2DeterministicAutomaton::ltl2da(*ltlFormula); STORM_LOG_INFO("Deterministic automaton for LTL formula has " << da->getNumberOfStates() << " states, " @@ -281,18 +287,16 @@ namespace storm { << *da->getAcceptance()->getAcceptanceExpression() << " as acceptance condition."); - //todo remove goal here? send dir instead? + // compute Pmax for MDP std::vector<ValueType> numericResult = computeDAProductProbabilities(env, *da, apSatSets, this->isQualitativeSet()); - // TODO optDir: helper.getOptimizationDirection for MDP - /* //for any path formula ψ: pmin(s, ψ) = 1- pmax(s, ¬ψ) if(Nondeterministic && this->getOptimizationDirection()==OptimizationDirection::Minimize) { - // compute 1-Pmax[!ltl] + // compute 1-Pmax[!fomula] for (auto& value : numericResult) { value = storm::utility::one<ValueType>() - value; } } - */ + return numericResult; } diff --git a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h index 3e69b6f8d..b8944446c 100644 --- a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h +++ b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h @@ -45,7 +45,7 @@ namespace storm { * Computes the ltl probabilities ...todo * @return a value for each state */ - std::vector<ValueType> computeLTLProbabilities(Environment const &env, storm::logic::Formula const& f, std::map<std::string, storm::storage::BitVector>& apSatSets); //todo was brauchen wir hier aps und ..? + std::vector<ValueType> computeLTLProbabilities(Environment const &env, storm::logic::Formula const& formula, std::map<std::string, storm::storage::BitVector>& apSatSets); //todo was brauchen wir hier aps und ..? private: diff --git a/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.cpp b/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.cpp index 85f89bf18..1623477f1 100644 --- a/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.cpp +++ b/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.cpp @@ -202,22 +202,7 @@ namespace storm { apSets[p.first] = std::move(sat); } - bool minimize = false; - CheckTask<storm::logic::Formula, ValueType> subTask(checkTask); - - if (checkTask.getOptimizationDirection() == OptimizationDirection::Minimize) { - minimize = true; - // negate - ltlFormula = std::make_shared<storm::logic::UnaryBooleanPathFormula>(storm::logic::UnaryBooleanOperatorType::Not, ltlFormula); - STORM_LOG_INFO("Computing Pmin, proceeding with negated LTL formula."); - - subTask = checkTask.negate().substituteFormula(*ltlFormula); - } else { - subTask = checkTask.substituteFormula(*ltlFormula); - } - const SparseMdpModelType& mdp = this->getModel(); - storm::solver::SolveGoal<ValueType> goal(mdp, subTask); //todo remove, infos now in helper, see below // TODO if (storm::settings::getModule<storm::settings::modules::DebugSettings>().isTraceSet()) { @@ -228,16 +213,9 @@ namespace storm { } storm::modelchecker::helper::SparseLTLHelper<ValueType, true> helper(mdp.getTransitionMatrix(), this->getModel().getNumberOfStates()); - storm::modelchecker::helper::setInformationFromCheckTaskNondeterministic(helper, subTask, mdp); + storm::modelchecker::helper::setInformationFromCheckTaskNondeterministic(helper, checkTask, mdp); std::vector<ValueType> numericResult = helper.computeLTLProbabilities(env, *ltlFormula, apSets); - if(minimize) { - // compute 1-Pmax[!ltl] - for (auto& value : numericResult) { - value = storm::utility::one<ValueType>() - value; - } - } - return std::unique_ptr<CheckResult>(new ExplicitQuantitativeCheckResult<ValueType>(std::move(numericResult))); } From 139ac3d0dc61e6f8a00f5a999d1461439dbadf1d Mon Sep 17 00:00:00 2001 From: hannah <hannah.mertens@rwth-aachen.de> Date: Wed, 26 May 2021 12:39:19 +0200 Subject: [PATCH 064/172] flag to indicate whether condition should be in dnf --- src/storm/automata/LTL2DeterministicAutomaton.cpp | 5 +++-- src/storm/automata/LTL2DeterministicAutomaton.h | 2 +- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/src/storm/automata/LTL2DeterministicAutomaton.cpp b/src/storm/automata/LTL2DeterministicAutomaton.cpp index 5383745ed..06ceb5f03 100644 --- a/src/storm/automata/LTL2DeterministicAutomaton.cpp +++ b/src/storm/automata/LTL2DeterministicAutomaton.cpp @@ -19,7 +19,7 @@ namespace storm { namespace automata { - std::shared_ptr<DeterministicAutomaton> LTL2DeterministicAutomaton::ltl2da(storm::logic::Formula const& f) { + std::shared_ptr<DeterministicAutomaton> LTL2DeterministicAutomaton::ltl2da(storm::logic::Formula const& f, bool dnf) { #ifdef STORM_HAVE_SPOT std::string prefixLtl = f.toPrefixString(); @@ -40,7 +40,8 @@ namespace storm { auto aut = trans.run(spotFormula); // TODO necessary for MDP LTL-MC - if(!(aut->get_acceptance().is_dnf())){ + if(!(aut->get_acceptance().is_dnf()) && dnf){ + STORM_LOG_INFO("Convert acceptance condition into DNF..."); aut->set_acceptance(aut->get_acceptance().to_dnf()); } diff --git a/src/storm/automata/LTL2DeterministicAutomaton.h b/src/storm/automata/LTL2DeterministicAutomaton.h index c39f1b235..32be1ca32 100644 --- a/src/storm/automata/LTL2DeterministicAutomaton.h +++ b/src/storm/automata/LTL2DeterministicAutomaton.h @@ -17,7 +17,7 @@ namespace storm { class LTL2DeterministicAutomaton { public: - static std::shared_ptr<DeterministicAutomaton> ltl2da(storm::logic::Formula const& f); + static std::shared_ptr<DeterministicAutomaton> ltl2da(storm::logic::Formula const&, bool dnf); }; } From 667d4a0e06291ceb72efb4c63f8cc0ddd40fe4f0 Mon Sep 17 00:00:00 2001 From: hannah <hannah.mertens@rwth-aachen.de> Date: Wed, 26 May 2021 12:44:07 +0200 Subject: [PATCH 065/172] documentation and renaming of some methods Conflicts: src/storm/modelchecker/csl/SparseCtmcCslModelChecker.cpp --- .../csl/SparseCtmcCslModelChecker.cpp | 84 +++++++++++++++---- .../helper/ltl/SparseLTLHelper.cpp | 26 ++---- .../modelchecker/helper/ltl/SparseLTLHelper.h | 44 ++++++---- .../prctl/SparseDtmcPrctlModelChecker.cpp | 1 - 4 files changed, 106 insertions(+), 49 deletions(-) diff --git a/src/storm/modelchecker/csl/SparseCtmcCslModelChecker.cpp b/src/storm/modelchecker/csl/SparseCtmcCslModelChecker.cpp index 513f9d8cb..5b296a5a2 100644 --- a/src/storm/modelchecker/csl/SparseCtmcCslModelChecker.cpp +++ b/src/storm/modelchecker/csl/SparseCtmcCslModelChecker.cpp @@ -30,7 +30,7 @@ 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); @@ -39,12 +39,12 @@ namespace storm { } 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 +68,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 +77,7 @@ 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>::computeUntilProbabilities(Environment const& env, CheckTask<storm::logic::UntilFormula, ValueType> const& checkTask) { storm::logic::UntilFormula const& pathFormula = checkTask.getFormula(); @@ -88,7 +88,61 @@ 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>::computeLTLProbabilities(Environment const& env, CheckTask<storm::logic::PathFormula, ValueType> const& checkTask) { + storm::logic::PathFormula const& pathFormula = checkTask.getFormula(); + + std::vector<storm::logic::ExtractMaximalStateFormulasVisitor::LabelFormulaPair> extracted; + std::shared_ptr<storm::logic::Formula> ltlFormula = storm::logic::ExtractMaximalStateFormulasVisitor::extract(pathFormula, extracted); + + STORM_LOG_INFO("Extracting maximal state formulas and computing satisfaction sets for path formula: " << pathFormula); + + std::map<std::string, storm::storage::BitVector> apSets; + + for (auto& p : extracted) { + STORM_LOG_INFO(" Computing satisfaction set for atomic proposition \"" << p.first << "\" <=> " << *p.second << "..."); + + std::unique_ptr<CheckResult> subResultPointer = this->check(env, *p.second); + ExplicitQualitativeCheckResult const& subResult = subResultPointer->asExplicitQualitativeCheckResult(); + auto sat = subResult.getTruthValuesVector(); + + STORM_LOG_INFO(" Atomic proposition \"" << p.first << "\" is satisfied by " << sat.getNumberOfSetBits() << " states."); + + apSets[p.first] = std::move(sat); + } + + STORM_LOG_INFO("Resulting LTL path formula: " << *ltlFormula); + STORM_LOG_INFO(" in prefix format: " << ltlFormula->toPrefixString()); + + std::shared_ptr<storm::automata::DeterministicAutomaton> da = storm::automata::LTL2DeterministicAutomaton::ltl2da(*ltlFormula, false); + + STORM_LOG_INFO("Deterministic automaton for LTL formula has " + << da->getNumberOfStates() << " states, " + << da->getAPSet().size() << " atomic propositions and " + << *da->getAcceptance()->getAcceptanceExpression() << " as acceptance condition."); + + const SparseCtmcModelType& ctmc = this->getModel(); + typedef typename storm::models::sparse::Dtmc<typename SparseCtmcModelType::ValueType> SparseDtmcModelType; + + STORM_LOG_INFO("Computing embedded DTMC..."); + // compute probability matrix (embedded DTMC) + storm::storage::SparseMatrix<ValueType> probabilityMatrix = storm::modelchecker::helper::SparseCtmcCslHelper::computeProbabilityMatrix(ctmc.getTransitionMatrix(), ctmc.getExitRateVector()); + // copy of the state labelings of the CTMC + storm::models::sparse::StateLabeling labeling(ctmc.getStateLabeling()); + + // the embedded DTMC, used for building the product and computing the probabilities in the product + SparseDtmcModelType embeddedDtmc(std::move(probabilityMatrix), std::move(labeling)); + storm::solver::SolveGoal<ValueType> goal(embeddedDtmc, checkTask); + + + STORM_LOG_INFO("Performing DA product and probability computations in embedded DTMC..."); + std::vector<ValueType> numericResult = storm::modelchecker::helper::SparseDtmcPrctlHelper<ValueType>::computeDAProductProbabilities(env, embeddedDtmc, std::move(goal), *da, apSets, checkTask.isQualitativeSet()); + // we can directly return the numericResult vector as the state space of the CTMC and the embedded DTMC are exactly the same + 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 +150,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 +159,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 +169,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 +200,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 +226,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/helper/ltl/SparseLTLHelper.cpp b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp index 12b51dcf4..36a066da6 100644 --- a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp +++ b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp @@ -23,9 +23,8 @@ namespace storm { } - // todo only for MDP and change name! template <typename ValueType, bool Nondeterministic> - storm::storage::BitVector SparseLTLHelper<ValueType, Nondeterministic>::computeSurelyAcceptingPmaxStates(automata::AcceptanceCondition const& acceptance, storm::storage::SparseMatrix<ValueType> const& transitionMatrix, storm::storage::SparseMatrix<ValueType> const& backwardTransitions) { + storm::storage::BitVector SparseLTLHelper<ValueType, Nondeterministic>::computeAcceptingECs(automata::AcceptanceCondition const& acceptance, storm::storage::SparseMatrix<ValueType> const& transitionMatrix, storm::storage::SparseMatrix<ValueType> const& backwardTransitions) { 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)"); @@ -135,9 +134,8 @@ namespace storm { return acceptingStates; } - // todo only for dtmc and change name! template <typename ValueType, bool Nondeterministic> - storm::storage::BitVector SparseLTLHelper<ValueType, Nondeterministic>::computeAcceptingComponentStates(automata::AcceptanceCondition const& acceptance, storm::storage::SparseMatrix<ValueType> const& transitionMatrix) { + 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 = storm::storage::BitVector(product->getProductModel().getNumberOfStates()); storm::storage::BitVector acceptingStates(transitionMatrix.getRowGroupCount(), false); @@ -179,7 +177,6 @@ namespace storm { } - // todo change text STORM_LOG_INFO("Building "+ (Nondeterministic ? std::string("MDP-DA") : std::string("DTMC-DA")) +"product with deterministic automaton, starting from " << statesOfInterest.getNumberOfSetBits() << " model states..."); storm::transformer::DAProductBuilder productBuilder(da, apLabels); @@ -200,19 +197,15 @@ namespace storm { STORM_LOG_TRACE(str.str()); } - // DTMC: BCC - // MDP: computeSurelyAcceptingPmaxStates + // Compute accepting states storm::storage::BitVector acceptingStates; if (Nondeterministic) { - STORM_LOG_INFO("Computing accepting end components..."); - // todo compute accepting states, same as below - acceptingStates = computeSurelyAcceptingPmaxStates(*product->getAcceptance(), product->getProductModel().getTransitionMatrix(), product->getProductModel().getBackwardTransitions()); - + STORM_LOG_INFO("Computing MECs and checking for acceptance..."); + acceptingStates = computeAcceptingECs(*product->getAcceptance(), product->getProductModel().getTransitionMatrix(), product->getProductModel().getBackwardTransitions()); } else { STORM_LOG_INFO("Computing BSCCs and checking for acceptance..."); - // todo compute accepting states, (no btm) - acceptingStates = computeAcceptingComponentStates(*product->getAcceptance(), product->getProductModel().getTransitionMatrix()); + acceptingStates = computeAcceptingBCCs(*product->getAcceptance(), product->getProductModel().getTransitionMatrix()); } @@ -227,7 +220,7 @@ namespace storm { storm::storage::BitVector bvTrue(product->getProductModel().getNumberOfStates(), true); storm::storage::BitVector soiProduct(product->getStatesOfInterest()); - // Create goal for computeUntilProbabilities, compute maximizing probabilities for DA product with MDP + // 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)); @@ -263,6 +256,7 @@ namespace storm { return numericResult; } + template<typename ValueType, bool Nondeterministic> std::vector <ValueType> SparseLTLHelper<ValueType, Nondeterministic>::computeLTLProbabilities(Environment const &env, storm::logic::Formula const& formula, std::map<std::string, storm::storage::BitVector>& apSatSets) { std::shared_ptr<storm::logic::Formula const> ltlFormula; @@ -279,7 +273,7 @@ namespace storm { STORM_LOG_INFO("Resulting LTL path formula: " << ltlFormula->toString()); STORM_LOG_INFO(" in prefix format: " << ltlFormula->toPrefixString()); - std::shared_ptr<storm::automata::DeterministicAutomaton> da = storm::automata::LTL2DeterministicAutomaton::ltl2da(*ltlFormula); + std::shared_ptr<storm::automata::DeterministicAutomaton> da = storm::automata::LTL2DeterministicAutomaton::ltl2da(*ltlFormula, Nondeterministic); STORM_LOG_INFO("Deterministic automaton for LTL formula has " << da->getNumberOfStates() << " states, " @@ -287,7 +281,6 @@ namespace storm { << *da->getAcceptance()->getAcceptanceExpression() << " as acceptance condition."); - // compute Pmax for MDP std::vector<ValueType> numericResult = computeDAProductProbabilities(env, *da, apSatSets, this->isQualitativeSet()); if(Nondeterministic && this->getOptimizationDirection()==OptimizationDirection::Minimize) { @@ -297,7 +290,6 @@ namespace storm { } } - return numericResult; } diff --git a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h index b8944446c..29ab7a100 100644 --- a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h +++ b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h @@ -12,7 +12,7 @@ namespace storm { namespace helper { /*! - * Helper class for todo... + * Helper class for LTL model checking * @tparam ValueType the type a value can have * @tparam Nondeterministic true if there is nondeterminism in the Model (MDP) */ @@ -22,47 +22,59 @@ namespace storm { public: /*! - * The type of the product automaton model // todo + * The type of the product automaton (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 (i.e. DTMC, MDP) + * Initializes the helper for a discrete time model (i.e. DTMC, MDP) + * @param the transition matrix of the model + * @param the number of states of the model */ SparseLTLHelper(storm::storage::SparseMatrix<ValueType> const& transitionMatrix, std::size_t numberOfSates); /*! - * todo - * Computes maximizing(!) probabilties for DA product with MDP - * @return + * Computes the LTL probabilities + * @param the LTL formula + * @param 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, bool qualitative); - + std::vector<ValueType> computeLTLProbabilities(Environment const &env, storm::logic::Formula const& formula, std::map<std::string, storm::storage::BitVector>& apSatSets); /*! - * Computes the ltl probabilities ...todo + * Computes the (maximizing) probabilities for the constructed DA product + * @param the DA to build the product with + * @param the atomic propositions and satisfaction sets + * @param a flag indicating whether qualitative model checking is performed * @return a value for each state */ - std::vector<ValueType> computeLTLProbabilities(Environment const &env, storm::logic::Formula const& formula, std::map<std::string, storm::storage::BitVector>& apSatSets); //todo was brauchen wir hier aps und ..? + std::vector<ValueType> computeDAProductProbabilities(Environment const& env, storm::automata::DeterministicAutomaton const& da, std::map<std::string, storm::storage::BitVector>& apSatSets, bool qualitative); private: - /*! todo only relevant for MDP - enable_if_t ? - * Compute a set S of states that admit a probability 1 strategy of satisfying the given acceptance conditon. + /*! + * Compute 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 the acceptance condition (in DNF) + * @param the transition matrix of the model + * @param the reversed transition relation */ - static storm::storage::BitVector computeSurelyAcceptingPmaxStates(automata::AcceptanceCondition const& acceptance, storm::storage::SparseMatrix<ValueType> const& transitionMatrix, storm::storage::SparseMatrix<ValueType> const& backwardTransitions); - - //todo only for dtmc, different to mdp: no backward tm - static storm::storage::BitVector computeAcceptingComponentStates(automata::AcceptanceCondition const& acceptance, storm::storage::SparseMatrix<ValueType> const& transitionMatrix); + static storm::storage::BitVector computeAcceptingECs(automata::AcceptanceCondition const& acceptance, storm::storage::SparseMatrix<ValueType> const& transitionMatrix, storm::storage::SparseMatrix<ValueType> const& backwardTransitions); + + /** + * Compute a set S of states that are contained in BSCCs that satisfy the given acceptance conditon. + * @tparam the acceptance condition + * @tparam the transition matrix of the model + */ + static storm::storage::BitVector computeAcceptingBCCs(automata::AcceptanceCondition const& acceptance, storm::storage::SparseMatrix<ValueType> const& transitionMatrix); storm::storage::SparseMatrix<ValueType> const& _transitionMatrix; diff --git a/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.cpp b/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.cpp index 28009225c..95e87164f 100644 --- a/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.cpp +++ b/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.cpp @@ -176,7 +176,6 @@ namespace storm { const SparseDtmcModelType& dtmc = this->getModel(); - // TODO if (storm::settings::getModule<storm::settings::modules::DebugSettings>().isTraceSet()) { STORM_LOG_TRACE("Writing model to model.dot"); std::ofstream modelDot("model.dot"); From e838ac13defde24902dbb76d162532502ad02569 Mon Sep 17 00:00:00 2001 From: hannah <hannah.mertens@rwth-aachen.de> Date: Wed, 26 May 2021 15:18:16 +0200 Subject: [PATCH 066/172] updated ltl tests --- .../prctl/dtmc/DtmcPrctlModelCheckerTest.cpp | 8 ++++++++ .../prctl/mdp/MdpPrctlModelCheckerTest.cpp | 11 +++++++++-- 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/src/test/storm/modelchecker/prctl/dtmc/DtmcPrctlModelCheckerTest.cpp b/src/test/storm/modelchecker/prctl/dtmc/DtmcPrctlModelCheckerTest.cpp index 8664fce18..d45519900 100755 --- a/src/test/storm/modelchecker/prctl/dtmc/DtmcPrctlModelCheckerTest.cpp +++ b/src/test/storm/modelchecker/prctl/dtmc/DtmcPrctlModelCheckerTest.cpp @@ -718,6 +718,7 @@ namespace { } 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))]"; @@ -760,9 +761,13 @@ namespace { } 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]"; @@ -798,6 +803,9 @@ namespace { } else { EXPECT_FALSE(checker->canHandle(tasks[0])); } +#else + GTEST_SKIP(); +#endif } } diff --git a/src/test/storm/modelchecker/prctl/mdp/MdpPrctlModelCheckerTest.cpp b/src/test/storm/modelchecker/prctl/mdp/MdpPrctlModelCheckerTest.cpp index 1f8018abb..9e2c1c2a7 100755 --- a/src/test/storm/modelchecker/prctl/mdp/MdpPrctlModelCheckerTest.cpp +++ b/src/test/storm/modelchecker/prctl/mdp/MdpPrctlModelCheckerTest.cpp @@ -700,6 +700,8 @@ namespace { #ifdef STORM_HAVE_LTL_MODELCHECKING_SUPPORT std::string formulasString = "Pmin=? [!(GF \"all_coins_equal_1\")]"; formulasString += "; Pmax=? [F \"all_coins_equal_1\" U \"finished\"]"; + // The following example results in an automaton with acceptance condition not in DNF (using spot) + formulasString += "; Pmax=?[ (GF !\"all_coins_equal_1\") & ((GF \"all_coins_equal_1\") | (FG \"finished\"))]"; auto modelFormulas = this->buildModelFormulas(STORM_TEST_RESOURCES_DIR "/mdp/coin2-2.nm", formulasString); auto model = std::move(modelFormulas.first); @@ -718,13 +720,18 @@ namespace { 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_NEAR(this->parseNumber("79/128"), this->getQuantitativeResultAtInitialState(model, result), this->precision()); + + } else { EXPECT_FALSE(checker->canHandle(tasks[0])); } - } #else - GTEST_SKIP(); + GTEST_SKIP(); #endif + } + } From ca4ac3a16676edbdd94fa2bfec7cd4778a0e7f6f Mon Sep 17 00:00:00 2001 From: hannah <hannah.mertens@rwth-aachen.de> Date: Sun, 6 Jun 2021 21:01:58 +0200 Subject: [PATCH 067/172] transform into generalized Rabin instead of DNF --- src/storm/automata/LTL2DeterministicAutomaton.cpp | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/src/storm/automata/LTL2DeterministicAutomaton.cpp b/src/storm/automata/LTL2DeterministicAutomaton.cpp index 06ceb5f03..2d30710bd 100644 --- a/src/storm/automata/LTL2DeterministicAutomaton.cpp +++ b/src/storm/automata/LTL2DeterministicAutomaton.cpp @@ -34,17 +34,21 @@ namespace storm { // Request a deterministic, complete automaton with state-based acceptance spot::translator trans = spot::translator(); - trans.set_type(spot::postprocessor::Generic); + trans.set_type(spot::postprocessor::Generic); //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); // TODO necessary for MDP LTL-MC if(!(aut->get_acceptance().is_dnf()) && dnf){ - STORM_LOG_INFO("Convert acceptance condition into DNF..."); - aut->set_acceptance(aut->get_acceptance().to_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(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"); From 3f030e23f0bc4eca936f7e7b4893846fc4f5b7d6 Mon Sep 17 00:00:00 2001 From: hannah <hannah.mertens@rwth-aachen.de> Date: Wed, 9 Jun 2021 23:14:24 +0200 Subject: [PATCH 068/172] allow external ltl2da tools --- .../automata/LTL2DeterministicAutomaton.cpp | 68 +++++++++++++++++-- .../automata/LTL2DeterministicAutomaton.h | 8 ++- 2 files changed, 70 insertions(+), 6 deletions(-) diff --git a/src/storm/automata/LTL2DeterministicAutomaton.cpp b/src/storm/automata/LTL2DeterministicAutomaton.cpp index 2d30710bd..0f07e2a4e 100644 --- a/src/storm/automata/LTL2DeterministicAutomaton.cpp +++ b/src/storm/automata/LTL2DeterministicAutomaton.cpp @@ -5,6 +5,9 @@ #include "storm/utility/macros.h" #include "storm/exceptions/ExpressionEvaluationException.h" #include "storm/exceptions/WrongFormatException.h" +#include "storm/exceptions/FileIoException.h" + +#include <sys/wait.h> #ifdef STORM_HAVE_SPOT #include "spot/tl/formula.hh" @@ -19,10 +22,13 @@ namespace storm { namespace automata { - std::shared_ptr<DeterministicAutomaton> LTL2DeterministicAutomaton::ltl2da(storm::logic::Formula const& f, bool dnf) { + bool LTL2DeterministicAutomaton::isExternalDaToolSet() { + return std::getenv("LTL2DA"); + } + + std::shared_ptr<DeterministicAutomaton> LTL2DeterministicAutomaton::ltl2daInternalTool(std::string const& prefixLtl, 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; @@ -34,12 +40,11 @@ namespace storm { // Request a deterministic, complete automaton with state-based acceptance spot::translator trans = spot::translator(); - trans.set_type(spot::postprocessor::Generic); //Generic + 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); - // TODO necessary for MDP LTL-MC 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 @@ -61,5 +66,60 @@ namespace storm { STORM_LOG_THROW(false, storm::exceptions::NotSupportedException, "Storm is compiled without Spot support."); #endif } + + // TODO: this is quite hacky, improve robustness + std::shared_ptr<DeterministicAutomaton> LTL2DeterministicAutomaton::ltl2daExternalTool(std::string const& prefixLtl) { + + + std::string ltl2da_tool = std::getenv("LTL2DA"); + + STORM_LOG_INFO("Calling external LTL->DA tool: " << ltl2da_tool << " '" << 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(ltl2da_tool.c_str(), ltl2da_tool.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); + + // TODO for MDP-MC the acceptance condition must be in DNF, otherwise Exception is thrown during computation if accepting ECs + STORM_LOG_INFO("Reading automaton for " << prefixLtl << " from da.hoa"); + + return DeterministicAutomaton::parseFromFile("da.hoa"); + } + } + + std::shared_ptr<DeterministicAutomaton> LTL2DeterministicAutomaton::ltl2da(storm::logic::Formula const& f, bool dnf) { + std::string prefixLtl = f.toPrefixString(); + + storm::automata::DeterministicAutomaton::ptr da; + if(isExternalDaToolSet()){ + da = ltl2daExternalTool(prefixLtl); + } else { + da = ltl2daInternalTool(prefixLtl, dnf); + } + return da; + } + } } diff --git a/src/storm/automata/LTL2DeterministicAutomaton.h b/src/storm/automata/LTL2DeterministicAutomaton.h index 32be1ca32..1471922d3 100644 --- a/src/storm/automata/LTL2DeterministicAutomaton.h +++ b/src/storm/automata/LTL2DeterministicAutomaton.h @@ -10,14 +10,18 @@ namespace storm { } namespace automata { - // fwd class DeterministicAutomaton; - class LTL2DeterministicAutomaton { public: static std::shared_ptr<DeterministicAutomaton> ltl2da(storm::logic::Formula const&, bool dnf); + + private: + static bool isExternalDaToolSet(); + + static std::shared_ptr<DeterministicAutomaton> ltl2daInternalTool(std::string const& prefixLtl, bool dnf); + static std::shared_ptr<DeterministicAutomaton> ltl2daExternalTool(std::string const& prefixLtl); }; } From b06151b913c0b6497a59e164f0f7b829165b9ebd Mon Sep 17 00:00:00 2001 From: hannah <hannah.mertens@rwth-aachen.de> Date: Wed, 9 Jun 2021 23:23:13 +0200 Subject: [PATCH 069/172] ctmc-ltl tests --- .../csl/CtmcCslModelCheckerTest.cpp | 77 +++++++++++++++++++ 1 file changed, 77 insertions(+) diff --git a/src/test/storm/modelchecker/csl/CtmcCslModelCheckerTest.cpp b/src/test/storm/modelchecker/csl/CtmcCslModelCheckerTest.cpp index 83414e72f..b57fd3754 100755 --- a/src/test/storm/modelchecker/csl/CtmcCslModelCheckerTest.cpp +++ b/src/test/storm/modelchecker/csl/CtmcCslModelCheckerTest.cpp @@ -446,4 +446,81 @@ 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\") ]"; + + 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; + + //TODO values + if (TypeParam::engine == CtmcEngine::PrismSparse || TypeParam::engine == CtmcEngine::JaniSparse || TypeParam::engine == CtmcEngine::JitSparse) { + result = checker->check(this->env(), tasks[0]); + EXPECT_NEAR(this->parseNumber("0.9345877711"),this->getQuantitativeResultAtInitialState(model, result), this->precision()); + + result = checker->check(this->env(), tasks[1]); + EXPECT_NEAR(this->parseNumber("0.8781042341"),this->getQuantitativeResultAtInitialState(model, result), this->precision()); + + result = checker->check(this->env(), tasks[2]); + EXPECT_NEAR(this->parseNumber("0.9345877711"),this->getQuantitativeResultAtInitialState(model, result), this->precision()); + } +#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) ]"; //TODO more test ctmc + + 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(21ul, 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()); + } +#else + GTEST_SKIP(); +#endif + + } + + TYPED_TEST(CtmcCslModelCheckerTest, LTLProbabilitiesTandem) { + //TODO LTL tests + std::string formulasString = "P=? [\"first_queue_full\"]"; + + auto modelFormulas = this->buildModelFormulas(STORM_TEST_RESOURCES_DIR "/ctmc/tandem5.sm", formulasString); + auto model = std::move(modelFormulas.first); + auto tasks = this->getTasks(modelFormulas.second); + EXPECT_EQ(66ul, model->getNumberOfStates()); + EXPECT_EQ(189ul, 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("0.20079750055570736"),this->getQuantitativeResultAtInitialState(model, result), this->precision()); + } + + } } From a038d9658eb6db9c59e2479b25dd89051ed7d02a Mon Sep 17 00:00:00 2001 From: hannah <hannah.mertens@rwth-aachen.de> Date: Sun, 13 Jun 2021 18:39:00 +0200 Subject: [PATCH 070/172] added TODOs --- src/storm/automata/LTL2DeterministicAutomaton.cpp | 3 ++- .../modelchecker/prctl/SparseDtmcPrctlModelChecker.cpp | 7 +++---- src/storm/transformer/DAProductBuilder.h | 2 +- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/storm/automata/LTL2DeterministicAutomaton.cpp b/src/storm/automata/LTL2DeterministicAutomaton.cpp index 0f07e2a4e..d780bf979 100644 --- a/src/storm/automata/LTL2DeterministicAutomaton.cpp +++ b/src/storm/automata/LTL2DeterministicAutomaton.cpp @@ -102,7 +102,8 @@ namespace storm { } STORM_LOG_THROW(rv == 0, storm::exceptions::FileIoException, "Could not construct deterministic automaton for " << prefixLtl << ", return code = " << rv); - // TODO for MDP-MC the acceptance condition must be in DNF, otherwise Exception is thrown during computation if accepting ECs + // TODO transition-based acceptance is required, + // and for MDP-MC the acceptance condition must be in DNF, otherwise an exception is thrown during computation if accepting ECs STORM_LOG_INFO("Reading automaton for " << prefixLtl << " from da.hoa"); return DeterministicAutomaton::parseFromFile("da.hoa"); diff --git a/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.cpp b/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.cpp index 95e87164f..fedbb5895 100644 --- a/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.cpp +++ b/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.cpp @@ -22,8 +22,6 @@ #include "storm/logic/ExtractMaximalStateFormulasVisitor.h" #include "storm/automata/AcceptanceCondition.h" -#include "storm/automata/DeterministicAutomaton.h" -#include "storm/automata/LTL2DeterministicAutomaton.h" #include "storm/models/sparse/StandardRewardModel.h" @@ -160,7 +158,7 @@ namespace storm { std::shared_ptr<storm::logic::Formula> ltlFormula = storm::logic::ExtractMaximalStateFormulasVisitor::extract(pathFormula, extracted); STORM_LOG_INFO("Extracting maximal state formulas and computing satisfaction sets for path formula: " << pathFormula); - + // TODO simplify APs std::map<std::string, storm::storage::BitVector> apSets; for (auto& p : extracted) { STORM_LOG_INFO(" Computing satisfaction set for atomic proposition \"" << p.first << "\" <=> " << *p.second << "..."); @@ -176,10 +174,11 @@ namespace storm { const SparseDtmcModelType& dtmc = this->getModel(); + // TODO ? if (storm::settings::getModule<storm::settings::modules::DebugSettings>().isTraceSet()) { STORM_LOG_TRACE("Writing model to model.dot"); std::ofstream modelDot("model.dot"); - this->getModel().writeDotToStream(modelDot); + dtmc.writeDotToStream(modelDot); modelDot.close(); } diff --git a/src/storm/transformer/DAProductBuilder.h b/src/storm/transformer/DAProductBuilder.h index d90d4b6dc..a6a53f9bd 100644 --- a/src/storm/transformer/DAProductBuilder.h +++ b/src/storm/transformer/DAProductBuilder.h @@ -22,7 +22,7 @@ namespace storm { } template <typename Model> - typename DAProduct<Model>::ptr build(const storm::storage::SparseMatrix<typename Model::ValueType>& originalMatrix, const storm::storage::BitVector& statesOfInterest) const { //todo transition matrix + 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(), From 7f95f1fdbf654e8860f9f6d8e8b7db033efab3b2 Mon Sep 17 00:00:00 2001 From: hannah <hannah.mertens@rwth-aachen.de> Date: Sun, 13 Jun 2021 18:40:31 +0200 Subject: [PATCH 071/172] ctmc and mdp tests --- .../csl/CtmcCslModelCheckerTest.cpp | 66 ++++++++++--------- .../prctl/mdp/MdpPrctlModelCheckerTest.cpp | 60 ++++++++++++++++- 2 files changed, 91 insertions(+), 35 deletions(-) diff --git a/src/test/storm/modelchecker/csl/CtmcCslModelCheckerTest.cpp b/src/test/storm/modelchecker/csl/CtmcCslModelCheckerTest.cpp index b57fd3754..f87fcae0c 100755 --- a/src/test/storm/modelchecker/csl/CtmcCslModelCheckerTest.cpp +++ b/src/test/storm/modelchecker/csl/CtmcCslModelCheckerTest.cpp @@ -448,11 +448,14 @@ namespace { } - TYPED_TEST(CtmcCslModelCheckerTest, LTLProbabilitiesEmbedded) { + 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\") ]"; + 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); @@ -460,19 +463,31 @@ namespace { 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; - - //TODO values if (TypeParam::engine == CtmcEngine::PrismSparse || TypeParam::engine == CtmcEngine::JaniSparse || TypeParam::engine == CtmcEngine::JitSparse) { result = checker->check(this->env(), tasks[0]); - EXPECT_NEAR(this->parseNumber("0.9345877711"),this->getQuantitativeResultAtInitialState(model, result), this->precision()); + + EXPECT_NEAR(this->parseNumber("0.93458777106264368"),this->getQuantitativeResultAtInitialState(model, result), this->precision()); result = checker->check(this->env(), tasks[1]); - EXPECT_NEAR(this->parseNumber("0.8781042341"),this->getQuantitativeResultAtInitialState(model, result), this->precision()); + EXPECT_NEAR(this->parseNumber("0.878104234117144888"),this->getQuantitativeResultAtInitialState(model, result), this->precision()); result = checker->check(this->env(), tasks[2]); - EXPECT_NEAR(this->parseNumber("0.9345877711"),this->getQuantitativeResultAtInitialState(model, result), this->precision()); + EXPECT_NEAR(this->parseNumber("0.934587771062649453"),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("0.999979077232484914"),this->getQuantitativeResultAtInitialState(model, result), this->precision()); + + } else { + EXPECT_FALSE(checker->canHandle(tasks[0])); } #else GTEST_SKIP(); @@ -480,47 +495,34 @@ namespace { } - - TYPED_TEST(CtmcCslModelCheckerTest, LTLProbabilitiesPolling) { + 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) ]"; //TODO more test ctmc + 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(21ul, model->getNumberOfTransitions()); + 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()); + EXPECT_NEAR(this->parseNumber("0.49999689056660507"),this->getQuantitativeResultAtInitialState(model, result), this->precision()); + + result = checker->check(this->env(), tasks[1]); + EXPECT_NEAR(this->parseNumber("0.0074564831701838807"),this->getQuantitativeResultAtInitialState(model, result), this->precision()); + + } else { + EXPECT_FALSE(checker->canHandle(tasks[0])); } #else GTEST_SKIP(); #endif } - - TYPED_TEST(CtmcCslModelCheckerTest, LTLProbabilitiesTandem) { - //TODO LTL tests - std::string formulasString = "P=? [\"first_queue_full\"]"; - - auto modelFormulas = this->buildModelFormulas(STORM_TEST_RESOURCES_DIR "/ctmc/tandem5.sm", formulasString); - auto model = std::move(modelFormulas.first); - auto tasks = this->getTasks(modelFormulas.second); - EXPECT_EQ(66ul, model->getNumberOfStates()); - EXPECT_EQ(189ul, 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("0.20079750055570736"),this->getQuantitativeResultAtInitialState(model, result), this->precision()); - } - - } } diff --git a/src/test/storm/modelchecker/prctl/mdp/MdpPrctlModelCheckerTest.cpp b/src/test/storm/modelchecker/prctl/mdp/MdpPrctlModelCheckerTest.cpp index 9e2c1c2a7..b49432538 100755 --- a/src/test/storm/modelchecker/prctl/mdp/MdpPrctlModelCheckerTest.cpp +++ b/src/test/storm/modelchecker/prctl/mdp/MdpPrctlModelCheckerTest.cpp @@ -700,8 +700,10 @@ namespace { #ifdef STORM_HAVE_LTL_MODELCHECKING_SUPPORT std::string formulasString = "Pmin=? [!(GF \"all_coins_equal_1\")]"; formulasString += "; Pmax=? [F \"all_coins_equal_1\" U \"finished\"]"; - // The following example results in an automaton with acceptance condition not in DNF (using spot) - formulasString += "; Pmax=?[ (GF !\"all_coins_equal_1\") & ((GF \"all_coins_equal_1\") | (FG \"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); @@ -721,7 +723,13 @@ namespace { EXPECT_NEAR(this->parseNumber("5/9"), this->getQuantitativeResultAtInitialState(model, result), this->precision()); result = checker->check(this->env(), tasks[2]); - EXPECT_NEAR(this->parseNumber("79/128"), this->getQuantitativeResultAtInitialState(model, result), this->precision()); + 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 { @@ -732,6 +740,52 @@ namespace { #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("1/12"), this->getQuantitativeResultAtInitialState(model, result), this->precision()); + + } else { + EXPECT_FALSE(checker->canHandle(tasks[0])); + } + +#else + GTEST_SKIP(); +#endif + + } } From 78058b515297fb46e67732150f694523ffde466b Mon Sep 17 00:00:00 2001 From: hannah <hannah.mertens@rwth-aachen.de> Date: Sun, 13 Jun 2021 18:47:33 +0200 Subject: [PATCH 072/172] ltl-mc with ctmcs Conflicts: src/storm/modelchecker/csl/SparseCtmcCslModelChecker.cpp --- .../csl/SparseCtmcCslModelChecker.cpp | 33 +++++++++++-------- 1 file changed, 20 insertions(+), 13 deletions(-) diff --git a/src/storm/modelchecker/csl/SparseCtmcCslModelChecker.cpp b/src/storm/modelchecker/csl/SparseCtmcCslModelChecker.cpp index 5b296a5a2..4d3dab7ec 100644 --- a/src/storm/modelchecker/csl/SparseCtmcCslModelChecker.cpp +++ b/src/storm/modelchecker/csl/SparseCtmcCslModelChecker.cpp @@ -16,7 +16,10 @@ #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/logic/ExtractMaximalStateFormulasVisitor.h" #include "storm/adapters/RationalFunctionAdapter.h" @@ -24,6 +27,10 @@ #include "storm/exceptions/InvalidPropertyException.h" #include "storm/exceptions/NotImplementedException.h" +#include "storm/settings/SettingsManager.h" +#include "storm/settings/modules/GeneralSettings.h" +#include "storm/settings/modules/DebugSettings.h" + namespace storm { namespace modelchecker { template <typename SparseCtmcModelType> @@ -99,7 +106,7 @@ namespace storm { STORM_LOG_INFO("Extracting maximal state formulas and computing satisfaction sets for path formula: " << pathFormula); std::map<std::string, storm::storage::BitVector> apSets; - + // TODO simplify APs for (auto& p : extracted) { STORM_LOG_INFO(" Computing satisfaction set for atomic proposition \"" << p.first << "\" <=> " << *p.second << "..."); @@ -112,16 +119,6 @@ namespace storm { apSets[p.first] = std::move(sat); } - STORM_LOG_INFO("Resulting LTL path formula: " << *ltlFormula); - STORM_LOG_INFO(" in prefix format: " << ltlFormula->toPrefixString()); - - std::shared_ptr<storm::automata::DeterministicAutomaton> da = storm::automata::LTL2DeterministicAutomaton::ltl2da(*ltlFormula, false); - - STORM_LOG_INFO("Deterministic automaton for LTL formula has " - << da->getNumberOfStates() << " states, " - << da->getAPSet().size() << " atomic propositions and " - << *da->getAcceptance()->getAcceptanceExpression() << " as acceptance condition."); - const SparseCtmcModelType& ctmc = this->getModel(); typedef typename storm::models::sparse::Dtmc<typename SparseCtmcModelType::ValueType> SparseDtmcModelType; @@ -135,9 +132,19 @@ namespace storm { SparseDtmcModelType embeddedDtmc(std::move(probabilityMatrix), std::move(labeling)); storm::solver::SolveGoal<ValueType> goal(embeddedDtmc, checkTask); + STORM_LOG_INFO("Performing ltl probability computations in embedded DTMC..."); + + if (storm::settings::getModule<storm::settings::modules::DebugSettings>().isTraceSet()) { + STORM_LOG_TRACE("Writing model to model.dot"); + std::ofstream modelDot("model.dot"); + embeddedDtmc.writeDotToStream(modelDot); + modelDot.close(); + } + + storm::modelchecker::helper::SparseLTLHelper<ValueType, false> helper(embeddedDtmc.getTransitionMatrix(), this->getModel().getNumberOfStates()); + storm::modelchecker::helper::setInformationFromCheckTaskDeterministic(helper, checkTask, embeddedDtmc); + std::vector<ValueType> numericResult = helper.computeLTLProbabilities(env, *ltlFormula, apSets); - STORM_LOG_INFO("Performing DA product and probability computations in embedded DTMC..."); - std::vector<ValueType> numericResult = storm::modelchecker::helper::SparseDtmcPrctlHelper<ValueType>::computeDAProductProbabilities(env, embeddedDtmc, std::move(goal), *da, apSets, checkTask.isQualitativeSet()); // we can directly return the numericResult vector as the state space of the CTMC and the embedded DTMC are exactly the same return std::unique_ptr<CheckResult>(new ExplicitQuantitativeCheckResult<ValueType>(std::move(numericResult))); } From 8ba4f17a92484fe566188272d0ca24f98ce06312 Mon Sep 17 00:00:00 2001 From: hannah <hannah.mertens@rwth-aachen.de> Date: Sun, 13 Jun 2021 18:53:46 +0200 Subject: [PATCH 073/172] ltl-mc with MAs --- .../SparseMarkovAutomatonCslModelChecker.cpp | 69 ++++++++++++++++++- .../SparseMarkovAutomatonCslModelChecker.h | 1 + 2 files changed, 68 insertions(+), 2 deletions(-) diff --git a/src/storm/modelchecker/csl/SparseMarkovAutomatonCslModelChecker.cpp b/src/storm/modelchecker/csl/SparseMarkovAutomatonCslModelChecker.cpp index e0844fbb8..cb8bf55ee 100644 --- a/src/storm/modelchecker/csl/SparseMarkovAutomatonCslModelChecker.cpp +++ b/src/storm/modelchecker/csl/SparseMarkovAutomatonCslModelChecker.cpp @@ -1,8 +1,9 @@ #include "storm/modelchecker/csl/SparseMarkovAutomatonCslModelChecker.h" - #include "storm/modelchecker/csl/helper/SparseMarkovAutomatonCslHelper.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" @@ -13,16 +14,23 @@ #include "storm/settings/SettingsManager.h" #include "storm/settings/modules/GeneralSettings.h" +#include "storm/settings/modules/DebugSettings.h" + #include "storm/solver/SolveGoal.h" +#include "storm/transformer/ContinuousToDiscreteTimeModelTransformer.h" + #include "storm/modelchecker/results/ExplicitQualitativeCheckResult.h" #include "storm/modelchecker/results/ExplicitQuantitativeCheckResult.h" #include "storm/logic/FragmentSpecification.h" +#include "storm/logic/ExtractMaximalStateFormulasVisitor.h" #include "storm/exceptions/InvalidPropertyException.h" #include "storm/exceptions/NotImplementedException.h" +#include "storm/api/storm.h" + namespace storm { namespace modelchecker { template<typename SparseMarkovAutomatonModelType> @@ -32,7 +40,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::csl().setGloballyFormulasAllowed(false).setNextFormulasAllowed(false).setRewardOperatorsAllowed(true).setReachabilityRewardFormulasAllowed(true).setTotalRewardFormulasAllowed(true).setTimeAllowed(true).setLongRunAverageProbabilitiesAllowed(true).setLongRunAverageRewardFormulasAllowed(true).setRewardAccumulationAllowed(true).setInstantaneousFormulasAllowed(false).setNestedPathFormulasAllowed(true); //TODO (hannah) correct? auto multiObjectiveFragment = storm::logic::multiObjective().setTimeAllowed(true).setTimeBoundedUntilFormulasAllowed(true).setRewardAccumulationAllowed(true); if (!storm::NumberTraits<ValueType>::SupportsExponential) { singleObjectiveFragment.setBoundedUntilFormulasAllowed(false).setCumulativeRewardFormulasAllowed(false); @@ -102,6 +110,63 @@ namespace storm { } 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(); + + std::vector<storm::logic::ExtractMaximalStateFormulasVisitor::LabelFormulaPair> extracted; + std::shared_ptr<storm::logic::Formula> ltlFormula = storm::logic::ExtractMaximalStateFormulasVisitor::extract(pathFormula, extracted); + + STORM_LOG_INFO("Extracting maximal state formulas and computing satisfaction sets for path formula: " << pathFormula); + + std::map<std::string, storm::storage::BitVector> apSets; + + // TODO simplify APs + for (auto& p : extracted) { + STORM_LOG_INFO(" Computing satisfaction set for atomic proposition \"" << p.first << "\" <=> " << *p.second << "..."); + + std::unique_ptr<CheckResult> subResultPointer = this->check(env, *p.second); + ExplicitQualitativeCheckResult const& subResult = subResultPointer->asExplicitQualitativeCheckResult(); + auto sat = subResult.getTruthValuesVector(); + + STORM_LOG_INFO(" Atomic proposition \"" << p.first << "\" is satisfied by " << sat.getNumberOfSetBits() << " states."); + + apSets[p.first] = std::move(sat); + } + + const SparseMarkovAutomatonModelType& ma = this->getModel(); + typedef typename storm::models::sparse::Mdp<typename SparseMarkovAutomatonModelType::ValueType> SparseMdpModelType; + + // TODO correct? + STORM_LOG_INFO("Computing embedded MDP..."); + storm::storage::SparseMatrix<ValueType> probabilityMatrix = ma.getTransitionMatrix(); + // Copy of the state labelings of the MDP + storm::models::sparse::StateLabeling labeling(ma.getStateLabeling()); + // The embedded MDP, used for building the product and computing the probabilities in the product + SparseMdpModelType embeddedMdp(std::move(probabilityMatrix), std::move(labeling)); + + storm::solver::SolveGoal<ValueType> goal(embeddedMdp, checkTask); + + STORM_LOG_INFO("Performing ltl probability computations in embedded MDP..."); + + // TODO ? + if (storm::settings::getModule<storm::settings::modules::DebugSettings>().isTraceSet()) { + STORM_LOG_TRACE("Writing model to model.dot"); + std::ofstream modelDot("model.dot"); + embeddedMdp.writeDotToStream(modelDot); + modelDot.close(); + } + + storm::modelchecker::helper::SparseLTLHelper<ValueType, true> helper(embeddedMdp.getTransitionMatrix(), this->getModel().getNumberOfStates()); + storm::modelchecker::helper::setInformationFromCheckTaskNondeterministic(helper, checkTask, embeddedMdp); + std::vector<ValueType> numericResult = helper.computeLTLProbabilities(env, *ltlFormula, apSets); + + // We can directly return the numericResult vector as the state space of the CTMC and the embedded MDP are exactly the same + return std::unique_ptr<CheckResult>(new ExplicitQuantitativeCheckResult<ValueType>(std::move(numericResult))); + } + template<typename SparseMarkovAutomatonModelType> std::unique_ptr<CheckResult> SparseMarkovAutomatonCslModelChecker<SparseMarkovAutomatonModelType>::computeReachabilityRewards(Environment const& env, storm::logic::RewardMeasureType, CheckTask<storm::logic::EventuallyFormula, ValueType> const& checkTask) { diff --git a/src/storm/modelchecker/csl/SparseMarkovAutomatonCslModelChecker.h b/src/storm/modelchecker/csl/SparseMarkovAutomatonCslModelChecker.h index f18f4a374..360739171 100644 --- a/src/storm/modelchecker/csl/SparseMarkovAutomatonCslModelChecker.h +++ b/src/storm/modelchecker/csl/SparseMarkovAutomatonCslModelChecker.h @@ -29,6 +29,7 @@ namespace storm { 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> 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> 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; From b75c16297f91efe77d96f6a6fcc054c4931f7084 Mon Sep 17 00:00:00 2001 From: hannah <hannah.mertens@rwth-aachen.de> Date: Tue, 15 Jun 2021 10:39:49 +0200 Subject: [PATCH 074/172] fixed some typos --- .../modelchecker/helper/ltl/SparseLTLHelper.cpp | 13 +++++++------ src/storm/modelchecker/helper/ltl/SparseLTLHelper.h | 2 +- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp index 36a066da6..080e6bc0a 100644 --- a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp +++ b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp @@ -156,7 +156,7 @@ namespace storm { } 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, bool qualitative) { + 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> apLabels; @@ -210,12 +210,12 @@ namespace storm { } if (acceptingStates.empty()) { - STORM_LOG_INFO("No acceptingStates states, skipping probability computation."); + STORM_LOG_INFO("No accepting states, skipping probability computation."); std::vector<ValueType> numericResult(this->_numberOfStates, storm::utility::zero<ValueType>()); return numericResult; } - STORM_LOG_INFO("Computing probabilities for reaching acceptingStates components..."); + STORM_LOG_INFO("Computing probabilities for reaching accepting components..."); storm::storage::BitVector bvTrue(product->getProductModel().getNumberOfStates(), true); storm::storage::BitVector soiProduct(product->getStatesOfInterest()); @@ -231,6 +231,7 @@ namespace storm { std::vector<ValueType> prodNumericResult; + if (Nondeterministic) { prodNumericResult = std::move(storm::modelchecker::helper::SparseMdpPrctlHelper<ValueType>::computeUntilProbabilities(env, std::move(solveGoalProduct), @@ -238,7 +239,7 @@ namespace storm { product->getProductModel().getBackwardTransitions(), bvTrue, acceptingStates, - qualitative, + this->isQualitativeSet(), false // no schedulers (at the moment) ).values); @@ -249,7 +250,7 @@ namespace storm { product->getProductModel().getBackwardTransitions(), bvTrue, acceptingStates, - qualitative); + this->isQualitativeSet()); } std::vector<ValueType> numericResult = product->projectToOriginalModel(this->_numberOfStates, prodNumericResult); @@ -281,7 +282,7 @@ namespace storm { << *da->getAcceptance()->getAcceptanceExpression() << " as acceptance condition."); - std::vector<ValueType> numericResult = computeDAProductProbabilities(env, *da, apSatSets, this->isQualitativeSet()); + std::vector<ValueType> numericResult = computeDAProductProbabilities(env, *da, apSatSets); if(Nondeterministic && this->getOptimizationDirection()==OptimizationDirection::Minimize) { // compute 1-Pmax[!fomula] diff --git a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h index 29ab7a100..7774daf01 100644 --- a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h +++ b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h @@ -50,7 +50,7 @@ namespace storm { * @param a flag indicating whether qualitative model checking is performed * @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, bool qualitative); + std::vector<ValueType> computeDAProductProbabilities(Environment const& env, storm::automata::DeterministicAutomaton const& da, std::map<std::string, storm::storage::BitVector>& apSatSets); private: From 1332e39b8cf693b78ad8f99f71209a78101451b7 Mon Sep 17 00:00:00 2001 From: hannah <hannah.mertens@rwth-aachen.de> Date: Tue, 15 Jun 2021 21:44:52 +0200 Subject: [PATCH 075/172] updated canHandle Conflicts: src/storm/modelchecker/csl/SparseCtmcCslModelChecker.cpp --- src/storm/modelchecker/csl/SparseCtmcCslModelChecker.cpp | 2 +- .../modelchecker/csl/SparseMarkovAutomatonCslModelChecker.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/storm/modelchecker/csl/SparseCtmcCslModelChecker.cpp b/src/storm/modelchecker/csl/SparseCtmcCslModelChecker.cpp index 4d3dab7ec..b36663dc9 100644 --- a/src/storm/modelchecker/csl/SparseCtmcCslModelChecker.cpp +++ b/src/storm/modelchecker/csl/SparseCtmcCslModelChecker.cpp @@ -40,7 +40,7 @@ namespace storm { 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().setGloballyFormulasAllowed(true).setLongRunAverageRewardFormulasAllowed(true).setLongRunAverageProbabilitiesAllowed(true).setTimeAllowed(true).setTimeOperatorsAllowed(true).setTotalRewardFormulasAllowed(true).setRewardAccumulationAllowed(true); if (!storm::NumberTraits<ValueType>::SupportsExponential) { fragment.setBoundedUntilFormulasAllowed(false).setCumulativeRewardFormulasAllowed(false).setInstantaneousFormulasAllowed(false); } diff --git a/src/storm/modelchecker/csl/SparseMarkovAutomatonCslModelChecker.cpp b/src/storm/modelchecker/csl/SparseMarkovAutomatonCslModelChecker.cpp index cb8bf55ee..1a9c9fe55 100644 --- a/src/storm/modelchecker/csl/SparseMarkovAutomatonCslModelChecker.cpp +++ b/src/storm/modelchecker/csl/SparseMarkovAutomatonCslModelChecker.cpp @@ -40,7 +40,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).setNestedPathFormulasAllowed(true); //TODO (hannah) correct? + auto singleObjectiveFragment = storm::logic::csl().setGloballyFormulasAllowed(true).setNextFormulasAllowed(true).setNestedPathFormulasAllowed(true).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); From ecd4637df348f7cce6e0e0dbfacf28d15f97743b Mon Sep 17 00:00:00 2001 From: hannah <hannah.mertens@rwth-aachen.de> Date: Tue, 15 Jun 2021 21:45:56 +0200 Subject: [PATCH 076/172] AP simplifications in LTL-Formula --- .../prctl/SparseMdpPrctlModelChecker.cpp | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.cpp b/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.cpp index 1623477f1..cc63d179a 100644 --- a/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.cpp +++ b/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.cpp @@ -189,7 +189,14 @@ namespace storm { STORM_LOG_INFO("Extracting maximal state formulas and computing satisfaction sets for path formula: " << pathFormula); + + std::map<std::string, storm::storage::BitVector> apSets; + std::map<std::string, std::string> substitution; + + // TODO Maintain a mapping from APsets to labels in order to use the same label for the same formulas + std::map<storm::storage::BitVector, std::string> labels; + for (auto& p : extracted) { STORM_LOG_INFO(" Computing satisfaction set for atomic proposition \"" << p.first << "\" <=> " << *p.second << "..."); @@ -199,9 +206,31 @@ namespace storm { STORM_LOG_INFO(" Atomic proposition \"" << p.first << "\" is satisfied by " << sat.getNumberOfSetBits() << " states."); + + auto occ = labels.find(sat); + if(occ != labels.end()){ + // Reuse AP + STORM_LOG_INFO(" Atomic proposition \"" << p.first << "\" is equivalent to " << occ->second << ", substituting..."); + substitution[p.first] = occ->second; + continue; + } + /*// equivalent to !pi + occ = labels.find(~sat); + if(occ != labels.end()){ + // Reuse negated AP + STORM_LOG_INFO(" Atomic proposition \"" << p.first << "\" is equivalent to !" << occ->second << ", substituting..."); + substitution[p.first] = todo: ! occ->second; + continue; + } + */ + + labels[sat] = p.first; apSets[p.first] = std::move(sat); + STORM_LOG_INFO(" Atomic proposition \"" << p.first << "\" is satisfied by " << sat.getNumberOfSetBits() << " states."); } + ltlFormula = ltlFormula->substitute(substitution); + const SparseMdpModelType& mdp = this->getModel(); // TODO From 75ddf49f2bc0a0518707e13fc838b70d86e64d62 Mon Sep 17 00:00:00 2001 From: hannah <hannah.mertens@rwth-aachen.de> Date: Thu, 17 Jun 2021 13:23:38 +0200 Subject: [PATCH 077/172] compute SatSets via LTLHelper --- .../csl/SparseCtmcCslModelChecker.cpp | 32 ++++------- .../SparseMarkovAutomatonCslModelChecker.cpp | 23 ++------ .../helper/ltl/SparseLTLHelper.cpp | 21 ++++++- .../modelchecker/helper/ltl/SparseLTLHelper.h | 14 ++++- .../prctl/SparseDtmcPrctlModelChecker.cpp | 22 +++----- .../prctl/SparseMdpPrctlModelChecker.cpp | 56 +++---------------- 6 files changed, 66 insertions(+), 102 deletions(-) diff --git a/src/storm/modelchecker/csl/SparseCtmcCslModelChecker.cpp b/src/storm/modelchecker/csl/SparseCtmcCslModelChecker.cpp index b36663dc9..995c06856 100644 --- a/src/storm/modelchecker/csl/SparseCtmcCslModelChecker.cpp +++ b/src/storm/modelchecker/csl/SparseCtmcCslModelChecker.cpp @@ -100,40 +100,27 @@ namespace storm { std::unique_ptr<CheckResult> SparseCtmcCslModelChecker<SparseCtmcModelType>::computeLTLProbabilities(Environment const& env, CheckTask<storm::logic::PathFormula, ValueType> const& checkTask) { storm::logic::PathFormula const& pathFormula = checkTask.getFormula(); + STORM_LOG_INFO("Extracting maximal state formulas for path formula: " << pathFormula); std::vector<storm::logic::ExtractMaximalStateFormulasVisitor::LabelFormulaPair> extracted; std::shared_ptr<storm::logic::Formula> ltlFormula = storm::logic::ExtractMaximalStateFormulasVisitor::extract(pathFormula, extracted); - STORM_LOG_INFO("Extracting maximal state formulas and computing satisfaction sets for path formula: " << pathFormula); - - std::map<std::string, storm::storage::BitVector> apSets; - // TODO simplify APs - for (auto& p : extracted) { - STORM_LOG_INFO(" Computing satisfaction set for atomic proposition \"" << p.first << "\" <=> " << *p.second << "..."); - - std::unique_ptr<CheckResult> subResultPointer = this->check(env, *p.second); - ExplicitQualitativeCheckResult const& subResult = subResultPointer->asExplicitQualitativeCheckResult(); - auto sat = subResult.getTruthValuesVector(); - - STORM_LOG_INFO(" Atomic proposition \"" << p.first << "\" is satisfied by " << sat.getNumberOfSetBits() << " states."); - - apSets[p.first] = std::move(sat); - } const SparseCtmcModelType& ctmc = this->getModel(); typedef typename storm::models::sparse::Dtmc<typename SparseCtmcModelType::ValueType> SparseDtmcModelType; STORM_LOG_INFO("Computing embedded DTMC..."); - // compute probability matrix (embedded DTMC) + // Compute probability matrix (embedded DTMC) storm::storage::SparseMatrix<ValueType> probabilityMatrix = storm::modelchecker::helper::SparseCtmcCslHelper::computeProbabilityMatrix(ctmc.getTransitionMatrix(), ctmc.getExitRateVector()); - // copy of the state labelings of the CTMC + // Copy of the state labelings of the CTMC storm::models::sparse::StateLabeling labeling(ctmc.getStateLabeling()); - // the embedded DTMC, used for building the product and computing the probabilities in the product + // The embedded DTMC, used for building the product and computing the probabilities in the product SparseDtmcModelType embeddedDtmc(std::move(probabilityMatrix), std::move(labeling)); storm::solver::SolveGoal<ValueType> goal(embeddedDtmc, checkTask); STORM_LOG_INFO("Performing ltl probability computations in embedded DTMC..."); + // TODO ? if (storm::settings::getModule<storm::settings::modules::DebugSettings>().isTraceSet()) { STORM_LOG_TRACE("Writing model to model.dot"); std::ofstream modelDot("model.dot"); @@ -141,11 +128,16 @@ namespace storm { modelDot.close(); } - storm::modelchecker::helper::SparseLTLHelper<ValueType, false> helper(embeddedDtmc.getTransitionMatrix(), this->getModel().getNumberOfStates()); + storm::modelchecker::helper::SparseLTLHelper<ValueType, false> helper(embeddedDtmc.getTransitionMatrix(), embeddedDtmc.getNumberOfStates()); storm::modelchecker::helper::setInformationFromCheckTaskDeterministic(helper, checkTask, embeddedDtmc); + + // Compute Satisfaction sets for APs + auto formulaChecker = [&] (std::shared_ptr<storm::logic::Formula const> const& formula) { return this->check(env, *formula); }; + std::map<std::string, storm::storage::BitVector> apSets = helper.computeApSets(extracted, formulaChecker); + std::vector<ValueType> numericResult = helper.computeLTLProbabilities(env, *ltlFormula, apSets); - // we can directly return the numericResult vector as the state space of the CTMC and the embedded DTMC are exactly the same + // We can directly return the numericResult vector as the state space of the CTMC and the embedded DTMC are exactly the same return std::unique_ptr<CheckResult>(new ExplicitQuantitativeCheckResult<ValueType>(std::move(numericResult))); } diff --git a/src/storm/modelchecker/csl/SparseMarkovAutomatonCslModelChecker.cpp b/src/storm/modelchecker/csl/SparseMarkovAutomatonCslModelChecker.cpp index 1a9c9fe55..90c13cf61 100644 --- a/src/storm/modelchecker/csl/SparseMarkovAutomatonCslModelChecker.cpp +++ b/src/storm/modelchecker/csl/SparseMarkovAutomatonCslModelChecker.cpp @@ -116,26 +116,10 @@ namespace storm { 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_INFO("Extracting maximal state formulas for path formula: " << pathFormula); std::vector<storm::logic::ExtractMaximalStateFormulasVisitor::LabelFormulaPair> extracted; std::shared_ptr<storm::logic::Formula> ltlFormula = storm::logic::ExtractMaximalStateFormulasVisitor::extract(pathFormula, extracted); - STORM_LOG_INFO("Extracting maximal state formulas and computing satisfaction sets for path formula: " << pathFormula); - - std::map<std::string, storm::storage::BitVector> apSets; - - // TODO simplify APs - for (auto& p : extracted) { - STORM_LOG_INFO(" Computing satisfaction set for atomic proposition \"" << p.first << "\" <=> " << *p.second << "..."); - - std::unique_ptr<CheckResult> subResultPointer = this->check(env, *p.second); - ExplicitQualitativeCheckResult const& subResult = subResultPointer->asExplicitQualitativeCheckResult(); - auto sat = subResult.getTruthValuesVector(); - - STORM_LOG_INFO(" Atomic proposition \"" << p.first << "\" is satisfied by " << sat.getNumberOfSetBits() << " states."); - - apSets[p.first] = std::move(sat); - } - const SparseMarkovAutomatonModelType& ma = this->getModel(); typedef typename storm::models::sparse::Mdp<typename SparseMarkovAutomatonModelType::ValueType> SparseMdpModelType; @@ -161,6 +145,11 @@ namespace storm { storm::modelchecker::helper::SparseLTLHelper<ValueType, true> helper(embeddedMdp.getTransitionMatrix(), this->getModel().getNumberOfStates()); storm::modelchecker::helper::setInformationFromCheckTaskNondeterministic(helper, checkTask, embeddedMdp); + + // Compute Satisfaction sets for APs + auto formulaChecker = [&] (std::shared_ptr<storm::logic::Formula const> const& formula) { return this->check(env, *formula); }; + std::map<std::string, storm::storage::BitVector> apSets = helper.computeApSets(extracted, formulaChecker); + std::vector<ValueType> numericResult = helper.computeLTLProbabilities(env, *ltlFormula, apSets); // We can directly return the numericResult vector as the state space of the CTMC and the embedded MDP are exactly the same diff --git a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp index 080e6bc0a..925f0ec3b 100644 --- a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp +++ b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp @@ -1,3 +1,5 @@ +#include <modelchecker/results/ExplicitQualitativeCheckResult.h> +#include <logic/ExtractMaximalStateFormulasVisitor.h> #include "SparseLTLHelper.h" #include "storm/transformer/DAProductBuilder.h" @@ -259,7 +261,7 @@ namespace storm { template<typename ValueType, bool Nondeterministic> - std::vector <ValueType> SparseLTLHelper<ValueType, Nondeterministic>::computeLTLProbabilities(Environment const &env, storm::logic::Formula const& formula, std::map<std::string, storm::storage::BitVector>& apSatSets) { + std::vector <ValueType> SparseLTLHelper<ValueType, Nondeterministic>::computeLTLProbabilities(Environment const& env, storm::logic::Formula 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) { @@ -294,6 +296,23 @@ namespace storm { return numericResult; } + template<typename ValueType, bool Nondeterministic> + std::map<std::string, storm::storage::BitVector> SparseLTLHelper<ValueType, Nondeterministic>::computeApSets(std::vector<storm::logic::ExtractMaximalStateFormulasVisitor::LabelFormulaPair> const& extracted, std::function<std::unique_ptr<CheckResult>(std::shared_ptr<storm::logic::Formula const> const& formula)> formulaChecker){ + std::map<std::string, storm::storage::BitVector> apSets; + for (auto& p : extracted) { + STORM_LOG_INFO(" Computing satisfaction set for atomic proposition \"" << p.first << "\" <=> " << *p.second << "..."); + + std::unique_ptr<CheckResult> subResultPointer = formulaChecker(p.second); + + ExplicitQualitativeCheckResult const& subResult = subResultPointer->asExplicitQualitativeCheckResult(); + auto sat = subResult.getTruthValuesVector(); + + apSets[p.first] = std::move(sat); + STORM_LOG_INFO(" Atomic proposition \"" << p.first << "\" is satisfied by " << sat.getNumberOfSetBits() << " states."); + } + return apSets; + } + template class SparseLTLHelper<double, false>; template class SparseLTLHelper<double, true>; diff --git a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h index 7774daf01..44e618644 100644 --- a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h +++ b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h @@ -4,6 +4,7 @@ #include "storm/solver/SolveGoal.h" #include "storm/models/sparse/Dtmc.h" #include "storm/models/sparse/Mdp.h" +#include "storm/logic/ExtractMaximalStateFormulasVisitor.h" namespace storm { @@ -27,6 +28,7 @@ namespace storm { 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 the transition matrix of the model @@ -43,6 +45,16 @@ namespace storm { */ std::vector<ValueType> computeLTLProbabilities(Environment const &env, storm::logic::Formula const& formula, std::map<std::string, storm::storage::BitVector>& apSatSets); + /*! + * todo computes Sat sets of AP + * @param + * @param + * @return + */ + std::map<std::string, storm::storage::BitVector> computeApSets(std::vector<storm::logic::ExtractMaximalStateFormulasVisitor::LabelFormulaPair> const& extracted, std::function<std::unique_ptr<CheckResult>(std::shared_ptr<storm::logic::Formula const> const& formula)> formulaChecker); + + + private: /*! * Computes the (maximizing) probabilities for the constructed DA product * @param the DA to build the product with @@ -53,8 +65,6 @@ namespace storm { std::vector<ValueType> computeDAProductProbabilities(Environment const& env, storm::automata::DeterministicAutomaton const& da, std::map<std::string, storm::storage::BitVector>& apSatSets); - private: - /*! * Compute a set S of states that admit a probability 1 strategy of satisfying the given acceptance condition (in DNF). * More precisely, let diff --git a/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.cpp b/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.cpp index fedbb5895..70f7cd475 100644 --- a/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.cpp +++ b/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.cpp @@ -146,6 +146,7 @@ namespace storm { const SparseDtmcModelType& dtmc = this->getModel(); storm::solver::SolveGoal<ValueType> goal(dtmc, checkTask); + // TODO HOA call LTL helper std::vector<ValueType> numericResult = storm::modelchecker::helper::SparseDtmcPrctlHelper<ValueType>::computeDAProductProbabilities(env, dtmc, std::move(goal), *da, apSets, checkTask.isQualitativeSet()); return std::unique_ptr<CheckResult>(new ExplicitQuantitativeCheckResult<ValueType>(std::move(numericResult))); } @@ -154,24 +155,10 @@ namespace storm { 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_LOG_INFO("Extracting maximal state formulas for path formula: " << pathFormula); std::vector<storm::logic::ExtractMaximalStateFormulasVisitor::LabelFormulaPair> extracted; std::shared_ptr<storm::logic::Formula> ltlFormula = storm::logic::ExtractMaximalStateFormulasVisitor::extract(pathFormula, extracted); - STORM_LOG_INFO("Extracting maximal state formulas and computing satisfaction sets for path formula: " << pathFormula); - // TODO simplify APs - std::map<std::string, storm::storage::BitVector> apSets; - for (auto& p : extracted) { - STORM_LOG_INFO(" Computing satisfaction set for atomic proposition \"" << p.first << "\" <=> " << *p.second << "..."); - - std::unique_ptr<CheckResult> subResultPointer = this->check(env, *p.second); - ExplicitQualitativeCheckResult const& subResult = subResultPointer->asExplicitQualitativeCheckResult(); - auto sat = subResult.getTruthValuesVector(); - - STORM_LOG_INFO(" Atomic proposition \"" << p.first << "\" is satisfied by " << sat.getNumberOfSetBits() << " states."); - - apSets[p.first] = std::move(sat); - } - const SparseDtmcModelType& dtmc = this->getModel(); // TODO ? @@ -184,6 +171,11 @@ namespace storm { storm::modelchecker::helper::SparseLTLHelper<ValueType, false> helper(dtmc.getTransitionMatrix(), this->getModel().getNumberOfStates()); storm::modelchecker::helper::setInformationFromCheckTaskDeterministic(helper, checkTask, dtmc); + + // Compute Satisfaction sets for APs + auto formulaChecker = [&] (std::shared_ptr<storm::logic::Formula const> const& formula) { return this->check(env, *formula); }; + std::map<std::string, storm::storage::BitVector> apSets = helper.computeApSets(extracted, formulaChecker); + std::vector<ValueType> numericResult = helper.computeLTLProbabilities(env, *ltlFormula, apSets); return std::unique_ptr<CheckResult>(new ExplicitQuantitativeCheckResult<ValueType>(std::move(numericResult))); diff --git a/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.cpp b/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.cpp index cc63d179a..500e893ea 100644 --- a/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.cpp +++ b/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.cpp @@ -184,56 +184,13 @@ namespace storm { 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_LOG_INFO("Extracting maximal state formulas for path formula: " << pathFormula); std::vector<storm::logic::ExtractMaximalStateFormulasVisitor::LabelFormulaPair> extracted; + std::shared_ptr<storm::logic::Formula> ltlFormula = storm::logic::ExtractMaximalStateFormulasVisitor::extract(pathFormula, extracted); - STORM_LOG_INFO("Extracting maximal state formulas and computing satisfaction sets for path formula: " << pathFormula); - - - - std::map<std::string, storm::storage::BitVector> apSets; - std::map<std::string, std::string> substitution; - - // TODO Maintain a mapping from APsets to labels in order to use the same label for the same formulas - std::map<storm::storage::BitVector, std::string> labels; - - for (auto& p : extracted) { - STORM_LOG_INFO(" Computing satisfaction set for atomic proposition \"" << p.first << "\" <=> " << *p.second << "..."); - - std::unique_ptr<CheckResult> subResultPointer = this->check(env, *p.second); - ExplicitQualitativeCheckResult const& subResult = subResultPointer->asExplicitQualitativeCheckResult(); - auto sat = subResult.getTruthValuesVector(); - - STORM_LOG_INFO(" Atomic proposition \"" << p.first << "\" is satisfied by " << sat.getNumberOfSetBits() << " states."); - - - auto occ = labels.find(sat); - if(occ != labels.end()){ - // Reuse AP - STORM_LOG_INFO(" Atomic proposition \"" << p.first << "\" is equivalent to " << occ->second << ", substituting..."); - substitution[p.first] = occ->second; - continue; - } - /*// equivalent to !pi - occ = labels.find(~sat); - if(occ != labels.end()){ - // Reuse negated AP - STORM_LOG_INFO(" Atomic proposition \"" << p.first << "\" is equivalent to !" << occ->second << ", substituting..."); - substitution[p.first] = todo: ! occ->second; - continue; - } - */ - - labels[sat] = p.first; - apSets[p.first] = std::move(sat); - STORM_LOG_INFO(" Atomic proposition \"" << p.first << "\" is satisfied by " << sat.getNumberOfSetBits() << " states."); - } - - ltlFormula = ltlFormula->substitute(substitution); - const SparseMdpModelType& mdp = this->getModel(); - - // TODO + // TODO ? if (storm::settings::getModule<storm::settings::modules::DebugSettings>().isTraceSet()) { STORM_LOG_TRACE("Writing model to model.dot"); std::ofstream modelDot("model.dot"); @@ -241,8 +198,13 @@ namespace storm { modelDot.close(); } - storm::modelchecker::helper::SparseLTLHelper<ValueType, true> helper(mdp.getTransitionMatrix(), this->getModel().getNumberOfStates()); + storm::modelchecker::helper::SparseLTLHelper<ValueType, true> helper(mdp.getTransitionMatrix(), mdp.getNumberOfStates()); storm::modelchecker::helper::setInformationFromCheckTaskNondeterministic(helper, checkTask, mdp); + + // Compute Satisfaction sets for APs + auto formulaChecker = [&] (std::shared_ptr<storm::logic::Formula const> const& formula) { return this->check(env, *formula); }; + std::map<std::string, storm::storage::BitVector> apSets = helper.computeApSets(extracted, formulaChecker); + std::vector<ValueType> numericResult = helper.computeLTLProbabilities(env, *ltlFormula, apSets); return std::unique_ptr<CheckResult>(new ExplicitQuantitativeCheckResult<ValueType>(std::move(numericResult))); From 1d5860de8d77be8a40c3dc7f854c3f06a5d0c53c Mon Sep 17 00:00:00 2001 From: hannah <hannah.mertens@rwth-aachen.de> Date: Thu, 17 Jun 2021 18:52:40 +0200 Subject: [PATCH 078/172] use same labels for equivalent maximal state formulas --- .../ExtractMaximalStateFormulasVisitor.cpp | 18 +++++++++++++----- .../logic/ExtractMaximalStateFormulasVisitor.h | 11 +++++++---- .../csl/SparseCtmcCslModelChecker.cpp | 4 +++- .../SparseMarkovAutomatonCslModelChecker.cpp | 4 +++- .../helper/ltl/SparseLTLHelper.cpp | 13 +++++++------ .../modelchecker/helper/ltl/SparseLTLHelper.h | 4 +--- .../prctl/SparseDtmcPrctlModelChecker.cpp | 4 +++- .../prctl/SparseMdpPrctlModelChecker.cpp | 5 +++-- .../prctl/helper/SparseMdpPrctlHelper.h | 2 -- 9 files changed, 40 insertions(+), 25 deletions(-) diff --git a/src/storm/logic/ExtractMaximalStateFormulasVisitor.cpp b/src/storm/logic/ExtractMaximalStateFormulasVisitor.cpp index d6f465027..30d4d683a 100644 --- a/src/storm/logic/ExtractMaximalStateFormulasVisitor.cpp +++ b/src/storm/logic/ExtractMaximalStateFormulasVisitor.cpp @@ -7,10 +7,10 @@ namespace storm { namespace logic { - ExtractMaximalStateFormulasVisitor::ExtractMaximalStateFormulasVisitor(std::vector<LabelFormulaPair>& extractedFormulas) : extractedFormulas(extractedFormulas), nestingLevel(0) { + ExtractMaximalStateFormulasVisitor::ExtractMaximalStateFormulasVisitor(FormulaLabelMapping& extractedFormulas) : extractedFormulas(extractedFormulas), nestingLevel(0) { } - std::shared_ptr<Formula> ExtractMaximalStateFormulasVisitor::extract(PathFormula const& f, std::vector<LabelFormulaPair>& extractedFormulas) { + std::shared_ptr<Formula> ExtractMaximalStateFormulasVisitor::extract(PathFormula const& f, FormulaLabelMapping& extractedFormulas) { ExtractMaximalStateFormulasVisitor visitor(extractedFormulas); boost::any result = f.accept(visitor, boost::any()); return boost::any_cast<std::shared_ptr<Formula>>(result); @@ -150,10 +150,18 @@ namespace storm { } std::shared_ptr<Formula> ExtractMaximalStateFormulasVisitor::extract(std::shared_ptr<Formula> f) const { - std::string label = "p" + std::to_string(extractedFormulas.size()); - - const_cast<std::vector<LabelFormulaPair>&>(extractedFormulas).emplace_back(label, f); + // TODO can be optimized + std::string label; + auto it = extractedFormulas.find(f->toString()); + if (it != extractedFormulas.end()){ + // Reuse label of equivalent formula + label = it->second.first; + } else { + // Create new label + label = "p" + std::to_string(extractedFormulas.size()); + } + extractedFormulas[f->toString()] = LabelFormulaPair(label, f); return std::make_shared<storm::logic::AtomicLabelFormula>(label); } diff --git a/src/storm/logic/ExtractMaximalStateFormulasVisitor.h b/src/storm/logic/ExtractMaximalStateFormulasVisitor.h index e3bd1cea5..de1cf8cda 100644 --- a/src/storm/logic/ExtractMaximalStateFormulasVisitor.h +++ b/src/storm/logic/ExtractMaximalStateFormulasVisitor.h @@ -1,7 +1,7 @@ #pragma once #include <vector> - +#include <map> #include "storm/logic/CloneVisitor.h" namespace storm { @@ -11,7 +11,10 @@ namespace storm { public: typedef std::pair<std::string, std::shared_ptr<Formula const>> LabelFormulaPair; - static std::shared_ptr<Formula> extract(PathFormula const& f, std::vector<LabelFormulaPair>& extractedFormulas); + // Maintain a mapping from formula-strings to formula-label pairs in order to use the same label for the equivalent formulas (as strings) + typedef std::map<std::string, LabelFormulaPair> FormulaLabelMapping; + + static std::shared_ptr<Formula> extract(PathFormula const& f, FormulaLabelMapping& 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; @@ -28,13 +31,13 @@ namespace storm { virtual boost::any visit(RewardOperatorFormula const& f, boost::any const& data) const override; private: - ExtractMaximalStateFormulasVisitor(std::vector<LabelFormulaPair>& extractedFormulas); + ExtractMaximalStateFormulasVisitor(FormulaLabelMapping& extractedFormulas); std::shared_ptr<Formula> extract(std::shared_ptr<Formula> f) const; void incrementNestingLevel() const; void decrementNestingLevel() const; - std::vector<LabelFormulaPair>& extractedFormulas; + FormulaLabelMapping& extractedFormulas; std::size_t nestingLevel; }; diff --git a/src/storm/modelchecker/csl/SparseCtmcCslModelChecker.cpp b/src/storm/modelchecker/csl/SparseCtmcCslModelChecker.cpp index 995c06856..be1910735 100644 --- a/src/storm/modelchecker/csl/SparseCtmcCslModelChecker.cpp +++ b/src/storm/modelchecker/csl/SparseCtmcCslModelChecker.cpp @@ -101,7 +101,9 @@ namespace storm { storm::logic::PathFormula const& pathFormula = checkTask.getFormula(); STORM_LOG_INFO("Extracting maximal state formulas for path formula: " << pathFormula); - std::vector<storm::logic::ExtractMaximalStateFormulasVisitor::LabelFormulaPair> extracted; + + // Maintain a mapping from formula-strings to pairs in order to reuse labels of equivalent (compared as strings) formulas + std::map<std::string, storm::logic::ExtractMaximalStateFormulasVisitor::LabelFormulaPair> extracted; std::shared_ptr<storm::logic::Formula> ltlFormula = storm::logic::ExtractMaximalStateFormulasVisitor::extract(pathFormula, extracted); diff --git a/src/storm/modelchecker/csl/SparseMarkovAutomatonCslModelChecker.cpp b/src/storm/modelchecker/csl/SparseMarkovAutomatonCslModelChecker.cpp index 90c13cf61..c35c05b43 100644 --- a/src/storm/modelchecker/csl/SparseMarkovAutomatonCslModelChecker.cpp +++ b/src/storm/modelchecker/csl/SparseMarkovAutomatonCslModelChecker.cpp @@ -117,7 +117,9 @@ namespace storm { storm::logic::PathFormula const& pathFormula = checkTask.getFormula(); STORM_LOG_INFO("Extracting maximal state formulas for path formula: " << pathFormula); - std::vector<storm::logic::ExtractMaximalStateFormulasVisitor::LabelFormulaPair> extracted; + + // Maintain a mapping from formula-strings to pairs in order to reuse labels of equivalent (compared as strings) formulas + std::map<std::string, storm::logic::ExtractMaximalStateFormulasVisitor::LabelFormulaPair> extracted; std::shared_ptr<storm::logic::Formula> ltlFormula = storm::logic::ExtractMaximalStateFormulasVisitor::extract(pathFormula, extracted); const SparseMarkovAutomatonModelType& ma = this->getModel(); diff --git a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp index 925f0ec3b..ea6df66fc 100644 --- a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp +++ b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp @@ -297,18 +297,19 @@ namespace storm { } template<typename ValueType, bool Nondeterministic> - std::map<std::string, storm::storage::BitVector> SparseLTLHelper<ValueType, Nondeterministic>::computeApSets(std::vector<storm::logic::ExtractMaximalStateFormulasVisitor::LabelFormulaPair> const& extracted, std::function<std::unique_ptr<CheckResult>(std::shared_ptr<storm::logic::Formula const> const& formula)> formulaChecker){ + std::map<std::string, storm::storage::BitVector> SparseLTLHelper<ValueType, Nondeterministic>::computeApSets(std::map<std::string, storm::logic::ExtractMaximalStateFormulasVisitor::LabelFormulaPair> const& extracted, std::function<std::unique_ptr<CheckResult>(std::shared_ptr<storm::logic::Formula const> const& formula)> formulaChecker){ std::map<std::string, storm::storage::BitVector> apSets; - for (auto& p : extracted) { - STORM_LOG_INFO(" Computing satisfaction set for atomic proposition \"" << p.first << "\" <=> " << *p.second << "..."); + for (auto& it: extracted) { + storm::logic::ExtractMaximalStateFormulasVisitor::LabelFormulaPair pair = it.second; + STORM_LOG_INFO(" Computing satisfaction set for atomic proposition \"" << pair.first << "\" <=> " << *pair.second << "..."); - std::unique_ptr<CheckResult> subResultPointer = formulaChecker(p.second); + std::unique_ptr<CheckResult> subResultPointer = formulaChecker(pair.second); ExplicitQualitativeCheckResult const& subResult = subResultPointer->asExplicitQualitativeCheckResult(); auto sat = subResult.getTruthValuesVector(); - apSets[p.first] = std::move(sat); - STORM_LOG_INFO(" Atomic proposition \"" << p.first << "\" is satisfied by " << sat.getNumberOfSetBits() << " states."); + apSets[pair.first] = std::move(sat); + STORM_LOG_INFO(" Atomic proposition \"" << pair.first << "\" is satisfied by " << sat.getNumberOfSetBits() << " states."); } return apSets; } diff --git a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h index 44e618644..a90f43370 100644 --- a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h +++ b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h @@ -27,8 +27,6 @@ namespace storm { */ 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 the transition matrix of the model @@ -51,7 +49,7 @@ namespace storm { * @param * @return */ - std::map<std::string, storm::storage::BitVector> computeApSets(std::vector<storm::logic::ExtractMaximalStateFormulasVisitor::LabelFormulaPair> const& extracted, std::function<std::unique_ptr<CheckResult>(std::shared_ptr<storm::logic::Formula const> const& formula)> formulaChecker); + std::map<std::string, storm::storage::BitVector> computeApSets(std::map<std::string, storm::logic::ExtractMaximalStateFormulasVisitor::LabelFormulaPair> const& extracted, std::function<std::unique_ptr<CheckResult>(std::shared_ptr<storm::logic::Formula const> const& formula)> formulaChecker); private: diff --git a/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.cpp b/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.cpp index 70f7cd475..ff41d1a73 100644 --- a/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.cpp +++ b/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.cpp @@ -156,7 +156,9 @@ namespace storm { storm::logic::PathFormula const& pathFormula = checkTask.getFormula(); STORM_LOG_INFO("Extracting maximal state formulas for path formula: " << pathFormula); - std::vector<storm::logic::ExtractMaximalStateFormulasVisitor::LabelFormulaPair> extracted; + + // Maintain a mapping from formula-strings to pairs in order to reuse labels of equivalent (compared as strings) formulas + std::map<std::string, storm::logic::ExtractMaximalStateFormulasVisitor::LabelFormulaPair> extracted; std::shared_ptr<storm::logic::Formula> ltlFormula = storm::logic::ExtractMaximalStateFormulasVisitor::extract(pathFormula, extracted); const SparseDtmcModelType& dtmc = this->getModel(); diff --git a/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.cpp b/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.cpp index 500e893ea..d567100fb 100644 --- a/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.cpp +++ b/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.cpp @@ -185,8 +185,9 @@ namespace storm { 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_LOG_INFO("Extracting maximal state formulas for path formula: " << pathFormula); - std::vector<storm::logic::ExtractMaximalStateFormulasVisitor::LabelFormulaPair> extracted; - + + // Maintain a mapping from formula-strings to pairs in order to reuse labels of equivalent (compared as strings) formulas + std::map<std::string, storm::logic::ExtractMaximalStateFormulasVisitor::LabelFormulaPair> extracted; std::shared_ptr<storm::logic::Formula> ltlFormula = storm::logic::ExtractMaximalStateFormulasVisitor::extract(pathFormula, extracted); const SparseMdpModelType& mdp = this->getModel(); diff --git a/src/storm/modelchecker/prctl/helper/SparseMdpPrctlHelper.h b/src/storm/modelchecker/prctl/helper/SparseMdpPrctlHelper.h index ea38383f0..6515b9d83 100644 --- a/src/storm/modelchecker/prctl/helper/SparseMdpPrctlHelper.h +++ b/src/storm/modelchecker/prctl/helper/SparseMdpPrctlHelper.h @@ -10,8 +10,6 @@ #include "storm/modelchecker/prctl/helper/rewardbounded/MultiDimensionalRewardUnfolding.h" #include "MDPModelCheckingHelperReturnType.h" -#include "storm/automata/AcceptanceCondition.h" - #include "storm/utility/solver.h" #include "storm/solver/SolveGoal.h" From 225169b2b38398357c8a70d585bcec29e4c36f1d Mon Sep 17 00:00:00 2001 From: hannah <hannah.mertens@rwth-aachen.de> Date: Fri, 18 Jun 2021 09:24:39 +0200 Subject: [PATCH 079/172] added ltl2da option --- .../automata/LTL2DeterministicAutomaton.cpp | 29 +++++-------------- .../automata/LTL2DeterministicAutomaton.h | 20 +++++++++---- .../modelchecker/ModelCheckerEnvironment.cpp | 25 +++++++++++++++- .../modelchecker/ModelCheckerEnvironment.h | 8 ++++- .../helper/ltl/SparseLTLHelper.cpp | 16 ++++++++-- .../settings/modules/ModelCheckerSettings.cpp | 10 +++++++ .../settings/modules/ModelCheckerSettings.h | 17 ++++++++++- 7 files changed, 93 insertions(+), 32 deletions(-) diff --git a/src/storm/automata/LTL2DeterministicAutomaton.cpp b/src/storm/automata/LTL2DeterministicAutomaton.cpp index d780bf979..bef88aaaf 100644 --- a/src/storm/automata/LTL2DeterministicAutomaton.cpp +++ b/src/storm/automata/LTL2DeterministicAutomaton.cpp @@ -22,12 +22,10 @@ namespace storm { namespace automata { - bool LTL2DeterministicAutomaton::isExternalDaToolSet() { - return std::getenv("LTL2DA"); - } - std::shared_ptr<DeterministicAutomaton> LTL2DeterministicAutomaton::ltl2daInternalTool(std::string const& prefixLtl, bool dnf) { + 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()){ @@ -68,12 +66,10 @@ namespace storm { } // TODO: this is quite hacky, improve robustness - std::shared_ptr<DeterministicAutomaton> LTL2DeterministicAutomaton::ltl2daExternalTool(std::string const& prefixLtl) { - - - std::string ltl2da_tool = std::getenv("LTL2DA"); + 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: " << ltl2da_tool << " '" << prefixLtl << "' da.hoa"); + STORM_LOG_INFO("Calling external LTL->DA tool: " << ltl2daTool << " '" << prefixLtl << "' da.hoa"); pid_t pid; @@ -82,7 +78,7 @@ namespace storm { if (pid == 0) { // we are in the child process - if (execlp(ltl2da_tool.c_str(), ltl2da_tool.c_str(), prefixLtl.c_str(), "da.hoa", NULL) < 0) { + 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); } @@ -110,17 +106,6 @@ namespace storm { } } - std::shared_ptr<DeterministicAutomaton> LTL2DeterministicAutomaton::ltl2da(storm::logic::Formula const& f, bool dnf) { - std::string prefixLtl = f.toPrefixString(); - - storm::automata::DeterministicAutomaton::ptr da; - if(isExternalDaToolSet()){ - da = ltl2daExternalTool(prefixLtl); - } else { - da = ltl2daInternalTool(prefixLtl, dnf); - } - return da; - } - } + } diff --git a/src/storm/automata/LTL2DeterministicAutomaton.h b/src/storm/automata/LTL2DeterministicAutomaton.h index 1471922d3..4134e326f 100644 --- a/src/storm/automata/LTL2DeterministicAutomaton.h +++ b/src/storm/automata/LTL2DeterministicAutomaton.h @@ -15,13 +15,23 @@ namespace storm { class LTL2DeterministicAutomaton { public: - static std::shared_ptr<DeterministicAutomaton> ltl2da(storm::logic::Formula const&, bool dnf); - private: - static bool isExternalDaToolSet(); + /*! + * TODO + * @param f + * @param dnf + * @return + */ + static std::shared_ptr<DeterministicAutomaton> ltl2daSpot(storm::logic::Formula const& f, bool dnf); + + /*! + * TODO + * @param f + * @param ltl2daTool + * @return + */ + static std::shared_ptr<DeterministicAutomaton> ltl2daExternalTool(storm::logic::Formula const& f, std::string ltl2daTool); - static std::shared_ptr<DeterministicAutomaton> ltl2daInternalTool(std::string const& prefixLtl, bool dnf); - static std::shared_ptr<DeterministicAutomaton> ltl2daExternalTool(std::string const& prefixLtl); }; } diff --git a/src/storm/environment/modelchecker/ModelCheckerEnvironment.cpp b/src/storm/environment/modelchecker/ModelCheckerEnvironment.cpp index f0d917a28..8836d57be 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.isLtl2daSet()) { + ltl2da = mcSettings.getLtl2da(); + } } ModelCheckerEnvironment::~ModelCheckerEnvironment() { @@ -26,6 +30,25 @@ namespace storm { MultiObjectiveModelCheckerEnvironment const& ModelCheckerEnvironment::multi() const { return multiObjectiveModelCheckerEnvironment.get(); } + + bool ModelCheckerEnvironment::isLtl2daSet() const { + return ltl2da.is_initialized(); + } + + boost::optional<std::string> const& ModelCheckerEnvironment::getLtl2da() const { + return ltl2da; + } + + void ModelCheckerEnvironment::setLtl2da(std::string const& value) { + ltl2da = value; + } + + void ModelCheckerEnvironment::unsetLtl2da() { + ltl2da = boost::none; + } + + + } diff --git a/src/storm/environment/modelchecker/ModelCheckerEnvironment.h b/src/storm/environment/modelchecker/ModelCheckerEnvironment.h index 2ec1eebd8..416172a36 100644 --- a/src/storm/environment/modelchecker/ModelCheckerEnvironment.h +++ b/src/storm/environment/modelchecker/ModelCheckerEnvironment.h @@ -20,9 +20,15 @@ namespace storm { MultiObjectiveModelCheckerEnvironment& multi(); MultiObjectiveModelCheckerEnvironment const& multi() const; - + bool isLtl2daSet() const; + boost::optional<std::string> const& getLtl2da() const; + void setLtl2da(std::string const& value); + void unsetLtl2da(); + + private: SubEnvironment<MultiObjectiveModelCheckerEnvironment> multiObjectiveModelCheckerEnvironment; + boost::optional<std::string> ltl2da; }; } diff --git a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp index ea6df66fc..89ab5737d 100644 --- a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp +++ b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp @@ -15,6 +15,8 @@ #include "storm/settings/modules/DebugSettings.h" #include "storm/exceptions/InvalidPropertyException.h" +#include "storm/environment/modelchecker/ModelCheckerEnvironment.h" + namespace storm { namespace modelchecker { namespace helper { @@ -272,11 +274,21 @@ namespace storm { ltlFormula = formula.asSharedPointer(); } - STORM_LOG_INFO("Resulting LTL path formula: " << ltlFormula->toString()); STORM_LOG_INFO(" in prefix format: " << ltlFormula->toPrefixString()); - std::shared_ptr<storm::automata::DeterministicAutomaton> da = storm::automata::LTL2DeterministicAutomaton::ltl2da(*ltlFormula, Nondeterministic); + // Convert LTL formula to a deterministic automaton + std::shared_ptr<storm::automata::DeterministicAutomaton> da; + if (env.modelchecker().isLtl2daSet()) { + // Use the external tool given via ltl2da + std::string ltl2da = env.modelchecker().getLtl2da().get(); + da = storm::automata::LTL2DeterministicAutomaton::ltl2daExternalTool(*ltlFormula, ltl2da); + } + 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, " diff --git a/src/storm/settings/modules/ModelCheckerSettings.cpp b/src/storm/settings/modules/ModelCheckerSettings.cpp index da0b64d8e..c68cc5a6b 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::ltl2daName = "ltl2da"; 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, ltl2daName, 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::isLtl2daSet() const { + return this->getOption(ltl2daName).getHasOptionBeenSet(); + } + + std::string ModelCheckerSettings::getLtl2da() const { + return this->getOption(ltl2daName).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..2f731690f 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 isLtl2daSet() 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 getLtl2da() 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 ltl2daName; }; } // namespace modules From 71f72d84b223e6f1f8f4111cbd72ca09f40a500c Mon Sep 17 00:00:00 2001 From: hannah <hannah.mertens@rwth-aachen.de> Date: Fri, 18 Jun 2021 12:29:24 +0200 Subject: [PATCH 080/172] Ma ltl-MC and tests --- .../SparseMarkovAutomatonCslModelChecker.cpp | 2 +- .../MarkovAutomatonCslModelCheckerTest.cpp | 35 +++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/src/storm/modelchecker/csl/SparseMarkovAutomatonCslModelChecker.cpp b/src/storm/modelchecker/csl/SparseMarkovAutomatonCslModelChecker.cpp index c35c05b43..35239a154 100644 --- a/src/storm/modelchecker/csl/SparseMarkovAutomatonCslModelChecker.cpp +++ b/src/storm/modelchecker/csl/SparseMarkovAutomatonCslModelChecker.cpp @@ -40,7 +40,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(true).setNextFormulasAllowed(true).setNestedPathFormulasAllowed(true).setRewardOperatorsAllowed(true).setReachabilityRewardFormulasAllowed(true).setTotalRewardFormulasAllowed(true).setTimeAllowed(true).setLongRunAverageProbabilitiesAllowed(true).setLongRunAverageRewardFormulasAllowed(true).setRewardAccumulationAllowed(true).setInstantaneousFormulasAllowed(false); + auto singleObjectiveFragment = storm::logic::csl().setUnaryBooleanPathFormulasAllowed(true).setBinaryBooleanPathFormulasAllowed(true).setNestedPathFormulasAllowed(true).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); diff --git a/src/test/storm/modelchecker/csl/MarkovAutomatonCslModelCheckerTest.cpp b/src/test/storm/modelchecker/csl/MarkovAutomatonCslModelCheckerTest.cpp index 745c32f55..07475ce7a 100755 --- a/src/test/storm/modelchecker/csl/MarkovAutomatonCslModelCheckerTest.cpp +++ b/src/test/storm/modelchecker/csl/MarkovAutomatonCslModelCheckerTest.cpp @@ -349,4 +349,39 @@ namespace { } #endif } + + TYPED_TEST(MarkovAutomatonCslModelCheckerTest, LtlSimple) { + 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])); + } + + } } From 57734226e2a58faa239d3601ee74f2fdc33a196d Mon Sep 17 00:00:00 2001 From: hannah <hannah.mertens@rwth-aachen.de> Date: Fri, 18 Jun 2021 13:52:51 +0200 Subject: [PATCH 081/172] channged data structure for extracted formulas --- .../ExtractMaximalStateFormulasVisitor.cpp | 18 +++++++++++------- .../logic/ExtractMaximalStateFormulasVisitor.h | 13 ++++++------- .../csl/SparseCtmcCslModelChecker.cpp | 8 ++++---- .../SparseMarkovAutomatonCslModelChecker.cpp | 9 ++++----- .../helper/ltl/SparseLTLHelper.cpp | 13 ++++++------- .../modelchecker/helper/ltl/SparseLTLHelper.h | 2 +- .../prctl/SparseDtmcPrctlModelChecker.cpp | 18 ++++++++++++++---- .../prctl/SparseMdpPrctlModelChecker.cpp | 8 ++++---- 8 files changed, 50 insertions(+), 39 deletions(-) diff --git a/src/storm/logic/ExtractMaximalStateFormulasVisitor.cpp b/src/storm/logic/ExtractMaximalStateFormulasVisitor.cpp index 30d4d683a..6652c868b 100644 --- a/src/storm/logic/ExtractMaximalStateFormulasVisitor.cpp +++ b/src/storm/logic/ExtractMaximalStateFormulasVisitor.cpp @@ -7,11 +7,11 @@ namespace storm { namespace logic { - ExtractMaximalStateFormulasVisitor::ExtractMaximalStateFormulasVisitor(FormulaLabelMapping& extractedFormulas) : extractedFormulas(extractedFormulas), nestingLevel(0) { + ExtractMaximalStateFormulasVisitor::ExtractMaximalStateFormulasVisitor(ApToFormulaMap& extractedFormulas, std::map<std::string, std::string>& cachedFormulas) : extractedFormulas(extractedFormulas), cachedFormulas(cachedFormulas), nestingLevel(0) { } - std::shared_ptr<Formula> ExtractMaximalStateFormulasVisitor::extract(PathFormula const& f, FormulaLabelMapping& extractedFormulas) { - ExtractMaximalStateFormulasVisitor visitor(extractedFormulas); + std::shared_ptr<Formula> ExtractMaximalStateFormulasVisitor::extract(PathFormula const& f, ApToFormulaMap& extractedFormulas, std::map<std::string, std::string>& cachedFormulas) { + ExtractMaximalStateFormulasVisitor visitor(extractedFormulas, cachedFormulas); boost::any result = f.accept(visitor, boost::any()); return boost::any_cast<std::shared_ptr<Formula>>(result); } @@ -152,16 +152,20 @@ namespace storm { std::shared_ptr<Formula> ExtractMaximalStateFormulasVisitor::extract(std::shared_ptr<Formula> f) const { // TODO can be optimized std::string label; - auto it = extractedFormulas.find(f->toString()); - if (it != extractedFormulas.end()){ + + // Find equivalent formula in cache + auto it = cachedFormulas.find(f->toString()); + if (it != cachedFormulas.end()){ // Reuse label of equivalent formula - label = it->second.first; + label = it->second; } else { // Create new label label = "p" + std::to_string(extractedFormulas.size()); + extractedFormulas[label] = f; + // Update cache + cachedFormulas[f->toString()] = label; } - extractedFormulas[f->toString()] = LabelFormulaPair(label, f); return std::make_shared<storm::logic::AtomicLabelFormula>(label); } diff --git a/src/storm/logic/ExtractMaximalStateFormulasVisitor.h b/src/storm/logic/ExtractMaximalStateFormulasVisitor.h index de1cf8cda..d1a188c3d 100644 --- a/src/storm/logic/ExtractMaximalStateFormulasVisitor.h +++ b/src/storm/logic/ExtractMaximalStateFormulasVisitor.h @@ -9,12 +9,9 @@ namespace storm { class ExtractMaximalStateFormulasVisitor : public CloneVisitor { public: - typedef std::pair<std::string, std::shared_ptr<Formula const>> LabelFormulaPair; + typedef std::map<std::string, std::shared_ptr<Formula const>> ApToFormulaMap; - // Maintain a mapping from formula-strings to formula-label pairs in order to use the same label for the equivalent formulas (as strings) - typedef std::map<std::string, LabelFormulaPair> FormulaLabelMapping; - - static std::shared_ptr<Formula> extract(PathFormula const& f, FormulaLabelMapping& extractedFormulas); + static std::shared_ptr<Formula> extract(PathFormula const& f, ApToFormulaMap& extractedFormulas, std::map<std::string, std::string>& cachedFormulas); 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; @@ -31,13 +28,15 @@ namespace storm { virtual boost::any visit(RewardOperatorFormula const& f, boost::any const& data) const override; private: - ExtractMaximalStateFormulasVisitor(FormulaLabelMapping& extractedFormulas); + ExtractMaximalStateFormulasVisitor(ApToFormulaMap& extractedFormulas, std::map<std::string, std::string>& cachedFormulas); std::shared_ptr<Formula> extract(std::shared_ptr<Formula> f) const; void incrementNestingLevel() const; void decrementNestingLevel() const; - FormulaLabelMapping& extractedFormulas; + ApToFormulaMap& extractedFormulas; + // A mapping from formula-strings to labels in order to use the same label for the equivalent formulas (as strings) + std::map<std::string, std::string>& cachedFormulas; std::size_t nestingLevel; }; diff --git a/src/storm/modelchecker/csl/SparseCtmcCslModelChecker.cpp b/src/storm/modelchecker/csl/SparseCtmcCslModelChecker.cpp index be1910735..28824477f 100644 --- a/src/storm/modelchecker/csl/SparseCtmcCslModelChecker.cpp +++ b/src/storm/modelchecker/csl/SparseCtmcCslModelChecker.cpp @@ -101,10 +101,10 @@ namespace storm { storm::logic::PathFormula const& pathFormula = checkTask.getFormula(); STORM_LOG_INFO("Extracting maximal state formulas for path formula: " << pathFormula); - - // Maintain a mapping from formula-strings to pairs in order to reuse labels of equivalent (compared as strings) formulas - std::map<std::string, storm::logic::ExtractMaximalStateFormulasVisitor::LabelFormulaPair> extracted; - std::shared_ptr<storm::logic::Formula> ltlFormula = storm::logic::ExtractMaximalStateFormulasVisitor::extract(pathFormula, extracted); + storm::logic::ExtractMaximalStateFormulasVisitor::ApToFormulaMap extracted; + // Maintain a mapping from formula-strings to labels in order to reuse labels of equivalent (compared as strings) formulas + std::map<std::string, std::string> cached; + std::shared_ptr<storm::logic::Formula> ltlFormula = storm::logic::ExtractMaximalStateFormulasVisitor::extract(pathFormula, extracted, cached); const SparseCtmcModelType& ctmc = this->getModel(); diff --git a/src/storm/modelchecker/csl/SparseMarkovAutomatonCslModelChecker.cpp b/src/storm/modelchecker/csl/SparseMarkovAutomatonCslModelChecker.cpp index 35239a154..6de3d079d 100644 --- a/src/storm/modelchecker/csl/SparseMarkovAutomatonCslModelChecker.cpp +++ b/src/storm/modelchecker/csl/SparseMarkovAutomatonCslModelChecker.cpp @@ -117,15 +117,14 @@ namespace storm { storm::logic::PathFormula const& pathFormula = checkTask.getFormula(); STORM_LOG_INFO("Extracting maximal state formulas for path formula: " << pathFormula); - - // Maintain a mapping from formula-strings to pairs in order to reuse labels of equivalent (compared as strings) formulas - std::map<std::string, storm::logic::ExtractMaximalStateFormulasVisitor::LabelFormulaPair> extracted; - std::shared_ptr<storm::logic::Formula> ltlFormula = storm::logic::ExtractMaximalStateFormulasVisitor::extract(pathFormula, extracted); + storm::logic::ExtractMaximalStateFormulasVisitor::ApToFormulaMap extracted; + // Maintain a mapping from formula-strings to labels in order to reuse labels of equivalent (compared as strings) formulas + std::map<std::string, std::string> cached; + std::shared_ptr<storm::logic::Formula> ltlFormula = storm::logic::ExtractMaximalStateFormulasVisitor::extract(pathFormula, extracted, cached); const SparseMarkovAutomatonModelType& ma = this->getModel(); typedef typename storm::models::sparse::Mdp<typename SparseMarkovAutomatonModelType::ValueType> SparseMdpModelType; - // TODO correct? STORM_LOG_INFO("Computing embedded MDP..."); storm::storage::SparseMatrix<ValueType> probabilityMatrix = ma.getTransitionMatrix(); // Copy of the state labelings of the MDP diff --git a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp index 89ab5737d..12c1f030c 100644 --- a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp +++ b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp @@ -309,19 +309,18 @@ namespace storm { } template<typename ValueType, bool Nondeterministic> - std::map<std::string, storm::storage::BitVector> SparseLTLHelper<ValueType, Nondeterministic>::computeApSets(std::map<std::string, storm::logic::ExtractMaximalStateFormulasVisitor::LabelFormulaPair> const& extracted, std::function<std::unique_ptr<CheckResult>(std::shared_ptr<storm::logic::Formula const> const& formula)> formulaChecker){ + std::map<std::string, storm::storage::BitVector> SparseLTLHelper<ValueType, Nondeterministic>::computeApSets(std::map<std::string, std::shared_ptr<storm::logic::Formula const>> const& extracted, std::function<std::unique_ptr<CheckResult>(std::shared_ptr<storm::logic::Formula const> const& formula)> formulaChecker){ std::map<std::string, storm::storage::BitVector> apSets; - for (auto& it: extracted) { - storm::logic::ExtractMaximalStateFormulasVisitor::LabelFormulaPair pair = it.second; - STORM_LOG_INFO(" Computing satisfaction set for atomic proposition \"" << pair.first << "\" <=> " << *pair.second << "..."); + for (auto& p: extracted) { + STORM_LOG_INFO(" Computing satisfaction set for atomic proposition \"" << p.first << "\" <=> " << *p.second << "..."); - std::unique_ptr<CheckResult> subResultPointer = formulaChecker(pair.second); + std::unique_ptr<CheckResult> subResultPointer = formulaChecker(p.second); ExplicitQualitativeCheckResult const& subResult = subResultPointer->asExplicitQualitativeCheckResult(); auto sat = subResult.getTruthValuesVector(); - apSets[pair.first] = std::move(sat); - STORM_LOG_INFO(" Atomic proposition \"" << pair.first << "\" is satisfied by " << sat.getNumberOfSetBits() << " states."); + apSets[p.first] = std::move(sat); + STORM_LOG_INFO(" Atomic proposition \"" << p.first << "\" is satisfied by " << sat.getNumberOfSetBits() << " states."); } return apSets; } diff --git a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h index a90f43370..71760e717 100644 --- a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h +++ b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h @@ -49,7 +49,7 @@ namespace storm { * @param * @return */ - std::map<std::string, storm::storage::BitVector> computeApSets(std::map<std::string, storm::logic::ExtractMaximalStateFormulasVisitor::LabelFormulaPair> const& extracted, std::function<std::unique_ptr<CheckResult>(std::shared_ptr<storm::logic::Formula const> const& formula)> formulaChecker); + std::map<std::string, storm::storage::BitVector> computeApSets(std::map<std::string, std::shared_ptr<storm::logic::Formula const>> const& extracted, std::function<std::unique_ptr<CheckResult>(std::shared_ptr<storm::logic::Formula const> const& formula)> formulaChecker); private: diff --git a/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.cpp b/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.cpp index ff41d1a73..7aa519bc6 100644 --- a/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.cpp +++ b/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.cpp @@ -132,6 +132,7 @@ namespace storm { << da->getAPSet().size() << " atomic propositions and " << *da->getAcceptance()->getAcceptanceExpression() << " as acceptance condition."); + // TODO move computation of apSets to SparseLTLHelper (extracted: AP to formula - std::map<std::string, std::shared_ptr<Formula const>>) std::map<std::string, storm::storage::BitVector> apSets; for (std::string const& ap : apSet.getAPs()) { std::shared_ptr<storm::logic::Formula const> expression = pathFormula.getAPMapping().at(ap); @@ -148,6 +149,15 @@ namespace storm { // TODO HOA call LTL helper std::vector<ValueType> numericResult = storm::modelchecker::helper::SparseDtmcPrctlHelper<ValueType>::computeDAProductProbabilities(env, dtmc, std::move(goal), *da, apSets, checkTask.isQualitativeSet()); + // storm::modelchecker::helper::SparseLTLHelper<ValueType, false> helper(dtmc.getTransitionMatrix(), this->getModel().getNumberOfStates()); + // storm::modelchecker::helper::setInformationFromCheckTaskDeterministic(helper, checkTask, dtmc); + + // Compute Satisfaction sets for APs (see above) + // auto formulaChecker = [&] (std::shared_ptr<storm::logic::Formula const> const& formula) {return this->check(*formula); }; + // std::map<std::string, storm::storage::BitVector> apSets = helper.computeApSets(extracted, formulaChecker); + + // std::vector<ValueType> numericResult = helper.computeDAProductProbabilities(env, *da, apSatSets); + return std::unique_ptr<CheckResult>(new ExplicitQuantitativeCheckResult<ValueType>(std::move(numericResult))); } @@ -156,10 +166,10 @@ namespace storm { storm::logic::PathFormula const& pathFormula = checkTask.getFormula(); STORM_LOG_INFO("Extracting maximal state formulas for path formula: " << pathFormula); - - // Maintain a mapping from formula-strings to pairs in order to reuse labels of equivalent (compared as strings) formulas - std::map<std::string, storm::logic::ExtractMaximalStateFormulasVisitor::LabelFormulaPair> extracted; - std::shared_ptr<storm::logic::Formula> ltlFormula = storm::logic::ExtractMaximalStateFormulasVisitor::extract(pathFormula, extracted); + storm::logic::ExtractMaximalStateFormulasVisitor::ApToFormulaMap extracted; + // Maintain a mapping from formula-strings to labels in order to reuse labels of equivalent (compared as strings) formulas + std::map<std::string, std::string> cached; + std::shared_ptr<storm::logic::Formula> ltlFormula = storm::logic::ExtractMaximalStateFormulasVisitor::extract(pathFormula, extracted, cached); const SparseDtmcModelType& dtmc = this->getModel(); diff --git a/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.cpp b/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.cpp index d567100fb..934517663 100644 --- a/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.cpp +++ b/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.cpp @@ -185,10 +185,10 @@ namespace storm { 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_LOG_INFO("Extracting maximal state formulas for path formula: " << pathFormula); - - // Maintain a mapping from formula-strings to pairs in order to reuse labels of equivalent (compared as strings) formulas - std::map<std::string, storm::logic::ExtractMaximalStateFormulasVisitor::LabelFormulaPair> extracted; - std::shared_ptr<storm::logic::Formula> ltlFormula = storm::logic::ExtractMaximalStateFormulasVisitor::extract(pathFormula, extracted); + storm::logic::ExtractMaximalStateFormulasVisitor::ApToFormulaMap extracted; + // Maintain a mapping from formula-strings to labels in order to reuse labels of equivalent (compared as strings) formulas + std::map<std::string, std::string> cached; + std::shared_ptr<storm::logic::Formula> ltlFormula = storm::logic::ExtractMaximalStateFormulasVisitor::extract(pathFormula, extracted, cached); const SparseMdpModelType& mdp = this->getModel(); // TODO ? From bf3894d2f82ffd66bca4131f5a6f8cd56ec09998 Mon Sep 17 00:00:00 2001 From: hannah <hannah.mertens@rwth-aachen.de> Date: Sun, 20 Jun 2021 16:05:29 +0200 Subject: [PATCH 082/172] DA state output --- src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp index 12c1f030c..b1a895ebc 100644 --- a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp +++ b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp @@ -290,10 +290,10 @@ namespace storm { da = storm::automata::LTL2DeterministicAutomaton::ltl2daSpot(*ltlFormula, Nondeterministic); } - STORM_LOG_INFO("Deterministic automaton for LTL formula has " + STORM_PRINT("Deterministic automaton for LTL formula has " << da->getNumberOfStates() << " states, " << da->getAPSet().size() << " atomic propositions and " - << *da->getAcceptance()->getAcceptanceExpression() << " as acceptance condition."); + << *da->getAcceptance()->getAcceptanceExpression() << " as acceptance condition." << std::endl); std::vector<ValueType> numericResult = computeDAProductProbabilities(env, *da, apSatSets); From 4cdd70949c1ebd969d60f585d48b8adfe1ef1013 Mon Sep 17 00:00:00 2001 From: Tim Quatmann <tim.quatmann@cs.rwth-aachen.de> Date: Wed, 23 Jun 2021 06:27:54 +0200 Subject: [PATCH 083/172] FormulaParser: HOA formulas shall only consider state-subformulas --- src/storm-parsers/parser/FormulaParserGrammar.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/storm-parsers/parser/FormulaParserGrammar.cpp b/src/storm-parsers/parser/FormulaParserGrammar.cpp index 6a522051a..18adfc932 100644 --- a/src/storm-parsers/parser/FormulaParserGrammar.cpp +++ b/src/storm-parsers/parser/FormulaParserGrammar.cpp @@ -126,7 +126,7 @@ namespace storm { 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::Path, qi::_r1) )[phoenix::bind(&FormulaParserGrammar::addHoaAPMapping, phoenix::ref(*this), *qi::_val, qi::_1, qi::_2)] + >> *(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"); From ca6b3b8ce2eb8e52661d9fb19ec9be0891a4a46c Mon Sep 17 00:00:00 2001 From: hannah <hannah.mertens@rwth-aachen.de> Date: Wed, 23 Jun 2021 08:44:19 +0200 Subject: [PATCH 084/172] missing include --- src/storm/automata/LTL2DeterministicAutomaton.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/storm/automata/LTL2DeterministicAutomaton.cpp b/src/storm/automata/LTL2DeterministicAutomaton.cpp index bef88aaaf..e2ff2863e 100644 --- a/src/storm/automata/LTL2DeterministicAutomaton.cpp +++ b/src/storm/automata/LTL2DeterministicAutomaton.cpp @@ -4,7 +4,7 @@ #include "storm/logic/Formula.h" #include "storm/utility/macros.h" #include "storm/exceptions/ExpressionEvaluationException.h" -#include "storm/exceptions/WrongFormatException.h" +#include "storm/exceptions/NotSupportedException.h" #include "storm/exceptions/FileIoException.h" #include <sys/wait.h> From d21d2ca7e693c9b74d69d6fa866385853550f252 Mon Sep 17 00:00:00 2001 From: hannah <hannah.mertens@rwth-aachen.de> Date: Wed, 23 Jun 2021 09:24:34 +0200 Subject: [PATCH 085/172] fixed exceptions --- src/storm/automata/APSet.cpp | 13 ++++++------- src/storm/automata/LTL2DeterministicAutomaton.cpp | 2 -- 2 files changed, 6 insertions(+), 9 deletions(-) diff --git a/src/storm/automata/APSet.cpp b/src/storm/automata/APSet.cpp index 937207215..6c136effd 100644 --- a/src/storm/automata/APSet.cpp +++ b/src/storm/automata/APSet.cpp @@ -1,5 +1,7 @@ #include "storm/automata/APSet.h" +#include "storm/exceptions/UnexpectedException.h" +#include "storm/utility/macros.h" #include <string> #include <exception> @@ -20,13 +22,12 @@ namespace storm { } void APSet::add(const std::string& ap) { - if (size() >= MAX_APS) - throw std::runtime_error("Set of atomic proposition size is limited to " + std::to_string(MAX_APS)); + 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; - if (!fresh) - throw std::runtime_error("Duplicate atomic proposition '" + ap + "' in APSet"); + STORM_LOG_THROW(fresh, storm::exceptions::UnexpectedException,"Duplicate atomic proposition '" << ap << "' in APSet"); + index_to_ap.push_back(ap); } @@ -54,9 +55,7 @@ namespace storm { } APSet::alphabet_element APSet::elementAddAP(alphabet_element element, unsigned int ap) const { - if (ap >= size()) { - throw std::runtime_error("AP out of range"); - } + STORM_LOG_THROW(ap < size(), storm::exceptions::UnexpectedException, "AP out of range"); return element | (1ul << ap); } diff --git a/src/storm/automata/LTL2DeterministicAutomaton.cpp b/src/storm/automata/LTL2DeterministicAutomaton.cpp index e2ff2863e..c70158354 100644 --- a/src/storm/automata/LTL2DeterministicAutomaton.cpp +++ b/src/storm/automata/LTL2DeterministicAutomaton.cpp @@ -15,8 +15,6 @@ #include "spot/twaalgos/translate.hh" #include "spot/twaalgos/hoa.hh" #include "spot/twaalgos/totgba.hh" -#include "spot/twaalgos/toparity.hh" -#include "spot/twa/acc.hh" #endif namespace storm { From 4655dc19a17a56f68c483474ad493e8f6da2dd3e Mon Sep 17 00:00:00 2001 From: hannah <hannah.mertens@rwth-aachen.de> Date: Wed, 23 Jun 2021 14:22:55 +0200 Subject: [PATCH 086/172] fixed MDP-LTL test --- .../storm/modelchecker/prctl/mdp/MdpPrctlModelCheckerTest.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/storm/modelchecker/prctl/mdp/MdpPrctlModelCheckerTest.cpp b/src/test/storm/modelchecker/prctl/mdp/MdpPrctlModelCheckerTest.cpp index b49432538..271c59321 100755 --- a/src/test/storm/modelchecker/prctl/mdp/MdpPrctlModelCheckerTest.cpp +++ b/src/test/storm/modelchecker/prctl/mdp/MdpPrctlModelCheckerTest.cpp @@ -775,7 +775,7 @@ namespace { EXPECT_NEAR(this->parseNumber("5/6"), this->getQuantitativeResultAtInitialState(model, result), this->precision()); result = checker->check(this->env(), tasks[4]); - EXPECT_NEAR(this->parseNumber("1/12"), this->getQuantitativeResultAtInitialState(model, result), this->precision()); + EXPECT_NEAR(this->parseNumber("31/36"), this->getQuantitativeResultAtInitialState(model, result), this->precision()); } else { EXPECT_FALSE(checker->canHandle(tasks[0])); From 97c3bdd5a72c46583da2ab293267fee94df8ead3 Mon Sep 17 00:00:00 2001 From: hannah <hannah.mertens@rwth-aachen.de> Date: Sun, 27 Jun 2021 13:35:55 +0200 Subject: [PATCH 087/172] HOA Formula Parser Tests --- src/test/storm/parser/FormulaParserTest.cpp | 63 ++++++++++++++++++++- 1 file changed, 61 insertions(+), 2 deletions(-) diff --git a/src/test/storm/parser/FormulaParserTest.cpp b/src/test/storm/parser/FormulaParserTest.cpp index 22e7e6fd9..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)"; @@ -337,7 +339,6 @@ TEST(FormulaParserTest, TemporalNegationTest) { TEST(FormulaParserTest, ComplexPathFormulaTest) { storm::parser::FormulaParser formulaParser; std::shared_ptr<storm::logic::Formula const> formula(nullptr); - formula = formulaParser.parseSingleFormulaFromString( "P=? [(X \"a\") U ( \"b\"& \"c\")]"); 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)); @@ -352,4 +353,62 @@ TEST(FormulaParserTest, ComplexPathFormulaTest) { 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); } From a88b64bad35544194718fdf535afa3ecb36d5a0f Mon Sep 17 00:00:00 2001 From: hannah <hannah.mertens@rwth-aachen.de> Date: Sun, 27 Jun 2021 15:14:41 +0200 Subject: [PATCH 088/172] DTMC HOA tests --- .../testfiles/hoa/automaton_Fandp0Xp1.hoa | 27 +++++++++++ .../testfiles/hoa/automaton_UXp0p1.hoa | 32 +++++++++++++ .../prctl/dtmc/DtmcPrctlModelCheckerTest.cpp | 48 +++++++++++++++++++ 3 files changed, 107 insertions(+) create mode 100644 resources/examples/testfiles/hoa/automaton_Fandp0Xp1.hoa create mode 100644 resources/examples/testfiles/hoa/automaton_UXp0p1.hoa 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/test/storm/modelchecker/prctl/dtmc/DtmcPrctlModelCheckerTest.cpp b/src/test/storm/modelchecker/prctl/dtmc/DtmcPrctlModelCheckerTest.cpp index d45519900..419f744cc 100755 --- a/src/test/storm/modelchecker/prctl/dtmc/DtmcPrctlModelCheckerTest.cpp +++ b/src/test/storm/modelchecker/prctl/dtmc/DtmcPrctlModelCheckerTest.cpp @@ -808,4 +808,52 @@ namespace { #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) }]"; + + 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()); + } else { + EXPECT_FALSE(checker->canHandle(tasks[0])); + } + + } + } From b49837eb4e89d67f766331e67b301f878cc71bb5 Mon Sep 17 00:00:00 2001 From: hannah <hannah.mertens@rwth-aachen.de> Date: Sun, 27 Jun 2021 16:22:00 +0200 Subject: [PATCH 089/172] use LTLHelper to compute HOAPath Formulas Conflicts: src/storm/modelchecker/AbstractModelChecker.cpp --- .../modelchecker/AbstractModelChecker.cpp | 7 ++++ .../helper/ltl/SparseLTLHelper.cpp | 33 +++++++++--------- .../modelchecker/helper/ltl/SparseLTLHelper.h | 22 ++++++------ .../prctl/SparseDtmcPrctlModelChecker.cpp | 34 +++++-------------- .../prctl/dtmc/DtmcPrctlModelCheckerTest.cpp | 5 +++ 5 files changed, 47 insertions(+), 54 deletions(-) diff --git a/src/storm/modelchecker/AbstractModelChecker.cpp b/src/storm/modelchecker/AbstractModelChecker.cpp index 8e40891f4..f2d880db0 100644 --- a/src/storm/modelchecker/AbstractModelChecker.cpp +++ b/src/storm/modelchecker/AbstractModelChecker.cpp @@ -64,6 +64,12 @@ 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(); + + //TODO if this is not checked first, computeStateFormulaProbabilities(...) is called (hasQualitativeResult true) + if (formula.isHOAPathFormula()) { + return this->computeHOAPathProbabilities(env, checkTask.substituteFormula(formula.asHOAPathFormula())); + } + if (formula.isStateFormula() || formula.hasQualitativeResult()) { return this->computeStateFormulaProbabilities(env, checkTask.substituteFormula(formula)); } @@ -83,6 +89,7 @@ namespace storm { } else if (formula.isUntilFormula()) { return this->computeUntilProbabilities(env, checkTask.substituteFormula(formula.asUntilFormula())); } else if (formula.isHOAPathFormula()) { + // TODO checked earlier? return this->computeHOAPathProbabilities(env, checkTask.substituteFormula(formula.asHOAPathFormula())); } else if (formula.isNextFormula()) { return this->computeNextProbabilities(env, checkTask.substituteFormula(formula.asNextFormula())); diff --git a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp index b1a895ebc..f564c8221 100644 --- a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp +++ b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp @@ -26,6 +26,23 @@ namespace storm { // Intentionally left empty. } + 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, std::function<std::unique_ptr<CheckResult>(std::shared_ptr<storm::logic::Formula const> const& formula)> formulaChecker){ + std::map<std::string, storm::storage::BitVector> apSets; + for (auto& p: extracted) { + STORM_LOG_INFO(" Computing satisfaction set for atomic proposition \"" << p.first << "\" <=> " << *p.second << "..."); + + std::unique_ptr<CheckResult> subResultPointer = formulaChecker(p.second); + + ExplicitQualitativeCheckResult const& subResult = subResultPointer->asExplicitQualitativeCheckResult(); + auto sat = subResult.getTruthValuesVector(); + + apSets[p.first] = std::move(sat); + STORM_LOG_INFO(" Atomic proposition \"" << p.first << "\" is satisfied by " << sat.getNumberOfSetBits() << " states."); + } + 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) { @@ -308,22 +325,6 @@ namespace storm { return numericResult; } - 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, std::function<std::unique_ptr<CheckResult>(std::shared_ptr<storm::logic::Formula const> const& formula)> formulaChecker){ - std::map<std::string, storm::storage::BitVector> apSets; - for (auto& p: extracted) { - STORM_LOG_INFO(" Computing satisfaction set for atomic proposition \"" << p.first << "\" <=> " << *p.second << "..."); - - std::unique_ptr<CheckResult> subResultPointer = formulaChecker(p.second); - - ExplicitQualitativeCheckResult const& subResult = subResultPointer->asExplicitQualitativeCheckResult(); - auto sat = subResult.getTruthValuesVector(); - - apSets[p.first] = std::move(sat); - STORM_LOG_INFO(" Atomic proposition \"" << p.first << "\" is satisfied by " << sat.getNumberOfSetBits() << " states."); - } - return apSets; - } template class SparseLTLHelper<double, false>; template class SparseLTLHelper<double, true>; diff --git a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h index 71760e717..c5e2a9c33 100644 --- a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h +++ b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h @@ -34,25 +34,14 @@ namespace storm { */ SparseLTLHelper(storm::storage::SparseMatrix<ValueType> const& transitionMatrix, std::size_t numberOfSates); - - /*! - * Computes the LTL probabilities - * @param the LTL formula - * @param the atomic propositions and satisfaction sets - * @return a value for each state - */ - std::vector<ValueType> computeLTLProbabilities(Environment const &env, storm::logic::Formula const& formula, std::map<std::string, storm::storage::BitVector>& apSatSets); - /*! * todo computes Sat sets of AP * @param * @param * @return */ - std::map<std::string, storm::storage::BitVector> computeApSets(std::map<std::string, std::shared_ptr<storm::logic::Formula const>> const& extracted, std::function<std::unique_ptr<CheckResult>(std::shared_ptr<storm::logic::Formula const> const& formula)> formulaChecker); - + static std::map<std::string, storm::storage::BitVector> computeApSets(std::map<std::string, std::shared_ptr<storm::logic::Formula const>> const& extracted, std::function<std::unique_ptr<CheckResult>(std::shared_ptr<storm::logic::Formula const> const& formula)> formulaChecker); - private: /*! * Computes the (maximizing) probabilities for the constructed DA product * @param the DA to build the product with @@ -62,6 +51,15 @@ namespace storm { */ 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 the LTL formula + * @param the atomic propositions and satisfaction sets + * @return a value for each state + */ + std::vector<ValueType> computeLTLProbabilities(Environment const &env, storm::logic::Formula const& formula, std::map<std::string, storm::storage::BitVector>& apSatSets); + + private: /*! * Compute a set S of states that admit a probability 1 strategy of satisfying the given acceptance condition (in DNF). diff --git a/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.cpp b/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.cpp index 7aa519bc6..ade41c728 100644 --- a/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.cpp +++ b/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.cpp @@ -125,39 +125,22 @@ namespace storm { storm::logic::HOAPathFormula const& pathFormula = checkTask.getFormula(); STORM_LOG_INFO("Obtaining HOA automaton..."); storm::automata::DeterministicAutomaton::ptr da = pathFormula.readAutomaton(); - const storm::automata::APSet& apSet = da->getAPSet(); STORM_LOG_INFO("Deterministic automaton from HOA file has " << da->getNumberOfStates() << " states, " << da->getAPSet().size() << " atomic propositions and " << *da->getAcceptance()->getAcceptanceExpression() << " as acceptance condition."); - // TODO move computation of apSets to SparseLTLHelper (extracted: AP to formula - std::map<std::string, std::shared_ptr<Formula const>>) - std::map<std::string, storm::storage::BitVector> apSets; - for (std::string const& ap : apSet.getAPs()) { - std::shared_ptr<storm::logic::Formula const> expression = pathFormula.getAPMapping().at(ap); - STORM_LOG_INFO("Computing satisfaction set for atomic proposition \"" << ap << "\" <=> " << *expression << "..."); - std::unique_ptr<CheckResult> resultPointer = this->check(*expression); - ExplicitQualitativeCheckResult const& result = resultPointer->asExplicitQualitativeCheckResult(); - storm::storage::BitVector bitVector = result.getTruthValuesVector(); - STORM_LOG_INFO("Atomic proposition \"" << ap << "\" is satisfied by " << bitVector.getNumberOfSetBits() << " states."); - apSets[ap] = std::move(bitVector); - } - const SparseDtmcModelType& dtmc = this->getModel(); - storm::solver::SolveGoal<ValueType> goal(dtmc, checkTask); - - // TODO HOA call LTL helper - std::vector<ValueType> numericResult = storm::modelchecker::helper::SparseDtmcPrctlHelper<ValueType>::computeDAProductProbabilities(env, dtmc, std::move(goal), *da, apSets, checkTask.isQualitativeSet()); - // storm::modelchecker::helper::SparseLTLHelper<ValueType, false> helper(dtmc.getTransitionMatrix(), this->getModel().getNumberOfStates()); - // storm::modelchecker::helper::setInformationFromCheckTaskDeterministic(helper, checkTask, dtmc); - - // Compute Satisfaction sets for APs (see above) - // auto formulaChecker = [&] (std::shared_ptr<storm::logic::Formula const> const& formula) {return this->check(*formula); }; - // std::map<std::string, storm::storage::BitVector> apSets = helper.computeApSets(extracted, formulaChecker); + storm::modelchecker::helper::SparseLTLHelper<ValueType, false> helper(dtmc.getTransitionMatrix(), dtmc.getNumberOfStates()); + storm::modelchecker::helper::setInformationFromCheckTaskDeterministic(helper, checkTask, dtmc); - // std::vector<ValueType> numericResult = helper.computeDAProductProbabilities(env, *da, apSatSets); + // Compute Satisfaction sets for APs + storm::logic::ExtractMaximalStateFormulasVisitor::ApToFormulaMap extracted = pathFormula.getAPMapping(); + auto formulaChecker = [&] (std::shared_ptr<storm::logic::Formula const> const& formula) {return this->check(*formula); }; + std::map<std::string, storm::storage::BitVector> apSets = helper.computeApSets(extracted, formulaChecker); + std::vector<ValueType> numericResult = helper.computeDAProductProbabilities(env, *da, apSets); return std::unique_ptr<CheckResult>(new ExplicitQuantitativeCheckResult<ValueType>(std::move(numericResult))); } @@ -180,7 +163,7 @@ namespace storm { dtmc.writeDotToStream(modelDot); modelDot.close(); } - + storm::modelchecker::helper::SparseLTLHelper<ValueType, false> helper(dtmc.getTransitionMatrix(), this->getModel().getNumberOfStates()); storm::modelchecker::helper::setInformationFromCheckTaskDeterministic(helper, checkTask, dtmc); @@ -189,7 +172,6 @@ namespace storm { std::map<std::string, storm::storage::BitVector> apSets = helper.computeApSets(extracted, formulaChecker); std::vector<ValueType> numericResult = helper.computeLTLProbabilities(env, *ltlFormula, apSets); - return std::unique_ptr<CheckResult>(new ExplicitQuantitativeCheckResult<ValueType>(std::move(numericResult))); } diff --git a/src/test/storm/modelchecker/prctl/dtmc/DtmcPrctlModelCheckerTest.cpp b/src/test/storm/modelchecker/prctl/dtmc/DtmcPrctlModelCheckerTest.cpp index 419f744cc..1fa6f4159 100755 --- a/src/test/storm/modelchecker/prctl/dtmc/DtmcPrctlModelCheckerTest.cpp +++ b/src/test/storm/modelchecker/prctl/dtmc/DtmcPrctlModelCheckerTest.cpp @@ -821,6 +821,8 @@ namespace { 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); @@ -850,6 +852,9 @@ namespace { 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])); } From 5cc5057cd60064747fa69ae2fe8b13db54678366 Mon Sep 17 00:00:00 2001 From: hannah <hannah.mertens@rwth-aachen.de> Date: Mon, 28 Jun 2021 07:56:49 +0200 Subject: [PATCH 090/172] removed unused function --- .../prctl/SparseDtmcPrctlModelChecker.cpp | 2 +- .../prctl/helper/SparseDtmcPrctlHelper.cpp | 92 ------------------- .../prctl/helper/SparseDtmcPrctlHelper.h | 2 - 3 files changed, 1 insertion(+), 95 deletions(-) diff --git a/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.cpp b/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.cpp index ade41c728..cd2422f2b 100644 --- a/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.cpp +++ b/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.cpp @@ -163,7 +163,7 @@ namespace storm { dtmc.writeDotToStream(modelDot); modelDot.close(); } - + storm::modelchecker::helper::SparseLTLHelper<ValueType, false> helper(dtmc.getTransitionMatrix(), this->getModel().getNumberOfStates()); storm::modelchecker::helper::setInformationFromCheckTaskDeterministic(helper, checkTask, dtmc); diff --git a/src/storm/modelchecker/prctl/helper/SparseDtmcPrctlHelper.cpp b/src/storm/modelchecker/prctl/helper/SparseDtmcPrctlHelper.cpp index 2bcc9478a..b9749ca55 100644 --- a/src/storm/modelchecker/prctl/helper/SparseDtmcPrctlHelper.cpp +++ b/src/storm/modelchecker/prctl/helper/SparseDtmcPrctlHelper.cpp @@ -313,98 +313,6 @@ namespace storm { multiplier->multiply(env, result, nullptr, result); return result; } - - template<typename ValueType, typename RewardModelType> - std::vector<ValueType> SparseDtmcPrctlHelper<ValueType, RewardModelType>::computeDAProductProbabilities(Environment const& env, typename storm::models::sparse::Dtmc<ValueType,RewardModelType> const& dtmc, storm::solver::SolveGoal<ValueType>&& goal, storm::automata::DeterministicAutomaton const& da, std::map<std::string, storm::storage::BitVector>& apSatSets, bool qualitative) { - const storm::automata::APSet& apSet = da.getAPSet(); - - std::vector<storm::storage::BitVector> apLabels; - 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"); - - apLabels.push_back(std::move(it->second)); - } - - storm::storage::BitVector statesOfInterest; - if (goal.hasRelevantValues()) { - statesOfInterest = goal.relevantValues(); - } else { - // product from all model states - statesOfInterest = storm::storage::BitVector(dtmc.getNumberOfStates(), true); - } - - STORM_LOG_INFO("Building DTMC-DA product with deterministic automaton, starting from " << statesOfInterest.getNumberOfSetBits() << " model states..."); - storm::transformer::DAProductBuilder productBuilder(da, apLabels); - auto product = productBuilder.build(dtmc, statesOfInterest); - STORM_LOG_INFO("Product DTMC has " << product->getProductModel().getNumberOfStates() << " states and " - << product->getProductModel().getNumberOfTransitions() << " transitions."); - - if (storm::settings::getModule<storm::settings::modules::DebugSettings>().isTraceSet()) { - STORM_LOG_TRACE("Writing model to model.dot"); - std::ofstream modelDot("model.dot"); - dtmc.writeDotToStream(modelDot); - modelDot.close(); - - STORM_LOG_TRACE("Writing product model to product.dot"); - std::ofstream productDot("product.dot"); - product->getProductModel().writeDotToStream(productDot); - productDot.close(); - - STORM_LOG_TRACE("Product model mapping:"); - std::stringstream str; - product->printMapping(str); - STORM_LOG_TRACE(str.str()); - } - - STORM_LOG_INFO("Computing BSCCs and checking for acceptance..."); - - storm::storage::StronglyConnectedComponentDecomposition<ValueType> bottomSccs(product->getProductModel().getTransitionMatrix(), - storage::StronglyConnectedComponentDecompositionOptions().onlyBottomSccs().dropNaiveSccs()); - storm::storage::BitVector acceptingBSCC(product->getProductModel().getNumberOfStates()); - std::size_t checkedBSCCs = 0, acceptingBSCCs = 0, acceptingBSCCStates = 0; - for (auto& scc : bottomSccs) { - checkedBSCCs++; - if (product->getAcceptance()->isAccepting(scc)) { - acceptingBSCCs++; - for (auto& state : scc) { - acceptingBSCC.set(state); - acceptingBSCCStates++; - } - } - } - - STORM_LOG_INFO("BSCC analysis: " << acceptingBSCCs << " of " << checkedBSCCs << " BSCCs were accepting (" << acceptingBSCCStates << " states in accepting BSCCs)."); - - if (acceptingBSCCs == 0) { - STORM_LOG_INFO("No accepting BSCCs, skipping probability computation."); - std::vector<ValueType> numericResult(dtmc.getNumberOfStates(), storm::utility::zero<ValueType>()); - return numericResult; - } - - STORM_LOG_INFO("Computing probabilities for reaching accepting BSCCs..."); - - storm::storage::BitVector bvTrue(product->getProductModel().getNumberOfStates(), true); - - storm::solver::SolveGoal<ValueType> solveGoalProduct(goal); - storm::storage::BitVector soiProduct(product->getStatesOfInterest()); - solveGoalProduct.setRelevantValues(std::move(soiProduct)); - - std::vector<ValueType> prodNumericResult - = storm::modelchecker::helper::SparseDtmcPrctlHelper<ValueType>::computeUntilProbabilities(env, - std::move(solveGoalProduct), - product->getProductModel().getTransitionMatrix(), - product->getProductModel().getBackwardTransitions(), - bvTrue, - acceptingBSCC, - qualitative); - - std::vector<ValueType> numericResult = product->projectToOriginalModel(dtmc, prodNumericResult); - return numericResult; - } - - - 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) { diff --git a/src/storm/modelchecker/prctl/helper/SparseDtmcPrctlHelper.h b/src/storm/modelchecker/prctl/helper/SparseDtmcPrctlHelper.h index 4af089f9b..aaea5b7c1 100644 --- a/src/storm/modelchecker/prctl/helper/SparseDtmcPrctlHelper.h +++ b/src/storm/modelchecker/prctl/helper/SparseDtmcPrctlHelper.h @@ -48,8 +48,6 @@ namespace storm { 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> computeDAProductProbabilities(Environment const& env, typename storm::models::sparse::Dtmc<ValueType,RewardModelType> const& dtmc, storm::solver::SolveGoal<ValueType>&& goal, storm::automata::DeterministicAutomaton const& da, std::map<std::string, storm::storage::BitVector>& apSatSets, 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); From 113f17372f3088d04150027d4b555606bd4d8d68 Mon Sep 17 00:00:00 2001 From: hannah <hannah.mertens@rwth-aachen.de> Date: Tue, 29 Jun 2021 08:19:22 +0200 Subject: [PATCH 091/172] set hasQualitativeResult to false for HOAFormulas --- src/storm/logic/HOAPathFormula.cpp | 4 ++++ src/storm/logic/HOAPathFormula.h | 1 + src/storm/modelchecker/AbstractModelChecker.cpp | 6 ------ 3 files changed, 5 insertions(+), 6 deletions(-) diff --git a/src/storm/logic/HOAPathFormula.cpp b/src/storm/logic/HOAPathFormula.cpp index cd17a6a46..b5dc17d27 100644 --- a/src/storm/logic/HOAPathFormula.cpp +++ b/src/storm/logic/HOAPathFormula.cpp @@ -43,6 +43,10 @@ namespace storm { 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); } diff --git a/src/storm/logic/HOAPathFormula.h b/src/storm/logic/HOAPathFormula.h index fd9ba1a93..53fcc1120 100644 --- a/src/storm/logic/HOAPathFormula.h +++ b/src/storm/logic/HOAPathFormula.h @@ -32,6 +32,7 @@ namespace storm { 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; diff --git a/src/storm/modelchecker/AbstractModelChecker.cpp b/src/storm/modelchecker/AbstractModelChecker.cpp index f2d880db0..fc1534585 100644 --- a/src/storm/modelchecker/AbstractModelChecker.cpp +++ b/src/storm/modelchecker/AbstractModelChecker.cpp @@ -65,11 +65,6 @@ namespace storm { std::unique_ptr<CheckResult> AbstractModelChecker<ModelType>::computeProbabilities(Environment const& env, CheckTask<storm::logic::Formula, ValueType> const& checkTask) { storm::logic::Formula const& formula = checkTask.getFormula(); - //TODO if this is not checked first, computeStateFormulaProbabilities(...) is called (hasQualitativeResult true) - if (formula.isHOAPathFormula()) { - return this->computeHOAPathProbabilities(env, checkTask.substituteFormula(formula.asHOAPathFormula())); - } - if (formula.isStateFormula() || formula.hasQualitativeResult()) { return this->computeStateFormulaProbabilities(env, checkTask.substituteFormula(formula)); } @@ -89,7 +84,6 @@ namespace storm { } else if (formula.isUntilFormula()) { return this->computeUntilProbabilities(env, checkTask.substituteFormula(formula.asUntilFormula())); } else if (formula.isHOAPathFormula()) { - // TODO checked earlier? return this->computeHOAPathProbabilities(env, checkTask.substituteFormula(formula.asHOAPathFormula())); } else if (formula.isNextFormula()) { return this->computeNextProbabilities(env, checkTask.substituteFormula(formula.asNextFormula())); From 7455bd8e00b7388391838e5b1c034b0d2dcc7e01 Mon Sep 17 00:00:00 2001 From: Tim Quatmann <tim.quatmann@cs.rwth-aachen.de> Date: Thu, 1 Jul 2021 12:29:43 +0200 Subject: [PATCH 092/172] add missing include --- src/storm/environment/modelchecker/ModelCheckerEnvironment.h | 1 + 1 file changed, 1 insertion(+) diff --git a/src/storm/environment/modelchecker/ModelCheckerEnvironment.h b/src/storm/environment/modelchecker/ModelCheckerEnvironment.h index 416172a36..b5bca9835 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" From f596d7f4868375dc177b693259011ad5de17252e Mon Sep 17 00:00:00 2001 From: hannah <hannah.mertens@rwth-aachen.de> Date: Mon, 5 Jul 2021 09:23:01 +0200 Subject: [PATCH 093/172] fixed output --- src/storm/automata/LTL2DeterministicAutomaton.cpp | 1 + src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/src/storm/automata/LTL2DeterministicAutomaton.cpp b/src/storm/automata/LTL2DeterministicAutomaton.cpp index c70158354..52e1192f0 100644 --- a/src/storm/automata/LTL2DeterministicAutomaton.cpp +++ b/src/storm/automata/LTL2DeterministicAutomaton.cpp @@ -47,6 +47,7 @@ namespace storm { aut = to_generalized_rabin(aut,true); } + STORM_LOG_INFO("The deterministic automaton has acceptance condition: "<< aut->get_acceptance()); STORM_LOG_INFO(aut->get_acceptance()); diff --git a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp index f564c8221..d80f4a64f 100644 --- a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp +++ b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp @@ -38,7 +38,7 @@ namespace storm { auto sat = subResult.getTruthValuesVector(); apSets[p.first] = std::move(sat); - STORM_LOG_INFO(" Atomic proposition \"" << p.first << "\" is satisfied by " << sat.getNumberOfSetBits() << " states."); + STORM_LOG_INFO(" Atomic proposition \"" << p.first << "\" is satisfied by " << apSets[p.first].getNumberOfSetBits() << " states."); } return apSets; } From 08c454f124c7a768da0851c0168171e0b17eabed Mon Sep 17 00:00:00 2001 From: hannah <hannah.mertens@rwth-aachen.de> Date: Mon, 5 Jul 2021 12:38:12 +0200 Subject: [PATCH 094/172] scheduler support for LTL-MC Conflicts: src/storm/storage/Scheduler.cpp --- .../SparseMarkovAutomatonCslModelChecker.cpp | 2 +- .../helper/ltl/SparseLTLHelper.cpp | 129 +++++++++++++++--- .../modelchecker/helper/ltl/SparseLTLHelper.h | 21 ++- .../prctl/SparseDtmcPrctlModelChecker.cpp | 2 +- .../prctl/SparseMdpPrctlModelChecker.cpp | 11 +- .../prctl/helper/SparseDtmcPrctlHelper.h | 4 - src/storm/storage/Scheduler.cpp | 4 + .../SparseModelMemoryProduct.cpp | 2 +- src/storm/transformer/DAProductBuilder.h | 2 +- src/storm/transformer/ProductBuilder.h | 1 - ...ulerGenerationMdpPrctlModelCheckerTest.cpp | 53 +++++++ 11 files changed, 199 insertions(+), 32 deletions(-) diff --git a/src/storm/modelchecker/csl/SparseMarkovAutomatonCslModelChecker.cpp b/src/storm/modelchecker/csl/SparseMarkovAutomatonCslModelChecker.cpp index 6de3d079d..641882d27 100644 --- a/src/storm/modelchecker/csl/SparseMarkovAutomatonCslModelChecker.cpp +++ b/src/storm/modelchecker/csl/SparseMarkovAutomatonCslModelChecker.cpp @@ -144,7 +144,7 @@ namespace storm { modelDot.close(); } - storm::modelchecker::helper::SparseLTLHelper<ValueType, true> helper(embeddedMdp.getTransitionMatrix(), this->getModel().getNumberOfStates()); + storm::modelchecker::helper::SparseLTLHelper<ValueType, true> helper(embeddedMdp.getTransitionMatrix(), embeddedMdp.getNumberOfStates()); storm::modelchecker::helper::setInformationFromCheckTaskNondeterministic(helper, checkTask, embeddedMdp); // Compute Satisfaction sets for APs diff --git a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp index d80f4a64f..8a59e5252 100644 --- a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp +++ b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp @@ -1,8 +1,5 @@ -#include <modelchecker/results/ExplicitQualitativeCheckResult.h> -#include <logic/ExtractMaximalStateFormulasVisitor.h> #include "SparseLTLHelper.h" -#include "storm/transformer/DAProductBuilder.h" #include "storm/automata/LTL2DeterministicAutomaton.h" #include "storm/modelchecker/prctl/helper/SparseDtmcPrctlHelper.h" @@ -10,6 +7,8 @@ #include "storm/storage/StronglyConnectedComponentDecomposition.h" #include "storm/storage/MaximalEndComponentDecomposition.h" +#include "storm/storage/memorystructure/MemoryStructure.h" +#include "storm/storage/memorystructure/MemoryStructureBuilder.h" #include "storm/settings/SettingsManager.h" #include "storm/settings/modules/DebugSettings.h" @@ -22,10 +21,59 @@ namespace storm { namespace helper { template <typename ValueType, bool Nondeterministic> - SparseLTLHelper<ValueType, Nondeterministic>::SparseLTLHelper(storm::storage::SparseMatrix<ValueType> const& transitionMatrix, std::size_t numberOfStates) : _transitionMatrix(transitionMatrix), _numberOfStates(numberOfStates) { + SparseLTLHelper<ValueType, Nondeterministic>::SparseLTLHelper(storm::storage::SparseMatrix<ValueType> const& transitionMatrix, std::size_t numberOfStates) : _transitionMatrix(transitionMatrix), _numberOfStates(numberOfStates){ // 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->_productChoices.is_initialized(), "Trying to extract the produced scheduler but none is available. Was there a computation call before?"); + STORM_LOG_ASSERT(this->_memoryTransitions.is_initialized(), "Trying to extract the DA transition structure but none is available. Was there a computation call before?"); + STORM_LOG_ASSERT(this->_memoryInitialStates.is_initialized(), "Trying to extract the initial states of the DA but there are none available. Was there a computation call before?"); + + // Create a memory structure for the MDP scheduler with memory. + typename storm::storage::MemoryStructureBuilder<ValueType>::MemoryStructureBuilder memoryBuilder(this->_memoryTransitions.get().size(), model); + + // Build the transitions between the memory states: startState--- modelStates (transitionVector) --->goalState + for (storm::storage::sparse::state_type startState = 0; startState < this->_memoryTransitions.get().size(); ++startState) { + for (storm::storage::sparse::state_type goalState = 0; goalState < this->_memoryTransitions.get().size(); ++goalState) { + // Bitvector that represents modelStates the model states that trigger this transition. + memoryBuilder.setTransition(startState, goalState, this->_memoryTransitions.get()[startState][goalState]); + } + } + + /* + memoryStateLabeling: Label the memory states to specify, e.g., accepting states // TODO where are these labels used? + for (storm::storage::sparse::state_type q : set) { + memoryBuilder.setLabel(q,//todo); + } + */ + + // initialMemoryStates: Assign an initial memory state to each initial state of the model. + for (uint_fast64_t s0 : model.getInitialStates()) { + // Label the state as initial TODO unnecessary? + //memoryBuilder.setLabel(q, "Initial for model state " s0) + memoryBuilder.setInitialMemoryState(s0, this->_memoryInitialStates.get()[s0]); + } + + + // Finally, we can build the memoryStructure. + storm::storage::MemoryStructure memoryStructure = memoryBuilder.build(); + + // Create a scheduler (with memory of size DA) for the model from the scheduler of the MDP-DA-product model. + storm::storage::Scheduler<ValueType> scheduler(this->_transitionMatrix.getRowGroupCount(), memoryStructure); + + // Use choices in the product model to create a choice based on model state and memory state + for (const auto &choice : this->_productChoices.get()) { + uint_fast64_t modelState = choice.first.first; + uint_fast64_t memoryState = choice.first.second; + scheduler.setChoice(choice.second, modelState, memoryState); + } + + return scheduler; + } 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, std::function<std::unique_ptr<CheckResult>(std::shared_ptr<storm::logic::Formula const> const& formula)> formulaChecker){ std::map<std::string, storm::storage::BitVector> apSets; @@ -141,7 +189,10 @@ namespace storm { if (accepting) { accMECs++; STORM_LOG_DEBUG("MEC is accepting"); + for (auto const& stateChoicePair : mec) { + // TODO extend scheduler by mec choices (which?) + // need adversary which forces (to remain in mec and) to visit all states of the mec inf. often with prob. 1 acceptingStates.set(stateChoicePair.first); } } @@ -180,12 +231,13 @@ namespace storm { 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> apLabels; + + 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"); - apLabels.push_back(std::move(it->second)); + statesForAP.push_back(std::move(it->second)); } storm::storage::BitVector statesOfInterest; @@ -199,9 +251,10 @@ namespace storm { STORM_LOG_INFO("Building "+ (Nondeterministic ? std::string("MDP-DA") : std::string("DTMC-DA")) +"product with deterministic automaton, starting from " << statesOfInterest.getNumberOfSetBits() << " model states..."); - storm::transformer::DAProductBuilder productBuilder(da, apLabels); + transformer::DAProductBuilder productBuilder(da, statesForAP); + + typename transformer::DAProduct<productModelType>::ptr product = productBuilder.build<productModelType>(this->_transitionMatrix, statesOfInterest); - 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."); @@ -254,15 +307,56 @@ namespace storm { if (Nondeterministic) { - prodNumericResult = std::move(storm::modelchecker::helper::SparseMdpPrctlHelper<ValueType>::computeUntilProbabilities(env, - std::move(solveGoalProduct), - product->getProductModel().getTransitionMatrix(), - product->getProductModel().getBackwardTransitions(), - bvTrue, - acceptingStates, - this->isQualitativeSet(), - false // no schedulers (at the moment) - ).values); + 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()) { + // Extract the choices of the scheduler for the MDP-DA product: <s,q> -> choice + this->_productChoices.emplace(); + for (storm::storage::sparse::state_type pState = 0; + pState < product->getProductModel().getNumberOfStates(); ++pState) { + this->_productChoices.get().insert({std::make_pair(product->getModelState(pState), product->getAutomatonState(pState)), prodCheckResult.scheduler->getChoice(pState)}); + } + + + // Prepare the memory structure. For that, we need: transitions, initialMemoryStates (and todo: memoryStateLabeling) + + // The next move function of the memory, will be build based on the transitions of the DA. + this->_memoryTransitions.emplace(da.getNumberOfStates(), std::vector<storm::storage::BitVector>(da.getNumberOfStates())); + + for (storm::storage::sparse::state_type startState = 0; startState < da.getNumberOfStates(); ++startState) { + for (storm::storage::sparse::state_type goalState = 0; + goalState < da.getNumberOfStates(); ++goalState) { + // Bitvector that represents modelStates the model states that trigger this transition. + storm::storage::BitVector modelStates(this->_transitionMatrix.getRowGroupCount(), false); + for (storm::storage::sparse::state_type modelState = 0; + modelState < this->_transitionMatrix.getRowGroupCount(); ++modelState) { + if (goalState == productBuilder.getSuccessor(modelState, startState, modelState)) { + modelStates.set(modelState); + } + } + // Insert a transition: startState--{modelStates}-->goalState + this->_memoryTransitions.get()[startState][goalState] = std::move(modelStates); + } + } + + this->_memoryInitialStates.emplace(); + this->_memoryInitialStates->resize(this->_transitionMatrix.getRowGroupCount()); + // Save for each automaton state for which model state it is initial. + for (storm::storage::sparse::state_type modelState = 0; modelState< this->_transitionMatrix.getRowGroupCount(); ++modelState) { + this->_memoryInitialStates.get().at(modelState) = productBuilder.getInitialState(modelState); + } + + // TODO labels (e.g. the accepting set?) for the automaton states + } } else { prodNumericResult = storm::modelchecker::helper::SparseDtmcPrctlHelper<ValueType>::computeUntilProbabilities(env, @@ -275,6 +369,7 @@ namespace storm { } std::vector<ValueType> numericResult = product->projectToOriginalModel(this->_numberOfStates, prodNumericResult); + return numericResult; } diff --git a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h index c5e2a9c33..3df887979 100644 --- a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h +++ b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h @@ -1,10 +1,12 @@ #include "storm/modelchecker/helper/SingleValueModelCheckerHelper.h" +#include "storm/modelchecker/results/ExplicitQualitativeCheckResult.h" #include "storm/automata/DeterministicAutomaton.h" #include "storm/storage/SparseMatrix.h" #include "storm/solver/SolveGoal.h" #include "storm/models/sparse/Dtmc.h" #include "storm/models/sparse/Mdp.h" #include "storm/logic/ExtractMaximalStateFormulasVisitor.h" +#include "storm/transformer/DAProductBuilder.h" namespace storm { @@ -34,6 +36,14 @@ namespace storm { */ SparseLTLHelper(storm::storage::SparseMatrix<ValueType> const& transitionMatrix, std::size_t numberOfSates); + + /*! + * @pre before calling this, a computation call should have been performed during which scheduler production was enabled. + * @param TODO + * @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); + /*! * todo computes Sat sets of AP * @param @@ -73,18 +83,23 @@ namespace storm { * @param the transition matrix of the model * @param the reversed transition relation */ - static storm::storage::BitVector computeAcceptingECs(automata::AcceptanceCondition const& acceptance, storm::storage::SparseMatrix<ValueType> const& transitionMatrix, storm::storage::SparseMatrix<ValueType> const& backwardTransitions); + storm::storage::BitVector computeAcceptingECs(automata::AcceptanceCondition const& acceptance, storm::storage::SparseMatrix<ValueType> const& transitionMatrix, storm::storage::SparseMatrix<ValueType> const& backwardTransitions); /** * Compute a set S of states that are contained in BSCCs that satisfy the given acceptance conditon. * @tparam the acceptance condition * @tparam the transition matrix of the model */ - static storm::storage::BitVector computeAcceptingBCCs(automata::AcceptanceCondition const& acceptance, storm::storage::SparseMatrix<ValueType> const& transitionMatrix); + storm::storage::BitVector computeAcceptingBCCs(automata::AcceptanceCondition const& acceptance, storm::storage::SparseMatrix<ValueType> const& transitionMatrix); storm::storage::SparseMatrix<ValueType> const& _transitionMatrix; - std::size_t _numberOfStates; + std::size_t _numberOfStates; //TODO just use _transitionMatrix.getRowGroupCount instead? + + // scheduler + boost::optional<std::map<std::pair<uint_fast64_t, uint_fast64_t>, storm::storage::SchedulerChoice<ValueType>>> _productChoices; // <s, q> --> choice + boost::optional<std::vector<std::vector<storm::storage::BitVector>>> _memoryTransitions; // BitVector contains the model states that lead from startState to goalSate of teh DA + boost::optional<std::vector<uint_fast64_t>> _memoryInitialStates; // Saves for each modelState which automaton state is reached from the initial state //TODO improve }; } diff --git a/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.cpp b/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.cpp index cd2422f2b..2e14c8fdb 100644 --- a/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.cpp +++ b/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.cpp @@ -164,7 +164,7 @@ namespace storm { modelDot.close(); } - storm::modelchecker::helper::SparseLTLHelper<ValueType, false> helper(dtmc.getTransitionMatrix(), this->getModel().getNumberOfStates()); + storm::modelchecker::helper::SparseLTLHelper<ValueType, false> helper(dtmc.getTransitionMatrix(), dtmc.getNumberOfStates()); storm::modelchecker::helper::setInformationFromCheckTaskDeterministic(helper, checkTask, dtmc); // Compute Satisfaction sets for APs diff --git a/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.cpp b/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.cpp index 934517663..1d68b1d1f 100644 --- a/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.cpp +++ b/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.cpp @@ -14,9 +14,7 @@ #include "storm/logic/FragmentSpecification.h" -#include "storm/transformer/DAProductBuilder.h" #include "storm/logic/ExtractMaximalStateFormulasVisitor.h" -#include "storm/automata/LTL2DeterministicAutomaton.h" #include "storm/models/sparse/StandardRewardModel.h" @@ -199,6 +197,7 @@ namespace storm { modelDot.close(); } + storm::modelchecker::helper::SparseLTLHelper<ValueType, true> helper(mdp.getTransitionMatrix(), mdp.getNumberOfStates()); storm::modelchecker::helper::setInformationFromCheckTaskNondeterministic(helper, checkTask, mdp); @@ -208,7 +207,13 @@ namespace storm { std::vector<ValueType> numericResult = helper.computeLTLProbabilities(env, *ltlFormula, apSets); - return std::unique_ptr<CheckResult>(new ExplicitQuantitativeCheckResult<ValueType>(std::move(numericResult))); + //TODO for MA too + 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(mdp))); + } + + return result; } template<typename SparseMdpModelType> diff --git a/src/storm/modelchecker/prctl/helper/SparseDtmcPrctlHelper.h b/src/storm/modelchecker/prctl/helper/SparseDtmcPrctlHelper.h index aaea5b7c1..97741d709 100644 --- a/src/storm/modelchecker/prctl/helper/SparseDtmcPrctlHelper.h +++ b/src/storm/modelchecker/prctl/helper/SparseDtmcPrctlHelper.h @@ -19,10 +19,6 @@ namespace storm { // fwd class Environment; - namespace automata { - class DeterministicAutomaton; - } - namespace models { namespace sparse { template <typename ValueType, typename RewardModelType> class Dtmc; diff --git a/src/storm/storage/Scheduler.cpp b/src/storm/storage/Scheduler.cpp index 0582fdd76..1c3d6c895 100644 --- a/src/storm/storage/Scheduler.cpp +++ b/src/storm/storage/Scheduler.cpp @@ -224,6 +224,10 @@ namespace storm { out << "Skipped " << numOfSkippedStatesWithUniqueChoice << " deterministic states with unique choice." << std::endl; } out << "___________________________________________________________________" << std::endl; + + // TODO only for tests: + out << memoryStructure->toString(); + out << std::endl; } template <> diff --git a/src/storm/storage/memorystructure/SparseModelMemoryProduct.cpp b/src/storm/storage/memorystructure/SparseModelMemoryProduct.cpp index 029387288..31708544d 100644 --- a/src/storm/storage/memorystructure/SparseModelMemoryProduct.cpp +++ b/src/storm/storage/memorystructure/SparseModelMemoryProduct.cpp @@ -288,7 +288,7 @@ namespace storm { uint64_t transitionId = entryIt - model.getTransitionMatrix().begin(); uint64_t successorMemoryState = memorySuccessors[transitionId * memoryStateCount + memoryState]; builder.addNextValue(currentRow, getResultState(entryIt->getColumn(), successorMemoryState), entryIt->getValue()); - } + } //TODO successor MemoryState is a problem here 8382838738483264 oder so } else { std::map<uint64_t, ValueType> transitions; for (auto const& choiceIndex : choice.getChoiceAsDistribution()) { diff --git a/src/storm/transformer/DAProductBuilder.h b/src/storm/transformer/DAProductBuilder.h index a6a53f9bd..7c882b3e8 100644 --- a/src/storm/transformer/DAProductBuilder.h +++ b/src/storm/transformer/DAProductBuilder.h @@ -35,7 +35,7 @@ namespace storm { return da.getSuccessor(da.getInitialState(), getLabelForState(modelState)); } - storm::storage::sparse::state_type getSuccessor(storm::storage::sparse::state_type modelFrom, + storm::storage::sparse::state_type getSuccessor(storm::storage::sparse::state_type modelFrom, //TODO delete modelFrom? storm::storage::sparse::state_type automatonFrom, storm::storage::sparse::state_type modelTo) const { return da.getSuccessor(automatonFrom, getLabelForState(modelTo)); diff --git a/src/storm/transformer/ProductBuilder.h b/src/storm/transformer/ProductBuilder.h index a82bd2839..a398a1811 100644 --- a/src/storm/transformer/ProductBuilder.h +++ b/src/storm/transformer/ProductBuilder.h @@ -33,7 +33,6 @@ namespace storm { // 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); diff --git a/src/test/storm/modelchecker/prctl/mdp/SchedulerGenerationMdpPrctlModelCheckerTest.cpp b/src/test/storm/modelchecker/prctl/mdp/SchedulerGenerationMdpPrctlModelCheckerTest.cpp index dbea6504d..a1844888b 100755 --- a/src/test/storm/modelchecker/prctl/mdp/SchedulerGenerationMdpPrctlModelCheckerTest.cpp +++ b/src/test/storm/modelchecker/prctl/mdp/SchedulerGenerationMdpPrctlModelCheckerTest.cpp @@ -173,6 +173,7 @@ namespace { 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>>(); @@ -201,5 +202,57 @@ namespace { EXPECT_NEAR(this->parseNumber("0"), inducedResult->template asExplicitQuantitativeCheckResult<ValueType>()[*mdp->getInitialStates().begin()], this->env().solver().lra().getPrecision()); } } + + TYPED_TEST(SchedulerGenerationMdpPrctlModelCheckerTest, ltl) { + typedef typename TestFixture::ValueType ValueType; + + std::string formulasString = "Pmax=? [X X \"target\"]; Pmin=? [G F \"target\"];"; + 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); + + { + auto result = checker.check(this->env(), tasks[0]); + ASSERT_TRUE(result->isExplicitQuantitativeCheckResult()); + 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("9/10"), inducedResult->template asExplicitQuantitativeCheckResult<ValueType>()[*mdp->getInitialStates().begin()], storm::settings::getModule<storm::settings::modules::GeneralSettings>().getPrecision()); + } + { + auto result = checker.check(this->env(), tasks[1]); + ASSERT_TRUE(result->isExplicitQuantitativeCheckResult()); + 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>()[*mdp->getInitialStates().begin()], storm::settings::getModule<storm::settings::modules::GeneralSettings>().getPrecision()); + } + } } \ No newline at end of file From 991cf35f2fd197c3624096d123c04747e9bbd473 Mon Sep 17 00:00:00 2001 From: hannah <hannah.mertens@rwth-aachen.de> Date: Mon, 5 Jul 2021 13:05:50 +0200 Subject: [PATCH 095/172] print memoryStructure --- src/storm/storage/Scheduler.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/storm/storage/Scheduler.cpp b/src/storm/storage/Scheduler.cpp index 1c3d6c895..27d5d6d37 100644 --- a/src/storm/storage/Scheduler.cpp +++ b/src/storm/storage/Scheduler.cpp @@ -226,8 +226,10 @@ namespace storm { out << "___________________________________________________________________" << std::endl; // TODO only for tests: - out << memoryStructure->toString(); - out << std::endl; + if(!isMemorylessScheduler()) { + out << memoryStructure->toString(); + out << std::endl; + } } template <> From 49e346d52b97d205cbee86e1de55b2a13b375bf4 Mon Sep 17 00:00:00 2001 From: hannah <hannah.mertens@rwth-aachen.de> Date: Wed, 7 Jul 2021 17:55:01 +0200 Subject: [PATCH 096/172] new Test --- .../helper/ltl/SparseLTLHelper.cpp | 6 ++--- .../modelchecker/helper/ltl/SparseLTLHelper.h | 8 +++++-- ...ulerGenerationMdpPrctlModelCheckerTest.cpp | 24 +++++++++++++++++-- 3 files changed, 31 insertions(+), 7 deletions(-) diff --git a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp index 8a59e5252..07940e3a7 100644 --- a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp +++ b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp @@ -71,9 +71,11 @@ namespace storm { uint_fast64_t memoryState = choice.first.second; scheduler.setChoice(choice.second, modelState, memoryState); } + // TODO set non-reachable (modelState,memoryState)-Pairs (i.e. those that are not contained in _productChoices) to "unreachable", (extend Scheduler by something like std::vector<std::Bitvector>> reachableSchedulerChoices; und isChoiceReachable(..)) return scheduler; } + 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, std::function<std::unique_ptr<CheckResult>(std::shared_ptr<storm::logic::Formula const> const& formula)> formulaChecker){ std::map<std::string, storm::storage::BitVector> apSets; @@ -191,8 +193,6 @@ namespace storm { STORM_LOG_DEBUG("MEC is accepting"); for (auto const& stateChoicePair : mec) { - // TODO extend scheduler by mec choices (which?) - // need adversary which forces (to remain in mec and) to visit all states of the mec inf. often with prob. 1 acceptingStates.set(stateChoicePair.first); } } @@ -339,7 +339,7 @@ namespace storm { storm::storage::BitVector modelStates(this->_transitionMatrix.getRowGroupCount(), false); for (storm::storage::sparse::state_type modelState = 0; modelState < this->_transitionMatrix.getRowGroupCount(); ++modelState) { - if (goalState == productBuilder.getSuccessor(modelState, startState, modelState)) { + if (goalState == productBuilder.getSuccessor(modelState, startState, modelState)) { //todo remove first parameter modelStates.set(modelState); } } diff --git a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h index 3df887979..0e7277b54 100644 --- a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h +++ b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h @@ -96,11 +96,15 @@ namespace storm { storm::storage::SparseMatrix<ValueType> const& _transitionMatrix; std::size_t _numberOfStates; //TODO just use _transitionMatrix.getRowGroupCount instead? - // scheduler + // REACH scheduler boost::optional<std::map<std::pair<uint_fast64_t, uint_fast64_t>, storm::storage::SchedulerChoice<ValueType>>> _productChoices; // <s, q> --> choice - boost::optional<std::vector<std::vector<storm::storage::BitVector>>> _memoryTransitions; // BitVector contains the model states that lead from startState to goalSate of teh DA + boost::optional<std::vector<std::vector<storm::storage::BitVector>>> _memoryTransitions; // BitVector contains the model states that lead from startState to goalSate of the DA boost::optional<std::vector<uint_fast64_t>> _memoryInitialStates; // Saves for each modelState which automaton state is reached from the initial state //TODO improve + // MEC scheduler + boost::optional<std::map <std::pair<uint_fast64_t,std::pair<uint_fast64_t, uint_fast64_t>> , storm::storage::SchedulerChoice<ValueType>>> _mecProductChoices; // <#literal, <s, daState>> ---> choice + boost::optional<std::vector<std::vector<storm::storage::BitVector>>> _mecMemoryTransitions; // BitVector contains the model states that lead from #INF(i) to #INF(i+1) of the AccCondition (#INF(1) AND #INF(2) ....) OR (..) + }; } } diff --git a/src/test/storm/modelchecker/prctl/mdp/SchedulerGenerationMdpPrctlModelCheckerTest.cpp b/src/test/storm/modelchecker/prctl/mdp/SchedulerGenerationMdpPrctlModelCheckerTest.cpp index a1844888b..45362994a 100755 --- a/src/test/storm/modelchecker/prctl/mdp/SchedulerGenerationMdpPrctlModelCheckerTest.cpp +++ b/src/test/storm/modelchecker/prctl/mdp/SchedulerGenerationMdpPrctlModelCheckerTest.cpp @@ -206,7 +206,7 @@ namespace { TYPED_TEST(SchedulerGenerationMdpPrctlModelCheckerTest, ltl) { typedef typename TestFixture::ValueType ValueType; - std::string formulasString = "Pmax=? [X X \"target\"]; Pmin=? [G F \"target\"];"; + std::string formulasString = "Pmax=? [X X \"target\"]; 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); @@ -228,7 +228,7 @@ namespace { 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>>(); + auto const& inducedMdp = inducedModel->template as<storm::models::sparse::Mdp<ValueType>>(); // TODO DTMC! EXPECT_EQ(inducedMdp->getNumberOfChoices(), inducedMdp->getNumberOfStates()); storm::modelchecker::SparseMdpPrctlModelChecker<storm::models::sparse::Mdp<ValueType>> inducedChecker(*inducedMdp); auto inducedResult = inducedChecker.check(this->env(), tasks[0]); @@ -253,6 +253,26 @@ namespace { ASSERT_TRUE(inducedResult->isExplicitQuantitativeCheckResult()); EXPECT_NEAR(this->parseNumber("1/2"), inducedResult->template asExplicitQuantitativeCheckResult<ValueType>()[*mdp->getInitialStates().begin()], storm::settings::getModule<storm::settings::modules::GeneralSettings>().getPrecision()); } + { + auto result = checker.check(this->env(), tasks[2]); + EXPECT_NEAR(this->parseNumber("1/2"), result->template asExplicitQuantitativeCheckResult<ValueType>()[*mdp->getInitialStates().begin()], storm::settings::getModule<storm::settings::modules::GeneralSettings>().getPrecision()); + + ASSERT_TRUE(result->isExplicitQuantitativeCheckResult()); + 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()); + EXPECT_NEAR(this->parseNumber("1/2"), inducedResult->template asExplicitQuantitativeCheckResult<ValueType>()[*mdp->getInitialStates().begin()], storm::settings::getModule<storm::settings::modules::GeneralSettings>().getPrecision()); + } } } \ No newline at end of file From 0983f2f5643e9a53b1f6b08004b611a04cbba511 Mon Sep 17 00:00:00 2001 From: hannah <hannah.mertens@rwth-aachen.de> Date: Sun, 11 Jul 2021 03:01:25 +0200 Subject: [PATCH 097/172] print memory updates Conflicts: src/storm/storage/Scheduler.cpp --- src/storm/storage/Scheduler.cpp | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/src/storm/storage/Scheduler.cpp b/src/storm/storage/Scheduler.cpp index 27d5d6d37..f834434ca 100644 --- a/src/storm/storage/Scheduler.cpp +++ b/src/storm/storage/Scheduler.cpp @@ -215,6 +215,18 @@ namespace storm { stateString << "undefined."; } + if(!isMemorylessScheduler()) { + stateString << " "; + for (auto const& choiceProbPair : choice.getChoiceAsDistribution()) { + for (auto entryIt = model->getTransitionMatrix().getRow(state + choiceProbPair.first).begin(); entryIt < model->getTransitionMatrix().getRow(state + choiceProbPair.first).end(); ++entryIt) { + out << ", model state' = " << entryIt->getColumn() << ": (transition = " << state+choiceProbPair.first << ") -> " << "(m' = "<<this->memoryStructure->getSuccessorMemoryState(memoryState, entryIt - model->getTransitionMatrix().begin()) <<")"; + } + + } + + stateString << std::endl; + } + // Todo: print memory updates out << stateString.str(); out << std::endl; From 93c2e92c2a3fd794c6c765280bafd27b390d1121 Mon Sep 17 00:00:00 2001 From: hannah <hannah.mertens@rwth-aachen.de> Date: Sun, 11 Jul 2021 03:01:58 +0200 Subject: [PATCH 098/172] updated LTL-scheduler --- .../helper/ltl/SparseLTLHelper.cpp | 223 ++++++++++++++---- .../modelchecker/helper/ltl/SparseLTLHelper.h | 17 +- .../SparseModelMemoryProduct.cpp | 2 +- src/storm/transformer/Product.h | 8 + src/storm/utility/graph.cpp | 9 +- ...ulerGenerationMdpPrctlModelCheckerTest.cpp | 93 ++++++-- 6 files changed, 278 insertions(+), 74 deletions(-) diff --git a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp index 07940e3a7..c102b800b 100644 --- a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp +++ b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp @@ -16,6 +16,8 @@ #include "storm/environment/modelchecker/ModelCheckerEnvironment.h" +#include "storm/utility/graph.h" + namespace storm { namespace modelchecker { namespace helper { @@ -30,9 +32,12 @@ namespace storm { 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->_productChoices.is_initialized(), "Trying to extract the produced scheduler but none is available. Was there a computation call before?"); + + // TODO fails for No accepting states, skipping probability computation. STORM_LOG_ASSERT(this->_memoryTransitions.is_initialized(), "Trying to extract the DA transition structure but none is available. Was there a computation call before?"); STORM_LOG_ASSERT(this->_memoryInitialStates.is_initialized(), "Trying to extract the initial states of the DA but there are none available. Was there a computation call before?"); + // Create a memory structure for the MDP scheduler with memory. typename storm::storage::MemoryStructureBuilder<ValueType>::MemoryStructureBuilder memoryBuilder(this->_memoryTransitions.get().size(), model); @@ -44,36 +49,36 @@ namespace storm { } } - /* - memoryStateLabeling: Label the memory states to specify, e.g., accepting states // TODO where are these labels used? - for (storm::storage::sparse::state_type q : set) { - memoryBuilder.setLabel(q,//todo); - } - */ - // initialMemoryStates: Assign an initial memory state to each initial state of the model. for (uint_fast64_t s0 : model.getInitialStates()) { - // Label the state as initial TODO unnecessary? - //memoryBuilder.setLabel(q, "Initial for model state " s0) memoryBuilder.setInitialMemoryState(s0, this->_memoryInitialStates.get()[s0]); } - - // Finally, we can build the memoryStructure. + // Now, we can build the memoryStructure. storm::storage::MemoryStructure memoryStructure = memoryBuilder.build(); - // Create a scheduler (with memory of size DA) for the model from the scheduler of the MDP-DA-product model. + // 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(this->_transitionMatrix.getRowGroupCount(), memoryStructure); // Use choices in the product model to create a choice based on model state and memory state for (const auto &choice : this->_productChoices.get()) { - uint_fast64_t modelState = choice.first.first; - uint_fast64_t memoryState = choice.first.second; + // <s, q, MEC, InfSet> -> choice + storm::storage::sparse::state_type modelState = std::get<0>(choice.first); + storm::storage::sparse::state_type automatonState = std::get<1>(choice.first); + uint_fast64_t mec = std::get<2>(choice.first); + uint_fast64_t infSet = std::get<3>(choice.first); + + // Encode as memory state + uint_fast64_t memoryState = (((infSet * _mecStatesInfSets.get().size()) + mec) * _numberOfDaStates.get()) + automatonState; scheduler.setChoice(choice.second, modelState, memoryState); } - // TODO set non-reachable (modelState,memoryState)-Pairs (i.e. those that are not contained in _productChoices) to "unreachable", (extend Scheduler by something like std::vector<std::Bitvector>> reachableSchedulerChoices; und isChoiceReachable(..)) + // TODO + // set non-reachable (modelState,memoryState)-Pairs (i.e. those that are not contained in _productChoices) to "unreachable", (extend Scheduler by something like std::vector<std::Bitvector>> reachableSchedulerChoices; und isChoiceReachable(..)) + // Sanity check for created scheduler. + STORM_LOG_ASSERT(scheduler.isDeterministicScheduler(), "Expected a deterministic scheduler"); return scheduler; + } template<typename ValueType, bool Nondeterministic> @@ -95,7 +100,7 @@ namespace storm { 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) { + 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)"); @@ -112,6 +117,14 @@ namespace storm { std::size_t accMECs = 0; std::size_t allMECs = 0; std::size_t i = 0; + + if (this->isProduceSchedulerSet()) { + _mecStatesInfSets.emplace(); + _productChoices.emplace(); + } + // Save the states that are already assigned a scheduler (MEC), a state is assigned to the first MEC we find. + storm::storage::BitVector finishedStates(transitionMatrix.getRowGroupCount(), false); + 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 @@ -153,12 +166,16 @@ namespace storm { storm::storage::MaximalEndComponentDecomposition<ValueType> mecs(transitionMatrix, backwardTransitions, allowed); allMECs += mecs.size(); for (const auto& mec : mecs) { + // Save the accSets that need to be visited inf often to satisfy a specific accepting MEC. + std::vector<storm::storage::BitVector> infSets = std::vector<storm::storage::BitVector>(); + STORM_LOG_DEBUG("Inspect MEC: " << mec); bool accepting = true; for (auto const& literal : conjunction) { if (literal->isTRUE()) { // skip + } else if (literal->isFALSE()) { accepting = false; break; @@ -173,6 +190,11 @@ namespace storm { accepting = false; break; } + + if (this->isProduceSchedulerSet()) { + infSets.emplace_back(~accSet); + } + } else { STORM_LOG_DEBUG("Checking against " << accSet); if (!mec.containsAnyState(accSet)) { @@ -180,7 +202,11 @@ namespace storm { accepting = false; break; } + if (this->isProduceSchedulerSet()) { + infSets.emplace_back(accSet); + } } + } 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"); @@ -192,14 +218,69 @@ namespace storm { accMECs++; STORM_LOG_DEBUG("MEC is accepting"); - for (auto const& stateChoicePair : mec) { + for (auto const &stateChoicePair : mec) { acceptingStates.set(stateChoicePair.first); } + + if (this->isProduceSchedulerSet()) { + + storm::storage::BitVector mecStates(transitionMatrix.getRowGroupCount(), false); + for (auto const &stateChoicePair : mec) { + mecStates.set(stateChoicePair.first); + } + + // If there are no InfSets (either all TRUE or only FIN in conjunction) + if (infSets.empty()) { + // We want to visit some states of this MEC inf. often + infSets.emplace_back(mecStates); + } + + // Save the states of this MEC (that are not contained in any other MEC yet) and the InfSets need to be visited inf. often to sat. the acc. cond. + _mecStatesInfSets.get().insert({accMECs, std::make_pair(mecStates & ~finishedStates, infSets)}); + + // Define scheduler choices for the states in this MEC (that are not in any other MEC) + for (uint_fast64_t infSet = 0; infSet < infSets.size(); ++infSet) { + // Scheduler that satisfies the MEC acceptance condition (visit each InfSet inf often, or switch to scheduler of another MEC) + storm::storage::Scheduler<ValueType> mecScheduler( + transitionMatrix.getRowGroupCount()); + + + + // Compute a scheduler that, with prob=1, reaches the infSet via mecStates starting from states that are not yet in other MEC + storm::utility::graph::computeSchedulerProb1E<ValueType>(_mecStatesInfSets.get()[accMECs].first, transitionMatrix, backwardTransitions, mecStates, _mecStatesInfSets.get()[accMECs].second[infSet], mecScheduler); + + // Prob1E sets an arbitrary choice for the psi states, but we want to stay in this accepting mec. + for (auto pState : (_mecStatesInfSets.get()[accMECs].first & _mecStatesInfSets.get()[accMECs].second[infSet])) { + // If we are in the InfSet, we stay in mec-states + // TODO is this correct: + // (*std::next(mec.getChoicesForState(pState).begin(), 0)) + mecScheduler.setChoice(storm::storage::SchedulerChoice<ValueType>((*std::next(mec.getChoicesForState(pState).begin()), 0)), pState); + } + + // Extract scheduler choices (only for states that are already assigned a scheduler, i.e are in another MEC) + for (auto pState : _mecStatesInfSets.get()[accMECs].first) { + //if (!_mecStatesInfSets.get()[accMECs].second[infSet].get(pState)) { + // We want to reach the InfSet, save choice: <s, q, MEC, InfSet> ---> choice + // TODO find test that fails, when ignoring these: + this->_productChoices.get().insert({std::make_tuple(product->getModelState(pState),product->getAutomatonState(pState), accMECs, infSet), mecScheduler.getChoice(pState)}); + } + + + } + + // The states in this MEC will not be reassigned + finishedStates = finishedStates | mecStates; + } } } } + if (this->isProduceSchedulerSet()) { + // Remaining states belong to no mec (REACH scheduler is computed later) + _mecStatesInfSets.get()[0] = std::make_pair(~finishedStates,std::vector<storm::storage::BitVector>(1,~finishedStates)); + } + STORM_LOG_DEBUG("Accepting states: " << acceptingStates); STORM_LOG_INFO("Found " << acceptingStates.getNumberOfSetBits() << " states in " << accMECs << " accepting MECs (considered " << allMECs << " MECs)."); @@ -209,7 +290,6 @@ namespace storm { 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 = storm::storage::BitVector(product->getProductModel().getNumberOfStates()); storm::storage::BitVector acceptingStates(transitionMatrix.getRowGroupCount(), false); std::size_t checkedBSCCs = 0, acceptingBSCCs = 0, acceptingBSCCStates = 0; @@ -275,9 +355,9 @@ namespace storm { 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()); + acceptingStates = computeAcceptingECs(*product->getAcceptance(), product->getProductModel().getTransitionMatrix(), product->getProductModel().getBackwardTransitions(), product); //TODO product is only needed for ->getModelState(pState) and DAStates for scheduler creation (maybe lambda instead) - } else { + } else { STORM_LOG_INFO("Computing BSCCs and checking for acceptance..."); acceptingStates = computeAcceptingBCCs(*product->getAcceptance(), product->getProductModel().getTransitionMatrix()); @@ -318,44 +398,101 @@ namespace storm { ); prodNumericResult = std::move(prodCheckResult.values); - if (this->isProduceSchedulerSet()) { - // Extract the choices of the scheduler for the MDP-DA product: <s,q> -> choice - this->_productChoices.emplace(); + if (this->isProduceSchedulerSet()) { // TODO create fct for this + _numberOfDaStates = da.getNumberOfStates(); + // TODO asserts _mecStatesInfSets initialized etc. + + // Extract the choices of the REACH-scheduler (choices to reach an acc. MEC) for the MDP-DA product: <s,q> -> choice for (storm::storage::sparse::state_type pState = 0; pState < product->getProductModel().getNumberOfStates(); ++pState) { - this->_productChoices.get().insert({std::make_pair(product->getModelState(pState), product->getAutomatonState(pState)), prodCheckResult.scheduler->getChoice(pState)}); + // <s,q, NoMec, 0> ---> choice + if(! acceptingStates.get(pState)){ + // Do not overwrite choices of states in an accepting MEC + this->_productChoices.get().insert({std::make_tuple(product->getModelState(pState), product->getAutomatonState(pState), 0, 0), prodCheckResult.scheduler->getChoice(pState)}); + } } + // Prepare the memory structure. For that, we need: transitions, initialMemoryStates (and memoryStateLabeling) - // Prepare the memory structure. For that, we need: transitions, initialMemoryStates (and todo: memoryStateLabeling) + // Compute size of the resulting memory structure: a state corresponds to <q <mec, infSet>> encoded as (((infSet * |mecs|) + mec) * |DAStates|) +q + uint64 numCopies =0; + for (auto const& mec: _mecStatesInfSets.get()) { + numCopies += mec.second.second.size(); + } + uint64 numMemoryStates = numCopies * _mecStatesInfSets.get().size() * da.getNumberOfStates() + da.getNumberOfStates(); //TODO is this correct // The next move function of the memory, will be build based on the transitions of the DA. - this->_memoryTransitions.emplace(da.getNumberOfStates(), std::vector<storm::storage::BitVector>(da.getNumberOfStates())); - - for (storm::storage::sparse::state_type startState = 0; startState < da.getNumberOfStates(); ++startState) { - for (storm::storage::sparse::state_type goalState = 0; - goalState < da.getNumberOfStates(); ++goalState) { - // Bitvector that represents modelStates the model states that trigger this transition. - storm::storage::BitVector modelStates(this->_transitionMatrix.getRowGroupCount(), false); - for (storm::storage::sparse::state_type modelState = 0; - modelState < this->_transitionMatrix.getRowGroupCount(); ++modelState) { - if (goalState == productBuilder.getSuccessor(modelState, startState, modelState)) { //todo remove first parameter - modelStates.set(modelState); + this->_memoryTransitions.emplace(numMemoryStates, std::vector<storm::storage::BitVector>(numMemoryStates, storm::storage::BitVector(this->_transitionMatrix.getRowGroupCount(), false))); + + + for (storm::storage::sparse::state_type automatonFrom = 0; automatonFrom < da.getNumberOfStates(); ++automatonFrom) { + for (storm::storage::sparse::state_type automatonTo = 0; automatonTo < da.getNumberOfStates(); ++automatonTo) { + // Find the modelStates that trigger this transition. + for (storm::storage::sparse::state_type modelState = 0; modelState < this->_transitionMatrix.getRowGroupCount(); ++modelState) { + + if(!product->isValidProductState(modelState, automatonTo)) { + // Memory state successor of the modelState-transition emanating <automatonFrom, ?, ? > not defined/reachable. + // TODO save as unreachable in scheduler + // STORM_PRINT("set to unreachable : (" << modelState <<" , " << automatonTo <<")"); + + } else if (automatonTo == productBuilder.getSuccessor(modelState, automatonFrom, modelState)) { //TODO remove first parameter of getSuccessor + // Add the modelState to one outgoing transition of all states of the form <automatonFrom <mec, InfSet>> (mec=0 equals NoMec) + for (uint_fast64_t mec = 0; mec < _mecStatesInfSets.get().size(); ++mec) { + for (uint_fast64_t infSet = 0; infSet < _mecStatesInfSets.get()[mec].second.size(); ++infSet) { + + // Find the goalState <automatonTo <mec', InfSet'>>, where <modelState, automatonTo> is in mec'. + if (_mecStatesInfSets.get()[mec].first.get(product->getProductStateIndex(modelState, automatonTo))) { + // <modelState, automatonTo> in contained in this MEC. Now check if we have reached the current InfSet. + if(_mecStatesInfSets.get()[mec].second[infSet].get(product->getProductStateIndex(modelState, automatonTo))){ + // InfSet satisfied: Add modelState to the transition from <automatonFrom <mec, InfSet>> to <automatonTo, <mec, NextInfSet>>. + uint64 from = (((infSet * _mecStatesInfSets.get().size()) + mec) * da.getNumberOfStates()) + automatonFrom; + uint64 to = ((((infSet+1 < _mecStatesInfSets.get()[mec].second.size() ? infSet+1 : 0) * _mecStatesInfSets.get().size()) + mec) * da.getNumberOfStates()) + automatonTo; + _memoryTransitions.get()[from][to].set(modelState); + } else { + // InfSet not satisfied: Add modelState to the transition from <automatonFrom <mec, InfSet>> to <automatonTo, <mec, InfSet>>. + uint64 from = (((infSet * _mecStatesInfSets.get().size()) + mec) * da.getNumberOfStates()) + automatonFrom; + uint64 to = (((infSet * _mecStatesInfSets.get().size()) + mec) * da.getNumberOfStates()) + automatonTo; + _memoryTransitions.get()[from][to].set(modelState); + } + } else { + // We need to find the unique MEC containing <modelState, automatonTo> and start in InfSet 0. + for (uint_fast64_t nextMec = 0; nextMec < _mecStatesInfSets.get().size(); ++nextMec) { + if (_mecStatesInfSets.get()[nextMec].first.get(product->getProductStateIndex(modelState, automatonTo))) { + // Add modelState to the transition from <automatonFrom <mec, InfSet>> to <automatonTo, nextMec, InfSet>> + uint64 from = (((infSet * _mecStatesInfSets.get().size()) + mec) * da.getNumberOfStates()) + automatonFrom; + uint64 to = (((0 * _mecStatesInfSets.get().size()) + nextMec) * da.getNumberOfStates()) + automatonTo; + _memoryTransitions.get()[from][to].set(modelState); + break; // Can stop, because the state is only contained in one MEC. + } + } + } + } + + } } } - // Insert a transition: startState--{modelStates}-->goalState - this->_memoryTransitions.get()[startState][goalState] = std::move(modelStates); } } + // Finished creation of transitions. + // Find initial memory states this->_memoryInitialStates.emplace(); this->_memoryInitialStates->resize(this->_transitionMatrix.getRowGroupCount()); - // Save for each automaton state for which model state it is initial. - for (storm::storage::sparse::state_type modelState = 0; modelState< this->_transitionMatrix.getRowGroupCount(); ++modelState) { - this->_memoryInitialStates.get().at(modelState) = productBuilder.getInitialState(modelState); - } + // Save for each relevant model state its initial memory state (get the s-successor of q0) + for (storm::storage::sparse::state_type modelState : statesOfInterest) { + storm::storage::sparse::state_type automatonInit = productBuilder.getInitialState(modelState); + STORM_LOG_ASSERT(product->isValidProductState(modelState, automatonInit), "The memory successor state for the model state "<< modelState << "does not exist in the DA-Model Product."); + + // Search mec which contains <automatonInit, modelState> + for (uint_fast64_t mec = 0; mec < _mecStatesInfSets.get().size(); ++mec) { + if (_mecStatesInfSets.get()[mec].first.get(product->getProductStateIndex(modelState, automatonInit))) { + this->_memoryInitialStates.get().at(modelState) = (((0 * _mecStatesInfSets.get().size()) + mec) * da.getNumberOfStates()) + automatonInit; + break; + } + } - // TODO labels (e.g. the accepting set?) for the automaton states + } + // Finished creation of initial states. } } else { diff --git a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h index 0e7277b54..35bcfd220 100644 --- a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h +++ b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h @@ -83,7 +83,7 @@ namespace storm { * @param the transition matrix of the model * @param the reversed transition relation */ - storm::storage::BitVector computeAcceptingECs(automata::AcceptanceCondition const& acceptance, storm::storage::SparseMatrix<ValueType> const& transitionMatrix, storm::storage::SparseMatrix<ValueType> const& backwardTransitions); + 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); /** * Compute a set S of states that are contained in BSCCs that satisfy the given acceptance conditon. @@ -96,14 +96,13 @@ namespace storm { storm::storage::SparseMatrix<ValueType> const& _transitionMatrix; std::size_t _numberOfStates; //TODO just use _transitionMatrix.getRowGroupCount instead? - // REACH scheduler - boost::optional<std::map<std::pair<uint_fast64_t, uint_fast64_t>, storm::storage::SchedulerChoice<ValueType>>> _productChoices; // <s, q> --> choice - boost::optional<std::vector<std::vector<storm::storage::BitVector>>> _memoryTransitions; // BitVector contains the model states that lead from startState to goalSate of the DA - boost::optional<std::vector<uint_fast64_t>> _memoryInitialStates; // Saves for each modelState which automaton state is reached from the initial state //TODO improve - - // MEC scheduler - boost::optional<std::map <std::pair<uint_fast64_t,std::pair<uint_fast64_t, uint_fast64_t>> , storm::storage::SchedulerChoice<ValueType>>> _mecProductChoices; // <#literal, <s, daState>> ---> choice - boost::optional<std::vector<std::vector<storm::storage::BitVector>>> _mecMemoryTransitions; // BitVector contains the model states that lead from #INF(i) to #INF(i+1) of the AccCondition (#INF(1) AND #INF(2) ....) OR (..) + // REACH scheduler and MEC scheduler + boost::optional<std::map <std::tuple<uint_fast64_t, uint_fast64_t, uint_fast64_t, uint_fast64_t>, storm::storage::SchedulerChoice<ValueType>>> _productChoices; // <s, q, MEC, InfSet> ---> ReachChoice and <s, q, MEC, InfSet> ---> MecChoice + boost::optional<std::map <uint_fast64_t, std::pair<storm::storage::BitVector, std::vector<storm::storage::BitVector>>>> _mecStatesInfSets; // Save for each accepting mec, its states <s, q> and the infinity sets that need to be visited inf. often (mec 0 corresponds to NoMec) + // Memory structure + boost::optional<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). + boost::optional<std::vector<uint_fast64_t>> _memoryInitialStates; // Save for each stateOfInterest s its initial memory state (which memory state is reached from the initial state after reading s) + boost::optional<std::size_t> _numberOfDaStates; }; } diff --git a/src/storm/storage/memorystructure/SparseModelMemoryProduct.cpp b/src/storm/storage/memorystructure/SparseModelMemoryProduct.cpp index 31708544d..029387288 100644 --- a/src/storm/storage/memorystructure/SparseModelMemoryProduct.cpp +++ b/src/storm/storage/memorystructure/SparseModelMemoryProduct.cpp @@ -288,7 +288,7 @@ namespace storm { uint64_t transitionId = entryIt - model.getTransitionMatrix().begin(); uint64_t successorMemoryState = memorySuccessors[transitionId * memoryStateCount + memoryState]; builder.addNextValue(currentRow, getResultState(entryIt->getColumn(), successorMemoryState), entryIt->getValue()); - } //TODO successor MemoryState is a problem here 8382838738483264 oder so + } } else { std::map<uint64_t, ValueType> transitions; for (auto const& choiceIndex : choice.getChoiceAsDistribution()) { diff --git a/src/storm/transformer/Product.h b/src/storm/transformer/Product.h index ee037784b..b30362466 100644 --- a/src/storm/transformer/Product.h +++ b/src/storm/transformer/Product.h @@ -36,6 +36,14 @@ namespace storm { return productIndexToProductState.at(productStateIndex).second; } + state_type getProductStateIndex(state_type modelState, state_type automatonState) const { + return productStateToProductIndex.at(product_state_type(modelState, automatonState)); //TODO does this work? + } + + bool isValidProductState(state_type modelState, state_type automatonState) const { + return (productStateToProductIndex.count(product_state_type(modelState, automatonState)) >0); //TODO does this work? + } + storm::storage::BitVector liftFromAutomaton(const storm::storage::BitVector& vector) const { state_type n = productModel.getNumberOfStates(); storm::storage::BitVector lifted(n, false); diff --git a/src/storm/utility/graph.cpp b/src/storm/utility/graph.cpp index 5df06c585..d5ca015c3 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,10 @@ 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); - - - + + // TODO remove? + 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/modelchecker/prctl/mdp/SchedulerGenerationMdpPrctlModelCheckerTest.cpp b/src/test/storm/modelchecker/prctl/mdp/SchedulerGenerationMdpPrctlModelCheckerTest.cpp index 45362994a..dd8846f74 100755 --- a/src/test/storm/modelchecker/prctl/mdp/SchedulerGenerationMdpPrctlModelCheckerTest.cpp +++ b/src/test/storm/modelchecker/prctl/mdp/SchedulerGenerationMdpPrctlModelCheckerTest.cpp @@ -203,11 +203,14 @@ namespace { } } + + TYPED_TEST(SchedulerGenerationMdpPrctlModelCheckerTest, ltl) { typedef typename TestFixture::ValueType ValueType; - std::string formulasString = "Pmax=? [X X \"target\"]; 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); + std::string formulasString = "Pmax=? [X X \"target\"]; 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()); @@ -221,58 +224,114 @@ namespace { auto result = checker.check(this->env(), tasks[0]); ASSERT_TRUE(result->isExplicitQuantitativeCheckResult()); ASSERT_TRUE(result->template asExplicitQuantitativeCheckResult<ValueType>().hasScheduler()); - storm::storage::Scheduler<ValueType> const& scheduler = result->template asExplicitQuantitativeCheckResult<ValueType>().getScheduler(); + storm::storage::Scheduler<ValueType> const &scheduler = result->template asExplicitQuantitativeCheckResult<ValueType>().getScheduler(); EXPECT_TRUE(scheduler.isDeterministicScheduler()); - EXPECT_TRUE(! scheduler.isMemorylessScheduler()); + 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>>(); // TODO DTMC! + auto const &inducedMdp = inducedModel->template as<storm::models::sparse::Mdp<ValueType>>(); // TODO DTMC! 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("9/10"), inducedResult->template asExplicitQuantitativeCheckResult<ValueType>()[*mdp->getInitialStates().begin()], storm::settings::getModule<storm::settings::modules::GeneralSettings>().getPrecision()); + EXPECT_NEAR(this->parseNumber("9/10"), + inducedResult->template asExplicitQuantitativeCheckResult<ValueType>()[*mdp->getInitialStates().begin()], //TODO other states, too + storm::settings::getModule<storm::settings::modules::GeneralSettings>().getPrecision()); } + { auto result = checker.check(this->env(), tasks[1]); ASSERT_TRUE(result->isExplicitQuantitativeCheckResult()); ASSERT_TRUE(result->template asExplicitQuantitativeCheckResult<ValueType>().hasScheduler()); - storm::storage::Scheduler<ValueType> const& scheduler = result->template asExplicitQuantitativeCheckResult<ValueType>().getScheduler(); + 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>>(); + 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); + 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>()[*mdp->getInitialStates().begin()], storm::settings::getModule<storm::settings::modules::GeneralSettings>().getPrecision()); + EXPECT_NEAR(this->parseNumber("1/2"), + inducedResult->template asExplicitQuantitativeCheckResult<ValueType>()[*mdp->getInitialStates().begin()], + storm::settings::getModule<storm::settings::modules::GeneralSettings>().getPrecision()); } + { auto result = checker.check(this->env(), tasks[2]); - EXPECT_NEAR(this->parseNumber("1/2"), result->template asExplicitQuantitativeCheckResult<ValueType>()[*mdp->getInitialStates().begin()], storm::settings::getModule<storm::settings::modules::GeneralSettings>().getPrecision()); - + EXPECT_NEAR(this->parseNumber("1/2"), + result->template asExplicitQuantitativeCheckResult<ValueType>()[*mdp->getInitialStates().begin()], + storm::settings::getModule<storm::settings::modules::GeneralSettings>().getPrecision()); ASSERT_TRUE(result->isExplicitQuantitativeCheckResult()); ASSERT_TRUE(result->template asExplicitQuantitativeCheckResult<ValueType>().hasScheduler()); - storm::storage::Scheduler<ValueType> const& scheduler = result->template asExplicitQuantitativeCheckResult<ValueType>().getScheduler(); + 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>>(); + 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); + storm::modelchecker::SparseMdpPrctlModelChecker<storm::models::sparse::Mdp<ValueType>> inducedChecker( + *inducedMdp); auto inducedResult = inducedChecker.check(this->env(), tasks[2]); ASSERT_TRUE(inducedResult->isExplicitQuantitativeCheckResult()); - EXPECT_NEAR(this->parseNumber("1/2"), inducedResult->template asExplicitQuantitativeCheckResult<ValueType>()[*mdp->getInitialStates().begin()], storm::settings::getModule<storm::settings::modules::GeneralSettings>().getPrecision()); + EXPECT_NEAR(this->parseNumber("1/2"), + inducedResult->template asExplicitQuantitativeCheckResult<ValueType>()[*mdp->getInitialStates().begin()], + storm::settings::getModule<storm::settings::modules::GeneralSettings>().getPrecision()); } + } - + + + TYPED_TEST(SchedulerGenerationMdpPrctlModelCheckerTest, ltl2) { + typedef typename TestFixture::ValueType ValueType; + //TODO find noMEC-scheduler-error (need nondet in EC) + + // Todo unreachable Product state error + 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); + + { + auto result = checker.check(this->env(), tasks[0]); + ASSERT_TRUE(result->isExplicitQuantitativeCheckResult()); + 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, true); + + + ASSERT_EQ(inducedModel->getType(), storm::models::ModelType::Mdp); + auto const &inducedMdp = inducedModel->template as<storm::models::sparse::Mdp<ValueType>>(); // TODO DTMC! + 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("todo"), inducedResult->template asExplicitQuantitativeCheckResult<ValueType>()[*mdp->getInitialStates().begin()], storm::settings::getModule<storm::settings::modules::GeneralSettings>().getPrecision()); + } + + } + } \ No newline at end of file From dd8d41074887a69f9e86a24e30bcedc5c5ebaedd Mon Sep 17 00:00:00 2001 From: hannah <hannah.mertens@rwth-aachen.de> Date: Mon, 12 Jul 2021 10:20:39 +0200 Subject: [PATCH 099/172] updated scheduler-print and tests Conflicts: src/storm/storage/Scheduler.cpp --- .../helper/ltl/SparseLTLHelper.cpp | 2 +- src/storm/storage/Scheduler.cpp | 8 +++---- ...ulerGenerationMdpPrctlModelCheckerTest.cpp | 24 +++++++------------ 3 files changed, 13 insertions(+), 21 deletions(-) diff --git a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp index c102b800b..bd782df1e 100644 --- a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp +++ b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp @@ -50,7 +50,7 @@ namespace storm { } // initialMemoryStates: Assign an initial memory state to each initial state of the model. - for (uint_fast64_t s0 : model.getInitialStates()) { + for (uint_fast64_t s0 : model.getInitialStates()) { // TODO should be relevantStates? memoryBuilder.setInitialMemoryState(s0, this->_memoryInitialStates.get()[s0]); } diff --git a/src/storm/storage/Scheduler.cpp b/src/storm/storage/Scheduler.cpp index f834434ca..8b8431e24 100644 --- a/src/storm/storage/Scheduler.cpp +++ b/src/storm/storage/Scheduler.cpp @@ -145,7 +145,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 @@ -215,11 +215,12 @@ namespace storm { stateString << "undefined."; } + // Print memory updates if(!isMemorylessScheduler()) { - stateString << " "; + out << " "; for (auto const& choiceProbPair : choice.getChoiceAsDistribution()) { for (auto entryIt = model->getTransitionMatrix().getRow(state + choiceProbPair.first).begin(); entryIt < model->getTransitionMatrix().getRow(state + choiceProbPair.first).end(); ++entryIt) { - out << ", model state' = " << entryIt->getColumn() << ": (transition = " << state+choiceProbPair.first << ") -> " << "(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()) <<")"; } } @@ -227,7 +228,6 @@ namespace storm { stateString << std::endl; } - // Todo: print memory updates out << stateString.str(); out << std::endl; } diff --git a/src/test/storm/modelchecker/prctl/mdp/SchedulerGenerationMdpPrctlModelCheckerTest.cpp b/src/test/storm/modelchecker/prctl/mdp/SchedulerGenerationMdpPrctlModelCheckerTest.cpp index dd8846f74..ba1e350dd 100755 --- a/src/test/storm/modelchecker/prctl/mdp/SchedulerGenerationMdpPrctlModelCheckerTest.cpp +++ b/src/test/storm/modelchecker/prctl/mdp/SchedulerGenerationMdpPrctlModelCheckerTest.cpp @@ -204,10 +204,10 @@ namespace { } - TYPED_TEST(SchedulerGenerationMdpPrctlModelCheckerTest, ltl) { typedef typename TestFixture::ValueType ValueType; + // TODO skip without LTL support std::string formulasString = "Pmax=? [X X \"target\"]; 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); @@ -238,11 +238,8 @@ 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("9/10"), - inducedResult->template asExplicitQuantitativeCheckResult<ValueType>()[*mdp->getInitialStates().begin()], //TODO other states, too - storm::settings::getModule<storm::settings::modules::GeneralSettings>().getPrecision()); + EXPECT_NEAR(this->parseNumber("9/10"), inducedResult->template asExplicitQuantitativeCheckResult<ValueType>()[*mdp->getInitialStates().begin()],storm::settings::getModule<storm::settings::modules::GeneralSettings>().getPrecision()); } - { auto result = checker.check(this->env(), tasks[1]); ASSERT_TRUE(result->isExplicitQuantitativeCheckResult()); @@ -256,15 +253,11 @@ namespace { 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); + 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>()[*mdp->getInitialStates().begin()], - storm::settings::getModule<storm::settings::modules::GeneralSettings>().getPrecision()); + EXPECT_NEAR(this->parseNumber("1/2"),inducedResult->template asExplicitQuantitativeCheckResult<ValueType>()[*mdp->getInitialStates().begin()],storm::settings::getModule<storm::settings::modules::GeneralSettings>().getPrecision()); } - { auto result = checker.check(this->env(), tasks[2]); EXPECT_NEAR(this->parseNumber("1/2"), @@ -293,11 +286,10 @@ namespace { } - TYPED_TEST(SchedulerGenerationMdpPrctlModelCheckerTest, ltl2) { + TYPED_TEST(SchedulerGenerationMdpPrctlModelCheckerTest, ltlMec) { typedef typename TestFixture::ValueType ValueType; - //TODO find noMEC-scheduler-error (need nondet in EC) - - // Todo unreachable Product state error + // TODO skip without LTL 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); @@ -329,7 +321,7 @@ 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("todo"), inducedResult->template asExplicitQuantitativeCheckResult<ValueType>()[*mdp->getInitialStates().begin()], storm::settings::getModule<storm::settings::modules::GeneralSettings>().getPrecision()); + EXPECT_NEAR(this->parseNumber("0.5"), inducedResult->template asExplicitQuantitativeCheckResult<ValueType>()[*mdp->getInitialStates().begin()], storm::settings::getModule<storm::settings::modules::GeneralSettings>().getPrecision()); } } From d7b696a753292b46865f4fcf1bd7b204c14d7f38 Mon Sep 17 00:00:00 2001 From: hannah <hannah.mertens@rwth-aachen.de> Date: Thu, 15 Jul 2021 20:21:00 +0200 Subject: [PATCH 100/172] restructured the ltl-scheduler --- .../helper/ltl/SparseLTLHelper.cpp | 225 ++++++++++-------- .../modelchecker/helper/ltl/SparseLTLHelper.h | 9 +- .../MemoryStructureBuilder.cpp | 2 +- src/storm/utility/graph.cpp | 1 - ...ulerGenerationMdpPrctlModelCheckerTest.cpp | 2 +- 5 files changed, 134 insertions(+), 105 deletions(-) diff --git a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp index bd782df1e..57efb19c3 100644 --- a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp +++ b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp @@ -50,7 +50,7 @@ namespace storm { } // initialMemoryStates: Assign an initial memory state to each initial state of the model. - for (uint_fast64_t s0 : model.getInitialStates()) { // TODO should be relevantStates? + for (uint_fast64_t s0 : model.getInitialStates()) { // TODO set all from _memoryInitialStates, not only mdoelInitial memoryBuilder.setInitialMemoryState(s0, this->_memoryInitialStates.get()[s0]); } @@ -62,15 +62,12 @@ namespace storm { // Use choices in the product model to create a choice based on model state and memory state for (const auto &choice : this->_productChoices.get()) { - // <s, q, MEC, InfSet> -> choice + // <s, q, InfSet> -> choice storm::storage::sparse::state_type modelState = std::get<0>(choice.first); storm::storage::sparse::state_type automatonState = std::get<1>(choice.first); - uint_fast64_t mec = std::get<2>(choice.first); - uint_fast64_t infSet = std::get<3>(choice.first); + uint_fast64_t infSet = std::get<2>(choice.first); - // Encode as memory state - uint_fast64_t memoryState = (((infSet * _mecStatesInfSets.get().size()) + mec) * _numberOfDaStates.get()) + automatonState; - scheduler.setChoice(choice.second, modelState, memoryState); + scheduler.setChoice(choice.second, modelState, automatonState*(_infSets.get().size()+1)+ infSet); } // TODO // set non-reachable (modelState,memoryState)-Pairs (i.e. those that are not contained in _productChoices) to "unreachable", (extend Scheduler by something like std::vector<std::Bitvector>> reachableSchedulerChoices; und isChoiceReachable(..)) @@ -119,11 +116,10 @@ namespace storm { std::size_t i = 0; if (this->isProduceSchedulerSet()) { - _mecStatesInfSets.emplace(); + _infSets.emplace(); + _accInfSets.emplace(product->getProductModel().getNumberOfStates(), boost::none); _productChoices.emplace(); } - // Save the states that are already assigned a scheduler (MEC), a state is assigned to the first MEC we find. - storm::storage::BitVector finishedStates(transitionMatrix.getRowGroupCount(), false); for (auto const& conjunction : dnf) { // determine the set of states of the subMDP that can satisfy the condition @@ -166,9 +162,6 @@ namespace storm { storm::storage::MaximalEndComponentDecomposition<ValueType> mecs(transitionMatrix, backwardTransitions, allowed); allMECs += mecs.size(); for (const auto& mec : mecs) { - // Save the accSets that need to be visited inf often to satisfy a specific accepting MEC. - std::vector<storm::storage::BitVector> infSets = std::vector<storm::storage::BitVector>(); - STORM_LOG_DEBUG("Inspect MEC: " << mec); bool accepting = true; @@ -191,10 +184,6 @@ namespace storm { break; } - if (this->isProduceSchedulerSet()) { - infSets.emplace_back(~accSet); - } - } else { STORM_LOG_DEBUG("Checking against " << accSet); if (!mec.containsAnyState(accSet)) { @@ -202,9 +191,7 @@ namespace storm { accepting = false; break; } - if (this->isProduceSchedulerSet()) { - infSets.emplace_back(accSet); - } + } } else if (atom.getType() == cpphoafparser::AtomAcceptance::TEMPORAL_FIN) { @@ -224,33 +211,87 @@ namespace storm { if (this->isProduceSchedulerSet()) { - storm::storage::BitVector mecStates(transitionMatrix.getRowGroupCount(), false); + // Save all states contained in this MEC + storm::storage::BitVector mecStates(product->getProductModel().getNumberOfStates(), false); for (auto const &stateChoicePair : mec) { mecStates.set(stateChoicePair.first); } - // If there are no InfSets (either all TRUE or only FIN in conjunction) - if (infSets.empty()) { - // We want to visit some states of this MEC inf. often - infSets.emplace_back(mecStates); + // We know the MEC satisfied the conjunction: Save InfSets + std::set<uint_fast64_t> infSetIds; + for (auto const& literal : conjunction) { + storm::storage::BitVector infSet; + if (literal->isTRUE()) { + // All states + infSet = storm::storage::BitVector(product->getProductModel().getNumberOfStates(), true); + + } else if (literal->isAtom()) { + const cpphoafparser::AtomAcceptance &atom = literal->getAtom(); + if (atom.getType() == cpphoafparser::AtomAcceptance::TEMPORAL_INF) { + if (atom.isNegated()) { + infSet = ~acceptance.getAcceptanceSet(atom.getAcceptanceSet()); + + } else { + infSet = acceptance.getAcceptanceSet(atom.getAcceptanceSet()); + } + } + else if (atom.getType() == cpphoafparser::AtomAcceptance::TEMPORAL_FIN) { + // If there are FinSets in the conjunction we use the InfSet containing all states in this MEC + infSet = mecStates; + } + } + + // Save new InfSets + if (infSet.size() > 0) { + auto it = std::find(_infSets.get().begin(), _infSets.get().end(), infSet); + if (it == _infSets.get().end()) { + _infSets.get().emplace_back(infSet); + infSetIds.insert(_infSets.get().size() - 1); + } else { + // save ID for accCond of the MEC states + infSetIds.insert(distance(_infSets.get().begin(), it)); //TODO test + } + } } - // Save the states of this MEC (that are not contained in any other MEC yet) and the InfSets need to be visited inf. often to sat. the acc. cond. - _mecStatesInfSets.get().insert({accMECs, std::make_pair(mecStates & ~finishedStates, infSets)}); + /* should not occur + if (infSetIds.empty()) { - // Define scheduler choices for the states in this MEC (that are not in any other MEC) - for (uint_fast64_t infSet = 0; infSet < infSets.size(); ++infSet) { - // Scheduler that satisfies the MEC acceptance condition (visit each InfSet inf often, or switch to scheduler of another MEC) - storm::storage::Scheduler<ValueType> mecScheduler( - transitionMatrix.getRowGroupCount()); + auto it = std::find(_infSets.get().begin(), _infSets.get().end(), mecStates); + if(it == _infSets.get().end()) { + _infSets.get().emplace_back(mecStates); + infSetIds.insert(_infSets.get().size()-1); + } else { + // save ID for accCond of the MEC states + infSetIds.insert(distance(_infSets.get().begin(), it)); //TODO test + } + } + */ + // Save the InfSets into the _accInfSets for states in this MEC, but only if there weren't assigned to any other MEC yet. + storm::storage::BitVector newMecStates(product->getProductModel().getNumberOfStates(), false); + for (auto const &stateChoicePair : mec) { + if (_accInfSets.get()[stateChoicePair.first] == boost::none) { + // state wasn't assigned to any other MEC yet. + _accInfSets.get()[stateChoicePair.first] = infSetIds; + newMecStates.set(stateChoicePair.first); + + } + } - // Compute a scheduler that, with prob=1, reaches the infSet via mecStates starting from states that are not yet in other MEC - storm::utility::graph::computeSchedulerProb1E<ValueType>(_mecStatesInfSets.get()[accMECs].first, transitionMatrix, backwardTransitions, mecStates, _mecStatesInfSets.get()[accMECs].second[infSet], mecScheduler); - // Prob1E sets an arbitrary choice for the psi states, but we want to stay in this accepting mec. - for (auto pState : (_mecStatesInfSets.get()[accMECs].first & _mecStatesInfSets.get()[accMECs].second[infSet])) { + + // Define scheduler choices for the states in this MEC (that are not in any other MEC) + for (uint_fast64_t id : infSetIds) { + // Scheduler that satisfies the MEC acceptance condition (visit each InfSet inf often, or switch to scheduler of another MEC) + storm::storage::Scheduler<ValueType> mecScheduler(transitionMatrix.getRowGroupCount()); + + // States not in InfSet: Compute a scheduler that, with prob=1, reaches the infSet via mecStates starting from states that are not yet in other MEC + storm::utility::graph::computeSchedulerProb1E<ValueType>(newMecStates, transitionMatrix, backwardTransitions, mecStates, _infSets.get()[id], mecScheduler); + + // States that already reached the InfSet: Prob1E sets an arbitrary choice for the psi states, but we want to stay in this accepting mec. + for (auto pState : (newMecStates & _infSets.get()[id])) { // If we are in the InfSet, we stay in mec-states // TODO is this correct: // (*std::next(mec.getChoicesForState(pState).begin(), 0)) @@ -258,29 +299,19 @@ namespace storm { } // Extract scheduler choices (only for states that are already assigned a scheduler, i.e are in another MEC) - for (auto pState : _mecStatesInfSets.get()[accMECs].first) { - //if (!_mecStatesInfSets.get()[accMECs].second[infSet].get(pState)) { - // We want to reach the InfSet, save choice: <s, q, MEC, InfSet> ---> choice - // TODO find test that fails, when ignoring these: - this->_productChoices.get().insert({std::make_tuple(product->getModelState(pState),product->getAutomatonState(pState), accMECs, infSet), mecScheduler.getChoice(pState)}); + for (auto pState : newMecStates) { + // We want to reach the InfSet, save choice: <s, q, InfSetID> ---> choice + this->_productChoices.get().insert({std::make_tuple(product->getModelState(pState),product->getAutomatonState(pState), id), mecScheduler.getChoice(pState)}); } } - - // The states in this MEC will not be reassigned - finishedStates = finishedStates | mecStates; } } } } - if (this->isProduceSchedulerSet()) { - // Remaining states belong to no mec (REACH scheduler is computed later) - _mecStatesInfSets.get()[0] = std::make_pair(~finishedStates,std::vector<storm::storage::BitVector>(1,~finishedStates)); - } - STORM_LOG_DEBUG("Accepting states: " << acceptingStates); STORM_LOG_INFO("Found " << acceptingStates.getNumberOfSetBits() << " states in " << accMECs << " accepting MECs (considered " << allMECs << " MECs)."); @@ -399,29 +430,27 @@ namespace storm { prodNumericResult = std::move(prodCheckResult.values); if (this->isProduceSchedulerSet()) { // TODO create fct for this - _numberOfDaStates = da.getNumberOfStates(); + // TODO asserts _mecStatesInfSets initialized etc. // Extract the choices of the REACH-scheduler (choices to reach an acc. MEC) for the MDP-DA product: <s,q> -> choice for (storm::storage::sparse::state_type pState = 0; pState < product->getProductModel().getNumberOfStates(); ++pState) { - // <s,q, NoMec, 0> ---> choice + // for state <s,q> not in any accEC <s,q, REACH> ---> choice if(! acceptingStates.get(pState)){ // Do not overwrite choices of states in an accepting MEC - this->_productChoices.get().insert({std::make_tuple(product->getModelState(pState), product->getAutomatonState(pState), 0, 0), prodCheckResult.scheduler->getChoice(pState)}); + this->_productChoices.get().insert({std::make_tuple(product->getModelState(pState), product->getAutomatonState(pState), _infSets.get().size()), prodCheckResult.scheduler->getChoice(pState)}); + // For non-accepting states that are not in any accepting EC we use the 'last' copy of the DA + this->_accInfSets.get()[pState] = {this->_infSets.get().size()}; } } // Prepare the memory structure. For that, we need: transitions, initialMemoryStates (and memoryStateLabeling) - // Compute size of the resulting memory structure: a state corresponds to <q <mec, infSet>> encoded as (((infSet * |mecs|) + mec) * |DAStates|) +q - uint64 numCopies =0; - for (auto const& mec: _mecStatesInfSets.get()) { - numCopies += mec.second.second.size(); - } - uint64 numMemoryStates = numCopies * _mecStatesInfSets.get().size() * da.getNumberOfStates() + da.getNumberOfStates(); //TODO is this correct + // Compute size of the resulting memory structure: a state corresponds to <q, infSet>> encoded as (q* (|infSets|+1))+infSet + uint64 numMemoryStates = (da.getNumberOfStates() * (_infSets.get().size()+1)) + _infSets.get().size()+1; //+1 for states outside accECs - // The next move function of the memory, will be build based on the transitions of the DA. + // The next move function of the memory, will be build based on the transitions of the DA and jumps between InfSets. this->_memoryTransitions.emplace(numMemoryStates, std::vector<storm::storage::BitVector>(numMemoryStates, storm::storage::BitVector(this->_transitionMatrix.getRowGroupCount(), false))); @@ -431,43 +460,42 @@ namespace storm { for (storm::storage::sparse::state_type modelState = 0; modelState < this->_transitionMatrix.getRowGroupCount(); ++modelState) { if(!product->isValidProductState(modelState, automatonTo)) { - // Memory state successor of the modelState-transition emanating <automatonFrom, ?, ? > not defined/reachable. + // Memory state successor of the modelState-transition emanating <automatonFrom, * > not defined/reachable. // TODO save as unreachable in scheduler // STORM_PRINT("set to unreachable : (" << modelState <<" , " << automatonTo <<")"); } else if (automatonTo == productBuilder.getSuccessor(modelState, automatonFrom, modelState)) { //TODO remove first parameter of getSuccessor - // Add the modelState to one outgoing transition of all states of the form <automatonFrom <mec, InfSet>> (mec=0 equals NoMec) - for (uint_fast64_t mec = 0; mec < _mecStatesInfSets.get().size(); ++mec) { - for (uint_fast64_t infSet = 0; infSet < _mecStatesInfSets.get()[mec].second.size(); ++infSet) { - - // Find the goalState <automatonTo <mec', InfSet'>>, where <modelState, automatonTo> is in mec'. - if (_mecStatesInfSets.get()[mec].first.get(product->getProductStateIndex(modelState, automatonTo))) { - // <modelState, automatonTo> in contained in this MEC. Now check if we have reached the current InfSet. - if(_mecStatesInfSets.get()[mec].second[infSet].get(product->getProductStateIndex(modelState, automatonTo))){ - // InfSet satisfied: Add modelState to the transition from <automatonFrom <mec, InfSet>> to <automatonTo, <mec, NextInfSet>>. - uint64 from = (((infSet * _mecStatesInfSets.get().size()) + mec) * da.getNumberOfStates()) + automatonFrom; - uint64 to = ((((infSet+1 < _mecStatesInfSets.get()[mec].second.size() ? infSet+1 : 0) * _mecStatesInfSets.get().size()) + mec) * da.getNumberOfStates()) + automatonTo; - _memoryTransitions.get()[from][to].set(modelState); - } else { - // InfSet not satisfied: Add modelState to the transition from <automatonFrom <mec, InfSet>> to <automatonTo, <mec, InfSet>>. - uint64 from = (((infSet * _mecStatesInfSets.get().size()) + mec) * da.getNumberOfStates()) + automatonFrom; - uint64 to = (((infSet * _mecStatesInfSets.get().size()) + mec) * da.getNumberOfStates()) + automatonTo; - _memoryTransitions.get()[from][to].set(modelState); - } + // Add the modelState to one outgoing transition of all states of the form <automatonFrom, InfSet> (Inf=lenInfSet equals not in MEC) + + // For the accepting states we jump through copies of the DA wrt. the infinity sets. + for (uint_fast64_t infSet = 0; infSet < _infSets.get().size()+1; ++infSet) { + // Check if we need to switch the acceptance condition + if (_accInfSets.get()[product->getProductStateIndex(modelState, automatonTo)].get().count(infSet) == 0) { + // the state is is in a different accepting MEC with a different accepting conjunction of InfSets. + auto newInfSet = _accInfSets.get()[product->getProductStateIndex(modelState, automatonTo)].get().begin(); + // Add modelState to the transition from <automatonFrom, InfSet>> to <automatonTo, firstInfSet>. + _memoryTransitions.get()[(automatonFrom * (_infSets.get().size()+1)) + infSet][(automatonTo * (_infSets.get().size()+1)) + *newInfSet].set(modelState); + + } else { + // The state is either not in an accepting EC or in an accepting EC that needs to satisfy the infSet. + if (infSet == _infSets.get().size() || _infSets.get()[infSet].get(product->getProductStateIndex(modelState, automatonTo))) { + // <modelState, automatonTo> is not in any accepting EC or does not satisfy the InfSet, we stay there. + // Add modelState to the transition from <automatonFrom, InfSet> to <automatonTo, InfSet> + _memoryTransitions.get()[(automatonFrom * (_infSets.get().size()+1)) + infSet][(automatonTo * (_infSets.get().size()+1)) + infSet].set(modelState); } else { - // We need to find the unique MEC containing <modelState, automatonTo> and start in InfSet 0. - for (uint_fast64_t nextMec = 0; nextMec < _mecStatesInfSets.get().size(); ++nextMec) { - if (_mecStatesInfSets.get()[nextMec].first.get(product->getProductStateIndex(modelState, automatonTo))) { - // Add modelState to the transition from <automatonFrom <mec, InfSet>> to <automatonTo, nextMec, InfSet>> - uint64 from = (((infSet * _mecStatesInfSets.get().size()) + mec) * da.getNumberOfStates()) + automatonFrom; - uint64 to = (((0 * _mecStatesInfSets.get().size()) + nextMec) * da.getNumberOfStates()) + automatonTo; - _memoryTransitions.get()[from][to].set(modelState); - break; // Can stop, because the state is only contained in one MEC. - } + STORM_LOG_ASSERT(_accInfSets.get()[product->getProductStateIndex(modelState, automatonTo)] != boost::none, "The list of InfSets for the product state <" <<modelState<< ", " << automatonTo<<"> is undefined."); + // <modelState, automatonTo> satisfies the InfSet, find the next one + auto it = std::find(_accInfSets.get()[product->getProductStateIndex(modelState, automatonTo)].get().begin(), _accInfSets.get()[product->getProductStateIndex(modelState, automatonTo)].get().end(), infSet); + STORM_LOG_ASSERT(it != _accInfSets.get()[product->getProductStateIndex(modelState, automatonTo)].get().end(), "The list of InfSets for the product state <" <<modelState<< ", " << automatonTo<<"> does not contain the infSet " << infSet); + it++; + if (it == _accInfSets.get()[product->getProductStateIndex(modelState, automatonTo)].get().end()) { + // Start again. + it = _accInfSets.get()[product->getProductStateIndex(modelState, automatonTo)].get().begin(); } + // Add modelState to the transition from <automatonFrom <mec, InfSet>> to <automatonTo, <mec, NextInfSet>>. + _memoryTransitions.get()[(automatonFrom * (_infSets.get().size()+1)) + infSet][(automatonTo * (_infSets.get().size()+1)) + *it].set(modelState); } } - } } } @@ -478,17 +506,18 @@ namespace storm { // Find initial memory states this->_memoryInitialStates.emplace(); this->_memoryInitialStates->resize(this->_transitionMatrix.getRowGroupCount()); - // Save for each relevant model state its initial memory state (get the s-successor of q0) + // Save for each relevant model state its initial memory state (get the s-successor q of q0) for (storm::storage::sparse::state_type modelState : statesOfInterest) { - storm::storage::sparse::state_type automatonInit = productBuilder.getInitialState(modelState); - STORM_LOG_ASSERT(product->isValidProductState(modelState, automatonInit), "The memory successor state for the model state "<< modelState << "does not exist in the DA-Model Product."); - - // Search mec which contains <automatonInit, modelState> - for (uint_fast64_t mec = 0; mec < _mecStatesInfSets.get().size(); ++mec) { - if (_mecStatesInfSets.get()[mec].first.get(product->getProductStateIndex(modelState, automatonInit))) { - this->_memoryInitialStates.get().at(modelState) = (((0 * _mecStatesInfSets.get().size()) + mec) * da.getNumberOfStates()) + automatonInit; - break; - } + 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."); + if (acceptingStates[product->getProductStateIndex(modelState, automatonState)]) { + STORM_LOG_ASSERT(_accInfSets.get()[product->getProductStateIndex(modelState, automatonState)] != boost::none, "The list of InfSets for the product state <" <<modelState<< ", " << automatonState<<"> is undefined."); + // If <s, q> is an accepting state start in the first InfSet of <s, q>. + auto infSet = _accInfSets.get()[product->getProductStateIndex(modelState, automatonState)].get().begin(); + _memoryInitialStates.get()[modelState] = (automatonState * (_infSets.get().size()+1)) + *infSet; + + } else { + _memoryInitialStates.get()[modelState] = (automatonState * (_infSets.get().size()+1)) + _infSets.get().size(); } } diff --git a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h index 35bcfd220..d73fe39b4 100644 --- a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h +++ b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h @@ -97,12 +97,13 @@ namespace storm { std::size_t _numberOfStates; //TODO just use _transitionMatrix.getRowGroupCount instead? // REACH scheduler and MEC scheduler - boost::optional<std::map <std::tuple<uint_fast64_t, uint_fast64_t, uint_fast64_t, uint_fast64_t>, storm::storage::SchedulerChoice<ValueType>>> _productChoices; // <s, q, MEC, InfSet> ---> ReachChoice and <s, q, MEC, InfSet> ---> MecChoice - boost::optional<std::map <uint_fast64_t, std::pair<storm::storage::BitVector, std::vector<storm::storage::BitVector>>>> _mecStatesInfSets; // Save for each accepting mec, its states <s, q> and the infinity sets that need to be visited inf. often (mec 0 corresponds to NoMec) + boost::optional<std::map <std::tuple<uint_fast64_t, uint_fast64_t, uint_fast64_t>, storm::storage::SchedulerChoice<ValueType>>> _productChoices; // <s, q, len(_infSets)> ---> ReachChoice and <s, q, InfSet> ---> MecChoice + boost::optional<std::vector<storm::storage::BitVector>> _infSets; // Save the InfSets of the Acceptance condition. + boost::optional<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 boost::optional<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). - boost::optional<std::vector<uint_fast64_t>> _memoryInitialStates; // Save for each stateOfInterest s its initial memory state (which memory state is reached from the initial state after reading s) - boost::optional<std::size_t> _numberOfDaStates; + boost::optional<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) }; } diff --git a/src/storm/storage/memorystructure/MemoryStructureBuilder.cpp b/src/storm/storage/memorystructure/MemoryStructureBuilder.cpp index f3a3818cc..f659e3381 100644 --- a/src/storm/storage/memorystructure/MemoryStructureBuilder.cpp +++ b/src/storm/storage/memorystructure/MemoryStructureBuilder.cpp @@ -24,7 +24,7 @@ namespace storm { 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(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(); + auto initMemStateIt = initialMemoryStates.begin(); // TODO allow all for (auto initState : model.getInitialStates()) { if (initState == initialModelState) { *initMemStateIt = initialMemoryState; diff --git a/src/storm/utility/graph.cpp b/src/storm/utility/graph.cpp index d5ca015c3..76203dbe9 100644 --- a/src/storm/utility/graph.cpp +++ b/src/storm/utility/graph.cpp @@ -1893,7 +1893,6 @@ 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); - // TODO remove? 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) ; diff --git a/src/test/storm/modelchecker/prctl/mdp/SchedulerGenerationMdpPrctlModelCheckerTest.cpp b/src/test/storm/modelchecker/prctl/mdp/SchedulerGenerationMdpPrctlModelCheckerTest.cpp index ba1e350dd..683cb14c7 100755 --- a/src/test/storm/modelchecker/prctl/mdp/SchedulerGenerationMdpPrctlModelCheckerTest.cpp +++ b/src/test/storm/modelchecker/prctl/mdp/SchedulerGenerationMdpPrctlModelCheckerTest.cpp @@ -232,7 +232,7 @@ namespace { auto inducedModel = mdp->applyScheduler(scheduler); ASSERT_EQ(inducedModel->getType(), storm::models::ModelType::Mdp); - auto const &inducedMdp = inducedModel->template as<storm::models::sparse::Mdp<ValueType>>(); // TODO DTMC! + 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); From bdb2aa8de97efe0059304bff829ebea96e2d02f2 Mon Sep 17 00:00:00 2001 From: hannah <hannah.mertens@rwth-aachen.de> Date: Fri, 16 Jul 2021 16:40:10 +0200 Subject: [PATCH 101/172] fixed scheduler output Conflicts: src/storm/storage/Scheduler.cpp --- src/storm/storage/Scheduler.cpp | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/src/storm/storage/Scheduler.cpp b/src/storm/storage/Scheduler.cpp index 8b8431e24..4dbc1df8f 100644 --- a/src/storm/storage/Scheduler.cpp +++ b/src/storm/storage/Scheduler.cpp @@ -216,11 +216,20 @@ namespace storm { } // Print memory updates + if(!isMemorylessScheduler()) { - out << " "; + stateString << std::setw(30); //todo set width for (auto const& choiceProbPair : choice.getChoiceAsDistribution()) { - for (auto entryIt = model->getTransitionMatrix().getRow(state + choiceProbPair.first).begin(); entryIt < model->getTransitionMatrix().getRow(state + choiceProbPair.first).end(); ++entryIt) { - out << ", model state' = " << entryIt->getColumn() << ": (transition = " << entryIt - model->getTransitionMatrix().begin() << ") -> " << "(m' = "<<this->memoryStructure->getSuccessorMemoryState(memoryState, entryIt - model->getTransitionMatrix().begin()) <<")"; + 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() << ": (transition = " << entryIt - model->getTransitionMatrix().begin() << ") -> " << "(m' = "<<this->memoryStructure->getSuccessorMemoryState(memoryState, entryIt - model->getTransitionMatrix().begin()) <<")"; + //out << ", model state' = " << entryIt->getColumn() << ": (transition = " << entryIt - model->getTransitionMatrix().begin() << ") -> " << "(m' = ?) "; } } From 1191e3068fff7ec6a710e1aeba5c7b680b257309 Mon Sep 17 00:00:00 2001 From: hannah <hannah.mertens@rwth-aachen.de> Date: Fri, 16 Jul 2021 16:40:41 +0200 Subject: [PATCH 102/172] more ltl scheduler tests --- ...ulerGenerationMdpPrctlModelCheckerTest.cpp | 87 +++++++++++++++++-- 1 file changed, 78 insertions(+), 9 deletions(-) diff --git a/src/test/storm/modelchecker/prctl/mdp/SchedulerGenerationMdpPrctlModelCheckerTest.cpp b/src/test/storm/modelchecker/prctl/mdp/SchedulerGenerationMdpPrctlModelCheckerTest.cpp index 683cb14c7..e7ee44930 100755 --- a/src/test/storm/modelchecker/prctl/mdp/SchedulerGenerationMdpPrctlModelCheckerTest.cpp +++ b/src/test/storm/modelchecker/prctl/mdp/SchedulerGenerationMdpPrctlModelCheckerTest.cpp @@ -208,7 +208,7 @@ namespace { typedef typename TestFixture::ValueType ValueType; // TODO skip without LTL support - std::string formulasString = "Pmax=? [X X \"target\"]; Pmin=? [G F \"target\"]; Pmax=? [(G F s>2) & (F G !(s=3))];"; + 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); @@ -223,9 +223,11 @@ namespace { { 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::settings::getModule<storm::settings::modules::GeneralSettings>().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()); @@ -238,11 +240,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("9/10"), inducedResult->template asExplicitQuantitativeCheckResult<ValueType>()[*mdp->getInitialStates().begin()],storm::settings::getModule<storm::settings::modules::GeneralSettings>().getPrecision()); + EXPECT_NEAR(this->parseNumber("81/100"), inducedResult->template asExplicitQuantitativeCheckResult<ValueType>()[*inducedMdp->getInitialStates().begin()],storm::settings::getModule<storm::settings::modules::GeneralSettings>().getPrecision()); } { 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::settings::getModule<storm::settings::modules::GeneralSettings>().getPrecision()); ASSERT_TRUE(result->template asExplicitQuantitativeCheckResult<ValueType>().hasScheduler()); storm::storage::Scheduler<ValueType> const &scheduler = result->template asExplicitQuantitativeCheckResult<ValueType>().getScheduler(); @@ -256,14 +259,14 @@ 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("1/2"),inducedResult->template asExplicitQuantitativeCheckResult<ValueType>()[*mdp->getInitialStates().begin()],storm::settings::getModule<storm::settings::modules::GeneralSettings>().getPrecision()); + EXPECT_NEAR(this->parseNumber("1/2"),inducedResult->template asExplicitQuantitativeCheckResult<ValueType>()[*inducedMdp->getInitialStates().begin()],storm::settings::getModule<storm::settings::modules::GeneralSettings>().getPrecision()); } { 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::settings::getModule<storm::settings::modules::GeneralSettings>().getPrecision()); - ASSERT_TRUE(result->isExplicitQuantitativeCheckResult()); ASSERT_TRUE(result->template asExplicitQuantitativeCheckResult<ValueType>().hasScheduler()); storm::storage::Scheduler<ValueType> const &scheduler = result->template asExplicitQuantitativeCheckResult<ValueType>().getScheduler(); @@ -279,14 +282,12 @@ namespace { auto inducedResult = inducedChecker.check(this->env(), tasks[2]); ASSERT_TRUE(inducedResult->isExplicitQuantitativeCheckResult()); EXPECT_NEAR(this->parseNumber("1/2"), - inducedResult->template asExplicitQuantitativeCheckResult<ValueType>()[*mdp->getInitialStates().begin()], + inducedResult->template asExplicitQuantitativeCheckResult<ValueType>()[*inducedMdp->getInitialStates().begin()], storm::settings::getModule<storm::settings::modules::GeneralSettings>().getPrecision()); } - } - - TYPED_TEST(SchedulerGenerationMdpPrctlModelCheckerTest, ltlMec) { + TYPED_TEST(SchedulerGenerationMdpPrctlModelCheckerTest, ltlNondetChoice) { typedef typename TestFixture::ValueType ValueType; // TODO skip without LTL support // Nondeterministic choice in an accepting EC. @@ -305,6 +306,8 @@ namespace { { auto result = checker.check(this->env(), tasks[0]); ASSERT_TRUE(result->isExplicitQuantitativeCheckResult()); + EXPECT_NEAR(this->parseNumber("0.5"),result->template asExplicitQuantitativeCheckResult<ValueType>()[*mdp->getInitialStates().begin()], + storm::settings::getModule<storm::settings::modules::GeneralSettings>().getPrecision()); ASSERT_TRUE(result->template asExplicitQuantitativeCheckResult<ValueType>().hasScheduler()); storm::storage::Scheduler<ValueType> const &scheduler = result->template asExplicitQuantitativeCheckResult<ValueType>().getScheduler(); @@ -315,7 +318,7 @@ namespace { ASSERT_EQ(inducedModel->getType(), storm::models::ModelType::Mdp); - auto const &inducedMdp = inducedModel->template as<storm::models::sparse::Mdp<ValueType>>(); // TODO DTMC! + 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); @@ -326,4 +329,70 @@ namespace { } + + TYPED_TEST(SchedulerGenerationMdpPrctlModelCheckerTest, ltlUnsat) { + typedef typename TestFixture::ValueType ValueType; + // TODO skip without LTL 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); + + { + 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::settings::getModule<storm::settings::modules::GeneralSettings>().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, true); + + 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::settings::getModule<storm::settings::modules::GeneralSettings>().getPrecision()); + } + + { + 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::settings::getModule<storm::settings::modules::GeneralSettings>().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, true); + + + 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::settings::getModule<storm::settings::modules::GeneralSettings>().getPrecision()); + } + + } + } \ No newline at end of file From b8712041bfecea12676e4628df7d65c48d47cbc8 Mon Sep 17 00:00:00 2001 From: hannah <hannah.mertens@rwth-aachen.de> Date: Fri, 16 Jul 2021 16:41:42 +0200 Subject: [PATCH 103/172] fixed memory structure --- .../helper/ltl/SparseLTLHelper.cpp | 83 ++++++++++--------- .../modelchecker/helper/ltl/SparseLTLHelper.h | 5 +- 2 files changed, 46 insertions(+), 42 deletions(-) diff --git a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp index 57efb19c3..a6502927b 100644 --- a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp +++ b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp @@ -31,9 +31,18 @@ namespace storm { 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->_productChoices.is_initialized(), "Trying to extract the produced scheduler but none is available. Was there a computation call before?"); + // If Pmax(phi) = 0 or Pmin(phi) = 1, we return a memoryless scheduler with arbitrary choices + if (_randomScheduler) { + storm::storage::Scheduler<ValueType> scheduler(this->_transitionMatrix.getRowGroupCount()); + for (storm::storage::sparse::state_type state = 0; state < this->_transitionMatrix.getRowGroupCount(); ++state) { + scheduler.setChoice(0, state); + + } + return scheduler; + } - // TODO fails for No accepting states, skipping probability computation. + // Otherwise, we compute a scheduler with memory. + STORM_LOG_ASSERT(this->_productChoices.is_initialized(), "Trying to extract the produced scheduler but none is available. Was there a computation call before?"); STORM_LOG_ASSERT(this->_memoryTransitions.is_initialized(), "Trying to extract the DA transition structure but none is available. Was there a computation call before?"); STORM_LOG_ASSERT(this->_memoryInitialStates.is_initialized(), "Trying to extract the initial states of the DA but there are none available. Was there a computation call before?"); @@ -50,7 +59,7 @@ namespace storm { } // initialMemoryStates: Assign an initial memory state to each initial state of the model. - for (uint_fast64_t s0 : model.getInitialStates()) { // TODO set all from _memoryInitialStates, not only mdoelInitial + for (uint_fast64_t s0 : model.getInitialStates()) { // TODO set all from _memoryInitialStates, not only modelInitial memoryBuilder.setInitialMemoryState(s0, this->_memoryInitialStates.get()[s0]); } @@ -67,7 +76,7 @@ namespace storm { storm::storage::sparse::state_type automatonState = std::get<1>(choice.first); uint_fast64_t infSet = std::get<2>(choice.first); - scheduler.setChoice(choice.second, modelState, automatonState*(_infSets.get().size()+1)+ infSet); + scheduler.setChoice(choice.second, modelState, (automatonState*(_infSets.get().size()+1))+ infSet); } // TODO // set non-reachable (modelState,memoryState)-Pairs (i.e. those that are not contained in _productChoices) to "unreachable", (extend Scheduler by something like std::vector<std::Bitvector>> reachableSchedulerChoices; und isChoiceReachable(..)) @@ -245,30 +254,15 @@ namespace storm { if (infSet.size() > 0) { auto it = std::find(_infSets.get().begin(), _infSets.get().end(), infSet); if (it == _infSets.get().end()) { + infSetIds.insert(_infSets.get().size()); _infSets.get().emplace_back(infSet); - infSetIds.insert(_infSets.get().size() - 1); } else { // save ID for accCond of the MEC states - infSetIds.insert(distance(_infSets.get().begin(), it)); //TODO test + infSetIds.insert(distance(_infSets.get().begin(), it)); } } } - /* should not occur - if (infSetIds.empty()) { - - auto it = std::find(_infSets.get().begin(), _infSets.get().end(), mecStates); - if(it == _infSets.get().end()) { - _infSets.get().emplace_back(mecStates); - infSetIds.insert(_infSets.get().size()-1); - } else { - // save ID for accCond of the MEC states - infSetIds.insert(distance(_infSets.get().begin(), it)); //TODO test - } - - } - */ - // Save the InfSets into the _accInfSets for states in this MEC, but only if there weren't assigned to any other MEC yet. storm::storage::BitVector newMecStates(product->getProductModel().getNumberOfStates(), false); for (auto const &stateChoicePair : mec) { @@ -288,23 +282,24 @@ namespace storm { storm::storage::Scheduler<ValueType> mecScheduler(transitionMatrix.getRowGroupCount()); // States not in InfSet: Compute a scheduler that, with prob=1, reaches the infSet via mecStates starting from states that are not yet in other MEC - storm::utility::graph::computeSchedulerProb1E<ValueType>(newMecStates, transitionMatrix, backwardTransitions, mecStates, _infSets.get()[id], mecScheduler); + storm::utility::graph::computeSchedulerProb1E<ValueType>(newMecStates, transitionMatrix, backwardTransitions, mecStates, _infSets.get()[id] & mecStates, mecScheduler); //todo &mecstates? nec.? // States that already reached the InfSet: Prob1E sets an arbitrary choice for the psi states, but we want to stay in this accepting mec. + for (auto pState : (newMecStates & _infSets.get()[id])) { // If we are in the InfSet, we stay in mec-states - // TODO is this correct: - // (*std::next(mec.getChoicesForState(pState).begin(), 0)) - mecScheduler.setChoice(storm::storage::SchedulerChoice<ValueType>((*std::next(mec.getChoicesForState(pState).begin()), 0)), pState); + // TODO these are global? + storm::storage::FlatSet<uint_fast64_t> test = mec.getChoicesForState(pState); + mecScheduler.setChoice(0, pState); //todo get first choice from mec.getChoicesForState(pState); but need local + } // Extract scheduler choices (only for states that are already assigned a scheduler, i.e are in another MEC) for (auto pState : newMecStates) { // We want to reach the InfSet, save choice: <s, q, InfSetID> ---> choice - this->_productChoices.get().insert({std::make_tuple(product->getModelState(pState),product->getAutomatonState(pState), id), mecScheduler.getChoice(pState)}); + this->_productChoices.get().insert({std::make_tuple(product->getModelState(pState), product->getAutomatonState(pState), id), mecScheduler.getChoice(pState)}); } - } } } @@ -361,7 +356,7 @@ namespace storm { } - STORM_LOG_INFO("Building "+ (Nondeterministic ? std::string("MDP-DA") : std::string("DTMC-DA")) +"product with deterministic automaton, starting from " << statesOfInterest.getNumberOfSetBits() << " model states..."); + 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); typename transformer::DAProduct<productModelType>::ptr product = productBuilder.build<productModelType>(this->_transitionMatrix, statesOfInterest); @@ -397,6 +392,7 @@ namespace storm { if (acceptingStates.empty()) { STORM_LOG_INFO("No accepting states, skipping probability computation."); std::vector<ValueType> numericResult(this->_numberOfStates, storm::utility::zero<ValueType>()); + this->_randomScheduler = true; return numericResult; } @@ -434,15 +430,14 @@ namespace storm { // TODO asserts _mecStatesInfSets initialized etc. // Extract the choices of the REACH-scheduler (choices to reach an acc. MEC) for the MDP-DA product: <s,q> -> choice - for (storm::storage::sparse::state_type pState = 0; - pState < product->getProductModel().getNumberOfStates(); ++pState) { + for (storm::storage::sparse::state_type pState : ~acceptingStates) { // for state <s,q> not in any accEC <s,q, REACH> ---> choice - if(! acceptingStates.get(pState)){ - // Do not overwrite choices of states in an accepting MEC - this->_productChoices.get().insert({std::make_tuple(product->getModelState(pState), product->getAutomatonState(pState), _infSets.get().size()), prodCheckResult.scheduler->getChoice(pState)}); - // For non-accepting states that are not in any accepting EC we use the 'last' copy of the DA - this->_accInfSets.get()[pState] = {this->_infSets.get().size()}; - } + + // Do not overwrite choices of states in an accepting MEC + this->_productChoices.get().insert({std::make_tuple(product->getModelState(pState), product->getAutomatonState(pState), _infSets.get().size()), prodCheckResult.scheduler->getChoice(pState)}); + // For non-accepting states that are not in any accepting EC we use the 'last' copy of the DA + this->_accInfSets.get()[pState] = {this->_infSets.get().size()}; + } // Prepare the memory structure. For that, we need: transitions, initialMemoryStates (and memoryStateLabeling) @@ -462,23 +457,31 @@ namespace storm { if(!product->isValidProductState(modelState, automatonTo)) { // Memory state successor of the modelState-transition emanating <automatonFrom, * > not defined/reachable. // TODO save as unreachable in scheduler - // STORM_PRINT("set to unreachable : (" << modelState <<" , " << automatonTo <<")"); + //STORM_PRINT("set to unreachable : <" << modelState <<" , " << automatonTo <<">"); } else if (automatonTo == productBuilder.getSuccessor(modelState, automatonFrom, modelState)) { //TODO remove first parameter of getSuccessor // Add the modelState to one outgoing transition of all states of the form <automatonFrom, InfSet> (Inf=lenInfSet equals not in MEC) + // For non-accepting states that are not in any accepting EC we use the 'last' copy of the DA + // For the accepting states we jump through copies of the DA wrt. the infinity sets. for (uint_fast64_t infSet = 0; infSet < _infSets.get().size()+1; ++infSet) { + // Check if we need to switch the acceptance condition if (_accInfSets.get()[product->getProductStateIndex(modelState, automatonTo)].get().count(infSet) == 0) { // the state is is in a different accepting MEC with a different accepting conjunction of InfSets. auto newInfSet = _accInfSets.get()[product->getProductStateIndex(modelState, automatonTo)].get().begin(); - // Add modelState to the transition from <automatonFrom, InfSet>> to <automatonTo, firstInfSet>. - _memoryTransitions.get()[(automatonFrom * (_infSets.get().size()+1)) + infSet][(automatonTo * (_infSets.get().size()+1)) + *newInfSet].set(modelState); + + // todo Never switch from NoMc to Mec? + //if (*newInfSet != _infSets.get().size() ){ + // Add modelState to the transition from <automatonFrom, InfSet>> to <automatonTo, firstInfSet>. + _memoryTransitions.get()[(automatonFrom * (_infSets.get().size()+1)) + infSet][(automatonTo * (_infSets.get().size()+1)) + *newInfSet].set(modelState); + // } + } else { // The state is either not in an accepting EC or in an accepting EC that needs to satisfy the infSet. - if (infSet == _infSets.get().size() || _infSets.get()[infSet].get(product->getProductStateIndex(modelState, automatonTo))) { + if (infSet == _infSets.get().size() || !(_infSets.get()[infSet].get(product->getProductStateIndex(modelState, automatonTo)))) { // <modelState, automatonTo> is not in any accepting EC or does not satisfy the InfSet, we stay there. // Add modelState to the transition from <automatonFrom, InfSet> to <automatonTo, InfSet> _memoryTransitions.get()[(automatonFrom * (_infSets.get().size()+1)) + infSet][(automatonTo * (_infSets.get().size()+1)) + infSet].set(modelState); diff --git a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h index d73fe39b4..d60027ade 100644 --- a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h +++ b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h @@ -96,11 +96,12 @@ namespace storm { storm::storage::SparseMatrix<ValueType> const& _transitionMatrix; std::size_t _numberOfStates; //TODO just use _transitionMatrix.getRowGroupCount instead? - // REACH scheduler and MEC scheduler + // scheduler + bool _randomScheduler = false; boost::optional<std::map <std::tuple<uint_fast64_t, uint_fast64_t, uint_fast64_t>, storm::storage::SchedulerChoice<ValueType>>> _productChoices; // <s, q, len(_infSets)> ---> ReachChoice and <s, q, InfSet> ---> MecChoice + boost::optional<std::vector<storm::storage::BitVector>> _infSets; // Save the InfSets of the Acceptance condition. boost::optional<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 boost::optional<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). boost::optional<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) From 5c204182eb55bd86588a66c13d0e1df052f778fc Mon Sep 17 00:00:00 2001 From: Tim Quatmann <tim.quatmann@cs.rwth-aachen.de> Date: Tue, 20 Jul 2021 14:16:16 +0200 Subject: [PATCH 104/172] Added some todos Conflicts: src/storm/modelchecker/prctl/helper/SparseMdpPrctlHelper.cpp src/storm/storage/Scheduler.h --- .../prctl/helper/SparseMdpPrctlHelper.cpp | 284 +++++++++--------- src/storm/storage/Scheduler.h | 8 +- .../memorystructure/MemoryStructureBuilder.h | 2 +- 3 files changed, 149 insertions(+), 145 deletions(-) diff --git a/src/storm/modelchecker/prctl/helper/SparseMdpPrctlHelper.cpp b/src/storm/modelchecker/prctl/helper/SparseMdpPrctlHelper.cpp index 17bef0ff8..9193c8f26 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,10 +429,10 @@ 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)) { @@ -443,7 +443,7 @@ namespace storm { } } #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,38 +583,38 @@ 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>()); - + // 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); @@ -629,7 +629,7 @@ namespace storm { } std::vector<ValueType> maybeStateChoiceValues = std::vector<ValueType>(sizeMaybeStateChoiceValues, storm::utility::zero<ValueType>()); - + // TODO: if a scheduler is to be produced and maybestatesNotRelevant is true, we have to set the scheduler for maybsetsates as "unreachable" TODO // 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 +640,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 +710,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 +745,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 +804,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 +819,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 +850,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 +858,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 +877,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 +893,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 +917,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 +934,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 +950,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 +961,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 +974,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 +983,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 +1000,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 +1023,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 +1042,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 +1063,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 +1109,7 @@ namespace storm { goal.setRelevantValues(std::move(newRelevantValues)); } } - + return result; } else { STORM_LOG_DEBUG("Not eliminating ECs as there are none."); @@ -1117,10 +1117,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 +1130,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 +1168,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 +1182,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 +1191,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 +1216,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 +1232,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 +1252,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 +1273,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 +1306,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 +1344,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 +1355,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 +1366,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/storage/Scheduler.h b/src/storm/storage/Scheduler.h index 43c7bb1cb..5107bb1cf 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 { @@ -65,7 +66,7 @@ namespace storm { 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; @@ -127,8 +128,11 @@ namespace storm { std::vector<std::vector<SchedulerChoice<ValueType>>> schedulerChoices; bool printUndefinedChoices = false; - uint_fast64_t numOfUndefinedChoices; + + std::vector<storm::storage::BitVector> reachableStates; + uint_fast64_t numOfUndefinedChoices; // Only consider reachable ones uint_fast64_t numOfDeterministicChoices; + uint_fast64_t numOfUnreachableStates; }; } } diff --git a/src/storm/storage/memorystructure/MemoryStructureBuilder.h b/src/storm/storage/memorystructure/MemoryStructureBuilder.h index bb310ccf3..0b3c6e9cf 100644 --- a/src/storm/storage/memorystructure/MemoryStructureBuilder.h +++ b/src/storm/storage/memorystructure/MemoryStructureBuilder.h @@ -19,7 +19,7 @@ namespace storm { * @param numberOfMemoryStates The number of states the resulting memory structure should have */ MemoryStructureBuilder(uint_fast64_t numberOfMemoryStates, storm::models::sparse::Model<ValueType, RewardModelType> const& model); - + // TODO: Add variant with a flag: Consider non-initial model states /*! * Initializes a new builder with the data from the provided memory structure */ From 6865ae14640bacd54a9d609b3be49d78ca19b8fc Mon Sep 17 00:00:00 2001 From: hannah <hannah.mertens@rwth-aachen.de> Date: Tue, 20 Jul 2021 16:31:49 +0200 Subject: [PATCH 105/172] build memory structure from all states --- .../helper/ltl/SparseLTLHelper.cpp | 35 ++++++++++------- .../memorystructure/MemoryStructure.cpp | 18 +++++++-- .../storage/memorystructure/MemoryStructure.h | 6 ++- .../MemoryStructureBuilder.cpp | 39 ++++++++++++++----- .../memorystructure/MemoryStructureBuilder.h | 10 ++++- .../SparseModelMemoryProduct.cpp | 14 +++++-- ...ulerGenerationMdpPrctlModelCheckerTest.cpp | 12 ++++-- 7 files changed, 100 insertions(+), 34 deletions(-) diff --git a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp index a6502927b..e097eaab5 100644 --- a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp +++ b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp @@ -47,8 +47,8 @@ namespace storm { STORM_LOG_ASSERT(this->_memoryInitialStates.is_initialized(), "Trying to extract the initial states of the DA but there are none available. Was there a computation call before?"); - // Create a memory structure for the MDP scheduler with memory. - typename storm::storage::MemoryStructureBuilder<ValueType>::MemoryStructureBuilder memoryBuilder(this->_memoryTransitions.get().size(), model); + // Create a memory structure for the MDP scheduler with memory. If hasRelevantStates is set, we only consider initial model states relevant. + typename storm::storage::MemoryStructureBuilder<ValueType>::MemoryStructureBuilder memoryBuilder(this->_memoryTransitions.get().size(), model, this->hasRelevantStates()); // Build the transitions between the memory states: startState--- modelStates (transitionVector) --->goalState for (storm::storage::sparse::state_type startState = 0; startState < this->_memoryTransitions.get().size(); ++startState) { @@ -58,11 +58,20 @@ namespace storm { } } - // initialMemoryStates: Assign an initial memory state to each initial state of the model. - for (uint_fast64_t s0 : model.getInitialStates()) { // TODO set all from _memoryInitialStates, not only modelInitial - memoryBuilder.setInitialMemoryState(s0, this->_memoryInitialStates.get()[s0]); + // initialMemoryStates: Assign an initial memory state model states + if (this->hasRelevantStates()) { + // Only consider initial model states + for (uint_fast64_t modelState : model.getInitialStates()) { + memoryBuilder.setInitialMemoryState(modelState, this->_memoryInitialStates.get()[modelState]); + } + } else { + // All model states are relevant + for (uint_fast64_t modelState = 0; modelState < model.getNumberOfStates(); ++modelState) { + memoryBuilder.setInitialMemoryState(modelState, this->_memoryInitialStates.get()[modelState]); + } } + // Now, we can build the memoryStructure. storm::storage::MemoryStructure memoryStructure = memoryBuilder.build(); @@ -79,7 +88,13 @@ namespace storm { scheduler.setChoice(choice.second, modelState, (automatonState*(_infSets.get().size()+1))+ infSet); } // TODO - // set non-reachable (modelState,memoryState)-Pairs (i.e. those that are not contained in _productChoices) to "unreachable", (extend Scheduler by something like std::vector<std::Bitvector>> reachableSchedulerChoices; und isChoiceReachable(..)) + // set non-reachable (modelState,memoryState)-Pairs (i.e. those that are not contained in _productChoices) to "unreachable", + // also: states that are never reached using the scheduler + // (extend Scheduler by something like std::vector<std::Bitvector>> + // + reachableSchedulerChoices; isChoiceReachable(..)) + // + change definition of partialScheduler/undefinedstates (true if there are undefined states (undefined states are always reachable)) + // + maybe states in trueUpsi are unreachable + // // Sanity check for created scheduler. STORM_LOG_ASSERT(scheduler.isDeterministicScheduler(), "Expected a deterministic scheduler"); @@ -471,13 +486,7 @@ namespace storm { if (_accInfSets.get()[product->getProductStateIndex(modelState, automatonTo)].get().count(infSet) == 0) { // the state is is in a different accepting MEC with a different accepting conjunction of InfSets. auto newInfSet = _accInfSets.get()[product->getProductStateIndex(modelState, automatonTo)].get().begin(); - - // todo Never switch from NoMc to Mec? - //if (*newInfSet != _infSets.get().size() ){ - // Add modelState to the transition from <automatonFrom, InfSet>> to <automatonTo, firstInfSet>. - _memoryTransitions.get()[(automatonFrom * (_infSets.get().size()+1)) + infSet][(automatonTo * (_infSets.get().size()+1)) + *newInfSet].set(modelState); - // } - + _memoryTransitions.get()[(automatonFrom * (_infSets.get().size()+1)) + infSet][(automatonTo * (_infSets.get().size()+1)) + *newInfSet].set(modelState); } else { // The state is either not in an accepting EC or in an accepting EC that needs to satisfy the infSet. diff --git a/src/storm/storage/memorystructure/MemoryStructure.cpp b/src/storm/storage/memorystructure/MemoryStructure.cpp index 83bc7ad81..6103c05dd 100644 --- a/src/storm/storage/memorystructure/MemoryStructure.cpp +++ b/src/storm/storage/memorystructure/MemoryStructure.cpp @@ -11,14 +11,26 @@ 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) : transitions(transitionMatrix), stateLabeling(memoryStateLabeling), initialMemoryStates(initialMemoryStates), onlyInitialStatesRelevant(true) { // 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) : transitions(std::move(transitionMatrix)), stateLabeling(std::move(memoryStateLabeling)), initialMemoryStates(std::move(initialMemoryStates)), onlyInitialStatesRelevant(true) { // intentionally left empty } - + + 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, 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..2476a4e63 100644 --- a/src/storm/storage/memorystructure/MemoryStructure.h +++ b/src/storm/storage/memorystructure/MemoryStructure.h @@ -37,7 +37,10 @@ namespace storm { */ 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); + MemoryStructure(TransitionMatrix&& transitionMatrix, storm::models::sparse::StateLabeling&& memoryStateLabeling, std::vector<uint_fast64_t>&& initialMemoryStates, bool onlyInitialStatesRelevant); + + bool IsOnlyInitialStatesRelevantSet () const; TransitionMatrix const& getTransitionMatrix() const; storm::models::sparse::StateLabeling const& getStateLabeling() const; std::vector<uint_fast64_t> const& getInitialMemoryStates() const; @@ -65,6 +68,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 f659e3381..859a92635 100644 --- a/src/storm/storage/memorystructure/MemoryStructureBuilder.cpp +++ b/src/storm/storage/memorystructure/MemoryStructureBuilder.cpp @@ -10,28 +10,47 @@ 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) : model(model), transitions(numberOfMemoryStates, std::vector<boost::optional<storm::storage::BitVector>>(numberOfMemoryStates)), stateLabeling(numberOfMemoryStates), initialMemoryStates(model.getInitialStates().getNumberOfSetBits(), 0), onlyInitialStatesRelevant(true) { + // Intentionally left empty + } + + template <typename ValueType, typename RewardModelType> + 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(true) { // 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(); // TODO allow all - for (auto initState : model.getInitialStates()) { - if (initState == initialModelState) { - *initMemStateIt = initialMemoryState; - break; + auto initMemStateIt = initialMemoryStates.begin(); + + 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 +104,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 0b3c6e9cf..1d067a4bc 100644 --- a/src/storm/storage/memorystructure/MemoryStructureBuilder.h +++ b/src/storm/storage/memorystructure/MemoryStructureBuilder.h @@ -19,7 +19,14 @@ namespace storm { * @param numberOfMemoryStates The number of states the resulting memory structure should have */ MemoryStructureBuilder(uint_fast64_t numberOfMemoryStates, storm::models::sparse::Model<ValueType, RewardModelType> const& model); - // TODO: Add variant with a flag: Consider non-initial model states + + /*! + * 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 allModelStatesRelevant Consider non-initial model states + */ + MemoryStructureBuilder(uint_fast64_t numberOfMemoryStates, storm::models::sparse::Model<ValueType, RewardModelType> const& model, bool onlyInitialStatesRelevant); + /*! * Initializes a new builder with the data from the provided memory structure */ @@ -73,6 +80,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..fd9163fa5 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."); diff --git a/src/test/storm/modelchecker/prctl/mdp/SchedulerGenerationMdpPrctlModelCheckerTest.cpp b/src/test/storm/modelchecker/prctl/mdp/SchedulerGenerationMdpPrctlModelCheckerTest.cpp index e7ee44930..cddf22db4 100755 --- a/src/test/storm/modelchecker/prctl/mdp/SchedulerGenerationMdpPrctlModelCheckerTest.cpp +++ b/src/test/storm/modelchecker/prctl/mdp/SchedulerGenerationMdpPrctlModelCheckerTest.cpp @@ -221,6 +221,7 @@ namespace { storm::modelchecker::SparseMdpPrctlModelChecker<storm::models::sparse::Mdp<ValueType>> checker(*mdp); { + tasks[0].setOnlyInitialStatesRelevant(true); // TODO for false, but need equivalent inducedModel state for model state 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::settings::getModule<storm::settings::modules::GeneralSettings>().getPrecision()); @@ -243,6 +244,7 @@ namespace { EXPECT_NEAR(this->parseNumber("81/100"), inducedResult->template asExplicitQuantitativeCheckResult<ValueType>()[*inducedMdp->getInitialStates().begin()],storm::settings::getModule<storm::settings::modules::GeneralSettings>().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::settings::getModule<storm::settings::modules::GeneralSettings>().getPrecision()); @@ -262,6 +264,7 @@ namespace { EXPECT_NEAR(this->parseNumber("1/2"),inducedResult->template asExplicitQuantitativeCheckResult<ValueType>()[*inducedMdp->getInitialStates().begin()],storm::settings::getModule<storm::settings::modules::GeneralSettings>().getPrecision()); } { + tasks[2].setOnlyInitialStatesRelevant(true); auto result = checker.check(this->env(), tasks[2]); ASSERT_TRUE(result->isExplicitQuantitativeCheckResult()); EXPECT_NEAR(this->parseNumber("1/2"), @@ -304,9 +307,10 @@ namespace { 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.5"),result->template asExplicitQuantitativeCheckResult<ValueType>()[*mdp->getInitialStates().begin()], + EXPECT_NEAR(this->parseNumber("1"),result->template asExplicitQuantitativeCheckResult<ValueType>()[*mdp->getInitialStates().begin()], storm::settings::getModule<storm::settings::modules::GeneralSettings>().getPrecision()); ASSERT_TRUE(result->template asExplicitQuantitativeCheckResult<ValueType>().hasScheduler()); storm::storage::Scheduler<ValueType> const &scheduler = result->template asExplicitQuantitativeCheckResult<ValueType>().getScheduler(); @@ -324,7 +328,7 @@ 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("0.5"), inducedResult->template asExplicitQuantitativeCheckResult<ValueType>()[*mdp->getInitialStates().begin()], storm::settings::getModule<storm::settings::modules::GeneralSettings>().getPrecision()); + EXPECT_NEAR(this->parseNumber("1"), inducedResult->template asExplicitQuantitativeCheckResult<ValueType>()[*inducedMdp->getInitialStates().begin()], storm::settings::getModule<storm::settings::modules::GeneralSettings>().getPrecision()); } } @@ -335,7 +339,7 @@ namespace { // TODO skip without LTL 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 modelFormulas = this->buildModelFormulas(STORM_TEST_RESOURCES_DIR "/mdp/scheduler_generation.nm", formulasString); auto mdp = std::move(modelFormulas.first); auto tasks = this->getTasks(modelFormulas.second); @@ -347,6 +351,7 @@ namespace { 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()], @@ -370,6 +375,7 @@ namespace { } { + tasks[1].setOnlyInitialStatesRelevant(true); auto result = checker.check(this->env(), tasks[1]); ASSERT_TRUE(result->isExplicitQuantitativeCheckResult()); ASSERT_TRUE(result->template asExplicitQuantitativeCheckResult<ValueType>().hasScheduler()); From 214d586d10f805800db28e3bf7be58dd55ecd1c5 Mon Sep 17 00:00:00 2001 From: hannah <hannah.mertens@rwth-aachen.de> Date: Tue, 20 Jul 2021 16:48:31 +0200 Subject: [PATCH 106/172] fixed scheduler choice in EC --- src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp index e097eaab5..d0f195604 100644 --- a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp +++ b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp @@ -302,11 +302,8 @@ namespace storm { // States that already reached the InfSet: Prob1E sets an arbitrary choice for the psi states, but we want to stay in this accepting mec. for (auto pState : (newMecStates & _infSets.get()[id])) { - // If we are in the InfSet, we stay in mec-states - // TODO these are global? - storm::storage::FlatSet<uint_fast64_t> test = mec.getChoicesForState(pState); - mecScheduler.setChoice(0, pState); //todo get first choice from mec.getChoicesForState(pState); but need local - + // If we are in the InfSet, we move to some state in this MEC. + mecScheduler.setChoice(*mec.getChoicesForState(pState).begin() - transitionMatrix.getRowGroupIndices()[pState], pState); } // Extract scheduler choices (only for states that are already assigned a scheduler, i.e are in another MEC) @@ -580,7 +577,7 @@ namespace storm { da = storm::automata::LTL2DeterministicAutomaton::ltl2daSpot(*ltlFormula, Nondeterministic); } - STORM_PRINT("Deterministic automaton for LTL formula has " + STORM_LOG_DEBUG("Deterministic automaton for LTL formula has " << da->getNumberOfStates() << " states, " << da->getAPSet().size() << " atomic propositions and " << *da->getAcceptance()->getAcceptanceExpression() << " as acceptance condition." << std::endl); From 412489a57fb0f60324f201ac632a15562e67d620 Mon Sep 17 00:00:00 2001 From: hannah <hannah.mertens@rwth-aachen.de> Date: Wed, 21 Jul 2021 10:19:21 +0200 Subject: [PATCH 107/172] Added possibility to set (un)reachable states for scheduler Conflicts: src/storm/modelchecker/prctl/helper/SparseMdpPrctlHelper.cpp It looks like you may be committing a cherry-pick. --- .../helper/ltl/SparseLTLHelper.cpp | 82 +++++++++++------ .../modelchecker/helper/ltl/SparseLTLHelper.h | 2 +- .../prctl/helper/SparseMdpPrctlHelper.cpp | 15 ++-- src/storm/storage/Scheduler.cpp | 88 +++++++++++++++---- src/storm/storage/Scheduler.h | 21 +++++ src/storm/transformer/DAProductBuilder.h | 2 +- ...ulerGenerationMdpPrctlModelCheckerTest.cpp | 6 +- 7 files changed, 159 insertions(+), 57 deletions(-) diff --git a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp index d0f195604..a1bb1f016 100644 --- a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp +++ b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp @@ -86,18 +86,25 @@ namespace storm { uint_fast64_t infSet = std::get<2>(choice.first); scheduler.setChoice(choice.second, modelState, (automatonState*(_infSets.get().size()+1))+ infSet); + + // TODO: shouldn't happen? + //STORM_LOG_ASSERT(!this->_unreachableStates.get()[(automatonState*(_infSets.get().size()+1))+ infSet].get(modelState), "Tried to set choice for unreachable state."); + } + + /* + for (uint_fast64_t memoryState = 0; this->_unreachableStates.get().size(); ++memoryState) { + for (auto state : this->_unreachableStates.get()[memoryState]) { + // todo fails, memory state = 9 + scheduler.setStateUnreachable(state, memoryState); + } } - // TODO - // set non-reachable (modelState,memoryState)-Pairs (i.e. those that are not contained in _productChoices) to "unreachable", - // also: states that are never reached using the scheduler - // (extend Scheduler by something like std::vector<std::Bitvector>> - // + reachableSchedulerChoices; isChoiceReachable(..)) - // + change definition of partialScheduler/undefinedstates (true if there are undefined states (undefined states are always reachable)) - // + maybe states in trueUpsi are unreachable - // + */ + + // 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; } @@ -290,7 +297,6 @@ namespace storm { } - // Define scheduler choices for the states in this MEC (that are not in any other MEC) for (uint_fast64_t id : infSetIds) { // Scheduler that satisfies the MEC acceptance condition (visit each InfSet inf often, or switch to scheduler of another MEC) @@ -311,7 +317,6 @@ namespace storm { // We want to reach the InfSet, save choice: <s, q, InfSetID> ---> choice this->_productChoices.get().insert({std::make_tuple(product->getModelState(pState), product->getAutomatonState(pState), id), mecScheduler.getChoice(pState)}); } - } } } @@ -441,68 +446,87 @@ namespace storm { // TODO asserts _mecStatesInfSets initialized etc. + // Compute size of the resulting memory structure: a state corresponds to <q, infSet>> encoded as (q* (|infSets|+1))+infSet + uint64 numMemoryStates = (da.getNumberOfStates() * (_infSets.get().size()+1)) + _infSets.get().size()+1; //+1 for states outside accECs + + _unreachableStates.emplace(numMemoryStates, storm::storage::BitVector(this->_transitionMatrix.getRowGroupCount(), false)); + + // Extract the choices of the REACH-scheduler (choices to reach an acc. MEC) for the MDP-DA product: <s,q> -> choice for (storm::storage::sparse::state_type pState : ~acceptingStates) { - // for state <s,q> not in any accEC <s,q, REACH> ---> choice - // Do not overwrite choices of states in an accepting MEC - this->_productChoices.get().insert({std::make_tuple(product->getModelState(pState), product->getAutomatonState(pState), _infSets.get().size()), prodCheckResult.scheduler->getChoice(pState)}); // For non-accepting states that are not in any accepting EC we use the 'last' copy of the DA - this->_accInfSets.get()[pState] = {this->_infSets.get().size()}; + this->_accInfSets.get()[pState] = {_infSets.get().size()}; + // For state <s,q> not in any accEC <s,q, REACH> ---> choice. Do not overwrite choices of states in an accepting MEC. + this->_productChoices.get().insert({std::make_tuple(product->getModelState(pState), product->getAutomatonState(pState), _infSets.get().size()), prodCheckResult.scheduler->getChoice(pState)}); + if (!prodCheckResult.scheduler->isStateReachable(pState)) { + //TODO + this->_unreachableStates.get()[(product->getAutomatonState(pState)) * (_infSets.get().size()+1) + _infSets.get().size()].set(product->getModelState(pState)); + } } // Prepare the memory structure. For that, we need: transitions, initialMemoryStates (and memoryStateLabeling) - // Compute size of the resulting memory structure: a state corresponds to <q, infSet>> encoded as (q* (|infSets|+1))+infSet - uint64 numMemoryStates = (da.getNumberOfStates() * (_infSets.get().size()+1)) + _infSets.get().size()+1; //+1 for states outside accECs + // The next move function of the memory, will be build based on the transitions of the DA and jumps between InfSets. this->_memoryTransitions.emplace(numMemoryStates, std::vector<storm::storage::BitVector>(numMemoryStates, storm::storage::BitVector(this->_transitionMatrix.getRowGroupCount(), false))); + + for (storm::storage::sparse::state_type automatonFrom = 0; automatonFrom < da.getNumberOfStates(); ++automatonFrom) { for (storm::storage::sparse::state_type automatonTo = 0; automatonTo < da.getNumberOfStates(); ++automatonTo) { // Find the modelStates that trigger this transition. for (storm::storage::sparse::state_type modelState = 0; modelState < this->_transitionMatrix.getRowGroupCount(); ++modelState) { if(!product->isValidProductState(modelState, automatonTo)) { - // Memory state successor of the modelState-transition emanating <automatonFrom, * > not defined/reachable. - // TODO save as unreachable in scheduler - //STORM_PRINT("set to unreachable : <" << modelState <<" , " << automatonTo <<">"); + // <modelState, automatonTo> is not defined in the Product. Thus, considered not reachable for the scheduler. + for (uint_fast64_t infSet = 0; infSet < _infSets.get().size(); ++infSet) { + this->_unreachableStates.get()[ (automatonTo* (_infSets.get().size()+1)) + infSet].set(modelState); + } } else if (automatonTo == productBuilder.getSuccessor(modelState, automatonFrom, modelState)) { //TODO remove first parameter of getSuccessor - // Add the modelState to one outgoing transition of all states of the form <automatonFrom, InfSet> (Inf=lenInfSet equals not in MEC) + // Add the modelState to one outgoing transition of all states of the form <automatonFrom, InfSet> (Inf=lenInfSet equals not in MEC) // For non-accepting states that are not in any accepting EC we use the 'last' copy of the DA - - // For the accepting states we jump through copies of the DA wrt. the infinity sets. + // and for the accepting states we jump through copies of the DA wrt. the infinity sets. for (uint_fast64_t infSet = 0; infSet < _infSets.get().size()+1; ++infSet) { - // Check if we need to switch the acceptance condition if (_accInfSets.get()[product->getProductStateIndex(modelState, automatonTo)].get().count(infSet) == 0) { // the state is is in a different accepting MEC with a different accepting conjunction of InfSets. auto newInfSet = _accInfSets.get()[product->getProductStateIndex(modelState, automatonTo)].get().begin(); _memoryTransitions.get()[(automatonFrom * (_infSets.get().size()+1)) + infSet][(automatonTo * (_infSets.get().size()+1)) + *newInfSet].set(modelState); + // TODO problem other inf set combis may not be reachable? + // this->_reachableStates.get()[(automatonTo * (_infSets.get().size()+1)) + *newInfSet].set(modelState, true); + } else { // The state is either not in an accepting EC or in an accepting EC that needs to satisfy the infSet. if (infSet == _infSets.get().size() || !(_infSets.get()[infSet].get(product->getProductStateIndex(modelState, automatonTo)))) { // <modelState, automatonTo> is not in any accepting EC or does not satisfy the InfSet, we stay there. // Add modelState to the transition from <automatonFrom, InfSet> to <automatonTo, InfSet> _memoryTransitions.get()[(automatonFrom * (_infSets.get().size()+1)) + infSet][(automatonTo * (_infSets.get().size()+1)) + infSet].set(modelState); + + // TODO problem other inf set combis may not be reachable? + //this->_reachableStates.get()[(automatonTo * (_infSets.get().size()+1)) + infSet].set(modelState, true); + } else { STORM_LOG_ASSERT(_accInfSets.get()[product->getProductStateIndex(modelState, automatonTo)] != boost::none, "The list of InfSets for the product state <" <<modelState<< ", " << automatonTo<<"> is undefined."); // <modelState, automatonTo> satisfies the InfSet, find the next one - auto it = std::find(_accInfSets.get()[product->getProductStateIndex(modelState, automatonTo)].get().begin(), _accInfSets.get()[product->getProductStateIndex(modelState, automatonTo)].get().end(), infSet); - STORM_LOG_ASSERT(it != _accInfSets.get()[product->getProductStateIndex(modelState, automatonTo)].get().end(), "The list of InfSets for the product state <" <<modelState<< ", " << automatonTo<<"> does not contain the infSet " << infSet); - it++; - if (it == _accInfSets.get()[product->getProductStateIndex(modelState, automatonTo)].get().end()) { + auto nextInfSet = std::find(_accInfSets.get()[product->getProductStateIndex(modelState, automatonTo)].get().begin(), _accInfSets.get()[product->getProductStateIndex(modelState, automatonTo)].get().end(), infSet); + STORM_LOG_ASSERT(nextInfSet != _accInfSets.get()[product->getProductStateIndex(modelState, automatonTo)].get().end(), "The list of InfSets for the product state <" <<modelState<< ", " << automatonTo<<"> does not contain the infSet " << infSet); + nextInfSet++; + if (nextInfSet == _accInfSets.get()[product->getProductStateIndex(modelState, automatonTo)].get().end()) { // Start again. - it = _accInfSets.get()[product->getProductStateIndex(modelState, automatonTo)].get().begin(); + nextInfSet = _accInfSets.get()[product->getProductStateIndex(modelState, automatonTo)].get().begin(); } // Add modelState to the transition from <automatonFrom <mec, InfSet>> to <automatonTo, <mec, NextInfSet>>. - _memoryTransitions.get()[(automatonFrom * (_infSets.get().size()+1)) + infSet][(automatonTo * (_infSets.get().size()+1)) + *it].set(modelState); + _memoryTransitions.get()[(automatonFrom * (_infSets.get().size()+1)) + infSet][(automatonTo * (_infSets.get().size()+1)) + *nextInfSet].set(modelState); + + // TODO problem other inf set combis may not be reachable? + // this->_reachableStates.get()[(automatonTo * (_infSets.get().size()+1)) + *nextInfSet].set(modelState, true); } } } diff --git a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h index d60027ade..919efc898 100644 --- a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h +++ b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h @@ -70,7 +70,6 @@ namespace storm { std::vector<ValueType> computeLTLProbabilities(Environment const &env, storm::logic::Formula const& formula, std::map<std::string, storm::storage::BitVector>& apSatSets); private: - /*! * Compute a set S of states that admit a probability 1 strategy of satisfying the given acceptance condition (in DNF). * More precisely, let @@ -99,6 +98,7 @@ namespace storm { // scheduler bool _randomScheduler = false; boost::optional<std::map <std::tuple<uint_fast64_t, uint_fast64_t, uint_fast64_t>, storm::storage::SchedulerChoice<ValueType>>> _productChoices; // <s, q, len(_infSets)> ---> ReachChoice and <s, q, InfSet> ---> MecChoice + boost::optional<std::vector<storm::storage::BitVector>> _unreachableStates; // unreachable memory state and model state combinations boost::optional<std::vector<storm::storage::BitVector>> _infSets; // Save the InfSets of the Acceptance condition. boost::optional<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) diff --git a/src/storm/modelchecker/prctl/helper/SparseMdpPrctlHelper.cpp b/src/storm/modelchecker/prctl/helper/SparseMdpPrctlHelper.cpp index 9193c8f26..5321960a9 100644 --- a/src/storm/modelchecker/prctl/helper/SparseMdpPrctlHelper.cpp +++ b/src/storm/modelchecker/prctl/helper/SparseMdpPrctlHelper.cpp @@ -609,14 +609,21 @@ namespace storm { // 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 "unreachable" + if (maybeStatesNotRelevant) { + for (auto state : qualitativeStateSets.maybeStates) { + scheduler->setStateUnreachable(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); @@ -628,8 +635,6 @@ namespace storm { } } - std::vector<ValueType> maybeStateChoiceValues = std::vector<ValueType>(sizeMaybeStateChoiceValues, storm::utility::zero<ValueType>()); - // TODO: if a scheduler is to be produced and maybestatesNotRelevant is true, we have to set the scheduler for maybsetsates as "unreachable" TODO // 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. diff --git a/src/storm/storage/Scheduler.cpp b/src/storm/storage/Scheduler.cpp index 4dbc1df8f..ab9fc40e3 100644 --- a/src/storm/storage/Scheduler.cpp +++ b/src/storm/storage/Scheduler.cpp @@ -13,41 +13,48 @@ 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)); + reachableStates = std::vector<storm::storage::BitVector>(numOfMemoryStates, storm::storage::BitVector(numberOfModelStates, true)); numOfUndefinedChoices = numOfMemoryStates * numberOfModelStates; numOfDeterministicChoices = 0; + numOfUnreachableStates = 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)); + reachableStates = std::vector<storm::storage::BitVector>(numOfMemoryStates, storm::storage::BitVector(numberOfModelStates, true)); numOfUndefinedChoices = numOfMemoryStates * numberOfModelStates; numOfDeterministicChoices = 0; + numOfUnreachableStates = 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); - --numOfUndefinedChoices; - } - } - if (schedulerChoice.isDeterministic()) { - if (!choice.isDeterministic()) { - assert(numOfDeterministicChoices > 0); - --numOfDeterministicChoices; + if (reachableStates[memoryState].get(modelState)) { + if (schedulerChoice.isDefined()) { + if (!choice.isDefined()) { + ++numOfUndefinedChoices; + } + } else { + if (choice.isDefined()) { + assert(numOfUndefinedChoices > 0); + --numOfUndefinedChoices; + } } - } else { - if (choice.isDeterministic()) { - ++numOfDeterministicChoices; + if (schedulerChoice.isDeterministic()) { + if (!choice.isDeterministic()) { + assert(numOfDeterministicChoices > 0); + --numOfDeterministicChoices; + } + } else { + if (choice.isDeterministic()) { + ++numOfDeterministicChoices; + } } } @@ -79,6 +86,49 @@ namespace storm { return schedulerChoices[memoryState][modelState]; } + template <typename ValueType> + void Scheduler<ValueType>::setStateUnreachable(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 (reachableStates[memoryState].get(modelState)) { + reachableStates[memoryState].set(modelState, false); + ++numOfUnreachableStates; + + // Choices for unreachable states are not considered undefined or deterministic + if (!schedulerChoice.isDefined()) { + --numOfUndefinedChoices; + } else if (schedulerChoice.isDeterministic()) { + --numOfDeterministicChoices; + } + + } + } + + template <typename ValueType> + void Scheduler<ValueType>::setStateReachable(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 (!reachableStates[memoryState].get(modelState)) { + reachableStates[memoryState].set(modelState, true); + --numOfUnreachableStates; + + // Choices for unreachable states are not considered undefined or deterministic + if (!schedulerChoice.isDefined()) { + ++numOfUndefinedChoices; + } else if (schedulerChoice.isDeterministic()) { + ++numOfDeterministicChoices; + } + + } + } + + template <typename ValueType> + bool Scheduler<ValueType>::isStateReachable(uint_fast64_t modelState, uint64_t memoryState) const { + return reachableStates[memoryState].get(modelState); + } + template<typename ValueType> storm::storage::BitVector Scheduler<ValueType>::computeActionSupport(std::vector<uint_fast64_t> const& nondeterministicChoiceIndices) const { auto nrActions = nondeterministicChoiceIndices.back(); @@ -104,7 +154,7 @@ namespace storm { template <typename ValueType> bool Scheduler<ValueType>::isDeterministicScheduler() const { - return numOfDeterministicChoices == (schedulerChoices.size() * schedulerChoices.begin()->size()) - numOfUndefinedChoices; + return numOfDeterministicChoices == (schedulerChoices.size() * schedulerChoices.begin()->size()) - numOfUndefinedChoices - numOfUnreachableStates; } template <typename ValueType> @@ -124,6 +174,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 { + // TODO ignore unreachable states 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(); @@ -260,6 +311,7 @@ namespace storm { template <typename ValueType> void Scheduler<ValueType>::printJsonToStream(std::ostream& out, std::shared_ptr<storm::models::sparse::Model<ValueType>> model, bool skipUniqueChoices) const { + //TODO not defined for memory and unreachable states are not considered 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."); diff --git a/src/storm/storage/Scheduler.h b/src/storm/storage/Scheduler.h index 5107bb1cf..18e3a8fb7 100644 --- a/src/storm/storage/Scheduler.h +++ b/src/storm/storage/Scheduler.h @@ -60,6 +60,27 @@ 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 unreachable. + * + * @param modelState The state of the model. + * @param memoryState The state of the memoryStructure. + */ + void setStateUnreachable(uint_fast64_t modelState, uint_fast64_t memoryState = 0); + + /*! + * Set the combination of model state and memoryStructure state to reachable. + * + * @param modelState The state of the model. + * @param memoryState The state of the memoryStructure. + */ + void setStateReachable(uint_fast64_t modelState, uint_fast64_t memoryState = 0); + + /*! + * Is the combination of model state and memoryStructure state to reachable? + */ + bool isStateReachable(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 */ diff --git a/src/storm/transformer/DAProductBuilder.h b/src/storm/transformer/DAProductBuilder.h index 7c882b3e8..a6a53f9bd 100644 --- a/src/storm/transformer/DAProductBuilder.h +++ b/src/storm/transformer/DAProductBuilder.h @@ -35,7 +35,7 @@ namespace storm { return da.getSuccessor(da.getInitialState(), getLabelForState(modelState)); } - storm::storage::sparse::state_type getSuccessor(storm::storage::sparse::state_type modelFrom, //TODO delete modelFrom? + storm::storage::sparse::state_type getSuccessor(storm::storage::sparse::state_type modelFrom, storm::storage::sparse::state_type automatonFrom, storm::storage::sparse::state_type modelTo) const { return da.getSuccessor(automatonFrom, getLabelForState(modelTo)); diff --git a/src/test/storm/modelchecker/prctl/mdp/SchedulerGenerationMdpPrctlModelCheckerTest.cpp b/src/test/storm/modelchecker/prctl/mdp/SchedulerGenerationMdpPrctlModelCheckerTest.cpp index cddf22db4..0ad528920 100755 --- a/src/test/storm/modelchecker/prctl/mdp/SchedulerGenerationMdpPrctlModelCheckerTest.cpp +++ b/src/test/storm/modelchecker/prctl/mdp/SchedulerGenerationMdpPrctlModelCheckerTest.cpp @@ -221,7 +221,7 @@ namespace { storm::modelchecker::SparseMdpPrctlModelChecker<storm::models::sparse::Mdp<ValueType>> checker(*mdp); { - tasks[0].setOnlyInitialStatesRelevant(true); // TODO for false, but need equivalent inducedModel state for model state + 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::settings::getModule<storm::settings::modules::GeneralSettings>().getPrecision()); @@ -244,7 +244,7 @@ namespace { EXPECT_NEAR(this->parseNumber("81/100"), inducedResult->template asExplicitQuantitativeCheckResult<ValueType>()[*inducedMdp->getInitialStates().begin()],storm::settings::getModule<storm::settings::modules::GeneralSettings>().getPrecision()); } { - tasks[1].setOnlyInitialStatesRelevant(true); + tasks[1].setOnlyInitialStatesRelevant(false); 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::settings::getModule<storm::settings::modules::GeneralSettings>().getPrecision()); @@ -258,7 +258,7 @@ namespace { 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); + 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::settings::getModule<storm::settings::modules::GeneralSettings>().getPrecision()); From c1b06f40b7889090b705c74f9002311b97a1c4ce Mon Sep 17 00:00:00 2001 From: Tim Quatmann <tim.quatmann@cs.rwth-aachen.de> Date: Wed, 21 Jul 2021 12:02:42 +0200 Subject: [PATCH 108/172] CMAKE: Added option to include and link against Spot Conflicts: CMakeLists.txt --- CMakeLists.txt | 1 + resources/cmake/find_modules/FindSPOT.cmake | 1 + 2 files changed, 2 insertions(+) diff --git a/CMakeLists.txt b/CMakeLists.txt index fd37f01f5..b7fc55f9d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -49,6 +49,7 @@ MARK_AS_ADVANCED(STORM_FORCE_SHIPPED_CARL) 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_FORCE_LTL_SUPPORT "Sets whether support for LTL model checking needs to be included." OFF) option(STORM_USE_SPOT "Sets whether Spot should be included." ON) MARK_AS_ADVANCED(STORM_USE_SPOT) diff --git a/resources/cmake/find_modules/FindSPOT.cmake b/resources/cmake/find_modules/FindSPOT.cmake index f4a0be599..f0ba32917 100644 --- a/resources/cmake/find_modules/FindSPOT.cmake +++ b/resources/cmake/find_modules/FindSPOT.cmake @@ -6,6 +6,7 @@ # 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) From 9626c3c5f153f2fd0c20847322273d53ae2e3d9d Mon Sep 17 00:00:00 2001 From: Tim Quatmann <tim.quatmann@cs.rwth-aachen.de> Date: Wed, 21 Jul 2021 12:06:26 +0200 Subject: [PATCH 109/172] Cmake: Fixed output when including spot. --- resources/3rdparty/include_spot.cmake | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/resources/3rdparty/include_spot.cmake b/resources/3rdparty/include_spot.cmake index 0332bdd4e..e64bad090 100644 --- a/resources/3rdparty/include_spot.cmake +++ b/resources/3rdparty/include_spot.cmake @@ -21,7 +21,7 @@ if(STORM_USE_SPOT AND NOT STORM_SHIPPED_SPOT AND NOT STORM_FORCE_SHIPPED_SPOT) endif() if (SPOT_FOUND) - message(STATUS "Storm - Linking with shipped Spot ${SPOT_VERSION} (include: ${SPOT_INCLUDE_DIR}, library: ${SPOT_LIBRARIES}).") + 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_FORCE_LTL_SUPPORT) 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_FORCE_LTL_SUPPORT to install Spot automatically. If you already installed Spot, consider setting cmake option SPOT_ROOT") @@ -54,7 +54,7 @@ if(STORM_FORCE_SHIPPED_SPOT OR (STORM_FORCE_LTL_SUPPORT AND NOT STORM_HAVE_SPOT) set(STORM_HAVE_SPOT ON) set(STORM_SHIPPED_SPOT ON) - message(STATUS "Storm - Linking with shipped Spot 2.9.6 (include: ${SPOT_INCLUDE_DIR}, library ${SPOT_LIBRARIES}).") + message(STATUS "Storm - Using shipped version of Spot 2.9.6 (include: ${SPOT_INCLUDE_DIR}, library ${SPOT_LIBRARIES}).") endif() From c057e437e4a6877f1cfa19f8a37fd95df7be3100 Mon Sep 17 00:00:00 2001 From: Tim Quatmann <tim.quatmann@cs.rwth-aachen.de> Date: Wed, 21 Jul 2021 12:36:51 +0200 Subject: [PATCH 110/172] CMAKE: Do not mark STORM_USE_SPOT as advanced. --- CMakeLists.txt | 1 - 1 file changed, 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index b7fc55f9d..5442379a6 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -52,7 +52,6 @@ option(USE_HYPRO "Sets whether HyPro should be included." OFF) mark_as_advanced(USE_HYPRO) option(STORM_FORCE_LTL_SUPPORT "Sets whether support for LTL model checking needs to be included." OFF) option(STORM_USE_SPOT "Sets whether Spot should be included." ON) -MARK_AS_ADVANCED(STORM_USE_SPOT) option(STORM_FORCE_SHIPPED_SPOT "Sets whether the Spot sources should be downloaded and installed." OFF) MARK_AS_ADVANCED(STORM_FORCE_SHIPPED_SPOT) option(XML_SUPPORT "Sets whether xml based format parsing should be included." ON) From 77ced0aefe6dec9208d3622f41fa67bed7847a1f Mon Sep 17 00:00:00 2001 From: hannah <hannah.mertens@rwth-aachen.de> Date: Wed, 21 Jul 2021 23:59:55 +0200 Subject: [PATCH 111/172] fixed warning --- .../helper/ltl/SparseLTLHelper.cpp | 49 ++++++++++++------- .../modelchecker/helper/ltl/SparseLTLHelper.h | 5 +- src/storm/transformer/Product.h | 4 +- 3 files changed, 36 insertions(+), 22 deletions(-) diff --git a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp index a1bb1f016..0235fa073 100644 --- a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp +++ b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp @@ -42,13 +42,13 @@ namespace storm { } // Otherwise, we compute a scheduler with memory. - STORM_LOG_ASSERT(this->_productChoices.is_initialized(), "Trying to extract the produced scheduler but none is available. Was there a computation call before?"); + STORM_LOG_ASSERT(this->_producedChoices.is_initialized(), "Trying to extract the produced scheduler but none is available. Was there a computation call before?"); STORM_LOG_ASSERT(this->_memoryTransitions.is_initialized(), "Trying to extract the DA transition structure but none is available. Was there a computation call before?"); STORM_LOG_ASSERT(this->_memoryInitialStates.is_initialized(), "Trying to extract the initial states of the DA but there are none available. Was there a computation call before?"); // Create a memory structure for the MDP scheduler with memory. If hasRelevantStates is set, we only consider initial model states relevant. - typename storm::storage::MemoryStructureBuilder<ValueType>::MemoryStructureBuilder memoryBuilder(this->_memoryTransitions.get().size(), model, this->hasRelevantStates()); + auto memoryBuilder = storm::storage::MemoryStructureBuilder<ValueType>(this->_memoryTransitions.get().size(), model, this->hasRelevantStates()); // Build the transitions between the memory states: startState--- modelStates (transitionVector) --->goalState for (storm::storage::sparse::state_type startState = 0; startState < this->_memoryTransitions.get().size(); ++startState) { @@ -79,7 +79,7 @@ namespace storm { storm::storage::Scheduler<ValueType> scheduler(this->_transitionMatrix.getRowGroupCount(), memoryStructure); // Use choices in the product model to create a choice based on model state and memory state - for (const auto &choice : this->_productChoices.get()) { + for (const auto &choice : this->_producedChoices.get()) { // <s, q, InfSet> -> choice storm::storage::sparse::state_type modelState = std::get<0>(choice.first); storm::storage::sparse::state_type automatonState = std::get<1>(choice.first); @@ -104,7 +104,7 @@ namespace storm { // Sanity check for created scheduler. STORM_LOG_ASSERT(scheduler.isDeterministicScheduler(), "Expected a deterministic scheduler"); - STORM_LOG_ASSERT(!scheduler.isPartialScheduler(), "Expected a fully defined scheduler"); + // TODO STORM_LOG_ASSERT(!scheduler.isPartialScheduler(), "Expected a fully defined scheduler"); return scheduler; } @@ -149,7 +149,7 @@ namespace storm { if (this->isProduceSchedulerSet()) { _infSets.emplace(); _accInfSets.emplace(product->getProductModel().getNumberOfStates(), boost::none); - _productChoices.emplace(); + _producedChoices.emplace(); } for (auto const& conjunction : dnf) { @@ -243,7 +243,7 @@ namespace storm { if (this->isProduceSchedulerSet()) { // Save all states contained in this MEC - storm::storage::BitVector mecStates(product->getProductModel().getNumberOfStates(), false); + storm::storage::BitVector mecStates(transitionMatrix.getRowGroupCount(), false); for (auto const &stateChoicePair : mec) { mecStates.set(stateChoicePair.first); } @@ -254,7 +254,7 @@ namespace storm { storm::storage::BitVector infSet; if (literal->isTRUE()) { // All states - infSet = storm::storage::BitVector(product->getProductModel().getNumberOfStates(), true); + infSet = storm::storage::BitVector(transitionMatrix.getRowGroupCount(), true); } else if (literal->isAtom()) { const cpphoafparser::AtomAcceptance &atom = literal->getAtom(); @@ -286,7 +286,7 @@ namespace storm { } // Save the InfSets into the _accInfSets for states in this MEC, but only if there weren't assigned to any other MEC yet. - storm::storage::BitVector newMecStates(product->getProductModel().getNumberOfStates(), false); + storm::storage::BitVector newMecStates(transitionMatrix.getRowGroupCount(), false); for (auto const &stateChoicePair : mec) { if (_accInfSets.get()[stateChoicePair.first] == boost::none) { // state wasn't assigned to any other MEC yet. @@ -315,7 +315,8 @@ namespace storm { // Extract scheduler choices (only for states that are already assigned a scheduler, i.e are in another MEC) for (auto pState : newMecStates) { // We want to reach the InfSet, save choice: <s, q, InfSetID> ---> choice - this->_productChoices.get().insert({std::make_tuple(product->getModelState(pState), product->getAutomatonState(pState), id), mecScheduler.getChoice(pState)}); + // TODO _mecChoices <pState, InfSetID> ---> choice (remove product arg, transform directly to memoryState) + this->_producedChoices.get().insert({std::make_tuple(product->getModelState(pState), product->getAutomatonState(pState), id), mecScheduler.getChoice(pState)}); } } } @@ -398,7 +399,7 @@ namespace storm { 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); //TODO product is only needed for ->getModelState(pState) and DAStates for scheduler creation (maybe lambda instead) + acceptingStates = computeAcceptingECs(*product->getAcceptance(), product->getProductModel().getTransitionMatrix(), product->getProductModel().getBackwardTransitions(), product); //TODO product is only needed for ->getModelState(pState) (remove arg) } else { STORM_LOG_INFO("Computing BSCCs and checking for acceptance..."); @@ -448,21 +449,31 @@ namespace storm { // Compute size of the resulting memory structure: a state corresponds to <q, infSet>> encoded as (q* (|infSets|+1))+infSet uint64 numMemoryStates = (da.getNumberOfStates() * (_infSets.get().size()+1)) + _infSets.get().size()+1; //+1 for states outside accECs - _unreachableStates.emplace(numMemoryStates, storm::storage::BitVector(this->_transitionMatrix.getRowGroupCount(), false)); + // Extract the choices of the REACH-scheduler (choices to reach an acc. MEC) for the MDP-DA product: <s,q> -> choice - for (storm::storage::sparse::state_type pState : ~acceptingStates) { + for (storm::storage::sparse::state_type pState = 0; pState < this->_transitionMatrix.getRowGroupCount(); ++pState) { - // For non-accepting states that are not in any accepting EC we use the 'last' copy of the DA - this->_accInfSets.get()[pState] = {_infSets.get().size()}; - // For state <s,q> not in any accEC <s,q, REACH> ---> choice. Do not overwrite choices of states in an accepting MEC. - this->_productChoices.get().insert({std::make_tuple(product->getModelState(pState), product->getAutomatonState(pState), _infSets.get().size()), prodCheckResult.scheduler->getChoice(pState)}); - if (!prodCheckResult.scheduler->isStateReachable(pState)) { - //TODO - this->_unreachableStates.get()[(product->getAutomatonState(pState)) * (_infSets.get().size()+1) + _infSets.get().size()].set(product->getModelState(pState)); + // set _producedChoices <s, <memory state>> ---> choice. + if (acceptingStates.get(pState)) { + // TODO extract _mecProductChoices // TODO directly translate into memstate , modelstate + } else { + // For non-accepting states that are not in any accepting EC we use the 'last' copy of the DA + this->_accInfSets.get()[pState] = {_infSets.get().size()}; + + // For state <s,q> not in any accEC: <s,q, REACH> ---> choice. + // TODO directly translate into memstate , modelstate + this->_producedChoices.get().insert({std::make_tuple(product->getModelState(pState), + product->getAutomatonState(pState), + _infSets.get().size()), + prodCheckResult.scheduler->getChoice(pState)}); + if (!prodCheckResult.scheduler->isStateReachable(pState)) { + //TODO + // this->_unreachableStates.get()[(product->getAutomatonState(pState)) * (_infSets.get().size()+1) + _infSets.get().size()].set(product->getModelState(pState)); + } } } diff --git a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h index 919efc898..e710676c9 100644 --- a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h +++ b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h @@ -97,9 +97,12 @@ namespace storm { // scheduler bool _randomScheduler = false; - boost::optional<std::map <std::tuple<uint_fast64_t, uint_fast64_t, uint_fast64_t>, storm::storage::SchedulerChoice<ValueType>>> _productChoices; // <s, q, len(_infSets)> ---> ReachChoice and <s, q, InfSet> ---> MecChoice + // todo directly memstate, state -> choice + boost::optional<std::map <std::tuple<uint_fast64_t, uint_fast64_t, uint_fast64_t>, storm::storage::SchedulerChoice<ValueType>>> _producedChoices; // <s, q, len(_infSets)> ---> ReachChoice and <s, q, InfSet> ---> MecChoice boost::optional<std::vector<storm::storage::BitVector>> _unreachableStates; // unreachable memory state and model state combinations + // Mec Scheduler + // _mecProductChoices <pstate> -> choice boost::optional<std::vector<storm::storage::BitVector>> _infSets; // Save the InfSets of the Acceptance condition. boost::optional<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 diff --git a/src/storm/transformer/Product.h b/src/storm/transformer/Product.h index b30362466..7d69bce57 100644 --- a/src/storm/transformer/Product.h +++ b/src/storm/transformer/Product.h @@ -37,11 +37,11 @@ namespace storm { } state_type getProductStateIndex(state_type modelState, state_type automatonState) const { - return productStateToProductIndex.at(product_state_type(modelState, automatonState)); //TODO does this work? + 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); //TODO does this work? + return (productStateToProductIndex.count(product_state_type(modelState, automatonState)) >0); } storm::storage::BitVector liftFromAutomaton(const storm::storage::BitVector& vector) const { From 6b0aaeadb46721007c3be3b7fb80e3c57683fb9b Mon Sep 17 00:00:00 2001 From: hannah <hannah.mertens@rwth-aachen.de> Date: Tue, 27 Jul 2021 11:05:41 +0200 Subject: [PATCH 112/172] ignore dontCare States while printing TODO Scheduler printing will need refactoring Conflicts: src/storm/storage/Scheduler.cpp src/storm/storage/Scheduler.h --- src/storm/storage/Scheduler.cpp | 48 +++++++++------------------------ src/storm/storage/Scheduler.h | 19 +++++-------- 2 files changed, 20 insertions(+), 47 deletions(-) diff --git a/src/storm/storage/Scheduler.cpp b/src/storm/storage/Scheduler.cpp index ab9fc40e3..51a3f40e8 100644 --- a/src/storm/storage/Scheduler.cpp +++ b/src/storm/storage/Scheduler.cpp @@ -13,20 +13,20 @@ 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)); - reachableStates = std::vector<storm::storage::BitVector>(numOfMemoryStates, storm::storage::BitVector(numberOfModelStates, true)); + dontCareStates = std::vector<storm::storage::BitVector>(numOfMemoryStates, storm::storage::BitVector(numberOfModelStates, false)); numOfUndefinedChoices = numOfMemoryStates * numberOfModelStates; numOfDeterministicChoices = 0; - numOfUnreachableStates = 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)); - reachableStates = std::vector<storm::storage::BitVector>(numOfMemoryStates, storm::storage::BitVector(numberOfModelStates, true)); + dontCareStates = std::vector<storm::storage::BitVector>(numOfMemoryStates, storm::storage::BitVector(numberOfModelStates, false)); numOfUndefinedChoices = numOfMemoryStates * numberOfModelStates; numOfDeterministicChoices = 0; - numOfUnreachableStates = 0; + numOfDontCareStates = 0; } template <typename ValueType> @@ -35,7 +35,7 @@ namespace storm { STORM_LOG_ASSERT(modelState < schedulerChoices[memoryState].size(), "Illegal model state index"); auto& schedulerChoice = schedulerChoices[memoryState][modelState]; - if (reachableStates[memoryState].get(modelState)) { + if (!dontCareStates[memoryState].get(modelState)) { if (schedulerChoice.isDefined()) { if (!choice.isDefined()) { ++numOfUndefinedChoices; @@ -87,13 +87,13 @@ namespace storm { } template <typename ValueType> - void Scheduler<ValueType>::setStateUnreachable(uint_fast64_t modelState, uint_fast64_t memoryState) { + void Scheduler<ValueType>::setDontCare(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 (reachableStates[memoryState].get(modelState)) { - reachableStates[memoryState].set(modelState, false); - ++numOfUnreachableStates; + if (!dontCareStates[memoryState].get(modelState)) { + dontCareStates[memoryState].set(modelState, true); + ++numOfDontCareStates; // Choices for unreachable states are not considered undefined or deterministic if (!schedulerChoice.isDefined()) { @@ -106,27 +106,8 @@ namespace storm { } template <typename ValueType> - void Scheduler<ValueType>::setStateReachable(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 (!reachableStates[memoryState].get(modelState)) { - reachableStates[memoryState].set(modelState, true); - --numOfUnreachableStates; - - // Choices for unreachable states are not considered undefined or deterministic - if (!schedulerChoice.isDefined()) { - ++numOfUndefinedChoices; - } else if (schedulerChoice.isDeterministic()) { - ++numOfDeterministicChoices; - } - - } - } - - template <typename ValueType> - bool Scheduler<ValueType>::isStateReachable(uint_fast64_t modelState, uint64_t memoryState) const { - return reachableStates[memoryState].get(modelState); + bool Scheduler<ValueType>::isDontCare(uint_fast64_t modelState, uint64_t memoryState) const { + return dontCareStates[memoryState].get(modelState); } template<typename ValueType> @@ -154,7 +135,7 @@ namespace storm { template <typename ValueType> bool Scheduler<ValueType>::isDeterministicScheduler() const { - return numOfDeterministicChoices == (schedulerChoices.size() * schedulerChoices.begin()->size()) - numOfUndefinedChoices - numOfUnreachableStates; + return numOfDeterministicChoices == (schedulerChoices.size() * schedulerChoices.begin()->size()) - numOfUndefinedChoices - numOfDontCareStates; } template <typename ValueType> @@ -174,7 +155,6 @@ namespace storm { template <typename ValueType> void Scheduler<ValueType>::printToStream(std::ostream& out, std::shared_ptr<storm::models::sparse::Model<ValueType>> model, bool skipUniqueChoices) const { - // TODO ignore unreachable states 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(); @@ -267,9 +247,8 @@ namespace storm { } // Print memory updates - if(!isMemorylessScheduler()) { - stateString << std::setw(30); //todo set width + out << std::setw(8); for (auto const& choiceProbPair : choice.getChoiceAsDistribution()) { uint64_t row = model->getTransitionMatrix().getRowGroupIndices()[state] + choiceProbPair.first; bool firstUpdate = true; @@ -282,7 +261,6 @@ namespace storm { stateString << "model state' = " << entryIt->getColumn() << ": (transition = " << entryIt - model->getTransitionMatrix().begin() << ") -> " << "(m' = "<<this->memoryStructure->getSuccessorMemoryState(memoryState, entryIt - model->getTransitionMatrix().begin()) <<")"; //out << ", model state' = " << entryIt->getColumn() << ": (transition = " << entryIt - model->getTransitionMatrix().begin() << ") -> " << "(m' = ?) "; } - } stateString << std::endl; diff --git a/src/storm/storage/Scheduler.h b/src/storm/storage/Scheduler.h index 18e3a8fb7..aeff2f225 100644 --- a/src/storm/storage/Scheduler.h +++ b/src/storm/storage/Scheduler.h @@ -61,25 +61,18 @@ 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 unreachable. + * Set the combination of model state and memoryStructure state to dontCare. + * This means the corresponding choices are neither considered undefined nor deterministic. * * @param modelState The state of the model. * @param memoryState The state of the memoryStructure. */ - void setStateUnreachable(uint_fast64_t modelState, uint_fast64_t memoryState = 0); - - /*! - * Set the combination of model state and memoryStructure state to reachable. - * - * @param modelState The state of the model. - * @param memoryState The state of the memoryStructure. - */ - void setStateReachable(uint_fast64_t modelState, uint_fast64_t memoryState = 0); + void setDontCare(uint_fast64_t modelState, uint_fast64_t memoryState = 0); /*! * Is the combination of model state and memoryStructure state to reachable? */ - bool isStateReachable(uint_fast64_t modelState, uint64_t memoryState = 0) const; + 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 @@ -152,8 +145,10 @@ namespace storm { std::vector<storm::storage::BitVector> reachableStates; uint_fast64_t numOfUndefinedChoices; // Only consider reachable ones + std::vector<storm::storage::BitVector> dontCareStates; // Their choices are neither considered deterministic nor undefined + uint_fast64_t numOfUndefinedChoices; uint_fast64_t numOfDeterministicChoices; - uint_fast64_t numOfUnreachableStates; + uint_fast64_t numOfDontCareStates; }; } } From f92b2104b599a4a2bd6b16f41cbda529d0b6c05a Mon Sep 17 00:00:00 2001 From: hannah <hannah.mertens@rwth-aachen.de> Date: Tue, 27 Jul 2021 11:07:10 +0200 Subject: [PATCH 113/172] TODOs and fixed an error during scheduler creation --- .../csl/SparseCtmcCslModelChecker.cpp | 2 +- .../SparseMarkovAutomatonCslModelChecker.cpp | 2 +- .../helper/ltl/SparseLTLHelper.cpp | 306 +++++++++--------- .../modelchecker/helper/ltl/SparseLTLHelper.h | 39 +-- .../prctl/SparseDtmcPrctlModelChecker.cpp | 4 +- .../prctl/SparseMdpPrctlModelChecker.cpp | 2 +- .../prctl/helper/SparseMdpPrctlHelper.cpp | 4 +- 7 files changed, 187 insertions(+), 172 deletions(-) diff --git a/src/storm/modelchecker/csl/SparseCtmcCslModelChecker.cpp b/src/storm/modelchecker/csl/SparseCtmcCslModelChecker.cpp index 28824477f..e83b692b7 100644 --- a/src/storm/modelchecker/csl/SparseCtmcCslModelChecker.cpp +++ b/src/storm/modelchecker/csl/SparseCtmcCslModelChecker.cpp @@ -130,7 +130,7 @@ namespace storm { modelDot.close(); } - storm::modelchecker::helper::SparseLTLHelper<ValueType, false> helper(embeddedDtmc.getTransitionMatrix(), embeddedDtmc.getNumberOfStates()); + storm::modelchecker::helper::SparseLTLHelper<ValueType, false> helper(embeddedDtmc.getTransitionMatrix()); storm::modelchecker::helper::setInformationFromCheckTaskDeterministic(helper, checkTask, embeddedDtmc); // Compute Satisfaction sets for APs diff --git a/src/storm/modelchecker/csl/SparseMarkovAutomatonCslModelChecker.cpp b/src/storm/modelchecker/csl/SparseMarkovAutomatonCslModelChecker.cpp index 641882d27..9ef8c5f1f 100644 --- a/src/storm/modelchecker/csl/SparseMarkovAutomatonCslModelChecker.cpp +++ b/src/storm/modelchecker/csl/SparseMarkovAutomatonCslModelChecker.cpp @@ -144,7 +144,7 @@ namespace storm { modelDot.close(); } - storm::modelchecker::helper::SparseLTLHelper<ValueType, true> helper(embeddedMdp.getTransitionMatrix(), embeddedMdp.getNumberOfStates()); + storm::modelchecker::helper::SparseLTLHelper<ValueType, true> helper(embeddedMdp.getTransitionMatrix()); storm::modelchecker::helper::setInformationFromCheckTaskNondeterministic(helper, checkTask, embeddedMdp); // Compute Satisfaction sets for APs diff --git a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp index 0235fa073..5c86422c1 100644 --- a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp +++ b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp @@ -23,7 +23,7 @@ namespace storm { namespace helper { template <typename ValueType, bool Nondeterministic> - SparseLTLHelper<ValueType, Nondeterministic>::SparseLTLHelper(storm::storage::SparseMatrix<ValueType> const& transitionMatrix, std::size_t numberOfStates) : _transitionMatrix(transitionMatrix), _numberOfStates(numberOfStates){ + SparseLTLHelper<ValueType, Nondeterministic>::SparseLTLHelper(storm::storage::SparseMatrix<ValueType> const& transitionMatrix) : _transitionMatrix(transitionMatrix){ // Intentionally left empty. } @@ -45,6 +45,7 @@ namespace storm { STORM_LOG_ASSERT(this->_producedChoices.is_initialized(), "Trying to extract the produced scheduler but none is available. Was there a computation call before?"); STORM_LOG_ASSERT(this->_memoryTransitions.is_initialized(), "Trying to extract the DA transition structure but none is available. Was there a computation call before?"); STORM_LOG_ASSERT(this->_memoryInitialStates.is_initialized(), "Trying to extract the initial states of the DA but there are none available. Was there a computation call before?"); + // todo STORM_LOG_ASSERT(this->_dontCareSates.is_initialized(), "Trying to extract the dontCare states of the Scheduler but there are none available. Was there a computation call before?"); // Create a memory structure for the MDP scheduler with memory. If hasRelevantStates is set, we only consider initial model states relevant. @@ -71,8 +72,7 @@ namespace storm { } } - - // Now, we can build the memoryStructure. + // 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. @@ -84,27 +84,23 @@ namespace storm { storm::storage::sparse::state_type modelState = std::get<0>(choice.first); storm::storage::sparse::state_type automatonState = std::get<1>(choice.first); uint_fast64_t infSet = std::get<2>(choice.first); - + STORM_LOG_ASSERT(!this->_dontCareStates.get()[(automatonState*(_infSets.get().size()+1))+ infSet].get(modelState), "Tried to set choice for dontCare state."); scheduler.setChoice(choice.second, modelState, (automatonState*(_infSets.get().size()+1))+ infSet); - - // TODO: shouldn't happen? - //STORM_LOG_ASSERT(!this->_unreachableStates.get()[(automatonState*(_infSets.get().size()+1))+ infSet].get(modelState), "Tried to set choice for unreachable state."); } - /* - for (uint_fast64_t memoryState = 0; this->_unreachableStates.get().size(); ++memoryState) { - for (auto state : this->_unreachableStates.get()[memoryState]) { - // todo fails, memory state = 9 - scheduler.setStateUnreachable(state, memoryState); + // todo Set don't care states + for (uint_fast64_t memoryState = 0; memoryState < this->_dontCareStates.get().size(); ++memoryState) { + for (auto state : this->_dontCareStates.get()[memoryState]) { + scheduler.setDontCare(state, memoryState); } + STORM_LOG_ASSERT(scheduler.isChoiceSelected(~_dontCareStates.get()[memoryState], memoryState), "choice missing" << memoryState); } - */ - // Sanity check for created scheduler. STORM_LOG_ASSERT(scheduler.isDeterministicScheduler(), "Expected a deterministic scheduler"); - // TODO STORM_LOG_ASSERT(!scheduler.isPartialScheduler(), "Expected a fully defined scheduler"); + STORM_LOG_ASSERT(!scheduler.isPartialScheduler(), "Expected a fully defined scheduler"); + return scheduler; } @@ -290,7 +286,7 @@ namespace storm { for (auto const &stateChoicePair : mec) { if (_accInfSets.get()[stateChoicePair.first] == boost::none) { // state wasn't assigned to any other MEC yet. - _accInfSets.get()[stateChoicePair.first] = infSetIds; + _accInfSets.get()[stateChoicePair.first].emplace(infSetIds); newMecStates.set(stateChoicePair.first); } @@ -303,19 +299,18 @@ namespace storm { storm::storage::Scheduler<ValueType> mecScheduler(transitionMatrix.getRowGroupCount()); // States not in InfSet: Compute a scheduler that, with prob=1, reaches the infSet via mecStates starting from states that are not yet in other MEC - storm::utility::graph::computeSchedulerProb1E<ValueType>(newMecStates, transitionMatrix, backwardTransitions, mecStates, _infSets.get()[id] & mecStates, mecScheduler); //todo &mecstates? nec.? - - // States that already reached the InfSet: Prob1E sets an arbitrary choice for the psi states, but we want to stay in this accepting mec. + storm::utility::graph::computeSchedulerProb1E<ValueType>(newMecStates, transitionMatrix, backwardTransitions, mecStates, _infSets.get()[id] & mecStates, mecScheduler); + // States that already reached the InfSet for (auto pState : (newMecStates & _infSets.get()[id])) { - // If we are in the InfSet, we move to some state in this MEC. + // Prob1E sets an arbitrary choice for the psi states, but we want to stay in this accepting MEC. mecScheduler.setChoice(*mec.getChoicesForState(pState).begin() - transitionMatrix.getRowGroupIndices()[pState], pState); } // Extract scheduler choices (only for states that are already assigned a scheduler, i.e are in another MEC) for (auto pState : newMecStates) { // We want to reach the InfSet, save choice: <s, q, InfSetID> ---> choice - // TODO _mecChoices <pState, InfSetID> ---> choice (remove product arg, transform directly to memoryState) + // TODO internal mec choices and transform to _producedChoices at end of fct? want to remove product ptr this->_producedChoices.get().insert({std::make_tuple(product->getModelState(pState), product->getAutomatonState(pState), id), mecScheduler.getChoice(pState)}); } } @@ -351,6 +346,89 @@ namespace storm { return acceptingStates; } + template <typename ValueType, bool Nondeterministic> + void SparseLTLHelper<ValueType, Nondeterministic>::createMemoryStructure(uint_fast64_t numDaStates, transformer::DAProductBuilder const& productBuilder, typename transformer::DAProduct<productModelType>::ptr product, storm::storage::BitVector const& acceptingProductStates, storm::storage::BitVector const& modelStatesOfInterest) { + // Prepare the memory structure. For that, we need: transitions, initialMemoryStates (and memoryStateLabeling) + + // Compute size of the resulting memory structure: a state corresponds to <q, infSet>> encoded as (q* (|infSets|+1))+infSet + //uint64 numMemoryStates = ((numDaStates-1) * (_infSets.get().size()+1)) + _infSets.get().size()+1; //+1 for states outside accECs + uint64 numMemoryStates = (numDaStates) * (_infSets.get().size()+1); //+1 for states outside accECs + STORM_LOG_INFO(" INF SETS: "<< (_infSets.get().size()+1)); + STORM_LOG_INFO(" INF SETS: "<< (numDaStates)); + + // The next move function of the memory, will be build based on the transitions of the DA and jumps between InfSets. + this->_memoryTransitions.emplace(numMemoryStates, std::vector<storm::storage::BitVector>(numMemoryStates, storm::storage::BitVector(this->_transitionMatrix.getRowGroupCount(), false))); + + + for (storm::storage::sparse::state_type automatonFrom = 0; automatonFrom < numDaStates; ++automatonFrom) { + for (storm::storage::sparse::state_type modelState = 0; modelState < this->_transitionMatrix.getRowGroupCount(); ++modelState) { + uint_fast64_t automatonTo = productBuilder.getSuccessor(modelState, automatonFrom, modelState); //TODO remove first parameter of getSuccessor + + if (product->isValidProductState(modelState, automatonTo)) { + // Add the modelState to one outgoing transition of all states of the form <automatonFrom, InfSet> (Inf=lenInfSet equals not in MEC) + // For non-accepting states that are not in any accepting EC we use the 'last' copy of the DA + // and for the accepting states we jump through copies of the DA wrt. the infinity sets. + for (uint_fast64_t infSet = 0; infSet < _infSets.get().size()+1; ++infSet) { + // Check if we need to switch the acceptance condition + STORM_LOG_ASSERT(_accInfSets.get()[product->getProductStateIndex(modelState, automatonTo)] != boost::none, "The list of InfSets for the product state <" <<modelState<< ", " << automatonTo<<"> is undefined."); + + if (_accInfSets.get()[product->getProductStateIndex(modelState, automatonTo)].get().count(infSet) == 0) { + // the state is is in a different accepting MEC with a different accepting conjunction of InfSets. + auto newInfSet = _accInfSets.get()[product->getProductStateIndex(modelState, automatonTo)].get().begin(); + _memoryTransitions.get()[(automatonFrom * (_infSets.get().size()+1)) + infSet][(automatonTo * (_infSets.get().size()+1)) + *newInfSet].set(modelState); + + + } else { + // Continue looking for any accepting EC (if we haven't reached one yet) or stay in the corresponding accepting EC, test whether we have reached the next infSet. + if (infSet == _infSets.get().size() || !(_infSets.get()[infSet].get(product->getProductStateIndex(modelState, automatonTo)))) { + // <modelState, automatonTo> is not in any accepting EC or does not satisfy the InfSet, we stay there. + // Add modelState to the transition from <automatonFrom, InfSet> to <automatonTo, InfSet> + _memoryTransitions.get()[(automatonFrom * (_infSets.get().size()+1)) + infSet][(automatonTo * (_infSets.get().size()+1)) + infSet].set(modelState); + + } else { + STORM_LOG_ASSERT(_accInfSets.get()[product->getProductStateIndex(modelState, automatonTo)] != boost::none, "The list of InfSets for the product state <" <<modelState<< ", " << automatonTo<<"> is undefined."); + // <modelState, automatonTo> satisfies the InfSet, find the next one. + auto nextInfSet = std::find(_accInfSets.get()[product->getProductStateIndex(modelState, automatonTo)].get().begin(), _accInfSets.get()[product->getProductStateIndex(modelState, automatonTo)].get().end(), infSet); + STORM_LOG_ASSERT(nextInfSet != _accInfSets.get()[product->getProductStateIndex(modelState, automatonTo)].get().end(), "The list of InfSets for the product state <" <<modelState<< ", " << automatonTo<<"> does not contain the infSet " << infSet); + nextInfSet++; + if (nextInfSet == _accInfSets.get()[product->getProductStateIndex(modelState, automatonTo)].get().end()) { + // Start again. + nextInfSet = _accInfSets.get()[product->getProductStateIndex(modelState, automatonTo)].get().begin(); + } + // Add modelState to the transition from <automatonFrom <mec, InfSet>> to <automatonTo, <mec, NextInfSet>>. + _memoryTransitions.get()[(automatonFrom * (_infSets.get().size()+1)) + infSet][(automatonTo * (_infSets.get().size()+1)) + *nextInfSet].set(modelState); + } + } + } + } + + } + } + // Finished creation of transitions. + + // Find initial memory states + + this->_memoryInitialStates.emplace(); + this->_memoryInitialStates->resize(this->_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."); + if (acceptingProductStates[product->getProductStateIndex(modelState, automatonState)]) { + STORM_LOG_ASSERT(_accInfSets.get()[product->getProductStateIndex(modelState, automatonState)] != boost::none, "The list of InfSets for the product state <" <<modelState<< ", " << automatonState<<"> is undefined."); + // If <s, q> is an accepting state start in the first InfSet of <s, q>. + auto infSet = _accInfSets.get()[product->getProductStateIndex(modelState, automatonState)].get().begin(); + _memoryInitialStates.get()[modelState] = (automatonState * (_infSets.get().size()+1)) + *infSet; + + } else { + _memoryInitialStates.get()[modelState] = (automatonState * (_infSets.get().size()+1)) + _infSets.get().size(); + } + + } + // Finished creation of initial states. + + } + 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(); @@ -370,18 +448,18 @@ namespace storm { statesOfInterest = this->getRelevantStates(); } else { // product from all model states - statesOfInterest = storm::storage::BitVector(this->_numberOfStates, true); + 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); - typename transformer::DAProduct<productModelType>::ptr product = productBuilder.build<productModelType>(this->_transitionMatrix, statesOfInterest); + 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."); + << product->getProductModel().getNumberOfTransitions() << " transitions."); if (storm::settings::getModule<storm::settings::modules::DebugSettings>().isTraceSet()) { STORM_LOG_TRACE("Writing product model to product.dot"); @@ -401,7 +479,7 @@ namespace storm { STORM_LOG_INFO("Computing MECs and checking for acceptance..."); acceptingStates = computeAcceptingECs(*product->getAcceptance(), product->getProductModel().getTransitionMatrix(), product->getProductModel().getBackwardTransitions(), product); //TODO product is only needed for ->getModelState(pState) (remove arg) - } else { + } else { STORM_LOG_INFO("Computing BSCCs and checking for acceptance..."); acceptingStates = computeAcceptingBCCs(*product->getAcceptance(), product->getProductModel().getTransitionMatrix()); @@ -409,7 +487,7 @@ namespace storm { if (acceptingStates.empty()) { STORM_LOG_INFO("No accepting states, skipping probability computation."); - std::vector<ValueType> numericResult(this->_numberOfStates, storm::utility::zero<ValueType>()); + std::vector<ValueType> numericResult(this->_transitionMatrix.getRowGroupCount(), storm::utility::zero<ValueType>()); this->_randomScheduler = true; return numericResult; } @@ -433,139 +511,73 @@ namespace storm { 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. - ); + 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()) { // TODO create fct for this + if (this->isProduceSchedulerSet()) { - // TODO asserts _mecStatesInfSets initialized etc. + STORM_LOG_ASSERT(this->_producedChoices.is_initialized(), "Trying to extract the produced scheduler but none is available. Was there a computation call before?"); + STORM_LOG_ASSERT(this->_infSets.is_initialized(), "Was there a computation call before?"); + STORM_LOG_ASSERT(this->_accInfSets.is_initialized(), "Was there a computation call before?"); - // Compute size of the resulting memory structure: a state corresponds to <q, infSet>> encoded as (q* (|infSets|+1))+infSet - uint64 numMemoryStates = (da.getNumberOfStates() * (_infSets.get().size()+1)) + _infSets.get().size()+1; //+1 for states outside accECs - _unreachableStates.emplace(numMemoryStates, storm::storage::BitVector(this->_transitionMatrix.getRowGroupCount(), false)); + // TODO fct + //_dontCareStates.emplace(((da.getNumberOfStates()-1) * (_infSets.get().size()+1)) + _infSets.get().size()+1, storm::storage::BitVector(this->_transitionMatrix.getRowGroupCount(), false)); + _dontCareStates.emplace(((da.getNumberOfStates()) * (_infSets.get().size()+1)), storm::storage::BitVector(this->_transitionMatrix.getRowGroupCount(), false)); + // TODO optimize: + for (storm::storage::sparse::state_type automatonState= 0; automatonState < da.getNumberOfStates(); ++automatonState) { + for (storm::storage::sparse::state_type modelState = 0; modelState < this->_transitionMatrix.getRowGroupCount(); ++modelState) { - // Extract the choices of the REACH-scheduler (choices to reach an acc. MEC) for the MDP-DA product: <s,q> -> choice - for (storm::storage::sparse::state_type pState = 0; pState < this->_transitionMatrix.getRowGroupCount(); ++pState) { - - - // set _producedChoices <s, <memory state>> ---> choice. - if (acceptingStates.get(pState)) { - // TODO extract _mecProductChoices // TODO directly translate into memstate , modelstate - } else { - // For non-accepting states that are not in any accepting EC we use the 'last' copy of the DA - this->_accInfSets.get()[pState] = {_infSets.get().size()}; - - // For state <s,q> not in any accEC: <s,q, REACH> ---> choice. - // TODO directly translate into memstate , modelstate - this->_producedChoices.get().insert({std::make_tuple(product->getModelState(pState), - product->getAutomatonState(pState), - _infSets.get().size()), - prodCheckResult.scheduler->getChoice(pState)}); - if (!prodCheckResult.scheduler->isStateReachable(pState)) { - //TODO - // this->_unreachableStates.get()[(product->getAutomatonState(pState)) * (_infSets.get().size()+1) + _infSets.get().size()].set(product->getModelState(pState)); + if (! product->isValidProductState(modelState, automatonState)) { + for (uint_fast64_t infSet = 0; infSet < _infSets.get().size()+1; ++infSet) { + _dontCareStates.get()[automatonState * (_infSets.get().size() + 1) + infSet].set(modelState, 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. - this->_memoryTransitions.emplace(numMemoryStates, std::vector<storm::storage::BitVector>(numMemoryStates, storm::storage::BitVector(this->_transitionMatrix.getRowGroupCount(), false))); - - - - - for (storm::storage::sparse::state_type automatonFrom = 0; automatonFrom < da.getNumberOfStates(); ++automatonFrom) { - for (storm::storage::sparse::state_type automatonTo = 0; automatonTo < da.getNumberOfStates(); ++automatonTo) { - // Find the modelStates that trigger this transition. - for (storm::storage::sparse::state_type modelState = 0; modelState < this->_transitionMatrix.getRowGroupCount(); ++modelState) { - - if(!product->isValidProductState(modelState, automatonTo)) { - // <modelState, automatonTo> is not defined in the Product. Thus, considered not reachable for the scheduler. - for (uint_fast64_t infSet = 0; infSet < _infSets.get().size(); ++infSet) { - this->_unreachableStates.get()[ (automatonTo* (_infSets.get().size()+1)) + infSet].set(modelState); - } - - } else if (automatonTo == productBuilder.getSuccessor(modelState, automatonFrom, modelState)) { //TODO remove first parameter of getSuccessor - - // Add the modelState to one outgoing transition of all states of the form <automatonFrom, InfSet> (Inf=lenInfSet equals not in MEC) - // For non-accepting states that are not in any accepting EC we use the 'last' copy of the DA - // and for the accepting states we jump through copies of the DA wrt. the infinity sets. - for (uint_fast64_t infSet = 0; infSet < _infSets.get().size()+1; ++infSet) { - // Check if we need to switch the acceptance condition - if (_accInfSets.get()[product->getProductStateIndex(modelState, automatonTo)].get().count(infSet) == 0) { - // the state is is in a different accepting MEC with a different accepting conjunction of InfSets. - auto newInfSet = _accInfSets.get()[product->getProductStateIndex(modelState, automatonTo)].get().begin(); - _memoryTransitions.get()[(automatonFrom * (_infSets.get().size()+1)) + infSet][(automatonTo * (_infSets.get().size()+1)) + *newInfSet].set(modelState); + // and optimize dontCare below: + // Extract the choices of the REACH-scheduler (choices to reach an acc. MEC) for the MDP-DA product: <s,q> -> choice + for (storm::storage::sparse::state_type pState = 0; pState < product->getProductModel().getTransitionMatrix().getRowGroupCount(); ++pState) { + if (acceptingStates.get(pState)) { + // Set the undefined MEC-scheduler combinations to dontCare. + for (uint_fast64_t infSet = 0; infSet < _infSets.get().size()+1; ++infSet) { // TODO infset+1 too? + // todo If <s, q, infSet> is not in _mecProductChoices it is dont Care? + if (_producedChoices.get().find(std::make_tuple(product->getModelState(pState), product->getAutomatonState(pState), infSet)) == _producedChoices.get().end() ) { + _dontCareStates.get()[(product->getAutomatonState(pState)) * (_infSets.get().size()+1) + infSet].set(product->getModelState(pState), true); + } + } + } else { + // Set choice For non-accepting states that are not in any accepting EC + this->_accInfSets.get()[pState] = {_infSets.get().size()}; + if (prodCheckResult.scheduler->isDontCare(pState)) { + _dontCareStates.get()[(product->getAutomatonState(pState)) * (_infSets.get().size()+1) + _infSets.get().size()].set(product->getModelState(pState), true); + } else { + // For state <s,q> not in any accEC: <s,q, REACH> ---> choice. + // Use the 'last' copy of the DA + this->_producedChoices.get().insert({std::make_tuple(product->getModelState(pState),product->getAutomatonState(pState),_infSets.get().size()),prodCheckResult.scheduler->getChoice(pState)}); + }; - // TODO problem other inf set combis may not be reachable? - // this->_reachableStates.get()[(automatonTo * (_infSets.get().size()+1)) + *newInfSet].set(modelState, true); + // todo correct? nonMec state x infSet do not exist + for (uint_fast64_t infSet = 0; infSet < _infSets.get().size(); ++infSet) { + _dontCareStates.get()[(product->getAutomatonState(pState)) * (_infSets.get().size()+1) + infSet].set(product->getModelState(pState), true); - } else { - // The state is either not in an accepting EC or in an accepting EC that needs to satisfy the infSet. - if (infSet == _infSets.get().size() || !(_infSets.get()[infSet].get(product->getProductStateIndex(modelState, automatonTo)))) { - // <modelState, automatonTo> is not in any accepting EC or does not satisfy the InfSet, we stay there. - // Add modelState to the transition from <automatonFrom, InfSet> to <automatonTo, InfSet> - _memoryTransitions.get()[(automatonFrom * (_infSets.get().size()+1)) + infSet][(automatonTo * (_infSets.get().size()+1)) + infSet].set(modelState); - - // TODO problem other inf set combis may not be reachable? - //this->_reachableStates.get()[(automatonTo * (_infSets.get().size()+1)) + infSet].set(modelState, true); - - } else { - STORM_LOG_ASSERT(_accInfSets.get()[product->getProductStateIndex(modelState, automatonTo)] != boost::none, "The list of InfSets for the product state <" <<modelState<< ", " << automatonTo<<"> is undefined."); - // <modelState, automatonTo> satisfies the InfSet, find the next one - auto nextInfSet = std::find(_accInfSets.get()[product->getProductStateIndex(modelState, automatonTo)].get().begin(), _accInfSets.get()[product->getProductStateIndex(modelState, automatonTo)].get().end(), infSet); - STORM_LOG_ASSERT(nextInfSet != _accInfSets.get()[product->getProductStateIndex(modelState, automatonTo)].get().end(), "The list of InfSets for the product state <" <<modelState<< ", " << automatonTo<<"> does not contain the infSet " << infSet); - nextInfSet++; - if (nextInfSet == _accInfSets.get()[product->getProductStateIndex(modelState, automatonTo)].get().end()) { - // Start again. - nextInfSet = _accInfSets.get()[product->getProductStateIndex(modelState, automatonTo)].get().begin(); - } - // Add modelState to the transition from <automatonFrom <mec, InfSet>> to <automatonTo, <mec, NextInfSet>>. - _memoryTransitions.get()[(automatonFrom * (_infSets.get().size()+1)) + infSet][(automatonTo * (_infSets.get().size()+1)) + *nextInfSet].set(modelState); - - // TODO problem other inf set combis may not be reachable? - // this->_reachableStates.get()[(automatonTo * (_infSets.get().size()+1)) + *nextInfSet].set(modelState, true); - } - } - } - } } } } - // Finished creation of transitions. - - // Find initial memory states - this->_memoryInitialStates.emplace(); - this->_memoryInitialStates->resize(this->_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 : statesOfInterest) { - 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."); - if (acceptingStates[product->getProductStateIndex(modelState, automatonState)]) { - STORM_LOG_ASSERT(_accInfSets.get()[product->getProductStateIndex(modelState, automatonState)] != boost::none, "The list of InfSets for the product state <" <<modelState<< ", " << automatonState<<"> is undefined."); - // If <s, q> is an accepting state start in the first InfSet of <s, q>. - auto infSet = _accInfSets.get()[product->getProductStateIndex(modelState, automatonState)].get().begin(); - _memoryInitialStates.get()[modelState] = (automatonState * (_infSets.get().size()+1)) + *infSet; - } else { - _memoryInitialStates.get()[modelState] = (automatonState * (_infSets.get().size()+1)) + _infSets.get().size(); - } + // todo extend by scheduler choices? + // todo extractSchedulerChoices() + createMemoryStructure(da.getNumberOfStates(), productBuilder, product, acceptingStates, statesOfInterest); - } - // Finished creation of initial states. } } else { @@ -576,9 +588,9 @@ namespace storm { bvTrue, acceptingStates, this->isQualitativeSet()); - } + } - std::vector<ValueType> numericResult = product->projectToOriginalModel(this->_numberOfStates, prodNumericResult); + std::vector<ValueType> numericResult = product->projectToOriginalModel(this->_transitionMatrix.getRowGroupCount(), prodNumericResult); return numericResult; } @@ -612,10 +624,10 @@ namespace storm { da = storm::automata::LTL2DeterministicAutomaton::ltl2daSpot(*ltlFormula, Nondeterministic); } - STORM_LOG_DEBUG("Deterministic automaton for LTL formula has " - << da->getNumberOfStates() << " states, " - << da->getAPSet().size() << " atomic propositions and " - << *da->getAcceptance()->getAcceptanceExpression() << " as acceptance condition." << std::endl); + 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); diff --git a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h index e710676c9..fb7bf0101 100644 --- a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h +++ b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h @@ -25,8 +25,8 @@ namespace storm { public: /*! - * The type of the product automaton (DTMC or MDP) that is used during the computation. - */ + * The type of the product automaton (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; /*! @@ -34,21 +34,21 @@ namespace storm { * @param the transition matrix of the model * @param the number of states of the model */ - SparseLTLHelper(storm::storage::SparseMatrix<ValueType> const& transitionMatrix, std::size_t numberOfSates); + 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 TODO + * @param 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); /*! - * todo computes Sat sets of AP - * @param - * @param - * @return + * Computes the states that are satisfying the AP. + * @param mapping from Ap to formula + * @param lambda that checks the provided formula + * @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, std::function<std::unique_ptr<CheckResult>(std::shared_ptr<storm::logic::Formula const> const& formula)> formulaChecker); @@ -71,7 +71,7 @@ namespace storm { private: /*! - * Compute a set S of states that admit a probability 1 strategy of satisfying the given acceptance condition (in DNF). + * 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 @@ -85,24 +85,27 @@ namespace storm { 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); /** - * Compute a set S of states that are contained in BSCCs that satisfy the given acceptance conditon. - * @tparam the acceptance condition - * @tparam the transition matrix of the model + * Computes a set S of states that are contained in BSCCs that satisfy the given acceptance conditon. + * @param the acceptance condition + * @param the transition matrix of the model */ storm::storage::BitVector computeAcceptingBCCs(automata::AcceptanceCondition const& acceptance, storm::storage::SparseMatrix<ValueType> const& transitionMatrix); + /** + * Helper function, creates the memory structure for the LTL-Scheduler. + * @param the acceptance condition + * @param the transition matrix of the model + */ + void createMemoryStructure(uint_fast64_t numDaStates, transformer::DAProductBuilder const& productBuilder, typename transformer::DAProduct<productModelType>::ptr product, storm::storage::BitVector const& acceptingProductStates, storm::storage::BitVector const& modelStatesOfInterest); + storm::storage::SparseMatrix<ValueType> const& _transitionMatrix; - std::size_t _numberOfStates; //TODO just use _transitionMatrix.getRowGroupCount instead? // scheduler bool _randomScheduler = false; - // todo directly memstate, state -> choice - boost::optional<std::map <std::tuple<uint_fast64_t, uint_fast64_t, uint_fast64_t>, storm::storage::SchedulerChoice<ValueType>>> _producedChoices; // <s, q, len(_infSets)> ---> ReachChoice and <s, q, InfSet> ---> MecChoice - boost::optional<std::vector<storm::storage::BitVector>> _unreachableStates; // unreachable memory state and model state combinations + boost::optional<std::map <std::tuple<uint_fast64_t, uint_fast64_t, uint_fast64_t>, storm::storage::SchedulerChoice<ValueType>>> _producedChoices; // <s, q, len(_infSets)> ---> ReachChoice and <s, q, InfSet> ---> MecChoice + boost::optional<std::vector<storm::storage::BitVector>> _dontCareStates; // memory state combinations that are never visited - // Mec Scheduler - // _mecProductChoices <pstate> -> choice boost::optional<std::vector<storm::storage::BitVector>> _infSets; // Save the InfSets of the Acceptance condition. boost::optional<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 diff --git a/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.cpp b/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.cpp index 2e14c8fdb..870a9a09a 100644 --- a/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.cpp +++ b/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.cpp @@ -132,7 +132,7 @@ namespace storm { << *da->getAcceptance()->getAcceptanceExpression() << " as acceptance condition."); const SparseDtmcModelType& dtmc = this->getModel(); - storm::modelchecker::helper::SparseLTLHelper<ValueType, false> helper(dtmc.getTransitionMatrix(), dtmc.getNumberOfStates()); + storm::modelchecker::helper::SparseLTLHelper<ValueType, false> helper(dtmc.getTransitionMatrix()); storm::modelchecker::helper::setInformationFromCheckTaskDeterministic(helper, checkTask, dtmc); // Compute Satisfaction sets for APs @@ -164,7 +164,7 @@ namespace storm { modelDot.close(); } - storm::modelchecker::helper::SparseLTLHelper<ValueType, false> helper(dtmc.getTransitionMatrix(), dtmc.getNumberOfStates()); + storm::modelchecker::helper::SparseLTLHelper<ValueType, false> helper(dtmc.getTransitionMatrix()); storm::modelchecker::helper::setInformationFromCheckTaskDeterministic(helper, checkTask, dtmc); // Compute Satisfaction sets for APs diff --git a/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.cpp b/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.cpp index 1d68b1d1f..cba1864d2 100644 --- a/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.cpp +++ b/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.cpp @@ -198,7 +198,7 @@ namespace storm { } - storm::modelchecker::helper::SparseLTLHelper<ValueType, true> helper(mdp.getTransitionMatrix(), mdp.getNumberOfStates()); + storm::modelchecker::helper::SparseLTLHelper<ValueType, true> helper(mdp.getTransitionMatrix()); storm::modelchecker::helper::setInformationFromCheckTaskNondeterministic(helper, checkTask, mdp); // Compute Satisfaction sets for APs diff --git a/src/storm/modelchecker/prctl/helper/SparseMdpPrctlHelper.cpp b/src/storm/modelchecker/prctl/helper/SparseMdpPrctlHelper.cpp index 5321960a9..de837daa3 100644 --- a/src/storm/modelchecker/prctl/helper/SparseMdpPrctlHelper.cpp +++ b/src/storm/modelchecker/prctl/helper/SparseMdpPrctlHelper.cpp @@ -616,10 +616,10 @@ namespace storm { 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 "unreachable" + // If maybeStatesNotRelevant is true, we have to set the scheduler for maybe states as "dontCare" if (maybeStatesNotRelevant) { for (auto state : qualitativeStateSets.maybeStates) { - scheduler->setStateUnreachable(state); + scheduler->setDontCare(state); } } From cceb3513ce04cbc2825e58799f826cb8d85e7e8c Mon Sep 17 00:00:00 2001 From: hannah <hannah.mertens@rwth-aachen.de> Date: Tue, 27 Jul 2021 14:10:36 +0200 Subject: [PATCH 114/172] set states to dontCare during scheduler computations, adapted Tests --- .../automata/LTL2DeterministicAutomaton.cpp | 5 +- .../helper/ltl/SparseLTLHelper.cpp | 132 ++++++++---------- .../modelchecker/helper/ltl/SparseLTLHelper.h | 10 +- src/storm/transformer/DAProductBuilder.h | 3 +- src/storm/transformer/ProductBuilder.h | 4 +- ...ulerGenerationMdpPrctlModelCheckerTest.cpp | 71 ++++++---- 6 files changed, 109 insertions(+), 116 deletions(-) diff --git a/src/storm/automata/LTL2DeterministicAutomaton.cpp b/src/storm/automata/LTL2DeterministicAutomaton.cpp index 52e1192f0..e33939f7b 100644 --- a/src/storm/automata/LTL2DeterministicAutomaton.cpp +++ b/src/storm/automata/LTL2DeterministicAutomaton.cpp @@ -64,7 +64,6 @@ namespace storm { #endif } - // TODO: this is quite hacky, improve robustness std::shared_ptr<DeterministicAutomaton> LTL2DeterministicAutomaton::ltl2daExternalTool(storm::logic::Formula const& f, std::string ltl2daTool) { std::string prefixLtl = f.toPrefixString(); @@ -97,8 +96,8 @@ namespace storm { } STORM_LOG_THROW(rv == 0, storm::exceptions::FileIoException, "Could not construct deterministic automaton for " << prefixLtl << ", return code = " << rv); - // TODO transition-based acceptance is required, - // and for MDP-MC the acceptance condition must be in DNF, otherwise an exception is thrown during computation if accepting ECs + // Transition-based acceptance is required. + // For MDP-MC the acceptance condition must be in DNF, otherwise an exception is thrown during computation if accepting ECs STORM_LOG_INFO("Reading automaton for " << prefixLtl << " from da.hoa"); return DeterministicAutomaton::parseFromFile("da.hoa"); diff --git a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp index 5c86422c1..b315aa2c0 100644 --- a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp +++ b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp @@ -45,7 +45,7 @@ namespace storm { STORM_LOG_ASSERT(this->_producedChoices.is_initialized(), "Trying to extract the produced scheduler but none is available. Was there a computation call before?"); STORM_LOG_ASSERT(this->_memoryTransitions.is_initialized(), "Trying to extract the DA transition structure but none is available. Was there a computation call before?"); STORM_LOG_ASSERT(this->_memoryInitialStates.is_initialized(), "Trying to extract the initial states of the DA but there are none available. Was there a computation call before?"); - // todo STORM_LOG_ASSERT(this->_dontCareSates.is_initialized(), "Trying to extract the dontCare states of the Scheduler but there are none available. Was there a computation call before?"); + STORM_LOG_ASSERT(this->_dontCareStates.is_initialized(), "Trying to extract the dontCare states of the Scheduler but there are none available. Was there a computation call before?"); // Create a memory structure for the MDP scheduler with memory. If hasRelevantStates is set, we only consider initial model states relevant. @@ -88,15 +88,13 @@ namespace storm { scheduler.setChoice(choice.second, modelState, (automatonState*(_infSets.get().size()+1))+ infSet); } - // todo Set don't care states + // Set "don't care" states for (uint_fast64_t memoryState = 0; memoryState < this->_dontCareStates.get().size(); ++memoryState) { for (auto state : this->_dontCareStates.get()[memoryState]) { scheduler.setDontCare(state, memoryState); } - STORM_LOG_ASSERT(scheduler.isChoiceSelected(~_dontCareStates.get()[memoryState], memoryState), "choice missing" << 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"); @@ -149,8 +147,7 @@ namespace storm { } 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 + // 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); STORM_LOG_INFO("Handle conjunction " << i); @@ -310,7 +307,6 @@ namespace storm { // Extract scheduler choices (only for states that are already assigned a scheduler, i.e are in another MEC) for (auto pState : newMecStates) { // We want to reach the InfSet, save choice: <s, q, InfSetID> ---> choice - // TODO internal mec choices and transform to _producedChoices at end of fct? want to remove product ptr this->_producedChoices.get().insert({std::make_tuple(product->getModelState(pState), product->getAutomatonState(pState), id), mecScheduler.getChoice(pState)}); } } @@ -347,22 +343,63 @@ namespace storm { } template <typename ValueType, bool Nondeterministic> - void SparseLTLHelper<ValueType, Nondeterministic>::createMemoryStructure(uint_fast64_t numDaStates, transformer::DAProductBuilder const& productBuilder, typename transformer::DAProduct<productModelType>::ptr product, storm::storage::BitVector const& acceptingProductStates, storm::storage::BitVector const& modelStatesOfInterest) { - // Prepare the memory structure. For that, we need: transitions, initialMemoryStates (and memoryStateLabeling) + void SparseLTLHelper<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_LOG_ASSERT(this->_producedChoices.is_initialized(), "Trying to extract the produced scheduler but none is available. Was there a computation call before?"); + STORM_LOG_ASSERT(this->_infSets.is_initialized(), "Was there a computation call before?"); + STORM_LOG_ASSERT(this->_accInfSets.is_initialized(), "Was there a computation call before?"); - // Compute size of the resulting memory structure: a state corresponds to <q, infSet>> encoded as (q* (|infSets|+1))+infSet - //uint64 numMemoryStates = ((numDaStates-1) * (_infSets.get().size()+1)) + _infSets.get().size()+1; //+1 for states outside accECs + // Compute size of the resulting memory structure: A state <q, infSet> is encoded as (q* (|infSets|+1))+ |infSet| uint64 numMemoryStates = (numDaStates) * (_infSets.get().size()+1); //+1 for states outside accECs - STORM_LOG_INFO(" INF SETS: "<< (_infSets.get().size()+1)); - STORM_LOG_INFO(" INF SETS: "<< (numDaStates)); + _dontCareStates.emplace(numMemoryStates, storm::storage::BitVector(this->_transitionMatrix.getRowGroupCount(), false)); - // The next move function of the memory, will be build based on the transitions of the DA and jumps between InfSets. - this->_memoryTransitions.emplace(numMemoryStates, std::vector<storm::storage::BitVector>(numMemoryStates, storm::storage::BitVector(this->_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 < this->_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.get().size()+1; ++infSet) { + _dontCareStates.get()[automatonState * (_infSets.get().size() + 1) + infSet].set(modelState, true); + } + } else { + auto pState = product->getProductStateIndex(modelState, automatonState); + if (acceptingProductStates.get(pState)) { + // For states in accepting ECs set the missing MEC-scheduler combinations are "dontCare", they are not reachable using the scheduler choices. //TODO is this correct? + for (uint_fast64_t infSet = 0; infSet < _infSets.get().size()+1; ++infSet) { + if (_producedChoices.get().find(std::make_tuple(product->getModelState(pState), product->getAutomatonState(pState), infSet)) == _producedChoices.get().end() ) { + _dontCareStates.get()[(product->getAutomatonState(pState)) * (_infSets.get().size()+1) + 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 "last" copy of the DA (_infSets.get().size()). + this->_accInfSets.get()[pState] = {_infSets.get().size()}; + if (reachScheduler->isDontCare(pState)) { + // Mark the maybe States of the untilProbability scheduler as "dontCare" + _dontCareStates.get()[(product->getAutomatonState(pState)) * (_infSets.get().size()+1) + _infSets.get().size()].set(product->getModelState(pState), true); + } else { + // Set choice For non-accepting states that are not in any accepting EC + this->_producedChoices.get().insert({std::make_tuple(product->getModelState(pState),product->getAutomatonState(pState),_infSets.get().size()),reachScheduler->getChoice(pState)}); + }; + // All other InfSet combinations are unreachable (dontCare) + for (uint_fast64_t infSet = 0; infSet < _infSets.get().size(); ++infSet) { + _dontCareStates.get()[(product->getAutomatonState(pState)) * (_infSets.get().size()+1) + 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.emplace(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 < this->_transitionMatrix.getRowGroupCount(); ++modelState) { - uint_fast64_t automatonTo = productBuilder.getSuccessor(modelState, automatonFrom, modelState); //TODO remove first parameter of getSuccessor + 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)) { // Add the modelState to one outgoing transition of all states of the form <automatonFrom, InfSet> (Inf=lenInfSet equals not in MEC) @@ -377,7 +414,6 @@ namespace storm { auto newInfSet = _accInfSets.get()[product->getProductStateIndex(modelState, automatonTo)].get().begin(); _memoryTransitions.get()[(automatonFrom * (_infSets.get().size()+1)) + infSet][(automatonTo * (_infSets.get().size()+1)) + *newInfSet].set(modelState); - } else { // Continue looking for any accepting EC (if we haven't reached one yet) or stay in the corresponding accepting EC, test whether we have reached the next infSet. if (infSet == _infSets.get().size() || !(_infSets.get()[infSet].get(product->getProductStateIndex(modelState, automatonTo)))) { @@ -407,7 +443,6 @@ namespace storm { // Finished creation of transitions. // Find initial memory states - this->_memoryInitialStates.emplace(); this->_memoryInitialStates->resize(this->_transitionMatrix.getRowGroupCount()); // Save for each relevant model state its initial memory state (get the s-successor q of q0) @@ -447,7 +482,7 @@ namespace storm { if (this->hasRelevantStates()) { statesOfInterest = this->getRelevantStates(); } else { - // product from all model states + // Product from all model states statesOfInterest = storm::storage::BitVector(this->_transitionMatrix.getRowGroupCount(), true); } @@ -522,62 +557,7 @@ namespace storm { prodNumericResult = std::move(prodCheckResult.values); if (this->isProduceSchedulerSet()) { - - STORM_LOG_ASSERT(this->_producedChoices.is_initialized(), "Trying to extract the produced scheduler but none is available. Was there a computation call before?"); - STORM_LOG_ASSERT(this->_infSets.is_initialized(), "Was there a computation call before?"); - STORM_LOG_ASSERT(this->_accInfSets.is_initialized(), "Was there a computation call before?"); - - // TODO fct - //_dontCareStates.emplace(((da.getNumberOfStates()-1) * (_infSets.get().size()+1)) + _infSets.get().size()+1, storm::storage::BitVector(this->_transitionMatrix.getRowGroupCount(), false)); - _dontCareStates.emplace(((da.getNumberOfStates()) * (_infSets.get().size()+1)), storm::storage::BitVector(this->_transitionMatrix.getRowGroupCount(), false)); - - - // TODO optimize: - for (storm::storage::sparse::state_type automatonState= 0; automatonState < da.getNumberOfStates(); ++automatonState) { - for (storm::storage::sparse::state_type modelState = 0; modelState < this->_transitionMatrix.getRowGroupCount(); ++modelState) { - - if (! product->isValidProductState(modelState, automatonState)) { - for (uint_fast64_t infSet = 0; infSet < _infSets.get().size()+1; ++infSet) { - _dontCareStates.get()[automatonState * (_infSets.get().size() + 1) + infSet].set(modelState, true); - } - } - } - } - - // and optimize dontCare below: - // Extract the choices of the REACH-scheduler (choices to reach an acc. MEC) for the MDP-DA product: <s,q> -> choice - for (storm::storage::sparse::state_type pState = 0; pState < product->getProductModel().getTransitionMatrix().getRowGroupCount(); ++pState) { - if (acceptingStates.get(pState)) { - // Set the undefined MEC-scheduler combinations to dontCare. - for (uint_fast64_t infSet = 0; infSet < _infSets.get().size()+1; ++infSet) { // TODO infset+1 too? - // todo If <s, q, infSet> is not in _mecProductChoices it is dont Care? - if (_producedChoices.get().find(std::make_tuple(product->getModelState(pState), product->getAutomatonState(pState), infSet)) == _producedChoices.get().end() ) { - _dontCareStates.get()[(product->getAutomatonState(pState)) * (_infSets.get().size()+1) + infSet].set(product->getModelState(pState), true); - } - } - } else { - // Set choice For non-accepting states that are not in any accepting EC - this->_accInfSets.get()[pState] = {_infSets.get().size()}; - if (prodCheckResult.scheduler->isDontCare(pState)) { - _dontCareStates.get()[(product->getAutomatonState(pState)) * (_infSets.get().size()+1) + _infSets.get().size()].set(product->getModelState(pState), true); - } else { - // For state <s,q> not in any accEC: <s,q, REACH> ---> choice. - // Use the 'last' copy of the DA - this->_producedChoices.get().insert({std::make_tuple(product->getModelState(pState),product->getAutomatonState(pState),_infSets.get().size()),prodCheckResult.scheduler->getChoice(pState)}); - }; - - // todo correct? nonMec state x infSet do not exist - for (uint_fast64_t infSet = 0; infSet < _infSets.get().size(); ++infSet) { - _dontCareStates.get()[(product->getAutomatonState(pState)) * (_infSets.get().size()+1) + infSet].set(product->getModelState(pState), true); - - } - } - } - - // todo extend by scheduler choices? - // todo extractSchedulerChoices() - createMemoryStructure(da.getNumberOfStates(), productBuilder, product, acceptingStates, statesOfInterest); - + prepareScheduler(da.getNumberOfStates(), acceptingStates, std::move(prodCheckResult.scheduler), productBuilder, product, statesOfInterest); } } else { diff --git a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h index fb7bf0101..8b85a07de 100644 --- a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h +++ b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h @@ -92,11 +92,13 @@ namespace storm { storm::storage::BitVector computeAcceptingBCCs(automata::AcceptanceCondition const& acceptance, storm::storage::SparseMatrix<ValueType> const& transitionMatrix); /** - * Helper function, creates the memory structure for the LTL-Scheduler. - * @param the acceptance condition - * @param the transition matrix of the model + * Helper function, extracts scheduler choices and creates the memory structure for the LTL-Scheduler. + * @param + * @param + * @param the scheduler enuring to reach some acceptingState, defined on the model-DA product + * @param */ - void createMemoryStructure(uint_fast64_t numDaStates, transformer::DAProductBuilder const& productBuilder, typename transformer::DAProduct<productModelType>::ptr product, storm::storage::BitVector const& acceptingProductStates, storm::storage::BitVector const& modelStatesOfInterest); + 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; diff --git a/src/storm/transformer/DAProductBuilder.h b/src/storm/transformer/DAProductBuilder.h index a6a53f9bd..c9e72331a 100644 --- a/src/storm/transformer/DAProductBuilder.h +++ b/src/storm/transformer/DAProductBuilder.h @@ -35,8 +35,7 @@ namespace storm { return da.getSuccessor(da.getInitialState(), getLabelForState(modelState)); } - storm::storage::sparse::state_type getSuccessor(storm::storage::sparse::state_type modelFrom, - storm::storage::sparse::state_type automatonFrom, + 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)); } diff --git a/src/storm/transformer/ProductBuilder.h b/src/storm/transformer/ProductBuilder.h index a398a1811..4be4bf045 100644 --- a/src/storm/transformer/ProductBuilder.h +++ b/src/storm/transformer/ProductBuilder.h @@ -58,7 +58,7 @@ namespace storm { 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.first, from.second, t); + state_type p = prodOp.getSuccessor(from.second, t); // std::cout << " p = " << p << "\n"; product_state_type t_p(t, p); state_type prodIndexTo; @@ -84,7 +84,7 @@ namespace storm { auto const& row = originalMatrix.getRow(from.first, i); for (auto const& entry : row) { state_type t = entry.getColumn(); - state_type p = prodOp.getSuccessor(from.first, from.second, t); + state_type p = prodOp.getSuccessor(from.second, t); // std::cout << " p = " << p << "\n"; product_state_type t_p(t, p); state_type prodIndexTo; diff --git a/src/test/storm/modelchecker/prctl/mdp/SchedulerGenerationMdpPrctlModelCheckerTest.cpp b/src/test/storm/modelchecker/prctl/mdp/SchedulerGenerationMdpPrctlModelCheckerTest.cpp index 0ad528920..33f97bed2 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" @@ -207,7 +208,7 @@ namespace { TYPED_TEST(SchedulerGenerationMdpPrctlModelCheckerTest, ltl) { typedef typename TestFixture::ValueType ValueType; - // TODO skip without LTL support +#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); @@ -231,17 +232,17 @@ namespace { EXPECT_TRUE(scheduler.isDeterministicScheduler()); EXPECT_TRUE(!scheduler.isMemorylessScheduler()); - EXPECT_TRUE(scheduler.isPartialScheduler()); + 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()); + ASSERT_EQ(inducedModel->getType(), storm::models::ModelType::Dtmc); + auto const &inducedDtmc = inducedModel->template as<storm::models::sparse::Dtmc<ValueType>>(); + EXPECT_EQ(inducedDtmc->getNumberOfChoices(), inducedDtmc->getNumberOfStates()); - storm::modelchecker::SparseMdpPrctlModelChecker<storm::models::sparse::Mdp<ValueType>> inducedChecker(*inducedMdp); + storm::modelchecker::SparseDtmcPrctlModelChecker<storm::models::sparse::Dtmc<ValueType>> inducedChecker(*inducedDtmc); 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::settings::getModule<storm::settings::modules::GeneralSettings>().getPrecision()); + EXPECT_NEAR(this->parseNumber("81/100"), inducedResult->template asExplicitQuantitativeCheckResult<ValueType>()[*inducedDtmc->getInitialStates().begin()],storm::settings::getModule<storm::settings::modules::GeneralSettings>().getPrecision()); } { tasks[1].setOnlyInitialStatesRelevant(false); @@ -253,15 +254,18 @@ namespace { EXPECT_TRUE(scheduler.isDeterministicScheduler()); EXPECT_TRUE(!scheduler.isMemorylessScheduler()); - EXPECT_TRUE(scheduler.isPartialScheduler()); + 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); + + ASSERT_EQ(inducedModel->getType(), storm::models::ModelType::Dtmc); + auto const &inducedDtmc = inducedModel->template as<storm::models::sparse::Dtmc<ValueType>>(); + EXPECT_EQ(inducedDtmc->getNumberOfChoices(), inducedDtmc->getNumberOfStates()); + + storm::modelchecker::SparseDtmcPrctlModelChecker<storm::models::sparse::Dtmc<ValueType>> inducedChecker(*inducedDtmc); 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::settings::getModule<storm::settings::modules::GeneralSettings>().getPrecision()); + EXPECT_NEAR(this->parseNumber("1/2"),inducedResult->template asExplicitQuantitativeCheckResult<ValueType>()[*inducedDtmc->getInitialStates().begin()],storm::settings::getModule<storm::settings::modules::GeneralSettings>().getPrecision()); + // TODO EXPECT_NEAR(this->parseNumber("1/2"),inducedResult->template asExplicitQuantitativeCheckResult<ValueType>()[*std::next(inducedDtmc->getInitialStates().begin())],storm::settings::getModule<storm::settings::modules::GeneralSettings>().getPrecision()); } { tasks[2].setOnlyInitialStatesRelevant(true); @@ -275,24 +279,27 @@ namespace { EXPECT_TRUE(scheduler.isDeterministicScheduler()); EXPECT_TRUE(!scheduler.isMemorylessScheduler()); - EXPECT_TRUE(scheduler.isPartialScheduler()); + 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); + ASSERT_EQ(inducedModel->getType(), storm::models::ModelType::Dtmc); + auto const &inducedDtmc = inducedModel->template as<storm::models::sparse::Dtmc<ValueType>>(); + EXPECT_EQ(inducedDtmc->getNumberOfChoices(), inducedDtmc->getNumberOfStates()); + + storm::modelchecker::SparseDtmcPrctlModelChecker<storm::models::sparse::Dtmc<ValueType>> inducedChecker(*inducedDtmc); auto inducedResult = inducedChecker.check(this->env(), tasks[2]); ASSERT_TRUE(inducedResult->isExplicitQuantitativeCheckResult()); EXPECT_NEAR(this->parseNumber("1/2"), - inducedResult->template asExplicitQuantitativeCheckResult<ValueType>()[*inducedMdp->getInitialStates().begin()], + inducedResult->template asExplicitQuantitativeCheckResult<ValueType>()[*inducedDtmc->getInitialStates().begin()], storm::settings::getModule<storm::settings::modules::GeneralSettings>().getPrecision()); } +#else + GTEST_SKIP(); +#endif } TYPED_TEST(SchedulerGenerationMdpPrctlModelCheckerTest, ltlNondetChoice) { typedef typename TestFixture::ValueType ValueType; - // TODO skip without LTL support +#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); @@ -317,26 +324,28 @@ namespace { EXPECT_TRUE(scheduler.isDeterministicScheduler()); EXPECT_TRUE(!scheduler.isMemorylessScheduler()); - EXPECT_TRUE(scheduler.isPartialScheduler()); + EXPECT_TRUE(!scheduler.isPartialScheduler()); auto inducedModel = mdp->applyScheduler(scheduler, true); + ASSERT_EQ(inducedModel->getType(), storm::models::ModelType::Dtmc); + auto const &inducedDtmc = inducedModel->template as<storm::models::sparse::Dtmc<ValueType>>(); + EXPECT_EQ(inducedDtmc->getNumberOfChoices(), inducedDtmc->getNumberOfStates()); - 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); + storm::modelchecker::SparseDtmcPrctlModelChecker<storm::models::sparse::Dtmc<ValueType>> inducedChecker(*inducedDtmc); 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::settings::getModule<storm::settings::modules::GeneralSettings>().getPrecision()); + EXPECT_NEAR(this->parseNumber("1"), inducedResult->template asExplicitQuantitativeCheckResult<ValueType>()[*inducedDtmc->getInitialStates().begin()], storm::settings::getModule<storm::settings::modules::GeneralSettings>().getPrecision()); } +#else + GTEST_SKIP(); +#endif } TYPED_TEST(SchedulerGenerationMdpPrctlModelCheckerTest, ltlUnsat) { typedef typename TestFixture::ValueType ValueType; - // TODO skip without LTL support +#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); @@ -364,6 +373,7 @@ namespace { EXPECT_TRUE(!scheduler.isPartialScheduler()); auto inducedModel = mdp->applyScheduler(scheduler, true); + // TODO not DTMC? 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()); @@ -398,6 +408,9 @@ namespace { ASSERT_TRUE(inducedResult->isExplicitQuantitativeCheckResult()); EXPECT_NEAR(this->parseNumber("1"), inducedResult->template asExplicitQuantitativeCheckResult<ValueType>()[*inducedMdp->getInitialStates().begin()], storm::settings::getModule<storm::settings::modules::GeneralSettings>().getPrecision()); } +#else + GTEST_SKIP(); +#endif } From 71100e9d653c24bbb419f21e4eebb22990b7ccd6 Mon Sep 17 00:00:00 2001 From: hannah <hannah.mertens@rwth-aachen.de> Date: Tue, 27 Jul 2021 20:42:38 +0200 Subject: [PATCH 115/172] scheduler json export Conflicts: src/storm/storage/Scheduler.cpp --- .../helper/ltl/SparseLTLHelper.cpp | 7 +- .../modelchecker/helper/ltl/SparseLTLHelper.h | 4 +- src/storm/storage/Scheduler.cpp | 102 +++++++++++------- 3 files changed, 70 insertions(+), 43 deletions(-) diff --git a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp index b315aa2c0..527cb3868 100644 --- a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp +++ b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp @@ -45,7 +45,7 @@ namespace storm { STORM_LOG_ASSERT(this->_producedChoices.is_initialized(), "Trying to extract the produced scheduler but none is available. Was there a computation call before?"); STORM_LOG_ASSERT(this->_memoryTransitions.is_initialized(), "Trying to extract the DA transition structure but none is available. Was there a computation call before?"); STORM_LOG_ASSERT(this->_memoryInitialStates.is_initialized(), "Trying to extract the initial states of the DA but there are none available. Was there a computation call before?"); - STORM_LOG_ASSERT(this->_dontCareStates.is_initialized(), "Trying to extract the dontCare states of the Scheduler but there are none available. Was there a computation call before?"); + STORM_LOG_ASSERT(this->_dontCareStates.is_initialized(), "Trying to extract the Scheduler-dontCare states but there are none available. Was there a computation call before?"); // Create a memory structure for the MDP scheduler with memory. If hasRelevantStates is set, we only consider initial model states relevant. @@ -147,7 +147,7 @@ namespace storm { } 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 + // 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); STORM_LOG_INFO("Handle conjunction " << i); @@ -182,7 +182,7 @@ namespace storm { STORM_LOG_DEBUG(" Allowed states: " << allowed); - // compute MECs in the allowed fragment + // Compute MECs in the allowed fragment storm::storage::MaximalEndComponentDecomposition<ValueType> mecs(transitionMatrix, backwardTransitions, allowed); allMECs += mecs.size(); for (const auto& mec : mecs) { @@ -387,7 +387,6 @@ namespace storm { } } - } } } diff --git a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h index 8b85a07de..3d7c21abe 100644 --- a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h +++ b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h @@ -25,8 +25,8 @@ namespace storm { public: /*! - * The type of the product automaton (DTMC or MDP) that is used during the computation. - */ + * The type of the product automaton (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; /*! diff --git a/src/storm/storage/Scheduler.cpp b/src/storm/storage/Scheduler.cpp index 51a3f40e8..268fb3b0b 100644 --- a/src/storm/storage/Scheduler.cpp +++ b/src/storm/storage/Scheduler.cpp @@ -248,7 +248,7 @@ namespace storm { // Print memory updates if(!isMemorylessScheduler()) { - out << std::setw(8); + out << std::setw(widthOfStates) << ""; for (auto const& choiceProbPair : choice.getChoiceAsDistribution()) { uint64_t row = model->getTransitionMatrix().getRowGroupIndices()[state] + choiceProbPair.first; bool firstUpdate = true; @@ -258,10 +258,9 @@ namespace storm { } else { stateString << ", "; } - stateString << "model state' = " << entryIt->getColumn() << ": (transition = " << entryIt - model->getTransitionMatrix().begin() << ") -> " << "(m' = "<<this->memoryStructure->getSuccessorMemoryState(memoryState, entryIt - model->getTransitionMatrix().begin()) <<")"; - //out << ", model state' = " << entryIt->getColumn() << ": (transition = " << entryIt - model->getTransitionMatrix().begin() << ") -> " << "(m' = ?) "; - } - } + 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()) <<")"; + } stateString << std::endl; } @@ -275,11 +274,6 @@ namespace storm { } out << "___________________________________________________________________" << std::endl; - // TODO only for tests: - if(!isMemorylessScheduler()) { - out << memoryStructure->toString(); - out << std::endl; - } } template <> @@ -289,44 +283,78 @@ namespace storm { template <typename ValueType> void Scheduler<ValueType>::printJsonToStream(std::ostream& out, std::shared_ptr<storm::models::sparse::Model<ValueType>> model, bool skipUniqueChoices) const { - //TODO not defined for memory and unreachable states are not considered 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 ((!isMemorylessScheduler()) && 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); } From c80a62ce0694710bbbbbe2bddc59b0b5d0715c85 Mon Sep 17 00:00:00 2001 From: hannah <hannah.mertens@rwth-aachen.de> Date: Tue, 27 Jul 2021 21:35:48 +0200 Subject: [PATCH 116/172] added function for computation of memory states --- .../helper/ltl/SparseLTLHelper.cpp | 39 ++++++++++--------- .../modelchecker/helper/ltl/SparseLTLHelper.h | 17 ++++++-- 2 files changed, 34 insertions(+), 22 deletions(-) diff --git a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp index 527cb3868..7bf56ce4c 100644 --- a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp +++ b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp @@ -27,6 +27,10 @@ namespace storm { // Intentionally left empty. } + template <typename ValueType, bool Nondeterministic> + uint_fast64_t SparseLTLHelper<ValueType, Nondeterministic>::SparseLTLHelper::getMemoryState(uint_fast64_t daState, uint_fast64_t infSet) { + return (daState * (_infSets.get().size()+1))+ infSet; + } template <typename ValueType, bool Nondeterministic> storm::storage::Scheduler<ValueType> SparseLTLHelper<ValueType, Nondeterministic>::SparseLTLHelper::extractScheduler(storm::models::sparse::Model<ValueType> const& model) { @@ -51,7 +55,7 @@ namespace storm { // 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.get().size(), model, this->hasRelevantStates()); - // Build the transitions between the memory states: startState--- modelStates (transitionVector) --->goalState + // Build the transitions between the memory states: startState to goalState using modelStates (transitionVector). for (storm::storage::sparse::state_type startState = 0; startState < this->_memoryTransitions.get().size(); ++startState) { for (storm::storage::sparse::state_type goalState = 0; goalState < this->_memoryTransitions.get().size(); ++goalState) { // Bitvector that represents modelStates the model states that trigger this transition. @@ -59,7 +63,7 @@ namespace storm { } } - // initialMemoryStates: Assign an initial memory state model states + // InitialMemoryStates: Assign an initial memory state model states if (this->hasRelevantStates()) { // Only consider initial model states for (uint_fast64_t modelState : model.getInitialStates()) { @@ -82,13 +86,13 @@ namespace storm { for (const auto &choice : this->_producedChoices.get()) { // <s, q, InfSet> -> choice storm::storage::sparse::state_type modelState = std::get<0>(choice.first); - storm::storage::sparse::state_type automatonState = std::get<1>(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.get()[(automatonState*(_infSets.get().size()+1))+ infSet].get(modelState), "Tried to set choice for dontCare state."); - scheduler.setChoice(choice.second, modelState, (automatonState*(_infSets.get().size()+1))+ infSet); + STORM_LOG_ASSERT(!this->_dontCareStates.get()[getMemoryState(daState, infSet)].get(modelState), "Tried to set choice for dontCare state."); + scheduler.setChoice(choice.second, modelState, getMemoryState(daState, infSet)); } - // Set "don't care" states + // Set "dontCare" states for (uint_fast64_t memoryState = 0; memoryState < this->_dontCareStates.get().size(); ++memoryState) { for (auto state : this->_dontCareStates.get()[memoryState]) { scheduler.setDontCare(state, memoryState); @@ -219,7 +223,7 @@ namespace storm { } } else if (atom.getType() == cpphoafparser::AtomAcceptance::TEMPORAL_FIN) { - // do only sanity checks here + // 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"); } } @@ -241,7 +245,7 @@ namespace storm { mecStates.set(stateChoicePair.first); } - // We know the MEC satisfied the conjunction: Save InfSets + // We know the MEC satisfied the conjunction: Save InfSets. std::set<uint_fast64_t> infSetIds; for (auto const& literal : conjunction) { storm::storage::BitVector infSet; @@ -359,7 +363,7 @@ namespace storm { 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.get().size()+1; ++infSet) { - _dontCareStates.get()[automatonState * (_infSets.get().size() + 1) + infSet].set(modelState, true); + _dontCareStates.get()[getMemoryState(automatonState, infSet)].set(modelState, true); } } else { auto pState = product->getProductStateIndex(modelState, automatonState); @@ -367,7 +371,7 @@ namespace storm { // For states in accepting ECs set the missing MEC-scheduler combinations are "dontCare", they are not reachable using the scheduler choices. //TODO is this correct? for (uint_fast64_t infSet = 0; infSet < _infSets.get().size()+1; ++infSet) { if (_producedChoices.get().find(std::make_tuple(product->getModelState(pState), product->getAutomatonState(pState), infSet)) == _producedChoices.get().end() ) { - _dontCareStates.get()[(product->getAutomatonState(pState)) * (_infSets.get().size()+1) + infSet].set(product->getModelState(pState), true); + _dontCareStates.get()[getMemoryState(product->getAutomatonState(pState), infSet)].set(product->getModelState(pState), true); } } @@ -376,14 +380,14 @@ namespace storm { this->_accInfSets.get()[pState] = {_infSets.get().size()}; if (reachScheduler->isDontCare(pState)) { // Mark the maybe States of the untilProbability scheduler as "dontCare" - _dontCareStates.get()[(product->getAutomatonState(pState)) * (_infSets.get().size()+1) + _infSets.get().size()].set(product->getModelState(pState), true); + _dontCareStates.get()[getMemoryState(product->getAutomatonState(pState), _infSets.get().size())].set(product->getModelState(pState), true); } else { // Set choice For non-accepting states that are not in any accepting EC this->_producedChoices.get().insert({std::make_tuple(product->getModelState(pState),product->getAutomatonState(pState),_infSets.get().size()),reachScheduler->getChoice(pState)}); }; // All other InfSet combinations are unreachable (dontCare) for (uint_fast64_t infSet = 0; infSet < _infSets.get().size(); ++infSet) { - _dontCareStates.get()[(product->getAutomatonState(pState)) * (_infSets.get().size()+1) + infSet].set(product->getModelState(pState), true); + _dontCareStates.get()[getMemoryState(product->getAutomatonState(pState), infSet)].set(product->getModelState(pState), true); } } @@ -411,14 +415,14 @@ namespace storm { if (_accInfSets.get()[product->getProductStateIndex(modelState, automatonTo)].get().count(infSet) == 0) { // the state is is in a different accepting MEC with a different accepting conjunction of InfSets. auto newInfSet = _accInfSets.get()[product->getProductStateIndex(modelState, automatonTo)].get().begin(); - _memoryTransitions.get()[(automatonFrom * (_infSets.get().size()+1)) + infSet][(automatonTo * (_infSets.get().size()+1)) + *newInfSet].set(modelState); + _memoryTransitions.get()[getMemoryState(automatonFrom, infSet)][getMemoryState(automatonTo, *newInfSet)].set(modelState); } else { // Continue looking for any accepting EC (if we haven't reached one yet) or stay in the corresponding accepting EC, test whether we have reached the next infSet. if (infSet == _infSets.get().size() || !(_infSets.get()[infSet].get(product->getProductStateIndex(modelState, automatonTo)))) { // <modelState, automatonTo> is not in any accepting EC or does not satisfy the InfSet, we stay there. // Add modelState to the transition from <automatonFrom, InfSet> to <automatonTo, InfSet> - _memoryTransitions.get()[(automatonFrom * (_infSets.get().size()+1)) + infSet][(automatonTo * (_infSets.get().size()+1)) + infSet].set(modelState); + _memoryTransitions.get()[getMemoryState(automatonFrom, infSet)][getMemoryState(automatonTo, infSet)].set(modelState); } else { STORM_LOG_ASSERT(_accInfSets.get()[product->getProductStateIndex(modelState, automatonTo)] != boost::none, "The list of InfSets for the product state <" <<modelState<< ", " << automatonTo<<"> is undefined."); @@ -431,7 +435,7 @@ namespace storm { nextInfSet = _accInfSets.get()[product->getProductStateIndex(modelState, automatonTo)].get().begin(); } // Add modelState to the transition from <automatonFrom <mec, InfSet>> to <automatonTo, <mec, NextInfSet>>. - _memoryTransitions.get()[(automatonFrom * (_infSets.get().size()+1)) + infSet][(automatonTo * (_infSets.get().size()+1)) + *nextInfSet].set(modelState); + _memoryTransitions.get()[getMemoryState(automatonFrom, infSet)][getMemoryState(automatonTo, *nextInfSet)].set(modelState); } } } @@ -452,14 +456,13 @@ namespace storm { STORM_LOG_ASSERT(_accInfSets.get()[product->getProductStateIndex(modelState, automatonState)] != boost::none, "The list of InfSets for the product state <" <<modelState<< ", " << automatonState<<"> is undefined."); // If <s, q> is an accepting state start in the first InfSet of <s, q>. auto infSet = _accInfSets.get()[product->getProductStateIndex(modelState, automatonState)].get().begin(); - _memoryInitialStates.get()[modelState] = (automatonState * (_infSets.get().size()+1)) + *infSet; + _memoryInitialStates.get()[modelState] = getMemoryState(automatonState, *infSet); } else { - _memoryInitialStates.get()[modelState] = (automatonState * (_infSets.get().size()+1)) + _infSets.get().size(); + _memoryInitialStates.get()[modelState] = getMemoryState(automatonState, _infSets.get().size()); } } - // Finished creation of initial states. } diff --git a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h index 3d7c21abe..82d81c598 100644 --- a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h +++ b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h @@ -93,13 +93,22 @@ namespace storm { /** * Helper function, extracts scheduler choices and creates the memory structure for the LTL-Scheduler. - * @param - * @param - * @param the scheduler enuring to reach some acceptingState, defined on the model-DA product - * @param + * @param number of DA-states + * @param states in accepting end components of the model-DA product + * @param the scheduler ensuring to reach some acceptingState, defined on the model-DA product + * @param the product builder + * @param the model-DA product + * @param relevant states 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); + /** + * Helper function, 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 DA-state + * @param infSet ID + */ + uint_fast64_t getMemoryState(uint_fast64_t daState, uint_fast64_t infSet); storm::storage::SparseMatrix<ValueType> const& _transitionMatrix; From ebdfb2def84f6f3585dab4d9325de781af804a46 Mon Sep 17 00:00:00 2001 From: hannah <hannah.mertens@rwth-aachen.de> Date: Thu, 29 Jul 2021 23:36:10 +0200 Subject: [PATCH 117/172] keep the original modeltype during product construction --- src/storm/storage/Scheduler.cpp | 2 +- .../SparseModelMemoryProduct.cpp | 10 +-- ...ulerGenerationMdpPrctlModelCheckerTest.cpp | 64 +++++++++---------- 3 files changed, 34 insertions(+), 42 deletions(-) diff --git a/src/storm/storage/Scheduler.cpp b/src/storm/storage/Scheduler.cpp index 268fb3b0b..ff745ed09 100644 --- a/src/storm/storage/Scheduler.cpp +++ b/src/storm/storage/Scheduler.cpp @@ -95,7 +95,7 @@ namespace storm { dontCareStates[memoryState].set(modelState, true); ++numOfDontCareStates; - // Choices for unreachable states are not considered undefined or deterministic + // Choices for dontCare states are not considered undefined or deterministic if (!schedulerChoice.isDefined()) { --numOfUndefinedChoices; } else if (schedulerChoice.isDeterministic()) { diff --git a/src/storm/storage/memorystructure/SparseModelMemoryProduct.cpp b/src/storm/storage/memorystructure/SparseModelMemoryProduct.cpp index fd9163fa5..b80910704 100644 --- a/src/storm/storage/memorystructure/SparseModelMemoryProduct.cpp +++ b/src/storm/storage/memorystructure/SparseModelMemoryProduct.cpp @@ -516,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/test/storm/modelchecker/prctl/mdp/SchedulerGenerationMdpPrctlModelCheckerTest.cpp b/src/test/storm/modelchecker/prctl/mdp/SchedulerGenerationMdpPrctlModelCheckerTest.cpp index 33f97bed2..63f4fd2d5 100755 --- a/src/test/storm/modelchecker/prctl/mdp/SchedulerGenerationMdpPrctlModelCheckerTest.cpp +++ b/src/test/storm/modelchecker/prctl/mdp/SchedulerGenerationMdpPrctlModelCheckerTest.cpp @@ -235,17 +235,17 @@ namespace { EXPECT_TRUE(!scheduler.isPartialScheduler()); auto inducedModel = mdp->applyScheduler(scheduler); - ASSERT_EQ(inducedModel->getType(), storm::models::ModelType::Dtmc); - auto const &inducedDtmc = inducedModel->template as<storm::models::sparse::Dtmc<ValueType>>(); - EXPECT_EQ(inducedDtmc->getNumberOfChoices(), inducedDtmc->getNumberOfStates()); + 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::SparseDtmcPrctlModelChecker<storm::models::sparse::Dtmc<ValueType>> inducedChecker(*inducedDtmc); + 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>()[*inducedDtmc->getInitialStates().begin()],storm::settings::getModule<storm::settings::modules::GeneralSettings>().getPrecision()); + EXPECT_NEAR(this->parseNumber("81/100"), inducedResult->template asExplicitQuantitativeCheckResult<ValueType>()[*inducedMdp->getInitialStates().begin()],storm::settings::getModule<storm::settings::modules::GeneralSettings>().getPrecision()); } { - tasks[1].setOnlyInitialStatesRelevant(false); + 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::settings::getModule<storm::settings::modules::GeneralSettings>().getPrecision()); @@ -257,23 +257,21 @@ namespace { EXPECT_TRUE(!scheduler.isPartialScheduler()); auto inducedModel = mdp->applyScheduler(scheduler); - ASSERT_EQ(inducedModel->getType(), storm::models::ModelType::Dtmc); - auto const &inducedDtmc = inducedModel->template as<storm::models::sparse::Dtmc<ValueType>>(); - EXPECT_EQ(inducedDtmc->getNumberOfChoices(), inducedDtmc->getNumberOfStates()); + 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::SparseDtmcPrctlModelChecker<storm::models::sparse::Dtmc<ValueType>> inducedChecker(*inducedDtmc); + 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>()[*inducedDtmc->getInitialStates().begin()],storm::settings::getModule<storm::settings::modules::GeneralSettings>().getPrecision()); - // TODO EXPECT_NEAR(this->parseNumber("1/2"),inducedResult->template asExplicitQuantitativeCheckResult<ValueType>()[*std::next(inducedDtmc->getInitialStates().begin())],storm::settings::getModule<storm::settings::modules::GeneralSettings>().getPrecision()); + + EXPECT_NEAR(this->parseNumber("1/2"),inducedResult->template asExplicitQuantitativeCheckResult<ValueType>()[*inducedMdp->getInitialStates().begin()],storm::settings::getModule<storm::settings::modules::GeneralSettings>().getPrecision()); } { - tasks[2].setOnlyInitialStatesRelevant(true); + 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::settings::getModule<storm::settings::modules::GeneralSettings>().getPrecision()); + EXPECT_NEAR(this->parseNumber("1/2"), result->template asExplicitQuantitativeCheckResult<ValueType>()[*mdp->getInitialStates().begin()], storm::settings::getModule<storm::settings::modules::GeneralSettings>().getPrecision()); ASSERT_TRUE(result->template asExplicitQuantitativeCheckResult<ValueType>().hasScheduler()); storm::storage::Scheduler<ValueType> const &scheduler = result->template asExplicitQuantitativeCheckResult<ValueType>().getScheduler(); @@ -281,16 +279,19 @@ namespace { EXPECT_TRUE(!scheduler.isMemorylessScheduler()); EXPECT_TRUE(!scheduler.isPartialScheduler()); auto inducedModel = mdp->applyScheduler(scheduler); - ASSERT_EQ(inducedModel->getType(), storm::models::ModelType::Dtmc); - auto const &inducedDtmc = inducedModel->template as<storm::models::sparse::Dtmc<ValueType>>(); - EXPECT_EQ(inducedDtmc->getNumberOfChoices(), inducedDtmc->getNumberOfStates()); - storm::modelchecker::SparseDtmcPrctlModelChecker<storm::models::sparse::Dtmc<ValueType>> inducedChecker(*inducedDtmc); + 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()); - EXPECT_NEAR(this->parseNumber("1/2"), - inducedResult->template asExplicitQuantitativeCheckResult<ValueType>()[*inducedDtmc->getInitialStates().begin()], - storm::settings::getModule<storm::settings::modules::GeneralSettings>().getPrecision()); + + auto test = inducedResult->template asExplicitQuantitativeCheckResult<ValueType>().getValueVector(); + EXPECT_NEAR(this->parseNumber("1/2"), inducedResult->template asExplicitQuantitativeCheckResult<ValueType>()[0], storm::settings::getModule<storm::settings::modules::GeneralSettings>().getPrecision()); + EXPECT_NEAR(this->parseNumber("1"), inducedResult->template asExplicitQuantitativeCheckResult<ValueType>()[1], storm::settings::getModule<storm::settings::modules::GeneralSettings>().getPrecision()); + EXPECT_NEAR(this->parseNumber("0"), inducedResult->template asExplicitQuantitativeCheckResult<ValueType>()[2], storm::settings::getModule<storm::settings::modules::GeneralSettings>().getPrecision()); } #else GTEST_SKIP(); @@ -325,16 +326,16 @@ namespace { EXPECT_TRUE(scheduler.isDeterministicScheduler()); EXPECT_TRUE(!scheduler.isMemorylessScheduler()); EXPECT_TRUE(!scheduler.isPartialScheduler()); - auto inducedModel = mdp->applyScheduler(scheduler, true); + auto inducedModel = mdp->applyScheduler(scheduler); - ASSERT_EQ(inducedModel->getType(), storm::models::ModelType::Dtmc); - auto const &inducedDtmc = inducedModel->template as<storm::models::sparse::Dtmc<ValueType>>(); - EXPECT_EQ(inducedDtmc->getNumberOfChoices(), inducedDtmc->getNumberOfStates()); + 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::SparseDtmcPrctlModelChecker<storm::models::sparse::Dtmc<ValueType>> inducedChecker(*inducedDtmc); + 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>()[*inducedDtmc->getInitialStates().begin()], storm::settings::getModule<storm::settings::modules::GeneralSettings>().getPrecision()); + EXPECT_NEAR(this->parseNumber("1"), inducedResult->template asExplicitQuantitativeCheckResult<ValueType>()[*inducedMdp->getInitialStates().begin()], storm::settings::getModule<storm::settings::modules::GeneralSettings>().getPrecision()); } #else GTEST_SKIP(); @@ -371,9 +372,8 @@ namespace { EXPECT_TRUE(scheduler.isDeterministicScheduler()); EXPECT_TRUE(scheduler.isMemorylessScheduler()); EXPECT_TRUE(!scheduler.isPartialScheduler()); - auto inducedModel = mdp->applyScheduler(scheduler, true); + auto inducedModel = mdp->applyScheduler(scheduler); - // TODO not DTMC? 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()); @@ -396,7 +396,7 @@ namespace { EXPECT_TRUE(scheduler.isDeterministicScheduler()); EXPECT_TRUE(scheduler.isMemorylessScheduler()); EXPECT_TRUE(!scheduler.isPartialScheduler()); - auto inducedModel = mdp->applyScheduler(scheduler, true); + auto inducedModel = mdp->applyScheduler(scheduler); ASSERT_EQ(inducedModel->getType(), storm::models::ModelType::Mdp); From 1f17b31bbe9a9e5eb5d5ca564f496ee30a4ac510 Mon Sep 17 00:00:00 2001 From: hannah <hannah.mertens@rwth-aachen.de> Date: Fri, 30 Jul 2021 01:02:44 +0200 Subject: [PATCH 118/172] arbitrary choice for dontCareStates --- src/storm/storage/Scheduler.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/storm/storage/Scheduler.cpp b/src/storm/storage/Scheduler.cpp index ff745ed09..0c087b269 100644 --- a/src/storm/storage/Scheduler.cpp +++ b/src/storm/storage/Scheduler.cpp @@ -102,6 +102,8 @@ namespace storm { --numOfDeterministicChoices; } + // Set an arbitrary choice + schedulerChoices[memoryState][modelState] = SchedulerChoice<ValueType>(0); } } From adc5d9ae686136fbc3beb35a1f44e5967a62a03d Mon Sep 17 00:00:00 2001 From: hannah <hannah.mertens@rwth-aachen.de> Date: Fri, 30 Jul 2021 01:03:10 +0200 Subject: [PATCH 119/172] MA scheduler export --- .../csl/SparseMarkovAutomatonCslModelChecker.cpp | 8 ++++++-- .../modelchecker/prctl/SparseMdpPrctlModelChecker.cpp | 2 -- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/src/storm/modelchecker/csl/SparseMarkovAutomatonCslModelChecker.cpp b/src/storm/modelchecker/csl/SparseMarkovAutomatonCslModelChecker.cpp index 9ef8c5f1f..5ebc3f8de 100644 --- a/src/storm/modelchecker/csl/SparseMarkovAutomatonCslModelChecker.cpp +++ b/src/storm/modelchecker/csl/SparseMarkovAutomatonCslModelChecker.cpp @@ -136,7 +136,6 @@ namespace storm { STORM_LOG_INFO("Performing ltl probability computations in embedded MDP..."); - // TODO ? if (storm::settings::getModule<storm::settings::modules::DebugSettings>().isTraceSet()) { STORM_LOG_TRACE("Writing model to model.dot"); std::ofstream modelDot("model.dot"); @@ -153,8 +152,13 @@ namespace storm { std::vector<ValueType> numericResult = helper.computeLTLProbabilities(env, *ltlFormula, 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(embeddedMdp))); + } + // We can directly return the numericResult vector as the state space of the CTMC and the embedded MDP are exactly the same - return std::unique_ptr<CheckResult>(new ExplicitQuantitativeCheckResult<ValueType>(std::move(numericResult))); + return result; } diff --git a/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.cpp b/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.cpp index cba1864d2..f386d416c 100644 --- a/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.cpp +++ b/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.cpp @@ -189,7 +189,6 @@ namespace storm { std::shared_ptr<storm::logic::Formula> ltlFormula = storm::logic::ExtractMaximalStateFormulasVisitor::extract(pathFormula, extracted, cached); const SparseMdpModelType& mdp = this->getModel(); - // TODO ? if (storm::settings::getModule<storm::settings::modules::DebugSettings>().isTraceSet()) { STORM_LOG_TRACE("Writing model to model.dot"); std::ofstream modelDot("model.dot"); @@ -207,7 +206,6 @@ namespace storm { std::vector<ValueType> numericResult = helper.computeLTLProbabilities(env, *ltlFormula, apSets); - //TODO for MA too 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(mdp))); From 093b01f0c50b470dee2820b5e70cf2388ba5dc3e Mon Sep 17 00:00:00 2001 From: hannah <hannah.mertens@rwth-aachen.de> Date: Tue, 3 Aug 2021 13:51:41 +0200 Subject: [PATCH 120/172] adjusted scheduler dontCare --- src/storm/storage/Scheduler.cpp | 28 ++++++++++++++++++++-------- src/storm/storage/Scheduler.h | 10 +++++++++- 2 files changed, 29 insertions(+), 9 deletions(-) diff --git a/src/storm/storage/Scheduler.cpp b/src/storm/storage/Scheduler.cpp index 0c087b269..55b842d37 100644 --- a/src/storm/storage/Scheduler.cpp +++ b/src/storm/storage/Scheduler.cpp @@ -90,23 +90,35 @@ namespace storm { void Scheduler<ValueType>::setDontCare(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 (!dontCareStates[memoryState].get(modelState)) { + auto& schedulerChoice = schedulerChoices[memoryState][modelState]; + if (!schedulerChoice.isDefined()) { + // Set an arbitrary choice + this->setChoice(0, modelState, memoryState); + } dontCareStates[memoryState].set(modelState, true); ++numOfDontCareStates; + } + } - // Choices for dontCare states are not considered undefined or deterministic + 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)) { + auto& schedulerChoice = schedulerChoices[memoryState][modelState]; if (!schedulerChoice.isDefined()) { - --numOfUndefinedChoices; - } else if (schedulerChoice.isDeterministic()) { - --numOfDeterministicChoices; + ++numOfUndefinedChoices; } + dontCareStates[memoryState].set(modelState, false); + --numOfDontCareStates; - // Set an arbitrary choice - schedulerChoices[memoryState][modelState] = SchedulerChoice<ValueType>(0); } } + template <typename ValueType> bool Scheduler<ValueType>::isDontCare(uint_fast64_t modelState, uint64_t memoryState) const { return dontCareStates[memoryState].get(modelState); @@ -137,7 +149,7 @@ namespace storm { template <typename ValueType> bool Scheduler<ValueType>::isDeterministicScheduler() const { - return numOfDeterministicChoices == (schedulerChoices.size() * schedulerChoices.begin()->size()) - numOfUndefinedChoices - numOfDontCareStates; + return numOfDeterministicChoices == (schedulerChoices.size() * schedulerChoices.begin()->size()) - numOfUndefinedChoices; } template <typename ValueType> diff --git a/src/storm/storage/Scheduler.h b/src/storm/storage/Scheduler.h index aeff2f225..cacd5b00b 100644 --- a/src/storm/storage/Scheduler.h +++ b/src/storm/storage/Scheduler.h @@ -62,13 +62,21 @@ namespace storm { /*! * Set the combination of model state and memoryStructure state to dontCare. - * This means the corresponding choices are neither considered undefined nor deterministic. + * Set an arbitrary choice an arbitrary choice if no choice exists. * * @param modelState The state of the model. * @param memoryState The state of the memoryStructure. */ void setDontCare(uint_fast64_t modelState, uint_fast64_t memoryState = 0); + /*! + * 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? */ From ba1d0d052da6ba164b328769f63ec3f6f36b20f6 Mon Sep 17 00:00:00 2001 From: Stefan Pranger <stefan.pranger@student.tugraz.at> Date: Sun, 8 Aug 2021 12:15:06 +0200 Subject: [PATCH 121/172] added simulator to tests ebc18bc6f2391ccd44d1c5ece951b8a328d89a79 --- src/test/storm/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/storm/CMakeLists.txt b/src/test/storm/CMakeLists.txt index ccf090674..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 automata builder logic model parser permissiveschedulers 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) From 4e6d334f9b70a9864be0340c6567315f9933bcbb Mon Sep 17 00:00:00 2001 From: Tim Quatmann <tim.quatmann@cs.rwth-aachen.de> Date: Tue, 3 Aug 2021 15:16:10 +0200 Subject: [PATCH 122/172] Updated Changelog --- CHANGELOG.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 955a43520..d0c6f96ff 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. +- Added cmake options `STORM_USE_SPOT` and `STORM_FORCE_SHIPPED_SPOT` 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 From 5a2e4894039ea484f29c46f8aaa3203e008ec88c Mon Sep 17 00:00:00 2001 From: Tim Quatmann <tim.quatmann@cs.rwth-aachen.de> Date: Tue, 3 Aug 2021 15:30:24 +0200 Subject: [PATCH 123/172] github buildtest workflow should test with spot. --- .github/workflows/buildtest.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/buildtest.yml b/.github/workflows/buildtest.yml index 59aba0cc3..b183c985d 100644 --- a/.github/workflows/buildtest.yml +++ b/.github/workflows/buildtest.yml @@ -19,8 +19,8 @@ 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=ON" + CMAKE_RELEASE: "-DCMAKE_BUILD_TYPE=Release -DSTORM_DEVELOPER=OFF -DSTORM_PORTABLE=ON -DSTORM_USE_SPOT=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" From e76c5ab4baffdb5044cb98ec0a7543ab63c0d1b6 Mon Sep 17 00:00:00 2001 From: Tim Quatmann <tim.quatmann@cs.rwth-aachen.de> Date: Tue, 3 Aug 2021 15:54:46 +0200 Subject: [PATCH 124/172] Fixed ambiguous operator overload. --- src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp index 7bf56ce4c..da1a32a93 100644 --- a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp +++ b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp @@ -377,7 +377,7 @@ namespace storm { } 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 "last" copy of the DA (_infSets.get().size()). - this->_accInfSets.get()[pState] = {_infSets.get().size()}; + this->_accInfSets.get()[pState] = std::set<uint_fast64_t>({_infSets.get().size()}); if (reachScheduler->isDontCare(pState)) { // Mark the maybe States of the untilProbability scheduler as "dontCare" _dontCareStates.get()[getMemoryState(product->getAutomatonState(pState), _infSets.get().size())].set(product->getModelState(pState), true); From efeeea0d54b0850f2a8593fcd1799e436e21ac69 Mon Sep 17 00:00:00 2001 From: Tim Quatmann <tim.quatmann@cs.rwth-aachen.de> Date: Wed, 4 Aug 2021 16:33:07 +0200 Subject: [PATCH 125/172] Spot: re-iterated cmake interface to hopefully make it more clean. Added documentation on how to update spot --- .github/workflows/buildtest.yml | 4 ++-- CHANGELOG.md | 2 +- CMakeLists.txt | 5 ++--- doc/update_resources.md | 4 ++++ resources/3rdparty/include_spot.cmake | 18 ++++-------------- 5 files changed, 13 insertions(+), 20 deletions(-) diff --git a/.github/workflows/buildtest.yml b/.github/workflows/buildtest.yml index b183c985d..a231f2430 100644 --- a/.github/workflows/buildtest.yml +++ b/.github/workflows/buildtest.yml @@ -19,8 +19,8 @@ env: NR_JOBS: "2" # cmake arguments - CMAKE_DEBUG: "-DCMAKE_BUILD_TYPE=Debug -DSTORM_DEVELOPER=ON -DSTORM_PORTABLE=ON -DSTORM_USE_SPOT=ON" - CMAKE_RELEASE: "-DCMAKE_BUILD_TYPE=Release -DSTORM_DEVELOPER=OFF -DSTORM_PORTABLE=ON -DSTORM_USE_SPOT=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" diff --git a/CHANGELOG.md b/CHANGELOG.md index d0c6f96ff..575df222b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,7 +10,7 @@ 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. -- Added cmake options `STORM_USE_SPOT` and `STORM_FORCE_SHIPPED_SPOT` to facilitate building Storm with [Spot](https://spot.lrde.epita.fr/). +- 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. diff --git a/CMakeLists.txt b/CMakeLists.txt index 5442379a6..c10d4f292 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -50,9 +50,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_FORCE_LTL_SUPPORT "Sets whether support for LTL model checking needs to be included." OFF) -option(STORM_USE_SPOT "Sets whether Spot should be included." ON) -option(STORM_FORCE_SHIPPED_SPOT "Sets whether the Spot sources should be downloaded and installed." OFF) +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) MARK_AS_ADVANCED(STORM_FORCE_SHIPPED_SPOT) option(XML_SUPPORT "Sets whether xml based format parsing should be included." ON) option(FORCE_COLOR "Force color output" OFF) 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/include_spot.cmake b/resources/3rdparty/include_spot.cmake index e64bad090..eaca6bc5a 100644 --- a/resources/3rdparty/include_spot.cmake +++ b/resources/3rdparty/include_spot.cmake @@ -1,16 +1,6 @@ set(STORM_HAVE_SPOT OFF) - -if (STORM_FORCE_SHIPPED_SPOT AND NOT STORM_USE_SPOT) - message(FATAL_ERROR "Storm - Incompatible cmake options: STORM_FORCE_SHIPPED_SPOT=ON and STORM_USE_SPOT=OFF.") -endif() - -if (STORM_FORCE_LTL_SUPPORT AND NOT STORM_USE_SPOT) - message(FATAL_ERROR "Storm - Incompatible cmake options: STORM_FORCE_LTL_SUPPORT=ON and STORM_USE_SPOT=OFF. LTL support requires Spot.") -endif() - -if(STORM_USE_SPOT AND NOT STORM_SHIPPED_SPOT AND NOT STORM_FORCE_SHIPPED_SPOT) - +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}") @@ -23,14 +13,14 @@ if(STORM_USE_SPOT AND NOT STORM_SHIPPED_SPOT AND NOT STORM_FORCE_SHIPPED_SPOT) 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_FORCE_LTL_SUPPORT) - 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_FORCE_LTL_SUPPORT to install Spot automatically. If you already installed Spot, consider setting cmake option SPOT_ROOT") + 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_FORCE_SHIPPED_SPOT OR (STORM_FORCE_LTL_SUPPORT AND NOT STORM_HAVE_SPOT)) +if(STORM_USE_SPOT_SHIPPED AND NOT STORM_HAVE_SPOT) # download and install shipped Spot ExternalProject_Add(spot From 3a3587370ed2e093977d4f618e08091b766a8d92 Mon Sep 17 00:00:00 2001 From: Tim Quatmann <tim.quatmann@cs.rwth-aachen.de> Date: Thu, 5 Aug 2021 11:30:41 +0200 Subject: [PATCH 126/172] Skip a test if LTL model checking is not available. --- .../modelchecker/csl/MarkovAutomatonCslModelCheckerTest.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/test/storm/modelchecker/csl/MarkovAutomatonCslModelCheckerTest.cpp b/src/test/storm/modelchecker/csl/MarkovAutomatonCslModelCheckerTest.cpp index 07475ce7a..58359c41a 100755 --- a/src/test/storm/modelchecker/csl/MarkovAutomatonCslModelCheckerTest.cpp +++ b/src/test/storm/modelchecker/csl/MarkovAutomatonCslModelCheckerTest.cpp @@ -351,6 +351,7 @@ namespace { } 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]"; @@ -382,6 +383,8 @@ namespace { } else { EXPECT_FALSE(checker->canHandle(tasks[0])); } - +#else + GTEST_SKIP(); +#endif } } From 98bb05b86fdfa777b18c0ab9f82f58776a5eb40a Mon Sep 17 00:00:00 2001 From: Tim Quatmann <tim.quatmann@cs.rwth-aachen.de> Date: Thu, 5 Aug 2021 11:31:22 +0200 Subject: [PATCH 127/172] Trying to build spot with a single thread --- resources/3rdparty/include_spot.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/resources/3rdparty/include_spot.cmake b/resources/3rdparty/include_spot.cmake index eaca6bc5a..d05f10b85 100644 --- a/resources/3rdparty/include_spot.cmake +++ b/resources/3rdparty/include_spot.cmake @@ -30,7 +30,7 @@ if(STORM_USE_SPOT_SHIPPED AND NOT STORM_HAVE_SPOT) 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 + BUILD_COMMAND make -j1 INSTALL_COMMAND make install LOG_CONFIGURE ON LOG_BUILD ON From feadd3af77629fb449365e5bb8184fc1d17280f3 Mon Sep 17 00:00:00 2001 From: Tim Quatmann <tim.quatmann@cs.rwth-aachen.de> Date: Thu, 5 Aug 2021 15:16:04 +0200 Subject: [PATCH 128/172] Added cmake option STORM_RESOURCES_BUILD_JOBCOUNT to have better control on how many jobs we shall use to build external stuff (like spot, carl, cudd, glpk, ?) --- CMakeLists.txt | 12 ++++++++++++ resources/3rdparty/CMakeLists.txt | 3 ++- resources/3rdparty/include_cudd.cmake | 2 +- resources/3rdparty/include_glpk.cmake | 2 +- resources/3rdparty/include_spot.cmake | 2 +- 5 files changed, 17 insertions(+), 4 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index c10d4f292..af4d02524 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -23,6 +23,7 @@ include(RegisterSourceGroup) include(imported) include(CheckCXXSourceCompiles) include(CheckCSourceCompiles) +include(ProcessorCount) ############################################################# ## @@ -84,6 +85,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/resources/3rdparty/CMakeLists.txt b/resources/3rdparty/CMakeLists.txt index cdc18db60..6bfd018ea 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.") ############################################################# ## @@ -338,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} 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 index d05f10b85..e7c138b2c 100644 --- a/resources/3rdparty/include_spot.cmake +++ b/resources/3rdparty/include_spot.cmake @@ -30,7 +30,7 @@ if(STORM_USE_SPOT_SHIPPED AND NOT STORM_HAVE_SPOT) 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 -j1 + BUILD_COMMAND make -j${STORM_RESOURCES_BUILD_JOBCOUNT} INSTALL_COMMAND make install LOG_CONFIGURE ON LOG_BUILD ON From 7a851901e260c431c47ff3d4e32954ba945a10f9 Mon Sep 17 00:00:00 2001 From: Stefan Pranger <stefan.pranger@student.tugraz.at> Date: Thu, 2 Sep 2021 12:53:46 +0200 Subject: [PATCH 129/172] updates after cherry pick --- .../parser/FormulaParserGrammar.cpp | 52 +++++++------------ .../parser/FormulaParserGrammar.h | 38 +++++++------- src/storm/logic/BoundedGloballyFormula.cpp | 4 +- src/storm/logic/BoundedGloballyFormula.h | 7 +-- src/storm/logic/Formula.h | 3 +- src/storm/logic/FragmentSpecification.cpp | 9 ++++ src/storm/logic/ToPrefixStringVisitor.cpp | 48 +++++++++-------- src/storm/logic/ToPrefixStringVisitor.h | 8 +-- .../csl/SparseCtmcCslModelChecker.h | 13 ++--- .../prctl/SparseDtmcPrctlModelChecker.h | 1 + .../prctl/helper/SparseMdpPrctlHelper.cpp | 2 + src/storm/storage/Scheduler.cpp | 3 +- src/storm/storage/Scheduler.h | 1 - 13 files changed, 96 insertions(+), 93 deletions(-) diff --git a/src/storm-parsers/parser/FormulaParserGrammar.cpp b/src/storm-parsers/parser/FormulaParserGrammar.cpp index 18adfc932..1d5360a90 100644 --- a/src/storm-parsers/parser/FormulaParserGrammar.cpp +++ b/src/storm-parsers/parser/FormulaParserGrammar.cpp @@ -29,7 +29,7 @@ namespace storm { 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)]); @@ -40,7 +40,7 @@ namespace storm { 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)] @@ -61,7 +61,7 @@ namespace storm { 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)]; @@ -72,7 +72,7 @@ namespace storm { 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(")"))) @@ -94,7 +94,7 @@ namespace storm { > 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 @@ -139,7 +139,7 @@ namespace storm { untilLevelPathFormula.name("until precedence level path formula"); pathFormula = untilLevelPathFormula(qi::_r1); pathFormula.name("path 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"); @@ -149,13 +149,13 @@ namespace storm { 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"); - + // Multi-objective, quantiles multiOperatorFormula = (qi::lit("multi") > qi::lit("(") > (operatorFormula % qi::lit(",")) @@ -165,14 +165,14 @@ namespace storm { 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"); - + // General formulae formula = (isPathFormula(qi::_r1) >> pathFormula(qi::_r2) | propositionalFormula(qi::_r1, qi::_r2)); formula.name("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"); @@ -183,7 +183,7 @@ namespace storm { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Woverloaded-shift-op-parentheses" - + 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"); @@ -236,7 +236,7 @@ namespace storm { // debug(filterProperty) // debug(constantDefinition ) // debug(start) - + // Enable error reporting. 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)); @@ -388,20 +388,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 { @@ -451,7 +439,7 @@ namespace storm { return storm::logic::OperatorInformation(optimizationDirection, boost::none); } } - + 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: @@ -469,7 +457,7 @@ namespace storm { 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)); } @@ -570,7 +558,7 @@ namespace storm { } 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)); } @@ -620,7 +608,7 @@ namespace storm { return storm::jani::Property(std::to_string(propertyCount), formula, this->getUndefinedConstants(formula)); } } - + storm::logic::PlayerCoalition FormulaParserGrammar::createPlayerCoalition(std::vector<boost::variant<std::string, storm::storage::PlayerIndex>> const& playerIds) const { return storm::logic::PlayerCoalition(playerIds); } @@ -628,7 +616,7 @@ namespace storm { 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)); } - + bool FormulaParserGrammar::isBooleanReturnType(std::shared_ptr<storm::logic::Formula const> const& formula, bool raiseErrorMessage) { if (formula->hasQualitativeResult()) { return true; @@ -636,7 +624,7 @@ namespace storm { STORM_LOG_ERROR_COND(!raiseErrorMessage, "Formula " << *formula << " does not have a Boolean return type."); return false; } - + 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; diff --git a/src/storm-parsers/parser/FormulaParserGrammar.h b/src/storm-parsers/parser/FormulaParserGrammar.h index 33d9e7935..63ba71f3e 100644 --- a/src/storm-parsers/parser/FormulaParserGrammar.h +++ b/src/storm-parsers/parser/FormulaParserGrammar.h @@ -63,7 +63,7 @@ namespace storm { }; // 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 @@ -78,7 +78,7 @@ namespace storm { // 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 @@ -91,7 +91,7 @@ namespace storm { // A parser used for recognizing the operators at the "relational" precedence level. relationalOperatorStruct relationalOperator_; - + struct optimalityOperatorStruct : qi::symbols<char, storm::OptimizationDirection> { optimalityOperatorStruct() { add @@ -132,7 +132,7 @@ namespace storm { // A parser used for recognizing the filter type. filterTypeStruct filterType_; - + struct operatorKeyword : qi::symbols<char, storm::logic::FormulaContext> { operatorKeyword() { add @@ -144,7 +144,7 @@ namespace storm { } }; operatorKeyword operatorKeyword_; - + enum class FormulaKind { State, /// PCTL*-like (boolean) state formula Path, /// PCTL*-like (boolean) path formula (include state formulae) @@ -161,23 +161,23 @@ namespace storm { // A symbol table that is a mapping from identifiers that can be used in expressions to the expressions // they are to be replaced with. qi::symbols<char, storm::expressions::Expression> identifiers_; - - + + // Rules - + // 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> quotedString; - + // 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; @@ -190,7 +190,7 @@ namespace storm { 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; @@ -205,13 +205,13 @@ namespace storm { 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; - + // 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; - + // 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; @@ -220,7 +220,7 @@ namespace storm { 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; @@ -228,7 +228,7 @@ namespace storm { // Properties qi::rule<Iterator, std::string(), Skipper> formulaName; qi::rule<Iterator, storm::jani::Property(), Skipper> filterProperty; - + // Constant declarations enum class ConstantDataType { Bool, Integer, Rational @@ -237,7 +237,7 @@ namespace storm { // 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; @@ -263,7 +263,7 @@ 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> createHOAPathFormula(const std::string& automataFile) const; @@ -289,10 +289,10 @@ namespace storm { 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); - + 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/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/Formula.h b/src/storm/logic/Formula.h index 92100326a..29eba01ff 100644 --- a/src/storm/logic/Formula.h +++ b/src/storm/logic/Formula.h @@ -74,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. @@ -244,7 +245,7 @@ namespace storm { * @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; diff --git a/src/storm/logic/FragmentSpecification.cpp b/src/storm/logic/FragmentSpecification.cpp index 3bd34e629..9e28eec3e 100644 --- a/src/storm/logic/FragmentSpecification.cpp +++ b/src/storm/logic/FragmentSpecification.cpp @@ -433,6 +433,15 @@ namespace storm { return *this; } + bool FragmentSpecification::areBinaryBooleanStateFormulasAllowed() const { + return binaryBooleanStateFormula; + } + + FragmentSpecification& FragmentSpecification::setBinaryBooleanStateFormulasAllowed(bool newValue) { + this->binaryBooleanStateFormula = newValue; + return *this; + } + bool FragmentSpecification::areBinaryBooleanPathFormulasAllowed() const { return binaryBooleanPathFormula; } diff --git a/src/storm/logic/ToPrefixStringVisitor.cpp b/src/storm/logic/ToPrefixStringVisitor.cpp index 6fc7640e4..af6e3f31c 100644 --- a/src/storm/logic/ToPrefixStringVisitor.cpp +++ b/src/storm/logic/ToPrefixStringVisitor.cpp @@ -7,20 +7,20 @@ 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)); @@ -34,7 +34,7 @@ namespace storm { } 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)); @@ -58,53 +58,57 @@ namespace storm { } return result; } - + + boost::any ToPrefixStringVisitor::visit(BoundedGloballyFormula const&, boost::any const&) const { + STORM_LOG_THROW(false, storm::exceptions::InvalidOperationException, "Can not convert to prefix string"); + } + 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"); } @@ -113,19 +117,19 @@ namespace storm { 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()) { @@ -151,7 +155,7 @@ namespace storm { 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 index 16b8fad4a..38a786458 100644 --- a/src/storm/logic/ToPrefixStringVisitor.h +++ b/src/storm/logic/ToPrefixStringVisitor.h @@ -6,16 +6,17 @@ 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; @@ -37,7 +38,6 @@ namespace storm { 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/modelchecker/csl/SparseCtmcCslModelChecker.h b/src/storm/modelchecker/csl/SparseCtmcCslModelChecker.h index fa43b6f9e..48de3aa16 100644 --- a/src/storm/modelchecker/csl/SparseCtmcCslModelChecker.h +++ b/src/storm/modelchecker/csl/SparseCtmcCslModelChecker.h @@ -10,25 +10,26 @@ #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> 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> 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 +51,7 @@ namespace storm { std::unique_ptr<CheckResult> computeSteadyStateDistribution(Environment const& env); }; - + } // namespace modelchecker } // namespace storm diff --git a/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.h b/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.h index e03ba42b8..6f49a1a6d 100644 --- a/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.h +++ b/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.h @@ -30,6 +30,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> 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; diff --git a/src/storm/modelchecker/prctl/helper/SparseMdpPrctlHelper.cpp b/src/storm/modelchecker/prctl/helper/SparseMdpPrctlHelper.cpp index de837daa3..85f80667f 100644 --- a/src/storm/modelchecker/prctl/helper/SparseMdpPrctlHelper.cpp +++ b/src/storm/modelchecker/prctl/helper/SparseMdpPrctlHelper.cpp @@ -635,6 +635,8 @@ 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. diff --git a/src/storm/storage/Scheduler.cpp b/src/storm/storage/Scheduler.cpp index 55b842d37..964346afc 100644 --- a/src/storm/storage/Scheduler.cpp +++ b/src/storm/storage/Scheduler.cpp @@ -274,7 +274,8 @@ namespace storm { } 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()) <<")"; - } + } + } stateString << std::endl; } diff --git a/src/storm/storage/Scheduler.h b/src/storm/storage/Scheduler.h index cacd5b00b..e953e21b7 100644 --- a/src/storm/storage/Scheduler.h +++ b/src/storm/storage/Scheduler.h @@ -154,7 +154,6 @@ namespace storm { std::vector<storm::storage::BitVector> reachableStates; uint_fast64_t numOfUndefinedChoices; // Only consider reachable ones std::vector<storm::storage::BitVector> dontCareStates; // Their choices are neither considered deterministic nor undefined - uint_fast64_t numOfUndefinedChoices; uint_fast64_t numOfDeterministicChoices; uint_fast64_t numOfDontCareStates; }; From 948e7fdaba129603fb9b69617fe338b63a83805a Mon Sep 17 00:00:00 2001 From: Tim Quatmann <tim.quatmann@cs.rwth-aachen.de> Date: Fri, 6 Aug 2021 15:18:28 +0200 Subject: [PATCH 130/172] cmake: Fixed marking non-existing option as advanced --- CMakeLists.txt | 1 - 1 file changed, 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index af4d02524..95d5cb822 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -53,7 +53,6 @@ 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) -MARK_AS_ADVANCED(STORM_FORCE_SHIPPED_SPOT) 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) From c8e9b431009df1d273d7cf3e1940f0d91d95a7cb Mon Sep 17 00:00:00 2001 From: Tim Quatmann <tim.quatmann@cs.rwth-aachen.de> Date: Mon, 9 Aug 2021 12:21:33 +0200 Subject: [PATCH 131/172] Changed ltl2da option to slightly more descriptive ltl2datool (this is also the name of the corresponding option in PRISM) --- .../modelchecker/ModelCheckerEnvironment.cpp | 20 +++++++++---------- .../modelchecker/ModelCheckerEnvironment.h | 11 +++++----- .../helper/ltl/SparseLTLHelper.cpp | 5 ++--- .../settings/modules/ModelCheckerSettings.cpp | 12 +++++------ .../settings/modules/ModelCheckerSettings.h | 6 +++--- 5 files changed, 27 insertions(+), 27 deletions(-) diff --git a/src/storm/environment/modelchecker/ModelCheckerEnvironment.cpp b/src/storm/environment/modelchecker/ModelCheckerEnvironment.cpp index 8836d57be..6dbb25890 100644 --- a/src/storm/environment/modelchecker/ModelCheckerEnvironment.cpp +++ b/src/storm/environment/modelchecker/ModelCheckerEnvironment.cpp @@ -14,8 +14,8 @@ namespace storm { ModelCheckerEnvironment::ModelCheckerEnvironment() { auto const& mcSettings = storm::settings::getModule<storm::settings::modules::ModelCheckerSettings>(); - if (mcSettings.isLtl2daSet()) { - ltl2da = mcSettings.getLtl2da(); + if (mcSettings.isLtl2daToolSet()) { + ltl2daTool = mcSettings.getLtl2daTool(); } } @@ -31,20 +31,20 @@ namespace storm { return multiObjectiveModelCheckerEnvironment.get(); } - bool ModelCheckerEnvironment::isLtl2daSet() const { - return ltl2da.is_initialized(); + bool ModelCheckerEnvironment::isLtl2daToolSet() const { + return ltl2daTool.is_initialized(); } - boost::optional<std::string> const& ModelCheckerEnvironment::getLtl2da() const { - return ltl2da; + std::string const& ModelCheckerEnvironment::getLtl2daTool() const { + return ltl2daTool.get(); } - void ModelCheckerEnvironment::setLtl2da(std::string const& value) { - ltl2da = value; + void ModelCheckerEnvironment::setLtl2daTool(std::string const& value) { + ltl2daTool = value; } - void ModelCheckerEnvironment::unsetLtl2da() { - ltl2da = boost::none; + void ModelCheckerEnvironment::unsetLtl2daTool() { + ltl2daTool = boost::none; } diff --git a/src/storm/environment/modelchecker/ModelCheckerEnvironment.h b/src/storm/environment/modelchecker/ModelCheckerEnvironment.h index b5bca9835..6867a487c 100644 --- a/src/storm/environment/modelchecker/ModelCheckerEnvironment.h +++ b/src/storm/environment/modelchecker/ModelCheckerEnvironment.h @@ -21,15 +21,16 @@ namespace storm { MultiObjectiveModelCheckerEnvironment& multi(); MultiObjectiveModelCheckerEnvironment const& multi() const; - bool isLtl2daSet() const; - boost::optional<std::string> const& getLtl2da() const; - void setLtl2da(std::string const& value); - void unsetLtl2da(); + + bool isLtl2daToolSet() const; + std::string const& getLtl2daTool() const; + void setLtl2daTool(std::string const& value); + void unsetLtl2daTool(); private: SubEnvironment<MultiObjectiveModelCheckerEnvironment> multiObjectiveModelCheckerEnvironment; - boost::optional<std::string> ltl2da; + boost::optional<std::string> ltl2daTool; }; } diff --git a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp index da1a32a93..8215aa4b3 100644 --- a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp +++ b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp @@ -595,10 +595,9 @@ namespace storm { // Convert LTL formula to a deterministic automaton std::shared_ptr<storm::automata::DeterministicAutomaton> da; - if (env.modelchecker().isLtl2daSet()) { + if (env.modelchecker().isLtl2daToolSet()) { // Use the external tool given via ltl2da - std::string ltl2da = env.modelchecker().getLtl2da().get(); - da = storm::automata::LTL2DeterministicAutomaton::ltl2daExternalTool(*ltlFormula, ltl2da); + da = storm::automata::LTL2DeterministicAutomaton::ltl2daExternalTool(*ltlFormula, env.modelchecker().getLtl2daTool()); } else { // Use the internal tool (Spot) diff --git a/src/storm/settings/modules/ModelCheckerSettings.cpp b/src/storm/settings/modules/ModelCheckerSettings.cpp index c68cc5a6b..d54e8a92e 100644 --- a/src/storm/settings/modules/ModelCheckerSettings.cpp +++ b/src/storm/settings/modules/ModelCheckerSettings.cpp @@ -14,23 +14,23 @@ namespace storm { const std::string ModelCheckerSettings::moduleName = "modelchecker"; const std::string ModelCheckerSettings::filterRewZeroOptionName = "filterrewzero"; - const std::string ModelCheckerSettings::ltl2daName = "ltl2da"; + 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, ltl2daName, 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()); + 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::isLtl2daSet() const { - return this->getOption(ltl2daName).getHasOptionBeenSet(); + bool ModelCheckerSettings::isLtl2daToolSet() const { + return this->getOption(ltl2daToolOptionName).getHasOptionBeenSet(); } - std::string ModelCheckerSettings::getLtl2da() const { - return this->getOption(ltl2daName).getArgumentByName("filename").getValueAsString(); + std::string ModelCheckerSettings::getLtl2daTool() const { + return this->getOption(ltl2daToolOptionName).getArgumentByName("filename").getValueAsString(); } } // namespace modules diff --git a/src/storm/settings/modules/ModelCheckerSettings.h b/src/storm/settings/modules/ModelCheckerSettings.h index 2f731690f..6d5511863 100644 --- a/src/storm/settings/modules/ModelCheckerSettings.h +++ b/src/storm/settings/modules/ModelCheckerSettings.h @@ -27,14 +27,14 @@ namespace storm { * * @return True iff the external ltl2da has been set. */ - bool isLtl2daSet() const; + 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 getLtl2da() const; + std::string getLtl2daTool() const; // The name of the module. static const std::string moduleName; @@ -42,7 +42,7 @@ namespace storm { private: // Define the string names of the options as constants. static const std::string filterRewZeroOptionName; - static const std::string ltl2daName; + static const std::string ltl2daToolOptionName; }; } // namespace modules From cdedf4e78fb25b545a92d2b39d3b5465f42a6f4b Mon Sep 17 00:00:00 2001 From: Tim Quatmann <tim.quatmann@cs.rwth-aachen.de> Date: Mon, 9 Aug 2021 12:28:36 +0200 Subject: [PATCH 132/172] Added comment for formula equality check. Strongly related to github issue #132. --- src/storm/logic/ExtractMaximalStateFormulasVisitor.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/storm/logic/ExtractMaximalStateFormulasVisitor.cpp b/src/storm/logic/ExtractMaximalStateFormulasVisitor.cpp index 6652c868b..c149a144f 100644 --- a/src/storm/logic/ExtractMaximalStateFormulasVisitor.cpp +++ b/src/storm/logic/ExtractMaximalStateFormulasVisitor.cpp @@ -150,7 +150,9 @@ namespace storm { } std::shared_ptr<Formula> ExtractMaximalStateFormulasVisitor::extract(std::shared_ptr<Formula> f) const { - // TODO can be optimized + // 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 From b097a442eeccbf10908cd3362719600d489edc88 Mon Sep 17 00:00:00 2001 From: Tim Quatmann <tim.quatmann@cs.rwth-aachen.de> Date: Mon, 9 Aug 2021 13:48:51 +0200 Subject: [PATCH 133/172] Processed some TODOs in storm/logic Conflicts: src/storm/logic/LiftableTransitionRewardsVisitor.cpp --- src/storm/logic/FormulaInformationVisitor.cpp | 7 +++---- src/storm/logic/FragmentChecker.cpp | 1 - src/storm/logic/LiftableTransitionRewardsVisitor.cpp | 7 +++---- 3 files changed, 6 insertions(+), 9 deletions(-) diff --git a/src/storm/logic/FormulaInformationVisitor.cpp b/src/storm/logic/FormulaInformationVisitor.cpp index 7a0b95f0c..0f174430b 100644 --- a/src/storm/logic/FormulaInformationVisitor.cpp +++ b/src/storm/logic/FormulaInformationVisitor.cpp @@ -134,12 +134,11 @@ namespace storm { } boost::any FormulaInformationVisitor::visit(QuantileFormula const& f, boost::any const& data) const { - // TODO (joachim): check is this correct? if (recurseIntoOperators) { return f.getSubformula().accept(*this, data); - } else { - return FormulaInformation(); - } + } else { + return FormulaInformation(); + } } boost::any FormulaInformationVisitor::visit(NextFormula const& f, boost::any const& data) const { diff --git a/src/storm/logic/FragmentChecker.cpp b/src/storm/logic/FragmentChecker.cpp index c40d703c9..6ee707ef5 100644 --- a/src/storm/logic/FragmentChecker.cpp +++ b/src/storm/logic/FragmentChecker.cpp @@ -341,7 +341,6 @@ namespace storm { 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(); - // TODO: check for (auto& mapped : f.getAPMapping()) { result = result && boost::any_cast<bool>(mapped.second->accept(*this, data)); } diff --git a/src/storm/logic/LiftableTransitionRewardsVisitor.cpp b/src/storm/logic/LiftableTransitionRewardsVisitor.cpp index fbb215440..7c3b1da97 100644 --- a/src/storm/logic/LiftableTransitionRewardsVisitor.cpp +++ b/src/storm/logic/LiftableTransitionRewardsVisitor.cpp @@ -22,13 +22,12 @@ namespace storm { return true; } - boost::any LiftableTransitionRewardsVisitor::visit(BinaryBooleanStateFormula const&, boost::any const&) const { - // TODO joachim: is this correct? - 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)); + return boost::any_cast<bool>(f.getLeftSubformula().accept(*this, data)) && boost::any_cast<bool>(f.getRightSubformula().accept(*this, data)); } From 10fc5d18c83a76978b77b8929dfa2c0eb81c84d2 Mon Sep 17 00:00:00 2001 From: Tim Quatmann <tim.quatmann@cs.rwth-aachen.de> Date: Mon, 9 Aug 2021 13:49:05 +0200 Subject: [PATCH 134/172] Clarified what a complex path formula is. --- src/storm/logic/FormulaInformation.h | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/storm/logic/FormulaInformation.h b/src/storm/logic/FormulaInformation.h index 280fa5e59..6d86ba3fd 100644 --- a/src/storm/logic/FormulaInformation.h +++ b/src/storm/logic/FormulaInformation.h @@ -18,6 +18,10 @@ namespace storm { bool containsCumulativeRewardFormula() const; 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); From 1207af13a2e491727c26b81a55833e53547f44db Mon Sep 17 00:00:00 2001 From: Tim Quatmann <tim.quatmann@cs.rwth-aachen.de> Date: Mon, 9 Aug 2021 15:21:20 +0200 Subject: [PATCH 135/172] symbolic and sparse models now have a public member `Representation` --- src/storm/models/sparse/Model.h | 2 ++ src/storm/models/symbolic/Model.h | 3 +++ 2 files changed, 5 insertions(+) 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; From 3a12b1cc103a709645bc9afa6150130d71553088 Mon Sep 17 00:00:00 2001 From: Tim Quatmann <tim.quatmann@cs.rwth-aachen.de> Date: Mon, 9 Aug 2021 15:22:22 +0200 Subject: [PATCH 136/172] Model Checkers: Reduced code duplications by using a single `computeStateFormulaProbabilities` method Conflicts: src/storm/modelchecker/AbstractModelChecker.h src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.cpp --- src/storm/modelchecker/AbstractModelChecker.cpp | 16 +++++++++++++++- src/storm/modelchecker/AbstractModelChecker.h | 2 +- .../prctl/HybridDtmcPrctlModelChecker.cpp | 8 -------- .../prctl/HybridDtmcPrctlModelChecker.h | 1 - .../prctl/HybridMdpPrctlModelChecker.cpp | 9 --------- .../prctl/HybridMdpPrctlModelChecker.h | 1 - .../prctl/SparseDtmcPrctlModelChecker.cpp | 8 -------- .../prctl/SparseDtmcPrctlModelChecker.h | 1 - .../prctl/SparseMdpPrctlModelChecker.cpp | 9 --------- .../prctl/SparseMdpPrctlModelChecker.h | 1 - .../prctl/SymbolicDtmcPrctlModelChecker.cpp | 8 -------- .../prctl/SymbolicDtmcPrctlModelChecker.h | 1 - .../prctl/SymbolicMdpPrctlModelChecker.cpp | 10 ---------- .../prctl/SymbolicMdpPrctlModelChecker.h | 1 - 14 files changed, 16 insertions(+), 60 deletions(-) diff --git a/src/storm/modelchecker/AbstractModelChecker.cpp b/src/storm/modelchecker/AbstractModelChecker.cpp index fc1534585..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" @@ -142,7 +146,17 @@ namespace storm { template<typename ModelType> std::unique_ptr<CheckResult> AbstractModelChecker<ModelType>::computeStateFormulaProbabilities(Environment const& env, CheckTask<storm::logic::Formula, ValueType> const& checkTask) { - STORM_LOG_THROW(false, storm::exceptions::NotImplementedException, "This model checker does not support the formula: " << checkTask.getFormula() << "."); + // 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> diff --git a/src/storm/modelchecker/AbstractModelChecker.h b/src/storm/modelchecker/AbstractModelChecker.h index 6eb3b0de8..2038e6361 100644 --- a/src/storm/modelchecker/AbstractModelChecker.h +++ b/src/storm/modelchecker/AbstractModelChecker.h @@ -65,7 +65,7 @@ namespace storm { 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); - virtual std::unique_ptr<CheckResult> computeStateFormulaProbabilities(Environment const& env, CheckTask<storm::logic::Formula, 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); diff --git a/src/storm/modelchecker/prctl/HybridDtmcPrctlModelChecker.cpp b/src/storm/modelchecker/prctl/HybridDtmcPrctlModelChecker.cpp index 44bd4ab3c..7bd2474de 100644 --- a/src/storm/modelchecker/prctl/HybridDtmcPrctlModelChecker.cpp +++ b/src/storm/modelchecker/prctl/HybridDtmcPrctlModelChecker.cpp @@ -82,14 +82,6 @@ namespace storm { 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>::computeStateFormulaProbabilities(Environment const& env, CheckTask<storm::logic::Formula, ValueType> const& checkTask) { - storm::logic::Formula const& formula = checkTask.getFormula(); - std::unique_ptr<CheckResult> resultPointer = this->check(env, formula); - SymbolicQualitativeCheckResult<DdType> const& result = resultPointer->asSymbolicQualitativeCheckResult<DdType>(); - return std::make_unique<SymbolicQuantitativeCheckResult<DdType, ValueType>>(result); - } - 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/HybridDtmcPrctlModelChecker.h b/src/storm/modelchecker/prctl/HybridDtmcPrctlModelChecker.h index 761d0168f..f779e1920 100644 --- a/src/storm/modelchecker/prctl/HybridDtmcPrctlModelChecker.h +++ b/src/storm/modelchecker/prctl/HybridDtmcPrctlModelChecker.h @@ -31,7 +31,6 @@ namespace storm { 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> computeLongRunAverageProbabilities(Environment const& env, CheckTask<storm::logic::StateFormula, ValueType> const& checkTask) override; - virtual std::unique_ptr<CheckResult> computeStateFormulaProbabilities(Environment const& env, CheckTask<storm::logic::Formula, 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> computeCumulativeRewards(Environment const& env, storm::logic::RewardMeasureType rewardMeasureType, CheckTask<storm::logic::CumulativeRewardFormula, ValueType> const& checkTask) override; diff --git a/src/storm/modelchecker/prctl/HybridMdpPrctlModelChecker.cpp b/src/storm/modelchecker/prctl/HybridMdpPrctlModelChecker.cpp index 275527797..e74c921a8 100644 --- a/src/storm/modelchecker/prctl/HybridMdpPrctlModelChecker.cpp +++ b/src/storm/modelchecker/prctl/HybridMdpPrctlModelChecker.cpp @@ -102,15 +102,6 @@ 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>::computeStateFormulaProbabilities(Environment const& env, CheckTask<storm::logic::Formula, ValueType> const& checkTask) { - storm::logic::Formula const& formula = checkTask.getFormula(); - std::unique_ptr<CheckResult> resultPointer = this->check(env, formula); - SymbolicQualitativeCheckResult<DdType> const& result = resultPointer->asSymbolicQualitativeCheckResult<DdType>(); - // min/max does not matters - return std::make_unique<SymbolicQuantitativeCheckResult<DdType, ValueType>>(result); - } template<typename ModelType> std::unique_ptr<CheckResult> HybridMdpPrctlModelChecker<ModelType>::computeCumulativeRewards(Environment const& env, storm::logic::RewardMeasureType, CheckTask<storm::logic::CumulativeRewardFormula, ValueType> const& checkTask) { diff --git a/src/storm/modelchecker/prctl/HybridMdpPrctlModelChecker.h b/src/storm/modelchecker/prctl/HybridMdpPrctlModelChecker.h index 3fa76a65a..d3b87f3a2 100644 --- a/src/storm/modelchecker/prctl/HybridMdpPrctlModelChecker.h +++ b/src/storm/modelchecker/prctl/HybridMdpPrctlModelChecker.h @@ -38,7 +38,6 @@ 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> computeStateFormulaProbabilities(Environment const& env, CheckTask<storm::logic::Formula, 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; diff --git a/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.cpp b/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.cpp index 870a9a09a..5ee8fe1ce 100644 --- a/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.cpp +++ b/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.cpp @@ -175,14 +175,6 @@ namespace storm { return std::unique_ptr<CheckResult>(new ExplicitQuantitativeCheckResult<ValueType>(std::move(numericResult))); } - template<typename SparseDtmcModelType> - std::unique_ptr<CheckResult> SparseDtmcPrctlModelChecker<SparseDtmcModelType>::computeStateFormulaProbabilities(Environment const& env, CheckTask<storm::logic::Formula, ValueType> const& checkTask) { - // recurse - std::unique_ptr<CheckResult> resultPointer = this->check(env, checkTask.getFormula()); - ExplicitQualitativeCheckResult const& result = resultPointer->asExplicitQualitativeCheckResult(); - return std::make_unique<ExplicitQuantitativeCheckResult<ValueType>>(result); - } - 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(); diff --git a/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.h b/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.h index 6f49a1a6d..e5ff0d5f4 100644 --- a/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.h +++ b/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.h @@ -34,7 +34,6 @@ namespace storm { 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> computeStateFormulaProbabilities(Environment const& env, CheckTask<storm::logic::Formula, 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; diff --git a/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.cpp b/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.cpp index f386d416c..2b8750c7d 100644 --- a/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.cpp +++ b/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.cpp @@ -167,15 +167,6 @@ namespace storm { return result; } - template<typename SparseMdpModelType> - std::unique_ptr<CheckResult> SparseMdpPrctlModelChecker<SparseMdpModelType>::computeStateFormulaProbabilities(Environment const& env, CheckTask<storm::logic::Formula, ValueType> const& checkTask) { - storm::logic::Formula const& formula = 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> resultPointer = this->check(env, formula); - ExplicitQualitativeCheckResult const& result = resultPointer->asExplicitQualitativeCheckResult(); - return std::make_unique<ExplicitQuantitativeCheckResult<ValueType>>(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(); diff --git a/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.h b/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.h index 2a09694c5..2a56528ba 100644 --- a/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.h +++ b/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.h @@ -40,7 +40,6 @@ 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> computeStateFormulaProbabilities(Environment const& env, CheckTask<storm::logic::Formula, 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> 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 6b68c945f..473a39cab 100644 --- a/src/storm/modelchecker/prctl/SymbolicDtmcPrctlModelChecker.cpp +++ b/src/storm/modelchecker/prctl/SymbolicDtmcPrctlModelChecker.cpp @@ -58,14 +58,6 @@ 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>::computeStateFormulaProbabilities(Environment const& env, CheckTask<storm::logic::Formula, ValueType> const& checkTask) { - storm::logic::Formula const& formula = checkTask.getFormula(); - std::unique_ptr<CheckResult> resultPointer = this->check(env, formula); - SymbolicQualitativeCheckResult<DdType> const& result = resultPointer->asSymbolicQualitativeCheckResult<DdType>(); - return std::make_unique<SymbolicQuantitativeCheckResult<DdType, ValueType>>(result); - } template<typename ModelType> std::unique_ptr<CheckResult> SymbolicDtmcPrctlModelChecker<ModelType>::computeNextProbabilities(Environment const& env, CheckTask<storm::logic::NextFormula, ValueType> const& checkTask) { diff --git a/src/storm/modelchecker/prctl/SymbolicDtmcPrctlModelChecker.h b/src/storm/modelchecker/prctl/SymbolicDtmcPrctlModelChecker.h index 17c96e927..1a115468f 100644 --- a/src/storm/modelchecker/prctl/SymbolicDtmcPrctlModelChecker.h +++ b/src/storm/modelchecker/prctl/SymbolicDtmcPrctlModelChecker.h @@ -26,7 +26,6 @@ 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> computeStateFormulaProbabilities(Environment const& env, CheckTask<storm::logic::Formula, 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/SymbolicMdpPrctlModelChecker.cpp b/src/storm/modelchecker/prctl/SymbolicMdpPrctlModelChecker.cpp index 8f366034a..d9937001d 100644 --- a/src/storm/modelchecker/prctl/SymbolicMdpPrctlModelChecker.cpp +++ b/src/storm/modelchecker/prctl/SymbolicMdpPrctlModelChecker.cpp @@ -58,16 +58,6 @@ 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>::computeStateFormulaProbabilities(Environment const& env, CheckTask<storm::logic::Formula, ValueType> const& checkTask) { - storm::logic::Formula const& formula = checkTask.getFormula(); - STORM_LOG_THROW(checkTask.isOptimizationDirectionSet(), storm::exceptions::InvalidArgumentException, "Formula needs to specify whether minimal or maximal values are to be computed on nondeterministic model."); - std::unique_ptr<CheckResult> resultPointer = this->check(env, formula); - SymbolicQualitativeCheckResult<DdType> const& result = resultPointer->asSymbolicQualitativeCheckResult<DdType>(); - // min/max does not matters - return std::make_unique<SymbolicQuantitativeCheckResult<DdType, ValueType>>(result); - } template<typename ModelType> std::unique_ptr<CheckResult> SymbolicMdpPrctlModelChecker<ModelType>::computeNextProbabilities(Environment const& env, CheckTask<storm::logic::NextFormula, ValueType> const& checkTask) { diff --git a/src/storm/modelchecker/prctl/SymbolicMdpPrctlModelChecker.h b/src/storm/modelchecker/prctl/SymbolicMdpPrctlModelChecker.h index e54f3579d..4fda40be3 100644 --- a/src/storm/modelchecker/prctl/SymbolicMdpPrctlModelChecker.h +++ b/src/storm/modelchecker/prctl/SymbolicMdpPrctlModelChecker.h @@ -27,7 +27,6 @@ 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> computeStateFormulaProbabilities(Environment const& env, CheckTask<storm::logic::Formula, 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; From 63104620602a1e335734f254092b31d51829bf85 Mon Sep 17 00:00:00 2001 From: Tim Quatmann <tim.quatmann@cs.rwth-aachen.de> Date: Mon, 9 Aug 2021 15:28:28 +0200 Subject: [PATCH 137/172] Cleaned up dtmc and mdp helpers a bit. --- .../modelchecker/prctl/helper/SparseDtmcPrctlHelper.cpp | 4 ---- .../modelchecker/prctl/helper/SparseDtmcPrctlHelper.h | 7 ------- .../modelchecker/prctl/helper/SparseMdpPrctlHelper.cpp | 1 - 3 files changed, 12 deletions(-) diff --git a/src/storm/modelchecker/prctl/helper/SparseDtmcPrctlHelper.cpp b/src/storm/modelchecker/prctl/helper/SparseDtmcPrctlHelper.cpp index b9749ca55..30619d8f0 100644 --- a/src/storm/modelchecker/prctl/helper/SparseDtmcPrctlHelper.cpp +++ b/src/storm/modelchecker/prctl/helper/SparseDtmcPrctlHelper.cpp @@ -22,12 +22,9 @@ #include "storm/environment/solver/SolverEnvironment.h" -#include "storm/transformer/DAProductBuilder.h" - #include "storm/settings/SettingsManager.h" #include "storm/settings/modules/GeneralSettings.h" #include "storm/settings/modules/CoreSettings.h" -#include "storm/settings/modules/DebugSettings.h" #include "storm/settings/modules/IOSettings.h" #include "storm/settings/modules/ModelCheckerSettings.h" @@ -45,7 +42,6 @@ #include "storm/exceptions/UncheckedRequirementException.h" #include "storm/exceptions/NotSupportedException.h" - namespace storm { namespace modelchecker { namespace helper { diff --git a/src/storm/modelchecker/prctl/helper/SparseDtmcPrctlHelper.h b/src/storm/modelchecker/prctl/helper/SparseDtmcPrctlHelper.h index 97741d709..79f03e80c 100644 --- a/src/storm/modelchecker/prctl/helper/SparseDtmcPrctlHelper.h +++ b/src/storm/modelchecker/prctl/helper/SparseDtmcPrctlHelper.h @@ -16,15 +16,8 @@ #include "storm/solver/SolveGoal.h" namespace storm { - // fwd class Environment; - namespace models { - namespace sparse { - template <typename ValueType, typename RewardModelType> class Dtmc; - } - } - namespace modelchecker { class CheckResult; diff --git a/src/storm/modelchecker/prctl/helper/SparseMdpPrctlHelper.cpp b/src/storm/modelchecker/prctl/helper/SparseMdpPrctlHelper.cpp index 85f80667f..212896447 100644 --- a/src/storm/modelchecker/prctl/helper/SparseMdpPrctlHelper.cpp +++ b/src/storm/modelchecker/prctl/helper/SparseMdpPrctlHelper.cpp @@ -621,7 +621,6 @@ namespace storm { for (auto state : qualitativeStateSets.maybeStates) { scheduler->setDontCare(state); } - } } From 9cf3d6af5d16e4d6147c16056dabe039ecbb8e4e Mon Sep 17 00:00:00 2001 From: Tim Quatmann <tim.quatmann@cs.rwth-aachen.de> Date: Mon, 9 Aug 2021 17:10:44 +0200 Subject: [PATCH 138/172] Adding debug output and file I/O checks whenever parsing a HOA automaton from a file. --- src/storm/automata/DeterministicAutomaton.cpp | 18 +++++++++++++++--- src/storm/logic/HOAPathFormula.cpp | 2 -- 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/src/storm/automata/DeterministicAutomaton.cpp b/src/storm/automata/DeterministicAutomaton.cpp index 62ae6c043..c19f55dbe 100644 --- a/src/storm/automata/DeterministicAutomaton.cpp +++ b/src/storm/automata/DeterministicAutomaton.cpp @@ -1,10 +1,15 @@ #include "storm/automata/DeterministicAutomaton.h" -#include "storm/automata/AcceptanceCondition.h" -#include "storm/automata/HOAConsumerDA.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) @@ -93,7 +98,14 @@ namespace storm { DeterministicAutomaton::ptr DeterministicAutomaton::parseFromFile(const std::string& filename) { std::ifstream in(filename); - return parse(in); + 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/logic/HOAPathFormula.cpp b/src/storm/logic/HOAPathFormula.cpp index b5dc17d27..39a0f60c9 100644 --- a/src/storm/logic/HOAPathFormula.cpp +++ b/src/storm/logic/HOAPathFormula.cpp @@ -6,7 +6,6 @@ #include "storm/exceptions/ExpressionEvaluationException.h" #include "storm/exceptions/IllegalArgumentException.h" #include "storm/exceptions/InvalidPropertyException.h" -#include "storm/exceptions/FileIoException.h" namespace storm { namespace logic { @@ -71,7 +70,6 @@ namespace storm { storm::automata::DeterministicAutomaton::ptr HOAPathFormula::readAutomaton() const { std::ifstream in(automatonFile); - STORM_LOG_THROW(in.good(), storm::exceptions::FileIoException, "Can not open '" << automatonFile << "' for reading."); 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."); From a81f5e284bb437d130024fe4da84962ab2c4c1e7 Mon Sep 17 00:00:00 2001 From: Tim Quatmann <tim.quatmann@cs.rwth-aachen.de> Date: Mon, 9 Aug 2021 17:12:59 +0200 Subject: [PATCH 139/172] Further simplified LTLHelper Interface a bit. Support for LTL and HOA formulaes for *all* (sparse) model types --- .../ExtractMaximalStateFormulasVisitor.cpp | 6 +- .../ExtractMaximalStateFormulasVisitor.h | 16 +++-- .../csl/SparseCtmcCslModelChecker.cpp | 63 +++++++----------- .../csl/SparseCtmcCslModelChecker.h | 2 + .../SparseMarkovAutomatonCslModelChecker.cpp | 64 ++++++++----------- .../SparseMarkovAutomatonCslModelChecker.h | 1 + .../helper/ltl/SparseLTLHelper.cpp | 35 +++++++--- .../modelchecker/helper/ltl/SparseLTLHelper.h | 39 ++++++++--- .../prctl/SparseDtmcPrctlModelChecker.cpp | 54 ++++------------ .../prctl/SparseMdpPrctlModelChecker.cpp | 53 ++++++++------- .../prctl/SparseMdpPrctlModelChecker.h | 1 + 11 files changed, 159 insertions(+), 175 deletions(-) diff --git a/src/storm/logic/ExtractMaximalStateFormulasVisitor.cpp b/src/storm/logic/ExtractMaximalStateFormulasVisitor.cpp index c149a144f..f0c434ab2 100644 --- a/src/storm/logic/ExtractMaximalStateFormulasVisitor.cpp +++ b/src/storm/logic/ExtractMaximalStateFormulasVisitor.cpp @@ -7,11 +7,11 @@ namespace storm { namespace logic { - ExtractMaximalStateFormulasVisitor::ExtractMaximalStateFormulasVisitor(ApToFormulaMap& extractedFormulas, std::map<std::string, std::string>& cachedFormulas) : extractedFormulas(extractedFormulas), cachedFormulas(cachedFormulas), nestingLevel(0) { + ExtractMaximalStateFormulasVisitor::ExtractMaximalStateFormulasVisitor(ApToFormulaMap& extractedFormulas) : extractedFormulas(extractedFormulas), nestingLevel(0) { } - std::shared_ptr<Formula> ExtractMaximalStateFormulasVisitor::extract(PathFormula const& f, ApToFormulaMap& extractedFormulas, std::map<std::string, std::string>& cachedFormulas) { - ExtractMaximalStateFormulasVisitor visitor(extractedFormulas, cachedFormulas); + 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); } diff --git a/src/storm/logic/ExtractMaximalStateFormulasVisitor.h b/src/storm/logic/ExtractMaximalStateFormulasVisitor.h index d1a188c3d..13c829dea 100644 --- a/src/storm/logic/ExtractMaximalStateFormulasVisitor.h +++ b/src/storm/logic/ExtractMaximalStateFormulasVisitor.h @@ -6,12 +6,18 @@ namespace storm { namespace logic { - + class ExtractMaximalStateFormulasVisitor : public CloneVisitor { public: typedef std::map<std::string, std::shared_ptr<Formula const>> ApToFormulaMap; - - static std::shared_ptr<Formula> extract(PathFormula const& f, ApToFormulaMap& extractedFormulas, std::map<std::string, std::string>& cachedFormulas); + + /*! + * 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; @@ -28,7 +34,7 @@ namespace storm { virtual boost::any visit(RewardOperatorFormula const& f, boost::any const& data) const override; private: - ExtractMaximalStateFormulasVisitor(ApToFormulaMap& extractedFormulas, std::map<std::string, std::string>& cachedFormulas); + ExtractMaximalStateFormulasVisitor(ApToFormulaMap& extractedFormulas); std::shared_ptr<Formula> extract(std::shared_ptr<Formula> f) const; void incrementNestingLevel() const; @@ -36,7 +42,7 @@ namespace storm { ApToFormulaMap& extractedFormulas; // A mapping from formula-strings to labels in order to use the same label for the equivalent formulas (as strings) - std::map<std::string, std::string>& cachedFormulas; + mutable std::map<std::string, std::string> cachedFormulas; std::size_t nestingLevel; }; diff --git a/src/storm/modelchecker/csl/SparseCtmcCslModelChecker.cpp b/src/storm/modelchecker/csl/SparseCtmcCslModelChecker.cpp index e83b692b7..baa780223 100644 --- a/src/storm/modelchecker/csl/SparseCtmcCslModelChecker.cpp +++ b/src/storm/modelchecker/csl/SparseCtmcCslModelChecker.cpp @@ -96,54 +96,35 @@ namespace storm { 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(); - STORM_LOG_INFO("Extracting maximal state formulas for path formula: " << pathFormula); - storm::logic::ExtractMaximalStateFormulasVisitor::ApToFormulaMap extracted; - // Maintain a mapping from formula-strings to labels in order to reuse labels of equivalent (compared as strings) formulas - std::map<std::string, std::string> cached; - std::shared_ptr<storm::logic::Formula> ltlFormula = storm::logic::ExtractMaximalStateFormulasVisitor::extract(pathFormula, extracted, cached); - - - const SparseCtmcModelType& ctmc = this->getModel(); - typedef typename storm::models::sparse::Dtmc<typename SparseCtmcModelType::ValueType> SparseDtmcModelType; - - STORM_LOG_INFO("Computing embedded DTMC..."); - // Compute probability matrix (embedded DTMC) - storm::storage::SparseMatrix<ValueType> probabilityMatrix = storm::modelchecker::helper::SparseCtmcCslHelper::computeProbabilityMatrix(ctmc.getTransitionMatrix(), ctmc.getExitRateVector()); - // Copy of the state labelings of the CTMC - storm::models::sparse::StateLabeling labeling(ctmc.getStateLabeling()); - - // The embedded DTMC, used for building the product and computing the probabilities in the product - SparseDtmcModelType embeddedDtmc(std::move(probabilityMatrix), std::move(labeling)); - storm::solver::SolveGoal<ValueType> goal(embeddedDtmc, checkTask); - - STORM_LOG_INFO("Performing ltl probability computations in embedded DTMC..."); - - // TODO ? - if (storm::settings::getModule<storm::settings::modules::DebugSettings>().isTraceSet()) { - STORM_LOG_TRACE("Writing model to model.dot"); - std::ofstream modelDot("model.dot"); - embeddedDtmc.writeDotToStream(modelDot); - modelDot.close(); - } - - storm::modelchecker::helper::SparseLTLHelper<ValueType, false> helper(embeddedDtmc.getTransitionMatrix()); - storm::modelchecker::helper::setInformationFromCheckTaskDeterministic(helper, checkTask, embeddedDtmc); - - // Compute Satisfaction sets for APs - auto formulaChecker = [&] (std::shared_ptr<storm::logic::Formula const> const& formula) { return this->check(env, *formula); }; - std::map<std::string, storm::storage::BitVector> apSets = helper.computeApSets(extracted, formulaChecker); - - std::vector<ValueType> numericResult = helper.computeLTLProbabilities(env, *ltlFormula, apSets); + 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); - // We can directly return the numericResult vector as the state space of the CTMC and the embedded DTMC are exactly the same 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(); diff --git a/src/storm/modelchecker/csl/SparseCtmcCslModelChecker.h b/src/storm/modelchecker/csl/SparseCtmcCslModelChecker.h index 48de3aa16..40b487eff 100644 --- a/src/storm/modelchecker/csl/SparseCtmcCslModelChecker.h +++ b/src/storm/modelchecker/csl/SparseCtmcCslModelChecker.h @@ -30,6 +30,8 @@ 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> 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; diff --git a/src/storm/modelchecker/csl/SparseMarkovAutomatonCslModelChecker.cpp b/src/storm/modelchecker/csl/SparseMarkovAutomatonCslModelChecker.cpp index 5ebc3f8de..56a567359 100644 --- a/src/storm/modelchecker/csl/SparseMarkovAutomatonCslModelChecker.cpp +++ b/src/storm/modelchecker/csl/SparseMarkovAutomatonCslModelChecker.cpp @@ -111,57 +111,45 @@ 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, 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); + + 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_INFO("Extracting maximal state formulas for path formula: " << pathFormula); - storm::logic::ExtractMaximalStateFormulasVisitor::ApToFormulaMap extracted; - // Maintain a mapping from formula-strings to labels in order to reuse labels of equivalent (compared as strings) formulas - std::map<std::string, std::string> cached; - std::shared_ptr<storm::logic::Formula> ltlFormula = storm::logic::ExtractMaximalStateFormulasVisitor::extract(pathFormula, extracted, cached); - - const SparseMarkovAutomatonModelType& ma = this->getModel(); - typedef typename storm::models::sparse::Mdp<typename SparseMarkovAutomatonModelType::ValueType> SparseMdpModelType; - - STORM_LOG_INFO("Computing embedded MDP..."); - storm::storage::SparseMatrix<ValueType> probabilityMatrix = ma.getTransitionMatrix(); - // Copy of the state labelings of the MDP - storm::models::sparse::StateLabeling labeling(ma.getStateLabeling()); - // The embedded MDP, used for building the product and computing the probabilities in the product - SparseMdpModelType embeddedMdp(std::move(probabilityMatrix), std::move(labeling)); - - storm::solver::SolveGoal<ValueType> goal(embeddedMdp, checkTask); - - STORM_LOG_INFO("Performing ltl probability computations in embedded MDP..."); - - if (storm::settings::getModule<storm::settings::modules::DebugSettings>().isTraceSet()) { - STORM_LOG_TRACE("Writing model to model.dot"); - std::ofstream modelDot("model.dot"); - embeddedMdp.writeDotToStream(modelDot); - modelDot.close(); - } - - storm::modelchecker::helper::SparseLTLHelper<ValueType, true> helper(embeddedMdp.getTransitionMatrix()); - storm::modelchecker::helper::setInformationFromCheckTaskNondeterministic(helper, checkTask, embeddedMdp); - - // Compute Satisfaction sets for APs - auto formulaChecker = [&] (std::shared_ptr<storm::logic::Formula const> const& formula) { return this->check(env, *formula); }; - std::map<std::string, storm::storage::BitVector> apSets = helper.computeApSets(extracted, formulaChecker); + 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::vector<ValueType> numericResult = helper.computeLTLProbabilities(env, *ltlFormula, apSets); + 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(embeddedMdp))); + result->asExplicitQuantitativeCheckResult<ValueType>().setScheduler(std::make_unique<storm::storage::Scheduler<ValueType>>(helper.extractScheduler(this->getModel()))); } - // We can directly return the numericResult vector as the state space of the CTMC and the embedded MDP are exactly the same 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 360739171..81f94bd7e 100644 --- a/src/storm/modelchecker/csl/SparseMarkovAutomatonCslModelChecker.h +++ b/src/storm/modelchecker/csl/SparseMarkovAutomatonCslModelChecker.h @@ -30,6 +30,7 @@ namespace storm { virtual std::unique_ptr<CheckResult> computeBoundedUntilProbabilities(Environment const& env, CheckTask<storm::logic::BoundedUntilFormula, 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> 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/ltl/SparseLTLHelper.cpp b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp index 8215aa4b3..6795e81b8 100644 --- a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp +++ b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp @@ -1,10 +1,14 @@ #include "SparseLTLHelper.h" #include "storm/automata/LTL2DeterministicAutomaton.h" +#include "storm/automata/DeterministicAutomaton.h" #include "storm/modelchecker/prctl/helper/SparseDtmcPrctlHelper.h" #include "storm/modelchecker/prctl/helper/SparseMdpPrctlHelper.h" +#include "storm/logic/ExtractMaximalStateFormulasVisitor.h" +#include "storm/solver/SolveGoal.h" + #include "storm/storage/StronglyConnectedComponentDecomposition.h" #include "storm/storage/MaximalEndComponentDecomposition.h" #include "storm/storage/memorystructure/MemoryStructure.h" @@ -108,18 +112,29 @@ namespace storm { } 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, std::function<std::unique_ptr<CheckResult>(std::shared_ptr<storm::logic::Formula const> const& formula)> formulaChecker){ - std::map<std::string, storm::storage::BitVector> apSets; - for (auto& p: extracted) { - STORM_LOG_INFO(" Computing satisfaction set for atomic proposition \"" << p.first << "\" <=> " << *p.second << "..."); + 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."); - std::unique_ptr<CheckResult> subResultPointer = formulaChecker(p.second); - ExplicitQualitativeCheckResult const& subResult = subResultPointer->asExplicitQualitativeCheckResult(); - auto sat = subResult.getTruthValuesVector(); + // 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); - apSets[p.first] = std::move(sat); - STORM_LOG_INFO(" Atomic proposition \"" << p.first << "\" is satisfied by " << apSets[p.first].getNumberOfSetBits() << " states."); + } + + 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; } @@ -579,7 +594,7 @@ namespace storm { template<typename ValueType, bool Nondeterministic> - std::vector <ValueType> SparseLTLHelper<ValueType, Nondeterministic>::computeLTLProbabilities(Environment const& env, storm::logic::Formula const& formula, std::map<std::string, storm::storage::BitVector>& apSatSets) { + 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) { diff --git a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h index 82d81c598..5a46b4bc9 100644 --- a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h +++ b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h @@ -1,16 +1,24 @@ #include "storm/modelchecker/helper/SingleValueModelCheckerHelper.h" -#include "storm/modelchecker/results/ExplicitQualitativeCheckResult.h" -#include "storm/automata/DeterministicAutomaton.h" + #include "storm/storage/SparseMatrix.h" -#include "storm/solver/SolveGoal.h" +#include "storm/storage/Scheduler.h" #include "storm/models/sparse/Dtmc.h" #include "storm/models/sparse/Mdp.h" -#include "storm/logic/ExtractMaximalStateFormulasVisitor.h" #include "storm/transformer/DAProductBuilder.h" namespace storm { + class Environment; + + namespace logic { + class Formula; + class PathFormula; + } + namespace automata { + class DeterministicAutomaton; + } + namespace modelchecker { namespace helper { @@ -24,6 +32,8 @@ namespace storm { public: + typedef std::function<storm::storage::BitVector(storm::logic::Formula const&)> CheckFormulaCallback; + /*! * The type of the product automaton (DTMC or MDP) that is used during the computation. */ @@ -44,13 +54,22 @@ namespace storm { */ storm::storage::Scheduler<ValueType> extractScheduler(storm::models::sparse::Model<ValueType> const& model); + /*! + * Computes the LTL probabilities + * @param 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 + * @param the atomic propositions occuring in the formula together with the satisfaction sets + * @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 mapping from Ap to formula - * @param lambda that checks the provided formula + * @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, std::function<std::unique_ptr<CheckResult>(std::shared_ptr<storm::logic::Formula const> const& formula)> formulaChecker); + 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 @@ -63,11 +82,11 @@ namespace storm { /*! * Computes the LTL probabilities - * @param the LTL formula - * @param the atomic propositions and satisfaction sets + * @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::Formula const& formula, std::map<std::string, storm::storage::BitVector>& apSatSets); + std::vector<ValueType> computeLTLProbabilities(Environment const &env, storm::logic::PathFormula const& formula, std::map<std::string, storm::storage::BitVector>& apSatSets); private: /*! diff --git a/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.cpp b/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.cpp index 5ee8fe1ce..4fb9802de 100644 --- a/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.cpp +++ b/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.cpp @@ -123,24 +123,14 @@ namespace storm { 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_LOG_INFO("Obtaining HOA automaton..."); - storm::automata::DeterministicAutomaton::ptr da = pathFormula.readAutomaton(); - - STORM_LOG_INFO("Deterministic automaton from HOA file has " - << da->getNumberOfStates() << " states, " - << da->getAPSet().size() << " atomic propositions and " - << *da->getAcceptance()->getAcceptanceExpression() << " as acceptance condition."); - - const SparseDtmcModelType& dtmc = this->getModel(); - storm::modelchecker::helper::SparseLTLHelper<ValueType, false> helper(dtmc.getTransitionMatrix()); - storm::modelchecker::helper::setInformationFromCheckTaskDeterministic(helper, checkTask, dtmc); - - // Compute Satisfaction sets for APs - storm::logic::ExtractMaximalStateFormulasVisitor::ApToFormulaMap extracted = pathFormula.getAPMapping(); - auto formulaChecker = [&] (std::shared_ptr<storm::logic::Formula const> const& formula) {return this->check(*formula); }; - std::map<std::string, storm::storage::BitVector> apSets = helper.computeApSets(extracted, formulaChecker); - - std::vector<ValueType> numericResult = helper.computeDAProductProbabilities(env, *da, apSets); + + 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))); } @@ -148,30 +138,12 @@ namespace storm { 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_LOG_INFO("Extracting maximal state formulas for path formula: " << pathFormula); - storm::logic::ExtractMaximalStateFormulasVisitor::ApToFormulaMap extracted; - // Maintain a mapping from formula-strings to labels in order to reuse labels of equivalent (compared as strings) formulas - std::map<std::string, std::string> cached; - std::shared_ptr<storm::logic::Formula> ltlFormula = storm::logic::ExtractMaximalStateFormulasVisitor::extract(pathFormula, extracted, cached); - - const SparseDtmcModelType& dtmc = this->getModel(); - - // TODO ? - if (storm::settings::getModule<storm::settings::modules::DebugSettings>().isTraceSet()) { - STORM_LOG_TRACE("Writing model to model.dot"); - std::ofstream modelDot("model.dot"); - dtmc.writeDotToStream(modelDot); - modelDot.close(); - } - - storm::modelchecker::helper::SparseLTLHelper<ValueType, false> helper(dtmc.getTransitionMatrix()); - storm::modelchecker::helper::setInformationFromCheckTaskDeterministic(helper, checkTask, dtmc); - - // Compute Satisfaction sets for APs - auto formulaChecker = [&] (std::shared_ptr<storm::logic::Formula const> const& formula) { return this->check(env, *formula); }; - std::map<std::string, storm::storage::BitVector> apSets = helper.computeApSets(extracted, formulaChecker); + 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); - std::vector<ValueType> numericResult = helper.computeLTLProbabilities(env, *ltlFormula, apSets); return std::unique_ptr<CheckResult>(new ExplicitQuantitativeCheckResult<ValueType>(std::move(numericResult))); } diff --git a/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.cpp b/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.cpp index 2b8750c7d..874bb1c84 100644 --- a/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.cpp +++ b/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.cpp @@ -14,8 +14,6 @@ #include "storm/logic/FragmentSpecification.h" -#include "storm/logic/ExtractMaximalStateFormulasVisitor.h" - #include "storm/models/sparse/StandardRewardModel.h" #include "storm/modelchecker/prctl/helper/SparseMdpPrctlHelper.h" @@ -167,44 +165,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, 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); + + 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_LOG_INFO("Extracting maximal state formulas for path formula: " << pathFormula); - storm::logic::ExtractMaximalStateFormulasVisitor::ApToFormulaMap extracted; - // Maintain a mapping from formula-strings to labels in order to reuse labels of equivalent (compared as strings) formulas - std::map<std::string, std::string> cached; - std::shared_ptr<storm::logic::Formula> ltlFormula = storm::logic::ExtractMaximalStateFormulasVisitor::extract(pathFormula, extracted, cached); - - const SparseMdpModelType& mdp = this->getModel(); - if (storm::settings::getModule<storm::settings::modules::DebugSettings>().isTraceSet()) { - STORM_LOG_TRACE("Writing model to model.dot"); - std::ofstream modelDot("model.dot"); - this->getModel().writeDotToStream(modelDot); - modelDot.close(); - } - - - storm::modelchecker::helper::SparseLTLHelper<ValueType, true> helper(mdp.getTransitionMatrix()); - storm::modelchecker::helper::setInformationFromCheckTaskNondeterministic(helper, checkTask, mdp); - - // Compute Satisfaction sets for APs - auto formulaChecker = [&] (std::shared_ptr<storm::logic::Formula const> const& formula) { return this->check(env, *formula); }; - std::map<std::string, storm::storage::BitVector> apSets = helper.computeApSets(extracted, formulaChecker); - - std::vector<ValueType> numericResult = helper.computeLTLProbabilities(env, *ltlFormula, apSets); + 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(mdp))); + 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 2a56528ba..74358d334 100644 --- a/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.h +++ b/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.h @@ -41,6 +41,7 @@ namespace storm { 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; From db16aa50e63d6b6d4ef74ce96d589582bc8c66d2 Mon Sep 17 00:00:00 2001 From: Tim Quatmann <tim.quatmann@cs.rwth-aachen.de> Date: Mon, 9 Aug 2021 17:51:43 +0200 Subject: [PATCH 140/172] LTL Helper: Removed some debug output to reduce clutter --- .../helper/ltl/SparseLTLHelper.cpp | 30 ++----------------- 1 file changed, 2 insertions(+), 28 deletions(-) diff --git a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp index 6795e81b8..46627e714 100644 --- a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp +++ b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp @@ -157,7 +157,6 @@ namespace storm { std::size_t accMECs = 0; std::size_t allMECs = 0; - std::size_t i = 0; if (this->isProduceSchedulerSet()) { _infSets.emplace(); @@ -168,11 +167,8 @@ namespace storm { 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); - - STORM_LOG_INFO("Handle conjunction " << i); - + for (auto const& literal : conjunction) { - STORM_LOG_INFO(" " << *literal); if (literal->isTRUE()) { // skip } else if (literal->isFALSE()) { @@ -198,14 +194,11 @@ namespace storm { // skip continue; } - - STORM_LOG_DEBUG(" Allowed states: " << allowed); - + // Compute MECs in the allowed fragment storm::storage::MaximalEndComponentDecomposition<ValueType> mecs(transitionMatrix, backwardTransitions, allowed); allMECs += mecs.size(); for (const auto& mec : mecs) { - STORM_LOG_DEBUG("Inspect MEC: " << mec); bool accepting = true; for (auto const& literal : conjunction) { @@ -220,17 +213,12 @@ namespace storm { const storm::storage::BitVector& accSet = acceptance.getAcceptanceSet(atom.getAcceptanceSet()); if (atom.getType() == cpphoafparser::AtomAcceptance::TEMPORAL_INF) { if (atom.isNegated()) { - STORM_LOG_DEBUG("Checking against " << ~accSet); if (!mec.containsAnyState(~accSet)) { - STORM_LOG_DEBUG(" -> not satisfied"); accepting = false; break; } - } else { - STORM_LOG_DEBUG("Checking against " << accSet); if (!mec.containsAnyState(accSet)) { - STORM_LOG_DEBUG(" -> not satisfied"); accepting = false; break; } @@ -246,7 +234,6 @@ namespace storm { if (accepting) { accMECs++; - STORM_LOG_DEBUG("MEC is accepting"); for (auto const &stateChoicePair : mec) { acceptingStates.set(stateChoicePair.first); @@ -335,7 +322,6 @@ namespace storm { } } - STORM_LOG_DEBUG("Accepting states: " << acceptingStates); STORM_LOG_INFO("Found " << acceptingStates.getNumberOfSetBits() << " states in " << accMECs << " accepting MECs (considered " << allMECs << " MECs)."); return acceptingStates; @@ -513,18 +499,6 @@ namespace storm { STORM_LOG_INFO("Product "+ (Nondeterministic ? std::string("MDP-DA") : std::string("DTMC-DA")) +" has " << product->getProductModel().getNumberOfStates() << " states and " << product->getProductModel().getNumberOfTransitions() << " transitions."); - if (storm::settings::getModule<storm::settings::modules::DebugSettings>().isTraceSet()) { - STORM_LOG_TRACE("Writing product model to product.dot"); - std::ofstream productDot("product.dot"); - product->getProductModel().writeDotToStream(productDot); - productDot.close(); - - STORM_LOG_TRACE("Product model mapping:"); - std::stringstream str; - product->printMapping(str); - STORM_LOG_TRACE(str.str()); - } - // Compute accepting states storm::storage::BitVector acceptingStates; if (Nondeterministic) { From e92e32239bbc1c37fd96ea5e9ceb9706f0f9dda5 Mon Sep 17 00:00:00 2001 From: Tim Quatmann <tim.quatmann@cs.rwth-aachen.de> Date: Mon, 9 Aug 2021 18:05:39 +0200 Subject: [PATCH 141/172] Support for globally and next formulae for Markov Automata and CTMC Conflicts: src/storm/modelchecker/csl/SparseCtmcCslModelChecker.cpp --- .../csl/SparseCtmcCslModelChecker.cpp | 27 ++++++++++-------- .../csl/SparseCtmcCslModelChecker.h | 1 + .../SparseMarkovAutomatonCslModelChecker.cpp | 28 ++++++++++++++++++- .../SparseMarkovAutomatonCslModelChecker.h | 2 ++ 4 files changed, 46 insertions(+), 12 deletions(-) diff --git a/src/storm/modelchecker/csl/SparseCtmcCslModelChecker.cpp b/src/storm/modelchecker/csl/SparseCtmcCslModelChecker.cpp index baa780223..f3c107c8b 100644 --- a/src/storm/modelchecker/csl/SparseCtmcCslModelChecker.cpp +++ b/src/storm/modelchecker/csl/SparseCtmcCslModelChecker.cpp @@ -19,7 +19,6 @@ #include "storm/modelchecker/helper/ltl/SparseLTLHelper.h" #include "storm/logic/FragmentSpecification.h" -#include "storm/logic/ExtractMaximalStateFormulasVisitor.h" #include "storm/adapters/RationalFunctionAdapter.h" @@ -27,10 +26,6 @@ #include "storm/exceptions/InvalidPropertyException.h" #include "storm/exceptions/NotImplementedException.h" -#include "storm/settings/SettingsManager.h" -#include "storm/settings/modules/GeneralSettings.h" -#include "storm/settings/modules/DebugSettings.h" - namespace storm { namespace modelchecker { template <typename SparseCtmcModelType> @@ -40,7 +35,7 @@ namespace storm { template <typename ModelType> bool SparseCtmcCslModelChecker<ModelType>::canHandleStatic(CheckTask<storm::logic::Formula, ValueType> const& checkTask) { - auto fragment = storm::logic::csrlstar().setGloballyFormulasAllowed(true).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); } @@ -85,6 +80,16 @@ namespace storm { 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(); @@ -99,15 +104,15 @@ namespace storm { 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))); } @@ -118,13 +123,13 @@ namespace storm { 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(); diff --git a/src/storm/modelchecker/csl/SparseCtmcCslModelChecker.h b/src/storm/modelchecker/csl/SparseCtmcCslModelChecker.h index 40b487eff..1730aa327 100644 --- a/src/storm/modelchecker/csl/SparseCtmcCslModelChecker.h +++ b/src/storm/modelchecker/csl/SparseCtmcCslModelChecker.h @@ -28,6 +28,7 @@ namespace storm { 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; diff --git a/src/storm/modelchecker/csl/SparseMarkovAutomatonCslModelChecker.cpp b/src/storm/modelchecker/csl/SparseMarkovAutomatonCslModelChecker.cpp index 56a567359..358945d14 100644 --- a/src/storm/modelchecker/csl/SparseMarkovAutomatonCslModelChecker.cpp +++ b/src/storm/modelchecker/csl/SparseMarkovAutomatonCslModelChecker.cpp @@ -1,5 +1,6 @@ #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" @@ -40,7 +41,7 @@ namespace storm { template <typename ModelType> bool SparseMarkovAutomatonCslModelChecker<ModelType>::canHandleStatic(CheckTask<storm::logic::Formula, ValueType> const& checkTask, bool* requiresSingleInitialState) { - auto singleObjectiveFragment = storm::logic::csl().setUnaryBooleanPathFormulasAllowed(true).setBinaryBooleanPathFormulasAllowed(true).setNestedPathFormulasAllowed(true).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); @@ -93,6 +94,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) { diff --git a/src/storm/modelchecker/csl/SparseMarkovAutomatonCslModelChecker.h b/src/storm/modelchecker/csl/SparseMarkovAutomatonCslModelChecker.h index 81f94bd7e..093df17aa 100644 --- a/src/storm/modelchecker/csl/SparseMarkovAutomatonCslModelChecker.h +++ b/src/storm/modelchecker/csl/SparseMarkovAutomatonCslModelChecker.h @@ -28,7 +28,9 @@ 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; From dffc04a2805152fbf58e373a6648d4a0bfc0fcdd Mon Sep 17 00:00:00 2001 From: Tim Quatmann <tim.quatmann@cs.rwth-aachen.de> Date: Mon, 9 Aug 2021 18:21:26 +0200 Subject: [PATCH 142/172] Cleaned up some includes for the model checkers. Conflicts: src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.h src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.cpp --- .../SparseMarkovAutomatonCslModelChecker.cpp | 9 -------- .../helper/ltl/SparseLTLHelper.cpp | 14 ++++++------- .../prctl/SparseDtmcPrctlModelChecker.cpp | 10 ++------- .../prctl/SparseDtmcPrctlModelChecker.h | 3 --- .../prctl/SparseMdpPrctlModelChecker.cpp | 21 ++++++------------- .../prctl/SparseMdpPrctlModelChecker.h | 3 --- .../prctl/helper/SparseDtmcPrctlHelper.cpp | 2 -- 7 files changed, 14 insertions(+), 48 deletions(-) diff --git a/src/storm/modelchecker/csl/SparseMarkovAutomatonCslModelChecker.cpp b/src/storm/modelchecker/csl/SparseMarkovAutomatonCslModelChecker.cpp index 358945d14..1874a1384 100644 --- a/src/storm/modelchecker/csl/SparseMarkovAutomatonCslModelChecker.cpp +++ b/src/storm/modelchecker/csl/SparseMarkovAutomatonCslModelChecker.cpp @@ -13,25 +13,16 @@ #include "storm/utility/FilteredRewardModel.h" #include "storm/utility/macros.h" -#include "storm/settings/SettingsManager.h" -#include "storm/settings/modules/GeneralSettings.h" -#include "storm/settings/modules/DebugSettings.h" - #include "storm/solver/SolveGoal.h" -#include "storm/transformer/ContinuousToDiscreteTimeModelTransformer.h" - #include "storm/modelchecker/results/ExplicitQualitativeCheckResult.h" #include "storm/modelchecker/results/ExplicitQuantitativeCheckResult.h" #include "storm/logic/FragmentSpecification.h" -#include "storm/logic/ExtractMaximalStateFormulasVisitor.h" #include "storm/exceptions/InvalidPropertyException.h" #include "storm/exceptions/NotImplementedException.h" -#include "storm/api/storm.h" - namespace storm { namespace modelchecker { template<typename SparseMarkovAutomatonModelType> diff --git a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp index 46627e714..151e3892e 100644 --- a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp +++ b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp @@ -3,24 +3,22 @@ #include "storm/automata/LTL2DeterministicAutomaton.h" #include "storm/automata/DeterministicAutomaton.h" -#include "storm/modelchecker/prctl/helper/SparseDtmcPrctlHelper.h" -#include "storm/modelchecker/prctl/helper/SparseMdpPrctlHelper.h" +#include "storm/environment/modelchecker/ModelCheckerEnvironment.h" #include "storm/logic/ExtractMaximalStateFormulasVisitor.h" -#include "storm/solver/SolveGoal.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/storage/memorystructure/MemoryStructure.h" #include "storm/storage/memorystructure/MemoryStructureBuilder.h" +#include "storm/solver/SolveGoal.h" +#include "storm/utility/graph.h" -#include "storm/settings/SettingsManager.h" -#include "storm/settings/modules/DebugSettings.h" #include "storm/exceptions/InvalidPropertyException.h" -#include "storm/environment/modelchecker/ModelCheckerEnvironment.h" - -#include "storm/utility/graph.h" namespace storm { namespace modelchecker { diff --git a/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.cpp b/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.cpp index 4fb9802de..838caf03d 100644 --- a/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.cpp +++ b/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.cpp @@ -19,18 +19,12 @@ #include "storm/modelchecker/helper/utility/SetInformationFromCheckTask.h" #include "storm/logic/FragmentSpecification.h" -#include "storm/logic/ExtractMaximalStateFormulasVisitor.h" -#include "storm/automata/AcceptanceCondition.h" + #include "storm/solver/SolveGoal.h" +#include "storm/models/sparse/Dtmc.h" #include "storm/models/sparse/StandardRewardModel.h" -#include "storm/settings/SettingsManager.h" -#include "storm/settings/modules/GeneralSettings.h" -#include "storm/settings/modules/DebugSettings.h" - -#include "storm/exceptions/InvalidStateException.h" - #include "storm/exceptions/InvalidPropertyException.h" namespace storm { diff --git a/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.h b/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.h index e5ff0d5f4..7ab10210f 100644 --- a/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.h +++ b/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.h @@ -3,9 +3,6 @@ #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 { diff --git a/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.cpp b/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.cpp index 874bb1c84..7ce739537 100644 --- a/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.cpp +++ b/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.cpp @@ -1,7 +1,5 @@ #include "storm/modelchecker/prctl/SparseMdpPrctlModelChecker.h" -#include <sstream> - #include "storm/utility/constants.h" #include "storm/utility/macros.h" #include "storm/utility/vector.h" @@ -30,17 +28,10 @@ #include "storm/shields/ShieldHandling.h" -#include "storm/settings/SettingsManager.h" - -#include "storm/settings/modules/GeneralSettings.h" -#include "storm/settings/modules/DebugSettings.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 { @@ -168,14 +159,14 @@ namespace storm { 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, 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); - + 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()))); @@ -183,7 +174,7 @@ namespace storm { 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(); @@ -192,7 +183,7 @@ namespace storm { 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); @@ -203,7 +194,7 @@ namespace storm { 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 74358d334..3feb0802d 100644 --- a/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.h +++ b/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.h @@ -4,7 +4,6 @@ #include "storm/modelchecker/propositional/SparsePropositionalModelChecker.h" #include "storm/models/sparse/Mdp.h" #include "storm/solver/MinMaxLinearEquationSolver.h" -#include "storm/solver/SolveGoal.h" namespace storm { @@ -45,8 +44,6 @@ namespace storm { 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; - private: - //std::vector<ValueType> computeDAProductProbabilities(Environment const& env, storm::solver::SolveGoal<ValueType>&& goal, storm::automata::DeterministicAutomaton const& da, std::map<std::string, storm::storage::BitVector>& apSatSets, bool qualitative) const; }; } // namespace modelchecker } // namespace storm diff --git a/src/storm/modelchecker/prctl/helper/SparseDtmcPrctlHelper.cpp b/src/storm/modelchecker/prctl/helper/SparseDtmcPrctlHelper.cpp index 30619d8f0..4ebfb4821 100644 --- a/src/storm/modelchecker/prctl/helper/SparseDtmcPrctlHelper.cpp +++ b/src/storm/modelchecker/prctl/helper/SparseDtmcPrctlHelper.cpp @@ -6,8 +6,6 @@ #include "storm/utility/vector.h" #include "storm/utility/graph.h" -#include "storm/models/sparse/Dtmc.h" - #include "storm/storage/StronglyConnectedComponentDecomposition.h" #include "storm/storage/DynamicPriorityQueue.h" #include "storm/storage/ConsecutiveUint64DynamicPriorityQueue.h" From 693d5470a301f94a712e08ca3c1e2302a6d7989e Mon Sep 17 00:00:00 2001 From: Tim Quatmann <tim.quatmann@cs.rwth-aachen.de> Date: Mon, 9 Aug 2021 18:21:44 +0200 Subject: [PATCH 143/172] Updated changelog a bit. --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 575df222b..f7e13b53d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,7 +9,7 @@ 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. +- 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) From c46c711eb76ea448753763dbdf6c89d732e90793 Mon Sep 17 00:00:00 2001 From: Tim Quatmann <tim.quatmann@cs.rwth-aachen.de> Date: Tue, 10 Aug 2021 12:53:44 +0200 Subject: [PATCH 144/172] cpphoafparser: added missing include. --- .../include/cpphoafparser/parser/hoa_parser_exception.hh | 1 + 1 file changed, 1 insertion(+) 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 index 46834d644..c68b05a44 100644 --- 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 @@ -30,6 +30,7 @@ #define CPPHOAFPARSER_HOAPARSEREXCEPTION_H #include <stdexcept> +#include <cassert> namespace cpphoafparser { From 4ddb9c43376acc978ab19c030719d38f0c0ef143 Mon Sep 17 00:00:00 2001 From: Tim Quatmann <tim.quatmann@cs.rwth-aachen.de> Date: Tue, 10 Aug 2021 14:30:19 +0200 Subject: [PATCH 145/172] Some simplifications for memory structure. --- .../storage/memorystructure/MemoryStructure.cpp | 10 +--------- .../storage/memorystructure/MemoryStructure.h | 11 +++++------ .../memorystructure/MemoryStructureBuilder.cpp | 7 +------ .../memorystructure/MemoryStructureBuilder.h | 16 +++++----------- .../memorystructure/SparseModelMemoryProduct.cpp | 2 +- 5 files changed, 13 insertions(+), 33 deletions(-) diff --git a/src/storm/storage/memorystructure/MemoryStructure.cpp b/src/storm/storage/memorystructure/MemoryStructure.cpp index 6103c05dd..1bcded410 100644 --- a/src/storm/storage/memorystructure/MemoryStructure.cpp +++ b/src/storm/storage/memorystructure/MemoryStructure.cpp @@ -11,14 +11,6 @@ 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), onlyInitialStatesRelevant(true) { - // 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)), onlyInitialStatesRelevant(true) { - // intentionally left empty - } - 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 } @@ -27,7 +19,7 @@ namespace storm { // intentionally left empty } - bool MemoryStructure::IsOnlyInitialStatesRelevantSet() const { + bool MemoryStructure::isOnlyInitialStatesRelevantSet() const { return onlyInitialStatesRelevant; } diff --git a/src/storm/storage/memorystructure/MemoryStructure.h b/src/storm/storage/memorystructure/MemoryStructure.h index 2476a4e63..e831b58cf 100644 --- a/src/storm/storage/memorystructure/MemoryStructure.h +++ b/src/storm/storage/memorystructure/MemoryStructure.h @@ -33,14 +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); - MemoryStructure(TransitionMatrix&& transitionMatrix, storm::models::sparse::StateLabeling&& memoryStateLabeling, std::vector<uint_fast64_t>&& initialMemoryStates, bool onlyInitialStatesRelevant); + 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; + bool isOnlyInitialStatesRelevantSet () const; TransitionMatrix const& getTransitionMatrix() const; storm::models::sparse::StateLabeling const& getStateLabeling() const; std::vector<uint_fast64_t> const& getInitialMemoryStates() const; diff --git a/src/storm/storage/memorystructure/MemoryStructureBuilder.cpp b/src/storm/storage/memorystructure/MemoryStructureBuilder.cpp index 859a92635..54accf38a 100644 --- a/src/storm/storage/memorystructure/MemoryStructureBuilder.cpp +++ b/src/storm/storage/memorystructure/MemoryStructureBuilder.cpp @@ -9,18 +9,13 @@ 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), onlyInitialStatesRelevant(true) { - // Intentionally left empty - } - template <typename ValueType, typename RewardModelType> 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()), onlyInitialStatesRelevant(true) { + 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 } diff --git a/src/storm/storage/memorystructure/MemoryStructureBuilder.h b/src/storm/storage/memorystructure/MemoryStructureBuilder.h index 1d067a4bc..b038fb98f 100644 --- a/src/storm/storage/memorystructure/MemoryStructureBuilder.h +++ b/src/storm/storage/memorystructure/MemoryStructureBuilder.h @@ -14,18 +14,12 @@ namespace storm { class MemoryStructureBuilder { public: - /*! - * Initializes a new builder for a memory structure - * @param numberOfMemoryStates The number of states the resulting memory structure should have - */ - MemoryStructureBuilder(uint_fast64_t numberOfMemoryStates, storm::models::sparse::Model<ValueType, RewardModelType> const& model); - - /*! + /*! * 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 allModelStatesRelevant Consider non-initial model states + * @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, bool onlyInitialStatesRelevant); + 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 @@ -33,11 +27,11 @@ namespace storm { 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); diff --git a/src/storm/storage/memorystructure/SparseModelMemoryProduct.cpp b/src/storm/storage/memorystructure/SparseModelMemoryProduct.cpp index b80910704..76fa593ba 100644 --- a/src/storm/storage/memorystructure/SparseModelMemoryProduct.cpp +++ b/src/storm/storage/memorystructure/SparseModelMemoryProduct.cpp @@ -38,7 +38,7 @@ 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(); - if (memory.IsOnlyInitialStatesRelevantSet()) { + if (memory.isOnlyInitialStatesRelevantSet()) { for (auto modelInit : model.getInitialStates()) { initialStates.set(modelInit * memoryStateCount + *memoryInitIt, true); ++memoryInitIt; From 396b39a21b80994a4f9f52d9711d4b3d56c5fa08 Mon Sep 17 00:00:00 2001 From: Tim Quatmann <tim.quatmann@cs.rwth-aachen.de> Date: Tue, 10 Aug 2021 14:32:33 +0200 Subject: [PATCH 146/172] Fixed a typo (thanks @PrangerStefan) --- src/storm/automata/AcceptanceCondition.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/storm/automata/AcceptanceCondition.cpp b/src/storm/automata/AcceptanceCondition.cpp index 14eb9c818..8360ec24a 100644 --- a/src/storm/automata/AcceptanceCondition.cpp +++ b/src/storm/automata/AcceptanceCondition.cpp @@ -42,7 +42,7 @@ bool AcceptanceCondition::isAccepting(const storm::storage::StateBlock& scc, acc 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()); + return isAccepting(scc, expr->getLeft()) || isAccepting(scc, expr->getRight()); case acceptance_expr::EXP_NOT: return !isAccepting(scc, expr->getLeft()); case acceptance_expr::EXP_TRUE: From 6c7d6b0d2b1ccd4d025305925f260f2b0a1bc696 Mon Sep 17 00:00:00 2001 From: Tim Quatmann <tim.quatmann@cs.rwth-aachen.de> Date: Tue, 10 Aug 2021 14:38:01 +0200 Subject: [PATCH 147/172] Silenced some unused variable-warnings. --- src/storm/automata/HOAConsumerDAHeader.h | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/src/storm/automata/HOAConsumerDAHeader.h b/src/storm/automata/HOAConsumerDAHeader.h index 4d12c0082..c206ef8e3 100644 --- a/src/storm/automata/HOAConsumerDAHeader.h +++ b/src/storm/automata/HOAConsumerDAHeader.h @@ -32,7 +32,7 @@ public: } /** Called by the parser for the "HOA: version" item [mandatory, once]. */ - virtual void notifyHeaderStart(const std::string& version) { + virtual void notifyHeaderStart(const std::string& /*version*/) { // TODO: Check version } @@ -101,7 +101,7 @@ public: /** * Called by the parser for the "name: ..." item [optional, once]. **/ - virtual void setName(const std::string& name) { + virtual void setName(const std::string& /*name*/) { // IGNORE } @@ -110,7 +110,7 @@ public: * @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) { + virtual void setTool(const std::string& /*name*/, std::shared_ptr<std::string> /*version*/) { // IGNORE } @@ -118,7 +118,7 @@ public: * 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) { + virtual void addProperties(const std::vector<std::string>& /*properties*/) { // TODO: check supported } @@ -127,7 +127,7 @@ public: * @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) { + virtual void addMiscHeader(const std::string& /*name*/, const std::vector<cpphoafparser::IntOrString>& /*content*/) { // TODO: Check semantic headers } @@ -145,7 +145,7 @@ public: * @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) { + virtual void addState(unsigned int /*id*/, std::shared_ptr<std::string> /*info*/, label_expr::ptr /*labelExpr*/, std::shared_ptr<int_list> /*accSignature*/) { // IGNORE } @@ -161,7 +161,7 @@ public: * @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) { + virtual void addEdgeImplicit(unsigned int /*stateId*/, const int_list& /*conjSuccessors*/, std::shared_ptr<int_list> /*accSignature*/) { // IGNORE } @@ -174,7 +174,7 @@ public: * @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) { + virtual void addEdgeWithLabel(unsigned int /*stateId*/, label_expr::ptr /*labelExpr*/, const int_list& /*conjSuccessors*/, std::shared_ptr<int_list> /*accSignature*/) { // IGNORE } @@ -182,7 +182,7 @@ public: * Called by the parser to notify the consumer that the definition for state `stateId` * has ended [multiple]. */ - virtual void notifyEndOfState(unsigned int stateId) { + virtual void notifyEndOfState(unsigned int /*stateId*/) { // IGNORE } From 62cede1759ca49cb2dde977cf4765257219478ec Mon Sep 17 00:00:00 2001 From: Tim Quatmann <tim.quatmann@cs.rwth-aachen.de> Date: Tue, 10 Aug 2021 15:34:04 +0200 Subject: [PATCH 148/172] Added missing include. --- src/storm-pars/analysis/AssumptionChecker.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/storm-pars/analysis/AssumptionChecker.cpp b/src/storm-pars/analysis/AssumptionChecker.cpp index 0d8d87cf9..8dad3bd48 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 { From 24ba65f5e19f458e82d47a0f624ae8d2e91a79eb Mon Sep 17 00:00:00 2001 From: hannah <hannah.mertens@rwth-aachen.de> Date: Wed, 11 Aug 2021 15:44:17 +0200 Subject: [PATCH 149/172] added documentation --- .../automata/LTL2DeterministicAutomaton.cpp | 2 -- .../automata/LTL2DeterministicAutomaton.h | 21 ++++++++++++------- 2 files changed, 13 insertions(+), 10 deletions(-) diff --git a/src/storm/automata/LTL2DeterministicAutomaton.cpp b/src/storm/automata/LTL2DeterministicAutomaton.cpp index e33939f7b..6e1636961 100644 --- a/src/storm/automata/LTL2DeterministicAutomaton.cpp +++ b/src/storm/automata/LTL2DeterministicAutomaton.cpp @@ -96,8 +96,6 @@ namespace storm { } STORM_LOG_THROW(rv == 0, storm::exceptions::FileIoException, "Could not construct deterministic automaton for " << prefixLtl << ", return code = " << rv); - // Transition-based acceptance is required. - // For MDP-MC the acceptance condition must be in DNF, otherwise an exception is thrown during computation if accepting ECs 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 index 4134e326f..94669138f 100644 --- a/src/storm/automata/LTL2DeterministicAutomaton.h +++ b/src/storm/automata/LTL2DeterministicAutomaton.h @@ -17,18 +17,23 @@ namespace storm { public: /*! - * TODO - * @param f - * @param dnf - * @return + * 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); /*! - * TODO - * @param f - * @param ltl2daTool - * @return + * 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); From e5b19643e82c0fc097bd07be2aef0b0a763baccb Mon Sep 17 00:00:00 2001 From: hannah <hannah.mertens@rwth-aachen.de> Date: Wed, 11 Aug 2021 16:45:45 +0200 Subject: [PATCH 150/172] dontCareStates can now be (non)deterministic and (un)defined Conflicts: src/storm/storage/Scheduler.h --- src/storm/storage/Scheduler.cpp | 46 ++++++++++++++------------------- src/storm/storage/Scheduler.h | 9 ++++--- 2 files changed, 25 insertions(+), 30 deletions(-) diff --git a/src/storm/storage/Scheduler.cpp b/src/storm/storage/Scheduler.cpp index 964346afc..c177747de 100644 --- a/src/storm/storage/Scheduler.cpp +++ b/src/storm/storage/Scheduler.cpp @@ -35,26 +35,25 @@ namespace storm { STORM_LOG_ASSERT(modelState < schedulerChoices[memoryState].size(), "Illegal model state index"); auto& schedulerChoice = schedulerChoices[memoryState][modelState]; - if (!dontCareStates[memoryState].get(modelState)) { - if (schedulerChoice.isDefined()) { - if (!choice.isDefined()) { - ++numOfUndefinedChoices; - } - } else { - if (choice.isDefined()) { - assert(numOfUndefinedChoices > 0); - --numOfUndefinedChoices; - } + + if (schedulerChoice.isDefined()) { + if (!choice.isDefined()) { + ++numOfUndefinedChoices; } - if (schedulerChoice.isDeterministic()) { - if (!choice.isDeterministic()) { - assert(numOfDeterministicChoices > 0); - --numOfDeterministicChoices; - } - } else { - if (choice.isDeterministic()) { - ++numOfDeterministicChoices; - } + } else { + if (choice.isDefined()) { + assert(numOfUndefinedChoices > 0); + --numOfUndefinedChoices; + } + } + if (schedulerChoice.isDeterministic()) { + if (!choice.isDeterministic()) { + assert(numOfDeterministicChoices > 0); + --numOfDeterministicChoices; + } + } else { + if (choice.isDeterministic()) { + ++numOfDeterministicChoices; } } @@ -87,13 +86,13 @@ namespace storm { } template <typename ValueType> - void Scheduler<ValueType>::setDontCare(uint_fast64_t modelState, uint_fast64_t memoryState) { + 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()) { + if (!schedulerChoice.isDefined() && setArbitraryChoice) { // Set an arbitrary choice this->setChoice(0, modelState, memoryState); } @@ -108,13 +107,8 @@ namespace storm { STORM_LOG_ASSERT(modelState < schedulerChoices[memoryState].size(), "Illegal model state index"); if (dontCareStates[memoryState].get(modelState)) { - auto& schedulerChoice = schedulerChoices[memoryState][modelState]; - if (!schedulerChoice.isDefined()) { - ++numOfUndefinedChoices; - } dontCareStates[memoryState].set(modelState, false); --numOfDontCareStates; - } } diff --git a/src/storm/storage/Scheduler.h b/src/storm/storage/Scheduler.h index e953e21b7..d6bdb9efd 100644 --- a/src/storm/storage/Scheduler.h +++ b/src/storm/storage/Scheduler.h @@ -62,12 +62,13 @@ namespace storm { /*! * Set the combination of model state and memoryStructure state to dontCare. - * Set an arbitrary choice an arbitrary choice if no choice exists. + * 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); + 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. @@ -152,8 +153,8 @@ namespace storm { bool printUndefinedChoices = false; std::vector<storm::storage::BitVector> reachableStates; - uint_fast64_t numOfUndefinedChoices; // Only consider reachable ones - std::vector<storm::storage::BitVector> dontCareStates; // Their choices are neither considered deterministic nor undefined + std::vector<storm::storage::BitVector> dontCareStates; + uint_fast64_t numOfUndefinedChoices; uint_fast64_t numOfDeterministicChoices; uint_fast64_t numOfDontCareStates; }; From 0713c5dccd2e2d7422c26bc47757134a14e79658 Mon Sep 17 00:00:00 2001 From: hannah <hannah.mertens@rwth-aachen.de> Date: Wed, 11 Aug 2021 17:08:05 +0200 Subject: [PATCH 151/172] skipDontCareStates-option for scheduler printing Conflicts: src/storm/storage/Scheduler.cpp src/storm/storage/Scheduler.h --- src/storm/api/export.h | 4 +-- src/storm/storage/Scheduler.cpp | 53 ++++++++++++++++++++------------- src/storm/storage/Scheduler.h | 9 ++---- 3 files changed, 37 insertions(+), 29 deletions(-) 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/storage/Scheduler.cpp b/src/storm/storage/Scheduler.cpp index c177747de..3d2c5a697 100644 --- a/src/storm/storage/Scheduler.cpp +++ b/src/storm/storage/Scheduler.cpp @@ -162,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(); @@ -214,6 +214,15 @@ 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; + } // Print choice info SchedulerChoice<ValueType> const& choice = schedulerChoices[memoryState][state]; @@ -254,44 +263,46 @@ namespace storm { stateString << "undefined."; } - // Print memory updates - if(!isMemorylessScheduler()) { - out << std::setw(widthOfStates) << ""; - 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 << ", "; + // 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()) <<")"; } - 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()) <<")"; } } stateString << std::endl; } - out << stateString.str(); - 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::json<storm::RationalNumber> output; @@ -303,7 +314,7 @@ namespace storm { for (uint_fast64_t memoryState = 0; memoryState < getNumberOfMemoryStates(); ++memoryState) { // Ignore dontCare states - if ((!isMemorylessScheduler()) && isDontCare(state, memoryState)) { + if (skipDontCareStates && isDontCare(state, memoryState)) { continue; } diff --git a/src/storm/storage/Scheduler.h b/src/storm/storage/Scheduler.h index d6bdb9efd..91681511f 100644 --- a/src/storm/storage/Scheduler.h +++ b/src/storm/storage/Scheduler.h @@ -135,18 +135,15 @@ namespace storm { * @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. */ - 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; From 133219f3c7a8300a343247e1801cdd1317f081c1 Mon Sep 17 00:00:00 2001 From: hannah <hannah.mertens@rwth-aachen.de> Date: Wed, 11 Aug 2021 18:12:03 +0200 Subject: [PATCH 152/172] using exact fractions in tests --- .../modelchecker/csl/CtmcCslModelCheckerTest.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/test/storm/modelchecker/csl/CtmcCslModelCheckerTest.cpp b/src/test/storm/modelchecker/csl/CtmcCslModelCheckerTest.cpp index f87fcae0c..d61224024 100755 --- a/src/test/storm/modelchecker/csl/CtmcCslModelCheckerTest.cpp +++ b/src/test/storm/modelchecker/csl/CtmcCslModelCheckerTest.cpp @@ -469,13 +469,13 @@ namespace { if (TypeParam::engine == CtmcEngine::PrismSparse || TypeParam::engine == CtmcEngine::JaniSparse || TypeParam::engine == CtmcEngine::JitSparse) { result = checker->check(this->env(), tasks[0]); - EXPECT_NEAR(this->parseNumber("0.93458777106264368"),this->getQuantitativeResultAtInitialState(model, result), this->precision()); + EXPECT_NEAR(this->parseNumber("6201111489217/6635130141055"),this->getQuantitativeResultAtInitialState(model, result), this->precision()); result = checker->check(this->env(), tasks[1]); - EXPECT_NEAR(this->parseNumber("0.878104234117144888"),this->getQuantitativeResultAtInitialState(model, result), this->precision()); + EXPECT_NEAR(this->parseNumber("182020967567825809324525759316263872210321582568114089975442470616306546970576799368889148054286400140039235238542379833694042687710639406937776190886135408090165698233430649593680647981952463347746024873495777857814386773710331804169990674529100754583695367774161875507044994661278270139591275881461260070117701448841596602041739425021618556458197240253807881255308059191194657575523127649292873946401600705744976789328068766287472574570803652848157332500632820598013756095085890607757713651215707639162546865863133892334758775858116620357147078085971884542677483086820336410289852315689173054718889915988181632722920483222289764504589120520736097022590652379/207288566091424649028720059396722579180935939731896317482437400340085729948319838320744587962528995351116735632610062501984165964160824743820968502984043393631527162621940700372437967239869902745684470791247218025011629936383683180819173695481357872127414459383695458034829702750095798077157671737142972112983783526417917830063407814131534204102733837172200651731758231462705370319722286895248244604663525334713443271108863630608264048954674658939565927125123713502020902415642152134952750797223075762309310186151383660810569853113110736677679624520398243456708277522978182665363672039087497825748539279661186260492946647251487454498033763681938956076478285935"),this->getQuantitativeResultAtInitialState(model, result), this->precision()); result = checker->check(this->env(), tasks[2]); - EXPECT_NEAR(this->parseNumber("0.934587771062649453"),this->getQuantitativeResultAtInitialState(model, result), this->precision()); + 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)); @@ -484,7 +484,7 @@ namespace { EXPECT_TRUE(this->getQualitativeResultAtInitialState(model, result)); result = checker->check(this->env(), tasks[5]); - EXPECT_NEAR(this->parseNumber("0.999979077232484914"),this->getQuantitativeResultAtInitialState(model, result), this->precision()); + EXPECT_NEAR(this->parseNumber("1202946881424160483813283754811216158529681407876794488562578158132042553611617599206276810240300260522066002609216899556806782592159369214025808794108439870476812421358247413140536419394633974952856222783873484713998841710951907938016323396243234904692402529616778550274612832580948290476037585840335145980480834541017213112991298412961159070334858462971422527038014973671594536802662479216742910965815165548764799425931464388642414276679044295398781842946801210199279858811082435065176154734735687314482662005774077569191240855183945543277103593833128730289929192543135438680962528094118605758445585995100073617/1202972050928710483231931881297292393407746913324566889646682839175998467151639078036566607429531813783366080734929392920005624456488274509559191073647430577878963431232759904608946782891839010213213206349818700590576273106941528872428420715245020013732520855670532992537989370310710476972890517512421272587449374385206819958406508377778081897385805121026698602418585526601660738490866798063415281360790178552717524631472037313126822801359812861351759990595156696407982588022635797417464794849389306521644962338915119549986021747121828809226061546105390273235103310319147341214480736689719855550298904337697187500"),this->getQuantitativeResultAtInitialState(model, result), this->precision()); } else { EXPECT_FALSE(checker->canHandle(tasks[0])); @@ -512,10 +512,10 @@ namespace { // 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("0.49999689056660507"),this->getQuantitativeResultAtInitialState(model, result), this->precision()); + EXPECT_NEAR(this->parseNumber("80400/160801"),this->getQuantitativeResultAtInitialState(model, result), this->precision()); result = checker->check(this->env(), tasks[1]); - EXPECT_NEAR(this->parseNumber("0.0074564831701838807"),this->getQuantitativeResultAtInitialState(model, result), this->precision()); + EXPECT_NEAR(this->parseNumber("601/80601"),this->getQuantitativeResultAtInitialState(model, result), this->precision()); } else { EXPECT_FALSE(checker->canHandle(tasks[0])); From 63a400ea5aed3ede6951a03487abb2813459c275 Mon Sep 17 00:00:00 2001 From: hannah <hannah.mertens@rwth-aachen.de> Date: Wed, 11 Aug 2021 20:42:44 +0200 Subject: [PATCH 153/172] added some documentation Conflicts: src/storm/storage/Scheduler.h --- src/storm/storage/Scheduler.h | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/storm/storage/Scheduler.h b/src/storm/storage/Scheduler.h index 91681511f..1a8322e81 100644 --- a/src/storm/storage/Scheduler.h +++ b/src/storm/storage/Scheduler.h @@ -62,6 +62,7 @@ namespace storm { /*! * 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. @@ -134,6 +135,7 @@ 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, bool skipDontCareStates = false) const; From 8a26af29f911c8b04ae68132ced01a686c49800b Mon Sep 17 00:00:00 2001 From: hannah <hannah.mertens@rwth-aachen.de> Date: Wed, 11 Aug 2021 21:01:29 +0200 Subject: [PATCH 154/172] allow HOA formulas for cslstar and pctlstar Conflicts: src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.cpp --- src/storm/logic/FragmentSpecification.cpp | 2 ++ .../SparseMarkovAutomatonCslModelChecker.cpp | 4 +-- .../prctl/SparseMdpPrctlModelChecker.cpp | 4 +-- .../csl/CtmcCslModelCheckerTest.cpp | 28 +++++++++++++++++++ .../MarkovAutomatonCslModelCheckerTest.cpp | 28 +++++++++++++++++++ .../prctl/mdp/MdpPrctlModelCheckerTest.cpp | 28 +++++++++++++++++++ 6 files changed, 90 insertions(+), 4 deletions(-) diff --git a/src/storm/logic/FragmentSpecification.cpp b/src/storm/logic/FragmentSpecification.cpp index 9e28eec3e..2272ef61f 100644 --- a/src/storm/logic/FragmentSpecification.cpp +++ b/src/storm/logic/FragmentSpecification.cpp @@ -52,6 +52,7 @@ namespace storm { pctlstar.setUnaryBooleanPathFormulasAllowed(true); pctlstar.setNestedOperatorsAllowed(true); pctlstar.setNestedPathFormulasAllowed(true); + pctlstar.setHOAPathFormulasAllowed(true); return pctlstar; } @@ -128,6 +129,7 @@ namespace storm { cslstar.setUnaryBooleanPathFormulasAllowed(true); cslstar.setNestedOperatorsAllowed(true); cslstar.setNestedPathFormulasAllowed(true); + cslstar.setHOAPathFormulasAllowed(true); return cslstar; } diff --git a/src/storm/modelchecker/csl/SparseMarkovAutomatonCslModelChecker.cpp b/src/storm/modelchecker/csl/SparseMarkovAutomatonCslModelChecker.cpp index 1874a1384..7afb03f38 100644 --- a/src/storm/modelchecker/csl/SparseMarkovAutomatonCslModelChecker.cpp +++ b/src/storm/modelchecker/csl/SparseMarkovAutomatonCslModelChecker.cpp @@ -132,8 +132,8 @@ namespace storm { 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, false> helper(this->getModel().getTransitionMatrix()); - storm::modelchecker::helper::setInformationFromCheckTaskDeterministic(helper, checkTask, this->getModel()); + 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); diff --git a/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.cpp b/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.cpp index 7ce739537..6551b61fe 100644 --- a/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.cpp +++ b/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.cpp @@ -160,8 +160,8 @@ namespace storm { 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, false> helper(this->getModel().getTransitionMatrix()); - storm::modelchecker::helper::setInformationFromCheckTaskDeterministic(helper, checkTask, this->getModel()); + 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); diff --git a/src/test/storm/modelchecker/csl/CtmcCslModelCheckerTest.cpp b/src/test/storm/modelchecker/csl/CtmcCslModelCheckerTest.cpp index d61224024..e13d0ebb1 100755 --- a/src/test/storm/modelchecker/csl/CtmcCslModelCheckerTest.cpp +++ b/src/test/storm/modelchecker/csl/CtmcCslModelCheckerTest.cpp @@ -525,4 +525,32 @@ namespace { #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 58359c41a..3d02af1c2 100755 --- a/src/test/storm/modelchecker/csl/MarkovAutomatonCslModelCheckerTest.cpp +++ b/src/test/storm/modelchecker/csl/MarkovAutomatonCslModelCheckerTest.cpp @@ -387,4 +387,32 @@ namespace { 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/mdp/MdpPrctlModelCheckerTest.cpp b/src/test/storm/modelchecker/prctl/mdp/MdpPrctlModelCheckerTest.cpp index 271c59321..82f25b7c0 100755 --- a/src/test/storm/modelchecker/prctl/mdp/MdpPrctlModelCheckerTest.cpp +++ b/src/test/storm/modelchecker/prctl/mdp/MdpPrctlModelCheckerTest.cpp @@ -787,5 +787,33 @@ namespace { } + 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])); + } + + } + } From 6af47eaadcea0cb7d40087d7c0339f16d931ed3b Mon Sep 17 00:00:00 2001 From: hannah <hannah.mertens@rwth-aachen.de> Date: Thu, 12 Aug 2021 12:45:59 +0200 Subject: [PATCH 155/172] new class for scheduler computation during LTL-MC --- .../helper/ltl/SparseLTLHelper.cpp | 296 +---------------- .../modelchecker/helper/ltl/SparseLTLHelper.h | 65 +--- .../ltl/internal/SparseLTLSchedulerHelper.cpp | 308 ++++++++++++++++++ .../ltl/internal/SparseLTLSchedulerHelper.h | 102 ++++++ 4 files changed, 445 insertions(+), 326 deletions(-) create mode 100644 src/storm/modelchecker/helper/ltl/internal/SparseLTLSchedulerHelper.cpp create mode 100644 src/storm/modelchecker/helper/ltl/internal/SparseLTLSchedulerHelper.h diff --git a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp index 151e3892e..2c01f8c4b 100644 --- a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp +++ b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp @@ -12,10 +12,8 @@ #include "storm/storage/StronglyConnectedComponentDecomposition.h" #include "storm/storage/MaximalEndComponentDecomposition.h" -#include "storm/storage/memorystructure/MemoryStructure.h" -#include "storm/storage/memorystructure/MemoryStructureBuilder.h" #include "storm/solver/SolveGoal.h" -#include "storm/utility/graph.h" + #include "storm/exceptions/InvalidPropertyException.h" @@ -25,90 +23,19 @@ namespace storm { namespace helper { template <typename ValueType, bool Nondeterministic> - SparseLTLHelper<ValueType, Nondeterministic>::SparseLTLHelper(storm::storage::SparseMatrix<ValueType> const& transitionMatrix) : _transitionMatrix(transitionMatrix){ + SparseLTLHelper<ValueType, Nondeterministic>::SparseLTLHelper(storm::storage::SparseMatrix<ValueType> const& transitionMatrix) : _transitionMatrix(transitionMatrix) { // Intentionally left empty. } - template <typename ValueType, bool Nondeterministic> - uint_fast64_t SparseLTLHelper<ValueType, Nondeterministic>::SparseLTLHelper::getMemoryState(uint_fast64_t daState, uint_fast64_t infSet) { - return (daState * (_infSets.get().size()+1))+ infSet; - } - 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."); - // If Pmax(phi) = 0 or Pmin(phi) = 1, we return a memoryless scheduler with arbitrary choices - if (_randomScheduler) { - storm::storage::Scheduler<ValueType> scheduler(this->_transitionMatrix.getRowGroupCount()); - for (storm::storage::sparse::state_type state = 0; state < this->_transitionMatrix.getRowGroupCount(); ++state) { - scheduler.setChoice(0, state); - - } - return scheduler; - } - - // Otherwise, we compute a scheduler with memory. - STORM_LOG_ASSERT(this->_producedChoices.is_initialized(), "Trying to extract the produced scheduler but none is available. Was there a computation call before?"); - STORM_LOG_ASSERT(this->_memoryTransitions.is_initialized(), "Trying to extract the DA transition structure but none is available. Was there a computation call before?"); - STORM_LOG_ASSERT(this->_memoryInitialStates.is_initialized(), "Trying to extract the initial states of the DA but there are none available. Was there a computation call before?"); - STORM_LOG_ASSERT(this->_dontCareStates.is_initialized(), "Trying to extract the Scheduler-dontCare states but there are none available. Was there a computation call before?"); - - - // 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.get().size(), model, this->hasRelevantStates()); - - // Build the transitions between the memory states: startState to goalState using modelStates (transitionVector). - for (storm::storage::sparse::state_type startState = 0; startState < this->_memoryTransitions.get().size(); ++startState) { - for (storm::storage::sparse::state_type goalState = 0; goalState < this->_memoryTransitions.get().size(); ++goalState) { - // Bitvector that represents modelStates the model states that trigger this transition. - memoryBuilder.setTransition(startState, goalState, this->_memoryTransitions.get()[startState][goalState]); - } - } - - // InitialMemoryStates: Assign an initial memory state model states - if (this->hasRelevantStates()) { - // Only consider initial model states - for (uint_fast64_t modelState : model.getInitialStates()) { - memoryBuilder.setInitialMemoryState(modelState, this->_memoryInitialStates.get()[modelState]); - } - } else { - // All model states are relevant - for (uint_fast64_t modelState = 0; modelState < model.getNumberOfStates(); ++modelState) { - memoryBuilder.setInitialMemoryState(modelState, this->_memoryInitialStates.get()[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(this->_transitionMatrix.getRowGroupCount(), memoryStructure); - - // Use choices in the product model to create a choice based on model state and memory state - for (const auto &choice : this->_producedChoices.get()) { - // <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.get()[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.get().size(); ++memoryState) { - for (auto state : this->_dontCareStates.get()[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; + 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) @@ -156,11 +83,6 @@ namespace storm { std::size_t accMECs = 0; std::size_t allMECs = 0; - if (this->isProduceSchedulerSet()) { - _infSets.emplace(); - _accInfSets.emplace(product->getProductModel().getNumberOfStates(), boost::none); - _producedChoices.emplace(); - } 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. @@ -238,82 +160,9 @@ namespace storm { } if (this->isProduceSchedulerSet()) { + // save choices for states that weren't assigned to any other MEC yet. + this->_schedulerHelper.get().saveProductEcChoices(acceptance, mec, conjunction, product); - // Save all states contained in this MEC - storm::storage::BitVector mecStates(transitionMatrix.getRowGroupCount(), false); - for (auto const &stateChoicePair : mec) { - mecStates.set(stateChoicePair.first); - } - - // We know the MEC satisfied the conjunction: Save InfSets. - std::set<uint_fast64_t> infSetIds; - for (auto const& literal : conjunction) { - storm::storage::BitVector infSet; - if (literal->isTRUE()) { - // All states - infSet = storm::storage::BitVector(transitionMatrix.getRowGroupCount(), true); - - } else if (literal->isAtom()) { - const cpphoafparser::AtomAcceptance &atom = literal->getAtom(); - if (atom.getType() == cpphoafparser::AtomAcceptance::TEMPORAL_INF) { - if (atom.isNegated()) { - infSet = ~acceptance.getAcceptanceSet(atom.getAcceptanceSet()); - - } else { - infSet = acceptance.getAcceptanceSet(atom.getAcceptanceSet()); - } - } - else if (atom.getType() == cpphoafparser::AtomAcceptance::TEMPORAL_FIN) { - // If there are FinSets in the conjunction we use the InfSet containing all states in this MEC - infSet = mecStates; - } - } - - // Save new InfSets - if (infSet.size() > 0) { - auto it = std::find(_infSets.get().begin(), _infSets.get().end(), infSet); - if (it == _infSets.get().end()) { - infSetIds.insert(_infSets.get().size()); - _infSets.get().emplace_back(infSet); - } else { - // save ID for accCond of the MEC states - infSetIds.insert(distance(_infSets.get().begin(), it)); - } - } - } - - // Save the InfSets into the _accInfSets for states in this MEC, but only if there weren't assigned to any other MEC yet. - storm::storage::BitVector newMecStates(transitionMatrix.getRowGroupCount(), false); - for (auto const &stateChoicePair : mec) { - if (_accInfSets.get()[stateChoicePair.first] == boost::none) { - // state wasn't assigned to any other MEC yet. - _accInfSets.get()[stateChoicePair.first].emplace(infSetIds); - newMecStates.set(stateChoicePair.first); - - } - } - - - // Define scheduler choices for the states in this MEC (that are not in any other MEC) - for (uint_fast64_t id : infSetIds) { - // Scheduler that satisfies the MEC acceptance condition (visit each InfSet inf often, or switch to scheduler of another MEC) - storm::storage::Scheduler<ValueType> mecScheduler(transitionMatrix.getRowGroupCount()); - - // States not in InfSet: Compute a scheduler that, with prob=1, reaches the infSet via mecStates starting from states that are not yet in other MEC - storm::utility::graph::computeSchedulerProb1E<ValueType>(newMecStates, transitionMatrix, backwardTransitions, mecStates, _infSets.get()[id] & mecStates, mecScheduler); - - // States that already reached the InfSet - for (auto pState : (newMecStates & _infSets.get()[id])) { - // Prob1E sets an arbitrary choice for the psi states, but we want to stay in this accepting MEC. - mecScheduler.setChoice(*mec.getChoicesForState(pState).begin() - transitionMatrix.getRowGroupIndices()[pState], pState); - } - - // Extract scheduler choices (only for states that are already assigned a scheduler, i.e are in another MEC) - for (auto pState : newMecStates) { - // We want to reach the InfSet, save choice: <s, q, InfSetID> ---> choice - this->_producedChoices.get().insert({std::make_tuple(product->getModelState(pState), product->getAutomatonState(pState), id), mecScheduler.getChoice(pState)}); - } - } } } @@ -345,125 +194,6 @@ namespace storm { return acceptingStates; } - template <typename ValueType, bool Nondeterministic> - void SparseLTLHelper<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_LOG_ASSERT(this->_producedChoices.is_initialized(), "Trying to extract the produced scheduler but none is available. Was there a computation call before?"); - STORM_LOG_ASSERT(this->_infSets.is_initialized(), "Was there a computation call before?"); - STORM_LOG_ASSERT(this->_accInfSets.is_initialized(), "Was there a computation call before?"); - - // Compute size of the resulting memory structure: A state <q, infSet> is encoded as (q* (|infSets|+1))+ |infSet| - uint64 numMemoryStates = (numDaStates) * (_infSets.get().size()+1); //+1 for states outside accECs - _dontCareStates.emplace(numMemoryStates, storm::storage::BitVector(this->_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 < this->_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.get().size()+1; ++infSet) { - _dontCareStates.get()[getMemoryState(automatonState, infSet)].set(modelState, true); - } - } else { - auto pState = product->getProductStateIndex(modelState, automatonState); - if (acceptingProductStates.get(pState)) { - // For states in accepting ECs set the missing MEC-scheduler combinations are "dontCare", they are not reachable using the scheduler choices. //TODO is this correct? - for (uint_fast64_t infSet = 0; infSet < _infSets.get().size()+1; ++infSet) { - if (_producedChoices.get().find(std::make_tuple(product->getModelState(pState), product->getAutomatonState(pState), infSet)) == _producedChoices.get().end() ) { - _dontCareStates.get()[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 "last" copy of the DA (_infSets.get().size()). - this->_accInfSets.get()[pState] = std::set<uint_fast64_t>({_infSets.get().size()}); - if (reachScheduler->isDontCare(pState)) { - // Mark the maybe States of the untilProbability scheduler as "dontCare" - _dontCareStates.get()[getMemoryState(product->getAutomatonState(pState), _infSets.get().size())].set(product->getModelState(pState), true); - } else { - // Set choice For non-accepting states that are not in any accepting EC - this->_producedChoices.get().insert({std::make_tuple(product->getModelState(pState),product->getAutomatonState(pState),_infSets.get().size()),reachScheduler->getChoice(pState)}); - }; - // All other InfSet combinations are unreachable (dontCare) - for (uint_fast64_t infSet = 0; infSet < _infSets.get().size(); ++infSet) { - _dontCareStates.get()[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.emplace(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)) { - // Add the modelState to one outgoing transition of all states of the form <automatonFrom, InfSet> (Inf=lenInfSet equals not in MEC) - // For non-accepting states that are not in any accepting EC we use the 'last' copy of the DA - // and for the accepting states we jump through copies of the DA wrt. the infinity sets. - for (uint_fast64_t infSet = 0; infSet < _infSets.get().size()+1; ++infSet) { - // Check if we need to switch the acceptance condition - STORM_LOG_ASSERT(_accInfSets.get()[product->getProductStateIndex(modelState, automatonTo)] != boost::none, "The list of InfSets for the product state <" <<modelState<< ", " << automatonTo<<"> is undefined."); - - if (_accInfSets.get()[product->getProductStateIndex(modelState, automatonTo)].get().count(infSet) == 0) { - // the state is is in a different accepting MEC with a different accepting conjunction of InfSets. - auto newInfSet = _accInfSets.get()[product->getProductStateIndex(modelState, automatonTo)].get().begin(); - _memoryTransitions.get()[getMemoryState(automatonFrom, infSet)][getMemoryState(automatonTo, *newInfSet)].set(modelState); - - } else { - // Continue looking for any accepting EC (if we haven't reached one yet) or stay in the corresponding accepting EC, test whether we have reached the next infSet. - if (infSet == _infSets.get().size() || !(_infSets.get()[infSet].get(product->getProductStateIndex(modelState, automatonTo)))) { - // <modelState, automatonTo> is not in any accepting EC or does not satisfy the InfSet, we stay there. - // Add modelState to the transition from <automatonFrom, InfSet> to <automatonTo, InfSet> - _memoryTransitions.get()[getMemoryState(automatonFrom, infSet)][getMemoryState(automatonTo, infSet)].set(modelState); - - } else { - STORM_LOG_ASSERT(_accInfSets.get()[product->getProductStateIndex(modelState, automatonTo)] != boost::none, "The list of InfSets for the product state <" <<modelState<< ", " << automatonTo<<"> is undefined."); - // <modelState, automatonTo> satisfies the InfSet, find the next one. - auto nextInfSet = std::find(_accInfSets.get()[product->getProductStateIndex(modelState, automatonTo)].get().begin(), _accInfSets.get()[product->getProductStateIndex(modelState, automatonTo)].get().end(), infSet); - STORM_LOG_ASSERT(nextInfSet != _accInfSets.get()[product->getProductStateIndex(modelState, automatonTo)].get().end(), "The list of InfSets for the product state <" <<modelState<< ", " << automatonTo<<"> does not contain the infSet " << infSet); - nextInfSet++; - if (nextInfSet == _accInfSets.get()[product->getProductStateIndex(modelState, automatonTo)].get().end()) { - // Start again. - nextInfSet = _accInfSets.get()[product->getProductStateIndex(modelState, automatonTo)].get().begin(); - } - // Add modelState to the transition from <automatonFrom <mec, InfSet>> to <automatonTo, <mec, NextInfSet>>. - _memoryTransitions.get()[getMemoryState(automatonFrom, infSet)][getMemoryState(automatonTo, *nextInfSet)].set(modelState); - } - } - } - } - - } - } - // Finished creation of transitions. - - // Find initial memory states - this->_memoryInitialStates.emplace(); - this->_memoryInitialStates->resize(this->_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."); - if (acceptingProductStates[product->getProductStateIndex(modelState, automatonState)]) { - STORM_LOG_ASSERT(_accInfSets.get()[product->getProductStateIndex(modelState, automatonState)] != boost::none, "The list of InfSets for the product state <" <<modelState<< ", " << automatonState<<"> is undefined."); - // If <s, q> is an accepting state start in the first InfSet of <s, q>. - auto infSet = _accInfSets.get()[product->getProductStateIndex(modelState, automatonState)].get().begin(); - _memoryInitialStates.get()[modelState] = getMemoryState(automatonState, *infSet); - - } else { - _memoryInitialStates.get()[modelState] = getMemoryState(automatonState, _infSets.get().size()); - } - - } - - } 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) { @@ -497,6 +227,12 @@ namespace storm { 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) { @@ -511,8 +247,10 @@ namespace storm { 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>()); - this->_randomScheduler = true; return numericResult; } @@ -546,7 +284,7 @@ namespace storm { prodNumericResult = std::move(prodCheckResult.values); if (this->isProduceSchedulerSet()) { - prepareScheduler(da.getNumberOfStates(), acceptingStates, std::move(prodCheckResult.scheduler), productBuilder, product, statesOfInterest); + this->_schedulerHelper.get().prepareScheduler(da.getNumberOfStates(), acceptingStates, std::move(prodCheckResult.scheduler), productBuilder, product, statesOfInterest, this->_transitionMatrix); } } else { diff --git a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h index 5a46b4bc9..ff19e475c 100644 --- a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h +++ b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.h @@ -1,7 +1,8 @@ #include "storm/modelchecker/helper/SingleValueModelCheckerHelper.h" +#include "storm/modelchecker/helper/ltl/internal/SparseLTLSchedulerHelper.h" + #include "storm/storage/SparseMatrix.h" -#include "storm/storage/Scheduler.h" #include "storm/models/sparse/Dtmc.h" #include "storm/models/sparse/Mdp.h" #include "storm/transformer/DAProductBuilder.h" @@ -25,7 +26,7 @@ namespace storm { /*! * Helper class for LTL model checking * @tparam ValueType the type a value can have - * @tparam Nondeterministic true if there is nondeterminism in the Model (MDP) + * @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> { @@ -35,30 +36,28 @@ namespace storm { typedef std::function<storm::storage::BitVector(storm::logic::Formula const&)> CheckFormulaCallback; /*! - * The type of the product automaton (DTMC or MDP) that is used during the computation. + * 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 the transition matrix of the model - * @param the number of states of the model + * @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 the model + * @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 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 - * @param the atomic propositions occuring in the formula together with the satisfaction sets + * @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); @@ -73,9 +72,8 @@ namespace storm { /*! * Computes the (maximizing) probabilities for the constructed DA product - * @param the DA to build the product with - * @param the atomic propositions and satisfaction sets - * @param a flag indicating whether qualitative model checking is performed + * @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); @@ -97,50 +95,23 @@ namespace storm { * 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 the acceptance condition (in DNF) - * @param the transition matrix of the model - * @param the reversed transition relation + * @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 the acceptance condition - * @param the transition matrix of the model + * @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); - /** - * Helper function, extracts scheduler choices and creates the memory structure for the LTL-Scheduler. - * @param number of DA-states - * @param states in accepting end components of the model-DA product - * @param the scheduler ensuring to reach some acceptingState, defined on the model-DA product - * @param the product builder - * @param the model-DA product - * @param relevant states 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); - - /** - * Helper function, 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 DA-state - * @param infSet ID - */ - uint_fast64_t getMemoryState(uint_fast64_t daState, uint_fast64_t infSet); storm::storage::SparseMatrix<ValueType> const& _transitionMatrix; - - // scheduler - bool _randomScheduler = false; - boost::optional<std::map <std::tuple<uint_fast64_t, uint_fast64_t, uint_fast64_t>, storm::storage::SchedulerChoice<ValueType>>> _producedChoices; // <s, q, len(_infSets)> ---> ReachChoice and <s, q, InfSet> ---> MecChoice - boost::optional<std::vector<storm::storage::BitVector>> _dontCareStates; // memory state combinations that are never visited - - boost::optional<std::vector<storm::storage::BitVector>> _infSets; // Save the InfSets of the Acceptance condition. - boost::optional<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 - boost::optional<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). - boost::optional<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) + + boost::optional<storm::modelchecker::helper::internal::SparseLTLSchedulerHelper<ValueType, Nondeterministic>> _schedulerHelper; }; } 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..03db6d7ba --- /dev/null +++ b/src/storm/modelchecker/helper/ltl/internal/SparseLTLSchedulerHelper.cpp @@ -0,0 +1,308 @@ +#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> + SparseLTLSchedulerHelper<ValueType, Nondeterministic>::SparseLTLSchedulerHelper(uint_fast64_t numProductStates) : _randomScheduler(false), _producedChoices(), _infSets(), _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()+1))+ 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 + storm::storage::BitVector mecStates(product->getProductModel().getNumberOfStates(), false); + for (auto const &stateChoicePair : mec) { + mecStates.set(stateChoicePair.first); + } + + // We know the MEC satisfied the conjunction: Save InfSets. + std::set<uint_fast64_t> infSetIds; + for (auto const& literal : conjunction) { + storm::storage::BitVector infSet; + if (literal->isTRUE()) { + // All states + infSet = storm::storage::BitVector(product->getProductModel().getNumberOfStates(), true); + + } else if (literal->isAtom()) { + const cpphoafparser::AtomAcceptance &atom = literal->getAtom(); + if (atom.getType() == cpphoafparser::AtomAcceptance::TEMPORAL_INF) { + if (atom.isNegated()) { + infSet = ~acceptance.getAcceptanceSet(atom.getAcceptanceSet()); + + } else { + infSet = acceptance.getAcceptanceSet(atom.getAcceptanceSet()); + } + } + else if (atom.getType() == cpphoafparser::AtomAcceptance::TEMPORAL_FIN) { + // If there are FinSets in the conjunction we use the InfSet containing all states in this MEC + infSet = mecStates; + } + } + + // Save new InfSets + if (infSet.size() > 0) { + auto it = std::find(_infSets.begin(), _infSets.end(), infSet); + if (it == _infSets.end()) { + infSetIds.insert(_infSets.size()); + _infSets.emplace_back(infSet); + } else { + // save ID for accCond of the MEC states + infSetIds.insert(distance(_infSets.begin(), it)); + } + } + } + + // Save the InfSets into the _accInfSets for states in this MEC, but only if there weren't assigned to any other MEC yet. + storm::storage::BitVector newMecStates(product->getProductModel().getNumberOfStates(), false); + for (auto const &stateChoicePair : mec) { + + if (_accInfSets[stateChoicePair.first] == boost::none) { + // state wasn't assigned to any other MEC yet. + _accInfSets[stateChoicePair.first].emplace(infSetIds); + newMecStates.set(stateChoicePair.first); + } + } + + + // Define scheduler choices for the states in this MEC (that are not in any other MEC) + for (uint_fast64_t id : infSetIds) { + // Scheduler that satisfies the MEC acceptance condition (visit each InfSet inf often, or switch to scheduler of another MEC) + storm::storage::Scheduler<ValueType> mecScheduler(product->getProductModel().getNumberOfStates()); + + // States not in InfSet: Compute a scheduler that, with prob=1, reaches the infSet via mecStates starting from states that are not yet in other MEC + storm::utility::graph::computeSchedulerProb1E<ValueType>(newMecStates, product->getProductModel().getTransitionMatrix(), product->getProductModel().getBackwardTransitions(), mecStates, _infSets[id] & mecStates, mecScheduler); + + // States that already reached the InfSet + for (auto pState : (newMecStates & _infSets[id])) { + // 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 (only for states that are already assigned a scheduler, i.e are in another MEC) + for (auto pState : newMecStates) { + // 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) { + // Compute size of the resulting memory structure: A state <q, infSet> is encoded as (q* (|infSets|+1))+ |infSet| + uint64 numMemoryStates = (numDaStates) * (_infSets.size()+1); //+1 for states outside accECs + _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()+1; ++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 missing MEC-scheduler combinations are "dontCare", they are not reachable using the scheduler choices. + for (uint_fast64_t infSet = 0; infSet < _infSets.size()+1; ++infSet) { + if (_producedChoices.find(std::make_tuple(product->getModelState(pState), product->getAutomatonState(pState), infSet)) == _producedChoices.end() ) { + _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 "last" copy of the DA (_infSets.get().size()). + this->_accInfSets[pState] = std::set<uint_fast64_t>({_infSets.size()}); + if (reachScheduler->isDontCare(pState)) { + // Mark the maybe States of the untilProbability scheduler as "dontCare" + _dontCareStates[getMemoryState(product->getAutomatonState(pState), _infSets.size())].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),_infSets.size()),reachScheduler->getChoice(pState)}); + }; + // All other InfSet combinations are unreachable (dontCare) + for (uint_fast64_t infSet = 0; 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)) { + // Add the modelState to one outgoing transition of all states of the form <automatonFrom, InfSet> (Inf=lenInfSet equals not in MEC) + // For non-accepting states that are not in any accepting EC we use the 'last' copy of the DA + // and for the accepting states we jump through copies of the DA wrt. the infinity sets. + for (uint_fast64_t infSet = 0; infSet < _infSets.size()+1; ++infSet) { + // Check if we need to switch the acceptance condition + STORM_LOG_ASSERT(_accInfSets[product->getProductStateIndex(modelState, automatonTo)] != boost::none, "The list of InfSets for the product state <" <<modelState<< ", " << automatonTo<<"> is undefined."); + + if (_accInfSets[product->getProductStateIndex(modelState, automatonTo)].get().count(infSet) == 0) { + // the state is is in a different accepting MEC with a different accepting conjunction of InfSets. + auto newInfSet = _accInfSets[product->getProductStateIndex(modelState, automatonTo)].get().begin(); + _memoryTransitions[getMemoryState(automatonFrom, infSet)][getMemoryState(automatonTo, *newInfSet)].set(modelState); + + } else { + // Continue looking for any accepting EC (if we haven't reached one yet) or stay in the corresponding accepting EC, test whether we have reached the next infSet. + if (infSet == _infSets.size() || !(_infSets[infSet].get(product->getProductStateIndex(modelState, automatonTo)))) { + // <modelState, automatonTo> is not in any accepting EC or does not satisfy the InfSet, we stay there. + // Add modelState to the transition from <automatonFrom, InfSet> to <automatonTo, InfSet> + _memoryTransitions[getMemoryState(automatonFrom, infSet)][getMemoryState(automatonTo, infSet)].set(modelState); + + } else { + STORM_LOG_ASSERT(_accInfSets[product->getProductStateIndex(modelState, automatonTo)] != boost::none, "The list of InfSets for the product state <" <<modelState<< ", " << automatonTo<<"> is undefined."); + // <modelState, automatonTo> satisfies the InfSet, find the next one. + auto nextInfSet = std::find(_accInfSets[product->getProductStateIndex(modelState, automatonTo)].get().begin(), _accInfSets[product->getProductStateIndex(modelState, automatonTo)].get().end(), infSet); + STORM_LOG_ASSERT(nextInfSet != _accInfSets[product->getProductStateIndex(modelState, automatonTo)].get().end(), "The list of InfSets for the product state <" <<modelState<< ", " << automatonTo<<"> does not contain the infSet " << infSet); + nextInfSet++; + if (nextInfSet == _accInfSets[product->getProductStateIndex(modelState, automatonTo)].get().end()) { + // Start again. + nextInfSet = _accInfSets[product->getProductStateIndex(modelState, automatonTo)].get().begin(); + } + // Add modelState to the transition from <automatonFrom <mec, InfSet>> to <automatonTo, <mec, NextInfSet>>. + _memoryTransitions[getMemoryState(automatonFrom, infSet)][getMemoryState(automatonTo, *nextInfSet)].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."); + if (acceptingProductStates[product->getProductStateIndex(modelState, automatonState)]) { + STORM_LOG_ASSERT(_accInfSets[product->getProductStateIndex(modelState, automatonState)] != boost::none, "The list of InfSets for the product state <" <<modelState<< ", " << automatonState<<"> is undefined."); + // If <s, q> is an accepting state start in the first InfSet of <s, q>. + auto infSet = _accInfSets[product->getProductStateIndex(modelState, automatonState)].get().begin(); + _memoryInitialStates[modelState] = getMemoryState(automatonState, *infSet); + + } else { + _memoryInitialStates[modelState] = getMemoryState(automatonState, _infSets.size()); + } + + } + + } + + + 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..89f5075c0 --- /dev/null +++ b/src/storm/modelchecker/helper/ltl/internal/SparseLTLSchedulerHelper.h @@ -0,0 +1,102 @@ +#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, + * but only set new choices for states that are not in any other EC yet. + * 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. + * + * @param acceptance the acceptance condition (in DNF) + * @param mec the accepting end component + * @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. + * + * @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); + + + bool _randomScheduler; + std::map <std::tuple<uint_fast64_t, uint_fast64_t, uint_fast64_t>, storm::storage::SchedulerChoice<ValueType>> _producedChoices; // <s, q, len(_infSets)> -> ReachChoice and <s, q, InfSet> -> MecChoice + std::vector<storm::storage::BitVector> _dontCareStates; // memorySate-modelState combinations that are never visited + + std::vector<storm::storage::BitVector> _infSets; // Save the InfSets of the acceptance condition. The BitVector contains the product model states that are contained in the infSet + 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 From 5fe81952cb56538346fd811f43ae7a23d752a54e Mon Sep 17 00:00:00 2001 From: Tim Quatmann <tim.quatmann@cs.rwth-aachen.de> Date: Fri, 13 Aug 2021 15:33:54 +0200 Subject: [PATCH 156/172] Removed an outdated TODO comment. --- src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp index 2c01f8c4b..677695e6a 100644 --- a/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp +++ b/src/storm/modelchecker/helper/ltl/SparseLTLHelper.cpp @@ -237,7 +237,7 @@ namespace storm { 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); //TODO product is only needed for ->getModelState(pState) (remove arg) + acceptingStates = computeAcceptingECs(*product->getAcceptance(), product->getProductModel().getTransitionMatrix(), product->getProductModel().getBackwardTransitions(), product); } else { STORM_LOG_INFO("Computing BSCCs and checking for acceptance..."); From 1e60fa79144ea0df290efdaeb81c79a312413c53 Mon Sep 17 00:00:00 2001 From: Tim Quatmann <tim.quatmann@cs.rwth-aachen.de> Date: Fri, 13 Aug 2021 15:42:34 +0200 Subject: [PATCH 157/172] LTLSchedulerHelper: make handling of overlapping ECs more explicit and reduced the amount of memory states. --- .../ltl/internal/SparseLTLSchedulerHelper.cpp | 273 ++++++++++-------- .../ltl/internal/SparseLTLSchedulerHelper.h | 50 +++- 2 files changed, 193 insertions(+), 130 deletions(-) diff --git a/src/storm/modelchecker/helper/ltl/internal/SparseLTLSchedulerHelper.cpp b/src/storm/modelchecker/helper/ltl/internal/SparseLTLSchedulerHelper.cpp index 03db6d7ba..b4a599634 100644 --- a/src/storm/modelchecker/helper/ltl/internal/SparseLTLSchedulerHelper.cpp +++ b/src/storm/modelchecker/helper/ltl/internal/SparseLTLSchedulerHelper.cpp @@ -12,14 +12,38 @@ namespace storm { namespace internal { template<typename ValueType, bool Nondeterministic> - SparseLTLSchedulerHelper<ValueType, Nondeterministic>::SparseLTLSchedulerHelper(uint_fast64_t numProductStates) : _randomScheduler(false), _producedChoices(), _infSets(), _accInfSets(numProductStates, boost::none) { + 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()+1))+ infSet; + return (daState * _infSets.size())+ infSet; } template<typename ValueType, bool Nondeterministic> @@ -29,79 +53,94 @@ namespace storm { 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 + // 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) { - mecStates.set(stateChoicePair.first); + if (_accInfSets[stateChoicePair.first].is_initialized()) { + overlapStates.resize(product->getProductModel().getNumberOfStates(), false); + overlapStates.set(stateChoicePair.first); + } else { + mecStates.set(stateChoicePair.first); + } } - - // We know the MEC satisfied the conjunction: Save InfSets. - std::set<uint_fast64_t> infSetIds; - for (auto const& literal : conjunction) { - storm::storage::BitVector infSet; - if (literal->isTRUE()) { - // All states - infSet = storm::storage::BitVector(product->getProductModel().getNumberOfStates(), true); - - } else if (literal->isAtom()) { - const cpphoafparser::AtomAcceptance &atom = literal->getAtom(); - if (atom.getType() == cpphoafparser::AtomAcceptance::TEMPORAL_INF) { - if (atom.isNegated()) { - infSet = ~acceptance.getAcceptanceSet(atom.getAcceptanceSet()); - - } else { - infSet = acceptance.getAcceptanceSet(atom.getAcceptanceSet()); - } + + 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}); } - else if (atom.getType() == cpphoafparser::AtomAcceptance::TEMPORAL_FIN) { - // If there are FinSets in the conjunction we use the InfSet containing all states in this MEC - infSet = mecStates; + + // 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)}); } } - - // Save new InfSets - if (infSet.size() > 0) { - auto it = std::find(_infSets.begin(), _infSets.end(), infSet); - if (it == _infSets.end()) { - infSetIds.insert(_infSets.size()); - _infSets.emplace_back(infSet); - } else { - // save ID for accCond of the MEC states - infSetIds.insert(distance(_infSets.begin(), it)); + } 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. } - } - - // Save the InfSets into the _accInfSets for states in this MEC, but only if there weren't assigned to any other MEC yet. - storm::storage::BitVector newMecStates(product->getProductModel().getNumberOfStates(), false); - for (auto const &stateChoicePair : mec) { - - if (_accInfSets[stateChoicePair.first] == boost::none) { - // state wasn't assigned to any other MEC yet. - _accInfSets[stateChoicePair.first].emplace(infSetIds); - newMecStates.set(stateChoicePair.first); + 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))); } - } - - - // Define scheduler choices for the states in this MEC (that are not in any other MEC) - for (uint_fast64_t id : infSetIds) { - // Scheduler that satisfies the MEC acceptance condition (visit each InfSet inf often, or switch to scheduler of another MEC) - storm::storage::Scheduler<ValueType> mecScheduler(product->getProductModel().getNumberOfStates()); - - // States not in InfSet: Compute a scheduler that, with prob=1, reaches the infSet via mecStates starting from states that are not yet in other MEC - storm::utility::graph::computeSchedulerProb1E<ValueType>(newMecStates, product->getProductModel().getTransitionMatrix(), product->getProductModel().getBackwardTransitions(), mecStates, _infSets[id] & mecStates, mecScheduler); - - // States that already reached the InfSet - for (auto pState : (newMecStates & _infSets[id])) { - // 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); + + // 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); } - - // Extract scheduler choices (only for states that are already assigned a scheduler, i.e are in another MEC) - for (auto pState : newMecStates) { - // 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)}); + + // 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)}); + } } } } @@ -109,8 +148,10 @@ namespace storm { 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) { - // Compute size of the resulting memory structure: A state <q, infSet> is encoded as (q* (|infSets|+1))+ |infSet| - uint64 numMemoryStates = (numDaStates) * (_infSets.size()+1); //+1 for states outside accECs + 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" @@ -119,40 +160,39 @@ namespace storm { 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()+1; ++infSet) { + 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 missing MEC-scheduler combinations are "dontCare", they are not reachable using the scheduler choices. - for (uint_fast64_t infSet = 0; infSet < _infSets.size()+1; ++infSet) { - if (_producedChoices.find(std::make_tuple(product->getModelState(pState), product->getAutomatonState(pState), infSet)) == _producedChoices.end() ) { + // 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 "last" copy of the DA (_infSets.get().size()). - this->_accInfSets[pState] = std::set<uint_fast64_t>({_infSets.size()}); + // 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), _infSets.size())].set(product->getModelState(pState), true); + _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),_infSets.size()),reachScheduler->getChoice(pState)}); + this->_producedChoices.insert({std::make_tuple(product->getModelState(pState), product->getAutomatonState(pState), DEFAULT_INFSET), reachScheduler->getChoice(pState)}); }; // All other InfSet combinations are unreachable (dontCare) - for (uint_fast64_t infSet = 0; infSet < _infSets.size(); ++infSet) { + 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. @@ -162,42 +202,37 @@ namespace storm { uint_fast64_t automatonTo = productBuilder.getSuccessor(automatonFrom, modelState); if (product->isValidProductState(modelState, automatonTo)) { - // Add the modelState to one outgoing transition of all states of the form <automatonFrom, InfSet> (Inf=lenInfSet equals not in MEC) - // For non-accepting states that are not in any accepting EC we use the 'last' copy of the DA - // and for the accepting states we jump through copies of the DA wrt. the infinity sets. - for (uint_fast64_t infSet = 0; infSet < _infSets.size()+1; ++infSet) { - // Check if we need to switch the acceptance condition - STORM_LOG_ASSERT(_accInfSets[product->getProductStateIndex(modelState, automatonTo)] != boost::none, "The list of InfSets for the product state <" <<modelState<< ", " << automatonTo<<"> is undefined."); - - if (_accInfSets[product->getProductStateIndex(modelState, automatonTo)].get().count(infSet) == 0) { - // the state is is in a different accepting MEC with a different accepting conjunction of InfSets. - auto newInfSet = _accInfSets[product->getProductStateIndex(modelState, automatonTo)].get().begin(); - _memoryTransitions[getMemoryState(automatonFrom, infSet)][getMemoryState(automatonTo, *newInfSet)].set(modelState); - - } else { - // Continue looking for any accepting EC (if we haven't reached one yet) or stay in the corresponding accepting EC, test whether we have reached the next infSet. - if (infSet == _infSets.size() || !(_infSets[infSet].get(product->getProductStateIndex(modelState, automatonTo)))) { - // <modelState, automatonTo> is not in any accepting EC or does not satisfy the InfSet, we stay there. - // Add modelState to the transition from <automatonFrom, InfSet> to <automatonTo, InfSet> - _memoryTransitions[getMemoryState(automatonFrom, infSet)][getMemoryState(automatonTo, infSet)].set(modelState); - - } else { - STORM_LOG_ASSERT(_accInfSets[product->getProductStateIndex(modelState, automatonTo)] != boost::none, "The list of InfSets for the product state <" <<modelState<< ", " << automatonTo<<"> is undefined."); - // <modelState, automatonTo> satisfies the InfSet, find the next one. - auto nextInfSet = std::find(_accInfSets[product->getProductStateIndex(modelState, automatonTo)].get().begin(), _accInfSets[product->getProductStateIndex(modelState, automatonTo)].get().end(), infSet); - STORM_LOG_ASSERT(nextInfSet != _accInfSets[product->getProductStateIndex(modelState, automatonTo)].get().end(), "The list of InfSets for the product state <" <<modelState<< ", " << automatonTo<<"> does not contain the infSet " << infSet); - nextInfSet++; - if (nextInfSet == _accInfSets[product->getProductStateIndex(modelState, automatonTo)].get().end()) { - // Start again. - nextInfSet = _accInfSets[product->getProductStateIndex(modelState, automatonTo)].get().begin(); - } - // Add modelState to the transition from <automatonFrom <mec, InfSet>> to <automatonTo, <mec, NextInfSet>>. - _memoryTransitions[getMemoryState(automatonFrom, infSet)][getMemoryState(automatonTo, *nextInfSet)].set(modelState); + 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. @@ -208,21 +243,13 @@ namespace storm { 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."); - if (acceptingProductStates[product->getProductStateIndex(modelState, automatonState)]) { - STORM_LOG_ASSERT(_accInfSets[product->getProductStateIndex(modelState, automatonState)] != boost::none, "The list of InfSets for the product state <" <<modelState<< ", " << automatonState<<"> is undefined."); - // If <s, q> is an accepting state start in the first InfSet of <s, q>. - auto infSet = _accInfSets[product->getProductStateIndex(modelState, automatonState)].get().begin(); - _memoryInitialStates[modelState] = getMemoryState(automatonState, *infSet); - - } else { - _memoryInitialStates[modelState] = getMemoryState(automatonState, _infSets.size()); - } - + 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) { diff --git a/src/storm/modelchecker/helper/ltl/internal/SparseLTLSchedulerHelper.h b/src/storm/modelchecker/helper/ltl/internal/SparseLTLSchedulerHelper.h index 89f5075c0..5f22a698a 100644 --- a/src/storm/modelchecker/helper/ltl/internal/SparseLTLSchedulerHelper.h +++ b/src/storm/modelchecker/helper/ltl/internal/SparseLTLSchedulerHelper.h @@ -38,13 +38,16 @@ namespace storm { void setRandom(); /*! - * Save choices for states in the accepting end component of the DA-Model product, - * but only set new choices for states that are not in any other EC yet. + * 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 + * @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 */ @@ -53,6 +56,8 @@ namespace storm { /*! * 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 @@ -82,13 +87,44 @@ namespace storm { * @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::map <std::tuple<uint_fast64_t, uint_fast64_t, uint_fast64_t>, storm::storage::SchedulerChoice<ValueType>> _producedChoices; // <s, q, len(_infSets)> -> ReachChoice and <s, q, InfSet> -> MecChoice std::vector<storm::storage::BitVector> _dontCareStates; // memorySate-modelState combinations that are never visited - std::vector<storm::storage::BitVector> _infSets; // Save the InfSets of the acceptance condition. The BitVector contains the product model states that are contained in the infSet + 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 From 6420709a503d88513af5c317e77b970b09772900 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Basg=C3=B6ze?= <dbasgoeze.github@basgoeze.com> Date: Fri, 13 Aug 2021 18:05:54 +0200 Subject: [PATCH 158/172] CI: Test GMP/CLN configurations and reduce tests --- .github/workflows/buildtest.yml | 32 ++++++++++++++++++++++++++++++-- 1 file changed, 30 insertions(+), 2 deletions(-) diff --git a/.github/workflows/buildtest.yml b/.github/workflows/buildtest.yml index a231f2430..5fee104ba 100644 --- a/.github/workflows/buildtest.yml +++ b/.github/workflows/buildtest.yml @@ -27,13 +27,41 @@ env: 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", args: "-DCMAKE_BUILD_TYPE=Debug -DSTORM_DEVELOPER=ON -DSTORM_PORTABLE=ON -DSTORM_USE_CLN_EA=OFF -DSTORM_USE_CLN_RF=OFF"} + # This is the standard config + # - {name: "GMP exact; CLN rational functions", args: "-DCMAKE_BUILD_TYPE=Debug -DSTORM_DEVELOPER=ON -DSTORM_PORTABLE=ON -DSTORM_USE_CLN_EA=OFF -DSTORM_USE_CLN_RF=ON"} + - {name: "CLN exact; GMP rational functions", args: "-DCMAKE_BUILD_TYPE=Debug -DSTORM_DEVELOPER=ON -DSTORM_PORTABLE=ON -DSTORM_USE_CLN_EA=ON -DSTORM_USE_CLN_RF=OFF"} + - {name: "CLN exact; CLN rational functions", args: "-DCMAKE_BUILD_TYPE=Debug -DSTORM_DEVELOPER=ON -DSTORM_PORTABLE=ON -DSTORM_USE_CLN_EA=ON -DSTORM_USE_CLN_RF=ON"} + 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 +188,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: From c6be1b6a922c70e4cb3432bb60e685d1d3089561 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Basg=C3=B6ze?= <dbasgoeze.github@basgoeze.com> Date: Tue, 24 Aug 2021 15:33:38 +0200 Subject: [PATCH 159/172] Always define CLN_INCLUDE_DIR when available --- resources/3rdparty/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/resources/3rdparty/CMakeLists.txt b/resources/3rdparty/CMakeLists.txt index 6bfd018ea..95a5cb67c 100644 --- a/resources/3rdparty/CMakeLists.txt +++ b/resources/3rdparty/CMakeLists.txt @@ -439,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() From 22388425d78c7b92436949e4194d678982193874 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Basg=C3=B6ze?= <dbasgoeze.github@basgoeze.com> Date: Tue, 24 Aug 2021 16:45:22 +0200 Subject: [PATCH 160/172] Remove unnecessary convertNumber Fixes build errors when GMP numbers are used --- src/storm-pars/analysis/AssumptionChecker.cpp | 2 +- src/storm-pars/analysis/MonotonicityHelper.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/storm-pars/analysis/AssumptionChecker.cpp b/src/storm-pars/analysis/AssumptionChecker.cpp index 8dad3bd48..a6ad9bbaf 100644 --- a/src/storm-pars/analysis/AssumptionChecker.cpp +++ b/src/storm-pars/analysis/AssumptionChecker.cpp @@ -34,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); From ebd85a43d3c4d184b9477a65cb1d70f93df377e2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Basg=C3=B6ze?= <dbasgoeze.github@basgoeze.com> Date: Tue, 24 Aug 2021 18:04:11 +0200 Subject: [PATCH 161/172] Fix conversion ambiguity: Use * instead of *= --- src/storm-pomdp/analysis/WinningRegion.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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 +} From a34fcca3393f30c4c7bbb14d0fcaea843c3d8ff4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Basg=C3=B6ze?= <dbasgoeze.github@basgoeze.com> Date: Tue, 24 Aug 2021 18:06:26 +0200 Subject: [PATCH 162/172] Fix conversion ambiguity: Use 1 instead of 1.0 --- src/storm/storage/geometry/ReduceVertexCloud.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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 +} From 8de8f1517a2dd61a32551d33062c4f66fdc3bd1f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Basg=C3=B6ze?= <dbasgoeze.github@basgoeze.com> Date: Tue, 24 Aug 2021 18:08:37 +0200 Subject: [PATCH 163/172] Fix conversion ambiguity: Use convertNumber() Conflicts: src/test/storm/modelchecker/prctl/mdp/SchedulerGenerationMdpPrctlModelCheckerTest.cpp --- ...SparseDtmcParameterLiftingModelChecker.cpp | 2 +- .../NondeterministicBeliefTracker.cpp | 2 +- .../prctl/helper/SparseMdpPrctlHelper.cpp | 2 +- ...ulerGenerationMdpPrctlModelCheckerTest.cpp | 38 +++++++++---------- 4 files changed, 22 insertions(+), 22 deletions(-) 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-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/modelchecker/prctl/helper/SparseMdpPrctlHelper.cpp b/src/storm/modelchecker/prctl/helper/SparseMdpPrctlHelper.cpp index 212896447..461435816 100644 --- a/src/storm/modelchecker/prctl/helper/SparseMdpPrctlHelper.cpp +++ b/src/storm/modelchecker/prctl/helper/SparseMdpPrctlHelper.cpp @@ -438,7 +438,7 @@ namespace storm { 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; } } diff --git a/src/test/storm/modelchecker/prctl/mdp/SchedulerGenerationMdpPrctlModelCheckerTest.cpp b/src/test/storm/modelchecker/prctl/mdp/SchedulerGenerationMdpPrctlModelCheckerTest.cpp index 63f4fd2d5..19b427f6a 100755 --- a/src/test/storm/modelchecker/prctl/mdp/SchedulerGenerationMdpPrctlModelCheckerTest.cpp +++ b/src/test/storm/modelchecker/prctl/mdp/SchedulerGenerationMdpPrctlModelCheckerTest.cpp @@ -72,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); @@ -88,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) { @@ -97,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, @@ -111,10 +111,10 @@ namespace { RationalPIEnvironment //RationalRationalSearchEnvironment > TestingTypes; - + TYPED_TEST_SUITE(SchedulerGenerationMdpPrctlModelCheckerTest, TestingTypes,); - + TYPED_TEST(SchedulerGenerationMdpPrctlModelCheckerTest, reachability) { typedef typename TestFixture::ValueType ValueType; @@ -126,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()); @@ -137,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()); @@ -147,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); @@ -161,14 +161,14 @@ 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()); @@ -182,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()); @@ -200,7 +200,7 @@ 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())); } } @@ -414,4 +414,4 @@ namespace { } -} \ No newline at end of file +} From 12111a91bdcfe0eb4dca1f1b7c22f5c253257e82 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Basg=C3=B6ze?= <dbasgoeze.github@basgoeze.com> Date: Tue, 24 Aug 2021 18:09:49 +0200 Subject: [PATCH 164/172] Use pass-by-value in constructor Pass by rvalue reference results in build errors when using CLN --- src/storm-pomdp/storage/BeliefManager.cpp | 4 ++-- src/storm-pomdp/storage/BeliefManager.h | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) 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 +} From 22a9703524bf5b336e89bb9f9fd33511476a069b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Basg=C3=B6ze?= <dbasgoeze.github@basgoeze.com> Date: Wed, 25 Aug 2021 13:09:51 +0200 Subject: [PATCH 165/172] Remove erroneous mutex lock in sylvan_wrapper Also remove trailing whitespace --- .../3rdparty/sylvan/src/storm_wrapper.cpp | 178 ++++++++---------- 1 file changed, 77 insertions(+), 101 deletions(-) diff --git a/resources/3rdparty/sylvan/src/storm_wrapper.cpp b/resources/3rdparty/sylvan/src/storm_wrapper.cpp index b0a10c1b8..44f406f1f 100644 --- a/resources/3rdparty/sylvan/src/storm_wrapper.cpp +++ b/resources/3rdparty/sylvan/src/storm_wrapper.cpp @@ -42,7 +42,7 @@ 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))); *a = srn_ptr; } @@ -51,7 +51,7 @@ 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; 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; - + return (srn_a == srn_b) ? 1 : 0; } @@ -71,7 +71,7 @@ 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; ss << srn_a; @@ -90,7 +90,7 @@ 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; } @@ -99,7 +99,7 @@ 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; } @@ -108,7 +108,7 @@ 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; } @@ -117,7 +117,7 @@ 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; } @@ -126,7 +126,7 @@ 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; } @@ -134,9 +134,9 @@ uint64_t storm_rational_number_hash(storm_rational_number_ptr const a, uint64_t #ifndef RATIONAL_NUMBER_THREAD_SAFE std::lock_guard<std::mutex> lock(rationalNumberMutex); #endif - + storm::RationalNumber const& srn_a = *(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,7 +145,7 @@ 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; 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,10 +163,10 @@ 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* result_srn = new storm::RationalNumber(srn_a + srn_b); return (storm_rational_number_ptr)result_srn; } @@ -175,10 +175,10 @@ storm_rational_number_ptr storm_rational_number_minus(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_b = *(storm::RationalNumber const*)b; - + storm::RationalNumber* result_srn = new storm::RationalNumber(srn_a - srn_b); return (storm_rational_number_ptr)result_srn; } @@ -187,10 +187,10 @@ storm_rational_number_ptr storm_rational_number_times(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_b = *(storm::RationalNumber const*)b; - + storm::RationalNumber* result_srn = new storm::RationalNumber(srn_a * srn_b); return (storm_rational_number_ptr)result_srn; } @@ -199,10 +199,10 @@ storm_rational_number_ptr storm_rational_number_divide(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_b = *(storm::RationalNumber const*)b; - + storm::RationalNumber* result_srn = new storm::RationalNumber(srn_a / srn_b); return (storm_rational_number_ptr)result_srn; } @@ -211,7 +211,7 @@ storm_rational_number_ptr storm_rational_number_pow(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; @@ -224,7 +224,7 @@ storm_rational_number_ptr storm_rational_number_mod(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; if (carl::isInteger(srn_a) && carl::isInteger(srn_b)) { @@ -235,18 +235,10 @@ storm_rational_number_ptr storm_rational_number_mod(storm_rational_number_ptr a, } 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; - + 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; - + 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,7 +280,7 @@ 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* result_srn = new storm::RationalNumber(-srn_a); return (storm_rational_number_ptr)result_srn; @@ -298,7 +290,7 @@ storm_rational_number_ptr storm_rational_number_floor(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* result_srn = new storm::RationalNumber(carl::floor(srn_a)); return (storm_rational_number_ptr)result_srn; @@ -308,7 +300,7 @@ 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* result_srn = new storm::RationalNumber(carl::ceil(srn_a)); return (storm_rational_number_ptr)result_srn; @@ -363,7 +355,7 @@ 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; } @@ -371,7 +363,7 @@ 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; ss << srn_a; @@ -387,7 +379,7 @@ 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))); *a = srf_ptr; } @@ -396,7 +388,7 @@ 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; delete srf; } @@ -405,10 +397,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; - + return (srf_a == srf_b) ? 1 : 0; } @@ -416,7 +408,7 @@ 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; ss << srf_a; @@ -435,7 +427,7 @@ 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; } @@ -444,7 +436,7 @@ 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; } @@ -453,7 +445,7 @@ 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; } @@ -462,7 +454,7 @@ 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; } @@ -472,7 +464,7 @@ 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; } @@ -480,9 +472,9 @@ uint64_t storm_rational_function_hash(storm_rational_function_ptr const a, uint6 #ifndef RATIONAL_FUNCTION_THREAD_SAFE std::lock_guard<std::mutex> lock(rationalFunctionMutex); #endif - + storm::RationalFunction const& srf_a = *(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,7 +483,7 @@ 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; if (srf_a.isConstant()) { return storm::utility::convertNumber<double>(srf_a); @@ -504,10 +496,10 @@ 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* result_srf = new storm::RationalFunction(srf_a); *result_srf += srf_b; return (storm_rational_function_ptr)result_srf; @@ -517,10 +509,10 @@ storm_rational_function_ptr storm_rational_function_minus(storm_rational_functio #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* result_srf = new storm::RationalFunction(srf_a); *result_srf -= srf_b; return (storm_rational_function_ptr)result_srf; @@ -530,10 +522,10 @@ storm_rational_function_ptr storm_rational_function_times(storm_rational_functio #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* result_srf = new storm::RationalFunction(srf_a); *result_srf *= srf_b; return (storm_rational_function_ptr)result_srf; @@ -543,10 +535,10 @@ storm_rational_function_ptr storm_rational_function_divide(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_b = *(storm::RationalFunction const*)b; - + storm::RationalFunction* result_srf = new storm::RationalFunction(srf_a); *result_srf /= srf_b; return (storm_rational_function_ptr)result_srf; @@ -556,10 +548,10 @@ storm_rational_function_ptr storm_rational_function_pow(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; - + 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; @@ -569,10 +561,10 @@ storm_rational_function_ptr storm_rational_function_mod(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; - + 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 +572,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; 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 +606,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; 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,7 +629,7 @@ 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* result_srf = new storm::RationalFunction(-srf_a); return (storm_rational_function_ptr)result_srf; @@ -663,7 +639,7 @@ storm_rational_function_ptr storm_rational_function_floor(storm_rational_functio #ifndef RATIONAL_FUNCTION_THREAD_SAFE std::lock_guard<std::mutex> lock(rationalFunctionMutex); #endif - + storm::RationalFunction const& srf_a = *(storm::RationalFunction const*)a; if (!storm::utility::isConstant(srf_a)) { throw storm::exceptions::InvalidOperationException() << "Operand of floor must not be non-constant rational function."; @@ -676,7 +652,7 @@ storm_rational_function_ptr storm_rational_function_ceil(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; if (!storm::utility::isConstant(srf_a)) { throw storm::exceptions::InvalidOperationException() << "Operand of ceil must not be non-constant rational function."; @@ -689,15 +665,15 @@ int storm_rational_function_equal_modulo_precision(int relative, storm_rational_ #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; - + 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,7 +689,7 @@ 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; std::cout << srf_a << std::flush; } @@ -722,7 +698,7 @@ 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; ss << srf_a; From 57874ff460c23edbb10aa80c1a9adb07f0760f65 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Basg=C3=B6ze?= <dbasgoeze.github@basgoeze.com> Date: Wed, 25 Aug 2021 13:40:27 +0200 Subject: [PATCH 166/172] Remove C-style casts in storm_wrapper.cpp --- .../3rdparty/sylvan/src/storm_wrapper.cpp | 194 +++++++++--------- 1 file changed, 97 insertions(+), 97 deletions(-) diff --git a/resources/3rdparty/sylvan/src/storm_wrapper.cpp b/resources/3rdparty/sylvan/src/storm_wrapper.cpp index 44f406f1f..4a9aeffe4 100644 --- a/resources/3rdparty/sylvan/src/storm_wrapper.cpp +++ b/resources/3rdparty/sylvan/src/storm_wrapper.cpp @@ -43,7 +43,7 @@ void storm_rational_number_init(storm_rational_number_ptr* a) { 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; } @@ -52,7 +52,7 @@ void storm_rational_number_destroy(storm_rational_number_ptr a) { 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; } @@ -61,8 +61,8 @@ int storm_rational_number_equals(storm_rational_number_ptr a, storm_rational_num 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; } @@ -73,14 +73,14 @@ char* storm_rational_number_to_str(storm_rational_number_ptr val, char *buf, siz #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; } @@ -91,8 +91,8 @@ storm_rational_number_ptr storm_rational_number_clone(storm_rational_number_ptr 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() { @@ -101,7 +101,7 @@ storm_rational_number_ptr storm_rational_number_get_zero() { #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() { @@ -110,7 +110,7 @@ storm_rational_number_ptr storm_rational_number_get_one() { #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() { @@ -119,7 +119,7 @@ storm_rational_number_ptr storm_rational_number_get_infinity() { #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) { @@ -127,7 +127,7 @@ int storm_rational_number_is_zero(storm_rational_number_ptr a) { 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) { @@ -135,7 +135,7 @@ uint64_t storm_rational_number_hash(storm_rational_number_ptr const a, uint64_t 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)); @@ -146,7 +146,7 @@ double storm_rational_number_get_value_double(storm_rational_number_ptr a) { 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); } @@ -164,11 +164,11 @@ storm_rational_number_ptr storm_rational_number_plus(storm_rational_number_ptr a 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) { @@ -176,11 +176,11 @@ storm_rational_number_ptr storm_rational_number_minus(storm_rational_number_ptr 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) { @@ -188,11 +188,11 @@ storm_rational_number_ptr storm_rational_number_times(storm_rational_number_ptr 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) { @@ -200,11 +200,11 @@ storm_rational_number_ptr storm_rational_number_divide(storm_rational_number_ptr 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) { @@ -212,12 +212,12 @@ storm_rational_number_ptr storm_rational_number_pow(storm_rational_number_ptr a, 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) { @@ -225,11 +225,11 @@ storm_rational_number_ptr storm_rational_number_mod(storm_rational_number_ptr a, 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."; } @@ -247,8 +247,8 @@ int storm_rational_number_less(storm_rational_number_ptr a, storm_rational_numbe 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; @@ -264,8 +264,8 @@ int storm_rational_number_less_or_equal(storm_rational_number_ptr a, storm_ratio 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; @@ -281,9 +281,9 @@ storm_rational_number_ptr storm_rational_number_negate(storm_rational_number_ptr 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) { @@ -291,9 +291,9 @@ storm_rational_number_ptr storm_rational_number_floor(storm_rational_number_ptr 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) { @@ -301,9 +301,9 @@ storm_rational_number_ptr storm_rational_number_ceil(storm_rational_number_ptr a 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) { @@ -314,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; } } @@ -325,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) { @@ -336,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)) { @@ -356,7 +356,7 @@ void print_storm_rational_number(storm_rational_number_ptr a) { 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); } void print_storm_rational_number_to_file(storm_rational_number_ptr a, FILE* out) { @@ -365,7 +365,7 @@ void print_storm_rational_number_to_file(storm_rational_number_ptr a, FILE* out) #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()); @@ -380,7 +380,7 @@ void storm_rational_function_init(storm_rational_function_ptr* a) { 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; } @@ -389,7 +389,7 @@ void storm_rational_function_destroy(storm_rational_function_ptr a) { std::lock_guard<std::mutex> lock(rationalFunctionMutex); #endif - storm::RationalFunction* srf = (storm::RationalFunction*)a; + storm::RationalFunction* srf = static_cast<storm::RationalFunction*>(a); delete srf; } @@ -398,8 +398,8 @@ int storm_rational_function_equals(storm_rational_function_ptr a, storm_rational 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; } @@ -410,14 +410,14 @@ char* storm_rational_function_to_str(storm_rational_function_ptr val, char* buf, #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()); return buf; } else { - char* result = (char*)malloc(s.size() + 1); + char* result = static_cast<char*>(malloc(s.size() + 1)); std::strcpy(result, s.c_str()); return result; } @@ -428,8 +428,8 @@ storm_rational_function_ptr storm_rational_function_clone(storm_rational_functio 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() { @@ -438,7 +438,7 @@ storm_rational_function_ptr storm_rational_function_get_zero() { #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() { @@ -447,7 +447,7 @@ storm_rational_function_ptr storm_rational_function_get_one() { #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() { @@ -456,7 +456,7 @@ storm_rational_function_ptr storm_rational_function_get_infinity() { #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); } @@ -465,7 +465,7 @@ int storm_rational_function_is_zero(storm_rational_function_ptr a) { 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) { @@ -473,7 +473,7 @@ uint64_t storm_rational_function_hash(storm_rational_function_ptr const a, uint6 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)); @@ -484,7 +484,7 @@ double storm_rational_function_get_value_double(storm_rational_function_ptr a) { 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 { @@ -497,12 +497,12 @@ storm_rational_function_ptr storm_rational_function_plus(storm_rational_function 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) { @@ -510,12 +510,12 @@ storm_rational_function_ptr storm_rational_function_minus(storm_rational_functio 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) { @@ -523,12 +523,12 @@ storm_rational_function_ptr storm_rational_function_times(storm_rational_functio 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) { @@ -536,12 +536,12 @@ storm_rational_function_ptr storm_rational_function_divide(storm_rational_functi 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) { @@ -549,12 +549,12 @@ storm_rational_function_ptr storm_rational_function_pow(storm_rational_function_ 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) { @@ -562,8 +562,8 @@ storm_rational_function_ptr storm_rational_function_mod(storm_rational_function_ 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."; @@ -584,8 +584,8 @@ int storm_rational_function_less(storm_rational_function_ptr a, storm_rational_f 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."; } @@ -607,8 +607,8 @@ int storm_rational_function_less_or_equal(storm_rational_function_ptr a, storm_r 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."; } @@ -630,9 +630,9 @@ storm_rational_function_ptr storm_rational_function_negate(storm_rational_functi 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) { @@ -640,12 +640,12 @@ storm_rational_function_ptr storm_rational_function_floor(storm_rational_functio 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) { @@ -653,12 +653,12 @@ storm_rational_function_ptr storm_rational_function_ceil(storm_rational_function 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) { @@ -666,9 +666,9 @@ int storm_rational_function_equal_modulo_precision(int relative, storm_rational_ 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."; @@ -690,7 +690,7 @@ void print_storm_rational_function(storm_rational_function_ptr a) { 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; } @@ -700,7 +700,7 @@ void print_storm_rational_function_to_file(storm_rational_function_ptr a, FILE* #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()); From 78a10f201e025a1a6d94d3bb226123260f4be8e5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Basg=C3=B6ze?= <dbasgoeze.github@basgoeze.com> Date: Wed, 25 Aug 2021 13:43:29 +0200 Subject: [PATCH 167/172] Use memcpy instead of strcpy --- resources/3rdparty/sylvan/src/storm_wrapper.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/resources/3rdparty/sylvan/src/storm_wrapper.cpp b/resources/3rdparty/sylvan/src/storm_wrapper.cpp index 4a9aeffe4..5e3e78c83 100644 --- a/resources/3rdparty/sylvan/src/storm_wrapper.cpp +++ b/resources/3rdparty/sylvan/src/storm_wrapper.cpp @@ -414,11 +414,11 @@ char* storm_rational_function_to_str(storm_rational_function_ptr val, char* buf, 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 = static_cast<char*>(malloc(s.size() + 1)); - std::strcpy(result, s.c_str()); + std::memcpy(result, s.c_str(), s.size() + 1); return result; } } From 94ec1a7aeb2ed02a7d971ac29a84daccdd19f4d5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Basg=C3=B6ze?= <dbasgoeze.github@basgoeze.com> Date: Wed, 25 Aug 2021 13:50:58 +0200 Subject: [PATCH 168/172] Fix print_storm_rational_number --- resources/3rdparty/sylvan/src/storm_wrapper.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/resources/3rdparty/sylvan/src/storm_wrapper.cpp b/resources/3rdparty/sylvan/src/storm_wrapper.cpp index 5e3e78c83..82c67f8f0 100644 --- a/resources/3rdparty/sylvan/src/storm_wrapper.cpp +++ b/resources/3rdparty/sylvan/src/storm_wrapper.cpp @@ -357,6 +357,7 @@ void print_storm_rational_number(storm_rational_number_ptr a) { #endif 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) { From 1dab4374968dba92d23cb2a8de30210cc1118635 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Basg=C3=B6ze?= <dbasgoeze.github@basgoeze.com> Date: Thu, 26 Aug 2021 12:47:15 +0200 Subject: [PATCH 169/172] Compare floating points upto precision instead == Fixes QuantileQueryTest with CLN Provided by Tim Quatmann --- src/test/storm/modelchecker/prctl/mdp/QuantileQueryTest.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) 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; } From e0e1b097eb70d869765ae39bfb2b3e027e3a5568 Mon Sep 17 00:00:00 2001 From: Tim Quatmann <tim.quatmann@cs.rwth-aachen.de> Date: Sat, 28 Aug 2021 13:24:23 +0200 Subject: [PATCH 170/172] Merge branch 'master' into ltl-github conflict in SchedulerGenerationMdpPrctlModelCheckerTest resolved. Conflicts: src/test/storm/modelchecker/prctl/mdp/SchedulerGenerationMdpPrctlModelCheckerTest.cpp --- ...ulerGenerationMdpPrctlModelCheckerTest.cpp | 29 +++++++++---------- 1 file changed, 14 insertions(+), 15 deletions(-) diff --git a/src/test/storm/modelchecker/prctl/mdp/SchedulerGenerationMdpPrctlModelCheckerTest.cpp b/src/test/storm/modelchecker/prctl/mdp/SchedulerGenerationMdpPrctlModelCheckerTest.cpp index 19b427f6a..02e37ab58 100755 --- a/src/test/storm/modelchecker/prctl/mdp/SchedulerGenerationMdpPrctlModelCheckerTest.cpp +++ b/src/test/storm/modelchecker/prctl/mdp/SchedulerGenerationMdpPrctlModelCheckerTest.cpp @@ -225,7 +225,7 @@ namespace { 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::settings::getModule<storm::settings::modules::GeneralSettings>().getPrecision()); + 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(); @@ -242,13 +242,13 @@ 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("81/100"), inducedResult->template asExplicitQuantitativeCheckResult<ValueType>()[*inducedMdp->getInitialStates().begin()],storm::settings::getModule<storm::settings::modules::GeneralSettings>().getPrecision()); + 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::settings::getModule<storm::settings::modules::GeneralSettings>().getPrecision()); + 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(); @@ -265,13 +265,13 @@ namespace { 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::settings::getModule<storm::settings::modules::GeneralSettings>().getPrecision()); + 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::settings::getModule<storm::settings::modules::GeneralSettings>().getPrecision()); + 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(); @@ -289,9 +289,9 @@ namespace { ASSERT_TRUE(inducedResult->isExplicitQuantitativeCheckResult()); auto test = inducedResult->template asExplicitQuantitativeCheckResult<ValueType>().getValueVector(); - EXPECT_NEAR(this->parseNumber("1/2"), inducedResult->template asExplicitQuantitativeCheckResult<ValueType>()[0], storm::settings::getModule<storm::settings::modules::GeneralSettings>().getPrecision()); - EXPECT_NEAR(this->parseNumber("1"), inducedResult->template asExplicitQuantitativeCheckResult<ValueType>()[1], storm::settings::getModule<storm::settings::modules::GeneralSettings>().getPrecision()); - EXPECT_NEAR(this->parseNumber("0"), inducedResult->template asExplicitQuantitativeCheckResult<ValueType>()[2], storm::settings::getModule<storm::settings::modules::GeneralSettings>().getPrecision()); + 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(); @@ -319,7 +319,7 @@ namespace { 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::settings::getModule<storm::settings::modules::GeneralSettings>().getPrecision()); + 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(); @@ -335,7 +335,7 @@ 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("1"), inducedResult->template asExplicitQuantitativeCheckResult<ValueType>()[*inducedMdp->getInitialStates().begin()], storm::settings::getModule<storm::settings::modules::GeneralSettings>().getPrecision()); + EXPECT_NEAR(this->parseNumber("1"), inducedResult->template asExplicitQuantitativeCheckResult<ValueType>()[*inducedMdp->getInitialStates().begin()], storm::utility::convertNumber<ValueType>(this->env().solver().minMax().getPrecision())); } #else GTEST_SKIP(); @@ -365,7 +365,7 @@ namespace { 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::settings::getModule<storm::settings::modules::GeneralSettings>().getPrecision()); + 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(); @@ -381,7 +381,7 @@ 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("0"), inducedResult->template asExplicitQuantitativeCheckResult<ValueType>()[*inducedMdp->getInitialStates().begin()], storm::settings::getModule<storm::settings::modules::GeneralSettings>().getPrecision()); + EXPECT_NEAR(this->parseNumber("0"), inducedResult->template asExplicitQuantitativeCheckResult<ValueType>()[*inducedMdp->getInitialStates().begin()], storm::utility::convertNumber<ValueType>(this->env().solver().minMax().getPrecision())); } { @@ -390,7 +390,7 @@ namespace { ASSERT_TRUE(result->isExplicitQuantitativeCheckResult()); ASSERT_TRUE(result->template asExplicitQuantitativeCheckResult<ValueType>().hasScheduler()); EXPECT_NEAR(this->parseNumber("1"),result->template asExplicitQuantitativeCheckResult<ValueType>()[*mdp->getInitialStates().begin()], - storm::settings::getModule<storm::settings::modules::GeneralSettings>().getPrecision()); + storm::utility::convertNumber<ValueType>(this->env().solver().minMax().getPrecision())); storm::storage::Scheduler<ValueType> const &scheduler = result->template asExplicitQuantitativeCheckResult<ValueType>().getScheduler(); EXPECT_TRUE(scheduler.isDeterministicScheduler()); @@ -406,12 +406,11 @@ 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("1"), inducedResult->template asExplicitQuantitativeCheckResult<ValueType>()[*inducedMdp->getInitialStates().begin()], storm::settings::getModule<storm::settings::modules::GeneralSettings>().getPrecision()); + 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 } - } From 3d96b0728d3da03b1ac7c318471ba62e9fd6d0f7 Mon Sep 17 00:00:00 2001 From: Tim Quatmann <tim.quatmann@cs.rwth-aachen.de> Date: Sat, 28 Aug 2021 13:32:23 +0200 Subject: [PATCH 171/172] CI: Use spot in all existing configurations. Add a new configuration without Spot. --- .github/workflows/buildtest.yml | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/.github/workflows/buildtest.yml b/.github/workflows/buildtest.yml index 5fee104ba..9ff93558e 100644 --- a/.github/workflows/buildtest.yml +++ b/.github/workflows/buildtest.yml @@ -35,11 +35,12 @@ jobs: strategy: matrix: cmakeArgs: - - {name: "GMP exact; GMP rational functions", args: "-DCMAKE_BUILD_TYPE=Debug -DSTORM_DEVELOPER=ON -DSTORM_PORTABLE=ON -DSTORM_USE_CLN_EA=OFF -DSTORM_USE_CLN_RF=OFF"} + - {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", args: "-DCMAKE_BUILD_TYPE=Debug -DSTORM_DEVELOPER=ON -DSTORM_PORTABLE=ON -DSTORM_USE_CLN_EA=OFF -DSTORM_USE_CLN_RF=ON"} - - {name: "CLN exact; GMP rational functions", args: "-DCMAKE_BUILD_TYPE=Debug -DSTORM_DEVELOPER=ON -DSTORM_PORTABLE=ON -DSTORM_USE_CLN_EA=ON -DSTORM_USE_CLN_RF=OFF"} - - {name: "CLN exact; CLN rational functions", args: "-DCMAKE_BUILD_TYPE=Debug -DSTORM_DEVELOPER=ON -DSTORM_PORTABLE=ON -DSTORM_USE_CLN_EA=ON -DSTORM_USE_CLN_RF=ON"} + # - {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} From 7e7d6defa0948b221fcfbe6f350ea8b9718c3a88 Mon Sep 17 00:00:00 2001 From: Tim Quatmann <tim.quatmann@cs.rwth-aachen.de> Date: Mon, 30 Aug 2021 12:41:16 +0200 Subject: [PATCH 172/172] Merge pull request #137 from tquatmann/ltl LTL Model Checking Also includes a reset of src/storm-parsers/parser/FormulaParserGrammar.cpp src/storm-parsers/parser/FormulaParserGrammar.h since there have been to many changes to fix them individually. Will follow up with a commit to introduce shield and smg formula parsing Conflicts: src/storm-parsers/parser/FormulaParserGrammar.cpp src/storm-parsers/parser/FormulaParserGrammar.h src/storm/logic/CloneVisitor.cpp src/storm/logic/Formula.h src/storm/logic/FragmentChecker.cpp src/storm/logic/FragmentSpecification.cpp src/storm/logic/FragmentSpecification.h src/storm/logic/LiftableTransitionRewardsVisitor.cpp src/storm/logic/ToPrefixStringVisitor.cpp src/storm/logic/ToPrefixStringVisitor.h src/storm/modelchecker/AbstractModelChecker.cpp src/storm/modelchecker/AbstractModelChecker.h src/storm/modelchecker/csl/SparseCtmcCslModelChecker.cpp src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.cpp src/storm/modelchecker/prctl/helper/SparseMdpPrctlHelper.cpp src/storm/storage/MaximalEndComponent.cpp src/storm/storage/Scheduler.cpp src/storm/storage/Scheduler.h src/storm/storage/jani/JSONExporter.cpp src/test/storm/modelchecker/prctl/mdp/SchedulerGenerationMdpPrctlModelCheckerTest.cpp --- .../parser/FormulaParserGrammar.cpp | 2 -- .../parser/FormulaParserGrammar.h | 4 --- src/storm/logic/Formula.h | 3 ++ src/storm/logic/FragmentSpecification.cpp | 29 +++++++++++++++ src/storm/logic/FragmentSpecification.h | 5 ++- .../LiftableTransitionRewardsVisitor.cpp | 1 - src/storm/logic/ToPrefixStringVisitor.cpp | 4 --- .../prctl/SparseDtmcPrctlModelChecker.cpp | 28 +++++++++++++++ .../prctl/SparseMdpPrctlModelChecker.cpp | 1 + src/storm/storage/Scheduler.cpp | 35 ++++++++++++++++++- src/storm/storage/Scheduler.h | 1 - src/storm/storage/jani/JSONExporter.cpp | 2 +- 12 files changed, 98 insertions(+), 17 deletions(-) diff --git a/src/storm-parsers/parser/FormulaParserGrammar.cpp b/src/storm-parsers/parser/FormulaParserGrammar.cpp index 1d5360a90..aa07a7961 100644 --- a/src/storm-parsers/parser/FormulaParserGrammar.cpp +++ b/src/storm-parsers/parser/FormulaParserGrammar.cpp @@ -176,8 +176,6 @@ namespace storm { 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"); diff --git a/src/storm-parsers/parser/FormulaParserGrammar.h b/src/storm-parsers/parser/FormulaParserGrammar.h index 63ba71f3e..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" @@ -243,9 +242,6 @@ namespace storm { 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); diff --git a/src/storm/logic/Formula.h b/src/storm/logic/Formula.h index 29eba01ff..0c83e718c 100644 --- a/src/storm/logic/Formula.h +++ b/src/storm/logic/Formula.h @@ -149,6 +149,9 @@ namespace storm { HOAPathFormula& asHOAPathFormula(); HOAPathFormula const& asHOAPathFormula() const; + HOAPathFormula& asHOAPathFormula(); + HOAPathFormula const& asHOAPathFormula() const; + BoundedUntilFormula& asBoundedUntilFormula(); BoundedUntilFormula const& asBoundedUntilFormula() const; diff --git a/src/storm/logic/FragmentSpecification.cpp b/src/storm/logic/FragmentSpecification.cpp index 2272ef61f..b75dca240 100644 --- a/src/storm/logic/FragmentSpecification.cpp +++ b/src/storm/logic/FragmentSpecification.cpp @@ -114,6 +114,35 @@ namespace storm { return rpatl; } + 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 csl() { FragmentSpecification csl = pctl(); diff --git a/src/storm/logic/FragmentSpecification.h b/src/storm/logic/FragmentSpecification.h index 18b8a8686..0bbe0fb17 100644 --- a/src/storm/logic/FragmentSpecification.h +++ b/src/storm/logic/FragmentSpecification.h @@ -249,6 +249,8 @@ namespace storm { // Flat PCTL. FragmentSpecification flatPctl(); + // rPATL for SMGs + FragmentSpecification rpatl(); // PCTL* FragmentSpecification pctlstar(); @@ -258,9 +260,6 @@ namespace storm { // PCTL* + cumulative, instantaneous, reachability and long-run rewards. FragmentSpecification prctlstar(); - // rPATL for SMGs - FragmentSpecification rpatl(); - // Regular CSL. FragmentSpecification csl(); diff --git a/src/storm/logic/LiftableTransitionRewardsVisitor.cpp b/src/storm/logic/LiftableTransitionRewardsVisitor.cpp index 7c3b1da97..2ead1325b 100644 --- a/src/storm/logic/LiftableTransitionRewardsVisitor.cpp +++ b/src/storm/logic/LiftableTransitionRewardsVisitor.cpp @@ -30,7 +30,6 @@ namespace storm { 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 { return true; } diff --git a/src/storm/logic/ToPrefixStringVisitor.cpp b/src/storm/logic/ToPrefixStringVisitor.cpp index af6e3f31c..300a53d97 100644 --- a/src/storm/logic/ToPrefixStringVisitor.cpp +++ b/src/storm/logic/ToPrefixStringVisitor.cpp @@ -59,10 +59,6 @@ namespace storm { return result; } - boost::any ToPrefixStringVisitor::visit(BoundedGloballyFormula const&, boost::any const&) const { - STORM_LOG_THROW(false, storm::exceptions::InvalidOperationException, "Can not convert to prefix string"); - } - boost::any ToPrefixStringVisitor::visit(BoundedUntilFormula const&, boost::any const&) const { STORM_LOG_THROW(false, storm::exceptions::InvalidOperationException, "Can not convert to prefix string"); } diff --git a/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.cpp b/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.cpp index 838caf03d..645564aa6 100644 --- a/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.cpp +++ b/src/storm/modelchecker/prctl/SparseDtmcPrctlModelChecker.cpp @@ -141,8 +141,36 @@ namespace storm { 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."); diff --git a/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.cpp b/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.cpp index 6551b61fe..a48995526 100644 --- a/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.cpp +++ b/src/storm/modelchecker/prctl/SparseMdpPrctlModelChecker.cpp @@ -28,6 +28,7 @@ #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" diff --git a/src/storm/storage/Scheduler.cpp b/src/storm/storage/Scheduler.cpp index 3d2c5a697..6405528a0 100644 --- a/src/storm/storage/Scheduler.cpp +++ b/src/storm/storage/Scheduler.cpp @@ -224,6 +224,18 @@ namespace storm { 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]; if (choice.isDefined()) { @@ -282,7 +294,28 @@ namespace storm { } } - stateString << std::endl; + // 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(); diff --git a/src/storm/storage/Scheduler.h b/src/storm/storage/Scheduler.h index 1a8322e81..96819be58 100644 --- a/src/storm/storage/Scheduler.h +++ b/src/storm/storage/Scheduler.h @@ -139,7 +139,6 @@ namespace storm { */ 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. */ diff --git a/src/storm/storage/jani/JSONExporter.cpp b/src/storm/storage/jani/JSONExporter.cpp index 5706618c6..bf5895d5e 100644 --- a/src/storm/storage/jani/JSONExporter.cpp +++ b/src/storm/storage/jani/JSONExporter.cpp @@ -711,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());