diff --git a/CMakeLists.txt b/CMakeLists.txt index bc5d1696e..7162aa250 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -23,7 +23,7 @@ include(imported) ############################################################# option(STORM_DEVELOPER "Sets whether the development mode is used." OFF) option(STORM_ALLWARNINGS "Compile with even more warnings" OFF) -option(STORM_PORTABLE_RELEASE "Sets whether a release build needs to be portable to another machine. This is only effective for release builds in non-development mode." OFF) +option(STORM_PORTABLE_RELEASE "Sets whether a release build needs to be portable to another machine." OFF) MARK_AS_ADVANCED(STORM_PORTABLE_RELEASE) option(STORM_USE_POPCNT "Sets whether the popcnt instruction is going to be used." ON) MARK_AS_ADVANCED(STORM_USE_POPCNT) @@ -77,6 +77,8 @@ message("CMAKE_INSTALL_DIR: ${CMAKE_INSTALL_DIR}") if (STORM_DEVELOPER) set(CMAKE_BUILD_TYPE "DEBUG") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DSTORM_DEV") +else() + set(STORM_LOG_DISABLE_DEBUG ON) endif() message(STATUS "Storm - Building ${CMAKE_BUILD_TYPE} version.") diff --git a/LICENSE b/LICENSE index 6d45519c8..94a9ed024 100644 --- a/LICENSE +++ b/LICENSE @@ -1,285 +1,626 @@ - GNU GENERAL PUBLIC LICENSE - Version 2, June 1991 + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 - Copyright (C) 1989, 1991 Free Software Foundation, Inc. - 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. - Preamble + Preamble - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -License is intended to guarantee your freedom to share and change free -software--to make sure the software is free for all its users. This -General Public License applies to most of the Free Software -Foundation's software and to any other program whose authors commit to -using it. (Some other Free Software Foundation software is covered by -the GNU Library General Public License instead.) You can apply it to + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for -this service if you wish), that you receive source code or can get it -if you want it, that you can change the software or use pieces of it -in new free programs; and that you know you can do these things. +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. - To protect your rights, we need to make restrictions that forbid -anyone to deny you these rights or to ask you to surrender the rights. -These restrictions translate to certain responsibilities for you if you -distribute copies of the software, or if you modify it. + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether -gratis or for a fee, you must give the recipients all the rights that -you have. You must make sure that they, too, receive or can get the -source code. And you must show them these terms so they know their -rights. - - We protect your rights with two steps: (1) copyright the software, and -(2) offer you this license which gives you legal permission to copy, -distribute and/or modify the software. - - Also, for each author's protection and ours, we want to make certain -that everyone understands that there is no warranty for this free -software. If the software is modified by someone else and passed on, we -want its recipients to know that what they have is not the original, so -that any problems introduced by others will not reflect on the original -authors' reputations. - - Finally, any free program is threatened constantly by software -patents. We wish to avoid the danger that redistributors of a free -program will individually obtain patent licenses, in effect making the -program proprietary. To prevent this, we have made it clear that any -patent must be licensed for everyone's free use or not licensed at all. +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. - GNU GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License applies to any program or other work which contains -a notice placed by the copyright holder saying it may be distributed -under the terms of this General Public License. The "Program", below, -refers to any such program or work, and a "work based on the Program" -means either the Program or any derivative work under copyright law: -that is to say, a work containing the Program or a portion of it, -either verbatim or with modifications and/or translated into another -language. (Hereinafter, translation is included without limitation in -the term "modification".) Each licensee is addressed as "you". - -Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running the Program is not restricted, and the output from the Program -is covered only if its contents constitute a work based on the -Program (independent of having been made by running the Program). -Whether that is true depends on what the Program does. - - 1. You may copy and distribute verbatim copies of the Program's -source code as you receive it, in any medium, provided that you -conspicuously and appropriately publish on each copy an appropriate -copyright notice and disclaimer of warranty; keep intact all the -notices that refer to this License and to the absence of any warranty; -and give any other recipients of the Program a copy of this License -along with the Program. - -You may charge a fee for the physical act of transferring a copy, and -you may at your option offer warranty protection in exchange for a fee. - - 2. You may modify your copy or copies of the Program or any portion -of it, thus forming a work based on the Program, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) You must cause the modified files to carry prominent notices - stating that you changed the files and the date of any change. - - b) You must cause any work that you distribute or publish, that in - whole or in part contains or is derived from the Program or any - part thereof, to be licensed as a whole at no charge to all third - parties under the terms of this License. - - c) If the modified program normally reads commands interactively - when run, you must cause it, when started running for such - interactive use in the most ordinary way, to print or display an - announcement including an appropriate copyright notice and a - notice that there is no warranty (or else, saying that you provide - a warranty) and that users may redistribute the program under - these conditions, and telling the user how to view a copy of this - License. (Exception: if the Program itself is interactive but - does not normally print such an announcement, your work based on - the Program is not required to print an announcement.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Program, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Program, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Program. - -In addition, mere aggregation of another work not based on the Program -with the Program (or with a work based on the Program) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may copy and distribute the Program (or a work based on it, -under Section 2) in object code or executable form under the terms of -Sections 1 and 2 above provided that you also do one of the following: - - a) Accompany it with the complete corresponding machine-readable - source code, which must be distributed under the terms of Sections - 1 and 2 above on a medium customarily used for software interchange; or, - - b) Accompany it with a written offer, valid for at least three - years, to give any third party, for a charge no more than your - cost of physically performing source distribution, a complete - machine-readable copy of the corresponding source code, to be - distributed under the terms of Sections 1 and 2 above on a medium - customarily used for software interchange; or, - - c) Accompany it with the information you received as to the offer - to distribute corresponding source code. (This alternative is - allowed only for noncommercial distribution and only if you - received the program in object code or executable form with such - an offer, in accord with Subsection b above.) - -The source code for a work means the preferred form of the work for -making modifications to it. For an executable work, complete source -code means all the source code for all modules it contains, plus any -associated interface definition files, plus the scripts used to -control compilation and installation of the executable. However, as a -special exception, the source code distributed need not include -anything that is normally distributed (in either source or binary -form) with the major components (compiler, kernel, and so on) of the -operating system on which the executable runs, unless that component -itself accompanies the executable. - -If distribution of executable or object code is made by offering -access to copy from a designated place, then offering equivalent -access to copy the source code from the same place counts as -distribution of the source code, even though third parties are not -compelled to copy the source along with the object code. - - 4. You may not copy, modify, sublicense, or distribute the Program -except as expressly provided under this License. Any attempt -otherwise to copy, modify, sublicense or distribute the Program is -void, and will automatically terminate your rights under this License. -However, parties who have received copies, or rights, from you under -this License will not have their licenses terminated so long as such -parties remain in full compliance. - - 5. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Program or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Program (or any work based on the -Program), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Program or works based on it. - - 6. Each time you redistribute the Program (or any work based on the -Program), the recipient automatically receives a license from the -original licensor to copy, distribute or modify the Program subject to -these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties to + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of this License. - 7. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Program at all. For example, if a patent -license would not permit royalty-free redistribution of the Program by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Program. - -If any portion of this section is held invalid or unenforceable under -any particular circumstance, the balance of the section is intended to -apply and the section as a whole is intended to apply in other -circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system, which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 8. If the distribution and/or use of the Program is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Program under this License -may add an explicit geographical distribution limitation excluding -those countries, so that distribution is permitted only in or among -countries not thus excluded. In such case, this License incorporates -the limitation as if written in the body of this License. - - 9. The Free Software Foundation may publish revised and/or new versions -of the General Public License from time to time. Such new versions will +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. -Each version is given a distinguishing version number. If the Program -specifies a version number of this License which applies to it and "any -later version", you have the option of following the terms and conditions -either of that version or of any later version published by the Free -Software Foundation. If the Program does not specify a version number of -this License, you may choose any version ever published by the Free Software -Foundation. - - 10. If you wish to incorporate parts of the Program into other free -programs whose distribution conditions are different, write to the author -to ask for permission. For software which is copyrighted by the Free -Software Foundation, write to the Free Software Foundation; we sometimes -make exceptions for this. Our decision will be guided by the two goals -of preserving the free status of all derivatives of our free software and -of promoting the sharing and reuse of software generally. - - NO WARRANTY - - 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY -FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN -OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES -PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED -OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS -TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE -PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, -REPAIR OR CORRECTION. - - 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR -REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, -INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING -OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED -TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY -YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER -PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE -POSSIBILITY OF SUCH DAMAGES. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it @@ -287,15 +628,15 @@ free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively -convey the exclusion of warranty; and each file should have at least +state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. <one line to give the program's name and a brief idea of what it does.> Copyright (C) <year> <name of author> - This program is free software; you can redistribute it and/or modify + This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or + the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, @@ -304,37 +645,30 @@ the "copyright" line and a pointer to where the full notice is found. GNU General Public License for more details. You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - + along with this program. If not, see <http://www.gnu.org/licenses/>. Also add information on how to contact you by electronic and paper mail. -If the program is interactive, make it output a short notice like this -when it starts in an interactive mode: + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: - Gnomovision version 69, Copyright (C) year name of author - Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + <program> Copyright (C) <year> <name of author> + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, the commands you use may -be called something other than `show w' and `show c'; they could even be -mouse-clicks or menu items--whatever suits your program. - -You should also get your employer (if you work as a programmer) or your -school, if any, to sign a "copyright disclaimer" for the program, if -necessary. Here is a sample; alter the names: - - Yoyodyne, Inc., hereby disclaims all copyright interest in the program - `Gnomovision' (which makes passes at compilers) written by James Hacker. - - <signature of Ty Coon>, 1 April 1989 - Ty Coon, President of Vice - -This General Public License does not permit incorporating your program into -proprietary programs. If your program is a subroutine library, you may -consider it more useful to permit linking proprietary applications with the -library. If this is what you want to do, use the GNU Library General -Public License instead of this License. +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +<http://www.gnu.org/licenses/>. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +<http://www.gnu.org/philosophy/why-not-lgpl.html>. diff --git a/README b/README deleted file mode 100644 index bef720bdf..000000000 --- a/README +++ /dev/null @@ -1,24 +0,0 @@ -# Create build directory for storm -mkdir build - -# Go to build directory -cd build - -# Configure the project -cmake .. -# If you want an interactive configuration, try "ccmake ..". Then you can press "c" to initially configure the project, change your values and then press "g" to generate the Makefile - -# After generating the Makefile you can build the resources we need for the project -make resources - -# Now we build the main project for DFTs -make storm-dft-main - -# Last you can run an example -./src/storm-dft -dft ../examples/dft/and.dft -mttf - -# To get a list of all available arguments run -./src/storm-dft --help - -# Example for DFT to Petri net translation -./src/storm-dft -dft ../examples/dft/and.dft --gspn diff --git a/README.md b/README.md index 54db5bddb..ffcc3bc5c 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ Storm ============================== -For more instructions, check out the documentation found in [Getting Started](doc/getting-started.md) +For more instructions, check out the documentation found in [Getting Started](https://moves-rwth.github.io/storm/getting-started.html) Benchmarks @@ -48,5 +48,6 @@ Storm has been developed at RWTH Aachen University. * Thomas Henn * Tom Janson * Gereon Kremer +* Sascha Vincent Kurowski * Manuel Sascha Weiand * Lukas Westhofen diff --git a/StormCPackConfig.cmake b/StormCPackConfig.cmake index 5ce6c0f53..6f58f9fd0 100644 --- a/StormCPackConfig.cmake +++ b/StormCPackConfig.cmake @@ -4,9 +4,9 @@ include(InstallRequiredSystemLibraries) # http://www.cmake.org/Wiki/CMake:CPackConfiguration ### general settings -set(CPACK_PACKAGE_NAME "StoRM") -set(CPACK_PACKAGE_VENDOR "i2 RWTH Aachen University") -set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "Stochastic Reward Model Checker - An extensible model checker written in C++.") +set(CPACK_PACKAGE_NAME "Storm") +set(CPACK_PACKAGE_VENDOR "RWTH Aachen University") +set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "Storm - A probabilistic model checker written in C++.") set(CPACK_RESOURCE_FILE_LICENSE "${CMAKE_SOURCE_DIR}/LICENSE") diff --git a/resources/3rdparty/CMakeLists.txt b/resources/3rdparty/CMakeLists.txt index dcb2d7005..67e8634c2 100644 --- a/resources/3rdparty/CMakeLists.txt +++ b/resources/3rdparty/CMakeLists.txt @@ -190,11 +190,13 @@ set(STORM_HAVE_CARL OFF) if(USE_CARL) find_package(carl QUIET) if(carl_FOUND) + set(STORM_SHIPPED_CARL OFF) set(STORM_HAVE_CARL ON) message(STATUS "Storm - Use system version of carl.") message(STATUS "Storm - Linking with carl ${carl_VERSION} (CARL_USE_CLN_NUMBERS: ${CARL_USE_CLN_NUMBERS}).") set(STORM_HAVE_CLN ${CARL_USE_CLN_NUMBERS}) else() + set(STORM_SHIPPED_CARL ON) # The first external project will be built at *configure stage* message("START CARL CONFIG PROCESS") file(MAKE_DIRECTORY ${STORM_3RDPARTY_BINARY_DIR}/carl_download) @@ -221,22 +223,23 @@ if(USE_CARL) message("END CARL CONFIG PROCESS") message(STATUS "Storm - Using shipped version of carl.") - set(CARL_BUILD_COMMAND make lib_carl) ExternalProject_Add( carl SOURCE_DIR ${STORM_3RDPARTY_BINARY_DIR}/carl CONFIGURE_COMMAND "" BUILD_IN_SOURCE 1 BUILD_COMMAND make lib_carl - INSTALL_COMMAND "" + INSTALL_COMMAND make install LOG_BUILD ON + LOG_INSTALL ON BUILD_BYPRODUCTS ${STORM_3RDPARTY_BINARY_DIR}/carl/lib/libcarl${DYNAMIC_EXT} ) include(${STORM_3RDPARTY_BINARY_DIR}/carl/carlConfig.cmake) message("CARL_USE_CLN_NUMBERS: ${CARL_USE_CLN_NUMBERS}") set(STORM_HAVE_CLN ${CARL_USE_CLN_NUMBERS}) - add_dependencies(resources carl) - set(carl_INCLUDE_DIR "${STORM_3RDPARTY_BINARY_DIR}/carl/build/include") + add_dependencies(resources carl) + set(carl_INCLUDE_DIR "${STORM_3RDPARTY_BINARY_DIR}/carl/include/") + set(carl_LIBRARIES ${STORM_3RDPARTY_BINARY_DIR}/carl/lib/libcarl${DYNAMIC_EXT}) set(STORM_HAVE_CARL ON) endif() if(STORM_USE_CLN_NUMBERS AND NOT STORM_HAVE_CLN) @@ -348,7 +351,7 @@ ExternalProject_Add( DOWNLOAD_COMMAND "" PREFIX "sylvan" SOURCE_DIR ${STORM_3RDPARTY_SOURCE_DIR}/sylvan - CMAKE_ARGS -DCMAKE_C_COMPILER=${CMAKE_C_COMPILER} -DSYLVAN_BUILD_TEST=Off -DSYLVAN_BUILD_EXAMPLES=Off -DCMAKE_BUILD_TYPE=Release -DCMAKE_POSITION_INDEPENDENT_CODE=ON + CMAKE_ARGS -DCMAKE_C_COMPILER=${CMAKE_C_COMPILER} -DSYLVAN_BUILD_TEST=Off -DSYLVAN_BUILD_EXAMPLES=Off -DCMAKE_BUILD_TYPE=Release -DCMAKE_POSITION_INDEPENDENT_CODE=ON -DUSE_CARL=ON -Dcarl_INCLUDE_DIR=${carl_INCLUDE_DIR} -DSYLVAN_PORTABLE=${STORM_PORTABLE_RELEASE} -Dcarl_LIBRARIES=${carl_LIBRARIES} BINARY_DIR ${STORM_3RDPARTY_BINARY_DIR}/sylvan BUILD_IN_SOURCE 0 INSTALL_COMMAND "" @@ -365,6 +368,9 @@ message(STATUS "Storm - Using shipped version of sylvan.") message(STATUS "Storm - Linking with sylvan.") add_imported_library(sylvan STATIC ${Sylvan_LIBRARY} ${Sylvan_INCLUDE_DIR}) add_dependencies(sylvan_STATIC sylvan) +if(USE_SHIPPED_CARL) + add_dependencies(sylvan carl) +endif() list(APPEND STORM_DEP_TARGETS sylvan_STATIC) find_package(Hwloc QUIET REQUIRED) diff --git a/resources/3rdparty/cudd-3.0.0/cudd/cuddSat.c b/resources/3rdparty/cudd-3.0.0/cudd/cuddSat.c index 91daa142b..c07b948c3 100644 --- a/resources/3rdparty/cudd-3.0.0/cudd/cuddSat.c +++ b/resources/3rdparty/cudd-3.0.0/cudd/cuddSat.c @@ -843,11 +843,12 @@ Cudd_EqualSupNormRel( /* Check terminal cases. */ if (f == g) return(1); if (Cudd_IsConstant(f) && Cudd_IsConstant(g)) { - if (ddAbs((cuddV(f) - cuddV(g))/cuddV(f)) < tolerance) { + CUDD_VALUE_TYPE absDiff = ddAbs((cuddV(f) - cuddV(g))); + if (absDiff/cuddV(f) < tolerance || absDiff < Cudd_ReadEpsilon(dd)) { return(1); } else { if (pr>0) { - (void) fprintf(dd->out,"Offending nodes:\n"); + (void) fprintf(dd->out,"Offending nodes (wrt. precision %0.30f) with diff %0.30f:\n", Cudd_ReadEpsilon(dd), absDiff); (void) fprintf(dd->out, "f: address = %p\t value = %40.30f\n", (void *) f, cuddV(f)); diff --git a/resources/3rdparty/include_cudd.cmake b/resources/3rdparty/include_cudd.cmake index 731758830..1c03de839 100644 --- a/resources/3rdparty/include_cudd.cmake +++ b/resources/3rdparty/include_cudd.cmake @@ -16,6 +16,11 @@ endif() set(CUDD_LIB_DIR ${STORM_3RDPARTY_BINARY_DIR}/cudd-3.0.0/lib) +set(STORM_CUDD_FLAGS "CFLAGS=-O3 -w -DPIC -DHAVE_IEEE_754 -fno-common -ffast-math -fno-finite-math-only") +if (NOT STORM_PORTABLE_RELEASE) + set(STORM_CUDD_FLAGS "${STORM_CUDD_FLAGS} -march=native") +endif() + ExternalProject_Add( cudd3 DOWNLOAD_COMMAND "" @@ -23,7 +28,7 @@ ExternalProject_Add( PREFIX ${STORM_3RDPARTY_BINARY_DIR}/cudd-3.0.0 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=${CMAKE_CXX_COMPILER} - BUILD_COMMAND make "CFLAGS=-O2 -w" + BUILD_COMMAND make ${STORM_CUDD_FLAGS} INSTALL_COMMAND make install BUILD_IN_SOURCE 0 LOG_CONFIGURE ON @@ -49,4 +54,4 @@ else() list(APPEND STORM_DEP_TARGETS cudd_STATIC) endif() -message(STATUS "Storm - Linking with CUDD ${CUDD_VERSION_STRING}.") \ No newline at end of file +message(STATUS "Storm - Linking with CUDD ${CUDD_VERSION_STRING}.") diff --git a/resources/3rdparty/include_xerces.cmake b/resources/3rdparty/include_xerces.cmake index 834f697d2..4a464835d 100644 --- a/resources/3rdparty/include_xerces.cmake +++ b/resources/3rdparty/include_xerces.cmake @@ -4,28 +4,28 @@ if(USE_XERCESC) message(STATUS "Storm - Use system version of xerces.") else() message(STATUS "Storm - Use shipped version of xerces.") - set(XERCESC_LIB_DIR ${STORM_3RDPARTY_BINARY_DIR}/xercesc-3.1.2/lib) + set(XercesC_LIB_DIR ${STORM_3RDPARTY_BINARY_DIR}/xercesc-3.1.2/lib) ExternalProject_Add( xercesc SOURCE_DIR ${STORM_3RDPARTY_SOURCE_DIR}/xercesc-3.1.2 - CONFIGURE_COMMAND ${STORM_3RDPARTY_SOURCE_DIR}/xercesc-3.1.2/configure --prefix=${STORM_3RDPARTY_BINARY_DIR}/xercesc-3.1.2 --libdir=${XERCESC_LIB_DIR} CC=${CMAKE_C_COMPILER} CXX=${CMAKE_CXX_COMPILER} CFLAGS=-O3 CXXFLAGS=-O3 + CONFIGURE_COMMAND ${STORM_3RDPARTY_SOURCE_DIR}/xercesc-3.1.2/configure --prefix=${STORM_3RDPARTY_BINARY_DIR}/xercesc-3.1.2 --libdir=${XercesC_LIB_DIR} CC=${CMAKE_C_COMPILER} CXX=${CMAKE_CXX_COMPILER} CFLAGS=-O3 CXXFLAGS=-O3 PREFIX ${STORM_3RDPARTY_BINARY_DIR}/xercesc-3.1.2 BUILD_COMMAND make BUILD_IN_SOURCE 0 LOG_CONFIGURE ON LOG_BUILD ON LOG_INSTALL ON - BUILD_BYPRODUCTS ${XERCESC_LIB_DIR}/libxerces-c${DYNAMIC_EXT} ${XERCESC_LIB_DIR}/libxerces-c${STATIC_EXT} + BUILD_BYPRODUCTS ${XercesC_LIB_DIR}/libxerces-c${DYNAMIC_EXT} ${XercesC_LIB_DIR}/libxerces-c${STATIC_EXT} ) - set(XERCESC_ROOT ${STORM_3RDPARTY_BINARY_DIR}/xercesc-3.1.2) - set(XercesC_INCLUDE_DIRS ${XERCESC_ROOT}/include) - set(XERCESC_LIBRARY_PATH ${XERCESC_LIB_DIR}) + set(XercesC_ROOT ${STORM_3RDPARTY_BINARY_DIR}/xercesc-3.1.2) + set(XercesC_INCLUDE_DIRS ${XercesC_ROOT}/include) + set(XercesC_LIBRARY_PATH ${XercesC_LIB_DIR}) if(BUILD_STATIC) - set(XercesC_LIBRARIES ${XERCESC_LIBRARY_PATH}/libxerces-c${STATIC_EXT}) + set(XercesC_LIBRARIES ${XercesC_LIBRARY_PATH}/libxerces-c${STATIC_EXT}) else() - set(XercesC_LIBRARIES ${XERCESC_LIBRARY_PATH}/libxerces-c${DYNAMIC_EXT}) + set(XercesC_LIBRARIES ${XercesC_LIBRARY_PATH}/libxerces-c${DYNAMIC_EXT}) endif() add_dependencies(resources xercesc) @@ -40,8 +40,9 @@ if(USE_XERCESC) mark_as_advanced(COREFOUNDATION_LIBRARY) mark_as_advanced(CORESERVICES_LIBRARY) endif() - find_package(CURL) + # find_package(CURL) list(APPEND STORM_GSPN_LINK_LIBRARIES ${XercesC_LIBRARIES} ${COREFOUNDATION_LIBRARY} ${CORESERVICES_LIBRARY} ${CURL_LIBRARIES}) else() + set(STORM_HAVE_XERCES OFF) message (WARNING "Storm - Building without Xerces disables parsing XML formats (for GSPNs)") endif(USE_XERCESC) diff --git a/resources/3rdparty/include_xerces.cmake.save b/resources/3rdparty/include_xerces.cmake.save deleted file mode 100644 index e69de29bb..000000000 diff --git a/resources/3rdparty/include_xerces.cmake.save.1 b/resources/3rdparty/include_xerces.cmake.save.1 deleted file mode 100644 index 4480844f5..000000000 --- a/resources/3rdparty/include_xerces.cmake.save.1 +++ /dev/null @@ -1,49 +0,0 @@ -if(USE_XERCESC) - set(XERCESC_FIND_QUIETLY ON) - set(XERCESC_STATIC OFF) - find_package(XercesC QUIET REQUIRED) - if(XERCESC_FOUND) - message(STATUS "Storm - Use system version of xerces.") - else() - message(STATUS "Storm - Use shipped version of xerces.") - set(XERCESC_LIB_DIR ${STORM_3RDPARTY_BINARY_DIR}/xercesc-3.1.2/lib) - ExternalProject_Add( - xercesc - SOURCE_DIR ${STORM_3RDPARTY_SOURCE_DIR}/xercesc-3.1.2 - CONFIGURE_COMMAND ${STORM_3RDPARTY_SOURCE_DIR}/xercesc-3.1.2/configure --prefix=${STORM_3RDPARTY_BINARY_DIR}/xercesc-3.1.2 --libdir=${XERCESC_LIB_DIR} CC=${CMAKE_C_COMPILER} CXX=${CMAKE_CXX_COMPILER} CFLAGS=-O3 CXXFLAGS=-O3 - PREFIX ${STORM_3RDPARTY_BINARY_DIR}/xercesc-3.1.2 - BUILD_COMMAND make - BUILD_IN_SOURCE 0 - LOG_CONFIGURE ON - LOG_BUILD ON - LOG_INSTALL ON - BUILD_BYPRODUCTS ${XERCESC_LIB_DIR}/libxerces-c${DYNAMIC_EXT} ${XERCESC_LIB_DIR}/libxerces-c${STATIC_EXT} - ) - - set(XERCESC_ROOT ${STORM_3RDPARTY_BINARY_DIR}/xercesc-3.1.2) - set(XERCESC_INCLUDE ${XERCESC_ROOT}/include) - set(XERCESC_LIBRARY_PATH ${XERCESC_LIB_DIR}) - - if(BUILD_STATIC) - set(XERCESC_LIBRARIES ${XERCESC_LIBRARY_PATH}/libxerces-c${STATIC_EXT}) - else() - set(XERCESC_LIBRARIES ${XERCESC_LIBRARY_PATH}/libxerces-c${DYNAMIC_EXT}) - endif() - - add_dependencies(resources xercesc) - endif() - - message (STATUS "Storm - Linking with xercesc.") - set(STORM_HAVE_XERCES ON) - include_directories(${XERCESC_INCLUDE}) - if(APPLE) - FIND_LIBRARY(COREFOUNDATION_LIBRARY CoreFoundation ) - FIND_LIBRARY(CORESERVICES_LIBRARY CoreServices ) - mark_as_advanced(COREFOUNDATION_LIBRARY) - mark_as_advanced(CORESERVICES_LIBRARY) - endif() - find_package(CURL) - list(APPEND STORM_GSPN_LINK_LIBRARIES ${XERCESC_LIBRARIES} ${COREFOUNDATION_LIBRARY} ${CORESERVICES_LIBRARY} ${CURL_LIBRARIES}) -else() - message (WARNING "Storm - Building without Xerces disables parsing XML formats (for GSPNs)") -endif(USE_XERCESC) diff --git a/resources/3rdparty/sparsepp/README.md b/resources/3rdparty/sparsepp/README.md index df473bed9..241b116b0 100644 --- a/resources/3rdparty/sparsepp/README.md +++ b/resources/3rdparty/sparsepp/README.md @@ -54,6 +54,12 @@ Since the full Sparsepp implementation is contained in a single header file `spa Optionally, a second header file `spp_utils.h` is provided, which implements only the spp::hash_combine() functionality. This is useful when we want to specify a hash function for a user-defined class in an header file, without including the full `sparsepp.h` header (this is demonstrated in [example 2](#example-2---providing-a-hash-function-for-a-user-defined-class) below). +## Warning - iterator invalidation on erase/insert + +1. erasing elements is likely to invalidate iterators (for example when calling `erase()`) + +2. inserting new elements is likely to invalidate iterators (iterator invalidation can also happen with std::unordered_map if rehashing occurs due to the insertion) + ## Usage As shown in the example above, you need to include the header file: `#include <sparsepp.h>` @@ -80,18 +86,47 @@ namespace spp These classes provide the same interface as std::unordered_map and std::unordered_set, with the following differences: -- Calls to erase() may invalidate iterators. However, conformant to the C++11 standard, the position and range erase functions return an iterator pointing to the position immediately following the last of the elements erased. This makes it easy to traverse a sparse hash table and delete elements matching a condition. For example to delete odd values: - -```c++ - for (auto it = c.begin(); it != c.end(); ) - if (it->first % 2 == 1) - it = c.erase(it); - else - ++it; -``` +- Calls to `erase()` may invalidate iterators. However, conformant to the C++11 standard, the position and range erase functions return an iterator pointing to the position immediately following the last of the elements erased. This makes it easy to traverse a sparse hash table and delete elements matching a condition. For example to delete odd values: + + ```c++ + for (auto it = c.begin(); it != c.end(); ) + if (it->first % 2 == 1) + it = c.erase(it); + else + ++it; + ``` + + As for std::unordered_map, the order of the elements that are not erased is preserved. - Since items are not grouped into buckets, Bucket APIs have been adapted: `max_bucket_count` is equivalent to `max_size`, and `bucket_count` returns the sparsetable size, which is normally at least twice the number of items inserted into the hash_map. +## Integer keys, and other hash function considerations. + +1. For basic integer types, sparsepp provides a default hash function which does some mixing of the bits of the keys (see [Integer Hashing](http://burtleburtle.net/bob/hash/integer.html)). This prevents a pathological case where inserted keys are sequential (1, 2, 3, 4, ...), and the lookup on non-present keys becomes very slow. + + Of course, the user of sparsepp may provide its own hash function, as shown below: + + ```c++ + #include <sparsepp.h> + + struct Hash64 { + size_t operator()(uint64_t k) const { return (k ^ 14695981039346656037ULL) * 1099511628211ULL; } + }; + + struct Hash32 { + size_t operator()(uint32_t k) const { return (k ^ 2166136261U) * 16777619UL; } + }; + + int main() + { + spp::sparse_hash_map<uint64_t, double, Hash64> map; + ... + } + + ``` + +2. When the user provides its own hash function, for example when inserting custom classes into a hash map, sometimes the resulting hash keys have similar low order bits and cause many collisions, decreasing the efficiency of the hash map. To address this use case, sparsepp provides an optional 'mixing' of the hash key (see [Integer Hash Function](https://gist.github.com/badboy/6267743) which can be enabled by defining the proprocessor macro: SPP_HASH_MIX. + ## Example 2 - providing a hash function for a user-defined class In order to use a sparse_hash_set or sparse_hash_map, a hash function should be provided. Even though a the hash function can be provided via the HashFcn template parameter, we recommend injecting a specialization of `std::hash` for the class into the "std" namespace. For example: diff --git a/resources/3rdparty/sparsepp/makefile b/resources/3rdparty/sparsepp/makefile index 3443f0e27..eed3e5bca 100644 --- a/resources/3rdparty/sparsepp/makefile +++ b/resources/3rdparty/sparsepp/makefile @@ -7,5 +7,11 @@ test: ./spp_test spp_test: spp_test.cc sparsepp.h makefile - $(CXX) -O2 -std=c++0x -D_CRT_SECURE_NO_WARNINGS spp_test.cc -o spp_test + $(CXX) -O2 -std=c++0x -Wall -pedantic -Wextra -D_XOPEN_SOURCE=700 -D_CRT_SECURE_NO_WARNINGS spp_test.cc -o spp_test + +spp_alloc_test: spp_alloc_test.cc spp_alloc.h spp_bitset.h sparsepp.h makefile + $(CXX) -O2 -DNDEBUG -std=c++11 spp_alloc_test.cc -o spp_alloc_test + +perftest1: perftest1.cc sparsepp.h makefile + $(CXX) -O2 -DNDEBUG -std=c++11 perftest1.cc -o perftest1 diff --git a/resources/3rdparty/sparsepp/sparsepp.h b/resources/3rdparty/sparsepp/sparsepp.h index 5706adb0d..8fc36ce47 100644 --- a/resources/3rdparty/sparsepp/sparsepp.h +++ b/resources/3rdparty/sparsepp/sparsepp.h @@ -920,6 +920,12 @@ template<int S, int H> class HashObject; // for Google's benchmark, not in spp n #define SPP_NOEXCEPT noexcept #endif +#ifdef SPP_NO_CXX11_CONSTEXPR + #define SPP_CONSTEXPR +#else + #define SPP_CONSTEXPR constexpr +#endif + #define SPP_INLINE #ifndef SPP_NAMESPACE @@ -955,75 +961,109 @@ struct spp_hash<T *> SPP_INLINE size_t operator()(const T *__v) const SPP_NOEXCEPT { - static const size_t shift = spp_log2(1 + sizeof(T)); + static const size_t shift = 3; // spp_log2(1 + sizeof(T)); // T might be incomplete! return static_cast<size_t>((*(reinterpret_cast<const uintptr_t *>(&__v))) >> shift); } }; +// from http://burtleburtle.net/bob/hash/integer.html +// fast and efficient for power of two table sizes where we always +// consider the last bits. +// --------------------------------------------------------------- +inline size_t spp_mix_32(uint32_t a) +{ + a = a ^ (a >> 4); + a = (a ^ 0xdeadbeef) + (a << 5); + a = a ^ (a >> 11); + return static_cast<size_t>(a); +} + +// Maybe we should do a more thorough scrambling as described in +// https://gist.github.com/badboy/6267743 +// ------------------------------------------------------------- +inline size_t spp_mix_64(uint64_t a) +{ + a = a ^ (a >> 4); + a = (a ^ 0xdeadbeef) + (a << 5); + a = a ^ (a >> 11); + return a; +} + template <> struct spp_hash<bool> : public std::unary_function<bool, size_t> { - SPP_INLINE size_t operator()(bool __v) const SPP_NOEXCEPT {return static_cast<size_t>(__v);} + SPP_INLINE size_t operator()(bool __v) const SPP_NOEXCEPT + { return static_cast<size_t>(__v); } }; template <> struct spp_hash<char> : public std::unary_function<char, size_t> { - SPP_INLINE size_t operator()(char __v) const SPP_NOEXCEPT {return static_cast<size_t>(__v);} + SPP_INLINE size_t operator()(char __v) const SPP_NOEXCEPT + { return static_cast<size_t>(__v); } }; template <> struct spp_hash<signed char> : public std::unary_function<signed char, size_t> { - SPP_INLINE size_t operator()(signed char __v) const SPP_NOEXCEPT {return static_cast<size_t>(__v);} + SPP_INLINE size_t operator()(signed char __v) const SPP_NOEXCEPT + { return static_cast<size_t>(__v); } }; template <> struct spp_hash<unsigned char> : public std::unary_function<unsigned char, size_t> { - SPP_INLINE size_t operator()(unsigned char __v) const SPP_NOEXCEPT {return static_cast<size_t>(__v);} + SPP_INLINE size_t operator()(unsigned char __v) const SPP_NOEXCEPT + { return static_cast<size_t>(__v); } }; template <> struct spp_hash<wchar_t> : public std::unary_function<wchar_t, size_t> { - SPP_INLINE size_t operator()(wchar_t __v) const SPP_NOEXCEPT {return static_cast<size_t>(__v);} + SPP_INLINE size_t operator()(wchar_t __v) const SPP_NOEXCEPT + { return static_cast<size_t>(__v); } }; template <> -struct spp_hash<short> : public std::unary_function<short, size_t> +struct spp_hash<int16_t> : public std::unary_function<int16_t, size_t> { - SPP_INLINE size_t operator()(short __v) const SPP_NOEXCEPT {return static_cast<size_t>(__v);} + SPP_INLINE size_t operator()(int16_t __v) const SPP_NOEXCEPT + { return spp_mix_32(static_cast<uint32_t>(__v)); } }; template <> -struct spp_hash<unsigned short> : public std::unary_function<unsigned short, size_t> +struct spp_hash<uint16_t> : public std::unary_function<uint16_t, size_t> { - SPP_INLINE size_t operator()(unsigned short __v) const SPP_NOEXCEPT {return static_cast<size_t>(__v);} + SPP_INLINE size_t operator()(uint16_t __v) const SPP_NOEXCEPT + { return spp_mix_32(static_cast<uint32_t>(__v)); } }; template <> -struct spp_hash<int> : public std::unary_function<int, size_t> +struct spp_hash<int32_t> : public std::unary_function<int32_t, size_t> { - SPP_INLINE size_t operator()(int __v) const SPP_NOEXCEPT {return static_cast<size_t>(__v);} + SPP_INLINE size_t operator()(int32_t __v) const SPP_NOEXCEPT + { return spp_mix_32(static_cast<uint32_t>(__v)); } }; template <> -struct spp_hash<unsigned int> : public std::unary_function<unsigned int, size_t> +struct spp_hash<uint32_t> : public std::unary_function<uint32_t, size_t> { - SPP_INLINE size_t operator()(unsigned int __v) const SPP_NOEXCEPT {return static_cast<size_t>(__v);} + SPP_INLINE size_t operator()(uint32_t __v) const SPP_NOEXCEPT + { return spp_mix_32(static_cast<uint32_t>(__v)); } }; template <> -struct spp_hash<long> : public std::unary_function<long, size_t> +struct spp_hash<int64_t> : public std::unary_function<int64_t, size_t> { - SPP_INLINE size_t operator()(long __v) const SPP_NOEXCEPT {return static_cast<size_t>(__v);} + SPP_INLINE size_t operator()(int64_t __v) const SPP_NOEXCEPT + { return spp_mix_64(static_cast<uint64_t>(__v)); } }; template <> -struct spp_hash<unsigned long> : public std::unary_function<unsigned long, size_t> +struct spp_hash<uint64_t> : public std::unary_function<uint64_t, size_t> { - SPP_INLINE size_t operator()(unsigned long __v) const SPP_NOEXCEPT {return static_cast<size_t>(__v);} + SPP_INLINE size_t operator()(uint64_t __v) const SPP_NOEXCEPT + { return spp_mix_64(static_cast<uint64_t>(__v)); } }; template <> @@ -1033,22 +1073,20 @@ struct spp_hash<float> : public std::unary_function<float, size_t> { // -0.0 and 0.0 should return same hash uint32_t *as_int = reinterpret_cast<uint32_t *>(&__v); - return (__v == 0) ? static_cast<size_t>(0) : static_cast<size_t>(*as_int); + return (__v == 0) ? static_cast<size_t>(0) : spp_mix_32(*as_int); } }; -#if 0 -// todo: we should not ignore half of the double => see libcxx/include/functional template <> struct spp_hash<double> : public std::unary_function<double, size_t> { SPP_INLINE size_t operator()(double __v) const SPP_NOEXCEPT { // -0.0 and 0.0 should return same hash - return (__v == 0) ? (size_t)0 : (size_t)*((uint64_t *)&__v); + uint64_t *as_int = reinterpret_cast<uint64_t *>(&__v); + return (__v == 0) ? static_cast<size_t>(0) : spp_mix_64(*as_int); } }; -#endif template <class T, int sz> struct Combiner { @@ -1080,7 +1118,7 @@ inline void hash_combine(std::size_t& seed, T const& v) combiner(seed, hasher(v)); } -}; +} #endif // spp_utils_h_guard_ @@ -1412,30 +1450,36 @@ namespace sparsehash_internal // Settings contains parameters for growing and shrinking the table. // It also packages zero-size functor (ie. hasher). // - // It does some munging of the hash value in cases where we think - // (fear) the original hash function might not be very good. In - // particular, the default hash of pointers is the identity hash, - // so probably all the low bits are 0. We identify when we think - // we're hashing a pointer, and chop off the low bits. Note this - // isn't perfect: even when the key is a pointer, we can't tell - // for sure that the hash is the identity hash. If it's not, this - // is needless work (and possibly, though not likely, harmful). + // It does some munging of the hash value for the cases where + // the original hash function is not be very good. // --------------------------------------------------------------- - template<typename Key, typename HashFunc, - typename SizeType, int HT_MIN_BUCKETS> + template<typename Key, typename HashFunc, typename SizeType, int HT_MIN_BUCKETS> class sh_hashtable_settings : public HashFunc { private: +#ifndef SPP_MIX_HASH + template <class T, int sz> struct Mixer + { + inline T operator()(T h) const { return h; } + }; +#else template <class T, int sz> struct Mixer { inline T operator()(T h) const; }; - template <class T> struct Mixer<T, 4> + template <class T> struct Mixer<T, 4> { inline T operator()(T h) const { - return h + (h >> 7) + (h >> 13) + (h >> 23); + // from Thomas Wang - https://gist.github.com/badboy/6267743 + // --------------------------------------------------------- + h = (h ^ 61) ^ (h >> 16); + h = h + (h << 3); + h = h ^ (h >> 4); + h = h * 0x27d4eb2d; + h = h ^ (h >> 15); + return h; } }; @@ -1443,9 +1487,19 @@ namespace sparsehash_internal { inline T operator()(T h) const { - return h + (h >> 7) + (h >> 13) + (h >> 23) + (h >> 32); + // from Thomas Wang - https://gist.github.com/badboy/6267743 + // --------------------------------------------------------- + h = (~h) + (h << 21); // h = (h << 21) - h - 1; + h = h ^ (h >> 24); + h = (h + (h << 3)) + (h << 8); // h * 265 + h = h ^ (h >> 14); + h = (h + (h << 2)) + (h << 4); // h * 21 + h = h ^ (h >> 28); + h = h + (h << 31); + return h; } }; +#endif public: typedef Key key_type; @@ -1507,8 +1561,8 @@ namespace sparsehash_internal // ------------------------------------------------------------ void set_resizing_parameters(float shrink, float grow) { - assert(shrink >= 0.0); - assert(grow <= 1.0); + assert(shrink >= 0.0f); + assert(grow <= 1.0f); if (shrink > grow/2.0f) shrink = grow / 2.0f; // otherwise we thrash hashtable size set_shrink_factor(shrink); @@ -1724,34 +1778,6 @@ template <class T, class U> struct is_relocatable<std::pair<T, U> > : // --------------------------------------------------------------------------- // --------------------------------------------------------------------------- -template <class tabletype> -class table_element_adaptor -{ -public: - typedef typename tabletype::value_type value_type; - typedef typename tabletype::size_type size_type; - typedef typename tabletype::reference reference; - typedef typename tabletype::pointer pointer; - - table_element_adaptor(tabletype *tbl, size_type p) : - table(tbl), pos(p) - { } - - table_element_adaptor& operator=(const value_type &val) - { - table->set(pos, val, false); - return *this; - } - - operator value_type() { return table->get(pos); } // we look like a value - - pointer operator& () { return &table->mutating_get(pos); } - -private: - tabletype* table; - size_type pos; -}; - // Our iterator as simple as iterators can be: basically it's just // the index into our table. Dereference, the only complicated // thing, we punt to the table class. This just goes to show how @@ -1774,23 +1800,11 @@ public: typedef typename tabletype::value_type value_type; typedef typename tabletype::difference_type difference_type; typedef typename tabletype::size_type size_type; - typedef table_element_adaptor<tabletype> reference; - typedef table_element_adaptor<tabletype>* pointer; explicit table_iterator(tabletype *tbl = 0, size_type p = 0) : table(tbl), pos(p) { } - // The main thing our iterator does is dereference. If the table entry - // we point to is empty, we return the default value type. - // This is the big different function from the const iterator. - reference operator*() - { - return table_element_adaptor<tabletype>(table, pos); - } - - pointer operator->() { return &(operator*()); } - // Helper function to assert things are ok; eg pos is still in range void check() const { @@ -1834,11 +1848,6 @@ public: return pos - it.pos; } - reference operator[](difference_type n) const - { - return *(*this + n); // simple though not totally efficient - } - // Comparisons. bool operator==(const iterator& it) const { @@ -2306,7 +2315,6 @@ public: typedef value_type* pointer; typedef const value_type* const_pointer; - typedef table_element_adaptor<sparsegroup<T, Alloc> > element_adaptor; typedef uint8_t size_type; // max # of buckets // These are our special iterators, that go over non-empty buckets in a @@ -2332,16 +2340,6 @@ public: const_reverse_ne_iterator ne_rend() const { return const_reverse_ne_iterator(ne_cbegin()); } const_reverse_ne_iterator ne_crend() const { return const_reverse_ne_iterator(ne_cbegin()); } - - // This gives us the "default" value to return for an empty bucket. - // We just use the default constructor on T, the template type - // ---------------------------------------------------------------- - const_reference default_value() const - { - static value_type defaultval = value_type(); - return defaultval; - } - private: // T can be std::pair<K, V>, but we need to return std::pair<const K, V> // --------------------------------------------------------------------- @@ -2566,16 +2564,6 @@ public: // We also may want to know how many *used* buckets there are size_type num_nonempty() const { return (size_type)_num_items(); } - // get()/set() are explicitly const/non-const. You can use [] if - // you want something that can be either (potentially more expensive). - const_reference get(size_type i) const - { - if (_bmtest(i)) // bucket i is occupied - return (const_reference)_group[pos_to_offset(i)]; - else - return default_value(); // return the default reference - } - // TODO(csilvers): make protected + friend // This is used by sparse_hashtable to get an element from the table // when we know it exists. @@ -2587,47 +2575,52 @@ public: typedef std::pair<mutable_pointer, bool> SetResult; - // returns a reference which can be assigned, so we have to create an entry if not - // already there - // ------------------------------------------------------------------------------- - reference mutating_get(Alloc &alloc, size_type i) - { - // fills bucket i before getting - if (!_bmtest(i)) - { - SetResult sr = set(alloc, i, false); - if (!sr.second) - ::new (sr.first) mutable_value_type(); - return *((pointer)sr.first); - } +private: + typedef spp_::integral_constant<bool, + (spp_::is_relocatable<value_type>::value && + spp_::is_same<allocator_type, + spp_::libc_allocator_with_realloc<mutable_value_type> >::value)> + realloc_and_memmove_ok; - return _group[pos_to_offset(i)]; + // ------------------------- memory at *p is uninitialized => need to construct + void _init_val(mutable_value_type *p, reference val) + { +#if !defined(SPP_NO_CXX11_RVALUE_REFERENCES) + ::new (p) mutable_value_type(std::move(val)); +#else + ::new (p) mutable_value_type(val); +#endif } - // Syntactic sugar. It's easy to return a const reference. To - // return a non-const reference, we need to use the assigner adaptor. - const_reference operator[](size_type i) const + // ------------------------- memory at *p is uninitialized => need to construct + void _init_val(mutable_value_type *p, const_reference val) { - return get(i); + ::new (p) mutable_value_type(val); } - element_adaptor operator[](size_type i) + // ------------------------------------------------ memory at *p is initialized + void _set_val(mutable_value_type *p, reference val) { - return element_adaptor(this, i); +#if !defined(SPP_NO_CXX11_RVALUE_REFERENCES) + *p = std::move(val); +#else + using std::swap; + swap(*p, spp_mutable_ref(val)); +#endif } -private: - typedef spp_::integral_constant<bool, - (spp_::is_relocatable<value_type>::value && - spp_::is_same<allocator_type, - spp_::libc_allocator_with_realloc<mutable_value_type> >::value)> - realloc_and_memmove_ok; + // ------------------------------------------------ memory at *p is initialized + void _set_val(mutable_value_type *p, const_reference val) + { + *p = spp_const_mutable_ref(val); + } // Our default allocator - try to merge memory buffers // right now it uses Google's traits, but we should use something like folly::IsRelocatable // return true if the slot was constructed (i.e. contains a valid mutable_value_type // --------------------------------------------------------------------------------- - bool _set_aux(Alloc &alloc, size_type offset, spp_::true_type) + template <class Val> + void _set_aux(Alloc &alloc, size_type offset, Val &val, spp_::true_type) { //static int x=0; if (++x < 10) printf("x\n"); // check we are getting here @@ -2643,14 +2636,16 @@ private: for (uint32_t i = num_items; i > offset; --i) memcpy(_group + i, _group + i-1, sizeof(*_group)); - return false; + + _init_val(_group + offset, val); } // Create space at _group[offset], without special assumptions about value_type // and allocator_type, with a default value // return true if the slot was constructed (i.e. contains a valid mutable_value_type // --------------------------------------------------------------------------------- - bool _set_aux(Alloc &alloc, size_type offset, spp_::false_type) + template <class Val> + void _set_aux(Alloc &alloc, size_type offset, Val &val, spp_::false_type) { uint32_t num_items = _num_items(); uint32_t num_alloc = _sizing(num_items); @@ -2659,9 +2654,9 @@ private: if (num_items < num_alloc) { // create new object at end and rotate it to position - ::new (&_group[num_items]) mutable_value_type(); + _init_val(&_group[num_items], val); std::rotate(_group + offset, _group + num_items, _group + num_items + 1); - return true; + return; } // This is valid because 0 <= offset <= num_items @@ -2674,57 +2669,37 @@ private: std::uninitialized_copy(MK_MOVE_IT(_group + offset), MK_MOVE_IT(_group + num_items), p + offset + 1); + _init_val(p + offset, val); _free_group(alloc, num_alloc); _group = p; - return false; } -public: - - // TODO(austern): Make this exception safe: handle exceptions from - // value_type's copy constructor. - // return true if the slot was constructed (i.e. contains a valid mutable_value_type) // ---------------------------------------------------------------------------------- - bool _set(Alloc &alloc, size_type i, size_type offset, bool erased) + template <class Val> + void _set(Alloc &alloc, size_type i, size_type offset, Val &val) { - if (erased) - { - // assert(_bme_test(i)); - _bme_clear(i); - } - if (!_bmtest(i)) { - bool res = _set_aux(alloc, offset, realloc_and_memmove_ok()); + _set_aux(alloc, offset, val, realloc_and_memmove_ok()); _incr_num_items(); _bmset(i); - return res; } - return true; + else + _set_val(&_group[offset], val); } - // This returns a pair (first is a pointer to the item's location, second is whether - // that location is constructed (i.e. contains a valid mutable_value_type) - // --------------------------------------------------------------------------------- - SetResult set(Alloc &alloc, size_type i, bool erased) - { - size_type offset = pos_to_offset(i); - bool constructed = _set(alloc, i, offset, erased); // may change _group pointer - return std::make_pair(_group + offset, constructed); - } +public: - // used in _move_from (where we can move the old value instead of copying it - // ------------------------------------------------------------------------- - void move(Alloc &alloc, size_type i, reference val) + // This returns the pointer to the inserted item + // --------------------------------------------- + template <class Val> + pointer set(Alloc &alloc, size_type i, Val &val) { - // assert(!_bmtest(i)); + _bme_clear(i); // in case this was an "erased" location - size_type offset = pos_to_offset(i); - if (!_set(alloc, i, offset, false)) - ::new (&_group[offset]) mutable_value_type(); - - using std::swap; - swap(_group[offset], spp_mutable_ref(val)); // called from _move_from, OK to swap + size_type offset = pos_to_offset(i); + _set(alloc, i, offset, val); // may change _group pointer + return (pointer)(_group + offset); } // We let you see if a bucket is non-empty without retrieving it @@ -3074,7 +3049,6 @@ public: typedef table_iterator<sparsetable<T, Alloc> > iterator; // defined with index typedef const_table_iterator<sparsetable<T, Alloc> > const_iterator; // defined with index - typedef table_element_adaptor<sparsetable<T, Alloc> > element_adaptor; typedef std::reverse_iterator<const_iterator> const_reverse_iterator; typedef std::reverse_iterator<iterator> reverse_iterator; @@ -3438,14 +3412,6 @@ public: return which_group(pos.pos).test(pos_in_group(pos.pos)); } - // We only return const_references because it's really hard to - // return something settable for empty buckets. Use set() instead. - const_reference get(size_type i) const - { - assert(i < _table_size); - return which_group(i).get(pos_in_group(i)); - } - // TODO(csilvers): make protected + friend // This is used by sparse_hashtable to get an element from the table // when we know it exists (because the caller has called test(i)). @@ -3457,30 +3423,6 @@ public: return which_group(i).unsafe_get(pos_in_group(i)); } - // TODO(csilvers): make protected + friend element_adaptor - reference mutating_get(size_type i) - { - // fills bucket i before getting - assert(i < _table_size); - - GroupsReference grp(which_group(i)); - typename group_type::size_type old_numbuckets = grp.num_nonempty(); - reference retval = grp.mutating_get(_alloc, pos_in_group(i)); - _num_buckets += grp.num_nonempty() - old_numbuckets; - return retval; - } - - // Syntactic sugar. As in sparsegroup, the non-const version is harder - const_reference operator[](size_type i) const - { - return get(i); - } - - element_adaptor operator[](size_type i) - { - return element_adaptor(this, i); - } - // Needed for hashtables, gets as a ne_iterator. Crashes for empty bcks const_ne_iterator get_iter(size_type i) const { @@ -3524,28 +3466,24 @@ public: _first_group[current_row].offset_to_pos(current_col)); } - // This returns a reference to the inserted item (which is a copy of val) - // The trick is to figure out whether we're replacing or inserting anew - // ---------------------------------------------------------------------- - reference set(size_type i, const_reference val, bool erased = false) + // Val can be reference or const_reference + // --------------------------------------- + template <class Val> + reference set(size_type i, Val &val) { assert(i < _table_size); group_type &group = which_group(i); typename group_type::size_type old_numbuckets = group.num_nonempty(); - typename group_type::SetResult sr(group.set(_alloc, pos_in_group(i), erased)); - if (!sr.second) - ::new (sr.first) mutable_value_type(val); - else - *sr.first = spp_const_mutable_ref(val); + pointer p(group.set(_alloc, pos_in_group(i), val)); _num_buckets += group.num_nonempty() - old_numbuckets; - return *((pointer)sr.first); + return *p; } // used in _move_from (where we can move the old value instead of copying it void move(size_type i, reference val) { assert(i < _table_size); - which_group(i).move(_alloc, pos_in_group(i), val); + which_group(i).set(_alloc, pos_in_group(i), val); ++_num_buckets; } @@ -3816,7 +3754,7 @@ private: public: typedef Key key_type; typedef typename spp::cvt<Value>::type value_type; - typedef HashFcn hasher; + typedef HashFcn hasher; // user provided or spp_hash<Key> typedef EqualKey key_equal; typedef Alloc allocator_type; @@ -4101,7 +4039,7 @@ private: assert(num_probes < bucket_count() && "Hashtable is full: an error in key_equal<> or hash<>"); } - table.set(bucknum, *it, false); // copies the value to here + table.set(bucknum, *it); // copies the value to here } settings.inc_num_ht_copies(); } @@ -4483,7 +4421,8 @@ public: // INSERTION ROUTINES private: // Private method used by insert_noresize and find_or_insert. - reference _insert_at(const_reference obj, size_type pos, bool erased) + template <class T> + reference _insert_at(T& obj, size_type pos, bool erased) { if (size() >= max_size()) { @@ -4494,11 +4433,12 @@ private: assert(num_deleted); --num_deleted; } - return table.set(pos, obj, erased); + return table.set(pos, obj); } // If you know *this is big enough to hold obj, use this routine - std::pair<iterator, bool> _insert_noresize(const_reference obj) + template <class T> + std::pair<iterator, bool> _insert_noresize(T& obj) { Position pos = _find_position(get_key(obj)); bool already_there = (pos._t == pt_full); @@ -4536,17 +4476,13 @@ private: public: -#if 0 && !defined(SPP_NO_CXX11_VARIADIC_TEMPLATES) +#if !defined(SPP_NO_CXX11_VARIADIC_TEMPLATES) template <class... Args> - pair<iterator, bool> emplace(Args&&... args) + std::pair<iterator, bool> emplace(Args&&... args) { - return rep.emplace_unique(std::forward<Args>(args)...); - } - - template <class... Args> - iterator emplace_hint(const_iterator p, Args&&... args) - { - return rep.emplace_unique(std::forward<Args>(args)...).first; + _resize_delta(1); + value_type obj(std::forward<Args>(args)...); + return _insert_noresize(obj); } #endif @@ -4589,12 +4525,14 @@ public: { // needed to rehash to make room // Since we resized, we can't use pos, so recalculate where to insert. - return *(_insert_noresize(default_value(key)).first); + value_type def(default_value(key)); + return *(_insert_noresize(def).first); } else { // no need to rehash, insert right here - return _insert_at(default_value(key), erased ? erased_pos : bucknum, erased); + value_type def(default_value(key)); + return _insert_at(def, erased ? erased_pos : bucknum, erased); } } if (grp_pos.test()) @@ -5153,6 +5091,20 @@ public: return it->second; } +#if !defined(SPP_NO_CXX11_VARIADIC_TEMPLATES) + template <class... Args> + std::pair<iterator, bool> emplace(Args&&... args) + { + return rep.emplace(std::forward<Args>(args)...); + } + + template <class... Args> + iterator emplace_hint(const_iterator , Args&&... args) + { + return rep.emplace(std::forward<Args>(args)...).first; + } +#endif + // Insert // ------ std::pair<iterator, bool> @@ -5496,17 +5448,17 @@ public: std::pair<iterator, iterator> equal_range(const key_type& key) const { return rep.equal_range(key); } -#if 0 && !defined(SPP_NO_CXX11_VARIADIC_TEMPLATES) +#if !defined(SPP_NO_CXX11_VARIADIC_TEMPLATES) template <class... Args> - pair<iterator, bool> emplace(Args&&... args) + std::pair<iterator, bool> emplace(Args&&... args) { - return rep.emplace_unique(std::forward<Args>(args)...); + return rep.emplace(std::forward<Args>(args)...); } template <class... Args> - iterator emplace_hint(const_iterator p, Args&&... args) + iterator emplace_hint(const_iterator , Args&&... args) { - return rep.emplace_unique(std::forward<Args>(args)...).first; + return rep.emplace(std::forward<Args>(args)...).first; } #endif diff --git a/resources/3rdparty/sparsepp/spp_test.cc b/resources/3rdparty/sparsepp/spp_test.cc index 281db9154..e17eb0f82 100644 --- a/resources/3rdparty/sparsepp/spp_test.cc +++ b/resources/3rdparty/sparsepp/spp_test.cc @@ -1,39 +1,9 @@ // ---------------------------------------------------------------------- -// Copyright (c) 2016, Steven Gregory Popovitch - greg7mdp@gmail.com +// Copyright (c) 2016, Gregory Popovitch - greg7mdp@gmail.com // All rights reserved. // // This work is derived from Google's sparsehash library -// (see https://github.com/sparsehash/sparsehash) whose copyright appears -// below this one. // -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * The name of Steven Gregory Popovitch may not be used to -// endorse or promote products derived from this software without -// specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// ---------------------------------------------------------------------- - -// ---------------------------------------------------------------------- // Copyright (c) 2010, Google Inc. // All rights reserved. // @@ -835,7 +805,7 @@ struct TypeList3 typedef typelist::type1 classname##_type6; \ typedef typelist::type1 classname##_type7; \ typedef typelist::type1 classname##_type8; \ - typedef typelist::type1 classname##_type9; + typedef typelist::type1 classname##_type9 template<typename C1, typename C2, typename C3, typename C4, typename C5, typename C6, typename C7, typename C8, typename C9> @@ -862,7 +832,7 @@ struct TypeList9 typedef typelist::type7 classname##_type7; \ typedef typelist::type8 classname##_type8; \ typedef typelist::type9 classname##_type9; \ - static const int classname##_numtypes = 9; + static const int classname##_numtypes = 9 #define TYPED_TEST(superclass, testname) \ template<typename TypeParam> \ @@ -1171,7 +1141,7 @@ struct Identity // This is just to avoid memory leaks -- it's a global pointer to // all the memory allocated by UniqueObjectHelper. We'll use it // to semi-test sparsetable as well. :-) -sparsetable<char*> g_unique_charstar_objects(16); +std::vector<char*> g_unique_charstar_objects(16, (char *)0); // This is an object-generator: pass in an index, and it will return a // unique object of type ItemType. We provide specializations for the @@ -1190,20 +1160,20 @@ template<> string UniqueObjectHelper(int index) template<> char* UniqueObjectHelper(int index) { // First grow the table if need be. - sparsetable<char*>::size_type table_size = g_unique_charstar_objects.size(); + size_t table_size = g_unique_charstar_objects.size(); while (index >= static_cast<int>(table_size)) { assert(table_size * 2 > table_size); // avoid overflow problems table_size *= 2; } if (table_size > g_unique_charstar_objects.size()) - g_unique_charstar_objects.resize(table_size); - - if (!g_unique_charstar_objects.test((size_t)index)) { + g_unique_charstar_objects.resize(table_size, (char *)0); + + if (!g_unique_charstar_objects[static_cast<size_t>(index)]) { char buffer[64]; snprintf(buffer, sizeof(buffer), "%d", index); - g_unique_charstar_objects[(size_t)index] = _strdup(buffer); + g_unique_charstar_objects[static_cast<size_t>(index)] = _strdup(buffer); } - return g_unique_charstar_objects.get((size_t)index); + return g_unique_charstar_objects[static_cast<size_t>(index)]; } template<> const char* UniqueObjectHelper(int index) { return UniqueObjectHelper<char*>(index); @@ -1475,6 +1445,8 @@ TYPED_TEST(HashtableIntTest, Typedefs) (void)dt; (void)p; (void)cp; + (void)kt; + (void)st; i = this->ht_.begin(); ci = this->ht_.begin(); li = this->ht_.begin(0); @@ -1493,6 +1465,93 @@ TYPED_TEST(HashtableAllTest, NormalIterators) } } + +#if !defined(SPP_NO_CXX11_VARIADIC_TEMPLATES) + +template <class T> struct MyHash; +typedef std::pair<std::string, std::string> StringPair; + +template<> struct MyHash<StringPair> +{ + size_t operator()(StringPair const& p) const + { + return std::hash<string>()(p.first); + } +}; + +class MovableOnlyType +{ + std::string _str; + std::uint64_t _int; + +public: + // Make object movable and non-copyable + MovableOnlyType(MovableOnlyType &&) = default; + MovableOnlyType(const MovableOnlyType &) = delete; + MovableOnlyType& operator=(MovableOnlyType &&) = default; + MovableOnlyType& operator=(const MovableOnlyType &) = delete; + MovableOnlyType() : _str("whatever"), _int(2) {} +}; + +void movable_emplace_test(std::size_t iterations, int container_size) +{ + for (std::size_t i=0;i<iterations;++i) + { + spp::sparse_hash_map<std::string,MovableOnlyType> m; + m.reserve(static_cast<size_t>(container_size)); + char buff[20]; + for (int j=0; j<container_size; ++j) + { + sprintf(buff, "%d", j); + m.emplace(buff, MovableOnlyType()); + } + } +} + +TEST(HashtableTest, Emplace) +{ + { + sparse_hash_map<std::string, std::string> mymap; + + mymap.emplace ("NCC-1701", "J.T. Kirk"); + mymap.emplace ("NCC-1701-D", "J.L. Picard"); + mymap.emplace ("NCC-74656", "K. Janeway"); + EXPECT_TRUE(mymap["NCC-74656"] == std::string("K. Janeway")); + + sparse_hash_set<StringPair, MyHash<StringPair> > myset; + myset.emplace ("NCC-1701", "J.T. Kirk"); + } + + movable_emplace_test(10, 50); +} +#endif + + +#if !defined(SPP_NO_CXX11_VARIADIC_TEMPLATES) +TEST(HashtableTest, IncompleteTypes) +{ + int i; + sparse_hash_map<int *, int> ht2; + ht2[&i] = 3; + + struct Bogus; + sparse_hash_map<Bogus *, int> ht3; + ht3[(Bogus *)0] = 8; +} +#endif + + +#if !defined(SPP_NO_CXX11_VARIADIC_TEMPLATES) +TEST(HashtableTest, ReferenceWrapper) +{ + sparse_hash_map<int, std::reference_wrapper<int>> x; + int a = 5; + x.insert(std::make_pair(3, std::ref(a))); + EXPECT_EQ(x.at(3), 5); +} +#endif + + TEST(HashtableTest, ModifyViaIterator) { // This only works for hash-maps, since only they have non-const values. diff --git a/resources/3rdparty/sparsepp/spp_utils.h b/resources/3rdparty/sparsepp/spp_utils.h index 6b627233c..96a8f5bf3 100644 --- a/resources/3rdparty/sparsepp/spp_utils.h +++ b/resources/3rdparty/sparsepp/spp_utils.h @@ -114,6 +114,12 @@ #define SPP_NOEXCEPT noexcept #endif +#ifdef SPP_NO_CXX11_CONSTEXPR + #define SPP_CONSTEXPR +#else + #define SPP_CONSTEXPR constexpr +#endif + #define SPP_INLINE #ifndef SPP_NAMESPACE @@ -149,75 +155,109 @@ struct spp_hash<T *> SPP_INLINE size_t operator()(const T *__v) const SPP_NOEXCEPT { - static const size_t shift = spp_log2(1 + sizeof(T)); + static const size_t shift = 3; // spp_log2(1 + sizeof(T)); // T might be incomplete! return static_cast<size_t>((*(reinterpret_cast<const uintptr_t *>(&__v))) >> shift); } }; +// from http://burtleburtle.net/bob/hash/integer.html +// fast and efficient for power of two table sizes where we always +// consider the last bits. +// --------------------------------------------------------------- +inline size_t spp_mix_32(uint32_t a) +{ + a = a ^ (a >> 4); + a = (a ^ 0xdeadbeef) + (a << 5); + a = a ^ (a >> 11); + return static_cast<size_t>(a); +} + +// Maybe we should do a more thorough scrambling as described in +// https://gist.github.com/badboy/6267743 +// ------------------------------------------------------------- +inline size_t spp_mix_64(uint64_t a) +{ + a = a ^ (a >> 4); + a = (a ^ 0xdeadbeef) + (a << 5); + a = a ^ (a >> 11); + return a; +} + template <> struct spp_hash<bool> : public std::unary_function<bool, size_t> { - SPP_INLINE size_t operator()(bool __v) const SPP_NOEXCEPT {return static_cast<size_t>(__v);} + SPP_INLINE size_t operator()(bool __v) const SPP_NOEXCEPT + { return static_cast<size_t>(__v); } }; template <> struct spp_hash<char> : public std::unary_function<char, size_t> { - SPP_INLINE size_t operator()(char __v) const SPP_NOEXCEPT {return static_cast<size_t>(__v);} + SPP_INLINE size_t operator()(char __v) const SPP_NOEXCEPT + { return static_cast<size_t>(__v); } }; template <> struct spp_hash<signed char> : public std::unary_function<signed char, size_t> { - SPP_INLINE size_t operator()(signed char __v) const SPP_NOEXCEPT {return static_cast<size_t>(__v);} + SPP_INLINE size_t operator()(signed char __v) const SPP_NOEXCEPT + { return static_cast<size_t>(__v); } }; template <> struct spp_hash<unsigned char> : public std::unary_function<unsigned char, size_t> { - SPP_INLINE size_t operator()(unsigned char __v) const SPP_NOEXCEPT {return static_cast<size_t>(__v);} + SPP_INLINE size_t operator()(unsigned char __v) const SPP_NOEXCEPT + { return static_cast<size_t>(__v); } }; template <> struct spp_hash<wchar_t> : public std::unary_function<wchar_t, size_t> { - SPP_INLINE size_t operator()(wchar_t __v) const SPP_NOEXCEPT {return static_cast<size_t>(__v);} + SPP_INLINE size_t operator()(wchar_t __v) const SPP_NOEXCEPT + { return static_cast<size_t>(__v); } }; template <> -struct spp_hash<short> : public std::unary_function<short, size_t> +struct spp_hash<int16_t> : public std::unary_function<int16_t, size_t> { - SPP_INLINE size_t operator()(short __v) const SPP_NOEXCEPT {return static_cast<size_t>(__v);} + SPP_INLINE size_t operator()(int16_t __v) const SPP_NOEXCEPT + { return spp_mix_32(static_cast<uint32_t>(__v)); } }; template <> -struct spp_hash<unsigned short> : public std::unary_function<unsigned short, size_t> +struct spp_hash<uint16_t> : public std::unary_function<uint16_t, size_t> { - SPP_INLINE size_t operator()(unsigned short __v) const SPP_NOEXCEPT {return static_cast<size_t>(__v);} + SPP_INLINE size_t operator()(uint16_t __v) const SPP_NOEXCEPT + { return spp_mix_32(static_cast<uint32_t>(__v)); } }; template <> -struct spp_hash<int> : public std::unary_function<int, size_t> +struct spp_hash<int32_t> : public std::unary_function<int32_t, size_t> { - SPP_INLINE size_t operator()(int __v) const SPP_NOEXCEPT {return static_cast<size_t>(__v);} + SPP_INLINE size_t operator()(int32_t __v) const SPP_NOEXCEPT + { return spp_mix_32(static_cast<uint32_t>(__v)); } }; template <> -struct spp_hash<unsigned int> : public std::unary_function<unsigned int, size_t> +struct spp_hash<uint32_t> : public std::unary_function<uint32_t, size_t> { - SPP_INLINE size_t operator()(unsigned int __v) const SPP_NOEXCEPT {return static_cast<size_t>(__v);} + SPP_INLINE size_t operator()(uint32_t __v) const SPP_NOEXCEPT + { return spp_mix_32(static_cast<uint32_t>(__v)); } }; template <> -struct spp_hash<long> : public std::unary_function<long, size_t> +struct spp_hash<int64_t> : public std::unary_function<int64_t, size_t> { - SPP_INLINE size_t operator()(long __v) const SPP_NOEXCEPT {return static_cast<size_t>(__v);} + SPP_INLINE size_t operator()(int64_t __v) const SPP_NOEXCEPT + { return spp_mix_64(static_cast<uint64_t>(__v)); } }; template <> -struct spp_hash<unsigned long> : public std::unary_function<unsigned long, size_t> +struct spp_hash<uint64_t> : public std::unary_function<uint64_t, size_t> { - SPP_INLINE size_t operator()(unsigned long __v) const SPP_NOEXCEPT {return static_cast<size_t>(__v);} + SPP_INLINE size_t operator()(uint64_t __v) const SPP_NOEXCEPT + { return spp_mix_64(static_cast<uint64_t>(__v)); } }; template <> @@ -227,22 +267,20 @@ struct spp_hash<float> : public std::unary_function<float, size_t> { // -0.0 and 0.0 should return same hash uint32_t *as_int = reinterpret_cast<uint32_t *>(&__v); - return (__v == 0) ? static_cast<size_t>(0) : static_cast<size_t>(*as_int); + return (__v == 0) ? static_cast<size_t>(0) : spp_mix_32(*as_int); } }; -#if 0 -// todo: we should not ignore half of the double => see libcxx/include/functional template <> struct spp_hash<double> : public std::unary_function<double, size_t> { SPP_INLINE size_t operator()(double __v) const SPP_NOEXCEPT { // -0.0 and 0.0 should return same hash - return (__v == 0) ? (size_t)0 : (size_t)*((uint64_t *)&__v); + uint64_t *as_int = reinterpret_cast<uint64_t *>(&__v); + return (__v == 0) ? static_cast<size_t>(0) : spp_mix_64(*as_int); } }; -#endif template <class T, int sz> struct Combiner { @@ -274,7 +312,7 @@ inline void hash_combine(std::size_t& seed, T const& v) combiner(seed, hasher(v)); } -}; +} #endif // spp_utils_h_guard_ diff --git a/resources/3rdparty/sylvan/CMakeLists.txt b/resources/3rdparty/sylvan/CMakeLists.txt index 558b0458d..3d7aaaca7 100644 --- a/resources/3rdparty/sylvan/CMakeLists.txt +++ b/resources/3rdparty/sylvan/CMakeLists.txt @@ -2,8 +2,15 @@ cmake_minimum_required(VERSION 2.6) project(sylvan C CXX) enable_testing() +option(SYLVAN_PORTABLE "If set, the created library will be portable." OFF) + set(CMAKE_C_FLAGS "-O3 -Wextra -Wall -fno-strict-aliasing -std=gnu11 -fPIC") -set(CMAKE_CXX_FLAGS "-O3 -Wextra -Wall -fno-strict-aliasing -Wno-deprecated-register -std=gnu++11 -fPIC") +set(CMAKE_CXX_FLAGS "-O3 -Wextra -Wall -fno-strict-aliasing -Wno-deprecated-register -std=c++14 -fPIC") + +if (NOT SYLVAN_PORTABLE) + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -march=native") + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -march=native") +endif() option(USE_CARL "Sets whether carl should be included." ON) option(WITH_COVERAGE "Add generation of test coverage" OFF) @@ -30,15 +37,9 @@ if(WITH_COVERAGE) endif() if(USE_CARL) - find_package(carl QUIET REQUIRED) - if(carl_FOUND) - add_definitions(-DSYLVAN_HAVE_CARL) - include_directories("${carl_INCLUDE_DIR}") - list(APPEND STORM_LINK_LIBRARIES ${carl_LIBRARIES}) - message(STATUS "Sylvan - using CARL.") - else() - message(FATAL_ERROR "Sylvan - CARL was requested but not found") - endif() + add_definitions(-DSYLVAN_HAVE_CARL) + include_directories("${carl_INCLUDE_DIR}") + message(STATUS "Sylvan - using CARL.") else() message(STATUS "Sylvan - not using CARL.") endif() @@ -51,7 +52,6 @@ include_directories("${PROJECT_SOURCE_DIR}/../../../src") include_directories("${PROJECT_BINARY_DIR}/../../../include") include_directories(src) -include_directories(src) add_subdirectory(src) diff --git a/resources/cmake/find_modules/FindXerces.cmake b/resources/cmake/find_modules/FindXerces.cmake deleted file mode 100644 index f16483769..000000000 --- a/resources/cmake/find_modules/FindXerces.cmake +++ /dev/null @@ -1,96 +0,0 @@ -# From https://code.google.com/p/libcitygml/source/browse/trunk/CMakeModules/FindXerces.cmake?r=95 -# - Try to find Xerces-C -# Once done this will define -# -# XERCESC_FOUND - system has Xerces-C -# XERCESC_INCLUDE - the Xerces-C include directory -# XERCESC_LIBRARY - Link these to use Xerces-C -# XERCESC_VERSION - Xerces-C found version - -IF (XERCESC_INCLUDE AND XERCESC_LIBRARY) - # in cache already - SET(XERCESC_FIND_QUIETLY TRUE) -ENDIF (XERCESC_INCLUDE AND XERCESC_LIBRARY) - - -FIND_PATH(XERCESC_INCLUDE NAMES xercesc/util/XercesVersion.hpp - PATHS - $ENV{XERCESC_INCLUDE_DIR} - ${XERCESC_INCLUDE_DIR} - /usr/local/include - /usr/include -) - -IF (XERCESC_STATIC) - FIND_LIBRARY(XERCESC_LIBRARIES NAMES xerces-c_static_3 xerces-c-3.1 xerces-c - PATHS - $ENV{XERCESC_LIBRARY_DIR} - ${XERCESC_LIBRARY_DIR} - /usr/lib - /usr/local/lib - ) - FIND_LIBRARY(XERCESC_LIBRARIES_DEBUG NAMES xerces-c_static_3D xerces-c-3.1D - PATHS - $ENV{XERCESC_LIBRARY_DIR} - ${XERCESC_LIBRARY_DIR} - /usr/lib - /usr/local/lib - ) - ADD_DEFINITIONS( -DXERCES_STATIC_LIBRARY ) -ELSE (XERCESC_STATIC) - FIND_LIBRARY(XERCESC_LIBRARY NAMES xerces-c_3 - PATHS - $ENV{XERCESC_LIBRARY_DIR} - ${XERCESC_LIBRARY_DIR} - ) - FIND_LIBRARY(XERCESC_LIBRARIES_DEBUG NAMES xerces-c_3D - PATHS - $ENV{XERCESC_LIBRARY_DIR} - ${XERCESC_LIBRARY_DIR} - ) -ENDIF (XERCESC_STATIC) - -IF (XERCESC_INCLUDE AND XERCESC_LIBRARIES) - SET(XERCESC_FOUND TRUE) -ELSE (XERCESC_INCLUDE AND XERCESC_LIBRARIES) - SET(XERCESC_FOUND FALSE) -ENDIF (XERCESC_INCLUDE AND XERCESC_LIBRARIES) - -IF(XERCESC_FOUND) - - FIND_PATH(XERCESC_XVERHPPPATH NAMES XercesVersion.hpp PATHS - ${XERCESC_INCLUDE} - PATH_SUFFIXES xercesc/util) - - IF ( ${XERCESC_XVERHPPPATH} STREQUAL XERCESC_XVERHPPPATH-NOTFOUND ) - SET(XERCES_VERSION "0") - ELSE( ${XERCESC_XVERHPPPATH} STREQUAL XERCESC_XVERHPPPATH-NOTFOUND ) - FILE(READ ${XERCESC_XVERHPPPATH}/XercesVersion.hpp XVERHPP) - - STRING(REGEX MATCHALL "\n *#define XERCES_VERSION_MAJOR +[0-9]+" XVERMAJ - ${XVERHPP}) - STRING(REGEX MATCH "\n *#define XERCES_VERSION_MINOR +[0-9]+" XVERMIN - ${XVERHPP}) - STRING(REGEX MATCH "\n *#define XERCES_VERSION_REVISION +[0-9]+" XVERREV - ${XVERHPP}) - - STRING(REGEX REPLACE "\n *#define XERCES_VERSION_MAJOR +" "" - XVERMAJ ${XVERMAJ}) - STRING(REGEX REPLACE "\n *#define XERCES_VERSION_MINOR +" "" - XVERMIN ${XVERMIN}) - STRING(REGEX REPLACE "\n *#define XERCES_VERSION_REVISION +" "" - XVERREV ${XVERREV}) - - SET(XERCESC_VERSION ${XVERMAJ}.${XVERMIN}.${XVERREV}) - - ENDIF ( ${XERCESC_XVERHPPPATH} STREQUAL XERCESC_XVERHPPPATH-NOTFOUND ) - - IF(NOT XERCESC_FIND_QUIETLY) - MESSAGE(STATUS "Found Xerces-C: ${XERCESC_LIBRARY}") - MESSAGE(STATUS " : ${XERCESC_INCLUDE}") - MESSAGE(STATUS " Version: ${XERCESC_VERSION}") - ENDIF(NOT XERCESC_FIND_QUIETLY) -ENDIF(XERCESC_FOUND) - - -MARK_AS_ADVANCED(XERCESC_INCLUDE XERCESC_LIBRARIES) diff --git a/src/storm-dft/modelchecker/dft/DFTModelChecker.cpp b/src/storm-dft/modelchecker/dft/DFTModelChecker.cpp index caa78060c..8ca775432 100644 --- a/src/storm-dft/modelchecker/dft/DFTModelChecker.cpp +++ b/src/storm-dft/modelchecker/dft/DFTModelChecker.cpp @@ -412,11 +412,11 @@ namespace storm { template<typename ValueType> void DFTModelChecker<ValueType>::printTimings(std::ostream& os) { os << "Times:" << std::endl; - os << "Exploration:\t" << explorationTimer.getTimeSeconds() << "s" << std::endl; - os << "Building:\t" << buildingTimer.getTimeSeconds() << "s" << std::endl; - os << "Bisimulation:\t" << bisimulationTimer.getTimeSeconds() << "s" << std::endl; - os << "Modelchecking:\t" << modelCheckingTimer.getTimeSeconds() << "s" << std::endl; - os << "Total:\t\t" << totalTimer.getTimeSeconds() << "s" << std::endl; + os << "Exploration:\t" << explorationTimer.getTimeInSeconds() << "s" << std::endl; + os << "Building:\t" << buildingTimer.getTimeInSeconds() << "s" << std::endl; + os << "Bisimulation:\t" << bisimulationTimer.getTimeInSeconds() << "s" << std::endl; + os << "Modelchecking:\t" << modelCheckingTimer.getTimeInSeconds() << "s" << std::endl; + os << "Total:\t\t" << totalTimer.getTimeInSeconds() << "s" << std::endl; } template<typename ValueType> diff --git a/src/storm-gspn-cli/storm-gspn.cpp b/src/storm-gspn-cli/storm-gspn.cpp index 12e3ef19f..fdf2594fc 100644 --- a/src/storm-gspn-cli/storm-gspn.cpp +++ b/src/storm-gspn-cli/storm-gspn.cpp @@ -31,6 +31,7 @@ #include "storm/settings/modules/CoreSettings.h" #include "storm/settings/modules/DebugSettings.h" #include "storm/settings/modules/JaniExportSettings.h" +#include "storm/settings/modules/ResourceSettings.h" /*! * Initialize the settings manager. @@ -45,6 +46,7 @@ void initializeSettings() { storm::settings::addModule<storm::settings::modules::CoreSettings>(); storm::settings::addModule<storm::settings::modules::DebugSettings>(); storm::settings::addModule<storm::settings::modules::JaniExportSettings>(); + storm::settings::addModule<storm::settings::modules::ResourceSettings>(); } @@ -94,21 +96,16 @@ int main(const int argc, const char **argv) { auto capacities = parseCapacitiesList(storm::settings::getModule<storm::settings::modules::GSPNSettings>().getCapacitiesFilename()); gspn->setCapacities(capacities); } - - - if(storm::settings::getModule<storm::settings::modules::GSPNExportSettings>().isWriteToDotSet()) { - std::ofstream file; - file.open(storm::settings::getModule<storm::settings::modules::GSPNExportSettings>().getWriteToDotFilename()); - gspn->writeDotToStream(file); - } + + storm::handleGSPNExportSettings(*gspn); if(storm::settings::getModule<storm::settings::modules::JaniExportSettings>().isJaniFileSet()) { storm::jani::Model* model = storm::buildJani(*gspn); storm::exportJaniModel(*model, {}, storm::settings::getModule<storm::settings::modules::JaniExportSettings>().getJaniFilename()); delete model; } - - + + delete gspn; return 0; // diff --git a/src/storm-gspn/adapters/XercesAdapter.h b/src/storm-gspn/adapters/XercesAdapter.h index d6fc4ea65..0a39c8f2e 100644 --- a/src/storm-gspn/adapters/XercesAdapter.h +++ b/src/storm-gspn/adapters/XercesAdapter.h @@ -1,7 +1,7 @@ #pragma once #include "storm-config.h" -#ifdef USE_XERCES +#ifdef STORM_HAVE_XERCES #include <xercesc/parsers/XercesDOMParser.hpp> #include <xercesc/util/XMLString.hpp> diff --git a/src/storm-gspn/builder/JaniGSPNBuilder.cpp b/src/storm-gspn/builder/JaniGSPNBuilder.cpp index 061e9bd67..386d2b0a2 100644 --- a/src/storm-gspn/builder/JaniGSPNBuilder.cpp +++ b/src/storm-gspn/builder/JaniGSPNBuilder.cpp @@ -1 +1,150 @@ #include "JaniGSPNBuilder.h" + +namespace storm { + namespace builder { + + storm::jani::Model* JaniGSPNBuilder::build(std::string const& automatonName) { + storm::jani::Model* model = new storm::jani::Model(gspn.getName(), storm::jani::ModelType::MA, janiVersion, expressionManager); + storm::jani::Automaton mainAutomaton(automatonName, expressionManager->declareIntegerVariable("loc")); + addVariables(model); + uint64_t locId = addLocation(mainAutomaton); + addEdges(mainAutomaton, locId); + model->addAutomaton(mainAutomaton); + model->setStandardSystemComposition(); + return model; + } + + void JaniGSPNBuilder::addVariables(storm::jani::Model* model) { + for (auto const& place : gspn.getPlaces()) { + storm::jani::Variable* janiVar = nullptr; + if (!place.hasRestrictedCapacity()) { + // Effectively no capacity limit known + janiVar = new storm::jani::UnboundedIntegerVariable(place.getName(), expressionManager->declareIntegerVariable(place.getName()), expressionManager->integer(place.getNumberOfInitialTokens())); + } else { + assert(place.hasRestrictedCapacity()); + janiVar = new storm::jani::BoundedIntegerVariable(place.getName(), expressionManager->declareIntegerVariable(place.getName()), expressionManager->integer(place.getNumberOfInitialTokens()), expressionManager->integer(0), expressionManager->integer(place.getCapacity())); + } + assert(janiVar != nullptr); + assert(vars.count(place.getID()) == 0); + vars[place.getID()] = &model->addVariable(*janiVar); + delete janiVar; + } + } + + uint64_t JaniGSPNBuilder::addLocation(storm::jani::Automaton& automaton) { + uint64_t janiLoc = automaton.addLocation(storm::jani::Location("loc")); + automaton.addInitialLocation("loc"); + return janiLoc; + } + + void JaniGSPNBuilder::addEdges(storm::jani::Automaton& automaton, uint64_t locId) { + + uint64_t lastPriority = -1; + storm::expressions::Expression lastPriorityGuard = expressionManager->boolean(false); + storm::expressions::Expression priorityGuard = expressionManager->boolean(true); + + for (auto const& partition : gspn.getPartitions()) { + storm::expressions::Expression guard = expressionManager->boolean(false); + + assert(lastPriority >= partition.priority); + if (lastPriority > partition.priority) { + priorityGuard = priorityGuard && !lastPriorityGuard; + lastPriority = partition.priority; + } else { + assert(lastPriority == partition.priority); + } + + // Compute enabled weight expression. + storm::expressions::Expression totalWeight = expressionManager->rational(0.0); + for (auto const& transId : partition.transitions) { + auto const& trans = gspn.getImmediateTransitions()[transId]; + if (trans.noWeightAttached()) { + continue; + } + storm::expressions::Expression destguard = expressionManager->boolean(true); + for (auto const& inPlaceEntry : trans.getInputPlaces()) { + destguard = destguard && (vars[inPlaceEntry.first]->getExpressionVariable() >= inPlaceEntry.second); + } + for (auto const& inhibPlaceEntry : trans.getInhibitionPlaces()) { + destguard = destguard && (vars[inhibPlaceEntry.first]->getExpressionVariable() < inhibPlaceEntry.second); + } + totalWeight = totalWeight + storm::expressions::ite(destguard, expressionManager->rational(trans.getWeight()), expressionManager->rational(0.0)); + + } + totalWeight = totalWeight.simplify(); + + + std::vector<storm::jani::OrderedAssignments> oas; + std::vector<storm::expressions::Expression> probabilities; + std::vector<uint64_t> destinationLocations; + for (auto const& transId : partition.transitions) { + auto const& trans = gspn.getImmediateTransitions()[transId]; + if (trans.noWeightAttached()) { + std::cout << "ERROR -- no weights attached at transition" << std::endl; + continue; + } + storm::expressions::Expression destguard = expressionManager->boolean(true); + std::vector<storm::jani::Assignment> assignments; + for (auto const& inPlaceEntry : trans.getInputPlaces()) { + destguard = destguard && (vars[inPlaceEntry.first]->getExpressionVariable() >= inPlaceEntry.second); + if (trans.getOutputPlaces().count(inPlaceEntry.first) == 0) { + assignments.emplace_back( *vars[inPlaceEntry.first], (vars[inPlaceEntry.first])->getExpressionVariable() - inPlaceEntry.second); + } + } + for (auto const& inhibPlaceEntry : trans.getInhibitionPlaces()) { + destguard = destguard && (vars[inhibPlaceEntry.first]->getExpressionVariable() < inhibPlaceEntry.second); + } + for (auto const& outputPlaceEntry : trans.getOutputPlaces()) { + if (trans.getInputPlaces().count(outputPlaceEntry.first) == 0) { + assignments.emplace_back( *vars[outputPlaceEntry.first], (vars[outputPlaceEntry.first])->getExpressionVariable() + outputPlaceEntry.second ); + } else { + assignments.emplace_back( *vars[outputPlaceEntry.first], (vars[outputPlaceEntry.first])->getExpressionVariable() + outputPlaceEntry.second - trans.getInputPlaces().at(outputPlaceEntry.first)); + } + } + destguard = destguard.simplify(); + guard = guard || destguard; + + oas.emplace_back(assignments); + destinationLocations.emplace_back(locId); + probabilities.emplace_back(storm::expressions::ite(destguard, (expressionManager->rational(trans.getWeight()) / totalWeight), expressionManager->rational(0.0))); + } + + std::shared_ptr<storm::jani::TemplateEdge> templateEdge = automaton.createTemplateEdge((priorityGuard && guard).simplify()); + for (auto const& oa : oas) { + templateEdge->addDestination(storm::jani::TemplateEdgeDestination(oa)); + } + storm::jani::Edge e(locId, storm::jani::Model::SILENT_ACTION_INDEX, boost::none, templateEdge, destinationLocations, probabilities); + automaton.addEdge(e); + lastPriorityGuard = lastPriorityGuard || guard; + + } + for (auto const& trans : gspn.getTimedTransitions()) { + storm::expressions::Expression guard = expressionManager->boolean(true); + + std::vector<storm::jani::Assignment> assignments; + for (auto const& inPlaceEntry : trans.getInputPlaces()) { + guard = guard && (vars[inPlaceEntry.first]->getExpressionVariable() >= inPlaceEntry.second); + if (trans.getOutputPlaces().count(inPlaceEntry.first) == 0) { + assignments.emplace_back( *vars[inPlaceEntry.first], (vars[inPlaceEntry.first])->getExpressionVariable() - inPlaceEntry.second); + } + } + for (auto const& inhibPlaceEntry : trans.getInhibitionPlaces()) { + guard = guard && (vars[inhibPlaceEntry.first]->getExpressionVariable() < inhibPlaceEntry.second); + } + for (auto const& outputPlaceEntry : trans.getOutputPlaces()) { + if (trans.getInputPlaces().count(outputPlaceEntry.first) == 0) { + assignments.emplace_back( *vars[outputPlaceEntry.first], (vars[outputPlaceEntry.first])->getExpressionVariable() + outputPlaceEntry.second ); + } else { + assignments.emplace_back( *vars[outputPlaceEntry.first], (vars[outputPlaceEntry.first])->getExpressionVariable() + outputPlaceEntry.second - trans.getInputPlaces().at(outputPlaceEntry.first)); + } + } + + std::shared_ptr<storm::jani::TemplateEdge> templateEdge = automaton.createTemplateEdge(guard); + templateEdge->addDestination(assignments); + storm::jani::Edge e(locId, storm::jani::Model::SILENT_ACTION_INDEX, expressionManager->rational(trans.getRate()), templateEdge, {locId}, {expressionManager->integer(1)}); + automaton.addEdge(e); + + } + } + } +} \ No newline at end of file diff --git a/src/storm-gspn/builder/JaniGSPNBuilder.h b/src/storm-gspn/builder/JaniGSPNBuilder.h index 92a7062b6..791989009 100644 --- a/src/storm-gspn/builder/JaniGSPNBuilder.h +++ b/src/storm-gspn/builder/JaniGSPNBuilder.h @@ -8,165 +8,32 @@ namespace storm { namespace builder { class JaniGSPNBuilder { public: - JaniGSPNBuilder(storm::gspn::GSPN const& gspn, std::shared_ptr<storm::expressions::ExpressionManager> const& expManager) : gspn(gspn), expressionManager(expManager) { + JaniGSPNBuilder(storm::gspn::GSPN const& gspn, std::shared_ptr<storm::expressions::ExpressionManager> const& expManager) + : gspn(gspn), expressionManager(expManager) { } virtual ~JaniGSPNBuilder() { - + // Intentionally left empty. } - storm::jani::Model* build() { - storm::jani::Model* model = new storm::jani::Model(gspn.getName(), storm::jani::ModelType::MA, janiVersion, expressionManager); - storm::jani::Automaton mainAutomaton("immediate", expressionManager->declareIntegerVariable("loc")); - addVariables(model); - uint64_t locId = addLocation(mainAutomaton); - addEdges(mainAutomaton, locId); - model->addAutomaton(mainAutomaton); - model->setStandardSystemComposition(); - return model; - } + storm::jani::Model* build(std::string const& automatonName = "gspn_automaton"); storm::jani::Variable const& getPlaceVariable(uint64_t placeId) { return *vars.at(placeId); } - - void addVariables(storm::jani::Model* model) { - for (auto const& place : gspn.getPlaces()) { - storm::jani::Variable* janiVar = nullptr; - if (!place.hasRestrictedCapacity()) { - // Effectively no capacity limit known - janiVar = new storm::jani::UnboundedIntegerVariable(place.getName(), expressionManager->declareIntegerVariable(place.getName()), expressionManager->integer(place.getNumberOfInitialTokens())); - } else { - assert(place.hasRestrictedCapacity()); - janiVar = new storm::jani::BoundedIntegerVariable(place.getName(), expressionManager->declareIntegerVariable(place.getName()), expressionManager->integer(place.getNumberOfInitialTokens()), expressionManager->integer(0), expressionManager->integer(place.getCapacity())); - } - assert(janiVar != nullptr); - assert(vars.count(place.getID()) == 0); - vars[place.getID()] = &model->addVariable(*janiVar); - delete janiVar; - } - } - - uint64_t addLocation(storm::jani::Automaton& automaton) { - uint64_t janiLoc = automaton.addLocation(storm::jani::Location("loc")); - automaton.addInitialLocation("loc"); - return janiLoc; - } - - void addEdges(storm::jani::Automaton& automaton, uint64_t locId) { - - uint64_t lastPriority = -1; - storm::expressions::Expression lastPriorityGuard = expressionManager->boolean(false); - storm::expressions::Expression priorityGuard = expressionManager->boolean(true); - // TODO here there is something to fix if we add transition partitions. - - for (auto const& partition : gspn.getPartitions()) { - storm::expressions::Expression guard = expressionManager->boolean(false); - - assert(lastPriority >= partition.priority); - if (lastPriority > partition.priority) { - priorityGuard = priorityGuard && !lastPriorityGuard; - lastPriority = partition.priority; - } else { - assert(lastPriority == partition.priority); - } - - // Compute enabled weight expression. - storm::expressions::Expression totalWeight = expressionManager->rational(0.0); - for (auto const& transId : partition.transitions) { - auto const& trans = gspn.getImmediateTransitions()[transId]; - if (trans.noWeightAttached()) { - continue; - } - storm::expressions::Expression destguard = expressionManager->boolean(true); - for (auto const& inPlaceEntry : trans.getInputPlaces()) { - destguard = destguard && (vars[inPlaceEntry.first]->getExpressionVariable() >= inPlaceEntry.second); - } - for (auto const& inhibPlaceEntry : trans.getInhibitionPlaces()) { - destguard = destguard && (vars[inhibPlaceEntry.first]->getExpressionVariable() < inhibPlaceEntry.second); - } - totalWeight = totalWeight + storm::expressions::ite(destguard, expressionManager->rational(trans.getWeight()), expressionManager->rational(0.0)); - - } - totalWeight = totalWeight.simplify(); - - - std::vector<storm::jani::OrderedAssignments> oas; - std::vector<storm::expressions::Expression> probabilities; - std::vector<uint64_t> destinationLocations; - for (auto const& transId : partition.transitions) { - auto const& trans = gspn.getImmediateTransitions()[transId]; - if (trans.noWeightAttached()) { - std::cout << "ERROR -- no weights attached at transition" << std::endl; - continue; - } - storm::expressions::Expression destguard = expressionManager->boolean(true); - std::vector<storm::jani::Assignment> assignments; - for (auto const& inPlaceEntry : trans.getInputPlaces()) { - destguard = destguard && (vars[inPlaceEntry.first]->getExpressionVariable() >= inPlaceEntry.second); - if (trans.getOutputPlaces().count(inPlaceEntry.first) == 0) { - assignments.emplace_back( *vars[inPlaceEntry.first], (vars[inPlaceEntry.first])->getExpressionVariable() - inPlaceEntry.second); - } - } - for (auto const& inhibPlaceEntry : trans.getInhibitionPlaces()) { - destguard = destguard && (vars[inhibPlaceEntry.first]->getExpressionVariable() < inhibPlaceEntry.second); - } - for (auto const& outputPlaceEntry : trans.getOutputPlaces()) { - if (trans.getInputPlaces().count(outputPlaceEntry.first) == 0) { - assignments.emplace_back( *vars[outputPlaceEntry.first], (vars[outputPlaceEntry.first])->getExpressionVariable() + outputPlaceEntry.second ); - } else { - assignments.emplace_back( *vars[outputPlaceEntry.first], (vars[outputPlaceEntry.first])->getExpressionVariable() + outputPlaceEntry.second - trans.getInputPlaces().at(outputPlaceEntry.first)); - } - } - destguard = destguard.simplify(); - guard = guard || destguard; - - oas.emplace_back(assignments); - destinationLocations.emplace_back(locId); - probabilities.emplace_back(storm::expressions::ite(destguard, (expressionManager->rational(trans.getWeight()) / totalWeight), expressionManager->rational(0.0))); - } - - std::shared_ptr<storm::jani::TemplateEdge> templateEdge = automaton.createTemplateEdge((priorityGuard && guard).simplify()); - for (auto const& oa : oas) { - templateEdge->addDestination(storm::jani::TemplateEdgeDestination(oa)); - } - storm::jani::Edge e(locId, storm::jani::Model::SILENT_ACTION_INDEX, boost::none, templateEdge, destinationLocations, probabilities); - automaton.addEdge(e); - lastPriorityGuard = lastPriorityGuard || guard; - - } - for (auto const& trans : gspn.getTimedTransitions()) { - storm::expressions::Expression guard = expressionManager->boolean(true); - - std::vector<storm::jani::Assignment> assignments; - for (auto const& inPlaceEntry : trans.getInputPlaces()) { - guard = guard && (vars[inPlaceEntry.first]->getExpressionVariable() >= inPlaceEntry.second); - if (trans.getOutputPlaces().count(inPlaceEntry.first) == 0) { - assignments.emplace_back( *vars[inPlaceEntry.first], (vars[inPlaceEntry.first])->getExpressionVariable() - inPlaceEntry.second); - } - } - for (auto const& inhibPlaceEntry : trans.getInhibitionPlaces()) { - guard = guard && (vars[inhibPlaceEntry.first]->getExpressionVariable() < inhibPlaceEntry.second); - } - for (auto const& outputPlaceEntry : trans.getOutputPlaces()) { - if (trans.getInputPlaces().count(outputPlaceEntry.first) == 0) { - assignments.emplace_back( *vars[outputPlaceEntry.first], (vars[outputPlaceEntry.first])->getExpressionVariable() + outputPlaceEntry.second ); - } else { - assignments.emplace_back( *vars[outputPlaceEntry.first], (vars[outputPlaceEntry.first])->getExpressionVariable() + outputPlaceEntry.second - trans.getInputPlaces().at(outputPlaceEntry.first)); - } - } - - std::shared_ptr<storm::jani::TemplateEdge> templateEdge = automaton.createTemplateEdge(guard); - templateEdge->addDestination(assignments); - storm::jani::Edge e(locId, storm::jani::Model::SILENT_ACTION_INDEX, expressionManager->rational(trans.getRate()), templateEdge, {locId}, {expressionManager->integer(1)}); - automaton.addEdge(e); - - } - } + private: + + + void addVariables(storm::jani::Model* model); + + uint64_t addLocation(storm::jani::Automaton& automaton); + + void addEdges(storm::jani::Automaton& automaton, uint64_t locId); + const uint64_t janiVersion = 1; storm::gspn::GSPN const& gspn; std::map<uint64_t, storm::jani::Variable const*> vars; diff --git a/src/storm-gspn/parser/GreatSpnEditorProjectParser.cpp b/src/storm-gspn/parser/GreatSpnEditorProjectParser.cpp index ce19a50a9..826124f25 100644 --- a/src/storm-gspn/parser/GreatSpnEditorProjectParser.cpp +++ b/src/storm-gspn/parser/GreatSpnEditorProjectParser.cpp @@ -1,9 +1,9 @@ #include "GreatSpnEditorProjectParser.h" -#ifdef USE_XERCES +#ifdef STORM_HAVE_XERCES #include <iostream> -#include "storm/adapters/XercesAdapter.h" +#include "storm-gspn/adapters/XercesAdapter.h" #include "storm/exceptions/UnexpectedException.h" #include "storm/exceptions/WrongFormatException.h" @@ -13,8 +13,8 @@ namespace storm { namespace parser { storm::gspn::GSPN* GreatSpnEditorProjectParser::parse(xercesc::DOMElement const* elementRoot) { if (storm::adapters::XMLtoString(elementRoot->getTagName()) == "project") { - GreatSpnEditorProjectParser p; - return p.parse(elementRoot); + traverseProjectElement(elementRoot); + return builder.buildGspn(); } else { // If the top-level node is not a "pnml" or "" node, then throw an exception. STORM_LOG_THROW(false, storm::exceptions::UnexpectedException, "Failed to identify the root element.\n"); @@ -311,11 +311,11 @@ namespace storm { if (kind.compare("INPUT") == 0) { - builder.addInputArc(head, tail, mult); + builder.addInputArc(tail, head, mult); } else if (kind.compare("INHIBITOR") == 0) { - builder.addInhibitionArc(head, tail, mult); + builder.addInhibitionArc(tail, head, mult); } else if (kind.compare("OUTPUT") == 0) { - builder.addOutputArc(head, tail, mult); + builder.addOutputArc(tail, head, mult); } else { // TODO error! } diff --git a/src/storm-gspn/parser/GreatSpnEditorProjectParser.h b/src/storm-gspn/parser/GreatSpnEditorProjectParser.h index f594aa993..7c0f5e713 100644 --- a/src/storm-gspn/parser/GreatSpnEditorProjectParser.h +++ b/src/storm-gspn/parser/GreatSpnEditorProjectParser.h @@ -1,15 +1,15 @@ #pragma once #include "storm-config.h" -#ifdef USE_XERCES +#ifdef STORM_HAVE_XERCES #include <string> #include <xercesc/parsers/XercesDOMParser.hpp> #include <xercesc/util/XMLString.hpp> -#include "storm/storage/gspn/GSPN.h" +#include "storm-gspn/storage/gspn/GSPN.h" -#include "storm/storage/gspn/GspnBuilder.h" +#include "storm-gspn/storage/gspn/GspnBuilder.h" namespace storm { namespace parser { diff --git a/src/storm-gspn/parser/GspnParser.cpp b/src/storm-gspn/parser/GspnParser.cpp index dfb3575d3..b92b6f006 100644 --- a/src/storm-gspn/parser/GspnParser.cpp +++ b/src/storm-gspn/parser/GspnParser.cpp @@ -13,7 +13,7 @@ namespace storm { namespace parser { storm::gspn::GSPN* GspnParser::parse(std::string const& filename) { -#ifdef USE_XERCES +#ifdef STORM_HAVE_XERCES // initialize xercesc try { xercesc::XMLPlatformUtils::Initialize(); diff --git a/src/storm-gspn/parser/PnmlParser.cpp b/src/storm-gspn/parser/PnmlParser.cpp index 4869405eb..3dfd9e2a6 100644 --- a/src/storm-gspn/parser/PnmlParser.cpp +++ b/src/storm-gspn/parser/PnmlParser.cpp @@ -1,9 +1,9 @@ #include "storm-gspn/parser/PnmlParser.h" -#ifdef USE_XERCES +#ifdef STORM_HAVE_XERCES #include <iostream> -#include "storm/adapters/XercesAdapter.h" +#include "storm-gspn/adapters/XercesAdapter.h" #include "storm/exceptions/UnexpectedException.h" #include "storm/exceptions/WrongFormatException.h" @@ -283,7 +283,7 @@ namespace storm { STORM_PRINT_AND_LOG("unknown multiplicity (node=arc): " + id + "\n"); } - STORM_LOG_THROW(false, storm::exceptions::UnexpectedException, "No arc type specified for arc '" + id + "'"); + if (type.second == "normal") { builder.addNormalArc(source.second, target.second, multiplicity.second); } else if (type.second == "inhibition") { diff --git a/src/storm-gspn/parser/PnmlParser.h b/src/storm-gspn/parser/PnmlParser.h index 8bf5592ae..e4b459eb2 100644 --- a/src/storm-gspn/parser/PnmlParser.h +++ b/src/storm-gspn/parser/PnmlParser.h @@ -1,14 +1,14 @@ #pragma once #include "storm-config.h" -#ifdef USE_XERCES +#ifdef STORM_HAVE_XERCES #include <string> #include <xercesc/parsers/XercesDOMParser.hpp> #include <xercesc/util/XMLString.hpp> -#include "storm/storage/gspn/GSPN.h" +#include "storm-gspn/storage/gspn/GSPN.h" -#include "storm/storage/gspn/GspnBuilder.h" +#include "storm-gspn/storage/gspn/GspnBuilder.h" namespace storm { namespace parser { diff --git a/src/storm-gspn/storage/gspn/GspnBuilder.cpp b/src/storm-gspn/storage/gspn/GspnBuilder.cpp index e0bbd76fd..a727ebebf 100644 --- a/src/storm-gspn/storage/gspn/GspnBuilder.cpp +++ b/src/storm-gspn/storage/gspn/GspnBuilder.cpp @@ -21,6 +21,7 @@ namespace storm { place.setNumberOfInitialTokens(initialTokens); place.setName(name); places.push_back(place); + placeNames.emplace(name, newId); return newId; } @@ -60,6 +61,8 @@ namespace storm { } immediateTransitions.push_back(trans); + + transitionNames.emplace(name, newId); return newId; } @@ -72,6 +75,8 @@ namespace storm { trans.setRate(rate); trans.setID(newId); timedTransitions.push_back(trans); + + transitionNames.emplace(name, newId); return newId; } diff --git a/src/storm/builder/DdJaniModelBuilder.cpp b/src/storm/builder/DdJaniModelBuilder.cpp index 929595495..33ee40758 100644 --- a/src/storm/builder/DdJaniModelBuilder.cpp +++ b/src/storm/builder/DdJaniModelBuilder.cpp @@ -51,9 +51,7 @@ namespace storm { template <storm::dd::DdType Type, typename ValueType> DdJaniModelBuilder<Type, ValueType>::Options::Options(std::vector<std::shared_ptr<storm::logic::Formula const>> const& formulas) : buildAllLabels(false), buildAllRewardModels(false), rewardModelsToBuild(), constantDefinitions(), terminalStates(), negatedTerminalStates() { - if (formulas.empty()) { - this->buildAllRewardModels = true; - } else { + if (!formulas.empty()) { for (auto const& formula : formulas) { this->preserveFormula(*formula); } diff --git a/src/storm/builder/DdPrismModelBuilder.cp b/src/storm/builder/DdPrismModelBuilder.cp new file mode 100644 index 000000000..26308f45b --- /dev/null +++ b/src/storm/builder/DdPrismModelBuilder.cp @@ -0,0 +1,1429 @@ +#include "storm/builder/DdPrismModelBuilder.h" + +#include <boost/algorithm/string/join.hpp> + +#include "storm/models/symbolic/Dtmc.h" +#include "storm/models/symbolic/Ctmc.h" +#include "storm/models/symbolic/Mdp.h" +#include "storm/models/symbolic/StandardRewardModel.h" + +#include "storm/settings/SettingsManager.h" + +#include "storm/exceptions/InvalidStateException.h" +#include "storm/exceptions/NotSupportedException.h" +#include "storm/exceptions/InvalidArgumentException.h" + +#include "storm/utility/prism.h" +#include "storm/utility/math.h" +#include "storm/utility/dd.h" + +#include "storm/storage/dd/DdManager.h" +#include "storm/storage/prism/Program.h" +#include "storm/storage/prism/Compositions.h" +#include "storm/storage/dd/Add.h" +#include "storm/storage/dd/cudd/CuddAddIterator.h" +#include "storm/storage/dd/Bdd.h" + +#include "storm/settings/modules/CoreSettings.h" + +namespace storm { + namespace builder { + + template <storm::dd::DdType Type, typename ValueType> + class DdPrismModelBuilder<Type, ValueType>::GenerationInformation { + public: + GenerationInformation(storm::prism::Program const& program) : program(program), manager(std::make_shared<storm::dd::DdManager<Type>>()), rowMetaVariables(), variableToRowMetaVariableMap(std::make_shared<std::map<storm::expressions::Variable, storm::expressions::Variable>>()), rowExpressionAdapter(std::make_shared<storm::adapters::AddExpressionAdapter<Type, ValueType>>(manager, variableToRowMetaVariableMap)), columnMetaVariables(), variableToColumnMetaVariableMap((std::make_shared<std::map<storm::expressions::Variable, storm::expressions::Variable>>())), columnExpressionAdapter(std::make_shared<storm::adapters::AddExpressionAdapter<Type, ValueType>>(manager, variableToColumnMetaVariableMap)), rowColumnMetaVariablePairs(), nondeterminismMetaVariables(), variableToIdentityMap(), allGlobalVariables(), moduleToIdentityMap() { + // Initializes variables and identity DDs. + createMetaVariablesAndIdentities(); + } + + // The program that is currently translated. + storm::prism::Program const& program; + + // The manager used to build the decision diagrams. + std::shared_ptr<storm::dd::DdManager<Type>> manager; + + // The meta variables for the row encoding. + std::set<storm::expressions::Variable> rowMetaVariables; + std::shared_ptr<std::map<storm::expressions::Variable, storm::expressions::Variable>> variableToRowMetaVariableMap; + std::shared_ptr<storm::adapters::AddExpressionAdapter<Type, ValueType>> rowExpressionAdapter; + + // The meta variables for the column encoding. + std::set<storm::expressions::Variable> columnMetaVariables; + std::shared_ptr<std::map<storm::expressions::Variable, storm::expressions::Variable>> variableToColumnMetaVariableMap; + std::shared_ptr<storm::adapters::AddExpressionAdapter<Type, ValueType>> columnExpressionAdapter; + + // All pairs of row/column meta variables. + std::vector<std::pair<storm::expressions::Variable, storm::expressions::Variable>> rowColumnMetaVariablePairs; + + // The meta variables used to encode the nondeterminism. + std::vector<storm::expressions::Variable> nondeterminismMetaVariables; + + // The meta variables used to encode the synchronization. + std::vector<storm::expressions::Variable> synchronizationMetaVariables; + + // A set of all variables used for encoding the nondeterminism (i.e. nondetermism + synchronization + // variables). This is handy to abstract from this variable set. + std::set<storm::expressions::Variable> allNondeterminismVariables; + + // As set of all variables used for encoding the synchronization. + std::set<storm::expressions::Variable> allSynchronizationMetaVariables; + + // DDs representing the identity for each variable. + std::map<storm::expressions::Variable, storm::dd::Add<Type, ValueType>> variableToIdentityMap; + + // A set of all meta variables that correspond to global variables. + std::set<storm::expressions::Variable> allGlobalVariables; + + // DDs representing the identity for each module. + std::map<std::string, storm::dd::Add<Type, ValueType>> moduleToIdentityMap; + + // DDs representing the valid ranges of the variables of each module. + std::map<std::string, storm::dd::Add<Type, ValueType>> moduleToRangeMap; + + private: + /*! + * Creates the required meta variables and variable/module identities. + */ + void createMetaVariablesAndIdentities() { + // Add synchronization variables. + for (auto const& actionIndex : program.getSynchronizingActionIndices()) { + std::pair<storm::expressions::Variable, storm::expressions::Variable> variablePair = manager->addMetaVariable(program.getActionName(actionIndex)); + synchronizationMetaVariables.push_back(variablePair.first); + allSynchronizationMetaVariables.insert(variablePair.first); + allNondeterminismVariables.insert(variablePair.first); + } + + // Add nondeterminism variables (number of modules + number of commands). + uint_fast64_t numberOfNondeterminismVariables = program.getModules().size(); + for (auto const& module : program.getModules()) { + numberOfNondeterminismVariables += module.getNumberOfCommands(); + } + for (uint_fast64_t i = 0; i < numberOfNondeterminismVariables; ++i) { + std::pair<storm::expressions::Variable, storm::expressions::Variable> variablePair = manager->addMetaVariable("nondet" + std::to_string(i)); + nondeterminismMetaVariables.push_back(variablePair.first); + allNondeterminismVariables.insert(variablePair.first); + } + + // Create meta variables for global program variables. + for (storm::prism::IntegerVariable const& integerVariable : program.getGlobalIntegerVariables()) { + int_fast64_t low = integerVariable.getLowerBoundExpression().evaluateAsInt(); + int_fast64_t high = integerVariable.getUpperBoundExpression().evaluateAsInt(); + std::pair<storm::expressions::Variable, storm::expressions::Variable> variablePair = manager->addMetaVariable(integerVariable.getName(), low, high); + + STORM_LOG_TRACE("Created meta variables for global integer variable: " << variablePair.first.getName() << "[" << variablePair.first.getIndex() << "] and " << variablePair.second.getName() << "[" << variablePair.second.getIndex() << "]"); + + rowMetaVariables.insert(variablePair.first); + variableToRowMetaVariableMap->emplace(integerVariable.getExpressionVariable(), variablePair.first); + + columnMetaVariables.insert(variablePair.second); + variableToColumnMetaVariableMap->emplace(integerVariable.getExpressionVariable(), variablePair.second); + + storm::dd::Add<Type, ValueType> variableIdentity = manager->template getIdentity<ValueType>(variablePair.first).equals(manager->template getIdentity<ValueType>(variablePair.second)).template toAdd<ValueType>() * manager->getRange(variablePair.first).template toAdd<ValueType>() * manager->getRange(variablePair.second).template toAdd<ValueType>(); + variableToIdentityMap.emplace(integerVariable.getExpressionVariable(), variableIdentity); + rowColumnMetaVariablePairs.push_back(variablePair); + + allGlobalVariables.insert(integerVariable.getExpressionVariable()); + } + for (storm::prism::BooleanVariable const& booleanVariable : program.getGlobalBooleanVariables()) { + std::pair<storm::expressions::Variable, storm::expressions::Variable> variablePair = manager->addMetaVariable(booleanVariable.getName()); + + STORM_LOG_TRACE("Created meta variables for global boolean variable: " << variablePair.first.getName() << "[" << variablePair.first.getIndex() << "] and " << variablePair.second.getName() << "[" << variablePair.second.getIndex() << "]"); + + rowMetaVariables.insert(variablePair.first); + variableToRowMetaVariableMap->emplace(booleanVariable.getExpressionVariable(), variablePair.first); + + columnMetaVariables.insert(variablePair.second); + variableToColumnMetaVariableMap->emplace(booleanVariable.getExpressionVariable(), variablePair.second); + + storm::dd::Add<Type, ValueType> variableIdentity = manager->template getIdentity<ValueType>(variablePair.first).equals(manager->template getIdentity<ValueType>(variablePair.second)).template toAdd<ValueType>(); + variableToIdentityMap.emplace(booleanVariable.getExpressionVariable(), variableIdentity); + + rowColumnMetaVariablePairs.push_back(variablePair); + allGlobalVariables.insert(booleanVariable.getExpressionVariable()); + } + + // Create meta variables for each of the modules' variables. + for (storm::prism::Module const& module : program.getModules()) { + storm::dd::Bdd<Type> moduleIdentity = manager->getBddOne(); + storm::dd::Bdd<Type> moduleRange = manager->getBddOne(); + + for (storm::prism::IntegerVariable const& integerVariable : module.getIntegerVariables()) { + int_fast64_t low = integerVariable.getLowerBoundExpression().evaluateAsInt(); + int_fast64_t high = integerVariable.getUpperBoundExpression().evaluateAsInt(); + std::pair<storm::expressions::Variable, storm::expressions::Variable> variablePair = manager->addMetaVariable(integerVariable.getName(), low, high); + STORM_LOG_TRACE("Created meta variables for integer variable: " << variablePair.first.getName() << "[" << variablePair.first.getIndex() << "] and " << variablePair.second.getName() << "[" << variablePair.second.getIndex() << "]"); + + rowMetaVariables.insert(variablePair.first); + variableToRowMetaVariableMap->emplace(integerVariable.getExpressionVariable(), variablePair.first); + + columnMetaVariables.insert(variablePair.second); + variableToColumnMetaVariableMap->emplace(integerVariable.getExpressionVariable(), variablePair.second); + + storm::dd::Bdd<Type> variableIdentity = manager->template getIdentity<ValueType>(variablePair.first).equals(manager->template getIdentity<ValueType>(variablePair.second)) && manager->getRange(variablePair.first) && manager->getRange(variablePair.second); + variableToIdentityMap.emplace(integerVariable.getExpressionVariable(), variableIdentity.template toAdd<ValueType>()); + moduleIdentity &= variableIdentity; + moduleRange &= manager->getRange(variablePair.first); + + rowColumnMetaVariablePairs.push_back(variablePair); + } + for (storm::prism::BooleanVariable const& booleanVariable : module.getBooleanVariables()) { + std::pair<storm::expressions::Variable, storm::expressions::Variable> variablePair = manager->addMetaVariable(booleanVariable.getName()); + STORM_LOG_TRACE("Created meta variables for boolean variable: " << variablePair.first.getName() << "[" << variablePair.first.getIndex() << "] and " << variablePair.second.getName() << "[" << variablePair.second.getIndex() << "]"); + + rowMetaVariables.insert(variablePair.first); + variableToRowMetaVariableMap->emplace(booleanVariable.getExpressionVariable(), variablePair.first); + + columnMetaVariables.insert(variablePair.second); + variableToColumnMetaVariableMap->emplace(booleanVariable.getExpressionVariable(), variablePair.second); + + storm::dd::Bdd<Type> variableIdentity = manager->template getIdentity<ValueType>(variablePair.first).equals(manager->template getIdentity<ValueType>(variablePair.second)) && manager->getRange(variablePair.first) && manager->getRange(variablePair.second); + variableToIdentityMap.emplace(booleanVariable.getExpressionVariable(), variableIdentity.template toAdd<ValueType>()); + moduleIdentity &= variableIdentity; + moduleRange &= manager->getRange(variablePair.first); + + rowColumnMetaVariablePairs.push_back(variablePair); + } + moduleToIdentityMap[module.getName()] = moduleIdentity.template toAdd<ValueType>(); + moduleToRangeMap[module.getName()] = moduleRange.template toAdd<ValueType>(); + } + } + }; + + template <storm::dd::DdType Type, typename ValueType> + class ModuleComposer : public storm::prism::CompositionVisitor { + public: + ModuleComposer(typename DdPrismModelBuilder<Type, ValueType>::GenerationInformation& generationInfo) : generationInfo(generationInfo) { + // Intentionally left empty. + } + + typename DdPrismModelBuilder<Type, ValueType>::ModuleDecisionDiagram compose(storm::prism::Composition const& composition) { + return boost::any_cast<typename DdPrismModelBuilder<Type, ValueType>::ModuleDecisionDiagram>(composition.accept(*this, newSynchronizingActionToOffsetMap())); + } + + std::map<uint_fast64_t, uint_fast64_t> newSynchronizingActionToOffsetMap() const { + std::map<uint_fast64_t, uint_fast64_t> result; + for (auto const& actionIndex : generationInfo.program.getSynchronizingActionIndices()) { + result[actionIndex] = 0; + } + return result; + } + + std::map<uint_fast64_t, uint_fast64_t> updateSynchronizingActionToOffsetMap(typename DdPrismModelBuilder<Type, ValueType>::ModuleDecisionDiagram const& sub, std::map<uint_fast64_t, uint_fast64_t> const& oldMapping) const { + std::map<uint_fast64_t, uint_fast64_t> result = oldMapping; + for (auto const& action : sub.synchronizingActionToDecisionDiagramMap) { + result[action.first] = action.second.numberOfUsedNondeterminismVariables; + } + return result; + } + + virtual boost::any visit(storm::prism::ModuleComposition const& composition, boost::any const& data) override { + STORM_LOG_TRACE("Translating module '" << composition.getModuleName() << "'."); + std::map<uint_fast64_t, uint_fast64_t> const& synchronizingActionToOffsetMap = boost::any_cast<std::map<uint_fast64_t, uint_fast64_t> const&>(data); + + typename DdPrismModelBuilder<Type, ValueType>::ModuleDecisionDiagram result = DdPrismModelBuilder<Type, ValueType>::createModuleDecisionDiagram(generationInfo, generationInfo.program.getModule(composition.getModuleName()), synchronizingActionToOffsetMap); + + return result; + } + + virtual boost::any visit(storm::prism::RenamingComposition const& composition, boost::any const& data) override { + // Create the mapping from action indices to action indices. + std::map<uint_fast64_t, uint_fast64_t> renaming; + for (auto const& namePair : composition.getActionRenaming()) { + STORM_LOG_THROW(generationInfo.program.hasAction(namePair.first), storm::exceptions::InvalidArgumentException, "Composition refers to unknown action '" << namePair.first << "'."); + STORM_LOG_THROW(generationInfo.program.hasAction(namePair.second), storm::exceptions::InvalidArgumentException, "Composition refers to unknown action '" << namePair.second << "'."); + renaming.emplace(generationInfo.program.getActionIndex(namePair.first), generationInfo.program.getActionIndex(namePair.second)); + } + + // Prepare the new offset mapping. + std::map<uint_fast64_t, uint_fast64_t> const& synchronizingActionToOffsetMap = boost::any_cast<std::map<uint_fast64_t, uint_fast64_t> const&>(data); + std::map<uint_fast64_t, uint_fast64_t> newSynchronizingActionToOffsetMap = synchronizingActionToOffsetMap; + for (auto const& indexPair : renaming) { + auto it = synchronizingActionToOffsetMap.find(indexPair.second); + STORM_LOG_THROW(it != synchronizingActionToOffsetMap.end(), storm::exceptions::InvalidArgumentException, "Invalid action index " << indexPair.second << "."); + newSynchronizingActionToOffsetMap[indexPair.first] = it->second; + } + + // Then, we translate the subcomposition. + typename DdPrismModelBuilder<Type, ValueType>::ModuleDecisionDiagram sub = boost::any_cast<typename DdPrismModelBuilder<Type, ValueType>::ModuleDecisionDiagram>(composition.getSubcomposition().accept(*this, newSynchronizingActionToOffsetMap)); + + // Perform the renaming and return result. + return rename(sub, renaming); + } + + virtual boost::any visit(storm::prism::HidingComposition const& composition, boost::any const& data) override { + // Create the mapping from action indices to action indices. + std::set<uint_fast64_t> actionIndicesToHide; + for (auto const& action : composition.getActionsToHide()) { + STORM_LOG_THROW(generationInfo.program.hasAction(action), storm::exceptions::InvalidArgumentException, "Composition refers to unknown action '" << action << "'."); + actionIndicesToHide.insert(generationInfo.program.getActionIndex(action)); + } + + // Prepare the new offset mapping. + std::map<uint_fast64_t, uint_fast64_t> const& synchronizingActionToOffsetMap = boost::any_cast<std::map<uint_fast64_t, uint_fast64_t> const&>(data); + std::map<uint_fast64_t, uint_fast64_t> newSynchronizingActionToOffsetMap = synchronizingActionToOffsetMap; + for (auto const& index : actionIndicesToHide) { + newSynchronizingActionToOffsetMap[index] = 0; + } + + // Then, we translate the subcomposition. + typename DdPrismModelBuilder<Type, ValueType>::ModuleDecisionDiagram sub = boost::any_cast<typename DdPrismModelBuilder<Type, ValueType>::ModuleDecisionDiagram>(composition.getSubcomposition().accept(*this, newSynchronizingActionToOffsetMap)); + + // Perform the hiding and return result. + hide(sub, actionIndicesToHide); + return sub; + } + + virtual boost::any visit(storm::prism::SynchronizingParallelComposition const& composition, boost::any const& data) override { + // First, we translate the subcompositions. + typename DdPrismModelBuilder<Type, ValueType>::ModuleDecisionDiagram left = boost::any_cast<typename DdPrismModelBuilder<Type, ValueType>::ModuleDecisionDiagram>(composition.getLeftSubcomposition().accept(*this, data)); + + // Prepare the new offset mapping. + std::map<uint_fast64_t, uint_fast64_t> const& synchronizingActionToOffsetMap = boost::any_cast<std::map<uint_fast64_t, uint_fast64_t> const&>(data); + std::map<uint_fast64_t, uint_fast64_t> newSynchronizingActionToOffsetMap = synchronizingActionToOffsetMap; + for (auto const& action : left.synchronizingActionToDecisionDiagramMap) { + newSynchronizingActionToOffsetMap[action.first] = action.second.numberOfUsedNondeterminismVariables; + } + + typename DdPrismModelBuilder<Type, ValueType>::ModuleDecisionDiagram right = boost::any_cast<typename DdPrismModelBuilder<Type, ValueType>::ModuleDecisionDiagram>(composition.getRightSubcomposition().accept(*this, newSynchronizingActionToOffsetMap)); + + // Then, determine the action indices on which we need to synchronize. + std::set<uint_fast64_t> leftSynchronizationActionIndices = left.getSynchronizingActionIndices(); + std::set<uint_fast64_t> rightSynchronizationActionIndices = right.getSynchronizingActionIndices(); + std::set<uint_fast64_t> synchronizationActionIndices; + std::set_intersection(leftSynchronizationActionIndices.begin(), leftSynchronizationActionIndices.end(), rightSynchronizationActionIndices.begin(), rightSynchronizationActionIndices.end(), std::inserter(synchronizationActionIndices, synchronizationActionIndices.begin())); + + // Finally, we compose the subcompositions to create the result. + composeInParallel(left, right, synchronizationActionIndices); + return left; + } + + virtual boost::any visit(storm::prism::InterleavingParallelComposition const& composition, boost::any const& data) override { + // First, we translate the subcompositions. + typename DdPrismModelBuilder<Type, ValueType>::ModuleDecisionDiagram left = boost::any_cast<typename DdPrismModelBuilder<Type, ValueType>::ModuleDecisionDiagram>(composition.getLeftSubcomposition().accept(*this, data)); + + typename DdPrismModelBuilder<Type, ValueType>::ModuleDecisionDiagram right = boost::any_cast<typename DdPrismModelBuilder<Type, ValueType>::ModuleDecisionDiagram>(composition.getRightSubcomposition().accept(*this, data)); + + // Finally, we compose the subcompositions to create the result. + composeInParallel(left, right, std::set<uint_fast64_t>()); + return left; + } + + virtual boost::any visit(storm::prism::RestrictedParallelComposition const& composition, boost::any const& data) override { + // Construct the synchronizing action indices from the synchronizing action names. + std::set<uint_fast64_t> synchronizingActionIndices; + for (auto const& action : composition.getSynchronizingActions()) { + synchronizingActionIndices.insert(generationInfo.program.getActionIndex(action)); + } + + // Then, we translate the subcompositions. + typename DdPrismModelBuilder<Type, ValueType>::ModuleDecisionDiagram left = boost::any_cast<typename DdPrismModelBuilder<Type, ValueType>::ModuleDecisionDiagram>(composition.getLeftSubcomposition().accept(*this, data)); + + // Prepare the new offset mapping. + std::map<uint_fast64_t, uint_fast64_t> const& synchronizingActionToOffsetMap = boost::any_cast<std::map<uint_fast64_t, uint_fast64_t> const&>(data); + std::map<uint_fast64_t, uint_fast64_t> newSynchronizingActionToOffsetMap = synchronizingActionToOffsetMap; + for (auto const& actionIndex : synchronizingActionIndices) { + auto it = left.synchronizingActionToDecisionDiagramMap.find(actionIndex); + if (it != left.synchronizingActionToDecisionDiagramMap.end()) { + newSynchronizingActionToOffsetMap[actionIndex] = it->second.numberOfUsedNondeterminismVariables; + } + } + + typename DdPrismModelBuilder<Type, ValueType>::ModuleDecisionDiagram right = boost::any_cast<typename DdPrismModelBuilder<Type, ValueType>::ModuleDecisionDiagram>(composition.getRightSubcomposition().accept(*this, newSynchronizingActionToOffsetMap)); + + std::set<uint_fast64_t> leftSynchronizationActionIndices = left.getSynchronizingActionIndices(); + bool isContainedInLeft = std::includes(leftSynchronizationActionIndices.begin(), leftSynchronizationActionIndices.end(), synchronizingActionIndices.begin(), synchronizingActionIndices.end()); + STORM_LOG_WARN_COND(isContainedInLeft, "Left subcomposition of composition '" << composition << "' does not include all actions over which to synchronize."); + + std::set<uint_fast64_t> rightSynchronizationActionIndices = right.getSynchronizingActionIndices(); + bool isContainedInRight = std::includes(rightSynchronizationActionIndices.begin(), rightSynchronizationActionIndices.end(), synchronizingActionIndices.begin(), synchronizingActionIndices.end()); + STORM_LOG_WARN_COND(isContainedInRight, "Right subcomposition of composition '" << composition << "' does not include all actions over which to synchronize."); + + // Finally, we compose the subcompositions to create the result. + composeInParallel(left, right, synchronizingActionIndices); + return left; + } + + private: + /*! + * Hides the actions of the given module according to the given set. As a result, the module is modified in + * place. + */ + void hide(typename DdPrismModelBuilder<Type, ValueType>::ModuleDecisionDiagram& sub, std::set<uint_fast64_t> const& actionIndicesToHide) const { + STORM_LOG_TRACE("Hiding actions."); + + for (auto const& actionIndex : actionIndicesToHide) { + auto it = sub.synchronizingActionToDecisionDiagramMap.find(actionIndex); + if (it != sub.synchronizingActionToDecisionDiagramMap.end()) { + sub.independentAction = DdPrismModelBuilder<Type, ValueType>::combineUnsynchronizedActions(generationInfo, sub.independentAction, it->second); + sub.numberOfUsedNondeterminismVariables = std::max(sub.numberOfUsedNondeterminismVariables, sub.independentAction.numberOfUsedNondeterminismVariables); + sub.synchronizingActionToDecisionDiagramMap.erase(it); + } + } + } + + /*! + * Renames the actions of the given module according to the given renaming. + */ + typename DdPrismModelBuilder<Type, ValueType>::ModuleDecisionDiagram rename(typename DdPrismModelBuilder<Type, ValueType>::ModuleDecisionDiagram& sub, std::map<uint_fast64_t, uint_fast64_t> const& renaming) const { + STORM_LOG_TRACE("Renaming actions."); + std::map<uint_fast64_t, typename DdPrismModelBuilder<Type, ValueType>::ActionDecisionDiagram> actionIndexToDdMap; + + // Go through all action DDs with a synchronizing label and rename them if they appear in the renaming. + for (auto& action : sub.synchronizingActionToDecisionDiagramMap) { + auto renamingIt = renaming.find(action.first); + if (renamingIt != renaming.end()) { + // If the action is to be renamed and an action with the target index already exists, we need + // to combine the action DDs. + auto itNewActions = actionIndexToDdMap.find(renamingIt->second); + if (itNewActions != actionIndexToDdMap.end()) { + actionIndexToDdMap[renamingIt->second] = DdPrismModelBuilder<Type, ValueType>::combineUnsynchronizedActions(generationInfo, action.second, itNewActions->second); + + } else { + // In this case, we can simply copy the action over. + actionIndexToDdMap[renamingIt->second] = action.second; + } + } else { + // If the action is not to be renamed, we need to copy it over. However, if some other action + // was renamed to the very same action name before, we need to combine the transitions. + auto itNewActions = actionIndexToDdMap.find(action.first); + if (itNewActions != actionIndexToDdMap.end()) { + actionIndexToDdMap[action.first] = DdPrismModelBuilder<Type, ValueType>::combineUnsynchronizedActions(generationInfo, action.second, itNewActions->second); + } else { + // In this case, we can simply copy the action over. + actionIndexToDdMap[action.first] = action.second; + } + } + } + + return typename DdPrismModelBuilder<Type, ValueType>::ModuleDecisionDiagram(sub.independentAction, actionIndexToDdMap, sub.identity, sub.numberOfUsedNondeterminismVariables); + } + + /*! + * Composes the given modules while synchronizing over the provided action indices. As a result, the first + * module is modified in place and will contain the composition after a call to this method. + */ + void composeInParallel(typename DdPrismModelBuilder<Type, ValueType>::ModuleDecisionDiagram& left, typename DdPrismModelBuilder<Type, ValueType>::ModuleDecisionDiagram& right, std::set<uint_fast64_t> const& synchronizationActionIndices) const { + STORM_LOG_TRACE("Composing two modules."); + + // Combine the tau action. + uint_fast64_t numberOfUsedNondeterminismVariables = right.independentAction.numberOfUsedNondeterminismVariables; + left.independentAction = DdPrismModelBuilder<Type, ValueType>::combineUnsynchronizedActions(generationInfo, left.independentAction, right.independentAction, left.identity, right.identity); + numberOfUsedNondeterminismVariables = std::max(numberOfUsedNondeterminismVariables, left.independentAction.numberOfUsedNondeterminismVariables); + + // Create an empty action for the case where one of the modules does not have a certain action. + typename DdPrismModelBuilder<Type, ValueType>::ActionDecisionDiagram emptyAction(*generationInfo.manager); + + // Treat all non-tau actions of the left module. + for (auto& action : left.synchronizingActionToDecisionDiagramMap) { + // If we need to synchronize over this action index, we try to do so now. + if (synchronizationActionIndices.find(action.first) != synchronizationActionIndices.end()) { + // If we are to synchronize over an action that does not exist in the second module, the result + // is that the synchronization is the empty action. + if (!right.hasSynchronizingAction(action.first)) { + action.second = emptyAction; + } else { + // Otherwise, the actions of the modules are synchronized. + action.second = DdPrismModelBuilder<Type, ValueType>::combineSynchronizingActions(action.second, right.synchronizingActionToDecisionDiagramMap[action.first]); + } + } else { + // If we don't synchronize over this action, we need to construct the interleaving. + + // If both modules contain the action, we need to mutually multiply the other identity. + if (right.hasSynchronizingAction(action.first)) { + action.second = DdPrismModelBuilder<Type, ValueType>::combineUnsynchronizedActions(generationInfo, action.second, right.synchronizingActionToDecisionDiagramMap[action.first], left.identity, right.identity); + } else { + // If only the first module has this action, we need to use a dummy action decision diagram + // for the second module. + action.second = DdPrismModelBuilder<Type, ValueType>::combineUnsynchronizedActions(generationInfo, action.second, emptyAction, left.identity, right.identity); + } + } + numberOfUsedNondeterminismVariables = std::max(numberOfUsedNondeterminismVariables, action.second.numberOfUsedNondeterminismVariables); + } + + // Treat all non-tau actions of the right module. + for (auto const& actionIndex : right.getSynchronizingActionIndices()) { + // Here, we only need to treat actions that the first module does not have, because we have handled + // this case earlier. + if (!left.hasSynchronizingAction(actionIndex)) { + if (synchronizationActionIndices.find(actionIndex) != synchronizationActionIndices.end()) { + // If we are to synchronize over this action that does not exist in the first module, the + // result is that the synchronization is the empty action. + left.synchronizingActionToDecisionDiagramMap[actionIndex] = emptyAction; + } else { + // If only the second module has this action, we need to use a dummy action decision diagram + // for the first module. + left.synchronizingActionToDecisionDiagramMap[actionIndex] = DdPrismModelBuilder<Type, ValueType>::combineUnsynchronizedActions(generationInfo, emptyAction, right.synchronizingActionToDecisionDiagramMap[actionIndex], left.identity, right.identity); + } + } + numberOfUsedNondeterminismVariables = std::max(numberOfUsedNondeterminismVariables, left.synchronizingActionToDecisionDiagramMap[actionIndex].numberOfUsedNondeterminismVariables); + } + + // Combine identity matrices. + left.identity = left.identity * right.identity; + + // Keep track of the number of nondeterminism variables used. + left.numberOfUsedNondeterminismVariables = std::max(left.numberOfUsedNondeterminismVariables, numberOfUsedNondeterminismVariables); + } + + typename DdPrismModelBuilder<Type, ValueType>::GenerationInformation& generationInfo; + }; + + template <storm::dd::DdType Type, typename ValueType> + DdPrismModelBuilder<Type, ValueType>::Options::Options() : buildAllRewardModels(false), rewardModelsToBuild(), buildAllLabels(false), labelsToBuild(), terminalStates(), negatedTerminalStates() { + // Intentionally left empty. + } + + template <storm::dd::DdType Type, typename ValueType> + DdPrismModelBuilder<Type, ValueType>::Options::Options(storm::logic::Formula const& formula) : buildAllRewardModels(false), rewardModelsToBuild(), buildAllLabels(false), labelsToBuild(std::set<std::string>()), terminalStates(), negatedTerminalStates() { + this->preserveFormula(formula); + this->setTerminalStatesFromFormula(formula); + } + + template <storm::dd::DdType Type, typename ValueType> + DdPrismModelBuilder<Type, ValueType>::Options::Options(std::vector<std::shared_ptr<storm::logic::Formula const>> const& formulas) : buildAllRewardModels(false), rewardModelsToBuild(), buildAllLabels(false), labelsToBuild(), terminalStates(), negatedTerminalStates() { + if (formulas.empty()) { + this->buildAllRewardModels = true; + this->buildAllLabels = true; + } else { + for (auto const& formula : formulas) { + this->preserveFormula(*formula); + } + if (formulas.size() == 1) { + this->setTerminalStatesFromFormula(*formulas.front()); + } + } + } + + template <storm::dd::DdType Type, typename ValueType> + void DdPrismModelBuilder<Type, ValueType>::Options::preserveFormula(storm::logic::Formula const& formula) { + // If we already had terminal states, we need to erase them. + if (terminalStates) { + terminalStates.reset(); + } + if (negatedTerminalStates) { + negatedTerminalStates.reset(); + } + + // If we are not required to build all reward models, we determine the reward models we need to build. + if (!buildAllRewardModels) { + std::set<std::string> referencedRewardModels = formula.getReferencedRewardModels(); + rewardModelsToBuild.insert(referencedRewardModels.begin(), referencedRewardModels.end()); + } + + // Extract all the labels used in the formula. + std::vector<std::shared_ptr<storm::logic::AtomicLabelFormula const>> atomicLabelFormulas = formula.getAtomicLabelFormulas(); + for (auto const& formula : atomicLabelFormulas) { + if (!labelsToBuild) { + labelsToBuild = std::set<std::string>(); + } + labelsToBuild.get().insert(formula.get()->getLabel()); + } + } + + template <storm::dd::DdType Type, typename ValueType> + void DdPrismModelBuilder<Type, ValueType>::Options::setTerminalStatesFromFormula(storm::logic::Formula const& formula) { + if (formula.isAtomicExpressionFormula()) { + terminalStates = formula.asAtomicExpressionFormula().getExpression(); + } else if (formula.isAtomicLabelFormula()) { + terminalStates = formula.asAtomicLabelFormula().getLabel(); + } else if (formula.isEventuallyFormula()) { + storm::logic::Formula const& sub = formula.asEventuallyFormula().getSubformula(); + if (sub.isAtomicExpressionFormula() || sub.isAtomicLabelFormula()) { + this->setTerminalStatesFromFormula(sub); + } + } else if (formula.isUntilFormula()) { + storm::logic::Formula const& right = formula.asUntilFormula().getRightSubformula(); + if (right.isAtomicExpressionFormula() || right.isAtomicLabelFormula()) { + this->setTerminalStatesFromFormula(right); + } + storm::logic::Formula const& left = formula.asUntilFormula().getLeftSubformula(); + if (left.isAtomicExpressionFormula()) { + negatedTerminalStates = left.asAtomicExpressionFormula().getExpression(); + } else if (left.isAtomicLabelFormula()) { + negatedTerminalStates = left.asAtomicLabelFormula().getLabel(); + } + } else if (formula.isProbabilityOperatorFormula()) { + storm::logic::Formula const& sub = formula.asProbabilityOperatorFormula().getSubformula(); + if (sub.isEventuallyFormula() || sub.isUntilFormula()) { + this->setTerminalStatesFromFormula(sub); + } + } + } + + template <storm::dd::DdType Type, typename ValueType> + struct DdPrismModelBuilder<Type, ValueType>::SystemResult { + SystemResult(storm::dd::Add<Type, ValueType> const& allTransitionsDd, DdPrismModelBuilder<Type, ValueType>::ModuleDecisionDiagram const& globalModule, storm::dd::Add<Type, ValueType> const& stateActionDd) : allTransitionsDd(allTransitionsDd), globalModule(globalModule), stateActionDd(stateActionDd) { + // Intentionally left empty. + } + + storm::dd::Add<Type, ValueType> allTransitionsDd; + typename DdPrismModelBuilder<Type, ValueType>::ModuleDecisionDiagram globalModule; + storm::dd::Add<Type, ValueType> stateActionDd; + }; + + template <storm::dd::DdType Type, typename ValueType> + typename DdPrismModelBuilder<Type, ValueType>::UpdateDecisionDiagram DdPrismModelBuilder<Type, ValueType>::createUpdateDecisionDiagram(GenerationInformation& generationInfo, storm::prism::Module const& module, storm::dd::Add<Type, ValueType> const& guard, storm::prism::Update const& update) { + storm::dd::Add<Type, ValueType> updateDd = generationInfo.manager->template getAddOne<ValueType>(); + + STORM_LOG_TRACE("Translating update " << update); + + // Iterate over all assignments (boolean and integer) and build the DD for it. + std::vector<storm::prism::Assignment> assignments = update.getAssignments(); + std::set<storm::expressions::Variable> assignedVariables; + for (auto const& assignment : assignments) { + // Record the variable as being written. + STORM_LOG_TRACE("Assigning to variable " << generationInfo.variableToRowMetaVariableMap->at(assignment.getVariable()).getName()); + assignedVariables.insert(assignment.getVariable()); + + // Translate the written variable. + auto const& primedMetaVariable = generationInfo.variableToColumnMetaVariableMap->at(assignment.getVariable()); + storm::dd::Add<Type, ValueType> writtenVariable = generationInfo.manager->template getIdentity<ValueType>(primedMetaVariable); + + // Translate the expression that is being assigned. + storm::dd::Add<Type, ValueType> updateExpression = generationInfo.rowExpressionAdapter->translateExpression(assignment.getExpression()); + + // Combine the update expression with the guard. + storm::dd::Add<Type, ValueType> result = updateExpression * guard; + + // Combine the variable and the assigned expression. + storm::dd::Add<Type, ValueType> tmp = result; + result = result.equals(writtenVariable).template toAdd<ValueType>(); + result *= guard; + + // Restrict the transitions to the range of the written variable. + result = result * generationInfo.manager->getRange(primedMetaVariable).template toAdd<ValueType>(); + + updateDd *= result; + } + + // Compute the set of assigned global variables. + std::set<storm::expressions::Variable> assignedGlobalVariables; + std::set_intersection(assignedVariables.begin(), assignedVariables.end(), generationInfo.allGlobalVariables.begin(), generationInfo.allGlobalVariables.end(), std::inserter(assignedGlobalVariables, assignedGlobalVariables.begin())); + + // All unassigned boolean variables need to keep their value. + for (storm::prism::BooleanVariable const& booleanVariable : module.getBooleanVariables()) { + if (assignedVariables.find(booleanVariable.getExpressionVariable()) == assignedVariables.end()) { + STORM_LOG_TRACE("Multiplying identity of variable " << booleanVariable.getName()); + updateDd *= generationInfo.variableToIdentityMap.at(booleanVariable.getExpressionVariable()); + } + } + + // All unassigned integer variables need to keep their value. + for (storm::prism::IntegerVariable const& integerVariable : module.getIntegerVariables()) { + if (assignedVariables.find(integerVariable.getExpressionVariable()) == assignedVariables.end()) { + STORM_LOG_TRACE("Multiplying identity of variable " << integerVariable.getName()); + updateDd *= generationInfo.variableToIdentityMap.at(integerVariable.getExpressionVariable()); + } + } + + return UpdateDecisionDiagram(updateDd, assignedGlobalVariables); + } + + template <storm::dd::DdType Type, typename ValueType> + typename DdPrismModelBuilder<Type, ValueType>::ActionDecisionDiagram DdPrismModelBuilder<Type, ValueType>::createCommandDecisionDiagram(GenerationInformation& generationInfo, storm::prism::Module const& module, storm::prism::Command const& command) { + STORM_LOG_TRACE("Translating guard " << command.getGuardExpression()); + storm::dd::Add<Type, ValueType> guard = generationInfo.rowExpressionAdapter->translateExpression(command.getGuardExpression()) * generationInfo.moduleToRangeMap[module.getName()]; + STORM_LOG_WARN_COND(!guard.isZero(), "The guard '" << command.getGuardExpression() << "' is unsatisfiable."); + + if (!guard.isZero()) { + // Create the DDs representing the individual updates. + std::vector<UpdateDecisionDiagram> updateResults; + for (storm::prism::Update const& update : command.getUpdates()) { + updateResults.push_back(createUpdateDecisionDiagram(generationInfo, module, guard, update)); + + STORM_LOG_WARN_COND(!updateResults.back().updateDd.isZero(), "Update '" << update << "' does not have any effect."); + } + + // Start by gathering all variables that were written in at least one update. + std::set<storm::expressions::Variable> globalVariablesInSomeUpdate; + + // If the command is labeled, we have to analyze which portion of the global variables was written by + // any of the updates and make all update results equal w.r.t. this set. If the command is not labeled, + // we can already multiply the identities of all global variables. + if (command.isLabeled()) { + std::for_each(updateResults.begin(), updateResults.end(), [&globalVariablesInSomeUpdate] (UpdateDecisionDiagram const& update) { globalVariablesInSomeUpdate.insert(update.assignedGlobalVariables.begin(), update.assignedGlobalVariables.end()); } ); + } else { + globalVariablesInSomeUpdate = generationInfo.allGlobalVariables; + } + + // Then, multiply the missing identities. + for (auto& updateResult : updateResults) { + std::set<storm::expressions::Variable> missingIdentities; + std::set_difference(globalVariablesInSomeUpdate.begin(), globalVariablesInSomeUpdate.end(), updateResult.assignedGlobalVariables.begin(), updateResult.assignedGlobalVariables.end(), std::inserter(missingIdentities, missingIdentities.begin())); + + for (auto const& variable : missingIdentities) { + STORM_LOG_TRACE("Multiplying identity for variable " << variable.getName() << "[" << variable.getIndex() << "] to update."); + updateResult.updateDd *= generationInfo.variableToIdentityMap.at(variable); + } + } + + // Now combine the update DDs to the command DD. + storm::dd::Add<Type, ValueType> commandDd = generationInfo.manager->template getAddZero<ValueType>(); + auto updateResultsIt = updateResults.begin(); + for (auto updateIt = command.getUpdates().begin(), updateIte = command.getUpdates().end(); updateIt != updateIte; ++updateIt, ++updateResultsIt) { + storm::dd::Add<Type, ValueType> probabilityDd = generationInfo.rowExpressionAdapter->translateExpression(updateIt->getLikelihoodExpression()); + commandDd += updateResultsIt->updateDd * probabilityDd; + } + + return ActionDecisionDiagram(guard, guard * commandDd, globalVariablesInSomeUpdate); + } else { + return ActionDecisionDiagram(*generationInfo.manager); + } + } + + template <storm::dd::DdType Type, typename ValueType> + typename DdPrismModelBuilder<Type, ValueType>::ActionDecisionDiagram DdPrismModelBuilder<Type, ValueType>::createActionDecisionDiagram(GenerationInformation& generationInfo, storm::prism::Module const& module, uint_fast64_t synchronizationActionIndex, uint_fast64_t nondeterminismVariableOffset) { + std::vector<ActionDecisionDiagram> commandDds; + for (storm::prism::Command const& command : module.getCommands()) { + + // Determine whether the command is relevant for the selected action. + bool relevant = (synchronizationActionIndex == 0 && !command.isLabeled()) || (synchronizationActionIndex && command.isLabeled() && command.getActionIndex() == synchronizationActionIndex); + + if (!relevant) { + continue; + } + + STORM_LOG_TRACE("Translating command " << command); + + // At this point, the command is known to be relevant for the action. + commandDds.push_back(createCommandDecisionDiagram(generationInfo, module, command)); + } + + ActionDecisionDiagram result(*generationInfo.manager); + if (!commandDds.empty()) { + switch (generationInfo.program.getModelType()){ + case storm::prism::Program::ModelType::DTMC: + case storm::prism::Program::ModelType::CTMC: + result = combineCommandsToActionMarkovChain(generationInfo, commandDds); + break; + case storm::prism::Program::ModelType::MDP: + result = combineCommandsToActionMDP(generationInfo, commandDds, nondeterminismVariableOffset); + break; + default: + STORM_LOG_THROW(false, storm::exceptions::InvalidArgumentException, "Cannot translate model of this type."); + } + } + + return result; + } + + template <storm::dd::DdType Type, typename ValueType> + std::set<storm::expressions::Variable> DdPrismModelBuilder<Type, ValueType>::equalizeAssignedGlobalVariables(GenerationInformation const& generationInfo, ActionDecisionDiagram& action1, ActionDecisionDiagram& action2) { + // Start by gathering all variables that were written in at least one action DD. + std::set<storm::expressions::Variable> globalVariablesInActionDd; + std::set_union(action1.assignedGlobalVariables.begin(), action1.assignedGlobalVariables.end(), action2.assignedGlobalVariables.begin(), action2.assignedGlobalVariables.end(), std::inserter(globalVariablesInActionDd, globalVariablesInActionDd.begin())); + + std::set<storm::expressions::Variable> missingIdentitiesInAction1; + std::set_difference(globalVariablesInActionDd.begin(), globalVariablesInActionDd.end(), action1.assignedGlobalVariables.begin(), action1.assignedGlobalVariables.end(), std::inserter(missingIdentitiesInAction1, missingIdentitiesInAction1.begin())); + for (auto const& variable : missingIdentitiesInAction1) { + action1.transitionsDd *= generationInfo.variableToIdentityMap.at(variable); + } + + std::set<storm::expressions::Variable> missingIdentitiesInAction2; + std::set_difference(globalVariablesInActionDd.begin(), globalVariablesInActionDd.end(), action1.assignedGlobalVariables.begin(), action1.assignedGlobalVariables.end(), std::inserter(missingIdentitiesInAction2, missingIdentitiesInAction2.begin())); + for (auto const& variable : missingIdentitiesInAction2) { + action2.transitionsDd *= generationInfo.variableToIdentityMap.at(variable); + } + + return globalVariablesInActionDd; + } + + template <storm::dd::DdType Type, typename ValueType> + std::set<storm::expressions::Variable> DdPrismModelBuilder<Type, ValueType>::equalizeAssignedGlobalVariables(GenerationInformation const& generationInfo, std::vector<ActionDecisionDiagram>& actionDds) { + // Start by gathering all variables that were written in at least one action DD. + std::set<storm::expressions::Variable> globalVariablesInActionDd; + for (auto const& commandDd : actionDds) { + globalVariablesInActionDd.insert(commandDd.assignedGlobalVariables.begin(), commandDd.assignedGlobalVariables.end()); + } + + STORM_LOG_TRACE("Equalizing assigned global variables."); + + // Then multiply the transitions of each action with the missing identities. + for (auto& actionDd : actionDds) { + STORM_LOG_TRACE("Equalizing next action."); + std::set<storm::expressions::Variable> missingIdentities; + std::set_difference(globalVariablesInActionDd.begin(), globalVariablesInActionDd.end(), actionDd.assignedGlobalVariables.begin(), actionDd.assignedGlobalVariables.end(), std::inserter(missingIdentities, missingIdentities.begin())); + for (auto const& variable : missingIdentities) { + STORM_LOG_TRACE("Multiplying identity of variable " << variable.getName() << "."); + actionDd.transitionsDd *= generationInfo.variableToIdentityMap.at(variable); + } + } + return globalVariablesInActionDd; + } + + template <storm::dd::DdType Type, typename ValueType> + typename DdPrismModelBuilder<Type, ValueType>::ActionDecisionDiagram DdPrismModelBuilder<Type, ValueType>::combineCommandsToActionMarkovChain(GenerationInformation& generationInfo, std::vector<ActionDecisionDiagram>& commandDds) { + storm::dd::Add<Type, ValueType> allGuards = generationInfo.manager->template getAddZero<ValueType>(); + storm::dd::Add<Type, ValueType> allCommands = generationInfo.manager->template getAddZero<ValueType>(); + storm::dd::Add<Type, ValueType> temporary; + + // Make all command DDs assign to the same global variables. + std::set<storm::expressions::Variable> assignedGlobalVariables = equalizeAssignedGlobalVariables(generationInfo, commandDds); + + // Then combine the commands to the full action DD and multiply missing identities along the way. + for (auto& commandDd : commandDds) { + // Check for overlapping guards. + temporary = commandDd.guardDd * allGuards; + + // Issue a warning if there are overlapping guards in a non-CTMC model. + STORM_LOG_WARN_COND(temporary.isZero() || generationInfo.program.getModelType() == storm::prism::Program::ModelType::CTMC, "Guard of a command overlaps with previous guards."); + + allGuards += commandDd.guardDd; + allCommands += commandDd.transitionsDd; + } + + return ActionDecisionDiagram(allGuards, allCommands, assignedGlobalVariables); + } + + template <storm::dd::DdType Type, typename ValueType> + storm::dd::Add<Type, ValueType> DdPrismModelBuilder<Type, ValueType>::encodeChoice(GenerationInformation& generationInfo, uint_fast64_t nondeterminismVariableOffset, uint_fast64_t numberOfBinaryVariables, int_fast64_t value) { + storm::dd::Add<Type, ValueType> result = generationInfo.manager->template getAddZero<ValueType>(); + + STORM_LOG_TRACE("Encoding " << value << " with " << numberOfBinaryVariables << " binary variable(s) starting from offset " << nondeterminismVariableOffset << "."); + + std::map<storm::expressions::Variable, int_fast64_t> metaVariableNameToValueMap; + for (uint_fast64_t i = nondeterminismVariableOffset; i < nondeterminismVariableOffset + numberOfBinaryVariables; ++i) { + if (value & (1ull << (numberOfBinaryVariables - i - 1))) { + metaVariableNameToValueMap.emplace(generationInfo.nondeterminismMetaVariables[i], 1); + } else { + metaVariableNameToValueMap.emplace(generationInfo.nondeterminismMetaVariables[i], 0); + } + } + + result.setValue(metaVariableNameToValueMap, ValueType(1)); + return result; + } + + template <storm::dd::DdType Type, typename ValueType> + typename DdPrismModelBuilder<Type, ValueType>::ActionDecisionDiagram DdPrismModelBuilder<Type, ValueType>::combineCommandsToActionMDP(GenerationInformation& generationInfo, std::vector<ActionDecisionDiagram>& commandDds, uint_fast64_t nondeterminismVariableOffset) { + storm::dd::Bdd<Type> allGuards = generationInfo.manager->getBddZero(); + storm::dd::Add<Type, ValueType> allCommands = generationInfo.manager->template getAddZero<ValueType>(); + + // Make all command DDs assign to the same global variables. + std::set<storm::expressions::Variable> assignedGlobalVariables = equalizeAssignedGlobalVariables(generationInfo, commandDds); + + // Sum all guards, so we can read off the maximal number of nondeterministic choices in any given state. + storm::dd::Add<Type, ValueType> sumOfGuards = generationInfo.manager->template getAddZero<ValueType>(); + for (auto const& commandDd : commandDds) { + sumOfGuards += commandDd.guardDd; + allGuards |= commandDd.guardDd.toBdd(); + } + uint_fast64_t maxChoices = static_cast<uint_fast64_t>(sumOfGuards.getMax()); + + STORM_LOG_TRACE("Found " << maxChoices << " local choices."); + + // Depending on the maximal number of nondeterminstic choices, we need to use some variables to encode the nondeterminism. + if (maxChoices == 0) { + return ActionDecisionDiagram(*generationInfo.manager); + } else if (maxChoices == 1) { + // Sum up all commands. + for (auto const& commandDd : commandDds) { + allCommands += commandDd.transitionsDd; + } + return ActionDecisionDiagram(sumOfGuards, allCommands, assignedGlobalVariables); + } else { + // Calculate number of required variables to encode the nondeterminism. + uint_fast64_t numberOfBinaryVariables = static_cast<uint_fast64_t>(std::ceil(storm::utility::math::log2(maxChoices))); + + storm::dd::Bdd<Type> equalsNumberOfChoicesDd; + std::vector<storm::dd::Add<Type, ValueType>> choiceDds(maxChoices, generationInfo.manager->template getAddZero<ValueType>()); + std::vector<storm::dd::Bdd<Type>> remainingDds(maxChoices, generationInfo.manager->getBddZero()); + + for (uint_fast64_t currentChoices = 1; currentChoices <= maxChoices; ++currentChoices) { + // Determine the set of states with exactly currentChoices choices. + equalsNumberOfChoicesDd = sumOfGuards.equals(generationInfo.manager->getConstant(ValueType(currentChoices))); + + // If there is no such state, continue with the next possible number of choices. + if (equalsNumberOfChoicesDd.isZero()) { + continue; + } + + // Reset the previously used intermediate storage. + for (uint_fast64_t j = 0; j < currentChoices; ++j) { + choiceDds[j] = generationInfo.manager->template getAddZero<ValueType>(); + remainingDds[j] = equalsNumberOfChoicesDd; + } + + for (std::size_t j = 0; j < commandDds.size(); ++j) { + // Check if command guard overlaps with equalsNumberOfChoicesDd. That is, there are states with exactly currentChoices + // choices such that one outgoing choice is given by the j-th command. + storm::dd::Bdd<Type> guardChoicesIntersection = commandDds[j].guardDd.toBdd() && equalsNumberOfChoicesDd; + + // If there is no such state, continue with the next command. + if (guardChoicesIntersection.isZero()) { + continue; + } + + // Split the nondeterministic choices. + for (uint_fast64_t k = 0; k < currentChoices; ++k) { + // Calculate the overlapping part of command guard and the remaining DD. + storm::dd::Bdd<Type> remainingGuardChoicesIntersection = guardChoicesIntersection && remainingDds[k]; + + // Check if we can add some overlapping parts to the current index. + if (!remainingGuardChoicesIntersection.isZero()) { + // Remove overlapping parts from the remaining DD. + remainingDds[k] = remainingDds[k] && !remainingGuardChoicesIntersection; + + // Combine the overlapping part of the guard with command updates and add it to the resulting DD. + choiceDds[k] += remainingGuardChoicesIntersection.template toAdd<ValueType>() * commandDds[j].transitionsDd; + } + + // Remove overlapping parts from the command guard DD + guardChoicesIntersection = guardChoicesIntersection && !remainingGuardChoicesIntersection; + + // If the guard DD has become equivalent to false, we can stop here. + if (guardChoicesIntersection.isZero()) { + break; + } + } + } + + // Add the meta variables that encode the nondeterminisim to the different choices. + for (uint_fast64_t j = 0; j < currentChoices; ++j) { + allCommands += encodeChoice(generationInfo, nondeterminismVariableOffset, numberOfBinaryVariables, j) * choiceDds[j]; + } + + // Delete currentChoices out of overlapping DD + sumOfGuards = sumOfGuards * (!equalsNumberOfChoicesDd).template toAdd<ValueType>(); + } + + return ActionDecisionDiagram(allGuards.template toAdd<ValueType>(), allCommands, assignedGlobalVariables, nondeterminismVariableOffset + numberOfBinaryVariables); + } + } + + template <storm::dd::DdType Type, typename ValueType> + typename DdPrismModelBuilder<Type, ValueType>::ActionDecisionDiagram DdPrismModelBuilder<Type, ValueType>::combineSynchronizingActions(ActionDecisionDiagram const& action1, ActionDecisionDiagram const& action2) { + std::set<storm::expressions::Variable> assignedGlobalVariables; + std::set_union(action1.assignedGlobalVariables.begin(), action1.assignedGlobalVariables.end(), action2.assignedGlobalVariables.begin(), action2.assignedGlobalVariables.end(), std::inserter(assignedGlobalVariables, assignedGlobalVariables.begin())); + return ActionDecisionDiagram(action1.guardDd * action2.guardDd, action1.transitionsDd * action2.transitionsDd, assignedGlobalVariables, std::max(action1.numberOfUsedNondeterminismVariables, action2.numberOfUsedNondeterminismVariables)); + } + + template <storm::dd::DdType Type, typename ValueType> + typename DdPrismModelBuilder<Type, ValueType>::ActionDecisionDiagram DdPrismModelBuilder<Type, ValueType>::combineUnsynchronizedActions(GenerationInformation const& generationInfo, ActionDecisionDiagram& action1, ActionDecisionDiagram& action2, storm::dd::Add<Type, ValueType> const& identityDd1, storm::dd::Add<Type, ValueType> const& identityDd2) { + + // First extend the action DDs by the other identities. + STORM_LOG_TRACE("Multiplying identities to combine unsynchronized actions."); + action1.transitionsDd = action1.transitionsDd * identityDd2; + action2.transitionsDd = action2.transitionsDd * identityDd1; + + // Then combine the extended action DDs. + return combineUnsynchronizedActions(generationInfo, action1, action2); + } + + template <storm::dd::DdType Type, typename ValueType> + typename DdPrismModelBuilder<Type, ValueType>::ActionDecisionDiagram DdPrismModelBuilder<Type, ValueType>::combineUnsynchronizedActions(GenerationInformation const& generationInfo, ActionDecisionDiagram& action1, ActionDecisionDiagram& action2) { + STORM_LOG_TRACE("Combining unsynchronized actions."); + + // Make both action DDs write to the same global variables. + std::set<storm::expressions::Variable> assignedGlobalVariables = equalizeAssignedGlobalVariables(generationInfo, action1, action2); + + if (generationInfo.program.getModelType() == storm::prism::Program::ModelType::DTMC || generationInfo.program.getModelType() == storm::prism::Program::ModelType::CTMC) { + return ActionDecisionDiagram(action1.guardDd + action2.guardDd, action1.transitionsDd + action2.transitionsDd, assignedGlobalVariables, 0); + } else if (generationInfo.program.getModelType() == storm::prism::Program::ModelType::MDP) { + if (action1.transitionsDd.isZero()) { + return ActionDecisionDiagram(action2.guardDd, action2.transitionsDd, assignedGlobalVariables, action2.numberOfUsedNondeterminismVariables); + } else if (action2.transitionsDd.isZero()) { + return ActionDecisionDiagram(action1.guardDd, action1.transitionsDd, assignedGlobalVariables, action1.numberOfUsedNondeterminismVariables); + } + + // Bring both choices to the same number of variables that encode the nondeterminism. + uint_fast64_t numberOfUsedNondeterminismVariables = std::max(action1.numberOfUsedNondeterminismVariables, action2.numberOfUsedNondeterminismVariables); + if (action1.numberOfUsedNondeterminismVariables > action2.numberOfUsedNondeterminismVariables) { + storm::dd::Add<Type, ValueType> nondeterminismEncoding = generationInfo.manager->template getAddOne<ValueType>(); + + for (uint_fast64_t i = action2.numberOfUsedNondeterminismVariables; i < action1.numberOfUsedNondeterminismVariables; ++i) { + nondeterminismEncoding *= generationInfo.manager->getEncoding(generationInfo.nondeterminismMetaVariables[i], 0).template toAdd<ValueType>(); + } + action2.transitionsDd *= nondeterminismEncoding; + } else if (action2.numberOfUsedNondeterminismVariables > action1.numberOfUsedNondeterminismVariables) { + storm::dd::Add<Type, ValueType> nondeterminismEncoding = generationInfo.manager->template getAddOne<ValueType>(); + + for (uint_fast64_t i = action1.numberOfUsedNondeterminismVariables; i < action2.numberOfUsedNondeterminismVariables; ++i) { + nondeterminismEncoding *= generationInfo.manager->getEncoding(generationInfo.nondeterminismMetaVariables[i], 0).template toAdd<ValueType>(); + } + action1.transitionsDd *= nondeterminismEncoding; + } + + // Add a new variable that resolves the nondeterminism between the two choices. + storm::dd::Add<Type, ValueType> combinedTransitions = generationInfo.manager->getEncoding(generationInfo.nondeterminismMetaVariables[numberOfUsedNondeterminismVariables], 1).ite(action2.transitionsDd, action1.transitionsDd); + + return ActionDecisionDiagram((action1.guardDd.toBdd() || action2.guardDd.toBdd()).template toAdd<ValueType>(), combinedTransitions, assignedGlobalVariables, numberOfUsedNondeterminismVariables + 1); + } else { + STORM_LOG_THROW(false, storm::exceptions::InvalidStateException, "Illegal model type."); + } + } + + template <storm::dd::DdType Type, typename ValueType> + typename DdPrismModelBuilder<Type, ValueType>::ModuleDecisionDiagram DdPrismModelBuilder<Type, ValueType>::createModuleDecisionDiagram(GenerationInformation& generationInfo, storm::prism::Module const& module, std::map<uint_fast64_t, uint_fast64_t> const& synchronizingActionToOffsetMap) { + // Start by creating the action DD for the independent action. + ActionDecisionDiagram independentActionDd = createActionDecisionDiagram(generationInfo, module, 0, 0); + uint_fast64_t numberOfUsedNondeterminismVariables = independentActionDd.numberOfUsedNondeterminismVariables; + + // Create module DD for all synchronizing actions of the module. + std::map<uint_fast64_t, ActionDecisionDiagram> actionIndexToDdMap; + for (auto const& actionIndex : module.getSynchronizingActionIndices()) { + STORM_LOG_TRACE("Creating DD for action '" << actionIndex << "'."); + ActionDecisionDiagram tmp = createActionDecisionDiagram(generationInfo, module, actionIndex, synchronizingActionToOffsetMap.at(actionIndex)); + numberOfUsedNondeterminismVariables = std::max(numberOfUsedNondeterminismVariables, tmp.numberOfUsedNondeterminismVariables); + actionIndexToDdMap.emplace(actionIndex, tmp); + } + + return ModuleDecisionDiagram(independentActionDd, actionIndexToDdMap, generationInfo.moduleToIdentityMap.at(module.getName()), numberOfUsedNondeterminismVariables); + } + + template <storm::dd::DdType Type, typename ValueType> + storm::dd::Add<Type, ValueType> DdPrismModelBuilder<Type, ValueType>::getSynchronizationDecisionDiagram(GenerationInformation& generationInfo, uint_fast64_t actionIndex) { + storm::dd::Add<Type, ValueType> synchronization = generationInfo.manager->template getAddOne<ValueType>(); + if (actionIndex != 0) { + for (uint_fast64_t i = 0; i < generationInfo.synchronizationMetaVariables.size(); ++i) { + if ((actionIndex - 1) == i) { + synchronization *= generationInfo.manager->getEncoding(generationInfo.synchronizationMetaVariables[i], 1).template toAdd<ValueType>(); + } else { + synchronization *= generationInfo.manager->getEncoding(generationInfo.synchronizationMetaVariables[i], 0).template toAdd<ValueType>(); + } + } + } else { + for (uint_fast64_t i = 0; i < generationInfo.synchronizationMetaVariables.size(); ++i) { + synchronization *= generationInfo.manager->getEncoding(generationInfo.synchronizationMetaVariables[i], 0).template toAdd<ValueType>(); + } + } + return synchronization; + } + + template <storm::dd::DdType Type, typename ValueType> + storm::dd::Add<Type, ValueType> DdPrismModelBuilder<Type, ValueType>::createSystemFromModule(GenerationInformation& generationInfo, ModuleDecisionDiagram const& module) { + // If the model is an MDP, we need to encode the nondeterminism using additional variables. + if (generationInfo.program.getModelType() == storm::prism::Program::ModelType::MDP) { + storm::dd::Add<Type, ValueType> result = generationInfo.manager->template getAddZero<ValueType>(); + + // First, determine the highest number of nondeterminism variables that is used in any action and make + // all actions use the same amout of nondeterminism variables. + uint_fast64_t numberOfUsedNondeterminismVariables = module.numberOfUsedNondeterminismVariables; + + // Compute missing global variable identities in independent action. + std::set<storm::expressions::Variable> missingIdentities; + std::set_difference(generationInfo.allGlobalVariables.begin(), generationInfo.allGlobalVariables.end(), module.independentAction.assignedGlobalVariables.begin(), module.independentAction.assignedGlobalVariables.end(), std::inserter(missingIdentities, missingIdentities.begin())); + storm::dd::Add<Type, ValueType> identityEncoding = generationInfo.manager->template getAddOne<ValueType>(); + for (auto const& variable : missingIdentities) { + STORM_LOG_TRACE("Multiplying identity of global variable " << variable.getName() << " to independent action."); + identityEncoding *= generationInfo.variableToIdentityMap.at(variable); + } + + // Add variables to independent action DD. + storm::dd::Add<Type, ValueType> nondeterminismEncoding = generationInfo.manager->template getAddOne<ValueType>(); + for (uint_fast64_t i = module.independentAction.numberOfUsedNondeterminismVariables; i < numberOfUsedNondeterminismVariables; ++i) { + nondeterminismEncoding *= generationInfo.manager->getEncoding(generationInfo.nondeterminismMetaVariables[i], 0).template toAdd<ValueType>(); + } + result = identityEncoding * module.independentAction.transitionsDd * nondeterminismEncoding; + + // Add variables to synchronized action DDs. + std::map<uint_fast64_t, storm::dd::Add<Type, ValueType>> synchronizingActionToDdMap; + for (auto const& synchronizingAction : module.synchronizingActionToDecisionDiagramMap) { + // Compute missing global variable identities in synchronizing actions. + missingIdentities = std::set<storm::expressions::Variable>(); + std::set_difference(generationInfo.allGlobalVariables.begin(), generationInfo.allGlobalVariables.end(), synchronizingAction.second.assignedGlobalVariables.begin(), synchronizingAction.second.assignedGlobalVariables.end(), std::inserter(missingIdentities, missingIdentities.begin())); + identityEncoding = generationInfo.manager->template getAddOne<ValueType>(); + for (auto const& variable : missingIdentities) { + STORM_LOG_TRACE("Multiplying identity of global variable " << variable.getName() << " to synchronizing action '" << synchronizingAction.first << "'."); + identityEncoding *= generationInfo.variableToIdentityMap.at(variable); + } + + nondeterminismEncoding = generationInfo.manager->template getAddOne<ValueType>(); + for (uint_fast64_t i = synchronizingAction.second.numberOfUsedNondeterminismVariables; i < numberOfUsedNondeterminismVariables; ++i) { + nondeterminismEncoding *= generationInfo.manager->getEncoding(generationInfo.nondeterminismMetaVariables[i], 0).template toAdd<ValueType>(); + } + synchronizingActionToDdMap.emplace(synchronizingAction.first, identityEncoding * synchronizingAction.second.transitionsDd * nondeterminismEncoding); + } + + // Add variables for synchronization. + result *= getSynchronizationDecisionDiagram(generationInfo); + + for (auto& synchronizingAction : synchronizingActionToDdMap) { + synchronizingAction.second *= getSynchronizationDecisionDiagram(generationInfo, synchronizingAction.first); + } + + // Now, we can simply add all synchronizing actions to the result. + for (auto const& synchronizingAction : synchronizingActionToDdMap) { + result += synchronizingAction.second; + } + + return result; + } else if (generationInfo.program.getModelType() == storm::prism::Program::ModelType::DTMC || generationInfo.program.getModelType() == storm::prism::Program::ModelType::CTMC) { + // Simply add all actions, but make sure to include the missing global variable identities. + + // Compute missing global variable identities in independent action. + std::set<storm::expressions::Variable> missingIdentities; + std::set_difference(generationInfo.allGlobalVariables.begin(), generationInfo.allGlobalVariables.end(), module.independentAction.assignedGlobalVariables.begin(), module.independentAction.assignedGlobalVariables.end(), std::inserter(missingIdentities, missingIdentities.begin())); + storm::dd::Add<Type, ValueType> identityEncoding = generationInfo.manager->template getAddOne<ValueType>(); + for (auto const& variable : missingIdentities) { + STORM_LOG_TRACE("Multiplying identity of global variable " << variable.getName() << " to independent action."); + identityEncoding *= generationInfo.variableToIdentityMap.at(variable); + } + + storm::dd::Add<Type, ValueType> result = identityEncoding * module.independentAction.transitionsDd; + + for (auto const& synchronizingAction : module.synchronizingActionToDecisionDiagramMap) { + // Compute missing global variable identities in synchronizing actions. + missingIdentities = std::set<storm::expressions::Variable>(); + std::set_difference(generationInfo.allGlobalVariables.begin(), generationInfo.allGlobalVariables.end(), synchronizingAction.second.assignedGlobalVariables.begin(), synchronizingAction.second.assignedGlobalVariables.end(), std::inserter(missingIdentities, missingIdentities.begin())); + identityEncoding = generationInfo.manager->template getAddOne<ValueType>(); + for (auto const& variable : missingIdentities) { + STORM_LOG_TRACE("Multiplying identity of global variable " << variable.getName() << " to synchronizing action '" << synchronizingAction.first << "'."); + identityEncoding *= generationInfo.variableToIdentityMap.at(variable); + } + + result += identityEncoding * synchronizingAction.second.transitionsDd; + } + return result; + } else { + STORM_LOG_THROW(false, storm::exceptions::InvalidArgumentException, "Illegal model type."); + } + } + + template <storm::dd::DdType Type, typename ValueType> + typename DdPrismModelBuilder<Type, ValueType>::SystemResult DdPrismModelBuilder<Type, ValueType>::createSystemDecisionDiagram(GenerationInformation& generationInfo) { + ModuleComposer<Type, ValueType> composer(generationInfo); + ModuleDecisionDiagram system = composer.compose(generationInfo.program.specifiesSystemComposition() ? generationInfo.program.getSystemCompositionConstruct().getSystemComposition() : *generationInfo.program.getDefaultSystemComposition()); + + storm::dd::Add<Type, ValueType> result = createSystemFromModule(generationInfo, system); + + // Create an auxiliary DD that is used later during the construction of reward models. + STORM_LOG_TRACE("Counting: " << result.getNonZeroCount() << " // " << result.getNodeCount()); + storm::dd::Add<Type, ValueType> stateActionDd = result.sumAbstract(generationInfo.columnMetaVariables); + + // For DTMCs, we normalize each row to 1 (to account for non-determinism). + if (generationInfo.program.getModelType() == storm::prism::Program::ModelType::DTMC) { + result = result / stateActionDd; + } else if (generationInfo.program.getModelType() == storm::prism::Program::ModelType::MDP) { + // For MDPs, we need to throw away the nondeterminism variables from the generation information that + // were never used. + for (uint_fast64_t index = system.numberOfUsedNondeterminismVariables; index < generationInfo.nondeterminismMetaVariables.size(); ++index) { + generationInfo.allNondeterminismVariables.erase(generationInfo.nondeterminismMetaVariables[index]); + } + generationInfo.nondeterminismMetaVariables.resize(system.numberOfUsedNondeterminismVariables); + } + + return SystemResult(result, system, stateActionDd); + } + + template <storm::dd::DdType Type, typename ValueType> + storm::models::symbolic::StandardRewardModel<Type, ValueType> DdPrismModelBuilder<Type, ValueType>::createRewardModelDecisionDiagrams(GenerationInformation& generationInfo, storm::prism::RewardModel const& rewardModel, ModuleDecisionDiagram const& globalModule, storm::dd::Add<Type, ValueType> const& reachableStatesAdd, storm::dd::Add<Type, ValueType> const& stateActionDd) { + + // Start by creating the state reward vector. + boost::optional<storm::dd::Add<Type, ValueType>> stateRewards; + if (rewardModel.hasStateRewards()) { + stateRewards = generationInfo.manager->template getAddZero<ValueType>(); + + for (auto const& stateReward : rewardModel.getStateRewards()) { + storm::dd::Add<Type, ValueType> states = generationInfo.rowExpressionAdapter->translateExpression(stateReward.getStatePredicateExpression()); + storm::dd::Add<Type, ValueType> rewards = generationInfo.rowExpressionAdapter->translateExpression(stateReward.getRewardValueExpression()); + + // Restrict the rewards to those states that satisfy the condition. + rewards = reachableStatesAdd * states * rewards; + + // Perform some sanity checks. + STORM_LOG_WARN_COND(rewards.getMin() >= 0, "The reward model assigns negative rewards to some states."); + STORM_LOG_WARN_COND(!rewards.isZero(), "The reward model does not assign any non-zero rewards."); + + // Add the rewards to the global state reward vector. + stateRewards.get() += rewards; + } + } + + // Next, build the state-action reward vector. + boost::optional<storm::dd::Add<Type, ValueType>> stateActionRewards; + if (rewardModel.hasStateActionRewards()) { + stateActionRewards = generationInfo.manager->template getAddZero<ValueType>(); + + for (auto const& stateActionReward : rewardModel.getStateActionRewards()) { + storm::dd::Add<Type, ValueType> states = generationInfo.rowExpressionAdapter->translateExpression(stateActionReward.getStatePredicateExpression()); + storm::dd::Add<Type, ValueType> rewards = generationInfo.rowExpressionAdapter->translateExpression(stateActionReward.getRewardValueExpression()); + storm::dd::Add<Type, ValueType> synchronization = generationInfo.manager->template getAddOne<ValueType>(); + + if (generationInfo.program.getModelType() == storm::prism::Program::ModelType::MDP) { + synchronization = getSynchronizationDecisionDiagram(generationInfo, stateActionReward.getActionIndex()); + } + ActionDecisionDiagram const& actionDd = stateActionReward.isLabeled() ? globalModule.synchronizingActionToDecisionDiagramMap.at(stateActionReward.getActionIndex()) : globalModule.independentAction; + states *= actionDd.guardDd * reachableStatesAdd; + storm::dd::Add<Type, ValueType> stateActionRewardDd = synchronization * states * rewards; + + // If we are building the state-action rewards for an MDP, we need to make sure that the encoding + // of the nondeterminism is present in the reward vector, so we ne need to multiply it with the + // legal state-actions. + if (generationInfo.program.getModelType() == storm::prism::Program::ModelType::MDP) { + stateActionRewardDd *= stateActionDd; + } else if (generationInfo.program.getModelType() == storm::prism::Program::ModelType::CTMC) { + // For CTMCs, we need to multiply the entries with the exit rate of the corresponding action. + stateActionRewardDd *= actionDd.transitionsDd.sumAbstract(generationInfo.columnMetaVariables); + } + + // Perform some sanity checks. + STORM_LOG_WARN_COND(stateActionRewardDd.getMin() >= 0, "The reward model assigns negative rewards to some states."); + STORM_LOG_WARN_COND(!stateActionRewardDd.isZero(), "The reward model does not assign any non-zero rewards."); + + // Add the rewards to the global transition reward matrix. + stateActionRewards.get() += stateActionRewardDd; + } + + // Scale state-action rewards for DTMCs and CTMCs. + if (generationInfo.program.getModelType() == storm::prism::Program::ModelType::DTMC || generationInfo.program.getModelType() == storm::prism::Program::ModelType::CTMC) { + stateActionRewards.get() /= stateActionDd; + } + } + + // Then build the transition reward matrix. + boost::optional<storm::dd::Add<Type, ValueType>> transitionRewards; + if (rewardModel.hasTransitionRewards()) { + transitionRewards = generationInfo.manager->template getAddZero<ValueType>(); + + for (auto const& transitionReward : rewardModel.getTransitionRewards()) { + storm::dd::Add<Type, ValueType> sourceStates = generationInfo.rowExpressionAdapter->translateExpression(transitionReward.getSourceStatePredicateExpression()); + storm::dd::Add<Type, ValueType> targetStates = generationInfo.rowExpressionAdapter->translateExpression(transitionReward.getTargetStatePredicateExpression()); + storm::dd::Add<Type, ValueType> rewards = generationInfo.rowExpressionAdapter->translateExpression(transitionReward.getRewardValueExpression()); + + storm::dd::Add<Type, ValueType> synchronization = generationInfo.manager->template getAddOne<ValueType>(); + + storm::dd::Add<Type, ValueType> transitions; + if (transitionReward.isLabeled()) { + if (generationInfo.program.getModelType() == storm::prism::Program::ModelType::MDP) { + synchronization = getSynchronizationDecisionDiagram(generationInfo, transitionReward.getActionIndex()); + } + transitions = globalModule.synchronizingActionToDecisionDiagramMap.at(transitionReward.getActionIndex()).transitionsDd; + } else { + if (generationInfo.program.getModelType() == storm::prism::Program::ModelType::MDP) { + synchronization = getSynchronizationDecisionDiagram(generationInfo); + } + transitions = globalModule.independentAction.transitionsDd; + } + + storm::dd::Add<Type, ValueType> transitionRewardDd = synchronization * sourceStates * targetStates * rewards; + if (generationInfo.program.getModelType() == storm::prism::Program::ModelType::DTMC) { + // For DTMCs we need to keep the weighting for the scaling that follows. + transitionRewardDd = transitions * transitionRewardDd; + } else { + // For all other model types, we do not scale the rewards. + transitionRewardDd = transitions.notZero().template toAdd<ValueType>() * transitionRewardDd; + } + + // Perform some sanity checks. + STORM_LOG_WARN_COND(transitionRewardDd.getMin() >= 0, "The reward model assigns negative rewards to some states."); + STORM_LOG_WARN_COND(!transitionRewardDd.isZero(), "The reward model does not assign any non-zero rewards."); + + // Add the rewards to the global transition reward matrix. + transitionRewards.get() += transitionRewardDd; + } + + // Scale transition rewards for DTMCs. + if (generationInfo.program.getModelType() == storm::prism::Program::ModelType::DTMC) { + transitionRewards.get() /= stateActionDd; + } + } + + return storm::models::symbolic::StandardRewardModel<Type, ValueType>(stateRewards, stateActionRewards, transitionRewards); + } + + template <storm::dd::DdType Type, typename ValueType> + std::shared_ptr<storm::models::symbolic::Model<Type, ValueType>> DdPrismModelBuilder<Type, ValueType>::build(storm::prism::Program const& program, Options const& options) { + if (program.hasUndefinedConstants()) { + std::vector<std::reference_wrapper<storm::prism::Constant const>> undefinedConstants = program.getUndefinedConstants(); + std::stringstream stream; + bool printComma = false; + for (auto const& constant : undefinedConstants) { + if (printComma) { + stream << ", "; + } else { + printComma = true; + } + stream << constant.get().getName() << " (" << constant.get().getType() << ")"; + } + stream << "."; + STORM_LOG_THROW(false, storm::exceptions::InvalidArgumentException, "Program still contains these undefined constants: " + stream.str()); + } + + STORM_LOG_TRACE("Building representation of program:" << std::endl << program << std::endl); + + // Start by initializing the structure used for storing all information needed during the model generation. + // In particular, this creates the meta variables used to encode the model. + GenerationInformation generationInfo(program); + + SystemResult system = createSystemDecisionDiagram(generationInfo); + storm::dd::Add<Type, ValueType> transitionMatrix = system.allTransitionsDd; + + ModuleDecisionDiagram const& globalModule = system.globalModule; + storm::dd::Add<Type, ValueType> stateActionDd = system.stateActionDd; + + // If we were asked to treat some states as terminal states, we cut away their transitions now. + storm::dd::Bdd<Type> terminalStatesBdd = generationInfo.manager->getBddZero(); + if (options.terminalStates || options.negatedTerminalStates) { + std::map<storm::expressions::Variable, storm::expressions::Expression> constantsSubstitution = program.getConstantsSubstitution(); + + if (options.terminalStates) { + storm::expressions::Expression terminalExpression; + if (options.terminalStates.get().type() == typeid(storm::expressions::Expression)) { + terminalExpression = boost::get<storm::expressions::Expression>(options.terminalStates.get()); + } else { + std::string const& labelName = boost::get<std::string>(options.terminalStates.get()); + if (program.hasLabel(labelName)) { + terminalExpression = program.getLabelExpression(labelName); + } else { + STORM_LOG_THROW(labelName == "init" || labelName == "deadlock", storm::exceptions::InvalidArgumentException, "Terminal states refer to illegal label '" << labelName << "'."); + } + } + + if (terminalExpression.isInitialized()) { + // If the expression refers to constants of the model, we need to substitute them. + terminalExpression = terminalExpression.substitute(constantsSubstitution); + + STORM_LOG_TRACE("Making the states satisfying " << terminalExpression << " terminal."); + terminalStatesBdd = generationInfo.rowExpressionAdapter->translateExpression(terminalExpression).toBdd(); + } + } + if (options.negatedTerminalStates) { + storm::expressions::Expression negatedTerminalExpression; + if (options.negatedTerminalStates.get().type() == typeid(storm::expressions::Expression)) { + negatedTerminalExpression = boost::get<storm::expressions::Expression>(options.negatedTerminalStates.get()); + } else { + std::string const& labelName = boost::get<std::string>(options.negatedTerminalStates.get()); + if (program.hasLabel(labelName)) { + negatedTerminalExpression = program.getLabelExpression(labelName); + } else { + STORM_LOG_THROW(labelName == "init" || labelName == "deadlock", storm::exceptions::InvalidArgumentException, "Terminal states refer to illegal label '" << labelName << "'."); + } + } + + if (negatedTerminalExpression.isInitialized()) { + // If the expression refers to constants of the model, we need to substitute them. + negatedTerminalExpression = negatedTerminalExpression.substitute(constantsSubstitution); + + STORM_LOG_TRACE("Making the states *not* satisfying " << negatedTerminalExpression << " terminal."); + terminalStatesBdd |= !generationInfo.rowExpressionAdapter->translateExpression(negatedTerminalExpression).toBdd(); + } + } + + transitionMatrix *= (!terminalStatesBdd).template toAdd<ValueType>(); + } + + std::cout << "trans matrix has size " << transitionMatrix.getNodeCount() << std::endl; + + // Cut the transitions and rewards to the reachable fragment of the state space. + storm::dd::Bdd<Type> initialStates = createInitialStatesDecisionDiagram(generationInfo); + + storm::dd::Bdd<Type> transitionMatrixBdd = transitionMatrix.notZero(); + if (program.getModelType() == storm::prism::Program::ModelType::MDP) { + transitionMatrixBdd = transitionMatrixBdd.existsAbstract(generationInfo.allNondeterminismVariables); + } + + storm::dd::Bdd<Type> reachableStates = storm::utility::dd::computeReachableStates<Type>(initialStates, transitionMatrixBdd, generationInfo.rowMetaVariables, generationInfo.columnMetaVariables); + storm::dd::Add<Type, ValueType> reachableStatesAdd = reachableStates.template toAdd<ValueType>(); + transitionMatrix *= reachableStatesAdd; + stateActionDd *= reachableStatesAdd; + + // Detect deadlocks and 1) fix them if requested 2) throw an error otherwise. + storm::dd::Bdd<Type> statesWithTransition = transitionMatrixBdd.existsAbstract(generationInfo.columnMetaVariables); + storm::dd::Bdd<Type> deadlockStates = reachableStates && !statesWithTransition; + + // If there are deadlocks, either fix them or raise an error. + if (!deadlockStates.isZero()) { + // If we need to fix deadlocks, we do so now. + if (!storm::settings::getModule<storm::settings::modules::CoreSettings>().isDontFixDeadlocksSet()) { + STORM_LOG_INFO("Fixing deadlocks in " << deadlockStates.getNonZeroCount() << " states. The first three of these states are: "); + + storm::dd::Add<Type, ValueType> deadlockStatesAdd = deadlockStates.template toAdd<ValueType>(); + uint_fast64_t count = 0; + for (auto it = deadlockStatesAdd.begin(), ite = deadlockStatesAdd.end(); it != ite && count < 3; ++it, ++count) { + STORM_LOG_INFO((*it).first.toPrettyString(generationInfo.rowMetaVariables) << std::endl); + } + + if (program.getModelType() == storm::prism::Program::ModelType::DTMC || program.getModelType() == storm::prism::Program::ModelType::CTMC) { + storm::dd::Add<Type, ValueType> identity = globalModule.identity; + + // Make sure that global variables do not change along the introduced self-loops. + for (auto const& var : generationInfo.allGlobalVariables) { + identity *= generationInfo.variableToIdentityMap.at(var); + } + + // For DTMCs, we can simply add the identity of the global module for all deadlock states. + transitionMatrix += deadlockStatesAdd * identity; + } else if (program.getModelType() == storm::prism::Program::ModelType::MDP) { + // For MDPs, however, we need to select an action associated with the self-loop, if we do not + // want to attach a lot of self-loops to the deadlock states. + storm::dd::Add<Type, ValueType> action = generationInfo.manager->template getAddOne<ValueType>(); + for (auto const& metaVariable : generationInfo.allNondeterminismVariables) { + action *= generationInfo.manager->template getIdentity<ValueType>(metaVariable); + } + // Make sure that global variables do not change along the introduced self-loops. + for (auto const& var : generationInfo.allGlobalVariables) { + action *= generationInfo.variableToIdentityMap.at(var); + } + transitionMatrix += deadlockStatesAdd * globalModule.identity * action; + } + } else { + STORM_LOG_THROW(false, storm::exceptions::InvalidArgumentException, "The model contains " << deadlockStates.getNonZeroCount() << " deadlock states. Please unset the option to not fix deadlocks, if you want to fix them automatically."); + } + } + + // Reduce the deadlock states by the states that we did simply not explore. + deadlockStates = deadlockStates && !terminalStatesBdd; + + // Now build the reward models. + std::vector<std::reference_wrapper<storm::prism::RewardModel const>> selectedRewardModels; + + // First, we make sure that all selected reward models actually exist. + for (auto const& rewardModelName : options.rewardModelsToBuild) { + STORM_LOG_THROW(rewardModelName.empty() || program.hasRewardModel(rewardModelName), storm::exceptions::InvalidArgumentException, "Model does not possess a reward model with the name '" << rewardModelName << "'."); + } + + for (auto const& rewardModel : program.getRewardModels()) { + if (options.buildAllRewardModels || options.rewardModelsToBuild.find(rewardModel.getName()) != options.rewardModelsToBuild.end()) { + std::cout << "build all? " << buildAllRewardModels << std::endl; + selectedRewardModels.push_back(rewardModel); + } + } + // If no reward model was selected until now and a referenced reward model appears to be unique, we build + // the only existing reward model (given that no explicit name was given for the referenced reward model). + if (selectedRewardModels.empty() && program.getNumberOfRewardModels() == 1 && options.rewardModelsToBuild.size() == 1 && *options.rewardModelsToBuild.begin() == "") { + selectedRewardModels.push_back(program.getRewardModel(0)); + } + + std::unordered_map<std::string, storm::models::symbolic::StandardRewardModel<Type, ValueType>> rewardModels; + for (auto const& rewardModel : selectedRewardModels) { + rewardModels.emplace(rewardModel.get().getName(), createRewardModelDecisionDiagrams(generationInfo, rewardModel.get(), globalModule, reachableStatesAdd, stateActionDd)); + } + + // Build the labels that can be accessed as a shortcut. + std::map<std::string, storm::expressions::Expression> labelToExpressionMapping; + for (auto const& label : program.getLabels()) { + labelToExpressionMapping.emplace(label.getName(), label.getStatePredicateExpression()); + } + + if (program.getModelType() == storm::prism::Program::ModelType::DTMC) { + return std::shared_ptr<storm::models::symbolic::Model<Type, ValueType>>(new storm::models::symbolic::Dtmc<Type, ValueType>(generationInfo.manager, reachableStates, initialStates, deadlockStates, transitionMatrix, generationInfo.rowMetaVariables, generationInfo.rowExpressionAdapter, generationInfo.columnMetaVariables, generationInfo.columnExpressionAdapter, generationInfo.rowColumnMetaVariablePairs, labelToExpressionMapping, rewardModels)); + } else if (program.getModelType() == storm::prism::Program::ModelType::CTMC) { + return std::shared_ptr<storm::models::symbolic::Model<Type, ValueType>>(new storm::models::symbolic::Ctmc<Type, ValueType>(generationInfo.manager, reachableStates, initialStates, deadlockStates, transitionMatrix, generationInfo.rowMetaVariables, generationInfo.rowExpressionAdapter, generationInfo.columnMetaVariables, generationInfo.columnExpressionAdapter, generationInfo.rowColumnMetaVariablePairs, labelToExpressionMapping, rewardModels)); + } else if (program.getModelType() == storm::prism::Program::ModelType::MDP) { + return std::shared_ptr<storm::models::symbolic::Model<Type, ValueType>>(new storm::models::symbolic::Mdp<Type, ValueType>(generationInfo.manager, reachableStates, initialStates, deadlockStates, transitionMatrix, generationInfo.rowMetaVariables, generationInfo.rowExpressionAdapter, generationInfo.columnMetaVariables, generationInfo.columnExpressionAdapter, generationInfo.rowColumnMetaVariablePairs, generationInfo.allNondeterminismVariables, labelToExpressionMapping, rewardModels)); + } else { + STORM_LOG_THROW(false, storm::exceptions::InvalidArgumentException, "Invalid model type."); + } + } + + template <storm::dd::DdType Type, typename ValueType> + storm::dd::Bdd<Type> DdPrismModelBuilder<Type, ValueType>::createInitialStatesDecisionDiagram(GenerationInformation& generationInfo) { + storm::dd::Bdd<Type> initialStates = generationInfo.rowExpressionAdapter->translateExpression(generationInfo.program.getInitialStatesExpression()).toBdd(); + + for (auto const& metaVariable : generationInfo.rowMetaVariables) { + initialStates &= generationInfo.manager->getRange(metaVariable); + } + + return initialStates; + } + + // Explicitly instantiate the symbolic model builder. + template class DdPrismModelBuilder<storm::dd::DdType::CUDD>; + template class DdPrismModelBuilder<storm::dd::DdType::Sylvan>; + + } // namespace adapters +} // namespace storm + + diff --git a/src/storm/builder/DdPrismModelBuilder.cpp b/src/storm/builder/DdPrismModelBuilder.cpp index 988335cbb..e2afeeae6 100644 --- a/src/storm/builder/DdPrismModelBuilder.cpp +++ b/src/storm/builder/DdPrismModelBuilder.cpp @@ -470,7 +470,7 @@ namespace storm { }; template <storm::dd::DdType Type, typename ValueType> - DdPrismModelBuilder<Type, ValueType>::Options::Options() : buildAllRewardModels(true), rewardModelsToBuild(), buildAllLabels(true), labelsToBuild(), terminalStates(), negatedTerminalStates() { + DdPrismModelBuilder<Type, ValueType>::Options::Options() : buildAllRewardModels(false), rewardModelsToBuild(), buildAllLabels(false), labelsToBuild(), terminalStates(), negatedTerminalStates() { // Intentionally left empty. } @@ -482,16 +482,11 @@ namespace storm { template <storm::dd::DdType Type, typename ValueType> DdPrismModelBuilder<Type, ValueType>::Options::Options(std::vector<std::shared_ptr<storm::logic::Formula const>> const& formulas) : buildAllRewardModels(false), rewardModelsToBuild(), buildAllLabels(false), labelsToBuild(), terminalStates(), negatedTerminalStates() { - if (formulas.empty()) { - this->buildAllRewardModels = true; - this->buildAllLabels = true; - } else { - for (auto const& formula : formulas) { - this->preserveFormula(*formula); - } - if (formulas.size() == 1) { - this->setTerminalStatesFromFormula(*formulas.front()); - } + for (auto const& formula : formulas) { + this->preserveFormula(*formula); + } + if (formulas.size() == 1) { + this->setTerminalStatesFromFormula(*formulas.front()); } } @@ -553,13 +548,13 @@ namespace storm { template <storm::dd::DdType Type, typename ValueType> struct DdPrismModelBuilder<Type, ValueType>::SystemResult { - SystemResult(storm::dd::Add<Type, ValueType> const& allTransitionsDd, DdPrismModelBuilder<Type, ValueType>::ModuleDecisionDiagram const& globalModule, storm::dd::Add<Type, ValueType> const& stateActionDd) : allTransitionsDd(allTransitionsDd), globalModule(globalModule), stateActionDd(stateActionDd) { + SystemResult(storm::dd::Add<Type, ValueType> const& allTransitionsDd, DdPrismModelBuilder<Type, ValueType>::ModuleDecisionDiagram const& globalModule, boost::optional<storm::dd::Add<Type, ValueType>> const& stateActionDd) : allTransitionsDd(allTransitionsDd), globalModule(globalModule), stateActionDd(stateActionDd) { // Intentionally left empty. } storm::dd::Add<Type, ValueType> allTransitionsDd; typename DdPrismModelBuilder<Type, ValueType>::ModuleDecisionDiagram globalModule; - storm::dd::Add<Type, ValueType> stateActionDd; + boost::optional<storm::dd::Add<Type, ValueType>> stateActionDd; }; template <storm::dd::DdType Type, typename ValueType> @@ -623,14 +618,14 @@ namespace storm { template <storm::dd::DdType Type, typename ValueType> typename DdPrismModelBuilder<Type, ValueType>::ActionDecisionDiagram DdPrismModelBuilder<Type, ValueType>::createCommandDecisionDiagram(GenerationInformation& generationInfo, storm::prism::Module const& module, storm::prism::Command const& command) { STORM_LOG_TRACE("Translating guard " << command.getGuardExpression()); - storm::dd::Add<Type, ValueType> guard = generationInfo.rowExpressionAdapter->translateExpression(command.getGuardExpression()) * generationInfo.moduleToRangeMap[module.getName()]; + storm::dd::Bdd<Type> guard = generationInfo.rowExpressionAdapter->translateBooleanExpression(command.getGuardExpression()) && generationInfo.moduleToRangeMap[module.getName()].notZero(); STORM_LOG_WARN_COND(!guard.isZero(), "The guard '" << command.getGuardExpression() << "' is unsatisfiable."); if (!guard.isZero()) { // Create the DDs representing the individual updates. std::vector<UpdateDecisionDiagram> updateResults; for (storm::prism::Update const& update : command.getUpdates()) { - updateResults.push_back(createUpdateDecisionDiagram(generationInfo, module, guard, update)); + updateResults.push_back(createUpdateDecisionDiagram(generationInfo, module, guard.template toAdd<ValueType>(), update)); STORM_LOG_WARN_COND(!updateResults.back().updateDd.isZero(), "Update '" << update << "' does not have any effect."); } @@ -666,7 +661,7 @@ namespace storm { commandDd += updateResultsIt->updateDd * probabilityDd; } - return ActionDecisionDiagram(guard, guard * commandDd, globalVariablesInSomeUpdate); + return ActionDecisionDiagram(guard, guard.template toAdd<ValueType>() * commandDd, globalVariablesInSomeUpdate); } else { return ActionDecisionDiagram(*generationInfo.manager); } @@ -754,9 +749,9 @@ namespace storm { template <storm::dd::DdType Type, typename ValueType> typename DdPrismModelBuilder<Type, ValueType>::ActionDecisionDiagram DdPrismModelBuilder<Type, ValueType>::combineCommandsToActionMarkovChain(GenerationInformation& generationInfo, std::vector<ActionDecisionDiagram>& commandDds) { - storm::dd::Add<Type, ValueType> allGuards = generationInfo.manager->template getAddZero<ValueType>(); + storm::dd::Bdd<Type> allGuards = generationInfo.manager->getBddZero(); storm::dd::Add<Type, ValueType> allCommands = generationInfo.manager->template getAddZero<ValueType>(); - storm::dd::Add<Type, ValueType> temporary; + storm::dd::Bdd<Type> temporary; // Make all command DDs assign to the same global variables. std::set<storm::expressions::Variable> assignedGlobalVariables = equalizeAssignedGlobalVariables(generationInfo, commandDds); @@ -764,12 +759,12 @@ namespace storm { // Then combine the commands to the full action DD and multiply missing identities along the way. for (auto& commandDd : commandDds) { // Check for overlapping guards. - temporary = commandDd.guardDd * allGuards; + temporary = commandDd.guardDd && allGuards; // Issue a warning if there are overlapping guards in a non-CTMC model. STORM_LOG_WARN_COND(temporary.isZero() || generationInfo.program.getModelType() == storm::prism::Program::ModelType::CTMC, "Guard of a command overlaps with previous guards."); - allGuards += commandDd.guardDd; + allGuards |= commandDd.guardDd; allCommands += commandDd.transitionsDd; } @@ -806,8 +801,8 @@ namespace storm { // Sum all guards, so we can read off the maximal number of nondeterministic choices in any given state. storm::dd::Add<Type, ValueType> sumOfGuards = generationInfo.manager->template getAddZero<ValueType>(); for (auto const& commandDd : commandDds) { - sumOfGuards += commandDd.guardDd; - allGuards |= commandDd.guardDd.toBdd(); + sumOfGuards += commandDd.guardDd.template toAdd<ValueType>(); + allGuards |= commandDd.guardDd; } uint_fast64_t maxChoices = static_cast<uint_fast64_t>(sumOfGuards.getMax()); @@ -821,7 +816,7 @@ namespace storm { for (auto const& commandDd : commandDds) { allCommands += commandDd.transitionsDd; } - return ActionDecisionDiagram(sumOfGuards, allCommands, assignedGlobalVariables); + return ActionDecisionDiagram(allGuards, allCommands, assignedGlobalVariables); } else { // Calculate number of required variables to encode the nondeterminism. uint_fast64_t numberOfBinaryVariables = static_cast<uint_fast64_t>(std::ceil(storm::utility::math::log2(maxChoices))); @@ -848,7 +843,7 @@ namespace storm { for (std::size_t j = 0; j < commandDds.size(); ++j) { // Check if command guard overlaps with equalsNumberOfChoicesDd. That is, there are states with exactly currentChoices // choices such that one outgoing choice is given by the j-th command. - storm::dd::Bdd<Type> guardChoicesIntersection = commandDds[j].guardDd.toBdd() && equalsNumberOfChoicesDd; + storm::dd::Bdd<Type> guardChoicesIntersection = commandDds[j].guardDd && equalsNumberOfChoicesDd; // If there is no such state, continue with the next command. if (guardChoicesIntersection.isZero()) { @@ -888,7 +883,7 @@ namespace storm { sumOfGuards = sumOfGuards * (!equalsNumberOfChoicesDd).template toAdd<ValueType>(); } - return ActionDecisionDiagram(allGuards.template toAdd<ValueType>(), allCommands, assignedGlobalVariables, nondeterminismVariableOffset + numberOfBinaryVariables); + return ActionDecisionDiagram(allGuards, allCommands, assignedGlobalVariables, nondeterminismVariableOffset + numberOfBinaryVariables); } } @@ -896,7 +891,7 @@ namespace storm { typename DdPrismModelBuilder<Type, ValueType>::ActionDecisionDiagram DdPrismModelBuilder<Type, ValueType>::combineSynchronizingActions(ActionDecisionDiagram const& action1, ActionDecisionDiagram const& action2) { std::set<storm::expressions::Variable> assignedGlobalVariables; std::set_union(action1.assignedGlobalVariables.begin(), action1.assignedGlobalVariables.end(), action2.assignedGlobalVariables.begin(), action2.assignedGlobalVariables.end(), std::inserter(assignedGlobalVariables, assignedGlobalVariables.begin())); - return ActionDecisionDiagram(action1.guardDd * action2.guardDd, action1.transitionsDd * action2.transitionsDd, assignedGlobalVariables, std::max(action1.numberOfUsedNondeterminismVariables, action2.numberOfUsedNondeterminismVariables)); + return ActionDecisionDiagram(action1.guardDd && action2.guardDd, action1.transitionsDd * action2.transitionsDd, assignedGlobalVariables, std::max(action1.numberOfUsedNondeterminismVariables, action2.numberOfUsedNondeterminismVariables)); } template <storm::dd::DdType Type, typename ValueType> @@ -919,7 +914,7 @@ namespace storm { std::set<storm::expressions::Variable> assignedGlobalVariables = equalizeAssignedGlobalVariables(generationInfo, action1, action2); if (generationInfo.program.getModelType() == storm::prism::Program::ModelType::DTMC || generationInfo.program.getModelType() == storm::prism::Program::ModelType::CTMC) { - return ActionDecisionDiagram(action1.guardDd + action2.guardDd, action1.transitionsDd + action2.transitionsDd, assignedGlobalVariables, 0); + return ActionDecisionDiagram(action1.guardDd || action2.guardDd, action1.transitionsDd + action2.transitionsDd, assignedGlobalVariables, 0); } else if (generationInfo.program.getModelType() == storm::prism::Program::ModelType::MDP) { if (action1.transitionsDd.isZero()) { return ActionDecisionDiagram(action2.guardDd, action2.transitionsDd, assignedGlobalVariables, action2.numberOfUsedNondeterminismVariables); @@ -948,7 +943,7 @@ namespace storm { // Add a new variable that resolves the nondeterminism between the two choices. storm::dd::Add<Type, ValueType> combinedTransitions = generationInfo.manager->getEncoding(generationInfo.nondeterminismMetaVariables[numberOfUsedNondeterminismVariables], 1).ite(action2.transitionsDd, action1.transitionsDd); - return ActionDecisionDiagram((action1.guardDd.toBdd() || action2.guardDd.toBdd()).template toAdd<ValueType>(), combinedTransitions, assignedGlobalVariables, numberOfUsedNondeterminismVariables + 1); + return ActionDecisionDiagram(action1.guardDd || action2.guardDd, combinedTransitions, assignedGlobalVariables, numberOfUsedNondeterminismVariables + 1); } else { STORM_LOG_THROW(false, storm::exceptions::InvalidStateException, "Illegal model type."); } @@ -1087,13 +1082,14 @@ namespace storm { ModuleDecisionDiagram system = composer.compose(generationInfo.program.specifiesSystemComposition() ? generationInfo.program.getSystemCompositionConstruct().getSystemComposition() : *generationInfo.program.getDefaultSystemComposition()); storm::dd::Add<Type, ValueType> result = createSystemFromModule(generationInfo, system); - + // Create an auxiliary DD that is used later during the construction of reward models. - storm::dd::Add<Type, ValueType> stateActionDd = result.sumAbstract(generationInfo.columnMetaVariables); + boost::optional<storm::dd::Add<Type, ValueType>> stateActionDd; // For DTMCs, we normalize each row to 1 (to account for non-determinism). if (generationInfo.program.getModelType() == storm::prism::Program::ModelType::DTMC) { - result = result / stateActionDd; + stateActionDd = result.sumAbstract(generationInfo.columnMetaVariables); + result = result / stateActionDd.get(); } else if (generationInfo.program.getModelType() == storm::prism::Program::ModelType::MDP) { // For MDPs, we need to throw away the nondeterminism variables from the generation information that // were never used. @@ -1107,7 +1103,16 @@ namespace storm { } template <storm::dd::DdType Type, typename ValueType> - storm::models::symbolic::StandardRewardModel<Type, ValueType> DdPrismModelBuilder<Type, ValueType>::createRewardModelDecisionDiagrams(GenerationInformation& generationInfo, storm::prism::RewardModel const& rewardModel, ModuleDecisionDiagram const& globalModule, storm::dd::Add<Type, ValueType> const& reachableStatesAdd, storm::dd::Add<Type, ValueType> const& stateActionDd) { + std::unordered_map<std::string, storm::models::symbolic::StandardRewardModel<Type, ValueType>> DdPrismModelBuilder<Type, ValueType>::createRewardModelDecisionDiagrams(std::vector<std::reference_wrapper<storm::prism::RewardModel const>> const& selectedRewardModels, SystemResult& system, GenerationInformation& generationInfo, ModuleDecisionDiagram const& globalModule, storm::dd::Add<Type, ValueType> const& reachableStatesAdd, storm::dd::Add<Type, ValueType> const& transitionMatrix) { + std::unordered_map<std::string, storm::models::symbolic::StandardRewardModel<Type, ValueType>> rewardModels; + for (auto const& rewardModel : selectedRewardModels) { + rewardModels.emplace(rewardModel.get().getName(), createRewardModelDecisionDiagrams(generationInfo, rewardModel.get(), globalModule, reachableStatesAdd, transitionMatrix, system.stateActionDd)); + } + return rewardModels; + } + + template <storm::dd::DdType Type, typename ValueType> + storm::models::symbolic::StandardRewardModel<Type, ValueType> DdPrismModelBuilder<Type, ValueType>::createRewardModelDecisionDiagrams(GenerationInformation& generationInfo, storm::prism::RewardModel const& rewardModel, ModuleDecisionDiagram const& globalModule, storm::dd::Add<Type, ValueType> const& reachableStatesAdd, storm::dd::Add<Type, ValueType> const& transitionMatrix, boost::optional<storm::dd::Add<Type, ValueType>>& stateActionDd) { // Start by creating the state reward vector. boost::optional<storm::dd::Add<Type, ValueType>> stateRewards; @@ -1144,14 +1149,16 @@ namespace storm { synchronization = getSynchronizationDecisionDiagram(generationInfo, stateActionReward.getActionIndex()); } ActionDecisionDiagram const& actionDd = stateActionReward.isLabeled() ? globalModule.synchronizingActionToDecisionDiagramMap.at(stateActionReward.getActionIndex()) : globalModule.independentAction; - states *= actionDd.guardDd * reachableStatesAdd; + states *= actionDd.guardDd.template toAdd<ValueType>() * reachableStatesAdd; storm::dd::Add<Type, ValueType> stateActionRewardDd = synchronization * states * rewards; - // If we are building the state-action rewards for an MDP, we need to make sure that the encoding - // of the nondeterminism is present in the reward vector, so we ne need to multiply it with the - // legal state-actions. + // If we are building the state-action rewards for an MDP, we need to make sure that the reward is + // only given on legal nondeterminism encodings, which is why we multiply with the state-action DD. if (generationInfo.program.getModelType() == storm::prism::Program::ModelType::MDP) { - stateActionRewardDd *= stateActionDd; + if (!stateActionDd) { + stateActionDd = transitionMatrix.notZero().existsAbstract(generationInfo.columnMetaVariables).template toAdd<ValueType>(); + } + stateActionRewardDd *= stateActionDd.get(); } else if (generationInfo.program.getModelType() == storm::prism::Program::ModelType::CTMC) { // For CTMCs, we need to multiply the entries with the exit rate of the corresponding action. stateActionRewardDd *= actionDd.transitionsDd.sumAbstract(generationInfo.columnMetaVariables); @@ -1167,7 +1174,11 @@ namespace storm { // Scale state-action rewards for DTMCs and CTMCs. if (generationInfo.program.getModelType() == storm::prism::Program::ModelType::DTMC || generationInfo.program.getModelType() == storm::prism::Program::ModelType::CTMC) { - stateActionRewards.get() /= stateActionDd; + if (!stateActionDd) { + stateActionDd = transitionMatrix.sumAbstract(generationInfo.columnMetaVariables); + } + + stateActionRewards.get() /= stateActionDd.get(); } } @@ -1215,7 +1226,7 @@ namespace storm { // Scale transition rewards for DTMCs. if (generationInfo.program.getModelType() == storm::prism::Program::ModelType::DTMC) { - transitionRewards.get() /= stateActionDd; + transitionRewards.get() /= stateActionDd.get(); } } @@ -1240,7 +1251,7 @@ namespace storm { STORM_LOG_THROW(false, storm::exceptions::InvalidArgumentException, "Program still contains these undefined constants: " + stream.str()); } - STORM_LOG_DEBUG("Building representation of program:" << std::endl << program << std::endl); + STORM_LOG_TRACE("Building representation of program:" << std::endl << program << std::endl); // Start by initializing the structure used for storing all information needed during the model generation. // In particular, this creates the meta variables used to encode the model. @@ -1250,7 +1261,6 @@ namespace storm { storm::dd::Add<Type, ValueType> transitionMatrix = system.allTransitionsDd; ModuleDecisionDiagram const& globalModule = system.globalModule; - storm::dd::Add<Type, ValueType> stateActionDd = system.stateActionDd; // If we were asked to treat some states as terminal states, we cut away their transitions now. storm::dd::Bdd<Type> terminalStatesBdd = generationInfo.manager->getBddZero(); @@ -1314,7 +1324,9 @@ namespace storm { storm::dd::Bdd<Type> reachableStates = storm::utility::dd::computeReachableStates<Type>(initialStates, transitionMatrixBdd, generationInfo.rowMetaVariables, generationInfo.columnMetaVariables); storm::dd::Add<Type, ValueType> reachableStatesAdd = reachableStates.template toAdd<ValueType>(); transitionMatrix *= reachableStatesAdd; - stateActionDd *= reachableStatesAdd; + if (system.stateActionDd) { + system.stateActionDd.get() *= reachableStatesAdd; + } // Detect deadlocks and 1) fix them if requested 2) throw an error otherwise. storm::dd::Bdd<Type> statesWithTransition = transitionMatrixBdd.existsAbstract(generationInfo.columnMetaVariables); @@ -1382,10 +1394,7 @@ namespace storm { selectedRewardModels.push_back(program.getRewardModel(0)); } - std::unordered_map<std::string, storm::models::symbolic::StandardRewardModel<Type, ValueType>> rewardModels; - for (auto const& rewardModel : selectedRewardModels) { - rewardModels.emplace(rewardModel.get().getName(), createRewardModelDecisionDiagrams(generationInfo, rewardModel.get(), globalModule, reachableStatesAdd, stateActionDd)); - } + std::unordered_map<std::string, storm::models::symbolic::StandardRewardModel<Type, ValueType>> rewardModels = createRewardModelDecisionDiagrams(selectedRewardModels, system, generationInfo, globalModule, reachableStatesAdd, transitionMatrix); // Build the labels that can be accessed as a shortcut. std::map<std::string, storm::expressions::Expression> labelToExpressionMapping; @@ -1396,7 +1405,7 @@ namespace storm { if (program.getModelType() == storm::prism::Program::ModelType::DTMC) { return std::shared_ptr<storm::models::symbolic::Model<Type, ValueType>>(new storm::models::symbolic::Dtmc<Type, ValueType>(generationInfo.manager, reachableStates, initialStates, deadlockStates, transitionMatrix, generationInfo.rowMetaVariables, generationInfo.rowExpressionAdapter, generationInfo.columnMetaVariables, generationInfo.columnExpressionAdapter, generationInfo.rowColumnMetaVariablePairs, labelToExpressionMapping, rewardModels)); } else if (program.getModelType() == storm::prism::Program::ModelType::CTMC) { - return std::shared_ptr<storm::models::symbolic::Model<Type, ValueType>>(new storm::models::symbolic::Ctmc<Type, ValueType>(generationInfo.manager, reachableStates, initialStates, deadlockStates, transitionMatrix, generationInfo.rowMetaVariables, generationInfo.rowExpressionAdapter, generationInfo.columnMetaVariables, generationInfo.columnExpressionAdapter, generationInfo.rowColumnMetaVariablePairs, labelToExpressionMapping, rewardModels)); + return std::shared_ptr<storm::models::symbolic::Model<Type, ValueType>>(new storm::models::symbolic::Ctmc<Type, ValueType>(generationInfo.manager, reachableStates, initialStates, deadlockStates, transitionMatrix, system.stateActionDd, generationInfo.rowMetaVariables, generationInfo.rowExpressionAdapter, generationInfo.columnMetaVariables, generationInfo.columnExpressionAdapter, generationInfo.rowColumnMetaVariablePairs, labelToExpressionMapping, rewardModels)); } else if (program.getModelType() == storm::prism::Program::ModelType::MDP) { return std::shared_ptr<storm::models::symbolic::Model<Type, ValueType>>(new storm::models::symbolic::Mdp<Type, ValueType>(generationInfo.manager, reachableStates, initialStates, deadlockStates, transitionMatrix, generationInfo.rowMetaVariables, generationInfo.rowExpressionAdapter, generationInfo.columnMetaVariables, generationInfo.columnExpressionAdapter, generationInfo.rowColumnMetaVariablePairs, generationInfo.allNondeterminismVariables, labelToExpressionMapping, rewardModels)); } else { diff --git a/src/storm/builder/DdPrismModelBuilder.h b/src/storm/builder/DdPrismModelBuilder.h index 5b1db357f..f3b7adc31 100644 --- a/src/storm/builder/DdPrismModelBuilder.h +++ b/src/storm/builder/DdPrismModelBuilder.h @@ -122,11 +122,11 @@ namespace storm { // Intentionally left empty. } - ActionDecisionDiagram(storm::dd::DdManager<Type> const& manager, std::set<storm::expressions::Variable> const& assignedGlobalVariables = std::set<storm::expressions::Variable>(), uint_fast64_t numberOfUsedNondeterminismVariables = 0) : guardDd(manager.template getAddZero<ValueType>()), transitionsDd(manager.template getAddZero<ValueType>()), numberOfUsedNondeterminismVariables(numberOfUsedNondeterminismVariables), assignedGlobalVariables(assignedGlobalVariables) { + ActionDecisionDiagram(storm::dd::DdManager<Type> const& manager, std::set<storm::expressions::Variable> const& assignedGlobalVariables = std::set<storm::expressions::Variable>(), uint_fast64_t numberOfUsedNondeterminismVariables = 0) : guardDd(manager.getBddZero()), transitionsDd(manager.template getAddZero<ValueType>()), numberOfUsedNondeterminismVariables(numberOfUsedNondeterminismVariables), assignedGlobalVariables(assignedGlobalVariables) { // Intentionally left empty. } - ActionDecisionDiagram(storm::dd::Add<Type, ValueType> guardDd, storm::dd::Add<Type, ValueType> transitionsDd, std::set<storm::expressions::Variable> const& assignedGlobalVariables = std::set<storm::expressions::Variable>(), uint_fast64_t numberOfUsedNondeterminismVariables = 0) : guardDd(guardDd), transitionsDd(transitionsDd), numberOfUsedNondeterminismVariables(numberOfUsedNondeterminismVariables), assignedGlobalVariables(assignedGlobalVariables) { + ActionDecisionDiagram(storm::dd::Bdd<Type> guardDd, storm::dd::Add<Type, ValueType> transitionsDd, std::set<storm::expressions::Variable> const& assignedGlobalVariables = std::set<storm::expressions::Variable>(), uint_fast64_t numberOfUsedNondeterminismVariables = 0) : guardDd(guardDd), transitionsDd(transitionsDd), numberOfUsedNondeterminismVariables(numberOfUsedNondeterminismVariables), assignedGlobalVariables(assignedGlobalVariables) { // Intentionally left empty. } @@ -134,7 +134,7 @@ namespace storm { ActionDecisionDiagram& operator=(ActionDecisionDiagram const& other) = default; // The guard of the action. - storm::dd::Add<Type, ValueType> guardDd; + storm::dd::Bdd<Type> guardDd; // The actual transitions (source and target states). storm::dd::Add<Type, ValueType> transitionsDd; @@ -230,7 +230,9 @@ namespace storm { static storm::dd::Add<Type, ValueType> createSystemFromModule(GenerationInformation& generationInfo, ModuleDecisionDiagram const& module); - static storm::models::symbolic::StandardRewardModel<Type, ValueType> createRewardModelDecisionDiagrams(GenerationInformation& generationInfo, storm::prism::RewardModel const& rewardModel, ModuleDecisionDiagram const& globalModule, storm::dd::Add<Type, ValueType> const& reachableStatesAdd, storm::dd::Add<Type, ValueType> const& stateActionDd); + static std::unordered_map<std::string, storm::models::symbolic::StandardRewardModel<Type, ValueType>> createRewardModelDecisionDiagrams(std::vector<std::reference_wrapper<storm::prism::RewardModel const>> const& selectedRewardModels, SystemResult& system, GenerationInformation& generationInfo, ModuleDecisionDiagram const& globalModule, storm::dd::Add<Type, ValueType> const& reachableStatesAdd, storm::dd::Add<Type, ValueType> const& transitionMatrix); + + static storm::models::symbolic::StandardRewardModel<Type, ValueType> createRewardModelDecisionDiagrams(GenerationInformation& generationInfo, storm::prism::RewardModel const& rewardModel, ModuleDecisionDiagram const& globalModule, storm::dd::Add<Type, ValueType> const& reachableStatesAdd, storm::dd::Add<Type, ValueType> const& transitionMatrix, boost::optional<storm::dd::Add<Type, ValueType>>& stateActionDd); static SystemResult createSystemDecisionDiagram(GenerationInformation& generationInfo); diff --git a/src/storm/builder/jit/ExplicitJitJaniModelBuilder.cpp b/src/storm/builder/jit/ExplicitJitJaniModelBuilder.cpp index 7a55f0c8a..3c6789324 100644 --- a/src/storm/builder/jit/ExplicitJitJaniModelBuilder.cpp +++ b/src/storm/builder/jit/ExplicitJitJaniModelBuilder.cpp @@ -32,6 +32,8 @@ namespace storm { namespace builder { namespace jit { + static const std::string JIT_VARIABLE_EXTENSION = "_jit_"; + #ifdef LINUX static const std::string DYLIB_EXTENSION = ".so"; #endif @@ -924,19 +926,19 @@ namespace storm { if (hasLocationRewards) { cpptempl::data_map locationReward; - locationReward["variable"] = variable.getName(); + locationReward["variable"] = variable.getName() + JIT_VARIABLE_EXTENSION; locationRewards.push_back(locationReward); } if (hasEdgeRewards) { cpptempl::data_map edgeReward; - edgeReward["variable"] = variable.getName(); + edgeReward["variable"] = variable.getName() + JIT_VARIABLE_EXTENSION; edgeReward["index"] = asString(rewardModelIndex); edgeRewards.push_back(edgeReward); } if (hasDestinationRewards) { cpptempl::data_map destinationReward; destinationReward["index"] = asString(rewardModelIndex); - destinationReward["variable"] = variable.getName(); + destinationReward["variable"] = variable.getName() + JIT_VARIABLE_EXTENSION; destinationRewards.push_back(destinationReward); } ++rewardModelIndex; @@ -1544,7 +1546,7 @@ namespace storm { STORM_LOG_THROW(variable.isBooleanVariable(), storm::exceptions::WrongFormatException, "Terminal label refers to non-boolean variable '" << variable.getName() << "."); STORM_LOG_THROW(variable.isTransient(), storm::exceptions::WrongFormatException, "Terminal label refers to non-transient variable '" << variable.getName() << "."); auto labelExpression = model.getLabelExpression(variable.asBooleanVariable(), parallelAutomata); - if (terminalEntry.second) { + if (!terminalEntry.second) { labelExpression = !labelExpression; } terminalExpressions.push_back(expressionTranslator.translate(shiftVariablesWrtLowerBound(labelExpression), storm::expressions::ToCppTranslationOptions(variablePrefixes, variableToName))); @@ -1578,7 +1580,7 @@ namespace storm { template <typename ValueType, typename RewardModelType> std::string const& ExplicitJitJaniModelBuilder<ValueType, RewardModelType>::registerVariable(storm::expressions::Variable const& variable, bool transient) { // Since the variable name might be illegal as a C++ identifier, we need to prepare it a bit. - variableToName[variable] = variable.getName() + "_jit_"; + variableToName[variable] = variable.getName() + JIT_VARIABLE_EXTENSION; if (transient) { transientVariables.insert(variable); variablePrefixes[variable] = "transientIn."; @@ -2348,7 +2350,7 @@ namespace storm { } void addStateBehaviour(IndexType const& stateId, StateBehaviour<IndexType, ValueType>& behaviour) { - if (behaviour.empty()) { + if (behaviour.empty() && behaviour.isExpanded()) { deadlockStates.push_back(stateId); } diff --git a/src/storm/builder/jit/StateBehaviour.cpp b/src/storm/builder/jit/StateBehaviour.cpp index a14261e1f..40cf06895 100644 --- a/src/storm/builder/jit/StateBehaviour.cpp +++ b/src/storm/builder/jit/StateBehaviour.cpp @@ -73,13 +73,14 @@ namespace storm { if (modelType == storm::jani::ModelType::CTMC) { for (auto const& choice : choices) { ValueType massOfChoice = storm::utility::zero<ValueType>(); - for (auto const& entry : choices.front().getDistribution()) { + for (auto const& entry : choice.getDistribution()) { massOfChoice += entry.getValue(); } - + totalExitRate += massOfChoice; + auto outIt = newRewards.begin(); for (auto const& reward : choice.getRewards()) { - *outIt += reward * massOfChoice / totalExitRate; + *outIt += reward * massOfChoice; ++outIt; } } @@ -87,12 +88,16 @@ namespace storm { for (auto const& choice : choices) { auto outIt = newRewards.begin(); for (auto const& reward : choice.getRewards()) { - *outIt += reward / totalExitRate; + *outIt += reward; ++outIt; } } } + for (auto& entry : newRewards) { + entry /= totalExitRate; + } + choices.front().setRewards(std::move(newRewards)); } diff --git a/src/storm/cli/cli.cpp b/src/storm/cli/cli.cpp index cb2b50e9a..9e566028c 100644 --- a/src/storm/cli/cli.cpp +++ b/src/storm/cli/cli.cpp @@ -130,52 +130,30 @@ namespace storm { } void showTimeAndMemoryStatistics(uint64_t wallclockMilliseconds) { -#ifndef WINDOWS struct rusage ru; getrusage(RUSAGE_SELF, &ru); - std::cout << "Performance statistics:" << std::endl; - std::cout << " * peak memory usage: " << ru.ru_maxrss/1024 << " mb" << std::endl; - std::cout << " * CPU time: " << ru.ru_utime.tv_sec << "." << std::setw(3) << std::setfill('0') << ru.ru_utime.tv_usec/1000 << " seconds" << std::endl; + std::cout << std::endl << "Performance statistics:" << std::endl; +#ifdef MACOS + // For Mac OS, this is returned in bytes. + uint64_t maximumResidentSizeInMegabytes = ru.ru_maxrss / 1024 / 1024; +#endif +#ifdef LINUX + // For Linux, this is returned in kilobytes. + uint64_t maximumResidentSizeInMegabytes = ru.ru_maxrss / 1024; +#endif + std::cout << " * peak memory usage: " << maximumResidentSizeInMegabytes << "MB" << std::endl; + std::cout << " * CPU time: " << ru.ru_utime.tv_sec << "." << std::setw(3) << std::setfill('0') << ru.ru_utime.tv_usec/1000 << "s" << std::endl; if (wallclockMilliseconds != 0) { - std::cout << " * wallclock time: " << (wallclockMilliseconds/1000) << "." << std::setw(3) << std::setfill('0') << (wallclockMilliseconds % 1000) << " seconds" << std::endl; + std::cout << " * wallclock time: " << (wallclockMilliseconds/1000) << "." << std::setw(3) << std::setfill('0') << (wallclockMilliseconds % 1000) << "s" << std::endl; } - std::cout << "STATISTICS_OVERALL_HEADERS;" << "memory;CPU time;wallclock time;" << std::endl; + + std::cout << "STATISTICS_OVERALL_HEADERS;" << "memory;CPU time;wallclock time;" << std::endl; std::cout << "STATISTICS_OVERALL_DATA;" << ru.ru_maxrss/1024 << ";" << ru.ru_utime.tv_sec << "." << std::setw(3) << std::setfill('0') << ru.ru_utime.tv_usec/1000 << ";" << (wallclockMilliseconds/1000) << "." << std::setw(3) << std::setfill('0') << (wallclockMilliseconds % 1000) << ";" << std::endl; -#else - HANDLE hProcess = GetCurrentProcess (); - FILETIME ftCreation, ftExit, ftUser, ftKernel; - PROCESS_MEMORY_COUNTERS pmc; - if (GetProcessMemoryInfo( hProcess, &pmc, sizeof(pmc))) { - std::cout << "Memory Usage: " << std::endl; - std::cout << "\tPageFaultCount: " << pmc.PageFaultCount << std::endl; - std::cout << "\tPeakWorkingSetSize: " << pmc.PeakWorkingSetSize << std::endl; - std::cout << "\tWorkingSetSize: " << pmc.WorkingSetSize << std::endl; - std::cout << "\tQuotaPeakPagedPoolUsage: " << pmc.QuotaPeakPagedPoolUsage << std::endl; - std::cout << "\tQuotaPagedPoolUsage: " << pmc.QuotaPagedPoolUsage << std::endl; - std::cout << "\tQuotaPeakNonPagedPoolUsage: " << pmc.QuotaPeakNonPagedPoolUsage << std::endl; - std::cout << "\tQuotaNonPagedPoolUsage: " << pmc.QuotaNonPagedPoolUsage << std::endl; - std::cout << "\tPagefileUsage:" << pmc.PagefileUsage << std::endl; - std::cout << "\tPeakPagefileUsage: " << pmc.PeakPagefileUsage << std::endl; - } - - GetProcessTimes (hProcess, &ftCreation, &ftExit, &ftKernel, &ftUser); - ULARGE_INTEGER uLargeInteger; - uLargeInteger.LowPart = ftKernel.dwLowDateTime; - uLargeInteger.HighPart = ftKernel.dwHighDateTime; - double kernelTime = static_cast<double>(uLargeInteger.QuadPart) / 10000.0; // 100 ns Resolution to milliseconds - uLargeInteger.LowPart = ftUser.dwLowDateTime; - uLargeInteger.HighPart = ftUser.dwHighDateTime; - double userTime = static_cast<double>(uLargeInteger.QuadPart) / 10000.0; - - std::cout << "CPU Time: " << std::endl; - std::cout << "\tKernel Time: " << std::setprecision(5) << kernelTime << "ms" << std::endl; - std::cout << "\tUser Time: " << std::setprecision(5) << userTime << "ms" << std::endl; -#endif } bool parseOptions(const int argc, const char* argv[]) { @@ -232,16 +210,29 @@ namespace storm { propertyFilter = storm::parsePropertyFilter(storm::settings::getModule<storm::settings::modules::GeneralSettings>().getPropertyFilter()); } + auto coreSettings = storm::settings::getModule<storm::settings::modules::CoreSettings>(); + auto generalSettings = storm::settings::getModule<storm::settings::modules::GeneralSettings>(); auto ioSettings = storm::settings::getModule<storm::settings::modules::IOSettings>(); if (ioSettings.isPrismOrJaniInputSet()) { storm::storage::SymbolicModelDescription model; std::vector<storm::jani::Property> properties; STORM_LOG_TRACE("Parsing symbolic input."); + boost::optional<std::map<std::string, std::string>> labelRenaming; if (ioSettings.isPrismInputSet()) { model = storm::parseProgram(ioSettings.getPrismInputFilename()); - if (ioSettings.isPrismToJaniSet()) { - model = model.toJani(true); + + bool transformToJani = ioSettings.isPrismToJaniSet(); + bool transformToJaniForJit = coreSettings.getEngine() == storm::settings::modules::CoreSettings::Engine::Sparse && ioSettings.isJitSet(); + STORM_LOG_WARN_COND(transformToJani || !transformToJaniForJit, "The JIT-based model builder is only available for JANI models, automatically converting the PRISM input model."); + transformToJani |= transformToJaniForJit; + + if (transformToJani) { + auto modelAndRenaming = model.toJaniWithLabelRenaming(true); + if (!modelAndRenaming.second.empty()) { + labelRenaming = modelAndRenaming.second; + } + model = modelAndRenaming.first; } } else if (ioSettings.isJaniInputSet()) { auto input = storm::parseJaniModel(ioSettings.getJaniInputFilename()); @@ -261,11 +252,19 @@ namespace storm { // Then proceed to parsing the properties (if given), since the model we are building may depend on the property. STORM_LOG_TRACE("Parsing properties."); - if (storm::settings::getModule<storm::settings::modules::GeneralSettings>().isPropertySet()) { + if (generalSettings.isPropertySet()) { if (model.isJaniModel()) { - properties = storm::parsePropertiesForJaniModel(storm::settings::getModule<storm::settings::modules::GeneralSettings>().getProperty(), model.asJaniModel(), propertyFilter); + properties = storm::parsePropertiesForJaniModel(generalSettings.getProperty(), model.asJaniModel(), propertyFilter); + + if (labelRenaming) { + std::vector<storm::jani::Property> amendedProperties; + for (auto const& property : properties) { + amendedProperties.emplace_back(property.substituteLabels(labelRenaming.get())); + } + properties = std::move(amendedProperties); + } } else { - properties = storm::parsePropertiesForPrismProgram(storm::settings::getModule<storm::settings::modules::GeneralSettings>().getProperty(), model.asPrismProgram(), propertyFilter); + properties = storm::parsePropertiesForPrismProgram(generalSettings.getProperty(), model.asPrismProgram(), propertyFilter); } constantDefinitions = model.parseConstantDefinitions(constantDefinitionString); @@ -284,13 +283,13 @@ namespace storm { } STORM_LOG_TRACE("Building and checking symbolic model."); - if (storm::settings::getModule<storm::settings::modules::GeneralSettings>().isParametricSet()) { + if (generalSettings.isParametricSet()) { #ifdef STORM_HAVE_CARL buildAndCheckSymbolicModel<storm::RationalFunction>(model, properties, true); #else STORM_LOG_THROW(false, storm::exceptions::NotSupportedException, "No parameters are supported in this build."); #endif - } else if (storm::settings::getModule<storm::settings::modules::GeneralSettings>().isExactSet()) { + } else if (generalSettings.isExactSet()) { #ifdef STORM_HAVE_CARL buildAndCheckSymbolicModel<storm::RationalNumber>(model, properties, true); #else @@ -299,14 +298,14 @@ namespace storm { } else { buildAndCheckSymbolicModel<double>(model, properties, true); } - } else if (storm::settings::getModule<storm::settings::modules::IOSettings>().isExplicitSet()) { - STORM_LOG_THROW(storm::settings::getModule<storm::settings::modules::CoreSettings>().getEngine() == storm::settings::modules::CoreSettings::Engine::Sparse, storm::exceptions::InvalidSettingsException, "Only the sparse engine supports explicit model input."); + } else if (ioSettings.isExplicitSet()) { + STORM_LOG_THROW(coreSettings.getEngine() == storm::settings::modules::CoreSettings::Engine::Sparse, storm::exceptions::InvalidSettingsException, "Only the sparse engine supports explicit model input."); // If the model is given in an explicit format, we parse the properties without allowing expressions // in formulas. std::vector<storm::jani::Property> properties; - if (storm::settings::getModule<storm::settings::modules::GeneralSettings>().isPropertySet()) { - properties = storm::parsePropertiesForExplicit(storm::settings::getModule<storm::settings::modules::GeneralSettings>().getProperty(), propertyFilter); + if (generalSettings.isPropertySet()) { + properties = storm::parsePropertiesForExplicit(generalSettings.getProperty(), propertyFilter); } buildAndCheckExplicitModel<double>(properties, true); diff --git a/src/storm/cli/entrypoints.h b/src/storm/cli/entrypoints.h index 9462f2643..1653d76ea 100644 --- a/src/storm/cli/entrypoints.h +++ b/src/storm/cli/entrypoints.h @@ -7,6 +7,7 @@ #include "storm/storage/SymbolicModelDescription.h" #include "storm/utility/ExplicitExporter.h" +#include "storm/utility/Stopwatch.h" #include "storm/exceptions/NotImplementedException.h" #include "storm/exceptions/InvalidSettingsException.h" @@ -18,24 +19,23 @@ namespace storm { template<typename ValueType> void applyFilterFunctionAndOutput(std::unique_ptr<storm::modelchecker::CheckResult> const& result, storm::modelchecker::FilterType ft) { - - if(result->isQuantitative()) { - switch(ft) { + if (result->isQuantitative()) { + switch (ft) { case storm::modelchecker::FilterType::VALUES: - std::cout << *result << std::endl; - return; + STORM_PRINT_AND_LOG(*result); + break; case storm::modelchecker::FilterType::SUM: - std::cout << result->asQuantitativeCheckResult<ValueType>().sum(); - return; + STORM_PRINT_AND_LOG(result->asQuantitativeCheckResult<ValueType>().sum()); + break; case storm::modelchecker::FilterType::AVG: - std::cout << result->asQuantitativeCheckResult<ValueType>().average(); - return; + STORM_PRINT_AND_LOG(result->asQuantitativeCheckResult<ValueType>().average()); + break; case storm::modelchecker::FilterType::MIN: - std::cout << result->asQuantitativeCheckResult<ValueType>().getMin(); - return; + STORM_PRINT_AND_LOG(result->asQuantitativeCheckResult<ValueType>().getMin()); + break; case storm::modelchecker::FilterType::MAX: - std::cout << result->asQuantitativeCheckResult<ValueType>().getMax(); - return; + STORM_PRINT_AND_LOG(result->asQuantitativeCheckResult<ValueType>().getMax()); + break; case storm::modelchecker::FilterType::ARGMIN: case storm::modelchecker::FilterType::ARGMAX: STORM_LOG_THROW(false, storm::exceptions::NotImplementedException, "Outputting states is not supported"); @@ -45,19 +45,19 @@ namespace storm { STORM_LOG_THROW(false, storm::exceptions::InvalidArgumentException, "FilterType only defined for qualitative results"); } } else { - switch(ft) { + switch (ft) { case storm::modelchecker::FilterType::VALUES: - std::cout << *result << std::endl; - return; + STORM_PRINT_AND_LOG(*result << std::endl); + break; case storm::modelchecker::FilterType::EXISTS: - std::cout << result->asQualitativeCheckResult().existsTrue(); - return; + STORM_PRINT_AND_LOG(result->asQualitativeCheckResult().existsTrue()); + break; case storm::modelchecker::FilterType::FORALL: - std::cout << result->asQualitativeCheckResult().forallTrue(); - return; + STORM_PRINT_AND_LOG(result->asQualitativeCheckResult().forallTrue()); + break; case storm::modelchecker::FilterType::COUNT: - std::cout << result->asQualitativeCheckResult().count(); - return; + STORM_PRINT_AND_LOG(result->asQualitativeCheckResult().count()); + break; case storm::modelchecker::FilterType::ARGMIN: case storm::modelchecker::FilterType::ARGMAX: @@ -68,24 +68,25 @@ namespace storm { case storm::modelchecker::FilterType::MAX: STORM_LOG_THROW(false, storm::exceptions::InvalidArgumentException, "FilterType only defined for quantitative results"); } - } + STORM_PRINT_AND_LOG(std::endl); } template<typename ValueType> void verifySparseModel(std::shared_ptr<storm::models::sparse::Model<ValueType>> model, std::vector<storm::jani::Property> const& properties, bool onlyInitialStatesRelevant = false) { for (auto const& property : properties) { - std::cout << std::endl << "Model checking property: " << property << " ..."; + STORM_PRINT_AND_LOG(std::endl << "Model checking property " << *property.getRawFormula() << " ..." << std::endl); std::cout.flush(); + storm::utility::Stopwatch modelCheckingWatch(true); std::unique_ptr<storm::modelchecker::CheckResult> result(storm::verifySparseModel(model, property.getFilter().getFormula(), onlyInitialStatesRelevant)); + modelCheckingWatch.stop(); if (result) { - std::cout << " done." << std::endl; - std::cout << "Result (initial states): "; + STORM_PRINT_AND_LOG("Result (initial states): "); result->filter(storm::modelchecker::ExplicitQualitativeCheckResult(model->getInitialStates())); applyFilterFunctionAndOutput<ValueType>(result, property.getFilter().getFilterType()); - std::cout << std::endl; + STORM_PRINT_AND_LOG("Time for model checking: " << modelCheckingWatch << "." << std::endl); } else { - std::cout << " skipped, because the modelling formalism is currently unsupported." << std::endl; + STORM_PRINT_AND_LOG(" skipped, because the modelling formalism is currently unsupported." << std::endl); } } } @@ -96,17 +97,18 @@ namespace storm { for (auto const& property : properties) { STORM_LOG_THROW(model->getType() == storm::models::ModelType::Dtmc || model->getType() == storm::models::ModelType::Ctmc, storm::exceptions::InvalidSettingsException, "Currently parametric verification is only available for DTMCs and CTMCs."); - std::cout << std::endl << "Model checking property: " << property << " ..."; + STORM_PRINT_AND_LOG(std::endl << "Model checking property " << *property.getRawFormula() << " ..." << std::endl); std::cout.flush(); + storm::utility::Stopwatch modelCheckingWatch(true); std::unique_ptr<storm::modelchecker::CheckResult> result(storm::verifySparseModel(model, property.getFilter().getFormula(), onlyInitialStatesRelevant)); + modelCheckingWatch.stop(); if (result) { - std::cout << " done." << std::endl; - std::cout << "Result (initial states): "; + STORM_PRINT_AND_LOG("Result (initial states): "); result->filter(storm::modelchecker::ExplicitQualitativeCheckResult(model->getInitialStates())); applyFilterFunctionAndOutput<storm::RationalFunction>(result, property.getFilter().getFilterType()); - std::cout << std::endl; + STORM_PRINT_AND_LOG("Time for model checking: " << modelCheckingWatch << "." << std::endl); } else { - std::cout << " skipped, because the modelling formalism is currently unsupported." << std::endl; + STORM_PRINT_AND_LOG(" skipped, because the modelling formalism is currently unsupported." << std::endl); } if (storm::settings::getModule<storm::settings::modules::ParametricSettings>().exportResultToFile()) { @@ -120,15 +122,17 @@ namespace storm { void verifySymbolicModelWithAbstractionRefinementEngine(storm::storage::SymbolicModelDescription const& model, std::vector<storm::jani::Property> const& properties, bool onlyInitialStatesRelevant = false) { typedef double ValueType; for (auto const& property : properties) { - std::cout << std::endl << "Model checking property: " << property << " ..."; + STORM_PRINT_AND_LOG(std::endl << "Model checking property " << *property.getRawFormula() << " ..." << std::endl); std::cout.flush(); + storm::utility::Stopwatch modelCheckingWatch(true); std::unique_ptr<storm::modelchecker::CheckResult> result(storm::verifySymbolicModelWithAbstractionRefinementEngine<DdType, ValueType>(model, property.getFilter().getFormula(), onlyInitialStatesRelevant)); + modelCheckingWatch.stop(); if (result) { - std::cout << " done." << std::endl; - std::cout << "Result (initial states): "; - std::cout << *result << std::endl; + STORM_PRINT_AND_LOG("Result (initial states): "); + STORM_PRINT_AND_LOG(*result); + STORM_PRINT_AND_LOG("Time for model checking: " << modelCheckingWatch << "." << std::endl); } else { - std::cout << " skipped, because the modelling formalism is currently unsupported." << std::endl; + STORM_PRINT_AND_LOG(" skipped, because the modelling formalism is currently unsupported." << std::endl); } } } @@ -140,18 +144,22 @@ namespace storm { STORM_LOG_THROW(program.getModelType() == storm::prism::Program::ModelType::DTMC || program.getModelType() == storm::prism::Program::ModelType::MDP, storm::exceptions::InvalidSettingsException, "Currently exploration-based verification is only available for DTMCs and MDPs."); for (auto const& property : formulas) { - std::cout << std::endl << "Model checking property: " << property << " ..."; + STORM_PRINT_AND_LOG(std::endl << "Model checking property " << *property.getRawFormula() << " ..." << std::endl); std::cout.flush(); bool formulaSupported = false; std::unique_ptr<storm::modelchecker::CheckResult> result; + storm::utility::Stopwatch modelCheckingWatch(false); + if (program.getModelType() == storm::prism::Program::ModelType::DTMC) { storm::modelchecker::SparseExplorationModelChecker<storm::models::sparse::Dtmc<ValueType>> checker(program); storm::modelchecker::CheckTask<storm::logic::Formula> task(*property.getFilter().getFormula(), onlyInitialStatesRelevant); formulaSupported = checker.canHandle(task); if (formulaSupported) { + modelCheckingWatch.start(); result = checker.check(task); + modelCheckingWatch.stop(); } } else if (program.getModelType() == storm::prism::Program::ModelType::MDP) { storm::modelchecker::SparseExplorationModelChecker<storm::models::sparse::Mdp<ValueType>> checker(program); @@ -159,23 +167,24 @@ namespace storm { formulaSupported = checker.canHandle(task); if (formulaSupported) { + modelCheckingWatch.start(); result = checker.check(task); + modelCheckingWatch.stop(); } } else { // Should be catched before. assert(false); } if (!formulaSupported) { - std::cout << " skipped, because the formula cannot be handled by the selected engine/method." << std::endl; + STORM_PRINT_AND_LOG(" skipped, because the formula cannot be handled by the selected engine/method." << std::endl); } if (result) { - std::cout << " done." << std::endl; - std::cout << "Result (initial states): "; + STORM_PRINT_AND_LOG("Result (initial states): "); applyFilterFunctionAndOutput<ValueType>(result, property.getFilter().getFilterType()); - std::cout << std::endl; + STORM_PRINT_AND_LOG("Time for model checking: " << modelCheckingWatch << "." << std::endl); } else { - std::cout << " skipped, because the modelling formalism is currently unsupported." << std::endl; + STORM_PRINT_AND_LOG(" skipped, because the modelling formalism is currently unsupported." << std::endl); } } } @@ -190,18 +199,20 @@ namespace storm { template<storm::dd::DdType DdType> void verifySymbolicModelWithHybridEngine(std::shared_ptr<storm::models::symbolic::Model<DdType>> model, std::vector<storm::jani::Property> const& formulas, bool onlyInitialStatesRelevant = false) { for (auto const& property : formulas) { - std::cout << std::endl << "Model checking property: " << property << " ..."; + STORM_PRINT_AND_LOG(std::endl << "Model checking property " << *property.getRawFormula() << " ..." << std::endl); std::cout.flush(); + + storm::utility::Stopwatch modelCheckingWatch(true); std::unique_ptr<storm::modelchecker::CheckResult> result(storm::verifySymbolicModelWithHybridEngine(model, property.getFilter().getFormula(), onlyInitialStatesRelevant)); + modelCheckingWatch.stop(); if (result) { - std::cout << " done." << std::endl; - std::cout << "Result (initial states): "; + STORM_PRINT_AND_LOG("Result (initial states): "); result->filter(storm::modelchecker::SymbolicQualitativeCheckResult<DdType>(model->getReachableStates(), model->getInitialStates())); applyFilterFunctionAndOutput<double>(result, property.getFilter().getFilterType()); - std::cout << std::endl; + STORM_PRINT_AND_LOG("Time for model checking: " << modelCheckingWatch << "." << std::endl); } else { - std::cout << " skipped, because the modelling formalism is currently unsupported." << std::endl; + STORM_PRINT_AND_LOG(" skipped, because the modelling formalism is currently unsupported." << std::endl); } } } @@ -209,17 +220,19 @@ namespace storm { template<storm::dd::DdType DdType> void verifySymbolicModelWithDdEngine(std::shared_ptr<storm::models::symbolic::Model<DdType>> model, std::vector<storm::jani::Property> const& formulas, bool onlyInitialStatesRelevant = false) { for (auto const& property : formulas) { - std::cout << std::endl << "Model checking property: " << property << " ..."; + STORM_PRINT_AND_LOG(std::endl << "Model checking property " << *property.getRawFormula() << " ..." << std::endl); std::cout.flush(); + + storm::utility::Stopwatch modelCheckingWatch(true); std::unique_ptr<storm::modelchecker::CheckResult> result(storm::verifySymbolicModelWithDdEngine(model, property.getFilter().getFormula(), onlyInitialStatesRelevant)); + modelCheckingWatch.stop(); if (result) { - std::cout << " done." << std::endl; - std::cout << "Result (initial states): "; + STORM_PRINT_AND_LOG("Result (initial states): "); result->filter(storm::modelchecker::SymbolicQualitativeCheckResult<DdType>(model->getReachableStates(), model->getInitialStates())); applyFilterFunctionAndOutput<double>(result, property.getFilter().getFilterType()); - std::cout << std::endl; + STORM_PRINT_AND_LOG("Time for model checking: " << modelCheckingWatch << "." << std::endl); } else { - std::cout << " skipped, because the modelling formalism is currently unsupported." << std::endl; + STORM_PRINT_AND_LOG(" skipped, because the modelling formalism is currently unsupported." << std::endl); } } } @@ -267,7 +280,10 @@ namespace storm { template<storm::dd::DdType LibraryType> void buildAndCheckSymbolicModelWithSymbolicEngine(bool hybrid, storm::storage::SymbolicModelDescription const& model, std::vector<storm::jani::Property> const& properties, bool onlyInitialStatesRelevant = false) { // Start by building the model. + storm::utility::Stopwatch modelBuildingWatch(true); auto markovModel = buildSymbolicModel<double, LibraryType>(model, extractFormulasFromProperties(properties)); + modelBuildingWatch.stop(); + STORM_PRINT_AND_LOG("Time for model construction: " << modelBuildingWatch << "." << std::endl << std::endl); // Print some information about the model. markovModel->printModelInformationToStream(std::cout); @@ -284,7 +300,10 @@ namespace storm { void buildAndCheckSymbolicModelWithSparseEngine(storm::storage::SymbolicModelDescription const& model, std::vector<storm::jani::Property> const& properties, bool onlyInitialStatesRelevant = false) { auto formulas = extractFormulasFromProperties(properties); // Start by building the model. + storm::utility::Stopwatch modelBuildingWatch(true); std::shared_ptr<storm::models::ModelBase> markovModel = buildSparseModel<ValueType>(model, formulas); + modelBuildingWatch.stop(); + STORM_PRINT_AND_LOG("Time for model construction: " << modelBuildingWatch << "." << std::endl << std::endl); STORM_LOG_THROW(markovModel, storm::exceptions::UnexpectedException, "The model was not successfully built."); @@ -359,7 +378,11 @@ namespace storm { storm::settings::modules::IOSettings const& settings = storm::settings::getModule<storm::settings::modules::IOSettings>(); STORM_LOG_THROW(settings.isExplicitSet(), storm::exceptions::InvalidStateException, "Unable to build explicit model without model files."); + + storm::utility::Stopwatch modelBuildingWatch(true); std::shared_ptr<storm::models::ModelBase> model = buildExplicitModel<ValueType>(settings.getTransitionFilename(), settings.getLabelingFilename(), settings.isStateRewardsSet() ? boost::optional<std::string>(settings.getStateRewardsFilename()) : boost::none, settings.isTransitionRewardsSet() ? boost::optional<std::string>(settings.getTransitionRewardsFilename()) : boost::none, settings.isChoiceLabelingSet() ? boost::optional<std::string>(settings.getChoiceLabelingFilename()) : boost::none); + modelBuildingWatch.stop(); + STORM_PRINT_AND_LOG("Time for model construction: " << modelBuildingWatch << "." << std::endl); // Preprocess the model if needed. BRANCH_ON_MODELTYPE(model, model, ValueType, storm::dd::DdType::CUDD, preprocessModel, extractFormulasFromProperties(properties)); diff --git a/src/storm/generator/JaniNextStateGenerator.cpp b/src/storm/generator/JaniNextStateGenerator.cpp index c7fe2497c..b5a3d420b 100644 --- a/src/storm/generator/JaniNextStateGenerator.cpp +++ b/src/storm/generator/JaniNextStateGenerator.cpp @@ -467,6 +467,9 @@ namespace storm { // If the new state was already found as a successor state, update the probability // and otherwise insert it. auto probability = stateProbabilityPair.second * this->evaluator->asRational(destination.getProbability()); + if (edge.hasRate()) { + probability *= this->evaluator->asRational(edge.getRate()); + } if (probability != storm::utility::zero<ValueType>()) { auto targetStateIt = newTargetStates->find(newTargetState); if (targetStateIt != newTargetStates->end()) { diff --git a/src/storm/generator/PrismNextStateGenerator.cpp b/src/storm/generator/PrismNextStateGenerator.cpp index 6b4c4c7d4..b3061db61 100644 --- a/src/storm/generator/PrismNextStateGenerator.cpp +++ b/src/storm/generator/PrismNextStateGenerator.cpp @@ -256,13 +256,13 @@ namespace storm { for (auto const& stateActionReward : rewardModel.get().getStateActionRewards()) { for (auto const& choice : allChoices) { if (stateActionReward.getActionIndex() == choice.getActionIndex() && this->evaluator->asBool(stateActionReward.getStatePredicateExpression())) { - stateActionRewardValue += ValueType(this->evaluator->asRational(stateActionReward.getRewardValueExpression())) * choice.getTotalMass() / totalExitRate; + stateActionRewardValue += ValueType(this->evaluator->asRational(stateActionReward.getRewardValueExpression())) * choice.getTotalMass(); } } } } - globalChoice.addReward(stateActionRewardValue); + globalChoice.addReward(stateActionRewardValue / totalExitRate); } // Move the newly fused choice in place. diff --git a/src/storm/logic/Formula.cpp b/src/storm/logic/Formula.cpp index d61129914..9038a2307 100644 --- a/src/storm/logic/Formula.cpp +++ b/src/storm/logic/Formula.cpp @@ -443,6 +443,11 @@ namespace storm { return visitor.substitute(*this); } + std::shared_ptr<Formula> Formula::substitute(std::map<std::string, std::string> const& labelSubstitution) const { + LabelSubstitutionVisitor visitor(labelSubstitution); + return visitor.substitute(*this); + } + storm::expressions::Expression Formula::toExpression(storm::expressions::ExpressionManager const& manager, std::map<std::string, storm::expressions::Expression> const& labelToExpressionMapping) const { ToExpressionVisitor visitor; if (labelToExpressionMapping.empty()) { diff --git a/src/storm/logic/Formula.h b/src/storm/logic/Formula.h index 80f31203f..2ad5e9477 100644 --- a/src/storm/logic/Formula.h +++ b/src/storm/logic/Formula.h @@ -197,6 +197,7 @@ namespace storm { std::shared_ptr<Formula> substitute(std::map<storm::expressions::Variable, storm::expressions::Expression> const& substitution) const; std::shared_ptr<Formula> substitute(std::map<std::string, storm::expressions::Expression> const& labelSubstitution) const; + std::shared_ptr<Formula> substitute(std::map<std::string, std::string> const& labelSubstitution) const; /*! * Takes the formula and converts it to an equivalent expression. The formula may contain atomic labels, but diff --git a/src/storm/logic/FragmentSpecification.cpp b/src/storm/logic/FragmentSpecification.cpp index 0790c48a6..0d4771552 100644 --- a/src/storm/logic/FragmentSpecification.cpp +++ b/src/storm/logic/FragmentSpecification.cpp @@ -325,7 +325,6 @@ namespace storm { return *this; } - bool FragmentSpecification::areTotalRewardFormulasAllowed() const { return totalRewardFormula; } diff --git a/src/storm/logic/LabelSubstitutionVisitor.cpp b/src/storm/logic/LabelSubstitutionVisitor.cpp index 9794b2530..1e17649a3 100644 --- a/src/storm/logic/LabelSubstitutionVisitor.cpp +++ b/src/storm/logic/LabelSubstitutionVisitor.cpp @@ -5,22 +5,35 @@ namespace storm { namespace logic { - LabelSubstitutionVisitor::LabelSubstitutionVisitor(std::map<std::string, storm::expressions::Expression> const& labelToExpressionMapping) : labelToExpressionMapping(labelToExpressionMapping) { + LabelSubstitutionVisitor::LabelSubstitutionVisitor(std::map<std::string, storm::expressions::Expression> const& labelToExpressionMapping) : labelToExpressionMapping(&labelToExpressionMapping), labelToLabelMapping(nullptr) { // Intentionally left empty. } + LabelSubstitutionVisitor::LabelSubstitutionVisitor(std::map<std::string, std::string> const& labelToLabelMapping) : labelToExpressionMapping(nullptr), labelToLabelMapping(&labelToLabelMapping) { + // Intentionally left empty. + } + std::shared_ptr<Formula> LabelSubstitutionVisitor::substitute(Formula const& f) const { boost::any result = f.accept(*this, boost::any()); return boost::any_cast<std::shared_ptr<Formula>>(result); } boost::any LabelSubstitutionVisitor::visit(AtomicLabelFormula const& f, boost::any const&) const { - auto it = labelToExpressionMapping.find(f.getLabel()); - if (it != labelToExpressionMapping.end()) { - return std::static_pointer_cast<Formula>(std::make_shared<AtomicExpressionFormula>(it->second)); + if (labelToExpressionMapping) { + auto it = labelToExpressionMapping->find(f.getLabel()); + if (it != labelToExpressionMapping->end()) { + return std::static_pointer_cast<Formula>(std::make_shared<AtomicExpressionFormula>(it->second)); + } else { + return f.asSharedPointer(); + } } else { - return std::static_pointer_cast<Formula>(std::make_shared<AtomicLabelFormula>(f)); + auto it = labelToLabelMapping->find(f.getLabel()); + if (it != labelToLabelMapping->end()) { + return std::static_pointer_cast<Formula>(std::make_shared<AtomicLabelFormula>(it->second)); + } else { + return f.asSharedPointer(); + } } - } + } } } diff --git a/src/storm/logic/LabelSubstitutionVisitor.h b/src/storm/logic/LabelSubstitutionVisitor.h index 928380be5..cac04fa72 100644 --- a/src/storm/logic/LabelSubstitutionVisitor.h +++ b/src/storm/logic/LabelSubstitutionVisitor.h @@ -13,13 +13,15 @@ namespace storm { class LabelSubstitutionVisitor : public CloneVisitor { public: LabelSubstitutionVisitor(std::map<std::string, storm::expressions::Expression> const& labelToExpressionMapping); + LabelSubstitutionVisitor(std::map<std::string, std::string> const& labelToLabelMapping); std::shared_ptr<Formula> substitute(Formula const& f) const; virtual boost::any visit(AtomicLabelFormula const& f, boost::any const& data) const override; private: - std::map<std::string, storm::expressions::Expression> const& labelToExpressionMapping; + std::map<std::string, storm::expressions::Expression> const* labelToExpressionMapping; + std::map<std::string, std::string> const* labelToLabelMapping; }; } diff --git a/src/storm/modelchecker/csl/SparseCtmcCslModelChecker.cpp b/src/storm/modelchecker/csl/SparseCtmcCslModelChecker.cpp index c528d4e12..4d6e9407f 100644 --- a/src/storm/modelchecker/csl/SparseCtmcCslModelChecker.cpp +++ b/src/storm/modelchecker/csl/SparseCtmcCslModelChecker.cpp @@ -49,7 +49,7 @@ namespace storm { template<typename CValueType, typename std::enable_if<!storm::NumberTraits<CValueType>::SupportsExponential, int>::type> bool SparseCtmcCslModelChecker<SparseCtmcModelType>::canHandleImplementation(CheckTask<storm::logic::Formula, CValueType> const& checkTask) const { storm::logic::Formula const& formula = checkTask.getFormula(); - return formula.isInFragment(storm::logic::prctl().setGloballyFormulasAllowed(false).setLongRunAverageRewardFormulasAllowed(false).setLongRunAverageProbabilitiesAllowed(true).setTimeAllowed(true)); + return formula.isInFragment(storm::logic::prctl().setGloballyFormulasAllowed(false).setLongRunAverageRewardFormulasAllowed(true).setLongRunAverageProbabilitiesAllowed(true).setTimeAllowed(true)); } template <typename SparseCtmcModelType> diff --git a/src/storm/modelchecker/csl/helper/HybridCtmcCslHelper.cpp b/src/storm/modelchecker/csl/helper/HybridCtmcCslHelper.cpp index 0f6fb9a4b..592ecc460 100644 --- a/src/storm/modelchecker/csl/helper/HybridCtmcCslHelper.cpp +++ b/src/storm/modelchecker/csl/helper/HybridCtmcCslHelper.cpp @@ -269,7 +269,7 @@ namespace storm { // Then compute the state reward vector to use in the computation. storm::dd::Add<DdType, ValueType> totalRewardVector = rewardModel.getTotalRewardVector(rateMatrix, model.getColumnVariables(), exitRateVector, false); std::vector<ValueType> explicitTotalRewardVector = totalRewardVector.toVector(odd); - + // Finally, compute the transient probabilities. std::vector<ValueType> result = storm::modelchecker::helper::SparseCtmcCslHelper::computeTransientProbabilities<ValueType, true>(explicitUniformizedMatrix, nullptr, timeBound, uniformizationRate, explicitTotalRewardVector, linearEquationSolverFactory); return std::unique_ptr<CheckResult>(new HybridQuantitativeCheckResult<DdType>(model.getReachableStates(), model.getManager().getBddZero(), model.getManager().template getAddZero<ValueType>(), model.getReachableStates(), std::move(odd), std::move(result))); diff --git a/src/storm/modelchecker/csl/helper/SparseCtmcCslHelper.cpp b/src/storm/modelchecker/csl/helper/SparseCtmcCslHelper.cpp index 15cbe2c64..10995f9b7 100644 --- a/src/storm/modelchecker/csl/helper/SparseCtmcCslHelper.cpp +++ b/src/storm/modelchecker/csl/helper/SparseCtmcCslHelper.cpp @@ -293,7 +293,7 @@ namespace storm { return storm::modelchecker::helper::SparseDtmcPrctlHelper<ValueType>::computeReachabilityRewards(probabilityMatrix, backwardTransitions, totalRewardVector, targetStates, qualitative, linearEquationSolverFactory); } - template <typename ValueType, typename RewardModelType, typename std::enable_if<storm::NumberTraits<ValueType>::SupportsExponential, int>::type> + template <typename ValueType, typename RewardModelType> std::vector<ValueType> SparseCtmcCslHelper::computeReachabilityRewards(storm::storage::SparseMatrix<ValueType> const& rateMatrix, storm::storage::SparseMatrix<ValueType> const& backwardTransitions, std::vector<ValueType> const& exitRateVector, RewardModelType const& rewardModel, storm::storage::BitVector const& targetStates, bool qualitative, storm::solver::LinearEquationSolverFactory<ValueType> const& linearEquationSolverFactory) { STORM_LOG_THROW(!rewardModel.empty(), storm::exceptions::InvalidPropertyException, "Missing reward model for formula. Skipping formula."); @@ -324,11 +324,6 @@ namespace storm { return storm::modelchecker::helper::SparseDtmcPrctlHelper<ValueType>::computeReachabilityRewards(probabilityMatrix, backwardTransitions, totalRewardVector, targetStates, qualitative, linearEquationSolverFactory); } - template <typename ValueType, typename RewardModelType, typename std::enable_if<!storm::NumberTraits<ValueType>::SupportsExponential, int>::type> - std::vector<ValueType> SparseCtmcCslHelper::computeReachabilityRewards(storm::storage::SparseMatrix<ValueType> const&, storm::storage::SparseMatrix<ValueType> const&, std::vector<ValueType> const&, RewardModelType const&, storm::storage::BitVector const&, bool, storm::solver::LinearEquationSolverFactory<ValueType> const&) { - STORM_LOG_THROW(false, storm::exceptions::InvalidOperationException, "Computing reachability rewards is unsupported for this value type."); - } - template <typename ValueType> std::vector<ValueType> SparseCtmcCslHelper::computeLongRunAverageProbabilities(storm::storage::SparseMatrix<ValueType> const& probabilityMatrix, storm::storage::BitVector const& psiStates, std::vector<ValueType> const* exitRateVector, storm::solver::LinearEquationSolverFactory<ValueType> const& linearEquationSolverFactory) { @@ -496,12 +491,6 @@ namespace storm { solver->solveEquations(bsccEquationSystemSolution, bsccEquationSystemRightSide); } -// std::vector<ValueType> tmp(probabilityMatrix.getRowCount(), storm::utility::zero<ValueType>()); -// probabilityMatrix.multiplyVectorWithMatrix(bsccEquationSystemSolution, tmp); -// for (uint64_t i = 0; i < tmp.size(); ++i) { -// std::cout << tmp[i] << " vs. " << bsccEquationSystemSolution[i] << std::endl; -// } - // If exit rates were given, we need to 'fix' the results to also account for the timing behaviour. if (exitRateVector != nullptr) { std::vector<ValueType> bsccTotalValue(bsccDecomposition.size(), zero); @@ -513,11 +502,7 @@ namespace storm { bsccEquationSystemSolution[indexInStatesInBsccs[*stateIter]] = (bsccEquationSystemSolution[indexInStatesInBsccs[*stateIter]] * (one / (*exitRateVector)[*stateIter])) / bsccTotalValue[stateToBsccIndexMap[indexInStatesInBsccs[*stateIter]]]; } } - -// for (auto const& val : bsccEquationSystemSolution) { -// std::cout << "val: " << val << std::endl; -// } - + // Calculate LRA Value for each BSCC from steady state distribution in BSCCs. for (uint_fast64_t bsccIndex = 0; bsccIndex < bsccDecomposition.size(); ++bsccIndex) { storm::storage::StronglyConnectedComponent const& bscc = bsccDecomposition[bsccIndex]; diff --git a/src/storm/modelchecker/csl/helper/SparseCtmcCslHelper.h b/src/storm/modelchecker/csl/helper/SparseCtmcCslHelper.h index be0f8255c..78787b748 100644 --- a/src/storm/modelchecker/csl/helper/SparseCtmcCslHelper.h +++ b/src/storm/modelchecker/csl/helper/SparseCtmcCslHelper.h @@ -38,10 +38,7 @@ namespace storm { template <typename ValueType, typename RewardModelType, typename std::enable_if<!storm::NumberTraits<ValueType>::SupportsExponential, int>::type = 0> static std::vector<ValueType> computeCumulativeRewards(storm::storage::SparseMatrix<ValueType> const& rateMatrix, std::vector<ValueType> const& exitRateVector, RewardModelType const& rewardModel, double timeBound, storm::solver::LinearEquationSolverFactory<ValueType> const& linearEquationSolverFactory); - template <typename ValueType, typename RewardModelType, typename std::enable_if<storm::NumberTraits<ValueType>::SupportsExponential, int>::type = 0> - static std::vector<ValueType> computeReachabilityRewards(storm::storage::SparseMatrix<ValueType> const& rateMatrix, storm::storage::SparseMatrix<ValueType> const& backwardTransitions, std::vector<ValueType> const& exitRateVector, RewardModelType const& rewardModel, storm::storage::BitVector const& targetStates, bool qualitative, storm::solver::LinearEquationSolverFactory<ValueType> const& linearEquationSolverFactory); - - template <typename ValueType, typename RewardModelType, typename std::enable_if<!storm::NumberTraits<ValueType>::SupportsExponential, int>::type = 0> + template <typename ValueType, typename RewardModelType> static std::vector<ValueType> computeReachabilityRewards(storm::storage::SparseMatrix<ValueType> const& rateMatrix, storm::storage::SparseMatrix<ValueType> const& backwardTransitions, std::vector<ValueType> const& exitRateVector, RewardModelType const& rewardModel, storm::storage::BitVector const& targetStates, bool qualitative, storm::solver::LinearEquationSolverFactory<ValueType> const& linearEquationSolverFactory); template <typename ValueType> diff --git a/src/storm/modelchecker/prctl/helper/HybridMdpPrctlHelper.cpp b/src/storm/modelchecker/prctl/helper/HybridMdpPrctlHelper.cpp index ad656a53b..1caae1606 100644 --- a/src/storm/modelchecker/prctl/helper/HybridMdpPrctlHelper.cpp +++ b/src/storm/modelchecker/prctl/helper/HybridMdpPrctlHelper.cpp @@ -243,16 +243,21 @@ namespace storm { // Then compute the state reward vector to use in the computation. storm::dd::Add<DdType, ValueType> subvector = rewardModel.getTotalRewardVector(maybeStatesAdd, submatrix, model.getColumnVariables()); + if (!rewardModel.hasStateActionRewards() && !rewardModel.hasTransitionRewards()) { + // If the reward model neither has state-action nor transition rewards, we need to multiply + // it with the legal nondetermism encodings in each state. + subvector *= transitionMatrixBdd.existsAbstract(model.getColumnVariables()).template toAdd<ValueType>(); + } // Since we are cutting away target and infinity states, we need to account for this by giving // choices the value infinity that have some successor contained in the infinity states. storm::dd::Bdd<DdType> choicesWithInfinitySuccessor = (maybeStates && transitionMatrixBdd && infinityStates.swapVariables(model.getRowColumnMetaVariablePairs())).existsAbstract(model.getColumnVariables()); subvector = choicesWithInfinitySuccessor.ite(model.getManager().template getInfinity<ValueType>(), subvector); - + // Before cutting the non-maybe columns, we need to compute the sizes of the row groups. - storm::dd::Add<DdType, uint_fast64_t> stateActionAdd = (submatrix.notZero().existsAbstract(model.getColumnVariables()) || subvector.notZero()).template toAdd<uint_fast64_t>(); + storm::dd::Add<DdType, uint_fast64_t> stateActionAdd = submatrix.notZero().existsAbstract(model.getColumnVariables()).template toAdd<uint_fast64_t>(); std::vector<uint_fast64_t> rowGroupSizes = stateActionAdd.sumAbstract(model.getNondeterminismVariables()).toVector(odd); - + // Finally cut away all columns targeting non-maybe states. submatrix *= maybeStatesAdd.swapVariables(model.getRowColumnMetaVariablePairs()); @@ -261,7 +266,7 @@ namespace storm { // Translate the symbolic matrix/vector to their explicit representations. std::pair<storm::storage::SparseMatrix<ValueType>, std::vector<ValueType>> explicitRepresentation = submatrix.toMatrixVector(subvector, std::move(rowGroupSizes), model.getNondeterminismVariables(), odd, odd); - + // Now solve the resulting equation system. std::unique_ptr<storm::solver::MinMaxLinearEquationSolver<ValueType>> solver = linearEquationSolverFactory.create(std::move(explicitRepresentation.first)); solver->solveEquations(dir, x, explicitRepresentation.second); diff --git a/src/storm/modelchecker/prctl/helper/SparseDtmcPrctlHelper.cpp b/src/storm/modelchecker/prctl/helper/SparseDtmcPrctlHelper.cpp index 4db5e15a9..5d84bd9fb 100644 --- a/src/storm/modelchecker/prctl/helper/SparseDtmcPrctlHelper.cpp +++ b/src/storm/modelchecker/prctl/helper/SparseDtmcPrctlHelper.cpp @@ -88,7 +88,6 @@ namespace storm { storm::utility::vector::selectVectorValues(x, maybeStates, resultHint.get()); } - // 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 'yes' state. std::vector<ValueType> b = transitionMatrix.getConstrainedRowSumVector(maybeStates, statesWithProbability1); diff --git a/src/storm/modelchecker/prctl/helper/SparseMdpPrctlHelper.cpp b/src/storm/modelchecker/prctl/helper/SparseMdpPrctlHelper.cpp index 61aa2636f..2db593ac9 100644 --- a/src/storm/modelchecker/prctl/helper/SparseMdpPrctlHelper.cpp +++ b/src/storm/modelchecker/prctl/helper/SparseMdpPrctlHelper.cpp @@ -330,7 +330,7 @@ namespace storm { } } } - + // Create vector for results for maybe states. std::vector<ValueType> x(maybeStates.getNumberOfSetBits(), storm::utility::zero<ValueType>()); diff --git a/src/storm/modelchecker/prctl/helper/SymbolicDtmcPrctlHelper.cpp b/src/storm/modelchecker/prctl/helper/SymbolicDtmcPrctlHelper.cpp index eff8fdf1b..ac1815d43 100644 --- a/src/storm/modelchecker/prctl/helper/SymbolicDtmcPrctlHelper.cpp +++ b/src/storm/modelchecker/prctl/helper/SymbolicDtmcPrctlHelper.cpp @@ -58,7 +58,7 @@ namespace storm { // Solve the equation system. std::unique_ptr<storm::solver::SymbolicLinearEquationSolver<DdType, ValueType>> solver = linearEquationSolverFactory.create(submatrix, maybeStates, model.getRowVariables(), model.getColumnVariables(), model.getRowColumnMetaVariablePairs()); - storm::dd::Add<DdType, ValueType> result = solver->solveEquations(model.getManager().getConstant(0.5) * maybeStatesAdd, subvector); + storm::dd::Add<DdType, ValueType> result = solver->solveEquations(model.getManager().getConstant(0.0), subvector); return statesWithProbability01.second.template toAdd<ValueType>() + result; } else { @@ -166,16 +166,16 @@ namespace storm { storm::dd::Add<DdType, ValueType> submatrix = transitionMatrix * maybeStatesAdd; // Then compute the state reward vector to use in the computation. - storm::dd::Add<DdType, ValueType> subvector = rewardModel.getTotalRewardVector(submatrix, model.getColumnVariables()); + storm::dd::Add<DdType, ValueType> subvector = rewardModel.getTotalRewardVector(maybeStatesAdd, submatrix, model.getColumnVariables()); // Finally cut away all columns targeting non-maybe states and convert the matrix into the matrix needed // for solving the equation system (i.e. compute (I-A)). submatrix *= maybeStatesAdd.swapVariables(model.getRowColumnMetaVariablePairs()); submatrix = (model.getRowColumnIdentity() * maybeStatesAdd) - submatrix; - + // Solve the equation system. std::unique_ptr<storm::solver::SymbolicLinearEquationSolver<DdType, ValueType>> solver = linearEquationSolverFactory.create(submatrix, maybeStates, model.getRowVariables(), model.getColumnVariables(), model.getRowColumnMetaVariablePairs()); - storm::dd::Add<DdType, ValueType> result = solver->solveEquations(model.getManager().getConstant(0.5) * maybeStatesAdd, subvector); + storm::dd::Add<DdType, ValueType> result = solver->solveEquations(model.getManager().getConstant(0.0), subvector); return infinityStates.ite(model.getManager().getConstant(storm::utility::infinity<ValueType>()), result); } else { diff --git a/src/storm/modelchecker/results/CheckResult.cpp b/src/storm/modelchecker/results/CheckResult.cpp index 8410c8728..210ca3b59 100644 --- a/src/storm/modelchecker/results/CheckResult.cpp +++ b/src/storm/modelchecker/results/CheckResult.cpp @@ -39,7 +39,7 @@ namespace storm { return false; } - std::ostream& operator<<(std::ostream& out, CheckResult& checkResult) { + std::ostream& operator<<(std::ostream& out, CheckResult const& checkResult) { checkResult.writeToStream(out); return out; } diff --git a/src/storm/modelchecker/results/CheckResult.h b/src/storm/modelchecker/results/CheckResult.h index 8c6b3a880..6cf39669d 100644 --- a/src/storm/modelchecker/results/CheckResult.h +++ b/src/storm/modelchecker/results/CheckResult.h @@ -106,7 +106,7 @@ namespace storm { virtual std::ostream& writeToStream(std::ostream& out) const = 0; }; - std::ostream& operator<<(std::ostream& out, CheckResult& checkResult); + std::ostream& operator<<(std::ostream& out, CheckResult const& checkResult); } } diff --git a/src/storm/modelchecker/results/ExplicitQuantitativeCheckResult.cpp b/src/storm/modelchecker/results/ExplicitQuantitativeCheckResult.cpp index ff46fc8f4..a4dd5f96c 100644 --- a/src/storm/modelchecker/results/ExplicitQuantitativeCheckResult.cpp +++ b/src/storm/modelchecker/results/ExplicitQuantitativeCheckResult.cpp @@ -208,14 +208,20 @@ namespace storm { if (valuesAsMap.size() >= 10 && minMaxSupported) { printAsRange = true; } else { - bool first = true; - for (auto const& element : valuesAsMap) { - if (!first) { - out << ", "; - } else { - first = false; + if (valuesAsMap.size() == 1) { + print(out, valuesAsMap.begin()->second); + } else { + out << "{"; + bool first = true; + for (auto const& element : valuesAsMap) { + if (!first) { + out << ", "; + } else { + first = false; + } + print(out, element.second); } - print(out, element.second); + out << "}"; } } } diff --git a/src/storm/modelchecker/results/HybridQuantitativeCheckResult.cpp b/src/storm/modelchecker/results/HybridQuantitativeCheckResult.cpp index 008dab7d1..ef52d6028 100644 --- a/src/storm/modelchecker/results/HybridQuantitativeCheckResult.cpp +++ b/src/storm/modelchecker/results/HybridQuantitativeCheckResult.cpp @@ -94,12 +94,19 @@ namespace storm { std::ostream& HybridQuantitativeCheckResult<Type, ValueType>::writeToStream(std::ostream& out) const { uint64_t totalNumberOfStates = this->symbolicStates.getNonZeroCount() + this->explicitStates.getNonZeroCount(); - if (totalNumberOfStates < 10) { + if (totalNumberOfStates == 1) { + if (this->symbolicStates.isZero()) { + out << *this->explicitValues.begin(); + } else { + out << this->symbolicValues.getMax(); + } + } else if (totalNumberOfStates < 10) { out << "{"; bool first = true; if (!this->symbolicStates.isZero()) { if (this->symbolicValues.isZero()) { out << "0"; + first = false; } else { for (auto valuationValuePair : this->symbolicValues) { if (!first) { @@ -109,6 +116,9 @@ namespace storm { } out << valuationValuePair.second; } + if (symbolicStates.getNonZeroCount() != this->symbolicValues.getNonZeroCount()) { + out << ", 0"; + } } } if (!this->explicitStates.isZero()) { diff --git a/src/storm/modelchecker/results/SymbolicQualitativeCheckResult.cpp b/src/storm/modelchecker/results/SymbolicQualitativeCheckResult.cpp index b638c031f..eb407eaa3 100644 --- a/src/storm/modelchecker/results/SymbolicQualitativeCheckResult.cpp +++ b/src/storm/modelchecker/results/SymbolicQualitativeCheckResult.cpp @@ -73,7 +73,13 @@ namespace storm { template <storm::dd::DdType Type> std::ostream& SymbolicQualitativeCheckResult<Type>::writeToStream(std::ostream& out) const { - if (states == truthValues) { + if (states.getNonZeroCount() == 1) { + if (truthValues.isZero()) { + out << "false"; + } else { + out << "true"; + } + } else if (states == truthValues) { out << "{true}" << std::endl; } else { if (truthValues.isZero()) { diff --git a/src/storm/modelchecker/results/SymbolicQuantitativeCheckResult.cpp b/src/storm/modelchecker/results/SymbolicQuantitativeCheckResult.cpp index f46c1dc68..9dce5fe56 100644 --- a/src/storm/modelchecker/results/SymbolicQuantitativeCheckResult.cpp +++ b/src/storm/modelchecker/results/SymbolicQuantitativeCheckResult.cpp @@ -59,7 +59,9 @@ namespace storm { template<storm::dd::DdType Type, typename ValueType> std::ostream& SymbolicQuantitativeCheckResult<Type, ValueType>::writeToStream(std::ostream& out) const { - if (states.getNonZeroCount() < 10) { + if (states.getNonZeroCount() == 1) { + out << this->values.getMax(); + } else if (states.getNonZeroCount() < 10) { out << "{"; if (this->values.isZero()) { out << "0"; @@ -73,6 +75,9 @@ namespace storm { } out << valuationValuePair.second; } + if (states.getNonZeroCount() != this->values.getNonZeroCount()) { + out << ", 0"; + } } out << "}"; } else { diff --git a/src/storm/models/ModelBase.h b/src/storm/models/ModelBase.h index c1a696c03..cbef9a9dc 100644 --- a/src/storm/models/ModelBase.h +++ b/src/storm/models/ModelBase.h @@ -60,14 +60,7 @@ namespace storm { * @return The number of (non-zero) transitions of the model. */ virtual uint_fast64_t getNumberOfTransitions() const = 0; - - /*! - * Retrieves (an approximation of) the size of the model in bytes. - * - * @return The size of th model in bytes. - */ - virtual std::size_t getSizeInBytes() const = 0; - + /*! * Prints information about the model to the specified stream. * diff --git a/src/storm/models/sparse/MarkovAutomaton.cpp b/src/storm/models/sparse/MarkovAutomaton.cpp index 40f9003c5..069ed1936 100644 --- a/src/storm/models/sparse/MarkovAutomaton.cpp +++ b/src/storm/models/sparse/MarkovAutomaton.cpp @@ -236,11 +236,6 @@ namespace storm { } } - template <typename ValueType, typename RewardModelType> - std::size_t MarkovAutomaton<ValueType, RewardModelType>::getSizeInBytes() const { - return NondeterministicModel<ValueType, RewardModelType>::getSizeInBytes() + markovianStates.getSizeInBytes() + exitRates.size() * sizeof(ValueType); - } - template <typename ValueType, typename RewardModelType> void MarkovAutomaton<ValueType, RewardModelType>::turnRatesToProbabilities() { this->exitRates.resize(this->getNumberOfStates()); diff --git a/src/storm/models/sparse/MarkovAutomaton.h b/src/storm/models/sparse/MarkovAutomaton.h index cd45b141b..477d0ee5f 100644 --- a/src/storm/models/sparse/MarkovAutomaton.h +++ b/src/storm/models/sparse/MarkovAutomaton.h @@ -194,9 +194,7 @@ namespace storm { std::shared_ptr<storm::models::sparse::Ctmc<ValueType, RewardModelType>> convertToCTMC() const; virtual void writeDotToStream(std::ostream& outStream, bool includeLabeling = true, storm::storage::BitVector const* subsystem = nullptr, std::vector<ValueType> const* firstValue = nullptr, std::vector<ValueType> const* secondValue = nullptr, std::vector<uint_fast64_t> const* stateColoring = nullptr, std::vector<std::string> const* colors = nullptr, std::vector<uint_fast64_t>* scheduler = nullptr, bool finalizeOutput = true) const override; - - std::size_t getSizeInBytes() const override; - + virtual void printModelInformationToStream(std::ostream& out) const override; private: diff --git a/src/storm/models/sparse/Model.cpp b/src/storm/models/sparse/Model.cpp index 890cfdae7..3f7774759 100644 --- a/src/storm/models/sparse/Model.cpp +++ b/src/storm/models/sparse/Model.cpp @@ -188,18 +188,6 @@ namespace storm { return static_cast<bool>(choiceLabeling); } - template<typename ValueType, typename RewardModelType> - std::size_t Model<ValueType, RewardModelType>::getSizeInBytes() const { - std::size_t result = transitionMatrix.getSizeInBytes() + stateLabeling.getSizeInBytes(); - for (auto const& rewardModel : this->rewardModels) { - result += rewardModel.second.getSizeInBytes(); - } - if (hasChoiceLabeling()) { - result += getChoiceLabeling().size() * sizeof(LabelSet); - } - return result; - } - template<typename ValueType, typename RewardModelType> void Model<ValueType, RewardModelType>::printModelInformationToStream(std::ostream& out) const { this->printModelInformationHeaderToStream(out); @@ -219,7 +207,6 @@ namespace storm { this->printRewardModelsInformationToStream(out); this->getStateLabeling().printLabelingInformationToStream(out); out << "choice labels: \t" << (this->hasChoiceLabeling() ? "yes" : "no") << std::noboolalpha << std::endl; - out << "Size in memory: " << (this->getSizeInBytes())/1024 << " kbytes" << std::endl; out << "-------------------------------------------------------------- " << std::endl; } diff --git a/src/storm/models/sparse/Model.h b/src/storm/models/sparse/Model.h index 70358191a..a545ae3ce 100644 --- a/src/storm/models/sparse/Model.h +++ b/src/storm/models/sparse/Model.h @@ -275,14 +275,7 @@ namespace storm { * properties, but it preserves expected rewards. */ virtual void reduceToStateBasedRewards() = 0; - - /*! - * Retrieves (an approximation of) the size of the model in bytes. - * - * @return The size of the internal representation of the model measured in bytes. - */ - virtual std::size_t getSizeInBytes() const override; - + /*! * Prints information about the model to the specified stream. * diff --git a/src/storm/models/sparse/StandardRewardModel.cpp b/src/storm/models/sparse/StandardRewardModel.cpp index 1866be5d2..fa2b63900 100644 --- a/src/storm/models/sparse/StandardRewardModel.cpp +++ b/src/storm/models/sparse/StandardRewardModel.cpp @@ -165,11 +165,6 @@ namespace storm { template<typename ValueType> template<typename MatrixValueType> std::vector<ValueType> StandardRewardModel<ValueType>::getTotalRewardVector(storm::storage::SparseMatrix<MatrixValueType> const& transitionMatrix) const { - if (this->hasStateActionRewards()) { - for (auto const& e : this->getStateActionRewardVector()) { - std::cout << "e " << e << std::endl; - } - } std::vector<ValueType> result = this->hasTransitionRewards() ? transitionMatrix.getPointwiseProductRowSumVector(this->getTransitionRewardMatrix()) : (this->hasStateActionRewards() ? this->getStateActionRewardVector() : std::vector<ValueType>(transitionMatrix.getRowCount())); if (this->hasStateActionRewards() && this->hasTransitionRewards()) { storm::utility::vector::addVectors(result, this->getStateActionRewardVector(), result); @@ -275,22 +270,6 @@ namespace storm { return true; } - - template<typename ValueType> - std::size_t StandardRewardModel<ValueType>::getSizeInBytes() const { - std::size_t result = 0; - if (this->hasStateRewards()) { - result += this->getStateRewardVector().size() * sizeof(ValueType); - } - if (this->hasStateActionRewards()) { - result += this->getStateActionRewardVector().size() * sizeof(ValueType); - } - if (this->hasTransitionRewards()) { - result += this->getTransitionRewardMatrix().getSizeInBytes(); - } - return result; - } - template <typename ValueType> std::ostream& operator<<(std::ostream& out, StandardRewardModel<ValueType> const& rewardModel) { out << std::boolalpha << "reward model [state reward: " diff --git a/src/storm/models/sparse/StandardRewardModel.h b/src/storm/models/sparse/StandardRewardModel.h index 85d6b5382..dbf484c40 100644 --- a/src/storm/models/sparse/StandardRewardModel.h +++ b/src/storm/models/sparse/StandardRewardModel.h @@ -274,13 +274,6 @@ namespace storm { * @param nrChoices The number of choices in the model */ bool isCompatible(uint_fast64_t nrStates, uint_fast64_t nrChoices) const; - - /*! - * Retrieves (an approximation of) the size of the model in bytes. - * - * @return The size of the internal representation of the model measured in bytes. - */ - std::size_t getSizeInBytes() const; template <typename ValueTypePrime> friend std::ostream& operator<<(std::ostream& out, StandardRewardModel<ValueTypePrime> const& rewardModel); diff --git a/src/storm/models/sparse/StateLabeling.cpp b/src/storm/models/sparse/StateLabeling.cpp index b3037d173..55eaa76d5 100644 --- a/src/storm/models/sparse/StateLabeling.cpp +++ b/src/storm/models/sparse/StateLabeling.cpp @@ -109,14 +109,6 @@ namespace storm { this->labelings[nameToLabelingIndexMap.at(label)] = labeling; } - std::size_t StateLabeling::getSizeInBytes() const { - std::size_t result = sizeof(*this); - if (!labelings.empty()) { - result += labelings.size() * labelings.front().getSizeInBytes(); - } - return result; - } - void StateLabeling::printLabelingInformationToStream(std::ostream& out) const { out << "Labels: \t" << this->getNumberOfLabels() << std::endl; for (auto const& labelIndexPair : this->nameToLabelingIndexMap) { diff --git a/src/storm/models/sparse/StateLabeling.h b/src/storm/models/sparse/StateLabeling.h index c3de34599..330a4d8fe 100644 --- a/src/storm/models/sparse/StateLabeling.h +++ b/src/storm/models/sparse/StateLabeling.h @@ -145,14 +145,7 @@ namespace storm { * @param labeling A bit vector that represents the set of states that will get this label. */ void setStates(std::string const& label, storage::BitVector&& labeling); - - /*! - * Returns (an approximation of) the size of the labeling measured in bytes. - * - * @return The size of the labeling measured in bytes. - */ - std::size_t getSizeInBytes() const; - + /*! * Prints information about the labeling to the specified stream. * diff --git a/src/storm/models/symbolic/Ctmc.cpp b/src/storm/models/symbolic/Ctmc.cpp index e3dd2e724..410e247b5 100644 --- a/src/storm/models/symbolic/Ctmc.cpp +++ b/src/storm/models/symbolic/Ctmc.cpp @@ -24,12 +24,33 @@ namespace storm { std::map<std::string, storm::expressions::Expression> labelToExpressionMap, std::unordered_map<std::string, RewardModelType> const& rewardModels) : DeterministicModel<Type, ValueType>(storm::models::ModelType::Ctmc, manager, reachableStates, initialStates, deadlockStates, transitionMatrix, rowVariables, rowExpressionAdapter, columnVariables, columnExpressionAdapter, rowColumnMetaVariablePairs, labelToExpressionMap, rewardModels) { - exitRates = this->getTransitionMatrix().sumAbstract(this->getColumnVariables()); + // Intentionally left empty. } - + + template<storm::dd::DdType Type, typename ValueType> + Ctmc<Type, ValueType>::Ctmc(std::shared_ptr<storm::dd::DdManager<Type>> manager, + storm::dd::Bdd<Type> reachableStates, + storm::dd::Bdd<Type> initialStates, + storm::dd::Bdd<Type> deadlockStates, + storm::dd::Add<Type, ValueType> transitionMatrix, + boost::optional<storm::dd::Add<Type, ValueType>> exitRateVector, + std::set<storm::expressions::Variable> const& rowVariables, + std::shared_ptr<storm::adapters::AddExpressionAdapter<Type, ValueType>> rowExpressionAdapter, + std::set<storm::expressions::Variable> const& columnVariables, + std::shared_ptr<storm::adapters::AddExpressionAdapter<Type, ValueType>> columnExpressionAdapter, + std::vector<std::pair<storm::expressions::Variable, storm::expressions::Variable>> const& rowColumnMetaVariablePairs, + std::map<std::string, storm::expressions::Expression> labelToExpressionMap, + std::unordered_map<std::string, RewardModelType> const& rewardModels) + : DeterministicModel<Type, ValueType>(storm::models::ModelType::Ctmc, manager, reachableStates, initialStates, deadlockStates, transitionMatrix, rowVariables, rowExpressionAdapter, columnVariables, columnExpressionAdapter, rowColumnMetaVariablePairs, labelToExpressionMap, rewardModels), exitRates(exitRateVector) { + // Intentionally left empty. + } + template<storm::dd::DdType Type, typename ValueType> storm::dd::Add<Type, ValueType> const& Ctmc<Type, ValueType>::getExitRateVector() const { - return exitRates; + if (!exitRates) { + exitRates = this->getTransitionMatrix().sumAbstract(this->getColumnVariables()); + } + return exitRates.get(); } // Explicitly instantiate the template class. diff --git a/src/storm/models/symbolic/Ctmc.h b/src/storm/models/symbolic/Ctmc.h index 8701ed148..c0c4054a3 100644 --- a/src/storm/models/symbolic/Ctmc.h +++ b/src/storm/models/symbolic/Ctmc.h @@ -54,7 +54,40 @@ namespace storm { std::vector<std::pair<storm::expressions::Variable, storm::expressions::Variable>> const& rowColumnMetaVariablePairs, std::map<std::string, storm::expressions::Expression> labelToExpressionMap = std::map<std::string, storm::expressions::Expression>(), std::unordered_map<std::string, RewardModelType> const& rewardModels = std::unordered_map<std::string, RewardModelType>()); - + + /*! + * Constructs a model from the given data. + * + * @param manager The manager responsible for the decision diagrams. + * @param reachableStates A DD representing the reachable states. + * @param initialStates A DD representing the initial states of the model. + * @param deadlockStates A DD representing the deadlock states of the model. + * @param transitionMatrix The matrix representing the transitions in the model. + * @param exitRateVector The vector specifying the exit rates for the states. + * @param rowVariables The set of row meta variables used in the DDs. + * @param rowExpressionAdapter An object that can be used to translate expressions in terms of the row + * meta variables. + * @param columVariables The set of column meta variables used in the DDs. + * @param columnExpressionAdapter An object that can be used to translate expressions in terms of the + * column meta variables. + * @param rowColumnMetaVariablePairs All pairs of row/column meta variables. + * @param labelToExpressionMap A mapping from label names to their defining expressions. + * @param rewardModels The reward models associated with the model. + */ + Ctmc(std::shared_ptr<storm::dd::DdManager<Type>> manager, + storm::dd::Bdd<Type> reachableStates, + storm::dd::Bdd<Type> initialStates, + storm::dd::Bdd<Type> deadlockStates, + storm::dd::Add<Type, ValueType> transitionMatrix, + boost::optional<storm::dd::Add<Type, ValueType>> exitRateVector, + std::set<storm::expressions::Variable> const& rowVariables, + std::shared_ptr<storm::adapters::AddExpressionAdapter<Type, ValueType>> rowExpressionAdapter, + std::set<storm::expressions::Variable> const& columnVariables, + std::shared_ptr<storm::adapters::AddExpressionAdapter<Type, ValueType>> columnExpressionAdapter, + std::vector<std::pair<storm::expressions::Variable, storm::expressions::Variable>> const& rowColumnMetaVariablePairs, + std::map<std::string, storm::expressions::Expression> labelToExpressionMap = std::map<std::string, storm::expressions::Expression>(), + std::unordered_map<std::string, RewardModelType> const& rewardModels = std::unordered_map<std::string, RewardModelType>()); + /*! * Retrieves the exit rate vector of the CTMC. * @@ -63,7 +96,7 @@ namespace storm { storm::dd::Add<Type, ValueType> const& getExitRateVector() const; private: - storm::dd::Add<Type, ValueType> exitRates; + mutable boost::optional<storm::dd::Add<Type, ValueType>> exitRates; }; } // namespace symbolic diff --git a/src/storm/models/symbolic/Model.cpp b/src/storm/models/symbolic/Model.cpp index 29f1d6ec7..1ebf69f48 100644 --- a/src/storm/models/symbolic/Model.cpp +++ b/src/storm/models/symbolic/Model.cpp @@ -114,12 +114,6 @@ namespace storm { return this->getTransitionMatrix().notZero(); } - template<storm::dd::DdType Type, typename ValueType> - std::size_t Model<Type, ValueType>::getSizeInBytes() const { - // FIXME: This assumes a fixed value of 16 bytes per node, which isn't necessarily true. - return sizeof(*this) + 16 * (reachableStates.getNodeCount() + initialStates.getNodeCount() + transitionMatrix.getNodeCount()); - } - template<storm::dd::DdType Type, typename ValueType> std::set<storm::expressions::Variable> const& Model<Type, ValueType>::getRowVariables() const { return rowVariables; @@ -222,7 +216,6 @@ namespace storm { for (auto const& label : labelToExpressionMap) { out << " * " << label.first << std::endl; } - out << "Size in memory: \t" << (this->getSizeInBytes())/1024 << " kbytes" << std::endl; out << "-------------------------------------------------------------- " << std::endl; } diff --git a/src/storm/models/symbolic/Model.h b/src/storm/models/symbolic/Model.h index 629f39411..14c4edbc5 100644 --- a/src/storm/models/symbolic/Model.h +++ b/src/storm/models/symbolic/Model.h @@ -254,8 +254,6 @@ namespace storm { */ uint_fast64_t getNumberOfRewardModels() const; - virtual std::size_t getSizeInBytes() const override; - virtual void printModelInformationToStream(std::ostream& out) const override; virtual bool isSymbolicModel() const override; diff --git a/src/storm/parser/DeterministicSparseTransitionParser.cpp b/src/storm/parser/DeterministicSparseTransitionParser.cpp index 984f3cbc2..7b53415cb 100644 --- a/src/storm/parser/DeterministicSparseTransitionParser.cpp +++ b/src/storm/parser/DeterministicSparseTransitionParser.cpp @@ -54,7 +54,7 @@ namespace storm { bool insertDiagonalEntriesIfMissing = !isRewardFile; DeterministicSparseTransitionParser<ValueType>::FirstPassResult firstPass = DeterministicSparseTransitionParser<ValueType>::firstPass(file.getData(), insertDiagonalEntriesIfMissing); - STORM_LOG_INFO("First pass on " << filename << " shows " << firstPass.numberOfNonzeroEntries << " NonZeros."); + STORM_LOG_TRACE("First pass on " << filename << " shows " << firstPass.numberOfNonzeroEntries << " non-zeros."); // If first pass returned zero, the file format was wrong. if (firstPass.numberOfNonzeroEntries == 0) { diff --git a/src/storm/parser/ExpressionCreator.cpp b/src/storm/parser/ExpressionCreator.cpp index 0be1846f4..6266206ef 100644 --- a/src/storm/parser/ExpressionCreator.cpp +++ b/src/storm/parser/ExpressionCreator.cpp @@ -228,7 +228,6 @@ namespace storm { } void ExpressionCreator::setIdentifierMapping(qi::symbols<char, storm::expressions::Expression> const* identifiers_) { - if (identifiers_ != nullptr) { createExpressions = true; identifiers = identifiers_; diff --git a/src/storm/parser/FormulaParser.cpp b/src/storm/parser/FormulaParser.cpp index 18ff5b247..6bb1687dc 100644 --- a/src/storm/parser/FormulaParser.cpp +++ b/src/storm/parser/FormulaParser.cpp @@ -31,7 +31,15 @@ namespace storm { // Intentionally left empty. } - FormulaParser::FormulaParser(storm::prism::Program const& program) : manager(program.getManager().getSharedPointer()), grammar(new FormulaParserGrammar(manager)) { + FormulaParser::FormulaParser(storm::prism::Program const& program) : manager(program.getManager().getSharedPointer()), grammar(new FormulaParserGrammar(program.getManager().getSharedPointer())) { + this->addFormulasAsIdentifiers(program); + } + + FormulaParser::FormulaParser(storm::prism::Program& program) : manager(program.getManager().getSharedPointer()), grammar(new FormulaParserGrammar(program.getManager().getSharedPointer())) { + this->addFormulasAsIdentifiers(program); + } + + void FormulaParser::addFormulasAsIdentifiers(storm::prism::Program const& program) { // Make the formulas of the program available to the parser. for (auto const& formula : program.getFormulas()) { this->addIdentifierExpression(formula.getName(), formula.getExpression()); diff --git a/src/storm/parser/FormulaParser.h b/src/storm/parser/FormulaParser.h index c9aa5c5f3..d9c06fa92 100644 --- a/src/storm/parser/FormulaParser.h +++ b/src/storm/parser/FormulaParser.h @@ -29,6 +29,7 @@ namespace storm { explicit FormulaParser(std::shared_ptr<storm::expressions::ExpressionManager const> const& manager); explicit FormulaParser(std::shared_ptr<storm::expressions::ExpressionManager> const& manager); explicit FormulaParser(storm::prism::Program const& program); + explicit FormulaParser(storm::prism::Program& program); FormulaParser(FormulaParser const& other); FormulaParser& operator=(FormulaParser const& other); @@ -67,6 +68,8 @@ namespace storm { void addIdentifierExpression(std::string const& identifier, storm::expressions::Expression const& expression); private: + void addFormulasAsIdentifiers(storm::prism::Program const& program); + // The manager used to parse expressions. std::shared_ptr<storm::expressions::ExpressionManager const> manager; diff --git a/src/storm/parser/FormulaParserGrammar.cpp b/src/storm/parser/FormulaParserGrammar.cpp index 86b34f19f..dcf1634a6 100644 --- a/src/storm/parser/FormulaParserGrammar.cpp +++ b/src/storm/parser/FormulaParserGrammar.cpp @@ -16,8 +16,7 @@ namespace storm { // Register all variables so we can parse them in the expressions. for (auto variableTypePair : *constManager) { identifiers_.add(variableTypePair.first.getName(), variableTypePair.first); - } - + } // Set the identifier mapping to actually generate expressions. expressionParser.setIdentifierMapping(&identifiers_); @@ -54,7 +53,10 @@ namespace storm { atomicStateFormula = booleanLiteralFormula | labelFormula | expressionFormula | (qi::lit("(") > stateFormula > qi::lit(")")) | operatorFormula; atomicStateFormula.name("atomic state formula"); - notStateFormula = (-unaryBooleanOperator_ >> atomicStateFormula)[qi::_val = phoenix::bind(&FormulaParserGrammar::createUnaryBooleanStateFormula, phoenix::ref(*this), qi::_2, qi::_1)]; + atomicStateFormulaWithoutExpression = booleanLiteralFormula | labelFormula | (qi::lit("(") > stateFormula > qi::lit(")")) | operatorFormula; + atomicStateFormula.name("atomic state formula without expression"); + + notStateFormula = (unaryBooleanOperator_ >> atomicStateFormulaWithoutExpression)[qi::_val = phoenix::bind(&FormulaParserGrammar::createUnaryBooleanStateFormula, phoenix::ref(*this), qi::_2, qi::_1)] | atomicStateFormula[qi::_val = qi::_1]; notStateFormula.name("negation formula"); eventuallyFormula = (qi::lit("F") >> -timeBound >> pathFormulaWithoutUntil(qi::_r1))[qi::_val = phoenix::bind(&FormulaParserGrammar::createEventuallyFormula, phoenix::ref(*this), qi::_1, qi::_r1, qi::_2)]; @@ -123,7 +125,15 @@ namespace storm { constantDefinition = (qi::lit("const") > qi::eps[qi::_a = true] > -(qi::lit("int") | qi::lit("double")[qi::_a = false]) >> identifier)[phoenix::bind(&FormulaParserGrammar::addConstant, phoenix::ref(*this), qi::_1, qi::_a)]; constantDefinition.name("constant definition"); - start = qi::eps > (((-formulaName >> stateFormula)[phoenix::bind(&FormulaParserGrammar::addProperty, phoenix::ref(*this), qi::_val, qi::_1, qi::_2)] | qi::eps(phoenix::bind(&FormulaParserGrammar::areConstantDefinitionsAllowed, phoenix::ref(*this))) >> constantDefinition | qi::eps) % +(qi::char_("\n;"))) >> qi::skip(boost::spirit::ascii::space | qi::lit("//") >> *(qi::char_ - (qi::eol | qi::eoi)))[qi::eps] >> qi::eoi; +#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(",") > qi::lit("\"init\"") > qi::lit(")")))[qi::_val = phoenix::bind(&FormulaParserGrammar::createProperty, phoenix::ref(*this), qi::_1, qi::_2, qi::_3)] | (-formulaName >> stateFormula)[qi::_val = phoenix::bind(&FormulaParserGrammar::createPropertyWithDefaultFilterType, phoenix::ref(*this), qi::_1, qi::_2)]; + filterProperty.name("filter property"); + +#pragma clang diagnostic pop + + start = ((qi::eps > filterProperty[phoenix::push_back(qi::_val, qi::_1)] | qi::eps(phoenix::bind(&FormulaParserGrammar::areConstantDefinitionsAllowed, phoenix::ref(*this))) >> constantDefinition | qi::eps) % +(qi::char_("\n;"))) >> qi::skip(boost::spirit::ascii::space | qi::lit("//") >> *(qi::char_ - (qi::eol | qi::eoi)))[qi::eps] >> qi::eoi; start.name("start"); // Enable the following lines to print debug output for most the rules. @@ -195,15 +205,6 @@ namespace storm { addIdentifierExpression(name, newVariable); } - void FormulaParserGrammar::addProperty(std::vector<storm::jani::Property>& properties, boost::optional<std::string> const& name, std::shared_ptr<storm::logic::Formula const> const& formula) { - if (name) { - properties.emplace_back(name.get(), formula); - } else { - properties.emplace_back(std::to_string(propertyCount), formula); - } - ++propertyCount; - } - bool FormulaParserGrammar::areConstantDefinitionsAllowed() const { return static_cast<bool>(manager); } @@ -327,5 +328,26 @@ namespace storm { std::shared_ptr<storm::logic::Formula const> FormulaParserGrammar::createMultiObjectiveFormula(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::jani::Property FormulaParserGrammar::createProperty(boost::optional<std::string> const& propertyName, storm::modelchecker::FilterType const& filterType, std::shared_ptr<storm::logic::Formula const> const& formula) { + storm::jani::FilterExpression filterExpression(formula, filterType); + + ++propertyCount; + if (propertyName) { + return storm::jani::Property(propertyName.get(), filterExpression); + } else { + return storm::jani::Property(std::to_string(propertyCount -1 ), filterExpression); + } + } + + storm::jani::Property FormulaParserGrammar::createPropertyWithDefaultFilterType(boost::optional<std::string> const& propertyName, std::shared_ptr<storm::logic::Formula const> const& formula) { + ++propertyCount; + if (propertyName) { + return storm::jani::Property(propertyName.get(), formula); + } else { + return storm::jani::Property(std::to_string(propertyCount), formula); + } + } + } } diff --git a/src/storm/parser/FormulaParserGrammar.h b/src/storm/parser/FormulaParserGrammar.h index c25e1394c..79b272246 100644 --- a/src/storm/parser/FormulaParserGrammar.h +++ b/src/storm/parser/FormulaParserGrammar.h @@ -9,6 +9,8 @@ #include "storm/logic/Formulas.h" #include "storm/parser/ExpressionParser.h" +#include "storm/modelchecker/results/FilterType.h" + #include "storm/storage/expressions/ExpressionEvaluator.h" namespace storm { @@ -111,6 +113,25 @@ namespace storm { // A parser used for recognizing the reward measure types. rewardMeasureTypeStruct rewardMeasureType_; + struct filterTypeStruct : qi::symbols<char, storm::modelchecker::FilterType> { + filterTypeStruct() { + add + ("min", storm::modelchecker::FilterType::MIN) + ("max", storm::modelchecker::FilterType::MAX) + ("sum", storm::modelchecker::FilterType::SUM) + ("avg", storm::modelchecker::FilterType::AVG) + ("count", storm::modelchecker::FilterType::COUNT) + ("forall", storm::modelchecker::FilterType::FORALL) + ("exists", storm::modelchecker::FilterType::EXISTS) + ("argmin", storm::modelchecker::FilterType::ARGMIN) + ("argmax", storm::modelchecker::FilterType::ARGMAX) + ("values", storm::modelchecker::FilterType::VALUES); + } + }; + + // A parser used for recognizing the filter type. + filterTypeStruct filterType_; + // The manager used to parse expressions. std::shared_ptr<storm::expressions::ExpressionManager const> constManager; std::shared_ptr<storm::expressions::ExpressionManager> manager; @@ -135,12 +156,14 @@ namespace storm { 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::jani::Property(), Skipper> filterProperty; qi::rule<Iterator, std::shared_ptr<storm::logic::Formula const>(), Skipper> simpleFormula; qi::rule<Iterator, std::shared_ptr<storm::logic::Formula const>(), Skipper> stateFormula; qi::rule<Iterator, std::shared_ptr<storm::logic::Formula const>(storm::logic::FormulaContext), Skipper> pathFormula; qi::rule<Iterator, std::shared_ptr<storm::logic::Formula const>(storm::logic::FormulaContext), Skipper> pathFormulaWithoutUntil; qi::rule<Iterator, std::shared_ptr<storm::logic::Formula const>(), Skipper> simplePathFormula; qi::rule<Iterator, std::shared_ptr<storm::logic::Formula const>(), Skipper> atomicStateFormula; + qi::rule<Iterator, std::shared_ptr<storm::logic::Formula const>(), Skipper> atomicStateFormulaWithoutExpression; qi::rule<Iterator, std::shared_ptr<storm::logic::Formula const>(), Skipper> operatorFormula; qi::rule<Iterator, std::string(), Skipper> label; qi::rule<Iterator, std::string(), Skipper> rewardModelName; @@ -200,6 +223,9 @@ 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> createMultiObjectiveFormula(std::vector<std::shared_ptr<storm::logic::Formula const>> const& subformulas); + storm::jani::Property createProperty(boost::optional<std::string> const& propertyName, storm::modelchecker::FilterType const& filterType, std::shared_ptr<storm::logic::Formula const> const& formula); + storm::jani::Property createPropertyWithDefaultFilterType(boost::optional<std::string> const& propertyName, std::shared_ptr<storm::logic::Formula const> const& formula); + // An error handler function. phoenix::function<SpiritErrorHandler> handler; diff --git a/src/storm/parser/PrismParser.cpp b/src/storm/parser/PrismParser.cpp index b6241731a..436d27c5d 100644 --- a/src/storm/parser/PrismParser.cpp +++ b/src/storm/parser/PrismParser.cpp @@ -99,7 +99,7 @@ namespace storm { definedBooleanConstantDefinition = ((qi::lit("const") >> qi::lit("bool") >> identifier >> qi::lit("=")) > expression_ > qi::lit(";"))[qi::_val = phoenix::bind(&PrismParser::createDefinedBooleanConstant, phoenix::ref(*this), qi::_1, qi::_2)]; definedBooleanConstantDefinition.name("defined boolean constant declaration"); - definedIntegerConstantDefinition = ((qi::lit("const") >> qi::lit("int") >> identifier >> qi::lit("=")) > expression_ >> qi::lit(";"))[qi::_val = phoenix::bind(&PrismParser::createDefinedIntegerConstant, phoenix::ref(*this), qi::_1, qi::_2)]; + definedIntegerConstantDefinition = ((qi::lit("const") >> -qi::lit("int") >> identifier >> qi::lit("=")) > expression_ >> qi::lit(";"))[qi::_val = phoenix::bind(&PrismParser::createDefinedIntegerConstant, phoenix::ref(*this), qi::_1, qi::_2)]; definedIntegerConstantDefinition.name("defined integer constant declaration"); definedDoubleConstantDefinition = ((qi::lit("const") >> qi::lit("double") >> identifier >> qi::lit("=")) > expression_ > qi::lit(";"))[qi::_val = phoenix::bind(&PrismParser::createDefinedDoubleConstant, phoenix::ref(*this), qi::_1, qi::_2)]; diff --git a/src/storm/settings/modules/IOSettings.cpp b/src/storm/settings/modules/IOSettings.cpp index c65b8797c..bf8055c31 100644 --- a/src/storm/settings/modules/IOSettings.cpp +++ b/src/storm/settings/modules/IOSettings.cpp @@ -195,7 +195,6 @@ namespace storm { return storm::parser::parseCommaSeperatedValues(this->getOption(janiPropertyOptionName).getArgumentByName("values").getValueAsString()); } - bool IOSettings::isPrismCompatibilityEnabled() const { return this->getOption(prismCompatibilityOptionName).getHasOptionBeenSet(); } diff --git a/src/storm/solver/EigenLinearEquationSolver.cpp b/src/storm/solver/EigenLinearEquationSolver.cpp index 0eed80f13..bf80f4db9 100644 --- a/src/storm/solver/EigenLinearEquationSolver.cpp +++ b/src/storm/solver/EigenLinearEquationSolver.cpp @@ -140,6 +140,9 @@ namespace storm { solver.compute(*this->eigenA); solver._solve_impl(eigenB, eigenX); } else { + bool converged = false; + uint64_t numberOfIterations = 0; + typename EigenLinearEquationSolverSettings<ValueType>::Preconditioner preconditioner = this->getSettings().getPreconditioner(); if (solutionMethod == EigenLinearEquationSolverSettings<ValueType>::SolutionMethod::BiCGSTAB) { if (preconditioner == EigenLinearEquationSolverSettings<ValueType>::Preconditioner::Ilu) { @@ -148,21 +151,24 @@ namespace storm { solver.setTolerance(this->getSettings().getPrecision()); solver.setMaxIterations(this->getSettings().getMaximalNumberOfIterations()); eigenX = solver.solveWithGuess(eigenB, eigenX); - return solver.info() == StormEigen::ComputationInfo::Success; + converged = solver.info() == StormEigen::ComputationInfo::Success; + numberOfIterations = solver.iterations(); } else if (preconditioner == EigenLinearEquationSolverSettings<ValueType>::Preconditioner::Diagonal) { StormEigen::BiCGSTAB<StormEigen::SparseMatrix<ValueType>, StormEigen::DiagonalPreconditioner<ValueType>> solver; solver.setTolerance(this->getSettings().getPrecision()); solver.setMaxIterations(this->getSettings().getMaximalNumberOfIterations()); solver.compute(*this->eigenA); eigenX = solver.solveWithGuess(eigenB, eigenX); - return solver.info() == StormEigen::ComputationInfo::Success; + converged = solver.info() == StormEigen::ComputationInfo::Success; + numberOfIterations = solver.iterations(); } else { StormEigen::BiCGSTAB<StormEigen::SparseMatrix<ValueType>, StormEigen::IdentityPreconditioner> solver; solver.setTolerance(this->getSettings().getPrecision()); solver.setMaxIterations(this->getSettings().getMaximalNumberOfIterations()); solver.compute(*this->eigenA); eigenX = solver.solveWithGuess(eigenB, eigenX); - return solver.info() == StormEigen::ComputationInfo::Success; + numberOfIterations = solver.iterations(); + converged = solver.info() == StormEigen::ComputationInfo::Success; } } else if (solutionMethod == EigenLinearEquationSolverSettings<ValueType>::SolutionMethod::DGMRES) { if (preconditioner == EigenLinearEquationSolverSettings<ValueType>::Preconditioner::Ilu) { @@ -172,7 +178,8 @@ namespace storm { solver.set_restart(this->getSettings().getNumberOfIterationsUntilRestart()); solver.compute(*this->eigenA); eigenX = solver.solveWithGuess(eigenB, eigenX); - return solver.info() == StormEigen::ComputationInfo::Success; + converged = solver.info() == StormEigen::ComputationInfo::Success; + numberOfIterations = solver.iterations(); } else if (preconditioner == EigenLinearEquationSolverSettings<ValueType>::Preconditioner::Diagonal) { StormEigen::DGMRES<StormEigen::SparseMatrix<ValueType>, StormEigen::DiagonalPreconditioner<ValueType>> solver; solver.setTolerance(this->getSettings().getPrecision()); @@ -180,7 +187,8 @@ namespace storm { solver.set_restart(this->getSettings().getNumberOfIterationsUntilRestart()); solver.compute(*this->eigenA); eigenX = solver.solveWithGuess(eigenB, eigenX); - return solver.info() == StormEigen::ComputationInfo::Success; + converged = solver.info() == StormEigen::ComputationInfo::Success; + numberOfIterations = solver.iterations(); } else { StormEigen::DGMRES<StormEigen::SparseMatrix<ValueType>, StormEigen::IdentityPreconditioner> solver; solver.setTolerance(this->getSettings().getPrecision()); @@ -188,7 +196,8 @@ namespace storm { solver.set_restart(this->getSettings().getNumberOfIterationsUntilRestart()); solver.compute(*this->eigenA); eigenX = solver.solveWithGuess(eigenB, eigenX); - return solver.info() == StormEigen::ComputationInfo::Success; + converged = solver.info() == StormEigen::ComputationInfo::Success; + numberOfIterations = solver.iterations(); } } else if (solutionMethod == EigenLinearEquationSolverSettings<ValueType>::SolutionMethod::GMRES) { if (preconditioner == EigenLinearEquationSolverSettings<ValueType>::Preconditioner::Ilu) { @@ -198,7 +207,8 @@ namespace storm { solver.set_restart(this->getSettings().getNumberOfIterationsUntilRestart()); solver.compute(*this->eigenA); eigenX = solver.solveWithGuess(eigenB, eigenX); - return solver.info() == StormEigen::ComputationInfo::Success; + converged = solver.info() == StormEigen::ComputationInfo::Success; + numberOfIterations = solver.iterations(); } else if (preconditioner == EigenLinearEquationSolverSettings<ValueType>::Preconditioner::Diagonal) { StormEigen::GMRES<StormEigen::SparseMatrix<ValueType>, StormEigen::DiagonalPreconditioner<ValueType>> solver; solver.setTolerance(this->getSettings().getPrecision()); @@ -206,7 +216,8 @@ namespace storm { solver.set_restart(this->getSettings().getNumberOfIterationsUntilRestart()); solver.compute(*this->eigenA); eigenX = solver.solveWithGuess(eigenB, eigenX); - return solver.info() == StormEigen::ComputationInfo::Success; + converged = solver.info() == StormEigen::ComputationInfo::Success; + numberOfIterations = solver.iterations(); } else { StormEigen::GMRES<StormEigen::SparseMatrix<ValueType>, StormEigen::IdentityPreconditioner> solver; solver.setTolerance(this->getSettings().getPrecision()); @@ -214,10 +225,21 @@ namespace storm { solver.set_restart(this->getSettings().getNumberOfIterationsUntilRestart()); solver.compute(*this->eigenA); eigenX = solver.solveWithGuess(eigenB, eigenX); - return solver.info() == StormEigen::ComputationInfo::Success; + converged = solver.info() == StormEigen::ComputationInfo::Success; + numberOfIterations = solver.iterations(); } } + + // Check if the solver converged and issue a warning otherwise. + if (converged) { + STORM_LOG_DEBUG("Iterative solver converged after " << numberOfIterations << " iterations."); + return true; + } else { + STORM_LOG_WARN("Iterative solver did not converge."); + return false; + } } + return false; } diff --git a/src/storm/solver/GmmxxLinearEquationSolver.cpp b/src/storm/solver/GmmxxLinearEquationSolver.cpp index 5ecd10f4c..c92817ac2 100644 --- a/src/storm/solver/GmmxxLinearEquationSolver.cpp +++ b/src/storm/solver/GmmxxLinearEquationSolver.cpp @@ -138,7 +138,7 @@ namespace storm { bool GmmxxLinearEquationSolver<ValueType>::solveEquations(std::vector<ValueType>& x, std::vector<ValueType> const& b) const { auto method = this->getSettings().getSolutionMethod(); auto preconditioner = this->getSettings().getPreconditioner(); - STORM_LOG_INFO("Using method '" << method << "' with preconditioner '" << preconditioner << "' (max. " << this->getSettings().getMaximalNumberOfIterations() << " iterations)."); + STORM_LOG_DEBUG("Using method '" << method << "' with preconditioner '" << preconditioner << "' (max. " << this->getSettings().getMaximalNumberOfIterations() << " iterations)."); if (method == GmmxxLinearEquationSolverSettings<ValueType>::SolutionMethod::Jacobi && preconditioner != GmmxxLinearEquationSolverSettings<ValueType>::Preconditioner::None) { STORM_LOG_WARN("Jacobi method currently does not support preconditioners. The requested preconditioner will be ignored."); } @@ -187,13 +187,13 @@ namespace storm { } } - if(!this->isCachingEnabled()) { + if (!this->isCachingEnabled()) { clearCache(); } // Check if the solver converged and issue a warning otherwise. if (iter.converged()) { - STORM_LOG_INFO("Iterative solver converged after " << iter.get_iteration() << " iterations."); + STORM_LOG_DEBUG("Iterative solver converged after " << iter.get_iteration() << " iterations."); return true; } else { STORM_LOG_WARN("Iterative solver did not converge."); @@ -204,7 +204,7 @@ namespace storm { // Check if the solver converged and issue a warning otherwise. if (iterations < this->getSettings().getMaximalNumberOfIterations()) { - STORM_LOG_INFO("Iterative solver converged after " << iterations << " iterations."); + STORM_LOG_DEBUG("Iterative solver converged after " << iterations << " iterations."); return true; } else { STORM_LOG_WARN("Iterative solver did not converge."); diff --git a/src/storm/solver/NativeLinearEquationSolver.cpp b/src/storm/solver/NativeLinearEquationSolver.cpp index fcd3ed83c..f9763434a 100644 --- a/src/storm/solver/NativeLinearEquationSolver.cpp +++ b/src/storm/solver/NativeLinearEquationSolver.cpp @@ -110,7 +110,7 @@ namespace storm { template<typename ValueType> bool NativeLinearEquationSolver<ValueType>::solveEquations(std::vector<ValueType>& x, std::vector<ValueType> const& b) const { - if(!this->cachedRowVector) { + if (!this->cachedRowVector) { this->cachedRowVector = std::make_unique<std::vector<ValueType>>(getMatrixRowCount()); } @@ -180,7 +180,7 @@ namespace storm { std::swap(x, *currentX); } - if(!this->isCachingEnabled()) { + if (!this->isCachingEnabled()) { clearCache(); } @@ -208,7 +208,7 @@ namespace storm { result.swap(*this->cachedRowVector); } - if(!this->isCachingEnabled()) { + if (!this->isCachingEnabled()) { clearCache(); } } diff --git a/src/storm/solver/SymbolicLinearEquationSolver.cpp b/src/storm/solver/SymbolicLinearEquationSolver.cpp index 90db5d037..0a77e2b34 100644 --- a/src/storm/solver/SymbolicLinearEquationSolver.cpp +++ b/src/storm/solver/SymbolicLinearEquationSolver.cpp @@ -37,7 +37,10 @@ namespace storm { storm::dd::Add<DdType, ValueType> lu = diagonal.ite(this->A.getDdManager().template getAddZero<ValueType>(), this->A); storm::dd::Add<DdType> diagonalAdd = diagonal.template toAdd<ValueType>(); - storm::dd::Add<DdType, ValueType> dinv = diagonalAdd / (diagonalAdd * this->A); + storm::dd::Add<DdType, ValueType> diag = diagonalAdd.multiplyMatrix(this->A, this->columnMetaVariables); + + storm::dd::Add<DdType, ValueType> scaledLu = lu / diag; + storm::dd::Add<DdType, ValueType> scaledB = b / diag; // Set up additional environment variables. storm::dd::Add<DdType, ValueType> xCopy = x; @@ -46,24 +49,23 @@ namespace storm { while (!converged && iterationCount < maximalNumberOfIterations) { storm::dd::Add<DdType, ValueType> xCopyAsColumn = xCopy.swapVariables(this->rowColumnMetaVariablePairs); - - storm::dd::Add<DdType, ValueType> tmp = lu.multiplyMatrix(xCopyAsColumn, this->columnMetaVariables); - tmp = b - tmp; - tmp = tmp.swapVariables(this->rowColumnMetaVariablePairs); - tmp = dinv.multiplyMatrix(tmp, this->columnMetaVariables); + storm::dd::Add<DdType, ValueType> tmp = scaledB - scaledLu.multiplyMatrix(xCopyAsColumn, this->columnMetaVariables); // Now check if the process already converged within our precision. - converged = xCopy.equalModuloPrecision(tmp, precision, relative); - - // If the method did not converge yet, we prepare the x vector for the next iteration. - if (!converged) { - xCopy = tmp; - } + converged = tmp.equalModuloPrecision(xCopy, precision, relative); + + xCopy = tmp; // Increase iteration count so we can abort if convergence is too slow. ++iterationCount; } - + + if (converged) { + STORM_LOG_TRACE("Iterative solver converged in " << iterationCount << " iterations."); + } else { + STORM_LOG_WARN("Iterative solver did not converge in " << iterationCount << " iterations."); + } + return xCopy; } diff --git a/src/storm/solver/SymbolicLinearEquationSolver.h b/src/storm/solver/SymbolicLinearEquationSolver.h index 1b64c1d55..13686d3f4 100644 --- a/src/storm/solver/SymbolicLinearEquationSolver.h +++ b/src/storm/solver/SymbolicLinearEquationSolver.h @@ -83,7 +83,7 @@ namespace storm { protected: // The matrix defining the coefficients of the linear equation system. - storm::dd::Add<DdType, ValueType> const& A; + storm::dd::Add<DdType, ValueType> A; // A BDD characterizing all rows of the equation system. storm::dd::Bdd<DdType> const& allRows; diff --git a/src/storm/solver/SymbolicMinMaxLinearEquationSolver.cpp b/src/storm/solver/SymbolicMinMaxLinearEquationSolver.cpp index eced26e13..5ceb5b7d7 100644 --- a/src/storm/solver/SymbolicMinMaxLinearEquationSolver.cpp +++ b/src/storm/solver/SymbolicMinMaxLinearEquationSolver.cpp @@ -43,8 +43,6 @@ namespace storm { tmp += b; if (minimize) { - // This is a hack and only here because of the lack of a suitable minAbstract/maxAbstract function - // that can properly deal with a restriction of the choices. tmp += illegalMaskAdd; tmp = tmp.minAbstract(this->choiceVariables); } else { @@ -54,14 +52,17 @@ namespace storm { // Now check if the process already converged within our precision. converged = xCopy.equalModuloPrecision(tmp, precision, relative); - // If the method did not converge yet, we prepare the x vector for the next iteration. - if (!converged) { - xCopy = tmp; - } + xCopy = tmp; ++iterations; } - + + if (converged) { + STORM_LOG_TRACE("Iterative solver converged in " << iterations << " iterations."); + } else { + STORM_LOG_WARN("Iterative solver did not converge in " << iterations << " iterations."); + } + return xCopy; } diff --git a/src/storm/storage/SparseMatrix.cpp b/src/storm/storage/SparseMatrix.cpp index 8794ac759..3f70b8f2a 100644 --- a/src/storm/storage/SparseMatrix.cpp +++ b/src/storm/storage/SparseMatrix.cpp @@ -1295,19 +1295,6 @@ namespace storm { } } - template<typename ValueType> - std::size_t SparseMatrix<ValueType>::getSizeInBytes() const { - uint_fast64_t size = sizeof(*this); - - // Add size of columns and values. - size += sizeof(MatrixEntry<index_type, ValueType>) * columnsAndValues.capacity(); - - // Add row_indications size. - size += sizeof(uint_fast64_t) * rowIndications.capacity(); - - return size; - } - template<typename ValueType> typename SparseMatrix<ValueType>::const_rows SparseMatrix<ValueType>::getRows(index_type startRow, index_type endRow) const { return const_rows(this->columnsAndValues.begin() + this->rowIndications[startRow], this->rowIndications[endRow] - this->rowIndications[startRow]); diff --git a/src/storm/storage/SparseMatrix.h b/src/storm/storage/SparseMatrix.h index a7cfc7b83..f897e1606 100644 --- a/src/storm/storage/SparseMatrix.h +++ b/src/storm/storage/SparseMatrix.h @@ -846,13 +846,6 @@ namespace storm { * @out The stream to output to. */ void printAsMatlabMatrix(std::ostream& out) const; - - /*! - * Returns the size of the matrix in memory measured in bytes. - * - * @return The size of the matrix in memory measured in bytes. - */ - std::size_t getSizeInBytes() const; /*! * Calculates a hash value over all values contained in the matrix. diff --git a/src/storm/storage/SymbolicModelDescription.cpp b/src/storm/storage/SymbolicModelDescription.cpp index da985d103..92b52c783 100644 --- a/src/storm/storage/SymbolicModelDescription.cpp +++ b/src/storm/storage/SymbolicModelDescription.cpp @@ -126,6 +126,18 @@ namespace storm { } } + std::pair<SymbolicModelDescription, std::map<std::string, std::string>> SymbolicModelDescription::toJaniWithLabelRenaming(bool makeVariablesGlobal) const { + if (this->isJaniModel()) { + return std::make_pair(*this, std::map<std::string, std::string>()); + } + if (this->isPrismProgram()) { + auto modelAndRenaming = this->asPrismProgram().toJaniWithLabelRenaming(makeVariablesGlobal); + return std::make_pair(SymbolicModelDescription(modelAndRenaming.first), modelAndRenaming.second); + } else { + STORM_LOG_THROW(false, storm::exceptions::InvalidOperationException, "Cannot transform model description to the JANI format."); + } + } + SymbolicModelDescription SymbolicModelDescription::preprocess(std::string const& constantDefinitionString) const { std::map<storm::expressions::Variable, storm::expressions::Expression> substitution = parseConstantDefinitions(constantDefinitionString); if (this->isJaniModel()) { diff --git a/src/storm/storage/SymbolicModelDescription.h b/src/storm/storage/SymbolicModelDescription.h index 8ed9fa7e0..05daa5ec2 100644 --- a/src/storm/storage/SymbolicModelDescription.h +++ b/src/storm/storage/SymbolicModelDescription.h @@ -39,6 +39,7 @@ namespace storm { std::vector<std::string> getParameterNames() const; SymbolicModelDescription toJani(bool makeVariablesGlobal = true) const; + std::pair<SymbolicModelDescription, std::map<std::string, std::string>> toJaniWithLabelRenaming(bool makeVariablesGlobal = true) const; SymbolicModelDescription preprocess(std::string const& constantDefinitionString = "") const; SymbolicModelDescription preprocess(std::map<storm::expressions::Variable, storm::expressions::Expression> const& constantDefinitions) const; diff --git a/src/storm/storage/dd/Add.cpp b/src/storm/storage/dd/Add.cpp index 93039e480..1f09fa687 100644 --- a/src/storm/storage/dd/Add.cpp +++ b/src/storm/storage/dd/Add.cpp @@ -550,7 +550,11 @@ namespace storm { // Next, we split the matrix into one for each group. Note that this only works if the group variables are // at the very top. - std::vector<InternalAdd<LibraryType, ValueType>> groups = internalAdd.splitIntoGroups(ddGroupVariableIndices); + std::vector<InternalAdd<LibraryType, ValueType>> internalAddGroups = internalAdd.splitIntoGroups(ddGroupVariableIndices); + std::vector<Add<LibraryType, ValueType>> groups; + for (auto const& internalAdd : internalAddGroups) { + groups.push_back(Add<LibraryType, ValueType>(this->getDdManager(), internalAdd, rowAndColumnMetaVariables)); + } // Create the actual storage for the non-zero entries. std::vector<storm::storage::MatrixEntry<uint_fast64_t, ValueType>> columnsAndValues(this->getNonZeroCount()); @@ -561,17 +565,20 @@ namespace storm { std::vector<InternalAdd<LibraryType, uint_fast64_t>> statesWithGroupEnabled(groups.size()); InternalAdd<LibraryType, uint_fast64_t> stateToRowGroupCount = this->getDdManager().template getAddZero<uint_fast64_t>(); for (uint_fast64_t i = 0; i < groups.size(); ++i) { - auto const& dd = groups[i]; + auto const& group = groups[i]; + auto groupNotZero = group.notZero(); - dd.toMatrixComponents(rowGroupIndices, rowIndications, columnsAndValues, rowOdd, columnOdd, ddRowVariableIndices, ddColumnVariableIndices, false); + std::vector<uint64_t> tmpRowIndications = groupNotZero.template toAdd<uint_fast64_t>().sumAbstract(columnMetaVariables).toVector(rowOdd); + for (uint64_t offset = 0; offset < tmpRowIndications.size(); ++offset) { + rowIndications[rowGroupIndices[offset]] += tmpRowIndications[offset]; + } - statesWithGroupEnabled[i] = dd.notZero().existsAbstract(columnVariableCube).template toAdd<uint_fast64_t>(); - stateToRowGroupCount += statesWithGroupEnabled[i]; + statesWithGroupEnabled[i] = groupNotZero.existsAbstract(columnMetaVariables).template toAdd<uint_fast64_t>(); statesWithGroupEnabled[i].composeWithExplicitVector(rowOdd, ddRowVariableIndices, rowGroupIndices, std::plus<uint_fast64_t>()); } // Since we modified the rowGroupIndices, we need to restore the correct values. - stateToRowGroupCount.composeWithExplicitVector(rowOdd, ddRowVariableIndices, rowGroupIndices, std::minus<uint_fast64_t>()); + stateToNumberOfChoices.internalAdd.composeWithExplicitVector(rowOdd, ddRowVariableIndices, rowGroupIndices, std::minus<uint_fast64_t>()); // Now that we computed the number of entries in each row, compute the corresponding offsets in the entry vector. tmp = 0; @@ -585,15 +592,15 @@ namespace storm { // Now actually fill the entry vector. for (uint_fast64_t i = 0; i < groups.size(); ++i) { - auto const& dd = groups[i]; + auto const& group = groups[i]; - dd.toMatrixComponents(rowGroupIndices, rowIndications, columnsAndValues, rowOdd, columnOdd, ddRowVariableIndices, ddColumnVariableIndices, true); + group.internalAdd.toMatrixComponents(rowGroupIndices, rowIndications, columnsAndValues, rowOdd, columnOdd, ddRowVariableIndices, ddColumnVariableIndices, true); statesWithGroupEnabled[i].composeWithExplicitVector(rowOdd, ddRowVariableIndices, rowGroupIndices, std::plus<uint_fast64_t>()); } // Since we modified the rowGroupIndices, we need to restore the correct values. - stateToRowGroupCount.composeWithExplicitVector(rowOdd, ddRowVariableIndices, rowGroupIndices, std::minus<uint_fast64_t>()); + stateToNumberOfChoices.internalAdd.composeWithExplicitVector(rowOdd, ddRowVariableIndices, rowGroupIndices, std::minus<uint_fast64_t>()); // Since the last call to toMatrixRec modified the rowIndications, we need to restore the correct values. for (uint_fast64_t i = rowIndications.size() - 1; i > 0; --i) { @@ -674,7 +681,11 @@ namespace storm { std::vector<ValueType> explicitVector(rowGroupIndices.back()); // Next, we split the matrix into one for each group. Note that this only works if the group variables are at the very top. - std::vector<std::pair<InternalAdd<LibraryType, ValueType>, InternalAdd<LibraryType, ValueType>>> groups = internalAdd.splitIntoGroups(vector, ddGroupVariableIndices); + std::vector<std::pair<InternalAdd<LibraryType, ValueType>, InternalAdd<LibraryType, ValueType>>> internalAddGroups = internalAdd.splitIntoGroups(vector, ddGroupVariableIndices); + std::vector<std::pair<Add<LibraryType, ValueType>, Add<LibraryType, ValueType>>> groups; + for (auto const& internalAdd : internalAddGroups) { + groups.push_back(std::make_pair(Add<LibraryType, ValueType>(this->getDdManager(), internalAdd.first, rowAndColumnMetaVariables), Add<LibraryType, ValueType>(this->getDdManager(), internalAdd.second, rowMetaVariables))); + } // Create the actual storage for the non-zero entries. std::vector<storm::storage::MatrixEntry<uint_fast64_t, ValueType>> columnsAndValues(this->getNonZeroCount()); @@ -685,12 +696,18 @@ namespace storm { std::vector<InternalAdd<LibraryType, uint_fast64_t>> statesWithGroupEnabled(groups.size()); InternalAdd<LibraryType, uint_fast64_t> stateToRowGroupCount = this->getDdManager().template getAddZero<uint_fast64_t>(); for (uint_fast64_t i = 0; i < groups.size(); ++i) { - std::pair<InternalAdd<LibraryType, ValueType>, InternalAdd<LibraryType, ValueType>> const& ddPair = groups[i]; - - ddPair.first.toMatrixComponents(rowGroupIndices, rowIndications, columnsAndValues, rowOdd, columnOdd, ddRowVariableIndices, ddColumnVariableIndices, false); - ddPair.second.composeWithExplicitVector(rowOdd, ddRowVariableIndices, rowGroupIndices, explicitVector, std::plus<ValueType>()); + std::pair<Add<LibraryType, ValueType>, Add<LibraryType, ValueType>> const& ddPair = groups[i]; + Bdd<LibraryType> matrixDdNotZero = ddPair.first.notZero(); + Bdd<LibraryType> vectorDdNotZero = ddPair.second.notZero(); + + std::vector<uint64_t> tmpRowIndications = matrixDdNotZero.template toAdd<uint_fast64_t>().sumAbstract(columnMetaVariables).toVector(rowOdd); + for (uint64_t offset = 0; offset < tmpRowIndications.size(); ++offset) { + rowIndications[rowGroupIndices[offset]] += tmpRowIndications[offset]; + } + + ddPair.second.internalAdd.composeWithExplicitVector(rowOdd, ddRowVariableIndices, rowGroupIndices, explicitVector, std::plus<ValueType>()); - statesWithGroupEnabled[i] = (ddPair.first.notZero().existsAbstract(columnVariableCube) || ddPair.second.notZero()).template toAdd<uint_fast64_t>(); + statesWithGroupEnabled[i] = (matrixDdNotZero.existsAbstract(columnMetaVariables) || vectorDdNotZero).template toAdd<uint_fast64_t>(); stateToRowGroupCount += statesWithGroupEnabled[i]; statesWithGroupEnabled[i].composeWithExplicitVector(rowOdd, ddRowVariableIndices, rowGroupIndices, std::plus<uint_fast64_t>()); } @@ -712,8 +729,7 @@ namespace storm { for (uint_fast64_t i = 0; i < groups.size(); ++i) { auto const& dd = groups[i].first; - dd.toMatrixComponents(rowGroupIndices, rowIndications, columnsAndValues, rowOdd, columnOdd, ddRowVariableIndices, ddColumnVariableIndices, true); - + dd.internalAdd.toMatrixComponents(rowGroupIndices, rowIndications, columnsAndValues, rowOdd, columnOdd, ddRowVariableIndices, ddColumnVariableIndices, true); statesWithGroupEnabled[i].composeWithExplicitVector(rowOdd, ddRowVariableIndices, rowGroupIndices, std::plus<uint_fast64_t>()); } diff --git a/src/storm/storage/dd/Bdd.h b/src/storm/storage/dd/Bdd.h index 84a0db845..1341a8e3b 100644 --- a/src/storm/storage/dd/Bdd.h +++ b/src/storm/storage/dd/Bdd.h @@ -35,7 +35,7 @@ namespace storm { Bdd& operator=(Bdd<LibraryType> const& other) = default; Bdd(Bdd<LibraryType>&& other) = default; Bdd& operator=(Bdd<LibraryType>&& other) = default; - + /*! * Constructs a BDD representation of all encodings that are in the requested relation with the given value. * diff --git a/src/storm/storage/dd/DdManager.cpp b/src/storm/storage/dd/DdManager.cpp index 3cd2539dd..9cca07b06 100644 --- a/src/storm/storage/dd/DdManager.cpp +++ b/src/storm/storage/dd/DdManager.cpp @@ -111,8 +111,17 @@ namespace storm { template<DdType LibraryType> Bdd<LibraryType> DdManager<LibraryType>::getCube(storm::expressions::Variable const& variable) const { - storm::dd::DdMetaVariable<LibraryType> const& metaVariable = this->getMetaVariable(variable); - return metaVariable.getCube(); + return getCube({variable}); + } + + template<DdType LibraryType> + Bdd<LibraryType> DdManager<LibraryType>::getCube(std::set<storm::expressions::Variable> const& variables) const { + Bdd<LibraryType> result = this->getBddOne(); + for (auto const& variable : variables) { + storm::dd::DdMetaVariable<LibraryType> const& metaVariable = this->getMetaVariable(variable); + result &= metaVariable.getCube(); + } + return result; } template<DdType LibraryType> diff --git a/src/storm/storage/dd/DdManager.h b/src/storm/storage/dd/DdManager.h index 0ab1ed1c9..7baffbcb8 100644 --- a/src/storm/storage/dd/DdManager.h +++ b/src/storm/storage/dd/DdManager.h @@ -125,7 +125,15 @@ namespace storm { * @return The cube of the meta variable. */ Bdd<LibraryType> getCube(storm::expressions::Variable const& variable) const; - + + /*! + * Retrieves a BDD that is the cube of the variables representing the given meta variables. + * + * @param variables The expression variables associated with the meta variables. + * @return The cube of the meta variables. + */ + Bdd<LibraryType> getCube(std::set<storm::expressions::Variable> const& variables) const; + /*! * Adds an integer meta variable with the given range. * diff --git a/src/storm/storage/dd/cudd/InternalCuddAdd.cpp b/src/storm/storage/dd/cudd/InternalCuddAdd.cpp index 4cf197970..872ef4856 100644 --- a/src/storm/storage/dd/cudd/InternalCuddAdd.cpp +++ b/src/storm/storage/dd/cudd/InternalCuddAdd.cpp @@ -17,7 +17,7 @@ namespace storm { InternalAdd<DdType::CUDD, ValueType>::InternalAdd(InternalDdManager<DdType::CUDD> const* ddManager, cudd::ADD cuddAdd) : ddManager(ddManager), cuddAdd(cuddAdd) { // Intentionally left empty. } - + template<typename ValueType> bool InternalAdd<DdType::CUDD, ValueType>::operator==(InternalAdd<DdType::CUDD, ValueType> const& other) const { return this->getCuddAdd() == other.getCuddAdd(); diff --git a/src/storm/storage/dd/sylvan/InternalSylvanAdd.cpp b/src/storm/storage/dd/sylvan/InternalSylvanAdd.cpp index 5e5043246..08eb74bb1 100644 --- a/src/storm/storage/dd/sylvan/InternalSylvanAdd.cpp +++ b/src/storm/storage/dd/sylvan/InternalSylvanAdd.cpp @@ -14,6 +14,11 @@ namespace storm { namespace dd { + template<typename ValueType> + InternalAdd<DdType::Sylvan, ValueType>::InternalAdd() : ddManager(nullptr), sylvanMtbdd() { + // Intentionally left empty. + } + template<typename ValueType> InternalAdd<DdType::Sylvan, ValueType>::InternalAdd(InternalDdManager<DdType::Sylvan> const* ddManager, sylvan::Mtbdd const& sylvanMtbdd) : ddManager(ddManager), sylvanMtbdd(sylvanMtbdd) { // Intentionally left empty. diff --git a/src/storm/storage/dd/sylvan/InternalSylvanAdd.h b/src/storm/storage/dd/sylvan/InternalSylvanAdd.h index 17fd8eca2..d91374903 100644 --- a/src/storm/storage/dd/sylvan/InternalSylvanAdd.h +++ b/src/storm/storage/dd/sylvan/InternalSylvanAdd.h @@ -55,12 +55,12 @@ namespace storm { InternalAdd(InternalDdManager<DdType::Sylvan> const* ddManager, sylvan::Mtbdd const& sylvanMtbdd); // Instantiate all copy/move constructors/assignments with the default implementation. - InternalAdd() = default; + InternalAdd(); InternalAdd(InternalAdd<DdType::Sylvan, ValueType> const& other) = default; InternalAdd& operator=(InternalAdd<DdType::Sylvan, ValueType> const& other) = default; InternalAdd(InternalAdd<DdType::Sylvan, ValueType>&& other) = default; InternalAdd& operator=(InternalAdd<DdType::Sylvan, ValueType>&& other) = default; - + /*! * Retrieves whether the two DDs represent the same function. * diff --git a/src/storm/storage/dd/sylvan/InternalSylvanBdd.cpp b/src/storm/storage/dd/sylvan/InternalSylvanBdd.cpp index 7097ac999..5c297be99 100644 --- a/src/storm/storage/dd/sylvan/InternalSylvanBdd.cpp +++ b/src/storm/storage/dd/sylvan/InternalSylvanBdd.cpp @@ -18,6 +18,10 @@ namespace storm { namespace dd { + InternalBdd<DdType::Sylvan>::InternalBdd() : ddManager(nullptr), sylvanBdd() { + // Intentionally left empty. + } + InternalBdd<DdType::Sylvan>::InternalBdd(InternalDdManager<DdType::Sylvan> const* ddManager, sylvan::Bdd const& sylvanBdd) : ddManager(ddManager), sylvanBdd(sylvanBdd) { // Intentionally left empty. } diff --git a/src/storm/storage/dd/sylvan/InternalSylvanBdd.h b/src/storm/storage/dd/sylvan/InternalSylvanBdd.h index 930966c01..fbeb49c4b 100644 --- a/src/storm/storage/dd/sylvan/InternalSylvanBdd.h +++ b/src/storm/storage/dd/sylvan/InternalSylvanBdd.h @@ -35,7 +35,7 @@ namespace storm { InternalBdd(InternalDdManager<DdType::Sylvan> const* ddManager, sylvan::Bdd const& sylvanBdd); // Instantiate all copy/move constructors/assignments with the default implementation. - InternalBdd() = default; + InternalBdd(); InternalBdd(InternalBdd<DdType::Sylvan> const& other) = default; InternalBdd& operator=(InternalBdd<DdType::Sylvan> const& other) = default; InternalBdd(InternalBdd<DdType::Sylvan>&& other) = default; diff --git a/src/storm/storage/expressions/ExpressionEvaluator.cpp b/src/storm/storage/expressions/ExpressionEvaluator.cpp index 541e2f7e7..abea0ce73 100644 --- a/src/storm/storage/expressions/ExpressionEvaluator.cpp +++ b/src/storm/storage/expressions/ExpressionEvaluator.cpp @@ -1,6 +1,8 @@ #include "storm/storage/expressions/ExpressionEvaluator.h" #include "storm/storage/expressions/ExpressionManager.h" +#include "storm/utility/constants.h" + namespace storm { namespace expressions { ExpressionEvaluator<double>::ExpressionEvaluator(storm::expressions::ExpressionManager const& manager) : ExprtkExpressionEvaluator(manager) { @@ -31,22 +33,52 @@ namespace storm { } #ifdef STORM_HAVE_CARL - ExpressionEvaluator<RationalNumber>::ExpressionEvaluator(storm::expressions::ExpressionManager const& manager) : ExpressionEvaluatorWithVariableToExpressionMap<RationalNumber>(manager) { + ExpressionEvaluator<RationalNumber>::ExpressionEvaluator(storm::expressions::ExpressionManager const& manager) : ExprtkExpressionEvaluatorBase<RationalNumber>(manager) { // Intentionally left empty. } + void ExpressionEvaluator<RationalNumber>::setBooleanValue(storm::expressions::Variable const& variable, bool value) { + ExprtkExpressionEvaluatorBase<RationalNumber>::setBooleanValue(variable, value); + + // Not forwarding value of variable to rational number visitor as it cannot treat boolean variables anyway. + } + + void ExpressionEvaluator<RationalNumber>::setIntegerValue(storm::expressions::Variable const& variable, int_fast64_t value) { + ExprtkExpressionEvaluatorBase<RationalNumber>::setIntegerValue(variable, value); + rationalNumberVisitor.setMapping(variable, storm::utility::convertNumber<RationalNumber>(value)); + } + + void ExpressionEvaluator<RationalNumber>::setRationalValue(storm::expressions::Variable const& variable, double value) { + ExprtkExpressionEvaluatorBase<RationalNumber>::setRationalValue(variable, value); + rationalNumberVisitor.setMapping(variable, storm::utility::convertNumber<RationalNumber>(value)); + } + RationalNumber ExpressionEvaluator<RationalNumber>::asRational(Expression const& expression) const { - Expression substitutedExpression = expression.substitute(this->variableToExpressionMap); - return this->rationalNumberVisitor.toRationalNumber(substitutedExpression); + return this->rationalNumberVisitor.toRationalNumber(expression); } - ExpressionEvaluator<RationalFunction>::ExpressionEvaluator(storm::expressions::ExpressionManager const& manager) : ExpressionEvaluatorWithVariableToExpressionMap<RationalFunction>(manager) { + ExpressionEvaluator<RationalFunction>::ExpressionEvaluator(storm::expressions::ExpressionManager const& manager) : ExprtkExpressionEvaluatorBase<RationalFunction>(manager) { // Intentionally left empty. } + void ExpressionEvaluator<RationalFunction>::setBooleanValue(storm::expressions::Variable const& variable, bool value) { + ExprtkExpressionEvaluatorBase<RationalFunction>::setBooleanValue(variable, value); + + // Not forwarding value of variable to rational number visitor as it cannot treat boolean variables anyway. + } + + void ExpressionEvaluator<RationalFunction>::setIntegerValue(storm::expressions::Variable const& variable, int_fast64_t value) { + ExprtkExpressionEvaluatorBase<RationalFunction>::setIntegerValue(variable, value); + rationalFunctionVisitor.setMapping(variable, storm::utility::convertNumber<RationalFunction>(value)); + } + + void ExpressionEvaluator<RationalFunction>::setRationalValue(storm::expressions::Variable const& variable, double value) { + ExprtkExpressionEvaluatorBase<RationalFunction>::setRationalValue(variable, value); + rationalFunctionVisitor.setMapping(variable, storm::utility::convertNumber<RationalFunction>(value)); + } + RationalFunction ExpressionEvaluator<RationalFunction>::asRational(Expression const& expression) const { - Expression substitutedExpression = expression.substitute(this->variableToExpressionMap); - return this->rationalFunctionVisitor.toRationalFunction(substitutedExpression); + return this->rationalFunctionVisitor.toRationalFunction(expression); } template class ExpressionEvaluatorWithVariableToExpressionMap<RationalNumber>; diff --git a/src/storm/storage/expressions/ExpressionEvaluator.h b/src/storm/storage/expressions/ExpressionEvaluator.h index 376b530c2..9308c912b 100644 --- a/src/storm/storage/expressions/ExpressionEvaluator.h +++ b/src/storm/storage/expressions/ExpressionEvaluator.h @@ -37,10 +37,14 @@ namespace storm { #ifdef STORM_HAVE_CARL template<> - class ExpressionEvaluator<RationalNumber> : public ExpressionEvaluatorWithVariableToExpressionMap<RationalNumber> { + class ExpressionEvaluator<RationalNumber> : public ExprtkExpressionEvaluatorBase<RationalNumber> { public: ExpressionEvaluator(storm::expressions::ExpressionManager const& manager); + void setBooleanValue(storm::expressions::Variable const& variable, bool value) override; + void setIntegerValue(storm::expressions::Variable const& variable, int_fast64_t value) override; + void setRationalValue(storm::expressions::Variable const& variable, double value) override; + RationalNumber asRational(Expression const& expression) const override; private: @@ -49,10 +53,14 @@ namespace storm { }; template<> - class ExpressionEvaluator<RationalFunction> : public ExpressionEvaluatorWithVariableToExpressionMap<RationalFunction> { + class ExpressionEvaluator<RationalFunction> : public ExprtkExpressionEvaluatorBase<RationalFunction> { public: ExpressionEvaluator(storm::expressions::ExpressionManager const& manager); + void setBooleanValue(storm::expressions::Variable const& variable, bool value) override; + void setIntegerValue(storm::expressions::Variable const& variable, int_fast64_t value) override; + void setRationalValue(storm::expressions::Variable const& variable, double value) override; + RationalFunction asRational(Expression const& expression) const override; private: diff --git a/src/storm/storage/expressions/ExpressionManager.cpp b/src/storm/storage/expressions/ExpressionManager.cpp index 3072c30e0..d1b3d15cd 100644 --- a/src/storm/storage/expressions/ExpressionManager.cpp +++ b/src/storm/storage/expressions/ExpressionManager.cpp @@ -52,7 +52,7 @@ namespace storm { } } - ExpressionManager::ExpressionManager() : nameToIndexMapping(), indexToNameMapping(), indexToTypeMapping(), numberOfBooleanVariables(0), numberOfIntegerVariables(0), numberOfBitVectorVariables(0), numberOfRationalVariables(0), numberOfAuxiliaryVariables(0), numberOfAuxiliaryBooleanVariables(0), numberOfAuxiliaryIntegerVariables(0), numberOfAuxiliaryBitVectorVariables(0), numberOfAuxiliaryRationalVariables(0), freshVariableCounter(0), types() { + ExpressionManager::ExpressionManager() : nameToIndexMapping(), indexToNameMapping(), indexToTypeMapping(), numberOfBooleanVariables(0), numberOfIntegerVariables(0), numberOfBitVectorVariables(0), numberOfRationalVariables(0), numberOfAuxiliaryVariables(0), numberOfAuxiliaryBooleanVariables(0), numberOfAuxiliaryIntegerVariables(0), numberOfAuxiliaryBitVectorVariables(0), numberOfAuxiliaryRationalVariables(0), freshVariableCounter(0) { // Intentionally left empty. } @@ -65,19 +65,19 @@ namespace storm { } Expression ExpressionManager::boolean(bool value) const { - return Expression(std::shared_ptr<BaseExpression>(new BooleanLiteralExpression(*this, value))); + return Expression(std::make_shared<BooleanLiteralExpression>(*this, value)); } Expression ExpressionManager::integer(int_fast64_t value) const { - return Expression(std::shared_ptr<BaseExpression>(new IntegerLiteralExpression(*this, value))); + return Expression(std::make_shared<IntegerLiteralExpression>(*this, value)); } Expression ExpressionManager::rational(double value) const { - return Expression(std::shared_ptr<BaseExpression>(new RationalLiteralExpression(*this, value))); + return Expression(std::make_shared<RationalLiteralExpression>(*this, value)); } Expression ExpressionManager::rational(storm::RationalNumber const& value) const { - return Expression(std::shared_ptr<BaseExpression>(new RationalLiteralExpression(*this, value))); + return Expression(std::make_shared<RationalLiteralExpression>(*this, value)); } bool ExpressionManager::operator==(ExpressionManager const& other) const { @@ -85,43 +85,34 @@ namespace storm { } Type const& ExpressionManager::getBooleanType() const { - Type type(this->getSharedPointer(), std::shared_ptr<BaseType>(new BooleanType())); - auto typeIterator = types.find(type); - if (typeIterator == types.end()) { - auto iteratorBoolPair = types.insert(type); - return *iteratorBoolPair.first; + if (!booleanType) { + booleanType = Type(this->getSharedPointer(), std::shared_ptr<BaseType>(new BooleanType())); } - return *typeIterator; + return booleanType.get(); } Type const& ExpressionManager::getIntegerType() const { - Type type(this->getSharedPointer(), std::shared_ptr<BaseType>(new IntegerType())); - auto typeIterator = types.find(type); - if (typeIterator == types.end()) { - auto iteratorBoolPair = types.insert(type); - return *iteratorBoolPair.first; + if (!integerType) { + integerType = Type(this->getSharedPointer(), std::shared_ptr<BaseType>(new IntegerType())); } - return *typeIterator; + return integerType.get(); } Type const& ExpressionManager::getBitVectorType(std::size_t width) const { Type type(this->getSharedPointer(), std::shared_ptr<BaseType>(new BitVectorType(width))); - auto typeIterator = types.find(type); - if (typeIterator == types.end()) { - auto iteratorBoolPair = types.insert(type); + auto typeIterator = bitvectorTypes.find(type); + if (typeIterator == bitvectorTypes.end()) { + auto iteratorBoolPair = bitvectorTypes.insert(type); return *iteratorBoolPair.first; } return *typeIterator; } Type const& ExpressionManager::getRationalType() const { - Type type(this->getSharedPointer(), std::shared_ptr<BaseType>(new RationalType())); - auto typeIterator = types.find(type); - if (typeIterator == types.end()) { - auto iteratorBoolPair = types.insert(type); - return *iteratorBoolPair.first; + if (!rationalType) { + rationalType = Type(this->getSharedPointer(), std::shared_ptr<BaseType>(new RationalType())); } - return *typeIterator; + return rationalType.get(); } bool ExpressionManager::isValidVariableName(std::string const& name) { diff --git a/src/storm/storage/expressions/ExpressionManager.h b/src/storm/storage/expressions/ExpressionManager.h index 9630a719d..1ad82b939 100644 --- a/src/storm/storage/expressions/ExpressionManager.h +++ b/src/storm/storage/expressions/ExpressionManager.h @@ -8,6 +8,8 @@ #include <unordered_set> #include <iostream> +#include <boost/optional.hpp> + #include "storm/storage/expressions/Variable.h" #include "storm/storage/expressions/Expression.h" #include "storm/adapters/CarlAdapter.h" @@ -455,8 +457,11 @@ namespace storm { uint_fast64_t freshVariableCounter; // The types managed by this manager. - mutable std::unordered_set<Type> types; - + mutable boost::optional<Type> booleanType; + mutable boost::optional<Type> integerType; + mutable std::unordered_set<Type> bitvectorTypes; + mutable boost::optional<Type> rationalType; + // A mask that can be used to query whether a variable is an auxiliary variable. static const uint64_t auxiliaryMask = (1ull << 50); diff --git a/src/storm/storage/expressions/ToCppVisitor.cpp b/src/storm/storage/expressions/ToCppVisitor.cpp index 717317d0e..d336d0d40 100644 --- a/src/storm/storage/expressions/ToCppVisitor.cpp +++ b/src/storm/storage/expressions/ToCppVisitor.cpp @@ -2,6 +2,11 @@ #include "storm/storage/expressions/Expressions.h" +#include "storm/adapters/CarlAdapter.h" + +#include "storm/utility/macros.h" +#include "storm/exceptions/NotSupportedException.h" + namespace storm { namespace expressions { @@ -251,6 +256,7 @@ namespace storm { } boost::any ToCppVisitor::visit(UnaryNumericalFunctionExpression const& expression, boost::any const& data) { + ToCppTranslationOptions const& options = boost::any_cast<ToCppTranslationOptions const&>(data); switch (expression.getOperatorType()) { case UnaryNumericalFunctionExpression::OperatorType::Minus: stream << "-("; @@ -258,12 +264,24 @@ namespace storm { stream << ")"; break; case UnaryNumericalFunctionExpression::OperatorType::Floor: - stream << "std::floor("; + STORM_LOG_THROW(options.getMode() != ToCppTranslationMode::CastRationalFunction, storm::exceptions::NotSupportedException, "Floor is not supported by rational functions."); + if (options.getMode() != ToCppTranslationMode::CastRationalNumber) { + stream << "std::floor"; + } else { + stream << "carl::floor"; + } + stream << "("; expression.getOperand()->accept(*this, data); stream << ")"; break; case UnaryNumericalFunctionExpression::OperatorType::Ceil: - stream << "std::ceil("; + STORM_LOG_THROW(options.getMode() != ToCppTranslationMode::CastRationalFunction, storm::exceptions::NotSupportedException, "Ceil is not supported by rational functions."); + if (options.getMode() != ToCppTranslationMode::CastRationalNumber) { + stream << "std::ceil"; + } else { + stream << "carl::ceil"; + } + stream << "("; expression.getOperand()->accept(*this, data); stream << ")"; break; @@ -299,7 +317,7 @@ namespace storm { ToCppTranslationOptions const& options = boost::any_cast<ToCppTranslationOptions const&>(data); switch (options.getMode()) { case ToCppTranslationMode::KeepType: - stream << expression.getValue(); + stream << "(static_cast<double>(" << carl::getNum(expression.getValue()) << ")/" << carl::getDenom(expression.getValue()) << ")"; break; case ToCppTranslationMode::CastDouble: stream << "static_cast<double>(" << expression.getValueAsDouble() << ")"; diff --git a/src/storm/storage/expressions/ToExprtkStringVisitor.cpp b/src/storm/storage/expressions/ToExprtkStringVisitor.cpp index fe46e8ca5..e0326dd09 100644 --- a/src/storm/storage/expressions/ToExprtkStringVisitor.cpp +++ b/src/storm/storage/expressions/ToExprtkStringVisitor.cpp @@ -213,7 +213,7 @@ namespace storm { } boost::any ToExprtkStringVisitor::visit(RationalLiteralExpression const& expression, boost::any const&) { - stream << expression.getValue(); + stream << "(" << expression.getValue() << ")"; return boost::any(); } } diff --git a/src/storm/storage/expressions/ToRationalFunctionVisitor.cpp b/src/storm/storage/expressions/ToRationalFunctionVisitor.cpp index 9dff8b060..9f8ab16ec 100644 --- a/src/storm/storage/expressions/ToRationalFunctionVisitor.cpp +++ b/src/storm/storage/expressions/ToRationalFunctionVisitor.cpp @@ -68,6 +68,11 @@ namespace storm { template<typename RationalFunctionType> boost::any ToRationalFunctionVisitor<RationalFunctionType>::visit(VariableExpression const& expression, boost::any const&) { + auto valueIt = valueMapping.find(expression.getVariable()); + if (valueIt != valueMapping.end()) { + return valueIt->second; + } + auto variablePair = variableToVariableMap.find(expression.getVariable()); if (variablePair != variableToVariableMap.end()) { return convertVariableToPolynomial(variablePair->second); @@ -95,13 +100,18 @@ namespace storm { template<typename RationalFunctionType> boost::any ToRationalFunctionVisitor<RationalFunctionType>::visit(IntegerLiteralExpression const& expression, boost::any const&) { - return RationalFunctionType(carl::rationalize<storm::RationalNumber>(static_cast<size_t>(expression.getValue()))); + return RationalFunctionType(storm::utility::convertNumber<storm::RationalFunction>(expression.getValue())); } template<typename RationalFunctionType> boost::any ToRationalFunctionVisitor<RationalFunctionType>::visit(RationalLiteralExpression const& expression, boost::any const&) { return storm::utility::convertNumber<storm::RationalFunction>(expression.getValue()); } + + template<typename RationalFunctionType> + void ToRationalFunctionVisitor<RationalFunctionType>::setMapping(storm::expressions::Variable const& variable, RationalFunctionType const& value) { + valueMapping[variable] = value; + } template class ToRationalFunctionVisitor<storm::RationalFunction>; #endif diff --git a/src/storm/storage/expressions/ToRationalFunctionVisitor.h b/src/storm/storage/expressions/ToRationalFunctionVisitor.h index 44696f940..7c7cfacf5 100644 --- a/src/storm/storage/expressions/ToRationalFunctionVisitor.h +++ b/src/storm/storage/expressions/ToRationalFunctionVisitor.h @@ -1,7 +1,10 @@ #ifndef STORM_STORAGE_EXPRESSIONS_TORATIONALFUNCTIONVISITOR_H_ #define STORM_STORAGE_EXPRESSIONS_TORATIONALFUNCTIONVISITOR_H_ +#include <unordered_map> + #include "storm/adapters/CarlAdapter.h" + #include "storm/storage/expressions/Expression.h" #include "storm/storage/expressions/Expressions.h" #include "storm/storage/expressions/ExpressionVisitor.h" @@ -29,6 +32,8 @@ namespace storm { virtual boost::any visit(IntegerLiteralExpression const& expression, boost::any const& data) override; virtual boost::any visit(RationalLiteralExpression const& expression, boost::any const& data) override; + void setMapping(storm::expressions::Variable const& variable, RationalFunctionType const& value); + private: template<typename TP = typename RationalFunctionType::PolyType, carl::EnableIf<carl::needs_cache<TP>> = carl::dummy> RationalFunctionType convertVariableToPolynomial(carl::Variable const& variable) { @@ -45,6 +50,9 @@ namespace storm { // The cache that is used in case the underlying type needs a cache. std::shared_ptr<carl::Cache<carl::PolynomialFactorizationPair<RawPolynomial>>> cache; + + // A mapping from variables to their values. + std::unordered_map<storm::expressions::Variable, RationalFunctionType> valueMapping; }; #endif } diff --git a/src/storm/storage/expressions/ToRationalNumberVisitor.cpp b/src/storm/storage/expressions/ToRationalNumberVisitor.cpp index 4ff7db433..d4ba17c06 100644 --- a/src/storm/storage/expressions/ToRationalNumberVisitor.cpp +++ b/src/storm/storage/expressions/ToRationalNumberVisitor.cpp @@ -68,8 +68,8 @@ namespace storm { } template<typename RationalNumberType> - boost::any ToRationalNumberVisitor<RationalNumberType>::visit(VariableExpression const&, boost::any const&) { - STORM_LOG_THROW(false, storm::exceptions::InvalidArgumentException, "Cannot transform expressions containing variables to a rational number."); + boost::any ToRationalNumberVisitor<RationalNumberType>::visit(VariableExpression const& expression, boost::any const&) { + return valueMapping.at(expression.getVariable()); } template<typename RationalNumberType> @@ -78,8 +78,13 @@ namespace storm { } template<typename RationalNumberType> - boost::any ToRationalNumberVisitor<RationalNumberType>::visit(UnaryNumericalFunctionExpression const&, boost::any const& ) { - STORM_LOG_THROW(false, storm::exceptions::InvalidArgumentException, "Expression cannot be translated into a rational number."); + boost::any ToRationalNumberVisitor<RationalNumberType>::visit(UnaryNumericalFunctionExpression const& expression, boost::any const& data) { + RationalNumberType operandAsRationalNumber = boost::any_cast<RationalNumberType>(expression.getOperand()->accept(*this, data)); + switch (expression.getOperatorType()) { + case UnaryNumericalFunctionExpression::OperatorType::Minus: return -operandAsRationalNumber; + case UnaryNumericalFunctionExpression::OperatorType::Floor: return storm::utility::floor(operandAsRationalNumber); + case UnaryNumericalFunctionExpression::OperatorType::Ceil: return storm::utility::ceil(operandAsRationalNumber); + } } template<typename RationalNumberType> @@ -107,6 +112,11 @@ namespace storm { #endif } + template<typename RationalNumberType> + void ToRationalNumberVisitor<RationalNumberType>::setMapping(storm::expressions::Variable const& variable, RationalNumberType const& value) { + valueMapping[variable] = value; + } + #ifdef STORM_HAVE_CARL template class ToRationalNumberVisitor<storm::RationalNumber>; #endif diff --git a/src/storm/storage/expressions/ToRationalNumberVisitor.h b/src/storm/storage/expressions/ToRationalNumberVisitor.h index c6badc7b1..6177fd2ae 100644 --- a/src/storm/storage/expressions/ToRationalNumberVisitor.h +++ b/src/storm/storage/expressions/ToRationalNumberVisitor.h @@ -1,6 +1,9 @@ #pragma once +#include <unordered_map> + #include "storm/adapters/CarlAdapter.h" + #include "storm/storage/expressions/Expression.h" #include "storm/storage/expressions/Expressions.h" #include "storm/storage/expressions/ExpressionVisitor.h" @@ -26,6 +29,11 @@ namespace storm { virtual boost::any visit(BooleanLiteralExpression const& expression, boost::any const& data) override; virtual boost::any visit(IntegerLiteralExpression const& expression, boost::any const& data) override; virtual boost::any visit(RationalLiteralExpression const& expression, boost::any const& data) override; + + void setMapping(storm::expressions::Variable const& variable, RationalNumberType const& value); + + private: + std::unordered_map<storm::expressions::Variable, RationalNumberType> valueMapping; }; } } diff --git a/src/storm/storage/jani/Model.cpp b/src/storm/storage/jani/Model.cpp index 7b1c6e908..e02bac355 100644 --- a/src/storm/storage/jani/Model.cpp +++ b/src/storm/storage/jani/Model.cpp @@ -998,7 +998,12 @@ namespace storm { for (auto const& location : automaton.get().getLocations()) { for (auto const& assignment : location.getAssignments().getTransientAssignments()) { if (assignment.getExpressionVariable() == transientVariable.getExpressionVariable()) { - auto newExpression = (locationVariable == this->getManager().integer(automaton.get().getLocationIndex(location.getName()))) && (negate ? !assignment.getAssignedExpression() : assignment.getAssignedExpression()); + storm::expressions::Expression newExpression; + if (automaton.get().getNumberOfLocations() <= 1) { + newExpression = (negate ? !assignment.getAssignedExpression() : assignment.getAssignedExpression()); + } else { + newExpression = (locationVariable == this->getManager().integer(automaton.get().getLocationIndex(location.getName()))) && (negate ? !assignment.getAssignedExpression() : assignment.getAssignedExpression()); + } if (result.isInitialized()) { result = result || newExpression; } else { diff --git a/src/storm/storage/jani/Property.cpp b/src/storm/storage/jani/Property.cpp index 896810526..e46d2ee50 100644 --- a/src/storm/storage/jani/Property.cpp +++ b/src/storm/storage/jani/Property.cpp @@ -32,6 +32,10 @@ namespace storm { return Property(name, filterExpression.substitute(substitution), comment); } + Property Property::substituteLabels(std::map<std::string, std::string> const& substitution) const { + return Property(name, filterExpression.substituteLabels(substitution), comment); + } + FilterExpression const& Property::getFilter() const { return this->filterExpression; } diff --git a/src/storm/storage/jani/Property.h b/src/storm/storage/jani/Property.h index 9d28d715a..52db07fef 100644 --- a/src/storm/storage/jani/Property.h +++ b/src/storm/storage/jani/Property.h @@ -28,8 +28,9 @@ namespace storm { class FilterExpression { public: - explicit FilterExpression(std::shared_ptr<storm::logic::Formula const> formula, storm::modelchecker::FilterType ft = storm::modelchecker::FilterType::VALUES) : formula(formula), ft(ft) {} + FilterExpression() = default; + explicit FilterExpression(std::shared_ptr<storm::logic::Formula const> formula, storm::modelchecker::FilterType ft = storm::modelchecker::FilterType::VALUES) : formula(formula), ft(ft) {} std::shared_ptr<storm::logic::Formula const> const& getFormula() const { return formula; @@ -42,6 +43,11 @@ namespace storm { FilterExpression substitute(std::map<storm::expressions::Variable, storm::expressions::Expression> const& substitution) const { return FilterExpression(formula->substitute(substitution), ft); } + + FilterExpression substituteLabels(std::map<std::string, std::string> const& labelSubstitution) const { + return FilterExpression(formula->substitute(labelSubstitution), ft); + } + private: // For now, we assume that the states are always the initial states. std::shared_ptr<storm::logic::Formula const> formula; @@ -55,6 +61,8 @@ namespace storm { class Property { public: + Property() = default; + /** * Constructs the property * @param name the name @@ -84,6 +92,7 @@ namespace storm { std::string const& getComment() const; Property substitute(std::map<storm::expressions::Variable, storm::expressions::Expression> const& substitution) const; + Property substituteLabels(std::map<std::string, std::string> const& labelSubstitution) const; FilterExpression const& getFilter() const; diff --git a/src/storm/storage/prism/Program.cpp b/src/storm/storage/prism/Program.cpp index c521d9c29..b96a1c7d2 100644 --- a/src/storm/storage/prism/Program.cpp +++ b/src/storm/storage/prism/Program.cpp @@ -5,6 +5,7 @@ #include <boost/algorithm/string/join.hpp> #include "storm/storage/jani/Model.h" +#include "storm/storage/jani/Property.h" #include "storm/storage/expressions/ExpressionManager.h" #include "storm/settings/SettingsManager.h" @@ -1009,7 +1010,6 @@ namespace storm { std::set<storm::expressions::Variable> variablesAndConstants; std::set_union(variables.begin(), variables.end(), constants.begin(), constants.end(), std::inserter(variablesAndConstants, variablesAndConstants.begin())); - // Check the commands of the modules. bool hasProbabilisticCommand = false; bool hasMarkovianCommand = false; @@ -1627,9 +1627,17 @@ namespace storm { storm::jani::Model Program::toJani(bool allVariablesGlobal) const { ToJaniConverter converter; - return converter.convert(*this, allVariablesGlobal); + storm::jani::Model resultingModel = converter.convert(*this, allVariablesGlobal); + STORM_LOG_WARN_COND(!converter.labelsWereRenamed(), "Labels were renamed in PRISM-to-JANI conversion, but the mapping is not stored."); + return resultingModel; } - + + std::pair<storm::jani::Model, std::map<std::string, std::string>> Program::toJaniWithLabelRenaming(bool allVariablesGlobal) const { + ToJaniConverter converter; + storm::jani::Model resultingModel = converter.convert(*this, allVariablesGlobal); + return std::make_pair(resultingModel, converter.getLabelRenaming()); + } + storm::expressions::ExpressionManager& Program::getManager() const { return *this->manager; } diff --git a/src/storm/storage/prism/Program.h b/src/storm/storage/prism/Program.h index a33484833..ccf56ead6 100644 --- a/src/storm/storage/prism/Program.h +++ b/src/storm/storage/prism/Program.h @@ -22,6 +22,7 @@ namespace storm { namespace jani { class Model; + class Property; } namespace prism { @@ -587,6 +588,12 @@ namespace storm { */ storm::jani::Model toJani(bool allVariablesGlobal = false) const; + /*! + * Converts the PRISM model into an equivalent JANI model and retrieves possible label renamings that had + * to be performed in the process. + */ + std::pair<storm::jani::Model, std::map<std::string, std::string>> toJaniWithLabelRenaming(bool allVariablesGlobal = false) const; + private: /*! * This function builds a command that corresponds to the synchronization of the given list of commands. diff --git a/src/storm/storage/prism/ToJaniConverter.cpp b/src/storm/storage/prism/ToJaniConverter.cpp index a544c9d83..21a806374 100644 --- a/src/storm/storage/prism/ToJaniConverter.cpp +++ b/src/storm/storage/prism/ToJaniConverter.cpp @@ -12,7 +12,7 @@ namespace storm { namespace prism { - storm::jani::Model ToJaniConverter::convert(storm::prism::Program const& program, bool allVariablesGlobal) const { + storm::jani::Model ToJaniConverter::convert(storm::prism::Program const& program, bool allVariablesGlobal) { std::shared_ptr<storm::expressions::ExpressionManager> manager = program.getManager().getSharedPointer(); // Start by creating an empty JANI model. @@ -94,10 +94,23 @@ namespace storm { } } + // Go through the labels and construct assignments to transient variables that are added to the loctions. + std::vector<storm::jani::Assignment> transientLocationAssignments; + for (auto const& label : program.getLabels()) { + bool renameLabel = manager->hasVariable(label.getName()) || program.hasRewardModel(label.getName()); + std::string finalLabelName = renameLabel ? "label_" + label.getName() : label.getName(); + if (renameLabel) { + STORM_LOG_WARN_COND(!renameLabel, "Label '" << label.getName() << "' was renamed to '" << finalLabelName << "' in PRISM-to-JANI conversion, as another variable with that name already exists."); + labelRenaming[label.getName()] = finalLabelName; + } + auto newExpressionVariable = manager->declareBooleanVariable(finalLabelName); + storm::jani::BooleanVariable const& newTransientVariable = janiModel.addVariable(storm::jani::BooleanVariable(newExpressionVariable.getName(), newExpressionVariable, manager->boolean(false), true)); + transientLocationAssignments.emplace_back(newTransientVariable, label.getStatePredicateExpression()); + } + // Go through the reward models and construct assignments to the transient variables that are to be added to // edges and transient assignments that are added to the locations. std::map<uint_fast64_t, std::vector<storm::jani::Assignment>> transientEdgeAssignments; - std::vector<storm::jani::Assignment> transientLocationAssignments; for (auto const& rewardModel : program.getRewardModels()) { auto newExpressionVariable = manager->declareRationalVariable(rewardModel.getName().empty() ? "default" : rewardModel.getName()); storm::jani::RealVariable const& newTransientVariable = janiModel.addVariable(storm::jani::RealVariable(rewardModel.getName().empty() ? "default" : rewardModel.getName(), newExpressionVariable, manager->rational(0.0), true)); @@ -141,6 +154,7 @@ namespace storm { // Now create the separate JANI automata from the modules of the PRISM program. While doing so, we use the // previously built mapping to make variables global that are read by more than one module. + std::set<uint64_t> firstModules; bool firstModule = true; for (auto const& module : program.getModules()) { // Keep track of the action indices contained in this module. @@ -179,7 +193,7 @@ namespace storm { uint64_t onlyLocationIndex = automaton.addLocation(storm::jani::Location("l")); automaton.addInitialLocation(onlyLocationIndex); - // If we are translating the first module, we need to add the transient assignments to the location. + // If we are translating the first module that has the action, we need to add the transient assignments to the location. if (firstModule) { storm::jani::Location& onlyLocation = automaton.getLocation(onlyLocationIndex); for (auto const& assignment : transientLocationAssignments) { @@ -189,7 +203,7 @@ namespace storm { for (auto const& command : module.getCommands()) { std::shared_ptr<storm::jani::TemplateEdge> templateEdge = automaton.createTemplateEdge(command.getGuardExpression()); - actionIndicesOfModule.insert(command.getActionIndex()); + actionIndicesOfModule.insert(janiModel.getActionIndex(command.getActionName())); boost::optional<storm::expressions::Expression> rateExpression; if (program.getModelType() == Program::ModelType::CTMC || program.getModelType() == Program::ModelType::CTMDP || (program.getModelType() == Program::ModelType::MA && command.isMarkovian())) { @@ -226,7 +240,6 @@ namespace storm { for (auto const& assignment : transientEdgeAssignmentsToAdd->second) { templateEdge->addTransientAssignment(assignment); } - transientEdgeAssignments.erase(transientEdgeAssignmentsToAdd); } // Create the edge object. @@ -276,5 +289,13 @@ namespace storm { return janiModel; } + bool ToJaniConverter::labelsWereRenamed() const { + return !labelRenaming.empty(); + } + + std::map<std::string, std::string> const& ToJaniConverter::getLabelRenaming() const { + return labelRenaming; + } + } } diff --git a/src/storm/storage/prism/ToJaniConverter.h b/src/storm/storage/prism/ToJaniConverter.h index bc32a3dd8..2ab5c0509 100644 --- a/src/storm/storage/prism/ToJaniConverter.h +++ b/src/storm/storage/prism/ToJaniConverter.h @@ -1,5 +1,8 @@ #pragma once +#include <map> +#include <string> + namespace storm { namespace jani { class Model; @@ -11,7 +14,13 @@ namespace storm { class ToJaniConverter { public: - storm::jani::Model convert(storm::prism::Program const& program, bool allVariablesGlobal = false) const; + storm::jani::Model convert(storm::prism::Program const& program, bool allVariablesGlobal = false); + + bool labelsWereRenamed() const; + std::map<std::string, std::string> const& getLabelRenaming() const; + + private: + std::map<std::string, std::string> labelRenaming; }; } diff --git a/src/storm/storm.cpp b/src/storm/storm.cpp index 7ce7611dc..20126f488 100644 --- a/src/storm/storm.cpp +++ b/src/storm/storm.cpp @@ -32,7 +32,7 @@ int main(const int argc, const char** argv) { totalTimer.stop(); if (storm::settings::getModule<storm::settings::modules::ResourceSettings>().isPrintTimeAndMemorySet()) { - storm::cli::showTimeAndMemoryStatistics(totalTimer.getTimeMilliseconds()); + storm::cli::showTimeAndMemoryStatistics(totalTimer.getTimeInMilliseconds()); } return 0; } catch (storm::exceptions::BaseException const& exception) { diff --git a/src/storm/utility/Stopwatch.cpp b/src/storm/utility/Stopwatch.cpp new file mode 100644 index 000000000..faefdb472 --- /dev/null +++ b/src/storm/utility/Stopwatch.cpp @@ -0,0 +1,51 @@ +#include "storm/utility/Stopwatch.h" + +namespace storm { + namespace utility { + + Stopwatch::Stopwatch(bool startNow) : accumulatedTime(std::chrono::nanoseconds::zero()), stopped(true), startOfCurrentMeasurement(std::chrono::nanoseconds::zero()) { + if (startNow) { + start(); + } + } + + Stopwatch::SecondType Stopwatch::getTimeInSeconds() const { + return std::chrono::duration_cast<std::chrono::seconds>(accumulatedTime).count(); + } + + Stopwatch::MilisecondType Stopwatch::getTimeInMilliseconds() const { + return std::chrono::duration_cast<std::chrono::milliseconds>(accumulatedTime).count(); + } + + Stopwatch::NanosecondType Stopwatch::getTimeInNanoseconds() const { + return accumulatedTime.count(); + } + + void Stopwatch::addToTime(std::chrono::nanoseconds timeNanoseconds) { + accumulatedTime += timeNanoseconds; + } + + void Stopwatch::stop() { + STORM_LOG_WARN_COND(!stopped, "Stopwatch is already paused."); + stopped = true; + accumulatedTime += std::chrono::high_resolution_clock::now() - startOfCurrentMeasurement; + } + + void Stopwatch::start() { + STORM_LOG_WARN_COND(stopped, "Stopwatch is already running."); + stopped = false; + startOfCurrentMeasurement = std::chrono::high_resolution_clock::now(); + } + + void Stopwatch::reset() { + accumulatedTime = std::chrono::nanoseconds::zero(); + stopped = true; + } + + std::ostream& operator<<(std::ostream& out, Stopwatch const& stopwatch) { + out << stopwatch.getTimeInSeconds() << "." << std::setw(3) << std::setfill('0') << (stopwatch.getTimeInMilliseconds() % 1000) << "s"; + return out; + } + + } +} diff --git a/src/storm/utility/Stopwatch.h b/src/storm/utility/Stopwatch.h index a30b40683..4f81ea8a8 100644 --- a/src/storm/utility/Stopwatch.h +++ b/src/storm/utility/Stopwatch.h @@ -13,106 +13,68 @@ namespace storm { */ class Stopwatch { public: - + typedef decltype(std::chrono::duration_cast<std::chrono::seconds>(std::chrono::seconds::zero()).count()) SecondType; + typedef decltype(std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::milliseconds::zero()).count()) MilisecondType; + typedef decltype(std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::nanoseconds::zero()).count()) NanosecondType; + /*! * Constructor. * * @param startNow If true, the stopwatch starts right away. */ - Stopwatch(bool startNow = false) : accumulatedTime(std::chrono::nanoseconds::zero()), stopped(true), startOfCurrentMeasurement(std::chrono::nanoseconds::zero()) { - if (startNow) { - start(); - } - } - - /*! - * Destructor. - */ - ~Stopwatch() = default; + Stopwatch(bool startNow = false); /*! - * Get measured time in seconds. - * - * @return seconds as floating point number. + * Gets the measured time in seconds. */ - double getTimeSeconds() const { - return std::chrono::duration<float>(accumulatedTime).count(); - } + SecondType getTimeInSeconds() const; /*! - * Get measured time in milliseconds. - * - * @return Milliseconds. + * Gets the measured time in milliseconds. */ - unsigned long long int getTimeMilliseconds() const { - return std::chrono::duration_cast<std::chrono::milliseconds>(accumulatedTime).count(); - } + MilisecondType getTimeInMilliseconds() const; /*! - * Get measured time in nanoseconds. - * - * @return Nanoseconds. + * Gets the measured time in nanoseconds. */ - unsigned long long int getTimeNanoseconds() const { - return accumulatedTime.count(); - } + NanosecondType getTimeInNanoseconds() const; /*! * Add given time to measured time. * * @param timeNanoseconds Additional time in nanoseconds. */ - void addToTime(std::chrono::nanoseconds timeNanoseconds) { - accumulatedTime += timeNanoseconds; - } + void addToTime(std::chrono::nanoseconds timeNanoseconds); /*! * Stop stopwatch and add measured time to total time. */ - void stop() { - if (stopped) { - // Assertions are only available in DEBUG build and therefore not used here. - STORM_LOG_WARN("Stopwatch is already paused."); - } - stopped = true; - accumulatedTime += std::chrono::high_resolution_clock::now() - startOfCurrentMeasurement; - } + void stop(); /*! * Start stopwatch (again) and start measuring time. */ - void start() { - if (!stopped) { - // Assertions are only available in DEBUG build and therefore not used here. - STORM_LOG_WARN("Stopwatch is already running."); - } - stopped = false; - startOfCurrentMeasurement = std::chrono::high_resolution_clock::now(); - } + void start(); /*! - * Reset the stopwatch. Reset the measured time to zero and stop the stopwatch. + * Reset the stopwatch. */ - void reset() { - accumulatedTime = std::chrono::nanoseconds::zero(); - stopped = true; - } + void reset(); - friend std::ostream& operator<<(std::ostream& out, Stopwatch const& stopwatch) { - out << stopwatch.getTimeSeconds(); - return out; - } - + friend std::ostream& operator<<(std::ostream& out, Stopwatch const& stopwatch); private: - // Total measured time + // The time accumulated so far. std::chrono::nanoseconds accumulatedTime; - // Flag indicating if the stopwatch is stopped right now. + + // A flag indicating if the stopwatch is stopped right now. bool stopped; - // Timepoint when the stopwatch was started the last time. - std::chrono::high_resolution_clock::time_point startOfCurrentMeasurement; + // The timepoint when the stopwatch was started the last time (if it's not stopped). + std::chrono::high_resolution_clock::time_point startOfCurrentMeasurement; }; + + std::ostream& operator<<(std::ostream& out, Stopwatch const& stopwatch); } } diff --git a/src/storm/utility/cli.cpp b/src/storm/utility/cli.cpp index b8da7a264..d7606149b 100644 --- a/src/storm/utility/cli.cpp +++ b/src/storm/utility/cli.cpp @@ -36,7 +36,11 @@ namespace storm { STORM_LOG_THROW(definedConstants.find(variable) == definedConstants.end(), storm::exceptions::WrongFormatException, "Illegally trying to define constant '" << constantName <<"' twice."); definedConstants.insert(variable); - if (variable.hasBooleanType()) { + if (manager.hasVariable(value)) { + auto const& valueVariable = manager.getVariable(value); + STORM_LOG_THROW(variable.getType() == valueVariable.getType(), storm::exceptions::WrongFormatException, "Illegally trying to define constant '" << constantName << "' by constant '" << valueVariable.getName() << " of different type."); + constantDefinitions[variable] = valueVariable.getExpression(); + } else if (variable.hasBooleanType()) { if (value == "true") { constantDefinitions[variable] = manager.boolean(true); } else if (value == "false") { diff --git a/src/storm/utility/constants.cpp b/src/storm/utility/constants.cpp index d5cf20a46..7eeae8106 100644 --- a/src/storm/utility/constants.cpp +++ b/src/storm/utility/constants.cpp @@ -195,6 +195,16 @@ namespace storm { return std::fabs(number); } + template<typename ValueType> + ValueType floor(ValueType const& number) { + return std::floor(number); + } + + template<typename ValueType> + ValueType ceil(ValueType const& number) { + return std::ceil(number); + } + template<> std::pair<storm::RationalFunction, storm::RationalFunction> minmax(std::vector<storm::RationalFunction> const&) { STORM_LOG_THROW(false, storm::exceptions::InvalidArgumentException, "Minimum/maximum for rational functions is not defined."); @@ -347,11 +357,23 @@ namespace storm { return carl::rationalize<RationalNumber>(static_cast<carl::uint>(number)); } + template<> + RationalNumber convertNumber(int_fast64_t const& number){ + STORM_LOG_ASSERT(static_cast<carl::sint>(number) == number, "Rationalizing failed, because the number is too large."); + return carl::rationalize<RationalNumber>(static_cast<carl::sint>(number)); + } + template<> RationalFunction convertNumber(double const& number){ return RationalFunction(carl::rationalize<RationalNumber>(number)); } + template<> + RationalFunction convertNumber(int_fast64_t const& number){ + STORM_LOG_ASSERT(static_cast<carl::sint>(number) == number, "Rationalizing failed, because the number is too large."); + return RationalFunction(carl::rationalize<RationalNumber>(static_cast<carl::uint>(number))); + } + template<> RationalNumber convertNumber(std::string const& number) { return carl::rationalize<RationalNumber>(number); @@ -376,7 +398,17 @@ namespace storm { RationalNumber abs(storm::RationalNumber const& number) { return carl::abs(number); } - + + template<> + RationalNumber floor(storm::RationalNumber const& number) { + return carl::floor(number); + } + + template<> + RationalNumber ceil(storm::RationalNumber const& number) { + return carl::ceil(number); + } + template<> RationalNumber pow(RationalNumber const& value, uint_fast64_t exponent) { return carl::pow(value, exponent); @@ -502,15 +534,13 @@ namespace storm { template std::pair<double, double> minmax(std::map<uint64_t, double> const&); template double minimum(std::map<uint64_t, double> const&); template double maximum(std::map<uint64_t, double> const&); - + +#ifdef STORM_HAVE_CARL + // Instantiations for rational number. template std::pair<storm::RationalNumber, storm::RationalNumber> minmax(std::map<uint64_t, storm::RationalNumber> const&); template storm::RationalNumber minimum(std::map<uint64_t, storm::RationalNumber> const&); template storm::RationalNumber maximum(std::map<uint64_t, storm::RationalNumber> const&); - template storm::RationalFunction minimum(std::map<uint64_t, storm::RationalFunction> const&); - template storm::RationalFunction maximum(std::map<uint64_t, storm::RationalFunction> const&); -#ifdef STORM_HAVE_CARL - // Instantiations for rational number. template bool isOne(storm::RationalNumber const& value); template bool isZero(storm::RationalNumber const& value); template bool isConstant(storm::RationalNumber const& value); @@ -526,8 +556,9 @@ namespace storm { RationalNumber convertNumber(std::string const& number); template storm::RationalNumber sqrt(storm::RationalNumber const& number); - template storm::RationalNumber abs(storm::RationalNumber const& number); + template storm::RationalNumber floor(storm::RationalNumber const& number); + template storm::RationalNumber ceil(storm::RationalNumber const& number); template storm::RationalNumber pow(storm::RationalNumber const& value, uint_fast64_t exponent); @@ -561,6 +592,9 @@ namespace storm { template Interval one(); template Interval zero(); + + template storm::RationalFunction minimum(std::map<uint64_t, storm::RationalFunction> const&); + template storm::RationalFunction maximum(std::map<uint64_t, storm::RationalFunction> const&); template storm::storage::MatrixEntry<storm::storage::sparse::state_type, RationalFunction> simplify(storm::storage::MatrixEntry<storm::storage::sparse::state_type, RationalFunction> matrixEntry); template storm::storage::MatrixEntry<storm::storage::sparse::state_type, RationalFunction>& simplify(storm::storage::MatrixEntry<storm::storage::sparse::state_type, RationalFunction>& matrixEntry); diff --git a/src/storm/utility/constants.h b/src/storm/utility/constants.h index e8bd62de0..26259d98b 100644 --- a/src/storm/utility/constants.h +++ b/src/storm/utility/constants.h @@ -85,7 +85,13 @@ namespace storm { template<typename ValueType> ValueType abs(ValueType const& number); - + + template<typename ValueType> + ValueType floor(ValueType const& number); + + template<typename ValueType> + ValueType ceil(ValueType const& number); + template<typename ValueType> bool isInteger(ValueType const& number); diff --git a/src/storm/utility/storm.cpp b/src/storm/utility/storm.cpp index 8ad4283b1..1023d6aa6 100644 --- a/src/storm/utility/storm.cpp +++ b/src/storm/utility/storm.cpp @@ -75,7 +75,7 @@ namespace storm{ } std::vector<storm::jani::Property> parsePropertiesForPrismProgram(std::string const& inputString, storm::prism::Program const& program, boost::optional<std::set<std::string>> const& propertyFilter) { - storm::parser::FormulaParser formulaParser(program.getManager().getSharedPointer()); + storm::parser::FormulaParser formulaParser(program); auto formulas = parseProperties(formulaParser, inputString, propertyFilter); return substituteConstantsInProperties(formulas, program.getConstantsSubstitution()); } diff --git a/src/storm/utility/storm.h b/src/storm/utility/storm.h index 46fcfdb67..7e81f2a36 100644 --- a/src/storm/utility/storm.h +++ b/src/storm/utility/storm.h @@ -96,7 +96,7 @@ #include "storm/exceptions/NotImplementedException.h" #include "storm/exceptions/NotSupportedException.h" -#include "storm/storage/jani/JSONExporter.h" +#include "storm/utility/Stopwatch.h" namespace storm { @@ -231,7 +231,11 @@ namespace storm { template<typename ModelType> std::shared_ptr<storm::models::ModelBase> preprocessModel(std::shared_ptr<storm::models::ModelBase> model, std::vector<std::shared_ptr<storm::logic::Formula const>> const& formulas) { + storm::utility::Stopwatch preprocessingWatch(true); + + bool operationPerformed = false; if (model->getType() == storm::models::ModelType::MarkovAutomaton && model->isSparseModel()) { + operationPerformed = true; std::shared_ptr<storm::models::sparse::MarkovAutomaton<typename ModelType::ValueType>> ma = model->template as<storm::models::sparse::MarkovAutomaton<typename ModelType::ValueType>>(); ma->close(); if (ma->hasOnlyTrivialNondeterminism()) { @@ -241,6 +245,7 @@ namespace storm { } if (model->isSparseModel() && storm::settings::getModule<storm::settings::modules::GeneralSettings>().isBisimulationSet()) { + operationPerformed = true; storm::storage::BisimulationType bisimType = storm::storage::BisimulationType::Strong; if (storm::settings::getModule<storm::settings::modules::BisimulationSettings>().isWeakBisimulationSet()) { bisimType = storm::storage::BisimulationType::Weak; @@ -250,6 +255,11 @@ namespace storm { return performBisimulationMinimization<ModelType>(model->template as<storm::models::sparse::Model<typename ModelType::ValueType>>(), formulas, bisimType); } + preprocessingWatch.stop(); + if (operationPerformed) { + STORM_PRINT_AND_LOG(std::endl << "Time for model preprocessing: " << preprocessingWatch << "." << std::endl << std::endl); + } + return model; } @@ -300,17 +310,17 @@ namespace storm { switch(storm::settings::getModule<storm::settings::modules::CoreSettings>().getEngine()) { case storm::settings::modules::CoreSettings::Engine::Sparse: { std::shared_ptr<storm::models::sparse::Model<ValueType>> sparseModel = model->template as<storm::models::sparse::Model<ValueType>>(); - STORM_LOG_THROW(sparseModel != nullptr, storm::exceptions::InvalidArgumentException, "Sparse engine requires a sparse input model"); + STORM_LOG_THROW(sparseModel != nullptr, storm::exceptions::InvalidArgumentException, "Sparse engine requires a sparse input model."); return (sparseModel, formula, onlyInitialStatesRelevant); } case storm::settings::modules::CoreSettings::Engine::Hybrid: { std::shared_ptr<storm::models::symbolic::Model<DdType>> ddModel = model->template as<storm::models::symbolic::Model<DdType>>(); - STORM_LOG_THROW(ddModel != nullptr, storm::exceptions::InvalidArgumentException, "Hybrid engine requires a dd input model"); + STORM_LOG_THROW(ddModel != nullptr, storm::exceptions::InvalidArgumentException, "Hybrid engine requires a DD-based input model."); return verifySymbolicModelWithHybridEngine(ddModel, formula, onlyInitialStatesRelevant); } case storm::settings::modules::CoreSettings::Engine::Dd: { std::shared_ptr<storm::models::symbolic::Model<DdType>> ddModel = model->template as<storm::models::symbolic::Model<DdType>>(); - STORM_LOG_THROW(ddModel != nullptr, storm::exceptions::InvalidArgumentException, "Dd engine requires a dd input model"); + STORM_LOG_THROW(ddModel != nullptr, storm::exceptions::InvalidArgumentException, "Dd engine requires a DD-based input model."); return verifySymbolicModelWithDdEngine(ddModel, formula, onlyInitialStatesRelevant); } default: { diff --git a/src/test/modelchecker/SymbolicDtmcPrctlModelCheckerTest.cpp b/src/test/modelchecker/SymbolicDtmcPrctlModelCheckerTest.cpp index 7a2be484b..e9819a2c7 100644 --- a/src/test/modelchecker/SymbolicDtmcPrctlModelCheckerTest.cpp +++ b/src/test/modelchecker/SymbolicDtmcPrctlModelCheckerTest.cpp @@ -76,8 +76,8 @@ TEST(SymbolicDtmcPrctlModelCheckerTest, Die_Cudd) { result->filter(storm::modelchecker::SymbolicQualitativeCheckResult<storm::dd::DdType::CUDD>(model->getReachableStates(), model->getInitialStates())); storm::modelchecker::SymbolicQuantitativeCheckResult<storm::dd::DdType::CUDD>& quantitativeResult4 = result->asSymbolicQuantitativeCheckResult<storm::dd::DdType::CUDD, double>(); - EXPECT_NEAR(3.6666622161865234, quantitativeResult4.getMin(), storm::settings::getModule<storm::settings::modules::NativeEquationSolverSettings>().getPrecision()); - EXPECT_NEAR(3.6666622161865234, quantitativeResult4.getMax(), storm::settings::getModule<storm::settings::modules::NativeEquationSolverSettings>().getPrecision()); + EXPECT_NEAR(3.6666646003723145, quantitativeResult4.getMin(), storm::settings::getModule<storm::settings::modules::NativeEquationSolverSettings>().getPrecision()); + EXPECT_NEAR(3.6666646003723145, quantitativeResult4.getMax(), storm::settings::getModule<storm::settings::modules::NativeEquationSolverSettings>().getPrecision()); } TEST(SymbolicDtmcPrctlModelCheckerTest, Die_Sylvan) { @@ -166,8 +166,8 @@ TEST(SymbolicDtmcPrctlModelCheckerTest, Crowds_Cudd) { result->filter(storm::modelchecker::SymbolicQualitativeCheckResult<storm::dd::DdType::CUDD>(model->getReachableStates(), model->getInitialStates())); storm::modelchecker::SymbolicQuantitativeCheckResult<storm::dd::DdType::CUDD>& quantitativeResult1 = result->asSymbolicQuantitativeCheckResult<storm::dd::DdType::CUDD, double>(); - EXPECT_NEAR(0.33288236360191303, quantitativeResult1.getMin(), storm::settings::getModule<storm::settings::modules::NativeEquationSolverSettings>().getPrecision()); - EXPECT_NEAR(0.33288236360191303, quantitativeResult1.getMax(), storm::settings::getModule<storm::settings::modules::NativeEquationSolverSettings>().getPrecision()); + EXPECT_NEAR(0.3328777473921436, quantitativeResult1.getMin(), storm::settings::getModule<storm::settings::modules::NativeEquationSolverSettings>().getPrecision()); + EXPECT_NEAR(0.3328777473921436, quantitativeResult1.getMax(), storm::settings::getModule<storm::settings::modules::NativeEquationSolverSettings>().getPrecision()); formula = formulaParser.parseSingleFormulaFromString("P=? [F \"observeIGreater1\"]"); @@ -175,8 +175,8 @@ TEST(SymbolicDtmcPrctlModelCheckerTest, Crowds_Cudd) { result->filter(storm::modelchecker::SymbolicQualitativeCheckResult<storm::dd::DdType::CUDD>(model->getReachableStates(), model->getInitialStates())); storm::modelchecker::SymbolicQuantitativeCheckResult<storm::dd::DdType::CUDD>& quantitativeResult2 = result->asSymbolicQuantitativeCheckResult<storm::dd::DdType::CUDD, double>(); - EXPECT_NEAR(0.15222081144084315, quantitativeResult2.getMin(), storm::settings::getModule<storm::settings::modules::NativeEquationSolverSettings>().getPrecision()); - EXPECT_NEAR(0.15222081144084315, quantitativeResult2.getMax(), storm::settings::getModule<storm::settings::modules::NativeEquationSolverSettings>().getPrecision()); + EXPECT_NEAR(0.15221847380560186, quantitativeResult2.getMin(), storm::settings::getModule<storm::settings::modules::NativeEquationSolverSettings>().getPrecision()); + EXPECT_NEAR(0.15221847380560186, quantitativeResult2.getMax(), storm::settings::getModule<storm::settings::modules::NativeEquationSolverSettings>().getPrecision()); formula = formulaParser.parseSingleFormulaFromString("P=? [F \"observeOnlyTrueSender\"]"); @@ -184,8 +184,8 @@ TEST(SymbolicDtmcPrctlModelCheckerTest, Crowds_Cudd) { result->filter(storm::modelchecker::SymbolicQualitativeCheckResult<storm::dd::DdType::CUDD>(model->getReachableStates(), model->getInitialStates())); storm::modelchecker::SymbolicQuantitativeCheckResult<storm::dd::DdType::CUDD>& quantitativeResult3 = result->asSymbolicQuantitativeCheckResult<storm::dd::DdType::CUDD, double>(); - EXPECT_NEAR(0.3215392962289586, quantitativeResult3.getMin(), storm::settings::getModule<storm::settings::modules::NativeEquationSolverSettings>().getPrecision()); - EXPECT_NEAR(0.3215392962289586, quantitativeResult3.getMax(), storm::settings::getModule<storm::settings::modules::NativeEquationSolverSettings>().getPrecision()); + EXPECT_NEAR(0.32153516079959443, quantitativeResult3.getMin(), storm::settings::getModule<storm::settings::modules::NativeEquationSolverSettings>().getPrecision()); + EXPECT_NEAR(0.32153516079959443, quantitativeResult3.getMax(), storm::settings::getModule<storm::settings::modules::NativeEquationSolverSettings>().getPrecision()); } TEST(SymbolicDtmcPrctlModelCheckerTest, Crowds_Sylvan) { diff --git a/src/test/modelchecker/SymbolicMdpPrctlModelCheckerTest.cpp b/src/test/modelchecker/SymbolicMdpPrctlModelCheckerTest.cpp index 34fc37c2d..872a8dbdf 100644 --- a/src/test/modelchecker/SymbolicMdpPrctlModelCheckerTest.cpp +++ b/src/test/modelchecker/SymbolicMdpPrctlModelCheckerTest.cpp @@ -103,8 +103,8 @@ TEST(SymbolicMdpPrctlModelCheckerTest, Dice_Cudd) { result->filter(storm::modelchecker::SymbolicQualitativeCheckResult<storm::dd::DdType::CUDD>(model->getReachableStates(), model->getInitialStates())); storm::modelchecker::SymbolicQuantitativeCheckResult<storm::dd::DdType::CUDD>& quantitativeResult7 = result->asSymbolicQuantitativeCheckResult<storm::dd::DdType::CUDD, double>(); - EXPECT_NEAR(7.3333272933959961, quantitativeResult7.getMin(), storm::settings::getModule<storm::settings::modules::NativeEquationSolverSettings>().getPrecision()); - EXPECT_NEAR(7.3333272933959961, quantitativeResult7.getMax(), storm::settings::getModule<storm::settings::modules::NativeEquationSolverSettings>().getPrecision()); + EXPECT_NEAR(7.3333294987678528, quantitativeResult7.getMin(), storm::settings::getModule<storm::settings::modules::NativeEquationSolverSettings>().getPrecision()); + EXPECT_NEAR(7.3333294987678528, quantitativeResult7.getMax(), storm::settings::getModule<storm::settings::modules::NativeEquationSolverSettings>().getPrecision()); formula = formulaParser.parseSingleFormulaFromString("Rmax=? [F \"done\"]"); @@ -112,8 +112,8 @@ TEST(SymbolicMdpPrctlModelCheckerTest, Dice_Cudd) { result->filter(storm::modelchecker::SymbolicQualitativeCheckResult<storm::dd::DdType::CUDD>(model->getReachableStates(), model->getInitialStates())); storm::modelchecker::SymbolicQuantitativeCheckResult<storm::dd::DdType::CUDD>& quantitativeResult8 = result->asSymbolicQuantitativeCheckResult<storm::dd::DdType::CUDD, double>(); - EXPECT_NEAR(7.3333272933959961, quantitativeResult8.getMin(), storm::settings::getModule<storm::settings::modules::NativeEquationSolverSettings>().getPrecision()); - EXPECT_NEAR(7.3333272933959961, quantitativeResult8.getMax(), storm::settings::getModule<storm::settings::modules::NativeEquationSolverSettings>().getPrecision()); + EXPECT_NEAR(7.3333294987678528, quantitativeResult8.getMin(), storm::settings::getModule<storm::settings::modules::NativeEquationSolverSettings>().getPrecision()); + EXPECT_NEAR(7.3333294987678528, quantitativeResult8.getMax(), storm::settings::getModule<storm::settings::modules::NativeEquationSolverSettings>().getPrecision()); } TEST(SymbolicMdpPrctlModelCheckerTest, Dice_Sylvan) { @@ -201,8 +201,8 @@ TEST(SymbolicMdpPrctlModelCheckerTest, Dice_Sylvan) { result->filter(storm::modelchecker::SymbolicQualitativeCheckResult<storm::dd::DdType::Sylvan>(model->getReachableStates(), model->getInitialStates())); storm::modelchecker::SymbolicQuantitativeCheckResult<storm::dd::DdType::Sylvan>& quantitativeResult7 = result->asSymbolicQuantitativeCheckResult<storm::dd::DdType::Sylvan, double>(); - EXPECT_NEAR(7.3333272933959961, quantitativeResult7.getMin(), storm::settings::getModule<storm::settings::modules::NativeEquationSolverSettings>().getPrecision()); - EXPECT_NEAR(7.3333272933959961, quantitativeResult7.getMax(), storm::settings::getModule<storm::settings::modules::NativeEquationSolverSettings>().getPrecision()); + EXPECT_NEAR(7.3333294987678528, quantitativeResult7.getMin(), storm::settings::getModule<storm::settings::modules::NativeEquationSolverSettings>().getPrecision()); + EXPECT_NEAR(7.3333294987678528, quantitativeResult7.getMax(), storm::settings::getModule<storm::settings::modules::NativeEquationSolverSettings>().getPrecision()); formula = formulaParser.parseSingleFormulaFromString("Rmax=? [F \"done\"]"); @@ -210,8 +210,8 @@ TEST(SymbolicMdpPrctlModelCheckerTest, Dice_Sylvan) { result->filter(storm::modelchecker::SymbolicQualitativeCheckResult<storm::dd::DdType::Sylvan>(model->getReachableStates(), model->getInitialStates())); storm::modelchecker::SymbolicQuantitativeCheckResult<storm::dd::DdType::Sylvan>& quantitativeResult8 = result->asSymbolicQuantitativeCheckResult<storm::dd::DdType::Sylvan, double>(); - EXPECT_NEAR(7.3333272933959961, quantitativeResult8.getMin(), storm::settings::getModule<storm::settings::modules::NativeEquationSolverSettings>().getPrecision()); - EXPECT_NEAR(7.3333272933959961, quantitativeResult8.getMax(), storm::settings::getModule<storm::settings::modules::NativeEquationSolverSettings>().getPrecision()); + EXPECT_NEAR(7.3333294987678528, quantitativeResult8.getMin(), storm::settings::getModule<storm::settings::modules::NativeEquationSolverSettings>().getPrecision()); + EXPECT_NEAR(7.3333294987678528, quantitativeResult8.getMax(), storm::settings::getModule<storm::settings::modules::NativeEquationSolverSettings>().getPrecision()); } TEST(SymbolicMdpPrctlModelCheckerTest, AsynchronousLeader_Cudd) { @@ -290,8 +290,8 @@ TEST(SymbolicMdpPrctlModelCheckerTest, AsynchronousLeader_Cudd) { result->filter(storm::modelchecker::SymbolicQualitativeCheckResult<storm::dd::DdType::CUDD>(model->getReachableStates(), model->getInitialStates())); storm::modelchecker::SymbolicQuantitativeCheckResult<storm::dd::DdType::CUDD>& quantitativeResult6 = result->asSymbolicQuantitativeCheckResult<storm::dd::DdType::CUDD, double>(); - EXPECT_NEAR(4.2856890848060498, quantitativeResult6.getMin(), storm::settings::getModule<storm::settings::modules::NativeEquationSolverSettings>().getPrecision()); - EXPECT_NEAR(4.2856890848060498, quantitativeResult6.getMax(), storm::settings::getModule<storm::settings::modules::NativeEquationSolverSettings>().getPrecision()); + EXPECT_NEAR(4.2856904354441401, quantitativeResult6.getMin(), storm::settings::getModule<storm::settings::modules::NativeEquationSolverSettings>().getPrecision()); + EXPECT_NEAR(4.2856904354441401, quantitativeResult6.getMax(), storm::settings::getModule<storm::settings::modules::NativeEquationSolverSettings>().getPrecision()); } TEST(SymbolicMdpPrctlModelCheckerTest, AsynchronousLeader_Sylvan) { diff --git a/src/test/storage/JaniModelTest.cpp b/src/test/storage/JaniModelTest.cpp index 764bfe5bc..7c7f393b3 100644 --- a/src/test/storage/JaniModelTest.cpp +++ b/src/test/storage/JaniModelTest.cpp @@ -7,7 +7,7 @@ #include "storm/storage/jani/Model.h" #ifdef STORM_HAVE_MSAT -TEST(JaniModelTest, FlattenModules) { +TEST(JaniModelTest, FlattenComposition) { storm::prism::Program program; ASSERT_NO_THROW(program = storm::parser::PrismParser::parse(STORM_TEST_RESOURCES_DIR "/mdp/leader3.nm")); storm::jani::Model janiModel = program.toJani(); @@ -19,7 +19,7 @@ TEST(JaniModelTest, FlattenModules) { EXPECT_EQ(74ull, janiModel.getAutomaton(0).getNumberOfEdges()); } -TEST(JaniModelTest, FlattenModules_Wlan_Mathsat) { +TEST(JaniModelTest, FlattenComposition_Wlan_Mathsat) { storm::prism::Program program; ASSERT_NO_THROW(program = storm::parser::PrismParser::parse(STORM_TEST_RESOURCES_DIR "/mdp/wlan0_collide.nm")); storm::jani::Model janiModel = program.toJani(); @@ -31,7 +31,7 @@ TEST(JaniModelTest, FlattenModules_Wlan_Mathsat) { EXPECT_EQ(179ull, janiModel.getAutomaton(0).getNumberOfEdges()); } -TEST(JaniModelTest, FlattenModules_Csma_Mathsat) { +TEST(JaniModelTest, FlattenComposition_Csma_Mathsat) { storm::prism::Program program; ASSERT_NO_THROW(program = storm::parser::PrismParser::parse(STORM_TEST_RESOURCES_DIR "/mdp/csma2_2.nm")); storm::jani::Model janiModel = program.toJani(); @@ -43,7 +43,7 @@ TEST(JaniModelTest, FlattenModules_Csma_Mathsat) { EXPECT_EQ(70ull, janiModel.getAutomaton(0).getNumberOfEdges()); } -TEST(JaniModelTest, FlattenModules_Firewire_Mathsat) { +TEST(JaniModelTest, FlattenComposition_Firewire_Mathsat) { storm::prism::Program program; ASSERT_NO_THROW(program = storm::parser::PrismParser::parse(STORM_TEST_RESOURCES_DIR "/mdp/firewire.nm")); storm::jani::Model janiModel = program.toJani(); @@ -55,7 +55,7 @@ TEST(JaniModelTest, FlattenModules_Firewire_Mathsat) { EXPECT_EQ(5024ull, janiModel.getAutomaton(0).getNumberOfEdges()); } -TEST(JaniModelTest, FlattenModules_Coin_Mathsat) { +TEST(JaniModelTest, FlattenComposition_Coin_Mathsat) { storm::prism::Program program; ASSERT_NO_THROW(program = storm::parser::PrismParser::parse(STORM_TEST_RESOURCES_DIR "/mdp/coin2.nm")); storm::jani::Model janiModel = program.toJani(); @@ -67,7 +67,7 @@ TEST(JaniModelTest, FlattenModules_Coin_Mathsat) { EXPECT_EQ(13ull, janiModel.getAutomaton(0).getNumberOfEdges()); } -TEST(JaniModelTest, FlattenModules_Dice_Mathsat) { +TEST(JaniModelTest, FlattenComposition_Dice_Mathsat) { storm::prism::Program program; ASSERT_NO_THROW(program = storm::parser::PrismParser::parse(STORM_TEST_RESOURCES_DIR "/mdp/two_dice.nm")); storm::jani::Model janiModel = program.toJani(); @@ -81,7 +81,7 @@ TEST(JaniModelTest, FlattenModules_Dice_Mathsat) { #endif #ifdef STORM_HAVE_Z3 -TEST(JaniModelTest, FlattenModules_Leader_Z3) { +TEST(JaniModelTest, FlattenComposition_Leader_Z3) { storm::prism::Program program; ASSERT_NO_THROW(program = storm::parser::PrismParser::parse(STORM_TEST_RESOURCES_DIR "/mdp/leader3.nm")); storm::jani::Model janiModel = program.toJani(); @@ -93,7 +93,7 @@ TEST(JaniModelTest, FlattenModules_Leader_Z3) { EXPECT_EQ(74ull, janiModel.getAutomaton(0).getNumberOfEdges()); } -TEST(JaniModelTest, FlattenModules_Wlan_Z3) { +TEST(JaniModelTest, FlattenComposition_Wlan_Z3) { storm::prism::Program program; ASSERT_NO_THROW(program = storm::parser::PrismParser::parse(STORM_TEST_RESOURCES_DIR "/mdp/wlan0_collide.nm")); storm::jani::Model janiModel = program.toJani(); @@ -105,7 +105,7 @@ TEST(JaniModelTest, FlattenModules_Wlan_Z3) { EXPECT_EQ(179ull, janiModel.getAutomaton(0).getNumberOfEdges()); } -TEST(JaniModelTest, FlattenModules_Csma_Z3) { +TEST(JaniModelTest, FlattenComposition_Csma_Z3) { storm::prism::Program program; ASSERT_NO_THROW(program = storm::parser::PrismParser::parse(STORM_TEST_RESOURCES_DIR "/mdp/csma2_2.nm")); storm::jani::Model janiModel = program.toJani(); @@ -117,7 +117,7 @@ TEST(JaniModelTest, FlattenModules_Csma_Z3) { EXPECT_EQ(70ull, janiModel.getAutomaton(0).getNumberOfEdges()); } -TEST(JaniModelTest, FlattenModules_Firewire_Z3) { +TEST(JaniModelTest, FlattenComposition_Firewire_Z3) { storm::prism::Program program; ASSERT_NO_THROW(program = storm::parser::PrismParser::parse(STORM_TEST_RESOURCES_DIR "/mdp/firewire.nm")); storm::jani::Model janiModel = program.toJani(); @@ -129,7 +129,7 @@ TEST(JaniModelTest, FlattenModules_Firewire_Z3) { EXPECT_EQ(5024ull, janiModel.getAutomaton(0).getNumberOfEdges()); } -TEST(JaniModelTest, FlattenModules_Coin_Z3) { +TEST(JaniModelTest, FlattenComposition_Coin_Z3) { storm::prism::Program program; ASSERT_NO_THROW(program = storm::parser::PrismParser::parse(STORM_TEST_RESOURCES_DIR "/mdp/coin2.nm")); storm::jani::Model janiModel = program.toJani(); @@ -141,7 +141,7 @@ TEST(JaniModelTest, FlattenModules_Coin_Z3) { EXPECT_EQ(13ull, janiModel.getAutomaton(0).getNumberOfEdges()); } -TEST(JaniModelTest, FlattenModules_Dice_Z3) { +TEST(JaniModelTest, FlattenComposition_Dice_Z3) { storm::prism::Program program; ASSERT_NO_THROW(program = storm::parser::PrismParser::parse(STORM_TEST_RESOURCES_DIR "/mdp/two_dice.nm")); storm::jani::Model janiModel = program.toJani(); diff --git a/storm-config.h.in b/storm-config.h.in index 074e72d1c..c5884679c 100644 --- a/storm-config.h.in +++ b/storm-config.h.in @@ -55,7 +55,7 @@ #cmakedefine STORM_USE_CLN_NUMBERS -#cmakedefine USE_XERCES +#cmakedefine STORM_HAVE_XERCES // Whether smtrat is available and to be used. #cmakedefine STORM_HAVE_SMTRAT