Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add method for adding piecewise linear constraints #776

Merged
merged 15 commits into from
Apr 1, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@

## Unreleased
### Added
- Added method for adding piecewise linear constraints
- Add SCIP function SCIPgetTreesizeEstimation and wrapper getTreesizeEstimation
- Add recipes sub-package
### Fixed
### Changed
### Removed
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ Building and solving a model

There are several [examples](https://github.com/scipopt/PySCIPOpt/blob/master/examples/finished) and
[tutorials](https://github.com/scipopt/PySCIPOpt/blob/master/examples/tutorial). These display some functionality of the
interface and can serve as an entry point for writing more complex code.
interface and can serve as an entry point for writing more complex code. Some of the common usecases are also available in the [recipes](https://github.com/scipopt/PySCIPOpt/blob/master/src/pyscipopt/recipes) sub-package.
You might also want to have a look at this article about PySCIPOpt:
<https://opus4.kobv.de/opus4-zib/frontdoor/index/index/docId/6045>. The
following steps are always required when using the interface:
Expand Down
4 changes: 2 additions & 2 deletions setup.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from setuptools import setup, Extension
from setuptools import find_packages, setup, Extension
import os, platform, sys, re

# look for environment variable that specifies path to SCIP
Expand Down Expand Up @@ -124,7 +124,7 @@
"Topic :: Scientific/Engineering :: Mathematics",
],
ext_modules=extensions,
packages=["pyscipopt"],
packages=find_packages(where="src"),
package_dir={"pyscipopt": packagedir},
package_data={"pyscipopt": ["scip.pyx", "scip.pxd", "*.pxi", "scip/lib/*"]},
include_package_data=True,
Expand Down
2 changes: 2 additions & 0 deletions src/pyscipopt/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
# export user-relevant objects:
from pyscipopt.Multidict import multidict
from pyscipopt.scip import Model
from pyscipopt.scip import Variable
from pyscipopt.scip import Constraint
from pyscipopt.scip import Benders
from pyscipopt.scip import Benderscut
from pyscipopt.scip import Branchrule
Expand Down
3 changes: 3 additions & 0 deletions src/pyscipopt/recipes/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Recipes sub-package

This sub-package provides a set of functions for common usecases for pyscipopt. This sub-package is for all functions that don't necessarily reflect the core functionality of SCIP, but are useful for working with the solver. The functions implemented in this sub-package might not be the most efficient way to solve/formulate a problem but would provide a good starting point.
Empty file.
36 changes: 36 additions & 0 deletions src/pyscipopt/recipes/piecewise.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@

from pyscipopt import Model, quicksum, Variable, Constraint

Check warning on line 2 in src/pyscipopt/recipes/piecewise.py

View check run for this annotation

Codecov / codecov/patch

src/pyscipopt/recipes/piecewise.py#L2

Added line #L2 was not covered by tests

def add_piecewise_linear_cons(model: Model, X: Variable, Y: Variable, a: list[float], b: list[float]) -> Constraint:

Check warning on line 4 in src/pyscipopt/recipes/piecewise.py

View check run for this annotation

Codecov / codecov/patch

src/pyscipopt/recipes/piecewise.py#L4

Added line #L4 was not covered by tests
"""add constraint of the form y = f(x), where f is a piecewise linear function

:param X: x variable
:param Y: y variable
:param a: array with x-coordinates of the points in the piecewise linear relation
:param b: array with y-coordinate of the points in the piecewise linear relation

Disclaimer: For the moment, can only model 2d piecewise linear functions
Adapted from https://github.com/scipopt/PySCIPOpt/blob/master/examples/finished/piecewise.py
"""
assert len(a) == len(b), "Must have the same number of x and y-coordinates"

Check warning on line 15 in src/pyscipopt/recipes/piecewise.py

View check run for this annotation

Codecov / codecov/patch

src/pyscipopt/recipes/piecewise.py#L15

Added line #L15 was not covered by tests

K = len(a)-1
w,z = {},{}
for k in range(K):
w[k] = model.addVar(lb=-model.infinity())
z[k] = model.addVar(vtype="B")

Check warning on line 21 in src/pyscipopt/recipes/piecewise.py

View check run for this annotation

Codecov / codecov/patch

src/pyscipopt/recipes/piecewise.py#L17-L21

Added lines #L17 - L21 were not covered by tests

for k in range(K):
model.addCons(w[k] >= a[k]*z[k])
model.addCons(w[k] <= a[k+1]*z[k])

Check warning on line 25 in src/pyscipopt/recipes/piecewise.py

View check run for this annotation

Codecov / codecov/patch

src/pyscipopt/recipes/piecewise.py#L23-L25

Added lines #L23 - L25 were not covered by tests

model.addCons(quicksum(z[k] for k in range(K)) == 1)

Check warning on line 27 in src/pyscipopt/recipes/piecewise.py

View check run for this annotation

Codecov / codecov/patch

src/pyscipopt/recipes/piecewise.py#L27

Added line #L27 was not covered by tests

model.addCons(X == quicksum(w[k] for k in range(K)))

Check warning on line 29 in src/pyscipopt/recipes/piecewise.py

View check run for this annotation

Codecov / codecov/patch

src/pyscipopt/recipes/piecewise.py#L29

Added line #L29 was not covered by tests

c = [float(b[k+1]-b[k]) / (a[k+1]-a[k]) for k in range(K)]
d = [b[k] - c[k]*a[k] for k in range(K)]

Check warning on line 32 in src/pyscipopt/recipes/piecewise.py

View check run for this annotation

Codecov / codecov/patch

src/pyscipopt/recipes/piecewise.py#L31-L32

Added lines #L31 - L32 were not covered by tests

new_cons = model.addCons(Y == quicksum(d[k]*z[k] + c[k]*w[k] for k in range(K)))

Check warning on line 34 in src/pyscipopt/recipes/piecewise.py

View check run for this annotation

Codecov / codecov/patch

src/pyscipopt/recipes/piecewise.py#L34

Added line #L34 was not covered by tests

return new_cons

Check warning on line 36 in src/pyscipopt/recipes/piecewise.py

View check run for this annotation

Codecov / codecov/patch

src/pyscipopt/recipes/piecewise.py#L36

Added line #L36 was not covered by tests
4 changes: 2 additions & 2 deletions src/pyscipopt/scip.pxi
Original file line number Diff line number Diff line change
Expand Up @@ -258,7 +258,7 @@
if rc == SCIP_OKAY:
pass
elif rc == SCIP_ERROR:
raise Exception('SCIP: unspecified error!')

Check failure on line 261 in src/pyscipopt/scip.pxi

View workflow job for this annotation

GitHub Actions / test-coverage (3.11)

SCIP: unspecified error!
elif rc == SCIP_NOMEMORY:
raise MemoryError('SCIP: insufficient memory error!')
elif rc == SCIP_READERROR:
Expand Down Expand Up @@ -2621,7 +2621,7 @@
PY_SCIP_CALL(SCIPaddVarSOS2(self._scip, scip_cons, var.scip_var, weights[i]))

PY_SCIP_CALL(SCIPaddCons(self._scip, scip_cons))
return Constraint.create(scip_cons)
return Constraint.create(scip_cons)

def addConsAnd(self, vars, resvar, name="ANDcons",
initial=True, separate=True, enforce=True, check=True,
Expand Down Expand Up @@ -2853,7 +2853,7 @@
PY_SCIP_CALL(SCIPreleaseCons(self._scip, &scip_cons))

return pyCons

def getSlackVarIndicator(self, Constraint cons):
"""Get slack variable of an indicator constraint.

Expand Down
30 changes: 30 additions & 0 deletions tests/test_piecewise.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@

from pyscipopt import Model
from pyscipopt.recipes.piecewise import add_piecewise_linear_cons

def test_add_piecewise_linear_cons():
m = Model()

xpoints = [1, 3, 5]
ypoints = [1, 2, 4]
x = m.addVar(lb=xpoints[0], ub=xpoints[-1], obj=2)
y = m.addVar(lb=-m.infinity(), obj=-3)
add_piecewise_linear_cons(m, x, y, xpoints, ypoints)

m.optimize()
assert m.isEQ(m.getObjVal(), -2)


def test_add_piecewise_linear_cons2():
m = Model()

xpoints = [1, 3, 5]
ypoints = [1, 2, 4]
x = m.addVar(lb=xpoints[0], ub=xpoints[-1], obj=2)
y = m.addVar(lb=-m.infinity(), obj=-3)
add_piecewise_linear_cons(m, x, y, xpoints, ypoints)

m.setMaximize()

m.optimize()
assert m.isEQ(m.getObjVal(), 0)
Loading