├── environment.yml ├── ppl ├── bit_arrays.pxd ├── mip_problem.pxd ├── congruence.pxd ├── linear_algebra.pxd ├── polyhedron.pxd ├── ppl_shim.cc ├── constraint.pxd ├── ppl_shim.hh ├── generator.pxd ├── bit_arrays.pyx ├── __init__.py ├── congruence.pyx ├── ppl_decl.pxd ├── mip_problem.pyx ├── constraint.pyx └── generator.pyx ├── CODE_OF_CONDUCT.md ├── environment.test.yml ├── tests ├── setup.py ├── setup2.py ├── test_variable.py ├── runtests.py ├── test_constraint.py ├── testpplpy2.pyx └── testpplpy.pyx ├── .gitignore ├── CONTRIBUTING.md ├── MANIFEST.in ├── docs ├── Makefile └── source │ ├── index.rst │ └── conf.py ├── CHANGES.txt ├── pyproject.toml ├── .github └── workflows │ ├── test.yml │ ├── doc.yml │ └── dist.yml ├── setup.py ├── README.rst └── LICENSE.txt /environment.yml: -------------------------------------------------------------------------------- 1 | name: pplpy-build 2 | channels: 3 | - conda-forge 4 | - defaults 5 | dependencies: 6 | - setuptools 7 | - gmpy2 8 | - cysignals 9 | - cython 10 | - ppl 11 | -------------------------------------------------------------------------------- /ppl/bit_arrays.pxd: -------------------------------------------------------------------------------- 1 | from .ppl_decl cimport * 2 | 3 | cdef class Bit_Row(object): 4 | cdef PPL_Bit_Row *thisptr 5 | 6 | cdef class Bit_Matrix(object): 7 | cdef PPL_Bit_Matrix *thisptr 8 | -------------------------------------------------------------------------------- /ppl/mip_problem.pxd: -------------------------------------------------------------------------------- 1 | from .linear_algebra cimport * 2 | from .generator cimport * 3 | from .constraint cimport * 4 | 5 | cdef class MIP_Problem(object): 6 | cdef PPL_MIP_Problem *thisptr 7 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | This is an open-source project maintained by the SageMath community. 2 | 3 | The [Code of Conduct](https://github.com/sagemath/sage/blob/develop/CODE_OF_CONDUCT.md) 4 | of the Sage community applies. 5 | -------------------------------------------------------------------------------- /environment.test.yml: -------------------------------------------------------------------------------- 1 | name: pplpy-test 2 | channels: 3 | - conda-forge 4 | - defaults 5 | dependencies: 6 | - sphinx 7 | - pip 8 | - setuptools 9 | - pip: 10 | - linkchecker 11 | - cython-lint 12 | -------------------------------------------------------------------------------- /tests/setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup 2 | from Cython.Build import cythonize 3 | 4 | 5 | opts = { 6 | 'compiler_directives': {'language_level': '3'} 7 | } 8 | 9 | 10 | setup(ext_modules=cythonize("testpplpy.pyx", **opts)) 11 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | build/* 2 | ppl.so 3 | ppl/*.c 4 | ppl/*.cpp 5 | ppl/*.so 6 | ppl/cygmp/*.c 7 | ppl/cygmp/*.cpp 8 | ppl/cygmp/*.so 9 | *.so 10 | *.o 11 | *.pyc 12 | *.c 13 | *.cpp 14 | *.swp 15 | dist/ 16 | pplpy.egg-info/ 17 | docs/build/ 18 | .idea/* 19 | /.tox 20 | -------------------------------------------------------------------------------- /ppl/congruence.pxd: -------------------------------------------------------------------------------- 1 | from .ppl_decl cimport * 2 | 3 | cdef _wrap_Congruence(PPL_Congruence) 4 | 5 | cdef class Congruence(object): 6 | cdef PPL_Congruence *thisptr 7 | 8 | cdef class Congruence_System(object): 9 | cdef PPL_Congruence_System *thisptr 10 | -------------------------------------------------------------------------------- /tests/setup2.py: -------------------------------------------------------------------------------- 1 | from setuptools import Extension, setup 2 | from Cython.Build import cythonize 3 | 4 | 5 | extension = Extension("testpplpy2", ["testpplpy2.pyx"], language='c++', libraries=['ppl']) 6 | opts = { 7 | 'compiler_directives': {'language_level': '3'} 8 | } 9 | 10 | 11 | setup(ext_modules=cythonize(extension, *opts)) 12 | -------------------------------------------------------------------------------- /tests/test_variable.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | from ppl import Variable 4 | 5 | class TestVariable(unittest.TestCase): 6 | def test_creation_valid(self): 7 | Variable(0) 8 | 9 | def test_creation_invalid(self): 10 | self.assertRaises(OverflowError, Variable, -1) 11 | self.assertRaises(TypeError, Variable, "hello") 12 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | This is an open-source project maintained by the SageMath community. 2 | 3 | Contributions of all sorts are heartily welcomed. 4 | 5 | See https://github.com/sagemath/sage/blob/develop/CONTRIBUTING.md for general 6 | guidance on how to contribute. 7 | 8 | Open issues or submit pull requests at https://github.com/sagemath/pplpy 9 | and join https://groups.google.com/group/sage-devel to discuss. 10 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include README.rst LICENSE.txt CHANGES.txt pyproject.toml setup.py setup.cfg tox.ini 2 | recursive-include ppl *.pxd *.pyx *.py 3 | recursive-include tests *.pyx *.py 4 | include ppl/ppl_shim.cc 5 | include ppl/ppl_shim.hh 6 | include docs/Makefile 7 | include docs/source/conf.py 8 | include docs/source/index.rst 9 | 10 | recursive-exclude ppl *.so *.c *.cpp 11 | recursive-exclude tests *.so *.c *.cpp 12 | -------------------------------------------------------------------------------- /ppl/linear_algebra.pxd: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | 3 | from .ppl_decl cimport * 4 | 5 | cdef class Variable(object): 6 | cdef PPL_Variable *thisptr 7 | 8 | cdef class Variables_Set(object): 9 | cdef PPL_Variables_Set *thisptr 10 | 11 | cdef class Linear_Expression(object): 12 | cdef PPL_Linear_Expression *thisptr 13 | 14 | cdef PPL_Coefficient PPL_Coefficient_from_pyobject(c) except * 15 | -------------------------------------------------------------------------------- /ppl/polyhedron.pxd: -------------------------------------------------------------------------------- 1 | from .ppl_decl cimport PPL_Polyhedron 2 | from .generator cimport Generator 3 | from .constraint cimport Constraint 4 | 5 | cdef class Polyhedron(object): 6 | cdef PPL_Polyhedron *thisptr 7 | cdef _relation_with_generator(Polyhedron self, Generator g) 8 | cdef _relation_with_constraint(Polyhedron self, Constraint c) 9 | 10 | cdef class C_Polyhedron(Polyhedron): 11 | pass 12 | 13 | cdef class NNC_Polyhedron(Polyhedron): 14 | pass 15 | -------------------------------------------------------------------------------- /ppl/ppl_shim.cc: -------------------------------------------------------------------------------- 1 | #include "ppl_shim.hh" 2 | 3 | Poly_Gen_Relation* new_relation_with(const Polyhedron &p, const Generator &g) 4 | { 5 | return new Poly_Gen_Relation(p.relation_with(g)); 6 | } 7 | 8 | Poly_Con_Relation* new_relation_with(const Polyhedron &p, const Constraint &c) 9 | { 10 | return new Poly_Con_Relation(p.relation_with(c)); 11 | } 12 | 13 | Congruence modulo(const Linear_Expression &expr, mpz_class mod) 14 | { 15 | return (expr %= 0) / mod; 16 | } 17 | -------------------------------------------------------------------------------- /ppl/constraint.pxd: -------------------------------------------------------------------------------- 1 | from .linear_algebra cimport * 2 | 3 | cdef _wrap_Constraint(PPL_Constraint constraint) 4 | 5 | cdef _wrap_Constraint_System(PPL_Constraint_System constraint_system) 6 | 7 | cdef _make_Constraint_from_richcmp(lhs_, rhs_, op) 8 | 9 | cdef class Constraint(object): 10 | cdef PPL_Constraint *thisptr 11 | 12 | cdef class Constraint_System(object): 13 | cdef PPL_Constraint_System *thisptr 14 | 15 | cdef class Poly_Con_Relation(object): 16 | cdef PPL_Poly_Con_Relation *thisptr 17 | -------------------------------------------------------------------------------- /ppl/ppl_shim.hh: -------------------------------------------------------------------------------- 1 | #ifndef PPL_SHIM__H 2 | #define PPL_SHIM__H 3 | 4 | 5 | 6 | #include 7 | 8 | using namespace Parma_Polyhedra_Library; 9 | 10 | // Poly_Gen_Relation/Poly_Con_Relation have no default constructor 11 | Poly_Gen_Relation* new_relation_with(const Polyhedron &p, const Generator &g); 12 | Poly_Con_Relation* new_relation_with(const Polyhedron &p, const Constraint &c); 13 | 14 | // the weird usage of the %= operator confuses Cython 15 | Congruence modulo(const Linear_Expression &e, mpz_class mod); 16 | 17 | #endif 18 | -------------------------------------------------------------------------------- /ppl/generator.pxd: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | 3 | from .ppl_decl cimport * 4 | from .linear_algebra cimport * 5 | 6 | cdef _wrap_Generator(PPL_Generator generator) 7 | 8 | cdef _wrap_Generator_System(PPL_Generator_System generator_system) 9 | 10 | cdef PPL_GeneratorType_str(PPL_GeneratorType t) 11 | 12 | cdef class Generator(object): 13 | cdef PPL_Generator *thisptr 14 | 15 | cdef class Generator_System(object): 16 | cdef PPL_Generator_System *thisptr 17 | 18 | cdef class Poly_Gen_Relation(object): 19 | cdef PPL_Poly_Gen_Relation *thisptr 20 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Minimal makefile for Sphinx documentation 2 | # NOTE: we removed the shortcut $(O) for passing options to 3 | # sphinx-build as this is undocummented and sometimes 4 | # confusing. 5 | 6 | # You can set these variables from the command line. 7 | SPHINXBUILD = sphinx-build 8 | SPHINXPROJ = pplpy 9 | SOURCEDIR = source 10 | BUILDDIR = build 11 | 12 | # Put it first so that "make" without argument is like "make help". 13 | help: 14 | @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) 15 | 16 | .PHONY: help Makefile 17 | 18 | # Catch-all target: route all unknown targets to Sphinx using the new 19 | # "make mode" option. 20 | %: Makefile 21 | @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) 22 | -------------------------------------------------------------------------------- /tests/runtests.py: -------------------------------------------------------------------------------- 1 | import ppl 2 | import sys 3 | import os 4 | 5 | path = os.path.dirname(__file__) 6 | if path: 7 | os.chdir(path) 8 | 9 | ans = 0 # set to nonzero if an error is found 10 | 11 | print("Running pplpy doctests") 12 | print('-'*80) 13 | import doctest 14 | for mod in [ppl, ppl.linear_algebra, ppl.mip_problem, ppl.polyhedron, ppl.generator, ppl.constraint, ppl.congruence, ppl.bit_arrays]: 15 | res = doctest.testmod(mod, optionflags=doctest.ELLIPSIS | doctest.REPORT_NDIFF | doctest.NORMALIZE_WHITESPACE) 16 | print(mod) 17 | print(res) 18 | print('-'*80) 19 | ans = ans | res[0] 20 | 21 | print("Running unittests") 22 | print('-'*80) 23 | import unittest 24 | for mod in ['test_variable', 'test_constraint']: 25 | res = unittest.main(module=mod, exit=False, failfast=False, verbosity=2) 26 | ans = ans | bool(res.result.errors) 27 | 28 | sys.exit(ans) 29 | -------------------------------------------------------------------------------- /tests/test_constraint.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | from ppl import Variable, Constraint, Constraint_System 4 | 5 | class TestConstraint(unittest.TestCase): 6 | def test_creation_empty(self): 7 | c = Constraint() 8 | self.assertTrue(c.is_tautological()) 9 | 10 | def test_creation_other(self): 11 | x = Variable(0) 12 | y = Variable(1) 13 | c = x + 3 * y == 1 14 | cc = Constraint(c) 15 | self.assertTrue(c.is_equivalent_to(cc)) 16 | 17 | def test_creation_invalid(self): 18 | self.assertRaises(TypeError, Constraint, "hello") 19 | 20 | class TestConstraint_System(unittest.TestCase): 21 | def test_creation_empty(self): 22 | cs = Constraint_System() 23 | self.assertTrue(cs.empty()) 24 | 25 | def test_creation_other(self): 26 | x = Variable(0) 27 | y = Variable(1) 28 | cs = Constraint_System(5*x - 2*y > 0) 29 | cs.insert(6 * x < 3 * y) 30 | ccs = Constraint_System(cs) 31 | self.assertTrue(cs[0].is_equivalent_to(ccs[0])) 32 | 33 | def test_creation_invalid(self): 34 | self.assertRaises(TypeError, Constraint_System, "hello") 35 | -------------------------------------------------------------------------------- /CHANGES.txt: -------------------------------------------------------------------------------- 1 | v0.8, 2019/01/18 2 | - switch from github to gitlab 3 | - some more support for PPL objects: permute_space_dimensions, Bit_Row, 4 | Bit_Matrix 5 | - upgrade gmpy2 version dependency 6 | - add pyproject.toml and setup.cfg files 7 | - remove the OK functions which caused trouble for clang on FreeBSD 8 | - switch back to github under SageMath organization 9 | - fast initialization of Linear_Expression from list/dict 10 | - CI (test, linter, doc build and deployment) 11 | - add a Cython pool for ppl.Variable 12 | - support for congruences 13 | v0.7, 2017/11/24 14 | - use of gmpy2 for integers and rationals (Vincent Delecroix/Vincent Klein) 15 | - tests on travis (Vincent Delecroix/Vincent Klein) 16 | - fixes in install scripts (Vincent Delecroix) 17 | - port some upgrades from Sage (Vincent Klein) 18 | - split in several Cython files (Vincent Klein) 19 | - adding widening (Jesús Doménech) 20 | v0.6, 2016/01/17 -- distribution bug fixes 21 | v0.5, 2016/01/17 -- bug fixes 22 | v0.4, 2016/01/16 -- iterator for MIP_Problem 23 | v0.3, 2016/01/16 -- Reworked documentation 24 | v0.2, 2016/01/16 -- Fix build 25 | v0.1, 2016/01/16 -- Initial release 26 | -------------------------------------------------------------------------------- /tests/testpplpy2.pyx: -------------------------------------------------------------------------------- 1 | """ 2 | The goal of this file is to test cython can use pplpy package properly 3 | In order to do this we do some test with objects from each packages and extension : 4 | ppl 5 | ppl.linear_algebra 6 | ppl.linear_algebra 7 | ppl.constraint 8 | ppl.mip_problem 9 | """ 10 | 11 | from ppl.linear_algebra cimport Variable 12 | from ppl.constraint cimport Constraint_System 13 | from ppl.mip_problem cimport MIP_Problem 14 | from ppl.polyhedron cimport C_Polyhedron 15 | 16 | def test(): 17 | x = Variable(0) 18 | y = Variable(1) 19 | cs = Constraint_System() 20 | cs.insert( x >= 0) 21 | cs.insert( y >= 0 ) 22 | cs.insert( 3 * x + 5 * y <= 10 ) 23 | m = MIP_Problem(2, cs, x + y) 24 | m.objective_function() 25 | 26 | from ppl import C_Polyhedron 27 | C_Polyhedron( 5*x-2*y >= x+y-1 ) 28 | 29 | print("-"*80) 30 | print("Cython test 2 OK") 31 | print("-"*80) 32 | 33 | def example(): 34 | "Cython version of the example from the README" 35 | cdef Variable x = Variable(0) 36 | cdef Variable y = Variable(1) 37 | cdef Variable z = Variable(2) 38 | cdef Constraint_System cs = Constraint_System() 39 | cs.insert(x >= 0) 40 | cs.insert(y >= 0) 41 | cs.insert(x + y + z == 1) 42 | cdef C_Polyhedron poly = C_Polyhedron(cs) 43 | print(poly.minimized_generators()) 44 | print('dim = %lu' % poly.thisptr.space_dimension()) 45 | print("-"*80) 46 | print("Cython example 2 OK") 47 | print("-"*80) 48 | -------------------------------------------------------------------------------- /tests/testpplpy.pyx: -------------------------------------------------------------------------------- 1 | # distutils: language = c++ 2 | # distutils: libraries = ppl 3 | """ 4 | The goal of this file is to test cython can use pplpy package properly 5 | In order to do this we do some test with objects from each packages and extension : 6 | ppl 7 | ppl.linear_algebra 8 | ppl.constraint 9 | ppl.mip_problem 10 | """ 11 | 12 | from ppl.linear_algebra cimport Variable 13 | from ppl.constraint cimport Constraint_System 14 | from ppl.mip_problem cimport MIP_Problem 15 | from ppl.polyhedron cimport C_Polyhedron 16 | 17 | def test(): 18 | x = Variable(0) 19 | y = Variable(1) 20 | cs = Constraint_System() 21 | cs.insert( x >= 0) 22 | cs.insert( y >= 0 ) 23 | cs.insert( 3 * x + 5 * y <= 10 ) 24 | m = MIP_Problem(2, cs, x + y) 25 | m.objective_function() 26 | 27 | from ppl import C_Polyhedron 28 | C_Polyhedron( 5*x-2*y >= x+y-1 ) 29 | 30 | print("-"*80) 31 | print("Cython test 1 OK") 32 | print("-"*80) 33 | 34 | def example(): 35 | "Cython version of the example from the README" 36 | cdef Variable x = Variable(0) 37 | cdef Variable y = Variable(1) 38 | cdef Variable z = Variable(2) 39 | cdef Constraint_System cs = Constraint_System() 40 | cs.insert(x >= 0) 41 | cs.insert(y >= 0) 42 | cs.insert(x + y + z == 1) 43 | cdef C_Polyhedron poly = C_Polyhedron(cs) 44 | print(poly.minimized_generators()) 45 | print('dim = %lu' % poly.thisptr.space_dimension()) 46 | print("-"*80) 47 | print("Cython example 1 OK") 48 | print("-"*80) 49 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = [ 3 | "setuptools>=61.2", 4 | "Cython", 5 | "cysignals", 6 | "gmpy2>=2.1.0b1", 7 | ] 8 | build-backend = "setuptools.build_meta" 9 | 10 | [project] 11 | name = "pplpy" 12 | description = "Python PPL wrapper" 13 | readme = "README.rst" 14 | authors = [{name = "Vincent Delecroix", email = "vincent.delecroix@labri.fr"}] 15 | license = {text = "GPL v3"} 16 | requires-python = ">=3.12" 17 | classifiers = [ 18 | "License :: OSI Approved :: GNU General Public License v3 (GPLv3)", 19 | "Programming Language :: C++", 20 | "Programming Language :: Python", 21 | "Development Status :: 5 - Production/Stable", 22 | "Operating System :: Unix", 23 | "Intended Audience :: Science/Research", 24 | "Programming Language :: Python :: 3", 25 | "Programming Language :: Python :: 3 :: Only", 26 | "Programming Language :: Python :: 3.12", 27 | "Programming Language :: Python :: 3.13", 28 | "Programming Language :: Python :: 3.14", 29 | ] 30 | keywords = [ 31 | "polyhedron", 32 | "polytope", 33 | "convex", 34 | "mathematics", 35 | "ppl", 36 | "milp", 37 | "linear-programming", 38 | ] 39 | dependencies = [ 40 | "cysignals", 41 | "gmpy2>=2.1.0b1", 42 | ] 43 | dynamic = ["version"] 44 | 45 | [project.optional-dependencies] 46 | doc = [ 47 | "sphinx", 48 | ] 49 | 50 | [project.urls] 51 | Homepage = "https://github.com/sagemath/pplpy" 52 | Download = "https://pypi.org/project/pplpy/#files" 53 | 54 | [tool.setuptools] 55 | packages = ["ppl"] 56 | platforms = ["any"] 57 | include-package-data = false 58 | 59 | [tool.setuptools.dynamic] 60 | version = {attr = "ppl.__version__"} 61 | 62 | [tool.setuptools.package-data] 63 | ppl = ["*.pxd", "*.h", "*.hh"] 64 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: Test 2 | on: 3 | push: { branches: [ "master" ] } 4 | pull_request: { branches: [ "master" ] } 5 | 6 | concurrency: 7 | group: test-${{ github.ref }} 8 | cancel-in-progress: true 9 | 10 | jobs: 11 | test: 12 | runs-on: ubuntu-latest 13 | strategy: 14 | fail-fast: false 15 | matrix: 16 | python: ["3.12", "3.13", "3.14"] 17 | steps: 18 | - uses: actions/checkout@v2 19 | with: { submodules: recursive } 20 | 21 | - name: Setup Conda environment 22 | uses: conda-incubator/setup-miniconda@v3 23 | with: 24 | python-version: ${{ matrix.python }} 25 | # Disabled for now due to 26 | # https://github.com/conda-incubator/setup-miniconda/issues/379 27 | # miniforge-version: latest 28 | use-mamba: true 29 | channels: conda-forge 30 | channel-priority: true 31 | 32 | - name: Install dependencies 33 | shell: bash -l {0} 34 | run: | 35 | conda install --quiet ppl gmp mpfr mpc 36 | 37 | - name: Build 38 | shell: bash -l {0} 39 | run: | 40 | pip install --verbose . 41 | 42 | - name: Install test dependencies 43 | run: | 44 | conda env update --quiet -n test -f environment.test.yml 45 | conda list 46 | 47 | - name: Lint 48 | shell: bash -l {0} 49 | run: | 50 | cython-lint --ignore=E265,E266,E501,E741 --exclude='ppl_decl.pxd' ppl/ 51 | 52 | - name: Run tests 53 | shell: bash -l {0} 54 | run: | 55 | python setup.py test 56 | 57 | - name: Show logs 58 | run: grep "" /dev/null `find -name '*.log'` || true 59 | if: ${{ always() }} 60 | -------------------------------------------------------------------------------- /.github/workflows/doc.yml: -------------------------------------------------------------------------------- 1 | name: Documentation 2 | on: 3 | push: { branches: [ "master" ] } 4 | pull_request: { branches: [ "master" ] } 5 | 6 | concurrency: 7 | group: doc-${{ github.ref }} 8 | cancel-in-progress: true 9 | 10 | jobs: 11 | build-manual: 12 | runs-on: ubuntu-latest 13 | steps: 14 | - uses: actions/checkout@v2 15 | with: { submodules: recursive } 16 | - uses: conda-incubator/setup-miniconda@v2 17 | with: { miniforge-variant: "Mambaforge", miniforge-version: "latest" } 18 | - name: Install pplpy dependencies 19 | shell: bash -l {0} 20 | run: | 21 | mamba env update --quiet -n test -f environment.yml 22 | conda list 23 | - name: Install pplpy 24 | shell: bash -l {0} 25 | run: | 26 | pip install --verbose --no-index --no-build-isolation . 27 | - name: Install test dependencies 28 | run: | 29 | mamba env update --quiet -n test -f environment.test.yml 30 | conda list 31 | - name: Build documentation 32 | shell: bash -l {0} 33 | run: 34 | sphinx-build docs/source html/pplpy 35 | - name: Detect broken links 36 | shell: bash -l {0} 37 | run: | 38 | python -m http.server 8880 --directory html & 39 | sleep 1 40 | # We ignore _modules since sphinx puts all modules in the module 41 | # overview but does not generate pages for .pyx modules. 42 | # We also ignore a url that is generated by sphinx itself (version 7.2.6). 43 | linkchecker --check-extern --ignore-url='_modules/|https://www.sphinx-doc.org/' http://localhost:8880 44 | - uses: JamesIves/github-pages-deploy-action@3.7.1 45 | with: 46 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 47 | BRANCH: gh-pages 48 | FOLDER: html/pplpy/ 49 | TARGET_FOLDER: docs/ 50 | if: ${{ github.event_name == 'push' }} 51 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import os 4 | import sys 5 | 6 | from setuptools import setup, Command 7 | from setuptools.extension import Extension 8 | 9 | # NOTE: setuptools build_ext does not work properly with Cython code 10 | from distutils.command.build_ext import build_ext as _build_ext 11 | 12 | # Adapted from Cython's new_build_ext 13 | class build_ext(_build_ext): 14 | def run(self): 15 | # Check dependencies 16 | try: 17 | from Cython.Build.Dependencies import cythonize 18 | except ImportError as E: 19 | sys.stderr.write("Error: {0}\n".format(E)) 20 | sys.stderr.write("The installation of ppl requires Cython\n") 21 | sys.exit(1) 22 | 23 | try: 24 | # We need the header files for cysignals at compile-time 25 | import cysignals 26 | except ImportError as E: 27 | sys.stderr.write("Error: {0}\n".format(E)) 28 | sys.stderr.write("The installation of ppl requires cysignals\n") 29 | sys.exit(1) 30 | 31 | try: 32 | # We need the header files for gmpy2 at compile-time 33 | import gmpy2 34 | except ImportError as E: 35 | sys.stderr.write("Error: {0}\n".format(E)) 36 | sys.stderr.write("The installation of ppl requires gmpy2\n") 37 | sys.exit(1) 38 | 39 | self.extensions[:] = cythonize( 40 | self.extensions, 41 | include_path=sys.path, 42 | compiler_directives={'embedsignature': True, 43 | 'language_level': '3'}) 44 | 45 | _build_ext.run(self) 46 | 47 | class TestCommand(Command): 48 | user_options = [] 49 | 50 | def initialize_options(self): 51 | pass 52 | 53 | def finalize_options(self): 54 | pass 55 | 56 | def run(self): 57 | import subprocess, os, tempfile, shutil 58 | 59 | old_path = os.getcwd() 60 | tempdir_path = tempfile.mkdtemp() 61 | try: 62 | shutil.copytree('./tests', tempdir_path, dirs_exist_ok=True) 63 | os.chdir(tempdir_path) 64 | 65 | if subprocess.call([sys.executable, 'runtests.py']): 66 | raise SystemExit("Doctest failures") 67 | 68 | if subprocess.call([sys.executable, 'setup.py', 'build_ext', '--inplace']) or \ 69 | subprocess.call([sys.executable, '-c', "import testpplpy; testpplpy.test(); testpplpy.example()"]): 70 | raise SystemExit("Cython test 1 failure") 71 | 72 | if subprocess.call([sys.executable, 'setup2.py', 'build_ext', '--inplace']) or \ 73 | subprocess.call([sys.executable, '-c', "import testpplpy2; testpplpy2.test(); testpplpy2.example()"]): 74 | raise SystemExit("Cython test 2 failure") 75 | finally: 76 | os.chdir(old_path) 77 | shutil.rmtree(tempdir_path) 78 | 79 | extensions = [ 80 | Extension('ppl.linear_algebra', sources=['ppl/linear_algebra.pyx', 'ppl/ppl_shim.cc']), 81 | Extension('ppl.mip_problem', sources=['ppl/mip_problem.pyx', 'ppl/ppl_shim.cc']), 82 | Extension('ppl.polyhedron', sources = ['ppl/polyhedron.pyx', 'ppl/ppl_shim.cc']), 83 | Extension('ppl.generator', sources = ['ppl/generator.pyx', 'ppl/ppl_shim.cc']), 84 | Extension('ppl.constraint', sources = ['ppl/constraint.pyx', 'ppl/ppl_shim.cc']), 85 | Extension('ppl.congruence', sources=['ppl/congruence.pyx', 'ppl/ppl_shim.cc']), 86 | Extension('ppl.bit_arrays', sources = ['ppl/bit_arrays.pyx', 'ppl/ppl_shim.cc']), 87 | ] 88 | 89 | setup( 90 | ext_modules = extensions, 91 | cmdclass = {'build_ext': build_ext, 'test': TestCommand}, 92 | ) 93 | -------------------------------------------------------------------------------- /docs/source/index.rst: -------------------------------------------------------------------------------- 1 | .. pplpy documentation master file 2 | 3 | Welcome to pplpy's documentation! 4 | ================================= 5 | 6 | Installation 7 | ------------ 8 | 9 | pplpy is available from the `Python Package Index `_. You can hence install it with:: 10 | 11 | $ pip install pplpy 12 | 13 | The code source can be obtained from `github `_:: 14 | 15 | $ git clone https://github.com/sagemath/pplpy.git 16 | 17 | Introduction 18 | ------------ 19 | 20 | .. automodule:: ppl 21 | 22 | Using in Cython 23 | --------------- 24 | 25 | All types from ppl are extension types and can be used with Cython. The following is a 26 | short sample of Cython code using pplpy:: 27 | 28 | from ppl.linear_algebra cimport Variable 29 | from ppl.constraint cimport Constraint_System 30 | from ppl.polyhedron cimport C_Polyhedron 31 | 32 | cdef Variable x = ppl.Variable(0) 33 | cdef Variable y = ppl.Variable(1) 34 | cdef Variable z = ppl.Variable(2) 35 | cdef Constraint_System cs = Constraint_System() 36 | cs.insert(x >= 0) 37 | cs.insert(y >= 0) 38 | cs.insert(x + y + z == 1) 39 | cdef C_Polyhedron poly = C_Polyhedron(cs) 40 | print(poly.minimized_generators()) 41 | 42 | Each extension type carries an attribute ``thisptr`` that holds a pointer to 43 | the corresponding C++ object from ppl. Continuing the above example, one can 44 | do:: 45 | 46 | print('dim = %lu' % poly.thisptr.space_dimension()) 47 | 48 | To avoid name collisions, the original C++ class names are prefixed with 49 | ``PPL_``, for example, the original ``Linear_Expression`` becomes 50 | ``PPL_Linear_Expression``. The Python wrapper has the same name as the original 51 | library class, that is, just ``Linear_Expression``. All ``ppl`` declarations 52 | are done in the ``.pxd`` file ``ppl/ppl_decl.pxd``. Only few functionalities 53 | from ``ppl`` are exposed in ``ppl_decl.pxd``. It is also preferable to avoid 54 | mixing C++ ``ppl`` objects with Cython ``pplpy`` extension types. 55 | 56 | To compile a Cython extension using pplpy you need to: 57 | 58 | - add the path of your pplpy installation to ``include_dirs`` 59 | - link with the ``ppl`` library 60 | 61 | Here is a minimal example of a ``setup.py`` file for a unique Cython file 62 | called ``test.pyx``:: 63 | 64 | from distutils.core import setup 65 | from distutils.extension import Extension 66 | from Cython.Build import cythonize 67 | import ppl 68 | 69 | extensions = [ 70 | Extension("test", ["test.pyx"], libraries=['ppl'], include_dirs=ppl.__path__, language='c++') 71 | ] 72 | 73 | setup(ext_modules=cythonize(extensions)) 74 | 75 | Module `ppl.constraint` 76 | ----------------------- 77 | 78 | .. automodule:: ppl.constraint 79 | :members: 80 | :undoc-members: 81 | :show-inheritance: 82 | 83 | Module `ppl.linear_algebra` 84 | --------------------------- 85 | 86 | .. automodule:: ppl.linear_algebra 87 | :members: 88 | :undoc-members: 89 | :show-inheritance: 90 | 91 | Module `ppl.generator` 92 | ---------------------- 93 | 94 | .. automodule:: ppl.generator 95 | :members: 96 | :undoc-members: 97 | :show-inheritance: 98 | 99 | Module `ppl.polyhedron` 100 | ----------------------- 101 | 102 | .. automodule:: ppl.polyhedron 103 | :members: 104 | :undoc-members: 105 | :show-inheritance: 106 | 107 | Module `ppl.mip_problem` 108 | ------------------------ 109 | 110 | .. automodule:: ppl.mip_problem 111 | :members: 112 | :undoc-members: 113 | :show-inheritance: 114 | 115 | Module `ppl.congruence` 116 | ----------------------- 117 | 118 | .. automodule:: ppl.congruence 119 | :members: 120 | :undoc-members: 121 | :show-inheritance: 122 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | PPL Python wrapper 2 | ================== 3 | 4 | This Python package provides a wrapper to the C++ `Parma Polyhedra Library 5 | (PPL) `_. 6 | 7 | The whole package started as a fork of a tiny part of the `Sage 8 | `_ software. 9 | 10 | How it works 11 | ------------ 12 | 13 | The names of objects and methods are the same as in the library: 14 | 15 | .. code:: python 16 | 17 | >>> import ppl 18 | >>> x = ppl.Variable(0) 19 | >>> y = ppl.Variable(1) 20 | >>> z = ppl.Variable(2) 21 | >>> cs = ppl.Constraint_System() 22 | >>> cs.insert(x >= 0) 23 | >>> cs.insert(y >= 0) 24 | >>> cs.insert(z >= 0) 25 | >>> cs.insert(x + y + z == 1) 26 | >>> poly = ppl.C_Polyhedron(cs) 27 | >>> poly.minimized_generators() 28 | Generator_System {point(1/1, 0/1, 0/1), point(0/1, 1/1, 0/1), point(0/1, 0/1, 1/1)} 29 | 30 | The available objects and functions from the `ppl` Python module are: 31 | 32 | - `Variable`, `Variables_Set`, `Linear_Expression` (defined in `ppl.linear_algebra`) 33 | 34 | - `MIP_Problem` (defined in `ppl.mip_problem`) 35 | 36 | - `C_Polyhedron`, `NNC_Polyhedron` (defined in `ppl.polyhedron`) 37 | 38 | - `Generator`, `Generator_System`, `Poly_Gen_Relation`, `point`, 39 | `closure_point`, `ray`, `line` (defined in `ppl.generator`) 40 | 41 | - `Constraint`, `Constraint_System`, `Poly_Con_Relation`, 42 | `inequality`, `equation`, `strict_inequality` (defined in `ppl.constraint`) 43 | 44 | Installation 45 | ------------ 46 | 47 | The project is available at `Python Package Index `_ and 48 | can be installed with pip:: 49 | 50 | $ pip install pplpy 51 | 52 | Note that if you have gmp and ppl installed in a non standard directory (e.g. you use brew 53 | on MacOSX) then you need to set appropriately the variables `CFLAGS` before calling `pip`. For 54 | example:: 55 | 56 | $ export CFLAGS="-I/path/to/gmp/include/ -L/path/to/gmp/lib/ -I/path/to/ppl/include/ -L/path/to/ppl/lib $CFLAGS" 57 | $ pip install pplpy 58 | 59 | Using from Cython 60 | ----------------- 61 | 62 | All Python classes from pplpy are extension types and can be used with Cython. Each 63 | extension type carries an attribute `thisptr` that holds a pointer to 64 | the corresponding C++ object from ppl. 65 | 66 | A complete example is provided with the files `tests/testpplpy.pyx` and `tests/setup.py`. 67 | 68 | Source 69 | ------ 70 | 71 | You can find the latest version of the source code on github: 72 | https://github.com/sagemath/pplpy 73 | 74 | Documentation 75 | ------------- 76 | 77 | An online version of the documentation is available at https://www.sagemath.org/pplpy/ 78 | 79 | Compiling the html documentation requires make and `sphinx `_. 80 | Before building the documentation, you need to install the pplpy package (sphinx uses Python introspection). 81 | The documentation source code is contained in the repository `docs` where there is a standard 82 | Makefile with a target `html`. Running `make html` in the `docs` repository builds the documentation 83 | inside `docs/build/html`. For more configuration options, run `make help`. 84 | 85 | License 86 | ------- 87 | 88 | pplpy is distributed under the terms of the GNU General Public License (GPL) 89 | published by the Free Software Foundation; either version 3 of 90 | the License, or (at your option) any later version. See http://www.gnu.org/licenses/. 91 | 92 | Requirements 93 | ------------ 94 | 95 | - `PPL `_ 96 | 97 | - `Cython `_ (tested with both 0.29 and 3.0) 98 | 99 | - `cysignals `_ 100 | 101 | - `gmpy2 `_ 102 | 103 | On Debian/Ubuntu systems the dependencies can be installed with:: 104 | 105 | $ sudo apt-get install libgmp-dev libmpfr-dev libmpc-dev libppl-dev cython3 python3-gmpy2 python3-cysignals-pari 106 | -------------------------------------------------------------------------------- /ppl/bit_arrays.pyx: -------------------------------------------------------------------------------- 1 | # distutils: language = c++ 2 | # distutils: libraries = gmp ppl m 3 | #***************************************************************************** 4 | # Copyright (C) 2018 Vincent Delecroix 5 | # 6 | # Distributed under the terms of the GNU General Public License (GPL) 7 | # as published by the Free Software Foundation; either version 3 of 8 | # the License, or (at youroption) any later version. 9 | # http://www.gnu.org/licenses/ 10 | #***************************************************************************** 11 | 12 | from libc.limits cimport ULONG_MAX 13 | 14 | from .ppl_decl cimport PPL_Bit_Row 15 | 16 | cdef class Bit_Row(object): 17 | r""" 18 | A bit row 19 | 20 | This can be considered as a subset of the non-negative integers (with 21 | upper bound the maximum value ``ULONG_MAX`` that fits in an 22 | ``unsigned long``). 23 | """ 24 | def __cinit__(self): 25 | self.thisptr = new PPL_Bit_Row() 26 | 27 | def __dealloc__(self): 28 | del self.thisptr 29 | 30 | def __repr__(self): 31 | r""" 32 | Examples: 33 | 34 | >>> from ppl import Bit_Row 35 | >>> r = Bit_Row() 36 | >>> r 37 | {} 38 | >>> r.set(2); r.set(12) 39 | >>> r 40 | {2, 12} 41 | """ 42 | cdef list l = [] 43 | cdef unsigned long k = self.thisptr.first() 44 | while k != ULONG_MAX: 45 | l.append(str(k)) 46 | k = self.thisptr.next(k) 47 | return "{" + ", ".join(l) + "}" 48 | 49 | def __hash__(self): 50 | r""" 51 | Examples: 52 | 53 | >>> from ppl import Bit_Row 54 | >>> r = Bit_Row() 55 | >>> hash(r) 56 | Traceback (most recent call last): 57 | ... 58 | TypeError: Bit_Row unhashable 59 | """ 60 | raise TypeError("Bit_Row unhashable") 61 | 62 | def set(self, unsigned long k): 63 | r""" 64 | Set the bit in position ``k`` 65 | 66 | Examples: 67 | 68 | >>> from ppl import Bit_Row 69 | >>> r = Bit_Row() 70 | >>> r.set(2); r.set(34); r.set(12) 71 | >>> r 72 | {2, 12, 34} 73 | >>> r.set(22) 74 | >>> r 75 | {2, 12, 22, 34} 76 | """ 77 | self.thisptr.set(k) 78 | 79 | def set_until(self, unsigned long k): 80 | r""" 81 | Set bits up to position ``k`` (excluded) 82 | 83 | Examples: 84 | 85 | >>> from ppl import Bit_Row 86 | >>> r = Bit_Row() 87 | >>> r.set_until(5) 88 | >>> r 89 | {0, 1, 2, 3, 4} 90 | """ 91 | self.thisptr.set_until(k) 92 | 93 | def clear_from(self, unsigned long k): 94 | r""" 95 | Clear bits from position ``k`` (included) onward 96 | 97 | Examples: 98 | 99 | >>> from ppl import Bit_Row 100 | >>> r = Bit_Row() 101 | >>> r.set_until(10) 102 | >>> r.clear_from(5) 103 | >>> r 104 | {0, 1, 2, 3, 4} 105 | """ 106 | self.thisptr.clear_from(k) 107 | 108 | def clear(self): 109 | r""" 110 | Clear all the bits of the row 111 | 112 | Examples: 113 | 114 | >>> from ppl import Bit_Row 115 | >>> r = Bit_Row() 116 | >>> r.set(1); r.set(3) 117 | >>> r 118 | {1, 3} 119 | >>> r.clear() 120 | >>> r 121 | {} 122 | """ 123 | self.thisptr.clear() 124 | 125 | def first(self): 126 | r""" 127 | Return the index of the first set bit or ``-1`` if no bit is set. 128 | 129 | Examples: 130 | 131 | >>> from ppl import Bit_Row 132 | >>> r = Bit_Row() 133 | >>> r.first() == -1 134 | True 135 | >>> r.set(127) 136 | >>> r.first() == 127 137 | True 138 | >>> r.set(2) 139 | >>> r.first() == 2 140 | True 141 | >>> r.set(253) 142 | >>> r.first() == 2 143 | True 144 | >>> r.clear() 145 | >>> r.first() == -1 146 | True 147 | """ 148 | cdef unsigned long k = self.thisptr.first() 149 | if k == ULONG_MAX: 150 | return -1 151 | else: 152 | return k 153 | 154 | def last(self): 155 | r""" 156 | Return the index of the last set bit or ``-1`` if no bit is set. 157 | 158 | Examples: 159 | 160 | >>> from ppl import Bit_Row 161 | >>> r = Bit_Row() 162 | >>> r.last() == -1 163 | True 164 | >>> r.set(127) 165 | >>> r.last() == 127 166 | True 167 | >>> r.set(2) 168 | >>> r.last() == 127 169 | True 170 | >>> r.set(253) 171 | >>> r.last() == 253 172 | True 173 | >>> r.clear() 174 | >>> r.last() == -1 175 | True 176 | """ 177 | cdef unsigned long k = self.thisptr.last() 178 | if k == ULONG_MAX: 179 | return -1 180 | else: 181 | return k 182 | 183 | cdef class Bit_Matrix(object): 184 | pass 185 | -------------------------------------------------------------------------------- /.github/workflows/dist.yml: -------------------------------------------------------------------------------- 1 | name: Distributions 2 | 3 | on: 4 | push: 5 | pull_request: 6 | workflow_dispatch: 7 | 8 | concurrency: 9 | # Cancel previous runs of this workflow for the same branch 10 | group: ${{ github.workflow }}-${{ github.ref }} 11 | cancel-in-progress: true 12 | 13 | jobs: 14 | 15 | sdists_for_pypi: 16 | name: Build sdist (and upload to PyPI on release tags) 17 | runs-on: ubuntu-latest 18 | env: 19 | CAN_DEPLOY: ${{ secrets.SAGEMATH_PYPI_API_TOKEN != '' }} 20 | steps: 21 | - uses: actions/checkout@v4 22 | - uses: actions/setup-python@v4 23 | - name: make sdist 24 | run: | 25 | python3 -m pip install build 26 | python3 -m build --sdist 27 | - uses: actions/upload-artifact@v5 28 | with: 29 | path: "dist/*.tar.gz" 30 | name: dist 31 | - uses: pypa/gh-action-pypi-publish@release/v1 32 | with: 33 | user: __token__ 34 | password: ${{ secrets.SAGEMATH_PYPI_API_TOKEN }} 35 | skip_existing: true 36 | verbose: true 37 | if: env.CAN_DEPLOY == 'true' && github.event_name == 'push' && startsWith(github.ref, 'refs/tags') 38 | 39 | build_wheels: 40 | name: Build wheels on ${{ matrix.os }} 41 | runs-on: ${{ matrix.os }} 42 | needs: sdists_for_pypi 43 | strategy: 44 | fail-fast: false 45 | matrix: 46 | os: 47 | - ubuntu-latest 48 | - macos-latest 49 | - ubuntu-24.04-arm 50 | - macos-15-intel 51 | env: 52 | # SPKGs to install as system packages 53 | SPKGS: _bootstrap _prereq gmp mpfr mpc 54 | # Non-Python packages to install as spkgs 55 | TARGETS_PRE: gmp mpfr mpc ppl-ensure 56 | # Environment during wheel build 57 | CIBW_ENVIRONMENT: "PATH=$(pwd)/local/bin:$PATH CPATH=$(pwd)/local/include:$CPATH LIBRARY_PATH=$(pwd)/local/lib:$LIBRARY_PATH LD_LIBRARY_PATH=$(pwd)/local/lib:$LD_LIBRARY_PATH PKG_CONFIG_PATH=$(pwd)/local/share/pkgconfig:$PKG_CONFIG_PATH ACLOCAL_PATH=/usr/share/aclocal" 58 | # Use 'build', not 'pip wheel' 59 | CIBW_BUILD_FRONTEND: build 60 | steps: 61 | - uses: actions/checkout@v4 62 | with: 63 | repository: sagemath/sage 64 | ref: develop 65 | 66 | - uses: actions/download-artifact@v6 67 | with: 68 | name: dist 69 | path: dist 70 | 71 | - uses: actions/setup-python@v5 72 | # As of 2024-02-03, the macOS M1 runners do not have preinstalled python or pipx. 73 | # Installing pipx follows the approach of https://github.com/pypa/cibuildwheel/pull/1743 74 | id: python 75 | with: 76 | python-version: "3.12 - 3.14" 77 | update-environment: false 78 | 79 | - name: Build platform wheels 80 | # We build the wheel from the sdist. 81 | # But we must run cibuildwheel with the unpacked source directory, not a tarball, 82 | # so that SAGE_ROOT is copied into the build containers. 83 | # 84 | # In the CIBW_BEFORE_ALL phase, we install libraries using the Sage distribution. 85 | # https://cibuildwheel.readthedocs.io/en/stable/options/#before-all 86 | run: | 87 | "${{ steps.python.outputs.python-path }}" -m pip install pipx 88 | export PATH=build/bin:$PATH 89 | export CIBW_BEFORE_ALL="( $(sage-print-system-package-command debian --yes --no-install-recommends install $(sage-get-system-packages debian $SPKGS)) || $(sage-print-system-package-command fedora --yes --no-install-recommends install $(sage-get-system-packages fedora $SPKGS | sed s/pkg-config/pkgconfig/)) || ( $(sage-print-system-package-command homebrew --yes --no-install-recommends install $(sage-get-system-packages homebrew $SPKGS)) || $(sage-print-system-package-command alpine --yes --no-install-recommends install $(sage-get-system-packages alpine $SPKGS)) || echo error ignored) ) && ./bootstrap && ./configure --enable-build-as-root --enable-fat-binary --disable-meson-check --disable-boost && MAKE=\"make -j6\" make V=0 $TARGETS_PRE" 90 | mkdir -p unpacked 91 | for pkg in pplpy; do 92 | (cd unpacked && tar xfz - ) < dist/$pkg*.tar.gz 93 | "${{ steps.python.outputs.python-path }}" -m pipx run cibuildwheel==3.2.1 unpacked/$pkg* 94 | done 95 | 96 | - uses: actions/upload-artifact@v5 97 | with: 98 | name: wheels-${{ matrix.os }} 99 | path: ./wheelhouse/*.whl 100 | 101 | pypi-publish: 102 | # https://github.com/pypa/gh-action-pypi-publish 103 | name: Upload wheels to PyPI 104 | needs: build_wheels 105 | if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags') 106 | runs-on: ubuntu-latest 107 | env: 108 | CAN_DEPLOY: ${{ secrets.SAGEMATH_PYPI_API_TOKEN != '' }} 109 | steps: 110 | 111 | - uses: actions/download-artifact@v6 112 | with: 113 | name: wheels 114 | path: wheelhouse 115 | 116 | - name: Publish package distributions to PyPI 117 | uses: pypa/gh-action-pypi-publish@release/v1 118 | with: 119 | user: __token__ 120 | password: ${{ secrets.SAGEMATH_PYPI_API_TOKEN }} 121 | packages_dir: wheelhouse/ 122 | skip_existing: true 123 | verbose: true 124 | if: env.CAN_DEPLOY == 'true' 125 | -------------------------------------------------------------------------------- /ppl/__init__.py: -------------------------------------------------------------------------------- 1 | r""" 2 | Cython wrapper for the Parma Polyhedra Library (PPL) 3 | 4 | The Parma Polyhedra Library (PPL) is a library for polyhedral computations over 5 | the rationals. This interface tries to reproduce the C++ API as faithfully as possible 6 | in Python. For example, the following C++ excerpt: 7 | 8 | .. code-block:: c++ 9 | 10 | Variable x(0); 11 | Variable y(1); 12 | Constraint_System cs; 13 | cs.insert(x >= 0); 14 | cs.insert(x <= 3); 15 | cs.insert(y >= 0); 16 | cs.insert(y <= 3); 17 | C_Polyhedron poly_from_constraints(cs); 18 | 19 | translates into: 20 | 21 | >>> from ppl import Variable, Constraint_System, C_Polyhedron 22 | >>> x = Variable(0) 23 | >>> y = Variable(1) 24 | >>> cs = Constraint_System() 25 | >>> cs.insert(x >= 0) 26 | >>> cs.insert(x <= 3) 27 | >>> cs.insert(y >= 0) 28 | >>> cs.insert(y <= 3) 29 | >>> poly_from_constraints = C_Polyhedron(cs) 30 | 31 | The same polyhedron constructed from generators: 32 | 33 | >>> from ppl import Variable, Generator_System, C_Polyhedron, point 34 | >>> gs = Generator_System() 35 | >>> gs.insert(point(0*x + 0*y)) 36 | >>> gs.insert(point(0*x + 3*y)) 37 | >>> gs.insert(point(3*x + 0*y)) 38 | >>> gs.insert(point(3*x + 3*y)) 39 | >>> poly_from_generators = C_Polyhedron(gs) 40 | 41 | Rich comparisons test equality/inequality and strict/non-strict 42 | containment: 43 | 44 | >>> poly_from_generators == poly_from_constraints 45 | True 46 | >>> poly_from_generators >= poly_from_constraints 47 | True 48 | >>> poly_from_generators < poly_from_constraints 49 | False 50 | >>> poly_from_constraints.minimized_generators() 51 | Generator_System {point(0/1, 0/1), point(0/1, 3/1), point(3/1, 0/1), point(3/1, 3/1)} 52 | >>> poly_from_constraints.minimized_constraints() 53 | Constraint_System {-x0+3>=0, -x1+3>=0, x0>=0, x1>=0} 54 | 55 | As we see above, the library is generally easy to use. There are a few 56 | pitfalls that are not entirely obvious without consulting the 57 | documentation, in particular: 58 | 59 | * There are no vectors used to describe :class:`Generator` (points, 60 | closure points, rays, lines) or :class:`Constraint` (strict 61 | inequalities, non-strict inequalities, or equations). Coordinates 62 | are always specified via linear polynomials in :class:`Variable` 63 | 64 | * All coordinates of rays and lines as well as all coefficients of 65 | constraint relations are (arbitrary precision) integers. Only the 66 | generators :func:`point` and :func:`closure_point` allow one to 67 | specify an overall divisor of the otherwise integral 68 | coordinates. For example: 69 | 70 | >>> from ppl import Variable, point 71 | >>> x = Variable(0); y = Variable(1) 72 | >>> p = point( 2*x+3*y, 5 ); p 73 | point(2/5, 3/5) 74 | >>> p.coefficient(x) 75 | mpz(2) 76 | >>> p.coefficient(y) 77 | mpz(3) 78 | >>> p.divisor() 79 | mpz(5) 80 | 81 | * PPL supports (topologically) closed polyhedra 82 | (:class:`C_Polyhedron`) as well as not necessarily closed polyhedra 83 | (:class:`NNC_Polyhedron`). Only the latter allows closure points 84 | (=points of the closure but not of the actual polyhedron) and strict 85 | inequalities (``>`` and ``<``) 86 | 87 | The naming convention for the C++ classes is that they start with 88 | ``PPL_``, for example, the original ``Linear_Expression`` becomes 89 | ``PPL_Linear_Expression``. The Python wrapper has the same name as the 90 | original library class, that is, just ``Linear_Expression``. In short: 91 | 92 | * If you are using the Python wrapper (if in doubt: that's you), then 93 | you use the same names as the PPL C++ class library. 94 | 95 | * If you are writing your own Cython code, you can access the 96 | underlying C++ classes by adding the prefix ``PPL_``. 97 | 98 | Finally, PPL is fast. For example, here is the permutahedron of 5 99 | basis vectors: 100 | 101 | >>> from ppl import Variable, Generator_System, point, C_Polyhedron 102 | >>> basis = range(0,5) 103 | >>> x = [ Variable(i) for i in basis ] 104 | >>> gs = Generator_System(); 105 | >>> from itertools import permutations 106 | >>> for coeff in permutations(basis): 107 | ... gs.insert(point( sum( (coeff[i]+1)*x[i] for i in basis ) )) 108 | >>> C_Polyhedron(gs) 109 | A 4-dimensional polyhedron in QQ^5 defined as the convex hull of 120 points 110 | 111 | DIFFERENCES VS. C++ 112 | 113 | Since Python and C++ syntax are not always compatible, there are 114 | necessarily some differences. The main ones are: 115 | 116 | * The :class:`Linear_Expression` also accepts an iterable as input for 117 | the homogeneous coefficients. 118 | 119 | AUTHORS: 120 | 121 | - Volker Braun (2010): initial version (within Sage). 122 | - Risan (2012): extension for MIP_Problem class (within Sage) 123 | - Vincent Delecroix (2016-2020): convert Sage files into a standalone Python package, 124 | interface bit_array, interface congruence 125 | - Vincent Klein (2017): improve doctest support and Python 3 compatibility 126 | Split the main code into several files. 127 | Remove the _mutable_immutable class. 128 | """ 129 | 130 | __version__ = "0.8.10" 131 | 132 | from .linear_algebra import ( 133 | Variable, Variables_Set, Linear_Expression, 134 | ) 135 | 136 | from .mip_problem import MIP_Problem 137 | 138 | from .polyhedron import C_Polyhedron, NNC_Polyhedron 139 | 140 | from .generator import Generator, Generator_System, Poly_Gen_Relation 141 | line = Generator.line 142 | point = Generator.point 143 | ray = Generator.ray 144 | closure_point = Generator.closure_point 145 | 146 | from .constraint import ( 147 | Constraint, Constraint_System, Poly_Con_Relation, 148 | inequality, equation, strict_inequality) 149 | 150 | from .congruence import Congruence, Congruence_System 151 | 152 | from .bit_arrays import Bit_Row, Bit_Matrix 153 | -------------------------------------------------------------------------------- /docs/source/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # pplpy documentation build configuration file 4 | # 5 | 6 | import sys 7 | import os 8 | 9 | # If extensions (or modules to document with autodoc) are in another directory, 10 | # add these directories to sys.path here. If the directory is relative to the 11 | # documentation root, use os.path.abspath to make it absolute, like shown here. 12 | #sys.path.insert(0, os.path.abspath('/home/vincent/programming/ppl/')) 13 | 14 | # -- General configuration ------------------------------------------------ 15 | 16 | # Sphinx extension modules 17 | extensions = [ 18 | 'sphinx.ext.autodoc', 19 | 'sphinx.ext.doctest', 20 | 'sphinx.ext.intersphinx', 21 | 'sphinx.ext.todo', 22 | 'sphinx.ext.coverage', 23 | 'sphinx.ext.mathjax', 24 | 'sphinx.ext.ifconfig', 25 | 'sphinx.ext.viewcode', 26 | ] 27 | 28 | # Add any paths that contain templates here, relative to this directory. 29 | templates_path = ['_templates'] 30 | 31 | # The suffix of source filenames. 32 | source_suffix = '.rst' 33 | 34 | # The master toctree document. 35 | master_doc = 'index' 36 | 37 | # General information about the project. 38 | project = u'pplpy' 39 | copyright = u'2016, Vincent Delecroix' 40 | 41 | # The version info for the project you're documenting, acts as replacement for 42 | # |version| and |release|, also used in various other places throughout the 43 | # built documents. 44 | # 45 | # The short X.Y version. 46 | from ppl import __version__ as release 47 | 48 | version = release 49 | 50 | # List of patterns, relative to source directory, that match files and 51 | # directories to ignore when looking for source files. 52 | exclude_patterns = [] 53 | 54 | # The name of the Pygments (syntax highlighting) style to use. 55 | pygments_style = 'sphinx' 56 | 57 | # If true, keep warnings as "system message" paragraphs in the built documents. 58 | #keep_warnings = False 59 | 60 | # -- Options for HTML output ---------------------------------------------- 61 | 62 | # The theme to use for HTML and HTML Help pages. See the documentation for 63 | # a list of builtin themes. 64 | html_theme = 'default' 65 | 66 | # The name of an image file (relative to this directory) to place at the top 67 | # of the sidebar. 68 | #html_logo = None 69 | 70 | # The name of an image file (within the static path) to use as favicon of the 71 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 72 | # pixels large. 73 | #html_favicon = None 74 | 75 | # Add any paths that contain custom static files (such as style sheets) here, 76 | # relative to this directory. They are copied after the builtin static files, 77 | # so a file named "default.css" will overwrite the builtin "default.css". 78 | # html_static_path = ['_static'] 79 | 80 | # Add any extra paths that contain custom files (such as robots.txt or 81 | # .htaccess) here, relative to this directory. These files are copied 82 | # directly to the root of the documentation. 83 | #html_extra_path = [] 84 | 85 | # If false, no module index is generated. 86 | #html_domain_indices = True 87 | 88 | # If false, no index is generated. 89 | #html_use_index = True 90 | 91 | # If true, the index is split into individual pages for each letter. 92 | #html_split_index = False 93 | 94 | # If true, links to the reST sources are added to the pages. 95 | #html_show_sourcelink = True 96 | 97 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. 98 | #html_show_sphinx = True 99 | 100 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. 101 | #html_show_copyright = True 102 | 103 | # If true, an OpenSearch description file will be output, and all pages will 104 | # contain a tag referring to it. The value of this option must be the 105 | # base URL from which the finished HTML is served. 106 | #html_use_opensearch = '' 107 | 108 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 109 | #html_file_suffix = None 110 | 111 | # Output file base name for HTML help builder. 112 | htmlhelp_basename = 'pplpydoc' 113 | 114 | 115 | # -- Options for LaTeX output --------------------------------------------- 116 | 117 | latex_elements = { 118 | # The paper size ('letterpaper' or 'a4paper'). 119 | 'papersize': 'a4paper', 120 | 121 | # The font size ('10pt', '11pt' or '12pt'). 122 | 'pointsize': '10pt', 123 | 124 | # Additional stuff for the LaTeX preamble. 125 | #'preamble': '', 126 | } 127 | 128 | # Grouping the document tree into LaTeX files. List of tuples 129 | # (source start file, target name, title, 130 | # author, documentclass [howto, manual, or own class]). 131 | latex_documents = [ 132 | ('index', 'pplpy.tex', u'pplpy Documentation', 133 | u'Vincent Delecroix', 'manual'), 134 | ] 135 | 136 | # The name of an image file (relative to this directory) to place at the top of 137 | # the title page. 138 | #latex_logo = None 139 | 140 | # For "manual" documents, if this is true, then toplevel headings are parts, 141 | # not chapters. 142 | #latex_use_parts = False 143 | 144 | # If true, show page references after internal links. 145 | #latex_show_pagerefs = False 146 | 147 | # If true, show URL addresses after external links. 148 | #latex_show_urls = False 149 | 150 | # Documents to append as an appendix to all manuals. 151 | #latex_appendices = [] 152 | 153 | # If false, no module index is generated. 154 | #latex_domain_indices = True 155 | 156 | 157 | # -- Options for manual page output --------------------------------------- 158 | 159 | # One entry per manual page. List of tuples 160 | # (source start file, name, description, authors, manual section). 161 | man_pages = [ 162 | ('index', 'pplpy', u'pplpy Documentation', 163 | [u'Vincent Delecroix'], 1) 164 | ] 165 | 166 | # If true, show URL addresses after external links. 167 | #man_show_urls = False 168 | 169 | 170 | # -- Options for Texinfo output ------------------------------------------- 171 | 172 | # Grouping the document tree into Texinfo files. List of tuples 173 | # (source start file, target name, title, author, 174 | # dir menu entry, description, category) 175 | texinfo_documents = [ 176 | ('index', 'pplpy', u'pplpy Documentation', 177 | u'Vincent Delecroix', 'pplpy', 'One line description of project.', 178 | 'Miscellaneous'), 179 | ] 180 | 181 | # Documents to append as an appendix to all manuals. 182 | #texinfo_appendices = [] 183 | 184 | # If false, no module index is generated. 185 | #texinfo_domain_indices = True 186 | 187 | # How to display URL addresses: 'footnote', 'no', or 'inline'. 188 | #texinfo_show_urls = 'footnote' 189 | 190 | # If true, do not generate a @detailmenu in the "Top" node's menu. 191 | #texinfo_no_detailmenu = False 192 | -------------------------------------------------------------------------------- /ppl/congruence.pyx: -------------------------------------------------------------------------------- 1 | # distutils: language = c++ 2 | # distutils: libraries = gmp gmpxx ppl m 3 | #***************************************************************************** 4 | # Copyright (C) 2020 Vincent Delecroix 5 | # 6 | # Distributed under the terms of the GNU General Public License (GPL) 7 | # as published by the Free Software Foundation; either version 3 of 8 | # the License, or (at youroption) any later version. 9 | # http://www.gnu.org/licenses/ 10 | #***************************************************************************** 11 | 12 | from cython.operator cimport dereference as deref 13 | 14 | from gmpy2 cimport GMPy_MPZ_From_mpz, mpz, import_gmpy2 15 | 16 | from .constraint cimport Constraint 17 | from .linear_algebra cimport Variable, Linear_Expression, PPL_Coefficient_from_pyobject 18 | 19 | import_gmpy2() 20 | 21 | 22 | def _dummy(): 23 | raise ValueError 24 | 25 | 26 | cdef class Congruence(object): 27 | r""" 28 | Wrapper for PPL's ``Congruence`` class. 29 | 30 | >>> import ppl 31 | >>> x = ppl.Variable(0) 32 | >>> y = ppl.Variable(1) 33 | >>> ppl.Congruence(x + 2*y - 1, 7) 34 | x0+2*x1-1==0 (mod 7) 35 | >>> ppl.Congruence(x + y == 2, 5) 36 | x0+x1-2==0 (mod 5) 37 | """ 38 | def __init__(self, arg=None, mod=None): 39 | if arg is None: 40 | self.thisptr = new PPL_Congruence() 41 | elif isinstance(arg, Congruence): 42 | self.thisptr = new PPL_Congruence(( arg).thisptr[0]) 43 | elif isinstance(arg, Variable): 44 | self.thisptr = new PPL_Congruence() 45 | if mod is None: 46 | mod = mpz(1) 47 | self.thisptr[0] = modulo(PPL_Linear_Expression(( arg).thisptr[0]), 48 | PPL_Coefficient_from_pyobject(mod)) 49 | elif isinstance(arg, Linear_Expression): 50 | self.thisptr = new PPL_Congruence() 51 | if mod is None: 52 | mod = mpz(1) 53 | self.thisptr[0] = modulo(( arg).thisptr[0], 54 | PPL_Coefficient_from_pyobject(mod)) 55 | elif isinstance(arg, Constraint): 56 | self.thisptr = new PPL_Congruence(( arg).thisptr[0]) 57 | if mod is None: 58 | mod = mpz(1) 59 | self.thisptr.set_modulus(PPL_Coefficient_from_pyobject(mod)) 60 | else: 61 | raise TypeError("invalid argument for Congruence") 62 | 63 | def __cinit__(self): 64 | self.thisptr = NULL 65 | 66 | def __dealloc__(self): 67 | del self.thisptr 68 | 69 | def is_equal(self, Congruence other): 70 | r""" 71 | Return whether ``self`` is equal to ``other``. 72 | 73 | Examples: 74 | 75 | >>> import ppl 76 | >>> x = ppl.Variable(0) 77 | >>> Congruence(x + 1, 3).is_equal(Congruence(x + 1, 3)) 78 | True 79 | >>> Congruence(x, 3).is_equal(Congruence(x - 2, 3)) 80 | False 81 | >>> Congruence(x, 3).is_equal(Congruence(x , 2)) 82 | False 83 | """ 84 | return ( self).thisptr[0] == ( other).thisptr[0] 85 | 86 | def coefficient(self, v): 87 | r""" 88 | Return the coefficient ``v`` of this congruence. 89 | 90 | Examples: 91 | 92 | >>> import ppl 93 | >>> x = ppl.Variable(0) 94 | >>> y = ppl.Variable(1) 95 | >>> c = (2 * x + y == 1) % 12 96 | >>> c.coefficient(0) 97 | mpz(2) 98 | >>> c.coefficient(x) 99 | mpz(2) 100 | 101 | Note that contrarily to :class:`Linear_Expression` the congruences raise 102 | an error when trying to access a coefficient beyond the dimension 103 | 104 | >>> c.coefficient(ppl.Variable(13)) 105 | Traceback (most recent call last): 106 | ... 107 | ValueError: PPL::Congruence::coefficient(v): 108 | this->space_dimension() == 2, v.space_dimension() == 14. 109 | """ 110 | cdef Variable vv 111 | if type(v) is Variable: 112 | vv = v 113 | else: 114 | vv = Variable(v) 115 | return GMPy_MPZ_From_mpz(self.thisptr.coefficient(vv.thisptr[0]).get_mpz_t()) 116 | 117 | def coefficients(self): 118 | r""" 119 | Return the coefficients of this congruence as a tuple. 120 | 121 | Examples: 122 | 123 | >>> import ppl 124 | >>> x = ppl.Variable(0) 125 | >>> y = ppl.Variable(1) 126 | >>> t = ppl.Variable(3) 127 | >>> c = ppl.Congruence(x + 2*y + t - 1, 7) 128 | >>> c.coefficients() 129 | (mpz(1), mpz(2), mpz(0), mpz(1)) 130 | """ 131 | cdef int d = self.space_dimension() 132 | cdef int i 133 | coeffs = [] 134 | for i in range(0, d): 135 | coeffs.append(GMPy_MPZ_From_mpz(self.thisptr.coefficient(PPL_Variable(i)).get_mpz_t())) 136 | return tuple(coeffs) 137 | 138 | def modulus(self): 139 | r""" 140 | Return the modulus of this congruence. 141 | 142 | Examples: 143 | 144 | >>> import ppl 145 | >>> x = ppl.Variable(0) 146 | >>> y = ppl.Variable(1) 147 | >>> c = ppl.Congruence(x + 2*y - 3, 7) 148 | >>> c.modulus() 149 | mpz(7) 150 | """ 151 | return GMPy_MPZ_From_mpz(self.thisptr.modulus().get_mpz_t()) 152 | 153 | def inhomogeneous_term(self): 154 | r""" 155 | Return the inhomogeneous term of this congruence. 156 | 157 | Examples: 158 | 159 | >>> import ppl 160 | >>> x = ppl.Variable(0) 161 | >>> y = ppl.Variable(1) 162 | >>> c = ppl.Congruence(x + 2*y - 3, 7) 163 | >>> c.inhomogeneous_term() 164 | mpz(-3) 165 | """ 166 | return GMPy_MPZ_From_mpz(self.thisptr.inhomogeneous_term().get_mpz_t()) 167 | 168 | def space_dimension(self): 169 | return self.thisptr.space_dimension() 170 | 171 | def __repr__(self): 172 | s = '' 173 | v = [Variable(i) for i in range(self.space_dimension())] 174 | e = sum(self.coefficient(x)*x for x in v) 175 | e += self.inhomogeneous_term() 176 | s = repr(e) + '==0 (mod %s)' % self.modulus() 177 | return s 178 | 179 | def __reduce__(self): 180 | r""" 181 | >>> from ppl import Variable, Congruence, Congruence_System 182 | >>> from pickle import loads, dumps 183 | >>> x = Variable(0) 184 | >>> y = Variable(1) 185 | >>> z = Variable(2) 186 | >>> c1 = Congruence(2*x + 3*y - 5*z == 3, 12) 187 | >>> c1 188 | 2*x0+3*x1-5*x2-3==0 (mod 12) 189 | >>> loads(dumps(c1)) 190 | 2*x0+3*x1-5*x2-3==0 (mod 12) 191 | >>> assert c1.is_equal(loads(dumps(c1))) 192 | """ 193 | le = Linear_Expression(self.coefficients(), self.inhomogeneous_term()) 194 | return (congruence, (le == 0, self.modulus())) 195 | 196 | cdef class Congruence_System(object): 197 | r""" 198 | Wrapper for PPL's ``Congruence_System`` class. 199 | 200 | >>> from ppl import Variable, Congruence, Congruence_System 201 | >>> x = Variable(0) 202 | >>> y = Variable(1) 203 | >>> z = Variable(2) 204 | >>> c1 = Congruence(2*x + 3*y - 5*z == 0, 12) 205 | >>> c2 = Congruence(4*x + y == 5, 18) 206 | >>> C = Congruence_System() 207 | >>> C.insert(c1) 208 | >>> C.insert(c2) 209 | >>> C 210 | Congruence_System {2*x0+3*x1-5*x2==0 (mod 12), 4*x0+x1+13==0 (mod 18)} 211 | """ 212 | def __init__(self, arg=None): 213 | if arg is None: 214 | self.thisptr = new PPL_Congruence_System() 215 | elif isinstance(arg, Congruence): 216 | c = arg 217 | self.thisptr = new PPL_Congruence_System(c.thisptr[0]) 218 | elif isinstance(arg, Congruence_System): 219 | cs = arg 220 | self.thisptr = new PPL_Congruence_System(cs.thisptr[0]) 221 | elif isinstance(arg, (list, tuple)): 222 | self.thisptr = new PPL_Congruence_System() 223 | for congruence in arg: 224 | self.insert(congruence) 225 | 226 | def ascii_dump(self): 227 | r""" 228 | Write an ASCII dump of this congruence to stderr. 229 | 230 | Examples: 231 | 232 | >>> cmd = 'from ppl import Variable, Congruence_System\n' 233 | >>> cmd += 'x = Variable(0)\n' 234 | >>> cmd += 'y = Variable(1)\n' 235 | >>> cmd += 'cs = Congruence_System( (3*x == 2*y+1) % 7 )\n' 236 | >>> cmd += 'cs.ascii_dump()\n' 237 | >>> import subprocess, sys 238 | >>> proc = subprocess.Popen([sys.executable, '-c', cmd], stderr=subprocess.PIPE) 239 | >>> out, err = proc.communicate() 240 | >>> print(str(err.decode('ascii'))) 241 | 1 x 2 SPARSE 242 | size 3 6 3 -2 m 7 243 | 244 | """ 245 | self.thisptr.ascii_dump() 246 | 247 | def __len__(self): 248 | r""" 249 | Return the number of congruences in the system. 250 | 251 | Examples: 252 | 253 | >>> from ppl import Variable, Congruence_System 254 | >>> x = Variable(0) 255 | >>> y = Variable(1) 256 | >>> cs = Congruence_System( [(x == 3) % 15, (2*y == 7) % 12]) 257 | >>> len(cs) 258 | 2 259 | >>> cs.insert((2*x + y == 12) % 22) 260 | >>> len(cs) 261 | 3 262 | >>> cs.clear() 263 | >>> len(cs) 264 | 0 265 | """ 266 | cdef Py_ssize_t l = 0 267 | cdef PPL_Congruence_System_iterator * csi_ptr = new PPL_Congruence_System_iterator(self.thisptr[0].begin()) 268 | 269 | while csi_ptr[0] != self.thisptr[0].end(): 270 | l += 1 271 | csi_ptr[0].inc(1) 272 | del csi_ptr 273 | return l 274 | 275 | def __iter__(self): 276 | cdef PPL_Congruence_System_iterator * csi_ptr = new PPL_Congruence_System_iterator(self.thisptr[0].begin()) 277 | 278 | try: 279 | while csi_ptr[0] != self.thisptr[0].end(): 280 | yield _wrap_Congruence(deref(csi_ptr[0].inc(1))) 281 | finally: 282 | del csi_ptr 283 | 284 | def __repr__(self): 285 | s = 'Congruence_System {' 286 | s += ', '.join([repr(c) for c in self]) 287 | s += '}' 288 | return s 289 | 290 | def insert(self, Congruence c): 291 | r""" 292 | Insert the congruence ``c`` into the congruence system. 293 | 294 | Examples: 295 | 296 | >>> from ppl import Variable, Congruence_System 297 | >>> x = Variable(0) 298 | >>> y = Variable(1) 299 | >>> cs = Congruence_System() 300 | >>> cs.insert((3 * x + 2 == 0) % 13) 301 | >>> cs 302 | Congruence_System {3*x0+2==0 (mod 13)} 303 | """ 304 | self.thisptr.insert(c.thisptr[0]) 305 | 306 | def clear(self): 307 | r""" 308 | Remove all congruences from this congruence system. 309 | 310 | >>> from ppl import Variable, Congruence_System 311 | >>> x = Variable(0) 312 | >>> y = Variable(1) 313 | >>> cs = Congruence_System([(3*x+2*y+1 == 3) % 15, (x+2*y + 7 == 0) % 22]) 314 | >>> len(cs) 315 | 2 316 | >>> cs.clear() 317 | >>> len(cs) 318 | 0 319 | """ 320 | self.thisptr.clear() 321 | 322 | def __reduce__(self): 323 | """ 324 | Pickle object. 325 | 326 | Examples: 327 | 328 | >>> from ppl import Variable, Congruence_System 329 | >>> from pickle import loads, dumps 330 | >>> x = Variable(0) 331 | >>> y = Variable(1) 332 | >>> cs = Congruence_System([(3*x+2*y+1 == 3) % 15, (x+2*y + 7 == 0) % 22]) 333 | >>> cs 334 | Congruence_System {3*x0+2*x1+13==0 (mod 15), x0+2*x1+7==0 (mod 22)} 335 | >>> loads(dumps(cs)) 336 | Congruence_System {3*x0+2*x1+13==0 (mod 15), x0+2*x1+7==0 (mod 22)} 337 | """ 338 | return (Congruence_System, (tuple(self),)) 339 | 340 | 341 | cdef _wrap_Congruence(PPL_Congruence congruence): 342 | cdef Congruence c = Congruence.__new__(Congruence) 343 | c.thisptr = new PPL_Congruence(congruence) 344 | return c 345 | 346 | 347 | def congruence(le, m): 348 | return Congruence(le, m) 349 | -------------------------------------------------------------------------------- /ppl/ppl_decl.pxd: -------------------------------------------------------------------------------- 1 | from libcpp cimport bool as cppbool 2 | from libcpp.vector cimport vector as cppvector 3 | 4 | cdef extern from "gmp.h": 5 | # gmp integer 6 | ctypedef struct __mpz_struct: 7 | pass 8 | ctypedef __mpz_struct mpz_t[1] 9 | ctypedef __mpz_struct *mpz_ptr 10 | ctypedef const __mpz_struct *mpz_srcptr 11 | 12 | void mpz_init(mpz_t) 13 | 14 | cdef extern from "gmpxx.h": 15 | # gmp integer 16 | cdef cppclass mpz_class: 17 | mpz_class() 18 | mpz_class(int i) 19 | mpz_class(mpz_t z) 20 | mpz_class(mpz_class) 21 | mpz_t get_mpz_t() 22 | mpz_class operator%(mpz_class, mpz_class) 23 | 24 | cdef extern from "ppl.hh" namespace "Parma_Polyhedra_Library::Generator": 25 | ctypedef enum PPL_GeneratorType "Parma_Polyhedra_Library::Generator::Type": 26 | LINE, RAY, POINT, CLOSURE_POINT 27 | 28 | cdef extern from "ppl.hh" namespace "Parma_Polyhedra_Library::Constraint": 29 | ctypedef enum PPL_ConstraintType "Parma_Polyhedra_Library::Constraint::Type": 30 | EQUALITY, NONSTRICT_INEQUALITY, STRICT_INEQUALITY 31 | 32 | cdef extern from "ppl.hh" namespace "Parma_Polyhedra_Library::MIP_Problem": 33 | ctypedef enum PPL_MIP_Problem_Control_Parameter_Name: 34 | PRICING 35 | ctypedef enum PPL_MIP_Problem_Control_Parameter_Value: 36 | PRICING_STEEPEST_EDGE_FLOAT, PRICING_STEEPEST_EDGE_EXACT, PRICING_TEXTBOOK 37 | 38 | cdef extern from "ppl.hh" namespace "Parma_Polyhedra_Library": 39 | ctypedef size_t PPL_dimension_type "Parma_Polyhedra_Library::dimension_type" 40 | ctypedef mpz_class PPL_Coefficient "Parma_Polyhedra_Library::Coefficient" 41 | cdef cppclass PPL_Variable "Parma_Polyhedra_Library::Variable" 42 | cdef cppclass PPL_Variables_Set "Parma_Polyhedra_Library::Variables_Set" 43 | cdef cppclass PPL_Linear_Expression "Parma_Polyhedra_Library::Linear_Expression" 44 | cdef cppclass PPL_Generator "Parma_Polyhedra_Library::Generator" 45 | cdef cppclass PPL_Generator_System "Parma_Polyhedra_Library::Generator_System" 46 | cdef cppclass PPL_Constraint "Parma_Polyhedra_Library::Constraint" 47 | cdef cppclass PPL_Constraint_System "Parma_Polyhedra_Library::Constraint_System" 48 | cdef cppclass PPL_Congruence "Parma_Polyhedra_Library::Congruence" 49 | cdef cppclass PPL_Congruence_System "Parma_Polyhedra_Library::Congruence_System" 50 | cdef cppclass PPL_Polyhedron "Parma_Polyhedra_Library::Polyhedron" 51 | cdef cppclass PPL_C_Polyhedron "Parma_Polyhedra_Library::C_Polyhedron" (PPL_Polyhedron) 52 | cdef cppclass PPL_NNC_Polyhedron "Parma_Polyhedra_Library::NNC_Polyhedron" (PPL_Polyhedron) 53 | cdef cppclass PPL_Poly_Gen_Relation "Parma_Polyhedra_Library::Poly_Gen_Relation" 54 | cdef cppclass PPL_Poly_Con_Relation "Parma_Polyhedra_Library::Poly_Con_Relation" 55 | cdef cppclass PPL_MIP_Problem "Parma_Polyhedra_Library::MIP_Problem" 56 | cdef cppclass PPL_mip_iterator "Parma_Polyhedra_Library::MIP_Problem::const_iterator" 57 | cdef cppclass PPL_gs_iterator "Parma_Polyhedra_Library::Generator_System::const_iterator" 58 | cdef cppclass PPL_Constraint_System_iterator "Parma_Polyhedra_Library::Constraint_System::const_iterator" 59 | cdef cppclass PPL_Congruence_System_iterator "Parma_Polyhedra_Library::Congruence_System::const_iterator" 60 | 61 | cdef cppclass PPL_Bit_Row "Parma_Polyhedra_Library::Bit_Row" 62 | cdef cppclass PPL_Bit_Matrix "Parma_Polyhedra_Library::Bit_Matrix" 63 | 64 | cdef cppclass PPL_Variable: 65 | PPL_Variable(PPL_dimension_type i) 66 | PPL_dimension_type id() 67 | PPL_dimension_type space_dimension() 68 | 69 | cdef cppclass PPL_Variables_Set: 70 | PPL_Variables_Set() 71 | PPL_Variables_Set(PPL_Variable v) 72 | PPL_Variables_Set(PPL_Variable v, PPL_Variable w) 73 | PPL_dimension_type space_dimension() 74 | void insert(PPL_Variable v) 75 | size_t size() 76 | void ascii_dump() 77 | 78 | # class Parma_Polyhedra_Library::Linear_Expression 79 | # lines 28238-28879 of ppl.hh 80 | cdef cppclass PPL_Linear_Expression: 81 | PPL_Linear_Expression() 82 | PPL_Linear_Expression(PPL_Linear_Expression &e) 83 | PPL_Linear_Expression(PPL_Coefficient n) 84 | PPL_Linear_Expression(PPL_Variable v) 85 | 86 | PPL_dimension_type max_space_dimension() 87 | PPL_dimension_type space_dimension() 88 | void set_space_dimension(PPL_dimension_type d) 89 | PPL_Coefficient coefficient(PPL_Variable v) 90 | void set_coefficient(PPL_Variable v, PPL_Coefficient) 91 | PPL_Coefficient inhomogeneous_term() 92 | void set_inhomogeneous_term(PPL_Coefficient n) 93 | void linear_combine(const PPL_Linear_Expression& y, PPL_Variable v) 94 | void linear_combine(const PPL_Linear_Expression& y, PPL_Coefficient c1, PPL_Coefficient c2) 95 | void linear_combine_lax(const PPL_Linear_Expression& u, PPL_Coefficient c1, PPL_Coefficient c2) 96 | void swap_space_dimensions(PPL_Variable v1, PPL_Variable v2) 97 | void remove_space_dimensions(const PPL_Variables_Set) 98 | void shift_space_dimensions(PPL_Variable v, PPL_dimension_type n) 99 | void permute_space_dimensions(const cppvector[PPL_Variable]& cycle) except +ValueError 100 | bint is_zero() 101 | bint all_homogeneous_terms_are_zero() 102 | bint is_equal_to(PPL_Linear_Expression& x) 103 | bint all_zeroes(const PPL_Variables_Set& v) 104 | 105 | void ascii_dump() 106 | 107 | #PPL_Linear_Expression operator+=(PPL_Linear_Expression& e) 108 | #PPL_Linear_Expression operator-=(PPL_Linear_Expression& e) 109 | #PPL_Linear_Expression operator*=(PPL_Coefficient n) 110 | #PPL_Linear_Expression operator/=(PPL_Coefficient n) 111 | PPL_Linear_Expression operator+(PPL_Linear_Expression& e) 112 | PPL_Linear_Expression operator-(PPL_Linear_Expression& e) 113 | PPL_Linear_Expression operator*(PPL_Coefficient n) 114 | PPL_Constraint operator> (PPL_Linear_Expression& e) 115 | PPL_Constraint operator>=(PPL_Linear_Expression& e) 116 | PPL_Constraint operator==(PPL_Linear_Expression& e) 117 | PPL_Constraint operator<=(PPL_Linear_Expression& e) 118 | PPL_Constraint operator< (PPL_Linear_Expression& e) 119 | 120 | cdef cppclass PPL_Constraint: 121 | PPL_Constraint() 122 | PPL_Constraint(PPL_Constraint &g) 123 | PPL_dimension_type space_dimension() 124 | PPL_ConstraintType type() 125 | bint is_equality() 126 | bint is_inequality() 127 | bint is_nonstrict_inequality() 128 | bint is_strict_inequality() 129 | PPL_Coefficient coefficient(PPL_Variable v) 130 | PPL_Coefficient inhomogeneous_term() 131 | bint is_tautological() 132 | bint is_inconsistent() 133 | bint is_equivalent_to(PPL_Constraint &y) 134 | void ascii_dump() 135 | void permute_space_dimensions(const cppvector[PPL_Variable]& cycle) except +ValueError 136 | 137 | cdef cppclass PPL_Generator: 138 | PPL_Generator(PPL_Generator &g) 139 | PPL_dimension_type space_dimension() 140 | void set_space_dimension(PPL_dimension_type n) 141 | PPL_GeneratorType type() 142 | bint is_line() 143 | bint is_ray() 144 | bint is_line_or_ray() 145 | bint is_point() 146 | bint is_closure_point() 147 | PPL_Coefficient coefficient(PPL_Variable v) 148 | PPL_Coefficient divisor() except + 149 | bint is_equivalent_to(PPL_Generator &y) 150 | void ascii_dump() 151 | void permute_space_dimensions(const cppvector[PPL_Variable]& cycle) except +ValueError 152 | 153 | cdef cppclass PPL_Congruence: 154 | PPL_Congruence() 155 | PPL_Congruence(const PPL_Congruence &g) 156 | PPL_Congruence(const PPL_Constraint &c) except +ValueError 157 | PPL_dimension_type space_dimension() 158 | # NOTE: curiously, this can raise an error (behavior different from Linear_Expression) 159 | PPL_Coefficient coefficient(PPL_Variable v) except +ValueError 160 | PPL_Coefficient inhomogeneous_term() 161 | PPL_Coefficient modulus() 162 | void set_modulus(PPL_Coefficient& m) 163 | void scale(PPL_Coefficient& m) 164 | bint is_tautological() 165 | bint is_inconsistent() 166 | bint is_proper_congruence() 167 | bint is_equality() 168 | void ascii_dump() 169 | void swap_space_dimension(PPL_Variable v1, PPL_Variable v2) 170 | void set_space_dimension(PPL_dimension_type n) 171 | void shift_space_dimensions(PPL_Variable v, PPL_dimension_type n) 172 | void sign_normalize() 173 | void normalize() 174 | void strong_normalize() 175 | PPL_dimension_type max_space_dimension() 176 | 177 | cppbool operator==(const PPL_Congruence &x, const PPL_Congruence &y) 178 | cppbool operator!=(const PPL_Congruence &x, const PPL_Congruence &y) 179 | 180 | cdef cppclass PPL_Congruence_System: 181 | PPL_Congruence_System() 182 | PPL_Congruence_System(PPL_Congruence &c) 183 | PPL_Congruence_System(PPL_Congruence_System &cs) 184 | PPL_dimension_type space_dimension() 185 | PPL_Congruence_System_iterator begin() 186 | PPL_Congruence_System_iterator end() 187 | bint has_equalities() 188 | bint has_strict_inequalities() 189 | void clear() 190 | void insert(PPL_Congruence &g) 191 | bint empty() 192 | void ascii_dump() 193 | 194 | cdef cppclass PPL_Congruence_System_iterator: 195 | PPL_Congruence_System_iterator() 196 | PPL_Congruence_System_iterator(PPL_Congruence_System_iterator &csi) 197 | PPL_Congruence& operator* () 198 | PPL_Congruence_System_iterator inc "operator++" (int i) 199 | cppbool operator==(PPL_Congruence_System_iterator& y) 200 | cppbool operator!=(PPL_Congruence_System_iterator& y) 201 | 202 | cdef cppclass PPL_Generator_System: 203 | PPL_Generator_System() 204 | PPL_Generator_System(PPL_Generator &g) 205 | PPL_Generator_System(PPL_Generator_System &gs) 206 | PPL_dimension_type space_dimension() 207 | void set_space_dimension(PPL_dimension_type space_dim) 208 | PPL_gs_iterator begin() 209 | PPL_gs_iterator end() 210 | void clear() 211 | void insert(PPL_Generator &g) 212 | bint empty() 213 | void ascii_dump() 214 | 215 | cdef cppclass PPL_mip_iterator: 216 | PPL_mip_iterator(PPL_mip_iterator &mipi) 217 | PPL_Constraint& operator* () 218 | PPL_mip_iterator inc "operator++" (int i) 219 | cppbool operator==(PPL_mip_iterator& y) 220 | cppbool operator!=(PPL_mip_iterator& y) 221 | 222 | cdef cppclass PPL_gs_iterator: 223 | PPL_gs_iterator() 224 | PPL_gs_iterator(PPL_gs_iterator &gsi) 225 | PPL_Generator& operator* () 226 | PPL_gs_iterator inc "operator++" (int i) 227 | cppbool operator==(PPL_gs_iterator& y) 228 | cppbool operator!=(PPL_gs_iterator& y) 229 | 230 | cdef cppclass PPL_Constraint_System_iterator: 231 | PPL_Constraint_System_iterator() 232 | PPL_Constraint_System_iterator(PPL_Constraint_System_iterator &csi) 233 | PPL_Constraint& operator* () 234 | PPL_Constraint_System_iterator inc "operator++" (int i) 235 | cppbool operator==(PPL_Constraint_System_iterator& y) 236 | cppbool operator!=(PPL_Constraint_System_iterator& y) 237 | 238 | cdef cppclass PPL_Constraint_System: 239 | PPL_Constraint_System() 240 | PPL_Constraint_System(PPL_Constraint &g) 241 | PPL_Constraint_System(PPL_Constraint_System &gs) 242 | PPL_dimension_type space_dimension() 243 | PPL_Constraint_System_iterator begin() 244 | PPL_Constraint_System_iterator end() 245 | bint has_equalities() 246 | bint has_strict_inequalities() 247 | void clear() 248 | void insert(PPL_Constraint &g) 249 | bint empty() 250 | void ascii_dump() 251 | 252 | cdef enum PPL_Degenerate_Element "Parma_Polyhedra_Library::Degenerate_Element": 253 | UNIVERSE, EMPTY 254 | 255 | cdef enum PPL_Optimization_Mode "Parma_Polyhedra_Library::Optimization_Mode": 256 | MINIMIZATION, MAXIMIZATION 257 | 258 | cdef enum PPL_MIP_Problem_Status "Parma_Polyhedra_Library::MIP_Problem_Status": 259 | UNFEASIBLE_MIP_PROBLEM, UNBOUNDED_MIP_PROBLEM, OPTIMIZED_MIP_PROBLEM 260 | 261 | cdef cppclass PPL_Polyhedron: 262 | PPL_dimension_type space_dimension() 263 | PPL_dimension_type affine_dimension() 264 | PPL_Constraint_System& constraints() 265 | PPL_Constraint_System& minimized_constraints() 266 | PPL_Generator_System& generators() 267 | PPL_Generator_System& minimized_generators() 268 | PPL_Poly_Con_Relation relation_with(PPL_Constraint &c) except +ValueError 269 | PPL_Poly_Gen_Relation relation_with(PPL_Generator &g) except +ValueError 270 | bint is_empty() 271 | bint is_universe() 272 | bint is_topologically_closed() 273 | bint is_disjoint_from(PPL_Polyhedron &y) except +ValueError 274 | bint is_discrete() 275 | bint is_bounded() 276 | bint contains_integer_point() 277 | bint constrains(PPL_Variable var) except +ValueError 278 | bint bounds_from_above(PPL_Linear_Expression &expr) except +ValueError 279 | bint bounds_from_below(PPL_Linear_Expression &expr) except +ValueError 280 | bint maximize(PPL_Linear_Expression &expr, PPL_Coefficient &sup_n, PPL_Coefficient &sup_d, 281 | cppbool &maximum) 282 | bint maximize(PPL_Linear_Expression &expr, PPL_Coefficient &sup_n, PPL_Coefficient &sup_d, 283 | cppbool &maximum, PPL_Generator &g) 284 | bint minimize(PPL_Linear_Expression &expr, PPL_Coefficient &inf_n, PPL_Coefficient &inf_d, 285 | cppbool &minimum) 286 | bint minimize(PPL_Linear_Expression &expr, PPL_Coefficient &inf_n, PPL_Coefficient &inf_d, 287 | cppbool &minimum, PPL_Generator &g) 288 | bint frequency(PPL_Linear_Expression &expr, PPL_Coefficient &freq_n, PPL_Coefficient &freq_d, 289 | PPL_Coefficient &val_n, PPL_Coefficient &val_d) 290 | bint contains(PPL_Polyhedron &y) except +ValueError 291 | bint strictly_contains(PPL_Polyhedron &y) except +ValueError 292 | void add_constraint(PPL_Constraint &c) except +ValueError 293 | void add_generator(PPL_Generator &g) except +ValueError 294 | void add_constraints(PPL_Constraint_System &cs) except +ValueError 295 | void add_generators(PPL_Generator_System &gs) except +ValueError 296 | void refine_with_constraint(PPL_Constraint &c) except +ValueError 297 | void refine_with_constraints(PPL_Constraint_System &cs) except +ValueError 298 | void unconstrain(PPL_Variable var) except +ValueError 299 | void intersection_assign(PPL_Polyhedron &y) except +ValueError 300 | void poly_hull_assign(PPL_Polyhedron &y) except +ValueError 301 | void upper_bound_assign(PPL_Polyhedron &y) except +ValueError 302 | void poly_difference_assign(PPL_Polyhedron &y) except +ValueError 303 | void difference_assign(PPL_Polyhedron &y) except +ValueError 304 | void drop_some_non_integer_points() 305 | void topological_closure_assign() 306 | void BHRZ03_widening_assign(PPL_Polyhedron &y, unsigned* tp) except +ValueError 307 | void limited_BHRZ03_extrapolation_assign(PPL_Polyhedron &y, PPL_Constraint_System &cs, unsigned* tp) except +ValueError 308 | void bounded_BHRZ03_extrapolation_assign(PPL_Polyhedron &y, PPL_Constraint_System &cs, unsigned* tp) except +ValueError 309 | void H79_widening_assign(PPL_Polyhedron &y, unsigned* tp) except +ValueError 310 | void widening_assign(PPL_Polyhedron &y, unsigned* tp) except +ValueError 311 | void limited_H79_extrapolation_assign(PPL_Polyhedron &y, PPL_Constraint_System &cs, unsigned* tp) except +ValueError 312 | void bounded_H79_extrapolation_assign(PPL_Polyhedron &y, PPL_Constraint_System &cs, unsigned* tp) except +ValueError 313 | void add_space_dimensions_and_embed(PPL_dimension_type m) except +ValueError 314 | void add_space_dimensions_and_project(PPL_dimension_type m) except +ValueError 315 | void concatenate_assign(PPL_Polyhedron &y) except +ValueError 316 | void remove_higher_space_dimensions(PPL_dimension_type new_dimension) except +ValueError 317 | void affine_image(const PPL_Variable, const PPL_Linear_Expression& expr) except +ValueError 318 | void affine_preimage(const PPL_Variable, const PPL_Linear_Expression& expr) except +ValueError 319 | void ascii_dump() 320 | int hash_code() 321 | PPL_dimension_type max_space_dimension() 322 | bint operator!=(PPL_Polyhedron &y) 323 | bint operator==(PPL_Polyhedron &y) 324 | 325 | cdef cppclass PPL_C_Polyhedron(PPL_Polyhedron): 326 | PPL_C_Polyhedron(PPL_dimension_type num_dimensions, PPL_Degenerate_Element) 327 | PPL_C_Polyhedron(PPL_Constraint_System &cs) except +ValueError 328 | PPL_C_Polyhedron(PPL_Generator_System &gs) except +ValueError 329 | PPL_C_Polyhedron(PPL_C_Polyhedron &y) 330 | 331 | cdef cppclass PPL_NNC_Polyhedron(PPL_Polyhedron): 332 | PPL_NNC_Polyhedron(PPL_dimension_type num_dimensions, PPL_Degenerate_Element kind) 333 | PPL_NNC_Polyhedron(PPL_Constraint_System &cs) except +ValueError 334 | PPL_NNC_Polyhedron(PPL_Generator_System &gs) except +ValueError 335 | PPL_NNC_Polyhedron(PPL_NNC_Polyhedron &y) 336 | PPL_NNC_Polyhedron(PPL_C_Polyhedron &y) 337 | 338 | cdef cppclass PPL_Poly_Gen_Relation: 339 | PPL_Poly_Gen_Relation(PPL_Poly_Gen_Relation &cpy_from) 340 | bint implies(PPL_Poly_Gen_Relation &y) 341 | void ascii_dump() 342 | 343 | cdef cppclass PPL_Poly_Con_Relation: 344 | PPL_Poly_Con_Relation(PPL_Poly_Con_Relation &cpy_from) 345 | bint implies(PPL_Poly_Con_Relation &y) 346 | void ascii_dump() 347 | 348 | cdef cppclass PPL_MIP_Problem: 349 | PPL_MIP_Problem(PPL_MIP_Problem &cpy_from) 350 | PPL_MIP_Problem(PPL_dimension_type dim) except +ValueError 351 | PPL_MIP_Problem(PPL_dimension_type dim, PPL_Constraint_System &cs, PPL_Linear_Expression &obj, PPL_Optimization_Mode) except +ValueError 352 | PPL_dimension_type space_dimension() 353 | PPL_Linear_Expression& objective_function() 354 | void clear() 355 | void add_space_dimensions_and_embed(PPL_dimension_type m) except +ValueError 356 | void add_constraint(PPL_Constraint &c) except +ValueError 357 | void add_constraints(PPL_Constraint_System &cs) except +ValueError 358 | void add_to_integer_space_dimensions(PPL_Variables_Set &i_vars) except +ValueError 359 | void set_objective_function(PPL_Linear_Expression &obj) except +ValueError 360 | void set_optimization_mode(PPL_Optimization_Mode mode) 361 | PPL_Optimization_Mode optimization_mode() 362 | bint is_satisfiable() 363 | PPL_MIP_Problem_Status solve() 364 | void evaluate_objective_function(PPL_Generator evaluating_point, PPL_Coefficient &num, PPL_Coefficient &den) except +ValueError 365 | PPL_Generator& feasible_point() 366 | PPL_Generator optimizing_point() except +ValueError 367 | void optimal_value(PPL_Coefficient &num, PPL_Coefficient &den) except +ValueError 368 | PPL_MIP_Problem_Control_Parameter_Value get_control_parameter(PPL_MIP_Problem_Control_Parameter_Name name) 369 | void set_control_parameter(PPL_MIP_Problem_Control_Parameter_Value value) 370 | PPL_mip_iterator constraints_begin() 371 | PPL_mip_iterator constraints_end() 372 | 373 | cdef cppclass PPL_Bit_Row: 374 | PPL_Bit_Row() 375 | PPL_Bit_Row(const PPL_Bit_Row& y, const PPL_Bit_Row& z) 376 | void set(unsigned long k) 377 | void set_until(unsigned long k) 378 | void clear_from(unsigned long k) 379 | void clear() 380 | void union_assign(const PPL_Bit_Row& x, const PPL_Bit_Row& y) 381 | void intersection_assign(const PPL_Bit_Row& x, const PPL_Bit_Row& y) 382 | void difference_assign(const PPL_Bit_Row&x, const PPL_Bit_Row& y) 383 | 384 | unsigned long first() 385 | unsigned long last() 386 | unsigned long prev(unsigned long position) 387 | unsigned long next(unsigned long position) 388 | unsigned long count_ones() 389 | cppbool empty() 390 | 391 | cdef cppclass PPL_Bit_Matrix: 392 | PPL_Bit_Matrix() 393 | PPL_Bit_Matrix(PPL_dimension_type n_rows, PPL_dimension_type n_columns) 394 | PPL_Bit_Matrix(const PPL_Bit_Matrix& y) 395 | 396 | PPL_Bit_Row& operator[](PPL_dimension_type k) 397 | const PPL_Bit_Row& operator[](PPL_dimension_type k) 398 | 399 | void transpose() 400 | void transpose_assign(const PPL_Bit_Matrix& y) 401 | 402 | PPL_dimension_type num_columns() 403 | PPL_dimension_type num_rows() 404 | 405 | void sort_rows() 406 | 407 | cdef extern from "ppl.hh": 408 | PPL_Generator PPL_line "Parma_Polyhedra_Library::line" (PPL_Linear_Expression &e) except +ValueError 409 | PPL_Generator PPL_ray "Parma_Polyhedra_Library::ray" (PPL_Linear_Expression &e) except +ValueError 410 | PPL_Generator PPL_point "Parma_Polyhedra_Library::point" (PPL_Linear_Expression &e, PPL_Coefficient &d) except +ValueError 411 | PPL_Generator PPL_closure_point "Parma_Polyhedra_Library::closure_point" (PPL_Linear_Expression &e, PPL_Coefficient &d) except +ValueError 412 | 413 | cdef extern from "ppl.hh": 414 | 415 | PPL_Poly_Gen_Relation PPL_Poly_Gen_Relation_nothing "Parma_Polyhedra_Library::Poly_Gen_Relation::nothing" () 416 | PPL_Poly_Gen_Relation PPL_Poly_Gen_Relation_subsumes "Parma_Polyhedra_Library::Poly_Gen_Relation::subsumes" () 417 | 418 | PPL_Poly_Con_Relation PPL_Poly_Con_Relation_nothing "Parma_Polyhedra_Library::Poly_Con_Relation::nothing" () 419 | PPL_Poly_Con_Relation PPL_Poly_Con_Relation_is_disjoint "Parma_Polyhedra_Library::Poly_Con_Relation::is_disjoint" () 420 | PPL_Poly_Con_Relation PPL_Poly_Con_Relation_strictly_intersects "Parma_Polyhedra_Library::Poly_Con_Relation::strictly_intersects" () 421 | PPL_Poly_Con_Relation PPL_Poly_Con_Relation_is_included "Parma_Polyhedra_Library::Poly_Con_Relation::is_included" () 422 | PPL_Poly_Con_Relation PPL_Poly_Con_Relation_saturates "Parma_Polyhedra_Library::Poly_Con_Relation::saturates" () 423 | 424 | cdef extern from "ppl_shim.hh": 425 | PPL_Poly_Gen_Relation* new_relation_with(PPL_Polyhedron &p, PPL_Generator &g) except +ValueError 426 | PPL_Poly_Con_Relation* new_relation_with(PPL_Polyhedron &p, PPL_Constraint &c) except +ValueError 427 | 428 | PPL_Congruence modulo(const PPL_Linear_Expression &expr, PPL_Coefficient& mod) 429 | -------------------------------------------------------------------------------- /ppl/mip_problem.pyx: -------------------------------------------------------------------------------- 1 | # distutils: language = c++ 2 | # distutils: libraries = gmp gmpxx ppl m 3 | #***************************************************************************** 4 | # Copyright (C) 2010-2014 Volker Braun 5 | # 2011 Simon King 6 | # 2011-2017 Jeroen Demeyer 7 | # 2012 Risan 8 | # 2013 Julien Puydt 9 | # 2013 Travis Scrimshaw 10 | # 2015 André Apitzsch 11 | # 2016 Jori Mäntysalo 12 | # 2016 Matthias Koeppe 13 | # 2016-2017 Frédéric Chapoton 14 | # 2016-2018 Vincent Delecroix 15 | # 2017-2018 Vincent Klein 16 | # 17 | # Distributed under the terms of the GNU General Public License (GPL) 18 | # as published by the Free Software Foundation; either version 3 of 19 | # the License, or (at youroption) any later version. 20 | # http://www.gnu.org/licenses/ 21 | #***************************************************************************** 22 | 23 | from cysignals.signals cimport sig_on, sig_off 24 | from gmpy2 cimport import_gmpy2, GMPy_MPQ_From_mpz 25 | from cython.operator cimport dereference as deref 26 | 27 | # PPL can use floating-point arithmetic to compute integers 28 | cdef extern from "ppl.hh" namespace "Parma_Polyhedra_Library": 29 | cdef void set_rounding_for_PPL() 30 | cdef void restore_pre_PPL_rounding() 31 | 32 | # initialize gmpy2 C API 33 | import_gmpy2() 34 | 35 | # but with PPL's rounding the gsl will be very unhappy; must turn off! 36 | restore_pre_PPL_rounding() 37 | 38 | 39 | cdef class MIP_Problem(object): 40 | r""" 41 | wrapper for PPL's MIP_Problem class 42 | 43 | An object of the class MIP_Problem represents a Mixed Integer 44 | (Linear) Program problem. 45 | 46 | INPUT: 47 | 48 | - ``dim`` -- integer 49 | - ``args`` -- an array of the defining data of the MIP_Problem. 50 | For each element, any one of the following is accepted: 51 | 52 | * A :class:`Constraint_System`. 53 | 54 | * A :class:`Linear_Expression`. 55 | 56 | OUTPUT: 57 | 58 | A :class:`MIP_Problem`. 59 | 60 | Examples: 61 | 62 | >>> from ppl import Variable, Constraint_System, MIP_Problem 63 | >>> x = Variable(0) 64 | >>> y = Variable(1) 65 | >>> cs = Constraint_System() 66 | >>> cs.insert(x >= 0) 67 | >>> cs.insert(y >= 0) 68 | >>> cs.insert(3 * x + 5 * y <= 10) 69 | >>> m = MIP_Problem(2, cs, x + y) 70 | >>> m 71 | MIP Problem (maximization, 2 variables, 3 constraints) 72 | >>> m.optimal_value() 73 | mpq(10,3) 74 | >>> float(_) 75 | 3.3333333333333335 76 | >>> m.optimizing_point() 77 | point(10/3, 0/3) 78 | """ 79 | def __repr__(self): 80 | """ 81 | String representation of MIP Problem. 82 | 83 | Examples: 84 | 85 | >>> from ppl import Variable, Constraint_System, MIP_Problem 86 | >>> x = Variable(0) 87 | >>> y = Variable(1) 88 | >>> cs = Constraint_System() 89 | >>> cs.insert( x >= 0 ) 90 | >>> cs.insert( y >= 0 ) 91 | >>> cs.insert( 3 * x + 5 * y <= 10 ) 92 | >>> m = MIP_Problem(2, cs, x + y) 93 | >>> m 94 | MIP Problem (maximization, 2 variables, 3 constraints) 95 | """ 96 | dim = self.space_dimension() 97 | ncs = sum(1 for _ in self) 98 | return 'MIP Problem ({}, {} variable{}, {} constraint{})'.format( 99 | self.optimization_mode(), 100 | dim, 101 | 's' if dim > 1 else '', 102 | ncs, 103 | 's' if ncs > 1 else '') 104 | 105 | def __cinit__(self, PPL_dimension_type dim = 0, *args): 106 | """ 107 | The Cython constructor. 108 | 109 | Tests: 110 | 111 | >>> from ppl import Variable, Constraint_System, MIP_Problem 112 | >>> MIP_Problem(0) 113 | A MIP_Problem 114 | Maximize: 0 115 | Subject to constraints 116 | >>> x = Variable(0) 117 | >>> y = Variable(1) 118 | >>> cs = Constraint_System() 119 | >>> cs.insert(x + y <= 2) 120 | >>> M = MIP_Problem(2, cs, 0) 121 | >>> M = MIP_Problem(2, cs, x) 122 | >>> M = MIP_Problem(2, None, None) 123 | Traceback (most recent call last): 124 | ... 125 | TypeError: Cannot convert NoneType to ppl.Constraint_System 126 | >>> M = MIP_Problem(2, cs, 'hey') 127 | Traceback (most recent call last): 128 | ... 129 | TypeError: unable to convert 'hey' to an integer 130 | >>> M = MIP_Problem(2, cs, x, 'middle') 131 | Traceback (most recent call last): 132 | ... 133 | ValueError: unknown mode 'middle' 134 | """ 135 | if not args: 136 | self.thisptr = new PPL_MIP_Problem(dim) 137 | return 138 | elif len(args) == 1: 139 | raise ValueError('cannot initialize from {}'.format(args)) 140 | 141 | cdef Constraint_System cs = args[0] 142 | cdef Linear_Expression obj 143 | try: 144 | obj = args[1] 145 | except TypeError: 146 | obj = Linear_Expression(args[1]) 147 | 148 | cdef PPL_Optimization_Mode mode = MAXIMIZATION 149 | if len(args) == 3: 150 | if args[2] == 'maximization': 151 | mode = MAXIMIZATION 152 | elif args[2] == 'minimization': 153 | mode = MINIMIZATION 154 | else: 155 | raise ValueError('unknown mode {!r}'.format(args[2])) 156 | self.thisptr = new PPL_MIP_Problem(dim, cs.thisptr[0], obj.thisptr[0], mode) 157 | 158 | def __dealloc__(self): 159 | """ 160 | The Cython destructor 161 | """ 162 | del self.thisptr 163 | 164 | def __iter__(self): 165 | r""" 166 | Iterator through the constraints 167 | Tests: 168 | 169 | >>> from ppl import Variable, MIP_Problem 170 | >>> x = Variable(0) 171 | >>> y = Variable(1) 172 | >>> M = MIP_Problem(2) 173 | >>> for c in M: print(c) 174 | >>> M.add_constraint(x + y <= 5) 175 | >>> for c in M: print(c) 176 | -x0-x1+5>=0 177 | >>> M.add_constraint(3*x - 18*y >= -2) 178 | >>> for c in M: print(c) 179 | -x0-x1+5>=0 180 | 3*x0-18*x1+2>=0 181 | >>> M = MIP_Problem(1) 182 | >>> M.add_constraint(x <= 5) 183 | >>> it = M.__iter__() 184 | >>> next(it) 185 | -x0+5>=0 186 | >>> next(it) 187 | Traceback (most recent call last): 188 | ... 189 | StopIteration 190 | """ 191 | cdef PPL_mip_iterator *mip_csi_ptr = new PPL_mip_iterator(self.thisptr[0].constraints_begin()) 192 | try: 193 | while mip_csi_ptr[0] != self.thisptr[0].constraints_end(): 194 | yield _wrap_Constraint(deref(mip_csi_ptr[0].inc(1))) 195 | finally: 196 | del mip_csi_ptr 197 | 198 | def constraints(self): 199 | r""" 200 | Return the constraints of this MIP 201 | 202 | The output is an instance of :class:`Constraint_System`. 203 | 204 | Examples: 205 | 206 | >>> from ppl import Variable, MIP_Problem 207 | >>> x = Variable(0) 208 | >>> y = Variable(1) 209 | >>> M = MIP_Problem(2) 210 | >>> M.add_constraint(x + y <= 5) 211 | >>> M.add_constraint(3*x - 18*y >= -2) 212 | >>> M.constraints() 213 | Constraint_System {-x0-x1+5>=0, 3*x0-18*x1+2>=0} 214 | 215 | Note that modifying the output of this method will not modify the 216 | underlying MIP problem object: 217 | 218 | >>> cs = M.constraints() 219 | >>> cs.insert(x <= 3) 220 | >>> cs 221 | Constraint_System {-x0-x1+5>=0, 3*x0-18*x1+2>=0, -x0+3>=0} 222 | >>> M.constraints() 223 | Constraint_System {-x0-x1+5>=0, 3*x0-18*x1+2>=0} 224 | """ 225 | cdef Constraint_System c = Constraint_System(None) 226 | cdef PPL_Constraint_System* cs = new PPL_Constraint_System() 227 | cdef PPL_mip_iterator* mip_it = new PPL_mip_iterator(self.thisptr[0].constraints_begin()) 228 | 229 | while mip_it[0] != self.thisptr[0].constraints_end(): 230 | cs[0].insert(deref(mip_it[0])) 231 | mip_it[0].inc(1) 232 | c.thisptr = cs 233 | del mip_it 234 | return c 235 | 236 | def optimization_mode(self): 237 | """ 238 | Return the optimization mode used in the MIP_Problem. 239 | 240 | It will return "maximization" if the MIP_Problem was set 241 | to MAXIMIZATION mode, and "minimization" otherwise. 242 | 243 | Examples: 244 | 245 | >>> from ppl import MIP_Problem 246 | >>> m = MIP_Problem() 247 | >>> m.optimization_mode() 248 | 'maximization' 249 | """ 250 | if self.thisptr.optimization_mode() == MAXIMIZATION: 251 | return "maximization" 252 | elif self.thisptr.optimization_mode() == MINIMIZATION: 253 | return "minimization" 254 | 255 | def optimal_value(self): 256 | """ 257 | Return the optimal value of the MIP_Problem. ValueError thrown if self does not 258 | have an optimizing point, i.e., if the MIP problem is unbounded or not satisfiable. 259 | 260 | Examples: 261 | 262 | >>> from ppl import Variable, Constraint_System, MIP_Problem 263 | >>> x = Variable(0) 264 | >>> y = Variable(1) 265 | >>> cs = Constraint_System() 266 | >>> cs.insert( x >= 0 ) 267 | >>> cs.insert( y >= 0 ) 268 | >>> cs.insert( 3 * x + 5 * y <= 10 ) 269 | >>> m = MIP_Problem(2, cs, x + y) 270 | >>> m.optimal_value() 271 | mpq(10,3) 272 | >>> cs = Constraint_System() 273 | >>> cs.insert( x >= 0 ) 274 | >>> m = MIP_Problem(1, cs, x + x ) 275 | >>> m.optimal_value() 276 | Traceback (most recent call last): 277 | ... 278 | ValueError: PPL::MIP_Problem::optimizing_point(): 279 | *this ... have an optimizing point. 280 | """ 281 | cdef PPL_Coefficient sup_n 282 | cdef PPL_Coefficient sup_d 283 | 284 | sig_on() 285 | try: 286 | self.thisptr.optimal_value(sup_n, sup_d) 287 | finally: 288 | sig_off() 289 | return GMPy_MPQ_From_mpz(sup_n.get_mpz_t(), sup_d.get_mpz_t()) 290 | 291 | def space_dimension(self): 292 | """ 293 | Return the space dimension of the MIP_Problem. 294 | 295 | Examples: 296 | 297 | >>> from ppl import Variable, Constraint_System, MIP_Problem 298 | >>> x = Variable(0) 299 | >>> y = Variable(1) 300 | >>> cs = Constraint_System() 301 | >>> cs.insert( x >= 0) 302 | >>> cs.insert( y >= 0 ) 303 | >>> cs.insert( 3 * x + 5 * y <= 10 ) 304 | >>> m = MIP_Problem(2, cs, x + y) 305 | >>> m.space_dimension() 306 | 2 307 | """ 308 | return self.thisptr.space_dimension() 309 | 310 | def objective_function(self): 311 | """ 312 | Return the optimal value of the MIP_Problem. 313 | 314 | Examples: 315 | 316 | >>> from ppl import Variable, Constraint_System, MIP_Problem 317 | >>> x = Variable(0) 318 | >>> y = Variable(1) 319 | >>> cs = Constraint_System() 320 | >>> cs.insert( x >= 0) 321 | >>> cs.insert( y >= 0 ) 322 | >>> cs.insert( 3 * x + 5 * y <= 10 ) 323 | >>> m = MIP_Problem(2, cs, x + y) 324 | >>> m.objective_function() 325 | x0+x1 326 | """ 327 | rc = Linear_Expression() 328 | rc.thisptr[0] = self.thisptr.objective_function() 329 | return rc 330 | 331 | def clear(self): 332 | """ 333 | Reset the MIP_Problem to be equal to the trivial MIP_Problem. 334 | 335 | Examples: 336 | 337 | >>> from ppl import Variable, Constraint_System, MIP_Problem 338 | >>> x = Variable(0) 339 | >>> y = Variable(1) 340 | >>> cs = Constraint_System() 341 | >>> cs.insert( x >= 0) 342 | >>> cs.insert( y >= 0 ) 343 | >>> cs.insert( 3 * x + 5 * y <= 10 ) 344 | >>> m = MIP_Problem(2, cs, x + y) 345 | >>> m.objective_function() 346 | x0+x1 347 | >>> m.clear() 348 | >>> m.objective_function() 349 | 0 350 | """ 351 | self.thisptr.clear() 352 | 353 | def add_space_dimensions_and_embed(self, PPL_dimension_type m): 354 | """ 355 | Adds m new space dimensions and embeds the old MIP problem in the new vector space. 356 | 357 | Examples: 358 | 359 | >>> from ppl import Variable, Constraint_System, MIP_Problem 360 | >>> x = Variable(0) 361 | >>> y = Variable(1) 362 | >>> cs = Constraint_System() 363 | >>> cs.insert( x >= 0) 364 | >>> cs.insert( y >= 0 ) 365 | >>> cs.insert( 3 * x + 5 * y <= 10 ) 366 | >>> m = MIP_Problem(2, cs, x + y) 367 | >>> m.add_space_dimensions_and_embed(5) 368 | >>> m.space_dimension() 369 | 7 370 | """ 371 | sig_on() 372 | self.thisptr.add_space_dimensions_and_embed(m) 373 | sig_off() 374 | 375 | def add_constraint(self, Constraint c): 376 | """ 377 | Adds a copy of constraint c to the MIP problem. 378 | 379 | Examples: 380 | 381 | >>> from ppl import Variable, MIP_Problem 382 | >>> x = Variable(0) 383 | >>> y = Variable(1) 384 | >>> m = MIP_Problem() 385 | >>> m.add_space_dimensions_and_embed(2) 386 | >>> m.add_constraint(x >= 0) 387 | >>> m.add_constraint(y >= 0) 388 | >>> m.add_constraint(3 * x + 5 * y <= 10) 389 | >>> m.set_objective_function(x + y) 390 | >>> m.optimal_value() 391 | mpq(10,3) 392 | 393 | Tests: 394 | 395 | >>> z = Variable(2) 396 | >>> m.add_constraint(z >= -3) 397 | Traceback (most recent call last): 398 | ... 399 | ValueError: PPL::MIP_Problem::add_constraint(c): 400 | c.space_dimension() == 3 exceeds this->space_dimension == 2. 401 | """ 402 | sig_on() 403 | try: 404 | self.thisptr.add_constraint(c.thisptr[0]) 405 | finally: 406 | sig_off() 407 | 408 | def add_constraints(self, Constraint_System cs): 409 | """ 410 | Adds a copy of the constraints in cs to the MIP problem. 411 | 412 | Examples: 413 | 414 | >>> from ppl import Variable, Constraint_System, MIP_Problem 415 | >>> x = Variable(0) 416 | >>> y = Variable(1) 417 | >>> cs = Constraint_System() 418 | >>> cs.insert(x >= 0) 419 | >>> cs.insert(y >= 0) 420 | >>> cs.insert(3 * x + 5 * y <= 10) 421 | >>> m = MIP_Problem(2) 422 | >>> m.set_objective_function(x + y) 423 | >>> m.add_constraints(cs) 424 | >>> m.optimal_value() 425 | mpq(10,3) 426 | 427 | Tests: 428 | 429 | >>> p = Variable(9) 430 | >>> cs.insert(p >= -3) 431 | >>> m.add_constraints(cs) 432 | Traceback (most recent call last): 433 | ... 434 | ValueError: PPL::MIP_Problem::add_constraints(cs): 435 | cs.space_dimension() == 10 exceeds this->space_dimension() == 2. 436 | """ 437 | sig_on() 438 | try: 439 | self.thisptr.add_constraints(cs.thisptr[0]) 440 | finally: 441 | sig_off() 442 | 443 | def add_to_integer_space_dimensions(self, Variables_Set i_vars): 444 | """ 445 | Sets the variables whose indexes are in set `i_vars` to be integer space dimensions. 446 | 447 | Examples: 448 | 449 | >>> from ppl import Variable, Variables_Set, Constraint_System, MIP_Problem 450 | >>> x = Variable(0) 451 | >>> y = Variable(1) 452 | >>> cs = Constraint_System() 453 | >>> cs.insert( x >= 0) 454 | >>> cs.insert( y >= 0 ) 455 | >>> cs.insert( 3 * x + 5 * y <= 10 ) 456 | >>> m = MIP_Problem(2) 457 | >>> m.set_objective_function(x + y) 458 | >>> m.add_constraints(cs) 459 | >>> i_vars = Variables_Set(x, y) 460 | >>> m.add_to_integer_space_dimensions(i_vars) 461 | >>> m.optimal_value() 462 | mpq(3,1) 463 | """ 464 | sig_on() 465 | try: 466 | self.thisptr.add_to_integer_space_dimensions(i_vars.thisptr[0]) 467 | finally: 468 | sig_off() 469 | 470 | def set_objective_function(self, obj): 471 | """ 472 | Sets the objective function to obj. 473 | 474 | Examples: 475 | 476 | >>> from ppl import Variable, MIP_Problem 477 | >>> x = Variable(0) 478 | >>> y = Variable(1) 479 | >>> m = MIP_Problem() 480 | >>> m.add_space_dimensions_and_embed(2) 481 | >>> m.add_constraint(x >= 0) 482 | >>> m.add_constraint(y >= 0) 483 | >>> m.add_constraint(3 * x + 5 * y <= 10) 484 | >>> m.set_objective_function(x + y) 485 | >>> m.optimal_value() 486 | mpq(10,3) 487 | 488 | Tests: 489 | 490 | >>> z = Variable(2) 491 | >>> m.set_objective_function(x + y + z) 492 | Traceback (most recent call last): 493 | ... 494 | ValueError: PPL::MIP_Problem::set_objective_function(obj): 495 | obj.space_dimension() == 3 exceeds this->space_dimension == 2. 496 | 497 | >>> M = MIP_Problem(1) 498 | >>> M.set_objective_function(Variable(0)) 499 | """ 500 | if isinstance(obj, Variable): 501 | obj = Linear_Expression(obj) 502 | elif not isinstance(obj, Linear_Expression): 503 | raise ValueError('not an objective function') 504 | self.thisptr.set_objective_function(( obj).thisptr[0]) 505 | 506 | def set_optimization_mode(self, mode): 507 | """ 508 | Sets the optimization mode to mode. 509 | 510 | Examples: 511 | 512 | >>> from ppl import MIP_Problem 513 | >>> m = MIP_Problem() 514 | >>> m.optimization_mode() 515 | 'maximization' 516 | >>> m.set_optimization_mode('minimization') 517 | >>> m.optimization_mode() 518 | 'minimization' 519 | 520 | Tests: 521 | 522 | >>> m.set_optimization_mode('max') 523 | Traceback (most recent call last): 524 | ... 525 | ValueError: Unknown value: mode=max. 526 | """ 527 | if mode == 'minimization': 528 | self.thisptr.set_optimization_mode(MINIMIZATION) 529 | elif mode == 'maximization': 530 | self.thisptr.set_optimization_mode(MAXIMIZATION) 531 | else: 532 | raise ValueError('Unknown value: mode='+str(mode)+'.') 533 | 534 | def is_satisfiable(self): 535 | """ 536 | Check if the MIP_Problem is satisfiable 537 | 538 | Examples: 539 | 540 | >>> from ppl import Variable, MIP_Problem 541 | >>> x = Variable(0) 542 | >>> y = Variable(1) 543 | >>> m = MIP_Problem() 544 | >>> m.add_space_dimensions_and_embed(2) 545 | >>> m.add_constraint(x >= 0) 546 | >>> m.add_constraint(y >= 0) 547 | >>> m.add_constraint(3 * x + 5 * y <= 10) 548 | >>> m.is_satisfiable() 549 | True 550 | """ 551 | return self.thisptr.is_satisfiable() 552 | 553 | def evaluate_objective_function(self, Generator evaluating_point): 554 | """ 555 | Return the result of evaluating the objective function on evaluating_point. ValueError thrown 556 | if self and evaluating_point are dimension-incompatible or if the generator evaluating_point is not a point. 557 | 558 | Examples: 559 | 560 | >>> from ppl import Variable, MIP_Problem, Generator 561 | >>> x = Variable(0) 562 | >>> y = Variable(1) 563 | >>> m = MIP_Problem() 564 | >>> m.add_space_dimensions_and_embed(2) 565 | >>> m.add_constraint(x >= 0) 566 | >>> m.add_constraint(y >= 0) 567 | >>> m.add_constraint(3 * x + 5 * y <= 10) 568 | >>> m.set_objective_function(x + y) 569 | >>> g = Generator.point(5 * x - 2 * y, 7) 570 | >>> m.evaluate_objective_function(g) 571 | mpq(3,7) 572 | >>> z = Variable(2) 573 | >>> g = Generator.point(5 * x - 2 * z, 7) 574 | >>> m.evaluate_objective_function(g) 575 | Traceback (most recent call last): 576 | ... 577 | ValueError: PPL::MIP_Problem::evaluate_objective_function(p, n, d): 578 | *this and p are dimension incompatible. 579 | """ 580 | cdef PPL_Coefficient sup_n 581 | cdef PPL_Coefficient sup_d 582 | 583 | sig_on() 584 | try: 585 | self.thisptr.evaluate_objective_function(evaluating_point.thisptr[0], sup_n, sup_d) 586 | finally: 587 | sig_off() 588 | 589 | return GMPy_MPQ_From_mpz(sup_n.get_mpz_t(), sup_d.get_mpz_t()) 590 | 591 | def solve(self): 592 | """ 593 | Optimizes the MIP_Problem 594 | 595 | Examples: 596 | 597 | >>> from ppl import Variable, MIP_Problem 598 | >>> x = Variable(0) 599 | >>> y = Variable(1) 600 | >>> m = MIP_Problem() 601 | >>> m.add_space_dimensions_and_embed(2) 602 | >>> m.add_constraint(x >= 0) 603 | >>> m.add_constraint(y >= 0) 604 | >>> m.add_constraint(3 * x + 5 * y <= 10) 605 | >>> m.set_objective_function(x + y) 606 | >>> m.solve() 607 | {'status': 'optimized'} 608 | """ 609 | sig_on() 610 | try: 611 | tmp = self.thisptr.solve() 612 | finally: 613 | sig_off() 614 | if tmp == UNFEASIBLE_MIP_PROBLEM: 615 | return {'status': 'unfeasible'} 616 | elif tmp == UNBOUNDED_MIP_PROBLEM: 617 | return {'status': 'unbounded'} 618 | else: 619 | return {'status': 'optimized'} 620 | 621 | def optimizing_point(self): 622 | """ 623 | Returns an optimal point for the MIP_Problem, if it exists. 624 | 625 | Examples: 626 | 627 | >>> from ppl import Variable, MIP_Problem 628 | >>> x = Variable(0) 629 | >>> y = Variable(1) 630 | >>> m = MIP_Problem() 631 | >>> m.add_space_dimensions_and_embed(2) 632 | >>> m.add_constraint(x >= 0) 633 | >>> m.add_constraint(y >= 0) 634 | >>> m.add_constraint(3 * x + 5 * y <= 10) 635 | >>> m.set_objective_function(x + y) 636 | >>> m.optimizing_point() 637 | point(10/3, 0/3) 638 | """ 639 | cdef PPL_Generator *g 640 | sig_on() 641 | try: 642 | g = new PPL_Generator(self.thisptr[0].optimizing_point()) 643 | finally: 644 | sig_off() 645 | return _wrap_Generator(g[0]) 646 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /ppl/constraint.pyx: -------------------------------------------------------------------------------- 1 | # distutils: language = c++ 2 | # distutils: libraries = gmp gmpxx ppl m 3 | #***************************************************************************** 4 | # Copyright (C) 2010-2014 Volker Braun 5 | # 2011 Simon King 6 | # 2011-2017 Jeroen Demeyer 7 | # 2012 Risan 8 | # 2013 Julien Puydt 9 | # 2013 Travis Scrimshaw 10 | # 2015 André Apitzsch 11 | # 2016 Jori Mäntysalo 12 | # 2016 Matthias Koeppe 13 | # 2016-2017 Frédéric Chapoton 14 | # 2016-2020 Vincent Delecroix 15 | # 2017-2018 Vincent Klein 16 | # 17 | # Distributed under the terms of the GNU General Public License (GPL) 18 | # as published by the Free Software Foundation; either version 3 of 19 | # the License, or (at youroption) any later version. 20 | # http://www.gnu.org/licenses/ 21 | #***************************************************************************** 22 | 23 | from gmpy2 cimport GMPy_MPZ_From_mpz, import_gmpy2 24 | from cython.operator cimport dereference as deref 25 | from cpython.object cimport Py_LT, Py_LE, Py_EQ, Py_NE, Py_GT, Py_GE 26 | 27 | from .congruence cimport Congruence 28 | 29 | # PPL can use floating-point arithmetic to compute integers 30 | cdef extern from "ppl.hh" namespace "Parma_Polyhedra_Library": 31 | cdef void set_rounding_for_PPL() 32 | cdef void restore_pre_PPL_rounding() 33 | 34 | # initialize gmpy2 C API 35 | import_gmpy2() 36 | 37 | # but with PPL's rounding the gsl will be very unhappy; must turn off! 38 | restore_pre_PPL_rounding() 39 | 40 | 41 | def _dummy(): 42 | raise ValueError 43 | 44 | 45 | cdef class Constraint(object): 46 | r""" 47 | Wrapper for PPL's ``Constraint`` class. 48 | 49 | An object of the class ``Constraint`` is either: 50 | 51 | * an equality :math:`\sum_{i=0}^{n-1} a_i x_i + b = 0` 52 | 53 | * a non-strict inequality :math:`\sum_{i=0}^{n-1} a_i x_i + b \geq 0` 54 | 55 | * a strict inequality :math:`\sum_{i=0}^{n-1} a_i x_i + b > 0` 56 | 57 | where :math:`n` is the dimension of the space, :math:`a_i` is the integer 58 | coefficient of variable :math:`x_i`, and :math:`b_i` is the integer 59 | inhomogeneous term. 60 | 61 | INPUT/OUTPUT: 62 | 63 | You construct constraints by writing inequalities in 64 | :class:`Linear_Expression`. Do not attempt to manually construct 65 | constraints. 66 | 67 | Examples: 68 | 69 | >>> from ppl import Variable, Linear_Expression 70 | >>> x = Variable(0) 71 | >>> y = Variable(1) 72 | >>> 5*x-2*y > x+y-1 73 | 4*x0-3*x1+1>0 74 | >>> 5*x-2*y >= x+y-1 75 | 4*x0-3*x1+1>=0 76 | >>> 5*x-2*y == x+y-1 77 | 4*x0-3*x1+1==0 78 | >>> 5*x-2*y <= x+y-1 79 | -4*x0+3*x1-1>=0 80 | >>> 5*x-2*y < x+y-1 81 | -4*x0+3*x1-1>0 82 | >>> x > 0 83 | x0>0 84 | 85 | Special care is needed if the left hand side is a constant: 86 | 87 | >>> 0 == 1 # watch out! 88 | False 89 | >>> Linear_Expression(0) == 1 90 | mpz(-1)==0 91 | """ 92 | def __init__(self, arg=None): 93 | if arg is None: 94 | self.thisptr = new PPL_Constraint() 95 | elif isinstance(arg, Constraint): 96 | self.thisptr = new PPL_Constraint(( arg).thisptr[0]) 97 | else: 98 | raise TypeError("invalid argument for Constraint") 99 | 100 | def __cinit__(self): 101 | """ 102 | The Cython constructor. 103 | 104 | See :class:`Constraint` for documentation. 105 | 106 | Tests: 107 | 108 | >>> from ppl import Variable 109 | >>> x = Variable(0) 110 | >>> x>0 # indirect doctest 111 | x0>0 112 | """ 113 | self.thisptr = NULL 114 | 115 | def __dealloc__(self): 116 | """ 117 | The Cython destructor. 118 | """ 119 | del self.thisptr 120 | 121 | def __hash__(self): 122 | r""" 123 | Tests: 124 | 125 | >>> import ppl 126 | >>> hash(ppl.Variable(0) == 3) 127 | Traceback (most recent call last): 128 | ... 129 | TypeError: Constraint unhashable 130 | """ 131 | raise TypeError('Constraint unhashable') 132 | 133 | def __repr__(self): 134 | """ 135 | Return a string representation of the constraint. 136 | 137 | OUTPUT: 138 | 139 | String. 140 | 141 | Examples: 142 | 143 | >>> from ppl import Variable 144 | >>> x = Variable(0) 145 | >>> y = Variable(1) 146 | >>> (2*x-y+5 > x).__repr__() 147 | 'x0-x1+5>0' 148 | >>> (2*x-y+5 == x).__repr__() 149 | 'x0-x1+5==0' 150 | >>> (2*x-y+5 >= x).__repr__() 151 | 'x0-x1+5>=0' 152 | """ 153 | e = sum(self.coefficient(x)*x 154 | for x in (Variable(i) 155 | for i in range(self.space_dimension()))) 156 | e += self.inhomogeneous_term() 157 | s = repr(e) 158 | t = self.thisptr.type() 159 | if t == EQUALITY: 160 | s += '==0' 161 | elif t == NONSTRICT_INEQUALITY: 162 | s += '>=0' 163 | elif t == STRICT_INEQUALITY: 164 | s += '>0' 165 | else: 166 | raise RuntimeError 167 | return s 168 | 169 | def space_dimension(self): 170 | r""" 171 | Return the dimension of the vector space enclosing ``self``. 172 | 173 | OUTPUT: 174 | 175 | Integer. 176 | 177 | Examples: 178 | 179 | >>> from ppl import Variable 180 | >>> x = Variable(0) 181 | >>> y = Variable(1) 182 | >>> (x>=0).space_dimension() 183 | 1 184 | >>> (y==1).space_dimension() 185 | 2 186 | """ 187 | return self.thisptr.space_dimension() 188 | 189 | def type(self): 190 | r""" 191 | Return the constraint type of ``self``. 192 | 193 | OUTPUT: 194 | 195 | String. One of ``'equality'``, ``'nonstrict_inequality'``, or 196 | ``'strict_inequality'``. 197 | 198 | Examples: 199 | 200 | >>> from ppl import Variable 201 | >>> x = Variable(0) 202 | >>> (x==0).type() 203 | 'equality' 204 | >>> (x>=0).type() 205 | 'nonstrict_inequality' 206 | >>> (x>0).type() 207 | 'strict_inequality' 208 | """ 209 | t = self.thisptr.type() 210 | if t == EQUALITY: 211 | return 'equality' 212 | elif t == NONSTRICT_INEQUALITY: 213 | return 'nonstrict_inequality' 214 | elif t == STRICT_INEQUALITY: 215 | return 'strict_inequality' 216 | else: 217 | raise RuntimeError 218 | 219 | def is_equality(self): 220 | r""" 221 | Test whether ``self`` is an equality. 222 | 223 | OUTPUT: 224 | 225 | Boolean. Returns ``True`` if and only if ``self`` is an 226 | equality constraint. 227 | 228 | Examples: 229 | 230 | >>> from ppl import Variable 231 | >>> x = Variable(0) 232 | >>> (x==0).is_equality() 233 | True 234 | >>> (x>=0).is_equality() 235 | False 236 | >>> (x>0).is_equality() 237 | False 238 | """ 239 | return self.thisptr.is_equality() 240 | 241 | def is_inequality(self): 242 | r""" 243 | Test whether ``self`` is an inequality. 244 | 245 | OUTPUT: 246 | 247 | Boolean. Returns ``True`` if and only if ``self`` is an 248 | inequality constraint, either strict or non-strict. 249 | 250 | Examples: 251 | 252 | >>> from ppl import Variable 253 | >>> x = Variable(0) 254 | >>> (x==0).is_inequality() 255 | False 256 | >>> (x>=0).is_inequality() 257 | True 258 | >>> (x>0).is_inequality() 259 | True 260 | """ 261 | return self.thisptr.is_inequality() 262 | 263 | def is_nonstrict_inequality(self): 264 | r""" 265 | Test whether ``self`` is a non-strict inequality. 266 | 267 | OUTPUT: 268 | 269 | Boolean. Returns ``True`` if and only if ``self`` is an 270 | non-strict inequality constraint. 271 | 272 | Examples: 273 | 274 | >>> from ppl import Variable 275 | >>> x = Variable(0) 276 | >>> (x==0).is_nonstrict_inequality() 277 | False 278 | >>> (x>=0).is_nonstrict_inequality() 279 | True 280 | >>> (x>0).is_nonstrict_inequality() 281 | False 282 | """ 283 | return self.thisptr.is_nonstrict_inequality() 284 | 285 | def is_strict_inequality(self): 286 | r""" 287 | Test whether ``self`` is a strict inequality. 288 | 289 | OUTPUT: 290 | 291 | Boolean. Returns ``True`` if and only if ``self`` is an 292 | strict inequality constraint. 293 | 294 | Examples: 295 | 296 | >>> from ppl import Variable 297 | >>> x = Variable(0) 298 | >>> (x==0).is_strict_inequality() 299 | False 300 | >>> (x>=0).is_strict_inequality() 301 | False 302 | >>> (x>0).is_strict_inequality() 303 | True 304 | """ 305 | return self.thisptr.is_strict_inequality() 306 | 307 | def coefficient(self, Variable v): 308 | """ 309 | Return the coefficient of the variable ``v``. 310 | 311 | INPUT: 312 | 313 | - ``v`` -- a :class:`Variable`. 314 | 315 | OUTPUT: 316 | 317 | An integer. 318 | 319 | Examples: 320 | 321 | >>> from ppl import Variable 322 | >>> x = Variable(0) 323 | >>> ineq = 3*x+1 > 0 324 | >>> ineq.coefficient(x) 325 | mpz(3) 326 | >>> y = Variable(1) 327 | >>> ineq = 3**50 * y + 2 > 1 328 | >>> str(ineq.coefficient(y)) 329 | '717897987691852588770249' 330 | >>> ineq.coefficient(x) 331 | mpz(0) 332 | """ 333 | return GMPy_MPZ_From_mpz(self.thisptr.coefficient(v.thisptr[0]).get_mpz_t()) 334 | 335 | def coefficients(self): 336 | """ 337 | Return the coefficients of the constraint. 338 | 339 | See also :meth:`coefficient`. 340 | 341 | OUTPUT: 342 | 343 | A tuple of integers of length :meth:`space_dimension`. 344 | 345 | Examples: 346 | 347 | >>> from ppl import Variable 348 | >>> x = Variable(0); y = Variable(1) 349 | >>> ineq = ( 3*x+5*y+1 == 2); ineq 350 | 3*x0+5*x1-1==0 351 | >>> ineq.coefficients() 352 | (mpz(3), mpz(5)) 353 | """ 354 | cdef int d = self.space_dimension() 355 | cdef int i 356 | coeffs = [] 357 | for i in range(0, d): 358 | coeffs.append(GMPy_MPZ_From_mpz(self.thisptr.coefficient(PPL_Variable(i)).get_mpz_t())) 359 | return tuple(coeffs) 360 | 361 | def inhomogeneous_term(self): 362 | """ 363 | Return the inhomogeneous term of the constraint. 364 | 365 | OUTPUT: 366 | 367 | Integer. 368 | 369 | Examples: 370 | 371 | >>> from ppl import Variable 372 | >>> y = Variable(1) 373 | >>> ineq = 10+y > 9 374 | >>> ineq 375 | x1+1>0 376 | >>> ineq.inhomogeneous_term() 377 | mpz(1) 378 | >>> ineq = 2**66 + y > 0 379 | >>> str(ineq.inhomogeneous_term()) 380 | '73786976294838206464' 381 | """ 382 | return GMPy_MPZ_From_mpz(self.thisptr.inhomogeneous_term().get_mpz_t()) 383 | 384 | def is_tautological(self): 385 | r""" 386 | Test whether ``self`` is a tautological constraint. 387 | 388 | A tautology can have either one of the following forms: 389 | 390 | * an equality: :math:`\sum 0 x_i + 0 = 0`, 391 | 392 | * a non-strict inequality: :math:`\sum 0 x_i + b \geq 0` with `b\geq 0`, or 393 | 394 | * a strict inequality: :math:`\sum 0 x_i + b > 0` with `b> 0`. 395 | 396 | OUTPUT: 397 | 398 | Boolean. Returns ``True`` if and only if ``self`` is a 399 | tautological constraint. 400 | 401 | Examples: 402 | 403 | >>> from ppl import Variable 404 | >>> x = Variable(0) 405 | >>> (x==0).is_tautological() 406 | False 407 | >>> (0*x>=0).is_tautological() 408 | True 409 | """ 410 | return self.thisptr.is_tautological() 411 | 412 | def is_inconsistent(self): 413 | r""" 414 | Test whether ``self`` is an inconsistent constraint, that is, always false. 415 | 416 | An inconsistent constraint can have either one of the 417 | following forms: 418 | 419 | * an equality: :math:`\sum 0 x_i + b = 0` with `b\not=0`, 420 | 421 | * a non-strict inequality: :math:`\sum 0 x_i + b \geq 0` with `b< 0`, or 422 | 423 | * a strict inequality: :math:`\sum 0 x_i + b > 0` with `b\leq 0`. 424 | 425 | OUTPUT: 426 | 427 | Boolean. Returns ``True`` if and only if ``self`` is an 428 | inconsistent constraint. 429 | 430 | Examples: 431 | 432 | >>> from ppl import Variable 433 | >>> x = Variable(0) 434 | >>> (x==1).is_inconsistent() 435 | False 436 | >>> (0*x>=1).is_inconsistent() 437 | True 438 | """ 439 | return self.thisptr.is_inconsistent() 440 | 441 | def is_equivalent_to(self, Constraint c): 442 | r""" 443 | Test whether ``self`` and ``c`` are equivalent. 444 | 445 | INPUT: 446 | 447 | - ``c`` -- a :class:`Constraint`. 448 | 449 | OUTPUT: 450 | 451 | Boolean. Returns ``True`` if and only if ``self`` and ``c`` 452 | are equivalent constraints. 453 | 454 | Note that constraints having different space dimensions are 455 | not equivalent. However, constraints having different types 456 | may nonetheless be equivalent, if they both are tautologies or 457 | inconsistent. 458 | 459 | Examples: 460 | 461 | >>> from ppl import Variable, Linear_Expression 462 | >>> x = Variable(0) 463 | >>> y = Variable(1) 464 | >>> (x > 0).is_equivalent_to(Linear_Expression(0) < x) 465 | True 466 | >>> (x > 0).is_equivalent_to(0*y < x) 467 | False 468 | >>> (0*x > 1).is_equivalent_to(0*x == -2) 469 | True 470 | """ 471 | return self.thisptr.is_equivalent_to(c.thisptr[0]) 472 | 473 | def ascii_dump(self): 474 | r""" 475 | Write an ASCII dump to stderr. 476 | 477 | Examples: 478 | 479 | >>> cmd = 'from ppl import Linear_Expression, Variable\n' 480 | >>> cmd += 'x = Variable(0)\n' 481 | >>> cmd += 'y = Variable(1)\n' 482 | >>> cmd += 'e = (3*x+2*y+1 > 0)\n' 483 | >>> cmd += 'e.ascii_dump()\n' 484 | >>> import subprocess, sys 485 | >>> proc = subprocess.Popen([sys.executable, '-c', cmd], stderr=subprocess.PIPE) 486 | >>> out, err = proc.communicate() 487 | >>> print(str(err.decode('ascii'))) 488 | size 4 1 3 2 -1 ... 489 | 490 | """ 491 | self.thisptr.ascii_dump() 492 | 493 | def __reduce__(self): 494 | """ 495 | Pickle object. 496 | 497 | Examples: 498 | 499 | >>> from ppl import Variable 500 | >>> from pickle import loads, dumps 501 | >>> x = Variable(0) 502 | >>> y = Variable(1) 503 | >>> loads(dumps(3*x+2*y+1>=5)) 504 | 3*x0+2*x1-4>=0 505 | >>> loads(dumps(3*x+2*y+1>5)) 506 | 3*x0+2*x1-4>0 507 | >>> loads(dumps(3*x+2*y+1==5)) 508 | 3*x0+2*x1-4==0 509 | """ 510 | le = Linear_Expression(self.coefficients(), self.inhomogeneous_term()) 511 | if self.is_nonstrict_inequality(): 512 | return (inequality, (le, )) 513 | elif self.is_strict_inequality(): 514 | return (strict_inequality, (le, )) 515 | elif self.is_equality(): 516 | return (equation, (le, )) 517 | else: 518 | raise RuntimeError 519 | 520 | def permute_space_dimensions(self, cycle): 521 | """ 522 | Permute the coordinates according to ``cycle``. 523 | 524 | >>> from ppl import Variable 525 | >>> x = Variable(0); y = Variable(1); z = Variable(2) 526 | >>> l = 2*x - y + 3*z 527 | >>> ieq = l >= 5 528 | >>> ieq.permute_space_dimensions([2, 1, 0]) 529 | >>> ieq 530 | -x0+3*x1+2*x2-5>=0 531 | """ 532 | cdef cppvector[PPL_Variable] cpp_cycle 533 | cdef int i 534 | for i in cycle: 535 | cpp_cycle.push_back(PPL_Variable(i)) 536 | self.thisptr.permute_space_dimensions(cpp_cycle) 537 | 538 | def __mod__(self, m): 539 | r""" 540 | Return this equality modulo m 541 | 542 | >>> import ppl 543 | >>> x = ppl.Variable(0) 544 | >>> y = ppl.Variable(1) 545 | >>> (2*x + 3*y == 3) % 5 546 | 2*x0+3*x1-3==0 (mod 5) 547 | 548 | >>> (x <= 3) % 5 549 | Traceback (most recent call last): 550 | ... 551 | ValueError: PPL::Congruence::Congruence(c, r): 552 | constraint c must be an equality. 553 | """ 554 | return Congruence(self, m) 555 | 556 | 557 | def inequality(expression): 558 | """ 559 | Construct an inequality. 560 | 561 | INPUT: 562 | 563 | - ``expression`` -- a :class:`Linear_Expression`. 564 | 565 | OUTPUT: 566 | 567 | The inequality ``expression`` >= 0. 568 | 569 | Examples: 570 | 571 | >>> from ppl import Variable, inequality 572 | >>> y = Variable(1) 573 | >>> 2*y+1 >= 0 574 | 2*x1+1>=0 575 | >>> inequality(2*y+1) 576 | 2*x1+1>=0 577 | """ 578 | return expression >= 0 579 | 580 | 581 | def strict_inequality(expression): 582 | """ 583 | Construct a strict inequality. 584 | 585 | INPUT: 586 | 587 | - ``expression`` -- a :class:`Linear_Expression`. 588 | 589 | OUTPUT: 590 | 591 | The inequality ``expression`` > 0. 592 | 593 | Examples: 594 | 595 | >>> from ppl import Variable, strict_inequality 596 | >>> y = Variable(1) 597 | >>> 2*y+1 > 0 598 | 2*x1+1>0 599 | >>> strict_inequality(2*y+1) 600 | 2*x1+1>0 601 | """ 602 | return expression > 0 603 | 604 | 605 | def equation(expression): 606 | """ 607 | Construct an equation. 608 | 609 | INPUT: 610 | 611 | - ``expression`` -- a :class:`Linear_Expression`. 612 | 613 | OUTPUT: 614 | 615 | The equation ``expression`` == 0. 616 | 617 | Examples: 618 | 619 | >>> from ppl import Variable, equation 620 | >>> y = Variable(1) 621 | >>> 2*y+1 == 0 622 | 2*x1+1==0 623 | >>> equation(2*y+1) 624 | 2*x1+1==0 625 | """ 626 | return expression == 0 627 | 628 | 629 | cdef class Constraint_System(object): 630 | """ 631 | Wrapper for PPL's ``Constraint_System`` class. 632 | 633 | An object of the class Constraint_System is a system of 634 | constraints, i.e., a multiset of objects of the class 635 | Constraint. When inserting constraints in a system, space 636 | dimensions are automatically adjusted so that all the constraints 637 | in the system are defined on the same vector space. 638 | 639 | Examples: 640 | 641 | >>> from ppl import Constraint_System, Variable 642 | >>> x = Variable(0) 643 | >>> y = Variable(1) 644 | >>> cs = Constraint_System( 5*x-2*y > 0 ) 645 | >>> cs.insert( 6*x < 3*y ) 646 | >>> cs.insert( x >= 2*x-7*y ) 647 | >>> cs 648 | Constraint_System {5*x0-2*x1>0, ...} 649 | >>> cs[0] 650 | 5*x0-2*x1>0 651 | """ 652 | def __init__(self, arg=None): 653 | if arg is None: 654 | self.thisptr = new PPL_Constraint_System() 655 | elif isinstance(arg, Constraint): 656 | g = arg 657 | self.thisptr = new PPL_Constraint_System(g.thisptr[0]) 658 | elif isinstance(arg, Constraint_System): 659 | gs = arg 660 | self.thisptr = new PPL_Constraint_System(gs.thisptr[0]) 661 | elif isinstance(arg, (list, tuple)): 662 | self.thisptr = new PPL_Constraint_System() 663 | for constraint in arg: 664 | self.insert(constraint) 665 | else: 666 | raise TypeError('cannot initialize from {!r}'.format(arg)) 667 | 668 | def __cinit__(self, arg=None): 669 | """ 670 | The Cython constructor. 671 | 672 | See :class:`Constraint_System` for documentation. 673 | 674 | Tests: 675 | 676 | >>> from ppl import Constraint_System 677 | >>> Constraint_System() 678 | Constraint_System {} 679 | """ 680 | self.thisptr = NULL 681 | 682 | def __dealloc__(self): 683 | """ 684 | The Cython destructor. 685 | """ 686 | del self.thisptr 687 | 688 | def __hash__(self): 689 | r""" 690 | Tests: 691 | 692 | >>> import ppl 693 | >>> hash(ppl.Constraint_System()) 694 | Traceback (most recent call last): 695 | ... 696 | TypeError: Constraint_System unhashable 697 | """ 698 | raise TypeError('Constraint_System unhashable') 699 | 700 | def space_dimension(self): 701 | r""" 702 | Return the dimension of the vector space enclosing ``self``. 703 | 704 | OUTPUT: 705 | 706 | Integer. 707 | 708 | Examples: 709 | 710 | >>> from ppl import Variable, Constraint_System 711 | >>> x = Variable(0) 712 | >>> cs = Constraint_System( x>0 ) 713 | >>> cs.space_dimension() 714 | 1 715 | """ 716 | return self.thisptr.space_dimension() 717 | 718 | def has_equalities(self): 719 | r""" 720 | Tests whether ``self`` contains one or more equality constraints. 721 | 722 | OUTPUT: 723 | 724 | Boolean. 725 | 726 | Examples: 727 | 728 | >>> from ppl import Variable, Constraint_System 729 | >>> x = Variable(0) 730 | >>> cs = Constraint_System() 731 | >>> cs.insert( x>0 ) 732 | >>> cs.insert( x<0 ) 733 | >>> cs.has_equalities() 734 | False 735 | >>> cs.insert( x==0 ) 736 | >>> cs.has_equalities() 737 | True 738 | """ 739 | return self.thisptr.has_equalities() 740 | 741 | def has_strict_inequalities(self): 742 | r""" 743 | Tests whether ``self`` contains one or more strict inequality constraints. 744 | 745 | OUTPUT: 746 | 747 | Boolean. 748 | 749 | Examples: 750 | 751 | >>> from ppl import Variable, Constraint_System 752 | >>> x = Variable(0) 753 | >>> cs = Constraint_System() 754 | >>> cs.insert( x>=0 ) 755 | >>> cs.insert( x==-1 ) 756 | >>> cs.has_strict_inequalities() 757 | False 758 | >>> cs.insert( x>0 ) 759 | >>> cs.has_strict_inequalities() 760 | True 761 | """ 762 | return self.thisptr.has_strict_inequalities() 763 | 764 | def clear(self): 765 | r""" 766 | Removes all constraints from the constraint system and sets its 767 | space dimension to 0. 768 | 769 | Examples: 770 | 771 | >>> from ppl import Variable, Constraint_System 772 | >>> x = Variable(0) 773 | >>> cs = Constraint_System(x>0) 774 | >>> cs 775 | Constraint_System {x0>0} 776 | >>> cs.clear() 777 | >>> cs 778 | Constraint_System {} 779 | """ 780 | self.thisptr.clear() 781 | 782 | def insert(self, Constraint c): 783 | """ 784 | Insert ``c`` into the constraint system. 785 | 786 | INPUT: 787 | 788 | - ``c`` -- a :class:`Constraint`. 789 | 790 | Examples: 791 | 792 | >>> from ppl import Variable, Constraint_System 793 | >>> x = Variable(0) 794 | >>> cs = Constraint_System() 795 | >>> cs.insert( x>0 ) 796 | >>> cs 797 | Constraint_System {x0>0} 798 | """ 799 | self.thisptr.insert(c.thisptr[0]) 800 | 801 | def empty(self): 802 | """ 803 | Return ``True`` if and only if ``self`` has no constraints. 804 | 805 | OUTPUT: 806 | 807 | Boolean. 808 | 809 | Examples: 810 | 811 | >>> from ppl import Variable, Constraint_System 812 | >>> x = Variable(0) 813 | >>> cs = Constraint_System() 814 | >>> cs.empty() 815 | True 816 | >>> cs.insert( x>0 ) 817 | >>> cs.empty() 818 | False 819 | """ 820 | return self.thisptr.empty() 821 | 822 | def ascii_dump(self): 823 | r""" 824 | Write an ASCII dump to stderr. 825 | 826 | Examples: 827 | 828 | >>> cmd = 'from ppl import Constraint_System, Variable\n' 829 | >>> cmd += 'x = Variable(0)\n' 830 | >>> cmd += 'y = Variable(1)\n' 831 | >>> cmd += 'cs = Constraint_System( 3*x > 2*y+1 )\n' 832 | >>> cmd += 'cs.ascii_dump()\n' 833 | >>> import subprocess, sys 834 | >>> proc = subprocess.Popen([sys.executable, '-c', cmd], stderr=subprocess.PIPE) 835 | >>> out, err = proc.communicate() 836 | >>> print(str(err.decode('ascii'))) 837 | topology NOT_NECESSARILY_CLOSED 838 | ... 839 | 840 | """ 841 | self.thisptr.ascii_dump() 842 | 843 | def __len__(self): 844 | """ 845 | Return the number of constraints in the system. 846 | 847 | Examples: 848 | 849 | >>> from ppl import Variable, Constraint_System 850 | >>> x = Variable(0) 851 | >>> cs = Constraint_System( [x>0, x<1] ) 852 | >>> len(cs) 853 | 2 854 | >>> cs.insert(2*x < 3) 855 | >>> len(cs) 856 | 3 857 | >>> cs.clear() 858 | >>> len(cs) 859 | 0 860 | """ 861 | cdef Py_ssize_t length = 0 862 | cdef PPL_Constraint_System_iterator *csi_ptr = new PPL_Constraint_System_iterator(self.thisptr[0].begin()) 863 | while csi_ptr[0] != self.thisptr[0].end(): 864 | length += 1 865 | csi_ptr[0].inc(1) 866 | del csi_ptr 867 | return length 868 | 869 | def __iter__(self): 870 | """ 871 | Iterate through the constraints of the system. 872 | 873 | Examples: 874 | 875 | >>> from ppl import Variable, Constraint_System 876 | >>> x = Variable(0) 877 | >>> cs = Constraint_System( x>0 ) 878 | >>> iter = cs.__iter__() 879 | >>> next(iter) 880 | x0>0 881 | >>> list(cs) # uses __iter__() internally 882 | [x0>0] 883 | >>> x = Variable(0) 884 | >>> y = Variable(1) 885 | >>> cs = Constraint_System( 5*x < 2*y ) 886 | >>> cs.insert( 6*x-y == 0 ) 887 | >>> cs.insert( x >= 2*x-7*y ) 888 | >>> next(cs.__iter__()) 889 | -5*x0+2*x1>0 890 | >>> list(cs) 891 | [-5*x0+2*x1>0, 6*x0-x1==0, -x0+7*x1>=0] 892 | >>> x = Variable(0) 893 | >>> cs = Constraint_System( x > 0 ) 894 | >>> cs.insert ( 2*x <= -3) 895 | >>> it = cs.__iter__() 896 | >>> next(it) 897 | x0>0 898 | >>> next(it) 899 | -2*x0-3>=0 900 | >>> next(it) 901 | Traceback (most recent call last): 902 | ... 903 | StopIteration 904 | """ 905 | cdef PPL_Constraint_System_iterator *csi_ptr = new PPL_Constraint_System_iterator(self.thisptr[0].begin()) 906 | try: 907 | while csi_ptr[0] != self.thisptr[0].end(): 908 | yield _wrap_Constraint(deref(csi_ptr[0].inc(1))) 909 | finally: 910 | del csi_ptr 911 | 912 | def __getitem__(self, int k): 913 | """ 914 | Return the k-th constraint. 915 | 916 | The correct way to read the individual constraints is to 917 | iterate over the constraint system. This method is for 918 | convenience only. 919 | 920 | INPUT: 921 | 922 | - ``k`` -- integer. The index of the constraint. 923 | 924 | OUTPUT: 925 | 926 | The `k`-th constraint of the constraint system. 927 | 928 | Examples: 929 | 930 | >>> from ppl import Variable, Constraint_System 931 | >>> x = Variable(0) 932 | >>> cs = Constraint_System( x>0 ) 933 | >>> cs.insert( x<1 ) 934 | >>> cs 935 | Constraint_System {x0>0, -x0+1>0} 936 | >>> cs[0] 937 | x0>0 938 | >>> cs[1] 939 | -x0+1>0 940 | """ 941 | if k < 0: 942 | raise IndexError('index must be nonnegative') 943 | iterator = iter(self) 944 | try: 945 | for i in range(k): 946 | next(iterator) 947 | except StopIteration: 948 | raise IndexError('index is past-the-end') 949 | return next(iterator) 950 | 951 | def __repr__(self): 952 | r""" 953 | Return a string representation of the constraint system. 954 | 955 | OUTPUT: 956 | 957 | A string. 958 | 959 | Examples: 960 | 961 | >>> from ppl import Constraint_System, Variable 962 | >>> x = Variable(0) 963 | >>> y = Variable(1) 964 | >>> cs = Constraint_System([3*x+2*y+1 < 3, 0*x>x+1]) 965 | >>> cs.__repr__() 966 | 'Constraint_System {-3*x0-2*x1+2>0, -x0-1>0}' 967 | """ 968 | s = 'Constraint_System {' 969 | s += ', '.join([repr(c) for c in self]) 970 | s += '}' 971 | return s 972 | 973 | def __reduce__(self): 974 | """ 975 | Pickle object. 976 | 977 | Tests: 978 | 979 | >>> from ppl import Constraint_System, Variable 980 | >>> from pickle import loads, dumps 981 | >>> x = Variable(0) 982 | >>> y = Variable(1) 983 | >>> cs = Constraint_System([3*x+2*y+1 < 3, 0*x>x+1]); cs 984 | Constraint_System {-3*x0-2*x1+2>0, -x0-1>0} 985 | >>> loads(dumps(cs)) 986 | Constraint_System {-3*x0-2*x1+2>0, -x0-1>0} 987 | """ 988 | return (Constraint_System, (tuple(self),)) 989 | 990 | 991 | cdef class Poly_Con_Relation(object): 992 | r""" 993 | Wrapper for PPL's ``Poly_Con_Relation`` class. 994 | 995 | INPUT/OUTPUT: 996 | 997 | You must not construct :class:`Poly_Con_Relation` objects 998 | manually. You will usually get them from 999 | :meth:`~sage.libs.ppl.Polyhedron.relation_with`. You can also get 1000 | pre-defined relations from the class methods :meth:`nothing`, 1001 | :meth:`is_disjoint`, :meth:`strictly_intersects`, 1002 | :meth:`is_included`, and :meth:`saturates`. 1003 | 1004 | Examples: 1005 | 1006 | >>> from ppl import Poly_Con_Relation 1007 | >>> saturates = Poly_Con_Relation.saturates(); saturates 1008 | saturates 1009 | >>> is_included = Poly_Con_Relation.is_included(); is_included 1010 | is_included 1011 | >>> is_included.implies(saturates) 1012 | False 1013 | >>> saturates.implies(is_included) 1014 | False 1015 | >>> rels = [] 1016 | >>> rels.append(Poly_Con_Relation.nothing()) 1017 | >>> rels.append(Poly_Con_Relation.is_disjoint()) 1018 | >>> rels.append(Poly_Con_Relation.strictly_intersects()) 1019 | >>> rels.append(Poly_Con_Relation.is_included()) 1020 | >>> rels.append(Poly_Con_Relation.saturates()) 1021 | >>> rels 1022 | [nothing, is_disjoint, strictly_intersects, is_included, saturates] 1023 | >>> for i, rel_i in enumerate(rels): 1024 | ... s = "" 1025 | ... for j, rel_j in enumerate(rels): 1026 | ... s=s+str(int(rel_i.implies(rel_j))) + ' ' 1027 | ... print(" ".join(str(int(rel_i.implies(rel_j))) for j, rel_j in enumerate(rels))) 1028 | 1 0 0 0 0 1029 | 1 1 0 0 0 1030 | 1 0 1 0 0 1031 | 1 0 0 1 0 1032 | 1 0 0 0 1 1033 | """ 1034 | def __cinit__(self, do_not_construct_manually=False): 1035 | """ 1036 | The Cython constructor. 1037 | 1038 | See :class:`Poly_Con_Relation` for documentation. 1039 | 1040 | Tests: 1041 | 1042 | >>> from ppl import Poly_Con_Relation 1043 | >>> Poly_Con_Relation.nothing() 1044 | nothing 1045 | """ 1046 | assert(do_not_construct_manually) 1047 | self.thisptr = NULL 1048 | 1049 | def __dealloc__(self): 1050 | """ 1051 | The Cython destructor. 1052 | """ 1053 | assert self.thisptr!=NULL, 'Do not construct Poly_Con_Relation objects manually!' 1054 | del self.thisptr 1055 | 1056 | def __hash__(self): 1057 | r""" 1058 | Tests: 1059 | 1060 | >>> import ppl 1061 | >>> hash(ppl.Poly_Con_Relation.saturates()) 1062 | Traceback (most recent call last): 1063 | ... 1064 | TypeError: Poly_Con_Relation unhashable 1065 | """ 1066 | raise TypeError('Poly_Con_Relation unhashable') 1067 | 1068 | def implies(self, Poly_Con_Relation y): 1069 | r""" 1070 | Test whether ``self`` implies ``y``. 1071 | 1072 | INPUT: 1073 | 1074 | - ``y`` -- a :class:`Poly_Con_Relation`. 1075 | 1076 | OUTPUT: 1077 | 1078 | Boolean. ``True`` if and only if ``self`` implies ``y``. 1079 | 1080 | Examples: 1081 | 1082 | >>> from ppl import Poly_Con_Relation 1083 | >>> nothing = Poly_Con_Relation.nothing() 1084 | >>> nothing.implies( nothing ) 1085 | True 1086 | """ 1087 | return self.thisptr.implies(y.thisptr[0]) 1088 | 1089 | @classmethod 1090 | def nothing(cls): 1091 | r""" 1092 | Return the assertion that says nothing. 1093 | 1094 | OUTPUT: 1095 | 1096 | A :class:`Poly_Con_Relation`. 1097 | 1098 | Examples: 1099 | 1100 | >>> from ppl import Poly_Con_Relation 1101 | >>> Poly_Con_Relation.nothing() 1102 | nothing 1103 | """ 1104 | return _wrap_Poly_Con_Relation(PPL_Poly_Con_Relation_nothing()) 1105 | 1106 | @classmethod 1107 | def is_disjoint(cls): 1108 | r""" 1109 | Return the assertion "The polyhedron and the set of points 1110 | satisfying the constraint are disjoint". 1111 | 1112 | OUTPUT: 1113 | 1114 | A :class:`Poly_Con_Relation`. 1115 | 1116 | Examples: 1117 | 1118 | >>> from ppl import Poly_Con_Relation 1119 | >>> Poly_Con_Relation.is_disjoint() 1120 | is_disjoint 1121 | """ 1122 | return _wrap_Poly_Con_Relation(PPL_Poly_Con_Relation_is_disjoint()) 1123 | 1124 | @classmethod 1125 | def strictly_intersects(cls): 1126 | r""" 1127 | Return the assertion "The polyhedron intersects the set of 1128 | points satisfying the constraint, but it is not included in 1129 | it". 1130 | 1131 | :return: a :class:`Poly_Con_Relation`. 1132 | 1133 | Examples: 1134 | 1135 | >>> from ppl import Poly_Con_Relation 1136 | >>> Poly_Con_Relation.strictly_intersects() 1137 | strictly_intersects 1138 | """ 1139 | return _wrap_Poly_Con_Relation(PPL_Poly_Con_Relation_strictly_intersects()) 1140 | 1141 | @classmethod 1142 | def is_included(cls): 1143 | r""" 1144 | Return the assertion "The polyhedron is included in the set of 1145 | points satisfying the constraint". 1146 | 1147 | OUTPUT: 1148 | 1149 | A :class:`Poly_Con_Relation`. 1150 | 1151 | Examples: 1152 | 1153 | >>> from ppl import Poly_Con_Relation 1154 | >>> Poly_Con_Relation.is_included() 1155 | is_included 1156 | """ 1157 | return _wrap_Poly_Con_Relation(PPL_Poly_Con_Relation_is_included()) 1158 | 1159 | @classmethod 1160 | def saturates(cls): 1161 | r""" 1162 | Return the assertion "". 1163 | 1164 | OUTPUT: 1165 | 1166 | A :class:`Poly_Con_Relation`. 1167 | 1168 | Examples: 1169 | 1170 | >>> from ppl import Poly_Con_Relation 1171 | >>> Poly_Con_Relation.saturates() 1172 | saturates 1173 | """ 1174 | return _wrap_Poly_Con_Relation(PPL_Poly_Con_Relation_saturates()) 1175 | 1176 | def ascii_dump(self): 1177 | r""" 1178 | Write an ASCII dump to stderr. 1179 | 1180 | Examples: 1181 | 1182 | >>> cmd = 'from ppl import Poly_Con_Relation\n' 1183 | >>> cmd += 'Poly_Con_Relation.nothing().ascii_dump()\n' 1184 | >>> import subprocess, sys 1185 | >>> proc = subprocess.Popen([sys.executable, '-c', cmd], stderr=subprocess.PIPE) 1186 | >>> out, err = proc.communicate() 1187 | >>> print(str(err.decode('ascii'))) 1188 | NOTHING 1189 | """ 1190 | self.thisptr.ascii_dump() 1191 | 1192 | def __repr__(self): 1193 | r""" 1194 | Return a string representation. 1195 | 1196 | OUTPUT: 1197 | 1198 | String. 1199 | 1200 | Examples: 1201 | 1202 | >>> from ppl import Poly_Con_Relation 1203 | >>> Poly_Con_Relation.nothing().__repr__() 1204 | 'nothing' 1205 | """ 1206 | rel = [] 1207 | if self.implies(Poly_Con_Relation.is_disjoint()): 1208 | rel.append('is_disjoint') 1209 | if self.implies(Poly_Con_Relation.strictly_intersects()): 1210 | rel.append('strictly_intersects') 1211 | if self.implies(Poly_Con_Relation.is_included()): 1212 | rel.append('is_included') 1213 | if self.implies(Poly_Con_Relation.saturates()): 1214 | rel.append('saturates') 1215 | if rel: 1216 | return ', '.join(rel) 1217 | else: 1218 | return 'nothing' 1219 | 1220 | 1221 | cdef _make_Constraint_from_richcmp(lhs_, rhs_, op): 1222 | cdef Linear_Expression lhs = Linear_Expression(lhs_) 1223 | cdef Linear_Expression rhs = Linear_Expression(rhs_) 1224 | if op == Py_LT: 1225 | return _wrap_Constraint(lhs.thisptr[0] < rhs.thisptr[0]) 1226 | elif op == Py_LE: 1227 | return _wrap_Constraint(lhs.thisptr[0] <= rhs.thisptr[0]) 1228 | elif op == Py_EQ: 1229 | return _wrap_Constraint(lhs.thisptr[0] == rhs.thisptr[0]) 1230 | elif op == Py_GT: 1231 | return _wrap_Constraint(lhs.thisptr[0] > rhs.thisptr[0]) 1232 | elif op == Py_GE: 1233 | return _wrap_Constraint(lhs.thisptr[0] >= rhs.thisptr[0]) 1234 | elif op == Py_NE: 1235 | raise NotImplementedError 1236 | else: 1237 | assert(False) 1238 | 1239 | 1240 | cdef _wrap_Constraint(PPL_Constraint constraint): 1241 | """ 1242 | Wrap a C++ ``PPL_Constraint`` into a Cython ``Constraint``. 1243 | """ 1244 | cdef Constraint c = Constraint.__new__(Constraint) 1245 | c.thisptr = new PPL_Constraint(constraint) 1246 | return c 1247 | 1248 | 1249 | cdef _wrap_Constraint_System(PPL_Constraint_System constraint_system): 1250 | """ 1251 | Wrap a C++ ``PPL_Constraint_System`` into a Cython ``Constraint_System``. 1252 | """ 1253 | cdef Constraint_System cs = Constraint_System.__new__(Constraint_System) 1254 | cs.thisptr = new PPL_Constraint_System(constraint_system) 1255 | return cs 1256 | 1257 | 1258 | cdef _wrap_Poly_Con_Relation(PPL_Poly_Con_Relation relation): 1259 | """ 1260 | Wrap a C++ ``PPL_Poly_Con_Relation`` into a Cython ``Poly_Con_Relation``. 1261 | """ 1262 | cdef Poly_Con_Relation rel = Poly_Con_Relation(True) 1263 | rel.thisptr = new PPL_Poly_Con_Relation(relation) 1264 | return rel 1265 | -------------------------------------------------------------------------------- /ppl/generator.pyx: -------------------------------------------------------------------------------- 1 | # distutils: language = c++ 2 | # distutils: libraries = gmp gmpxx ppl m 3 | #***************************************************************************** 4 | # Copyright (C) 2010-2014 Volker Braun 5 | # 2011 Simon King 6 | # 2011-2017 Jeroen Demeyer 7 | # 2012 Risan 8 | # 2013 Julien Puydt 9 | # 2013 Travis Scrimshaw 10 | # 2015 André Apitzsch 11 | # 2016 Jori Mäntysalo 12 | # 2016 Matthias Koeppe 13 | # 2016-2017 Frédéric Chapoton 14 | # 2016-2018 Vincent Delecroix 15 | # 2017-2018 Vincent Klein 16 | # 17 | # Distributed under the terms of the GNU General Public License (GPL) 18 | # as published by the Free Software Foundation; either version 3 of 19 | # the License, or (at youroption) any later version. 20 | # http://www.gnu.org/licenses/ 21 | #***************************************************************************** 22 | 23 | from gmpy2 cimport GMPy_MPZ_From_mpz, import_gmpy2 24 | from cython.operator cimport dereference as deref 25 | from .linear_algebra cimport PPL_Coefficient_from_pyobject 26 | 27 | 28 | # PPL can use floating-point arithmetic to compute integers 29 | cdef extern from "ppl.hh" namespace "Parma_Polyhedra_Library": 30 | cdef void set_rounding_for_PPL() 31 | cdef void restore_pre_PPL_rounding() 32 | 33 | # initialize gmpy2 C API 34 | import_gmpy2() 35 | 36 | # but with PPL's rounding the gsl will be very unhappy; must turn off! 37 | restore_pre_PPL_rounding() 38 | 39 | #################################################### 40 | cdef class Generator(object): 41 | r""" 42 | Wrapper for PPL's ``Generator`` class. 43 | 44 | An object of the class Generator is one of the following: 45 | 46 | * a line :math:`\ell = (a_0, \dots, a_{n-1})^T` 47 | 48 | * a ray :math:`r = (a_0, \dots, a_{n-1})^T` 49 | 50 | * a point :math:`p = (\tfrac{a_0}{d}, \dots, \tfrac{a_{n-1}}{d})^T` 51 | 52 | * a closure point :math:`c = (\tfrac{a_0}{d}, \dots, \tfrac{a_{n-1}}{d})^T` 53 | 54 | where :math:`n` is the dimension of the space and, for points and 55 | closure points, :math:`d` is the divisor. 56 | 57 | INPUT/OUTPUT: 58 | 59 | Use the helper functions :func:`line`, :func:`ray`, :func:`point`, 60 | and :func:`closure_point` to construct generators. Analogous class 61 | methods are also available, see :meth:`Generator.line`, 62 | :meth:`Generator.ray`, :meth:`Generator.point`, 63 | :meth:`Generator.closure_point`. Do not attempt to construct 64 | generators manually. 65 | 66 | .. NOTE:: 67 | 68 | The generators are constructed from linear expressions. The 69 | inhomogeneous term is always silently discarded. 70 | 71 | Examples: 72 | 73 | >>> from ppl import Generator, Variable 74 | >>> x = Variable(0) 75 | >>> y = Variable(1) 76 | >>> Generator.line(5*x-2*y) 77 | line(5, -2) 78 | >>> Generator.ray(5*x-2*y) 79 | ray(5, -2) 80 | >>> Generator.point(5*x-2*y, 7) 81 | point(5/7, -2/7) 82 | >>> Generator.closure_point(5*x-2*y, 7) 83 | closure_point(5/7, -2/7) 84 | """ 85 | def __cinit__(self, do_not_construct_manually=False): 86 | """ 87 | The Cython constructor. 88 | 89 | See :class:`Variable` for documentation. 90 | 91 | Tests: 92 | 93 | >>> from ppl import Variable, line 94 | >>> x = Variable(0) 95 | >>> line(x) # indirect doctest 96 | line(1) 97 | """ 98 | assert(do_not_construct_manually) 99 | self.thisptr = NULL 100 | 101 | def __dealloc__(self): 102 | """ 103 | The Cython destructor. 104 | """ 105 | assert self.thisptr!=NULL, 'Do not construct Generators manually!' 106 | del self.thisptr 107 | 108 | def __hash__(self): 109 | r""" 110 | Tests: 111 | 112 | >>> import ppl 113 | >>> hash(ppl.point()) 114 | Traceback (most recent call last): 115 | ... 116 | TypeError: Generator unhashable 117 | """ 118 | raise TypeError('Generator unhashable') 119 | 120 | @classmethod 121 | def line(cls, expression): 122 | """ 123 | Construct a line. 124 | 125 | INPUT: 126 | 127 | - ``expression`` -- a :class:`Linear_Expression` or something 128 | convertible to it (:class:`Variable` or integer). 129 | 130 | OUTPUT: 131 | 132 | A new :class:`Generator` representing the line. 133 | 134 | Raises a ``ValueError` if the homogeneous part of 135 | ``expression`` represents the origin of the vector space. 136 | 137 | Examples: 138 | 139 | >>> from ppl import Generator, Variable 140 | >>> y = Variable(1) 141 | >>> Generator.line(2*y) 142 | line(0, 1) 143 | >>> Generator.line(y) 144 | line(0, 1) 145 | >>> Generator.line(1) 146 | Traceback (most recent call last): 147 | ... 148 | ValueError: PPL::line(e): 149 | e == 0, but the origin cannot be a line. 150 | """ 151 | cdef Linear_Expression e = Linear_Expression(expression) 152 | # This does not work as Cython gets confused by the private default ctor 153 | # return _wrap_Generator(PPL_line(e.thisptr[0])) 154 | # workaround follows 155 | cdef Generator g = Generator(True) 156 | try: 157 | g.thisptr = new PPL_Generator(PPL_line(e.thisptr[0])) 158 | except BaseException: 159 | # g.thisptr must be set to something valid or g.__dealloc__() will segfault 160 | g.thisptr = new PPL_Generator(PPL_point(e.thisptr[0], PPL_Coefficient(1))) 161 | raise 162 | return g 163 | 164 | @classmethod 165 | def ray(cls, expression): 166 | """ 167 | Construct a ray. 168 | 169 | INPUT: 170 | 171 | - ``expression`` -- a :class:`Linear_Expression` or something 172 | convertible to it (:class:`Variable` or integer). 173 | 174 | OUTPUT: 175 | 176 | A new :class:`Generator` representing the ray. 177 | 178 | Raises a ``ValueError` if the homogeneous part of 179 | ``expression`` represents the origin of the vector space. 180 | 181 | Examples: 182 | 183 | >>> from ppl import Generator, Variable 184 | >>> y = Variable(1) 185 | >>> Generator.ray(2*y) 186 | ray(0, 1) 187 | >>> Generator.ray(y) 188 | ray(0, 1) 189 | >>> Generator.ray(1) 190 | Traceback (most recent call last): 191 | ... 192 | ValueError: PPL::ray(e): 193 | e == 0, but the origin cannot be a ray. 194 | """ 195 | cdef Linear_Expression e = Linear_Expression(expression) 196 | # This does not work as Cython gets confused by the private default ctor 197 | # return _wrap_Generator(PPL_ray(e.thisptr[0])) 198 | # workaround follows 199 | cdef Generator g = Generator(True) 200 | try: 201 | g.thisptr = new PPL_Generator(PPL_ray(e.thisptr[0])) 202 | except BaseException: 203 | # g.thisptr must be set to something valid or g.__dealloc__() will segfault 204 | g.thisptr = new PPL_Generator(PPL_point(e.thisptr[0], PPL_Coefficient(1))) 205 | raise 206 | return g 207 | 208 | @classmethod 209 | def point(cls, expression=0, divisor=1): 210 | """ 211 | Construct a point. 212 | 213 | INPUT: 214 | 215 | - ``expression`` -- a :class:`Linear_Expression` or something 216 | convertible to it (:class:`Variable` or integer). 217 | 218 | - ``divisor`` -- an integer. 219 | 220 | OUTPUT: 221 | 222 | A new :class:`Generator` representing the point. 223 | 224 | Raises a ``ValueError` if ``divisor==0``. 225 | 226 | Examples: 227 | 228 | >>> from ppl import Generator, Variable 229 | >>> y = Variable(1) 230 | >>> Generator.point(2*y+7, 3) 231 | point(0/3, 2/3) 232 | >>> Generator.point(y+7, 3) 233 | point(0/3, 1/3) 234 | >>> Generator.point(7, 3) 235 | point() 236 | >>> Generator.point(0, 0) 237 | Traceback (most recent call last): 238 | ... 239 | ValueError: PPL::point(e, d): 240 | d == 0. 241 | """ 242 | cdef Linear_Expression e = Linear_Expression(expression) 243 | # This does not work as Cython gets confused by the private default ctor 244 | # return _wrap_Generator(PPL_point(e.thisptr[0], PPL_Coefficient(d.value))) 245 | # workaround follows 246 | cdef Generator g = Generator(True) 247 | try: 248 | g.thisptr = new PPL_Generator(PPL_point(e.thisptr[0], PPL_Coefficient_from_pyobject(divisor))) 249 | except BaseException: 250 | # g.thisptr must be set to something valid or g.__dealloc__() will segfault 251 | g.thisptr = new PPL_Generator(PPL_point(e.thisptr[0], PPL_Coefficient(1))) 252 | raise 253 | return g 254 | 255 | @classmethod 256 | def closure_point(cls, expression=0, divisor=1): 257 | """ 258 | Construct a closure point. 259 | 260 | A closure point is a point of the topological closure of a 261 | polyhedron that is not a point of the polyhedron itself. 262 | 263 | INPUT: 264 | 265 | - ``expression`` -- a :class:`Linear_Expression` or something 266 | convertible to it (:class:`Variable` or integer). 267 | 268 | - ``divisor`` -- an integer. 269 | 270 | OUTPUT: 271 | 272 | A new :class:`Generator` representing the point. 273 | 274 | Raises a ``ValueError` if ``divisor==0``. 275 | 276 | Examples: 277 | 278 | >>> from ppl import Generator, Variable 279 | >>> y = Variable(1) 280 | >>> Generator.closure_point(2*y+7, 3) 281 | closure_point(0/3, 2/3) 282 | >>> Generator.closure_point(y+7, 3) 283 | closure_point(0/3, 1/3) 284 | >>> Generator.closure_point(7, 3) 285 | closure_point() 286 | >>> Generator.closure_point(0, 0) 287 | Traceback (most recent call last): 288 | ... 289 | ValueError: PPL::closure_point(e, d): 290 | d == 0. 291 | """ 292 | cdef Linear_Expression e = Linear_Expression(expression) 293 | # This does not work as Cython gets confused by the private default ctor 294 | # return _wrap_Generator(PPL_closure_point(e.thisptr[0], PPL_Coefficient(d.value))) 295 | # workaround follows 296 | cdef Generator g = Generator(True) 297 | try: 298 | g.thisptr = new PPL_Generator(PPL_closure_point(e.thisptr[0], PPL_Coefficient_from_pyobject(divisor))) 299 | except BaseException: 300 | # g.thisptr must be set to something valid or g.__dealloc__() will segfault 301 | g.thisptr = new PPL_Generator(PPL_point(e.thisptr[0], PPL_Coefficient(1))) 302 | raise 303 | return g 304 | 305 | def __repr__(self): 306 | """ 307 | Return a string representation of the generator. 308 | 309 | OUTPUT: 310 | 311 | String. 312 | 313 | Examples: 314 | 315 | >>> from ppl import Generator, Variable 316 | >>> x = Variable(0) 317 | >>> y = Variable(1) 318 | >>> e = 2*x-y+5 319 | >>> Generator.line(e) 320 | line(2, -1) 321 | >>> Generator.ray(e) 322 | ray(2, -1) 323 | >>> Generator.point(e, 3) 324 | point(2/3, -1/3) 325 | >>> Generator.closure_point(e, 3) 326 | closure_point(2/3, -1/3) 327 | """ 328 | cdef PPL_GeneratorType t = self.thisptr.type() 329 | if t == LINE or t == RAY: 330 | div = '' 331 | elif t == POINT or t == CLOSURE_POINT: 332 | div = '/' + str(self.divisor()) 333 | else: 334 | raise RuntimeError 335 | 336 | s = ', '.join(str(self.coefficient(Variable(i))) + div for i in range(self.space_dimension())) 337 | return PPL_GeneratorType_str(t) + '(' + s + ')' 338 | 339 | def space_dimension(self): 340 | r""" 341 | Return the dimension of the vector space enclosing ``self``. 342 | 343 | OUTPUT: 344 | 345 | Integer. 346 | 347 | Examples: 348 | 349 | >>> from ppl import Variable, point 350 | >>> x = Variable(0) 351 | >>> y = Variable(1) 352 | >>> point(x).space_dimension() 353 | 1 354 | >>> point(y).space_dimension() 355 | 2 356 | """ 357 | return self.thisptr.space_dimension() 358 | 359 | def set_space_dimension(self, size_t n): 360 | r""" 361 | Set the dimension of this generator to ``n`` 362 | 363 | Examples: 364 | 365 | >>> import ppl 366 | >>> p = ppl.point() 367 | >>> p 368 | point() 369 | >>> p.set_space_dimension(5) 370 | >>> p 371 | point(0/1, 0/1, 0/1, 0/1, 0/1) 372 | 373 | >>> p = ppl.point(1 * ppl.Variable(0) + 2 * ppl.Variable(1) + 3 * ppl.Variable(2)) 374 | >>> p.set_space_dimension(2) 375 | >>> p 376 | point(1/1, 2/1) 377 | """ 378 | self.thisptr.set_space_dimension(n) 379 | 380 | def type(self): 381 | r""" 382 | Return the generator type of ``self``. 383 | 384 | OUTPUT: 385 | 386 | String. One of ``'line'``, ``'ray'``, ``'point'``, or 387 | ``'closure_point'``. 388 | 389 | Examples: 390 | 391 | >>> from ppl import Variable, point, closure_point, ray, line 392 | >>> x = Variable(0) 393 | >>> line(x).type() 394 | 'line' 395 | >>> ray(x).type() 396 | 'ray' 397 | >>> point(x,2).type() 398 | 'point' 399 | >>> closure_point(x,2).type() 400 | 'closure_point' 401 | """ 402 | return PPL_GeneratorType_str(self.thisptr.type()) 403 | 404 | def is_line(self): 405 | r""" 406 | Test whether ``self`` is a line. 407 | 408 | OUTPUT: 409 | 410 | Boolean. 411 | 412 | Examples: 413 | 414 | >>> from ppl import Variable, point, closure_point, ray, line 415 | >>> x = Variable(0) 416 | >>> line(x).is_line() 417 | True 418 | >>> ray(x).is_line() 419 | False 420 | >>> point(x,2).is_line() 421 | False 422 | >>> closure_point(x,2).is_line() 423 | False 424 | """ 425 | return self.thisptr.is_line() 426 | 427 | def is_ray(self): 428 | r""" 429 | Test whether ``self`` is a ray. 430 | 431 | OUTPUT: 432 | 433 | Boolean. 434 | 435 | Examples: 436 | 437 | >>> from ppl import Variable, point, closure_point, ray, line 438 | >>> x = Variable(0) 439 | >>> line(x).is_ray() 440 | False 441 | >>> ray(x).is_ray() 442 | True 443 | >>> point(x,2).is_ray() 444 | False 445 | >>> closure_point(x,2).is_ray() 446 | False 447 | """ 448 | return self.thisptr.is_ray() 449 | 450 | def is_line_or_ray(self): 451 | r""" 452 | Test whether ``self`` is a line or a ray. 453 | 454 | OUTPUT: 455 | 456 | Boolean. 457 | 458 | Examples: 459 | 460 | >>> from ppl import Variable, point, closure_point, ray, line 461 | >>> x = Variable(0) 462 | >>> line(x).is_line_or_ray() 463 | True 464 | >>> ray(x).is_line_or_ray() 465 | True 466 | >>> point(x,2).is_line_or_ray() 467 | False 468 | >>> closure_point(x,2).is_line_or_ray() 469 | False 470 | """ 471 | return self.thisptr.is_line_or_ray() 472 | 473 | def is_point(self): 474 | r""" 475 | Test whether ``self`` is a point. 476 | 477 | OUTPUT: 478 | 479 | Boolean. 480 | 481 | Examples: 482 | 483 | >>> from ppl import Variable, point, closure_point, ray, line 484 | >>> x = Variable(0) 485 | >>> line(x).is_point() 486 | False 487 | >>> ray(x).is_point() 488 | False 489 | >>> point(x,2).is_point() 490 | True 491 | >>> closure_point(x,2).is_point() 492 | False 493 | """ 494 | return self.thisptr.is_point() 495 | 496 | def is_closure_point(self): 497 | r""" 498 | Test whether ``self`` is a closure point. 499 | 500 | OUTPUT: 501 | 502 | Boolean. 503 | 504 | Examples: 505 | 506 | >>> from ppl import Variable, point, closure_point, ray, line 507 | >>> x = Variable(0) 508 | >>> line(x).is_closure_point() 509 | False 510 | >>> ray(x).is_closure_point() 511 | False 512 | >>> point(x,2).is_closure_point() 513 | False 514 | >>> closure_point(x,2).is_closure_point() 515 | True 516 | """ 517 | return self.thisptr.is_closure_point() 518 | 519 | def coefficient(self, Variable v): 520 | """ 521 | Return the coefficient of the variable ``v``. 522 | 523 | INPUT: 524 | 525 | - ``v`` -- a :class:`Variable`. 526 | 527 | OUTPUT: 528 | 529 | An integer. 530 | 531 | Examples: 532 | 533 | >>> from ppl import Variable, line 534 | >>> x = Variable(0) 535 | >>> line = line(3*x+1) 536 | >>> line 537 | line(1) 538 | >>> line.coefficient(x) 539 | mpz(1) 540 | """ 541 | return GMPy_MPZ_From_mpz(self.thisptr.coefficient(v.thisptr[0]).get_mpz_t()) 542 | 543 | def coefficients(self): 544 | """ 545 | Return the coefficients of the generator. 546 | 547 | See also :meth:`coefficient`. 548 | 549 | OUTPUT: 550 | 551 | A tuple of integers of length :meth:`space_dimension`. 552 | 553 | Examples: 554 | 555 | >>> from ppl import Variable, point 556 | >>> x = Variable(0); y = Variable(1) 557 | >>> p = point(3*x+5*y+1, 2); p 558 | point(3/2, 5/2) 559 | >>> p.coefficients() 560 | (mpz(3), mpz(5)) 561 | """ 562 | cdef int d = self.space_dimension() 563 | cdef int i 564 | coeffs = [] 565 | for i in range(0, d): 566 | coeffs.append(GMPy_MPZ_From_mpz(self.thisptr.coefficient(PPL_Variable(i)).get_mpz_t())) 567 | return tuple(coeffs) 568 | 569 | def divisor(self): 570 | """ 571 | If ``self`` is either a point or a closure point, return its 572 | divisor. 573 | 574 | OUTPUT: 575 | 576 | An integer. If ``self`` is a ray or a line, raises 577 | ``ValueError``. 578 | 579 | Examples: 580 | 581 | >>> from ppl import Generator, Variable 582 | >>> x = Variable(0) 583 | >>> y = Variable(1) 584 | >>> point = Generator.point(2*x-y+5) 585 | >>> point.divisor() 586 | mpz(1) 587 | >>> line = Generator.line(2*x-y+5) 588 | >>> line.divisor() 589 | Traceback (most recent call last): 590 | ... 591 | ValueError: PPL::Generator::divisor(): 592 | *this is neither a point nor a closure point. 593 | """ 594 | return GMPy_MPZ_From_mpz(self.thisptr.divisor().get_mpz_t()) 595 | 596 | def is_equivalent_to(self, Generator g): 597 | r""" 598 | Test whether ``self`` and ``g`` are equivalent. 599 | 600 | INPUT: 601 | 602 | - ``g`` -- a :class:`Generator`. 603 | 604 | OUTPUT: 605 | 606 | Boolean. Returns ``True`` if and only if ``self`` and ``g`` 607 | are equivalent generators. 608 | 609 | Note that generators having different space dimensions are not 610 | equivalent. 611 | 612 | Examples: 613 | 614 | >>> from ppl import Variable, point, line 615 | >>> x = Variable(0) 616 | >>> y = Variable(1) 617 | >>> point(2*x , 2).is_equivalent_to( point(x) ) 618 | True 619 | >>> point(2*x+0*y, 2).is_equivalent_to( point(x) ) 620 | False 621 | >>> line(4*x).is_equivalent_to(line(x)) 622 | True 623 | """ 624 | return self.thisptr.is_equivalent_to(g.thisptr[0]) 625 | 626 | def ascii_dump(self): 627 | r""" 628 | Write an ASCII dump to stderr. 629 | 630 | Examples: 631 | 632 | >>> cmd = 'from ppl import Linear_Expression, Variable, point\n' 633 | >>> cmd += 'x = Variable(0)\n' 634 | >>> cmd += 'y = Variable(1)\n' 635 | >>> cmd += 'p = point(3*x+2*y)\n' 636 | >>> cmd += 'p.ascii_dump()\n' 637 | >>> import subprocess 638 | >>> import sys 639 | >>> proc = subprocess.Popen([sys.executable, '-c', cmd], stderr=subprocess.PIPE) 640 | >>> out, err = proc.communicate() 641 | >>> print(str(err.decode('ascii'))) 642 | size 3 1 3 2 ... 643 | 644 | """ 645 | self.thisptr.ascii_dump() 646 | 647 | def __reduce__(self): 648 | """ 649 | Pickle object. 650 | 651 | Tests: 652 | 653 | >>> from ppl import Generator, Variable 654 | >>> from pickle import loads, dumps 655 | >>> x = Variable(0); y = Variable(1) 656 | >>> loads(dumps(Generator.point(2*x+7*y, 3))) 657 | point(2/3, 7/3) 658 | >>> loads(dumps(Generator.closure_point(2*x+7*y, 3))) 659 | closure_point(2/3, 7/3) 660 | >>> loads(dumps(Generator.line(2*x+7*y))) 661 | line(2, 7) 662 | >>> loads(dumps(Generator.ray(2*x+7*y))) 663 | ray(2, 7) 664 | """ 665 | le = Linear_Expression(self.coefficients(), 0) 666 | t = self.thisptr.type() 667 | if t == LINE: 668 | return (Generator.line, (le,)) 669 | elif t == RAY: 670 | return (Generator.ray, (le,)) 671 | elif t == POINT: 672 | return (Generator.point, (le, self.divisor())) 673 | elif t == CLOSURE_POINT: 674 | return (Generator.closure_point, (le, self.divisor())) 675 | else: 676 | raise RuntimeError 677 | 678 | def permute_space_dimensions(self, cycle): 679 | r""" 680 | Permute the coordinates according to ``cycle``. 681 | 682 | >>> from ppl import Generator, Variable 683 | >>> x = Variable(0); y = Variable(1); z = Variable(2) 684 | >>> p = Generator.point(2*x+7*y-z, 3) 685 | >>> p.permute_space_dimensions([0, 1]) 686 | >>> p 687 | point(7/3, 2/3, -1/3) 688 | >>> p.permute_space_dimensions([0, 2, 1]) 689 | >>> p 690 | point(2/3, -1/3, 7/3) 691 | """ 692 | cdef cppvector[PPL_Variable] cpp_cycle 693 | cdef int i 694 | for i in cycle: 695 | cpp_cycle.push_back(PPL_Variable(i)) 696 | self.thisptr.permute_space_dimensions(cpp_cycle) 697 | 698 | #################################################### 699 | ### Generator_System ############################## 700 | #################################################### 701 | #################################################### 702 | cdef class Generator_System(object): 703 | """ 704 | Wrapper for PPL's ``Generator_System`` class. 705 | 706 | An object of the class Generator_System is a system of generators, 707 | i.e., a multiset of objects of the class Generator (lines, rays, 708 | points and closure points). When inserting generators in a system, 709 | space dimensions are automatically adjusted so that all the 710 | generators in the system are defined on the same vector space. A 711 | system of generators which is meant to define a non-empty 712 | polyhedron must include at least one point: the reason is that 713 | lines, rays and closure points need a supporting point (lines and 714 | rays only specify directions while closure points only specify 715 | points in the topological closure of the NNC polyhedron). 716 | 717 | Examples: 718 | 719 | >>> from ppl import Generator_System, Variable, line, ray, point, closure_point 720 | >>> x = Variable(0) 721 | >>> y = Variable(1) 722 | >>> gs = Generator_System(line(5*x-2*y)) 723 | >>> gs.insert(ray(6*x-3*y)) 724 | >>> gs.insert(point(2*x-7*y, 5)) 725 | >>> gs.insert(closure_point(9*x-1*y, 2)) 726 | >>> gs 727 | Generator_System {line(5, -2), ray(2, -1), point(2/5, -7/5), closure_point(9/2, -1/2)} 728 | """ 729 | def __cinit__(self, arg=None): 730 | """ 731 | The Cython constructor. 732 | 733 | See :class:`Generator_System` for documentation. 734 | 735 | Tests: 736 | 737 | >>> from ppl import Generator_System 738 | >>> Generator_System() # indirect doctest 739 | Generator_System {} 740 | """ 741 | if arg is None: 742 | self.thisptr = new PPL_Generator_System() 743 | return 744 | if isinstance(arg, Generator): 745 | g = arg 746 | self.thisptr = new PPL_Generator_System(g.thisptr[0]) 747 | return 748 | if isinstance(arg, Generator_System): 749 | gs = arg 750 | self.thisptr = new PPL_Generator_System(gs.thisptr[0]) 751 | return 752 | if isinstance(arg, (list, tuple)): 753 | self.thisptr = new PPL_Generator_System() 754 | for generator in arg: 755 | self.insert(generator) 756 | return 757 | raise ValueError('Cannot initialize with '+str(arg)+'.') 758 | 759 | def __dealloc__(self): 760 | """ 761 | The Cython destructor. 762 | """ 763 | del self.thisptr 764 | 765 | def __hash__(self): 766 | r""" 767 | Tests: 768 | 769 | >>> import ppl 770 | >>> hash(ppl.Generator_System()) 771 | Traceback (most recent call last): 772 | ... 773 | TypeError: Generator_System unhashable 774 | """ 775 | raise TypeError('Generator_System unhashable') 776 | 777 | def space_dimension(self): 778 | r""" 779 | Return the dimension of the vector space enclosing ``self``. 780 | 781 | OUTPUT: 782 | 783 | Integer. 784 | 785 | Examples: 786 | 787 | >>> from ppl import Variable, Generator_System, point 788 | >>> x = Variable(0) 789 | >>> gs = Generator_System( point(3*x) ) 790 | >>> gs.space_dimension() 791 | 1 792 | """ 793 | return self.thisptr.space_dimension() 794 | 795 | def set_space_dimension(self, size_t n): 796 | r""" 797 | Set the dimension of the vector space enclosing ``self`` 798 | 799 | Examples: 800 | 801 | >>> import ppl 802 | >>> gs = ppl.Generator_System() 803 | >>> gs.insert(ppl.point(ppl.Variable(0) + ppl.Variable(12))) 804 | >>> gs.insert(ppl.point(ppl.Variable(1) + 2*ppl.Variable(3))) 805 | >>> gs.space_dimension() 806 | 13 807 | >>> gs.set_space_dimension(25) 808 | >>> gs.space_dimension() 809 | 25 810 | >>> gs.set_space_dimension(3) 811 | >>> gs.space_dimension() 812 | 3 813 | """ 814 | self.thisptr.set_space_dimension(n) 815 | 816 | def clear(self): 817 | r""" 818 | Removes all generators from the generator system and sets its 819 | space dimension to 0. 820 | 821 | Examples: 822 | 823 | >>> from ppl import Variable, Generator_System, point 824 | >>> x = Variable(0) 825 | >>> gs = Generator_System( point(3*x) ); gs 826 | Generator_System {point(3/1)} 827 | >>> gs.clear() 828 | >>> gs 829 | Generator_System {} 830 | """ 831 | self.thisptr.clear() 832 | 833 | def insert(self, Generator g): 834 | """ 835 | Insert ``g`` into the generator system. 836 | 837 | The number of space dimensions of ``self`` is increased, if needed. 838 | 839 | INPUT: 840 | 841 | - ``g`` -- a :class:`Generator`. 842 | 843 | Examples: 844 | 845 | >>> from ppl import Variable, Generator_System, point 846 | >>> x = Variable(0) 847 | >>> gs = Generator_System( point(3*x) ) 848 | >>> gs.insert( point(-3*x) ) 849 | >>> gs 850 | Generator_System {point(3/1), point(-3/1)} 851 | """ 852 | self.thisptr.insert(g.thisptr[0]) 853 | 854 | def empty(self): 855 | """ 856 | Return ``True`` if and only if ``self`` has no generators. 857 | 858 | OUTPUT: 859 | 860 | Boolean. 861 | 862 | Examples: 863 | 864 | >>> from ppl import Variable, Generator_System, point 865 | >>> x = Variable(0) 866 | >>> gs = Generator_System() 867 | >>> gs.empty() 868 | True 869 | >>> gs.insert( point(-3*x) ) 870 | >>> gs.empty() 871 | False 872 | """ 873 | return self.thisptr.empty() 874 | 875 | def ascii_dump(self): 876 | r""" 877 | Write an ASCII dump to stderr. 878 | 879 | Examples: 880 | 881 | >>> cmd = 'from ppl import Generator_System, point, Variable\n' 882 | >>> cmd += 'x = Variable(0)\n' 883 | >>> cmd += 'y = Variable(1)\n' 884 | >>> cmd += 'gs = Generator_System( point(3*x+2*y+1) )\n' 885 | >>> cmd += 'gs.ascii_dump()\n' 886 | >>> import subprocess, sys 887 | >>> proc = subprocess.Popen([sys.executable, '-c', cmd], stderr=subprocess.PIPE) 888 | >>> out, err = proc.communicate() 889 | >>> print(str(err.decode('ascii'))) 890 | topology NECESSARILY_CLOSED 891 | ... 892 | 893 | """ 894 | self.thisptr.ascii_dump() 895 | 896 | def __len__(self): 897 | """ 898 | Return the number of generators in the system. 899 | 900 | >>> from ppl import Variable, Generator_System, point 901 | >>> x = Variable(0) 902 | >>> y = Variable(1) 903 | >>> gs = Generator_System() 904 | >>> gs.insert(point(3*x+2*y)) 905 | >>> gs.insert(point(x)) 906 | >>> gs.insert(point(y)) 907 | >>> len(gs) 908 | 3 909 | """ 910 | return sum([1 for g in self]) 911 | 912 | def __iter__(self): 913 | """ 914 | Iterate through the generators of the system. 915 | Examples: 916 | 917 | >>> from ppl import Generator_System, Variable, point, ray, line, closure_point 918 | >>> x = Variable(0) 919 | >>> gs = Generator_System(point(3*x)) 920 | >>> iter = gs.__iter__() 921 | >>> next(iter) 922 | point(3/1) 923 | >>> next(iter) 924 | Traceback (most recent call last): 925 | ... 926 | StopIteration 927 | >>> x = Variable(0) 928 | >>> y = Variable(1) 929 | >>> gs = Generator_System( line(5*x-2*y) ) 930 | >>> gs.insert( ray(6*x-3*y) ) 931 | >>> gs.insert( point(2*x-7*y, 5) ) 932 | >>> gs.insert( closure_point(9*x-1*y, 2) ) 933 | >>> next(gs.__iter__()) 934 | line(5, -2) 935 | >>> list(gs) 936 | [line(5, -2), ray(2, -1), point(2/5, -7/5), closure_point(9/2, -1/2)] 937 | """ 938 | cdef PPL_gs_iterator *gsi_ptr = new PPL_gs_iterator(self.thisptr[0].begin()) 939 | try: 940 | while gsi_ptr[0] != self.thisptr[0].end(): 941 | yield _wrap_Generator(deref(gsi_ptr[0].inc(1))) 942 | finally: 943 | del gsi_ptr 944 | 945 | def __getitem__(self, int k): 946 | """ 947 | Return the ``k``-th generator. 948 | 949 | The correct way to read the individual generators is to 950 | iterate over the generator system. This method is for 951 | convenience only. 952 | 953 | INPUT: 954 | 955 | - ``k`` -- integer. The index of the generator. 956 | 957 | OUTPUT: 958 | 959 | The ``k``-th constraint of the generator system. 960 | 961 | Examples: 962 | 963 | >>> from ppl import Generator_System, Variable, point 964 | >>> x = Variable(0) 965 | >>> gs = Generator_System() 966 | >>> gs.insert(point(3*x)) 967 | >>> gs.insert(point(-2*x)) 968 | >>> gs 969 | Generator_System {point(3/1), point(-2/1)} 970 | >>> gs[0] 971 | point(3/1) 972 | >>> gs[1] 973 | point(-2/1) 974 | """ 975 | if k < 0: 976 | raise IndexError('index must be nonnegative') 977 | iterator = iter(self) 978 | try: 979 | for i in range(k): 980 | next(iterator) 981 | except StopIteration: 982 | raise IndexError('index is past-the-end') 983 | return next(iterator) 984 | 985 | def __repr__(self): 986 | r""" 987 | Return a string representation of the generator system. 988 | 989 | OUTPUT: 990 | 991 | A string. 992 | 993 | Examples: 994 | 995 | >>> from ppl import Generator_System, Variable, point, ray 996 | >>> x = Variable(0) 997 | >>> y = Variable(1) 998 | >>> gs = Generator_System(point(3*x+2*y+1)) 999 | >>> gs.insert(ray(x)) 1000 | >>> gs.__repr__() 1001 | 'Generator_System {point(3/1, 2/1), ray(1, 0)}' 1002 | """ 1003 | s = 'Generator_System {' 1004 | s += ', '.join([repr(g) for g in self]) 1005 | s += '}' 1006 | return s 1007 | 1008 | def __reduce__(self): 1009 | """ 1010 | Pickle object. 1011 | 1012 | Tests: 1013 | 1014 | >>> from ppl import Generator_System, Variable, point, ray 1015 | >>> from pickle import loads, dumps 1016 | >>> x = Variable(0) 1017 | >>> y = Variable(1) 1018 | >>> gs = Generator_System((point(3*x+2*y+1), ray(x))); gs 1019 | Generator_System {point(3/1, 2/1), ray(1, 0)} 1020 | >>> loads(dumps(gs)) 1021 | Generator_System {point(3/1, 2/1), ray(1, 0)} 1022 | """ 1023 | return (Generator_System, (tuple(self), )) 1024 | 1025 | cdef PPL_GeneratorType_str(PPL_GeneratorType t): 1026 | if t == LINE: 1027 | return 'line' 1028 | elif t == RAY: 1029 | return 'ray' 1030 | elif t == POINT: 1031 | return 'point' 1032 | elif t == CLOSURE_POINT: 1033 | return 'closure_point' 1034 | else: 1035 | raise RuntimeError 1036 | 1037 | cdef _wrap_Generator(PPL_Generator generator): 1038 | """ 1039 | Wrap a C++ ``PPL_Generator`` into a Cython ``Generator``. 1040 | """ 1041 | cdef Generator g = Generator(True) 1042 | g.thisptr = new PPL_Generator(generator) 1043 | return g 1044 | 1045 | 1046 | cdef _wrap_Generator_System(PPL_Generator_System generator_system): 1047 | """ 1048 | Wrap a C++ ``PPL_Generator_System`` into a Cython ``Generator_System``. 1049 | """ 1050 | cdef Generator_System gs = Generator_System() 1051 | del gs.thisptr 1052 | gs.thisptr = new PPL_Generator_System(generator_system) 1053 | return gs 1054 | 1055 | cdef class Poly_Gen_Relation(object): 1056 | r""" 1057 | Wrapper for PPL's ``Poly_Con_Relation`` class. 1058 | 1059 | INPUT/OUTPUT: 1060 | 1061 | You must not construct :class:`Poly_Gen_Relation` objects 1062 | manually. You will usually get them from 1063 | :meth:`~sage.libs.ppl.Polyhedron.relation_with`. You can also get 1064 | pre-defined relations from the class methods :meth:`nothing` and 1065 | :meth:`subsumes`. 1066 | 1067 | Examples: 1068 | 1069 | >>> from ppl import Poly_Gen_Relation 1070 | >>> nothing = Poly_Gen_Relation.nothing(); nothing 1071 | nothing 1072 | >>> subsumes = Poly_Gen_Relation.subsumes(); subsumes 1073 | subsumes 1074 | >>> nothing.implies( subsumes ) 1075 | False 1076 | >>> subsumes.implies( nothing ) 1077 | True 1078 | """ 1079 | def __cinit__(self, do_not_construct_manually=False): 1080 | """ 1081 | The Cython constructor. 1082 | 1083 | See :class:`Poly_Gen_Relation` for documentation. 1084 | 1085 | Tests: 1086 | 1087 | >>> from ppl import Poly_Gen_Relation 1088 | >>> Poly_Gen_Relation.nothing() 1089 | nothing 1090 | """ 1091 | assert(do_not_construct_manually) 1092 | self.thisptr = NULL 1093 | 1094 | def __dealloc__(self): 1095 | """ 1096 | The Cython destructor. 1097 | """ 1098 | assert self.thisptr!=NULL, 'Do not construct Poly_Gen_Relation objects manually!' 1099 | del self.thisptr 1100 | 1101 | def __hash__(self): 1102 | r""" 1103 | Tests: 1104 | 1105 | >>> import ppl 1106 | >>> hash(ppl.Poly_Gen_Relation.nothing()) 1107 | Traceback (most recent call last): 1108 | ... 1109 | TypeError: Poly_Gen_Relation unhashable 1110 | """ 1111 | raise TypeError('Poly_Gen_Relation unhashable') 1112 | 1113 | def implies(self, Poly_Gen_Relation y): 1114 | r""" 1115 | Test whether ``self`` implies ``y``. 1116 | 1117 | INPUT: 1118 | 1119 | - ``y`` -- a :class:`Poly_Gen_Relation`. 1120 | 1121 | OUTPUT: 1122 | 1123 | Boolean. ``True`` if and only if ``self`` implies ``y``. 1124 | 1125 | Examples: 1126 | 1127 | >>> from ppl import Poly_Gen_Relation 1128 | >>> nothing = Poly_Gen_Relation.nothing() 1129 | >>> nothing.implies( nothing ) 1130 | True 1131 | """ 1132 | return self.thisptr.implies(y.thisptr[0]) 1133 | 1134 | @classmethod 1135 | def nothing(cls): 1136 | r""" 1137 | Return the assertion that says nothing. 1138 | 1139 | OUTPUT: 1140 | 1141 | A :class:`Poly_Gen_Relation`. 1142 | 1143 | Examples: 1144 | 1145 | >>> from ppl import Poly_Gen_Relation 1146 | >>> Poly_Gen_Relation.nothing() 1147 | nothing 1148 | """ 1149 | return _wrap_Poly_Gen_Relation(PPL_Poly_Gen_Relation_nothing()) 1150 | 1151 | @classmethod 1152 | def subsumes(cls): 1153 | r""" 1154 | Return the assertion "Adding the generator would not change 1155 | the polyhedron". 1156 | 1157 | OUTPUT: 1158 | 1159 | A :class:`Poly_Gen_Relation`. 1160 | 1161 | Examples: 1162 | 1163 | >>> from ppl import Poly_Gen_Relation 1164 | >>> Poly_Gen_Relation.subsumes() 1165 | subsumes 1166 | """ 1167 | return _wrap_Poly_Gen_Relation(PPL_Poly_Gen_Relation_subsumes()) 1168 | 1169 | def ascii_dump(self): 1170 | r""" 1171 | Write an ASCII dump to stderr. 1172 | 1173 | Examples: 1174 | 1175 | >>> cmd = 'from ppl import Poly_Gen_Relation\n' 1176 | >>> cmd += 'Poly_Gen_Relation.nothing().ascii_dump()\n' 1177 | >>> from subprocess import Popen, PIPE 1178 | >>> import sys 1179 | >>> proc = Popen([sys.executable, '-c', cmd], stderr=PIPE) 1180 | >>> out, err = proc.communicate() 1181 | >>> print(str(err.decode('ascii'))) 1182 | NOTHING 1183 | >>> proc.returncode 1184 | 0 1185 | """ 1186 | self.thisptr.ascii_dump() 1187 | 1188 | def __repr__(self): 1189 | r""" 1190 | Return a string representation. 1191 | 1192 | OUTPUT: 1193 | 1194 | String. 1195 | 1196 | Examples: 1197 | 1198 | >>> from ppl import Poly_Gen_Relation 1199 | >>> Poly_Gen_Relation.nothing().__repr__() 1200 | 'nothing' 1201 | """ 1202 | if self.implies(Poly_Gen_Relation.subsumes()): 1203 | return 'subsumes' 1204 | else: 1205 | return 'nothing' 1206 | 1207 | cdef _wrap_Poly_Gen_Relation(PPL_Poly_Gen_Relation relation): 1208 | """ 1209 | Wrap a C++ ``PPL_Poly_Gen_Relation`` into a Cython ``Poly_Gen_Relation``. 1210 | """ 1211 | cdef Poly_Gen_Relation rel = Poly_Gen_Relation(True) 1212 | rel.thisptr = new PPL_Poly_Gen_Relation(relation) 1213 | return rel 1214 | --------------------------------------------------------------------------------