pax_global_header00006660000000000000000000000064146013033200014502gustar00rootroot0000000000000052 comment=12e7c1fd994d4c40cf7159008a67579f470df616 ocplib-simplex-0.5.1/000077500000000000000000000000001460130332000144345ustar00rootroot00000000000000ocplib-simplex-0.5.1/.editorconfig000066400000000000000000000002411460130332000171060ustar00rootroot00000000000000root = true [*] indent_style = space indent_size = 2 charset = utf-8 trim_trailing_whitespace = true insert_final_newline = true [Makefile] indent_style = tab ocplib-simplex-0.5.1/.github/000077500000000000000000000000001460130332000157745ustar00rootroot00000000000000ocplib-simplex-0.5.1/.github/workflows/000077500000000000000000000000001460130332000200315ustar00rootroot00000000000000ocplib-simplex-0.5.1/.github/workflows/build.yml000066400000000000000000000020201460130332000216450ustar00rootroot00000000000000name: Build on: push: pull_request: permissions: {} env: OCAML_DEFAULT_VERSION: 4.08.1 # Add OPAMYES=true to the environment, this is usefill to replace `-y` option # in any opam call OPAMYES: true jobs: build: strategy: fail-fast: false matrix: os: - macos-latest - ubuntu-latest ocaml-compiler: - 4.08.1 - 5.0.0 runs-on: ${{ matrix.os }} steps: - name: Checkout uses: actions/checkout@v4 with: persist-credentials: true - name: Use OCaml ${{ matrix.ocaml-compiler }} uses: ocaml/setup-ocaml@v2 with: allow-prerelease-opam: true ocaml-compiler: ${{ matrix.ocaml-compiler }} dune-cache: true - name: Install dependencies run: opam exec -- opam install -y . --locked --deps-only --with-test - name: Build ocplib-simplex with opam run: opam exec -- opam reinstall . - name: Run tests run: opam exec -- make test ocplib-simplex-0.5.1/.github/workflows/documentation.yml000066400000000000000000000015461460130332000234330ustar00rootroot00000000000000name: Documentation on: push: branches: - master env: OCAML_DEFAULT_VERSION: 5.0.0 OPAMYES: true jobs: build-and-deploy: runs-on: ubuntu-latest env: OPAMWITHDOC: true steps: - name: Checkout uses: actions/checkout@v4 - name: Use OCaml ${{ env.OCAML_DEFAULT_VERSION }} uses: ocaml/setup-ocaml@v2 with: allow-prerelease-opam: true ocaml-compiler: ${{ env.OCAML_DEFAULT_VERSION }} dune-cache: true - name: Install dependencies run: opam install . --deps-only --with-doc - name: Make odoc documentation run: opam exec -- make doc - name: Deploy uses: JamesIves/github-pages-deploy-action@v4 with: token: ${{ secrets.GITHUB_TOKEN }} branch: gh-pages folder: _build/default/_doc/_html/ ocplib-simplex-0.5.1/.gitignore000066400000000000000000000000461460130332000164240ustar00rootroot00000000000000_opam _build .merlin *.install *.swp ocplib-simplex-0.5.1/CHANGES.md000066400000000000000000000033241460130332000160300ustar00rootroot00000000000000## unreleased ## v0.5.1 (2024-03-28) * Add documentation for solving system (PR #16). * Separate types for coefficents and values (PR #17). * Remove the dependency on `num` (PR #19). * Remove messages at the `App` level (PR #22). ## 0.4.1 (2023-04-21) * Fix the issue 13 about strict formats (PR #18). ## 0.5 (2022-11-15) * Reworking the library build system, now only relying on dune. The Makefile is now clearer and simpler to use. * Logs are handled by the `logs` library and debug is activated by this library. * The `Rat2` module now abstract bounds as strict upper, strict lower or soft bounds instead of pairs of rationals. ## 0.4 (2017-08-22) * 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. ## 0.3 (2016-11-09) * Bugfix in maximization ## 0.2 (2016-08-24) * 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 ## 0.1 (2016-07-11) * 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.5.1/CONTRIBUTING.md000066400000000000000000000013551460130332000166710ustar00rootroot00000000000000# Guide to contributing to Ocplib-simplex ## Release Process - Make a PR on `master` to initiate the release. The PR must introduce a new section in `CHANGES.md` with the new version number; - Once the PR is merged, create a new `vX.Y.Z` branch for the release from the current `master`. ## Make the release The release is made using `dune-release`, and follows standard procedure for the tool: - `dune-release check` performs basic check; - `dune-release tag vX.Y.Z` creates a tag on the current branch; - `dune-release distrib` creates the distribution archive; - `dune-release publish` publishes the release on GitHub; - `dune-release opam pkg` creates an archive for opam; - `dune-release opam submit` opens a PR on the opam repository. ocplib-simplex-0.5.1/LICENSE000066400000000000000000000647711460130332000154600ustar00rootroot00000000000000In 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.5.1/Makefile000066400000000000000000000015431460130332000160770ustar00rootroot00000000000000 build: @dune build @all @install doc: @dune build @doc all: build doc clean: @dune clean test: build @dune runtest --no-buffer -f lock: dune build ./ocplib-simplex.opam opam lock ./ocplib-simplex.opam -w # Remove OCaml compiler constraints sed -i '/"ocaml"\|"ocaml-base-compiler"\|"ocaml-system"\|"ocaml-config"/d' ./ocplib-simplex.opam.locked WATCH?= @all watch: @dune build $(WATCH) -w install: build @dune install uninstall: @dune uninstall reindent: @find src '(' -name '*.ml' -or -name '*.mli' ')' -print0 | xargs -0 echo "reindenting: " @find src '(' -name '*.ml' -or -name '*.mli' ')' -print0 | xargs -0 sed -i 's/[[:space:]]*$$//' @find src '(' -name '*.ml' -or -name '*.mli' ')' -print0 | xargs -0 ocp-indent -i opam-deps: opam install . --deps-only .PHONY: build doc all clean test lock watch install uninstall reindent opam-deps ocplib-simplex-0.5.1/README.md000066400000000000000000000033201460130332000157110ustar00rootroot00000000000000# Ocplib-simplex `Ocplib-simplex` a is library implementing a simplex algorithm, in a functional style, for solving systems of linear inequalities and optimizing linear objective functions. The implementation is incremental and backtrackable. It is able to extract unsat-cores for unsatisfiable problems. Versions `> 0.1` also support linear optimization. ## Website Ocplib-simplex's web is available at: https://ocamlpro.github.io/ocplib-simplex ## Dependencies `ocplib-simplex` requires `4.08.1` 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: $ 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. Please follow the [contribution guide][contributing]. ## 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.5.1/dune-project000066400000000000000000000021421460130332000167550ustar00rootroot00000000000000(lang dune 2.0) (generate_opam_files true) (name ocplib-simplex) (version dev) (source (github OCamlPro/ocplib-simplex)) (authors "Mohamed Iguernlala " "Hichem Ait El Hara " "Steven de Oliveira " "Guillaume Bury " "Pierre Villemot " ) (maintainers "OCamlPro ") (documentation "https://ocamlpro.github.io/ocplib-simplex") (package (name ocplib-simplex) (synopsis "A library implementing a simplex algorithm, in a functional style, for solving systems of linear inequalities") (description "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.") (license "LGPL-2.1-or-later") (depends (ocaml (>= 4.02.0)) (dune (>= 2.0)) (ocamlfind (>= 1.9.1)) (zarith :with-test) (logs (>= 0.5.0)) (odoc :with-doc) )) ocplib-simplex-0.5.1/extra/000077500000000000000000000000001460130332000155575ustar00rootroot00000000000000ocplib-simplex-0.5.1/extra/TODO.txt000066400000000000000000000017131460130332000170670ustar00rootroot00000000000000global: ------- - 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 - optimization: early detection of unsat if one of the variables in fixme cannot be fixed 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.5.1/extra/simplex_invariants.txt000066400000000000000000000050451460130332000222430ustar00rootroot00000000000000Basic 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.5.1/ocplib-simplex.opam000066400000000000000000000026021460130332000202410ustar00rootroot00000000000000# This file is generated by dune, edit dune-project instead opam-version: "2.0" version: "dev" synopsis: "A library implementing a simplex algorithm, in a functional style, for solving systems of linear inequalities" description: "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." maintainer: ["OCamlPro "] authors: [ "Mohamed Iguernlala " "Hichem Ait El Hara " "Steven de Oliveira " "Guillaume Bury " "Pierre Villemot " ] license: "LGPL-2.1-or-later" homepage: "https://github.com/OCamlPro/ocplib-simplex" doc: "https://ocamlpro.github.io/ocplib-simplex" bug-reports: "https://github.com/OCamlPro/ocplib-simplex/issues" depends: [ "ocaml" {>= "4.02.0"} "dune" {>= "2.0"} "ocamlfind" {>= "1.9.1"} "zarith" {with-test} "logs" {>= "0.5.0"} "odoc" {with-doc} ] build: [ ["dune" "subst"] {pinned} [ "dune" "build" "-p" name "-j" jobs "@install" "@runtest" {with-test} "@doc" {with-doc} ] ] dev-repo: "git+https://github.com/OCamlPro/ocplib-simplex.git" ocplib-simplex-0.5.1/ocplib-simplex.opam.locked000066400000000000000000000027051460130332000215050ustar00rootroot00000000000000opam-version: "2.0" name: "ocplib-simplex" version: "0.5" synopsis: "ocplib-simplex: A library implementing a simplex algorithm, in a functional style, for solving systems of linear inequalities" description: "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." maintainer: "OCamlPro " authors: [ "Mohamed Iguernlala " "Hichem Ait El Hara " "Steven de Oliveira " "Guillaume Bury " ] license: "LICENSE" homepage: "https://github.com/OCamlPro/ocplib-simplex" doc: "https://github.com/OCamlPro/ocplib-simplex" bug-reports: "https://github.com/OCamlPro/ocplib-simplex/issues" depends: [ "base-bigarray" {= "base"} "base-threads" {= "base"} "base-unix" {= "base"} "conf-gmp" {= "4" & with-test} "dune" {= "3.14.2"} "logs" {= "0.7.0"} "ocamlbuild" {= "0.14.3"} "ocamlfind" {= "1.9.6"} "topkg" {= "1.0.7"} "zarith" {= "1.13" & with-test} ] build: [ ["dune" "subst"] {pinned} [ "dune" "build" "-p" name "-j" jobs "@install" "@runtest" {with-test} "@doc" {with-doc} ] ] dev-repo: "git+https://github.com/OCamlPro/ocplib-simplex.git" ocplib-simplex-0.5.1/src/000077500000000000000000000000001460130332000152235ustar00rootroot00000000000000ocplib-simplex-0.5.1/src/assertBounds.ml000066400000000000000000000226171460130332000202410ustar00rootroot00000000000000(******************************************************************************) (* ocplib-simplex *) (* *) (* Copyright (C) --- OCamlPro --- See README.md for information and licensing *) (******************************************************************************) module type S = sig module Core : CoreSig.S val var : Core.t -> ?min:Core.bound -> ?max:Core.bound -> Core.Var.t -> Core.t * bool val poly : Core.t -> Core.P.t -> ?min:Core.bound -> ?max:Core.bound -> Core.Var.t -> Core.t * bool end module Make(Core : CoreSig.S) : S with module Core = Core = struct module Core = Core module Result = Result.Make(Core) open Core let empty_info value = { mini = None; maxi = None; value; vstatus = ValueOK; empty_dom = false; } (* If the environment works on integers and bounds are strict, we shift the bound so that it is a large bound. Same goes on rational bounds in an integer simplex. Ex: * x > 5 + Ɛ -> x >= 6 * x > 4/3 -> x >= 2 *) let update_bound (get_closer : R2.t -> R2.t) (env : Core.t) (bnd : bound option) = match bnd with | Some b when env.is_int -> Some {b with bvalue = get_closer b.bvalue} | other -> other let update_min_bound = update_bound R2.ceiling let update_max_bound = update_bound R2.floor 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 maxi = let info, poly, changed = try let info, poly = MX.find x env.basic in let info, chang1 = set_min_bound info mini in let info, chang2 = set_max_bound info maxi 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 maxi = let info, use = try MX.find x env.non_basic with Not_found -> empty_info R2.zero, SX.empty in let info, chang1 = set_min_bound info mini in let info, chang2 = set_max_bound info maxi 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 ?min ?max x = debug "[entry of assert_var]" env (Result.get None); check_invariants env (Result.get None); let mini = update_min_bound env min in let maxi = update_max_bound env max in let env, changed = if MX.mem x env.basic then assert_basic_var env x mini maxi else assert_non_basic_var env x mini maxi 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 None 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 ?min ?max slk = debug "[entry of assert_poly]" env (Result.get None); check_invariants env (Result.get None); assert (P.is_polynomial p); let mini = update_min_bound env min in let maxi = update_max_bound env max in 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 in let info, chang2 = set_max_bound info maxi 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 in let info, chang2 = set_max_bound info maxi 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 (evaluate_poly env np) in let info, chang1 = set_min_bound info mini in let info, chang2 = set_max_bound info maxi 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.5.1/src/assertBounds.mli000066400000000000000000000031321460130332000204010ustar00rootroot00000000000000(******************************************************************************) (* ocplib-simplex *) (* *) (* Copyright (C) --- OCamlPro --- See README.md for information and licensing *) (******************************************************************************) module type S = sig module Core : CoreSig.S (* The returned bool is [true] if the asserted bounds are not trivial (i.e. not implied by known bounds) *) (** [var env min max x] returns a new environment obtained by changing the bounds of [x] in [env] to [min] and [max]. If the bounds were implied by other known bounds (in other words, if the environment did not change) the associated boolean will be [false]. *) val var : Core.t -> ?min:Core.bound -> ?max:Core.bound -> Core.Var.t -> Core.t * bool (* The returned bool is [true] if the asserted bounds are not trivial (i.e. not implied by known bounds) *) (** [poly env poly min max x] returns a new environment obtained by changing the bounds of [poly] in [env] to [min] and [max]. The polynomial is represented by the slack variable [x]. If the bounds were implied by other known bounds (in other words, if the environment did not change) the associated boolean will be [false]. *) val poly : Core.t -> Core.P.t -> ?min:Core.bound -> ?max:Core.bound -> Core.Var.t -> Core.t * bool end module Make(Core : CoreSig.S) : S with module Core = Core ocplib-simplex-0.5.1/src/basic.ml000066400000000000000000000017231460130332000166410ustar00rootroot00000000000000(******************************************************************************) (* ocplib-simplex *) (* *) (* Copyright (C) --- OCamlPro --- See README.md for information and licensing *) (******************************************************************************) open ExtSigs module Make (Var : Variables) (R : Rationals) (Ex : Explanations) : sig module Core : CoreSig.S with module Var=Var and type R.t = R.t and type V.t = R.t and module Ex=Ex module Assert : AssertBounds.S with module Core := Core module Solve : SolveBounds.S with module Core := Core module Result : Result.S 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.5.1/src/basic.mli000066400000000000000000000020031460130332000170020ustar00rootroot00000000000000(******************************************************************************) (* ocplib-simplex *) (* *) (* Copyright (C) --- OCamlPro --- See README.md for information and licensing *) (******************************************************************************) open ExtSigs (** The main entry point of the library. It provides a functor building each key module of OcplibSimplex. *) module Make (Var : Variables)(R : Rationals)(Ex : Explanations) : sig (** The core module defines the different data types used by the project and some functions to handle them. *) module Core : CoreSig.S with module Var=Var and type R.t=R.t and type V.t = R.t and module Ex=Ex module Assert : AssertBounds.S with module Core := Core module Solve : SolveBounds.S with module Core := Core module Result : Result.S with module Core := Core end ocplib-simplex-0.5.1/src/core.ml000066400000000000000000000442021460130332000165070ustar00rootroot00000000000000(******************************************************************************) (* ocplib-simplex *) (* *) (* Copyright (C) --- OCamlPro --- See README.md for information and licensing *) (******************************************************************************) open Format open ExtSigs let src = Logs.Src.create "OcplibSimplex.Core" ~doc:"The Core of the simplex solver" module MakeExpert (Var : Variables) (R : Coefs) (V : Value with type r = R.t) (Ex : Explanations) (R2 : Rat2.SIG with module R = R and module V = V) (P : Polys.SIG with module Var = Var and module R = R) (MX : MapSig with type key = Var.t) (SX : SetSig with type elt = Var.t) : CoreSig.S with module Var=Var and module R=R and module V = V and module Ex=Ex and module P = P and module MX = MX and module SX = SX = struct module Var = Var module R = R module V = V module Ex = Ex module R2 = R2 module P = P module MX = MX module SX = SX type bound = { bvalue : R2.t; explanation : Ex.t } type value_status = ValueOK | LowerKO | UpperKO type var_info = { mini : bound option; maxi : bound option; value : R2.t; vstatus : value_status; empty_dom : bool; } type solution = { main_vars : (Var.t * V.t) list; slake_vars : (Var.t * V.t) list; int_sol : bool; (* always set to false for rational simplexes*) epsilon : V.t; } type maximum = { max_v : bound; is_le : bool; (* bool = true <-> large bound *) } 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; check_invs: bool; nb_pivots : int ref; } let empty ~is_int ~check_invs = { basic = MX.empty; non_basic = MX.empty; slake = MX.empty; fixme = SX.empty; status = UNK; is_int; check_invs; nb_pivots = ref 0 } let on_integers env = env.is_int let equals_optimum (b : R2.t) (opt : bound option) = match opt with | None -> false | Some opt -> R2.compare b opt.bvalue = 0 let violates_min_bound (b : R2.t) (mn : bound option) = match mn with | None -> false (* min is -infinity *) | Some min -> R2.compare b min.bvalue < 0 let violates_max_bound (b : R2.t) (mx : bound option) = match mx with | None -> false (* max is +infinity *) | Some max -> R2.compare b max.bvalue > 0 let consistent_bound_value min max = R2.compare min max <= 0 let consistent_bounds_aux (mini : bound option) (maxi : bound option) = match mini, maxi with | None, None | Some _, None | None, Some _ -> true | Some {bvalue = min; _}, Some {bvalue = max; _} -> consistent_bound_value min max let consistent_bounds info = consistent_bounds_aux info.mini info.maxi let set_min_bound info (bnd : bound option) = match bnd with | None -> info, false | Some _new -> let mini = info.mini in if violates_min_bound _new.bvalue mini || equals_optimum _new.bvalue 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; vstatus = LowerKO; empty_dom} else {info with mini = bnd; empty_dom} in i', true let set_max_bound info (bnd : bound option) = match bnd with | None -> info, false | Some _new -> let maxi = info.maxi in if violates_max_bound _new.bvalue maxi || equals_optimum _new.bvalue 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; vstatus = UpperKO; empty_dom} else {info with maxi = bnd; 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.bvalue}, true | LowerKO -> {info with vstatus = ValueOK; value = match info.mini with | None -> assert false | Some bnd -> bnd.bvalue}, 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 let expl_of_min_bound vinfo = match vinfo.mini with | None -> Ex.empty | Some {explanation; _} -> explanation let expl_of_max_bound vinfo = match vinfo.maxi with | None -> Ex.empty | Some {explanation; _} -> explanation (* debug functions *) module Debug = struct let string_of_status = function | ValueOK -> "OK " | UpperKO -> "KO(Upper)" | LowerKO -> "KO(Lower)" let print_min_bound fmt (i : var_info) = match i.mini with | None -> fprintf fmt "-∞ <" | Some min -> fprintf fmt "%a <=" R2.print min.bvalue let print_max_bound fmt i = match i.maxi with | None -> fprintf fmt "< +∞" | Some max -> fprintf fmt "<= %a" R2.print max.bvalue 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 v = info.value in let comp_status = re_computed_status_of_info info in Format.fprintf fmt "%a [ %a == %a ] %a (computed %s) (flag %s)@." print_min_bound info Var.print x R2.print v 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 V.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@." R2.print mx.max_v.bvalue mx.is_le Ex.print mx.max_v.explanation (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 "%a = %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 Logs.Src.level src <> None then let result = get_result env in Logs.info ~src (fun p -> p "@.%s@.%a@." msg (print result) env) (* check invariants of the simplex: these invariants are listed in extra/simplexe_invariants.txt *) module SP : Set.S with type elt = P.t = Set.Make(P) 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 v = info.value in assert (not (violates_min_bound v info.mini)); assert (not (violates_max_bound v info.maxi)); assert (not int_sol || V.is_int v.R2.v && R.is_zero v.R2.offset) ) mx in match result with | Unsat _ | Unknown -> () | 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 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 m -> let i = m.bvalue.R2.offset in 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 m -> let i = m.bvalue.R2.offset in 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 = R2.of_r v 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 = Logs.info ~src (fun p -> p ~header:"[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.equal vp s); )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 module Make (Var : Variables) (R : Rationals) (Ex : Explanations) : CoreSig.S with module Var=Var and type R.t = R.t and type V.t = R.t and module Ex=Ex = struct module V' = struct include R type r = t let mult_by_coef = mult let div_by_coef = div end include MakeExpert(Var)(R)(V')(Ex)(Rat2.Make(R)(V'))(Polys.Make(Var)(R)) (Map.Make(Var))(Set.Make(Var)) end ocplib-simplex-0.5.1/src/core.mli000066400000000000000000000022311460130332000166540ustar00rootroot00000000000000(******************************************************************************) (* ocplib-simplex *) (* *) (* Copyright (C) --- OCamlPro --- See README.md for information and licensing *) (******************************************************************************) open ExtSigs val src : Logs.src module Make (Var : Variables) (R : Rationals) (Ex : Explanations) : CoreSig.S with module Var = Var and type R.t = R.t and type V.t = R.t and module Ex = Ex module MakeExpert (Var : Variables) (R : Coefs) (V : Value with type r = R.t) (Ex : Explanations) (R2 : Rat2.SIG with module R = R and module V = V) (P : Polys.SIG with module Var = Var and module R = R) (MX : MapSig with type key = Var.t) (SX : SetSig with type elt = Var.t) : CoreSig.S with module Var=Var and module R=R and module V=V and module Ex=Ex and module P = P and module MX = MX and module SX = SX (** Same than Make but allows to choose the implementation of polynomials, maps and sets *) ocplib-simplex-0.5.1/src/coreSig.mli000066400000000000000000000137451460130332000173330ustar00rootroot00000000000000(******************************************************************************) (* ocplib-simplex *) (* *) (* Copyright (C) --- OCamlPro --- See README.md for information and licensing *) (******************************************************************************) open ExtSigs (** Interface of the main types and auxiliary of the simplex. *) module type S = sig (** {1 Modules} *) (** The type of variables maipulated by the simplex algorithm. *) module Var : Variables (** An interface for explanations; in practice, they are labels attached to bounds used for backtracking information on how bounds were discovered. The simplex algorithm does not create explanations: it will only attach empty explanations to bounds, build the union of explanations and print them. It is the user's job to provide the initial explanations when initializing the simplex core. *) module Ex : Explanations (** The interface for rationals provided by users for the coefficient. *) module R : Coefs (** The interface for values of variable and bounds provided by users. *) module V : Value with type r = R.t (** Pairs of rationals R representing bounds with an offset [x + kƐ]. *) module R2 : Rat2.SIG with module R = R and module V = V (** Linear relations of variables. *) module P : Polys.SIG with module Var = Var and module R = R (** Collections of variables. *) module MX : MapSig with type key = Var.t module SX : SetSig with type elt = Var.t (*module SLAKE : Map.S with type key = P.t*) (** {1 Types} *) (** A bound is a value of the form [x + kƐ] and an explanation. *) type bound = { bvalue : R2.t; explanation : Ex.t } type value_status = | ValueOK (** The value is inbetween bounds. *) | LowerKO (** The value is smaller than the lower bound. *) | UpperKO (** The value is greater than the upper bound. *) type var_info = { mini : bound option; (* None -> -inf *) maxi : bound option; (* None -> +inf *) value : R2.t; vstatus : value_status; empty_dom : bool; } type solution = { main_vars : (Var.t * V.t) list; slake_vars : (Var.t * V.t) list; int_sol : bool; (* Always set to false for rational simplexes. *) epsilon : V.t; } type maximum = { max_v : bound; is_le : bool; (* bool = true <-> large bound *) } 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; check_invs : bool; nb_pivots : int ref; } (** Returns a simplex environment with three parameters: - [is_int]: will the simplex work on an integer optimization problem or a rational problem? - [check_invs]: processes checks after the calculation (deprecated). *) val empty : is_int : bool -> check_invs : bool -> t (** Returns [true] if the simplex environment is on integers. *) val on_integers : t -> bool (** Equality check between bounds. *) val equals_optimum : R2.t -> bound option -> bool (** Checks if the lower bound of a variable is smaller than its upper bound. *) val consistent_bounds : var_info -> bool (** [violates_min_bound b mb] returns [true] if [b] is smaller than [mb]. *) val violates_min_bound : R2.t -> bound option -> bool (** [violates_max_bound b mb] returns [true] if [b] is greater than [mb]. *) val violates_max_bound : R2.t -> bound option -> bool (* The returned bool is [true] if the asserted bounds are not trivial (i.e. not implied by known bounds). *) (** [set_min_bound vinfo b] returns a couple [(vinfo', changed)] where: - [vinfo'] is the new variable info where the new min bound [b] has been set. - [changed] is [true] if the new bound has changed the variable info *) val set_min_bound : var_info -> bound option -> var_info * bool (** Same as {!val:set_min_bound}, but for max bounds. *) val set_max_bound : var_info -> bound option -> var_info * bool (** [ajust_value_of_non_basic vinfo] updates the info's value with the upper bound (resp. the lower bound), if [vinfo]'s status is {!constructor:UpperKO} (resp. {!constructor:LowerKO}). Otherwise, do nothing. The boolean returned is [true] if the new variable [var_info] has changed. *) val ajust_value_of_non_basic: var_info -> var_info * bool (* vstatus is supposed to be well set *) (** [ajust_status_of_basic vinfo] checks a variable info's bound matches its status. If its value violates its lower bound, its status is set to {!constructor:LowerKO}. In the other case, it is set to {!constructor:UpperKO}. If the value is between the two bounds, it is set to {!constructor:ValueOK}. *) val ajust_status_of_basic : var_info -> var_info (* valuation is supposed to be well computed *) (** Evaluates a polynomial of non basic variables. *) val evaluate_poly : t -> P.t -> R2.t (** [poly_of_slake env slake] returns the polynomial associated to the variable [slake] in [env]. *) val poly_of_slake : t -> Var.t -> P.t option (** Returns the explanation associated to a variable lower bound. *) val expl_of_min_bound : var_info -> Ex.t (** Same as `expl_of_min_bound`, but for upper bounds. *) val expl_of_max_bound : var_info -> Ex.t (** {1 Debug functions} *) (** Only use for internal debugging *) (** Checks several invariants in the project *) val check_invariants : t -> (t -> result) -> unit (** Pretty prints the environment. *) val print : result -> Format.formatter -> t -> unit (** @deprecated *) val debug : string -> t -> (t -> result) -> unit end ocplib-simplex-0.5.1/src/dune000066400000000000000000000002031460130332000160740ustar00rootroot00000000000000(library (name OcplibSimplex) (public_name ocplib-simplex) (libraries logs) (modules_without_implementation coreSig extSigs) ) ocplib-simplex-0.5.1/src/extSigs.mli000066400000000000000000000073761460130332000173710ustar00rootroot00000000000000(******************************************************************************) (* ocplib-simplex *) (* *) (* Copyright (C) --- OCamlPro --- See README.md for information and licensing *) (******************************************************************************) (*----------------------------------------------------------------------------*) (** Interface required for variables *) module type Variables = 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 Rationals = 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 val floor : t -> t val ceiling : t -> t end (** Interface required for coefs *) module type Coefs = 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 required for bounds and solutions *) module type Value = 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 add : t -> t -> t val sub : t -> 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 val floor : t -> t val ceiling : t -> t type r val mult_by_coef: t -> r -> t val div_by_coef: t -> r -> t end (*----------------------------------------------------------------------------*) (** Interface of explanations *) module type Explanations = sig type t val empty : t val union : t -> t -> t val print : Format.formatter -> t -> unit end module type MapSig = sig type 'a t type key val empty : 'a t val find : key -> 'a t -> 'a val add : key -> 'a -> 'a t -> 'a t val remove : key -> 'a t -> 'a t val mem: key -> 'a t -> bool val fold : (key -> 'a -> 'b -> 'b) -> 'a t -> 'b -> 'b val iter : (key -> 'a -> unit) -> 'a t -> unit val cardinal : 'a t -> int end module type SetSig = sig type t type elt val empty : t val is_empty : t -> bool val choose : t -> elt val elements : t -> elt list val add : elt -> t -> t val mem : elt -> t -> bool val remove : elt -> t -> t val fold : (elt -> 'b -> 'b) -> t -> 'b -> 'b val iter : (elt -> unit) -> t -> unit val union : t -> t -> t end ocplib-simplex-0.5.1/src/polys.ml000066400000000000000000000064521460130332000167320ustar00rootroot00000000000000(******************************************************************************) (* ocplib-simplex *) (* *) (* Copyright (C) --- OCamlPro --- See README.md for information and licensing *) (******************************************************************************) open ExtSigs module type SIG = sig module Var : Variables module R : Coefs 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: Variables)(R : Rationals) : 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.5.1/src/polys.mli000066400000000000000000000025551460130332000171030ustar00rootroot00000000000000(******************************************************************************) (* ocplib-simplex *) (* *) (* Copyright (C) --- OCamlPro --- See README.md for information and licensing *) (******************************************************************************) open ExtSigs module type SIG = sig module Var : Variables module R : Coefs 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: Variables)(R : Rationals) : SIG with module Var = Var and module R = R ocplib-simplex-0.5.1/src/rat2.ml000066400000000000000000000054021460130332000164260ustar00rootroot00000000000000(******************************************************************************) (* ocplib-simplex *) (* *) (* Copyright (C) --- OCamlPro --- See README.md for information and licensing *) (******************************************************************************) open ExtSigs module type SIG = sig module R : Coefs module V : Value with type r = R.t type t = private {v: V.t; offset: R.t} val zero : t val of_r : V.t -> t val upper : V.t -> t val lower : V.t -> t val minus : t -> t val add : t -> t -> t val sub : 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 equal : t -> t -> bool val is_zero : t -> bool val is_pure_rational : t -> bool val is_int : t -> bool val floor : t -> t val ceiling : t -> t val print : Format.formatter -> t -> unit end module Make(R : Rationals)(V : Value with type r = R.t) : SIG with module R = R and module V = V = struct module R = R module V = V type t = { v: V.t; offset: R.t; (* When working on strict bounds, an epsilon is added to the bounds. The offset represents the amount of epsilon are added. *) } let of_r v = {v; offset = R.zero} let upper v = {v; offset = R.m_one} let lower v = {v; offset = R.one} let zero = of_r V.zero let is_pure_rational r = R.equal r.offset R.zero let is_int r = is_pure_rational r && V.is_int r.v let map f g a = {v = f a.v; offset = g a.offset} let map2 f g a b = {v = f a.v b.v; offset = g a.offset b.offset} let add = map2 V.add R.add let sub = map2 V.sub R.sub let mult_by_const c e = if R.is_one c then e else map (fun v -> V.mult_by_coef v c) (fun v -> R.mult v c) e let div_by_const c e = if R.is_one c then e else map (fun v -> V.div_by_coef v c) (fun v -> R.div v c) e let compare a b = let c = V.compare a.v b.v in if c <> 0 then c else R.compare a.offset b.offset let equal a b = compare a b = 0 let is_zero a = V.is_zero a.v && R.is_zero a.offset let minus = map V.minus R.minus let floor r = if V.is_int r.v then if is_pure_rational r then r else of_r (V.sub r.v V.one) else of_r (V.floor r.v) let ceiling r = if V.is_int r.v then if is_pure_rational r then r else of_r (V.add r.v V.one) else of_r (V.ceiling r.v) let print_offset fmt off = let c = R.compare off R.zero in if c = 0 then () else if c > 0 then Format.fprintf fmt "+%aƐ" R.print off else Format.fprintf fmt "%aƐ" R.print off let print fmt r = Format.fprintf fmt "%a%a" V.print r.v print_offset r.offset end ocplib-simplex-0.5.1/src/rat2.mli000066400000000000000000000052111460130332000165750ustar00rootroot00000000000000(******************************************************************************) (* ocplib-simplex *) (* *) (* Copyright (C) --- OCamlPro --- See README.md for information and licensing *) (******************************************************************************) (** A representation of rationals bound, which is a pair of rationals: - the raw value of the bound - an epsilon used as an offset for representing strict bounds. For example, for the inequality [x < 3], the upper bound of [x] will be represented by [3 - Ɛ], where [Ɛ] is a positive integer that will be calculated later. *) open ExtSigs module type SIG = sig module R : Coefs module V : Value with type r = R.t (** {1 Type} *) type t = private { v: V.t; (** The raw value of the bound. *) offset: R.t (** The number of epsilons to add to the bound. *) } (** {1 Constructors} *) (** The zero bound with no offset. *) val zero : t (** From a rational [r], returns the Rat2 representation with no offset. *) val of_r : V.t -> t (** From a rational [r], returns [r - Ɛ]. *) val upper : V.t -> t (** From a rational [r], returns [r + Ɛ]. *) val lower : V.t -> t (** {1 Algebraic operations} *) (** From a bound [r + kƐ], returns [-r -kƐ]. *) val minus : t -> t (** Adds two bounds. *) val add : t -> t -> t (** Substracts two bounds. *) val sub : t -> t -> t (** Multiplies a bound by a rational constant (both v and offset are multiplied). *) val mult_by_const : R.t -> t -> t (** Divides a bound by a constant. Fails if the constant is zero. *) val div_by_const : R.t -> t -> t (** {1 Comparison functions} *) (** Compares two bounds; returns 0 iff the two bounds are strictly equal. *) val compare : t -> t -> int (** Returns [true] iff the bounds are strictly equal. *) val equal : t -> t -> bool (** Returns [true] iff the bound in argument is zero. *) val is_zero : t -> bool (** Returns [true] iff the offset is 0. *) val is_pure_rational : t -> bool (** Returns [true] iff the offset is 0 and the field [v] is an integer. *) val is_int : t -> bool (** {1 Misc} *) (** Returns the greatest (pure) integer smaller or equal to the argument. *) val floor : t -> t (** Returns the smallest (pure) integer greater or equal to the argument. *) val ceiling : t -> t (** Prints a bound. *) val print : Format.formatter -> t -> unit end module Make(R : Rationals)(V : Value with type r = R.t) : SIG with module R = R and module V = V ocplib-simplex-0.5.1/src/result.ml000066400000000000000000000135101460130332000170730ustar00rootroot00000000000000(******************************************************************************) (* ocplib-simplex *) (* *) (* Copyright (C) --- OCamlPro --- See README.md for information and licensing *) (******************************************************************************) module type S = sig module Core : CoreSig.S val get : (Core.P.t * bool) option -> Core.t -> Core.result end module Make(Core : CoreSig.S) : S 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 (Core.expl_of_max_bound xi), xi.maxi else Ex.union ex (Core.expl_of_min_bound xi), 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 (Core.expl_of_min_bound si) (Core.expl_of_max_bound si) else match si.vstatus with | ValueOK -> assert false | LowerKO -> explain_poly env.non_basic p (Core.expl_of_min_bound si) true | UpperKO -> explain_poly env.non_basic p (Core.expl_of_max_bound si) false with Not_found -> let si, _ = MX.find s env.non_basic in assert (not (consistent_bounds si)); Ex.union (Core.expl_of_min_bound si) (Core.expl_of_max_bound si) let get_int_solution env = let is_int_sol = ref true in let sol = MX.fold (fun x (xi,_) sol -> let v = xi.value in assert (R2.is_pure_rational v); is_int_sol := !is_int_sol && V.is_int v.R2.v; (x, v.R2.v) :: sol ) env.non_basic [] in let sol = MX.fold (fun x (xi, _) sol -> let v = xi.value in assert (R2.is_pure_rational v); is_int_sol := !is_int_sol && V.is_int v.R2.v; (x, v.R2.v) :: 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; epsilon = V.zero} let eval_eps (eps : V.t) (inf : R2.t) (sup : R2.t) = let {R2.v = inf_r; offset = inf_d} : R2.t = inf in let {R2.v = sup_r; offset = sup_d} : R2.t = sup in let c = V.compare inf_r sup_r in assert (c <= 0); if c = 0 || R.compare inf_d sup_d <= 0 then eps else V.min eps (V.div_by_coef (V.sub sup_r inf_r) (R.sub inf_d sup_d)) let eps_for_mini (i : Core.var_info) (min : R2.t) (eps : V.t) : V.t = assert (R2.is_pure_rational min || R.equal min.R2.offset R.one); let eps = eval_eps eps min i.value in eps let eps_for_maxi (i : Core.var_info) (max : R2.t) (eps : V.t) : V.t = assert (R2.is_pure_rational max || R.equal max.R2.offset R.m_one); let eps = eval_eps eps i.value max in eps let get_rat_solution = let compute_epsilon mp eps = MX.fold (fun _ (i, _) eps -> let eps' = match i.mini , i.maxi with | None, None -> eps | Some min, None -> eps_for_mini i min.bvalue eps | None, Some max -> eps_for_maxi i max.bvalue eps | Some min, Some max -> eps |> eps_for_mini i min.bvalue |> eps_for_maxi i max.bvalue in assert (V.compare eps' V.zero > 0); eps' ) mp eps in let compute_solution slake mp eps acc = MX.fold (fun x (info, _) (m, s) -> let {R2.v = q1; offset = q2} = info.value in let q = V.add q1 (V.mult_by_coef eps q2) in let q2 = R2.of_r q in assert (not (violates_min_bound q2 info.mini)); assert (not (violates_max_bound q2 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 V.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; epsilon = eps } 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 : Core.bound = Core.P.fold (fun x c (max_v : Core.bound) -> let xi, _ = try MX.find x non_basic with Not_found -> assert false in let bnd = if R.sign c > 0 then xi.maxi else xi.mini in let ex = match bnd with | None -> Core.Ex.empty | Some {explanation; _} -> explanation in let value = xi.value in assert (equals_optimum value bnd); { bvalue = R2.add max_v.bvalue (R2.mult_by_const c value); explanation = Ex.union max_v.explanation ex } ) p {bvalue = R2.zero; explanation = Ex.empty} in {max_v; is_le = R.is_zero max_v.bvalue.R2.offset} 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.5.1/src/result.mli000066400000000000000000000020221460130332000172400ustar00rootroot00000000000000(******************************************************************************) (* ocplib-simplex *) (* *) (* Copyright (C) --- OCamlPro --- See README.md for information and licensing *) (******************************************************************************) module type S = sig module Core : CoreSig.S val get : (Core.P.t * bool) option -> Core.t -> Core.result (** [get (objective, is_max_bounded) env] retrieves the result from a simplex [env]. This needs to be called after the system [env] has been solved by {!module-SolveBounds}. @param objective the optimization objective if any @param is_max_bounded whether the result is bounded @param env the simplex environment (system of linear inequalities) containing the solution @return solution that satisfies the constraints if any *) end module Make(Core : CoreSig.S) : S with module Core = Core ocplib-simplex-0.5.1/src/solveBounds.ml000066400000000000000000000427641460130332000200750ustar00rootroot00000000000000(******************************************************************************) (* ocplib-simplex *) (* *) (* Copyright (C) --- OCamlPro --- See README.md for information and licensing *) (******************************************************************************) let src = Logs.Src.create "OcplibSimplex.SolveBounds" ~doc:"A module providing arithmetical utilities for solving the simplex" module type S = sig module Core : CoreSig.S 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.S) : S 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) -> Logs.debug ~src (fun p -> p ~header:"[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 {bvalue = 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 {bvalue = 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 {bvalue = 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 {bvalue = 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 {bvalue = 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 = Logs.debug ~src (fun p -> p "[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 -> Logs.debug (fun p -> p "max reached@."); rnd, env, Some (opt, true) (* max reached *) | Some (_x, _c, _xi, _use_x, _should_incr) -> Logs.debug (fun p -> p "pivot non basic var %a ?@." Var.print _x); match basic_var_to_pivot_for_maximization env _x _use_x _should_incr with | Free -> Logs.debug (fun p -> p "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) -> Logs.debug (fun p -> p "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 -> Logs.debug (fun p -> p "no pivot finally(no upper bnd), pb unbounded@."); rnd, env, Some (opt, false) (* unbounded *) end | Stuck -> Logs.debug (fun p -> p "no pivot finally, pb unbounded@."); rnd, env, Some (opt, false) (* unbounded *) | Progress (ratio, s, si, p, c_px, bnd, _is_min) -> Logs.debug (fun p -> p "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) -> Logs.debug (fun p -> p "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 Logs.debug (fun p -> p "[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 -> Logs.debug (fun p -> p "[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 Logs.debug (fun p -> p "start maximization@."); let rnd, env, is_max = maximize_rec env opt 1 in Core.check_invariants env (Result.get is_max); Logs.debug (fun p -> p "[maximize] pb SAT! Max found ? %b for %a == %a@." (is_max != None) P.print opt0 P.print opt); Logs.debug (fun p -> p "maximization done after %d steps@." rnd); env, is_max end end ocplib-simplex-0.5.1/src/solveBounds.mli000066400000000000000000000017671460130332000202440ustar00rootroot00000000000000(******************************************************************************) (* ocplib-simplex *) (* *) (* Copyright (C) --- OCamlPro --- See README.md for information and licensing *) (******************************************************************************) val src : Logs.src module type S = sig module Core : CoreSig.S val solve : Core.t -> Core.t (** [solve env] solves the linear inequalities in the simplex [env]. Use {!module-Result} to retrieve the solution if any. *) val maximize : Core.t -> Core.P.t -> Core.t * (Core.P.t * bool) option (** [maximize env objective] finds the maximum value of [objective] that satisfies the system of linear inequalities in [env]. Use {!module-Result} to retrieve the solution if any. @return env,(objective,is_max_bounded) *) end module Make(Core : CoreSig.S) : S with module Core = Core ocplib-simplex-0.5.1/src/version.ml000066400000000000000000000006501460130332000172430ustar00rootroot00000000000000(******************************************************************************) (* ocplib-simplex *) (* *) (* Copyright (C) --- OCamlPro --- See README.md for information and licensing *) (******************************************************************************) let version="0.5" ocplib-simplex-0.5.1/src/version.mli000066400000000000000000000006531460130332000174170ustar00rootroot00000000000000(******************************************************************************) (* ocplib-simplex *) (* *) (* Copyright (C) --- OCamlPro --- See README.md for information and licensing *) (******************************************************************************) val version : string ocplib-simplex-0.5.1/tests/000077500000000000000000000000001460130332000155765ustar00rootroot00000000000000ocplib-simplex-0.5.1/tests/dune000066400000000000000000000013601460130332000164540ustar00rootroot00000000000000(tests (names solveEmpty standalone_minimal_maximization standalone_minimal standalone_test_strict_bounds) (modules simplex solveEmpty standalone_minimal_maximization standalone_minimal standalone_test_strict_bounds) (libraries ocplib-simplex zarith)) (rule (alias runtest) (action (diff solveEmpty.expected solveEmpty.output) ) ) (rule (alias runtest) (action (diff standalone_minimal_maximization.expected standalone_minimal_maximization.output ) ) ) (rule (alias runtest) (action (diff standalone_minimal.expected standalone_minimal.output ) ) ) (rule (alias runtest) (action (diff standalone_test_strict_bounds.expected standalone_test_strict_bounds.output ) ) ) ocplib-simplex-0.5.1/tests/simplex.ml000066400000000000000000000034301460130332000176110ustar00rootroot00000000000000(******************************************************************************) (* ocplib-simplex *) (* *) (* Copyright (C) --- OCamlPro --- See README.md for information and licensing *) (******************************************************************************) 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 Rat = struct type t = Q.t let add = Q.add let minus = Q.neg let mult = Q.mul let abs = Q.abs let compare = Q.compare let equal = Q.equal let zero = Q.zero let one = Q.one let m_one = Q.minus_one let is_zero n = Q.equal n Q.zero let to_string = Q.to_string let print = Q.pp_print let is_int v = Z.equal (Q.den v) Z.one let div = Q.div let sub = Q.sub let is_one v = Q.equal v Q.one let is_m_one v = Q.equal v Q.minus_one let sign = Q.sign let min = Q.min let floor v = Z.fdiv (Q.num v) (Q.den v) |> Q.of_bigint let ceiling v = Z.cdiv (Q.num v) (Q.den v) |> Q.of_bigint end module Ex = struct include Set.Make(String) 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 Ty = OcplibSimplex.Core.Make(Var)(Rat)(Ex) module AB = OcplibSimplex.AssertBounds.Make(Ty) module Sim = OcplibSimplex.Basic.Make(Var)(Rat)(Ex) let aux header (sim, opt) = Format.printf "%a" header (); Format.printf "%a" (Sim.Core.print (Sim.Result.get opt sim)) sim let () = Logs.Src.set_level OcplibSimplex.Core.src (Some Debug); Logs.Src.set_level OcplibSimplex.SolveBounds.src (Some Debug) ocplib-simplex-0.5.1/tests/solveEmpty.expected000066400000000000000000000014001460130332000214630ustar00rootroot00000000000000 ### Test Solve Empty == begin ======================================== on integers ? false --- values of non-basic --------------------------- --------------------------------------------------- --- values of basic ------------------------------- --------------------------------------------------- --- matrix ---------------------------------------- --------------------------------------------------- --- sets of uses ---------------------------------- --------------------------------------------------- --- basic variables in fixme ---------------------- (fixme is empty) --------------------------------------------------- --- simplex status -------------------------------- Sat: == end ========================================== ocplib-simplex-0.5.1/tests/solveEmpty.ml000066400000000000000000000003261460130332000203000ustar00rootroot00000000000000 open Simplex let () = let sim = Sim.Core.empty ~is_int:false ~check_invs:true in let sim = Sim.Solve.solve sim in aux ( fun fmt () -> Format.fprintf fmt "\n### Test Solve Empty@." ) (sim, None) ocplib-simplex-0.5.1/tests/standalone_minimal.expected000066400000000000000000000020551460130332000231610ustar00rootroot00000000000000 ### Test Solve Unsat == begin ======================================== on integers ? true --- values of non-basic --------------------------- 0 <= [ x == 0 ] < +∞ (computed OK ) (flag OK ) 0 <= [ y == 0 ] < +∞ (computed OK ) (flag OK ) --------------------------------------------------- --- values of basic ------------------------------- --------------------------------------------------- -∞ < [ z == 0 ] <= -1 (computed KO(Upper)) (flag KO(Upper)) --- matrix ---------------------------------------- z = (1) * x + (1) * y --------------------------------------------------- --- sets of uses ---------------------------------- variables that use x are: z, variables that use y are: z, --------------------------------------------------- --- basic variables in fixme ---------------------- (fixme is empty) --------------------------------------------------- --- simplex status -------------------------------- Unsat:x+y<=-1, x>=0, y>=0 == end ========================================== ocplib-simplex-0.5.1/tests/standalone_minimal.ml000066400000000000000000000014131460130332000217650ustar00rootroot00000000000000 open Simplex let () = let sim = Sim.Core.empty ~is_int:true ~check_invs:true in let zero = Sim.Core.R2.zero in let m_one = (Sim.Core.R2.of_r Rat.m_one) in (* x >= 0 *) let sim, _ = Sim.Assert.var sim "x" ~min:{Sim.Core.bvalue = zero; explanation = Ex.singleton "x>=0"} in (* y >= 0 *) let sim, _ = Sim.Assert.var sim "y" ~min:{Sim.Core.bvalue = zero; explanation = Ex.singleton "y>=0"} 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" ~max:{Sim.Core.bvalue = m_one; explanation = Ex.singleton "x+y<=-1"} in let sim = Sim.Solve.solve sim in aux ( fun fmt () -> Format.fprintf fmt "\n### Test Solve Unsat@." ) (sim, None) ocplib-simplex-0.5.1/tests/standalone_minimal_maximization.expected000066400000000000000000000065331460130332000257570ustar00rootroot00000000000000### Problem 'max (1) * x + (1) * y' == begin ======================================== on integers ? true --- values of non-basic --------------------------- -∞ < [ s == 10 ] <= 10 (computed OK ) (flag OK ) -∞ < [ y == 0 ] < +∞ (computed OK ) (flag OK ) --------------------------------------------------- --- values of basic ------------------------------- --------------------------------------------------- 3 <= [ x == 10 ] < +∞ (computed OK ) (flag OK ) --- matrix ---------------------------------------- x = (1) * s + (-1) * y --------------------------------------------------- --- sets of uses ---------------------------------- variables that use s are: x, variables that use y are: x, --------------------------------------------------- --- basic variables in fixme ---------------------- (fixme is empty) --------------------------------------------------- --- simplex status -------------------------------- Max: (v=10, is_le=true, ex=x+y<=10) (int solution ? true) x --> 10 y --> 0 s --> 10 == end ========================================== ### Problem 'max (1) * y' == begin ======================================== on integers ? true --- values of non-basic --------------------------- -∞ < [ s == 10 ] <= 10 (computed OK ) (flag OK ) 3 <= [ x == 3 ] < +∞ (computed OK ) (flag OK ) --------------------------------------------------- --- values of basic ------------------------------- --------------------------------------------------- -∞ < [ y == 7 ] < +∞ (computed OK ) (flag OK ) --- matrix ---------------------------------------- y = (1) * s + (-1) * x --------------------------------------------------- --- sets of uses ---------------------------------- variables that use s are: y, variables that use x are: y, --------------------------------------------------- --- basic variables in fixme ---------------------- (fixme is empty) --------------------------------------------------- --- simplex status -------------------------------- Max: (v=7, is_le=true, ex=x+y<=10, x>=3) (int solution ? true) y --> 7 x --> 3 s --> 10 == end ========================================== ### Problem 'max (-1) * y' == begin ======================================== on integers ? true --- values of non-basic --------------------------- 3 <= [ x == 3 ] < +∞ (computed OK ) (flag OK ) -∞ < [ y == 0 ] < +∞ (computed OK ) (flag OK ) --------------------------------------------------- --- values of basic ------------------------------- --------------------------------------------------- -∞ < [ s == 3 ] <= 10 (computed OK ) (flag OK ) --- matrix ---------------------------------------- s = (1) * x + (1) * y --------------------------------------------------- --- sets of uses ---------------------------------- variables that use x are: s, variables that use y are: s, --------------------------------------------------- --- basic variables in fixme ---------------------- (fixme is empty) --------------------------------------------------- --- simplex status -------------------------------- Unbounded: (int solution ? true) y --> 0 x --> 3 s --> 3 == end ========================================== ocplib-simplex-0.5.1/tests/standalone_minimal_maximization.ml000066400000000000000000000020141460130332000245540ustar00rootroot00000000000000 open Simplex let large i = Sim.Core.R2.of_r (Q.of_int i) let upper i = Sim.Core.R2.upper (Q.of_int i) let lower i = Sim.Core.R2.lower (Q.of_int i) let bnd r e = {Sim.Core.bvalue = r; explanation = e} let () = let sim = Sim.Core.empty ~is_int:true ~check_invs:true in let x_y = Sim.Core.P.from_list ["x", Rat.one; "y", Rat.one] in let y1 = Sim.Core.P.from_list ["y", Rat.one] in let ym1 = Sim.Core.P.from_list ["y", Rat.m_one] in (* s == x + y >= 10 let sim = Sim.Assert.poly sim x_y "s" (large 10) Ex.empty None Ex.empty in *) (* x <= 5 *) let sim, _ = Sim.Assert.var sim "x" ~min:(bnd (large 3) (Ex.singleton "x>=3")) in (* s == x + y <= 10 *) let sim, _ = Sim.Assert.poly sim x_y "s" ~max:(bnd (large 10) (Ex.singleton "x+y<=10")) in let max_hdr pb fmt () = Format.fprintf fmt "### Problem 'max %a'@." Sim.Core.P.print pb in aux (max_hdr x_y) (Sim.Solve.maximize sim x_y); aux (max_hdr y1) (Sim.Solve.maximize sim y1); aux (max_hdr ym1) (Sim.Solve.maximize sim ym1) ocplib-simplex-0.5.1/tests/standalone_test_strict_bounds.expected000066400000000000000000000003251460130332000254520ustar00rootroot00000000000000-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ The problem 'max (2) * x + (2) * y' ... has an upper bound: 18 (is_le = true)(reason: x<=5, y<5) -+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ocplib-simplex-0.5.1/tests/standalone_test_strict_bounds.ml000066400000000000000000000042121460130332000242600ustar00rootroot00000000000000open Simplex let sep () = Format.printf "-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+@." let pp_epsilon fmt (max_v, eps) = let pp = if Sim.Core.R2.is_pure_rational max_v.Sim.Core.bvalue then Format.ifprintf else Format.fprintf in pp fmt "(epsilon: %a)" Rat.print eps 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,sol) -> let {Sim.Core.max_v; is_le} = Lazy.force mx in let sol = Lazy.force sol in Format.printf " has an upper bound: %a (is_le = %b)(reason: %a)%a@." Sim.Core.R2.print max_v.Sim.Core.bvalue is_le Ex.print max_v.Sim.Core.explanation pp_epsilon (max_v, sol.Sim.Core.epsilon) ; end; sep (); Format.printf "@." let large i = Sim.Core.R2.of_r (Q.of_int i) let upper i = Sim.Core.R2.upper (Q.of_int i) let lower i = Sim.Core.R2.lower (Q.of_int i) let bnd r e = {Sim.Core.bvalue = r; explanation = e} let r_two = Rat.add Rat.one Rat.one let () = let sim = Sim.Core.empty ~is_int:true ~check_invs:false in let x_m_y = Sim.Core.P.from_list ["x", Rat.one; "y", Rat.m_one] in let tx_ty = Sim.Core.P.from_list ["x", r_two; "y", r_two] in (* 3 < y < 5*) let sim, _ = Sim.Assert.var sim "y" ~min:(bnd (lower 3) (Ex.singleton "y>3")) ~max:(bnd (upper 5) (Ex.singleton "y<5")) in (* 3 < x < 4 *) let sim, _ = Sim.Assert.var sim "x" ~min:(bnd (lower 3) (Ex.singleton "x>3")) ~max:(bnd (large 5) (Ex.singleton "x<=5")) in (* 0 <= x - y *) let sim, _ = Sim.Assert.poly sim x_m_y "s'" ~min:(bnd (large 1) (Ex.singleton "x-y>=1")) in (* s == 2x + 2y <= 20 *) let sim, _ = Sim.Assert.poly sim tx_ty "s" ~max:(bnd (large 20) (Ex.singleton "2x+2y<=20")) in aux sim tx_ty