pax_global_header00006660000000000000000000000064144751722140014521gustar00rootroot0000000000000052 comment=2218709b97a11ec87bacddae354aa682e483626b pplpy-0.8.9/000077500000000000000000000000001447517221400127035ustar00rootroot00000000000000pplpy-0.8.9/.github/000077500000000000000000000000001447517221400142435ustar00rootroot00000000000000pplpy-0.8.9/.github/workflows/000077500000000000000000000000001447517221400163005ustar00rootroot00000000000000pplpy-0.8.9/.github/workflows/doc.yml000066400000000000000000000031421447517221400175700ustar00rootroot00000000000000name: Documentation on: push: { branches: [ "master" ] } pull_request: { branches: [ "master" ] } concurrency: group: doc-${{ github.ref }} cancel-in-progress: true jobs: build-manual: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 with: { submodules: recursive } - uses: conda-incubator/setup-miniconda@v2 with: { miniforge-variant: "Mambaforge", miniforge-version: "latest" } - name: Install pplpy dependencies shell: bash -l {0} run: | mamba env update --quiet -n test -f environment.yml conda list - name: Install pplpy shell: bash -l {0} run: | pip install --verbose --no-index --no-build-isolation . - name: Install test dependencies run: | mamba env update --quiet -n test -f environment.test.yml conda list - name: Build documentation shell: bash -l {0} run: sphinx-build docs/source html/pplpy - name: Detect broken links shell: bash -l {0} run: | python -m http.server 8880 --directory html & sleep 1 # We ignore _modules since sphinx puts all modules in the module # overview but does not generate pages for .pyx modules. linkchecker --check-extern --ignore-url=_modules/ http://localhost:8880 - uses: JamesIves/github-pages-deploy-action@3.7.1 with: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} BRANCH: gh-pages FOLDER: html/pplpy/ TARGET_FOLDER: docs/ if: ${{ github.event_name == 'push' }} pplpy-0.8.9/.github/workflows/test.yml000066400000000000000000000026051447517221400200050ustar00rootroot00000000000000name: Test on: push: { branches: [ "master" ] } pull_request: { branches: [ "master" ] } concurrency: group: test-${{ github.ref }} cancel-in-progress: true jobs: test: runs-on: ubuntu-latest strategy: matrix: python-version: ["3.8", "3.9", "3.10", "3.11"] cython: ["cython", "cython<3.0.0"] steps: - uses: actions/checkout@v2 with: { submodules: recursive } - uses: conda-incubator/setup-miniconda@v2 with: { miniforge-variant: "Mambaforge", miniforge-version: "latest", python-version: "${{matrix.python-version}}" } - name: Install pplpy dependencies shell: bash -l {0} run: | mamba install --quiet setuptools gmpy2 cysignals ppl "${{matrix.cython}}" conda list - name: Install pplpy shell: bash -l {0} run: | pip install --verbose --no-index --no-build-isolation . - name: Install test dependencies run: | mamba env update --quiet -n test -f environment.test.yml conda list - name: Linter shell: bash -l {0} run: | cython-lint --ignore=E265,E266,E501,E741 --exclude='ppl_decl.pxd' ppl/ - name: Run tests shell: bash -l {0} run: | python setup.py test - name: Show logs run: grep "" /dev/null `find -name '*.log'` || true if: ${{ always() }} pplpy-0.8.9/.gitignore000066400000000000000000000002461447517221400146750ustar00rootroot00000000000000build/* ppl.so ppl/*.c ppl/*.cpp ppl/*.so ppl/cygmp/*.c ppl/cygmp/*.cpp ppl/cygmp/*.so *.so *.o *.pyc *.c *.cpp *.swp dist/ pplpy.egg-info/ docs/build/ .idea/* /.tox pplpy-0.8.9/.gitlab-ci.yml000066400000000000000000000014761447517221400153470ustar00rootroot00000000000000image: ubuntu:20.04 before_script: - export DEBIAN_FRONTEND=noninteractive # avoid tzdata interactive configuration - apt-get -qq update - apt-get install -y apt-utils git libgmp-dev libmpfr-dev libmpc-dev libppl-dev $PKGS - $PYTHON --version # NOTE: currently it seems not possible to build the sdist without manually installing # dependencies. pyproject.toml is ignored by the call to 'setup.py sdist' below and the # install_requires of setuptools is broken with Cython. - $PYTHON -m pip install "gmpy2>=2.1.0b1" - $PYTHON setup.py sdist - $PYTHON -m pip -v install dist/pplpy-*.tar.gz python3: stage: test variables: PYTHON: python3 PKGS: python3 python3-dev python3-pip python3-setuptools python3-wheel python3-sphinx cython3 python3-cysignals-bare script: - $PYTHON setup.py test - make -w -C docs html pplpy-0.8.9/CHANGES.txt000066400000000000000000000021121447517221400145100ustar00rootroot00000000000000v0.8, 2019/01/18 - switch from github to gitlab - some more support for PPL objects: permute_space_dimensions, Bit_Row, Bit_Matrix - upgrade gmpy2 version dependency - add pyproject.toml and setup.cfg files - remove the OK functions which caused trouble for clang on FreeBSD - switch back to github under SageMath organization - fast initialization of Linear_Expression from list/dict - CI (test, linter, doc build and deployment) - add a Cython pool for ppl.Variable - support for congruences v0.7, 2017/11/24 - use of gmpy2 for integers and rationals (Vincent Delecroix/Vincent Klein) - tests on travis (Vincent Delecroix/Vincent Klein) - fixes in install scripts (Vincent Delecroix) - port some upgrades from Sage (Vincent Klein) - split in several Cython files (Vincent Klein) - adding widening (Jesús Doménech) v0.6, 2016/01/17 -- distribution bug fixes v0.5, 2016/01/17 -- bug fixes v0.4, 2016/01/16 -- iterator for MIP_Problem v0.3, 2016/01/16 -- Reworked documentation v0.2, 2016/01/16 -- Fix build v0.1, 2016/01/16 -- Initial release pplpy-0.8.9/LICENSE.txt000066400000000000000000001045131447517221400145320ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . pplpy-0.8.9/MANIFEST.in000066400000000000000000000005551447517221400144460ustar00rootroot00000000000000include README.rst LICENSE.txt CHANGES.txt pyproject.toml setup.py setup.cfg tox.ini recursive-include ppl *.pxd *.pyx *.py recursive-include tests *.pyx *.py include ppl/ppl_shim.cc include ppl/ppl_shim.hh include docs/Makefile include docs/source/conf.py include docs/source/index.rst recursive-exclude ppl *.so *.c *.cpp recursive-exclude tests *.so *.c *.cpp pplpy-0.8.9/README.rst000066400000000000000000000067171447517221400144050ustar00rootroot00000000000000PPL Python wrapper ================== This Python package provides a wrapper to the C++ `Parma Polyhedra Library (PPL) `_. The whole package started as a fork of a tiny part of the `Sage `_ software. How it works ------------ The names of objects and methods are the same as in the library: .. code:: python >>> import ppl >>> x = ppl.Variable(0) >>> y = ppl.Variable(1) >>> z = ppl.Variable(2) >>> cs = ppl.Constraint_System() >>> cs.insert(x >= 0) >>> cs.insert(y >= 0) >>> cs.insert(z >= 0) >>> cs.insert(x + y + z == 1) >>> poly = ppl.C_Polyhedron(cs) >>> poly.minimized_generators() Generator_System {point(1/1, 0/1, 0/1), point(0/1, 1/1, 0/1), point(0/1, 0/1, 1/1)} The available objects and functions from the `ppl` Python module are: - `Variable`, `Variables_Set`, `Linear_Expression` (defined in `ppl.linear_algebra`) - `MIP_Problem` (defined in `ppl.mip_problem`) - `C_Polyhedron`, `NNC_Polyhedron` (defined in `ppl.polyhedron`) - `Generator`, `Generator_System`, `Poly_Gen_Relation`, `point`, `closure_point`, `ray`, `line` (defined in `ppl.generator`) - `Constraint`, `Constraint_System`, `Poly_Con_Relation`, `inequality`, `equation`, `strict_inequality` (defined in `ppl.constraint`) Installation ------------ The project is available at `Python Package Index `_ and can be installed with pip:: $ pip install pplpy Note that if you have gmp and ppl installed in a non standard directory (e.g. you use brew on MacOSX) then you need to set appropriately the variables `CFLAGS` before calling `pip`. For example:: $ export CFLAGS="-I/path/to/gmp/include/ -L/path/to/gmp/lib/ -I/path/to/ppl/include/ -L/path/to/ppl/lib $CFLAGS" $ pip install pplpy Using from Cython ----------------- All Python classes from pplpy are extension types and can be used with Cython. Each extension type carries an attribute `thisptr` that holds a pointer to the corresponding C++ object from ppl. A complete example is provided with the files `tests/testpplpy.pyx` and `tests/setup.py`. Source ------ You can find the latest version of the source code on github: https://github.com/sagemath/pplpy Documentation ------------- An online version of the documentation is available at https://www.sagemath.org/pplpy/ Compiling the html documentation requires make and `sphinx `_. Before building the documentation, you need to install the pplpy package (sphinx uses Python introspection). The documentation source code is contained in the repository `docs` where there is a standard Makefile with a target `html`. Running `make html` in the `docs` repository builds the documentation inside `docs/build/html`. For more configuration options, run `make help`. License ------- pplpy is distributed under the terms of the GNU General Public License (GPL) published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. See http://www.gnu.org/licenses/. Requirements ------------ - `PPL `_ - `Cython `_ (tested with both 0.29 and 3.0) - `cysignals `_ - `gmpy2 `_ On Debian/Ubuntu systems the dependencies can be installed with:: $ sudo apt-get install libgmp-dev libmpfr-dev libmpc-dev libppl-dev cython3 python3-gmpy2 python3-cysignals-pari pplpy-0.8.9/docs/000077500000000000000000000000001447517221400136335ustar00rootroot00000000000000pplpy-0.8.9/docs/Makefile000066400000000000000000000012221447517221400152700ustar00rootroot00000000000000# Minimal makefile for Sphinx documentation # NOTE: we removed the shortcut $(O) for passing options to # sphinx-build as this is undocummented and sometimes # confusing. # You can set these variables from the command line. SPHINXBUILD = sphinx-build SPHINXPROJ = pplpy SOURCEDIR = source BUILDDIR = build # Put it first so that "make" without argument is like "make help". help: @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) .PHONY: help Makefile # Catch-all target: route all unknown targets to Sphinx using the new # "make mode" option. %: Makefile @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) pplpy-0.8.9/docs/source/000077500000000000000000000000001447517221400151335ustar00rootroot00000000000000pplpy-0.8.9/docs/source/conf.py000066400000000000000000000137521447517221400164420ustar00rootroot00000000000000# -*- coding: utf-8 -*- # # pplpy documentation build configuration file # import sys import os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('/home/vincent/programming/ppl/')) # -- General configuration ------------------------------------------------ # Sphinx extension modules extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.intersphinx', 'sphinx.ext.todo', 'sphinx.ext.coverage', 'sphinx.ext.mathjax', 'sphinx.ext.ifconfig', 'sphinx.ext.viewcode', ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The master toctree document. master_doc = 'index' # General information about the project. project = u'pplpy' copyright = u'2016, Vincent Delecroix' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. import configparser config = configparser.ConfigParser(allow_no_value=True) try: with open("../../setup.cfg", encoding='utf-8') as f: config.read_string(f.read()) except TypeError: # NOTE: encoding is not a keyword in Python 2 with open("../../setup.cfg") as f: config.read_string(f.read().decode('utf-8')) version = release = config['metadata']['version'] # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = [] # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # If true, keep warnings as "system message" paragraphs in the built documents. #keep_warnings = False # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'default' # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". # html_static_path = ['_static'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. #html_extra_path = [] # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'pplpydoc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). 'papersize': 'a4paper', # The font size ('10pt', '11pt' or '12pt'). 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ ('index', 'pplpy.tex', u'pplpy Documentation', u'Vincent Delecroix', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'pplpy', u'pplpy Documentation', [u'Vincent Delecroix'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'pplpy', u'pplpy Documentation', u'Vincent Delecroix', 'pplpy', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. #texinfo_no_detailmenu = False pplpy-0.8.9/docs/source/index.rst000066400000000000000000000062411447517221400167770ustar00rootroot00000000000000.. pplpy documentation master file Welcome to pplpy's documentation! ================================= Installation ------------ pplpy is available from the `Python Package Index `_. You can hence install it with:: $ pip install pplpy The code source can be obtained from `github `_:: $ git clone https://github.com/sagemath/pplpy.git Introduction ------------ .. automodule:: ppl Using in Cython --------------- All types from ppl are extension types and can be used with Cython. The following is a short sample of Cython code using pplpy:: from ppl.linear_algebra cimport Variable from ppl.constraint cimport Constraint_System from ppl.polyhedron cimport C_Polyhedron cdef Variable x = ppl.Variable(0) cdef Variable y = ppl.Variable(1) cdef Variable z = ppl.Variable(2) cdef Constraint_System cs = Constraint_System() cs.insert(x >= 0) cs.insert(y >= 0) cs.insert(x + y + z == 1) cdef C_Polyhedron poly = C_Polyhedron(cs) print(poly.minimized_generators()) Each extension type carries an attribute ``thisptr`` that holds a pointer to the corresponding C++ object from ppl. Continuing the above example, one can do:: print('dim = %lu' % poly.thisptr.space_dimension()) To avoid name collisions, the original C++ class names are prefixed with ``PPL_``, for example, the original ``Linear_Expression`` becomes ``PPL_Linear_Expression``. The Python wrapper has the same name as the original library class, that is, just ``Linear_Expression``. All ``ppl`` declarations are done in the ``.pxd`` file ``ppl/ppl_decl.pxd``. Only few functionalities from ``ppl`` are exposed in ``ppl_decl.pxd``. It is also preferable to avoid mixing C++ ``ppl`` objects with Cython ``pplpy`` extension types. To compile a Cython extension using pplpy you need to: - add the path of your pplpy installation to ``include_dirs`` - link with the ``ppl`` library Here is a minimal example of a ``setup.py`` file for a unique Cython file called ``test.pyx``:: from distutils.core import setup from distutils.extension import Extension from Cython.Build import cythonize import ppl extensions = [ Extension("test", ["test.pyx"], libraries=['ppl'], include_dirs=ppl.__path__, language='c++') ] setup(ext_modules=cythonize(extensions)) Module `ppl.constraint` ----------------------- .. automodule:: ppl.constraint :members: :undoc-members: :show-inheritance: Module `ppl.linear_algebra` --------------------------- .. automodule:: ppl.linear_algebra :members: :undoc-members: :show-inheritance: Module `ppl.generator` ---------------------- .. automodule:: ppl.generator :members: :undoc-members: :show-inheritance: Module `ppl.polyhedron` ----------------------- .. automodule:: ppl.polyhedron :members: :undoc-members: :show-inheritance: Module `ppl.mip_problem` ------------------------ .. automodule:: ppl.mip_problem :members: :undoc-members: :show-inheritance: Module `ppl.congruence` ----------------------- .. automodule:: ppl.congruence :members: :undoc-members: :show-inheritance: pplpy-0.8.9/environment.test.yml000066400000000000000000000001771447517221400167550ustar00rootroot00000000000000name: pplpy-test channels: - conda-forge - defaults dependencies: - sphinx - pip: - linkchecker - cython-lint pplpy-0.8.9/environment.yml000066400000000000000000000002011447517221400157630ustar00rootroot00000000000000name: pplpy-build channels: - conda-forge - defaults dependencies: - setuptools - gmpy2 - cysignals - cython - ppl pplpy-0.8.9/ppl/000077500000000000000000000000001447517221400134765ustar00rootroot00000000000000pplpy-0.8.9/ppl/__init__.py000066400000000000000000000117111447517221400156100ustar00rootroot00000000000000r""" Cython wrapper for the Parma Polyhedra Library (PPL) The Parma Polyhedra Library (PPL) is a library for polyhedral computations over the rationals. This interface tries to reproduce the C++ API as faithfully as possible in Python. For example, the following C++ excerpt: .. code-block:: c++ Variable x(0); Variable y(1); Constraint_System cs; cs.insert(x >= 0); cs.insert(x <= 3); cs.insert(y >= 0); cs.insert(y <= 3); C_Polyhedron poly_from_constraints(cs); translates into: >>> from ppl import Variable, Constraint_System, C_Polyhedron >>> x = Variable(0) >>> y = Variable(1) >>> cs = Constraint_System() >>> cs.insert(x >= 0) >>> cs.insert(x <= 3) >>> cs.insert(y >= 0) >>> cs.insert(y <= 3) >>> poly_from_constraints = C_Polyhedron(cs) The same polyhedron constructed from generators: >>> from ppl import Variable, Generator_System, C_Polyhedron, point >>> gs = Generator_System() >>> gs.insert(point(0*x + 0*y)) >>> gs.insert(point(0*x + 3*y)) >>> gs.insert(point(3*x + 0*y)) >>> gs.insert(point(3*x + 3*y)) >>> poly_from_generators = C_Polyhedron(gs) Rich comparisons test equality/inequality and strict/non-strict containment: >>> poly_from_generators == poly_from_constraints True >>> poly_from_generators >= poly_from_constraints True >>> poly_from_generators < poly_from_constraints False >>> poly_from_constraints.minimized_generators() Generator_System {point(0/1, 0/1), point(0/1, 3/1), point(3/1, 0/1), point(3/1, 3/1)} >>> poly_from_constraints.minimized_constraints() Constraint_System {-x0+3>=0, -x1+3>=0, x0>=0, x1>=0} As we see above, the library is generally easy to use. There are a few pitfalls that are not entirely obvious without consulting the documentation, in particular: * There are no vectors used to describe :class:`Generator` (points, closure points, rays, lines) or :class:`Constraint` (strict inequalities, non-strict inequalities, or equations). Coordinates are always specified via linear polynomials in :class:`Variable` * All coordinates of rays and lines as well as all coefficients of constraint relations are (arbitrary precision) integers. Only the generators :func:`point` and :func:`closure_point` allow one to specify an overall divisor of the otherwise integral coordinates. For example: >>> from ppl import Variable, point >>> x = Variable(0); y = Variable(1) >>> p = point( 2*x+3*y, 5 ); p point(2/5, 3/5) >>> p.coefficient(x) mpz(2) >>> p.coefficient(y) mpz(3) >>> p.divisor() mpz(5) * PPL supports (topologically) closed polyhedra (:class:`C_Polyhedron`) as well as not necessarily closed polyhedra (:class:`NNC_Polyhedron`). Only the latter allows closure points (=points of the closure but not of the actual polyhedron) and strict inequalities (``>`` and ``<``) The naming convention for the C++ classes is that they start with ``PPL_``, for example, the original ``Linear_Expression`` becomes ``PPL_Linear_Expression``. The Python wrapper has the same name as the original library class, that is, just ``Linear_Expression``. In short: * If you are using the Python wrapper (if in doubt: that's you), then you use the same names as the PPL C++ class library. * If you are writing your own Cython code, you can access the underlying C++ classes by adding the prefix ``PPL_``. Finally, PPL is fast. For example, here is the permutahedron of 5 basis vectors: >>> from ppl import Variable, Generator_System, point, C_Polyhedron >>> basis = range(0,5) >>> x = [ Variable(i) for i in basis ] >>> gs = Generator_System(); >>> from itertools import permutations >>> for coeff in permutations(basis): ... gs.insert(point( sum( (coeff[i]+1)*x[i] for i in basis ) )) >>> C_Polyhedron(gs) A 4-dimensional polyhedron in QQ^5 defined as the convex hull of 120 points DIFFERENCES VS. C++ Since Python and C++ syntax are not always compatible, there are necessarily some differences. The main ones are: * The :class:`Linear_Expression` also accepts an iterable as input for the homogeneous coefficients. AUTHORS: - Volker Braun (2010): initial version (within Sage). - Risan (2012): extension for MIP_Problem class (within Sage) - Vincent Delecroix (2016-2020): convert Sage files into a standalone Python package, interface bit_array, interface congruence - Vincent Klein (2017): improve doctest support and Python 3 compatibility Split the main code into several files. Remove the _mutable_immutable class. """ from .linear_algebra import ( Variable, Variables_Set, Linear_Expression, ) from .mip_problem import MIP_Problem from .polyhedron import C_Polyhedron, NNC_Polyhedron from .generator import Generator, Generator_System, Poly_Gen_Relation line = Generator.line point = Generator.point ray = Generator.ray closure_point = Generator.closure_point from .constraint import ( Constraint, Constraint_System, Poly_Con_Relation, inequality, equation, strict_inequality) from .congruence import Congruence, Congruence_System from .bit_arrays import Bit_Row, Bit_Matrix pplpy-0.8.9/ppl/bit_arrays.pxd000066400000000000000000000002251447517221400163510ustar00rootroot00000000000000from .ppl_decl cimport * cdef class Bit_Row(object): cdef PPL_Bit_Row *thisptr cdef class Bit_Matrix(object): cdef PPL_Bit_Matrix *thisptr pplpy-0.8.9/ppl/bit_arrays.pyx000066400000000000000000000102441447517221400164000ustar00rootroot00000000000000# distutils: language = c++ # distutils: libraries = gmp ppl m #***************************************************************************** # Copyright (C) 2018 Vincent Delecroix # # Distributed under the terms of the GNU General Public License (GPL) # as published by the Free Software Foundation; either version 3 of # the License, or (at youroption) any later version. # http://www.gnu.org/licenses/ #***************************************************************************** from libc.limits cimport ULONG_MAX from .ppl_decl cimport PPL_Bit_Row cdef class Bit_Row(object): r""" A bit row This can be considered as a subset of the non-negative integers (with upper bound the maximum value ``ULONG_MAX`` that fits in an ``unsigned long``). """ def __cinit__(self): self.thisptr = new PPL_Bit_Row() def __dealloc__(self): del self.thisptr def __repr__(self): r""" Examples: >>> from ppl import Bit_Row >>> r = Bit_Row() >>> r {} >>> r.set(2); r.set(12) >>> r {2, 12} """ cdef list l = [] cdef unsigned long k = self.thisptr.first() while k != ULONG_MAX: l.append(str(k)) k = self.thisptr.next(k) return "{" + ", ".join(l) + "}" def __hash__(self): r""" Examples: >>> from ppl import Bit_Row >>> r = Bit_Row() >>> hash(r) Traceback (most recent call last): ... TypeError: Bit_Row unhashable """ raise TypeError("Bit_Row unhashable") def set(self, unsigned long k): r""" Set the bit in position ``k`` Examples: >>> from ppl import Bit_Row >>> r = Bit_Row() >>> r.set(2); r.set(34); r.set(12) >>> r {2, 12, 34} >>> r.set(22) >>> r {2, 12, 22, 34} """ self.thisptr.set(k) def set_until(self, unsigned long k): r""" Set bits up to position ``k`` (excluded) Examples: >>> from ppl import Bit_Row >>> r = Bit_Row() >>> r.set_until(5) >>> r {0, 1, 2, 3, 4} """ self.thisptr.set_until(k) def clear_from(self, unsigned long k): r""" Clear bits from position ``k`` (included) onward Examples: >>> from ppl import Bit_Row >>> r = Bit_Row() >>> r.set_until(10) >>> r.clear_from(5) >>> r {0, 1, 2, 3, 4} """ self.thisptr.clear_from(k) def clear(self): r""" Clear all the bits of the row Examples: >>> from ppl import Bit_Row >>> r = Bit_Row() >>> r.set(1); r.set(3) >>> r {1, 3} >>> r.clear() >>> r {} """ self.thisptr.clear() def first(self): r""" Return the index of the first set bit or ``-1`` if no bit is set. Examples: >>> from ppl import Bit_Row >>> r = Bit_Row() >>> r.first() == -1 True >>> r.set(127) >>> r.first() == 127 True >>> r.set(2) >>> r.first() == 2 True >>> r.set(253) >>> r.first() == 2 True >>> r.clear() >>> r.first() == -1 True """ cdef unsigned long k = self.thisptr.first() if k == ULONG_MAX: return -1 else: return k def last(self): r""" Return the index of the last set bit or ``-1`` if no bit is set. Examples: >>> from ppl import Bit_Row >>> r = Bit_Row() >>> r.last() == -1 True >>> r.set(127) >>> r.last() == 127 True >>> r.set(2) >>> r.last() == 127 True >>> r.set(253) >>> r.last() == 253 True >>> r.clear() >>> r.last() == -1 True """ cdef unsigned long k = self.thisptr.last() if k == ULONG_MAX: return -1 else: return k cdef class Bit_Matrix(object): pass pplpy-0.8.9/ppl/congruence.pxd000066400000000000000000000003201447517221400163360ustar00rootroot00000000000000from .ppl_decl cimport * cdef _wrap_Congruence(PPL_Congruence) cdef class Congruence(object): cdef PPL_Congruence *thisptr cdef class Congruence_System(object): cdef PPL_Congruence_System *thisptr pplpy-0.8.9/ppl/congruence.pyx000066400000000000000000000250671447517221400164020ustar00rootroot00000000000000# distutils: language = c++ # distutils: libraries = gmp gmpxx ppl m #***************************************************************************** # Copyright (C) 2020 Vincent Delecroix # # Distributed under the terms of the GNU General Public License (GPL) # as published by the Free Software Foundation; either version 3 of # the License, or (at youroption) any later version. # http://www.gnu.org/licenses/ #***************************************************************************** from cython.operator cimport dereference as deref from gmpy2 cimport GMPy_MPZ_From_mpz, mpz, import_gmpy2 from .constraint cimport Constraint from .linear_algebra cimport Variable, Linear_Expression, PPL_Coefficient_from_pyobject import_gmpy2() def _dummy(): raise ValueError cdef class Congruence(object): r""" Wrapper for PPL's ``Congruence`` class. >>> import ppl >>> x = ppl.Variable(0) >>> y = ppl.Variable(1) >>> ppl.Congruence(x + 2*y - 1, 7) x0+2*x1-1==0 (mod 7) >>> ppl.Congruence(x + y == 2, 5) x0+x1-2==0 (mod 5) """ def __init__(self, arg=None, mod=None): if arg is None: self.thisptr = new PPL_Congruence() elif isinstance(arg, Congruence): self.thisptr = new PPL_Congruence(( arg).thisptr[0]) elif isinstance(arg, Variable): self.thisptr = new PPL_Congruence() if mod is None: mod = mpz(1) self.thisptr[0] = modulo(PPL_Linear_Expression(( arg).thisptr[0]), PPL_Coefficient_from_pyobject(mod)) elif isinstance(arg, Linear_Expression): self.thisptr = new PPL_Congruence() if mod is None: mod = mpz(1) self.thisptr[0] = modulo(( arg).thisptr[0], PPL_Coefficient_from_pyobject(mod)) elif isinstance(arg, Constraint): self.thisptr = new PPL_Congruence(( arg).thisptr[0]) if mod is None: mod = mpz(1) self.thisptr.set_modulus(PPL_Coefficient_from_pyobject(mod)) else: raise TypeError("invalid argument for Congruence") def __cinit__(self): self.thisptr = NULL def __dealloc__(self): del self.thisptr def is_equal(self, Congruence other): r""" Return whether ``self`` is equal to ``other``. Examples: >>> import ppl >>> x = ppl.Variable(0) >>> Congruence(x + 1, 3).is_equal(Congruence(x + 1, 3)) True >>> Congruence(x, 3).is_equal(Congruence(x - 2, 3)) False >>> Congruence(x, 3).is_equal(Congruence(x , 2)) False """ return ( self).thisptr[0] == ( other).thisptr[0] def coefficient(self, v): r""" Return the coefficient ``v`` of this congruence. Examples: >>> import ppl >>> x = ppl.Variable(0) >>> y = ppl.Variable(1) >>> c = (2 * x + y == 1) % 12 >>> c.coefficient(0) mpz(2) >>> c.coefficient(x) mpz(2) Note that contrarily to :class:`Linear_Expression` the congruences raise an error when trying to access a coefficient beyond the dimension >>> c.coefficient(ppl.Variable(13)) Traceback (most recent call last): ... ValueError: PPL::Congruence::coefficient(v): this->space_dimension() == 2, v.space_dimension() == 14. """ cdef Variable vv if type(v) is Variable: vv = v else: vv = Variable(v) return GMPy_MPZ_From_mpz(self.thisptr.coefficient(vv.thisptr[0]).get_mpz_t()) def coefficients(self): r""" Return the coefficients of this congruence as a tuple. Examples: >>> import ppl >>> x = ppl.Variable(0) >>> y = ppl.Variable(1) >>> t = ppl.Variable(3) >>> c = ppl.Congruence(x + 2*y + t - 1, 7) >>> c.coefficients() (mpz(1), mpz(2), mpz(0), mpz(1)) """ cdef int d = self.space_dimension() cdef int i coeffs = [] for i in range(0, d): coeffs.append(GMPy_MPZ_From_mpz(self.thisptr.coefficient(PPL_Variable(i)).get_mpz_t())) return tuple(coeffs) def modulus(self): r""" Return the modulus of this congruence. Examples: >>> import ppl >>> x = ppl.Variable(0) >>> y = ppl.Variable(1) >>> c = ppl.Congruence(x + 2*y - 3, 7) >>> c.modulus() mpz(7) """ return GMPy_MPZ_From_mpz(self.thisptr.modulus().get_mpz_t()) def inhomogeneous_term(self): r""" Return the inhomogeneous term of this congruence. Examples: >>> import ppl >>> x = ppl.Variable(0) >>> y = ppl.Variable(1) >>> c = ppl.Congruence(x + 2*y - 3, 7) >>> c.inhomogeneous_term() mpz(-3) """ return GMPy_MPZ_From_mpz(self.thisptr.inhomogeneous_term().get_mpz_t()) def space_dimension(self): return self.thisptr.space_dimension() def __repr__(self): s = '' v = [Variable(i) for i in range(self.space_dimension())] e = sum(self.coefficient(x)*x for x in v) e += self.inhomogeneous_term() s = repr(e) + '==0 (mod %s)' % self.modulus() return s def __reduce__(self): r""" >>> from ppl import Variable, Congruence, Congruence_System >>> from pickle import loads, dumps >>> x = Variable(0) >>> y = Variable(1) >>> z = Variable(2) >>> c1 = Congruence(2*x + 3*y - 5*z == 3, 12) >>> c1 2*x0+3*x1-5*x2-3==0 (mod 12) >>> loads(dumps(c1)) 2*x0+3*x1-5*x2-3==0 (mod 12) >>> assert c1.is_equal(loads(dumps(c1))) """ le = Linear_Expression(self.coefficients(), self.inhomogeneous_term()) return (congruence, (le == 0, self.modulus())) cdef class Congruence_System(object): r""" Wrapper for PPL's ``Congruence_System`` class. >>> from ppl import Variable, Congruence, Congruence_System >>> x = Variable(0) >>> y = Variable(1) >>> z = Variable(2) >>> c1 = Congruence(2*x + 3*y - 5*z == 0, 12) >>> c2 = Congruence(4*x + y == 5, 18) >>> C = Congruence_System() >>> C.insert(c1) >>> C.insert(c2) >>> C Congruence_System {2*x0+3*x1-5*x2==0 (mod 12), 4*x0+x1+13==0 (mod 18)} """ def __init__(self, arg=None): if arg is None: self.thisptr = new PPL_Congruence_System() elif isinstance(arg, Congruence): c = arg self.thisptr = new PPL_Congruence_System(c.thisptr[0]) elif isinstance(arg, Congruence_System): cs = arg self.thisptr = new PPL_Congruence_System(cs.thisptr[0]) elif isinstance(arg, (list, tuple)): self.thisptr = new PPL_Congruence_System() for congruence in arg: self.insert(congruence) def ascii_dump(self): r""" Write an ASCII dump of this congruence to stderr. Examples: >>> cmd = 'from ppl import Variable, Congruence_System\n' >>> cmd += 'x = Variable(0)\n' >>> cmd += 'y = Variable(1)\n' >>> cmd += 'cs = Congruence_System( (3*x == 2*y+1) % 7 )\n' >>> cmd += 'cs.ascii_dump()\n' >>> import subprocess, sys >>> proc = subprocess.Popen([sys.executable, '-c', cmd], stderr=subprocess.PIPE) >>> out, err = proc.communicate() >>> print(str(err.decode('ascii'))) 1 x 2 SPARSE size 3 6 3 -2 m 7 """ self.thisptr.ascii_dump() def __len__(self): r""" Return the number of congruences in the system. Examples: >>> from ppl import Variable, Congruence_System >>> x = Variable(0) >>> y = Variable(1) >>> cs = Congruence_System( [(x == 3) % 15, (2*y == 7) % 12]) >>> len(cs) 2 >>> cs.insert((2*x + y == 12) % 22) >>> len(cs) 3 >>> cs.clear() >>> len(cs) 0 """ cdef Py_ssize_t l = 0 cdef PPL_Congruence_System_iterator * csi_ptr = new PPL_Congruence_System_iterator(self.thisptr[0].begin()) while csi_ptr[0] != self.thisptr[0].end(): l += 1 csi_ptr[0].inc(1) del csi_ptr return l def __iter__(self): cdef PPL_Congruence_System_iterator * csi_ptr = new PPL_Congruence_System_iterator(self.thisptr[0].begin()) try: while csi_ptr[0] != self.thisptr[0].end(): yield _wrap_Congruence(deref(csi_ptr[0].inc(1))) finally: del csi_ptr def __repr__(self): s = 'Congruence_System {' s += ', '.join([repr(c) for c in self]) s += '}' return s def insert(self, Congruence c): r""" Insert the congruence ``c`` into the congruence system. Examples: >>> from ppl import Variable, Congruence_System >>> x = Variable(0) >>> y = Variable(1) >>> cs = Congruence_System() >>> cs.insert((3 * x + 2 == 0) % 13) >>> cs Congruence_System {3*x0+2==0 (mod 13)} """ self.thisptr.insert(c.thisptr[0]) def clear(self): r""" Remove all congruences from this congruence system. >>> from ppl import Variable, Congruence_System >>> x = Variable(0) >>> y = Variable(1) >>> cs = Congruence_System([(3*x+2*y+1 == 3) % 15, (x+2*y + 7 == 0) % 22]) >>> len(cs) 2 >>> cs.clear() >>> len(cs) 0 """ self.thisptr.clear() def __reduce__(self): """ Pickle object. Examples: >>> from ppl import Variable, Congruence_System >>> from pickle import loads, dumps >>> x = Variable(0) >>> y = Variable(1) >>> cs = Congruence_System([(3*x+2*y+1 == 3) % 15, (x+2*y + 7 == 0) % 22]) >>> cs Congruence_System {3*x0+2*x1+13==0 (mod 15), x0+2*x1+7==0 (mod 22)} >>> loads(dumps(cs)) Congruence_System {3*x0+2*x1+13==0 (mod 15), x0+2*x1+7==0 (mod 22)} """ return (Congruence_System, (tuple(self),)) cdef _wrap_Congruence(PPL_Congruence congruence): cdef Congruence c = Congruence.__new__(Congruence) c.thisptr = new PPL_Congruence(congruence) return c def congruence(le, m): return Congruence(le, m) pplpy-0.8.9/ppl/constraint.pxd000066400000000000000000000006531447517221400164030ustar00rootroot00000000000000from .linear_algebra cimport * cdef _wrap_Constraint(PPL_Constraint constraint) cdef _wrap_Constraint_System(PPL_Constraint_System constraint_system) cdef _make_Constraint_from_richcmp(lhs_, rhs_, op) cdef class Constraint(object): cdef PPL_Constraint *thisptr cdef class Constraint_System(object): cdef PPL_Constraint_System *thisptr cdef class Poly_Con_Relation(object): cdef PPL_Poly_Con_Relation *thisptr pplpy-0.8.9/ppl/constraint.pyx000066400000000000000000001014711447517221400164300ustar00rootroot00000000000000# distutils: language = c++ # distutils: libraries = gmp gmpxx ppl m #***************************************************************************** # Copyright (C) 2010-2014 Volker Braun # 2011 Simon King # 2011-2017 Jeroen Demeyer # 2012 Risan # 2013 Julien Puydt # 2013 Travis Scrimshaw # 2015 André Apitzsch # 2016 Jori Mäntysalo # 2016 Matthias Koeppe # 2016-2017 Frédéric Chapoton # 2016-2020 Vincent Delecroix # 2017-2018 Vincent Klein # # Distributed under the terms of the GNU General Public License (GPL) # as published by the Free Software Foundation; either version 3 of # the License, or (at youroption) any later version. # http://www.gnu.org/licenses/ #***************************************************************************** from gmpy2 cimport GMPy_MPZ_From_mpz, import_gmpy2 from cython.operator cimport dereference as deref from cpython.object cimport Py_LT, Py_LE, Py_EQ, Py_NE, Py_GT, Py_GE from .congruence cimport Congruence # PPL can use floating-point arithmetic to compute integers cdef extern from "ppl.hh" namespace "Parma_Polyhedra_Library": cdef void set_rounding_for_PPL() cdef void restore_pre_PPL_rounding() # initialize gmpy2 C API import_gmpy2() # but with PPL's rounding the gsl will be very unhappy; must turn off! restore_pre_PPL_rounding() def _dummy(): raise ValueError cdef class Constraint(object): r""" Wrapper for PPL's ``Constraint`` class. An object of the class ``Constraint`` is either: * an equality :math:`\sum_{i=0}^{n-1} a_i x_i + b = 0` * a non-strict inequality :math:`\sum_{i=0}^{n-1} a_i x_i + b \geq 0` * a strict inequality :math:`\sum_{i=0}^{n-1} a_i x_i + b > 0` where :math:`n` is the dimension of the space, :math:`a_i` is the integer coefficient of variable :math:`x_i`, and :math:`b_i` is the integer inhomogeneous term. INPUT/OUTPUT: You construct constraints by writing inequalities in :class:`Linear_Expression`. Do not attempt to manually construct constraints. Examples: >>> from ppl import Variable, Linear_Expression >>> x = Variable(0) >>> y = Variable(1) >>> 5*x-2*y > x+y-1 4*x0-3*x1+1>0 >>> 5*x-2*y >= x+y-1 4*x0-3*x1+1>=0 >>> 5*x-2*y == x+y-1 4*x0-3*x1+1==0 >>> 5*x-2*y <= x+y-1 -4*x0+3*x1-1>=0 >>> 5*x-2*y < x+y-1 -4*x0+3*x1-1>0 >>> x > 0 x0>0 Special care is needed if the left hand side is a constant: >>> 0 == 1 # watch out! False >>> Linear_Expression(0) == 1 mpz(-1)==0 """ def __init__(self, arg=None): if arg is None: self.thisptr = new PPL_Constraint() elif isinstance(arg, Constraint): self.thisptr = new PPL_Constraint(( arg).thisptr[0]) else: raise TypeError("invalid argument for Constraint") def __cinit__(self): """ The Cython constructor. See :class:`Constraint` for documentation. Tests: >>> from ppl import Variable >>> x = Variable(0) >>> x>0 # indirect doctest x0>0 """ self.thisptr = NULL def __dealloc__(self): """ The Cython destructor. """ del self.thisptr def __hash__(self): r""" Tests: >>> import ppl >>> hash(ppl.Variable(0) == 3) Traceback (most recent call last): ... TypeError: Constraint unhashable """ raise TypeError('Constraint unhashable') def __repr__(self): """ Return a string representation of the constraint. OUTPUT: String. Examples: >>> from ppl import Variable >>> x = Variable(0) >>> y = Variable(1) >>> (2*x-y+5 > x).__repr__() 'x0-x1+5>0' >>> (2*x-y+5 == x).__repr__() 'x0-x1+5==0' >>> (2*x-y+5 >= x).__repr__() 'x0-x1+5>=0' """ e = sum(self.coefficient(x)*x for x in (Variable(i) for i in range(self.space_dimension()))) e += self.inhomogeneous_term() s = repr(e) t = self.thisptr.type() if t == EQUALITY: s += '==0' elif t == NONSTRICT_INEQUALITY: s += '>=0' elif t == STRICT_INEQUALITY: s += '>0' else: raise RuntimeError return s def space_dimension(self): r""" Return the dimension of the vector space enclosing ``self``. OUTPUT: Integer. Examples: >>> from ppl import Variable >>> x = Variable(0) >>> y = Variable(1) >>> (x>=0).space_dimension() 1 >>> (y==1).space_dimension() 2 """ return self.thisptr.space_dimension() def type(self): r""" Return the constraint type of ``self``. OUTPUT: String. One of ``'equality'``, ``'nonstrict_inequality'``, or ``'strict_inequality'``. Examples: >>> from ppl import Variable >>> x = Variable(0) >>> (x==0).type() 'equality' >>> (x>=0).type() 'nonstrict_inequality' >>> (x>0).type() 'strict_inequality' """ t = self.thisptr.type() if t == EQUALITY: return 'equality' elif t == NONSTRICT_INEQUALITY: return 'nonstrict_inequality' elif t == STRICT_INEQUALITY: return 'strict_inequality' else: raise RuntimeError def is_equality(self): r""" Test whether ``self`` is an equality. OUTPUT: Boolean. Returns ``True`` if and only if ``self`` is an equality constraint. Examples: >>> from ppl import Variable >>> x = Variable(0) >>> (x==0).is_equality() True >>> (x>=0).is_equality() False >>> (x>0).is_equality() False """ return self.thisptr.is_equality() def is_inequality(self): r""" Test whether ``self`` is an inequality. OUTPUT: Boolean. Returns ``True`` if and only if ``self`` is an inequality constraint, either strict or non-strict. Examples: >>> from ppl import Variable >>> x = Variable(0) >>> (x==0).is_inequality() False >>> (x>=0).is_inequality() True >>> (x>0).is_inequality() True """ return self.thisptr.is_inequality() def is_nonstrict_inequality(self): r""" Test whether ``self`` is a non-strict inequality. OUTPUT: Boolean. Returns ``True`` if and only if ``self`` is an non-strict inequality constraint. Examples: >>> from ppl import Variable >>> x = Variable(0) >>> (x==0).is_nonstrict_inequality() False >>> (x>=0).is_nonstrict_inequality() True >>> (x>0).is_nonstrict_inequality() False """ return self.thisptr.is_nonstrict_inequality() def is_strict_inequality(self): r""" Test whether ``self`` is a strict inequality. OUTPUT: Boolean. Returns ``True`` if and only if ``self`` is an strict inequality constraint. Examples: >>> from ppl import Variable >>> x = Variable(0) >>> (x==0).is_strict_inequality() False >>> (x>=0).is_strict_inequality() False >>> (x>0).is_strict_inequality() True """ return self.thisptr.is_strict_inequality() def coefficient(self, Variable v): """ Return the coefficient of the variable ``v``. INPUT: - ``v`` -- a :class:`Variable`. OUTPUT: An integer. Examples: >>> from ppl import Variable >>> x = Variable(0) >>> ineq = 3*x+1 > 0 >>> ineq.coefficient(x) mpz(3) >>> y = Variable(1) >>> ineq = 3**50 * y + 2 > 1 >>> str(ineq.coefficient(y)) '717897987691852588770249' >>> ineq.coefficient(x) mpz(0) """ return GMPy_MPZ_From_mpz(self.thisptr.coefficient(v.thisptr[0]).get_mpz_t()) def coefficients(self): """ Return the coefficients of the constraint. See also :meth:`coefficient`. OUTPUT: A tuple of integers of length :meth:`space_dimension`. Examples: >>> from ppl import Variable >>> x = Variable(0); y = Variable(1) >>> ineq = ( 3*x+5*y+1 == 2); ineq 3*x0+5*x1-1==0 >>> ineq.coefficients() (mpz(3), mpz(5)) """ cdef int d = self.space_dimension() cdef int i coeffs = [] for i in range(0, d): coeffs.append(GMPy_MPZ_From_mpz(self.thisptr.coefficient(PPL_Variable(i)).get_mpz_t())) return tuple(coeffs) def inhomogeneous_term(self): """ Return the inhomogeneous term of the constraint. OUTPUT: Integer. Examples: >>> from ppl import Variable >>> y = Variable(1) >>> ineq = 10+y > 9 >>> ineq x1+1>0 >>> ineq.inhomogeneous_term() mpz(1) >>> ineq = 2**66 + y > 0 >>> str(ineq.inhomogeneous_term()) '73786976294838206464' """ return GMPy_MPZ_From_mpz(self.thisptr.inhomogeneous_term().get_mpz_t()) def is_tautological(self): r""" Test whether ``self`` is a tautological constraint. A tautology can have either one of the following forms: * an equality: :math:`\sum 0 x_i + 0 = 0`, * a non-strict inequality: :math:`\sum 0 x_i + b \geq 0` with `b\geq 0`, or * a strict inequality: :math:`\sum 0 x_i + b > 0` with `b> 0`. OUTPUT: Boolean. Returns ``True`` if and only if ``self`` is a tautological constraint. Examples: >>> from ppl import Variable >>> x = Variable(0) >>> (x==0).is_tautological() False >>> (0*x>=0).is_tautological() True """ return self.thisptr.is_tautological() def is_inconsistent(self): r""" Test whether ``self`` is an inconsistent constraint, that is, always false. An inconsistent constraint can have either one of the following forms: * an equality: :math:`\sum 0 x_i + b = 0` with `b\not=0`, * a non-strict inequality: :math:`\sum 0 x_i + b \geq 0` with `b< 0`, or * a strict inequality: :math:`\sum 0 x_i + b > 0` with `b\leq 0`. OUTPUT: Boolean. Returns ``True`` if and only if ``self`` is an inconsistent constraint. Examples: >>> from ppl import Variable >>> x = Variable(0) >>> (x==1).is_inconsistent() False >>> (0*x>=1).is_inconsistent() True """ return self.thisptr.is_inconsistent() def is_equivalent_to(self, Constraint c): r""" Test whether ``self`` and ``c`` are equivalent. INPUT: - ``c`` -- a :class:`Constraint`. OUTPUT: Boolean. Returns ``True`` if and only if ``self`` and ``c`` are equivalent constraints. Note that constraints having different space dimensions are not equivalent. However, constraints having different types may nonetheless be equivalent, if they both are tautologies or inconsistent. Examples: >>> from ppl import Variable, Linear_Expression >>> x = Variable(0) >>> y = Variable(1) >>> (x > 0).is_equivalent_to(Linear_Expression(0) < x) True >>> (x > 0).is_equivalent_to(0*y < x) False >>> (0*x > 1).is_equivalent_to(0*x == -2) True """ return self.thisptr.is_equivalent_to(c.thisptr[0]) def ascii_dump(self): r""" Write an ASCII dump to stderr. Examples: >>> cmd = 'from ppl import Linear_Expression, Variable\n' >>> cmd += 'x = Variable(0)\n' >>> cmd += 'y = Variable(1)\n' >>> cmd += 'e = (3*x+2*y+1 > 0)\n' >>> cmd += 'e.ascii_dump()\n' >>> import subprocess, sys >>> proc = subprocess.Popen([sys.executable, '-c', cmd], stderr=subprocess.PIPE) >>> out, err = proc.communicate() >>> print(str(err.decode('ascii'))) size 4 1 3 2 -1 ... """ self.thisptr.ascii_dump() def __reduce__(self): """ Pickle object. Examples: >>> from ppl import Variable >>> from pickle import loads, dumps >>> x = Variable(0) >>> y = Variable(1) >>> loads(dumps(3*x+2*y+1>=5)) 3*x0+2*x1-4>=0 >>> loads(dumps(3*x+2*y+1>5)) 3*x0+2*x1-4>0 >>> loads(dumps(3*x+2*y+1==5)) 3*x0+2*x1-4==0 """ le = Linear_Expression(self.coefficients(), self.inhomogeneous_term()) if self.is_nonstrict_inequality(): return (inequality, (le, )) elif self.is_strict_inequality(): return (strict_inequality, (le, )) elif self.is_equality(): return (equation, (le, )) else: raise RuntimeError def permute_space_dimensions(self, cycle): """ Permute the coordinates according to ``cycle``. >>> from ppl import Variable >>> x = Variable(0); y = Variable(1); z = Variable(2) >>> l = 2*x - y + 3*z >>> ieq = l >= 5 >>> ieq.permute_space_dimensions([2, 1, 0]) >>> ieq -x0+3*x1+2*x2-5>=0 """ cdef cppvector[PPL_Variable] cpp_cycle cdef int i for i in cycle: cpp_cycle.push_back(PPL_Variable(i)) self.thisptr.permute_space_dimensions(cpp_cycle) def __mod__(self, m): r""" Return this equality modulo m >>> import ppl >>> x = ppl.Variable(0) >>> y = ppl.Variable(1) >>> (2*x + 3*y == 3) % 5 2*x0+3*x1-3==0 (mod 5) >>> (x <= 3) % 5 Traceback (most recent call last): ... ValueError: PPL::Congruence::Congruence(c, r): constraint c must be an equality. """ return Congruence(self, m) def inequality(expression): """ Construct an inequality. INPUT: - ``expression`` -- a :class:`Linear_Expression`. OUTPUT: The inequality ``expression`` >= 0. Examples: >>> from ppl import Variable, inequality >>> y = Variable(1) >>> 2*y+1 >= 0 2*x1+1>=0 >>> inequality(2*y+1) 2*x1+1>=0 """ return expression >= 0 def strict_inequality(expression): """ Construct a strict inequality. INPUT: - ``expression`` -- a :class:`Linear_Expression`. OUTPUT: The inequality ``expression`` > 0. Examples: >>> from ppl import Variable, strict_inequality >>> y = Variable(1) >>> 2*y+1 > 0 2*x1+1>0 >>> strict_inequality(2*y+1) 2*x1+1>0 """ return expression > 0 def equation(expression): """ Construct an equation. INPUT: - ``expression`` -- a :class:`Linear_Expression`. OUTPUT: The equation ``expression`` == 0. Examples: >>> from ppl import Variable, equation >>> y = Variable(1) >>> 2*y+1 == 0 2*x1+1==0 >>> equation(2*y+1) 2*x1+1==0 """ return expression == 0 cdef class Constraint_System(object): """ Wrapper for PPL's ``Constraint_System`` class. An object of the class Constraint_System is a system of constraints, i.e., a multiset of objects of the class Constraint. When inserting constraints in a system, space dimensions are automatically adjusted so that all the constraints in the system are defined on the same vector space. Examples: >>> from ppl import Constraint_System, Variable >>> x = Variable(0) >>> y = Variable(1) >>> cs = Constraint_System( 5*x-2*y > 0 ) >>> cs.insert( 6*x < 3*y ) >>> cs.insert( x >= 2*x-7*y ) >>> cs Constraint_System {5*x0-2*x1>0, ...} >>> cs[0] 5*x0-2*x1>0 """ def __init__(self, arg=None): if arg is None: self.thisptr = new PPL_Constraint_System() elif isinstance(arg, Constraint): g = arg self.thisptr = new PPL_Constraint_System(g.thisptr[0]) elif isinstance(arg, Constraint_System): gs = arg self.thisptr = new PPL_Constraint_System(gs.thisptr[0]) elif isinstance(arg, (list, tuple)): self.thisptr = new PPL_Constraint_System() for constraint in arg: self.insert(constraint) else: raise TypeError('cannot initialize from {!r}'.format(arg)) def __cinit__(self, arg=None): """ The Cython constructor. See :class:`Constraint_System` for documentation. Tests: >>> from ppl import Constraint_System >>> Constraint_System() Constraint_System {} """ self.thisptr = NULL def __dealloc__(self): """ The Cython destructor. """ del self.thisptr def __hash__(self): r""" Tests: >>> import ppl >>> hash(ppl.Constraint_System()) Traceback (most recent call last): ... TypeError: Constraint_System unhashable """ raise TypeError('Constraint_System unhashable') def space_dimension(self): r""" Return the dimension of the vector space enclosing ``self``. OUTPUT: Integer. Examples: >>> from ppl import Variable, Constraint_System >>> x = Variable(0) >>> cs = Constraint_System( x>0 ) >>> cs.space_dimension() 1 """ return self.thisptr.space_dimension() def has_equalities(self): r""" Tests whether ``self`` contains one or more equality constraints. OUTPUT: Boolean. Examples: >>> from ppl import Variable, Constraint_System >>> x = Variable(0) >>> cs = Constraint_System() >>> cs.insert( x>0 ) >>> cs.insert( x<0 ) >>> cs.has_equalities() False >>> cs.insert( x==0 ) >>> cs.has_equalities() True """ return self.thisptr.has_equalities() def has_strict_inequalities(self): r""" Tests whether ``self`` contains one or more strict inequality constraints. OUTPUT: Boolean. Examples: >>> from ppl import Variable, Constraint_System >>> x = Variable(0) >>> cs = Constraint_System() >>> cs.insert( x>=0 ) >>> cs.insert( x==-1 ) >>> cs.has_strict_inequalities() False >>> cs.insert( x>0 ) >>> cs.has_strict_inequalities() True """ return self.thisptr.has_strict_inequalities() def clear(self): r""" Removes all constraints from the constraint system and sets its space dimension to 0. Examples: >>> from ppl import Variable, Constraint_System >>> x = Variable(0) >>> cs = Constraint_System(x>0) >>> cs Constraint_System {x0>0} >>> cs.clear() >>> cs Constraint_System {} """ self.thisptr.clear() def insert(self, Constraint c): """ Insert ``c`` into the constraint system. INPUT: - ``c`` -- a :class:`Constraint`. Examples: >>> from ppl import Variable, Constraint_System >>> x = Variable(0) >>> cs = Constraint_System() >>> cs.insert( x>0 ) >>> cs Constraint_System {x0>0} """ self.thisptr.insert(c.thisptr[0]) def empty(self): """ Return ``True`` if and only if ``self`` has no constraints. OUTPUT: Boolean. Examples: >>> from ppl import Variable, Constraint_System >>> x = Variable(0) >>> cs = Constraint_System() >>> cs.empty() True >>> cs.insert( x>0 ) >>> cs.empty() False """ return self.thisptr.empty() def ascii_dump(self): r""" Write an ASCII dump to stderr. Examples: >>> cmd = 'from ppl import Constraint_System, Variable\n' >>> cmd += 'x = Variable(0)\n' >>> cmd += 'y = Variable(1)\n' >>> cmd += 'cs = Constraint_System( 3*x > 2*y+1 )\n' >>> cmd += 'cs.ascii_dump()\n' >>> import subprocess, sys >>> proc = subprocess.Popen([sys.executable, '-c', cmd], stderr=subprocess.PIPE) >>> out, err = proc.communicate() >>> print(str(err.decode('ascii'))) topology NOT_NECESSARILY_CLOSED ... """ self.thisptr.ascii_dump() def __len__(self): """ Return the number of constraints in the system. Examples: >>> from ppl import Variable, Constraint_System >>> x = Variable(0) >>> cs = Constraint_System( [x>0, x<1] ) >>> len(cs) 2 >>> cs.insert(2*x < 3) >>> len(cs) 3 >>> cs.clear() >>> len(cs) 0 """ cdef Py_ssize_t length = 0 cdef PPL_Constraint_System_iterator *csi_ptr = new PPL_Constraint_System_iterator(self.thisptr[0].begin()) while csi_ptr[0] != self.thisptr[0].end(): length += 1 csi_ptr[0].inc(1) del csi_ptr return length def __iter__(self): """ Iterate through the constraints of the system. Examples: >>> from ppl import Variable, Constraint_System >>> x = Variable(0) >>> cs = Constraint_System( x>0 ) >>> iter = cs.__iter__() >>> next(iter) x0>0 >>> list(cs) # uses __iter__() internally [x0>0] >>> x = Variable(0) >>> y = Variable(1) >>> cs = Constraint_System( 5*x < 2*y ) >>> cs.insert( 6*x-y == 0 ) >>> cs.insert( x >= 2*x-7*y ) >>> next(cs.__iter__()) -5*x0+2*x1>0 >>> list(cs) [-5*x0+2*x1>0, 6*x0-x1==0, -x0+7*x1>=0] >>> x = Variable(0) >>> cs = Constraint_System( x > 0 ) >>> cs.insert ( 2*x <= -3) >>> it = cs.__iter__() >>> next(it) x0>0 >>> next(it) -2*x0-3>=0 >>> next(it) Traceback (most recent call last): ... StopIteration """ cdef PPL_Constraint_System_iterator *csi_ptr = new PPL_Constraint_System_iterator(self.thisptr[0].begin()) try: while csi_ptr[0] != self.thisptr[0].end(): yield _wrap_Constraint(deref(csi_ptr[0].inc(1))) finally: del csi_ptr def __getitem__(self, int k): """ Return the k-th constraint. The correct way to read the individual constraints is to iterate over the constraint system. This method is for convenience only. INPUT: - ``k`` -- integer. The index of the constraint. OUTPUT: The `k`-th constraint of the constraint system. Examples: >>> from ppl import Variable, Constraint_System >>> x = Variable(0) >>> cs = Constraint_System( x>0 ) >>> cs.insert( x<1 ) >>> cs Constraint_System {x0>0, -x0+1>0} >>> cs[0] x0>0 >>> cs[1] -x0+1>0 """ if k < 0: raise IndexError('index must be nonnegative') iterator = iter(self) try: for i in range(k): next(iterator) except StopIteration: raise IndexError('index is past-the-end') return next(iterator) def __repr__(self): r""" Return a string representation of the constraint system. OUTPUT: A string. Examples: >>> from ppl import Constraint_System, Variable >>> x = Variable(0) >>> y = Variable(1) >>> cs = Constraint_System([3*x+2*y+1 < 3, 0*x>x+1]) >>> cs.__repr__() 'Constraint_System {-3*x0-2*x1+2>0, -x0-1>0}' """ s = 'Constraint_System {' s += ', '.join([repr(c) for c in self]) s += '}' return s def __reduce__(self): """ Pickle object. Tests: >>> from ppl import Constraint_System, Variable >>> from pickle import loads, dumps >>> x = Variable(0) >>> y = Variable(1) >>> cs = Constraint_System([3*x+2*y+1 < 3, 0*x>x+1]); cs Constraint_System {-3*x0-2*x1+2>0, -x0-1>0} >>> loads(dumps(cs)) Constraint_System {-3*x0-2*x1+2>0, -x0-1>0} """ return (Constraint_System, (tuple(self),)) cdef class Poly_Con_Relation(object): r""" Wrapper for PPL's ``Poly_Con_Relation`` class. INPUT/OUTPUT: You must not construct :class:`Poly_Con_Relation` objects manually. You will usually get them from :meth:`~sage.libs.ppl.Polyhedron.relation_with`. You can also get pre-defined relations from the class methods :meth:`nothing`, :meth:`is_disjoint`, :meth:`strictly_intersects`, :meth:`is_included`, and :meth:`saturates`. Examples: >>> from ppl import Poly_Con_Relation >>> saturates = Poly_Con_Relation.saturates(); saturates saturates >>> is_included = Poly_Con_Relation.is_included(); is_included is_included >>> is_included.implies(saturates) False >>> saturates.implies(is_included) False >>> rels = [] >>> rels.append(Poly_Con_Relation.nothing()) >>> rels.append(Poly_Con_Relation.is_disjoint()) >>> rels.append(Poly_Con_Relation.strictly_intersects()) >>> rels.append(Poly_Con_Relation.is_included()) >>> rels.append(Poly_Con_Relation.saturates()) >>> rels [nothing, is_disjoint, strictly_intersects, is_included, saturates] >>> for i, rel_i in enumerate(rels): ... s = "" ... for j, rel_j in enumerate(rels): ... s=s+str(int(rel_i.implies(rel_j))) + ' ' ... print(" ".join(str(int(rel_i.implies(rel_j))) for j, rel_j in enumerate(rels))) 1 0 0 0 0 1 1 0 0 0 1 0 1 0 0 1 0 0 1 0 1 0 0 0 1 """ def __cinit__(self, do_not_construct_manually=False): """ The Cython constructor. See :class:`Poly_Con_Relation` for documentation. Tests: >>> from ppl import Poly_Con_Relation >>> Poly_Con_Relation.nothing() nothing """ assert(do_not_construct_manually) self.thisptr = NULL def __dealloc__(self): """ The Cython destructor. """ assert self.thisptr!=NULL, 'Do not construct Poly_Con_Relation objects manually!' del self.thisptr def __hash__(self): r""" Tests: >>> import ppl >>> hash(ppl.Poly_Con_Relation.saturates()) Traceback (most recent call last): ... TypeError: Poly_Con_Relation unhashable """ raise TypeError('Poly_Con_Relation unhashable') def implies(self, Poly_Con_Relation y): r""" Test whether ``self`` implies ``y``. INPUT: - ``y`` -- a :class:`Poly_Con_Relation`. OUTPUT: Boolean. ``True`` if and only if ``self`` implies ``y``. Examples: >>> from ppl import Poly_Con_Relation >>> nothing = Poly_Con_Relation.nothing() >>> nothing.implies( nothing ) True """ return self.thisptr.implies(y.thisptr[0]) @classmethod def nothing(cls): r""" Return the assertion that says nothing. OUTPUT: A :class:`Poly_Con_Relation`. Examples: >>> from ppl import Poly_Con_Relation >>> Poly_Con_Relation.nothing() nothing """ return _wrap_Poly_Con_Relation(PPL_Poly_Con_Relation_nothing()) @classmethod def is_disjoint(cls): r""" Return the assertion "The polyhedron and the set of points satisfying the constraint are disjoint". OUTPUT: A :class:`Poly_Con_Relation`. Examples: >>> from ppl import Poly_Con_Relation >>> Poly_Con_Relation.is_disjoint() is_disjoint """ return _wrap_Poly_Con_Relation(PPL_Poly_Con_Relation_is_disjoint()) @classmethod def strictly_intersects(cls): r""" Return the assertion "The polyhedron intersects the set of points satisfying the constraint, but it is not included in it". :return: a :class:`Poly_Con_Relation`. Examples: >>> from ppl import Poly_Con_Relation >>> Poly_Con_Relation.strictly_intersects() strictly_intersects """ return _wrap_Poly_Con_Relation(PPL_Poly_Con_Relation_strictly_intersects()) @classmethod def is_included(cls): r""" Return the assertion "The polyhedron is included in the set of points satisfying the constraint". OUTPUT: A :class:`Poly_Con_Relation`. Examples: >>> from ppl import Poly_Con_Relation >>> Poly_Con_Relation.is_included() is_included """ return _wrap_Poly_Con_Relation(PPL_Poly_Con_Relation_is_included()) @classmethod def saturates(cls): r""" Return the assertion "". OUTPUT: A :class:`Poly_Con_Relation`. Examples: >>> from ppl import Poly_Con_Relation >>> Poly_Con_Relation.saturates() saturates """ return _wrap_Poly_Con_Relation(PPL_Poly_Con_Relation_saturates()) def ascii_dump(self): r""" Write an ASCII dump to stderr. Examples: >>> cmd = 'from ppl import Poly_Con_Relation\n' >>> cmd += 'Poly_Con_Relation.nothing().ascii_dump()\n' >>> import subprocess, sys >>> proc = subprocess.Popen([sys.executable, '-c', cmd], stderr=subprocess.PIPE) >>> out, err = proc.communicate() >>> print(str(err.decode('ascii'))) NOTHING """ self.thisptr.ascii_dump() def __repr__(self): r""" Return a string representation. OUTPUT: String. Examples: >>> from ppl import Poly_Con_Relation >>> Poly_Con_Relation.nothing().__repr__() 'nothing' """ rel = [] if self.implies(Poly_Con_Relation.is_disjoint()): rel.append('is_disjoint') if self.implies(Poly_Con_Relation.strictly_intersects()): rel.append('strictly_intersects') if self.implies(Poly_Con_Relation.is_included()): rel.append('is_included') if self.implies(Poly_Con_Relation.saturates()): rel.append('saturates') if rel: return ', '.join(rel) else: return 'nothing' cdef _make_Constraint_from_richcmp(lhs_, rhs_, op): cdef Linear_Expression lhs = Linear_Expression(lhs_) cdef Linear_Expression rhs = Linear_Expression(rhs_) if op == Py_LT: return _wrap_Constraint(lhs.thisptr[0] < rhs.thisptr[0]) elif op == Py_LE: return _wrap_Constraint(lhs.thisptr[0] <= rhs.thisptr[0]) elif op == Py_EQ: return _wrap_Constraint(lhs.thisptr[0] == rhs.thisptr[0]) elif op == Py_GT: return _wrap_Constraint(lhs.thisptr[0] > rhs.thisptr[0]) elif op == Py_GE: return _wrap_Constraint(lhs.thisptr[0] >= rhs.thisptr[0]) elif op == Py_NE: raise NotImplementedError else: assert(False) cdef _wrap_Constraint(PPL_Constraint constraint): """ Wrap a C++ ``PPL_Constraint`` into a Cython ``Constraint``. """ cdef Constraint c = Constraint.__new__(Constraint) c.thisptr = new PPL_Constraint(constraint) return c cdef _wrap_Constraint_System(PPL_Constraint_System constraint_system): """ Wrap a C++ ``PPL_Constraint_System`` into a Cython ``Constraint_System``. """ cdef Constraint_System cs = Constraint_System.__new__(Constraint_System) cs.thisptr = new PPL_Constraint_System(constraint_system) return cs cdef _wrap_Poly_Con_Relation(PPL_Poly_Con_Relation relation): """ Wrap a C++ ``PPL_Poly_Con_Relation`` into a Cython ``Poly_Con_Relation``. """ cdef Poly_Con_Relation rel = Poly_Con_Relation(True) rel.thisptr = new PPL_Poly_Con_Relation(relation) return rel pplpy-0.8.9/ppl/generator.pxd000066400000000000000000000007371447517221400162100ustar00rootroot00000000000000from __future__ import absolute_import from .ppl_decl cimport * from .linear_algebra cimport * cdef _wrap_Generator(PPL_Generator generator) cdef _wrap_Generator_System(PPL_Generator_System generator_system) cdef PPL_GeneratorType_str(PPL_GeneratorType t) cdef class Generator(object): cdef PPL_Generator *thisptr cdef class Generator_System(object): cdef PPL_Generator_System *thisptr cdef class Poly_Gen_Relation(object): cdef PPL_Poly_Gen_Relation *thisptr pplpy-0.8.9/ppl/generator.pyx000066400000000000000000001032041447517221400162260ustar00rootroot00000000000000# distutils: language = c++ # distutils: libraries = gmp gmpxx ppl m #***************************************************************************** # Copyright (C) 2010-2014 Volker Braun # 2011 Simon King # 2011-2017 Jeroen Demeyer # 2012 Risan # 2013 Julien Puydt # 2013 Travis Scrimshaw # 2015 André Apitzsch # 2016 Jori Mäntysalo # 2016 Matthias Koeppe # 2016-2017 Frédéric Chapoton # 2016-2018 Vincent Delecroix # 2017-2018 Vincent Klein # # Distributed under the terms of the GNU General Public License (GPL) # as published by the Free Software Foundation; either version 3 of # the License, or (at youroption) any later version. # http://www.gnu.org/licenses/ #***************************************************************************** from gmpy2 cimport GMPy_MPZ_From_mpz, import_gmpy2 from cython.operator cimport dereference as deref from .linear_algebra cimport PPL_Coefficient_from_pyobject # PPL can use floating-point arithmetic to compute integers cdef extern from "ppl.hh" namespace "Parma_Polyhedra_Library": cdef void set_rounding_for_PPL() cdef void restore_pre_PPL_rounding() # initialize gmpy2 C API import_gmpy2() # but with PPL's rounding the gsl will be very unhappy; must turn off! restore_pre_PPL_rounding() #################################################### cdef class Generator(object): r""" Wrapper for PPL's ``Generator`` class. An object of the class Generator is one of the following: * a line :math:`\ell = (a_0, \dots, a_{n-1})^T` * a ray :math:`r = (a_0, \dots, a_{n-1})^T` * a point :math:`p = (\tfrac{a_0}{d}, \dots, \tfrac{a_{n-1}}{d})^T` * a closure point :math:`c = (\tfrac{a_0}{d}, \dots, \tfrac{a_{n-1}}{d})^T` where :math:`n` is the dimension of the space and, for points and closure points, :math:`d` is the divisor. INPUT/OUTPUT: Use the helper functions :func:`line`, :func:`ray`, :func:`point`, and :func:`closure_point` to construct generators. Analogous class methods are also available, see :meth:`Generator.line`, :meth:`Generator.ray`, :meth:`Generator.point`, :meth:`Generator.closure_point`. Do not attempt to construct generators manually. .. NOTE:: The generators are constructed from linear expressions. The inhomogeneous term is always silently discarded. Examples: >>> from ppl import Generator, Variable >>> x = Variable(0) >>> y = Variable(1) >>> Generator.line(5*x-2*y) line(5, -2) >>> Generator.ray(5*x-2*y) ray(5, -2) >>> Generator.point(5*x-2*y, 7) point(5/7, -2/7) >>> Generator.closure_point(5*x-2*y, 7) closure_point(5/7, -2/7) """ def __cinit__(self, do_not_construct_manually=False): """ The Cython constructor. See :class:`Variable` for documentation. Tests: >>> from ppl import Variable, line >>> x = Variable(0) >>> line(x) # indirect doctest line(1) """ assert(do_not_construct_manually) self.thisptr = NULL def __dealloc__(self): """ The Cython destructor. """ assert self.thisptr!=NULL, 'Do not construct Generators manually!' del self.thisptr def __hash__(self): r""" Tests: >>> import ppl >>> hash(ppl.point()) Traceback (most recent call last): ... TypeError: Generator unhashable """ raise TypeError('Generator unhashable') @classmethod def line(cls, expression): """ Construct a line. INPUT: - ``expression`` -- a :class:`Linear_Expression` or something convertible to it (:class:`Variable` or integer). OUTPUT: A new :class:`Generator` representing the line. Raises a ``ValueError` if the homogeneous part of ``expression`` represents the origin of the vector space. Examples: >>> from ppl import Generator, Variable >>> y = Variable(1) >>> Generator.line(2*y) line(0, 1) >>> Generator.line(y) line(0, 1) >>> Generator.line(1) Traceback (most recent call last): ... ValueError: PPL::line(e): e == 0, but the origin cannot be a line. """ cdef Linear_Expression e = Linear_Expression(expression) # This does not work as Cython gets confused by the private default ctor # return _wrap_Generator(PPL_line(e.thisptr[0])) # workaround follows cdef Generator g = Generator(True) try: g.thisptr = new PPL_Generator(PPL_line(e.thisptr[0])) except BaseException: # g.thisptr must be set to something valid or g.__dealloc__() will segfault g.thisptr = new PPL_Generator(PPL_point(e.thisptr[0], PPL_Coefficient(1))) raise return g @classmethod def ray(cls, expression): """ Construct a ray. INPUT: - ``expression`` -- a :class:`Linear_Expression` or something convertible to it (:class:`Variable` or integer). OUTPUT: A new :class:`Generator` representing the ray. Raises a ``ValueError` if the homogeneous part of ``expression`` represents the origin of the vector space. Examples: >>> from ppl import Generator, Variable >>> y = Variable(1) >>> Generator.ray(2*y) ray(0, 1) >>> Generator.ray(y) ray(0, 1) >>> Generator.ray(1) Traceback (most recent call last): ... ValueError: PPL::ray(e): e == 0, but the origin cannot be a ray. """ cdef Linear_Expression e = Linear_Expression(expression) # This does not work as Cython gets confused by the private default ctor # return _wrap_Generator(PPL_ray(e.thisptr[0])) # workaround follows cdef Generator g = Generator(True) try: g.thisptr = new PPL_Generator(PPL_ray(e.thisptr[0])) except BaseException: # g.thisptr must be set to something valid or g.__dealloc__() will segfault g.thisptr = new PPL_Generator(PPL_point(e.thisptr[0], PPL_Coefficient(1))) raise return g @classmethod def point(cls, expression=0, divisor=1): """ Construct a point. INPUT: - ``expression`` -- a :class:`Linear_Expression` or something convertible to it (:class:`Variable` or integer). - ``divisor`` -- an integer. OUTPUT: A new :class:`Generator` representing the point. Raises a ``ValueError` if ``divisor==0``. Examples: >>> from ppl import Generator, Variable >>> y = Variable(1) >>> Generator.point(2*y+7, 3) point(0/3, 2/3) >>> Generator.point(y+7, 3) point(0/3, 1/3) >>> Generator.point(7, 3) point() >>> Generator.point(0, 0) Traceback (most recent call last): ... ValueError: PPL::point(e, d): d == 0. """ cdef Linear_Expression e = Linear_Expression(expression) # This does not work as Cython gets confused by the private default ctor # return _wrap_Generator(PPL_point(e.thisptr[0], PPL_Coefficient(d.value))) # workaround follows cdef Generator g = Generator(True) try: g.thisptr = new PPL_Generator(PPL_point(e.thisptr[0], PPL_Coefficient_from_pyobject(divisor))) except BaseException: # g.thisptr must be set to something valid or g.__dealloc__() will segfault g.thisptr = new PPL_Generator(PPL_point(e.thisptr[0], PPL_Coefficient(1))) raise return g @classmethod def closure_point(cls, expression=0, divisor=1): """ Construct a closure point. A closure point is a point of the topological closure of a polyhedron that is not a point of the polyhedron itself. INPUT: - ``expression`` -- a :class:`Linear_Expression` or something convertible to it (:class:`Variable` or integer). - ``divisor`` -- an integer. OUTPUT: A new :class:`Generator` representing the point. Raises a ``ValueError` if ``divisor==0``. Examples: >>> from ppl import Generator, Variable >>> y = Variable(1) >>> Generator.closure_point(2*y+7, 3) closure_point(0/3, 2/3) >>> Generator.closure_point(y+7, 3) closure_point(0/3, 1/3) >>> Generator.closure_point(7, 3) closure_point() >>> Generator.closure_point(0, 0) Traceback (most recent call last): ... ValueError: PPL::closure_point(e, d): d == 0. """ cdef Linear_Expression e = Linear_Expression(expression) # This does not work as Cython gets confused by the private default ctor # return _wrap_Generator(PPL_closure_point(e.thisptr[0], PPL_Coefficient(d.value))) # workaround follows cdef Generator g = Generator(True) try: g.thisptr = new PPL_Generator(PPL_closure_point(e.thisptr[0], PPL_Coefficient_from_pyobject(divisor))) except BaseException: # g.thisptr must be set to something valid or g.__dealloc__() will segfault g.thisptr = new PPL_Generator(PPL_point(e.thisptr[0], PPL_Coefficient(1))) raise return g def __repr__(self): """ Return a string representation of the generator. OUTPUT: String. Examples: >>> from ppl import Generator, Variable >>> x = Variable(0) >>> y = Variable(1) >>> e = 2*x-y+5 >>> Generator.line(e) line(2, -1) >>> Generator.ray(e) ray(2, -1) >>> Generator.point(e, 3) point(2/3, -1/3) >>> Generator.closure_point(e, 3) closure_point(2/3, -1/3) """ cdef PPL_GeneratorType t = self.thisptr.type() if t == LINE or t == RAY: div = '' elif t == POINT or t == CLOSURE_POINT: div = '/' + str(self.divisor()) else: raise RuntimeError s = ', '.join(str(self.coefficient(Variable(i))) + div for i in range(self.space_dimension())) return PPL_GeneratorType_str(t) + '(' + s + ')' def space_dimension(self): r""" Return the dimension of the vector space enclosing ``self``. OUTPUT: Integer. Examples: >>> from ppl import Variable, point >>> x = Variable(0) >>> y = Variable(1) >>> point(x).space_dimension() 1 >>> point(y).space_dimension() 2 """ return self.thisptr.space_dimension() def set_space_dimension(self, size_t n): r""" Set the dimension of this generator to ``n`` Examples: >>> import ppl >>> p = ppl.point() >>> p point() >>> p.set_space_dimension(5) >>> p point(0/1, 0/1, 0/1, 0/1, 0/1) >>> p = ppl.point(1 * ppl.Variable(0) + 2 * ppl.Variable(1) + 3 * ppl.Variable(2)) >>> p.set_space_dimension(2) >>> p point(1/1, 2/1) """ self.thisptr.set_space_dimension(n) def type(self): r""" Return the generator type of ``self``. OUTPUT: String. One of ``'line'``, ``'ray'``, ``'point'``, or ``'closure_point'``. Examples: >>> from ppl import Variable, point, closure_point, ray, line >>> x = Variable(0) >>> line(x).type() 'line' >>> ray(x).type() 'ray' >>> point(x,2).type() 'point' >>> closure_point(x,2).type() 'closure_point' """ return PPL_GeneratorType_str(self.thisptr.type()) def is_line(self): r""" Test whether ``self`` is a line. OUTPUT: Boolean. Examples: >>> from ppl import Variable, point, closure_point, ray, line >>> x = Variable(0) >>> line(x).is_line() True >>> ray(x).is_line() False >>> point(x,2).is_line() False >>> closure_point(x,2).is_line() False """ return self.thisptr.is_line() def is_ray(self): r""" Test whether ``self`` is a ray. OUTPUT: Boolean. Examples: >>> from ppl import Variable, point, closure_point, ray, line >>> x = Variable(0) >>> line(x).is_ray() False >>> ray(x).is_ray() True >>> point(x,2).is_ray() False >>> closure_point(x,2).is_ray() False """ return self.thisptr.is_ray() def is_line_or_ray(self): r""" Test whether ``self`` is a line or a ray. OUTPUT: Boolean. Examples: >>> from ppl import Variable, point, closure_point, ray, line >>> x = Variable(0) >>> line(x).is_line_or_ray() True >>> ray(x).is_line_or_ray() True >>> point(x,2).is_line_or_ray() False >>> closure_point(x,2).is_line_or_ray() False """ return self.thisptr.is_line_or_ray() def is_point(self): r""" Test whether ``self`` is a point. OUTPUT: Boolean. Examples: >>> from ppl import Variable, point, closure_point, ray, line >>> x = Variable(0) >>> line(x).is_point() False >>> ray(x).is_point() False >>> point(x,2).is_point() True >>> closure_point(x,2).is_point() False """ return self.thisptr.is_point() def is_closure_point(self): r""" Test whether ``self`` is a closure point. OUTPUT: Boolean. Examples: >>> from ppl import Variable, point, closure_point, ray, line >>> x = Variable(0) >>> line(x).is_closure_point() False >>> ray(x).is_closure_point() False >>> point(x,2).is_closure_point() False >>> closure_point(x,2).is_closure_point() True """ return self.thisptr.is_closure_point() def coefficient(self, Variable v): """ Return the coefficient of the variable ``v``. INPUT: - ``v`` -- a :class:`Variable`. OUTPUT: An integer. Examples: >>> from ppl import Variable, line >>> x = Variable(0) >>> line = line(3*x+1) >>> line line(1) >>> line.coefficient(x) mpz(1) """ return GMPy_MPZ_From_mpz(self.thisptr.coefficient(v.thisptr[0]).get_mpz_t()) def coefficients(self): """ Return the coefficients of the generator. See also :meth:`coefficient`. OUTPUT: A tuple of integers of length :meth:`space_dimension`. Examples: >>> from ppl import Variable, point >>> x = Variable(0); y = Variable(1) >>> p = point(3*x+5*y+1, 2); p point(3/2, 5/2) >>> p.coefficients() (mpz(3), mpz(5)) """ cdef int d = self.space_dimension() cdef int i coeffs = [] for i in range(0, d): coeffs.append(GMPy_MPZ_From_mpz(self.thisptr.coefficient(PPL_Variable(i)).get_mpz_t())) return tuple(coeffs) def divisor(self): """ If ``self`` is either a point or a closure point, return its divisor. OUTPUT: An integer. If ``self`` is a ray or a line, raises ``ValueError``. Examples: >>> from ppl import Generator, Variable >>> x = Variable(0) >>> y = Variable(1) >>> point = Generator.point(2*x-y+5) >>> point.divisor() mpz(1) >>> line = Generator.line(2*x-y+5) >>> line.divisor() Traceback (most recent call last): ... ValueError: PPL::Generator::divisor(): *this is neither a point nor a closure point. """ return GMPy_MPZ_From_mpz(self.thisptr.divisor().get_mpz_t()) def is_equivalent_to(self, Generator g): r""" Test whether ``self`` and ``g`` are equivalent. INPUT: - ``g`` -- a :class:`Generator`. OUTPUT: Boolean. Returns ``True`` if and only if ``self`` and ``g`` are equivalent generators. Note that generators having different space dimensions are not equivalent. Examples: >>> from ppl import Variable, point, line >>> x = Variable(0) >>> y = Variable(1) >>> point(2*x , 2).is_equivalent_to( point(x) ) True >>> point(2*x+0*y, 2).is_equivalent_to( point(x) ) False >>> line(4*x).is_equivalent_to(line(x)) True """ return self.thisptr.is_equivalent_to(g.thisptr[0]) def ascii_dump(self): r""" Write an ASCII dump to stderr. Examples: >>> cmd = 'from ppl import Linear_Expression, Variable, point\n' >>> cmd += 'x = Variable(0)\n' >>> cmd += 'y = Variable(1)\n' >>> cmd += 'p = point(3*x+2*y)\n' >>> cmd += 'p.ascii_dump()\n' >>> import subprocess >>> import sys >>> proc = subprocess.Popen([sys.executable, '-c', cmd], stderr=subprocess.PIPE) >>> out, err = proc.communicate() >>> print(str(err.decode('ascii'))) size 3 1 3 2 ... """ self.thisptr.ascii_dump() def __reduce__(self): """ Pickle object. Tests: >>> from ppl import Generator, Variable >>> from pickle import loads, dumps >>> x = Variable(0); y = Variable(1) >>> loads(dumps(Generator.point(2*x+7*y, 3))) point(2/3, 7/3) >>> loads(dumps(Generator.closure_point(2*x+7*y, 3))) closure_point(2/3, 7/3) >>> loads(dumps(Generator.line(2*x+7*y))) line(2, 7) >>> loads(dumps(Generator.ray(2*x+7*y))) ray(2, 7) """ le = Linear_Expression(self.coefficients(), 0) t = self.thisptr.type() if t == LINE: return (Generator.line, (le,)) elif t == RAY: return (Generator.ray, (le,)) elif t == POINT: return (Generator.point, (le, self.divisor())) elif t == CLOSURE_POINT: return (Generator.closure_point, (le, self.divisor())) else: raise RuntimeError def permute_space_dimensions(self, cycle): r""" Permute the coordinates according to ``cycle``. >>> from ppl import Generator, Variable >>> x = Variable(0); y = Variable(1); z = Variable(2) >>> p = Generator.point(2*x+7*y-z, 3) >>> p.permute_space_dimensions([0, 1]) >>> p point(7/3, 2/3, -1/3) >>> p.permute_space_dimensions([0, 2, 1]) >>> p point(2/3, -1/3, 7/3) """ cdef cppvector[PPL_Variable] cpp_cycle cdef int i for i in cycle: cpp_cycle.push_back(PPL_Variable(i)) self.thisptr.permute_space_dimensions(cpp_cycle) #################################################### ### Generator_System ############################## #################################################### #################################################### cdef class Generator_System(object): """ Wrapper for PPL's ``Generator_System`` class. An object of the class Generator_System is a system of generators, i.e., a multiset of objects of the class Generator (lines, rays, points and closure points). When inserting generators in a system, space dimensions are automatically adjusted so that all the generators in the system are defined on the same vector space. A system of generators which is meant to define a non-empty polyhedron must include at least one point: the reason is that lines, rays and closure points need a supporting point (lines and rays only specify directions while closure points only specify points in the topological closure of the NNC polyhedron). Examples: >>> from ppl import Generator_System, Variable, line, ray, point, closure_point >>> x = Variable(0) >>> y = Variable(1) >>> gs = Generator_System(line(5*x-2*y)) >>> gs.insert(ray(6*x-3*y)) >>> gs.insert(point(2*x-7*y, 5)) >>> gs.insert(closure_point(9*x-1*y, 2)) >>> gs Generator_System {line(5, -2), ray(2, -1), point(2/5, -7/5), closure_point(9/2, -1/2)} """ def __cinit__(self, arg=None): """ The Cython constructor. See :class:`Generator_System` for documentation. Tests: >>> from ppl import Generator_System >>> Generator_System() # indirect doctest Generator_System {} """ if arg is None: self.thisptr = new PPL_Generator_System() return if isinstance(arg, Generator): g = arg self.thisptr = new PPL_Generator_System(g.thisptr[0]) return if isinstance(arg, Generator_System): gs = arg self.thisptr = new PPL_Generator_System(gs.thisptr[0]) return if isinstance(arg, (list, tuple)): self.thisptr = new PPL_Generator_System() for generator in arg: self.insert(generator) return raise ValueError('Cannot initialize with '+str(arg)+'.') def __dealloc__(self): """ The Cython destructor. """ del self.thisptr def __hash__(self): r""" Tests: >>> import ppl >>> hash(ppl.Generator_System()) Traceback (most recent call last): ... TypeError: Generator_System unhashable """ raise TypeError('Generator_System unhashable') def space_dimension(self): r""" Return the dimension of the vector space enclosing ``self``. OUTPUT: Integer. Examples: >>> from ppl import Variable, Generator_System, point >>> x = Variable(0) >>> gs = Generator_System( point(3*x) ) >>> gs.space_dimension() 1 """ return self.thisptr.space_dimension() def set_space_dimension(self, size_t n): r""" Set the dimension of the vector space enclosing ``self`` Examples: >>> import ppl >>> gs = ppl.Generator_System() >>> gs.insert(ppl.point(ppl.Variable(0) + ppl.Variable(12))) >>> gs.insert(ppl.point(ppl.Variable(1) + 2*ppl.Variable(3))) >>> gs.space_dimension() 13 >>> gs.set_space_dimension(25) >>> gs.space_dimension() 25 >>> gs.set_space_dimension(3) >>> gs.space_dimension() 3 """ self.thisptr.set_space_dimension(n) def clear(self): r""" Removes all generators from the generator system and sets its space dimension to 0. Examples: >>> from ppl import Variable, Generator_System, point >>> x = Variable(0) >>> gs = Generator_System( point(3*x) ); gs Generator_System {point(3/1)} >>> gs.clear() >>> gs Generator_System {} """ self.thisptr.clear() def insert(self, Generator g): """ Insert ``g`` into the generator system. The number of space dimensions of ``self`` is increased, if needed. INPUT: - ``g`` -- a :class:`Generator`. Examples: >>> from ppl import Variable, Generator_System, point >>> x = Variable(0) >>> gs = Generator_System( point(3*x) ) >>> gs.insert( point(-3*x) ) >>> gs Generator_System {point(3/1), point(-3/1)} """ self.thisptr.insert(g.thisptr[0]) def empty(self): """ Return ``True`` if and only if ``self`` has no generators. OUTPUT: Boolean. Examples: >>> from ppl import Variable, Generator_System, point >>> x = Variable(0) >>> gs = Generator_System() >>> gs.empty() True >>> gs.insert( point(-3*x) ) >>> gs.empty() False """ return self.thisptr.empty() def ascii_dump(self): r""" Write an ASCII dump to stderr. Examples: >>> cmd = 'from ppl import Generator_System, point, Variable\n' >>> cmd += 'x = Variable(0)\n' >>> cmd += 'y = Variable(1)\n' >>> cmd += 'gs = Generator_System( point(3*x+2*y+1) )\n' >>> cmd += 'gs.ascii_dump()\n' >>> import subprocess, sys >>> proc = subprocess.Popen([sys.executable, '-c', cmd], stderr=subprocess.PIPE) >>> out, err = proc.communicate() >>> print(str(err.decode('ascii'))) topology NECESSARILY_CLOSED ... """ self.thisptr.ascii_dump() def __len__(self): """ Return the number of generators in the system. >>> from ppl import Variable, Generator_System, point >>> x = Variable(0) >>> y = Variable(1) >>> gs = Generator_System() >>> gs.insert(point(3*x+2*y)) >>> gs.insert(point(x)) >>> gs.insert(point(y)) >>> len(gs) 3 """ return sum([1 for g in self]) def __iter__(self): """ Iterate through the generators of the system. Examples: >>> from ppl import Generator_System, Variable, point, ray, line, closure_point >>> x = Variable(0) >>> gs = Generator_System(point(3*x)) >>> iter = gs.__iter__() >>> next(iter) point(3/1) >>> next(iter) Traceback (most recent call last): ... StopIteration >>> x = Variable(0) >>> y = Variable(1) >>> gs = Generator_System( line(5*x-2*y) ) >>> gs.insert( ray(6*x-3*y) ) >>> gs.insert( point(2*x-7*y, 5) ) >>> gs.insert( closure_point(9*x-1*y, 2) ) >>> next(gs.__iter__()) line(5, -2) >>> list(gs) [line(5, -2), ray(2, -1), point(2/5, -7/5), closure_point(9/2, -1/2)] """ cdef PPL_gs_iterator *gsi_ptr = new PPL_gs_iterator(self.thisptr[0].begin()) try: while gsi_ptr[0] != self.thisptr[0].end(): yield _wrap_Generator(deref(gsi_ptr[0].inc(1))) finally: del gsi_ptr def __getitem__(self, int k): """ Return the ``k``-th generator. The correct way to read the individual generators is to iterate over the generator system. This method is for convenience only. INPUT: - ``k`` -- integer. The index of the generator. OUTPUT: The ``k``-th constraint of the generator system. Examples: >>> from ppl import Generator_System, Variable, point >>> x = Variable(0) >>> gs = Generator_System() >>> gs.insert(point(3*x)) >>> gs.insert(point(-2*x)) >>> gs Generator_System {point(3/1), point(-2/1)} >>> gs[0] point(3/1) >>> gs[1] point(-2/1) """ if k < 0: raise IndexError('index must be nonnegative') iterator = iter(self) try: for i in range(k): next(iterator) except StopIteration: raise IndexError('index is past-the-end') return next(iterator) def __repr__(self): r""" Return a string representation of the generator system. OUTPUT: A string. Examples: >>> from ppl import Generator_System, Variable, point, ray >>> x = Variable(0) >>> y = Variable(1) >>> gs = Generator_System(point(3*x+2*y+1)) >>> gs.insert(ray(x)) >>> gs.__repr__() 'Generator_System {point(3/1, 2/1), ray(1, 0)}' """ s = 'Generator_System {' s += ', '.join([repr(g) for g in self]) s += '}' return s def __reduce__(self): """ Pickle object. Tests: >>> from ppl import Generator_System, Variable, point, ray >>> from pickle import loads, dumps >>> x = Variable(0) >>> y = Variable(1) >>> gs = Generator_System((point(3*x+2*y+1), ray(x))); gs Generator_System {point(3/1, 2/1), ray(1, 0)} >>> loads(dumps(gs)) Generator_System {point(3/1, 2/1), ray(1, 0)} """ return (Generator_System, (tuple(self), )) cdef PPL_GeneratorType_str(PPL_GeneratorType t): if t == LINE: return 'line' elif t == RAY: return 'ray' elif t == POINT: return 'point' elif t == CLOSURE_POINT: return 'closure_point' else: raise RuntimeError cdef _wrap_Generator(PPL_Generator generator): """ Wrap a C++ ``PPL_Generator`` into a Cython ``Generator``. """ cdef Generator g = Generator(True) g.thisptr = new PPL_Generator(generator) return g cdef _wrap_Generator_System(PPL_Generator_System generator_system): """ Wrap a C++ ``PPL_Generator_System`` into a Cython ``Generator_System``. """ cdef Generator_System gs = Generator_System() del gs.thisptr gs.thisptr = new PPL_Generator_System(generator_system) return gs cdef class Poly_Gen_Relation(object): r""" Wrapper for PPL's ``Poly_Con_Relation`` class. INPUT/OUTPUT: You must not construct :class:`Poly_Gen_Relation` objects manually. You will usually get them from :meth:`~sage.libs.ppl.Polyhedron.relation_with`. You can also get pre-defined relations from the class methods :meth:`nothing` and :meth:`subsumes`. Examples: >>> from ppl import Poly_Gen_Relation >>> nothing = Poly_Gen_Relation.nothing(); nothing nothing >>> subsumes = Poly_Gen_Relation.subsumes(); subsumes subsumes >>> nothing.implies( subsumes ) False >>> subsumes.implies( nothing ) True """ def __cinit__(self, do_not_construct_manually=False): """ The Cython constructor. See :class:`Poly_Gen_Relation` for documentation. Tests: >>> from ppl import Poly_Gen_Relation >>> Poly_Gen_Relation.nothing() nothing """ assert(do_not_construct_manually) self.thisptr = NULL def __dealloc__(self): """ The Cython destructor. """ assert self.thisptr!=NULL, 'Do not construct Poly_Gen_Relation objects manually!' del self.thisptr def __hash__(self): r""" Tests: >>> import ppl >>> hash(ppl.Poly_Gen_Relation.nothing()) Traceback (most recent call last): ... TypeError: Poly_Gen_Relation unhashable """ raise TypeError('Poly_Gen_Relation unhashable') def implies(self, Poly_Gen_Relation y): r""" Test whether ``self`` implies ``y``. INPUT: - ``y`` -- a :class:`Poly_Gen_Relation`. OUTPUT: Boolean. ``True`` if and only if ``self`` implies ``y``. Examples: >>> from ppl import Poly_Gen_Relation >>> nothing = Poly_Gen_Relation.nothing() >>> nothing.implies( nothing ) True """ return self.thisptr.implies(y.thisptr[0]) @classmethod def nothing(cls): r""" Return the assertion that says nothing. OUTPUT: A :class:`Poly_Gen_Relation`. Examples: >>> from ppl import Poly_Gen_Relation >>> Poly_Gen_Relation.nothing() nothing """ return _wrap_Poly_Gen_Relation(PPL_Poly_Gen_Relation_nothing()) @classmethod def subsumes(cls): r""" Return the assertion "Adding the generator would not change the polyhedron". OUTPUT: A :class:`Poly_Gen_Relation`. Examples: >>> from ppl import Poly_Gen_Relation >>> Poly_Gen_Relation.subsumes() subsumes """ return _wrap_Poly_Gen_Relation(PPL_Poly_Gen_Relation_subsumes()) def ascii_dump(self): r""" Write an ASCII dump to stderr. Examples: >>> cmd = 'from ppl import Poly_Gen_Relation\n' >>> cmd += 'Poly_Gen_Relation.nothing().ascii_dump()\n' >>> from subprocess import Popen, PIPE >>> import sys >>> proc = Popen([sys.executable, '-c', cmd], stderr=PIPE) >>> out, err = proc.communicate() >>> print(str(err.decode('ascii'))) NOTHING >>> proc.returncode 0 """ self.thisptr.ascii_dump() def __repr__(self): r""" Return a string representation. OUTPUT: String. Examples: >>> from ppl import Poly_Gen_Relation >>> Poly_Gen_Relation.nothing().__repr__() 'nothing' """ if self.implies(Poly_Gen_Relation.subsumes()): return 'subsumes' else: return 'nothing' cdef _wrap_Poly_Gen_Relation(PPL_Poly_Gen_Relation relation): """ Wrap a C++ ``PPL_Poly_Gen_Relation`` into a Cython ``Poly_Gen_Relation``. """ cdef Poly_Gen_Relation rel = Poly_Gen_Relation(True) rel.thisptr = new PPL_Poly_Gen_Relation(relation) return rel pplpy-0.8.9/ppl/linear_algebra.pxd000066400000000000000000000005241447517221400171430ustar00rootroot00000000000000from __future__ import absolute_import from .ppl_decl cimport * cdef class Variable(object): cdef PPL_Variable *thisptr cdef class Variables_Set(object): cdef PPL_Variables_Set *thisptr cdef class Linear_Expression(object): cdef PPL_Linear_Expression *thisptr cdef PPL_Coefficient PPL_Coefficient_from_pyobject(c) except * pplpy-0.8.9/ppl/linear_algebra.pyx000066400000000000000000001046461447517221400172020ustar00rootroot00000000000000# distutils: language = c++ # distutils: libraries = gmp gmpxx ppl m #***************************************************************************** # Copyright (C) 2010-2014 Volker Braun # 2011 Simon King # 2011-2017 Jeroen Demeyer # 2012 Risan # 2013 Julien Puydt # 2013 Travis Scrimshaw # 2015 André Apitzsch # 2016 Jori Mäntysalo # 2016 Matthias Koeppe # 2016-2017 Frédéric Chapoton # 2016-2020 Vincent Delecroix # 2017-2018 Vincent Klein # # Distributed under the terms of the GNU General Public License (GPL) # as published by the Free Software Foundation; either version 3 of # the License, or (at youroption) any later version. # http://www.gnu.org/licenses/ #***************************************************************************** cimport cython from gmpy2 cimport import_gmpy2, mpz, GMPy_MPZ_From_mpz, MPZ_Check from .constraint cimport _make_Constraint_from_richcmp # initialize gmpy2 C API import_gmpy2() #################################################### # PPL can use floating-point arithmetic to compute integers cdef extern from "ppl.hh" namespace "Parma_Polyhedra_Library": cdef void set_rounding_for_PPL() cdef void restore_pre_PPL_rounding() # but with PPL's rounding the gsl will be very unhappy; must turn off! restore_pre_PPL_rounding() cdef PPL_Coefficient PPL_Coefficient_from_pyobject(c) except *: cdef mpz coeff if MPZ_Check(c): coeff = c elif isinstance(c, (int, str)): coeff = mpz(c) else: coeff = mpz(c) if coeff != c or c != coeff: raise TypeError('ppl coefficients must be integral') return PPL_Coefficient(coeff.z) @cython.freelist(128) cdef class Variable(object): r""" Wrapper for PPL's ``Variable`` class. A dimension of the vector space. An object of the class Variable represents a dimension of the space, that is one of the Cartesian axes. Variables are used as basic blocks in order to build more complex linear expressions. Each variable is identified by a non-negative integer, representing the index of the corresponding Cartesian axis (the first axis has index 0). The space dimension of a variable is the dimension of the vector space made by all the Cartesian axes having an index less than or equal to that of the considered variable; thus, if a variable has index `i`, its space dimension is `i+1`. INPUT: - ``i`` -- integer. The index of the axis. OUTPUT: A :class:`Variable` Examples: >>> from ppl import Variable >>> x = Variable(123) >>> x.id() 123 >>> x x123 Note that the "meaning" of an object of the class Variable is completely specified by the integer index provided to its constructor: be careful not to be mislead by C++ language variable names. For instance, in the following example the linear expressions ``e1`` and ``e2`` are equivalent, since the two variables ``x`` and ``z`` denote the same Cartesian axis: >>> x = Variable(0) >>> y = Variable(1) >>> z = Variable(0) >>> e1 = x + y; e1 x0+x1 >>> e2 = y + z; e2 x0+x1 >>> e1 - e2 0 """ def __cinit__(self, PPL_dimension_type i): """ The Cython constructor. See :class:`Variable` for documentation. Tests: >>> from ppl import Variable >>> Variable(123) # indirect doctest x123 """ self.thisptr = new PPL_Variable(i) def __dealloc__(self): """ The Cython destructor. """ del self.thisptr def __hash__(self): r""" Tests: >>> import ppl >>> hash(ppl.Variable(12)) Traceback (most recent call last): ... TypeError: Variable unhashable """ raise TypeError('Variable unhashable') def id(self): """ Return the index of the Cartesian axis associated to the variable. Examples: >>> from ppl import Variable >>> x = Variable(123) >>> x.id() 123 """ return self.thisptr.id() def space_dimension(self): r""" Return the dimension of the vector space enclosing ``self``. OUTPUT: Integer. The returned value is ``self.id()+1``. Examples: >>> from ppl import Variable >>> x = Variable(0) >>> x.space_dimension() 1 """ return self.thisptr.space_dimension() def __repr__(self): """ Return a string representation. OUTPUT: String. Examples: >>> from ppl import Variable >>> x = Variable(0) >>> x.__repr__() 'x0' """ return 'x{0}'.format(self.id()) def __add__(self, other): r""" Return the sum ``self`` + ``other``. INPUT: - ``self``, ``other`` -- anything convertible to ``Linear_Expression``: An integer, a :class:`Variable`, or a :class:`Linear_Expression`. OUTPUT: A :class:`Linear_Expression` representing ``self`` + ``other``. Examples: >>> from ppl import Variable >>> x = Variable(0); y = Variable(1) >>> x + 15 x0+15 >>> 15 + y x1+15 >>> from gmpy2 import mpz >>> x + mpz(3) x0+3 >>> mpz(-5) + y x1-5 >>> x + 1.5 Traceback (most recent call last): ... TypeError: ppl coefficients must be integral >>> 1.5 + x Traceback (most recent call last): ... TypeError: ppl coefficients must be integral """ return Linear_Expression(self) + Linear_Expression(other) def __radd__(self, other): return Linear_Expression(self) + Linear_Expression(other) def __sub__(self, other): r""" Return the difference ``self`` - ``other``. INPUT: - ``self``, ``other`` -- anything convertible to ``Linear_Expression``: An integer, a :class:`Variable`, or a :class:`Linear_Expression`. OUTPUT: A :class:`Linear_Expression` representing ``self`` - ``other``. Examples: >>> from ppl import Variable >>> x = Variable(0); y = Variable(1) >>> x - 15 x0-15 >>> 15 - y -x1+15 """ return Linear_Expression(self) - Linear_Expression(other) def __rsub__(self, other): return Linear_Expression(other) - Linear_Expression(self) def __mul__(self, other): r""" Return the product ``self`` * ``other``. INPUT: - ``self``, ``other`` -- One must be an integer, the other a :class:`Variable`. OUTPUT: A :class:`Linear_Expression` representing ``self`` * ``other``. Examples: >>> from ppl import Variable >>> x = Variable(0); y = Variable(1) >>> x * 15 15*x0 >>> 15 * y 15*x1 >>> 1.5 * x Traceback (most recent call last): ... TypeError: ppl coefficients must be integral >>> x * 1.5 Traceback (most recent call last): ... TypeError: ppl coefficients must be integral """ if isinstance(self, Variable): return Linear_Expression(self) * other else: # NOTE: this code path will only be executed when compiled with cython < 3.0.0 return Linear_Expression(other) * self def __rmul__(self, other): return Linear_Expression(self) * other def __pos__(self): r""" Return ``self`` as :class:`Linear_Expression` OUTPUT: The :class:`Linear_Expression` ``+self`` Examples: >>> from ppl import Variable >>> x = Variable(0); x x0 >>> +x x0 """ return Linear_Expression(self) def __neg__(self): r""" Return -``self`` as :class:`Linear_Expression` OUTPUT: The :class:`Linear_Expression` ``-self`` Examples: >>> from ppl import Variable >>> x = Variable(0); x x0 >>> -x -x0 """ return Linear_Expression(self)*(-1) def __richcmp__(self, other, op): """ Construct :class:`Constraint` from equalities or inequalities. INPUT: - ``self``, ``other`` -- anything convertible to a :class:`Linear_Expression` - ``op`` -- the operation. Examples: >>> from ppl import Variable >>> x = Variable(0) >>> y = Variable(1) >>> x < y -x0+x1>0 >>> x <= 0 -x0>=0 >>> x == y-y x0==0 >>> x >= -2 x0+2>=0 >>> x > 0 x0>0 >>> 0 == 1 # watch out! False >>> 0*x == 1 -1==0 """ return _make_Constraint_from_richcmp(self, other, op) #################################################### ### Variables_Set ################################## #################################################### cdef class Variables_Set(object): r""" Wrapper for PPL's ``Variables_Set`` class. A set of variables' indexes. Examples: Build the empty set of variable indexes: >>> from ppl import Variable, Variables_Set >>> Variables_Set() Variables_Set of cardinality 0 Build the singleton set of indexes containing the index of the variable: >>> v123 = Variable(123) >>> Variables_Set(v123) Variables_Set of cardinality 1 Build the set of variables' indexes in the range from one variable to another variable: >>> v127 = Variable(127) >>> Variables_Set(v123,v127) Variables_Set of cardinality 5 You can alternatively use integers: >>> Variables_Set(23) Variables_Set of cardinality 1 >>> Variables_Set(10, 14) Variables_Set of cardinality 5 """ def __cinit__(self, *args): """ The Cython constructor. See :class:`Variables_Set` for documentation. Tests: >>> from ppl import Variable, Variables_Set >>> Variables_Set() Variables_Set of cardinality 0 """ cdef Variable arg0, arg1 if len(args) == 0: self.thisptr = new PPL_Variables_Set() elif len(args) == 1: if type(args[0]) is Variable: arg0 = args[0] else: arg0 = Variable(args[0]) self.thisptr = new PPL_Variables_Set(arg0.thisptr[0]) elif len(args) == 2: if type(args[0]) is Variable: arg0 = args[0] else: arg0 = Variable(args[0]) if type(args[1]) is Variable: arg1 = args[1] else: arg1 = Variable(args[1]) self.thisptr = new PPL_Variables_Set(arg0.thisptr[0], arg1.thisptr[0]) def __hash__(self): r""" Tests: >>> import ppl >>> hash(ppl.Variables_Set()) Traceback (most recent call last): ... TypeError: Variables_Set unhashable """ raise TypeError('Variables_Set unhashable') def __dealloc__(self): """ The Cython destructor """ del self.thisptr def space_dimension(self): r""" Returns the dimension of the smallest vector space enclosing all the variables whose indexes are in the set. OUTPUT: Integer. EXAMPLES:: >>> from ppl import Variable, Variables_Set >>> v123 = Variable(123) >>> S = Variables_Set(v123) >>> S.space_dimension() 124 """ return self.thisptr.space_dimension() def insert(self, Variable v): r""" Inserts the index of variable `v` into the set. EXAMPLES:: >>> from ppl import Variable, Variables_Set >>> S = Variables_Set() >>> v123 = Variable(123) >>> S.insert(v123) >>> S.space_dimension() 124 """ self.thisptr.insert(v.thisptr[0]) def ascii_dump(self): r""" Write an ASCII dump to stderr. TODO: rewrite examples EXAMPLES:: >>> cmd = 'from ppl import Variable, Variables_Set\n' >>> cmd += 'v123 = Variable(123)\n' >>> cmd += 'S = Variables_Set(v123)\n' >>> cmd += 'S.ascii_dump()\n' >>> import subprocess >>> import sys >>> proc = subprocess.Popen([sys.executable, '-c', cmd], stderr=subprocess.PIPE) >>> out, err = proc.communicate() >>> print(str(err.decode('ascii'))) variables( 1 ) 123 """ self.thisptr.ascii_dump() def __repr__(self): """ Return a string representation. OUTPUT: String. EXAMPLES:: >>> from ppl import Variable, Variables_Set >>> S = Variables_Set() >>> S.__repr__() 'Variables_Set of cardinality 0' """ return 'Variables_Set of cardinality {}'.format(self.thisptr.size()) #################################################### ### Linear_Expression ############################## #################################################### cdef class Linear_Expression(object): r""" Wrapper for PPL's ``PPL_Linear_Expression`` class. INPUT: The constructor accepts zero, one, or two arguments. If there are two arguments ``Linear_Expression(a,b)``, they are interpreted as - ``a`` -- either a dictionary whose indices are space dimension and values are coefficients or an iterable coefficients (e.g. a list or tuple). - ``b`` -- an integer. The inhomogeneous term. A single argument ``Linear_Expression(arg)`` is interpreted as - ``arg`` -- something that determines a linear expression. Possibilities are: * a :class:`Variable`: The linear expression given by that variable. * a :class:`Linear_Expression`: The copy constructor. * an integer: Constructs the constant linear expression. No argument is the default constructor and returns the zero linear expression. OUTPUT: A :class:`Linear_Expression` Examples: >>> from ppl import Variable, Linear_Expression >>> Linear_Expression({1: -3, 7: 1}, 0) -3*x1+x7 >>> Linear_Expression([1, 2, 3, 4], 5) x0+2*x1+3*x2+4*x3+5 >>> Linear_Expression(10) 10 >>> Linear_Expression() 0 >>> Linear_Expression({}, 2) 2 >>> Linear_Expression([], 2) 2 >>> Linear_Expression(10).inhomogeneous_term() mpz(10) >>> x = Variable(123) >>> expr = x+1 >>> expr x123+1 >>> expr.coefficient(x) mpz(1) >>> expr.coefficient(Variable(124)) mpz(0) >>> from gmpy2 import mpz, mpq >>> Linear_Expression(mpz(3)) 3 >>> Linear_Expression([mpz(5), mpz(2)], mpz(-2)) 5*x0+2*x1-2 String, rationals and floating point types are accepted as long as they represent exact integers: >>> Linear_Expression(('4', 1), 2) 4*x0+x1+2 >>> Linear_Expression((4, 1.0, mpq('4/2')), 2.0) 4*x0+x1+2*x2+2 >>> Linear_Expression(('1.5',), 0) Traceback (most recent call last): ... ValueError: invalid digits >>> Linear_Expression((mpq('3/2'),), 0) Traceback (most recent call last): ... TypeError: ppl coefficients must be integral >>> Linear_Expression((1, 2.1, 1), 1) Traceback (most recent call last): ... TypeError: ppl coefficients must be integral >>> Linear_Expression(mpq('1/2')) Traceback (most recent call last): ... TypeError: ppl coefficients must be integral >>> Linear_Expression('I am a linear expression') Traceback (most recent call last): ... ValueError: invalid digits >>> Linear_Expression(('I','am','a','linear','expression')) Traceback (most recent call last): ... TypeError: mpz() requires numeric or string argument """ def __init__(self, *args): """ The Cython constructor. See :class:`Linear_Expression` for documentation. Tests: >>> from ppl import Linear_Expression >>> Linear_Expression(10) # indirect doctest 10 """ cdef size_t i if len(args) == 2: a = args[0] b = args[1] self.thisptr = new PPL_Linear_Expression() if isinstance(a, dict): if a: self.thisptr.set_space_dimension(1 + max(a)) for i, coeff in a.items(): self.thisptr.set_coefficient(PPL_Variable(i), PPL_Coefficient_from_pyobject(coeff)) else: self.thisptr.set_space_dimension(len(a)) for i, coeff in enumerate(a): self.thisptr.set_coefficient(PPL_Variable(i), PPL_Coefficient_from_pyobject(coeff)) self.thisptr.set_inhomogeneous_term(PPL_Coefficient_from_pyobject(b)) return elif len(args) == 1: arg = args[0] if isinstance(arg, Variable): v = arg self.thisptr = new PPL_Linear_Expression(v.thisptr[0]) return if isinstance(arg, Linear_Expression): e = arg self.thisptr = new PPL_Linear_Expression(e.thisptr[0]) return self.thisptr = new PPL_Linear_Expression(PPL_Coefficient_from_pyobject(arg)) elif len(args) == 0: self.thisptr = new PPL_Linear_Expression() return else: raise ValueError("Cannot initialize with more than 2 arguments.") def __dealloc__(self): """ The Cython destructor. """ del self.thisptr def __hash__(self): r""" Tests: >>> import ppl >>> hash(ppl.Linear_Expression(10)) Traceback (most recent call last): ... TypeError: Linear_Expression unhashable """ raise TypeError('Linear_Expression unhashable') def space_dimension(self): """ Return the dimension of the vector space necessary for the linear expression. OUTPUT: Integer. Examples: >>> from ppl import Variable >>> x = Variable(0) >>> y = Variable(1) >>> (x+y+1).space_dimension() 2 >>> (x+y).space_dimension() 2 >>> (y+1).space_dimension() 2 >>> (x+1).space_dimension() 1 >>> (y+1-y).space_dimension() 2 """ return self.thisptr.space_dimension() def set_space_dimension(self, PPL_dimension_type n): r""" Set the dimension of the ambient space to ``n`` Examples: >>> import ppl >>> L = ppl.Variable(0) + ppl.Variable(3) >>> L.space_dimension() 4 >>> L.set_space_dimension(6) >>> L.space_dimension() 6 >>> L = ppl.Variable(5) - ppl.Variable(2) >>> L.set_space_dimension(3) >>> L -x2 """ self.thisptr.set_space_dimension(n) def swap_space_dimensions(self, v1, v2): r""" Swaps the coefficients of ``v1`` and ``v2``. INPUT: - ``v1``, ``v2`` - variables or indices of variables Examples: >>> import ppl >>> L = ppl.Variable(1) - 3 * ppl.Variable(3) >>> L.swap_space_dimensions(ppl.Variable(1), ppl.Variable(3)) >>> L -3*x1+x3 >>> L = ppl.Variable(1) - 3 * ppl.Variable(3) >>> L.swap_space_dimensions(1, 3) >>> L -3*x1+x3 """ cdef Variable vv1, vv2 if type(v1) is Variable: vv1 = v1 else: vv1 = Variable(v1) if type(v2) is Variable: vv2 = v2 else: vv2 = Variable(v2) self.thisptr.swap_space_dimensions(vv1.thisptr[0], vv2.thisptr[0]) def shift_space_dimensions(self, v, PPL_dimension_type n): r""" Shift by ``n`` the coefficients of variables starting from the coefficient of ``v``. This increases the space dimension by ``n``. Examples: >>> import ppl >>> L = ppl.Variable(0) + 13 * ppl.Variable(2) + 5 * ppl.Variable(7) >>> L x0+13*x2+5*x7 >>> L.shift_space_dimensions(ppl.Variable(2), 2) >>> L x0+13*x4+5*x9 >>> L.shift_space_dimensions(ppl.Variable(7), 3) >>> L x0+13*x4+5*x12 """ cdef Variable vv if type(v) is Variable: vv = v else: vv = Variable(v) self.thisptr.shift_space_dimensions(vv.thisptr[0], n) def remove_space_dimensions(self, Variables_Set V): r""" Removes the dimension specified by the set of variables ``V``. See :class:`Variables_Set` to construct set of variables. Examples: >>> import ppl >>> L = sum(i * ppl.Variable(i) for i in range(10)) >>> L x1+2*x2+3*x3+4*x4+5*x5+6*x6+7*x7+8*x8+9*x9 >>> L.remove_space_dimensions(ppl.Variables_Set(3,5)) >>> L x1+2*x2+6*x3+7*x4+8*x5+9*x6 """ self.thisptr.remove_space_dimensions(V.thisptr[0]) def coefficient(self, v): """ Return the coefficient of the variable ``v``. INPUT: - ``v`` -- a :class:`Variable`. OUTPUT: A gmpy2 integer. Examples: >>> from ppl import Variable >>> x = Variable(0) >>> e = 3*x+1 >>> e.coefficient(x) mpz(3) >>> e.coefficient(Variable(13)) mpz(0) """ cdef Variable vv if type(v) is Variable: vv = v else: vv = Variable(v) return GMPy_MPZ_From_mpz(self.thisptr.coefficient(vv.thisptr[0]).get_mpz_t()) def coefficients(self): """ Return the coefficients of the linear expression. OUTPUT: A tuple of gmpy2 integers of length :meth:`space_dimension`. Examples: >>> from ppl import Variable >>> x = Variable(0); y = Variable(1) >>> e = 3*x+5*y+1 >>> e.coefficients() (mpz(3), mpz(5)) """ cdef int d = self.space_dimension() cdef int i cdef list coeffs = [None]*d for i in range(d): coeffs[i] = GMPy_MPZ_From_mpz(self.thisptr.coefficient(PPL_Variable(i)).get_mpz_t()) return tuple(coeffs) def set_coefficient(self, i, v): """ Set the ``i``-th coefficient to ``v``. INPUT: - ``i`` - variable or variable index - ``v`` - integer Examples: >>> from ppl import Variable >>> L = Variable(0) + 3 * Variable(1) >>> L.set_coefficient(1, -5) >>> L.set_coefficient(7, 3) >>> L x0-5*x1 """ cdef Variable ii if type(i) is Variable: ii = i else: ii = Variable(i) cdef PPL_Coefficient vv = PPL_Coefficient_from_pyobject(v) self.thisptr.set_coefficient(ii.thisptr[0], vv) def inhomogeneous_term(self): """ Return the inhomogeneous term of the linear expression. OUTPUT: Integer. Examples: >>> from ppl import Linear_Expression >>> Linear_Expression(10).inhomogeneous_term() mpz(10) """ return GMPy_MPZ_From_mpz(self.thisptr.inhomogeneous_term().get_mpz_t()) def set_inhomogeneous_term(self, v): """ Set the inhomogeneous term of this linear expression. Examples: >>> from ppl import Linear_Expression >>> L = Linear_Expression() >>> L.set_inhomogeneous_term(-1313958534578713747) >>> L.inhomogeneous_term() mpz(-1313958534578713747) """ cdef PPL_Coefficient vv = PPL_Coefficient_from_pyobject(v) self.thisptr.set_inhomogeneous_term(vv) def is_zero(self): """ Test if ``self`` is the zero linear expression. OUTPUT: Boolean. Examples: >>> from ppl import Variable, Linear_Expression >>> Linear_Expression(0).is_zero() True >>> Linear_Expression(10).is_zero() False """ return self.thisptr.is_zero() def all_homogeneous_terms_are_zero(self): """ Test if ``self`` is a constant linear expression. OUTPUT: Boolean. Examples: >>> from ppl import Variable, Linear_Expression >>> Linear_Expression(10).all_homogeneous_terms_are_zero() True """ return self.thisptr.all_homogeneous_terms_are_zero() def is_equal_to(self, Linear_Expression other): """ Test equality with another linear expression. OUTPUT: boolean Examples: >>> from ppl import Variable >>> L1 = Variable(0) + 2 * Variable(3) >>> L2 = Variable(0) + 2 * Variable(3) >>> L3 = Variable(0) - Variable(2) >>> L1.is_equal_to(L2) True >>> L1.is_equal_to(L3) False """ return self.thisptr.is_equal_to(other.thisptr[0]) def ascii_dump(self): r""" Write an ASCII dump to stderr. Examples: >>> cmd = 'from ppl import Linear_Expression, Variable\n' >>> cmd += 'x = Variable(0)\n' >>> cmd += 'y = Variable(1)\n' >>> cmd += 'e = 3*x+2*y+1\n' >>> cmd += 'e.ascii_dump()\n' >>> from subprocess import Popen, PIPE >>> import sys >>> proc = Popen([sys.executable, '-c', cmd], stdout=PIPE, stderr=PIPE) >>> out, err = proc.communicate() >>> len(out) == 0 True >>> len(err) > 0 True """ self.thisptr.ascii_dump() def __repr__(self): r""" Return a string representation of the linear expression. OUTPUT: A string. Examples: >>> from ppl import Linear_Expression, Variable >>> x = Variable(0) >>> y = Variable(1) >>> x+1 x0+1 >>> x+1-x 1 >>> 2*x 2*x0 >>> x-x-1 -1 >>> x-x 0 """ s = '' first = True for i in range(self.space_dimension()): x = Variable(i) coeff = self.coefficient(x) if coeff == 0: continue if first and coeff == 1: s += '%r' % x first = False elif first and coeff == -1: s += '-%r' % x first = False elif first and coeff != 1: s += '%d*%r' % (coeff, x) first = False elif coeff == 1: s += '+%r' % x elif coeff == -1: s += '-%r' % x else: s += '%+d*%r' % (coeff, x) inhomog = self.inhomogeneous_term() if inhomog != 0: if first: s += '%d' % inhomog first = False else: s += '%+d' % inhomog if first: s = '0' return s def __add__(self, other): r""" Add ``self`` and ``other``. INPUT: - ``self``, ``other`` -- anything that can be used to construct a :class:`Linear_Expression`. One of them, not necessarily ``self``, is guaranteed to be a :class:``Linear_Expression``, otherwise Python would not have called this method. OUTPUT: The sum as a :class:`Linear_Expression` Examples: >>> from ppl import Linear_Expression, Variable >>> x = Variable(0) >>> y = Variable(1) >>> 9 + x + y + (1 + x) + y + y 2*x0+3*x1+10 >>> from gmpy2 import mpz >>> mpz(3) + x + mpz(5) + y + mpz(7) x0+x1+15 >>> from gmpy2 import mpz >>> x + mpz(5) x0+5 """ cdef Linear_Expression lhs, rhs if isinstance(self, Linear_Expression): lhs = self else: # NOTE: this code path will only be executed when compiled with cython < 3.0.0 lhs = Linear_Expression(self) if isinstance(other, Linear_Expression): rhs = other else: rhs = Linear_Expression(other) cdef Linear_Expression result = Linear_Expression() result.thisptr[0] = lhs.thisptr[0] + rhs.thisptr[0] return result def __radd__(self, other): r""" Add ``self`` and ``other``. """ cdef Linear_Expression lhs, rhs lhs = self if isinstance(other, Linear_Expression): rhs = other else: rhs = Linear_Expression(other) cdef Linear_Expression result = Linear_Expression() result.thisptr[0] = lhs.thisptr[0] + rhs.thisptr[0] return result def __sub__(self, other): r""" Subtract ``other`` from ``self``. INPUT: - ``self``, ``other`` -- anything that can be used to construct a :class:`Linear_Expression`. One of them, not necessarily ``self``, is guaranteed to be a :class:``Linear_Expression``, otherwise Python would not have called this method. OUTPUT: The difference as a :class:`Linear_Expression` Examples: >>> from ppl import Linear_Expression, Variable >>> x = Variable(0) >>> y = Variable(1) >>> 9-x-y-(1-x)-y-y -3*x1+8 >>> from gmpy2 import mpz >>> mpz(5)-x-(mpz(3)-y)-x-mpz(7) -2*x0+x1-5 """ cdef Linear_Expression lhs, rhs if isinstance(self, Linear_Expression): lhs = self else: lhs = Linear_Expression(self) if isinstance(other, Linear_Expression): rhs = other else: rhs = Linear_Expression(other) cdef Linear_Expression result = Linear_Expression() result.thisptr[0] = lhs.thisptr[0] - rhs.thisptr[0] return result def __mul__(self, other): r""" Multiply ``self`` with ``other``. INPUT: - ``self``, ``other`` -- anything that can be used to construct a :class:`Linear_Expression`. One of them, not necessarily ``self``, is guaranteed to be a :class:``Linear_Expression``, otherwise Python would not have called this method. OUTPUT: The product as a :class:`Linear_Expression` Examples: >>> from ppl import Variable >>> x = Variable(0) >>> y = Variable(1) >>> 8 * (x + 1) 8*x0+8 >>> y * 8 8*x1 >>> 2**128 * x 340282366920938463463374607431768211456*x0 >>> from gmpy2 import mpz >>> mpz(3) * x * mpz(5) 15*x0 """ cdef Linear_Expression e cdef c if isinstance(self, Linear_Expression): e = self c = other else: # NOTE: this code path will only be executed when compiled with cython < 3.0.0 e = other c = self cdef PPL_Coefficient cc = PPL_Coefficient_from_pyobject(c) cdef Linear_Expression result = Linear_Expression() result.thisptr[0] = e.thisptr[0] * cc return result def __rmul__(self, other): r""" Multiply ``self`` with ``other`` """ cdef Linear_Expression e cdef c e = self c = other cdef PPL_Coefficient cc = PPL_Coefficient_from_pyobject(c) cdef Linear_Expression result = Linear_Expression() result.thisptr[0] = e.thisptr[0] * cc return result def __pos__(self): """ Return ``self``. Examples: >>> from ppl import Variable, Linear_Expression >>> +Linear_Expression(1) 1 >>> x = Variable(0) >>> +(x+1) x0+1 """ return self def __neg__(self): """ Return the negative of ``self``. Examples: >>> from ppl import Variable, Linear_Expression >>> -Linear_Expression(1) -1 >>> x = Variable(0) >>> -(x+1) -x0-1 """ return self*(-1) def __richcmp__(self, other, int op): """ Construct :class:`Constraint`s Examples: >>> from ppl import Variable >>> x = Variable(0) >>> y = Variable(1) >>> x+1 < y-2 -x0+x1-3>0 >>> x+1 <= y-2 -x0+x1-3>=0 >>> x+1 == y-2 x0-x1+3==0 >>> x+1 >= y-2 x0-x1+3>=0 >>> x+1 > y-2 x0-x1+3>0 """ return _make_Constraint_from_richcmp(self, other, op) def __reduce__(self): """ Pickle object Examples: >>> from ppl import Linear_Expression >>> from pickle import loads, dumps >>> le = loads(dumps(Linear_Expression([1,2,3],4))) >>> le.coefficients() == (1,2,3) True >>> le.inhomogeneous_term() == 4 True """ return (Linear_Expression, (self.coefficients(), self.inhomogeneous_term())) def permute_space_dimensions(self, cycle): r""" Permute the coordinates according to ``cycle``. Examples: >>> from ppl import Variable >>> x = Variable(0); y = Variable(1); z = Variable(2) >>> l = 2*x - y + 3*z >>> l.permute_space_dimensions([0, 2]) >>> l 3*x0-x1+2*x2 >>> l.permute_space_dimensions([1, 0, 2]) >>> l -x0+2*x1+3*x2 """ cdef cppvector[PPL_Variable] cpp_cycle cdef PPL_dimension_type i for i in cycle: cpp_cycle.push_back(PPL_Variable(i)) self.thisptr.permute_space_dimensions(cpp_cycle) pplpy-0.8.9/ppl/mip_problem.pxd000066400000000000000000000002271447517221400165210ustar00rootroot00000000000000from .linear_algebra cimport * from .generator cimport * from .constraint cimport * cdef class MIP_Problem(object): cdef PPL_MIP_Problem *thisptr pplpy-0.8.9/ppl/mip_problem.pyx000066400000000000000000000476471447517221400165670ustar00rootroot00000000000000# distutils: language = c++ # distutils: libraries = gmp gmpxx ppl m #***************************************************************************** # Copyright (C) 2010-2014 Volker Braun # 2011 Simon King # 2011-2017 Jeroen Demeyer # 2012 Risan # 2013 Julien Puydt # 2013 Travis Scrimshaw # 2015 André Apitzsch # 2016 Jori Mäntysalo # 2016 Matthias Koeppe # 2016-2017 Frédéric Chapoton # 2016-2018 Vincent Delecroix # 2017-2018 Vincent Klein # # Distributed under the terms of the GNU General Public License (GPL) # as published by the Free Software Foundation; either version 3 of # the License, or (at youroption) any later version. # http://www.gnu.org/licenses/ #***************************************************************************** from cysignals.signals cimport sig_on, sig_off from gmpy2 cimport import_gmpy2, GMPy_MPQ_From_mpz from cython.operator cimport dereference as deref # PPL can use floating-point arithmetic to compute integers cdef extern from "ppl.hh" namespace "Parma_Polyhedra_Library": cdef void set_rounding_for_PPL() cdef void restore_pre_PPL_rounding() # initialize gmpy2 C API import_gmpy2() # but with PPL's rounding the gsl will be very unhappy; must turn off! restore_pre_PPL_rounding() cdef class MIP_Problem(object): r""" wrapper for PPL's MIP_Problem class An object of the class MIP_Problem represents a Mixed Integer (Linear) Program problem. INPUT: - ``dim`` -- integer - ``args`` -- an array of the defining data of the MIP_Problem. For each element, any one of the following is accepted: * A :class:`Constraint_System`. * A :class:`Linear_Expression`. OUTPUT: A :class:`MIP_Problem`. Examples: >>> from ppl import Variable, Constraint_System, MIP_Problem >>> x = Variable(0) >>> y = Variable(1) >>> cs = Constraint_System() >>> cs.insert(x >= 0) >>> cs.insert(y >= 0) >>> cs.insert(3 * x + 5 * y <= 10) >>> m = MIP_Problem(2, cs, x + y) >>> m MIP Problem (maximization, 2 variables, 3 constraints) >>> m.optimal_value() mpq(10,3) >>> float(_) 3.333333333333333 >>> m.optimizing_point() point(10/3, 0/3) """ def __repr__(self): """ String representation of MIP Problem. Examples: >>> from ppl import Variable, Constraint_System, MIP_Problem >>> x = Variable(0) >>> y = Variable(1) >>> cs = Constraint_System() >>> cs.insert( x >= 0 ) >>> cs.insert( y >= 0 ) >>> cs.insert( 3 * x + 5 * y <= 10 ) >>> m = MIP_Problem(2, cs, x + y) >>> m MIP Problem (maximization, 2 variables, 3 constraints) """ dim = self.space_dimension() ncs = sum(1 for _ in self) return 'MIP Problem ({}, {} variable{}, {} constraint{})'.format( self.optimization_mode(), dim, 's' if dim > 1 else '', ncs, 's' if ncs > 1 else '') def __cinit__(self, PPL_dimension_type dim = 0, *args): """ The Cython constructor. Tests: >>> from ppl import Variable, Constraint_System, MIP_Problem >>> MIP_Problem(0) A MIP_Problem Maximize: 0 Subject to constraints >>> x = Variable(0) >>> y = Variable(1) >>> cs = Constraint_System() >>> cs.insert(x + y <= 2) >>> M = MIP_Problem(2, cs, 0) >>> M = MIP_Problem(2, cs, x) >>> M = MIP_Problem(2, None, None) Traceback (most recent call last): ... TypeError: Cannot convert NoneType to ppl.Constraint_System >>> M = MIP_Problem(2, cs, 'hey') Traceback (most recent call last): ... TypeError: unable to convert 'hey' to an integer >>> M = MIP_Problem(2, cs, x, 'middle') Traceback (most recent call last): ... ValueError: unknown mode 'middle' """ if not args: self.thisptr = new PPL_MIP_Problem(dim) return elif len(args) == 1: raise ValueError('cannot initialize from {}'.format(args)) cdef Constraint_System cs = args[0] cdef Linear_Expression obj try: obj = args[1] except TypeError: obj = Linear_Expression(args[1]) cdef PPL_Optimization_Mode mode = MAXIMIZATION if len(args) == 3: if args[2] == 'maximization': mode = MAXIMIZATION elif args[2] == 'minimization': mode = MINIMIZATION else: raise ValueError('unknown mode {!r}'.format(args[2])) self.thisptr = new PPL_MIP_Problem(dim, cs.thisptr[0], obj.thisptr[0], mode) def __dealloc__(self): """ The Cython destructor """ del self.thisptr def __iter__(self): r""" Iterator through the constraints Tests: >>> from ppl import Variable, MIP_Problem >>> x = Variable(0) >>> y = Variable(1) >>> M = MIP_Problem(2) >>> for c in M: print(c) >>> M.add_constraint(x + y <= 5) >>> for c in M: print(c) -x0-x1+5>=0 >>> M.add_constraint(3*x - 18*y >= -2) >>> for c in M: print(c) -x0-x1+5>=0 3*x0-18*x1+2>=0 >>> M = MIP_Problem(1) >>> M.add_constraint(x <= 5) >>> it = M.__iter__() >>> next(it) -x0+5>=0 >>> next(it) Traceback (most recent call last): ... StopIteration """ cdef PPL_mip_iterator *mip_csi_ptr = new PPL_mip_iterator(self.thisptr[0].constraints_begin()) try: while mip_csi_ptr[0] != self.thisptr[0].constraints_end(): yield _wrap_Constraint(deref(mip_csi_ptr[0].inc(1))) finally: del mip_csi_ptr def constraints(self): r""" Return the constraints of this MIP The output is an instance of :class:`Constraint_System`. Examples: >>> from ppl import Variable, MIP_Problem >>> x = Variable(0) >>> y = Variable(1) >>> M = MIP_Problem(2) >>> M.add_constraint(x + y <= 5) >>> M.add_constraint(3*x - 18*y >= -2) >>> M.constraints() Constraint_System {-x0-x1+5>=0, 3*x0-18*x1+2>=0} Note that modifying the output of this method will not modify the underlying MIP problem object: >>> cs = M.constraints() >>> cs.insert(x <= 3) >>> cs Constraint_System {-x0-x1+5>=0, 3*x0-18*x1+2>=0, -x0+3>=0} >>> M.constraints() Constraint_System {-x0-x1+5>=0, 3*x0-18*x1+2>=0} """ cdef Constraint_System c = Constraint_System(None) cdef PPL_Constraint_System* cs = new PPL_Constraint_System() cdef PPL_mip_iterator* mip_it = new PPL_mip_iterator(self.thisptr[0].constraints_begin()) while mip_it[0] != self.thisptr[0].constraints_end(): cs[0].insert(deref(mip_it[0])) mip_it[0].inc(1) c.thisptr = cs del mip_it return c def optimization_mode(self): """ Return the optimization mode used in the MIP_Problem. It will return "maximization" if the MIP_Problem was set to MAXIMIZATION mode, and "minimization" otherwise. Examples: >>> from ppl import MIP_Problem >>> m = MIP_Problem() >>> m.optimization_mode() 'maximization' """ if self.thisptr.optimization_mode() == MAXIMIZATION: return "maximization" elif self.thisptr.optimization_mode() == MINIMIZATION: return "minimization" def optimal_value(self): """ Return the optimal value of the MIP_Problem. ValueError thrown if self does not have an optimizing point, i.e., if the MIP problem is unbounded or not satisfiable. Examples: >>> from ppl import Variable, Constraint_System, MIP_Problem >>> x = Variable(0) >>> y = Variable(1) >>> cs = Constraint_System() >>> cs.insert( x >= 0 ) >>> cs.insert( y >= 0 ) >>> cs.insert( 3 * x + 5 * y <= 10 ) >>> m = MIP_Problem(2, cs, x + y) >>> m.optimal_value() mpq(10,3) >>> cs = Constraint_System() >>> cs.insert( x >= 0 ) >>> m = MIP_Problem(1, cs, x + x ) >>> m.optimal_value() Traceback (most recent call last): ... ValueError: PPL::MIP_Problem::optimizing_point(): *this ... have an optimizing point. """ cdef PPL_Coefficient sup_n cdef PPL_Coefficient sup_d sig_on() try: self.thisptr.optimal_value(sup_n, sup_d) finally: sig_off() return GMPy_MPQ_From_mpz(sup_n.get_mpz_t(), sup_d.get_mpz_t()) def space_dimension(self): """ Return the space dimension of the MIP_Problem. Examples: >>> from ppl import Variable, Constraint_System, MIP_Problem >>> x = Variable(0) >>> y = Variable(1) >>> cs = Constraint_System() >>> cs.insert( x >= 0) >>> cs.insert( y >= 0 ) >>> cs.insert( 3 * x + 5 * y <= 10 ) >>> m = MIP_Problem(2, cs, x + y) >>> m.space_dimension() 2 """ return self.thisptr.space_dimension() def objective_function(self): """ Return the optimal value of the MIP_Problem. Examples: >>> from ppl import Variable, Constraint_System, MIP_Problem >>> x = Variable(0) >>> y = Variable(1) >>> cs = Constraint_System() >>> cs.insert( x >= 0) >>> cs.insert( y >= 0 ) >>> cs.insert( 3 * x + 5 * y <= 10 ) >>> m = MIP_Problem(2, cs, x + y) >>> m.objective_function() x0+x1 """ rc = Linear_Expression() rc.thisptr[0] = self.thisptr.objective_function() return rc def clear(self): """ Reset the MIP_Problem to be equal to the trivial MIP_Problem. Examples: >>> from ppl import Variable, Constraint_System, MIP_Problem >>> x = Variable(0) >>> y = Variable(1) >>> cs = Constraint_System() >>> cs.insert( x >= 0) >>> cs.insert( y >= 0 ) >>> cs.insert( 3 * x + 5 * y <= 10 ) >>> m = MIP_Problem(2, cs, x + y) >>> m.objective_function() x0+x1 >>> m.clear() >>> m.objective_function() 0 """ self.thisptr.clear() def add_space_dimensions_and_embed(self, PPL_dimension_type m): """ Adds m new space dimensions and embeds the old MIP problem in the new vector space. Examples: >>> from ppl import Variable, Constraint_System, MIP_Problem >>> x = Variable(0) >>> y = Variable(1) >>> cs = Constraint_System() >>> cs.insert( x >= 0) >>> cs.insert( y >= 0 ) >>> cs.insert( 3 * x + 5 * y <= 10 ) >>> m = MIP_Problem(2, cs, x + y) >>> m.add_space_dimensions_and_embed(5) >>> m.space_dimension() 7 """ sig_on() self.thisptr.add_space_dimensions_and_embed(m) sig_off() def add_constraint(self, Constraint c): """ Adds a copy of constraint c to the MIP problem. Examples: >>> from ppl import Variable, MIP_Problem >>> x = Variable(0) >>> y = Variable(1) >>> m = MIP_Problem() >>> m.add_space_dimensions_and_embed(2) >>> m.add_constraint(x >= 0) >>> m.add_constraint(y >= 0) >>> m.add_constraint(3 * x + 5 * y <= 10) >>> m.set_objective_function(x + y) >>> m.optimal_value() mpq(10,3) Tests: >>> z = Variable(2) >>> m.add_constraint(z >= -3) Traceback (most recent call last): ... ValueError: PPL::MIP_Problem::add_constraint(c): c.space_dimension() == 3 exceeds this->space_dimension == 2. """ sig_on() try: self.thisptr.add_constraint(c.thisptr[0]) finally: sig_off() def add_constraints(self, Constraint_System cs): """ Adds a copy of the constraints in cs to the MIP problem. Examples: >>> from ppl import Variable, Constraint_System, MIP_Problem >>> x = Variable(0) >>> y = Variable(1) >>> cs = Constraint_System() >>> cs.insert(x >= 0) >>> cs.insert(y >= 0) >>> cs.insert(3 * x + 5 * y <= 10) >>> m = MIP_Problem(2) >>> m.set_objective_function(x + y) >>> m.add_constraints(cs) >>> m.optimal_value() mpq(10,3) Tests: >>> p = Variable(9) >>> cs.insert(p >= -3) >>> m.add_constraints(cs) Traceback (most recent call last): ... ValueError: PPL::MIP_Problem::add_constraints(cs): cs.space_dimension() == 10 exceeds this->space_dimension() == 2. """ sig_on() try: self.thisptr.add_constraints(cs.thisptr[0]) finally: sig_off() def add_to_integer_space_dimensions(self, Variables_Set i_vars): """ Sets the variables whose indexes are in set `i_vars` to be integer space dimensions. Examples: >>> from ppl import Variable, Variables_Set, Constraint_System, MIP_Problem >>> x = Variable(0) >>> y = Variable(1) >>> cs = Constraint_System() >>> cs.insert( x >= 0) >>> cs.insert( y >= 0 ) >>> cs.insert( 3 * x + 5 * y <= 10 ) >>> m = MIP_Problem(2) >>> m.set_objective_function(x + y) >>> m.add_constraints(cs) >>> i_vars = Variables_Set(x, y) >>> m.add_to_integer_space_dimensions(i_vars) >>> m.optimal_value() mpq(3,1) """ sig_on() try: self.thisptr.add_to_integer_space_dimensions(i_vars.thisptr[0]) finally: sig_off() def set_objective_function(self, obj): """ Sets the objective function to obj. Examples: >>> from ppl import Variable, MIP_Problem >>> x = Variable(0) >>> y = Variable(1) >>> m = MIP_Problem() >>> m.add_space_dimensions_and_embed(2) >>> m.add_constraint(x >= 0) >>> m.add_constraint(y >= 0) >>> m.add_constraint(3 * x + 5 * y <= 10) >>> m.set_objective_function(x + y) >>> m.optimal_value() mpq(10,3) Tests: >>> z = Variable(2) >>> m.set_objective_function(x + y + z) Traceback (most recent call last): ... ValueError: PPL::MIP_Problem::set_objective_function(obj): obj.space_dimension() == 3 exceeds this->space_dimension == 2. >>> M = MIP_Problem(1) >>> M.set_objective_function(Variable(0)) """ if isinstance(obj, Variable): obj = Linear_Expression(obj) elif not isinstance(obj, Linear_Expression): raise ValueError('not an objective function') self.thisptr.set_objective_function(( obj).thisptr[0]) def set_optimization_mode(self, mode): """ Sets the optimization mode to mode. Examples: >>> from ppl import MIP_Problem >>> m = MIP_Problem() >>> m.optimization_mode() 'maximization' >>> m.set_optimization_mode('minimization') >>> m.optimization_mode() 'minimization' Tests: >>> m.set_optimization_mode('max') Traceback (most recent call last): ... ValueError: Unknown value: mode=max. """ if mode == 'minimization': self.thisptr.set_optimization_mode(MINIMIZATION) elif mode == 'maximization': self.thisptr.set_optimization_mode(MAXIMIZATION) else: raise ValueError('Unknown value: mode='+str(mode)+'.') def is_satisfiable(self): """ Check if the MIP_Problem is satisfiable Examples: >>> from ppl import Variable, MIP_Problem >>> x = Variable(0) >>> y = Variable(1) >>> m = MIP_Problem() >>> m.add_space_dimensions_and_embed(2) >>> m.add_constraint(x >= 0) >>> m.add_constraint(y >= 0) >>> m.add_constraint(3 * x + 5 * y <= 10) >>> m.is_satisfiable() True """ return self.thisptr.is_satisfiable() def evaluate_objective_function(self, Generator evaluating_point): """ Return the result of evaluating the objective function on evaluating_point. ValueError thrown if self and evaluating_point are dimension-incompatible or if the generator evaluating_point is not a point. Examples: >>> from ppl import Variable, MIP_Problem, Generator >>> x = Variable(0) >>> y = Variable(1) >>> m = MIP_Problem() >>> m.add_space_dimensions_and_embed(2) >>> m.add_constraint(x >= 0) >>> m.add_constraint(y >= 0) >>> m.add_constraint(3 * x + 5 * y <= 10) >>> m.set_objective_function(x + y) >>> g = Generator.point(5 * x - 2 * y, 7) >>> m.evaluate_objective_function(g) mpq(3,7) >>> z = Variable(2) >>> g = Generator.point(5 * x - 2 * z, 7) >>> m.evaluate_objective_function(g) Traceback (most recent call last): ... ValueError: PPL::MIP_Problem::evaluate_objective_function(p, n, d): *this and p are dimension incompatible. """ cdef PPL_Coefficient sup_n cdef PPL_Coefficient sup_d sig_on() try: self.thisptr.evaluate_objective_function(evaluating_point.thisptr[0], sup_n, sup_d) finally: sig_off() return GMPy_MPQ_From_mpz(sup_n.get_mpz_t(), sup_d.get_mpz_t()) def solve(self): """ Optimizes the MIP_Problem Examples: >>> from ppl import Variable, MIP_Problem >>> x = Variable(0) >>> y = Variable(1) >>> m = MIP_Problem() >>> m.add_space_dimensions_and_embed(2) >>> m.add_constraint(x >= 0) >>> m.add_constraint(y >= 0) >>> m.add_constraint(3 * x + 5 * y <= 10) >>> m.set_objective_function(x + y) >>> m.solve() {'status': 'optimized'} """ sig_on() try: tmp = self.thisptr.solve() finally: sig_off() if tmp == UNFEASIBLE_MIP_PROBLEM: return {'status': 'unfeasible'} elif tmp == UNBOUNDED_MIP_PROBLEM: return {'status': 'unbounded'} else: return {'status': 'optimized'} def optimizing_point(self): """ Returns an optimal point for the MIP_Problem, if it exists. Examples: >>> from ppl import Variable, MIP_Problem >>> x = Variable(0) >>> y = Variable(1) >>> m = MIP_Problem() >>> m.add_space_dimensions_and_embed(2) >>> m.add_constraint(x >= 0) >>> m.add_constraint(y >= 0) >>> m.add_constraint(3 * x + 5 * y <= 10) >>> m.set_objective_function(x + y) >>> m.optimizing_point() point(10/3, 0/3) """ cdef PPL_Generator *g sig_on() try: g = new PPL_Generator(self.thisptr[0].optimizing_point()) finally: sig_off() return _wrap_Generator(g[0]) pplpy-0.8.9/ppl/polyhedron.pxd000066400000000000000000000006171447517221400164020ustar00rootroot00000000000000from .ppl_decl cimport PPL_Polyhedron from .generator cimport Generator from .constraint cimport Constraint cdef class Polyhedron(object): cdef PPL_Polyhedron *thisptr cdef _relation_with_generator(Polyhedron self, Generator g) cdef _relation_with_constraint(Polyhedron self, Constraint c) cdef class C_Polyhedron(Polyhedron): pass cdef class NNC_Polyhedron(Polyhedron): pass pplpy-0.8.9/ppl/polyhedron.pyx000066400000000000000000002526731447517221400164420ustar00rootroot00000000000000# distutils: language = c++ # distutils: libraries = gmp gmpxx ppl m #***************************************************************************** # Copyright (C) 2010-2014 Volker Braun # 2011 Simon King # 2011-2017 Jeroen Demeyer # 2012 Risan # 2013 Julien Puydt # 2013 Travis Scrimshaw # 2015 André Apitzsch # 2016 Jori Mäntysalo # 2016 Matthias Koeppe # 2016-2017 Frédéric Chapoton # 2016-2018 Vincent Delecroix # 2017-2018 Vincent Klein # # Distributed under the terms of the GNU General Public License (GPL) # as published by the Free Software Foundation; either version 3 of # the License, or (at youroption) any later version. # http://www.gnu.org/licenses/ #***************************************************************************** from cpython.object cimport Py_LT, Py_LE, Py_EQ, Py_NE, Py_GT, Py_GE from cysignals.signals cimport sig_on, sig_off from gmpy2 cimport GMPy_MPZ_From_mpz, import_gmpy2 from .ppl_decl cimport * from .constraint cimport Constraint_System, Poly_Con_Relation, _wrap_Constraint_System from .generator cimport Generator_System, Poly_Gen_Relation, _wrap_Generator_System from .linear_algebra cimport * # PPL can use floating-point arithmetic to compute integers cdef extern from "ppl.hh" namespace "Parma_Polyhedra_Library": cdef void set_rounding_for_PPL() cdef void restore_pre_PPL_rounding() # initialize gmpy2 C API import_gmpy2() # but with PPL's rounding the gsl will be very unhappy; must turn off! restore_pre_PPL_rounding() cdef class Polyhedron(object): r""" Wrapper for PPL's ``Polyhedron`` class. An object of the class Polyhedron represents a convex polyhedron in the vector space. A polyhedron can be specified as either a finite system of constraints or a finite system of generators (see Section Representations of Convex Polyhedra) and it is always possible to obtain either representation. That is, if we know the system of constraints, we can obtain from this the system of generators that define the same polyhedron and vice versa. These systems can contain redundant members: in this case we say that they are not in the minimal form. INPUT/OUTPUT: This is an abstract base for :class:`C_Polyhedron` and :class:`NNC_Polyhedron`. You cannot instantiate this class. """ def __init__(self): r""" The Python constructor. See also :class:`C_Polyhedron` and :class:`NNC_Polyhedron`. You must not instantiate :class:`Polyhedron` objects. Tests: >>> from ppl.polyhedron import Polyhedron >>> Polyhedron() Traceback (most recent call last): ... NotImplementedError: The Polyhedron class is abstract, you must not instantiate it. """ raise NotImplementedError('The Polyhedron class is abstract, you must not instantiate it.') def __hash__(self): r""" Tests: >>> import ppl >>> hash(ppl.C_Polyhedron(ppl.point())) Traceback (most recent call last): ... TypeError: Polyhedron not hashable >>> cs = ppl.Constraint_System(ppl.Variable(0) > 0) >>> hash(NNC_Polyhedron(cs)) Traceback (most recent call last): ... TypeError: Polyhedron not hashable """ raise TypeError('Polyhedron not hashable') def __repr__(self): """ Return a string representation. OUTPUT: String. Examples: >>> from ppl import Variable, C_Polyhedron >>> x = Variable(0) >>> y = Variable(1) >>> C_Polyhedron( 5*x-2*y >= x+y-1 ).__repr__() 'A 2-dimensional polyhedron in QQ^2 defined as the convex hull of 1 point, 1 ray, 1 line' Special cases:: >>> C_Polyhedron(3, 'empty').__repr__() 'The empty polyhedron in QQ^3' >>> C_Polyhedron(3, 'universe').__repr__() 'The space-filling polyhedron in QQ^3' """ dim = self.affine_dimension() ambient_dim = self.space_dimension() gs = self.minimized_generators() n_points = 0 n_closure_points = 0 n_lines = 0 n_rays = 0 for g in gs: if g.is_line(): n_lines += 1 elif g.is_ray(): n_rays += 1 elif g.is_point(): n_points += 1 elif g.is_closure_point(): n_closure_points += 1 else: raise RuntimeError if self.is_empty(): return 'The empty polyhedron in QQ^'+str(ambient_dim) if self.is_universe(): return 'The space-filling polyhedron in QQ^'+str(ambient_dim) desc = 'A ' + str(dim) + '-dimensional polyhedron' desc += ' in QQ' desc += '^' + str(ambient_dim) desc += ' defined as the convex hull of ' first = True if n_points>0: if not first: desc += ", " first = False desc += str(n_points) if n_points == 1: desc += ' point' else: desc += ' points' if n_closure_points>0: if not first: desc += ", " first = False desc += str(n_closure_points) if n_closure_points == 1: desc += ' closure_point' else: desc += ' closure_points' if n_rays>0: if not first: desc += ", " first = False desc += str(n_rays) if n_rays == 1: desc += ' ray' else: desc += ' rays' if n_lines>0: if not first: desc += ", " first = False desc += repr(n_lines) if n_lines == 1: desc +=' line' else: desc +=' lines' return desc def space_dimension(self): r""" Return the dimension of the vector space enclosing ``self``. OUTPUT: Integer. Examples: >>> from ppl import Variable, C_Polyhedron >>> x = Variable(0) >>> y = Variable(1) >>> p = C_Polyhedron( 5*x-2*y >= x+y-1 ) >>> p.space_dimension() 2 """ return self.thisptr.space_dimension() def affine_dimension(self): r""" Return the affine dimension of ``self``. OUTPUT: An integer. Returns 0 if ``self`` is empty. Otherwise, returns the affine dimension of ``self``. Examples: >>> from ppl import Variable, C_Polyhedron >>> x = Variable(0) >>> y = Variable(1) >>> p = C_Polyhedron( 5*x-2*y == x+y-1 ) >>> p.affine_dimension() 1 """ sig_on() cdef size_t dim = self.thisptr.affine_dimension() sig_off() return dim def constraints(self): r""" Returns the system of constraints. See also :meth:`minimized_constraints`. OUTPUT: A :class:`Constraint_System`. Examples: >>> from ppl import Variable, C_Polyhedron >>> x = Variable(0) >>> y = Variable(1) >>> p = C_Polyhedron(y >= 0) >>> p.add_constraint(x >= 0) >>> p.add_constraint(x+y >= 0) >>> p.constraints() Constraint_System {x1>=0, x0>=0, x0+x1>=0} >>> p.minimized_constraints() Constraint_System {x1>=0, x0>=0} """ sig_on() cdef PPL_Constraint_System cs = self.thisptr.constraints() sig_off() return _wrap_Constraint_System(cs) def minimized_constraints(self): r""" Returns the minimized system of constraints. See also :meth:`constraints`. OUTPUT: A :class:`Constraint_System`. Examples: >>> from ppl import Variable, C_Polyhedron >>> x = Variable(0) >>> y = Variable(1) >>> p = C_Polyhedron(y >= 0) >>> p.add_constraint(x >= 0) >>> p.add_constraint(x+y >= 0) >>> p.constraints() Constraint_System {x1>=0, x0>=0, x0+x1>=0} >>> p.minimized_constraints() Constraint_System {x1>=0, x0>=0} """ sig_on() cdef PPL_Constraint_System cs = self.thisptr.minimized_constraints() sig_off() return _wrap_Constraint_System(cs) def generators(self): r""" Returns the system of generators. See also :meth:`minimized_generators`. OUTPUT: A :class:`Generator_System`. Examples: >>> from ppl import Variable, C_Polyhedron, point >>> x = Variable(0) >>> y = Variable(1) >>> p = C_Polyhedron(3,'empty') >>> p.add_generator(point(-x-y)) >>> p.add_generator(point(0)) >>> p.add_generator(point(+x+y)) >>> p.generators() Generator_System {point(-1/1, -1/1, 0/1), point(0/1, 0/1, 0/1), point(1/1, 1/1, 0/1)} >>> p.minimized_generators() Generator_System {point(-1/1, -1/1, 0/1), point(1/1, 1/1, 0/1)} """ sig_on() cdef PPL_Generator_System gs = self.thisptr.generators() sig_off() return _wrap_Generator_System(gs) def minimized_generators(self): r""" Returns the minimized system of generators. See also :meth:`generators`. OUTPUT: A :class:`Generator_System`. Examples: >>> from ppl import Variable, C_Polyhedron, point >>> x = Variable(0) >>> y = Variable(1) >>> p = C_Polyhedron(3,'empty') >>> p.add_generator(point(-x-y)) >>> p.add_generator(point(0)) >>> p.add_generator(point(+x+y)) >>> p.generators() Generator_System {point(-1/1, -1/1, 0/1), point(0/1, 0/1, 0/1), point(1/1, 1/1, 0/1)} >>> p.minimized_generators() Generator_System {point(-1/1, -1/1, 0/1), point(1/1, 1/1, 0/1)} """ sig_on() cdef PPL_Generator_System gs = self.thisptr.minimized_generators() sig_off() return _wrap_Generator_System(gs) cdef _relation_with_generator(Polyhedron self, Generator g): r""" Helper method for :meth:`relation_with`. """ rel = Poly_Gen_Relation(True) try: sig_on() try: rel.thisptr = new_relation_with(self.thisptr[0], g.thisptr[0]) finally: sig_off() except BaseException: # rel.thisptr must be set to something valid or rel.__dealloc__() will segfault rel.thisptr = new PPL_Poly_Gen_Relation(PPL_Poly_Gen_Relation_nothing()) raise return rel cdef _relation_with_constraint(Polyhedron self, Constraint c): r""" Helper method for :meth:`relation_with`. """ rel = Poly_Con_Relation(True) try: sig_on() try: rel.thisptr = new_relation_with(self.thisptr[0], c.thisptr[0]) finally: sig_off() except BaseException: # rel.thisptr must be set to something valid or rel.__dealloc__() will segfault rel.thisptr = new PPL_Poly_Con_Relation(PPL_Poly_Con_Relation_nothing()) raise return rel def relation_with(self, arg): r""" Return the relations holding between the polyhedron ``self`` and the generator or constraint ``arg``. INPUT: - ``arg`` -- a :class:`Generator` or a :class:`Constraint`. OUTPUT: A :class:`Poly_Gen_Relation` or a :class:`Poly_Con_Relation` according to the type of the input. Raises ``ValueError`` if ``self`` and the generator/constraint ``arg`` are dimension-incompatible. Examples: >>> from ppl import Variable, C_Polyhedron, point >>> x = Variable(0); y = Variable(1) >>> p = C_Polyhedron(2, 'empty') >>> p.add_generator( point(1*x+0*y) ) >>> p.add_generator( point(0*x+1*y) ) >>> p.minimized_constraints() Constraint_System {x0+x1-1==0, -x1+1>=0, x1>=0} >>> p.relation_with( point(1*x+1*y) ) nothing >>> p.relation_with( point(1*x+1*y, 2) ) subsumes >>> p.relation_with( x+y==-1 ) is_disjoint >>> p.relation_with( x==y ) strictly_intersects >>> p.relation_with( x+y<=1 ) is_included, saturates >>> p.relation_with( x+y<1 ) is_disjoint, saturates In a Python program you will usually use :meth:`relation_with` together with :meth:`~ppl.Poly_Gen_Relation.implies` or :meth:`~ppl.Poly_Con_Relation.implies`, for example: >>> from ppl import Poly_Con_Relation >>> p.relation_with( x+y<1 ).implies(Poly_Con_Relation.saturates()) True You can only get relations with dimension-compatible generators or constraints: >>> z = Variable(2) >>> p.relation_with( point(x+y+z) ) Traceback (most recent call last): ... ValueError: PPL::C_Polyhedron::relation_with(g): this->space_dimension() == 2, g.space_dimension() == 3. >>> p.relation_with( z>0 ) Traceback (most recent call last): ... ValueError: PPL::C_Polyhedron::relation_with(c): this->space_dimension() == 2, c.space_dimension() == 3. """ if isinstance(arg, Generator): return self._relation_with_generator(arg) if isinstance(arg, Constraint): return self._relation_with_constraint(arg) else: raise TypeError('Argument must be Generator or a Constraint') def is_empty(self): """ Test if ``self`` is an empty polyhedron. OUTPUT: Boolean. Examples: >>> from ppl import C_Polyhedron >>> C_Polyhedron(3, 'empty').is_empty() True >>> C_Polyhedron(3, 'universe').is_empty() False """ sig_on() cdef bint result = self.thisptr.is_empty() sig_off() return result def is_universe(self): """ Test if ``self`` is a universe (space-filling) polyhedron. OUTPUT: Boolean. Examples: >>> from ppl import C_Polyhedron >>> C_Polyhedron(3, 'empty').is_universe() False >>> C_Polyhedron(3, 'universe').is_universe() True """ sig_on() cdef bint result = self.thisptr.is_universe() sig_off() return result def is_topologically_closed(self): """ Tests if ``self`` is topologically closed. OUTPUT: Returns ``True`` if and only if ``self`` is a topologically closed subset of the ambient vector space. Examples: >>> from ppl import Variable, C_Polyhedron, NNC_Polyhedron >>> x = Variable(0); y = Variable(1) >>> C_Polyhedron(3, 'universe').is_topologically_closed() True >>> C_Polyhedron( x>=1 ).is_topologically_closed() True >>> NNC_Polyhedron( x>1 ).is_topologically_closed() False """ sig_on() cdef bint result = self.thisptr.is_topologically_closed() sig_off() return result def is_disjoint_from(self, Polyhedron y): r""" Tests whether ``self`` and ``y`` are disjoint. INPUT: - ``y`` -- a :class:`Polyhedron`. OUTPUT: Boolean. Returns ``True`` if and only if ``self`` and ``y`` are disjoint. Rayises a ``ValueError`` if ``self`` and ``y`` are topology-incompatible or dimension-incompatible. Examples: >>> from ppl import Variable, C_Polyhedron, NNC_Polyhedron >>> x = Variable(0); y = Variable(1) >>> C_Polyhedron(x<=0).is_disjoint_from( C_Polyhedron(x>=1) ) True This is not allowed: >>> x = Variable(0); y = Variable(1) >>> poly_1d = C_Polyhedron(x<=0) >>> poly_2d = C_Polyhedron(x+0*y>=1) >>> poly_1d.is_disjoint_from(poly_2d) Traceback (most recent call last): ... ValueError: PPL::C_Polyhedron::intersection_assign(y): this->space_dimension() == 1, y.space_dimension() == 2. Nor is this: >>> x = Variable(0); y = Variable(1) >>> c_poly = C_Polyhedron( x<=0 ) >>> nnc_poly = NNC_Polyhedron( x >0 ) >>> c_poly.is_disjoint_from(nnc_poly) Traceback (most recent call last): ... ValueError: PPL::C_Polyhedron::intersection_assign(y): y is a NNC_Polyhedron. >>> NNC_Polyhedron(c_poly).is_disjoint_from(nnc_poly) True """ cdef bint result sig_on() try: result = self.thisptr.is_disjoint_from(y.thisptr[0]) finally: sig_off() return result def is_discrete(self): r""" Test whether ``self`` is discrete. OUTPUT: Boolean. Returns ``True`` if and only if ``self`` is discrete. Examples: >>> from ppl import Variable, C_Polyhedron, point >>> x = Variable(0); y = Variable(1) >>> p = C_Polyhedron( point(1*x+2*y) ) >>> p.is_discrete() True >>> p.add_generator( point(x) ) >>> p.is_discrete() False """ sig_on() cdef bint result = self.thisptr.is_discrete() sig_off() return result def is_bounded(self): r""" Test whether ``self`` is bounded. OUTPUT: Boolean. Returns ``True`` if and only if ``self`` is a bounded polyhedron. Examples: >>> from ppl import Variable, NNC_Polyhedron, point, closure_point, ray >>> x = Variable(0) >>> p = NNC_Polyhedron( point(0*x) ) >>> p.add_generator( closure_point(1*x) ) >>> p.is_bounded() True >>> p.add_generator( ray(1*x) ) >>> p.is_bounded() False """ sig_on() cdef bint result = self.thisptr.is_bounded() sig_off() return result def contains_integer_point(self): r""" Test whether ``self`` contains an integer point. OUTPUT: Boolean. Returns ``True`` if and only if ``self`` contains an integer point. Examples: >>> from ppl import Variable, NNC_Polyhedron >>> x = Variable(0) >>> p = NNC_Polyhedron(x>0) >>> p.add_constraint(x<1) >>> p.contains_integer_point() False >>> p.topological_closure_assign() >>> p.contains_integer_point() True """ sig_on() cdef bint result = self.thisptr.contains_integer_point() sig_off() return result def constrains(self, Variable var): r""" Test whether ``var`` is constrained in ``self``. INPUT: - ``var`` -- a :class:`Variable`. OUTPUT: Boolean. Returns ``True`` if and only if ``var`` is constrained in ``self``. Raises a ``ValueError`` if ``var`` is not a space dimension of ``self``. Examples: >>> from ppl import Variable, C_Polyhedron >>> x = Variable(0) >>> p = C_Polyhedron(1, 'universe') >>> p.constrains(x) False >>> p = C_Polyhedron(x>=0) >>> p.constrains(x) True >>> y = Variable(1) >>> p.constrains(y) Traceback (most recent call last): ... ValueError: PPL::C_Polyhedron::constrains(v): this->space_dimension() == 1, v.space_dimension() == 2. """ cdef bint result sig_on() try: result = self.thisptr.constrains(var.thisptr[0]) finally: sig_off() return result def bounds_from_above(self, Linear_Expression expr): r""" Test whether the ``expr`` is bounded from above. INPUT: - ``expr`` -- a :class:`Linear_Expression` OUTPUT: Boolean. Returns ``True`` if and only if ``expr`` is bounded from above in ``self``. Raises a ``ValueError`` if ``expr`` and ``this`` are dimension-incompatible. Examples: >>> from ppl import Variable, C_Polyhedron, Linear_Expression >>> x = Variable(0); y = Variable(1) >>> p = C_Polyhedron(y<=0) >>> p.bounds_from_above(x+1) False >>> p.bounds_from_above(Linear_Expression(y)) True >>> p = C_Polyhedron(x<=0) >>> p.bounds_from_above(y+1) Traceback (most recent call last): ... ValueError: PPL::C_Polyhedron::bounds_from_above(e): this->space_dimension() == 1, e.space_dimension() == 2. """ cdef bint result sig_on() try: result = self.thisptr.bounds_from_above(expr.thisptr[0]) finally: sig_off() return result def bounds_from_below(self, Linear_Expression expr): r""" Test whether the ``expr`` is bounded from above. INPUT: - ``expr`` -- a :class:`Linear_Expression` OUTPUT: Boolean. Returns ``True`` if and only if ``expr`` is bounded from above in ``self``. Raises a ``ValueError`` if ``expr`` and ``this`` are dimension-incompatible. Examples: >>> from ppl import Variable, C_Polyhedron, Linear_Expression >>> x = Variable(0); y = Variable(1) >>> p = C_Polyhedron(y>=0) >>> p.bounds_from_below(x+1) False >>> p.bounds_from_below(Linear_Expression(y)) True >>> p = C_Polyhedron(x<=0) >>> p.bounds_from_below(y+1) Traceback (most recent call last): ... ValueError: PPL::C_Polyhedron::bounds_from_below(e): this->space_dimension() == 1, e.space_dimension() == 2. """ cdef bint result sig_on() try: result = self.thisptr.bounds_from_below(expr.thisptr[0]) finally: sig_off() return result def maximize(self, Linear_Expression expr): r""" Maximize ``expr``. INPUT: - ``expr`` -- a :class:`Linear_Expression`. OUTPUT: A dictionary with the following keyword:value pair: * ``'bounded'``: Boolean. Whether the linear expression ``expr`` is bounded from above on ``self``. If ``expr`` is bounded from above, the following additional keyword:value pairs are set to provide information about the supremum: * ``'sup_n'``: Integer. The numerator of the supremum value. * ``'sup_d'``: Non-zero integer. The denominator of the supremum value. * ``'maximum'``: Boolean. ``True`` if and only if the supremum is also the maximum value. * ``'generator'``: a :class:`Generator`. A point or closure point where expr reaches its supremum value. Examples: >>> from ppl import Variable, C_Polyhedron, NNC_Polyhedron, Constraint_System >>> x = Variable(0); y = Variable(1) >>> cs = Constraint_System() >>> cs.insert(x >= 0) >>> cs.insert(y >= 0) >>> cs.insert(3*x+5*y <= 10) >>> p = C_Polyhedron(cs) >>> pm = p.maximize(x+y) >>> for key in sorted(pm): ... print("{} {}".format(key, pm[key])) bounded True generator point(10/3, 0/3) maximum True sup_d 3 sup_n 10 Unbounded case: >>> cs = Constraint_System() >>> cs.insert(x > 0) >>> p = NNC_Polyhedron(cs) >>> p.maximize(+x) {'bounded': False} >>> pm = p.maximize(-x) >>> for key in sorted(pm): ... print("{} {}".format(key, pm[key])) bounded True generator closure_point(0/1) maximum False sup_d 1 sup_n 0 """ cdef PPL_Coefficient sup_n cdef PPL_Coefficient sup_d cdef Generator g = Generator.point() cdef cppbool maximum sig_on() rc = self.thisptr.maximize(expr.thisptr[0], sup_n, sup_d, maximum, g.thisptr[0]) sig_off() mpz_sup_n = GMPy_MPZ_From_mpz(sup_n.get_mpz_t()) mpz_sup_d = GMPy_MPZ_From_mpz(sup_d.get_mpz_t()) if rc: return {'bounded': True, 'sup_n': mpz_sup_n, 'sup_d': mpz_sup_d, 'maximum': maximum, 'generator': g} else: return {'bounded': False} def minimize(self, Linear_Expression expr): r""" Minimize ``expr``. INPUT: - ``expr`` -- a :class:`Linear_Expression`. OUTPUT: A dictionary with the following keyword:value pair: * ``'bounded'``: Boolean. Whether the linear expression ``expr`` is bounded from below on ``self``. If ``expr`` is bounded from below, the following additional keyword:value pairs are set to provide information about the infimum: * ``'inf_n'``: Integer. The numerator of the infimum value. * ``'inf_d'``: Non-zero integer. The denominator of the infimum value. * ``'minimum'``: Boolean. ``True`` if and only if the infimum is also the minimum value. * ``'generator'``: a :class:`Generator`. A point or closure point where expr reaches its infimum value. Examples: >>> from ppl import Variable, C_Polyhedron, NNC_Polyhedron, Constraint_System >>> x = Variable(0); y = Variable(1) >>> cs = Constraint_System() >>> cs.insert( x>=0 ) >>> cs.insert( y>=0 ) >>> cs.insert( 3*x+5*y<=10 ) >>> p = C_Polyhedron(cs) >>> pm = p.minimize( x+y ) >>> for key in sorted(pm): ... print("{} {}".format(key, pm[key])) bounded True generator point(0/1, 0/1) inf_d 1 inf_n 0 minimum True Unbounded case: >>> cs = Constraint_System() >>> cs.insert(x > 0) >>> p = NNC_Polyhedron(cs) >>> pm = p.minimize(+x) >>> for key in sorted(pm): ... print("{} {}".format(key, pm[key])) bounded True generator closure_point(0/1) inf_d 1 inf_n 0 minimum False >>> p.minimize( -x ) {'bounded': False} """ cdef PPL_Coefficient inf_n cdef PPL_Coefficient inf_d cdef Generator g = Generator.point() cdef cppbool minimum sig_on() rc = self.thisptr.minimize(expr.thisptr[0], inf_n, inf_d, minimum, g.thisptr[0]) sig_off() mpz_inf_n = GMPy_MPZ_From_mpz(inf_n.get_mpz_t()) mpz_inf_d = GMPy_MPZ_From_mpz(inf_d.get_mpz_t()) if rc: return {'bounded': True, 'inf_n': mpz_inf_n, 'inf_d': mpz_inf_d, 'minimum': minimum, 'generator': g} else: return {'bounded': False} def contains(self, Polyhedron y): r""" Test whether ``self`` contains ``y``. INPUT: - ``y`` -- a :class:`Polyhedron`. OUTPUT: Boolean. Returns ``True`` if and only if ``self`` contains ``y``. Raises a ``ValueError`` if ``self`` and ``y`` are topology-incompatible or dimension-incompatible. Examples: >>> from ppl import Variable, C_Polyhedron, NNC_Polyhedron >>> x = Variable(0) >>> y = Variable(1) >>> p0 = C_Polyhedron( x>=0 ) >>> p1 = C_Polyhedron( x>=1 ) >>> p0.contains(p1) True >>> p1.contains(p0) False Errors are raised if the dimension or topology is not compatible: >>> p0.contains(C_Polyhedron(y>=0)) Traceback (most recent call last): ... ValueError: PPL::C_Polyhedron::contains(y): this->space_dimension() == 1, y.space_dimension() == 2. >>> p0.contains(NNC_Polyhedron(x>0)) Traceback (most recent call last): ... ValueError: PPL::C_Polyhedron::contains(y): y is a NNC_Polyhedron. """ cdef bint result sig_on() try: result = self.thisptr.contains(y.thisptr[0]) finally: sig_off() return result def strictly_contains(self, Polyhedron y): r""" Test whether ``self`` strictly contains ``y``. INPUT: - ``y`` -- a :class:`Polyhedron`. OUTPUT: Boolean. Returns ``True`` if and only if ``self`` contains ``y`` and ``self`` does not equal ``y``. Raises a ``ValueError`` if ``self`` and ``y`` are topology-incompatible or dimension-incompatible. Examples: >>> from ppl import Variable, C_Polyhedron, NNC_Polyhedron >>> x = Variable(0) >>> y = Variable(1) >>> p0 = C_Polyhedron( x>=0 ) >>> p1 = C_Polyhedron( x>=1 ) >>> p0.strictly_contains(p1) True >>> p1.strictly_contains(p0) False Errors are raised if the dimension or topology is not compatible: >>> p0.strictly_contains(C_Polyhedron(y>=0)) Traceback (most recent call last): ... ValueError: PPL::C_Polyhedron::contains(y): this->space_dimension() == 1, y.space_dimension() == 2. >>> p0.strictly_contains(NNC_Polyhedron(x>0)) Traceback (most recent call last): ... ValueError: PPL::C_Polyhedron::contains(y): y is a NNC_Polyhedron. """ cdef bint result sig_on() try: result = self.thisptr.strictly_contains(y.thisptr[0]) finally: sig_off() return result def add_constraint(self, Constraint c): r""" Add a constraint to the polyhedron. Adds a copy of constraint ``c`` to the system of constraints of ``self``, without minimizing the result. See also :meth:`add_constraints`. INPUT: - ``c`` -- the :class:`Constraint` that will be added to the system of constraints of ``self``. OUTPUT: This method modifies the polyhedron ``self`` and does not return anything. Raises a ``ValueError`` if ``self`` and the constraint ``c`` are topology-incompatible or dimension-incompatible. Examples: >>> from ppl import Variable, C_Polyhedron >>> x = Variable(0) >>> y = Variable(1) >>> p = C_Polyhedron( y>=0 ) >>> p.add_constraint( x>=0 ) We just added a 1-d constraint to a 2-d polyhedron, this is fine. The other way is not: >>> p = C_Polyhedron( x>=0 ) >>> p.add_constraint( y>=0 ) Traceback (most recent call last): ... ValueError: PPL::C_Polyhedron::add_constraint(c): this->space_dimension() == 1, c.space_dimension() == 2. The constraint must also be topology-compatible, that is, :class:`C_Polyhedron` only allows non-strict inequalities: >>> p = C_Polyhedron( x>=0 ) >>> p.add_constraint( x< 1 ) Traceback (most recent call last): ... ValueError: PPL::C_Polyhedron::add_constraint(c): c is a strict inequality. """ sig_on() try: self.thisptr.add_constraint(c.thisptr[0]) finally: sig_off() def add_generator(self, Generator g): r""" Add a generator to the polyhedron. Adds a copy of constraint ``c`` to the system of generators of ``self``, without minimizing the result. INPUT: - ``g`` -- the :class:`Generator` that will be added to the system of Generators of ``self``. OUTPUT: This method modifies the polyhedron ``self`` and does not return anything. Raises a ``ValueError`` if ``self`` and the generator ``g`` are topology-incompatible or dimension-incompatible, or if ``self`` is an empty polyhedron and ``g`` is not a point. Examples: >>> from ppl import Variable, C_Polyhedron, point, closure_point, ray >>> x = Variable(0) >>> y = Variable(1) >>> p = C_Polyhedron(1, 'empty') >>> p.add_generator( point(0*x) ) We just added a 1-d generator to a 2-d polyhedron, this is fine. The other way is not: >>> p = C_Polyhedron(1, 'empty') >>> p.add_generator( point(0*y) ) Traceback (most recent call last): ... ValueError: PPL::C_Polyhedron::add_generator(g): this->space_dimension() == 1, g.space_dimension() == 2. The constraint must also be topology-compatible, that is, :class:`C_Polyhedron` does not allow :func:`closure_point` generators: >>> p = C_Polyhedron( point(0*x+0*y) ) >>> p.add_generator( closure_point(0*x) ) Traceback (most recent call last): ... ValueError: PPL::C_Polyhedron::add_generator(g): g is a closure point. Finally, ever non-empty polyhedron must have at least one point generator: >>> p = C_Polyhedron(3, 'empty') >>> p.add_generator( ray(x) ) Traceback (most recent call last): ... ValueError: PPL::C_Polyhedron::add_generator(g): *this is an empty polyhedron and g is not a point. """ sig_on() try: self.thisptr.add_generator(g.thisptr[0]) finally: sig_off() def add_constraints(self, Constraint_System cs): r""" Add constraints to the polyhedron. Adds a copy of constraints in ``cs`` to the system of constraints of ``self``, without minimizing the result. See also :meth:`add_constraint`. INPUT: - ``cs`` -- the :class:`Constraint_System` that will be added to the system of constraints of ``self``. OUTPUT: This method modifies the polyhedron ``self`` and does not return anything. Raises a ``ValueError`` if ``self`` and the constraints in ``cs`` are topology-incompatible or dimension-incompatible. Examples: >>> from ppl import Variable, C_Polyhedron, Constraint_System >>> x = Variable(0) >>> y = Variable(1) >>> cs = Constraint_System() >>> cs.insert(x>=0) >>> cs.insert(y>=0) >>> p = C_Polyhedron( y<=1 ) >>> p.add_constraints(cs) We just added a 1-d constraint to a 2-d polyhedron, this is fine. The other way is not: >>> p = C_Polyhedron( x<=1 ) >>> p.add_constraints(cs) Traceback (most recent call last): ... ValueError: PPL::C_Polyhedron::add_recycled_constraints(cs): this->space_dimension() == 1, cs.space_dimension() == 2. The constraints must also be topology-compatible, that is, :class:`C_Polyhedron` only allows non-strict inequalities: >>> p = C_Polyhedron( x>=0 ) >>> p.add_constraints( Constraint_System(x<0) ) Traceback (most recent call last): ... ValueError: PPL::C_Polyhedron::add_recycled_constraints(cs): cs contains strict inequalities. """ sig_on() try: self.thisptr.add_constraints(cs.thisptr[0]) finally: sig_off() def add_generators(self, Generator_System gs): r""" Add generators to the polyhedron. Adds a copy of the generators in ``gs`` to the system of generators of ``self``, without minimizing the result. See also :meth:`add_generator`. INPUT: - ``gs`` -- the :class:`Generator_System` that will be added to the system of constraints of ``self``. OUTPUT: This method modifies the polyhedron ``self`` and does not return anything. Raises a ``ValueError`` if ``self`` and one of the generators in ``gs`` are topology-incompatible or dimension-incompatible, or if ``self`` is an empty polyhedron and ``gs`` does not contain a point. Examples: >>> from ppl import Variable, C_Polyhedron, Generator_System, point, ray, closure_point >>> x = Variable(0) >>> y = Variable(1) >>> gs = Generator_System() >>> gs.insert(point(0*x+0*y)) >>> gs.insert(point(1*x+1*y)) >>> p = C_Polyhedron(2, 'empty') >>> p.add_generators(gs) We just added a 1-d constraint to a 2-d polyhedron, this is fine. The other way is not: >>> p = C_Polyhedron(1, 'empty') >>> p.add_generators(gs) Traceback (most recent call last): ... ValueError: PPL::C_Polyhedron::add_recycled_generators(gs): this->space_dimension() == 1, gs.space_dimension() == 2. The constraints must also be topology-compatible, that is, :class:`C_Polyhedron` does not allow :func:`closure_point` generators: >>> p = C_Polyhedron( point(0*x+0*y) ) >>> p.add_generators( Generator_System(closure_point(x) )) Traceback (most recent call last): ... ValueError: PPL::C_Polyhedron::add_recycled_generators(gs): gs contains closure points. """ sig_on() try: self.thisptr.add_generators(gs.thisptr[0]) finally: sig_off() def unconstrain(self, Variable var): r""" Compute the cylindrification of ``self`` with respect to space dimension ``var``. INPUT: - ``var`` -- a :class:`Variable`. The space dimension that will be unconstrained. Exceptions: OUTPUT: This method assigns the cylindrification to ``self`` and does not return anything. Raises a ``ValueError`` if ``var`` is not a space dimension of ``self``. Examples: >>> from ppl import Variable, C_Polyhedron, point >>> x = Variable(0) >>> y = Variable(1) >>> p = C_Polyhedron( point(x+y) ); p A 0-dimensional polyhedron in QQ^2 defined as the convex hull of 1 point >>> p.unconstrain(x); p A 1-dimensional polyhedron in QQ^2 defined as the convex hull of 1 point, 1 line >>> z = Variable(2) >>> p.unconstrain(z) Traceback (most recent call last): ... ValueError: PPL::C_Polyhedron::unconstrain(var): this->space_dimension() == 2, required space dimension == 3. """ sig_on() try: self.thisptr.unconstrain(var.thisptr[0]) finally: sig_off() def intersection_assign(self, Polyhedron y): r""" Assign to ``self`` the intersection of ``self`` and ``y``. INPUT: - ``y`` -- a :class:`Polyhedron` OUTPUT: This method assigns the intersection to ``self`` and does not return anything. Raises a ``ValueError`` if ``self`` and and ``y`` are topology-incompatible or dimension-incompatible. Examples: >>> from ppl import Variable, C_Polyhedron, NNC_Polyhedron >>> x = Variable(0) >>> y = Variable(1) >>> p = C_Polyhedron( 1*x+0*y >= 0 ) >>> p.intersection_assign( C_Polyhedron(y>=0) ) >>> p.constraints() Constraint_System {x0>=0, x1>=0} >>> z = Variable(2) >>> p.intersection_assign( C_Polyhedron(z>=0) ) Traceback (most recent call last): ... ValueError: PPL::C_Polyhedron::intersection_assign(y): this->space_dimension() == 2, y.space_dimension() == 3. >>> p.intersection_assign( NNC_Polyhedron(x+y<1) ) Traceback (most recent call last): ... ValueError: PPL::C_Polyhedron::intersection_assign(y): y is a NNC_Polyhedron. """ sig_on() try: self.thisptr.intersection_assign(y.thisptr[0]) finally: sig_off() def poly_hull_assign(self, Polyhedron y): r""" Assign to ``self`` the poly-hull of ``self`` and ``y``. For any pair of NNC polyhedra `P_1` and `P_2`, the convex polyhedral hull (or poly-hull) of is the smallest NNC polyhedron that includes both `P_1` and `P_2`. The poly-hull of any pair of closed polyhedra in is also closed. INPUT: - ``y`` -- a :class:`Polyhedron` OUTPUT: This method assigns the poly-hull to ``self`` and does not return anything. Raises a ``ValueError`` if ``self`` and and ``y`` are topology-incompatible or dimension-incompatible. Examples: >>> from ppl import Variable, C_Polyhedron, point, NNC_Polyhedron >>> x = Variable(0) >>> y = Variable(1) >>> p = C_Polyhedron( point(1*x+0*y) ) >>> p.poly_hull_assign(C_Polyhedron( point(0*x+1*y) )) >>> p.generators() Generator_System {point(0/1, 1/1), point(1/1, 0/1)} ``self`` and ``y`` must be dimension- and topology-compatible, or an exception is raised: >>> z = Variable(2) >>> p.poly_hull_assign( C_Polyhedron(z>=0) ) Traceback (most recent call last): ... ValueError: PPL::C_Polyhedron::poly_hull_assign(y): this->space_dimension() == 2, y.space_dimension() == 3. >>> p.poly_hull_assign( NNC_Polyhedron(x+y<1) ) Traceback (most recent call last): ... ValueError: PPL::C_Polyhedron::poly_hull_assign(y): y is a NNC_Polyhedron. """ sig_on() try: self.thisptr.poly_hull_assign(y.thisptr[0]) finally: sig_off() upper_bound_assign = poly_hull_assign def poly_difference_assign(self, Polyhedron y): r""" Assign to ``self`` the poly-difference of ``self`` and ``y``. For any pair of NNC polyhedra `P_1` and `P_2` the convex polyhedral difference (or poly-difference) of `P_1` and `P_2` is defined as the smallest convex polyhedron containing the set-theoretic difference `P_1\setminus P_2` of `P_1` and `P_2`. In general, even if `P_1` and `P_2` are topologically closed polyhedra, their poly-difference may be a convex polyhedron that is not topologically closed. For this reason, when computing the poly-difference of two :class:`C_Polyhedron`, the library will enforce the topological closure of the result. INPUT: - ``y`` -- a :class:`Polyhedron` OUTPUT: This method assigns the poly-difference to ``self`` and does not return anything. Raises a ``ValueError`` if ``self`` and and ``y`` are topology-incompatible or dimension-incompatible. Examples: >>> from ppl import Variable, C_Polyhedron, point, NNC_Polyhedron >>> x = Variable(0) >>> p = NNC_Polyhedron( point(0*x) ) >>> p.add_generator( point(1*x) ) >>> p.poly_difference_assign(NNC_Polyhedron( point(0*x) )) >>> p.minimized_constraints() Constraint_System {-x0+1>=0, x0>0} The poly-difference of :class:`C_polyhedron` is really its closure: >>> p = C_Polyhedron( point(0*x) ) >>> p.add_generator( point(1*x) ) >>> p.poly_difference_assign(C_Polyhedron( point(0*x) )) >>> p.minimized_constraints() Constraint_System {x0>=0, -x0+1>=0} ``self`` and ``y`` must be dimension- and topology-compatible, or an exception is raised: >>> y = Variable(1) >>> p.poly_difference_assign( C_Polyhedron(y>=0) ) Traceback (most recent call last): ... ValueError: PPL::C_Polyhedron::poly_difference_assign(y): this->space_dimension() == 1, y.space_dimension() == 2. >>> p.poly_difference_assign( NNC_Polyhedron(x+y<1) ) Traceback (most recent call last): ... ValueError: PPL::C_Polyhedron::poly_difference_assign(y): y is a NNC_Polyhedron. """ sig_on() try: self.thisptr.poly_difference_assign(y.thisptr[0]) finally: sig_off() difference_assign = poly_difference_assign def drop_some_non_integer_points(self): r""" Possibly tighten ``self`` by dropping some points with non-integer coordinates. The modified polyhedron satisfies: * it is (not necessarily strictly) contained in the original polyhedron. * integral vertices (generating points with integer coordinates) of the original polyhedron are not removed. .. note:: The modified polyhedron is not necessarily a lattice polyhedron; Some vertices will, in general, still be rational. Lattice points interior to the polyhedron may be lost in the process. Examples: >>> from ppl import Variable, NNC_Polyhedron, Constraint_System >>> x = Variable(0) >>> y = Variable(1) >>> cs = Constraint_System() >>> cs.insert( x>=0 ) >>> cs.insert( y>=0 ) >>> cs.insert( 3*x+2*y<5 ) >>> p = NNC_Polyhedron(cs) >>> p.minimized_generators() Generator_System {point(0/1, 0/1), closure_point(0/2, 5/2), closure_point(5/3, 0/3)} >>> p.drop_some_non_integer_points() >>> p.minimized_generators() Generator_System {point(0/1, 0/1), point(0/1, 2/1), point(4/3, 0/3)} """ sig_on() self.thisptr.drop_some_non_integer_points() sig_off() def topological_closure_assign(self): r""" Assign to ``self`` its topological closure. Examples: >>> from ppl import Variable, NNC_Polyhedron >>> x = Variable(0) >>> p = NNC_Polyhedron(x>0) >>> p.is_topologically_closed() False >>> p.topological_closure_assign() >>> p.is_topologically_closed() True >>> p.minimized_constraints() Constraint_System {x0>=0} """ sig_on() self.thisptr.topological_closure_assign() sig_off() def BHRZ03_widening_assign(self, Polyhedron y, unsigned tp = 0): r""" Assigns to ``self``` the result of computing the `BHRZ03-widening` between ``self`` and ``y``. INPUT: - ``y`` -- a :class:`Polyhedron` that must be contained in ``self`` - ``tp`` -- an optional unsigned variable with the number of available tokens (to be used when applying the `widening with tokens` delay technique). OUTPUT: This method assigns to ``self`` the result of computing the BHRZ03-widening between ``self`` and ``y``. And returns the new value of ``tp``. Raises a ``ValueError`` if ``self`` and ``y`` are topology-incompatible. Examples: >>> from ppl import NNC_Polyhedron, Variable >>> x = Variable(0) >>> y = Variable(1) >>> ph1 = NNC_Polyhedron(2) >>> ph1.add_constraint( y >= 0 ) >>> ph1.add_constraint( x + y > 0 ) >>> ph1.add_constraint( x - y < 1 ) >>> ph2 = NNC_Polyhedron(2) >>> ph2.add_constraint( y >= 0 ) >>> ph2.add_constraint( x > 0 ) >>> ph2.add_constraint( x < 1 ) >>> tp = ph1.BHRZ03_widening_assign( ph2 ) >>> known_result = NNC_Polyhedron(2) >>> known_result.add_constraint(y >= 0) >>> known_result == ph1 True >>> from ppl import C_Polyhedron, Generator_System, point, ray >>> gs1 = Generator_System() >>> gs1.insert(point()) >>> gs1.insert(point( x + 2 * y )) >>> gs1.insert(ray( x )) >>> gs1.insert(ray( 2 * x + y )) >>> ph1 = C_Polyhedron(gs1) >>> gs2 = Generator_System() >>> gs2.insert(point()) >>> gs2.insert(point( x + 2 * y )) >>> gs2.insert(ray( x )) >>> gs2.insert(ray( x + y )) >>> ph2 = C_Polyhedron( gs2 ) >>> tp = ph2.BHRZ03_widening_assign( ph1 ) >>> known_result = C_Polyhedron(2) >>> known_result.add_constraint( y >= 0 ) >>> known_result.add_constraint( 2 * x - y >= 0 ) >>> ph2 == known_result True if this method is going to be called too many times, the ``tp`` parameter allows one to reduce the computation cost by computing the widening only when ``tp`` is equal to 0, otherwise the this method will decrement the value of ``tp`` and return it. >>> from ppl import closure_point >>> gs1 = Generator_System() >>> gs1.insert(point( 2 * x )) >>> gs1.insert(closure_point( x + y )) >>> gs1.insert(closure_point( 3 * x + y )) >>> ph1 = NNC_Polyhedron(gs1) >>> gs2 = Generator_System() >>> gs2.insert(point( 2 * x )) >>> gs2.insert(closure_point( y )) >>> gs2.insert(closure_point( 4 * x + y )) >>> ph2 = NNC_Polyhedron(gs2) >>> ph2_copy = NNC_Polyhedron(ph2) >>> known_result = NNC_Polyhedron(2) >>> known_result.add_constraint(y >= 0) >>> known_result.add_constraint(y < 1) >>> tp = ph2.BHRZ03_widening_assign(ph1, 1) >>> tp == 0 True >>> ph2 == ph2_copy True >>> tp = ph2.BHRZ03_widening_assign(ph1, 0) >>> tp == 0 True >>> ph2 == known_result True """ sig_on() try: self.thisptr.BHRZ03_widening_assign(y.thisptr[0], &tp) finally: sig_off() return tp def limited_BHRZ03_extrapolation_assign(self, Polyhedron y, Constraint_System cs, unsigned tp = 0): r""" Assigns to ``self``` the result of computing the limited extrapolation between ``self`` and ``y`` using the `BHRZ03-widening` operator. INPUT: - ``y`` -- a :class:`Polyhedron` that must be contained in ``self`` - ``cs`` -- a :class:`Constraint_System` used to improve the widened polyhedron - ``tp`` -- an optional unsigned variable with the number of available tokens (to be used when applying the `widening with tokens` delay technique). OUTPUT: This method assigns to ``self`` the result of computing the limited extrapolation between ``self`` and ``y`` using the BHRZ03-widening operator. And returns the new value of ``tp``. Raises a ``ValueError`` if ``self`` and ``y`` are topology-incompatible or dimesion-incompatible. Examples: >>> from ppl import C_Polyhedron, Generator_System, Variable, point, Constraint_System >>> x = Variable(0) >>> y = Variable(1) >>> gs1 = Generator_System() >>> gs1.insert(point()) >>> gs1.insert(point( x + y )) >>> gs1.insert(point( x )) >>> ph1 = C_Polyhedron( gs1 ) >>> gs2 = Generator_System() >>> gs2.insert(point()) >>> gs2.insert(point( 2 * x )) >>> gs2.insert(point( 2 * x + 2 * y )) >>> ph2 = C_Polyhedron( gs2 ) >>> cs = Constraint_System() >>> cs.insert( x <= 5 ) >>> cs.insert( y <= 4 ) >>> tp = ph2.limited_BHRZ03_extrapolation_assign(ph1, cs) >>> known_result = C_Polyhedron(2) >>> known_result.add_constraint(y >= 0) >>> known_result.add_constraint(x - y >= 0) >>> known_result.add_constraint(y <= 4) >>> known_result.add_constraint(x <= 5) >>> known_result == ph2 True """ sig_on() try: self.thisptr.limited_BHRZ03_extrapolation_assign(y.thisptr[0], cs.thisptr[0], &tp) finally: sig_off() return tp def bounded_BHRZ03_extrapolation_assign(self, Polyhedron y, Constraint_System cs, unsigned tp = 0): r""" Assigns to ``self``` the result of computing the bounded extrapolation between ``self`` and ``y`` using the `BHRZ03-widening` operator. INPUT: - ``y`` -- a :class:`Polyhedron` that must be contained in ``self`` - ``cs`` -- a :class:`Constraint_System` used to improve the widened polyhedron - ``tp`` -- an optional unsigned variable with the number of available tokens (to be used when applying the `widening with tokens` delay technique). OUTPUT: This method assigns to ``self`` the result of computing the bounded extrapolation between ``self`` and ``y`` using the BHRZ03-widening operator. And returns the new value of ``tp``. Raises a ``ValueError`` if ``self`` and ``y`` are topology-incompatible or dimesion-incompatible. Examples: >>> from ppl import Variable, Constraint_System, C_Polyhedron >>> x = Variable(0) >>> ph1 = C_Polyhedron(1) >>> ph1.add_constraint( 1 <= x ) >>> ph1.add_constraint( x <= 2 ) >>> ph2 = C_Polyhedron(1) >>> ph2.add_constraint( 0 <= x ) >>> ph2.add_constraint( x <= 3 ) >>> cs = Constraint_System() >>> tp = ph2.bounded_BHRZ03_extrapolation_assign(ph1, cs) >>> known_result = C_Polyhedron(1) >>> known_result.add_constraint(0 <= x) >>> known_result == ph2 True """ sig_on() try: self.thisptr.bounded_BHRZ03_extrapolation_assign(y.thisptr[0], cs.thisptr[0], &tp) finally: sig_off() return tp def H79_widening_assign(self, Polyhedron y, unsigned tp = 0): r""" Assigns to ``self``` the result of computing the `H79-widening` between ``self`` and ``y``. INPUT: - ``y`` -- a :class:`Polyhedron` that must be contained in ``self`` - ``tp`` -- an optional unsigned variable with the number of available tokens (to be used when applying the `widening with tokens` delay technique). OUTPUT: This method assigns to ``self`` the result of computing the BHRZ03-widening between ``self`` and ``y``. And returns the new value of ``tp``. Raises a ``ValueError`` if ``self`` and ``y`` are topology-incompatible. Examples: >>> from ppl import Variable, C_Polyhedron >>> x = Variable(0) >>> y = Variable(1) >>> ph1 = C_Polyhedron(2) >>> ph1.add_constraint( x >= 2 ) >>> ph1.add_constraint( y >= 0 ) >>> ph2 = C_Polyhedron(2) >>> ph2.add_constraint( x >= 0 ) >>> ph2.add_constraint( y >= 0 ) >>> ph2.add_constraint( x-y >= 2 ) >>> tp = ph1.H79_widening_assign(ph2) >>> known_result = C_Polyhedron(2) >>> known_result.add_constraint(y >= 0) >>> known_result == ph1 True ``self`` and ``y`` must be dimension- and topology-compatible, or an exception is raised: >>> z = Variable(2) >>> ph1.H79_widening_assign( C_Polyhedron(z>=0) ) Traceback (most recent call last): ... ValueError: PPL::C_Polyhedron::H79_widening_assign(y): this->space_dimension() == 2, y.space_dimension() == 3. if this method is going to be called too many times, the ``tp`` parameter allows one to reduce the computation cost by computing the widening only when ``tp`` is equal to 0, otherwise the this method will decrement the value of ``tp`` and return it. >>> from ppl import point, ray, Generator_System >>> gs1 = Generator_System() >>> gs1.insert(point()) >>> gs1.insert(ray( x + y )) >>> gs1.insert(ray( x )) >>> ph1 = C_Polyhedron(gs1) >>> gs2 = Generator_System() >>> gs2.insert(point()) >>> gs2.insert(ray( x )) >>> gs2.insert(ray( x + 2 * y )) >>> ph2 = C_Polyhedron(gs2) >>> ph2_copy = C_Polyhedron(ph2) >>> known_result = C_Polyhedron(2) >>> known_result.add_constraint(y >= 0) >>> tp = ph2.H79_widening_assign(ph1, 1) >>> tp == 0 True >>> ph2 == ph2_copy True >>> tp = ph2.H79_widening_assign(ph1, 0) >>> tp == 0 True >>> ph2 == known_result True """ sig_on() try: self.thisptr.H79_widening_assign(y.thisptr[0], &tp) finally: sig_off() return tp widening_assign = H79_widening_assign def limited_H79_extrapolation_assign(self, Polyhedron y, Constraint_System cs, unsigned tp = 0): r""" Assigns to ``self``` the result of computing the limited extrapolation between ``self`` and ``y`` using the `H79-widening` operator. INPUT: - ``y`` -- a :class:`Polyhedron` that must be contained in ``self`` - ``cs`` -- a :class:`Constraint_System` used to improve the widened polyhedron - ``tp`` -- an optional unsigned variable with the number of available tokens (to be used when applying the `widening with tokens` delay technique). OUTPUT: This method assigns to ``self`` the result of computing the limited extrapolation between ``self`` and ``y`` using the H79-widening operator. And returns the new value of ``tp``. Raises a ``ValueError`` if ``self`` and ``y`` are topology-incompatible or dimesion-incompatible. Examples: >>> from ppl import Variable, C_Polyhedron, Constraint_System, point >>> x = Variable(0) >>> y = Variable(1) >>> ph1 = C_Polyhedron(2) >>> ph1.add_constraint( x >= 0 ) >>> ph1.add_constraint( x <= 1 ) >>> ph1.add_constraint( y >= 0 ) >>> ph1.add_constraint( x - y >= 0 ) >>> ph2 = C_Polyhedron(2) >>> ph2.add_constraint( x >= 0 ) >>> ph2.add_constraint( x <= 2 ) >>> ph2.add_constraint( y >= 0 ) >>> ph2.add_constraint( x - y >= 0 ) >>> cs = Constraint_System() >>> cs.insert( x >= 0 ) >>> cs.insert( y >= 0 ) >>> cs.insert( x <= 5 ) >>> cs.insert( y <= 5 ) >>> tp = ph2.limited_H79_extrapolation_assign(ph1, cs) >>> known_result = C_Polyhedron(2) >>> known_result.add_constraint( x - y >= 0) >>> known_result.add_constraint(y >= 0) >>> known_result.add_constraint(x <= 5) >>> known_result == ph2 True >>> ph1 = C_Polyhedron(2) >>> ph1.add_constraint( x >= 0 ) >>> ph1.add_constraint( x <= 1 ) >>> ph1.add_constraint( y == 0 ) >>> ph2 = C_Polyhedron(2) >>> ph2.add_constraint( x <= 2 ) >>> ph2.add_constraint( y >= 0 ) >>> ph2.add_constraint( y <= x ) >>> cs = Constraint_System() >>> cs.insert( x <= 5 ) >>> cs.insert( y <= -1 ) >>> known_result = C_Polyhedron(ph2) >>> known_result.add_generator(point(5*x)) >>> known_result.add_generator(point(5*x + 5*y)) >>> tp = ph2.limited_H79_extrapolation_assign(ph1, cs) >>> known_result == ph2 True """ sig_on() try: self.thisptr.limited_H79_extrapolation_assign(y.thisptr[0], cs.thisptr[0], &tp) finally: sig_off() return tp def bounded_H79_extrapolation_assign(self, Polyhedron y, Constraint_System cs, unsigned tp = 0): r""" Assigns to ``self``` the result of computing the bounded extrapolation between ``self`` and ``y`` using the `H79-widening` operator. INPUT: - ``y`` -- a :class:`Polyhedron` that must be contained in ``self`` - ``cs`` -- a :class:`Constraint_System` used to improve the widened polyhedron - ``tp`` -- an optional unsigned variable with the number of available tokens (to be used when applying the `widening with tokens` delay technique). OUTPUT: This method assigns to ``self`` the result of computing the bounded extrapolation between ``self`` and ``y`` using the H79-widening operator. And returns the new value of ``tp``. Raises a ``ValueError`` if ``self`` and ``y`` are topology-incompatible or dimesion-incompatible. Examples: >>> from ppl import Variable, C_Polyhedron, Constraint_System >>> x = Variable(0) >>> y = Variable(1) >>> ph1 = C_Polyhedron(2) >>> ph1.add_constraint( x-3 >= 0 ) >>> ph1.add_constraint( x-3 <= 1 ) >>> ph1.add_constraint( y >= 0 ) >>> ph1.add_constraint( y <= 1 ) >>> ph2 = C_Polyhedron(2) >>> ph2.add_constraint( 2*x-5 >= 0 ) >>> ph2.add_constraint( x-3 <= 1 ) >>> ph2.add_constraint( 2*y+3 >= 0 ) >>> ph2.add_constraint( 2*y-5 <= 0 ) >>> cs = Constraint_System() >>> cs.insert( x >= y ) >>> tp = ph2.bounded_H79_extrapolation_assign(ph1, cs) >>> known_result = C_Polyhedron(2) >>> known_result.add_constraint( x >= 2 ) >>> known_result.add_constraint( x <= 4 ) >>> known_result.add_constraint( y >= -2 ) >>> known_result.add_constraint( x >= y ) >>> known_result == ph2 True """ sig_on() try: self.thisptr.bounded_H79_extrapolation_assign(y.thisptr[0], cs.thisptr[0], &tp) finally: sig_off() return tp def add_space_dimensions_and_embed(self, m): r""" Add ``m`` new space dimensions and embed ``self`` in the new vector space. The new space dimensions will be those having the highest indexes in the new polyhedron, which is characterized by a system of constraints in which the variables running through the new dimensions are not constrained. For instance, when starting from the polyhedron `P` and adding a third space dimension, the result will be the polyhedron .. MATH:: \Big\{ (x,y,z)^T \in \mathbb{R}^3 \Big| (x,y)^T \in P \Big\} INPUT: - ``m`` -- integer. OUTPUT: This method assigns the embedded polyhedron to ``self`` and does not return anything. Raises a ``ValueError`` if adding ``m`` new space dimensions would cause the vector space to exceed dimension ``self.max_space_dimension()``. Examples: >>> from ppl import Variable, C_Polyhedron, point >>> x = Variable(0) >>> p = C_Polyhedron( point(3*x) ) >>> p.add_space_dimensions_and_embed(1) >>> p.minimized_generators() Generator_System {line(0, 1), point(3/1, 0/1)} >>> p.add_space_dimensions_and_embed( p.max_space_dimension() ) Traceback (most recent call last): ... ValueError: PPL::C_Polyhedron::add_space_dimensions_and_embed(m): adding m new space dimensions exceeds the maximum allowed space dimension. """ m = int(m) sig_on() try: self.thisptr.add_space_dimensions_and_embed(m) finally: sig_off() def add_space_dimensions_and_project(self, m): r""" Add ``m`` new space dimensions and embed ``self`` in the new vector space. The new space dimensions will be those having the highest indexes in the new polyhedron, which is characterized by a system of constraints in which the variables running through the new dimensions are all constrained to be equal to `0`. For instance, when starting from the polyhedron `P` and adding a third space dimension, the result will be the polyhedron .. MATH:: \Big\{ (x,y,0)^T \in \mathbb{R}^3 \Big| (x,y)^T \in P \Big\} INPUT: - ``m`` -- integer. OUTPUT: This method assigns the projected polyhedron to ``self`` and does not return anything. Raises a ``ValueError`` if adding ``m`` new space dimensions would cause the vector space to exceed dimension ``self.max_space_dimension()``. Examples: >>> from ppl import Variable, C_Polyhedron, point >>> x = Variable(0) >>> p = C_Polyhedron( point(3*x) ) >>> p.add_space_dimensions_and_project(1) >>> p.minimized_generators() Generator_System {point(3/1, 0/1)} >>> p.add_space_dimensions_and_project( p.max_space_dimension() ) Traceback (most recent call last): ... ValueError: PPL::C_Polyhedron::add_space_dimensions_and_project(m): adding m new space dimensions exceeds the maximum allowed space dimension. """ m = int(m) sig_on() try: self.thisptr.add_space_dimensions_and_project(m) finally: sig_off() def concatenate_assign(self, Polyhedron y): r""" Assign to ``self`` the concatenation of ``self`` and ``y``. This functions returns the Cartesian product of ``self`` and ``y``. Viewing a polyhedron as a set of tuples (its points), it is sometimes useful to consider the set of tuples obtained by concatenating an ordered pair of polyhedra. Formally, the concatenation of the polyhedra `P` and `Q` (taken in this order) is the polyhedron such that .. MATH:: R = \Big\{ (x_0,\dots,x_{n-1},y_0,\dots,y_{m-1})^T \in \mathbb{R}^{n+m} \Big| (x_0,\dots,x_{n-1})^T \in P ,~ (y_0,\dots,y_{m-1})^T \in Q \Big\} Another way of seeing it is as follows: first embed polyhedron `P` into a vector space of dimension `n+m` and then add a suitably renamed-apart version of the constraints defining `Q`. INPUT: - ``m`` -- integer. OUTPUT: This method assigns the concatenated polyhedron to ``self`` and does not return anything. Raises a ``ValueError`` if ``self`` and ``y`` are topology-incompatible or if adding ``y.space_dimension()`` new space dimensions would cause the vector space to exceed dimension ``self.max_space_dimension()``. Examples: >>> from ppl import Variable, C_Polyhedron, NNC_Polyhedron, point >>> x = Variable(0) >>> p1 = C_Polyhedron( point(1*x) ) >>> p2 = C_Polyhedron( point(2*x) ) >>> p1.concatenate_assign(p2) >>> p1.minimized_generators() Generator_System {point(1/1, 2/1)} The polyhedra must be topology-compatible and not exceed the maximum space dimension: >>> p1.concatenate_assign( NNC_Polyhedron(1, 'universe') ) Traceback (most recent call last): ... ValueError: PPL::C_Polyhedron::concatenate_assign(y): y is a NNC_Polyhedron. >>> p1.concatenate_assign( C_Polyhedron(p1.max_space_dimension(), 'empty') ) Traceback (most recent call last): ... ValueError: PPL::C_Polyhedron::concatenate_assign(y): concatenation exceeds the maximum allowed space dimension. """ sig_on() try: self.thisptr.concatenate_assign(y.thisptr[0]) finally: sig_off() def remove_higher_space_dimensions(self, new_dimension): r""" Remove the higher dimensions of the vector space so that the resulting space will have dimension ``new_dimension``. OUTPUT: This method modifies ``self`` and does not return anything. Raises a ``ValueError`` if ``new_dimensions`` is greater than the space dimension of ``self``. Examples: >>> from ppl import C_Polyhedron, Variable >>> x = Variable(0) >>> y = Variable(1) >>> p = C_Polyhedron(3*x+0*y==2) >>> p.remove_higher_space_dimensions(1) >>> p.minimized_constraints() Constraint_System {3*x0-2==0} >>> p.remove_higher_space_dimensions(2) Traceback (most recent call last): ... ValueError: PPL::C_Polyhedron::remove_higher_space_dimensions(nd): this->space_dimension() == 1, required space dimension == 2. """ new_dimension = int(new_dimension) sig_on() try: self.thisptr.remove_higher_space_dimensions(new_dimension) finally: sig_off() def affine_image(self, Variable v, Linear_Expression le): r""" Set this polyhedron to the image of the map `v -> le` INPUT: - ``v`` -- a variable - ``le`` -- a linear expression Examples: >>> import ppl >>> x = ppl.Variable(0) >>> y = ppl.Variable(1) >>> gs0 = ppl.Generator_System() >>> gs0.insert(ppl.point()) >>> gs0.insert(ppl.point(x)) >>> gs0.insert(ppl.point(y)) >>> gs0.insert(ppl.point(x+y)) >>> p0 = ppl.C_Polyhedron(gs0) >>> gs1 = ppl.Generator_System() >>> gs1.insert(ppl.point()) >>> gs1.insert(ppl.point(x)) >>> gs1.insert(ppl.point(x+y)) >>> gs1.insert(ppl.point(2*x+y)) >>> p1 = ppl.C_Polyhedron(gs1) >>> p0 == p1 False >>> p0.affine_image(x, x+y) >>> p0 == p1 True """ self.thisptr.affine_image(v.thisptr[0], le.thisptr[0]) def affine_preimage(self, Variable v, Linear_Expression le): r""" Set this polyhedron to the preimage of the map `v -> le` INPUT: - ``v`` -- a variable - ``le`` -- a linear expression Examples: >>> import ppl >>> x = ppl.Variable(0) >>> y = ppl.Variable(1) >>> gs0 = ppl.Generator_System() >>> gs0.insert(ppl.point()) >>> gs0.insert(ppl.point(x)) >>> gs0.insert(ppl.point(y)) >>> gs0.insert(ppl.point(x+y)) >>> p0 = ppl.C_Polyhedron(gs0) >>> gs1 = ppl.Generator_System() >>> gs1.insert(ppl.point()) >>> gs1.insert(ppl.point(x)) >>> gs1.insert(ppl.point(x+y)) >>> gs1.insert(ppl.point(2*x+y)) >>> p1 = ppl.C_Polyhedron(gs1) >>> p0 == p1 False >>> p1.affine_preimage(x, x+y) >>> p0 == p1 True """ self.thisptr.affine_preimage(v.thisptr[0], le.thisptr[0]) def ascii_dump(self): r""" Write an ASCII dump to stderr. Examples: >>> cmd = 'from ppl import C_Polyhedron, Variable\n' >>> cmd += 'x = Variable(0)\n' >>> cmd += 'y = Variable(1)\n' >>> cmd += 'p = C_Polyhedron(3*x+2*y==1)\n' >>> cmd += 'p.minimized_generators()\n' >>> cmd += 'p.ascii_dump()\n' >>> from subprocess import Popen, PIPE >>> import sys >>> proc = Popen([sys.executable, '-c', cmd], stdout=PIPE, stderr=PIPE) >>> out, err = proc.communicate() >>> len(out) 0 >>> print(str(err.decode('ascii'))) space_dim 2 ... con_sys (up-to-date) topology NECESSARILY_CLOSED ... sat_c 0 x 0 sat_g 2 x 2 0 0 0 1 """ sig_on() self.thisptr.ascii_dump() sig_off() def max_space_dimension(self): r""" Return the maximum space dimension all kinds of Polyhedron can handle. OUTPUT: Integer. Examples: >>> from ppl import C_Polyhedron >>> C_Polyhedron(1, 'empty').max_space_dimension() > 2**20 True """ return self.thisptr.max_space_dimension() def hash_code(self): r""" Return a hash code Tests: >>> from ppl import Constraint_System, Variable, C_Polyhedron >>> x = Variable(0) >>> p = C_Polyhedron( 5*x >= 3 ) >>> p.hash_code() 1 >>> y = Variable(1) >>> cs = Constraint_System() >>> cs.insert( x >= 0 ) >>> cs.insert( y >= 0 ) >>> p = C_Polyhedron(cs) >>> p.hash_code() 2 """ return self.thisptr[0].hash_code() def __richcmp__(Polyhedron lhs, Polyhedron rhs, int op): r""" Comparison for polyhedra. INPUT: - ``lhs``, ``rhs`` -- :class:`Polyhedron`. - ``op`` -- integer. The comparison operation to be performed. OUTPUT: Boolean. Examples: >>> from ppl import Variable, C_Polyhedron >>> x = Variable(0) >>> C_Polyhedron(x >= 0) > C_Polyhedron(x >= 1) True """ cdef result sig_on() if op == Py_LT: # < 0 result = rhs.strictly_contains(lhs) elif op == Py_LE: # <= 1 result = rhs.contains(lhs) elif op == Py_EQ: # == 2 result = (lhs.thisptr[0] == rhs.thisptr[0]) elif op == Py_GT: # > 4 result = lhs.strictly_contains(rhs) elif op == Py_GE: # >= 5 result = lhs.contains(rhs) elif op == Py_NE: # != 3 result = (lhs.thisptr[0] != rhs.thisptr[0]) else: raise RuntimeError # unreachable sig_off() return result #################################################### ### C_Polyhedron ################################### #################################################### cdef class C_Polyhedron(Polyhedron): r""" Wrapper for PPL's ``C_Polyhedron`` class. An object of the class :class:`C_Polyhedron` represents a topologically closed convex polyhedron in the vector space. See :class:`NNC_Polyhedron` for more general (not necessarily closed) polyhedra. When building a closed polyhedron starting from a system of constraints, an exception is thrown if the system contains a strict inequality constraint. Similarly, an exception is thrown when building a closed polyhedron starting from a system of generators containing a closure point. INPUT: - ``arg`` -- the defining data of the polyhedron. Any one of the following is accepted: * A non-negative integer. Depending on ``degenerate_element``, either the space-filling or the empty polytope in the given dimension ``arg`` is constructed. * A :class:`Constraint_System`. * A :class:`Generator_System`. * A single :class:`Constraint`. * A single :class:`Generator`. * A :class:`C_Polyhedron`. - ``degenerate_element`` -- string, either ``'universe'`` or ``'empty'``. Only used if ``arg`` is an integer. OUTPUT: A :class:`C_Polyhedron`. Examples: >>> from ppl import Constraint_System, Generator_System, Variable, C_Polyhedron, point, ray >>> x = Variable(0) >>> y = Variable(1) >>> C_Polyhedron( 5*x-2*y >= x+y-1 ) A 2-dimensional polyhedron in QQ^2 defined as the convex hull of 1 point, 1 ray, 1 line >>> cs = Constraint_System() >>> cs.insert( x >= 0 ) >>> cs.insert( y >= 0 ) >>> C_Polyhedron(cs) A 2-dimensional polyhedron in QQ^2 defined as the convex hull of 1 point, 2 rays >>> C_Polyhedron( point(x+y) ) A 0-dimensional polyhedron in QQ^2 defined as the convex hull of 1 point >>> gs = Generator_System() >>> gs.insert( point(-x-y) ) >>> gs.insert( ray(x) ) >>> C_Polyhedron(gs) A 1-dimensional polyhedron in QQ^2 defined as the convex hull of 1 point, 1 ray The empty and universe polyhedra are constructed like this: >>> C_Polyhedron(3, 'empty') The empty polyhedron in QQ^3 >>> C_Polyhedron(3, 'empty').constraints() Constraint_System {-1==0} >>> C_Polyhedron(3, 'universe') The space-filling polyhedron in QQ^3 >>> C_Polyhedron(3, 'universe').constraints() Constraint_System {} Note that, by convention, the generator system of a polyhedron is either empty or contains at least one point. In particular, if you define a polyhedron via a non-empty :class:`Generator_System` it must contain a point (at any position). If you start with a single generator, this generator must be a point: >>> C_Polyhedron( ray(x) ) Traceback (most recent call last): ... ValueError: PPL::C_Polyhedron::C_Polyhedron(gs): *this is an empty polyhedron and the non-empty generator system gs contains no points. """ def __cinit__(self, arg, degenerate_element='universe'): """ The Cython constructor. See :class:`C_Polyhedron` for documentation. Tests: >>> from ppl import C_Polyhedron >>> C_Polyhedron(3, 'empty') # indirect doctest The empty polyhedron in QQ^3 """ if isinstance(arg, C_Polyhedron): ph = arg self.thisptr = new PPL_C_Polyhedron(ph.thisptr[0]) return if isinstance(arg, Generator): arg = Generator_System(arg) if isinstance(arg, Constraint): arg = Constraint_System(arg) if isinstance(arg, Generator_System): gs = arg self.thisptr = new PPL_C_Polyhedron(gs.thisptr[0]) return if isinstance(arg, Constraint_System): cs = arg self.thisptr = new PPL_C_Polyhedron(cs.thisptr[0]) return try: dim = int(arg) assert dim>=0 except ValueError: raise ValueError('Cannot initialize C_Polyhedron with '+str(arg)+'.') degenerate_element = degenerate_element.lower() if degenerate_element=='universe': self.thisptr = new PPL_C_Polyhedron(dim, UNIVERSE) return elif degenerate_element=='empty': self.thisptr = new PPL_C_Polyhedron(dim, EMPTY) return else: raise ValueError('Unknown value: degenerate_element='+str(degenerate_element)+'.') def __init__(self, *args): """ The Python destructor. See :class:`C_Polyhedron` for documentation. Tests: >>> from ppl import C_Polyhedron >>> C_Polyhedron(3, 'empty') # indirect doctest The empty polyhedron in QQ^3 """ # override Polyhedron.__init__ pass def __dealloc__(self): """ The Cython destructor. """ del self.thisptr def __reduce__(self): """ Pickle object Tests: >>> from ppl import C_Polyhedron, Variable >>> from pickle import loads, dumps >>> P = C_Polyhedron(3, 'empty') >>> loads(dumps(P)) The empty polyhedron in QQ^3 >>> Q = C_Polyhedron(5, 'universe') >>> loads(dumps(Q)) The space-filling polyhedron in QQ^5 >>> x = Variable(0) >>> y = Variable(1) >>> H = C_Polyhedron( 5*x-2*y >= x+y-1 ) >>> loads(dumps(H)) A 2-dimensional polyhedron in QQ^2 defined as the convex hull of 1 point, 1 ray, 1 line """ if self.is_empty(): return (C_Polyhedron, (self.space_dimension(), 'empty')) elif self.is_universe(): return (C_Polyhedron, (self.space_dimension(), 'universe')) else: return (C_Polyhedron, (self.generators(),)) #################################################### ### NNC_Polyhedron ################################### #################################################### cdef class NNC_Polyhedron(Polyhedron): r""" Wrapper for PPL's ``NNC_Polyhedron`` class. An object of the class ``NNC_Polyhedron`` represents a not necessarily closed (NNC) convex polyhedron in the vector space. Note: Since NNC polyhedra are a generalization of closed polyhedra, any object of the class :class:`C_Polyhedron` can be (explicitly) converted into an object of the class :class:`NNC_Polyhedron`. The reason for defining two different classes is that objects of the class :class:`C_Polyhedron` are characterized by a more efficient implementation, requiring less time and memory resources. INPUT: - ``arg`` -- the defining data of the polyhedron. Any one of the following is accepted: * An non-negative integer. Depending on ``degenerate_element``, either the space-filling or the empty polytope in the given dimension ``arg`` is constructed. * A :class:`Constraint_System`. * A :class:`Generator_System`. * A single :class:`Constraint`. * A single :class:`Generator`. * A :class:`NNC_Polyhedron`. * A :class:`C_Polyhedron`. - ``degenerate_element`` -- string, either ``'universe'`` or ``'empty'``. Only used if ``arg`` is an integer. OUTPUT: A :class:`C_Polyhedron`. Examples: >>> from ppl import Constraint, Constraint_System, Generator, Generator_System, Variable, NNC_Polyhedron, point, ray, closure_point >>> x = Variable(0) >>> y = Variable(1) >>> NNC_Polyhedron( 5*x-2*y > x+y-1 ) A 2-dimensional polyhedron in QQ^2 defined as the convex hull of 1 point, 1 closure_point, 1 ray, 1 line >>> cs = Constraint_System() >>> cs.insert( x > 0 ) >>> cs.insert( y > 0 ) >>> NNC_Polyhedron(cs) A 2-dimensional polyhedron in QQ^2 defined as the convex hull of 1 point, 1 closure_point, 2 rays >>> NNC_Polyhedron( point(x+y) ) A 0-dimensional polyhedron in QQ^2 defined as the convex hull of 1 point >>> gs = Generator_System() >>> gs.insert( point(-y) ) >>> gs.insert( closure_point(-x-y) ) >>> gs.insert( ray(x) ) >>> p = NNC_Polyhedron(gs); p A 1-dimensional polyhedron in QQ^2 defined as the convex hull of 1 point, 1 closure_point, 1 ray >>> p.minimized_constraints() Constraint_System {x1+1==0, x0+1>0} Note that, by convention, every polyhedron must contain a point: >>> NNC_Polyhedron( closure_point(x+y) ) Traceback (most recent call last): ... ValueError: PPL::NNC_Polyhedron::NNC_Polyhedron(gs): *this is an empty polyhedron and the non-empty generator system gs contains no points. """ def __cinit__(self, arg, degenerate_element='universe'): """ The Cython constructor. See :class:`NNC_Polyhedron` for documentation. Tests: >>> from ppl import NNC_Polyhedron >>> NNC_Polyhedron(3, 'empty') # indirect doctest The empty polyhedron in QQ^3 """ if isinstance(arg, NNC_Polyhedron): p_nnc = arg self.thisptr = new PPL_NNC_Polyhedron(p_nnc.thisptr[0]) return if isinstance(arg, C_Polyhedron): p_c = arg self.thisptr = new PPL_NNC_Polyhedron(p_c.thisptr[0]) return if isinstance(arg, Generator): arg = Generator_System(arg) if isinstance(arg, Constraint): arg = Constraint_System(arg) if isinstance(arg, Generator_System): gs = arg self.thisptr = new PPL_NNC_Polyhedron(gs.thisptr[0]) return if isinstance(arg, Constraint_System): cs = arg self.thisptr = new PPL_NNC_Polyhedron(cs.thisptr[0]) return try: dim = int(arg) assert dim>=0 except ValueError: raise ValueError('Cannot initialize NNC_Polyhedron with '+str(arg)+'.') degenerate_element = degenerate_element.lower() if degenerate_element=='universe': self.thisptr = new PPL_NNC_Polyhedron(dim, UNIVERSE) return elif degenerate_element=='empty': self.thisptr = new PPL_NNC_Polyhedron(dim, EMPTY) return else: raise ValueError('Unknown value: degenerate_element='+str(degenerate_element)+'.') def __init__(self, *args): """ The Python destructor. See :class:`NNC_Polyhedron` for documentation. Tests: >>> from ppl import NNC_Polyhedron >>> NNC_Polyhedron(3, 'empty') # indirect doctest The empty polyhedron in QQ^3 """ # override Polyhedron.__init__ pass def __dealloc__(self): """ The Cython destructor. """ del self.thisptr def __reduce__(self): """ Pickle object Tests: >>> from ppl import NNC_Polyhedron, Variable >>> from pickle import loads, dumps >>> P = NNC_Polyhedron(3, 'empty') >>> loads(dumps(P)) The empty polyhedron in QQ^3 >>> Q = NNC_Polyhedron(5, 'universe') >>> loads(dumps(Q)) The space-filling polyhedron in QQ^5 >>> x = Variable(0) >>> y = Variable(1) >>> H = NNC_Polyhedron( 5*x-2*y > x+y-1 ) >>> loads(dumps(H)) A 2-dimensional polyhedron in QQ^2 defined as the convex hull of 1 point, 1 closure_point, 1 ray, 1 line """ if self.is_empty(): return (NNC_Polyhedron, (self.space_dimension(), 'empty')) elif self.is_universe(): return (NNC_Polyhedron, (self.space_dimension(), 'universe')) else: return (NNC_Polyhedron, (self.generators(),)) pplpy-0.8.9/ppl/ppl_decl.pxd000066400000000000000000000517421447517221400160060ustar00rootroot00000000000000from libcpp cimport bool as cppbool from libcpp.vector cimport vector as cppvector cdef extern from "gmp.h": # gmp integer ctypedef struct __mpz_struct: pass ctypedef __mpz_struct mpz_t[1] ctypedef __mpz_struct *mpz_ptr ctypedef const __mpz_struct *mpz_srcptr void mpz_init(mpz_t) cdef extern from "gmpxx.h": # gmp integer cdef cppclass mpz_class: mpz_class() mpz_class(int i) mpz_class(mpz_t z) mpz_class(mpz_class) mpz_t get_mpz_t() mpz_class operator%(mpz_class, mpz_class) cdef extern from "ppl.hh" namespace "Parma_Polyhedra_Library::Generator": ctypedef enum PPL_GeneratorType "Parma_Polyhedra_Library::Generator::Type": LINE, RAY, POINT, CLOSURE_POINT cdef extern from "ppl.hh" namespace "Parma_Polyhedra_Library::Constraint": ctypedef enum PPL_ConstraintType "Parma_Polyhedra_Library::Constraint::Type": EQUALITY, NONSTRICT_INEQUALITY, STRICT_INEQUALITY cdef extern from "ppl.hh" namespace "Parma_Polyhedra_Library::MIP_Problem": ctypedef enum PPL_MIP_Problem_Control_Parameter_Name: PRICING ctypedef enum PPL_MIP_Problem_Control_Parameter_Value: PRICING_STEEPEST_EDGE_FLOAT, PRICING_STEEPEST_EDGE_EXACT, PRICING_TEXTBOOK cdef extern from "ppl.hh" namespace "Parma_Polyhedra_Library": ctypedef size_t PPL_dimension_type "Parma_Polyhedra_Library::dimension_type" ctypedef mpz_class PPL_Coefficient "Parma_Polyhedra_Library::Coefficient" cdef cppclass PPL_Variable "Parma_Polyhedra_Library::Variable" cdef cppclass PPL_Variables_Set "Parma_Polyhedra_Library::Variables_Set" cdef cppclass PPL_Linear_Expression "Parma_Polyhedra_Library::Linear_Expression" cdef cppclass PPL_Generator "Parma_Polyhedra_Library::Generator" cdef cppclass PPL_Generator_System "Parma_Polyhedra_Library::Generator_System" cdef cppclass PPL_Constraint "Parma_Polyhedra_Library::Constraint" cdef cppclass PPL_Constraint_System "Parma_Polyhedra_Library::Constraint_System" cdef cppclass PPL_Congruence "Parma_Polyhedra_Library::Congruence" cdef cppclass PPL_Congruence_System "Parma_Polyhedra_Library::Congruence_System" cdef cppclass PPL_Polyhedron "Parma_Polyhedra_Library::Polyhedron" cdef cppclass PPL_C_Polyhedron "Parma_Polyhedra_Library::C_Polyhedron" (PPL_Polyhedron) cdef cppclass PPL_NNC_Polyhedron "Parma_Polyhedra_Library::NNC_Polyhedron" (PPL_Polyhedron) cdef cppclass PPL_Poly_Gen_Relation "Parma_Polyhedra_Library::Poly_Gen_Relation" cdef cppclass PPL_Poly_Con_Relation "Parma_Polyhedra_Library::Poly_Con_Relation" cdef cppclass PPL_MIP_Problem "Parma_Polyhedra_Library::MIP_Problem" cdef cppclass PPL_mip_iterator "Parma_Polyhedra_Library::MIP_Problem::const_iterator" cdef cppclass PPL_gs_iterator "Parma_Polyhedra_Library::Generator_System::const_iterator" cdef cppclass PPL_Constraint_System_iterator "Parma_Polyhedra_Library::Constraint_System::const_iterator" cdef cppclass PPL_Congruence_System_iterator "Parma_Polyhedra_Library::Congruence_System::const_iterator" cdef cppclass PPL_Bit_Row "Parma_Polyhedra_Library::Bit_Row" cdef cppclass PPL_Bit_Matrix "Parma_Polyhedra_Library::Bit_Matrix" cdef cppclass PPL_Variable: PPL_Variable(PPL_dimension_type i) PPL_dimension_type id() PPL_dimension_type space_dimension() cdef cppclass PPL_Variables_Set: PPL_Variables_Set() PPL_Variables_Set(PPL_Variable v) PPL_Variables_Set(PPL_Variable v, PPL_Variable w) PPL_dimension_type space_dimension() void insert(PPL_Variable v) size_t size() void ascii_dump() # class Parma_Polyhedra_Library::Linear_Expression # lines 28238-28879 of ppl.hh cdef cppclass PPL_Linear_Expression: PPL_Linear_Expression() PPL_Linear_Expression(PPL_Linear_Expression &e) PPL_Linear_Expression(PPL_Coefficient n) PPL_Linear_Expression(PPL_Variable v) PPL_dimension_type max_space_dimension() PPL_dimension_type space_dimension() void set_space_dimension(PPL_dimension_type d) PPL_Coefficient coefficient(PPL_Variable v) void set_coefficient(PPL_Variable v, PPL_Coefficient) PPL_Coefficient inhomogeneous_term() void set_inhomogeneous_term(PPL_Coefficient n) void linear_combine(const PPL_Linear_Expression& y, PPL_Variable v) void linear_combine(const PPL_Linear_Expression& y, PPL_Coefficient c1, PPL_Coefficient c2) void linear_combine_lax(const PPL_Linear_Expression& u, PPL_Coefficient c1, PPL_Coefficient c2) void swap_space_dimensions(PPL_Variable v1, PPL_Variable v2) void remove_space_dimensions(const PPL_Variables_Set) void shift_space_dimensions(PPL_Variable v, PPL_dimension_type n) void permute_space_dimensions(const cppvector[PPL_Variable]& cycle) except +ValueError bint is_zero() bint all_homogeneous_terms_are_zero() bint is_equal_to(PPL_Linear_Expression& x) bint all_zeroes(const PPL_Variables_Set& v) void ascii_dump() #PPL_Linear_Expression operator+=(PPL_Linear_Expression& e) #PPL_Linear_Expression operator-=(PPL_Linear_Expression& e) #PPL_Linear_Expression operator*=(PPL_Coefficient n) #PPL_Linear_Expression operator/=(PPL_Coefficient n) PPL_Linear_Expression operator+(PPL_Linear_Expression& e) PPL_Linear_Expression operator-(PPL_Linear_Expression& e) PPL_Linear_Expression operator*(PPL_Coefficient n) PPL_Constraint operator> (PPL_Linear_Expression& e) PPL_Constraint operator>=(PPL_Linear_Expression& e) PPL_Constraint operator==(PPL_Linear_Expression& e) PPL_Constraint operator<=(PPL_Linear_Expression& e) PPL_Constraint operator< (PPL_Linear_Expression& e) cdef cppclass PPL_Constraint: PPL_Constraint() PPL_Constraint(PPL_Constraint &g) PPL_dimension_type space_dimension() PPL_ConstraintType type() bint is_equality() bint is_inequality() bint is_nonstrict_inequality() bint is_strict_inequality() PPL_Coefficient coefficient(PPL_Variable v) PPL_Coefficient inhomogeneous_term() bint is_tautological() bint is_inconsistent() bint is_equivalent_to(PPL_Constraint &y) void ascii_dump() void permute_space_dimensions(const cppvector[PPL_Variable]& cycle) except +ValueError cdef cppclass PPL_Generator: PPL_Generator(PPL_Generator &g) PPL_dimension_type space_dimension() void set_space_dimension(PPL_dimension_type n) PPL_GeneratorType type() bint is_line() bint is_ray() bint is_line_or_ray() bint is_point() bint is_closure_point() PPL_Coefficient coefficient(PPL_Variable v) PPL_Coefficient divisor() except + bint is_equivalent_to(PPL_Generator &y) void ascii_dump() void permute_space_dimensions(const cppvector[PPL_Variable]& cycle) except +ValueError cdef cppclass PPL_Congruence: PPL_Congruence() PPL_Congruence(const PPL_Congruence &g) PPL_Congruence(const PPL_Constraint &c) except +ValueError PPL_dimension_type space_dimension() # NOTE: curiously, this can raise an error (behavior different from Linear_Expression) PPL_Coefficient coefficient(PPL_Variable v) except +ValueError PPL_Coefficient inhomogeneous_term() PPL_Coefficient modulus() void set_modulus(PPL_Coefficient& m) void scale(PPL_Coefficient& m) bint is_tautological() bint is_inconsistent() bint is_proper_congruence() bint is_equality() void ascii_dump() void swap_space_dimension(PPL_Variable v1, PPL_Variable v2) void set_space_dimension(PPL_dimension_type n) void shift_space_dimensions(PPL_Variable v, PPL_dimension_type n) void sign_normalize() void normalize() void strong_normalize() PPL_dimension_type max_space_dimension() cppbool operator==(const PPL_Congruence &x, const PPL_Congruence &y) cppbool operator!=(const PPL_Congruence &x, const PPL_Congruence &y) cdef cppclass PPL_Congruence_System: PPL_Congruence_System() PPL_Congruence_System(PPL_Congruence &c) PPL_Congruence_System(PPL_Congruence_System &cs) PPL_dimension_type space_dimension() PPL_Congruence_System_iterator begin() PPL_Congruence_System_iterator end() bint has_equalities() bint has_strict_inequalities() void clear() void insert(PPL_Congruence &g) bint empty() void ascii_dump() cdef cppclass PPL_Congruence_System_iterator: PPL_Congruence_System_iterator() PPL_Congruence_System_iterator(PPL_Congruence_System_iterator &csi) PPL_Congruence& operator* () PPL_Congruence_System_iterator inc "operator++" (int i) cppbool operator==(PPL_Congruence_System_iterator& y) cppbool operator!=(PPL_Congruence_System_iterator& y) cdef cppclass PPL_Generator_System: PPL_Generator_System() PPL_Generator_System(PPL_Generator &g) PPL_Generator_System(PPL_Generator_System &gs) PPL_dimension_type space_dimension() void set_space_dimension(PPL_dimension_type space_dim) PPL_gs_iterator begin() PPL_gs_iterator end() void clear() void insert(PPL_Generator &g) bint empty() void ascii_dump() cdef cppclass PPL_mip_iterator: PPL_mip_iterator(PPL_mip_iterator &mipi) PPL_Constraint& operator* () PPL_mip_iterator inc "operator++" (int i) cppbool operator==(PPL_mip_iterator& y) cppbool operator!=(PPL_mip_iterator& y) cdef cppclass PPL_gs_iterator: PPL_gs_iterator() PPL_gs_iterator(PPL_gs_iterator &gsi) PPL_Generator& operator* () PPL_gs_iterator inc "operator++" (int i) cppbool operator==(PPL_gs_iterator& y) cppbool operator!=(PPL_gs_iterator& y) cdef cppclass PPL_Constraint_System_iterator: PPL_Constraint_System_iterator() PPL_Constraint_System_iterator(PPL_Constraint_System_iterator &csi) PPL_Constraint& operator* () PPL_Constraint_System_iterator inc "operator++" (int i) cppbool operator==(PPL_Constraint_System_iterator& y) cppbool operator!=(PPL_Constraint_System_iterator& y) cdef cppclass PPL_Constraint_System: PPL_Constraint_System() PPL_Constraint_System(PPL_Constraint &g) PPL_Constraint_System(PPL_Constraint_System &gs) PPL_dimension_type space_dimension() PPL_Constraint_System_iterator begin() PPL_Constraint_System_iterator end() bint has_equalities() bint has_strict_inequalities() void clear() void insert(PPL_Constraint &g) bint empty() void ascii_dump() cdef enum PPL_Degenerate_Element "Parma_Polyhedra_Library::Degenerate_Element": UNIVERSE, EMPTY cdef enum PPL_Optimization_Mode "Parma_Polyhedra_Library::Optimization_Mode": MINIMIZATION, MAXIMIZATION cdef enum PPL_MIP_Problem_Status "Parma_Polyhedra_Library::MIP_Problem_Status": UNFEASIBLE_MIP_PROBLEM, UNBOUNDED_MIP_PROBLEM, OPTIMIZED_MIP_PROBLEM cdef cppclass PPL_Polyhedron: PPL_dimension_type space_dimension() PPL_dimension_type affine_dimension() PPL_Constraint_System& constraints() PPL_Constraint_System& minimized_constraints() PPL_Generator_System& generators() PPL_Generator_System& minimized_generators() PPL_Poly_Con_Relation relation_with(PPL_Constraint &c) except +ValueError PPL_Poly_Gen_Relation relation_with(PPL_Generator &g) except +ValueError bint is_empty() bint is_universe() bint is_topologically_closed() bint is_disjoint_from(PPL_Polyhedron &y) except +ValueError bint is_discrete() bint is_bounded() bint contains_integer_point() bint constrains(PPL_Variable var) except +ValueError bint bounds_from_above(PPL_Linear_Expression &expr) except +ValueError bint bounds_from_below(PPL_Linear_Expression &expr) except +ValueError bint maximize(PPL_Linear_Expression &expr, PPL_Coefficient &sup_n, PPL_Coefficient &sup_d, cppbool &maximum) bint maximize(PPL_Linear_Expression &expr, PPL_Coefficient &sup_n, PPL_Coefficient &sup_d, cppbool &maximum, PPL_Generator &g) bint minimize(PPL_Linear_Expression &expr, PPL_Coefficient &inf_n, PPL_Coefficient &inf_d, cppbool &minimum) bint minimize(PPL_Linear_Expression &expr, PPL_Coefficient &inf_n, PPL_Coefficient &inf_d, cppbool &minimum, PPL_Generator &g) bint frequency(PPL_Linear_Expression &expr, PPL_Coefficient &freq_n, PPL_Coefficient &freq_d, PPL_Coefficient &val_n, PPL_Coefficient &val_d) bint contains(PPL_Polyhedron &y) except +ValueError bint strictly_contains(PPL_Polyhedron &y) except +ValueError void add_constraint(PPL_Constraint &c) except +ValueError void add_generator(PPL_Generator &g) except +ValueError void add_constraints(PPL_Constraint_System &cs) except +ValueError void add_generators(PPL_Generator_System &gs) except +ValueError void refine_with_constraint(PPL_Constraint &c) except +ValueError void refine_with_constraints(PPL_Constraint_System &cs) except +ValueError void unconstrain(PPL_Variable var) except +ValueError void intersection_assign(PPL_Polyhedron &y) except +ValueError void poly_hull_assign(PPL_Polyhedron &y) except +ValueError void upper_bound_assign(PPL_Polyhedron &y) except +ValueError void poly_difference_assign(PPL_Polyhedron &y) except +ValueError void difference_assign(PPL_Polyhedron &y) except +ValueError void drop_some_non_integer_points() void topological_closure_assign() void BHRZ03_widening_assign(PPL_Polyhedron &y, unsigned* tp) except +ValueError void limited_BHRZ03_extrapolation_assign(PPL_Polyhedron &y, PPL_Constraint_System &cs, unsigned* tp) except +ValueError void bounded_BHRZ03_extrapolation_assign(PPL_Polyhedron &y, PPL_Constraint_System &cs, unsigned* tp) except +ValueError void H79_widening_assign(PPL_Polyhedron &y, unsigned* tp) except +ValueError void widening_assign(PPL_Polyhedron &y, unsigned* tp) except +ValueError void limited_H79_extrapolation_assign(PPL_Polyhedron &y, PPL_Constraint_System &cs, unsigned* tp) except +ValueError void bounded_H79_extrapolation_assign(PPL_Polyhedron &y, PPL_Constraint_System &cs, unsigned* tp) except +ValueError void add_space_dimensions_and_embed(PPL_dimension_type m) except +ValueError void add_space_dimensions_and_project(PPL_dimension_type m) except +ValueError void concatenate_assign(PPL_Polyhedron &y) except +ValueError void remove_higher_space_dimensions(PPL_dimension_type new_dimension) except +ValueError void affine_image(const PPL_Variable, const PPL_Linear_Expression& expr) except +ValueError void affine_preimage(const PPL_Variable, const PPL_Linear_Expression& expr) except +ValueError void ascii_dump() int hash_code() PPL_dimension_type max_space_dimension() bint operator!=(PPL_Polyhedron &y) bint operator==(PPL_Polyhedron &y) cdef cppclass PPL_C_Polyhedron(PPL_Polyhedron): PPL_C_Polyhedron(PPL_dimension_type num_dimensions, PPL_Degenerate_Element) PPL_C_Polyhedron(PPL_Constraint_System &cs) except +ValueError PPL_C_Polyhedron(PPL_Generator_System &gs) except +ValueError PPL_C_Polyhedron(PPL_C_Polyhedron &y) cdef cppclass PPL_NNC_Polyhedron(PPL_Polyhedron): PPL_NNC_Polyhedron(PPL_dimension_type num_dimensions, PPL_Degenerate_Element kind) PPL_NNC_Polyhedron(PPL_Constraint_System &cs) except +ValueError PPL_NNC_Polyhedron(PPL_Generator_System &gs) except +ValueError PPL_NNC_Polyhedron(PPL_NNC_Polyhedron &y) PPL_NNC_Polyhedron(PPL_C_Polyhedron &y) cdef cppclass PPL_Poly_Gen_Relation: PPL_Poly_Gen_Relation(PPL_Poly_Gen_Relation &cpy_from) bint implies(PPL_Poly_Gen_Relation &y) void ascii_dump() cdef cppclass PPL_Poly_Con_Relation: PPL_Poly_Con_Relation(PPL_Poly_Con_Relation &cpy_from) bint implies(PPL_Poly_Con_Relation &y) void ascii_dump() cdef cppclass PPL_MIP_Problem: PPL_MIP_Problem(PPL_MIP_Problem &cpy_from) PPL_MIP_Problem(PPL_dimension_type dim) except +ValueError PPL_MIP_Problem(PPL_dimension_type dim, PPL_Constraint_System &cs, PPL_Linear_Expression &obj, PPL_Optimization_Mode) except +ValueError PPL_dimension_type space_dimension() PPL_Linear_Expression& objective_function() void clear() void add_space_dimensions_and_embed(PPL_dimension_type m) except +ValueError void add_constraint(PPL_Constraint &c) except +ValueError void add_constraints(PPL_Constraint_System &cs) except +ValueError void add_to_integer_space_dimensions(PPL_Variables_Set &i_vars) except +ValueError void set_objective_function(PPL_Linear_Expression &obj) except +ValueError void set_optimization_mode(PPL_Optimization_Mode mode) PPL_Optimization_Mode optimization_mode() bint is_satisfiable() PPL_MIP_Problem_Status solve() void evaluate_objective_function(PPL_Generator evaluating_point, PPL_Coefficient &num, PPL_Coefficient &den) except +ValueError PPL_Generator& feasible_point() PPL_Generator optimizing_point() except +ValueError void optimal_value(PPL_Coefficient &num, PPL_Coefficient &den) except +ValueError PPL_MIP_Problem_Control_Parameter_Value get_control_parameter(PPL_MIP_Problem_Control_Parameter_Name name) void set_control_parameter(PPL_MIP_Problem_Control_Parameter_Value value) PPL_mip_iterator constraints_begin() PPL_mip_iterator constraints_end() cdef cppclass PPL_Bit_Row: PPL_Bit_Row() PPL_Bit_Row(const PPL_Bit_Row& y, const PPL_Bit_Row& z) void set(unsigned long k) void set_until(unsigned long k) void clear_from(unsigned long k) void clear() void union_assign(const PPL_Bit_Row& x, const PPL_Bit_Row& y) void intersection_assign(const PPL_Bit_Row& x, const PPL_Bit_Row& y) void difference_assign(const PPL_Bit_Row&x, const PPL_Bit_Row& y) unsigned long first() unsigned long last() unsigned long prev(unsigned long position) unsigned long next(unsigned long position) unsigned long count_ones() cppbool empty() cdef cppclass PPL_Bit_Matrix: PPL_Bit_Matrix() PPL_Bit_Matrix(PPL_dimension_type n_rows, PPL_dimension_type n_columns) PPL_Bit_Matrix(const PPL_Bit_Matrix& y) PPL_Bit_Row& operator[](PPL_dimension_type k) const PPL_Bit_Row& operator[](PPL_dimension_type k) void transpose() void transpose_assign(const PPL_Bit_Matrix& y) PPL_dimension_type num_columns() PPL_dimension_type num_rows() void sort_rows() cdef extern from "ppl.hh": PPL_Generator PPL_line "Parma_Polyhedra_Library::line" (PPL_Linear_Expression &e) except +ValueError PPL_Generator PPL_ray "Parma_Polyhedra_Library::ray" (PPL_Linear_Expression &e) except +ValueError PPL_Generator PPL_point "Parma_Polyhedra_Library::point" (PPL_Linear_Expression &e, PPL_Coefficient &d) except +ValueError PPL_Generator PPL_closure_point "Parma_Polyhedra_Library::closure_point" (PPL_Linear_Expression &e, PPL_Coefficient &d) except +ValueError cdef extern from "ppl.hh": PPL_Poly_Gen_Relation PPL_Poly_Gen_Relation_nothing "Parma_Polyhedra_Library::Poly_Gen_Relation::nothing" () PPL_Poly_Gen_Relation PPL_Poly_Gen_Relation_subsumes "Parma_Polyhedra_Library::Poly_Gen_Relation::subsumes" () PPL_Poly_Con_Relation PPL_Poly_Con_Relation_nothing "Parma_Polyhedra_Library::Poly_Con_Relation::nothing" () PPL_Poly_Con_Relation PPL_Poly_Con_Relation_is_disjoint "Parma_Polyhedra_Library::Poly_Con_Relation::is_disjoint" () PPL_Poly_Con_Relation PPL_Poly_Con_Relation_strictly_intersects "Parma_Polyhedra_Library::Poly_Con_Relation::strictly_intersects" () PPL_Poly_Con_Relation PPL_Poly_Con_Relation_is_included "Parma_Polyhedra_Library::Poly_Con_Relation::is_included" () PPL_Poly_Con_Relation PPL_Poly_Con_Relation_saturates "Parma_Polyhedra_Library::Poly_Con_Relation::saturates" () cdef extern from "ppl_shim.hh": PPL_Poly_Gen_Relation* new_relation_with(PPL_Polyhedron &p, PPL_Generator &g) except +ValueError PPL_Poly_Con_Relation* new_relation_with(PPL_Polyhedron &p, PPL_Constraint &c) except +ValueError PPL_Congruence modulo(const PPL_Linear_Expression &expr, PPL_Coefficient& mod) pplpy-0.8.9/ppl/ppl_shim.cc000066400000000000000000000006111447517221400156160ustar00rootroot00000000000000#include "ppl_shim.hh" Poly_Gen_Relation* new_relation_with(const Polyhedron &p, const Generator &g) { return new Poly_Gen_Relation(p.relation_with(g)); } Poly_Con_Relation* new_relation_with(const Polyhedron &p, const Constraint &c) { return new Poly_Con_Relation(p.relation_with(c)); } Congruence modulo(const Linear_Expression &expr, mpz_class mod) { return (expr %= 0) / mod; } pplpy-0.8.9/ppl/ppl_shim.hh000066400000000000000000000007071447517221400156360ustar00rootroot00000000000000#ifndef PPL_SHIM__H #define PPL_SHIM__H #include using namespace Parma_Polyhedra_Library; // Poly_Gen_Relation/Poly_Con_Relation have no default constructor Poly_Gen_Relation* new_relation_with(const Polyhedron &p, const Generator &g); Poly_Con_Relation* new_relation_with(const Polyhedron &p, const Constraint &c); // the weird usage of the %= operator confuses Cython Congruence modulo(const Linear_Expression &e, mpz_class mod); #endif pplpy-0.8.9/pyproject.toml000066400000000000000000000002151447517221400156150ustar00rootroot00000000000000[build-system] requires = ["setuptools", "wheel", "Cython", "cysignals", "sphinx", "gmpy2>=2.1.0b1"] build-backend = "setuptools.build_meta" pplpy-0.8.9/setup.cfg000066400000000000000000000016321447517221400145260ustar00rootroot00000000000000[metadata] name = pplpy version = 0.8.9 description = Python PPL wrapper long_description = file: README.rst author = Vincent Delecroix author_email = vincent.delecroix@labri.fr url = https://github.com/sagemath/pplpy download_url = https://pypi.org/project/pplpy/#files license = GPL v3 platforms = any classifiers = License :: OSI Approved :: GNU General Public License v3 (GPLv3) Programming Language :: C++ Programming Language :: Python Development Status :: 5 - Production/Stable Operating System :: Unix Intended Audience :: Science/Research Programming Language :: Python :: 3.8 Programming Language :: Python :: 3.9 Programming Language :: Python :: 3.10 Programming Language :: Python :: 3.11 keywords = polyhedron polytope convex mathematics ppl milp linear-programming [options] packages = ppl [options.package_data] ppl = *.pxd, *.h, *.hh pplpy-0.8.9/setup.py000077500000000000000000000064431447517221400144270ustar00rootroot00000000000000#!/usr/bin/env python import os import sys from setuptools import setup, Command from setuptools.extension import Extension # NOTE: setuptools build_ext does not work properly with Cython code from distutils.command.build_ext import build_ext as _build_ext # Adapted from Cython's new_build_ext class build_ext(_build_ext): def run(self): # Check dependencies try: from Cython.Build.Dependencies import cythonize except ImportError as E: sys.stderr.write("Error: {0}\n".format(E)) sys.stderr.write("The installation of ppl requires Cython\n") sys.exit(1) try: # We need the header files for cysignals at compile-time import cysignals except ImportError as E: sys.stderr.write("Error: {0}\n".format(E)) sys.stderr.write("The installation of ppl requires cysignals\n") sys.exit(1) try: # We need the header files for gmpy2 at compile-time import gmpy2 except ImportError as E: sys.stderr.write("Error: {0}\n".format(E)) sys.stderr.write("The installation of ppl requires gmpy2\n") sys.exit(1) self.extensions[:] = cythonize( self.extensions, include_path=sys.path, compiler_directives={'embedsignature': True, 'language_level': '3'}) _build_ext.run(self) class TestCommand(Command): user_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self): import subprocess, os, tempfile, shutil old_path = os.getcwd() tempdir_path = tempfile.mkdtemp() try: shutil.copytree('./tests', tempdir_path, dirs_exist_ok=True) os.chdir(tempdir_path) if subprocess.call([sys.executable, 'runtests.py']): raise SystemExit("Doctest failures") if subprocess.call([sys.executable, 'setup.py', 'build_ext', '--inplace']) or \ subprocess.call([sys.executable, '-c', "import testpplpy; testpplpy.test(); testpplpy.example()"]): raise SystemExit("Cython test 1 failure") if subprocess.call([sys.executable, 'setup2.py', 'build_ext', '--inplace']) or \ subprocess.call([sys.executable, '-c', "import testpplpy2; testpplpy2.test(); testpplpy2.example()"]): raise SystemExit("Cython test 2 failure") finally: os.chdir(old_path) shutil.rmtree(tempdir_path) extensions = [ Extension('ppl.linear_algebra', sources=['ppl/linear_algebra.pyx', 'ppl/ppl_shim.cc']), Extension('ppl.mip_problem', sources=['ppl/mip_problem.pyx', 'ppl/ppl_shim.cc']), Extension('ppl.polyhedron', sources = ['ppl/polyhedron.pyx', 'ppl/ppl_shim.cc']), Extension('ppl.generator', sources = ['ppl/generator.pyx', 'ppl/ppl_shim.cc']), Extension('ppl.constraint', sources = ['ppl/constraint.pyx', 'ppl/ppl_shim.cc']), Extension('ppl.congruence', sources=['ppl/congruence.pyx', 'ppl/ppl_shim.cc']), Extension('ppl.bit_arrays', sources = ['ppl/bit_arrays.pyx', 'ppl/ppl_shim.cc']), ] setup( ext_modules = extensions, cmdclass = {'build_ext': build_ext, 'test': TestCommand}, ) pplpy-0.8.9/tests/000077500000000000000000000000001447517221400140455ustar00rootroot00000000000000pplpy-0.8.9/tests/runtests.py000066400000000000000000000013721447517221400163110ustar00rootroot00000000000000import ppl import sys import os path = os.path.dirname(__file__) if path: os.chdir(path) ans = 0 # set to nonzero if an error is found print("Running pplpy doctests") print('-'*80) import doctest for mod in [ppl, ppl.linear_algebra, ppl.mip_problem, ppl.polyhedron, ppl.generator, ppl.constraint, ppl.congruence, ppl.bit_arrays]: res = doctest.testmod(mod, optionflags=doctest.ELLIPSIS | doctest.REPORT_NDIFF | doctest.NORMALIZE_WHITESPACE) print(mod) print(res) print('-'*80) ans = ans | res[0] print("Running unittests") print('-'*80) import unittest for mod in ['test_variable', 'test_constraint']: res = unittest.main(module=mod, exit=False, failfast=False, verbosity=2) ans = ans | bool(res.result.errors) sys.exit(ans) pplpy-0.8.9/tests/setup.py000066400000000000000000000002741447517221400155620ustar00rootroot00000000000000from setuptools import setup from Cython.Build import cythonize opts = { 'compiler_directives': {'language_level': '3'} } setup(ext_modules=cythonize("testpplpy.pyx", **opts)) pplpy-0.8.9/tests/setup2.py000066400000000000000000000004331447517221400156410ustar00rootroot00000000000000from setuptools import Extension, setup from Cython.Build import cythonize extension = Extension("testpplpy2", ["testpplpy2.pyx"], language='c++', libraries=['ppl']) opts = { 'compiler_directives': {'language_level': '3'} } setup(ext_modules=cythonize(extension, *opts)) pplpy-0.8.9/tests/test_constraint.py000066400000000000000000000017651447517221400176530ustar00rootroot00000000000000import unittest from ppl import Variable, Constraint, Constraint_System class TestConstraint(unittest.TestCase): def test_creation_empty(self): c = Constraint() self.assertTrue(c.is_tautological()) def test_creation_other(self): x = Variable(0) y = Variable(1) c = x + 3 * y == 1 cc = Constraint(c) self.assertTrue(c.is_equivalent_to(cc)) def test_creation_invalid(self): self.assertRaises(TypeError, Constraint, "hello") class TestConstraint_System(unittest.TestCase): def test_creation_empty(self): cs = Constraint_System() self.assertTrue(cs.empty()) def test_creation_other(self): x = Variable(0) y = Variable(1) cs = Constraint_System(5*x - 2*y > 0) cs.insert(6 * x < 3 * y) ccs = Constraint_System(cs) self.assertTrue(cs[0].is_equivalent_to(ccs[0])) def test_creation_invalid(self): self.assertRaises(TypeError, Constraint_System, "hello") pplpy-0.8.9/tests/test_variable.py000066400000000000000000000004421447517221400172430ustar00rootroot00000000000000import unittest from ppl import Variable class TestVariable(unittest.TestCase): def test_creation_valid(self): Variable(0) def test_creation_invalid(self): self.assertRaises(OverflowError, Variable, -1) self.assertRaises(TypeError, Variable, "hello") pplpy-0.8.9/tests/testpplpy.pyx000066400000000000000000000024441447517221400166570ustar00rootroot00000000000000# distutils: language = c++ # distutils: libraries = ppl """ The goal of this file is to test cython can use pplpy package properly In order to do this we do some test with objects from each packages and extension : ppl ppl.linear_algebra ppl.constraint ppl.mip_problem """ from ppl.linear_algebra cimport Variable from ppl.constraint cimport Constraint_System from ppl.mip_problem cimport MIP_Problem from ppl.polyhedron cimport C_Polyhedron def test(): x = Variable(0) y = Variable(1) cs = Constraint_System() cs.insert( x >= 0) cs.insert( y >= 0 ) cs.insert( 3 * x + 5 * y <= 10 ) m = MIP_Problem(2, cs, x + y) m.objective_function() from ppl import C_Polyhedron C_Polyhedron( 5*x-2*y >= x+y-1 ) print("-"*80) print("Cython test 1 OK") print("-"*80) def example(): "Cython version of the example from the README" cdef Variable x = Variable(0) cdef Variable y = Variable(1) cdef Variable z = Variable(2) cdef Constraint_System cs = Constraint_System() cs.insert(x >= 0) cs.insert(y >= 0) cs.insert(x + y + z == 1) cdef C_Polyhedron poly = C_Polyhedron(cs) print(poly.minimized_generators()) print('dim = %lu' % poly.thisptr.space_dimension()) print("-"*80) print("Cython example 1 OK") print("-"*80) pplpy-0.8.9/tests/testpplpy2.pyx000066400000000000000000000023761447517221400167450ustar00rootroot00000000000000""" The goal of this file is to test cython can use pplpy package properly In order to do this we do some test with objects from each packages and extension : ppl ppl.linear_algebra ppl.linear_algebra ppl.constraint ppl.mip_problem """ from ppl.linear_algebra cimport Variable from ppl.constraint cimport Constraint_System from ppl.mip_problem cimport MIP_Problem from ppl.polyhedron cimport C_Polyhedron def test(): x = Variable(0) y = Variable(1) cs = Constraint_System() cs.insert( x >= 0) cs.insert( y >= 0 ) cs.insert( 3 * x + 5 * y <= 10 ) m = MIP_Problem(2, cs, x + y) m.objective_function() from ppl import C_Polyhedron C_Polyhedron( 5*x-2*y >= x+y-1 ) print("-"*80) print("Cython test 2 OK") print("-"*80) def example(): "Cython version of the example from the README" cdef Variable x = Variable(0) cdef Variable y = Variable(1) cdef Variable z = Variable(2) cdef Constraint_System cs = Constraint_System() cs.insert(x >= 0) cs.insert(y >= 0) cs.insert(x + y + z == 1) cdef C_Polyhedron poly = C_Polyhedron(cs) print(poly.minimized_generators()) print('dim = %lu' % poly.thisptr.space_dimension()) print("-"*80) print("Cython example 2 OK") print("-"*80) pplpy-0.8.9/tox.ini000066400000000000000000000002601447517221400142140ustar00rootroot00000000000000[tox] envlist = py27, py36, py37, py38 skip_missing_interpreters = true [testenv] whitelist_externals = make commands = {envpython} setup.py test make -w -C docs html