pax_global_header00006660000000000000000000000064131472747600014525gustar00rootroot0000000000000052 comment=9b6cc06c6aac72c54ef704d540b0597d03ef3dd1 ocplib-simplex-0.4/000077500000000000000000000000001314727476000143175ustar00rootroot00000000000000ocplib-simplex-0.4/.gitignore000066400000000000000000000002441314727476000163070ustar00rootroot00000000000000_obuild .gitignore _olint .ocplint *~ #* autom4te.cache configure config.status .depend *.cm* *.o *.annot *.a src/coreSig.ml src/extSigs.ml config.log Makefile METAocplib-simplex-0.4/.ocplint000066400000000000000000000144001314727476000157670ustar00rootroot00000000000000 (*************************************) (* Never edit options files while *) (* the program is running *) (*************************************) (* SECTION : Header *) (* These options must be read first *) (*************************************) (* Module to ignore during the lint. *) ignore = [ tests ] (* Time before erasing cached results (in days). *) db_persistence = 1 (* Number of parallel jobs *) jobs = 4 plugin_typedtree = { (* A plugin with linters on typed tree *) enabled = true fully_qualified_identifiers = { (* Enable/Disable linter "Fully-Qualified Identifiers". *) enabled = true (* Module to ignore durint the lint of "Fully-Qualified Identifiers" *) ignore = [ ] (* Enable/Disable warnings from "Fully-Qualified Identifiers" *) warnings = "+A" ignored_modules = [ Pervasives; StringCompat; ] ignore_operators = true ignore_depth = 2 } polymorphic_function = { (* Enable/Disable linter "Polymorphic function". *) enabled = true (* Module to ignore durint the lint of "Polymorphic function" *) ignore = [ ] (* Enable/Disable warnings from "Polymorphic function" *) warnings = "+A" } } plugin_text = { (* A plugin with linters on the source *) enabled = true code_length = { (* Enable/Disable linter "Code Length". *) enabled = true (* Module to ignore durint the lint of "Code Length" *) ignore = [ ] (* Enable/Disable warnings from "Code Length" *) warnings = "+A" (* Maximum line length *) max_line_length = 80 } useless_space_line = { (* Enable/Disable linter "Useless space character and empty line at the end of file.". *) enabled = true (* Module to ignore durint the lint of "Useless space character and empty line at the end of file." *) ignore = [ ] (* Enable/Disable warnings from "Useless space character and empty line at the end of file." *) warnings = "+A" } not_that_char = { (* Enable/Disable linter "Detect use of unwanted chars in files". *) enabled = true (* Module to ignore durint the lint of "Detect use of unwanted chars in files" *) ignore = [ ] (* Enable/Disable warnings from "Detect use of unwanted chars in files" *) warnings = "+A" } } plugin_patch = { (* Detect pattern with semantic patch. *) enabled = true sempatch_lint = { (* Enable/Disable linter "Lint from semantic patches.". *) enabled = true (* Module to ignore durint the lint of "Lint from semantic patches." *) ignore = [ ] (* Enable/Disable warnings from "Lint from semantic patches." *) warnings = "+A" } } plugin_parsing = { (* Analyses requiring to re-parse the file *) enabled = true raw_syntax = { (* Enable/Disable linter "Raw Syntax". *) enabled = true (* Module to ignore durint the lint of "Raw Syntax" *) ignore = [ ] (* Enable/Disable warnings from "Raw Syntax" *) warnings = "+A" } } plugin_parsetree = { (* A plugin with linters on parsetree *) enabled = true code_identifier_length = { (* Enable/Disable linter "Code Identifier Length". *) enabled = true (* Module to ignore durint the lint of "Code Identifier Length" *) ignore = [ ] (* Enable/Disable warnings from "Code Identifier Length" *) warnings = "+A" (* Identifiers with a shorter name will trigger a warning *) min_identifier_length = 1 (* Identifiers with a longer name will trigger a warning *) max_identifier_length = 80 } code_list_on_singleton = { (* Enable/Disable linter "List function on singleton". *) enabled = true (* Module to ignore durint the lint of "List function on singleton" *) ignore = [ ] (* Enable/Disable warnings from "List function on singleton" *) warnings = "+A" } phys_comp_allocated_lit = { (* Enable/Disable linter "Physical comparison between allocated litterals.". *) enabled = true (* Module to ignore durint the lint of "Physical comparison between allocated litterals." *) ignore = [ ] (* Enable/Disable warnings from "Physical comparison between allocated litterals." *) warnings = "+A" } fabrice_good_practices = { (* Enable/Disable linter "Good Practices". *) enabled = true (* Module to ignore durint the lint of "Good Practices" *) ignore = [ ] (* Enable/Disable warnings from "Good Practices" *) warnings = "+A" } check_constr_args = { (* Enable/Disable linter "Check Constructor Arguments". *) enabled = true (* Module to ignore durint the lint of "Check Constructor Arguments" *) ignore = [ ] (* Enable/Disable warnings from "Check Constructor Arguments" *) warnings = "+A" } code_redefine_stdlib_module = { (* Enable/Disable linter "Refedine Stdlib Module". *) enabled = true (* Module to ignore durint the lint of "Refedine Stdlib Module" *) ignore = [ ] (* Enable/Disable warnings from "Refedine Stdlib Module" *) warnings = "+A" } } plugin_indent = { (* A plugin with linters on the source *) enabled = true ocp_indent = { (* Enable/Disable linter "Indention with ocp-indent". *) enabled = true (* Module to ignore durint the lint of "Indention with ocp-indent" *) ignore = [ ] (* Enable/Disable warnings from "Indention with ocp-indent" *) warnings = "+A" } } plugin_file_system = { (* A plugin with linters on file system like interface missing, etc *) enabled = true interface_missing = { (* Enable/Disable linter "Missing interface". *) enabled = true (* Module to ignore durint the lint of "Missing interface" *) ignore = [ ] (* Enable/Disable warnings from "Missing interface" *) warnings = "+A" } project_files = { (* Enable/Disable linter "File Names". *) enabled = true (* Module to ignore durint the lint of "File Names" *) ignore = [ ] (* Enable/Disable warnings from "File Names" *) warnings = "+A" } } plugin_complex = { (* A plugin with linters on different inputs *) enabled = true interface_module_type_name = { (* Enable/Disable linter "Checks on module type name.". *) enabled = true (* Module to ignore durint the lint of "Checks on module type name." *) ignore = [ ] (* Enable/Disable warnings from "Checks on module type name." *) warnings = "+A" } } (* The following options are not used (errors, obsolete, ...) *) ignored_files = [ ] ocplib-simplex-0.4/CHANGES.md000066400000000000000000000025041314727476000157120ustar00rootroot00000000000000(!!! = may break code that uses previous versions) version 0.4, August 22, 2017 =============================== * (!!!) Now, asserting bounds returns whether these bounds are trivially implied by those that are already known * add a field nb_pivots in the environment to count the number of pivots that have been made so far. verion 0.3, November 09, 2016 =============================== * bugfix in maximization verion 0.2, August 24, 2016 =============================== * add support for linear optimization (!!!). An minimal example is given in tests/standalone_minimal_maximization.ml * some bugfixes when assuming inconsistent bounds * improve build and testing first public 0.1, July 11, 2016 =============================== * A functor called `Basic` provides three modules: - `Core`: provides some basic functions, and a function `empty` to create an empty environment - `Assert`: exports two functions `var` and `polys` to assert bounds on variables and polynomials, respectively - `Solve`: exports a function `solve` that tries to find a solution for the constrains * two flags can be set when creating an empty environment to activate debug mode and some invariants verification * implementation is fully functional, incremental and backtrackable * linear optimization is not supported yet ocplib-simplex-0.4/LICENSE000066400000000000000000000647711314727476000153430ustar00rootroot00000000000000In the following, ocplib-simplex refers to all files marked "Copyright OCamlPro" in this distribution. ocplib-simplex is distributed under the terms of the GNU Lesser General Public License (LGPL) version 2.1 (included below). As a special exception to the GNU Lesser General Public License, you may link, statically or dynamically, a "work that uses ocplib-simplex" with a publicly distributed version of ocplib-simplex to produce an executable file containing portions of ocplib-simplex, and distribute that executable file under terms of your choice, without any of the additional requirements listed in clause 6 of the GNU Lesser General Public License. By "a publicly distributed version of ocplib-simplex", we mean either the unmodified ocplib-simplex as distributed by OCamlpro, or a modified version of ocplib-simplex that is distributed under the conditions defined in clause 2 of the GNU Lesser General Public License. This exception does not however invalidate any other reasons why the executable file might be covered by the GNU Lesser General Public License. ---------------------------------------------------------------------- GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 Free Software Foundation, Inc. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. one line to give the library's name and an idea of what it does. Copyright (C) year name of author This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. signature of Ty Coon, 1 April 1990 Ty Coon, President of Vice That's all there is to it! -------------------------------------------------- ocplib-simplex-0.4/Makefile.in000066400000000000000000000151051314727476000163660ustar00rootroot00000000000000# sample Makefile for Objective Caml # Copyright (C) 2001 Jean-Christophe FILLIATRE # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License version 2, as published by the Free Software Foundation. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # # See the GNU Library General Public License version 2 for more details # (enclosed in the file LGPL). # where to install the binaries DESTDIR=@prefix@ # prefix=@prefix@ # exec_prefix=@exec_prefix@ # BINDIR=$(DESTDIR)@bindir@ LIBDIR=$(DESTDIR)/lib/ # DATADIR=$(DESTDIR)@datadir@/ocplib-simplex # where to install the man page MANDIR=$(DESTDIR)@mandir@ # other variables set by ./configure OCAMLC = @OCAMLC@ OCAMLOPT = @OCAMLOPT@ OCAMLDEP = @OCAMLDEP@ OCAMLBEST = @OCAMLBEST@ OCAMLVERSION = @OCAMLVERSION@ OCAMLWIN32 = @OCAMLWIN32@ OCAMLLIB = @OCAMLLIB@ LIBNAME=ocplibSimplex EXE =@EXE@ ARCH = $(shell uname -m) VERSION=$(shell grep "=" src/version.ml | cut -d"=" -f2 | head -n 1) LOCAL_INC = -I src INCLUDES = $(LOCAL_INC) #for coverage # -I /usr/local/lib/ocaml/3.12.1/bisect -pp "camlp4o str.cma /usr/local/lib/ocaml/3.12.1/bisect/bisect_pp.cmo" OFLAGS_LIGHT = -annot -absname -bin-annot -short-paths -strict-sequence -w +A -g -inline 100 $(INCLUDES) BFLAGS_LIGHT = -annot -absname -bin-annot -short-paths -strict-sequence -w +A -g $(INCLUDES) BFLAGS = $(BFLAGS_LIGHT) -for-pack OcplibSimplex OFLAGS = $(OFLAGS_LIGHT) -for-pack OcplibSimplex BIBBYTE = # for coverage bisect.cma BIBOPT = $(BIBBYTE:.cma=.cmxa) GENERATED = src/extSigs.ml src/coreSig.ml #src/ocplibSimplex.mli CMO = src/version.cmo src/rat2.cmo src/extSigs.cmo src/polys.cmo src/coreSig.cmo src/core.cmo \ src/result.cmo src/assertBounds.cmo src/solveBounds.cmo src/basic.cmo CMX = $(CMO:.cmo=.cmx) # Build ######### all: $(OCAMLBEST) byte: src/$(LIBNAME).cma opt: src/$(LIBNAME).cma src/$(LIBNAME).cmxa src/$(LIBNAME).cmxs src/$(LIBNAME).cma: src/$(LIBNAME).cmo $(OCAMLC) -a $(BFLAGS_LIGHT) -o $@ $^ src/$(LIBNAME).cmxa: src/$(LIBNAME).cmx $(OCAMLOPT) -a $(OFLAGS_LIGHT) -o $@ $^ src/$(LIBNAME).cmxs: src/$(LIBNAME).cmx $(OCAMLOPT) -shared $(OFLAGS_LIGHT) -o $@ $^ src/$(LIBNAME).cmo: $(CMO) # src/$(LIBNAME).cmi $(OCAMLC) $(BFLAGS_LIGHT) -pack -o src/$(LIBNAME).cmo $^ src/$(LIBNAME).cmx: $(CMX) # src/$(LIBNAME).cmi $(OCAMLOPT) $(OFLAGS_LIGHT) -pack -o src/$(LIBNAME).cmx $^ src/extSigs.ml: src/extSigs.mli cp src/extSigs.mli src/extSigs.ml src/coreSig.ml: src/coreSig.mli cp src/coreSig.mli src/coreSig.ml .PHONY: all META: config.status @echo "description = \"ocplib-simplex: A library implementing a simplex algorithm, in a functional style, for solving systems of linear inequalities\"" > META @echo "version = \""$(VERSION)"\"" >> META @echo "archive(byte) = \"$(LIBNAME).cma\"" >> META @echo "archive(native) = \"$(LIBNAME).cmxa\"" >> META @echo "archive(native, plugin) = \"$(LIBNAME).cmxs\"" >> META @echo "archive(byte, plugin) = \"$(LIBNAME).cma\"" >> META @echo "requires = \"\"" >> META @echo "exists_if = \"$(LIBNAME).cma\"" >> META # installation ############## install: all META OCAMLFIND_DESTDIR=$(LIBDIR) \ ocamlfind install ocplib-simplex src/$(LIBNAME).* src/*.mli META uninstall: ocamlfind remove ocplib-simplex # generic rules ############### .SUFFIXES: .mli .ml .cmi .cmo .cmx .mll .mly .tex .dvi .ps .html .mli.cmi: $(OCAMLC) -c $(BFLAGS) $< .ml.cmo: $(OCAMLC) -c $(BFLAGS) $< .ml.o: $(OCAMLOPT) -c $(OFLAGS) $< .ml.cmx: $(OCAMLOPT) -c $(OFLAGS) $< .mll.ml: $(OCAMLLEX) $< > /dev/null .mly.ml: $(OCAMLYACC) -v $< .mly.mli: $(OCAMLYACC) -v $< # clean ####### clean: @for dd in . src tests; do \ rm -f $$dd/*.cm* $$dd/*.a $$dd/*.o $$dd/*~ $$dd/*.annot $$dd/*.owz $(GENERATED) *.byte *.opt;\ done @rm -rf META # depend ######## .depend depend: $(GENERATED) $(OCAMLDEP) $(LOCAL_INC) src/*.ml* > .depend include .depend #show-dest-dirs: # @echo INSTALL DIR = $(INSTALLDIR) # Makefile.configurable is rebuilt whenever Makefile.configurable.in # or configure.in is modified ###################################################################### configure: configure.in autoconf ./configure Makefile.configurable: Makefile.in configure.in ./config.status config.status: configure ./config.status --recheck archi: depend ocamldot .depend > archi.dot && dot -Tpdf archi.dot > archi.pdf && evince archi.pdf & lint: ocp-lint --disable-plugin-indent --pwarning --perror edit: emacs src/*ml* & opam-deps: opam install ocamlfind opam-tests-deps: opam install ocamlfind num repin: opam remove ocplib-simplex opam pin add . --y local-tests: all ## minimal example with solve: byte and opt >> lib is local $(OCAMLC) -o standalone_minimal_local.byte -I src -I tests ocplibSimplex.cma nums.cma tests/standalone_minimal.ml ./standalone_minimal_local.byte 2> /dev/null $(OCAMLOPT) -o standalone_minimal_local.opt -I src -I tests ocplibSimplex.cmxa nums.cmxa tests/standalone_minimal.ml ./standalone_minimal_local.opt 2> /dev/null ## minimal example with maximization: byte and opt >> lib is local $(OCAMLC) -o standalone_minimal_maximization_local.byte -I src -I tests ocplibSimplex.cma nums.cma tests/standalone_minimal_maximization.ml ./standalone_minimal_maximization_local.byte 2> /dev/null $(OCAMLOPT) -o standalone_minimal_maximization_local.opt -I src -I tests ocplibSimplex.cmxa nums.cmxa tests/standalone_minimal_maximization.ml ./standalone_minimal_maximization_local.opt 2> /dev/null opam-installed-tests: repin ## minimal example with solve: byte and opt >> lib is pinned with OPAM $(OCAMLC) -o standalone_minimal_opam.byte -I `ocamlfind query ocplib-simplex` -I tests ocplibSimplex.cma nums.cma tests/standalone_minimal.ml ./standalone_minimal_opam.byte 2> /dev/null $(OCAMLOPT) -o standalone_minimal_opam.opt -I `ocamlfind query ocplib-simplex` -I tests ocplibSimplex.cmxa nums.cmxa tests/standalone_minimal.ml ./standalone_minimal_opam.opt 2> /dev/null ## minimal example with maximization: byte and opt >> lib is pinned with OPAM $(OCAMLC) -o standalone_minimal_maximization_opam.byte -I `ocamlfind query ocplib-simplex` -I tests ocplibSimplex.cma nums.cma tests/standalone_minimal_maximization.ml ./standalone_minimal_maximization_opam.byte 2> /dev/null $(OCAMLOPT) -o standalone_minimal_maximization_opam.opt -I `ocamlfind query ocplib-simplex` -I tests ocplibSimplex.cmxa nums.cmxa tests/standalone_minimal_maximization.ml ./standalone_minimal_maximization_opam.opt 2> /dev/null tests: local-tests opam-installed-tests ocplib-simplex-0.4/README.md000066400000000000000000000033701314727476000156010ustar00rootroot00000000000000# ocplib-simplex A library implementing a simplex algorithm, in a functional style, for solving systems of linear inequalities and optimizing linear objective functions ## Overview `ocplib-simplex` is a (fully) functional OCaml implementation of the simplex algorithm for solving systems of linear inequalities. The implementation is incremental and backtrackable. It is able to extract unsat-cores for unsatisfiable problems. Versions `> 0.1` also support linear optimization ## Dependencies `ocplib-simplex` requires `4.01.0` or higher and `ocamlfind`. You can use `make opam-deps` to install dependencies in the current switch. ## Build and Install Instructions The easiest way to install ocplib-simplex is to use OPAM: $ opam install ocplib-simplex If you want to install ocplib-simplex from sources, use the following instructions: $ autoconf (if configure is not present) $ ./configure $ make opam-deps (if you are using OPAM and some deps are missing) $ make $ make install to compile and install `ocplib-simplex` on your system. You can uninstall the library with `make uninstall`. ## Minimal Examples Solving a system of linear inequalities: see the file `tests/standalone_minimal.ml` Linear optimization: see the file `tests/standalone_minimal_maximization.ml` ## Contributing Don't hesitate to report encountered bugs on this Git repo's issues tracker. ## TODO - the code is not (well) documented, - some parts of the code need factorization/simplification, - some invariants (check unsat-core, linear optimization) are missing. ## Licensing `ocplib-simplex` is Copyright (C) --- OCamlPro. it is distributed under the terms of the GNU Lesser General Public License (LGPL) version 2.1 (see LICENSE file for more details).ocplib-simplex-0.4/configure.in000066400000000000000000000107041314727476000166320ustar00rootroot00000000000000# autoconf input for Objective Caml programs # Copyright (C) 2001 Jean-Christophe Filliātre # from a first script by Georges Mariano # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License version 2, as published by the Free Software Foundation. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # # See the GNU Library General Public License version 2 for more details # (enclosed in the file LGPL). # the script generated by autoconf from this input will set the following # variables: # OCAMLC "ocamlc" if present in the path, or a failure # or "ocamlc.opt" if present with same version number as ocamlc # OCAMLOPT "ocamlopt" (or "ocamlopt.opt" if present), or "no" # OCAMLBEST either "byte" if no native compiler was found, # or "opt" otherwise # OCAMLDEP "ocamldep" # OCAMLLEX "ocamllex" (or "ocamllex.opt" if present) # OCAMLYACC "ocamlyac" # OCAMLLIB the path to the ocaml standard library # OCAMLVERSION the ocaml version number # OCAMLWEB "ocamlweb" (not mandatory) # OCAMLWIN32 "yes"/"no" depending on Sys.os_type = "Win32" # EXE ".exe" if OCAMLWIN32=yes, "" otherwise # check for one particular file of the sources # ADAPT THE FOLLOWING LINE TO YOUR SOURCES! AC_INIT(src/core.ml) # Check for Ocaml compilers # we first look for ocamlc in the path; if not present, we fail AC_CHECK_PROGS(OCAMLC,ocamlc,no) if test "$OCAMLC" = no ; then AC_MSG_ERROR(Cannot find ocamlc.) fi # we extract Ocaml version number and library path OCAMLVERSION=`$OCAMLC -v | sed -n -e 's|.*version *\(.*\)$|\1|p' ` echo "ocaml version is $OCAMLVERSION" OCAMLLIB=`$OCAMLC -v | tail -1 | cut -f 4 -d " " | tr -d '\\r'` echo "ocaml library path is $OCAMLLIB" # we look for ocamlfind; if not present, we just don't use it to find # libraries AC_CHECK_PROG(USEOCAMLFIND,ocamlfind,yes,no) if test "$USEOCAMLFIND" = yes; then OCAMLFINDLIB=$(ocamlfind printconf stdlib) OCAMLFIND=$(which ocamlfind) if test "$OCAMLFINDLIB" != "$OCAMLLIB"; then USEOCAMLFIND=no; echo "but your ocamlfind is not compatible with your ocamlc:" echo "ocamlfind : $OCAMLFINDLIB, ocamlc : $OCAMLLIB" fi fi # then we look for ocamlopt; if not present, we issue a warning # if the version is not the same, we also discard it # we set OCAMLBEST to "opt" or "byte", whether ocamlopt is available or not AC_CHECK_PROGS(OCAMLOPT,ocamlopt,no) OCAMLBEST=byte if test "$OCAMLOPT" = no ; then AC_MSG_WARN(Cannot find ocamlopt; bytecode compilation only.) else AC_MSG_CHECKING(ocamlopt version) TMPVERSION=`$OCAMLOPT -v | sed -n -e 's|.*version *\(.*\)$|\1|p' ` if test "$TMPVERSION" != "$OCAMLVERSION" ; then AC_MSG_RESULT(differs from ocamlc; ocamlopt discarded.) OCAMLOPT=no else AC_MSG_RESULT(ok) OCAMLBEST=opt fi fi # checking for ocamlc.opt AC_CHECK_PROGS(OCAMLCDOTOPT,ocamlc.opt,no) if test "$OCAMLCDOTOPT" != no ; then AC_MSG_CHECKING(ocamlc.opt version) TMPVERSION=`$OCAMLCDOTOPT -v | sed -n -e 's|.*version *\(.*\)$|\1|p' ` if test "$TMPVERSION" != "$OCAMLVERSION" ; then AC_MSG_RESULT(differs from ocamlc; ocamlc.opt discarded.) else AC_MSG_RESULT(ok) OCAMLC=$OCAMLCDOTOPT fi fi # checking for ocamlopt.opt if test "$OCAMLOPT" != no ; then AC_CHECK_PROGS(OCAMLOPTDOTOPT,ocamlopt.opt,no) if test "$OCAMLOPTDOTOPT" != no ; then AC_MSG_CHECKING(ocamlopt.opt version) TMPVER=`$OCAMLOPTDOTOPT -v | sed -n -e 's|.*version *\(.*\)$|\1|p' ` if test "$TMPVER" != "$OCAMLVERSION" ; then AC_MSG_RESULT(differs from ocamlc; ocamlopt.opt discarded.) else AC_MSG_RESULT(ok) OCAMLOPT=$OCAMLOPTDOTOPT fi fi fi # ocamldep should also be present in the path AC_CHECK_PROG(OCAMLDEP,ocamldep,ocamldep,no) if test "$OCAMLDEP" = no ; then AC_MSG_ERROR(Cannot find ocamldep.) fi # platform AC_MSG_CHECKING(platform) if echo "let _ = Sys.os_type;;" | ocaml | grep -q Win32; then AC_MSG_RESULT(Win32) OCAMLWIN32=yes EXE=.exe else OCAMLWIN32=no EXE= fi # substitutions to perform AC_SUBST(OCAMLC) AC_SUBST(OCAMLOPT) AC_SUBST(OCAMLDEP) AC_SUBST(OCAMLBEST) AC_SUBST(OCAMLVERSION) AC_SUBST(OCAMLLIB) AC_SUBST(OCAMLWIN32) AC_SUBST(EXE) # Finally create the Makefile.configurable from Makefile.configurable.in AC_OUTPUT(Makefile) chmod a-w Makefile ocplib-simplex-0.4/extra/000077500000000000000000000000001314727476000154425ustar00rootroot00000000000000ocplib-simplex-0.4/extra/TODO.txt000066400000000000000000000015571314727476000167600ustar00rootroot00000000000000global: ------- - put some documentation in .mli files - try some more heuristics to extract models for simplexes over ints. - add the ability to do some encoding (with a flag): (eg. cubes-test for LIA) - add the ability to backtrack by directly relaxing bounds. This would allow to not rely on the functional style to backtrack, and to keep the pivots and valuation that have been computed so far - add the ability to apply substitutions resulting from pivots lazily. This is very important for scalability assertBounds.ml: ---------------- - assert_var and assert_poly should ignore bounds when Pb is UNSAT - assert_var and assert_poly should ignore bounds that are implied by those of the simplex - add a mode for assert_var and assert_poly to ignore previously asserted bounds ? (i.e. mode force_bounds) useful for assertUI.ml ? - deduce bounds from the simplex ? ocplib-simplex-0.4/extra/simplex_invariants.txt000066400000000000000000000050451314727476000221260ustar00rootroot00000000000000Basic formulation: ---------------- version 0.1 has the following env. type value_status = ValueOK | LowerKO | UpperKO type var_info = { mini : bound; maxi : bound; min_ex : Ex.t; max_ex : Ex.t; value : R.t * R.t; vstatus : value_status; is_slake : bool; } type t = { basic : (var_info * P.t) MX.t; non_basic : (var_info * SX.t) MX.t; slake_cache : Var.t SLAKE.t; fixme : SX.t; is_int : bool; status : simplex_status; debug : int; check_invariants : bool } (1) forall x in basic U non_basic U used_by U polys(basic) U slake_cache U polys(slake_cache) U fixeme. is_int <=> Var.is_int x (2) basic intersect non_basic = empty (3) forall p in polys(basic) U polys(slake_cache). forall (x, c) in p. (x in basic xor x in non_basic) and c <> 0 (4) used_by intersect non_basic = empty (5) forall y. forall x in used_by(y). (*y is no_basic and x is basic*) let _, p = basic(x) y in vars(p) (* i.e. with a coef != 0 *) (6) forall s. forall p such that basic(s) = _, p. forall x in vars(p). s in used_by(x) (* 5 and 6 mean that used_by contain exactly what needed *) (7) forall x in non_basic. min_bound <= val(x) <= max_bound (8) status = SAT => forall x in basic. min_bound <= val(x) <= max_bound (9) status = IntSAT => (8) and forall x. val(x) is an integer (10) is_int => (* ie simplex on integers *) coefs of delta_i's in min and max bounds are equal to zero (11) not is_int => (* ie simplex on rationnals *) coefs of delta_i's in min bounds are in {0, 1} and coefs of delta_i's in max bounds are in {0, -1} (12) status = SAT (sol) => sol satisfies the bounds of every constraints and sol satisfies every equality s = p, with (s, p) in basic. (13) status = UNSAT ({x_i, ex_i)} => /\ min_bound_i <= x_i <= max_bound_i in UNSAT on rationnals (* use FM to check this ? *) (14). fixme subset basic (15) forall x. x in fixme => ( val(x) < min_bound_x or val(x) > max_bound_x ) (16) status != UNSAT => forall x. x not in fixme => min_bound_x <= val(x) <= max_bound_x (17) status != Unknown => fixme = empty (* When UNSAT is deduced, we empty fixme *) (18) forall (s, p) in basic. val(s) = eval(p) (19) forall (x, i) in basic U non_basic min_bound_x <= val(x) <= max_bound_x => i.vstatus = ValueOK) and val(x) < min_bound_x => i.vstatus = LowerKO and max_bound_x < val(x) => i.vstatus = UpperKO (20) status != Unsat => forall (x, i) in basic U non_basic (min_bound_x <= max_bound_x) ocplib-simplex-0.4/opam000066400000000000000000000013231314727476000151750ustar00rootroot00000000000000opam-version: "1.2" name: "ocplib-simplex" version: "0.4" authors: "Mohamed Iguernlala " maintainer: "Mohamed Iguernlala " license: "LGPL version 2.1" homepage: "https://github.com/OCamlPro-Iguernlala/ocplib-simplex" bug-reports: "https://github.com/OCamlPro-Iguernlala/ocplib-simplex/issues" dev-repo: "https://github.com/OCamlPro-Iguernlala/ocplib-simplex.git" build:[ ["autoconf"] ["./configure" "-prefix" "%{prefix}%"] [make] ] install:[ [make "install"] ] remove:[ ["ocamlfind" "remove" "ocplib-simplex"] ] depends: [ "ocamlfind" {build} "conf-autoconf" {build} "num" ] available: [ ocaml-version >= "4.01.0" ]ocplib-simplex-0.4/src/000077500000000000000000000000001314727476000151065ustar00rootroot00000000000000ocplib-simplex-0.4/src/assertBounds.ml000066400000000000000000000213561314727476000201230ustar00rootroot00000000000000(******************************************************************************) (* ocplib-simplex *) (* *) (* Copyright (C) --- OCamlPro --- See README.md for information and licensing *) (******************************************************************************) module type SIG = sig module Core : CoreSig.SIG val var : Core.t -> Core.Var.t -> Core.bound -> Core.Ex.t -> Core.bound -> Core.Ex.t -> Core.t * bool val poly : Core.t -> Core.P.t -> Core.Var.t -> Core.bound -> Core.Ex.t -> Core.bound -> Core.Ex.t -> Core.t * bool end module Make(Core : CoreSig.SIG) : SIG with module Core = Core = struct module Core = Core module Result = Result.Make(Core) open Core let new_status_basic stt fixme s info consistent_bnds = let has_bad_value = info.vstatus != ValueOK in match stt, consistent_bnds with | UNSAT _, _ -> stt, fixme | _, false -> UNSAT s, SX.empty | UNK, true -> stt, if has_bad_value then SX.add s fixme else SX.remove s fixme | SAT, _ -> assert (fixme == SX.empty); if has_bad_value then UNK, SX.add s fixme else stt, fixme let assert_basic_var env x mini min_ex maxi max_ex = let info, poly, changed = try let info, poly = MX.find x env.basic in let info, chang1 = set_min_bound info mini min_ex in let info, chang2 = set_max_bound info maxi max_ex in info, poly, chang1 || chang2 with Not_found -> assert false in let status, fixme = new_status_basic env.status env.fixme x info (consistent_bounds info) in {env with basic = MX.add x (info, poly) env.basic; status; fixme}, changed (* *) let new_status_non_basic x stt fixme ({mini; maxi; value; _} as info) = match stt with | UNSAT _ -> stt, fixme | SAT | UNK when consistent_bounds info -> assert (not (violates_min_bound value mini)); assert (not (violates_max_bound value maxi)); assert (stt != SAT || fixme == SX.empty); stt, fixme | SAT | UNK -> UNSAT x, SX.empty let adapt_values_of_basic_vars env _old _new x use = let {basic; _} = env in let diff = R2.sub _new _old in SX.fold (fun s env -> let info, p = try MX.find s basic with Not_found -> assert false in let c_x = try P.find x p with Not_found -> assert false in let info = {info with value = R2.add info.value (R2.mult_by_const c_x diff)} in let info = ajust_status_of_basic info in let status, fixme = new_status_basic env.status env.fixme s info true in {env with status; fixme; basic = MX.add s (info, p) env.basic} )use env let assert_non_basic_var env x mini min_ex maxi max_ex = let info, use = try MX.find x env.non_basic with Not_found -> empty_info, SX.empty in let info, chang1 = set_min_bound info mini min_ex in let info, chang2 = set_max_bound info maxi max_ex in let old_val = info.value in let info, changed = ajust_value_of_non_basic info in let status, fixme = new_status_non_basic x env.status env.fixme info in let env = {env with non_basic = MX.add x (info, use) env.non_basic; status; fixme} in let env = if not changed then env else adapt_values_of_basic_vars env old_val info.value x use in env, chang1 || chang2 (* exported function: check_invariants called before and after *) let var env x mini ex_min maxi ex_max = debug "[entry of assert_var]" env (Result.get None); check_invariants env (Result.get None); let env, changed = if MX.mem x env.basic then assert_basic_var env x mini ex_min maxi ex_max else assert_non_basic_var env x mini ex_min maxi ex_max in debug "[exit of assert_var]" env (Result.get None); check_invariants env (Result.get None); env, changed let register_slake slk p env = if MX.mem slk env.slake then env, false else {env with slake = MX.add slk p env.slake}, true let update_use is_fresh_slk x_status slk use = match x_status with | P.Exists -> assert (SX.mem slk use); use | P.Removed -> assert (SX.mem slk use); SX.remove slk use | P.New -> assert (not is_fresh_slk || not (SX.mem slk use)); SX.add slk use let update_use_list is_fresh modified_stt slk non_basic = List.fold_left (fun non_basic (x, x_status) -> try let i, u = MX.find x non_basic in MX.add x (i, update_use is_fresh x_status slk u) non_basic with Not_found -> assert false )non_basic modified_stt let normalize_polynomial is_fresh slk p env = P.fold (fun x c (q, env) -> try let info, use = MX.find x env.non_basic in let new_q, x_status = P.accumulate x c q in let use = update_use is_fresh x_status slk use in new_q, {env with non_basic = MX.add x (info, use) env.non_basic} with Not_found -> try let _ , p_of_x = MX.find x env.basic in let new_q, modified_stt = P.append q c p_of_x in new_q, {env with non_basic = update_use_list is_fresh modified_stt slk env.non_basic} with Not_found -> (* var not initied -> new non_basic *) let env, chang = assert_non_basic_var env x None Ex.empty None Ex.empty in assert (not chang); let new_q, x_status = P.replace x c q in assert (x_status == P.New); let info, use = try MX.find x env.non_basic with Not_found -> assert false in let use = update_use is_fresh x_status slk use in new_q, { env with non_basic = MX.add x (info, use) env.non_basic} )p (P.empty, env) (* exported function: check_invariants called before and after *) let poly env p slk mini min_ex maxi max_ex = debug "[entry of assert_poly]" env (Result.get None); check_invariants env (Result.get None); assert (P.is_polynomial p); let env, is_fresh = register_slake slk p env in let info, is_basic, env, change = try (* non basic existing var ? *) let info, use = MX.find slk env.non_basic in assert ( let np, _ = normalize_polynomial is_fresh slk p env in let zp, _ = P.accumulate slk R.m_one np in P.is_empty zp ); let info, chang1 = set_min_bound info mini min_ex in let info, chang2 = set_max_bound info maxi max_ex in let old_val = info.value in let info, changed = ajust_value_of_non_basic info in let env = {env with non_basic = MX.add slk (info, use) env.non_basic} in let env = if not changed then env else adapt_values_of_basic_vars env old_val info.value slk use in info, false, env, chang1 || chang2 with Not_found -> try (* basic existing var ? *) let info, poly = MX.find slk env.basic in assert ( let np, _ = normalize_polynomial is_fresh slk p env in P.equal np poly ); let info, chang1 = set_min_bound info mini min_ex in let info, chang2 = set_max_bound info maxi max_ex in info, true, {env with basic = MX.add slk (info, poly) env.basic}, chang1 || chang2 with Not_found -> (* fresh basic var *) assert (is_fresh); let np, env = normalize_polynomial is_fresh slk p env in let info = {empty_info with value = evaluate_poly env np} in let info, chang1 = set_min_bound info mini min_ex in let info, chang2 = set_max_bound info maxi max_ex in info, true, {env with basic = MX.add slk (info, np) env.basic}, chang1 || chang2 in let status, fixme = if is_basic then new_status_basic env.status env.fixme slk info (consistent_bounds info) else new_status_non_basic slk env.status env.fixme info in let env = {env with status; fixme } in debug "[exit of assert_poly]" env (Result.get None); check_invariants env (Result.get None); env, change end (* end of functor Make *) ocplib-simplex-0.4/src/assertBounds.mli000066400000000000000000000020121314727476000202600ustar00rootroot00000000000000(******************************************************************************) (* ocplib-simplex *) (* *) (* Copyright (C) --- OCamlPro --- See README.md for information and licensing *) (******************************************************************************) module type SIG = sig module Core : CoreSig.SIG (* The returned bool is true if the asserted bounds are not trivial (i.e. not implied by known bounds) *) val var : Core.t -> Core.Var.t -> Core.bound -> Core.Ex.t -> Core.bound -> Core.Ex.t -> Core.t * bool (* The returned bool is true if the asserted bounds are not trivial (i.e. not implied by known bounds) *) val poly : Core.t -> Core.P.t -> Core.Var.t -> Core.bound -> Core.Ex.t -> Core.bound -> Core.Ex.t -> Core.t * bool end module Make(Core : CoreSig.SIG) : SIG with module Core = Core ocplib-simplex-0.4/src/basic.ml000066400000000000000000000016441314727476000165260ustar00rootroot00000000000000(******************************************************************************) (* ocplib-simplex *) (* *) (* Copyright (C) --- OCamlPro --- See README.md for information and licensing *) (******************************************************************************) module Make (Var : ExtSigs.VAR_SIG)(R : ExtSigs.R_SIG)(Ex : ExtSigs.EX_SIG) : sig module Core : CoreSig.SIG with module Var=Var and module R=R and module Ex=Ex module Assert : AssertBounds.SIG with module Core := Core module Solve : SolveBounds.SIG with module Core := Core module Result : Result.SIG with module Core := Core end = struct module Core = Core.Make(Var)(R)(Ex) module Assert = AssertBounds.Make(Core) module Solve = SolveBounds.Make(Core) module Result = Result.Make(Core) end ocplib-simplex-0.4/src/basic.mli000066400000000000000000000013671314727476000167010ustar00rootroot00000000000000(******************************************************************************) (* ocplib-simplex *) (* *) (* Copyright (C) --- OCamlPro --- See README.md for information and licensing *) (******************************************************************************) module Make (Var : ExtSigs.VAR_SIG)(R : ExtSigs.R_SIG)(Ex : ExtSigs.EX_SIG) : sig module Core : CoreSig.SIG with module Var=Var and module R=R and module Ex=Ex module Assert : AssertBounds.SIG with module Core := Core module Solve : SolveBounds.SIG with module Core := Core module Result : Result.SIG with module Core := Core end ocplib-simplex-0.4/src/build.ocp000066400000000000000000000011111314727476000167020ustar00rootroot00000000000000comp += [ "-g" ] link += [ "-g" ] comp += [ "-bin-annot" ] comp += [ "-annot" ] comp += [ "-w" "+A" ] comp += [ "-absname" ] comp += [ "-short-paths" ] comp += [ "-strict-sequence" ] begin library "ocplibSimplex" files = [ "version.mli" "version.ml" "extSigs.mli" "rat2.mli" "rat2.ml" "polys.mli" "polys.ml" "coreSig.mli" "core.mli" "core.ml" "result.mli" "result.ml" "assertBounds.mli" "assertBounds.ml" "solveBounds.mli" "solveBounds.ml" "basic.mli" "basic.ml" ] end ocplib-simplex-0.4/src/core.ml000066400000000000000000000441441314727476000163770ustar00rootroot00000000000000(******************************************************************************) (* ocplib-simplex *) (* *) (* Copyright (C) --- OCamlPro --- See README.md for information and licensing *) (******************************************************************************) open Format module Make (Var : ExtSigs.VAR_SIG) (R : ExtSigs.R_SIG) (Ex : ExtSigs.EX_SIG) : CoreSig.SIG with module Var=Var and module R=R and module Ex=Ex = struct module Var = Var module R = R module Ex = Ex module R2 = Rat2.Make(R) module P : Polys.SIG with module Var = Var and module R = R = Polys.Make(Var) (R) module MX : Map.S with type key = Var.t = Map.Make(Var) module SX : Set.S with type elt = Var.t = Set.Make(Var) module SP : Set.S with type elt = P.t = Set.Make(P) type bound = R2.t option type value_status = ValueOK | LowerKO | UpperKO type var_info = { mini : bound; maxi : bound; min_ex : Ex.t; max_ex : Ex.t; value : R2.t; vstatus : value_status; empty_dom : bool; } type solution = { main_vars : (Var.t * R.t) list; slake_vars : (Var.t * R.t) list; int_sol : bool (* always set to false for rational simplexes*) } type maximum = { max_v : R.t; is_le : bool; (* bool = true <-> large bound *) reason: Ex.t } type result = | Unknown | Unsat of Ex.t Lazy.t | Sat of solution Lazy.t | Unbounded of solution Lazy.t | Max of maximum Lazy.t * solution Lazy.t type simplex_status = UNK | UNSAT of Var.t | SAT type t = { basic : (var_info * P.t) MX.t; non_basic : (var_info * SX.t) MX.t; slake : P.t MX.t; fixme : SX.t; is_int : bool; status : simplex_status; debug : int; check_invs: bool; nb_pivots : int ref; } let empty_info = { mini = None; maxi = None; min_ex = Ex.empty; max_ex = Ex.empty; value = R2.zero; vstatus = ValueOK; empty_dom = false; } let empty ~is_int ~check_invs ~debug = { basic = MX.empty; non_basic = MX.empty; slake = MX.empty; fixme = SX.empty; status = UNK; is_int; check_invs; debug; nb_pivots = ref 0 } let on_integers env = env.is_int let equals_optimum v opt = match opt with | None -> false | Some opt -> R2.compare v opt = 0 let violates_min_bound value mn = match mn with | None -> false (* min is -infinity *) | Some min -> R2.compare value min < 0 let violates_max_bound value mx = match mx with | None -> false (* max is +infinity *) | Some max -> R2.compare value max > 0 let consistent_bounds_aux mini maxi = match mini, maxi with | None, None | Some _, None | None, Some _ -> true | Some min, Some max -> R2.compare min max <= 0 let consistent_bounds info = consistent_bounds_aux info.mini info.maxi let set_min_bound info bnd ex = match bnd with | None -> info, false | Some _new -> let mini = info.mini in if violates_min_bound _new mini || equals_optimum _new mini then info, false else let empty_dom = not (consistent_bounds_aux bnd info.maxi) in let i' = if violates_min_bound info.value bnd then {info with mini = bnd; min_ex = ex; vstatus = LowerKO; empty_dom} else {info with mini = bnd; min_ex = ex; empty_dom} in i', true let set_max_bound info bnd ex = match bnd with | None -> info, false | Some _new -> let maxi = info.maxi in if violates_max_bound _new maxi || equals_optimum _new maxi then info, false else let empty_dom = not (consistent_bounds_aux info.mini bnd) in let i' = if violates_max_bound info.value bnd then {info with maxi = bnd; max_ex = ex; vstatus = UpperKO; empty_dom} else {info with maxi = bnd; max_ex = ex; empty_dom} in i', true let ajust_value_of_non_basic info = if info.empty_dom then begin assert (info.vstatus != ValueOK); info, false (* not changed if not sat_bnds *) end else match info.vstatus with | ValueOK -> info, false | UpperKO -> {info with vstatus = ValueOK; value = match info.maxi with | None -> assert false | Some bnd -> bnd}, true | LowerKO -> {info with vstatus = ValueOK; value = match info.mini with | None -> assert false | Some bnd -> bnd}, true let ajust_status_of_basic info = let _new = if violates_min_bound info.value info.mini then LowerKO else if violates_max_bound info.value info.maxi then UpperKO else ValueOK in if info.vstatus == _new then info else {info with vstatus = _new} let evaluate_poly {non_basic; _} p = P.fold (fun x c acc -> let {value = v; _}, _ = try MX.find x non_basic with Not_found -> assert false in R2.add acc (R2.mult_by_const c v) )p R2.zero let poly_of_slake env slk = try Some (MX.find slk env.slake) with Not_found -> None (* debug functions *) module Debug = struct let string_of_status = function | ValueOK -> "OK " | UpperKO -> "KO(Upper)" | LowerKO -> "KO(Lower)" let print_min_bound fmt i = match i.mini with | None -> fprintf fmt "-inf <" | Some (re, im) -> fprintf fmt "%a <%s" R.print re (if R.equal im R.zero then "=" else "") let print_max_bound fmt i = match i.maxi with | None -> fprintf fmt "< +inf" | Some (re, im) -> fprintf fmt "<%s %a" (if R.equal im R.zero then "=" else "") R.print re let re_computed_status_of_info v = if violates_min_bound v.value v.mini then LowerKO else if violates_max_bound v.value v.maxi then UpperKO else ValueOK let print_bounds_and_values fmt mx = MX.iter (fun x (info, _) -> let re, im = info.value in let comp_status = re_computed_status_of_info info in Format.fprintf fmt "%a [ %a == (%4a , %4a) ] %a (computed %s) (flag %s)@." print_min_bound info Var.print x R.print re R.print im print_max_bound info (string_of_status comp_status) (string_of_status info.vstatus); assert (info.empty_dom || comp_status == info.vstatus); )mx let print_uses fmt non_basic = MX.iter (fun x (_, use_x) -> Format.fprintf fmt "variables that use %a are: %a@." Var.print x (fun fmt s -> SX.iter(fprintf fmt "%a , " Var.print) s) use_x; )non_basic let print_solution = let aux fmt l = List.iter (fun (x, q) -> fprintf fmt " %a --> %a@." Var.print x R.print q; )l in fun is_int fmt s -> if is_int then fprintf fmt " (int solution ? %b)@." s.int_sol; aux fmt s.main_vars; aux fmt s.slake_vars let print_result is_int fmt status = match status with | Unknown -> fprintf fmt "Unknown" | Sat s -> fprintf fmt "Sat:@.%a@." (print_solution is_int) (Lazy.force s) | Unsat ex -> fprintf fmt "Unsat:%a@." Ex.print (Lazy.force ex) | Unbounded s -> fprintf fmt "Unbounded:@.%a@." (print_solution is_int) (Lazy.force s) | Max(mx, s) -> let mx = Lazy.force mx in fprintf fmt "Max: (v=%a, is_le=%b, ex=%a)@.%a@." R.print mx.max_v mx.is_le Ex.print mx.reason (print_solution is_int) (Lazy.force s) let print_fixme fmt sx = match SX.elements sx with | [] -> fprintf fmt " (fixme is empty)@."; | l -> List.iter (fprintf fmt " >> %a@." Var.print) l let print_matrix fmt env = MX.iter (fun x (_, p) ->fprintf fmt "%4a = %a@." Var.print x P.print p) env.basic let print result fmt env = Format.fprintf fmt "== begin ========================================@."; fprintf fmt "on integers ? %b@." env.is_int; fprintf fmt "--- values of non-basic ---------------------------@."; print_bounds_and_values fmt env.non_basic; fprintf fmt "---------------------------------------------------@."; fprintf fmt "--- values of basic -------------------------------@."; fprintf fmt "---------------------------------------------------@."; print_bounds_and_values fmt env.basic; fprintf fmt "--- matrix ----------------------------------------@."; print_matrix fmt env; fprintf fmt "---------------------------------------------------@."; fprintf fmt "--- sets of uses ----------------------------------@."; print_uses fmt env.non_basic; fprintf fmt "---------------------------------------------------@."; fprintf fmt "--- basic variables in fixme ----------------------@."; print_fixme fmt env.fixme; fprintf fmt "---------------------------------------------------@."; fprintf fmt "--- simplex status --------------------------------@."; fprintf fmt "%a@." (print_result env.is_int) result; fprintf fmt "== end ==========================================@."; end (* end of module Debug *) let print = Debug.print let debug msg env get_result = if env.debug > 0 then let result = get_result env in Format.eprintf "@.%s@.%a@." msg (print result) env (* check invariants of the simplex: these invariants are listed in extra/simplexe_invariants.txt *) let get_all_polys env = let sp = MX.fold (fun _ (_,p) sp -> SP.add p sp) env.basic SP.empty in MX.fold (fun _ p sp -> SP.add p sp) env.slake sp let get_all_vars env all_polys = let sx = env.fixme in let sx = MX.fold (fun x _ sx -> SX.add x sx) env.basic sx in let sx = MX.fold (fun x (_, use) sx -> SX.union use (SX.add x sx)) env.non_basic sx in let sx = MX.fold (fun x _ sx -> SX.add x sx) env.slake sx in SP.fold (P.fold (fun x _ sx -> SX.add x sx)) all_polys sx let info_of x env = try fst (MX.find x env.non_basic) with Not_found -> try fst (MX.find x env.basic) with Not_found -> assert false let _01__check_type is_int all_vars = SX.iter (fun x -> assert (is_int == Var.is_int x)) all_vars let _02__check_basic_non_basic_disjoint env = MX.iter (fun x _ -> assert (not (MX.mem x env.non_basic))) env.basic; MX.iter (fun x _ -> assert (not (MX.mem x env.basic))) env.non_basic let _03__check_vars_of_polys env polys = SP.iter (P.iter (fun x c -> assert (R.sign c <> 0); assert (MX.mem x env.basic || MX.mem x env.non_basic) ))polys let _04_05_06__check_use env = MX.iter (fun x (_, use) -> SX.iter (fun s -> assert (not (MX.mem s env.non_basic)); (* 04 *) try assert (P.mem x (snd (MX.find s env.basic))) (*05*) with Not_found -> assert false ) use )env.non_basic; MX.iter (fun s (_, p) -> P.iter (fun x _ -> try assert (SX.mem s (snd (MX.find x env.non_basic))); (*06*) with Not_found -> assert false )p; )env.basic let _07__values_ok_for_non_basic_vars env = MX.iter (fun _ (info, _) -> if consistent_bounds info then begin assert (not (violates_min_bound info.value info.mini)); assert (not (violates_max_bound info.value info.maxi)); end else match env.status with | UNSAT _ -> () | SAT | UNK -> assert false )env.non_basic let _08_09__values_ok_when_sat env result = let check mx int_sol = MX.iter (fun _ (info, _) -> let r, i = info.value in assert (not (violates_min_bound info.value info.mini)); assert (not (violates_max_bound info.value info.maxi)); assert (not int_sol || R.is_int r && R.is_zero i) )mx in match result with | Sat s | Unbounded s | Max(_,s) -> let s = Lazy.force s in check env.basic s.int_sol; check env.non_basic s.int_sol | Unsat _ | Unknown -> () let _10_11__check_handling_strict_ineqs env = let is_int = env.is_int in let aux _ (info, _) = begin match info.mini with | None -> () | Some (_, i) -> assert (not is_int || R.is_zero i); assert (is_int || R.is_zero i || R.is_one i); end; begin match info.maxi with | None -> () | Some (_, i) -> assert (not is_int || R.is_zero i); assert (is_int || R.is_zero i || R.is_m_one i); end in MX.iter aux env.basic; MX.iter aux env.non_basic let _12__check_solution_when_sat = let aux l env = List.iter (fun (x, v) -> let info = info_of x env in let v2 = v, R.zero in assert (not (violates_min_bound v2 info.mini)); assert (not (violates_max_bound v2 info.maxi)); )l in fun env result -> match result with | Unsat _ | Unknown -> () | Sat s | Unbounded s | Max(_,s) -> let s = Lazy.force s in let v = List.length s.main_vars + List.length s.slake_vars in let w = MX.cardinal env.non_basic + MX.cardinal env.basic in assert ( if v <> w then eprintf "model length = %d, but basic + non_basic = %d@." v w; v = w); aux s.main_vars env; aux s.slake_vars env let _13__check_reason_when_unsat env = if env.debug > 0 then Format.eprintf "@.[check-invariants] _13__check_reason_when_unsat: TODO@.@." let _14_15__fixme_is_subset_of_basic env = SX.iter (fun x -> try let info, _ = MX.find x env.basic in assert ((violates_min_bound info.value info.mini) || (violates_max_bound info.value info.maxi)); (*15*) with Not_found -> assert false (*14*) ) env.fixme let _16__fixme_containts_basic_with_bad_values_if_not_unsat env all_vars result = match result with | Unsat _ | Unbounded _ | Max _ -> () | Unknown | Sat _ -> SX.iter (fun x -> if not (SX.mem x env.fixme) then let info = info_of x env in assert (not (violates_min_bound info.value info.mini)); assert (not (violates_max_bound info.value info.maxi)) )all_vars let _17__fixme_is_empty_if_not_unknown env result = match result with | Unknown -> () | Unsat _ | Sat _ | Unbounded _ | Max _ -> assert (SX.is_empty env.fixme) let _18__vals_of_basic_vars_computation env = MX.iter (fun _ ({value = s; _}, p) -> let vp = evaluate_poly env p in assert (R2.compare vp s = 0); )env.basic let _19__check_that_vstatus_are_well_set env = let aux _ (info, _) = if info.empty_dom then assert (info.vstatus != ValueOK) else let vmin = violates_min_bound info.value info.mini in let vmax = violates_max_bound info.value info.maxi in match info.vstatus with | ValueOK -> assert (not vmin); assert(not vmax); | UpperKO -> assert (not vmin); assert(vmax); | LowerKO -> assert (vmin); assert(not vmax); in MX.iter aux env.basic; MX.iter aux env.non_basic let _20__bounds_are_consistent_if_not_unsat env result = match result with | Unsat _ -> () | Unknown | Sat _ | Unbounded _ | Max _ -> let aux _ (info, _) = assert (consistent_bounds info) in MX.iter aux env.basic; MX.iter aux env.non_basic let _21__check_coherence_of_empty_dom = let aux mx = MX.iter (fun _ (info, _) -> assert (consistent_bounds info == not info.empty_dom); if info.empty_dom then assert (violates_min_bound info.value info.mini || violates_max_bound info.value info.maxi); )mx in fun env -> aux env.non_basic; aux env.basic let check_invariants env get_result = if env.check_invs then let polys = get_all_polys env in let all_vars = get_all_vars env polys in let result = get_result env in _01__check_type env.is_int all_vars; _02__check_basic_non_basic_disjoint env; _03__check_vars_of_polys env polys; _04_05_06__check_use env; _07__values_ok_for_non_basic_vars env; _08_09__values_ok_when_sat env result; _10_11__check_handling_strict_ineqs env; _12__check_solution_when_sat env result; _13__check_reason_when_unsat env; _14_15__fixme_is_subset_of_basic env; _16__fixme_containts_basic_with_bad_values_if_not_unsat env all_vars result; _17__fixme_is_empty_if_not_unknown env result; _18__vals_of_basic_vars_computation env; _19__check_that_vstatus_are_well_set env; _20__bounds_are_consistent_if_not_unsat env result; (*_21__check_coherence_of_empty_dom env;*) end ocplib-simplex-0.4/src/core.mli000066400000000000000000000010671314727476000165450ustar00rootroot00000000000000(******************************************************************************) (* ocplib-simplex *) (* *) (* Copyright (C) --- OCamlPro --- See README.md for information and licensing *) (******************************************************************************) module Make (Var : ExtSigs.VAR_SIG) (R : ExtSigs.R_SIG) (Ex : ExtSigs.EX_SIG) : CoreSig.SIG with module Var = Var and module R = R and module Ex = Ex ocplib-simplex-0.4/src/coreSig.mli000066400000000000000000000060021314727476000172020ustar00rootroot00000000000000(******************************************************************************) (* ocplib-simplex *) (* *) (* Copyright (C) --- OCamlPro --- See README.md for information and licensing *) (******************************************************************************) (** Interface of the main types and auxiliary of the simplex *) module type SIG = sig module Var : ExtSigs.VAR_SIG module Ex : ExtSigs.EX_SIG module R : ExtSigs.R_SIG module R2 : Rat2.SIG with module R = R module P : Polys.SIG with module Var = Var and module R = R module MX : Map.S with type key = Var.t module SX : Set.S with type elt = Var.t (*module SLAKE : Map.S with type key = P.t*) type bound = R2.t option type value_status = ValueOK | LowerKO | UpperKO type var_info = { mini : bound; maxi : bound; min_ex : Ex.t; max_ex : Ex.t; value : R2.t; vstatus : value_status; empty_dom : bool; } type solution = { main_vars : (Var.t * R.t) list; slake_vars : (Var.t * R.t) list; int_sol : bool (* always set to false for rational simplexes*) } type maximum = { max_v : R.t; is_le : bool; (* bool = true <-> large bound *) reason: Ex.t } type result = | Unknown | Unsat of Ex.t Lazy.t | Sat of solution Lazy.t | Unbounded of solution Lazy.t | Max of maximum Lazy.t * solution Lazy.t type simplex_status = UNK | UNSAT of Var.t | SAT type t = { basic : (var_info * P.t) MX.t; non_basic : (var_info * SX.t) MX.t; slake : P.t MX.t; fixme : SX.t; is_int : bool; status : simplex_status; debug : int; check_invs: bool; nb_pivots : int ref; } val empty_info : var_info val empty : is_int : bool -> check_invs : bool -> debug : int -> t val on_integers : t -> bool val equals_optimum : R2.t -> bound -> bool val consistent_bounds : var_info -> bool val violates_min_bound : R2.t -> bound -> bool val violates_max_bound : R2.t -> bound -> bool (* The returned bool is true if the asserted bounds are not trivial (i.e. not implied by known bounds) *) val set_min_bound : var_info -> bound -> Ex.t -> var_info * bool (* The returned bool is true if the asserted bounds are not trivial (i.e. not implied by known bounds) *) val set_max_bound : var_info -> bound -> Ex.t -> var_info * bool (* vstatus is supposed to be well set *) val ajust_value_of_non_basic: var_info -> var_info * bool (* valuation is supposed to be well computed *) val ajust_status_of_basic : var_info -> var_info val evaluate_poly : t -> P.t -> R2.t val poly_of_slake : t -> Var.t -> P.t option (* debug functions and invariants *) val check_invariants : t -> (t -> result) -> unit val print : result -> Format.formatter -> t -> unit val debug : string -> t -> (t -> result) -> unit end ocplib-simplex-0.4/src/extSigs.mli000066400000000000000000000034561314727476000172470ustar00rootroot00000000000000(******************************************************************************) (* ocplib-simplex *) (* *) (* Copyright (C) --- OCamlPro --- See README.md for information and licensing *) (******************************************************************************) (*----------------------------------------------------------------------------*) (** Interface required for variables *) module type VAR_SIG = sig (** type of variables used in the simplex *) type t (** compare function on vars *) val compare : t -> t -> int (** [is_int v] returns true if the variable has integer type, and false otherwise *) val is_int : t -> bool (** [print fmt v] prints the given var *) val print : Format.formatter -> t -> unit end (*----------------------------------------------------------------------------*) (** Interface required for rationnals *) module type R_SIG = sig (** type of rationnal numbers *) type t val zero : t val one : t val m_one : t val sign : t -> int (* can be used to quickly compare with zero *) val compare : t -> t -> int val equal : t -> t -> bool val is_zero : t -> bool val is_one : t -> bool val is_m_one : t -> bool val add : t -> t -> t val sub : t -> t -> t val div : t -> t -> t val mult : t -> t -> t val abs : t -> t val is_int : t -> bool val print : Format.formatter -> t -> unit val to_string : t -> string val min : t -> t -> t val minus : t -> t end (*----------------------------------------------------------------------------*) (** Interface of explanations *) module type EX_SIG = sig type t val empty : t val union : t -> t -> t val print : Format.formatter -> t -> unit end ocplib-simplex-0.4/src/polys.ml000066400000000000000000000064641314727476000166200ustar00rootroot00000000000000(******************************************************************************) (* ocplib-simplex *) (* *) (* Copyright (C) --- OCamlPro --- See README.md for information and licensing *) (******************************************************************************) module type SIG = sig module Var : ExtSigs.VAR_SIG module R : ExtSigs.R_SIG type t type var_status = New | Exists | Removed val empty : t val is_polynomial : t -> bool val is_empty : t -> bool val replace : Var.t -> R.t -> t -> t * var_status val accumulate : Var.t -> R.t -> t -> t * var_status val append : t -> R.t -> t -> t * (Var.t * var_status) list val subst : Var.t -> t -> t -> t * (Var.t * var_status) list val from_list : (Var.t * R.t) list -> t val print : Format.formatter -> t -> unit val fold: (Var.t -> R.t -> 'a -> 'a) -> t -> 'a -> 'a val iter: (Var.t -> R.t -> unit) -> t -> unit val partition: (Var.t -> R.t -> bool) -> t -> t * t val compare : t -> t -> int val mem : Var.t -> t -> bool val equal : t -> t -> bool val bindings : t -> (Var.t * R.t) list val find : Var.t -> t -> R.t val remove : Var.t -> t -> t end module Make(Var: ExtSigs.VAR_SIG)(R : ExtSigs.R_SIG) : SIG with module Var = Var and module R = R = struct module Var = Var module R = R module MV = Map.Make(Var) type t = R.t MV.t type var_status = New | Exists | Removed let empty = MV.empty let fold = MV.fold let iter = MV.iter let compare = MV.compare R.compare let partition = MV.partition let remove = MV.remove let find = MV.find let bindings = MV.bindings let equal = MV.equal R.equal let mem = MV.mem let is_empty = MV.is_empty let is_polynomial p = try let cpt = ref 0 in iter (fun _ _ -> incr cpt; if !cpt > 1 then raise Exit) p; false with Exit -> true let replace v q t = if R.is_zero q then MV.remove v t, Removed else MV.add v q t, (if MV.mem v t then Exists else New) let accumulate v q t = let new_q = try R.add q (find v t) with Not_found -> q in replace v new_q t (* TODO: We can maybe replace mp with a list, since keys are unique ... *) let append_aux p coef q = fold (fun x c (p, mp) -> let p, x_status = accumulate x (R.mult coef c) p in p, MV.add x x_status mp ) q (p, MV.empty) let append p coef q = let p, mp = append_aux p coef q in p, MV.bindings mp let subst v p q = try let new_q, modified = append_aux (remove v q) (find v q) p in new_q, MV.bindings (MV.add v Removed modified) with Not_found -> (* This will oblige us to enforce strong invariants !! We should know exactly where we have to substitute !! *) assert false let from_list l = List.fold_left (fun p (x, c) -> fst (accumulate x c p)) empty l let print fmt p = let l = MV.bindings p in match l with | [] -> Format.fprintf fmt "(empty-poly)" | (x, q)::l -> Format.fprintf fmt "(%a) * %a" R.print q Var.print x; List.iter (fun (x,q) -> Format.fprintf fmt " + (%a) * %a" R.print q Var.print x) l end ocplib-simplex-0.4/src/polys.mli000066400000000000000000000025671314727476000167710ustar00rootroot00000000000000(******************************************************************************) (* ocplib-simplex *) (* *) (* Copyright (C) --- OCamlPro --- See README.md for information and licensing *) (******************************************************************************) module type SIG = sig module Var : ExtSigs.VAR_SIG module R : ExtSigs.R_SIG type t type var_status = New | Exists | Removed val empty : t val is_polynomial : t -> bool val is_empty : t -> bool val replace : Var.t -> R.t -> t -> t * var_status val accumulate : Var.t -> R.t -> t -> t * var_status val append : t -> R.t -> t -> t * (Var.t * var_status) list val subst : Var.t -> t -> t -> t * (Var.t * var_status) list val from_list : (Var.t * R.t) list -> t val print : Format.formatter -> t -> unit val fold: (Var.t -> R.t -> 'a -> 'a) -> t -> 'a -> 'a val iter: (Var.t -> R.t -> unit) -> t -> unit val partition: (Var.t -> R.t -> bool) -> t -> t * t val compare : t -> t -> int val mem : Var.t -> t -> bool val equal : t -> t -> bool val bindings : t -> (Var.t * R.t) list val find : Var.t -> t -> R.t val remove : Var.t -> t -> t end module Make(Var: ExtSigs.VAR_SIG)(R : ExtSigs.R_SIG) : SIG with module Var = Var and module R = R ocplib-simplex-0.4/src/rat2.ml000066400000000000000000000025621314727476000163150ustar00rootroot00000000000000(******************************************************************************) (* ocplib-simplex *) (* *) (* Copyright (C) --- OCamlPro --- See README.md for information and licensing *) (******************************************************************************) module type SIG = sig module R : ExtSigs.R_SIG type t = R.t * R.t val zero : t val minus : t -> t val add : t -> t -> t val sub : t -> t -> t val mult : t -> t -> t val mult_by_const : R.t -> t -> t val div_by_const : R.t -> t -> t val compare : t -> t -> int val is_zero : t -> bool end module Make(R : ExtSigs.R_SIG) : SIG with module R = R = struct module R = R type t = R.t * R.t let zero = R.zero, R.zero let add (a, b) (x, y) = R.add a x, R.add b y let sub (a, b) (x, y) = R.sub a x, R.sub b y let mult (a, b) (x, y) = R.mult a x, R.mult b y let mult_by_const c e = if R.is_one c then e else let a, b = e in R.mult a c, R.mult b c let div_by_const c e = if R.is_one c then e else let a, b = e in R.div a c, R.div b c let compare (a, b) (x, y) = let c = R.compare a x in if c <> 0 then c else R.compare b y let is_zero (a, b) = R.is_zero a && R.is_zero b let minus (a, b) = R.minus a, R.minus b end ocplib-simplex-0.4/src/rat2.mli000066400000000000000000000014051314727476000164610ustar00rootroot00000000000000(******************************************************************************) (* ocplib-simplex *) (* *) (* Copyright (C) --- OCamlPro --- See README.md for information and licensing *) (******************************************************************************) module type SIG = sig module R : ExtSigs.R_SIG type t = R.t * R.t val zero : t val minus : t -> t val add : t -> t -> t val sub : t -> t -> t val mult : t -> t -> t val mult_by_const : R.t -> t -> t val div_by_const : R.t -> t -> t val compare : t -> t -> int val is_zero : t -> bool end module Make(R : ExtSigs.R_SIG) : SIG with module R = R ocplib-simplex-0.4/src/result.ml000066400000000000000000000124261314727476000167630ustar00rootroot00000000000000(******************************************************************************) (* ocplib-simplex *) (* *) (* Copyright (C) --- OCamlPro --- See README.md for information and licensing *) (******************************************************************************) module type SIG = sig module Core : CoreSig.SIG val get : (Core.P.t * bool) option -> Core.t -> Core.result end module Make(Core : CoreSig.SIG) : SIG with module Core = Core = struct module Core = Core open Core let explain_poly non_basic p ex is_lower = let invert_sign = if is_lower then 1 else -1 in P.fold (fun x coef ex -> let c = invert_sign * R.sign coef in assert (c <> 0); let xi, _ = try MX.find x non_basic with Not_found -> assert false in let ex, optimum = if c > 0 then Ex.union ex xi.max_ex, xi.maxi else Ex.union ex xi.min_ex, xi.mini in assert (equals_optimum xi.value optimum); ex )p ex let get_unsat_core s env = try let si, p = MX.find s env.basic in if not (consistent_bounds si) then Ex.union si.min_ex si.max_ex else match si.vstatus with | ValueOK -> assert false | LowerKO -> explain_poly env.non_basic p si.min_ex true | UpperKO -> explain_poly env.non_basic p si.max_ex false with Not_found -> let si, _ = MX.find s env.non_basic in if not (consistent_bounds si) then Ex.union si.min_ex si.max_ex else assert false let get_int_solution env = let is_int_sol = ref true in let sol = MX.fold (fun x (xi,_) sol -> let re, im = xi.value in assert (R.sign im = 0); is_int_sol := !is_int_sol && R.is_int re; (x, re) :: sol ) env.non_basic [] in let sol = MX.fold (fun x (xi, _) sol -> let re, im = xi.value in assert (R.sign im = 0); is_int_sol := !is_int_sol && R.is_int re; (x, re) :: sol )env.basic sol in let slake = env.slake in let sol_slk, sol = List.partition (fun (x, _) -> MX.mem x slake) sol in { main_vars = sol; slake_vars = sol_slk; int_sol = !is_int_sol } let eval_eps eps inf_r inf_d sup_r sup_d = let c = R.compare inf_r sup_r in assert (c <= 0); if c = 0 || R.compare inf_d sup_d <= 0 then eps else R.min eps (R.div (R.sub sup_r inf_r) (R.sub inf_d sup_d)) let get_rat_solution = let compute_epsilon mp eps = MX.fold (fun _ (i, _) eps -> match i.mini , i.maxi with | None, None -> eps | Some (min_r, min_d), None -> let q1,q2 = i.value in assert (R.equal min_d R.zero || R.equal min_d R.one); let eps = eval_eps eps min_r min_d q1 q2 in assert (R.compare eps R.zero > 0); eps | None, Some (max_r, max_d) -> let q1,q2 = i.value in assert (R.equal max_d R.zero || R.equal max_d R.m_one); let eps = eval_eps eps q1 q2 max_r max_d in assert (R.compare eps R.zero > 0); eps | Some (min_r, min_d), Some (max_r, max_d) -> let q1,q2 = i.value in assert (R.equal min_d R.zero || R.equal min_d R.one); assert (R.equal max_d R.zero || R.equal max_d R.m_one); let eps = eval_eps eps min_r min_d q1 q2 in let eps = eval_eps eps q1 q2 max_r max_d in assert (R.compare eps R.zero > 0); eps ) mp eps in let compute_solution slake mp eps acc = MX.fold (fun x (info, _) (m, s) -> let q1,q2 = info.value in let q = R.add q1 (R.mult q2 eps) in assert (not (violates_min_bound (q, R.zero) info.mini)); assert (not (violates_max_bound (q, R.zero) info.maxi)); if MX.mem x slake then m, (x, q) :: s else (x,q) :: m, s )mp acc in fun env -> let eps = compute_epsilon env.basic R.one in let eps = compute_epsilon env.non_basic eps in let acc = compute_solution env.slake env.basic eps ([], []) in let m,s = compute_solution env.slake env.non_basic eps acc in { main_vars = m ; slake_vars = s; int_sol = false } let get_solution env = if env.is_int then get_int_solution env else get_rat_solution env let get_max_info {non_basic; _} p = let (max_v, symb), reason = Core.P.fold (fun x c (max_v, reason) -> let xi, _ = try MX.find x non_basic with Not_found -> assert false in let ex, bnd = if R.sign c > 0 then xi.max_ex, xi.maxi else xi.min_ex, xi.mini in let value = xi.value in assert (equals_optimum value bnd); R2.add max_v (R2.mult_by_const c value), Ex.union reason ex )p (R2.zero, Ex.empty) in {max_v; is_le = R.is_zero symb; reason} let get opt env = match env.status with | UNK -> Unknown | UNSAT s -> Unsat (lazy (get_unsat_core s env)) | SAT -> match opt with | None -> Sat (lazy (get_solution env)) | Some(_, false) -> Unbounded (lazy (get_solution env)) | Some(p, true) -> Max (lazy(get_max_info env p), lazy(get_solution env)) end ocplib-simplex-0.4/src/result.mli000066400000000000000000000011111314727476000171210ustar00rootroot00000000000000(******************************************************************************) (* ocplib-simplex *) (* *) (* Copyright (C) --- OCamlPro --- See README.md for information and licensing *) (******************************************************************************) module type SIG = sig module Core : CoreSig.SIG val get : (Core.P.t * bool) option -> Core.t -> Core.result end module Make(Core : CoreSig.SIG) : SIG with module Core = Core ocplib-simplex-0.4/src/solveBounds.ml000066400000000000000000000430241314727476000177460ustar00rootroot00000000000000(******************************************************************************) (* ocplib-simplex *) (* *) (* Copyright (C) --- OCamlPro --- See README.md for information and licensing *) (******************************************************************************) module type SIG = sig module Core : CoreSig.SIG val solve : Core.t -> Core.t val maximize : Core.t -> Core.P.t -> Core.t * (Core.P.t * bool) option end module Make(Core : CoreSig.SIG) : SIG with module Core = Core = struct module Core = Core module Result = Result.Make(Core) open Core let gauss_pivot s p x c = let p, _ = P.replace s R.m_one (P.remove x p) in let c = R.div R.m_one c in if R.is_one c then p else P.fold (fun y d q -> fst (P.replace y (R.mult c d) q)) p P.empty exception Out of Var.t * R.t * var_info * SX.t let look_for_next_pivot si pi non_basic = let status = si.vstatus in let is_lower = match status with | ValueOK -> assert false | LowerKO -> 1 | UpperKO -> -1 in try P.iter (fun x coef -> let xi,use = try MX.find x non_basic with Not_found -> assert false in let c = is_lower * R.sign coef in assert (c <> 0); if c > 0 && not (equals_optimum xi.value xi.maxi) then raise (Out (x, coef, xi, use)); if c < 0 && not (equals_optimum xi.value xi.mini) then raise (Out (x, coef, xi, use)); )pi; None with Out (x, c, xi, use) -> Some (x, c, xi, use) let adapt_valuation_of_newly_basic old_si new_si old_xi c_x = let diff = R2.div_by_const c_x (R2.sub new_si.value old_si.value) in { old_xi with value = R2.add diff old_xi.value } (* let string_of_var_status stt = match stt with | P.Removed -> "Removed" | P.New -> "New" | P.Exists -> "Exists" *) (* TODO : review and improve this function *) let rec solve_rec env round = Core.debug (Format.sprintf "[solve] round %d" round) env (Result.get None); Core.check_invariants env (Result.get None); if SX.is_empty env.fixme then {env with status = SAT} else let s = SX.choose env.fixme in let fixme = SX.remove s env.fixme in let si, p = try MX.find s env.basic with Not_found -> assert false in match look_for_next_pivot si p env.non_basic with | None -> {env with fixme = SX.empty; status = UNSAT s} | Some(x, c, xi, use_x) -> if env.debug > 1 then Format.eprintf "[solve_rec] pivot basic %a and non-basic %a@." Var.print s Var.print x; let basic = MX.remove s env.basic in let non_basic = MX.remove x env.non_basic in let q = gauss_pivot s p x c in assert (SX.mem s use_x); let use_x = SX.remove s use_x in let old_si = si in let si, changed = Core.ajust_value_of_non_basic si in assert (changed); let old_xi = xi in let xi = adapt_valuation_of_newly_basic old_si si xi c in let xi = ajust_status_of_basic xi in let diff_xi_val = R2.sub xi.value old_xi.value in let fixme = (* do this earlier to detect bad pivots *) if xi.vstatus == ValueOK then fixme else SX.add x fixme in let non_basic = P.fold (fun y _ non_basic -> let yi, use_y = try MX.find y non_basic with Not_found -> assert false in MX.add y (yi, SX.add x (SX.remove s use_y)) non_basic )(P.remove s q) non_basic in let non_basic = MX.add s (si, SX.add x use_x) non_basic in let basic, non_basic, fixme = SX.fold (fun t (basic, non_basic, fixme) -> let ti0, r = try MX.find t basic with Not_found -> assert false in let cx = try P.find x r with Not_found -> assert false in (*should update_ti*) let diff_cx = R2.mult_by_const cx diff_xi_val in let ti = {ti0 with value = R2.add ti0.value diff_cx} in let ti = ajust_status_of_basic ti in let r', changed = P.subst x q r in (* Format.eprintf "update poly of basic %a@." Var.print t; List.iter (fun (v, vstt) -> Format.eprintf " %a ---> %s@." Var.print v (string_of_var_status vstt); )changed; *) let non_basic = List.fold_left (fun non_basic (z, vstt) -> match vstt with | P.Exists -> non_basic | P.New -> let zi, use_z = try MX.find z non_basic with Not_found -> assert false in MX.add z (zi, SX.add t use_z) non_basic | P.Removed -> if Var.compare z x = 0 then non_basic else let zi, use_z = try MX.find z non_basic with Not_found -> assert false in MX.add z (zi, SX.remove t use_z) non_basic )non_basic changed in (*val subst : Var.t -> t -> t -> t * (Var.t * var_status) list*) let basic = MX.add t (ti, r') basic in let fixme = if ti.vstatus == ValueOK then if ti0.vstatus == ValueOK then fixme else SX.remove t fixme else SX.add t fixme in basic, non_basic, fixme )use_x (basic, non_basic, fixme) in (* ... *) let basic = MX.add x (xi, q) basic in (* ... *) let env = {env with fixme; basic; non_basic} in env.nb_pivots := !(env.nb_pivots) + 1; solve_rec env (round + 1) let solve env = Core.debug "[entry of solve]" env (Result.get None); Core.check_invariants env (Result.get None); let env = match env.Core.status with | Core.UNSAT _ | Core.SAT -> env | Core.UNK -> solve_rec env 1 in Core.debug "[exit of solve]" env (Result.get None); Core.check_invariants env (Result.get None); env let non_basic_to_maximize {non_basic=n_b; _} opt = let acc = ref None in try P.iter (fun x c -> let xi, use = try MX.find x n_b with Not_found -> assert false in let sg = R.sign c in if sg > 0 && not (equals_optimum xi.value xi.maxi) || sg < 0 && not (equals_optimum xi.value xi.mini) then begin acc := Some (x, c, xi, use, sg > 0); raise Exit end )opt; !acc with Exit -> !acc type 'a maximiza_basic = | Free | Stuck | Progress of 'a let basic_var_to_pivot_for_maximization = let choose_best_pivot acc s si p c_px bnd_opt is_min = match bnd_opt with | None -> if !acc = Stuck then acc := Free (* !!! to check *) | Some bnd -> let tmp = if is_min then R2.sub si.value bnd else R2.sub bnd si.value in let ratio = R2.div_by_const (R.abs c_px) tmp in begin match !acc with | Free | Stuck -> acc := Progress (ratio, s, si, p, c_px, bnd, is_min) | Progress (r_old,_,_,_,_,_,_) -> if R2.compare r_old ratio > 0 then acc := Progress (ratio, s, si, p, c_px, bnd, is_min) end; if R2.is_zero ratio then raise Exit (* in the case, the pivot is found*) in fun {basic; _} x use_x should_incr_x -> (* Initially, we assume that we are stuck, unless, use_x is empty *) let acc = ref (if SX.is_empty use_x then Free else Stuck) in try SX.iter (fun s -> let si, p = try MX.find s basic with Not_found -> assert false in let c_px = try P.find x p with Not_found -> assert false in let sg = R.sign c_px in assert (sg <> 0); match should_incr_x, sg > 0, si.mini, si.maxi with | true , true , _, mx_opt -> (* by increasing x, s will increase and max(s) <> +infty *) choose_best_pivot acc s si p c_px mx_opt false | true , false, mn_opt, _ -> (* by increasing x, s will decrease and min(s) <> -infty *) choose_best_pivot acc s si p c_px mn_opt true | false, true , mn_opt, _ -> (* by decreasing x, s will decreease and min(s) <> -infty *) choose_best_pivot acc s si p c_px mn_opt true | false, false, _, mx_opt -> (* by decreasning x, s will increase and max(s) <> +infty *) choose_best_pivot acc s si p c_px mx_opt false (*| true, true, _, None | true, false, None, _ | false, true, None, _ | false, false, _, None -> (* for the cases where max or max = infty, we keep acc unchanged. if acc = None at the end, the problem is unbounded *) () *) )use_x; !acc with Exit -> !acc let can_fix_valuation_without_pivot should_incr xi ratio_opt = if should_incr then match xi.maxi, ratio_opt with | None, _ -> None | Some bnd, Some ratio -> let diff = R2.sub bnd xi.value in if R2.compare diff ratio < 0 then Some ({xi with value = bnd}, diff) else None | Some bnd, None -> let diff = R2.sub bnd xi.value in Some ({xi with value = bnd}, diff) else match xi.mini, ratio_opt with | None, _ -> None | Some bnd, Some ratio -> let diff = R2.sub xi.value bnd in if R2.compare diff ratio < 0 then Some ({xi with value = bnd}, diff) else None | Some bnd, None -> let diff = R2.sub xi.value bnd in Some ({xi with value = bnd}, diff) let update_valuation_without_pivot ({basic; non_basic; _ } as env) x use_x new_xi diff _should_incr = let non_basic = MX.add x (new_xi, use_x) non_basic in let diff = if _should_incr then diff else R2.minus diff in let basic = SX.fold (fun s basic -> let si, p = try MX.find s basic with Not_found -> assert false in let cx = try P.find x p with Not_found -> assert false in assert (not (R.is_zero cx)); let delta = R2.mult_by_const cx diff in let si = {si with value = R2.add si.value delta} in MX.add s (si, p) basic )use_x basic in {env with basic; non_basic} let rec maximize_rec env opt rnd = if env.debug > 1 then Format.eprintf "[maximize_rec] round %d // OPT = %a@." rnd P.print opt; Core.debug (Format.sprintf "[maximize_rec] round %d" rnd) env (Result.get None); Core.check_invariants env (Result.get None); match non_basic_to_maximize env opt with | None -> if env.debug > 1 then Format.eprintf "max reached@."; rnd, env, Some (opt, true) (* max reached *) | Some (_x, _c, _xi, _use_x, _should_incr) -> if env.debug > 1 then Format.eprintf "pivot non basic var %a ?@." Var.print _x; match basic_var_to_pivot_for_maximization env _x _use_x _should_incr with | Free -> if env.debug > 1 then Format.eprintf "non basic %a not constrained by basic vars: Set it to max@." Var.print _x; begin match can_fix_valuation_without_pivot _should_incr _xi None with | Some (new_xi, diff) -> if env.debug > 1 then Format.eprintf "No --> I can set value of %a to min/max WO pivot@." Var.print _x; let env, opt = update_valuation_without_pivot env _x _use_x new_xi diff _should_incr, opt in (* no pivot *) maximize_rec env opt (rnd + 1) | None -> if env.debug > 1 then Format.eprintf "no pivot finally(no upper bnd), pb unbounded@."; rnd, env, Some (opt, false) (* unbounded *) end | Stuck -> if env.debug > 1 then Format.eprintf "no pivot finally, pb unbounded@."; rnd, env, Some (opt, false) (* unbounded *) | Progress (ratio, s, si, p, c_px, bnd, _is_min) -> if env.debug > 1 then Format.eprintf "pivot with basic var %a ?@." Var.print s; let env, opt = match can_fix_valuation_without_pivot _should_incr _xi (Some ratio) with | Some (new_xi, diff) -> if env.debug > 1 then Format.eprintf "No --> I can set value of %a to min/max WO pivot@." Var.print _x; update_valuation_without_pivot env _x _use_x new_xi diff _should_incr, opt | None -> let x = _x in let c = c_px in let use_x = _use_x in let xi = _xi in if env.debug > 1 then Format.eprintf "[maximize_rec] pivot basic %a and non-basic %a@." Var.print s Var.print x; let basic = MX.remove s env.basic in let non_basic = MX.remove x env.non_basic in let q = gauss_pivot s p x c in assert (SX.mem s use_x); let use_x = SX.remove s use_x in let old_si = si in let si = {si with value = bnd} in (* difference wrt solve *) (* because the code of solve below, assumes that value in si violotas a bound let si, changed = Core.ajust_value_of_non_basic si in assert (changed); *) let old_xi = xi in let xi = adapt_valuation_of_newly_basic old_si si xi c in let xi = ajust_status_of_basic xi in let diff_xi_val = R2.sub xi.value old_xi.value in assert(xi.vstatus == ValueOK); let non_basic = P.fold (fun y _ non_basic -> let yi, use_y = try MX.find y non_basic with Not_found -> assert false in MX.add y (yi, SX.add x (SX.remove s use_y)) non_basic )(P.remove s q) non_basic in let non_basic = MX.add s (si, SX.add x use_x) non_basic in let basic, non_basic = SX.fold (fun t (basic, non_basic) -> let ti0, r = try MX.find t basic with Not_found -> assert false in let cx = try P.find x r with Not_found -> assert false in (*should update_ti*) let diff_cx = R2.mult_by_const cx diff_xi_val in let ti = {ti0 with value = R2.add ti0.value diff_cx} in let ti = ajust_status_of_basic ti in let r', changed = P.subst x q r in let non_basic = List.fold_left (fun non_basic (z, vstt) -> match vstt with | P.Exists -> non_basic | P.New -> let zi, use_z = try MX.find z non_basic with Not_found -> assert false in MX.add z (zi, SX.add t use_z) non_basic | P.Removed -> if Var.compare z x = 0 then non_basic else let zi, use_z = try MX.find z non_basic with Not_found -> assert false in MX.add z (zi, SX.remove t use_z) non_basic )non_basic changed in let basic = MX.add t (ti, r') basic in assert(ti.vstatus == ValueOK); basic, non_basic )use_x (basic, non_basic) in (* ... *) let basic = MX.add x (xi, q) basic in (* ... *) {env with basic; non_basic}, (fst (P.subst x q opt)) in env.nb_pivots := !(env.nb_pivots) + 1; maximize_rec env opt (rnd + 1) let maximize env opt0 = let env = solve env in match env.status with | UNK -> assert false | UNSAT _ -> env, None | SAT -> if env.debug > 1 then Format.eprintf "[maximize] pb SAT! try to maximize %a@." P.print opt0; let {basic; non_basic; _} = env in let unbnd = ref false in let opt = P.fold (fun x c acc -> if MX.mem x non_basic then fst (P.accumulate x c acc) else try fst (P.append acc c (snd (MX.find x basic))) with Not_found -> unbnd := true; fst (P.accumulate x c acc) )opt0 P.empty in if !unbnd then env, Some (opt, false) (* unbounded *) else begin if env.debug > 1 then Format.eprintf "start maximization@."; let rnd, env, is_max = maximize_rec env opt 1 in Core.check_invariants env (Result.get is_max); if env.debug > 1 then Format.eprintf "[maximize] pb SAT! Max found ? %b for %a == %a@." (is_max != None) P.print opt0 P.print opt; if env.debug > 1 then Format.eprintf "maximization done after %d steps@." rnd; env, is_max end end ocplib-simplex-0.4/src/solveBounds.mli000066400000000000000000000011631314727476000201150ustar00rootroot00000000000000(******************************************************************************) (* ocplib-simplex *) (* *) (* Copyright (C) --- OCamlPro --- See README.md for information and licensing *) (******************************************************************************) module type SIG = sig module Core : CoreSig.SIG val solve : Core.t -> Core.t val maximize : Core.t -> Core.P.t -> Core.t * (Core.P.t * bool) option end module Make(Core : CoreSig.SIG) : SIG with module Core = Core ocplib-simplex-0.4/src/version.ml000066400000000000000000000006501314727476000171260ustar00rootroot00000000000000(******************************************************************************) (* ocplib-simplex *) (* *) (* Copyright (C) --- OCamlPro --- See README.md for information and licensing *) (******************************************************************************) let version="0.4" ocplib-simplex-0.4/src/version.mli000066400000000000000000000006531314727476000173020ustar00rootroot00000000000000(******************************************************************************) (* ocplib-simplex *) (* *) (* Copyright (C) --- OCamlPro --- See README.md for information and licensing *) (******************************************************************************) val version : string ocplib-simplex-0.4/tests/000077500000000000000000000000001314727476000154615ustar00rootroot00000000000000ocplib-simplex-0.4/tests/ex.ml000066400000000000000000000001771314727476000164340ustar00rootroot00000000000000type t = unit let empty = () let union _ _ = () let print fmt _ = Format.fprintf fmt "[no explanations for this example]" ocplib-simplex-0.4/tests/instantiateBasicFunctor.ml000066400000000000000000000010161314727476000226370ustar00rootroot00000000000000(******************************************************************************) (* ocp-fun-sim *) (* *) (* Copyright (C) --- OCamlPro --- See README.md for information and licensing *) (******************************************************************************) module Ty = Core.Make(Var)(Rat)(Ex) module AB = AssertBounds.Make(Ty) module Basic = OcpFunSim.MakeBasic(Var)(Rat)(Ex) ocplib-simplex-0.4/tests/rat.ml000066400000000000000000000006471314727476000166100ustar00rootroot00000000000000open Num type t = num let add = ( +/ ) let mult = ( */ ) let compare = compare_num let equal = ( =/ ) let zero = Int 0 let one = Int 1 let m_one = Int (-1) let is_zero n = n =/ zero let to_string = string_of_num let print fmt t = Format.fprintf fmt "%s" (to_string t) let is_int = is_integer_num let div = (//) let sub = (-/) let is_one v = v =/ Int 1 let is_m_one v = v =/ Int (-1) let sign = sign_num let min = min_num ocplib-simplex-0.4/tests/solveEmpty.ml000066400000000000000000000005431314727476000201640ustar00rootroot00000000000000module Sim = InstantiateBasicFunctor.Basic let () = let sim = Sim.Core.empty ~is_int:false ~check_invs:true ~debug:1 in let sim = Sim.Solve.solve sim in ignore (sim); match Sim.Result.get sim with | Sim.Core.Unknown -> assert false | Sim.Core.Unsat _ -> assert false | Sim.Core.Sat _ -> Format.printf "[test solveEmpty]: result is Sat@." ocplib-simplex-0.4/tests/standalone_minimal.ml000066400000000000000000000044401314727476000216530ustar00rootroot00000000000000(*== Build the example with: "ocamlopt -o standalone_minimal -I `ocamlfind query ocplib-simplex` \ ocplibSimplex.cmxa nums.cmxa standalone_minimal.ml" if the lib is installed, or with: "ocamlopt -o standalone_minimal -I ../src ocplibSimplex.cmxa \ nums.cmxa standalone_minimal.ml" if the lib is built but not installed ==*) module Var = struct type t = string let print fmt s = Format.fprintf fmt "%s" s let compare = String.compare let is_int _ = true end module Ex = struct module S = Set.Make(String) include S let print fmt s = match elements s with | [] -> Format.fprintf fmt "()" | e::l -> Format.fprintf fmt "%s" e; List.iter (Format.fprintf fmt ", %s") l end module Rat = struct open Num type t = num let add = ( +/ ) let mult = ( */ ) let compare = compare_num let equal = ( =/ ) let zero = Int 0 let one = Int 1 let m_one = Int (-1) let is_zero n = n =/ zero let to_string = string_of_num let print fmt t = Format.fprintf fmt "%s" (to_string t) let is_int = is_integer_num let div = (//) let sub = (-/) let is_one v = v =/ Int 1 let is_m_one v = v =/ Int (-1) let sign = sign_num let min = min_num let abs = abs_num let minus = minus_num end module Sim = OcplibSimplex.Basic.Make(Var)(Rat)(Ex) let () = let sim = Sim.Core.empty ~is_int:true ~check_invs:true ~debug:1 in let zero = Some (Rat.zero, Rat.zero) in let m_one = Some (Rat.m_one, Rat.zero) in (* x >= 0 *) let sim = Sim.Assert.var sim "x" zero (Ex.singleton "x>=0") None Ex.empty in (* y >= 0 *) let sim = Sim.Assert.var sim "y" zero (Ex.singleton "y>=0") None Ex.empty in let x_y = Sim.Core.P.from_list ["x", Rat.one; "y", Rat.one] in (* z == x + y <= -1 *) let sim = Sim.Assert.poly sim x_y "z" None Ex.empty m_one (Ex.singleton "x+y<=-1") in let sim = Sim.Solve.solve sim in match Sim.Result.get None sim with | Sim.Core.Unknown -> assert false | Sim.Core.Sat _ -> assert false | Sim.Core.Max _ -> assert false | Sim.Core.Unbounded _ -> assert false | Sim.Core.Unsat ex -> Format.printf "-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+@."; Format.printf "The problem is unsat! reason: %a@." Ex.print (Lazy.force ex); Format.printf "-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+@.@." ocplib-simplex-0.4/tests/standalone_minimal_maximization.ml000066400000000000000000000053701314727476000244470ustar00rootroot00000000000000(*== Build the example with: "ocamlopt -o standalone_minimal_maximization \ -I `ocamlfind query ocplib-simplex` ocplibSimplex.cmxa nums.cmxa \ standalone_minimal_maximization.ml" if the lib is installed, or with: "ocamlopt -o standalone_minimal_maximization -I ../src ocplibSimplex.cmxa \ nums.cmxa standalone_minimal_maximization.ml" if the lib is built but not installed ==*) module Var = struct type t = string let print fmt s = Format.fprintf fmt "%s" s let compare = String.compare let is_int _ = true end module Ex = struct module S = Set.Make(String) include S let print fmt s = match elements s with | [] -> Format.fprintf fmt "()" | e::l -> Format.fprintf fmt "%s" e; List.iter (Format.fprintf fmt ", %s") l end module Rat = struct open Num type t = num let add = ( +/ ) let mult = ( */ ) let compare = compare_num let equal = ( =/ ) let zero = Int 0 let one = Int 1 let m_one = Int (-1) let is_zero n = n =/ zero let to_string = string_of_num let print fmt t = Format.fprintf fmt "%s" (to_string t) let is_int = is_integer_num let div = (//) let sub = (-/) let is_one v = v =/ Int 1 let is_m_one v = v =/ Int (-1) let sign = sign_num let min = min_num let abs = abs_num let minus = minus_num end module Sim = OcplibSimplex.Basic.Make(Var)(Rat)(Ex) let sep () = Format.printf "-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+@." let aux sim opt_p = let sim, opt = Sim.Solve.maximize sim opt_p in sep (); Format.printf "The problem 'max %a' ...@." Sim.Core.P.print opt_p; begin match Sim.Result.get opt sim with | Sim.Core.Unknown -> assert false | Sim.Core.Sat _ -> assert false | Sim.Core.Unsat ex -> Format.printf " is unsat (reason = %a)@." Ex.print (Lazy.force ex); | Sim.Core.Unbounded _ -> Format.printf " is unbounded@." | Sim.Core.Max (mx,_) -> let {Sim.Core.max_v; is_le; reason} = Lazy.force mx in Format.printf " has an upper bound: %a (is_le = %b)(reason: %a)@." Rat.print max_v is_le Ex.print reason; end; sep (); Format.printf "@." let () = let sim = Sim.Core.empty ~is_int:true ~check_invs:true ~debug:0 in let x_y = Sim.Core.P.from_list ["x", Rat.one; "y", Rat.one] in let ten = Some (Num.Int (10), Num.Int 0) in let three = Some (Num.Int (3), Num.Int 0) in (* s == x + y >= 10 let sim = Sim.Assert.poly sim x_y "s" ten Ex.empty None Ex.empty in *) (* x <= 5 *) let sim = Sim.Assert.var sim "x" three (Ex.singleton "x>=3") None Ex.empty in (* s == x + y <= 10 *) let sim = Sim.Assert.poly sim x_y "s" None Ex.empty ten (Ex.singleton "x+y<=10") in aux sim x_y; aux sim (Sim.Core.P.from_list ["y", Rat.one]); aux sim (Sim.Core.P.from_list ["y", Rat.m_one]); ocplib-simplex-0.4/tests/var.ml000066400000000000000000000010061314727476000166000ustar00rootroot00000000000000(******************************************************************************) (* ocp-fun-sim *) (* *) (* Copyright (C) --- OCamlPro --- See README.md for information and licensing *) (******************************************************************************) type t = string let print fmt s = Format.fprintf fmt "%s" s let compare = String.compare let is_int _ = true